discussion framework migration

This commit is contained in:
bQUARKz 2026-03-26 20:17:12 +00:00
parent 928ea53eb8
commit e2de6c5913
Signed by: bquarkz
SSH Key Fingerprint: SHA256:Z7dgqoglWwoK6j6u4QC87OveEq74WOhFN+gitsxtkf8
105 changed files with 18 additions and 11420 deletions

View File

@ -1,90 +1,28 @@
# PBS Documentation
This directory contains the working and normative documentation for PBS.
This directory now contains durable PBS domain knowledge.
## Tree
```text
docs/pbs/
├── agendas/
├── decisions/
├── pull-requests/
└── specs/
docs/compiler/pbs/
└── learn/
```
## Responsibilities
Normative PBS specifications live in:
### `agendas/`
- `docs/specs/compiler-languages/pbs/`
- `docs/specs/compiler/`
`agendas/` contains open topics.
## Purpose
`docs/compiler/pbs/learn/` is the long-term didactic layer for PBS.
Use it to:
- record unresolved questions,
- define scope, dependencies, and non-goals,
- structure discussion order,
- keep only active TODO topics visible.
- explain the final architectural model,
- preserve implementation-relevant lessons,
- summarize the reasoning that survived workflow closure,
- and accelerate onboarding for future PBS work.
An agenda is a discussion artifact, not a final normative document.
Once a topic is settled, it should leave this directory.
### `decisions/`
`decisions/` contains closed decision records between discussion and spec integration.
Use it to:
- record the adopted decision clearly,
- capture invariants and architectural constraints,
- state what was explicitly left undecided,
- identify which specs must be updated,
- preserve traceability without turning specs into debate logs.
Architecture and decisions come before implementation.
### `specs/`
`specs/` contains the normative PBS corpus.
Use it to:
- consolidate the official PBS contract,
- integrate already-closed decisions in normative language,
- define precedence, scope, rules, and exit criteria,
- provide the baseline for implementation, verification, and conformance.
`docs/pbs/specs` is language-specific.
Cross-language acceptance specs live in `docs/general/specs`.
Specs must not operate as discussion backlogs.
If a point is still disputed or underspecified, it belongs in `agendas/` or `decisions/`, not directly in `specs/`.
### `pull-requests/`
`pull-requests/` contains self-contained change proposals for review.
Use it to:
- package a proposed change across multiple documents,
- explain motivation, target, method, acceptance criteria, and tests,
- make the review surface explicit before final integration,
- keep architectural and decision-level review ahead of implementation work.
If implementation reveals an unresolved ambiguity, stop and ask the question explicitly.
Do not infer missing architectural decisions during implementation.
## Recommended Flow
The preferred pipeline is:
1. `agendas/`: open and discuss unresolved topics.
2. `decisions/`: record the decision and its constraints.
3. `specs/`: integrate the closed decision into normative text.
4. `pull-requests/`: use when a change should be reviewed as a self-contained proposal before merge.
## Practical Rule
- `agendas/` stores open questions.
- `decisions/` stores closed answers.
- `specs/` stores the PBS-specific normative contract.
- `pull-requests/` stores reviewable change packages.
Transient workflow artifacts such as agendas, decision records, and execution plans are intentionally pruned from this directory once their knowledge has been consolidated here or into the normative specs.

View File

@ -1,689 +0,0 @@
# Globals, Synthetic Module Init, and FRAME_RET Agenda
## Status
Open
## Purpose
Define how PBS should introduce runtime globals and lifecycle-driven executable bootstrap without changing the runtime contract in this phase.
This document is the umbrella agenda for topic `19`.
It exists to:
- keep the full problem framed in one place;
- define the dependency order between discussions;
- prevent later discussions from re-opening earlier boundaries casually;
- and provide the parent reference for any follow-up agendas created under this topic.
This agenda must converge on:
- the source-level model for mutable module storage;
- the lifecycle model for module init, optional program init, and frame execution;
- the ownership of `FRAME_RET` once the published entrypoint stops being the user's `frame()` directly;
- the migration path from explicit `FrontendSpec` entrypoint configuration to source-derived PBS entrypoint discovery.
## Domain Owner
`docs/compiler/pbs`
Este tema pertence ao domínio PBS do compiler porque afeta diretamente:
- a surface language de declarações top-level;
- a detecção de entrypoints pelo frontend PBS;
- o modelo de inicialização de módulo e programa;
- o lowering de entrypoint de frame;
- a relação entre entrypoint lógico do usuário e entrypoint publicado no artefato;
- o contrato interno entre frontend, `IRBackend`, `IRVM` lowering e bytecode final.
Nesta fase, o owner continua sendo `compiler/pbs` mesmo quando o resultado reutilizar capacidades já existentes da VM, porque a discussão é sobre como o compiler vai expor e orquestrar essas capacidades.
## Problema
Hoje o PBS não expõe variáveis globais mutáveis de módulo.
O topo do arquivo aceita `declare const`, mas `declare const` é compile-time e não storage runtime. Isso impede formas como:
```pbs
declare struct Vec2(x: int, y: int);
declare global origin: Vec2 = new Vec2(0, 0);
```
Ao mesmo tempo:
1. a VM já tem suporte operacional para globals por slot;
2. o compiler não modela globals no IR executável atual;
3. o entrypoint de frame do usuário hoje coincide, na prática, com a função que delimita o frame lógico;
4. o pipeline atual usa `FRAME_RET` no final desse fluxo de frame lógico.
5. a seleção do entrypoint ainda depende de configuração explícita em `FrontendSpec`, em vez de ser derivada da própria source language do PBS.
Se introduzirmos `declare global`, o compiler precisará definir:
1. como globals são inicializados;
2. quando essa inicialização roda;
3. como garantir execução uma única vez;
4. como conviver com um `init()` custom do usuário;
5. como detectar de forma canônica quais funções do usuário exercem os papéis de `init` e `frame`;
6. como preservar o contrato de frame lógico quando a função publicada deixar de ser a função `frame()` original do usuário.
## Contexto
O estado atual do sistema é:
- PBS proíbe `let` top-level e não expõe storage mutável de módulo;
- `declare const` é avaliado em compile time e pode ser inlinado/foldado;
- inicializadores não constantes como `new`, call sugar, `some`, `none`, `if`, `switch` e outras formas executáveis não pertencem ao modelo de `declare const`;
- a VM do runtime já possui `GetGlobal` e `SetGlobal`;
- o `IRBackend` executável atual modela locals, calls, jumps e literais, mas não modela globals;
- o entrypoint de frame hoje é tratado como raiz do frame lógico, inclusive para o ponto final onde `FRAME_RET` é emitido;
- o frontend PBS ainda depende de configuração explícita em `FrontendSpec` para saber qual callable é o entrypoint publicado;
- hoje isso aparece como acoplamento a nomes/configuração que deveriam ser deduzidos pela própria linguagem.
O cenário motivador é permitir globals de módulo no PBS sem exigir, nesta fase, mudança de runtime.
Também queremos aproveitar essa discussão para mover a detecção de entrypoint para a source language do PBS, usando atributos explícitos:
```pbs
[Init]
fn init() -> void {}
[Frame]
fn frame() -> void {}
```
Essa direção permitiria ao frontend PBS:
1. localizar explicitamente o init do usuário;
2. localizar explicitamente o frame root do usuário;
3. montar o wrapper sintético final sem depender de configuração paralela em `FrontendSpec`;
4. eliminar, nesta linha de evolução, a configuração explícita atual de entrypoint no registry/spec do frontend.
Esta agenda também cobre a extensão desse modelo para discutir:
1. se `[Init]` deve existir apenas como hook final de programa ou também como surface por módulo;
2. qual é exatamente o comportamento operacional de `[Frame]` como root lógico de frame do usuário;
3. como `[Init]` por módulo, `[Init]` final de programa, wrapper sintético e `FRAME_RET` se compõem sem ambiguidade.
Isso empurra a solução para o compiler:
1. synth de init por módulo;
2. synth de wrapper do frame published entrypoint;
3. eventual símbolo privado `boot_done`;
4. redefinição do ponto onde o frame lógico realmente termina;
5. detecção de `init`/`frame` a partir de atributos de source;
6. remoção progressiva das configs explícitas atuais em `FrontendSpec`.
## Inputs
Relevant inputs already present in the repository:
- `docs/vm-arch/ISA_CORE.md` already exposes `GET_GLOBAL` and `SET_GLOBAL`;
- `docs/compiler/pbs/specs/13. Lowering IRBackend Specification.md` currently requires a canonical executable entrypoint to be declared through `FrontendSpec`;
- `docs/compiler/pbs/specs/7. Cartridge Manifest and Runtime Capabilities Specification.md` currently expects PBS v1 manifest `entrypoint` to align with frontend-declared `frame`.
The discussion here must preserve compatibility with those contracts unless it explicitly proposes the propagation work needed to evolve them.
## Core Questions
1. PBS deve introduzir `declare global` como declaração top-level distinta de `declare const`?
2. `declare global` deve aceitar inicializadores executáveis como `new Vec2(...)`, calls e outras expressões lowerables?
3. O compiler deve sintetizar um module init por módulo que contenha `declare global`?
4. A inicialização deve rodar eager no boot lógico do programa ou lazy no primeiro frame?
5. Deve existir um `init()` custom do usuário que roda depois de todos os module inits e antes do primeiro `frame()`?
6. O PBS deve introduzir atributos explícitos `[Init]` e `[Frame]` para identificar as funções corretas do usuário?
7. A descoberta de entrypoint no frontend PBS deve deixar de depender de configuração explícita em `FrontendSpec`?
8. `[Init]` deve poder existir também em escopo/módulo de forma declarativa para orientar module init explícito, ou o compiler deve manter module init sempre totalmente sintético?
9. Qual é o contrato preciso de comportamento de `[Frame]` no PBS: callable obrigatório, assinatura fixa, frequência esperada e relação com o frame lógico publicado?
10. O published frame entrypoint deve passar a ser um wrapper sintético, por exemplo `__pbs_frame()`, em vez do `frame()` do usuário?
11. `FRAME_RET` deve continuar significando "fim do frame lógico" e apenas mudar de owner, saindo da função do usuário para o wrapper sintético?
12. Como o compiler deve tratar ordem topológica, dependências e ciclos entre globals de módulos distintos?
13. Qual política vale quando algum module init ou `init()` do usuário falha: retry no próximo frame, fail-fast, ou outra forma?
14. Globals exportados por `mod.barrel` devem se comportar como storage compartilhado de módulo ou como snapshot/importação por valor?
## Inputs Already Fixed Elsewhere
Os seguintes pontos já parecem fixos ou fortemente estabelecidos e não devem ser contraditos nesta agenda:
- a VM já suporta globals em nível de bytecode/execução;
- `declare const` não é storage mutável/runtime-initialized;
- o runtime já sabe executar um entrypoint published por frame;
- `FRAME_RET` já é usado como marcador do fim de um frame lógico;
- o frontend PBS hoje ainda carrega configuração explícita de entrypoint fora da source language;
- nesta fase queremos evitar mudanças novas no runtime e concentrar a evolução no compiler.
## Decisions To Produce
Como umbrella agenda, esta agenda não deve tentar fechar toda a solução normativa de uma vez.
Ela deve sair com:
1. a decomposição oficial do tema em discussões derivadas;
2. a ordem canônica dessas discussões;
3. os inputs e outputs esperados de cada boundary;
4. a lista de artefatos que não podem ser editados antes do boundary anterior fechar.
Depois que as discussões derivadas fecharem, o conjunto deve produzir direção suficiente para virar uma `decision` cobrindo pelo menos:
1. a surface syntax e o modelo semântico de `declare global`;
2. o modelo de bootstrap entre module init sintético, `[Init]` de programa e `[Frame]`;
3. o owner real do frame lógico publicado e o ponto correto de emissão de `FRAME_RET`;
4. a política de descoberta de entrypoint a partir da source language do PBS;
5. a política de ordenação, ciclos e falhas para globals e module init;
6. a política de imports/exports para globals entre módulos.
## Options
### Option A
Adicionar `declare global`, introduzir `[Init]` e `[Frame]` como superfícies explícitas para lifecycle/entrypoint, discutir `[Init]` final vs `[Init]` por módulo, gerar module init sintético por módulo, gerar wrapper sintético de frame published entrypoint e mover o `FRAME_RET` para esse wrapper.
### Option B
Adicionar `declare global`, mas exigir init totalmente estático ou restrito, sem `init()` custom do usuário e sem wrapper published separado do `frame()` atual.
### Option C
Não adicionar `declare global` agora; manter apenas `declare const` e postergar a discussão até existir um modelo maior de bootstrap/program lifecycle.
### Option D
Adicionar `declare global`, mas exigir lazy materialization no primeiro acesso em vez de module init explícito por ordem topológica.
## Tradeoffs
### Option A
- Prós:
- modelo explícito e fácil de explicar;
- acomoda `declare global` com inicializadores realmente executáveis;
- faz o PBS declarar na própria linguagem quais são os callables de `init` e `frame`;
- abre espaço para discutir de forma unificada `init` por módulo, `init` final e root de frame;
- permite `init()` custom do usuário sem mudar o runtime;
- preserva o significado de `FRAME_RET` como fim do frame lógico;
- remove um acoplamento indesejado entre frontend PBS e configuração manual de entrypoint em `FrontendSpec`.
- Contras:
- exige nova modelagem no compiler para globals, init synthesis e published frame wrapper;
- exige regras novas de atributo e validação de unicidade para `[Init]` e `[Frame]`;
- obriga decisão clara sobre ordem, ciclos e falhas;
- muda a relação atual entre `frame()` do usuário e entrypoint publicado.
### Option B
- Prós:
- escopo menor;
- reduz a superfície de lifecycle;
- pode evitar parte da complexidade de wrapper e boot state.
- Contras:
- resolve mal o caso motivador com `new Vec2(...)`;
- produz uma feature de globais com restrição semântica forte demais;
- deixa o `init()` do usuário para outra rodada e pode forçar redesign posterior.
### Option C
- Prós:
- nenhum risco imediato em pipeline/backend;
- preserva o estado atual do compiler.
- Contras:
- não resolve o caso desejado;
- mantém uma lacuna entre capacidade da VM e surface language do PBS;
- posterga um problema arquitetural que já apareceu de forma concreta.
### Option D
- Prós:
- evita bootstrap eager explícito;
- pode reduzir custo de init em módulos não usados.
- Contras:
- complica determinismo e observabilidade;
- torna mais difícil explicar dependências entre módulos;
- aumenta risco semântico para reentrância, ciclos e ordem de efeitos;
- parece desnecessariamente sofisticado para v1.
## Recommendation
Seguir com a **Option A**.
Direção recomendada para discussão:
1. introduzir `declare global` como nova declaração top-level distinta de `declare const`;
2. permitir inicializadores executáveis lowerables, incluindo `new` e calls compatíveis com o modelo de lowering executável;
3. sintetizar um module init por módulo owner de globals;
4. ordenar os module inits de forma determinística e topológica;
5. introduzir `[Init]` e `[Frame]` como superfícies explícitas de detecção do init/frame do usuário;
6. remover da evolução do PBS a dependência de configuração explícita de entrypoint em `FrontendSpec`, migrando a seleção para a análise da source language;
7. discutir explicitamente se `[Init]` por módulo será uma surface do usuário ou se módulo continuará com init apenas sintético;
8. permitir um `init()` custom opcional do usuário, executado depois de todos os module inits;
9. publicar um wrapper sintético de frame, por exemplo `__pbs_frame()`, como verdadeiro frame root;
10. tratar `frame()` do usuário como callable normal invocado por esse wrapper;
11. manter `FRAME_RET` como marcador do fim do frame lógico, mas emitido no wrapper sintético publicado em vez de no `frame()` do usuário;
12. manter toda a primeira fase restrita ao compiler e ao backend pipeline, sem novos requisitos para o runtime além dos contratos já existentes.
Essa recomendação ainda deixa alguns pontos para fechamento na `decision`, mas já estabelece um shape arquitetural coerente:
- storage global pertence ao módulo owner;
- bootstrap observável pertence ao compiler, não ao runtime;
- `frame()` do usuário deixa de ser o entrypoint publicado e passa a ser o root lógico invocado pelo wrapper;
- `FRAME_RET` continua significando fim do frame lógico, apenas com novo owner sintético;
- a seleção de entrypoint deixa de ser configuração paralela e vira semântica explícita da linguagem.
## Open Questions
1. O nome surface deve ser exatamente `declare global`, ou outra forma top-level?
2. Globals devem exigir initializer obrigatório em v1, ou existirão shells reservados parecidos com builtin const?
3. `[Init]` e `[Frame]` devem ser atributos reservados do PBS ou outra forma de marker surface?
4. `[Init]` deve exigir assinatura fixa `fn init() -> void`?
5. `[Frame]` deve exigir assinatura fixa `fn frame() -> void`?
6. Deve existir no máximo um `[Init]` e um `[Frame]` por programa, por módulo owner, ou por outro escopo?
7. Module init deve permanecer sempre sintético em v1, ou o usuário pode anotar hooks por módulo em alguma forma futura?
8. A política de falha de init deve ser fail-fast definitivo no boot, ou existe algum caso legítimo para retry controlado?
9. Reexport de globals entre módulos deve preservar identidade de storage do owner original ou materializar aliases/import bindings sem storage próprio?
10. O manifest `entrypoint` deve continuar expondo `frame` por compatibilidade nominal ou passar a refletir o símbolo sintético publicado?
## Main Difficulties
Os principais pontos de dificuldade desta agenda não são sintáticos; eles estão na composição entre contratos já existentes.
### 1. `declare global` colide com o recorte atual de `declare const`
Hoje a semântica estática do PBS fixa que:
- `declare const` entra no value namespace;
- `declare const` não materializa storage mutável runtime;
- inicializadores de `declare const` pertencem a um subset estritamente compile-time;
- dependências entre `declare const` são acíclicas e resolvidas por análise de dependência, não por ordem textual.
Introduzir `declare global` exige decidir o que é reaproveitado desse modelo e o que deixa de valer:
- namespace e visibilidade podem reaproveitar parte do modelo atual;
- constant evaluation não pode ser reutilizada como está;
- o modelo de dependência deixa de ser apenas compile-time e passa a produzir efeitos runtime.
### 2. A surface de atributos hoje tem um conjunto reservado fechado
O PBS já trata atributos como metadata compile-time com lowering explícito apenas quando outra spec define esse efeito.
Isso é favorável para `[Init]` e `[Frame]`, mas cria trabalho em três frentes:
- reservar novos atributos no conjunto normativo;
- definir targets válidos, unicidade e diagnóstico;
- definir o lowering sem deixar atributos "soltos" como metadata sem efeito operacional claro.
### 3. O entrypoint publicado hoje ainda está acoplado ao `FrontendSpec`
Existe uma obrigação atual em `13. Lowering IRBackend Specification.md` para o frontend declarar um `EntrypointRef` canônico.
A agenda 19 quer mover a descoberta para a source language, mas isso abre uma transição delicada:
- PBS precisa derivar esse `EntrypointRef` da source language;
- o contrato de `IRBackend` não deve perder determinismo;
- a migração não pode deixar coexistirem por muito tempo duas autoridades independentes para entrypoint.
### 4. O manifest ainda assume `frame` como callable publicado
`7. Cartridge Manifest and Runtime Capabilities Specification.md` hoje sugere alinhamento nominal entre manifest `entrypoint` e callable `frame`.
Se o compiler publicar `__pbs_frame()`:
- ou o manifest passa a refletir o símbolo sintético real;
- ou o manifest preserva um nome lógico enquanto o símbolo real do artefato muda;
- ou a pipeline passa a distinguir entrypoint lógico e entrypoint físico.
Sem fechar isso, a solução de wrapper fica tecnicamente incompleta.
### 5. `FRAME_RET` hoje coincide com o fim do callable do usuário
O ponto difícil não é só "mover um opcode". É redefinir qual callable delimita semanticamente o frame lógico:
- `frame()` do usuário continua sendo apenas código de frame;
- o wrapper sintético vira o owner do frame published entrypoint;
- `FRAME_RET` continua com o mesmo significado semântico, mas sua posição material muda.
Isso afeta lowering, testes de conformance e a forma de explicar o modelo da linguagem.
### 6. Globals intermodulares introduzem um problema novo de identidade e ordem
Hoje `declare const` exportado via `mod.barrel` é simples porque não há storage mutável compartilhado.
Com `declare global`, a agenda precisa fechar:
- quem é o owner real do storage;
- o que um import recebe: binding para o owner ou cópia/snapshot;
- como ciclos entre módulos são detectados;
- se init pode ler globals de módulos predecessores;
- qual é a ordem determinística entre módulos quando há efeitos de inicialização.
### 7. A política de falha deixa de ser apenas rejeição de build
Hoje boa parte do pipeline falha antes da emissão.
Com module init e `init()` do usuário, surge um problema runtime-observable:
- o que acontece quando o boot parcial falha;
- se o programa entra em estado terminal;
- se existe retry;
- como isso se relaciona com o fato de `FRAME_SYNC` permanecer o safepoint normativo.
## Work Boundaries
Para manter a agenda executável e evitar mistura de artefatos, o trabalho pode ser separado nos seguintes boundaries.
### Boundary A. Surface Language and AST
Owner principal: syntax + AST.
Inclui:
- gramática de `declare global`;
- superfície de atributos `[Init]` e `[Frame]`;
- targets permitidos desses atributos;
- novos nós ou flags obrigatórios no AST para globals e lifecycle markers.
Pergunta de fechamento:
- o parser apenas aceita as superfícies ou já impõe parte das restrições estruturais de target/shape?
### Boundary B. Static Semantics and Linking
Owner principal: static semantics + linking.
Inclui:
- namespace e visibilidade de `declare global`;
- regras de initializer obrigatório ou opcional;
- compatibilidade de tipo do initializer;
- unicidade e assinatura válida para `[Init]` e `[Frame]`;
- regras de import/export/barrel para globals;
- detecção de ciclos de dependência entre globals;
- política de identidade do storage através de imports e reexports.
Pergunta de fechamento:
- globals entram no mesmo value namespace de `let`/`declare const` ou exigem distinção semântica adicional apesar do namespace compartilhado?
### Boundary C. Dynamic Semantics and Lifecycle Model
Owner principal: dynamic semantics.
Inclui:
- ordem observável entre module init, `[Init]` de programa e `[Frame]`;
- definição de boot one-shot;
- política de falha de init;
- contrato semântico de `[Frame]` como raiz lógica do tick/frame do usuário;
- relação entre frame lógico do usuário e entrypoint efetivamente publicado.
Pergunta de fechamento:
- o programa tem dois conceitos distintos, `logical frame root` e `published runtime entrypoint`, ou a spec tenta esconder essa distinção do usuário?
### Boundary D. IR and Backend Lowering
Owner principal: lowering executável.
Inclui:
- representação de globals no `IRBackend` ou boundary imediatamente anterior;
- synthesis de module init;
- synthesis de wrapper published entrypoint;
- materialização do guard one-shot de boot;
- reposicionamento do `FRAME_RET`;
- preservação do `EntrypointRef` canônico para o restante do backend.
Pergunta de fechamento:
- globals entram como primitivo explícito no IR ou aparecem apenas em lowering posterior antes de IRVM/bytecode?
### Boundary E. Artifact and Manifest Publication
Owner principal: artifact contracts.
Inclui:
- nome do entrypoint exposto no manifest;
- relação entre callable do usuário, símbolo sintético e entrypoint published;
- compatibilidade com o contrato atual do cartridge manifest;
- possíveis ajustes na leitura de tooling sobre qual callable é o entrypoint "real".
Pergunta de fechamento:
- o manifest publica identidade lógica da linguagem ou identidade física do artefato executável?
### Boundary F. Diagnostics and Conformance
Owner principal: diagnostics + fixture model.
Inclui:
- diagnósticos para target inválido de `[Init]` e `[Frame]`;
- duplicidade ou ausência de markers obrigatórios;
- initializer inválido de `declare global`;
- ciclos intra/inter-módulo;
- imports/reexports ilegais de globals;
- fixture coverage para init ordering, wrapper published entrypoint e `FRAME_RET`.
Pergunta de fechamento:
- quais erros pertencem ao frontend/linking e quais só podem ser cobertos por fixtures de toolchain completo?
## Discussion Order
As discussões derivadas desta umbrella agenda devem seguir a ordem abaixo.
O objetivo da ordem é simples:
- fechar primeiro autoridade semântica e surface;
- depois fechar comportamento observável;
- só então descer para lowering, artefato publicado e conformance.
### Stage 1. Globals Surface and Static Identity
Boundary owner:
- `Boundary A. Surface Language and AST`
- `Boundary B. Static Semantics and Linking`
Esta discussão deve fechar primeiro porque todas as outras dependem da definição do que é um global no PBS.
Ela precisa decidir:
- a forma exata de `declare global`;
- initializer obrigatório ou opcional;
- namespace, visibilidade e barrel/export/import;
- identidade do storage owner;
- política de reexport;
- ciclos e dependências entre globals em nível de linking/static semantics.
Sem esse fechamento:
- lifecycle ainda não sabe o que precisa inicializar;
- lowering ainda não sabe que entidade precisa materializar;
- manifest ainda não sabe se está publicando símbolos que dependem de storage global importado.
### Stage 2. Lifecycle Markers and Program Bootstrap Semantics
Boundary owner:
- `Boundary C. Dynamic Semantics and Lifecycle Model`
Esta discussão vem depois de Stage 1 porque init e frame só fazem sentido quando o modelo de globals já estiver fixado.
Ela precisa decidir:
- se `[Init]` e `[Frame]` entram como superfícies oficiais;
- unicidade e assinatura desses markers;
- ordem entre module init, `[Init]` de programa e `[Frame]`;
- política de boot one-shot;
- política de falha;
- papel semântico exato de `frame()` do usuário.
Sem esse fechamento:
- o wrapper sintético não tem contrato observável estável;
- `FRAME_RET` não tem owner definido;
- qualquer modelagem de IR corre risco de materializar o comportamento errado.
### Stage 3. Published Entrypoint, Wrapper Ownership, and `FRAME_RET`
Boundary owner:
- `Boundary C. Dynamic Semantics and Lifecycle Model`
- `Boundary D. IR and Backend Lowering`
- `Boundary E. Artifact and Manifest Publication`
Esta discussão depende de Stage 2 porque ela não decide mais "o que é lifecycle"; ela decide como lifecycle é publicado.
Ela precisa decidir:
- se o published entrypoint é um wrapper sintético;
- qual é a relação entre `frame()` do usuário e esse wrapper;
- onde `FRAME_RET` passa a ser emitido;
- se o manifest expõe entrypoint lógico, entrypoint físico ou ambos;
- como o `EntrypointRef` do frontend continua determinístico durante a transição.
Sem esse fechamento:
- não existe contrato estável para lowering final;
- specs de manifest e `IRBackend` ficam em tensão;
- o tooling pode continuar com duas autoridades concorrentes para entrypoint.
### Stage 4. IR Representation and Lowering Mechanics
Boundary owner:
- `Boundary D. IR and Backend Lowering`
Esta discussão vem depois de Stage 3 porque a forma do IR depende do que exatamente precisa ser publicado e executado.
Ela precisa decidir:
- se globals entram como primitivo explícito do IR ou apenas em lowering posterior;
- como module init é representado;
- como o guard de boot é materializado;
- como o wrapper published entrypoint é emitido;
- como `FRAME_RET` é reposicionado mantendo o mesmo significado.
Sem esse fechamento:
- código pode ser implementado cedo demais sobre contratos ainda móveis;
- a propagação para specs gerais de lowering fica prematura;
- testes de backend podem congelar um shape errado.
### Stage 5. Diagnostics, Gates, and Conformance Coverage
Boundary owner:
- `Boundary F. Diagnostics and Conformance`
Esta discussão deve vir por último porque ela consolida o que as anteriores já fixaram.
Ela precisa decidir:
- catálogo mínimo de diagnósticos novos;
- divisão entre erro de syntax/AST, linking/static semantics, lowering e toolchain;
- fixtures obrigatórios para globals, lifecycle, wrapper e entrypoint publication;
- critérios de aceite para a migração de `FrontendSpec` entrypoint config para source-derived entrypoint discovery.
Fazer isso antes cria dois riscos:
- congelar diagnósticos para regras ainda instáveis;
- ou escrever fixtures de conformance que depois precisam ser reabertas por mudança arquitetural.
## Derived Agenda Outline
Se quisermos quebrar a umbrella agenda em agendas filhas, a ordem recomendada é:
1. `19.1. PBS Globals Surface, Identity, and Module Boundaries Agenda`
2. `19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda`
3. `19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda`
4. `19.4. Globals and Lifecycle Lowering to IRBackend/IRVM Agenda`
5. `19.5. Diagnostics, Manifest Propagation, and Conformance Coverage Agenda`
Cada agenda filha deve declarar explicitamente:
- que deriva da umbrella agenda `19`;
- quais stages anteriores já são input fixo;
- e quais outputs ela precisa entregar para a agenda seguinte.
## Boundary Locking Rules
Para evitar que discussões posteriores prejudiquem as anteriores, esta umbrella agenda fixa as seguintes regras de sequenciamento:
1. `19.2` não redefine surface syntax ou identidade de globals já fechadas em `19.1`.
2. `19.3` não redefine o significado semântico de `[Init]`, `[Frame]` ou boot ordering já fechados em `19.2`.
3. `19.4` não reabre decisões de linguagem ou de lifecycle; ela apenas escolhe a representação e o mecanismo de lowering compatíveis com elas.
4. `19.5` não reabre arquitetura; ela consolida diagnostics, manifest propagation e coverage.
5. Qualquer ponto que force reabertura de stage anterior deve voltar explicitamente para a agenda filha owner correta, em vez de ser resolvido informalmente na etapa posterior.
## Likely Propagation Targets
Mesmo sem virar `decision` ainda, esta agenda já mostra impacto provável nos seguintes artefatos.
### PBS Specs
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `9. Dynamic Semantics Specification.md`
- `11. AST Specification.md`
- `12. Diagnostics Specification.md`
- `13. Lowering IRBackend Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
### Cross-Domain / VM Architecture
- `docs/vm-arch/ISA_CORE.md` provavelmente não precisa mudar em capability, mas precisa ser referenciado explicitamente como base de `GET_GLOBAL`/`SET_GLOBAL`;
- specs gerais de lowering fora de `docs/compiler/pbs` podem precisar propagação posterior se `IRBackend` ganhar representação explícita de globals ou novo contrato para entrypoint published.
### Compiler / Implementation Areas
- parser e AST model;
- linking/resolution;
- static semantics;
- IR model do frontend PBS;
- executable lowering para `IRBackend` e `IRVM`;
- montagem do manifest/cartridge metadata;
- suites de fixture de frontend, lowering e toolchain.
## Boundary Risks
Se os boundaries acima não forem respeitados, os riscos mais prováveis são:
1. criar `declare global` como açúcar superficial sem lifecycle coerente;
2. introduzir `[Init]` e `[Frame]` sem autoridade clara sobre `FrontendSpec`;
3. mover `FRAME_RET` sem redefinir com precisão o owner do frame lógico;
4. resolver globals intra-módulo mas deixar imports/reexports semanticamente ambíguos;
5. fechar a solução do compiler sem fechar o contrato do manifest;
6. misturar nesta agenda decisões de produto/runtime que deveriam continuar fora de escopo.
## Expected Spec Material
Se esta agenda virar `decision`, a propagação esperada deve atingir pelo menos:
- spec de declarações top-level do PBS para introduzir `declare global`;
- spec de lifecycle/entrypoint attributes para `[Init]` e `[Frame]`;
- spec de lowering executável/`IRBackend` para module init synthesis, wrapper published entrypoint e ownership de `FRAME_RET`;
- spec de cartridge manifest para esclarecer a relação entre entrypoint lógico do usuário e entrypoint publicado no artefato;
- diagnósticos de validação para unicidade, assinatura inválida, ciclos de init e uso incorreto de globals.
## Non-Goals
Esta agenda não deve:
1. redesenhar o runtime ou introduzir novas instruções de VM;
2. escrever a spec normativa final de globals e lifecycle;
3. redefinir o modelo geral de módulos do compiler fora do necessário para globals/init;
4. resolver todos os possíveis hooks futuros de programa além de `[Init]` e `[Frame]`;
5. discutir otimizações de performance de init além do necessário para garantir semântica determinística.
## Next Step
Usar esta agenda como parent reference e abrir as agendas filhas na ordem abaixo:
1. `19.1. PBS Globals Surface, Identity, and Module Boundaries Agenda`
2. `19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda`
3. `19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda`
4. `19.4. Globals and Lifecycle Lowering to IRBackend/IRVM Agenda`
5. `19.5. Diagnostics, Manifest Propagation, and Conformance Coverage Agenda`
Somente depois do fechamento dessas agendas derivadas esta linha deve virar uma `decision` consolidada em `docs/compiler/pbs/decisions`.

View File

@ -1,406 +0,0 @@
# PBS Globals Surface, Identity, and Module Boundaries Agenda
## Status
Open
## Parent Agenda
This agenda derives from:
- `19. Globals, Synthetic Module Init, and FRAME_RET Agenda`
This is the first derived discussion under umbrella topic `19`.
## Purpose
Define the source-level and module-level model for PBS runtime globals before lifecycle, entrypoint publication, or lowering details are discussed.
This agenda exists to close the semantic base for:
- the `declare global` surface;
- storage ownership;
- import/export/alias behavior;
- and dependency/cycle rules at module boundary level.
Later agendas under topic `19` must treat the outputs of this agenda as fixed input.
## Domain Owner
`docs/compiler/pbs`
Este tema pertence ao domínio PBS do compiler porque define surface language, linking semantics e boundaries de módulo para uma nova categoria de declaração top-level.
## Context
Hoje o PBS já possui `declare const`, mas esse surface é estritamente compile-time:
- `declare const` entra no value namespace;
- `declare const` continua reservado a valores imutáveis que não representam storage mutável de módulo;
- `declare const` não materializa storage mutável runtime;
- o initializer de `declare const` pertence a um subset constante;
- dependências de `declare const` são resolvidas por análise de dependência compile-time.
Ao mesmo tempo:
- a VM já expõe `GET_GLOBAL` e `SET_GLOBAL`;
- a linguagem ainda não expõe globals mutáveis de módulo;
- `mod.barrel` hoje já governa export/import de `const`, `fn`, tipos e outras famílias de declaração;
- não existe ainda contrato explícito para storage compartilhado intermodular em source PBS.
Antes de discutir init, frame wrapper ou `FRAME_RET`, precisamos fechar o que um `global` é no modelo da linguagem.
## Inputs Already Fixed Elsewhere
Os seguintes inputs já parecem fixos e não devem ser reabertos aqui:
- `declare const` não é storage mutável/runtime-initialized;
- `declare const` continua semanticamente separado de `declare global`;
- `declare const` continua voltado a valores imutáveis e não deve ser reutilizado como surface de global;
- modules e globals devem compartilhar o mesmo tipo estrutural de análise de dependência;
- essa análise comum deve vir de um refactor do algoritmo atual de modules para um `DependencyGraphAnaliser` em `util.structures` na infra;
- top-level executable statements continuam proibidos;
- a VM já suporta globals por slot;
- esta fase ainda é compiler-driven e não deve exigir capability nova do runtime;
- barrel continua sendo a fonte de visibilidade entre módulos.
## Decisions To Produce
Esta agenda deve produzir direção suficiente para fechar:
1. a surface exata de `declare global`;
2. a obrigatoriedade de initializer em todos os globals de v1;
3. o namespace ocupado por globals;
4. a política de visibility/barrel para globals;
5. a identidade do storage owner;
6. a semântica de import, export e alias;
7. a política de dependência e ciclos entre globals.
## Core Questions
1. PBS deve introduzir exatamente `declare global name: T = expr;` como nova forma top-level?
2. `declare global` deve exigir type annotation explícita em todos os casos?
3. Quais formas de initializer executável são admissíveis para `declare global` em v1?
4. `declare global` entra no mesmo value namespace de `let` e `declare const`?
5. O barrel deve ganhar uma entrada `global` distinta?
6. Um `global` importado referencia sempre o storage do módulo owner original?
7. Como imports de globals usam alias quando necessário sem introduzir shadowing?
8. O que é proibido em imports de globals para evitar ambiguidade?
9. A dependência entre globals deve ser modelada por grafo determinístico semelhante ao de `declare const`, mas agora com efeito runtime?
10. Como ciclos entre globals intra-módulo e inter-módulo devem ser detectados e reportados?
11. Como o grafo de globals mapeia para o `DependencyGraphAnaliser` comum sem perder owner canônico nem attribution?
## Options
### Option A
Adicionar `declare global` como nova declaração top-level explícita, com type annotation obrigatória, initializer obrigatório em v1, entry própria `global` em barrel, sem reexport e identidade de storage sempre pertencente ao módulo owner original.
### Option B
Adicionar `declare global`, mas permitir globals sem initializer em v1 e tratar inicialização default como parte do modelo base.
## Tradeoffs
### Option A
- Prós:
- semântica explícita e fácil de ensinar;
- evita ambiguidade entre constant value e mutable storage;
- força o barrel e os imports a refletirem corretamente a nova categoria declarativa;
- reduz risco de globals parcialmente formados sem política clara de init.
- Contras:
- aumenta a superfície da linguagem;
- exige atualização de parser, AST, linking e barrel matching.
### Option B
- Prós:
- maior flexibilidade futura;
- permite reservar globals antes de decidir a inicialização concreta.
- Contras:
- empurra complexidade para lifecycle e diagnostics;
- enfraquece a previsibilidade de v1;
- cria edge cases sobre leitura antes de materialização.
## Recommendation
Seguir com a **Option A**.
Direção recomendada:
1. `declare global` deve ser uma declaração top-level distinta de `declare const`;
2. type annotation explícita deve ser obrigatória;
3. initializer deve ser obrigatório em v1;
4. `declare const` não deve ser reutilizado para globals e continua reservado a valores imutáveis;
5. globals devem entrar no value namespace, mas com categoria declarativa distinta;
6. barrel deve refletir essa distinção explicitamente com `mod global` e `pub global`;
7. PBS não deve introduzir reexport de globals nesta linha;
8. imports de globals devem preservar a identidade do storage owner original e usar alias quando necessário;
9. shadowing entre imports de `fn`, `service`, `global` e `const` deve ser compile-time error;
10. dependências entre globals devem ser determinísticas e diagnosticáveis.
Também fica registrado nesta agenda um direction técnico já decidido:
1. modules e globals usarão o mesmo tipo estrutural de análise de dependência;
2. isso deve nascer de um refactor do algoritmo atual de modules;
3. o artefato comum deve viver na infra como `DependencyGraphAnaliser` em `util.structures`;
4. cada domínio continua responsável por construir seus próprios nós canônicos, suas arestas e seu mapeamento de diagnóstico;
5. o que é compartilhado é o kernel estrutural de ordenação topológica e detecção de ciclos, não a semântica específica de cada grafo.
## Global Dependencies
O ponto mais sensível desta agenda é a dependência entre globals.
Com `declare const`, dependência significa apenas ordem de avaliação compile-time.
Com `declare global`, dependência passa a significar ordem de materialização runtime, identidade de storage e risco real de efeito parcial.
Exemplos do tipo de dependência que passam a existir:
```pbs
declare global a: int = 1;
declare global b: int = a + 1;
```
Aqui `b` depende de `a` porque o initializer de `b` lê o valor de `a`.
```pbs
declare global origin: Vec2 = new Vec2(0, 0);
declare global camera: Camera = new Camera(origin);
```
Aqui `camera` depende de `origin` porque o initializer usa o valor já materializado de outro global.
Quando há múltiplos módulos, o problema cresce:
```pbs
// module A
declare global seed: int = 7;
// module B
import { seed } from @project:A;
declare global rng: Rng = new Rng(seed);
```
Agora a ordem de materialização não é apenas intra-módulo. Ela atravessa módulos e precisa continuar determinística.
### Dependency Kinds
Esta agenda precisa distinguir pelo menos três formas de dependência:
1. dependência local entre globals do mesmo módulo;
2. dependência intermodular por import de global do módulo owner original;
3. dependência indireta por alias de import, onde o nome local muda, mas o owner do storage permanece igual.
### Main Problems
Os principais problemas de dependência de globals são:
1. ordem de inicialização deixa de poder depender de ordem textual do arquivo;
2. imports com alias podem esconder o owner real do storage;
3. leitura de global ainda não materializado precisa ser proibida por modelo, não tratada como comportamento oportunista;
4. ciclos deixam de ser apenas "ciclos de expressão" e passam a ser ciclos de materialização runtime;
5. o grafo de dependências pode cruzar múltiplos módulos e aliases, o que piora atribuição de diagnóstico.
### Risks
Se a política de dependência de globals ficar frouxa, os riscos são altos:
1. inicialização parcialmente observável:
um global pode ler outro antes de ele existir semanticamente;
2. ordem acidental por arquivo:
a implementação pode acabar usando ordem textual ou ordem de carregamento do projeto, o que quebra determinismo;
3. aliasing ambíguo:
aliases de import podem parecer símbolo novo quando na verdade são só outro nome para o mesmo owner;
4. ciclos opacos:
`A -> B -> C -> A` pode ficar escondido atrás de import e alias, dificultando explicação ao usuário;
5. bootstrap contaminado:
se essa agenda deixar dependência frouxa, a 19.2 herda um lifecycle impossível de explicar;
6. lowering prematuro:
se o compiler materializar a ordem no backend sem política semântica firme, a arquitetura congela cedo demais.
### Direction for Discussion
Minha direção recomendada para dependências de globals nesta agenda é:
1. toda leitura de outro global no initializer cria uma edge explícita no grafo de dependência;
2. a resolução do grafo deve ser determinística e independente de source-file order;
3. imports e aliases devem preservar o owner original do storage no grafo;
4. ciclos entre globals devem ser erro estático, não comportamento runtime com retry ou valor parcial;
5. a agenda deve deixar claro que esta política fecha apenas identidade e dependência;
boot ordering completo continua pertencendo à `19.2`.
### Structural Reuse Decision
Esta agenda também registra uma decisão arquitetural de implementação que afeta a evolução futura:
1. o algoritmo atual usado para dependência de modules deve ser refatorado em um componente estrutural reutilizável;
2. esse componente comum deve se chamar `DependencyGraphAnaliser`;
3. ele deve viver em `util.structures` na infra;
4. modules e globals devem consumir esse mesmo componente estrutural;
5. a semântica que descobre edges continua separada por domínio.
Isso significa:
- o import graph de modules e o init graph de globals não serão o mesmo grafo semântico;
- mas ambos deverão usar o mesmo kernel estrutural para:
- topological ordering,
- cycle detection,
- e suporte a diagnóstico determinístico.
## Current Direction
Os pontos abaixo já podem ser tratados como direção fechada desta agenda, salvo objeção nova forte:
1. a surface correta é `declare global BLA: int = 1;`;
2. type annotation é obrigatória, como em `declare const`;
3. initializer é sempre obrigatório;
4. globals entram no value namespace como categoria declarativa distinta;
5. `mod.barrel` deve expor globals com entradas `mod global Name;` e `pub global Name;`;
6. imports de globals usam o mesmo esquema de alias quando necessário;
7. PBS não introduz reexport de globals nesta linha;
8. shadowing entre imports de `fn`, `service`, `global` e `const` é compile-time error e deve ser resolvido com alias;
9. detecção de dependência, ordenação e ciclo deve nascer do `DependencyGraphAnaliser` comum, com contexto semântico próprio de globals.
Também fica explicitado o modelo de namespace:
1. globals entram no value namespace;
2. `declare const`, `declare global` e o singleton canônico de `service` convivem no espaço nominal de valores;
3. `fn`, `service`, `global` e `const` não podem introduzir o mesmo nome visível no mesmo scope de resolução;
4. essa colisão é erro de compile time, mesmo quando a ambiguidade nasce de import;
5. `locals > struct/class members > globals`, inclusive quando o global veio por import.
## Remaining Open Points
Com a direção já consolidada nesta agenda, não restam pontos substantivos em aberto dentro do boundary de `19.1`.
Os temas adicionais de lifecycle seguem encaminhados para a `19.2`.
## Initializer Boundary
Esta agenda também precisa deixar explícita a fronteira entre:
1. init da declaração `global`;
2. init por módulo;
3. init de projeto.
Direção recomendada:
- o initializer de `declare global` deve permanecer restrito e simples;
- ele existe para materializar o valor inicial da storage de módulo;
- ele não deve carregar lógica procedural maior nem depender de top-level `fn`;
- lógica adicional de setup pertence ao init por módulo;
- setup de programa pertence ao init de projeto.
Com isso, a linha proposta fica:
1. init da global:
permite primitivas, operações simples com valor, member access com valor nessa etapa, `new`, e leitura de outras globals compatíveis com o dep graph;
2. init do módulo:
permite lógica adicional de conveniência e mutações nas globals do próprio módulo após a materialização inicial;
3. init do projeto:
permite setup do projeto como um todo, depois do fechamento do estado de módulo necessário.
### Consequence for `fn` in Global Initializers
Seguindo essa separação, esta agenda recomenda que:
1. calls para top-level `fn` não sejam permitidas em initializer de `global` em v1;
2. a necessidade de lógica mais rica seja absorvida pelo init de módulo discutido na `19.2`;
3. isso mantenha o dep graph de globals focado em materialização declarativa, não em execução procedural arbitrária.
Também fica recomendado que, em v1:
1. `some(...)` e `none` não façam parte do initializer declarativo de `global`;
2. `if` e `switch` não sejam permitidos diretamente na declaração de `global`.
## Diagnostics Recommendation
Esta agenda fecha o seguinte catálogo pequeno, forte e didático de diagnósticos obrigatórios.
### 1. Invalid Global Initializer
Quando o initializer usar uma forma não admissível em v1, o compiler deve emitir um erro apontando a subexpressão inválida.
Mensagem semântica recomendada:
- `global initializer uses unsupported form`
Exemplos de motivo associado:
- top-level `fn` call not allowed in global initializer;
- `some(...)` not allowed in global initializer;
- `if` not allowed in global initializer.
### 2. Global Dependency Cycle
Quando houver ciclo, o compiler deve diagnosticar o global owner local e, quando possível, renderizar o caminho canônico do ciclo.
Mensagem semântica recomendada:
- `global dependency cycle detected`
Detalhe recomendado:
- incluir o símbolo local que participa do ciclo;
- incluir o caminho canônico quando disponível, por exemplo:
`@project:A.seed -> @project:B.rng -> @project:C.config -> @project:A.seed`
### 3. Shadowing Requires Alias
Quando um import introduzir nome que colide com `fn`, `service`, `global` ou `const` já visível, o compiler deve rejeitar e exigir alias explícito.
Mensagem semântica recomendada:
- `imported symbol shadows existing visible symbol; alias required`
### 4. Global Import Category Mismatch
Se o barrel e a importação não preservarem corretamente a categoria declarativa `global`, o compiler deve rejeitar explicitamente em vez de tentar degradar para `const` ou valor genérico.
Mensagem semântica recomendada:
- `global import must resolve through a global barrel entry`
Essa escolha existe para preservar:
- clareza semântica;
- diagnósticos mais simples;
- e uma separação limpa entre storage initialization e lifecycle hooks.
## Forwarded To 19.2
Os seguintes temas surgiram desta agenda, mas pertencem ao boundary de lifecycle e devem ser tratados na `19.2`:
1. init por módulo como fase procedural separada do initializer declarativo de `global`;
2. init de projeto como fase distinta de coordenação final;
3. permissão de loops em init de módulo e init de projeto;
4. proibição de host calls por padrão durante init;
5. permissão apenas para host calls marcadas com atributo reservado `[InitAllowed]`;
6. validação compile-time dessa admissibilidade;
7. separação entre restrição normativa de host interaction e recomendação de design para manter bootstrap leve.
## Expected Spec Material
Se esta agenda fechar, a propagação esperada atinge pelo menos:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `11. AST Specification.md`
- `12. Diagnostics Specification.md`
## Non-Goals
Esta agenda não deve:
1. definir boot ordering;
2. definir `[Init]` ou `[Frame]`;
3. definir wrapper published entrypoint;
4. definir posicionamento de `FRAME_RET`;
5. escolher a representação de IR/bytecode para globals.
## Next Step
Depois de fechar esta agenda, abrir ou aprofundar:
- `19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda`

View File

@ -1,361 +0,0 @@
# PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda
## Status
Open
## Parent Agenda
This agenda derives from:
- `19. Globals, Synthetic Module Init, and FRAME_RET Agenda`
Expected fixed input from previous stage:
- `19.1. PBS Globals Surface, Identity, and Module Boundaries Agenda`
## Purpose
Define the observable lifecycle model of PBS once runtime globals exist.
This agenda must close:
- whether `[Init]` and `[Frame]` become official source markers;
- the relationship between module init and program init;
- boot one-shot behavior;
- failure policy;
- and the semantic role of the user's frame root.
## Domain Owner
`docs/compiler/pbs`
Este tema pertence ao domínio PBS porque define lifecycle observável da linguagem, não apenas mecanismo de backend.
## Context
Depois que `declare global` existir como storage runtime de módulo, o compiler precisará definir:
- quando os globals são materializados;
- em que ordem isso acontece;
- se existe um hook explícito de init de programa;
- se existe um init procedural por módulo separado do initializer declarativo de `global`;
- como a linguagem identifica o frame root do usuário;
- e o que acontece quando o boot falha.
Esta agenda ainda não decide a forma exata do wrapper published entrypoint nem o shape do IR. Ela define primeiro o comportamento observável que essas camadas posteriores terão de respeitar.
## Inputs Already Fixed Elsewhere
Os seguintes inputs devem ser tratados como fechados ou fortemente estáveis aqui:
- o modelo base de globals vindo de `19.1`;
- o initializer declarativo de `global` permanece restrito a primitivas, `new` e leitura de outras globals compatíveis com o dep graph;
- top-level `fn` não são permitidas em initializer de `global` em v1;
- `FRAME_SYNC` permanece como safepoint normativo;
- PBS v1 continua determinístico e single-threaded;
- esta fase continua evitando mudanças novas no runtime.
## Decisions To Produce
Esta agenda deve produzir direção suficiente para fechar:
1. se `[Init]` e `[Frame]` entram na surface oficial;
2. targets válidos, unicidade e assinaturas exigidas;
3. ordem entre module init, init de programa e frame;
4. política de boot one-shot;
5. política de falha;
6. papel semântico de `frame()` do usuário;
7. política de loops e host calls admissíveis durante init.
## Core Questions
1. PBS deve introduzir `[Init]` e `[Frame]` como atributos reservados?
2. `[Init]` deve ser permitido tanto por módulo quanto no init final de projeto?
3. `[Frame]` deve existir exatamente uma vez por programa?
4. `[Init]` deve existir no máximo uma vez por programa?
5. `[Init]` e `[Frame]` devem exigir assinatura fixa `fn ...() -> void`?
6. Todos os module inits devem rodar antes do `[Init]` do usuário?
7. A ausência de `[Init]` deve ser válida?
8. A ausência de `[Frame]` deve ser erro hard para programa executável?
9. Em caso de falha durante module init ou `[Init]`, o programa deve falhar definitivamente ou pode haver retry?
10. Qual é a definição semântica correta de `frame()` do usuário: root lógico do tick, callable publicado, ou apenas callable invocado por infraestrutura sintética futura?
11. Loops devem ser permitidos em init de módulo e init de projeto?
12. Host calls devem ser proibidas por padrão durante init?
13. Apenas host calls marcadas com `[InitAllowed]` devem ser admissíveis durante init?
14. Como a admissibilidade de `[InitAllowed]` é validada em compile time?
## Options
### Option A
Introduzir `[Init]` e `[Frame]` como markers reservados explícitos, com assinaturas fixas, `[Init]` opcional por módulo e por projeto, `[Frame]` obrigatório e único por projeto executável, permitindo init procedural por módulo e mantendo política restritiva de host interaction durante init.
### Option B
Introduzir apenas `[Frame]` e manter init inteiramente sintético, sem hook de programa do usuário nesta fase.
### Option C
Manter lifecycle implícito, sem markers source-level, e continuar derivando entrypoint/configuração fora da linguagem.
## Tradeoffs
### Option A
- Prós:
- deixa lifecycle explícito na linguagem;
- reduz dependência de configuração paralela;
- dá base clara para wrapper, manifest e lowering posteriores.
- Contras:
- amplia a surface de atributos reservados;
- exige validação de target, unicidade e assinatura.
### Option B
- Prós:
- escopo menor;
- adia parte da discussão de init.
- Contras:
- resolve só metade do lifecycle;
- pode forçar redesign quando o hook de init do usuário voltar.
### Option C
- Prós:
- menor custo imediato.
- Contras:
- mantém a autoridade do lifecycle fora da linguagem;
- enfraquece a coerência da série 19.
## Recommendation
Seguir com a **Option A**.
Direção recomendada:
1. `[Init]` e `[Frame]` devem ser markers reservados explícitos;
2. `declare global` sempre lowera para o init sintético do módulo owner;
3. `[Init]` de módulo deve ser opcional e executar depois de todos os `declare global` do módulo;
4. o init de projeto deve seguir o mesmo modelo, mas associado ao projeto que contém o `[Frame]`;
5. `[Init]` de projeto deve ser opcional;
6. `[Frame]` deve ser obrigatório para programa executável e único por projeto;
7. `[Init]` e `[Frame]` devem exigir assinatura fixa `fn name() -> void`;
8. boot deve ser one-shot;
9. falha de boot deve seguir direção fail-fast, salvo argumento forte em contrário;
10. loops devem ser permitidos em init de módulo e init de projeto;
11. host calls devem ser proibidas por padrão durante init;
12. apenas host calls com atributo reservado `[InitAllowed]` devem ser admissíveis durante init;
13. `[InitAllowed]` é atributo reservado de SDK, não userland.
## Additional Lifecycle Concerns
Esta agenda também precisa fechar a separação entre três camadas de bootstrap:
1. initializer declarativo de `global`;
2. init por módulo;
3. init de projeto.
Direção herdada da `19.1`:
- `global` materializa storage inicial;
- init de módulo executa lógica procedural de conveniência sobre globals do próprio módulo;
- init de projeto executa coordenação final do programa.
Com esse modelo:
- loops são legítimos em init de módulo e init de projeto, especialmente para carga e preparação de arrays e estruturas derivadas;
- a restrição normativa mais forte deve cair sobre host interaction;
- "bootstrap leve" continua sendo recomendação de design, não um limite impossível de verificar semanticamente.
## Current Direction
Os pontos abaixo já podem ser tratados como direção fechada desta agenda, salvo objeção nova forte:
1. `[Init]` e `[Frame]` entram como atributos reservados explícitos;
2. `declare global X: T = expr;` lowera sempre para o init sintético do módulo owner;
3. cada arquivo pode declarar opcionalmente um `[Init]` procedural próprio;
4. o `[Init]` de cada arquivo roda sempre depois das globals daquele arquivo e participa do init sintético do módulo;
5. existe também um init de projeto opcional, que é o `[Init]` associado ao projeto que contém o `[Frame]`;
6. `[Frame]` é obrigatório e único por projeto executável;
7. `[Init]` e `[Frame]` seguem a forma recomendada:
```pbs
[Init]
fn init() -> void { ... }
```
```pbs
[Frame]
fn frame() -> void { ... }
```
8. a assinatura exigida é sempre `fn name() -> void`;
9. loops são permitidos nos inits;
10. host calls são proibidas por padrão durante init;
11. apenas host calls com `[InitAllowed]` podem ser usadas durante init;
12. `[InitAllowed]` pertence às superfícies reservadas de SDK, não a userland;
13. falha de boot é fail-fast com mensagem coerente.
Também fica fechada a seguinte regra operacional:
14. o `[Init]` que estiver no mesmo arquivo que o `[Frame]` é o init de projeto;
15. `[Init]` em outros arquivos continuam sendo init de módulo;
16. `[Frame]` e o init de projeto devem ser co-localizados no mesmo arquivo por decisão deliberada de source organization.
17. cada arquivo pode declarar no máximo um `[Init]`;
18. cada módulo possui exatamente um init sintético de módulo, dentro do qual os inits por arquivo são ordenados e compostos;
19. a distinção entre init de módulo e init de projeto é apenas de ordenação e papel semântico, não de surface diferente;
20. como consequência, existe no máximo um `[Init]` de projeto por projeto executável.
21. arquivos sem globals podem declarar um `[Init]`, desde que continuem respeitando a regra de no máximo um `[Init]` por arquivo;
22. o `project init` segue exatamente a mesma assinatura `fn init() -> void`.
## Lifecycle Order Direction
Esta agenda também já aponta para a seguinte ordem lógica de bootstrap:
1. materialização das globals de cada arquivo do módulo conforme a ordem determinada pelo dependency graph;
2. execução do `[Init]` daquele arquivo, quando existir;
3. composição desses passos em um único init sintético do módulo;
4. depois do fechamento dos módulos necessários, execução do `[Init]` de projeto, quando existir;
5. entrada no primeiro `frame()`.
Lendo essa ordem de forma operacional:
1. cada arquivo inicializa suas próprias globals;
2. cada arquivo pode então executar seu `[Init]` opcional;
3. tudo isso se aninha dentro de um único init sintético por módulo;
4. o `[Init]` co-localizado com `[Frame]` é elevado a init de projeto por ordem e papel semântico.
Também fica fechada a seguinte direção adicional:
5. a ordem entre arquivos do mesmo módulo deve seguir a ordem derivada do `DependencyGraphAnaliser` das globals;
6. quando dois arquivos não tiverem dependência entre si, o compiler deve usar uma ordem determinística estável.
## Remaining Open Points
Com a direção já consolidada nesta agenda, não restam pontos substantivos em aberto dentro do boundary de `19.2`.
Os temas seguintes agora pertencem à `19.3`.
## InitAllowed Direction
Esta agenda fecha também o seguinte shape normativo inicial para `[InitAllowed]`:
1. `[InitAllowed]` é um atributo reservado sem argumentos em v1;
2. ele é válido apenas em host methods de SDK;
3. ele é inválido em userland;
4. ele é inválido em `fn`, `global`, `service` e demais superfícies que não sejam host methods de SDK;
5. seu papel é exclusivamente validar, em compile time, quais host calls podem aparecer durante init;
6. ele não faz distinção entre init de módulo e init de projeto;
7. a diferença entre esses inits é de ordenação e papel semântico, não de permissão separada de host call.
Exemplo recomendado:
```pbs
declare host Runtime {
[Host(module = "runtime", name = "random_u32", version = 1)]
[Capability(name = "runtime")]
[InitAllowed]
fn random_u32() -> int;
}
```
## Diagnostics Recommendation
Esta agenda fecha o seguinte catálogo mínimo de diagnósticos de lifecycle e bootstrap.
### 1. Project Init Must Be Colocated With Frame
Mensagem semântica recomendada:
- `project init must be colocated with frame`
### 2. Multiple Project Init Functions Detected
Mensagem semântica recomendada:
- `multiple project init functions detected`
### 3. Multiple Frame Functions Detected
Mensagem semântica recomendada:
- `multiple frame functions detected`
### 4. Missing Frame Function For Executable Project
Mensagem semântica recomendada:
- `missing frame function for executable project`
### 5. Invalid Init Signature
Mensagem semântica recomendada:
- `init function must have signature fn name() -> void`
### 6. Invalid Frame Signature
Mensagem semântica recomendada:
- `frame function must have signature fn name() -> void`
### 7. Host Call Not Allowed During Init
Mensagem semântica recomendada:
- `host call not allowed during init`
### 8. Invalid InitAllowed Target
Mensagem semântica recomendada:
- `InitAllowed is valid only on SDK host methods`
### 9. Boot Failed During Module Init
Mensagem semântica recomendada:
- `boot failed during module init`
### 10. Boot Failed During Project Init
Mensagem semântica recomendada:
- `boot failed during project init`
### 11. Multiple Module Init Functions Detected
Mensagem semântica recomendada:
- `multiple module init functions detected`
### 12. Init Attribute Target Invalid
Mensagem semântica recomendada:
- `Init attribute target invalid`
## Expected Spec Material
Se esta agenda fechar, a propagação esperada atinge pelo menos:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `9. Dynamic Semantics Specification.md`
- `12. Diagnostics Specification.md`
## Non-Goals
Esta agenda não deve:
1. decidir o nome físico do wrapper published entrypoint;
2. decidir o nome físico do entrypoint no manifest;
3. definir shape de IR;
4. definir como `FRAME_RET` será reposicionado materialmente.
## Next Step
Depois de fechar esta agenda, abrir ou aprofundar:
- `19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda`

View File

@ -1,203 +0,0 @@
# Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda
## Status
Open
## Parent Agenda
This agenda derives from:
- `19. Globals, Synthetic Module Init, and FRAME_RET Agenda`
Expected fixed inputs from previous stages:
- `19.1. PBS Globals Surface, Identity, and Module Boundaries Agenda`
- `19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda`
## Purpose
Define how PBS lifecycle is published into the executable artifact once globals and lifecycle semantics are already fixed.
This agenda must close:
- whether the published entrypoint becomes a synthetic wrapper;
- the semantic and publication relationship between user `frame()` and the published entrypoint;
- the new owner of `FRAME_RET`;
- and the contract boundary between source-derived entrypoint discovery, `FrontendSpec`, and cartridge manifest publication.
## Domain Owner
`docs/compiler/pbs`
Este tema pertence ao domínio PBS porque decide a fronteira entre semântica da linguagem, entrypoint publicado e artefato executável.
## Context
Se `frame()` do usuário deixar de ser o callable publicado diretamente, o compiler precisará publicar outro root executável.
Isso abre quatro perguntas acopladas:
- quem é o entrypoint físico do artefato;
- qual callable continua sendo o root lógico do código do usuário;
- onde `FRAME_RET` passa a ser emitido;
- e como manifest e `FrontendSpec` representam isso sem ambiguidade.
Esta agenda existe para fechar esse contrato antes de discutir detalhe de representação de IR.
## Inputs Already Fixed Elsewhere
Os seguintes inputs devem ser tratados como fixos aqui:
- o modelo de globals vindo de `19.1`;
- o modelo de lifecycle e markers vindo de `19.2`;
- `FRAME_RET` continua significando fim do frame lógico;
- o runtime continua esperando um entrypoint published por frame.
## Decisions To Produce
Esta agenda deve produzir direção suficiente para fechar:
1. se o published entrypoint é um wrapper sintético;
2. qual é a relação entre `frame()` do usuário e esse wrapper;
3. onde `FRAME_RET` passa a viver;
4. como a autoridade de entrypoint sai de `FrontendSpec` e passa ao compiler PBS;
5. como o protocolo de runtime/manifest representa esse entrypoint.
## Core Questions
1. O compiler deve publicar um wrapper sintético como entrypoint real?
2. `frame()` do usuário deixa de ser o callable publicado e passa a ser apenas root lógico interno?
3. `FRAME_RET` deve ser emitido no wrapper, não mais no callable do usuário?
4. O compiler PBS deve se tornar a única autoridade para definir o entrypoint publicado?
5. O wrapper sintético deve ocupar protocolarmente o entrypoint físico `0`?
6. O campo `entrypoint` deve deixar de existir no `manifest.json` como estado alvo do protocolo?
7. Existe algum caso em que o wrapper não seja necessário depois de `19.2`?
## Options
### Option A
Publicar um wrapper sintético como entrypoint físico, tratar `frame()` do usuário como root lógico interno, mover `FRAME_RET` para o wrapper, tornar o compiler PBS a autoridade exclusiva de entrypoint e fixar protocolarmente o entrypoint físico em `0`.
### Option B
Manter `frame()` do usuário como entrypoint publicado e tentar acoplar boot/lifecycle diretamente nele.
### Option C
Publicar wrapper sintético, mas manter `entrypoint` no manifest como autoridade nominal paralela.
## Tradeoffs
### Option A
- Prós:
- separa lifecycle publicado do callable do usuário;
- acomoda boot one-shot de forma limpa;
- preserva o significado de `FRAME_RET` com owner mais correto.
- alinha melhor o protocolo físico do artefato com a política já existente de `func_id = 0` como entrypoint;
- remove autoridade duplicada entre compiler, manifest e `FrontendSpec`.
- Contras:
- exige trabalho claro de migração em manifest, runtime e `FrontendSpec`;
- torna a relação lógico/físico explicitamente dupla.
### Option B
- Prós:
- preserva a superfície atual de publicação.
- Contras:
- mistura responsabilidades demais no callable do usuário;
- enfraquece a clareza do lifecycle.
### Option C
- Prós:
- parece reduzir custo de transição imediata.
- Contras:
- mantém duas autoridades para entrypoint;
- cria dívida documental e de runtime desnecessária;
- enfraquece a ideia de entrypoint como protocolo fixo do artefato.
## Recommendation
Seguir com a **Option A**.
## Current Direction
Os pontos abaixo já podem ser tratados como direção fechada desta agenda, salvo objeção nova forte:
1. o compiler deve publicar um wrapper sintético como entrypoint físico real;
2. esse wrapper deve conter:
- boot one-shot,
- os inits necessários apenas uma vez,
- a chamada ao `frame()` do usuário,
- e o `FRAME_RET` final;
3. `frame()` anotado com `[Frame]` permanece como root lógico do usuário;
4. o wrapper sintético é o root físico publicado;
5. `FRAME_RET` sai do final do `frame()` do usuário e passa a existir no wrapper;
6. `FrontendSpec` perde autoridade para referenciar quem é o entrypoint;
7. a autoridade de entrypoint fica outorgada exclusivamente ao compiler PBS;
8. o wrapper sintético deve ser compilado no entrypoint físico `0`;
9. o estado alvo do protocolo deve remover `entrypoint` do `manifest.json`;
10. o runtime/loader deve tratar o entrypoint como protocolo fixo do artefato, não como metadado nominal configurável no manifest.
## Manifest and Runtime Direction
Esta agenda também já aponta para a seguinte direção de contrato:
1. o campo `entrypoint` deve deixar de existir no `manifest.json` como estado final do protocolo;
2. o runtime deve assumir protocolarmente o entrypoint físico `0`;
3. o compiler garante que esse índice `0` pertence ao wrapper sintético publicado;
4. export nominal do callable deixa de ser a autoridade de boot;
5. qualquer compatibilidade temporária com manifest nominal deve ser tratada apenas como transição, não como contrato final desejado.
## Exports Boundary
Esta agenda também fecha a seguinte separação:
1. exports nominais de funções podem continuar existindo no artefato;
2. esses exports deixam de ser usados como autoridade de loader/boot;
3. boot passa a depender exclusivamente do entrypoint físico `0` publicado pelo compiler;
4. exports nominais permanecem apenas como superfície útil para tooling, debug, introspection e casos correlatos.
## Remaining Open Points
Com a direção acima, os pontos que ainda pedem fechamento real nesta agenda ficam reduzidos a:
1. a forma de propagação normativa dessa mudança para specs gerais de bytecode, lowering e cartridge contract.
## Runtime Propagation
Esta agenda também deve referenciar explicitamente a discussão correspondente no domínio runtime:
- `../runtime/docs/runtime/agendas/025-cartridge-manifest-entrypoint-removal-and-runtime-protocol.md`
Direção fechada desta agenda:
1. não há linha de compatibilidade desejada como estado-alvo;
2. a remoção de `entrypoint` do runtime deve ser executada em prioridade alinhada ao compiler;
3. a agenda de runtime é o owner da discussão operacional de loader/VM/manifest no outro domínio.
## Expected Spec Material
Se esta agenda fechar, a propagação esperada atinge pelo menos:
- `9. Dynamic Semantics Specification.md`
- `13. Lowering IRBackend Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
- `12. Diagnostics Specification.md`
## Non-Goals
Esta agenda não deve:
1. escolher o encoding exato do wrapper no IR;
2. definir estrutura detalhada de module init lowering;
3. escrever fixtures completos de conformance.
## Next Step
Depois de fechar esta agenda, abrir ou aprofundar:
- `19.4. Globals and Lifecycle Lowering to IRBackend/IRVM Agenda`

View File

@ -1,305 +0,0 @@
# Globals and Lifecycle Lowering to IRBackend/IRVM Agenda
## Status
Open
## Parent Agenda
This agenda derives from:
- `19. Globals, Synthetic Module Init, and FRAME_RET Agenda`
Expected fixed inputs from previous stages:
- `19.1. PBS Globals Surface, Identity, and Module Boundaries Agenda`
- `19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda`
- `19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda`
## Purpose
Define how the already-decided globals and lifecycle model are represented and lowered through the executable compiler pipeline.
This agenda must close:
- the representation boundary for globals;
- module init synthesis;
- boot guard materialization;
- wrapper lowering;
- and the executable path that preserves the chosen `FRAME_RET` ownership.
## Domain Owner
`docs/compiler/pbs`
Este tema pertence ao domínio PBS, mas encosta diretamente nas specs gerais de lowering e nas interfaces entre frontend e backend.
## Context
Depois que surface, lifecycle e publication contract estiverem fechados, ainda restará decidir:
- em que boundary globals passam a existir como entidade explícita;
- se `IRBackend` carrega globals diretamente ou só uma forma anterior;
- como module init sintético é representado;
- como o wrapper published entrypoint é emitido;
- como o guard one-shot de boot é materializado.
Esta agenda é mecânica/arquitetural. Ela não deve reabrir decisões de linguagem.
## Inputs Already Fixed Elsewhere
Os seguintes inputs devem ser tratados como fixos aqui:
- surface e identidade de globals vindas de `19.1`;
- lifecycle semântico vindo de `19.2`;
- owner do published entrypoint e de `FRAME_RET` vindo de `19.3`;
- `GET_GLOBAL` e `SET_GLOBAL` já existem na VM.
## Decisions To Produce
Esta agenda deve produzir direção suficiente para fechar:
1. se globals entram explicitamente no `IRBackend` ou apenas em lowering posterior;
2. como module init é sintetizado;
3. como o guard one-shot de boot é materializado;
4. como o wrapper é lowered;
5. como `FRAME_RET` é preservado no ponto correto;
6. quais contracts gerais de lowering precisam propagação.
## Core Questions
1. `IRBackend` deve ganhar representação explícita para globals?
2. Se não, qual é o boundary intermediário responsável por materializá-los antes de `IRVM`?
3. Module init sintético é emitido como callable próprio por módulo?
4. O boot guard é global oculto, local estático de wrapper, ou outra forma interna?
5. O wrapper published entrypoint é um callable sintético explícito no graph do frontend?
6. Como manter attribution e diagnostics úteis para código sintético?
7. Que mudanças mínimas precisam acontecer em specs gerais fora de `docs/compiler/pbs`?
8. O lowering deve introduzir uma classe explícita de funções sintéticas com ergonomia própria, em vez de emissão ad hoc?
## Options
### Option A
Dar representação explícita a globals e callables sintéticos já no boundary de `IRBackend`, preservando attribution e identidade suficientes para lowering posterior.
### Option B
Manter `IRBackend` sem globals explícitos e adiar essa materialização para um lowering mais baixo.
### Option C
Tratar globals como açúcar compilado diretamente para slots/ops sem entidade intermediária estável.
## Tradeoffs
### Option A
- Prós:
- boundary mais explícito e testável;
- menor inferência textual em lowers posteriores;
- facilita explicar wrapper e init synthesis.
- Contras:
- aumenta o contrato do `IRBackend`;
- pode exigir propagação além do domínio PBS.
### Option B
- Prós:
- preserva o boundary atual por mais tempo.
- Contras:
- empurra complexidade para fases posteriores;
- dificulta conformance do shape intermediário.
### Option C
- Prós:
- menor aparente custo de modelagem.
- Contras:
- fraco para teste, attribution e manutenção;
- mistura lowering demais cedo.
## Recommendation
Seguir com a **Option A**, salvo impedimento forte de boundary cross-domain.
## Current Direction
Os pontos abaixo já podem ser tratados como direção fechada desta agenda, salvo objeção nova forte:
1. globals devem entrar explicitamente no `IRBackend`;
2. o pipeline não deve adiar globals para uma materialização implícita tardia abaixo desse boundary;
3. fragments de init por arquivo, init sintético por módulo, init de projeto e wrapper published entrypoint devem existir como callables sintéticos explícitos;
4. o boot guard deve ser materializado como um global oculto;
5. esse global oculto não pode ser referenciado nem alterado por userland;
6. o wrapper published entrypoint deve existir explicitamente no graph de lowering;
7. o lowering deve seguir direção direta para as operações de globals já suportadas em `IRVM`/VM, isto é, `GET_GLOBAL` e `SET_GLOBAL`;
8. attribution e diagnostics devem preservar separadamente:
- origem em source userland,
- e origem sintética gerada pelo compiler;
9. quando algum erro estrutural ou de lowering surgir em código sintetizado, a superfície sintética deve ser capaz de carregar attribution de volta ao código real que originou aquele trecho;
10. spans e diagnostics devem preferir apontar para código real de userland sempre que essa origem existir;
11. o frontend/lowering deve introduzir uma classe explícita de funções sintéticas com ergonomia própria;
12. a emissão dessas funções não deve ser ad hoc caso a caso.
## Synthetic Callable Direction
Esta agenda também fecha a seguinte direção arquitetural:
1. callables sintéticos não devem ser tratados como acidentes de emissão;
2. eles devem possuir classe/identidade própria no lowering;
3. essa classe deve cobrir pelo menos:
- fragmentos de init por arquivo,
- init sintético por módulo,
- init de projeto,
- wrapper físico publicado;
4. a ergonomia dessa classe própria deve facilitar:
- ordenação,
- attribution,
- debug,
- testes,
- e futuras extensões de lifecycle sem reabrir o modelo básico.
Também fica fechada a seguinte exigência de diagnóstico:
1. a superfície sintética precisa carregar origem suficiente para remapear erros ao código real;
2. quando existir origem userland inequívoca, o diagnóstico deve preferir essa origem em vez de um span puramente sintético;
3. spans puramente sintéticos só devem aparecer quando não houver origem real defensável.
## Hidden Boot Guard Direction
O boot guard também fica com direção fechada nesta agenda:
1. ele deve existir como global oculto de programa;
2. ele pertence ao estado interno publicado pelo compiler;
3. userland não pode nomeá-lo, ler seu valor ou alterá-lo;
4. sua única função é garantir a semântica one-shot do bootstrap no wrapper físico.
## IRBackend Shape Direction
Esta agenda também fecha o seguinte shape estrutural mínimo para o `IRBackend`.
### 1. Backend Globals
O `IRBackend` deve carregar globals explicitamente como entidades estruturais, não apenas como efeitos implícitos no corpo de funções.
Direção mínima recomendada para cada global:
- `name`
- `ownerModuleId`
- `type`
- `slot`
- `visibility`
- `isHidden`
- `origin`
Isso deve cobrir:
- globals de userland;
- e globals ocultos do compiler, incluindo o boot guard.
### 2. Backend Callables
O `IRBackend` deve distinguir explicitamente:
- callables normais de userland;
- callables sintéticos gerados pelo compiler.
### 3. Synthetic Callable Kind
O conjunto mínimo de kinds sintéticos desta agenda deve cobrir:
- `FILE_INIT_FRAGMENT`
- `MODULE_INIT`
- `PROJECT_INIT`
- `PUBLISHED_FRAME_WRAPPER`
### 4. Synthetic Origin
Todo callable ou global sintético deve carregar metadados suficientes para attribution e remapeamento de diagnóstico.
Direção mínima recomendada:
- `derivedFromFile`
- `derivedFromModule`
- `derivedFromUserSymbol`
- `primarySpan`
- `fallbackSyntheticLabel`
### 5. Hidden Global Kind
O boot guard deve aparecer como global oculto com identidade estrutural explícita, não como convenção informal de nome.
Direção mínima recomendada:
- `BOOT_GUARD`
## Diagnostics and Conformance Direction
Esta agenda também fecha o seguinte conjunto mínimo de checks estruturais e evidências de conformance.
### Structural Diagnostics / Validation
1. `synthetic wrapper entrypoint missing`
- quando o pipeline não conseguir publicar o wrapper exigido.
2. `published entrypoint is not function index 0`
- quando o lowering violar o protocolo físico.
3. `hidden boot guard is missing`
- quando a semântica one-shot exigir o guard e ele não existir.
4. `synthetic callable origin missing`
- quando o lowering gerar callable sintético sem attribution suficiente para diagnóstico defensável.
### Conformance / Fixture Expectations
1. fixture com `declare global` + `[Init]` por arquivo + `[Init]` de projeto + `[Frame]`;
2. evidência de geração de:
- file init fragment,
- module init,
- project init,
- published wrapper,
- hidden boot guard;
3. evidência de que o wrapper ocupa `func_id = 0`;
4. evidência de que `FRAME_RET` está no wrapper;
5. evidência de que erro em lowering sintético remapeia para span real quando houver origem de userland defensável.
## Spec and Learn Propagation Direction
Esta agenda também fecha a seguinte direção editorial:
1. specs de lowering devem explicar de forma normativa:
- a classe de callables sintéticos,
- o lifecycle de init no lowering,
- o wrapper publicado,
- o hidden boot guard,
- e a relação desses artefatos com attribution e diagnostics;
2. `learn` deve explicar esse modelo de forma didática com exemplos de código source;
3. `learn` deve mostrar como:
- `declare global`,
- `[Init]` por arquivo,
- `[Init]` de projeto,
- e `[Frame]`
se compõem até virar o wrapper físico publicado;
4. a explicação didática em `learn` deve privilegiar exemplos concretos de source e composição, não apenas descrição abstrata do pipeline.
## Expected Spec Material
Se esta agenda fechar, a propagação esperada atinge pelo menos:
- `13. Lowering IRBackend Specification.md`
- specs gerais de lowering/backend fora do domínio PBS, se necessário
- `12. Diagnostics Specification.md`
## Non-Goals
Esta agenda não deve:
1. redefinir surface syntax;
2. redefinir lifecycle;
3. redefinir manifest publication;
4. fechar catálogo final de fixtures.
## Next Step
Depois de fechar esta agenda, abrir ou aprofundar:
- `19.5. Diagnostics, Manifest Propagation, and Conformance Coverage Agenda`

View File

@ -1,277 +0,0 @@
# Diagnostics, Manifest Propagation, and Conformance Coverage Agenda
## Status
Closed
## Parent Agenda
This agenda derives from:
- `19. Globals, Synthetic Module Init, and FRAME_RET Agenda`
Expected fixed inputs from previous stages:
- `19.1. PBS Globals Surface, Identity, and Module Boundaries Agenda`
- `19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda`
- `19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda`
- `19.4. Globals and Lifecycle Lowering to IRBackend/IRVM Agenda`
## Purpose
Consolidate the propagation layer of topic `19` after the architectural decisions are already fixed.
This agenda must close:
- the diagnostics surface;
- manifest-facing propagation details;
- fixture and conformance coverage;
- and the acceptance gates for declaring topic `19` ready to become a decision plus implementation plan.
## Domain Owner
`docs/compiler/pbs`
Este tema pertence ao domínio PBS, mas toca tanto specs normativas quanto critérios de teste e artefato publicado.
## Context
Depois que surface, lifecycle, published entrypoint e lowering estiverem fechados, ainda faltará consolidar:
- quais erros novos são obrigatórios;
- em que fase cada erro aparece;
- como o manifest final reflete a arquitetura escolhida;
- e que coverage mínima de fixtures e gates garante que a série 19 ficou estável.
Esta agenda é de consolidação. Ela não deve rediscutir a arquitetura central.
## Inputs Already Fixed Elsewhere
Os seguintes inputs devem ser tratados como fixos aqui:
- shape de globals vindo de `19.1`;
- lifecycle vindo de `19.2`;
- publication contract vindo de `19.3`;
- lowering mechanics vindo de `19.4`.
## Decisions To Produce
Esta agenda deve produzir direção suficiente para fechar:
1. catálogo mínimo de diagnósticos;
2. fase responsável por cada diagnóstico;
3. propagação final para manifest/specs;
4. fixture matrix mínima;
5. critérios de aceite para converter a série 19 em `decision` e depois `pull-request/plan`.
## Core Questions
1. Quais diagnósticos são obrigatórios para `declare global`, imports/reexports e ciclos?
2. Quais diagnósticos são obrigatórios para `[Init]` e `[Frame]`?
3. Quais erros pertencem a parser/AST, static semantics/linking, lowering, ou toolchain full pipeline?
4. Como o manifest final deve refletir entrypoint lógico e/ou físico escolhido em `19.3`?
5. Que fixtures mínimas precisam existir para globals, module init, boot failure, wrapper e `FRAME_RET`?
6. Em que ponto a configuração explícita antiga de entrypoint em `FrontendSpec` pode ser considerada removida?
7. Quais gates de conformance precisam ser atualizados para cobrir a série 19?
## Options
### Option A
Consolidar diagnostics e coverage somente depois que os quatro stages anteriores estiverem fechados, com fixture matrix explícita por fase.
### Option B
Começar fixtures e diagnostics cedo, mesmo com arquitetura ainda mudando.
## Tradeoffs
### Option A
- Prós:
- reduz retrabalho;
- evita congelar erro e coverage cedo demais;
- combina melhor com a disciplina de umbrella agenda.
- Contras:
- posterga parte da validação final.
### Option B
- Prós:
- feedback mais cedo.
- Contras:
- alto risco de churn e reabertura de artefatos;
- conflita com os locking rules da umbrella 19.
## Recommendation
Seguir com a **Option A**.
## Current Direction
Os pontos abaixo já podem ser tratados como direção fechada desta agenda, salvo objeção nova forte:
1. a 19.5 não reabre arquitetura; ela consolida diagnostics, propagation e coverage da série 19;
2. o catálogo final deve ser agrupado por fase, não apenas por ordem histórica das agendas;
3. a propagation final deve nomear explicitamente:
- PBS specs,
- general compiler specs,
- runtime cross-domain owner,
- e `learn`;
4. a conformance matrix mínima deve cobrir:
- positive source flow,
- negative frontend cases,
- negative lowering/structural cases,
- runtime integration.
## Consolidated Diagnostics Direction
Esta agenda fecha a seguinte consolidação de diagnósticos por fase.
### Frontend / Static Semantics
- `global initializer uses unsupported form`
- `global dependency cycle detected`
- `imported symbol shadows existing visible symbol; alias required`
- `global import must resolve through a global barrel entry`
- `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`
- `Init attribute target invalid`
- `project init must be colocated with frame`
- `InitAllowed is valid only on SDK host methods`
- `host call not allowed during init`
### Lowering / Structural Validation
- `synthetic wrapper entrypoint missing`
- `published entrypoint is not function index 0`
- `hidden boot guard is missing`
- `synthetic callable origin missing`
### Runtime / Boot Failure
- `boot failed during module init`
- `boot failed during project init`
Também fica fechada a seguinte leitura:
1. diagnósticos de frontend/static semantics são user-facing do compiler;
2. checks de lowering podem aparecer como diagnostics, validation failures ou invariant violations, desde que a falha seja observável e testável;
3. falhas de boot do runtime pertencem à superfície de falha operacional, não ao frontend static diagnostic catalog.
## Propagation Targets Direction
Esta agenda fecha a seguinte lista mínima de propagation targets.
### PBS Specs
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `9. Dynamic Semantics Specification.md`
- `11. AST Specification.md`
- `12. Diagnostics Specification.md`
- `13. Lowering IRBackend Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
### General Compiler Specs
- `15. Bytecode and PBX Mapping Specification.md`
- `20. IRBackend to IRVM Lowering Specification.md`
### Runtime Cross-Domain Owner
- `../runtime/docs/runtime/agendas/025-cartridge-manifest-entrypoint-removal-and-runtime-protocol.md`
### Learn
- um learn consolidado para globals + lifecycle + published wrapper + entrypoint protocol
- com explicação source-first e depois lowering/publication
## Conformance Matrix Direction
Esta agenda fecha a seguinte matrix mínima de coverage.
### Positive Coverage
Projeto com:
- `declare global`
- `[Init]` por arquivo
- `[Init]` de projeto
- `[Frame]`
Assert mínimo:
- globals aceitos
- ordering aceito
- wrapper publicado
- `func_id = 0`
- `FRAME_RET` no wrapper
- boot guard presente
### Negative Frontend Coverage
- `global` com `fn` no initializer
- `global` com `if`
- ciclo entre globals
- collision entre import e `const`/`global`/`service`/`fn`
- `[Init]` com assinatura errada
- `[Frame]` com assinatura errada
- dois `[Frame]`
- dois `project init`
- `project init` fora do arquivo do `[Frame]`
- host call em init sem `[InitAllowed]`
- `[InitAllowed]` em target inválido
### Negative Lowering Coverage
- ausência de wrapper publicado
- wrapper fora do índice `0`
- ausência de boot guard
- callable sintético sem origin metadata
### Runtime Integration Coverage
- artefato sobe com entrypoint físico `0`
- runtime não depende de export nominal para boot
- boot failure em module init gera falha coerente
- boot failure em project init gera falha coerente
## Exit Direction
Esta agenda considera a série 19 pronta para virar execução quando houver:
1. catálogo consolidado de diagnósticos fechado;
2. propagation targets explicitamente nomeados;
3. conformance matrix mínima aceita;
4. owner explícito para a frente cross-domain de runtime.
## Expected Spec Material
Se esta agenda fechar, a propagação esperada atinge pelo menos:
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
- `12. Diagnostics Specification.md`
- `13. Lowering IRBackend Specification.md`
- docs de conformance/fixtures relevantes
## Non-Goals
Esta agenda não deve:
1. redefinir semântica de globals;
2. redefinir lifecycle;
3. redefinir wrapper ou ownership de `FRAME_RET`;
4. redefinir shape de IR.
## Next Step
Esta agenda foi consolidada em:
- `docs/compiler/pbs/decisions/Diagnostics, Manifest Propagation, and Conformance Coverage Decision.md`
Com isso, a família `19` fica pronta para ser decomposta em `pull-request/plan` de execução.

View File

@ -1,76 +0,0 @@
# PBS Agendas
This directory contains active PBS discussion agendas.
Closed agendas are moved to `docs/compiler/pbs/agendas/archive`.
## Active Agendas
1. `18.4. Asset References in Game Code - Names vs Compile-Time Lowering Agenda.md`
2. `18.5. Ignored Call Results in Executable Lowering Agenda.md`
3. `19. Globals, Synthetic Module Init, and FRAME_RET Agenda.md`
4. `19.1. PBS Globals Surface, Identity, and Module Boundaries Agenda.md`
5. `19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda.md`
6. `19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda.md`
7. `19.4. Globals and Lifecycle Lowering to IRBackend-IRVM Agenda.md`
8. `19.5. Diagnostics, Manifest Propagation, and Conformance Coverage Agenda.md`
## Consolidated Agenda 18 Material
Agenda 18 backend-orchestration material (`18.0` through `18.3`) is no longer part of the active agenda set.
That slice has already been propagated into:
1. the backend execution plan in `docs/compiler/pbs/pull-requests/INDEX.md` under `Backend VM Pipeline PR Sequence (Agenda 18)`,
2. decision material such as `docs/compiler/pbs/decisions/IRVM Optimization Stage Placement Decision.md`,
3. normative backend specs:
- `docs/compiler/general/specs/19. Verification and Safety Checks Specification.md`,
- `docs/compiler/general/specs/20. IRBackend to IRVM Lowering Specification.md`,
- `docs/compiler/general/specs/21. IRVM Optimization Pipeline Specification.md`,
- `docs/compiler/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`,
4. and implemented/tested backend pipeline stages in `prometeu-compiler/prometeu-build-pipeline`.
Only `18.4` and `18.5` remain open from the `18.*` family.
## Purpose
An agenda exists to drive a decision, not to serve as final normative text.
Use an agenda when:
- the topic is still open,
- multiple options or tradeoffs must be evaluated,
- the scope and non-goals need to be made explicit,
- the order of discussion matters.
Move an agenda to `docs/compiler/pbs/agendas/archive` once the topic is no longer active.
## Expected Format
An agenda should usually include:
1. Title
2. Status
3. Purpose
4. Context
5. Decisions to Produce
6. Core Questions
7. Expected Spec Material
8. Non-Goals
9. Inputs
## Writing Rules
- Keep the document oriented around unresolved questions.
- Separate open questions from assumptions already fixed elsewhere.
- Name the concrete decisions the discussion must produce.
- Avoid drafting large blocks of final normative spec text here.
- Prefer explicit non-goals to prevent scope drift.
## Exit Rule
An agenda should move out of the active set when:
- the key questions have been answered,
- the architectural direction is clear enough to record,
- and the topic is ready to become a decision record and then a spec update.

View File

@ -1,53 +0,0 @@
# AST Contract and Root Model Decision
Status: Accepted
Date: 2026-03-05
Related Agenda: `docs/pbs/agendas/archive/11.1. AST Workshop 1 - AST Contract and Root Model.md`
## Context
PBS introduced `11. AST Specification.md` as the language-specific AST layer between parser output and frontend lowering to `IRBackend`.
The open question was whether AST should be standardized by one mandatory implementation model (for example one Java class hierarchy) or by observable contract obligations.
## Decision
PBS adopts an obligations-first AST contract.
The specification standardizes required observable AST behavior and invariants, not one mandatory in-memory representation.
The following are required:
1. one AST root per source file;
2. deterministic child ordering consistent with source order;
3. mandatory source attribution (`file`, `start`, `end`) on nodes consumed by diagnostics or lowering;
4. explicit declaration/statement/expression node families for the supported v1 source slice;
5. deterministic rejection for unsupported forms, without permissive synthetic AST that hides rejection.
## Invariants
1. AST conformance is implementation-language agnostic.
2. Missing required attribution on mandatory nodes is non-conformant.
3. Parser recovery may produce partial AST, but structural integrity must remain valid for continued diagnostics.
4. Lowering and diagnostics are allowed to depend on the required AST invariants above.
## Explicit Non-Decisions
1. This decision does not freeze one parser architecture.
2. This decision does not define full static-semantics rules.
3. This decision does not define `IRBackend -> IRVM` lowering.
4. This decision does not define runtime/bytecode/verifier policies.
## Spec Impact
1. `docs/pbs/specs/11. AST Specification.md` must encode the obligations-first contract and invariants.
2. `docs/pbs/specs/12. Diagnostics Specification.md` remains the authority for diagnostic identity/phase/attribution payload rules consumed by AST-facing diagnostics.
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md` may assume the mandatory AST invariants as lowering preconditions.
## Validation Notes
At minimum, Gate U evidence (per `docs/general/specs/13. Conformance Test Specification.md`) should include:
1. valid AST shape fixtures for representative declarations/statements/expressions;
2. deterministic syntax rejection fixtures with stable diagnostics;
3. attribution checks (`file/start/end`) on nodes required by diagnostics and lowering.

View File

@ -1,69 +0,0 @@
# AST Declarations and Type Surfaces Decision
Status: Accepted
Date: 2026-03-05
Related Agenda: `docs/pbs/agendas/archive/11.2. AST Workshop 2 - Declarations and Type Surfaces.md`
## Context
After closing the AST contract/root model, PBS needed a precise declaration-layer AST decision for v1 so parser output, diagnostics, and IRBackend lowering remain aligned.
The open points were:
- mandatory declaration families in AST,
- declaration identity preservation,
- declaration metadata requirements for downstream phases,
- AST/static-semantics phase boundary,
- rejection and recovery behavior for malformed declarations,
- and minimum Gate U evidence.
## Decision
PBS adopts the following declaration/type-surface AST policy for v1:
1. Mandatory declaration families include:
- imports,
- top-level `fn`,
- `struct`, `contract`, `service`, `error`, `enum`, `callback`,
- `declare const`,
- and declaration nodes required by barrel/linking flow.
2. Declaration identity is preserved at AST boundary; implementations must not prematurely merge declarations (including overload sets).
3. Minimum declaration metadata includes:
- declaration name,
- declared signature/surface (parameters/return when applicable),
- stable source attribution (`file/start/end`),
- and required declaration-level syntactic flags/attributes needed by later phases.
4. AST/static boundary is explicit:
- AST preserves structure,
- static/linking phases own semantic compatibility and resolution rules.
5. Unsupported declaration forms are deterministic parser/AST rejection with stable diagnostics.
6. Recovery may continue after declaration syntax errors, but recovered AST must remain structurally coherent and attribution-consistent.
7. Gate U evidence must include positive and negative declaration fixtures with AST-shape, attribution, and diagnostics assertions.
## Invariants
1. Declaration AST remains obligations-first and implementation-language agnostic.
2. Overload identity is not collapsed at AST layer.
3. Missing required declaration metadata on mandatory nodes is non-conformant.
4. Recovery must not fabricate permissive declaration shapes that hide syntax failures.
## Explicit Non-Decisions
1. This decision does not define static type-checking algorithms.
2. This decision does not define lowering from `IRBackend` to `IRVM`.
3. This decision does not define runtime/bytecode/verifier policy.
4. This decision does not freeze one parser architecture.
## Spec Impact
1. `docs/pbs/specs/11. AST Specification.md` must encode declaration families, identity preservation, metadata minimums, and recovery/rejection invariants.
2. `docs/pbs/specs/12. Diagnostics Specification.md` remains authority for diagnostic identity/phase/attribution semantics consumed by declaration diagnostics.
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md` may assume declaration metadata invariants as lowering preconditions.
## Validation Notes
Gate U evidence (per `docs/general/specs/13. Conformance Test Specification.md`) should include:
1. valid declaration fixtures for each mandatory family,
2. malformed declaration fixtures with deterministic rejection diagnostics,
3. AST assertions for declaration identity, spans, and required metadata fields.

View File

@ -1,64 +0,0 @@
# AST Diagnostics, Recovery, and Gate Evidence Decision
Status: Accepted
Date: 2026-03-05
Related Agenda: `docs/pbs/agendas/archive/11.4. AST Workshop 4 - Diagnostics, Recovery, and Gate Evidence.md`
## Context
After closing AST contract, declaration surfaces, and statement/expression surfaces, PBS needed to close AST-facing diagnostics and parser-recovery policy plus the minimum Gate U evidence baseline.
Additionally, localization policy needed explicit alignment: diagnostics wording is locale-dependent and should be keyed by stable message tokens/template ids.
## Decision
PBS adopts the following AST diagnostics/recovery/evidence policy:
1. AST must preserve diagnostic fidelity:
- required syntax diagnostics remain stable in `code`, `severity`, `phase`, `primary file`, and `primary span`.
2. Human-readable message text is locale/rendering-dependent and not a conformance identity key.
3. Stable diagnostics identity for i18n is carried by:
- `diagnostic code`,
- `phase`,
- `message template id` (token),
- and primary attribution.
4. Parser recovery is allowed to continue diagnostics, but recovered AST must remain structurally coherent and attribution-consistent.
5. Recovery must not fabricate permissive valid shapes that hide real syntax failures.
6. Gate U AST evidence must include:
- representative valid AST fixtures,
- malformed/recovery fixtures,
- deterministic diagnostics assertions,
- and attribution assertions (`file/start/end`) on required nodes.
7. Minimum mandatory negative fixture families include:
- unexpected token in declaration context,
- missing required closer (`)`, `}`, or `;`) as applicable,
- non-associative forbidden chain forms,
- unsupported form outside the active syntax slice with deterministic rejection.
## Invariants
1. Diagnostics identity is token-based and locale-agnostic.
2. Recovery cannot downgrade a required rejection into accepted semantics.
3. AST attribution quality remains sufficient for `12` diagnostics contract and `13` lowering preconditions.
4. Gate U fixtures must lock rejection stability for required AST-facing failures.
## Explicit Non-Decisions
1. This decision does not define transport-specific wire schemas.
2. This decision does not define static type-checking rules.
3. This decision does not define backend/runtime/verifier algorithms.
4. This decision does not require one exact localized wording set.
## Spec Impact
1. `docs/pbs/specs/11. AST Specification.md` must encode recovery integrity and AST-facing rejection/recovery invariants.
2. `docs/pbs/specs/12. Diagnostics Specification.md` remains authority for diagnostics identity fields, including template/token identity.
3. `docs/general/specs/13. Conformance Test Specification.md` provides Gate U evidence obligations referenced here.
## Validation Notes
Gate U validation should assert:
1. stable diagnostic identity keys (`code`, `phase`, template/token id, primary attribution),
2. recovery integrity without semantic masking,
3. deterministic results for the mandatory negative fixture families above.

View File

@ -1,51 +0,0 @@
# AST Statements and Expressions Decision
Status: Accepted
Date: 2026-03-05
Related Agenda: `docs/pbs/agendas/archive/11.3. AST Workshop 3 - Statements and Expressions.md`
## Context
After closing AST contract/root and declaration surfaces, PBS needed a precise v1 decision for statement/expression AST obligations, including precedence/associativity representation, unsupported-form behavior, and Gate U evidence.
## Decision
PBS adopts the following statement/expression AST policy for v1:
1. Mandatory statement/expression AST families must cover the supported PBS core syntax slice, including at minimum:
- statements: `block`, `let`, `return`, expression statement, and other supported statement forms;
- expressions: `identifier`, literals, `unary`, `binary`, `call`, `group`, and other supported expression forms.
2. Precedence and associativity parsing outcomes are normative via AST shape and must be preserved explicitly.
3. Non-associative or forbidden chained forms are deterministic reject with stable diagnostics.
4. AST remains structural; semantic compatibility/type decisions are owned by static semantics/linking phases.
5. Unsupported statement/expression forms are deterministic reject and must not be represented by permissive synthetic placeholder nodes that mask real rejection.
6. Parser recovery may continue after syntax errors, but recovered AST must remain structurally coherent with stable attribution.
7. Gate U evidence must include positive and negative fixtures with AST-shape assertions and diagnostics assertions.
## Invariants
1. Statement/expression AST obligations are implementation-language agnostic.
2. AST shape must not be post-rewritten in a way that changes source-observable parse meaning.
3. Required nodes for diagnostics/lowering must preserve stable `file/start/end`.
4. Recovery must preserve integrity and must not silently convert invalid syntax into valid semantics.
## Explicit Non-Decisions
1. This decision does not define static type-checking algorithms.
2. This decision does not define `IRBackend -> IRVM` lowering.
3. This decision does not define runtime/bytecode/verifier policy.
4. This decision does not freeze one parser implementation strategy.
## Spec Impact
1. `docs/pbs/specs/11. AST Specification.md` must encode statement/expression node-family obligations, precedence/associativity shape obligations, and recovery/rejection invariants.
2. `docs/pbs/specs/12. Diagnostics Specification.md` remains the authority for stable diagnostics identity/phase/attribution requirements.
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md` may assume statement/expression AST invariants as lowering preconditions.
## Validation Notes
Gate U evidence (per `docs/general/specs/13. Conformance Test Specification.md`) should include:
1. valid fixtures proving expected precedence/associativity AST shape;
2. invalid fixtures for non-associative or unsupported forms with deterministic diagnostics;
3. assertions for stable node attribution (`file/start/end`) where diagnostics and lowering consume those nodes.

View File

@ -1,154 +0,0 @@
# Allocation and Cost Visibility Decision
Status: Accepted (Implemented)
Cycle: Initial allocation-and-cost closure pass
## 1. Context
PBS v1 needs a minimal but explicit contract for which runtime cost facts matter semantically and which belong only to diagnostics/profiling quality.
Earlier decisions already fixed important inputs:
- `bind(context, fn_name)` has real retention/storage consequences,
- `optional`, `result`, `handle`, `!`, `if`, and `switch` are not intended to hide implicit allocation semantics,
- host/userland interaction is stack-only across the boundary,
- and value categories already distinguish copied payload from preserved aliasing.
## 2. Decision
PBS v1 adopts the following cost-visibility baseline:
1. The normatively relevant cost facts are:
- whether an operation may allocate VM-owned runtime storage,
- whether an operation retains state beyond the current evaluation,
- whether an operation copies payload versus preserves aliasing,
- whether an operation crosses the host boundary,
- and whether an operation may trap.
2. `bind(context, fn_name)` is normatively retention-bearing and requires runtime storage sufficient to keep the callback target and captured context alive.
3. `apply` is not allocation-bearing by itself.
4. `optional`, `result`, `handle`, `!`, `if`, and `switch` are not allocation-bearing by themselves.
5. Host-boundary crossing is a normatively relevant cost fact, but concrete host-side allocation details belong to subsystem-specific contracts rather than to a general PBS rule.
6. Quantitative reporting such as exact byte counts, exact object counts, or precise collector timing is not a normative language guarantee in v1.
## 3. Normatively Relevant Cost Facts
The following cost facts are part of the PBS semantic model and may be relied on by later tooling/spec work:
- VM allocation-bearing versus non-allocation-bearing behavior,
- retention-bearing versus non-retention-bearing behavior,
- copy versus aliasing preservation,
- host-boundary crossing,
- trap possibility.
These facts matter because they affect how advanced tooling, diagnostics, and performance reasoning should interpret a construct.
## 4. `bind`
`bind(context, fn_name)` is the strongest closed cost case in the current PBS core.
Rules:
- `bind` is not semantically free,
- `bind` is retention-bearing,
- `bind` requires runtime storage sufficient to preserve the callback target and captured context,
- the captured context remains alive while the callback value remains alive.
This decision does not require the spec to freeze the exact runtime layout used to implement that storage.
## 5. Non-Allocation-Bearing Surfaces
The following constructs are not allocation-bearing by themselves in PBS v1:
- `optional`
- `result`
- `handle`
- `!`
- `if`
- `switch`
- `apply`
If allocation or retention occurs while evaluating one of these constructs, that cost arises from:
- subexpression evaluation,
- called targets,
- payload formation already defined elsewhere,
- or runtime behavior outside the surface itself.
## 6. Copy Versus Aliasing
Copy versus aliasing is a normatively relevant cost fact.
The language already distinguishes:
- pure values copied by value,
- identity-bearing values passed by preserved aliasing,
- carriers that preserve the semantics of their contained values.
Tooling and later specs may rely on these distinctions even if PBS v1 does not require a warning at every such site.
## 7. Host Boundary
Crossing the host boundary is a normatively relevant cost fact.
However, this decision does not impose a universal rule for:
- host-side allocation volume,
- host-side object count,
- or host-side retention internals.
Those details belong to subsystem-specific contracts when and if they become relevant.
## 8. Normative Versus Best-Effort Reporting
### 8.1 Normative facts
The following facts are normative and may be surfaced by diagnostics/tooling:
- whether a construct is retention-bearing,
- whether a construct crosses the host boundary,
- whether semantics preserve aliasing or copy payload,
- whether a construct may trap.
### 8.2 Best-effort facts
The following facts are not normative language guarantees in v1:
- exact byte counts,
- exact object counts,
- exact collector timing,
- exact host-side allocation volume,
- precise performance ranking beyond the semantic facts above.
These may be surfaced by implementations as profiling or tooling enrichment, but they are not part of the core language contract.
## 9. Invariants
- The language must not imply hidden allocation semantics where none were intentionally specified.
- `bind` remains the canonical retention-bearing callback-forming construct in v1.
- Cost visibility must be strong enough for advanced tooling without forcing exact runtime accounting into the language spec.
- Host-boundary cost reporting must not pretend to know subsystem-specific runtime internals unless those are explicitly specified.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the final diagnostics wording for warnings or notes,
- subsystem-specific host cost contracts,
- precise collection/profiling metrics,
- optimizer-facing reporting policy.
## 11. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
## 12. Validation Notes
The intended split is:
- semantic cost facts are explicit,
- `bind` is the main retained-storage construct already closed,
- most other core surfaces are not allocation-bearing by themselves,
- and quantitative performance reporting remains tooling-quality rather than normative language behavior.

View File

@ -1,133 +0,0 @@
# Artifact-Level Conformance and Fixture Model Decision
Status: Superseded
Cycle: Conformance agenda closure pass
Superseded by:
- `docs/general/specs/13. Conformance Test Specification.md` (Quality-Gate Baseline)
- `docs/general/specs/19. Verification and Safety Checks Specification.md` (Quality-Gate Baseline)
Superseded on: 2026-03-04
## 1. Context
PBS v1 needed a decision for the point where conformance stops being source-only and begins asserting artifact-facing behavior.
The open questions from the conformance agenda closure pass and Workshop 3 were:
- whether artifact-level conformance is mandatory for every claim or only for full toolchain claims,
- whether conformance should snapshot whole binaries or only stable invariants,
- what the smallest honest fixture model is for stdlib and host-backed scenarios,
- and how `13`, `12`, `15`, and `19` divide responsibility.
The adopted direction needed to keep full conformance meaningful without freezing one emitter layout, one repository structure, or one implementation-specific binary image.
## 2. Decision
PBS v1 adopts the following artifact-level conformance baseline:
1. Artifact-level conformance belongs only to `full toolchain conformance`.
2. `frontend conformance` and `source-runtime conformance` do not require artifact-level oracle checks.
3. Full toolchain conformance must assert stable artifact invariants rather than one opaque byte-for-byte binary snapshot.
4. The conformance fixture model must explicitly declare the resolved environment assumptions that affect observable admission or lowering behavior.
5. `12` defines what semantic and artifact-boundary facts lowering must preserve.
6. `15` defines how the conformance-facing artifact facts appear in PBX/bytecode-visible form.
7. `19` defines which later safety and validation obligations are checked by loader and verifier rather than by lowering itself.
## 3. Artifact-Level Oracle Baseline
The v1 artifact-level oracle is invariant-based.
Full toolchain conformance must be able to assert, at minimum:
1. required canonical host-binding declarations are emitted for admitted host-backed uses;
2. `SYSC` entries are deduplicated by canonical identity;
3. `SYSC` entry order follows first occurrence in the lowered program;
4. host-backed callsites are emitted in pre-load form as `HOSTCALL <sysc_index>` referencing the emitted canonical binding set;
5. VM-owned builtin projections, builtin constants, and intrinsic callsites do not leak into host-binding metadata such as `SYSC`;
6. stdlib interface modules remain compile-time-only and do not emit executable bytecode by themselves;
7. emitted artifacts preserve at least one source-attribution hook for backend failures that remain source-attributable and user-actionable under the diagnostics contract.
This baseline does not require:
- one full PBX binary snapshot,
- one exact section byte layout outside the stable invariants above,
- one exact source-map format,
- or one verifier-internal trace shape.
## 4. Fixture Model
Conformance fixtures must model the resolved environment honestly whenever the selected environment affects acceptance, lowering, or artifact meaning.
Every fixture that depends on environment selection must declare, as applicable:
- selected stdlib environment or reserved stdlib line,
- selected host registry line,
- granted capability set,
- and selected runtime line.
If an axis is irrelevant for a fixture, the fixture should declare that explicitly rather than leaving it implicit.
The minimum reusable fixture families for v1 are:
1. source-only fixtures whose expectations do not depend on host registry or runtime selection;
2. stdlib-resolved fixtures that name the selected stdlib environment when reserved modules affect acceptance or behavior;
3. host-admitted fixtures that name both host registry line and granted capabilities for positive host-backed cases;
4. host-rejected fixtures that name the missing or unauthorized capability or host-registry condition for deterministic negative cases;
5. full-toolchain artifact fixtures that name the runtime line whenever emitted intrinsic or host-binding form depends on the selected executable target line.
This model is intentionally small. It is sufficient to prevent fake portability claims while avoiding one mandatory repository layout.
## 5. Boundary Across `13`, `12`, `15`, and `19`
The adopted boundary is:
- `13. Conformance Test Specification.md` defines which invariant families are pass/fail conformance obligations and which fixture assumptions must be declared;
- `13. Lowering IRBackend Specification.md` defines the semantic and artifact-boundary facts that lowering must preserve before loader or verifier work begins;
- `15. Bytecode and PBX Mapping Specification.md` defines the PBX/bytecode-visible mapping of those facts into inspectable artifact surfaces;
- `19. Verification and Safety Checks Specification.md` defines the later validation and rejection obligations applied after lowering and, where relevant, after loader patching.
Conformance therefore does not require `12` to define one binary encoding and does not require `15` to redefine semantic ownership already fixed in `12`.
## 6. Invariants
- Artifact-level conformance is required only for the full toolchain claim.
- The v1 artifact oracle is invariant-based, not whole-image-based.
- Fixture assumptions that change observable behavior must be explicit.
- Host-binding metadata remains distinct from VM-owned builtin and intrinsic lowering.
- The boundary among lowering, encoding, and verification must remain reviewable and non-overlapping.
- Source-attributable backend failures must retain at least one recoverable source location, but richer debug surfaces remain optional.
## 7. Explicit Non-Decisions
This decision record does not yet close:
- which PBX sections beyond the current stable invariant baseline become part of the PBS-facing contract,
- whether intrinsic declarations require an additional dedicated PBX preload section in v1,
- the full verifier test surface for conformance,
- the compatibility-matrix policy for aging and retirement of published combinations,
- or one repository structure for the conformance corpus.
## 8. Spec Impact
This decision should feed at least:
- `docs/general/specs/13. Conformance Test Specification.md`
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
It should also constrain later work in:
- `docs/general/specs/19. Verification and Safety Checks Specification.md`
- `docs/general/specs/17. Compatibility and Evolution Policy.md`
- `docs/pbs/decisions/Compatibility Matrix and Published Claims Decision.md`
- `docs/pbs/agendas/13.4. IR and Lowering Workshop 4 - Builtins, Host Bindings, and Artifact Invariants.md`
## 9. Validation Notes
The intended operational reading is:
- a direct interpreter may still claim `source-runtime conformance` without artifact checks,
- a full compiler toolchain must expose enough artifact surface to prove the stable invariants above,
- and a host-backed test is not valid conformance evidence unless the selected registry, capability set, and runtime assumptions are declared where they affect the outcome.

View File

@ -1,164 +0,0 @@
# Compatibility Matrix and Published Claims Decision
Status: Superseded
Cycle: Conformance and compatibility agenda closure pass
Superseded by:
- `docs/general/specs/13. Conformance Test Specification.md` (Quality-Gate Baseline)
- `docs/general/specs/17. Compatibility and Evolution Policy.md` (Quality-Gate Baseline)
Superseded on: 2026-03-04
## 1. Context
PBS v1 needed one operational policy for how support claims are published, tested, aged, and retired over time.
The open questions from the conformance closure pass, especially Workshop 4, and from `17. Compatibility and Evolution Policy Agenda.md`, Workshop 3 were:
- what enters the regression corpus,
- which compatibility dimensions PBS must publish explicitly,
- what counts as a published support claim,
- how claims relate to conformance evidence,
- and how supported combinations retire without becoming ambiguous.
The adopted direction needed to ensure that compatibility tables and support statements are executable commitments rather than prose-only promises.
## 2. Decision
PBS v1 adopts the following baseline policy:
1. Published support claims must be represented by an explicit compatibility matrix.
2. Every published supported combination must be backed by maintained conformance or regression evidence appropriate to the claim level being published.
3. The regression corpus is not limited to bug reproductions; it also includes already-published normative examples, accepted behavior claims, and supported matrix combinations.
4. Unsupported combinations must be stated explicitly rather than inferred from silence.
5. Claim retirement must be deliberate: when support narrows or ends, the matrix entry, supporting tests, and migration/support note must all change together.
## 3. Compatibility Matrix Baseline
The minimum PBS compatibility matrix must expose, at minimum, the following dimensions where support is published:
1. language line,
2. stdlib line when reserved stdlib environment selection affects the claim,
3. runtime line when execution target selection affects the claim,
4. conformance claim level.
The matrix must also expose an explicit support state for each published combination.
The minimum support states are:
- `supported`
- `unsupported`
- `provisional`
Meanings:
- `supported` means the combination is promised by the publisher and backed by maintained evidence.
- `unsupported` means the combination is intentionally not promised and tools may reject or decline it without violating the published support policy.
- `provisional` means the combination is published as incomplete or experimental and must not be confused with ordinary stable support.
Silence must not be used where a published matrix exists and a reasonable reader could infer support.
## 4. Published Claims and Evidence
A published support claim exists whenever a publisher represents, in user-facing or tool-facing form, that a combination or behavior is supported, conforming, or maintained.
This includes, at minimum:
- a matrix entry marked `supported`,
- an unqualified or qualified PBS conformance claim,
- compatibility statements in product or release documentation,
- and published examples or fixtures presented as normative or supported behavior.
Every published claim must map to maintained executable evidence.
The evidence may be:
- conformance tests,
- regression tests,
- or both,
provided the evidence covers the claim scope actually being published.
`frontend conformance`, `source-runtime conformance`, and `full toolchain conformance` may therefore have different evidence sets, but each published claim still needs evidence inside its own scope.
## 5. Regression Corpus Policy
The regression corpus must preserve already-published behavior inside the scope of active support claims.
At minimum, the regression corpus must include:
1. bug reproductions for behavior that was fixed and remains within a supported scope;
2. published examples that are treated as normative or supported behavior;
3. accepted conformance claims and the behavior they promise;
4. supported compatibility-matrix combinations and their required outcomes.
The regression corpus may be organized into separate slices by claim level or domain.
What matters normatively is:
- published supported behavior is regression-protected,
- evidence remains attributable to the claim it protects,
- and narrowing support requires deliberate retirement rather than silent drift.
## 6. Retirement and Narrowing Policy
When a supported combination is retired or narrowed:
1. the matrix entry must change explicitly;
2. the old support state must not remain implied by stale documentation;
3. the corresponding evidence must be retired, reclassified, or moved to a historical/non-supporting corpus deliberately;
4. a migration, support-boundary, or rationale note must accompany the change when users could reasonably depend on the retired combination.
Retirement does not require one universal changelog format in this decision.
It does require that the support boundary become visible and reviewable.
## 7. Boundary Between `13` and `17`
The adopted split is:
- `13. Conformance Test Specification.md` defines the executable evidence obligations: what must enter the conformance or regression corpus and how supported claims become test-backed;
- `17. Compatibility and Evolution Policy.md` defines the publication policy: which matrix dimensions and support states are required and how supported combinations age or retire.
This keeps `13` test-oriented and `17` promise-oriented while ensuring both documents describe the same support contract.
## 8. Invariants
- Published support claims must be test-backed.
- A compatibility matrix is normative only when its states have executable meaning.
- `unsupported` must be explicit when omission would mislead users.
- `provisional` must not be mistaken for ordinary supported compatibility.
- Regression protection follows published supported behavior, not only bug history.
- Narrowing support is a deliberate policy act, not an accidental omission.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- exact compatibility-window lengths by domain,
- exact migration-tooling triggers,
- PBX-specific binary compatibility policy,
- release tooling implementation,
- or one repository layout for matrix and regression data.
## 10. Spec Impact
This decision should feed at least:
- `docs/general/specs/13. Conformance Test Specification.md`
- `docs/general/specs/17. Compatibility and Evolution Policy.md`
It should also constrain later work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
- `docs/pbs/agendas/17.4. Compatibility Workshop 4 - Artifact and PBX Compatibility Policy.md`
## 11. Validation Notes
The intended operational reading is:
- if a publisher marks one matrix row as `supported`, there must be maintained evidence for that row;
- if a combination is no longer supported, the matrix must say so explicitly rather than simply dropping mention of it;
- and if an example or claim is published as supported behavior, it belongs in the regression story even if it did not originate as a bug report.

View File

@ -1,167 +0,0 @@
# Conformance Claim Levels Decision
Status: Superseded
Cycle: Conformance agenda closure pass
Superseded by:
- `docs/general/specs/13. Conformance Test Specification.md` (Quality-Gate Baseline)
- `docs/general/specs/17. Compatibility and Evolution Policy.md` (Quality-Gate Baseline)
Superseded on: 2026-03-04
## 1. Context
PBS v1 needed a conformance-claim model that stays honest while the conformance corpus matures across frontend, runtime, and artifact-facing work.
The open questions from the conformance agenda closure pass and Workshop 1 were:
- whether PBS should use one conformance label or staged claims,
- what a partial implementation is allowed to claim,
- how published conformance claims must describe missing coverage,
- and how claim levels constrain later compatibility policy.
The adopted direction needed to avoid two failure modes:
- pretending an unfinished backend is already full PBS v1 conformance,
- and allowing vague marketing language that hides excluded domains such as artifact emission or verifier behavior.
## 2. Decision
PBS v1 adopts staged conformance claims.
The canonical claim levels are:
1. `frontend conformance`
2. `source-runtime conformance`
3. `full toolchain conformance`
These claims mean:
1. `frontend conformance` covers deterministic source acceptance and rejection behavior through parsing, manifest/import resolution, linking/static semantics, and the stable diagnostics surface required for those rejection tests.
2. `source-runtime conformance` covers all frontend obligations plus source-level runtime, memory/identity, and host-boundary behavior already defined as language-observable in the active specs.
3. `full toolchain conformance` covers all source-runtime obligations plus the artifact-facing, loader-facing, verifier-facing, and compatibility obligations required by the full active PBS v1 spec set.
Only `full toolchain conformance` may be published without qualifier as `PBS v1 conforming`.
Any narrower claim must remain explicitly qualified in published wording, for example:
- `PBS v1 frontend conforming`
- `PBS v1 source-runtime conforming`
An implementation that does not satisfy one complete canonical level must not claim PBS conformance merely because it implements a subset such as parsing-only or parser-plus-binder behavior.
Any partial claim must explicitly state excluded domains when they matter to user expectations, including as applicable:
- artifact emission,
- loader interaction,
- verifier behavior,
- supported runtime line,
- selected stdlib environment,
- host-registry line,
- and capability assumptions.
The unqualified claim `PBS v1 conforming` is reserved until the artifact-facing conformance surface is fully closed in `13`, `12`, `15`, and `19`.
## 3. Claim Meanings
### 3.1 Frontend Conformance
`frontend conformance` is the minimum canonical PBS conformance claim.
It requires:
- deterministic parsing behavior,
- deterministic source rejection for in-scope syntax, linking, and static-semantics failures,
- deterministic manifest/import resolution outcomes,
- regression protection for already-published behavior inside that claim scope,
- and the stable diagnostics fields required by the diagnostics contract for those failures.
It does not imply:
- runtime execution support,
- host-backed call execution,
- artifact emission,
- loader integration,
- or verifier integration.
### 3.2 Source-Runtime Conformance
`source-runtime conformance` extends `frontend conformance`.
It additionally requires:
- source-level runtime oracle coverage,
- source-level memory and identity oracle coverage,
- host-boundary behavior already fixed by the Host ABI and capability specs at source-visible level,
- and regression protection for already-published behavior inside that claim scope.
It does not by itself imply:
- one normative PBX image shape,
- one artifact-level golden contract,
- loader patching behavior beyond source-visible requirements,
- or verifier-surface conformance.
### 3.3 Full Toolchain Conformance
`full toolchain conformance` is the top-level PBS v1 conformance claim.
It requires:
- all `source-runtime conformance` obligations,
- all artifact-level oracle requirements once closed,
- loader/verifier-facing acceptance and rejection obligations that belong to PBS-facing conformance,
- required fixture modeling for stdlib, registry, capability, and runtime lines,
- and maintained regression/compatibility evidence for every published supported combination inside the claim.
Until those artifact-facing obligations are normatively closed, implementations may publish only the narrower qualified claims above.
## 4. Naming and Publication Rules
- If the word `conforming` is used in a PBS v1 product claim, it must use one of the canonical claim levels.
- The bare wording `PBS v1 conforming` is reserved for the full toolchain claim only.
- `frontend` and `source-runtime` claims must keep the qualifier adjacent to the published claim and must not be shortened to imply full PBS v1 conformance.
- If an implementation is still below `frontend conformance`, it should describe itself as partial, experimental, or implementation-specific rather than conforming.
- Published conformance claims must state the tested scope when environment selection changes observable behavior.
## 5. Invariants
- PBS conformance is staged, not all-or-nothing, during the v1 maturation path.
- The meaning of the unqualified top-level claim must remain stronger than any partial claim.
- Partial claims must not hide excluded domains behind vague wording.
- Conformance claims and compatibility claims are related but not identical; compatibility policy may refine promise strength per claim level without redefining the claim levels themselves.
- Published claims must be backed by executable evidence in the conformance or regression corpus appropriate to that claim level.
## 6. Explicit Non-Decisions
This decision record does not yet close:
- the full fixture model for stdlib, host-registry, capability, and runtime-line scenarios,
- the final artifact-level oracle for PBX or lowering invariants,
- the compatibility-matrix dimensions and retirement policy,
- or the exact repository layout of the conformance corpus.
## 7. Spec Impact
This decision should feed at least:
- `docs/general/specs/13. Conformance Test Specification.md`
- `docs/general/specs/17. Compatibility and Evolution Policy.md`
It should also constrain later work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
- `docs/general/specs/19. Verification and Safety Checks Specification.md`
- `docs/pbs/decisions/Artifact-Level Conformance and Fixture Model Decision.md`
- `docs/pbs/decisions/Compatibility Matrix and Published Claims Decision.md`
- `docs/pbs/agendas/17.1. Compatibility Workshop 1 - Compatibility Domains and Promise Levels.md`
## 8. Validation Notes
The intended operational reading is:
- a parser-plus-binder implementation may claim `frontend conformance` only if it actually satisfies the complete frontend obligations, including deterministic rejection behavior and the stable diagnostics surface in scope,
- an interpreter or direct-execution implementation may claim `source-runtime conformance` without yet claiming artifact or verifier conformance,
- and no implementation should imply full PBS v1 conformance until the artifact-facing contract is normatively testable.

View File

@ -1,215 +0,0 @@
# Diagnostics Contract Decision
Status: Accepted (Implemented)
Cycle: Diagnostics agenda closure pass
## 1. Context
PBS v1 needed one coherent diagnostics contract that closes the open questions from the diagnostics agenda:
- diagnostic identity,
- attribution and cross-file reporting,
- wording and localization boundaries,
- warning and cost-diagnostics policy,
- and the boundary between PBS-facing diagnostics and backend/artifact-facing failures.
The adopted direction needed to stay deterministic and conformance-friendly without freezing one editor UX, one compiler architecture, or one backend-internal reporting format.
## 2. Decision
PBS v1 adopts the following diagnostics baseline:
1. Every PBS-facing diagnostic has a mandatory `diagnostic code`.
2. Every PBS-facing diagnostic has a mandatory `severity`.
3. The stable external diagnostic phases include:
- `syntax`,
- `static semantics`,
- `manifest/import resolution`,
- `linking`,
- `host-binding/capability admission`,
- and load-facing rejection when directly attributable to malformed or unauthorized PBS-facing artifact usage.
4. `linking` is a first-class diagnostics phase and should remain visible to users as part of the didactic pipeline.
5. The minimum source-facing payload is:
- `diagnostic code`,
- `severity`,
- `phase`,
- `primary file`,
- `primary span/location`,
- and a human-readable message.
6. The diagnostics model must also carry a stable `message template id` with stable named placeholders for localized rendering.
7. Human wording is not byte-for-byte normative. The normative contract is the stable association among diagnostic code, message template id, placeholders, and rejection meaning.
8. Implementations may localize rendered messages by language, provided the rendered message preserves the same normative rejection meaning.
9. For future interoperability-oriented transports such as a possible LSP integration, implementations should preserve the ability to render an English default/fallback message even when a product renders another locale locally.
10. In cross-file failures, the primary site must be the source location where the user action triggered the failure.
11. `notes` and `related sites` are optional by default.
12. For `duplicate` and `conflict` classes, at least one related site is mandatory.
13. `hint` is a reserved diagnostics category in v1, but hint content is not mandatory.
14. `help` and guided remediation are outside the core conformance contract in v1.
15. Warnings are supported and recommended in v1, but they are not part of the minimum mandatory conformance baseline.
16. Qualitative cost facts may be surfaced as warnings or notes, especially for:
- retention-bearing `bind`,
- host-boundary crossings,
- and observable copy-versus-alias behavior.
17. Quantitative reporting such as byte counts, allocation counts, and performance ranking is outside the diagnostics contract and belongs to profiling/tooling.
18. Only backend-originated failures that remain source-attributable and user-actionable belong to the PBS-facing diagnostics contract.
19. Pure artifact corruption, verifier internals, loader internals, and compiler implementation bugs remain outside the PBS-facing diagnostics contract unless they are directly attributable to validly analyzed PBS source or to malformed/unauthorized PBS-facing artifact usage already in scope.
20. 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.
## 3. Diagnostic Identity and Payload
The minimum stable identity of a PBS-facing diagnostic is not free-form wording.
The stable identity is carried by:
- `diagnostic code`,
- stable phase attribution,
- and the rejection class semantics represented by the code/template pair.
The minimum externally relevant fields are:
- `diagnostic code`,
- `severity`,
- `phase`,
- `primary file`,
- `primary span/location`,
- `message template id`,
- stable named placeholders,
- and a rendered human-readable message.
This baseline keeps diagnostics testable and localizable without forcing one exact byte-for-byte phrasing.
## 4. Cross-File Attribution
Cross-file attribution follows an action-first rule.
Rules:
- import failures point primarily to the importing site,
- barrel failures point primarily to the barrel entry or reference site that triggered the failure,
- linking or cross-module lookup failures 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 in addition to the primary site.
This keeps diagnostics actionable for users and stable enough for conformance.
## 5. Message Rendering and Localization
PBS v1 permits localized diagnostics, including localized editor-first experiences.
The normative boundary is:
- codes are stable,
- template ids are stable,
- placeholders are stable,
- and rendered wording may vary by locale and product surface.
Examples in specs should therefore be treated as illustrative unless a spec explicitly marks a template shape or placeholder contract as normative.
## 6. Categories, Notes, and Hints
The stable visible categories currently reserved are:
- `error`,
- `warning`,
- `note`,
- `hint`.
`notes` are optional by default in v1.
`hint` exists in the diagnostics model from v1 onward so implementations can grow into educational guidance without changing the core schema.
This decision does not require one exact distinction between short hints and richer remediation flows.
## 7. Warning and Cost-Diagnostics Boundary
PBS v1 deliberately keeps warnings out of the minimum conformance baseline.
This means:
- implementations may emit warnings,
- the editor can use warnings aggressively for pedagogy,
- but conformance does not currently fail merely because an implementation omits optional warnings.
The diagnostics contract does recognize the importance of qualitative cost facts already fixed elsewhere, but it does not promote them to mandatory warnings in v1.
## 8. Backend-Originated Failure Boundary
PBS-facing diagnostics stop where failures stop being source-attributable and user-actionable.
In scope for PBS-facing diagnostics:
- lowering failures that reflect a normative source-facing lowering rule or impossibility,
- verifier or loader rejections that are directly attributable to malformed or unauthorized PBS-facing artifact usage,
- and backend-originated failures that can still be mapped back to source in a way the user can act on.
Out of scope for PBS-facing diagnostics:
- internal compiler exceptions,
- implementation bugs,
- artifact corruption not attributable to valid PBS source or to in-scope malformed/unauthorized artifact usage,
- and backend-internal failure surfaces with no stable user-facing source attribution.
## 9. Conformance Boundary
The conformance surface for diagnostics should check only stable external fields.
Conformance may assert:
- rejection versus acceptance,
- diagnostic code,
- severity/category when in scope,
- phase,
- source attribution,
- and related-site requirements for narrow classes such as `duplicate` or `conflict`.
Conformance should not require:
- one exact rendered message,
- one exact localized wording,
- one exact note shape outside explicitly required classes,
- one verifier/loader internal format,
- or one profiling/reporting style.
Warnings remain outside pass/fail conformance in v1, though any emitted warning must remain semantically compatible with the spec.
## 10. Invariants
- The diagnostics contract must remain deterministic across conforming implementations.
- Diagnostic identity must not depend on one locale or one exact rendered sentence.
- `linking` remains a visible diagnostics phase rather than being collapsed away into a generic resolution bucket.
- Cross-file diagnostics must remain action-oriented from the user's point of view.
- Localized rendering must not erase the stable machine-readable identity of a diagnostic.
- The contract must stay narrow enough that more than one toolchain can implement it.
- Backend-internal reporting must not leak into the PBS language contract unless the failure is source-attributable and user-actionable.
## 11. Explicit Non-Decisions
This decision record does not yet close:
- the full warning catalog for future versions,
- whether a future version promotes a subset of warnings into mandatory conformance,
- exact remediation/help-content policy,
- exact source-map or artifact-offset formats,
- verifier trace schemas,
- transport-specific LSP field mapping,
- or internal compiler bug-reporting policy.
## 12. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
- `docs/general/specs/19. Verification and Safety Checks Specification.md`
## 13. Validation Notes
The intended operational reading is:
- diagnostics are machine-identifiable first and human-rendered second,
- localized editor UX is fully compatible with the contract,
- a future interoperable transport can still fall back to English rendering,
- warnings are available for pedagogy without being required for conformance,
- and backend-originated failures only enter the PBS-facing contract when they still behave like actionable source diagnostics rather than internal tool failures.

View File

@ -1,210 +0,0 @@
# Diagnostics, Manifest Propagation, and Conformance Coverage Decision
Status: Accepted
Date: 2026-03-22
Related Agenda: `docs/compiler/pbs/agendas/19.5. Diagnostics, Manifest Propagation, and Conformance Coverage Agenda.md`
## Context
After closing globals, lifecycle markers, published wrapper ownership, and lowering structure, PBS v1 still needed one final consolidation step for topic `19`.
The remaining work was no longer architectural debate.
It was operational consolidation across the whole line:
- which diagnostics are now mandatory,
- which phase owns each failure surface,
- which specs and cross-domain artifacts must be updated,
- and what minimum conformance evidence is required before execution planning begins.
Important fixed inputs already existed:
- `19.1` closed the source surface and dependency rules for globals;
- `19.2` closed lifecycle markers, init ordering, and init restrictions;
- `19.3` closed published wrapper ownership, physical entrypoint `0`, and manifest protocol direction;
- `19.4` closed explicit lowering structure, synthetic callable classes, hidden boot guard policy, and lowering-side invariants.
## Decision
PBS accepts the following consolidation for topic `19`:
1. The diagnostics line for family `19` is grouped by phase rather than by historical agenda order.
2. The final propagation line for family `19` must name PBS specs, general compiler specs, runtime cross-domain ownership, and `learn`.
3. The conformance line for family `19` must cover positive flow, negative frontend coverage, negative lowering coverage, and runtime integration.
4. Runtime-side work required by entrypoint protocol changes remains explicitly cross-domain and is owned through:
- `../runtime/docs/runtime/agendas/025-cartridge-manifest-entrypoint-removal-and-runtime-protocol.md`
## Consolidated Diagnostics
PBS adopts the following minimum diagnostics and failure surfaces for family `19`.
### Frontend / Static Semantics
The compiler must provide, at minimum:
1. `global initializer uses unsupported form`
2. `global dependency cycle detected`
3. `imported symbol shadows existing visible symbol; alias required`
4. `global import must resolve through a global barrel entry`
5. `init function must have signature fn name() -> void`
6. `frame function must have signature fn name() -> void`
7. `multiple module init functions detected`
8. `multiple project init functions detected`
9. `multiple frame functions detected`
10. `missing frame function for executable project`
11. `Init attribute target invalid`
12. `project init must be colocated with frame`
13. `InitAllowed is valid only on SDK host methods`
14. `host call not allowed during init`
### Lowering / Structural Validation
The lowering line must enforce, at minimum:
1. `synthetic wrapper entrypoint missing`
2. `published entrypoint is not function index 0`
3. `hidden boot guard is missing`
4. `synthetic callable origin missing`
These may appear as backend diagnostics, validation failures, or invariant violations, as long as the failure is observable and testable.
### Runtime / Boot Failure
The runtime-facing failure surface must distinguish, at minimum:
1. `boot failed during module init`
2. `boot failed during project init`
These belong to operational boot failure reporting rather than to the static compiler diagnostic catalog.
## Propagation Targets
PBS adopts the following minimum propagation line for family `19`.
### PBS Specs
This decision must propagate to at least:
1. `docs/compiler/pbs/specs/3. Core Syntax Specification.md`
2. `docs/compiler/pbs/specs/4. Static Semantics Specification.md`
3. `docs/compiler/pbs/specs/7. Cartridge Manifest and Runtime Capabilities Specification.md`
4. `docs/compiler/pbs/specs/9. Dynamic Semantics Specification.md`
5. `docs/compiler/pbs/specs/11. AST Specification.md`
6. `docs/compiler/pbs/specs/12. Diagnostics Specification.md`
7. `docs/compiler/pbs/specs/13. Lowering IRBackend Specification.md`
### General Compiler Specs
This decision must also propagate to at least:
1. `docs/compiler/general/specs/15. Bytecode and PBX Mapping Specification.md`
2. `docs/compiler/general/specs/20. IRBackend to IRVM Lowering Specification.md`
### Runtime Cross-Domain Owner
The runtime half of the protocol change remains explicitly cross-domain and must be tracked through:
1. `../runtime/docs/runtime/agendas/025-cartridge-manifest-entrypoint-removal-and-runtime-protocol.md`
### Learn
PBS must also produce a consolidated `learn` artifact explaining:
1. globals,
2. lifecycle markers,
3. published wrapper composition,
4. fixed entrypoint protocol,
5. and the relationship between source flow and lowered artifacts.
## Conformance Matrix
PBS adopts the following minimum conformance matrix for family `19`.
### Positive Coverage
At minimum, one positive fixture must cover:
1. `declare global`
2. file-level `[Init]`
3. project-level `[Init]`
4. `[Frame]`
That fixture must provide evidence for:
1. accepted globals and ordering,
2. generated wrapper publication,
3. `func_id = 0`,
4. `FRAME_RET` in the wrapper path,
5. and hidden boot guard presence.
### Negative Frontend Coverage
At minimum, negative frontend coverage must include:
1. `global` using `fn` in its initializer
2. `global` using `if` in its initializer
3. cycle between globals
4. symbol collision between imported and visible `const` / `global` / `service` / `fn`
5. invalid `[Init]` signature
6. invalid `[Frame]` signature
7. multiple `[Frame]`
8. multiple project init candidates
9. project init outside the `[Frame]` file
10. host call during init without `[InitAllowed]`
11. invalid `[InitAllowed]` target
### Negative Lowering Coverage
At minimum, negative lowering coverage must include:
1. missing published wrapper
2. published wrapper outside physical index `0`
3. missing hidden boot guard
4. missing synthetic origin metadata
### Runtime Integration Coverage
At minimum, runtime integration coverage must include:
1. artifact boot through physical entrypoint `0`
2. evidence that runtime boot no longer depends on nominal export resolution
3. coherent fail-fast reporting for module init failure
4. coherent fail-fast reporting for project init failure
## Rationale
This decision intentionally turns the last umbrella stage of topic `19` into an execution gate rather than another semantic layer.
That matters because the line is already architecturally closed.
What remained was the discipline required to make implementation safe:
- explicit diagnostics,
- explicit propagation ownership,
- explicit cross-domain runtime ownership,
- and explicit conformance evidence.
Without this consolidation step, execution work would still have room to drift across specs, runtime, and compiler validation.
## Invariants
1. Family `19` diagnostics remain partitioned by phase.
2. Family `19` propagation remains explicit across PBS specs, general specs, runtime, and `learn`.
3. Runtime entrypoint-protocol work remains a named cross-domain dependency rather than an implicit follow-up.
4. Family `19` is not considered implementation-ready without the declared conformance matrix.
## Explicit Non-Decisions
1. This decision does not redefine globals surface semantics.
2. This decision does not redefine lifecycle marker semantics.
3. This decision does not redefine published wrapper ownership.
4. This decision does not redefine lowering structure.
5. This decision does not replace the runtime-domain decision work required outside the PBS domain.
## Execution Readiness
With this decision accepted, family `19` is considered ready to move into `pull-request/plan` decomposition for:
1. spec propagation,
2. compiler implementation,
3. runtime cross-domain coordination,
4. diagnostics integration,
5. and conformance fixture execution.

View File

@ -1,128 +0,0 @@
# Dynamic Semantics - Branch Selection Decision
Status: Accepted (Implemented)
Cycle: Initial branch-selection closure pass
## 1. Context
PBS v1 needs a closed runtime contract for `if` and `switch` before the dynamic semantics spec can be completed.
The remaining questions were:
- whether conditions and selectors are evaluated once,
- whether non-selected branches evaluate at all,
- which selector categories are admitted for `switch`,
- and whether branch selection itself may trap.
## 2. Decision
PBS v1 adopts the following branch-selection rules:
1. `if` evaluates its condition exactly once.
2. `switch` evaluates its selector exactly once.
3. Only the selected branch or arm executes.
4. Non-selected branches and arms perform no evaluation.
5. `if` and `switch` are trap-free by themselves; only selected subexpressions may trap.
6. `switch` is limited to statically discriminable selector categories.
7. `switch` does not accept `result`, `error`, structs, string objects, or heap-backed types as selectors in v1.
## 3. `if`
For:
```text
if cond { then_block } else { else_block }
```
the runtime behaves as follows:
1. evaluate `cond` exactly once,
2. if it yields `true`, execute only `then_block`,
3. if it yields `false`, execute only `else_block`.
The non-selected branch is not evaluated, even partially.
Any trap associated with `if` arises only from:
- evaluating `cond`,
- or executing the selected branch.
## 4. `switch`
### 4.1 Selector evaluation
For:
```text
switch selector { ... }
```
the runtime:
1. evaluates `selector` exactly once,
2. determines the matching arm using the canonical matching rule for the selector category,
3. executes exactly one selected arm.
No non-selected arm is evaluated.
### 4.2 Admitted selector categories
In v1, `switch` is restricted to selector categories with static, deterministic matching behavior.
These include:
- literal-comparable scalar values,
- enum values,
- `str` values with canonical static identity,
- and other compile-time-constant-compatible selector categories only if explicitly admitted elsewhere.
`switch` does not accept:
- `result` values,
- `error` values,
- structs,
- string object/reference types distinct from canonical `str`,
- or heap-backed selector categories.
Dynamic or structural matching belongs to a future `match`-style construct rather than to `switch`.
### 4.3 Matching rule
`switch` arm selection is exact and deterministic for the admitted selector type.
- Enum selectors match by canonical enum-case identity.
- Scalar selectors match by the exact equality rule already defined for that scalar category.
- `str` selectors match by canonical static string identity rather than by heap-object comparison.
`switch` does not perform structural matching, guard evaluation, or user-defined equality dispatch.
## 5. Invariants
- `if` and `switch` never evaluate more than one branch or arm.
- Branch selection is deterministic for the same selector value.
- `switch` remains a static discriminant-selection construct, not a result/error-processing construct.
- Error processing with logic belongs to `handle`, not to `switch`.
## 6. Explicit Non-Decisions
This decision record does not yet close:
- the final future design of `match`,
- whether additional scalar-like selector categories will be admitted later,
- the complete memory/cost wording associated with selector evaluation.
## 7. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/9. Dynamic Semantics Specification.md`
- `docs/pbs/specs/4. Static Semantics Specification.md`
- `docs/pbs/specs/3. Core Syntax Specification.md`
## 8. Validation Notes
The intended split is:
- `if` and `switch` perform static, deterministic branch selection,
- `handle` processes modeled `result` errors,
- future dynamic or structural branching belongs to `match`, not to `switch`.

View File

@ -1,355 +0,0 @@
# Dynamic Semantics - Effect Surfaces Decision
Status: Accepted (Implemented)
Cycle: Initial effect-surfaces closure pass
## 1. Context
PBS v1 already commits to several effect and control surfaces in syntax and static semantics, but their runtime behavior must be closed before normative dynamic semantics can be written.
This decision record captures the first closed subset of that work:
- `optional`,
- `result<E>`,
- `!` propagation,
- `handle` processing.
Allocation, retention, copy visibility, and heap-facing cost wording are delegated to the memory and heap decision track.
## 2. Decision
PBS v1 adopts the following baseline runtime rules for `optional` and `result<E>` surfaces:
1. `optional` is a runtime presence/absence carrier with canonical `some(payload)` and `none` states.
2. `some(expr)` evaluates `expr` eagerly and exactly once before forming the `some` carrier.
3. `opt else fallback` evaluates the left operand exactly once and evaluates `fallback` only when the left operand is `none`.
4. `optional` is trap-free by itself; only subexpression evaluation may trap.
5. `result<E>` is the runtime carrier for expected, modelable failure in function return flow.
6. `expr!` evaluates `expr` exactly once and performs immediate enclosing-function error propagation on failure.
7. `handle expr { ... }` evaluates `expr` exactly once and, on error, executes exactly one matching arm.
8. A `handle` arm may execute user-defined logic.
9. A `handle` arm must terminate with either `ok(payload)` or `err(E2.case)`.
10. `ok(payload)` in a `handle` arm recovers locally and yields the payload as the value of the `handle` expression.
11. `err(E2.case)` in a `handle` arm performs immediate enclosing-function return with that error.
12. `handle` supports a short remap form `E1.case -> E2.case` as sugar for a block that returns `err(E2.case)`.
13. Neither `!` nor `handle` intercepts or converts traps.
14. `apply` is the canonical universal call surface for PBS v1 across all callable categories.
15. `apply` chains parse right-associatively but preserve the already-closed left-to-right observable evaluation model.
16. `apply` does not introduce implicit composition of `optional` or `result` surfaces.
17. `bind(context, fn_name)` forms a nominal callback value by attaching a struct context to a top-level function target.
18. `bind` evaluates its context expression exactly once, captures the same runtime context identity without copying it, and injects that context as the first argument when the callback is invoked.
19. `bind` is not a general closure mechanism and is trap-free at the language level.
## 3. `optional`
### 3.1 Runtime model
`optional` has exactly two runtime states:
- `some(payload)`
- `none`
`none` is the canonical absence of payload.
### 3.2 Construction
`some(expr)`:
- evaluates `expr` eagerly,
- evaluates it exactly once,
- then forms the `some(payload)` carrier from the produced payload.
### 3.3 Extraction
`opt else fallback`:
1. evaluates `opt` exactly once,
2. if the result is `some(payload)`, yields the extracted payload and does not evaluate `fallback`,
3. if the result is `none`, evaluates `fallback` and yields that value.
`else` is extraction with fallback, not error handling.
### 3.4 Trap behavior
`optional` itself does not trap.
Any trap associated with `some(expr)` or `opt else fallback` arises only from:
- evaluating `expr`,
- evaluating the left operand,
- or evaluating the fallback when it is needed.
## 4. `result<E>`
### 4.1 Runtime role
`result<E>` is the runtime carrier for success-or-modeled-failure at function boundaries and in expressions whose static type is `result<E> P`.
In v1, `ok(...)` and `err(...)` are special result-flow forms.
They are not general-purpose first-class userland constructors for arbitrary data modeling.
They are valid in:
- function return flow for `result<E>`,
- and `handle` arms, where they control recovery or propagation.
### 4.2 `!` propagation
`expr!`:
1. evaluates `expr` exactly once,
2. if `expr` yields success, yields the extracted success payload as the value of the expression,
3. if `expr` yields error, performs immediate enclosing-function return with the same `err(...)`.
`!` does not:
- remap the error,
- intercept traps,
- or continue ordinary evaluation after the propagated error path is chosen.
### 4.3 `handle`
`handle expr { ... }`:
1. evaluates `expr` exactly once,
2. if `expr` yields success, yields the extracted success payload directly,
3. if `expr` yields error, selects exactly one matching handle arm,
4. executes the selected arm,
5. requires that arm to terminate with either `ok(payload)` or `err(E2.case)`.
### 4.4 `handle` arm results
The selected `handle` arm has two admissible result forms:
- `ok(payload)`
- `err(E2.case)`
Their semantics are:
- `ok(payload)` recovers locally and makes the `handle` expression yield `payload`,
- `err(E2.case)` performs immediate enclosing-function return with `err(E2.case)`.
The `payload` in `ok(payload)` must be compatible with the success payload shape produced by the surrounding `handle` expression.
The `E2.case` in `err(E2.case)` must belong to the target error type required by the enclosing context.
### 4.5 `handle` sugar
For the common remap-only case, `handle` supports a short arm form:
```text
E1.case -> E2.case
```
This is sugar for:
```text
E1.case -> { err(E2.case) }
```
Recovery with `ok(payload)` requires the explicit block form.
### 4.6 `handle` scope
`handle` may execute user-defined logic inside an arm, but it remains specific to modeled `result` errors.
It does not provide:
- trap interception,
- arbitrary processing of non-`result` failure channels,
- or a general-purpose exception system.
## 5. Invariants
- `optional` models absence, not failure.
- Expected recoverable failure remains in `result<E>`, not in `optional`.
- `!` is an early-return propagation surface.
- `handle` is a typed result-processing surface with controlled recovery or propagation.
- Success paths produce payload values directly.
- Error paths in `result<E>` remain explicit and typed.
- Trap remains outside ordinary recoverable error flow.
- `apply` remains the single semantic call surface even when user code uses direct-call sugar.
- Callable-specific dispatch differences do not change the user-visible call pipeline.
- Effect boundaries remain explicit; `apply` does not auto-lift through `optional` or `result`.
## 6. `apply`
### 6.1 Canonical role
`apply` is the canonical universal call surface in PBS v1.
Direct call syntax is only sugar over `apply` and does not define separate runtime semantics.
The same observable call model applies to:
- top-level functions,
- struct methods,
- service methods,
- contract calls,
- callback calls,
- host-backed calls.
### 6.2 Shared observable pipeline
For `lhs apply rhs`, the shared observable runtime pipeline is:
1. form the call target from `lhs`,
2. evaluate any receiver or callable artifact needed for target formation exactly once,
3. evaluate `rhs` exactly once,
4. invoke the resolved target,
5. produce one of:
- normal return,
- explicit `result<Error>` propagation,
- or `trap`.
Callable-specific dispatch strategy may differ internally, but it does not change this user-visible sequencing model.
### 6.3 Chained `apply`
`apply` chains are parsed right-associatively.
For example:
```text
f1 apply f2 apply f3 apply params
```
parses as:
```text
f1 apply (f2 apply (f3 apply params))
```
The observable evaluation order still follows the already-closed left-to-right model:
1. form the target of `f1`,
2. evaluate the argument expression for `f1`,
3. within that argument expression, form the target of `f2`,
4. evaluate the argument expression for `f2`,
5. within that argument expression, form the target of `f3`,
6. evaluate `params`,
7. invoke `f3`,
8. invoke `f2`,
9. invoke `f1`.
### 6.4 Effect boundaries
`apply` does not introduce implicit effect composition.
If a callable returns:
- `optional<P>`, extraction remains explicit through `else`,
- `result<E> P`, propagation or remapping remains explicit through `!` or `handle`.
PBS v1 does not auto-lift ordinary call chains through `optional` or `result` boundaries.
## 7. `bind`
### 7.1 Role
`bind(context, fn_name)` is the explicit callback-formation mechanism in PBS v1.
It exists to attach a struct context to a compatible top-level function without introducing general lexical closures.
### 7.2 Context and target
`bind` requires:
- a context expression whose runtime value is a struct instance,
- a top-level function target whose first parameter is compatible with that struct type,
- and an expected callback type already validated by static semantics.
### 7.3 Runtime artifact
`bind(context, fn_name)` produces a nominal callback value that stores:
- the resolved top-level function target,
- the captured runtime identity of the context value.
The context is not copied or rematerialized during binding.
When the callback is later invoked, the runtime behaves as if it calls:
```text
fn_name(context, ...)
```
where `context` is the same captured runtime instance.
### 7.4 Evaluation and identity
The context expression is evaluated exactly once at bind time.
That evaluation exists only to obtain the struct instance that will be attached to the callback.
After capture:
- the same runtime context identity remains attached,
- mutations performed through the callback observe and affect that same context instance,
- `bind` does not create a detached copy of the context.
### 7.5 Storage and retention
`bind` is not semantically free.
Forming a callback through `bind` requires runtime storage sufficient to keep:
- the callback target identity,
- and the captured context alive while the callback value remains alive.
For the purposes of PBS v1 semantics, `bind` should be treated as a callback-forming operation with real retention and heap-facing consequences, even though the final memory/lifetime wording belongs in the dedicated memory specification.
### 7.6 Trap behavior
At the language-semantics level, `bind` is trap-free.
Incompatible context type, incompatible function target, or invalid callback shape are compile-time errors rather than runtime traps.
`bind` introduces no ordinary recoverable error surface and no bind-specific trap surface.
### 7.7 Non-goal
`bind` is not:
- general closure capture,
- arbitrary local-environment capture,
- or a promise that future closure features must behave identically.
It is the explicit v1 callback-binding mechanism only.
## 8. Explicit Non-Decisions
This decision record does not yet close:
- the final memory/lifetime wording for allocation, copy, and retention visibility,
- the final catalog of trap sources that may arise from subexpression evaluation.
## 9. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/9. Dynamic Semantics Specification.md`
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
The unresolved cost and retention wording for these surfaces should be completed through:
- `docs/pbs/agendas/Memory and Lifetime - Agenda.md`
- `docs/pbs/agendas/Heap Model - Agenda.md`
## 10. Validation Notes
The intended behavior is:
- `some(expr)` is eager,
- `opt else fallback` is short-circuit on `some`,
- `!` propagates the same typed error unchanged,
- `handle` remaps typed errors without introducing custom logic,
- `apply` remains the universal call surface across callable kinds,
- chained `apply` does not create implicit optional/result composition,
- `bind` captures a struct context identity without copying it,
- `bind` forms a callback with real retention/storage consequences,
- `handle` may recover with `ok(payload)` or propagate with `err(E2.case)`,
- short-form `handle` arms are sugar for propagation-only remap blocks,
- `trap` remains outside both `!` and `handle`.

View File

@ -1,131 +0,0 @@
# Dynamic Semantics - Execution Model Decision
Status: Accepted (Implemented)
Cycle: Initial execution-model closure pass
## 1. Context
PBS needs a closed execution-model baseline before effect surfaces and memory/lifetime semantics can be specified normatively.
The key open questions were:
- whether execution is single-threaded per program instance,
- which runtime effects are observable to user code,
- what the default evaluation order is,
- which constructs guarantee single evaluation,
- how abrupt completion behaves,
- how `result<Error>` differs from `trap`,
- and how host calls interact with `FRAME_SYNC` without perturbing user-visible sequencing.
## 2. Decision
PBS v1 adopts the following execution-model baseline:
1. Execution is single-threaded per program instance.
2. User-visible execution is deterministic and does not expose concurrent interleaving.
3. The default evaluation rule is strict left-to-right unless a construct explicitly states otherwise.
4. Call evaluation proceeds by forming the call target first, then evaluating arguments left-to-right, then invoking the target.
5. Abrupt completion terminates the current construct immediately and prevents later sibling evaluation.
6. Recoverable, expected failures belong to `result<Error>`, not to `trap`.
7. `trap` is reserved for non-recoverable runtime failures outside ordinary userland error flow.
8. Any trap aborts the current PBS program execution rather than returning control to ordinary userland flow.
9. `FRAME_SYNC` is the only normative safepoint in PBS v1.
10. `FRAME_SYNC` remains the execution boundary for userland progress; host-side work during that boundary must not reorder PBS-observable semantics.
## 3. Invariants
- PBS v1 does not expose a user-visible concurrent execution model.
- User-visible sequencing is defined by evaluation order, branch selection, abrupt completion, result propagation, trap propagation, and host-call boundaries.
- Traps are not recoverable in userland and do not resume PBS execution.
- VM-internal frame layout, temporary storage, and lowering steps are not observable unless they change the semantic effects above.
- Unless a construct states otherwise, subexpressions are evaluated once and in left-to-right order.
- `return`, `break`, `continue`, result propagation via `!`, and `trap` abort further evaluation in the current construct.
- Host calls must not introduce user-visible reordering of already-defined PBS evaluation order.
- No normative safepoint exists in v1 other than `FRAME_SYNC`.
## 4. Call Evaluation Rule
The runtime call rule for v1 is:
1. Form the call target.
2. Evaluate any receiver that participates in target formation.
3. Evaluate arguments in source order from left to right.
4. Invoke the resolved target.
5. Produce one of:
- normal return,
- explicit `result<Error>` propagation,
- or `trap`.
This rule applies to canonical `apply` and to ordinary call sugar that desugars to `apply`.
## 5. Error Boundary
`result<Error>` and `trap` are distinct runtime categories.
### 5.1 `result<Error>`
`result<Error>` is the required mechanism for failures that are:
- expected by the API contract,
- recoverable in ordinary userland control flow,
- modelable through an explicit PBS error type.
Such failures may be:
- processed with `handle`,
- propagated with `!`,
- and discussed as part of ordinary function contract design.
### 5.2 `trap`
`trap` is reserved for failures that are:
- outside the ordinary userland contract,
- not suitably representable as the declared `result<Error>` surface,
- caused by runtime or host invariant failure,
- or severe enough that ordinary userland recovery is not part of the v1 language model.
PBS v1 does not define `try/catch` for traps.
Traps are not part of ordinary recoverable control flow.
Once a trap is raised, PBS userland execution aborts and control transfers to runtime or firmware crash handling outside the ordinary language model.
## 6. Consequences
- User-authored code does not explicitly throw traps as part of ordinary PBS semantics.
- API surfaces must not use trap as a substitute for a modelable `result<Error>` failure.
- Host-backed operations must expose predictable operational failures through `result<Error>` when those failures are part of the callable contract.
- Residual host or runtime failures that cannot be represented by the declared PBS contract may still trap.
- The language-level consequence of trap is program abort rather than catchable failure handling.
- In v1, no safepoint inventory is normative beyond `FRAME_SYNC`.
## 7. Explicit Non-Decisions
This decision does not yet close:
- the exact list of constructs with explicit single-evaluation wording as finally integrated into the dynamic-semantics spec,
- the final wording split between dynamic semantics and runtime-initialization for trap/crash handoff.
Those points must be integrated by the remaining dynamic-semantics and memory/lifetime decisions.
## 8. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/9. Dynamic Semantics Specification.md`
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/general/specs/16. Runtime Execution and Initialization Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
## 9. Validation Notes
The intended rule is:
- expected domain failure: `result<Error>`
- remappable, processable, or propagatable failure: `result<Error>`
- runtime invariant breakage or non-contract catastrophic failure: `trap`
In practical terms, a host-backed API must not rely on trap for ordinary operational failures if those failures can be declared and modeled explicitly in PBS. The only normative safepoint in v1 is `FRAME_SYNC`, and any trap aborts PBS userland execution rather than returning through an in-language recovery path.

View File

@ -1,130 +0,0 @@
# GC and Reachability Decision
Status: Accepted (Implemented)
Cycle: Initial GC-and-reachability closure pass
## 1. Context
PBS v1 uses GC as the baseline runtime model, but the language still needs a precise statement of:
- what reachability guarantees are normative,
- what reclamation guarantees are normative,
- what remains implementation-defined,
- how GC interacts with the single normative safepoint at `FRAME_SYNC`,
- and what user code may or may not observe.
## 2. Decision
PBS v1 adopts the following GC-and-reachability baseline:
1. GC is the baseline runtime model for VM-owned memory in PBS core.
2. Reachability is the normative liveness criterion for GC-managed values.
3. Eventual reclamation is the strongest reclamation guarantee in v1.
4. `FRAME_SYNC` is the only normative safepoint relevant to GC-observable behavior.
5. User code cannot observe reclamation directly.
6. PBS v1 defines no user-authored finalizers, destructors, or reclamation callbacks.
7. Implementations may perform internal GC work outside `FRAME_SYNC` only if doing so creates no additional user-visible semantic effects.
## 3. Normative Reachability Contract
For GC-managed VM-owned values, liveness is defined by reachability from the runtime roots that matter to PBS semantics.
At minimum, these roots include:
- currently active local/frame state,
- reachable fields of reachable struct instances,
- service singleton roots,
- retained callback state that remains reachable,
- and any other runtime roots required to preserve already-observable PBS behavior.
If a GC-managed value remains reachable through the normative runtime state, the implementation must preserve its continued semantic availability.
If a value becomes unreachable, user code must not rely on when reclamation occurs.
## 4. Reclamation Guarantee
PBS v1 guarantees eventual reclamation, not prompt reclamation.
This means:
- unreachable GC-managed memory may be reclaimed later,
- the language does not promise immediate reclamation,
- the language does not promise reclamation at a specific frame boundary,
- and the language does not expose a semantic event when reclamation occurs.
## 5. Safepoint Relationship
`FRAME_SYNC` is the only normative safepoint in PBS v1.
For GC semantics, this means:
- the language does not promise any additional observable GC safepoints,
- no user-visible program rule may depend on another safepoint existing,
- and any internal collector work outside `FRAME_SYNC` must remain semantically invisible to PBS userland.
The spec does not require a specific collector architecture.
It only constrains what may become observable.
## 6. Observability
User code cannot observe reclamation directly.
PBS v1 provides no user-visible mechanism for:
- detecting that a value was collected,
- registering a callback on reclamation,
- forcing immediate collection,
- or sequencing user code against GC timing.
GC-related information may appear in diagnostics, profiling, or runtime tooling, but those surfaces are not ordinary language semantics.
## 7. Finalization and Cleanup
PBS v1 forbids user-authored finalizers and destructor-like reclamation hooks.
GC reclamation of pure VM-owned values does not trigger user code.
Host-backed cleanup policy is not defined by GC finalization semantics in this decision.
If host-backed resources require explicit or contract-specific cleanup rules, those belong to the host-boundary decision track rather than to GC finalization in userland.
## 8. Invariants
- Reachability, not timing, is the normative semantic axis.
- Reclamation timing remains implementation-defined.
- No direct user-visible behavior is allowed to depend on collector timing.
- The only normative safepoint is `FRAME_SYNC`.
- GC must not create extra user-visible sequencing effects outside the already-closed execution model.
## 9. Beginner-Facing Model
The user-facing explanation should be:
- if a value can still be reached by the program, it remains alive,
- once it can no longer be reached, the runtime may clean it up later,
- the program does not control or directly observe that cleanup moment.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the exact collector algorithm,
- host-backed resource cleanup semantics,
- diagnostics wording for GC-related tooling surfaces,
- the full root-set wording as finally integrated into the memory specification.
## 11. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/16. Runtime Execution and Initialization Specification.md`
## 12. Validation Notes
The intended split is:
- GC defines reachability and eventual reclamation,
- `FRAME_SYNC` is the only normative safepoint,
- reclamation timing is not user-observable,
- host-backed cleanup is a separate boundary question rather than a user finalization feature.

View File

@ -1,154 +0,0 @@
# Globals Surface, Identity, and Module Boundaries Decision
Status: Accepted
Date: 2026-03-22
Related Agenda: `docs/compiler/pbs/agendas/19.1. PBS Globals Surface, Identity, and Module Boundaries Agenda.md`
## Context
PBS v1 needed a precise language and linking policy for runtime globals before lifecycle, published entrypoint, and lowering work under topic `19` could proceed safely.
The open problem was not merely syntax.
It also required closing:
- how globals differ from `declare const`,
- how globals participate in value visibility and import flow,
- how module ownership of storage is preserved,
- how dependency order between globals is modeled,
- and which diagnostics are mandatory when that model is violated.
Important fixed inputs already existed:
- `declare const` is compile-time only and does not denote mutable module storage,
- top-level executable statements remain forbidden,
- the VM already exposes global-slot access,
- and `mod.barrel` remains the visibility authority for module exports.
## Decision
PBS adopts the following policy for runtime globals in v1:
1. PBS introduces a distinct top-level declaration form:
- `declare global Name: T = expr;`
2. `declare global` is not a variant of `declare const`.
3. `declare const` remains reserved to immutable values and must not be reused as runtime module storage.
4. `declare global` requires:
- an explicit type annotation,
- and an explicit initializer in all ordinary v1 cases.
5. Globals participate in the value namespace, but remain a distinct declaration category.
6. `mod.barrel` must expose globals through explicit `global` entries:
- `mod global Name;`
- `pub global Name;`
7. PBS does not introduce global re-export in this line of work.
8. Import of a global preserves the storage identity of the original owner module.
9. Imports may use aliasing when needed, but aliasing changes only the local visible name, never the canonical storage owner.
10. Shadowing between visible `fn`, `service`, `global`, and `const` names is a compile-time error and must be resolved with aliasing.
11. Lookup precedence remains:
- locals,
- then struct/class members,
- then globals,
including globals introduced by import.
12. Global dependency order is defined by a deterministic dependency graph:
- every read of another global in a global initializer creates a dependency edge,
- imports and aliases preserve canonical owner identity in that graph,
- source-file order must not affect dependency resolution.
13. Cycles between globals are compile-time errors.
14. Modules and globals must share the same structural dependency-analysis kernel through a refactor of the existing module dependency algorithm into:
- `DependencyGraphAnaliser`
- located in infra `util.structures`.
15. What is shared is the structural graph analysis kernel:
- topological ordering,
- cycle detection,
- deterministic traversal support.
16. What is not shared is domain semantics:
- each domain remains responsible for constructing canonical nodes, edges, and diagnostics.
## Global Initializer Policy
PBS v1 adopts the following initializer policy for `declare global`:
1. The initializer exists only to materialize the initial module storage value.
2. Admissible forms in v1 include:
- primitive literals and simple value operations,
- value-bearing member access at this stage,
- `new Struct(...)`,
- and reads of other globals compatible with the dependency graph.
3. Top-level `fn` calls are not permitted in a global initializer in v1.
4. `some(...)` and `none` are not permitted in a global initializer in v1.
5. `if` and `switch` are not permitted directly in the declaration initializer in v1.
6. Richer procedural setup belongs to later lifecycle stages rather than the declaration initializer itself.
## Rationale
This decision intentionally keeps global declarations narrow and explicit.
That choice:
- prevents semantic collapse between immutable constants and mutable runtime storage,
- keeps import and visibility rules legible,
- makes dependency analysis deterministic and explainable,
- avoids hiding lifecycle logic inside declaration expressions,
- and prepares a clean handoff to later topic `19` work on module init, project init, and published entrypoint behavior.
The decision also rejects implicit complexity:
- no silent reuse of `const`,
- no global re-export,
- no ambiguous cross-category name merging,
- and no procedural `fn`-driven initialization inside `declare global`.
## Mandatory Diagnostics
PBS must provide, at minimum, the following diagnostics for this policy:
1. `global initializer uses unsupported form`
- emitted at the invalid subexpression inside a global initializer.
2. `global dependency cycle detected`
- emitted on the local participating global,
- and should include the canonical cycle path when available.
3. `imported symbol shadows existing visible symbol; alias required`
- emitted when an imported `fn`, `service`, `global`, or `const` collides with an already-visible symbol of those categories.
4. `global import must resolve through a global barrel entry`
- emitted when import resolution would otherwise degrade a global into another category.
## Invariants
1. `declare const` and `declare global` remain semantically distinct.
2. Runtime storage ownership remains attached to the canonical owner module.
3. Global dependency order is semantic, not textual.
4. Alias spelling must not change canonical global identity.
5. The dependency-analysis kernel may be shared structurally, but semantic graph construction remains domain-owned.
## Explicit Non-Decisions
1. This decision does not define module init or project init behavior.
2. This decision does not define `[INIT]`, `[FRAME]`, or lifecycle markers.
3. This decision does not define published entrypoint or `FRAME_RET` ownership.
4. This decision does not define the final IR representation of globals.
5. This decision does not define host-call admissibility during lifecycle hooks.
## Spec Impact
This decision should feed at least:
1. `docs/compiler/pbs/specs/3. Core Syntax Specification.md`
2. `docs/compiler/pbs/specs/4. Static Semantics Specification.md`
3. `docs/compiler/pbs/specs/11. AST Specification.md`
4. `docs/compiler/pbs/specs/12. Diagnostics Specification.md`
It also constrains future topic `19` work in:
1. `docs/compiler/pbs/agendas/19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda.md`
2. `docs/compiler/pbs/agendas/19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda.md`
3. `docs/compiler/pbs/agendas/19.4. Globals and Lifecycle Lowering to IRBackend/IRVM Agenda.md`
## Validation Notes
At minimum, validation for this decision should include:
1. accepted fixtures for `declare global` with primitive, member-value, `new`, and dependent-global initializers;
2. rejection fixtures for forbidden initializer forms such as top-level `fn`, `some(...)`, `if`, and `switch`;
3. import fixtures proving alias-based disambiguation;
4. negative fixtures for cross-category collisions;
5. dependency fixtures proving deterministic ordering independent of source-file order;
6. cycle fixtures proving deterministic detection and diagnostics for intra-module and inter-module cycles.

View File

@ -1,194 +0,0 @@
# Globals and Lifecycle Lowering to IRBackend and IRVM Decision
Status: Accepted
Date: 2026-03-22
Related Agenda: `docs/compiler/pbs/agendas/19.4. Globals and Lifecycle Lowering to IRBackend/IRVM Agenda.md`
## Context
After closing globals, lifecycle markers, and published wrapper ownership, PBS v1 still needed a precise lowering contract for how those decisions appear in executable compiler artifacts.
The remaining problem was not semantic policy anymore.
It was structural representation:
- where globals become explicit,
- how synthetic lifecycle callables are represented,
- how one-shot boot state is materialized,
- how diagnostics and attribution survive synthetic lowering,
- and what minimum backend shape must be preserved before `IRVM`.
Important fixed inputs already existed:
- runtime globals are part of the PBS source model,
- module init and project init are semantically defined,
- the published wrapper is the physical entrypoint,
- `FRAME_RET` belongs to that wrapper,
- and VM-level global access already exists as `GET_GLOBAL` / `SET_GLOBAL`.
## Decision
PBS adopts the following lowering policy in v1:
1. Globals must become explicit structural entities at the `IRBackend` boundary.
2. Globals must not be deferred to an implicit late materialization below that boundary.
3. The lowering pipeline must represent synthetic lifecycle artifacts explicitly as synthetic callables rather than ad hoc emitted fragments.
4. The following synthetic callable classes are mandatory:
- `FILE_INIT_FRAGMENT`
- `MODULE_INIT`
- `PROJECT_INIT`
- `PUBLISHED_FRAME_WRAPPER`
5. The wrapper published as the physical entrypoint must exist explicitly in the lowered graph.
6. The one-shot boot guard must exist explicitly as a hidden global.
7. That hidden global is compiler-owned internal state and is not user-visible.
8. The lowering path must target the already-existing VM global operations:
- `GET_GLOBAL`
- `SET_GLOBAL`
## IRBackend Shape
PBS adopts the following minimum structural shape for `IRBackend`-level representation.
### Globals
Each backend global must preserve, at minimum:
1. `name`
2. `ownerModuleId`
3. `type`
4. `slot`
5. `visibility`
6. `isHidden`
7. `origin`
This applies both to:
- user-authored globals,
- and compiler-generated hidden globals such as the boot guard.
### Callables
The backend must distinguish explicitly between:
1. ordinary userland callables,
2. synthetic compiler-generated callables.
Synthetic callables must carry stable class identity rather than being inferred from naming convention alone.
### Hidden Global Kind
The hidden boot guard must carry explicit structural identity:
1. `BOOT_GUARD`
It must not be modeled merely as an informal hidden symbol name.
## Attribution and Diagnostics
PBS adopts the following attribution policy for synthetic lowering:
1. Synthetic globals and synthetic callables must carry origin metadata sufficient for remapping errors to real userland code where possible.
2. Synthetic origin metadata must preserve, at minimum:
- `derivedFromFile`
- `derivedFromModule`
- `derivedFromUserSymbol`
- `primarySpan`
- `fallbackSyntheticLabel`
3. When an error originates from synthetic lowering but has a defensible real userland origin, diagnostics must prefer the real userland span.
4. Purely synthetic spans should be shown only when no defensible userland origin exists.
## Synthetic Callable Policy
PBS adopts the following architectural rule:
1. Synthetic callables are first-class lowering artifacts.
2. They are not incidental codegen accidents.
3. Their explicit class identity exists to support:
- deterministic ordering,
- attribution,
- debug and tooling,
- conformance tests,
- and future lifecycle extensions without reopening the lowering model.
## Hidden Boot Guard Policy
PBS adopts the following policy for the boot guard:
1. It exists as a hidden program-owned global.
2. Userland cannot name it.
3. Userland cannot read it.
4. Userland cannot mutate it.
5. Its sole role is to enforce one-shot bootstrap semantics in the physical wrapper.
## Rationale
This decision intentionally chooses an explicit backend shape over implicit late-stage magic.
That matters because:
- globals are now part of the language contract,
- lifecycle artifacts now exist as semantically meaningful structure,
- diagnostics must remain attributable to real source even after synthesis,
- and backend conformance becomes much harder if the representation boundary stays implicit.
The chosen model also creates a stable editorial split:
- specs explain the structure normatively,
- and `learn` explains the composition through real source examples.
## Structural Diagnostics and Validation
PBS must provide, at minimum, the following structural checks or equivalent validation evidence:
1. `synthetic wrapper entrypoint missing`
2. `published entrypoint is not function index 0`
3. `hidden boot guard is missing`
4. `synthetic callable origin missing`
These may be implemented as backend diagnostics, validation failures, or conformance assertions, as long as the invariant remains enforced and observable.
## Invariants
1. Globals are explicit at the `IRBackend` boundary.
2. Synthetic lifecycle callables are explicit at the `IRBackend` boundary.
3. Hidden compiler state remains distinguishable from user state.
4. Synthetic lowering must preserve enough origin metadata for defensible remapping.
5. The lowering path to `IRVM` must preserve the previously accepted wrapper and entrypoint protocol.
## Explicit Non-Decisions
1. This decision does not redefine source syntax.
2. This decision does not redefine lifecycle semantics.
3. This decision does not redefine manifest publication.
4. This decision does not freeze one concrete implementation class hierarchy.
## Spec and Learn Impact
This decision should feed at least:
1. `docs/compiler/pbs/specs/13. Lowering IRBackend Specification.md`
2. relevant general lowering specs outside the PBS domain, when they need the new explicit shape
3. `docs/compiler/pbs/specs/12. Diagnostics Specification.md`
It also requires didactic propagation to PBS `learn`, where the model should be explained with source-level examples showing how:
1. `declare global`
2. file `[Init]`
3. project `[Init]`
4. and `[Frame]`
compose into synthetic lowered artifacts and the published wrapper.
## Validation Notes
At minimum, validation for this decision should include:
1. a fixture combining globals, file init, project init, and frame;
2. evidence of generated:
- file init fragment,
- module init,
- project init,
- published wrapper,
- hidden boot guard;
3. evidence that the wrapper occupies `func_id = 0`;
4. evidence that `FRAME_RET` lives in the wrapper path;
5. evidence that a synthetic-lowering error remaps to real userland span when a defensible origin exists.

View File

@ -1,115 +0,0 @@
# Host Memory Boundary Decision
Status: Accepted (Implemented)
Cycle: Initial host-boundary closure pass
## 1. Context
PBS needs a user-visible contract for the boundary between VM-owned semantics and host-provided runtime services.
At the current stage of the language, userland does not expose complex host-owned resource models.
The runtime offers features and the frontend consumes them; PBS should be careful not to project unnecessary language-level memory abstractions into runtime internals too early.
## 2. Decision
PBS v1 adopts the following host-memory boundary baseline:
1. Cross-boundary interaction between host and PBS userland is restricted to stack-only values.
2. PBS userland does not expose host memory as ordinary language values.
3. Raw pointers are not exposed in PBS userland.
4. Borrowed host-memory views are not exposed in PBS userland.
5. Pinning is not exposed in PBS v1.
6. Zero-copy transfer is not exposed in PBS v1.
7. Heap-shared boundary values between host and PBS userland are not part of the v1 model.
8. Long-lived host resources, if later exposed, must be specified explicitly by subsystem contract rather than inferred from a general host-memory model.
## 3. Boundary Rule
The host/userland boundary in PBS v1 is value-based rather than memory-sharing-based.
This means:
- host-backed interaction happens through explicit call boundaries,
- data crossing that boundary is limited to stack-only value forms,
- and userland never receives direct access to host-owned memory regions.
PBS therefore does not model host memory as something the language can directly hold, borrow, pin, or traverse.
## 4. What Is Not Exposed
PBS v1 does not expose any general userland model for:
- raw host pointers,
- borrowed host slices or views,
- pinned host memory,
- zero-copy host/userland transfer,
- shared heap objects spanning host memory and VM memory.
These features are out of scope for the v1 language model.
## 5. Role of Syscalls
At the current stage, host interaction should be understood primarily through syscall-style host-backed contracts.
Those contracts may accept and return stack-only values, but they do not imply that PBS userland owns, borrows, or directly manipulates host memory.
## 6. Long-Lived Host Resources
PBS v1 does not yet define a general-purpose language model for long-lived host-owned resources such as:
- banks,
- mixers,
- or other subsystem-specific retained resources.
If such resources are exposed later, they must be specified by explicit subsystem contract rather than by assuming a general host-memory-handle model in core PBS.
## 7. Failure Model Scope
This decision does not force a universal language-level error projection for all runtime-internal host behavior.
It only closes the memory-boundary side of the question:
- PBS userland does not directly manipulate host memory,
- and cross-boundary interaction remains stack-value-based.
Concrete error modeling for particular host-backed surfaces belongs to the contract of those surfaces rather than to a general raw-memory boundary rule.
## 8. Invariants
- The host/runtime may own internal memory and resource lifetimes that PBS userland never sees directly.
- PBS userland remains insulated from host-memory unsoundness by not exposing raw memory access at the language level.
- The absence of pointers and borrowed host views is a core v1 safety property.
- Boundary simplicity takes priority over premature expressiveness in this area.
## 9. Beginner-Facing Model
The user-facing explanation should be:
- the runtime can provide services to PBS programs,
- programs pass ordinary values into those services and receive ordinary values back,
- but programs do not directly hold or manipulate host memory.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the future design of subsystem-specific long-lived host resources,
- the future design of any explicit resource-release APIs,
- the concrete error contract of each host-backed surface,
- the final wording of host-boundary diagnostics.
## 11. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/6. VM-owned vs Host-backed.md`
- `docs/pbs/specs/6.2. Host ABI Binding and Loader Resolution Specification.md`
## 12. Validation Notes
The intended split is:
- runtime and host internals may remain complex,
- PBS userland sees only stack-only value exchange across the boundary,
- and any richer host-resource model must be introduced later by explicit subsystem contract.

View File

@ -1,64 +0,0 @@
# IRVM Optimization Stage Placement Decision
Status: Accepted
Date: 2026-03-07
Related Agendas:
- `docs/pbs/agendas/18.0. Backend VM Pipeline - Orchestration Agenda.md`
- `docs/pbs/agendas/18.2. Backend Workshop 2 - LowerToIRVM and IRVM Contract.md`
- `docs/pbs/agendas/18.3. Backend Workshop 3 - Bytecode Marshaling and Runtime Conformance.md`
## Context
Ao fechar a trilha backend executavel (`IRBackend -> IRVM -> bytecode`), surgiu a necessidade de definir onde a otimizacao deve ocorrer.
As opcoes praticas eram:
1. otimizar no runtime,
2. otimizar durante emissao de bytecode,
3. otimizar em etapa dedicada sobre `IRVM` antes da emissao.
O runtime atual privilegia determinismo, loader/verifier estritos e execucao numeric-only.
## Decision
PBS adota etapa dedicada de otimizacao entre lowering e emissao:
1. `LowerToIRVM` gera `IRVM`;
2. `OptimizeIRVM` aplica transformacoes `IRVM -> IRVM` semanticamente equivalentes;
3. `EmitBytecode` serializa o `IRVM` otimizado em artefato pre-load.
A etapa `OptimizeIRVM` passa a ser parte canônica do pipeline backend executavel.
## Invariants
1. `OptimizeIRVM` e compile-time, nao runtime.
2. `OptimizeIRVM` MUST preservar semantica observavel do programa.
3. `OptimizeIRVM` MUST preservar contratos de chamada/retorno/slots.
4. `OptimizeIRVM` MUST preservar determinismo para o mesmo grafo de entrada admitido.
5. `OptimizeIRVM` MUST respeitar `vm_profile` alvo e nao deixar opcodes internos nao-eliminados para a emissao final.
6. `EmitBytecode` continua responsavel por produzir artefato pre-load conforme contrato de loader/verifier.
7. Runtime nao assume papel de otimizador semantico do programa.
## Explicit Non-Decisions
1. Esta decisao nao define o catalogo completo de passes de otimizacao.
2. Esta decisao nao define heuristicas de custo/performance por alvo.
3. Esta decisao nao redefine regras de verifier/loader do runtime.
4. Esta decisao nao define fluxo de packer/cartucho.
## Spec Impact
1. A orquestracao de pipeline em `18.0` passa a incluir `OptimizeIRVM` entre `LowerToIRVM` e `EmitBytecode`.
2. A futura spec de `IRVM` (`18.2`) deve explicitar pre/post-condicoes da etapa de otimizacao.
3. A futura spec de marshaling (`18.3`) deve explicitar que a emissao opera sobre `IRVM` pos-otimizacao.
4. `docs/general/specs/19. Verification and Safety Checks Specification.md` deve refletir cobertura de regressao para pipeline com otimizacao intermediaria.
## Validation Notes
Para validacao minima da decisao:
1. o pipeline executa na ordem `LowerToIRVM -> OptimizeIRVM -> EmitBytecode`;
2. fixtures equivalentes com e sem otimizacao produzem comportamento runtime equivalente;
3. casos negativos de loader/verifier continuam falhando de forma deterministica apos a introducao de `OptimizeIRVM`.

View File

@ -1,194 +0,0 @@
# Lifecycle Markers, Program Init, and Frame Root Semantics Decision
Status: Accepted
Date: 2026-03-22
Related Agenda: `docs/compiler/pbs/agendas/19.2. PBS Lifecycle Markers, Program Init, and Frame Root Semantics Agenda.md`
## Context
After closing the globals surface and module-boundary model, PBS v1 needed a precise lifecycle policy for:
- module bootstrap,
- project bootstrap,
- frame-root identification,
- host-call admissibility during init,
- and failure behavior at boot.
The key requirement was to keep initialization expressive enough for real setup work, while preserving deterministic semantics and preventing the declaration initializer of `global` from becoming a general procedural execution surface.
Important fixed inputs already existed:
- `declare global` lowers into module-owned runtime storage,
- global initializers remain declarative and restricted,
- top-level `fn` calls are not allowed inside `declare global` initializers,
- `FRAME_SYNC` remains the only normative safepoint,
- and PBS v1 remains deterministic and single-threaded.
## Decision
PBS adopts the following lifecycle-marker and bootstrap policy in v1:
1. PBS introduces the reserved userland attributes:
- `[Init]`
- `[Frame]`
2. `[Frame]` is mandatory for an executable project.
3. `[Frame]` is unique per executable project.
4. `[Init]` is optional.
5. `[Init]` may appear in ordinary userland source both for module-local bootstrap and for project bootstrap.
6. Both `[Init]` and `[Frame]` require the same signature shape:
- `fn name() -> void`
7. Recommended canonical source forms are:
```pbs
[Init]
fn init() -> void { ... }
```
```pbs
[Frame]
fn frame() -> void { ... }
```
## Module Init and Project Init Policy
PBS adopts the following bootstrap layering:
1. Every module has exactly one synthetic module init.
2. `declare global` always lowers into that synthetic module init.
3. Each file may declare at most one `[Init]`.
4. A file may declare `[Init]` even when it declares no globals.
5. For one file:
- that file's globals are materialized first,
- then that file's `[Init]`, if present, executes.
6. File-level init fragments are then composed into the one synthetic module init.
7. The `[Init]` colocated in the same file as `[Frame]` is the project init.
8. `[Init]` in other files remains module init.
9. The distinction between module init and project init is one of ordering and semantic role, not one of different source syntax.
10. There is therefore at most one project init per executable project.
11. Project init uses the same signature shape:
- `fn init() -> void`
## Bootstrap Order
PBS adopts the following logical bootstrap order:
1. materialize globals for each file according to dependency order,
2. execute that file's `[Init]`, if present,
3. compose those steps into one synthetic module init,
4. after required module work is complete, execute project init, if present,
5. then enter the first `frame()`.
Within one module:
1. file ordering must follow the order derived from the globals `DependencyGraphAnaliser`,
2. and when two files have no dependency edge between them, the compiler must still use a deterministic stable order.
## Host Interaction During Init
PBS adopts the following init-time host-call policy:
1. Loops are permitted in module init and project init.
2. Host calls are forbidden by default during init.
3. The only host calls admissible during init are host methods marked with `[InitAllowed]`.
4. `[InitAllowed]` is a reserved SDK attribute, not a userland attribute.
5. `[InitAllowed]` has no arguments in v1.
6. `[InitAllowed]` is valid only on SDK host methods.
7. `[InitAllowed]` is invalid on userland `fn`, `global`, `service`, or any non-host-method surface.
8. `[InitAllowed]` does not distinguish module init from project init.
9. The difference between those phases is ordering and semantic role, not a separate host-permission class.
10. Admissibility of `[InitAllowed]` must be checked at compile time.
Illustrative shape:
```pbs
declare host Runtime {
[Host(module = "runtime", name = "random_u32", version = 1)]
[Capability(name = "runtime")]
[InitAllowed]
fn random_u32() -> int;
}
```
## Failure Policy
PBS adopts a fail-fast boot policy:
1. Failure during module init aborts boot.
2. Failure during project init aborts boot.
3. No automatic retry occurs on the next frame.
4. Implementations must surface a coherent failure message identifying the failing boot phase.
## Rationale
This decision keeps the declaration initializer of `global` simple, while still allowing practical bootstrap work in later lifecycle stages.
That balance matters because:
- arrays and derived data often require loops during setup,
- module bootstrap must remain expressive enough for real projects,
- host interaction during boot must still be tightly controlled,
- and the runtime model must remain deterministic and explainable.
Colocation of project init with frame was chosen deliberately as a source-organization rule.
It avoids introducing a second project-level marker while keeping project bootstrap discoverable in source.
## Mandatory Diagnostics
PBS must provide, at minimum, the following diagnostics for this policy:
1. `project init must be colocated with frame`
2. `multiple project init functions detected`
3. `multiple frame functions detected`
4. `missing frame function for executable project`
5. `init function must have signature fn name() -> void`
6. `frame function must have signature fn name() -> void`
7. `host call not allowed during init`
8. `InitAllowed is valid only on SDK host methods`
9. `boot failed during module init`
10. `boot failed during project init`
11. `multiple module init functions detected`
12. `Init attribute target invalid`
## Invariants
1. `[Frame]` remains unique per executable project.
2. Project init is identified by colocation with `[Frame]`.
3. Each file contributes at most one init fragment.
4. Each module contributes exactly one synthetic module init.
5. Host-call admissibility during init is explicit and compile-time validated.
6. Boot ordering remains deterministic.
## Explicit Non-Decisions
1. This decision does not define the published synthetic wrapper entrypoint.
2. This decision does not define `FRAME_RET` ownership.
3. This decision does not define the final IR encoding of bootstrap.
4. This decision does not define cartridge manifest publication details.
## Spec Impact
This decision should feed at least:
1. `docs/compiler/pbs/specs/3. Core Syntax Specification.md`
2. `docs/compiler/pbs/specs/4. Static Semantics Specification.md`
3. `docs/compiler/pbs/specs/9. Dynamic Semantics Specification.md`
4. `docs/compiler/pbs/specs/12. Diagnostics Specification.md`
It also constrains future topic `19` work in:
1. `docs/compiler/pbs/agendas/19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda.md`
2. `docs/compiler/pbs/agendas/19.4. Globals and Lifecycle Lowering to IRBackend/IRVM Agenda.md`
3. `docs/compiler/pbs/agendas/19.5. Diagnostics, Manifest Propagation, and Conformance Coverage Agenda.md`
## Validation Notes
At minimum, validation for this decision should include:
1. accepted fixtures for `[Init]` and `[Frame]` with correct signatures;
2. accepted fixtures for file-level `[Init]` without globals;
3. accepted fixtures for loops inside module init and project init;
4. rejection fixtures for invalid marker targets and invalid signatures;
5. rejection fixtures for illegal host calls during init;
6. accepted fixtures for SDK host calls marked `[InitAllowed]`;
7. failure fixtures that distinguish module-init boot failure from project-init boot failure;
8. ordering fixtures proving deterministic file ordering within one module.

View File

@ -1,121 +0,0 @@
# Lifetime Control and Future Profiles Decision
Status: Accepted (Implemented)
Cycle: Initial lifetime-control policy closure pass
## 1. Context
PBS v1 no longer uses the old RC/HIP model as an active core-language direction.
The remaining question is not how to design explicit lifetime control now, but how the project should treat legacy concepts and what policy should govern any future reintroduction of lifetime-oriented language features.
## 2. Decision
PBS v1 adopts the following lifetime-control policy baseline:
1. No lifetime-control keyword is reserved in core PBS merely for possible future use.
2. If a lifetime-control surface is not active in v1, it should not remain in the language as a reserved future-only keyword on that basis alone.
3. Advanced memory workflows should default to library/tooling-first exploration rather than syntax-first activation.
4. GC remains the default core model; future explicit lifetime control, if ever introduced, must be profile-gated rather than silently folded into the default language.
5. Future lifetime-oriented syntax may be introduced only when there is concrete evidence that library/tooling approaches are insufficient.
## 3. Legacy RC/HIP Concepts
Legacy concepts such as:
- `alloc`
- `borrow`
- `take`
- `weak`
- pool-style and arena-style control patterns
- object reuse patterns
do not remain active merely by historical inertia.
For PBS v1 policy:
- legacy concepts may survive as historical or design-reference material,
- but they do not imply reserved syntax commitment,
- and they do not imply a roadmap promise of later activation.
## 4. Language Versus Library Boundary
The default policy is:
- library first,
- tooling first,
- profile later only if justified,
- syntax last.
This means advanced workflows should first be explored through:
- stdlib APIs,
- tooling support,
- diagnostics,
- profiling guidance,
- subsystem-specific contracts where needed.
The language should not absorb explicit lifetime syntax simply because a legacy concept existed before.
## 5. Migration Narrative
The official migration narrative is:
- PBS v1 moves away from RC/HIP-style user-authored lifetime control as the core user model,
- GC plus deterministic execution is the baseline,
- performance-sensitive reasoning remains important,
- but performance and memory control should rise through explicit APIs and tooling before new syntax is considered.
This is a deliberate simplification, not a temporary placeholder awaiting automatic return to explicit ownership syntax.
## 6. Future Activation Criteria
Any future lifetime-oriented language/profile work must satisfy all of the following:
1. Real implementation and product evidence shows that library/tooling-first approaches are insufficient.
2. The proposed feature has a coherent semantic model that does not break the GC baseline by accident.
3. The feature can be isolated behind an explicit profile or equivalent opt-in boundary.
4. Diagnostics, conformance, and migration obligations are clear.
5. The feature does not degrade the beginner-facing default language without strong justification.
Future activation must be justified by present need and validated design, not by preserving speculative syntax in the current language.
## 7. Invariants
- GC remains the default core runtime model.
- Core PBS v1 does not promise future activation of legacy lifetime syntax.
- Absence of reserved lifetime keywords is a deliberate policy choice.
- Future explicit control must be explicit, justified, and profile-gated.
## 8. Beginner-Facing Model
The user-facing explanation should be:
- PBS v1 does not require ownership or lifetime syntax in ordinary code,
- advanced control is not removed as a future possibility,
- but it will be introduced only if it proves necessary and only through explicit design, not through dormant keywords left in the language.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- the exact shape of any future profile mechanism,
- the exact syntax of any future explicit lifetime feature,
- the future stdlib design for pools, arenas, or weak-reference-like patterns.
## 10. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/general/specs/17. Compatibility and Evolution Policy.md`
- `docs/pbs/specs/3. Core Syntax Specification.md`
## 11. Validation Notes
The intended policy is:
- no dormant lifetime keywords in core v1,
- no nostalgia-based reservation policy,
- library/tooling first,
- profile-gated language activation only when clearly justified.

View File

@ -1,168 +0,0 @@
# Name Resolution - Builtin Shells and Host Owners Decision
Status: Accepted (Implemented)
Cycle: Initial name-resolution closure pass
## 1. Context
PBS v1 needs a deterministic rule for how reserved stdlib shells participate in source-level name resolution.
The open questions were:
- whether builtin shells and host owners enter lookup as ordinary imported declarations or as special compiler-only names,
- whether builtin intrinsic methods participate in free callable lookup,
- whether reserved shells receive special collision priority,
- whether builtin shells belong under `@core:*` or `@sdk:*` by policy,
- and which phase owns failures related to builtin member lookup and canonical identity duplication.
Important fixed inputs already existed:
- reserved stdlib project spaces are resolved from the selected stdlib environment,
- source-visible builtin names resolve through imported builtin shell declarations,
- canonical builtin and host identities come from metadata rather than local spelling,
- builtin intrinsic methods are not imported as free functions,
- and host-owner namespace remains distinct from type, value, and callable namespaces.
## 2. Decision
PBS v1 adopts the following baseline for builtin shells and host-owner resolution:
1. Source-visible declarations exposed by reserved builtin shells are imported into their ordinary corresponding namespaces.
2. This means builtin-exposed types enter type lookup as imported type declarations, builtin-exposed constants enter value lookup as imported values, and host owners enter host-owner lookup as imported host-owner declarations.
3. `declare builtin type` itself remains a reserved stdlib/toolchain declaration form rather than ordinary user-authored source syntax.
4. Reserved-shell metadata exists to drive canonical identity and later lowering, not to create special source-level lookup priority.
5. Builtin simple types `int`, `float`, `bool`, and `str` remain separate always-available reserved type names and are not treated as ordinary imported builtin shells.
6. Builtin intrinsic methods never participate in free lookup.
7. Builtin intrinsic methods are resolved only through member lookup on a receiver already known to have the corresponding builtin type.
8. Reserved builtin shells and host owners follow the same collision policy as ordinary imported declarations: same visible name in the same namespace is an error unless another already-closed rule explicitly permits otherwise.
9. By policy, builtin shells are preferred under `@core:*`.
10. Member lookup failure on an already-typed builtin receiver belongs to static semantics.
11. Duplicate canonical builtin identities or duplicate canonical host identities in one resolved environment belong normatively to linking rather than to syntax or ordinary static semantics.
## 3. Reserved Shells As Imported Declarations
Reserved shells are source-visible through ordinary import and visibility rules.
This means:
- the user imports the shell from a reserved stdlib module,
- the imported shell becomes visible in the matching namespace,
- and source-level lookup treats that visible declaration like other imported declarations of the same namespace.
The compiler still recognizes the reserved metadata attached to those declarations, but that metadata does not create a parallel hidden namespace.
## 4. Builtin Simple Types Versus Imported Builtin Shells
PBS distinguishes:
- the tiny predeclared builtin simple-type set: `int`, `float`, `bool`, `str`,
- and imported builtin shells such as `Vec2`, `Color`, or similar stdlib-exposed types.
Rules:
- builtin simple types remain always available without import,
- imported builtin shells are not promoted to that same status,
- and the two categories must not be conflated in source-level lookup.
## 5. Intrinsic Member Lookup
Builtin intrinsic members are resolved only through receiver-member lookup.
Rules:
- they do not appear in top-level callable lookup,
- they are not introduced by import as free functions,
- and aliasing the owner builtin type changes only the local visible owner spelling, not the intrinsic's canonical identity.
This keeps member semantics uniform and avoids special free-function treatment for reserved surfaces.
## 6. Collision Policy
Reserved shells receive no special collision privilege.
Rules:
- if an imported builtin shell declaration and another visible declaration produce the same visible name in the same namespace, the program is rejected under the ordinary collision rules already chosen,
- if a host owner shares a spelling with a type or value, that alone is not a conflict because host-owner namespace remains distinct,
- and reserved-shell status does not authorize silent shadowing.
## 7. Reserved Project-Space Policy
For source-level policy:
- builtin shells are preferred under `@core:*`,
- host-facing capability surfaces remain the natural fit for `@sdk:*`.
This is a policy direction for clarity and separation of concerns.
It does not change the underlying ownership model governed by other specs.
## 8. Failure Ownership Baseline
The current baseline is:
- failure to resolve a reserved stdlib module remains manifest/import resolution,
- import of a non-exported reserved shell remains linking,
- member lookup failure on an already-typed builtin receiver remains static semantics,
- duplicate canonical builtin or host identities in one resolved environment remain linking failures.
Implementations may internally perform some of these checks during environment validation, but the normative external phase ownership is linking where the linking-phase decision assigns it.
## 9. Invariants
- Reserved-shell metadata does not create special source-level lookup priority.
- Builtin intrinsic methods are never free functions in source-level lookup.
- Builtin simple types remain separate from stdlib-delivered builtin shells.
- Host owners remain in the host-owner namespace only.
- Ordinary collision rules apply to reserved-shell imports unless a later explicit rule says otherwise.
- Canonical identity conflicts are linking problems, not syntax problems.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the full stdlib-surface policy of `18. Standard Library Surface Specification.md`,
- and the final lowering consequences in `13. Lowering IRBackend Specification.md`.
## 11. Spec Impact
This decision should feed at least:
- `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
- `docs/general/specs/18. Standard Library Surface Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## 12. Validation Notes
The intended baseline is:
- reserved builtin shells are imported like ordinary declarations into the matching namespace,
- builtin methods are found only through receiver-member lookup,
- builtin simple types remain always available without import,
- `@core:*` is the preferred home for builtin shells,
- and duplicate canonical builtin or host identities are rejected at linking time.
Illustrative examples:
```pbs
import { Vec2 } from @core:math;
```
`Vec2` becomes an imported visible type declaration with builtin metadata.
```pbs
import { Vec2 } from @core:math;
Vec2.zero()
```
If `zero` is a builtin intrinsic member, it resolves through builtin member lookup on `Vec2`-typed receiver use and not through free callable lookup by the name `zero`.
```pbs
import { Vec2 } from @core:math;
declare const Vec2: int = 1;
```
This is rejected as an ordinary same-namespace collision rather than resolved by reserved-shell priority.

View File

@ -1,173 +0,0 @@
# Name Resolution - Callable Sets and Cross-Module Linking Decision
Status: Accepted (Implemented)
Cycle: Initial name-resolution closure pass
## 1. Context
PBS v1 needs a deterministic rule for how callable names cross module boundaries.
The open questions were:
- what exactly `import { f } from @project:path;` imports when `f` has multiple exported signatures,
- whether callable sets from different origins may merge,
- whether same-name imported callables from different origins are tolerated until callsite analysis,
- whether local and imported callable names may coexist under one visible function name,
- and how `mod.barrel` bounds the callable set that becomes importable.
Earlier closure already fixed important inputs:
- `mod.barrel` is the single source of module visibility,
- only `pub` names may be imported from another module,
- local function names and imported function names with the same visible name are already being treated as collisions in this closure pass,
- and callable identity is determined by callable shape rather than parameter-label spelling alone.
## 2. Decision
PBS v1 adopts the following baseline for callable sets and cross-module linking:
1. `import { f } from @project:path;` imports the exported callable set named `f` from the target module.
2. The imported callable set for `f` consists only of those overload signatures of `f` that are exported through that module's `mod.barrel`.
3. Non-exported overloads in the target module do not participate in the imported callable set.
4. Two imports of the same visible callable name are tolerated when they resolve to the same canonical underlying callable-set origin after module resolution.
5. Such same-origin duplicate imports are redundant but not errors.
6. Two imports of the same visible callable name from different canonical origins are rejected immediately.
7. The program must not wait until a callsite to reject different-origin callable-name collisions.
8. A module-local function name and an imported function name with the same visible name are rejected immediately.
9. Automatic merging of callable sets across different origins is not permitted in this closure pass.
10. Ordinary overload resolution occurs only after one unambiguous visible callable set has already been formed.
## 3. Imported Callable Set
The meaning of:
```pbs
import { f } from @project:path;
```
is:
- resolve the target module,
- collect the exported callable entries named `f` from that module,
- form the callable set consisting only of those exported overloads,
- and make that callable set visible locally under the imported visible name.
This import does not:
- reach non-exported overloads,
- merge with hidden module-internal overloads,
- or import one overload at a time independently from the exported callable name.
## 4. Same-Origin Versus Different-Origin Imports
### 4.1 Same origin
If the same visible callable name is imported more than once and both imports resolve to the same canonical underlying callable-set origin:
- the duplicate import is tolerated,
- but it remains redundant.
### 4.2 Different origin
If the same visible callable name is imported from different canonical origins:
- the program is rejected immediately,
- and one of the imports must be removed or aliased.
The implementation must not:
- merge the callable sets,
- defer the conflict to overload resolution,
- or allow callsite context to decide which imported origin wins.
## 5. Local Versus Imported Callable Names
If a module-local function name and an imported function name are the same visible callable name:
- the program is rejected immediately,
- and the implementation must not merge the local and imported callable sets.
This preserves deterministic visibility and keeps callable origin traceable.
## 6. Barrel Boundary
`mod.barrel` defines the exact boundary of the callable set that may cross module boundaries.
Rules:
- only overloads exported through `mod.barrel` are part of the importable callable set,
- overloads with the same source-level function name but not exported through `mod.barrel` are invisible to importing modules,
- and imported callable-set visibility is therefore a direct consequence of the source module's barrel contract.
## 7. Overload Resolution Boundary
This decision deliberately separates:
- callable-set formation,
- and overload resolution at a callsite.
The implementation must first form one unambiguous visible callable set.
Only then may ordinary overload resolution operate on the candidate signatures of that set.
Callsite context must not be used to resolve ambiguity between different imported callable origins.
## 8. Invariants
- Imported callable visibility is bounded by barrel export.
- Different callable origins must not merge automatically.
- Same-origin duplicate imports may be tolerated as redundancy, not as new callable contributions.
- Local and imported function names do not coexist under one merged visible callable name in this closure pass.
- Overload resolution happens after visible callable-set formation, not instead of it.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- per-overload import syntax,
- aliasing policy for callable imports beyond the already-closed generic alias rules,
- and any lowering consequences in `13. Lowering IRBackend Specification.md`.
## 10. Spec Impact
This decision should feed at least:
- `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## 11. Validation Notes
The intended baseline is:
- callable imports operate on exported callable names,
- all exported overloads of that name come together from one module,
- same-origin duplicate imports are tolerated,
- different-origin same-name imports are rejected immediately,
- and local/import callable collisions are also rejected immediately.
Illustrative examples:
```pbs
import { f } from @a:m;
import { f } from @a:m;
```
This is tolerated as redundant same-origin duplication.
```pbs
import { f } from @a:m;
import { f } from @b:n;
```
This is rejected immediately because the visible callable names match but the canonical origins differ.
```pbs
fn f(a: int) -> int { ... }
import { f } from @a:m;
```
This is rejected as a local-versus-import callable collision.

View File

@ -1,200 +0,0 @@
# Name Resolution - Linking Phase Boundary Decision
Status: Accepted (Implemented)
Cycle: Initial name-resolution closure pass
## 1. Context
PBS v1 needs an explicit phase boundary around source-level name resolution so that:
- frontend implementation does not invent phase ownership,
- diagnostics can attribute failures consistently,
- conformance can test rejection classes coherently,
- and later lowering work does not have to guess whether a failure belongs to syntax, linking, or typing.
Earlier closure already established rules for:
- module scope construction,
- import naming and aliasing,
- builtin shell visibility,
- callable-set visibility across modules.
The remaining open question was how to classify the failure classes that arise while assembling visible declarations across files and modules.
## 2. Decision
PBS v1 adopts the following normative phase baseline for name resolution and related frontend failures:
1. `syntax` is a distinct normative phase.
2. `manifest/import resolution` is a distinct normative phase.
3. `linking` is a distinct normative phase.
4. `static semantics` is a distinct normative phase.
5. `syntax` owns malformed import grammar and other token-shape or grammar-shape failures.
6. `manifest/import resolution` owns failures to resolve project space, reserved stdlib space, dependency graph, module path, or environment source.
7. `linking` owns assembly of visible declarations across files and modules.
8. `linking` therefore owns:
- import of non-exported names,
- unresolved barrel entries against module declarations,
- collisions between visible imported names from different canonical origins,
- local-versus-import visibility collisions,
- callable-origin conflicts across module boundaries,
- and duplicate canonical builtin or host identities in one resolved environment.
9. `static semantics` owns declaration validity, type checking, member lookup once the receiver type is known, and overload resolution within an already-formed visible callable set.
10. Member lookup failure on an already-typed builtin receiver belongs to `static semantics`.
11. Ambiguity between different imported origins must be rejected in `linking` before any callsite analysis.
## 3. Phase Roles
### 3.1 Syntax
`syntax` owns failures that arise before module or declaration assembly.
Examples:
- malformed import declaration shape,
- malformed alias syntax,
- malformed declaration grammar,
- unexpected tokens.
### 3.2 Manifest and Import Resolution
`manifest/import resolution` owns failures of locating and loading the source of a module or reserved environment.
Examples:
- unresolved `@project:*` dependency target,
- unresolved reserved stdlib module,
- invalid project-space selection,
- failure to load the module source from the selected environment.
### 3.3 Linking
`linking` owns the assembly of the visible declaration space after modules have been found and loaded.
Examples:
- imported name is not exported by the target module,
- `mod.barrel` entry does not resolve against declarations of the module,
- two imports expose the same visible name from different canonical origins,
- a local visible declaration collides with an imported visible declaration,
- callable-origin conflicts across module boundaries,
- duplicate canonical builtin identities in one resolved environment,
- duplicate canonical host identities in one resolved environment.
### 3.4 Static Semantics
`static semantics` owns validation and typing of the already-linked visible program.
Examples:
- duplicate local declarations,
- invalid declaration validity conditions,
- type mismatch,
- member lookup on a known receiver type,
- overload resolution inside one already-visible callable set.
## 4. Linking As A Real Normative Phase
PBS keeps `linking` as a distinct normative phase rather than collapsing it fully into `static semantics`.
Reasoning:
- some failures arise only when assembling visible declarations across files and modules,
- those failures are neither pure grammar failures nor ordinary local typing failures,
- and naming `linking` gives diagnostics and conformance a stable vocabulary for them.
This does not require every implementation to expose one identical internal compiler pass graph.
It only requires the externally visible failure ownership to map back to this normative phase model.
## 5. Barrel Matching And Visible Assembly
`mod.barrel` matching belongs to `linking`.
This means:
- failure of a barrel item to resolve to a declaration of the module is not merely a syntax issue,
- and it is not deferred until later typing or lowering.
Barrel matching is part of assembling the module's visible declaration contract.
## 6. Imported-Origin Conflicts
Conflicts between different imported origins are rejected in `linking` immediately.
This means:
- the implementation must not wait for a specific callsite or use-site,
- overload resolution is not allowed to rescue ambiguity between different imported origins,
- and visible declaration conflicts are resolved structurally before later typing work proceeds.
## 7. Builtin Receiver Lookup
Member lookup on a builtin receiver whose type is already known remains `static semantics`.
The reason is:
- by that point the relevant shell visibility work has already completed,
- and the remaining question is ordinary typed member validity rather than module assembly.
## 8. Invariants
- The phase model exposed to users and conformance must remain deterministic.
- `linking` remains the phase for visible declaration assembly across module boundaries.
- Callsite analysis must not be used to resolve imported-origin conflicts.
- `static semantics` operates on an already-linked visible declaration space.
- Syntax and manifest/import resolution remain narrower than linking and do not absorb visible-name conflicts that arise only after module loading.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- the full diagnostics-code taxonomy,
- whether implementations expose one explicit user-facing `linking` label or a mapped equivalent wording class,
- the final artifact-facing phase vocabulary after lowering and verification specs close,
- and the exact implementation architecture of one compiler pipeline.
## 10. Spec Impact
This decision should feed at least:
- `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/pbs/decisions/Name Resolution - Scope, Lookup, and Imports Decision.md`
- `docs/pbs/decisions/Name Resolution - Builtin Shells and Host Owners Decision.md`
- `docs/pbs/decisions/Name Resolution - Callable Sets and Cross-Module Linking Decision.md`
## 11. Validation Notes
The intended phase split is:
- `syntax` parses declaration and import shape,
- `manifest/import resolution` finds and loads modules,
- `linking` assembles visible names across modules and barrels,
- `static semantics` validates and types the already-linked visible program.
Illustrative examples:
```pbs
import { Missing } from @a:m;
```
If `@a:m` resolves successfully but does not export `Missing`, this is a `linking` failure.
```pbs
import { f } from @a:m;
import { f } from @b:n;
```
If the canonical origins differ, this is a `linking` failure and is rejected before any callsite analysis.
```pbs
import { Vec2 } from @core:math;
value.zero()
```
If `value` is already known to have builtin type `Vec2` and `.zero` is not a valid member on that receiver type, the failure is `static semantics`.

View File

@ -1,270 +0,0 @@
# Name Resolution - Scope, Lookup, and Imports Decision
Status: Accepted (Implemented)
Cycle: Initial name-resolution closure pass
## 1. Context
PBS v1 needs a deterministic frontend-visible rule for:
- how module scope is formed,
- how lookup works by namespace,
- what imports actually introduce into local scope,
- how collisions between local and imported names are handled,
- and which failures belong to syntax, manifest/import resolution, static semantics, or linking.
Existing specs already fix important inputs:
- `mod.barrel` is the single source of module visibility,
- imports target modules, not files,
- only `pub` names may be imported from another module,
- PBS has distinct type, value, callable, and host-owner namespaces,
- builtin simple types `int`, `float`, `bool`, and `str` are always available in type position,
- and reserved stdlib project spaces resolve only from the selected stdlib environment.
The remaining goal of this decision is to close the minimum name-resolution baseline needed for normative frontend work around ordinary scope construction, ordinary lookup, and import naming.
## 2. Decision
PBS v1 adopts the following baseline for scope construction, lookup, and imports:
1. Top-level declarations of a module are collected across all `.pbs` files in the module before visibility filtering is applied.
2. `mod.barrel` is a visibility filter over existing module declarations, not the source of declaration existence.
3. Module-internal top-level availability does not depend on source-file order.
4. Local block scopes nest normally over module scope.
5. In value position, lookup prefers the nearest lexical value binding before any module-level or imported value.
6. Parameters and local `let` bindings participate in the same nearest lexical value-scope layer for lookup purposes.
7. In type position, visible module-local type declarations are considered before imported type declarations, and builtin simple types remain always-available reserved type names outside ordinary import competition.
8. In callable position, visible module-local callable declarations are considered before imported callable declarations.
9. In host-owner position, visible module-local host owners are considered before imported host owners.
10. The local visible name introduced by an import is always the post-alias name when an alias is present.
11. `import { X } from @project:path;` introduces the imported exported name `X` into the matching namespace.
12. `import { X as Y } from @project:path;` introduces only the local visible name `Y` into the matching namespace.
13. Alias spelling changes only the local visible name, never canonical builtin identity or canonical host identity.
14. `import { * } from @project:path;` is the whole-module import form for bringing the target module's exported names into local visibility under their exported names.
15. A collision between a module-local declaration and an imported visible name in the same namespace is a deterministic error rather than silent shadowing.
16. A collision between two imported visible names in the same namespace is not an error only when both imports denote the same canonical underlying declaration after module resolution.
17. If two imported visible names in the same namespace come from different canonical underlying declarations, the program is rejected and one of the imports must be aliased or removed.
18. `import { * } from @project:path;` does not create a first-class module object, module namespace value, or other source-visible binding by itself; it only introduces the exported names of the target module.
19. A module-local function and an imported function with the same visible name produce a deterministic error in this closure pass.
20. Non-callable namespaces do not merge by name.
## 3. Scope Construction
### 3.1 Module collection
For one module:
- the compiler collects top-level declarations from all `.pbs` files in that module,
- forms one module-level declaration space,
- then applies `mod.barrel` to determine `mod` and `pub` visibility.
This means:
- declaration existence is not derived from barrel entries,
- and module-internal declaration availability is not ordered by file traversal.
### 3.2 Lexical scope
Inside executable bodies:
- lexical block scope is nested normally,
- nearest local bindings win within value lookup,
- and lexical nesting remains independent from cross-module visibility.
## 4. Lookup By Namespace
### 4.1 Value position
Value-position lookup follows this order:
1. nearest local lexical bindings,
2. parameters in the current lexical function scope,
3. visible module-local values,
4. visible imported values.
For lookup purposes, parameters and local `let` bindings are one nearest lexical value layer.
The distinction between them may still matter for diagnostics wording.
### 4.2 Type position
Type-position lookup follows this order:
1. visible module-local type declarations,
2. visible imported type declarations,
3. builtin simple types `int`, `float`, `bool`, and `str` as always-available reserved type names.
Builtin simple types are not treated as ordinary imported declarations and do not participate in ordinary import competition.
### 4.3 Callable position
Callable-position lookup follows this order:
1. visible module-local callables,
2. visible imported callables.
If a visible module-local function name and a visible imported function name are the same, the program is rejected in this closure pass rather than merged.
### 4.4 Host-owner position
Host-owner lookup follows this order:
1. visible module-local host owners,
2. visible imported host owners.
Host-owner lookup remains separate from type, value, and callable lookup.
## 5. Import Surface
### 5.1 Named import
`import { X } from @project:path;`:
- resolves the target module,
- checks that `X` is exported and importable from that module,
- and introduces `X` into the corresponding namespace locally.
### 5.2 Aliased import
`import { X as Y } from @project:path;`:
- resolves the same exported declaration as the non-aliased form,
- but introduces only `Y` as the local visible name.
Alias spelling does not change canonical identity governed elsewhere.
### 5.3 Whole-module import
`import { * } from @project:path;`:
- validates and resolves the target module,
- introduces the target module's exported visible names under their exported spellings,
- but does not create a module-valued binding,
- does not create a namespace object,
- and does not authorize qualified member access by itself.
If PBS later wants module-object or namespace-qualified source semantics, that must be added explicitly rather than inferred from this form.
## 6. Collision Policy
### 6.1 Local versus imported
If a module-local declaration and an imported declaration produce the same visible name in the same namespace:
- the program is rejected,
- and the implementation must not silently shadow the imported declaration or the local declaration.
This includes function names.
In this closure pass, a local function and an imported function with the same visible name are rejected rather than merged.
### 6.2 Imported versus imported
If two imports produce the same visible name in the same namespace:
- the program is not rejected if both imports resolve to the same canonical underlying declaration after module resolution,
- but the duplicate import is still redundant,
- and the program is rejected if the imports resolve to different canonical underlying declarations.
### 6.3 Namespace separation
Names in different namespaces do not collide merely by spelling.
For example:
- a host owner and a type declaration do not collide by spelling alone,
- because host-owner namespace remains distinct from type namespace.
## 7. Relationship To Later Name-Resolution Decisions
This decision is intentionally limited to:
- ordinary scope construction,
- ordinary namespace lookup,
- import naming,
- and ordinary collision policy.
Later name-resolution decisions close:
- reserved builtin shells and host owners,
- callable-set visibility across modules,
- and the final phase boundary between syntax, manifest/import resolution, linking, and static semantics.
## 8. Invariants
- Name lookup must be deterministic.
- Module-internal top-level declaration availability must not depend on file order.
- `mod.barrel` remains a visibility mechanism rather than a declaration source.
- Imports must not invent first-class module-object semantics accidentally.
- The effective visible name of an import is always the post-alias name when an alias is present.
- Builtin simple types remain a reserved always-available core type set, distinct from ordinary imported declarations.
- Implementations must not assume silent local-over-import shadowing.
- Implementations must not merge local and imported function names automatically.
## 9. Explicit Non-Decisions
This decision record does not yet close:
- reserved-shell-specific lookup and collision details,
- callable-set import behavior across module boundaries beyond the local-versus-import collision baseline,
- and backend-facing lowering consequences of the resolved lookup model.
## 10. Spec Impact
This decision should feed at least:
- `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
- `docs/general/specs/13. Conformance Test Specification.md`
It should also constrain future work in:
- `docs/pbs/specs/13. Lowering IRBackend Specification.md`
- `docs/pbs/decisions/Name Resolution - Builtin Shells and Host Owners Decision.md`
- `docs/pbs/decisions/Name Resolution - Callable Sets and Cross-Module Linking Decision.md`
- `docs/pbs/decisions/Name Resolution - Linking Phase Boundary Decision.md`
## 11. Validation Notes
The intended baseline is:
- all top-level declarations in a module exist before barrel filtering,
- lookup is namespace-specific and deterministic,
- the effective visible import name is the alias name when an alias is present,
- whole-module import through `import { * } from @project:path;` introduces exported names rather than a module object,
- local/import collisions are rejected rather than shadowed,
- and builtin simple types remain reserved always-available names outside ordinary import competition.
Illustrative examples:
```pbs
import { Foo } from @a:m;
declare const Foo: int = 1;
```
This is rejected as a local-versus-import collision in the value namespace.
```pbs
import { f } from @a:m;
import { f } from @b:n;
```
This is rejected because the visible imported names match but the canonical origins differ.
```pbs
fn f(a: int) -> int { ... }
import { f } from @a:m;
```
This is rejected as a local-versus-import collision in callable position.
```pbs
import { * } from @a:m;
```
This introduces the exported visible names of `@a:m`, but does not introduce a source-visible module object in v1.
```pbs
import { A as aaa } from @a:m;
```
The visible local declaration name is `aaa`, not `A`.

View File

@ -1,130 +0,0 @@
# Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Decision
Status: Accepted
Date: 2026-03-22
Related Agenda: `docs/compiler/pbs/agendas/19.3. Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Agenda.md`
## Context
After closing globals and lifecycle semantics, PBS v1 still needed a precise publication contract for executable boot.
The remaining problem was no longer how initialization behaves in userland.
It was how that behavior is published into the artifact and consumed by backend stages and runtime.
The open points were:
- whether the published entrypoint is still the user `frame()` callable,
- whether a synthetic wrapper becomes the true physical entrypoint,
- where `FRAME_RET` must live once lifecycle bootstrap exists,
- whether `FrontendSpec` continues to hold authority over entrypoint identity,
- and whether `manifest.json` remains part of entrypoint authority.
Important fixed inputs already existed:
- `[Frame]` identifies the userland logical frame root,
- module init and project init are already defined in lifecycle terms,
- boot is one-shot and fail-fast,
- and general backend specs already converge on entrypoint function index `0`.
## Decision
PBS adopts the following publication and ownership policy for executable boot in v1:
1. The compiler publishes a synthetic wrapper as the physical executable entrypoint.
2. The userland callable marked with `[Frame]` remains the logical frame root of user code.
3. The synthetic wrapper is therefore the physical root, while `[Frame]` remains the logical root.
4. The wrapper must contain:
- one-shot boot orchestration,
- the required init execution exactly once,
- invocation of the userland `[Frame]` callable,
- and the final `FRAME_RET`.
5. `FRAME_RET` no longer belongs at the end of the userland `frame()` body.
6. `FRAME_RET` belongs to the published wrapper.
7. The published wrapper must occupy physical entrypoint index `0`.
## Entrypoint Authority
PBS adopts the following authority model:
1. `FrontendSpec` no longer holds authority to decide which callable is the published entrypoint for PBS.
2. Entrypoint authority is owned exclusively by the PBS compiler.
3. Source-derived lifecycle semantics determine the logical frame root.
4. The compiler then publishes the physical wrapper that realizes that lifecycle contract.
5. Backend handoff must therefore preserve the compiler-selected published wrapper as the effective entrypoint identity.
## Manifest and Runtime Protocol
PBS adopts the following target protocol direction:
1. `entrypoint` must stop being part of the final `manifest.json` contract.
2. Runtime boot must not depend on nominal entrypoint resolution from the manifest.
3. Runtime boot must treat physical entrypoint index `0` as protocol.
4. The compiler guarantees that the published wrapper occupies that index.
5. Any temporary compatibility line with manifest-declared nominal entrypoint is transitional only and is not the target contract.
## Exports Boundary
PBS adopts the following boundary for nominal exports:
1. Nominal function exports may continue to exist in the emitted artifact.
2. Those exports are no longer authoritative for loader or boot.
3. Boot depends exclusively on the published physical entrypoint at index `0`.
4. Nominal exports remain useful only for tooling, debug, introspection, and related non-boot concerns.
## Rationale
This decision keeps logical user semantics and physical boot publication clearly separated.
That matters because:
- the user `frame()` callable should remain the semantic root of frame logic,
- the one-shot bootstrap sequence must still execute before normal frame work,
- `FRAME_RET` should mark the true end of the logical published frame,
- and the compiler must be the single authority that turns source lifecycle into executable publication.
The decision also deliberately removes duplicated authority:
- not `FrontendSpec`,
- not manifest nominal metadata,
- and not PBX nominal exports
are allowed to compete with the compiler-selected physical wrapper as boot authority.
## Invariants
1. `[Frame]` remains the userland logical frame root.
2. The published wrapper remains the physical executable root.
3. `FRAME_RET` belongs to the published wrapper.
4. Physical entrypoint index `0` belongs to that wrapper.
5. Nominal exports are not boot authority.
6. Entrypoint authority for PBS belongs to the compiler, not to `FrontendSpec` or manifest metadata.
## Explicit Non-Decisions
1. This decision does not define the final IR encoding of the wrapper body.
2. This decision does not define the detailed lowering mechanics of globals and lifecycle into IR.
3. This decision does not define the runtime-side migration implementation plan in detail.
4. This decision does not define the final diagnostics catalog for backend/runtime structural failures.
## Spec Impact
This decision should feed at least:
1. `docs/compiler/pbs/specs/9. Dynamic Semantics Specification.md`
2. `docs/compiler/pbs/specs/13. Lowering IRBackend Specification.md`
3. `docs/compiler/pbs/specs/7. Cartridge Manifest and Runtime Capabilities Specification.md`
4. `docs/compiler/general/specs/15. Bytecode and PBX Mapping Specification.md`
5. `docs/compiler/general/specs/20. IRBackend to IRVM Lowering Specification.md`
It also requires explicit cross-domain propagation to:
1. `../runtime/docs/runtime/agendas/025-cartridge-manifest-entrypoint-removal-and-runtime-protocol.md`
## Validation Notes
At minimum, validation for this decision should include:
1. emitted artifact evidence that the published wrapper occupies function index `0`;
2. conformance evidence that the userland `[Frame]` callable is invoked by that wrapper rather than being published directly;
3. evidence that `FRAME_RET` is emitted in the wrapper path;
4. evidence that nominal exports, when present, do not participate in boot authority;
5. integration evidence that runtime boot aligns with the fixed physical entrypoint protocol.

View File

@ -1,44 +0,0 @@
# PBS Decisions
This directory contains PBS decision records.
## Purpose
A decision record is the bridge between agenda discussion and normative spec text.
Use this directory to capture:
- what was decided,
- why that direction was chosen,
- which constraints now apply,
- what remains intentionally out of scope,
- which specs must be updated.
Architecture and decisions must be resolved before implementation.
## Expected Format
A decision record should usually include:
1. Title
2. Status
3. Date or Cycle
4. Context
5. Decision
6. Invariants
7. Explicit Non-Decisions
8. Spec Impact
9. Validation Notes or Examples
## Writing Rules
- Write in stable, reviewable language.
- State the adopted decision first and clearly.
- Capture architectural constraints and invariants explicitly.
- Record what is still not decided so later implementation does not guess.
- Point to the exact specs that need integration.
## Implementation Rule
If implementation work exposes a missing decision, do not infer it.
Stop, surface the ambiguity, and return it to agenda or decision review.

View File

@ -1,41 +0,0 @@
# SPAWN-YIELD v1 Claim Rescope Decision
Status: Accepted
Cycle: Agenda 18 / PR-06.6
## Context
Os requisitos `G20-9.4.2` e `G20-9.4.3` estavam em estado `deferred` porque `SPAWN` e `YIELD` ainda nao fazem parte da superficie executavel v1 atualmente claimada pelo backend.
Sem uma decisao formal, o claim ficava ambiguo para auditoria externa.
## Decision
Adotamos oficialmente a **Trilha B**.
1. `SPAWN` e `YIELD` ficam fora do escopo do claim executavel `core-v1`.
2. O backend v1 deve tratar essas formas como nao-suportadas no escopo claimado.
3. Invariantes especificas de aridade/stack para `SPAWN` e `YIELD` ficam reservadas para um perfil futuro que as admita explicitamente.
## Invariants
1. Nenhum claim `core-v1` pode implicar suporte executavel a `SPAWN`/`YIELD`.
2. Se um perfil futuro admitir `SPAWN`/`YIELD`, deve publicar evidencias de conformidade dedicadas antes de claim de suporte.
3. Matriz de conformidade deve explicitar o rescope para evitar regressao silenciosa de claim.
## Spec Impact
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`:
- secao 9.4 passa a declarar `SPAWN`/`YIELD` fora do escopo de `core-v1`.
2. `docs/general/specs/17. Compatibility and Evolution Policy.md`:
- claims suportados devem explicitar superficies executaveis excluidas.
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`:
- linhas `G20-9.4.2` e `G20-9.4.3` saem de `deferred` para status alinhado ao rescope.
## Validation Notes
Validacao desta decisao e documental/policy:
1. testes de integridade de spec/matriz para `SPAWN`/`YIELD` claim rescope;
2. verificacao explicita de status e notas na matriz;
3. rastreabilidade via esta decision record.

View File

@ -1,190 +0,0 @@
# Value Representation and Identity Decision
Status: Accepted (Implemented)
Cycle: Initial value-representation closure pass
## 1. Context
PBS v1 needs a stable user-visible model for:
- which values are pure copied payloads,
- which values preserve shared runtime identity,
- which carriers merely wrap other values,
- and how callback values fit into the language without exposing general first-class functions or closures.
Earlier decisions already fixed important inputs:
- structs are reference-like in ordinary use,
- services are canonical singleton values,
- `bind(context, fn_name)` captures the same struct identity without copying it,
- `optional` and `result` remain explicit carriers rather than implicit effect-lifting mechanisms.
## 2. Decision
PBS v1 adopts the following value-representation baseline:
1. Pure scalar-like values are copied by value and do not carry user-visible identity.
2. Struct values are identity-bearing, heap-backed reference values.
3. Service values are identity-bearing canonical singleton values.
4. Host-backed resource values are identity-bearing values on the PBS side, even though their backing authority remains host-owned.
5. Tuple, `optional`, and `result` carriers do not introduce identity of their own.
6. Contract values do not introduce a new user-visible identity distinct from the underlying struct or service value.
7. Callback values are first-class callable values in PBS v1, but callback identity is not promoted as a user-visible identity concept.
8. Assignment, parameter passing, and return preserve aliasing for identity-bearing values and copy payload for pure value kinds.
## 3. Value Categories
### 3.1 Pure copied values
The following value kinds are pure copied values in the user model:
- `int`
- `float`
- `bool`
- enum values
- canonical `str`
Assignment, parameter passing, and return of these values copy the value itself.
### 3.2 Identity-bearing values
The following value kinds carry stable user-visible identity:
- struct values
- service values
- host-backed resource/handle values
Assignment, parameter passing, and return of these values preserve aliasing to the same runtime entity rather than copying an independent underlying object.
### 3.3 Carrier-only values
The following value kinds are carriers and do not create identity of their own:
- tuples
- `optional`
- `result`
They preserve the semantics of the values they contain.
If a carrier contains an identity-bearing payload, the carrier transports that same payload identity rather than inventing a new one.
## 4. Structs
Struct values are always reference-like in PBS v1.
Rules:
- `new Struct(...)` produces a fresh struct identity.
- Assignment of a struct value copies the reference, not the underlying field storage.
- Passing or returning a struct value preserves aliasing to the same struct instance.
- Mutation through one alias is observable through other aliases to that same struct instance.
## 5. Services
Service values are canonical module-owned singleton values.
Rules:
- A service value denotes the same singleton identity wherever it is used in the same resolved program.
- Assignment, parameter passing, and return preserve that same singleton identity.
- Service use does not create fresh service instances.
## 6. Contract Values
Contract values do not introduce a new user-visible entity.
A contract value is a runtime view over:
- an underlying struct identity or service singleton identity,
- together with the selected contract implementation used for dispatch.
For user-facing semantics:
- aliasing is defined by the underlying struct or service value,
- not by treating the contract wrapper as a separate identity-bearing object.
## 7. Callback Values
Callback values are first-class callable values in PBS v1.
This means they may be:
- assigned to variables,
- passed as arguments,
- and returned from functions.
However, PBS v1 does not promote callback identity as an explicit user-visible identity concept.
### 7.1 Plain callback values
When a callback value is formed from a compatible top-level `fn`, it denotes a callable value over that target function.
### 7.2 Bound callback values
When a callback value is formed through `bind(context, fn_name)`:
- the same struct context identity is captured,
- the context is not copied,
- the callback retains the target function together with that captured context,
- and invoking the callback behaves as if the target function is called with the captured context as its first argument.
### 7.3 User model
The language must explain callback behavior without requiring the user to reason about callback identity as if callbacks were ordinary heap objects.
It is sufficient to state that:
- callbacks are first-class callable values,
- bound callbacks retain their captured context,
- and copies of a callback value preserve the same callable meaning and retained context.
## 8. Copy Versus Aliasing Rule
The general rule for PBS v1 is:
- pure value kinds are copied by value,
- identity-bearing kinds preserve aliasing,
- carrier kinds preserve the semantics of their contained values and do not create identity of their own.
Examples:
- assigning an `int` copies the integer value,
- assigning a `Struct` value copies the reference to the same struct instance,
- assigning an `optional<Player>` that contains `some(player)` preserves the same `Player` identity inside the carrier,
- assigning a `result<E> Player` success payload preserves the same `Player` identity inside the carrier.
## 9. Beginner-Facing Model
The user-facing explanation should be:
- some values are plain data, so passing them passes the value,
- structs and services are shared entities, so passing them passes access to the same entity,
- tuples, `optional`, and `result` only package values and do not become new entities by themselves,
- callbacks are callable values, and bound callbacks keep the same captured context rather than copying it.
This wording is simple enough for beginners while still preserving the performance-relevant truth about aliasing and mutation.
## 10. Explicit Non-Decisions
This decision record does not yet close:
- the exact runtime layout of any heap object,
- collection value categories in detail,
- the final host-backed handle representation syntax,
- the final diagnostics wording for aliasing/copy visibility.
## 11. Spec Impact
This decision should feed at least:
- `docs/pbs/specs/10. Memory and Lifetime Specification.md`
- `docs/pbs/specs/4. Static Semantics Specification.md`
- `docs/pbs/specs/12. Diagnostics Specification.md`
## 12. Validation Notes
The intended split is:
- structs, services, and host-backed resources behave like identity-bearing entities,
- tuples, `optional`, and `result` are carriers,
- callbacks are first-class callable values without promoted callback identity in the user model.

View File

@ -1,211 +0,0 @@
# PBS Frontend PR Sequence
Este indice organiza uma sequencia de PRs atomicas para levar `frontends/pbs` ao contrato das specs.
1. `PR-001-pbs-lexer-core-syntax-alignment.md`
2. `PR-002-pbs-ast-contract-v1.md`
3. `PR-003-pbs-parser-declarations-and-types.md`
4. `PR-004-pbs-parser-statements-and-control-flow.md`
5. `PR-005-pbs-parser-expressions-optional-result-apply.md`
6. `PR-006-pbs-barrel-and-module-visibility.md`
7. `PR-006.2-pbs-parser-ast-syntax-hardening.md`
8. `PR-006.3-pbs-syntax-completeness-and-module-hygiene.md`
9. `PR-007-pbs-static-semantics-declaration-validation.md`
10. `PR-008-pbs-static-semantics-call-resolution-and-flow.md`
11. `PR-009-pbs-diagnostics-contract-v1.md`
12. `PR-010-pbs-irbackend-lowering-contract.md`
13. `PR-011-pbs-gate-u-conformance-fixtures.md`
Cada documento e auto contido e inclui: `Briefing`, `Target`, `Method`, `Acceptance Criteria` e `Tests`.
## Non-Conformance Remediation PRs
14. `PR-012-pbs-byte-offset-spans.md`
15. `PR-013-pbs-import-unresolved-diagnostics.md`
16. `PR-014-pbs-switch-wildcard-rules.md`
17. `PR-015-pbs-this-self-context-validation.md`
18. `PR-016-pbs-assignment-target-and-field-access-semantics.md`
19. `PR-017-pbs-const-evaluation-and-dependency-rules.md`
20. `PR-018-pbs-result-flow-ok-err-handle-rules.md`
21. `PR-019-pbs-non-unit-fallthrough-diagnostics.md`
22. `PR-020-pbs-lowering-admission-gates.md`
23. `PR-021-pbs-handle-aware-fallthrough-completion.md`
24. `PR-022-pbs-source-kind-and-module-origin-pipeline.md`
25. `PR-023-pbs-stdlib-environment-resolver-and-loader.md`
26. `PR-024-pbs-parser-ast-interface-module-mode.md`
27. `PR-025-pbs-interface-module-semantics-and-linking.md`
28. `PR-026-pbs-sdk-minimal-core-color-and-gfx.md`
29. `PR-027-pbs-builtin-metadata-extraction-and-ir-lowering-admission.md`
30. `PR-028-pbs-gate-u-sdk-interface-module-fixtures.md`
31. `PR-029-pbs-builtin-slot-inference-and-layout-semantics.md`
32. `PR-030-pbs-host-admission-capability-gating.md`
33. `PR-031-pbs-dependency-scoped-fail-fast-admission.md`
## Backend VM Pipeline PR Sequence (Agenda 18)
Esta sequencia organiza implementacao atomica para `IRBackend -> IRVM -> OptimizeIRVM -> EmitBytecode`, com trilha de montagem do output para o input (bytecode ate IRBackend).
34. `PR-032-backend-bytecode-module-serializer-baseline.md`
35. `PR-033-backend-bytecode-function-layout-and-debug-minimum.md`
36. `PR-034-backend-emitter-hostcall-sysc-contract.md`
37. `PR-035-backend-emit-stage-pipeline-wiring.md`
38. `PR-036-backend-irvm-core-model-and-validator.md`
39. `PR-037-backend-optimize-irvm-noop-stage-and-guards.md`
40. `PR-038-irbackend-v2-executable-contract-model.md`
41. `PR-039-pbs-frontend-irbackend-v2-lowering.md`
42. `PR-040-backend-lower-to-irvm-stage-implementation.md`
43. `PR-041-backend-gate-i-runtime-compat-integration-fixtures.md`
## JVM-Grade Remediation Waves (Execution Plan)
Esta trilha organiza as PRs por ondas para execucao incremental com rollback simples por item.
### Onda O1 - Conformance and Correctness Hardening
1. `PR-O1.1-backend-diagnostics-taxonomy-and-attribution.md`
2. `PR-O1.2-irbackend-executable-contract-hardening.md`
3. `PR-O1.3-pbs-executable-lowering-fidelity.md`
4. `PR-O1.4-lower-to-irvm-callsite-prechecks.md`
5. `PR-O1.5-bytecode-debug-minimum-completeness.md`
6. `PR-O1.6-gate-su-safety-matrix-completion.md`
### Onda O2 - JVM-Inspired Verification and Linking Boundaries
1. `PR-O2.1-bytecode-link-precheck-stage.md`
2. `PR-O2.2-bytecode-preload-verifier.md`
3. `PR-O2.3-optimize-irvm-pass-manager-and-equivalence.md`
4. `PR-O2.4-gate-i-runtime-backed-compat-harness.md`
### Onda O3 - Evolution and Scale
1. `PR-O3.1-irvm-control-flow-lowering-label-resolution.md`
2. `PR-O3.2-bytecode-constpool-symbol-interning-determinism.md`
3. `PR-O3.3-irvm-profile-evolution-and-feature-gates.md`
### Onda O4 - JVM-Grade Uplift
1. `PR-O4.1-callable-signature-identity-and-dense-symbol-table.md`
2. `PR-O4.2-global-intrinsic-table-and-reindexing.md`
3. `PR-O4.3-semantic-lowering-cfg-and-stack-analysis.md`
4. `PR-O4.4-irvm-program-single-source-of-truth.md`
5. `PR-O4.5-vm-profile-end-to-end-pipeline.md`
6. `PR-O4.6-strict-bytecode-precheck-unknown-opcode-rejection.md`
7. `PR-O4.7-gate-i-runtime-backed-execution-adapter.md`
8. `PR-O4.8-jvm-grade-regression-matrix-and-golden-artifacts.md`
### Onda O5.0 - Dense Table Identity Foundation (Pre-O5)
1. `PR-05.0.1-frontend-phase-shared-name-table-context.md`
2. `PR-05.0.2-module-identity-dense-table-and-moduleid-wiring.md`
3. `PR-05.0.3-irbackend-typed-callable-and-intrinsic-ids.md`
4. `PR-05.0.4-callable-shape-and-signature-interning.md`
5. `PR-05.0.5-synthetic-stdlib-fileid-via-filetable.md`
6. `PR-05.0.6-host-binding-key-interning-and-capability-identity.md`
### Onda O5 - JVM-Grade Score Evolution (5.6 -> 8.5+)
Prerequisito de execucao: concluir a Onda O5.0.
1. `PR-05.1-pbs-frontend-semantic-executable-lowering-cfg.md`
2. `PR-05.2-irbackend-callsite-classification-by-semantic-identity.md`
3. `PR-05.3-irvm-deterministic-function-id-and-entrypoint-policy.md`
4. `PR-05.4-irvm-program-coherence-without-bypass.md`
5. `PR-05.5-irvm-validator-real-stack-effects-hostcall-intrinsic.md`
6. `PR-05.6-optimize-irvm-real-deterministic-passes.md`
7. `PR-05.7-gate-i-runtime-backed-mandatory-in-ci.md`
8. `PR-05.8-backend-spec-to-test-conformance-matrix.md`
### Onda O6 - JVM-Grade Score Evolution (8.0 -> 9.0+)
Foco: fechar `partial/deferred` relevantes da matriz normativa e endurecer evidencia de conformidade.
1. `PR-06.1-source-attribution-and-diagnostics-evidence-hardening.md`
2. `PR-06.2-optimize-irvm-semantic-equivalence-harness.md`
3. `PR-06.3-irvm-ext-contract-and-elimination-fixtures.md`
4. `PR-06.4-gate-i-runtime-line-repeatability-ci.md`
5. `PR-06.5-conformance-matrix-hard-gate-policy.md`
6. `PR-06.6-spawn-yield-v1-or-claim-rescope.md`
### Onda O7 - Partial Closure Before IDE Focus
Foco: eliminar os dois `partial` remanescentes na matriz backend antes de mover foco principal para IDE.
1. `PR-07.1-optimize-irvm-span-source-hook-preservation.md`
2. `PR-07.2-pbs-callsite-category-no-textual-heuristics-regression.md`
3. `PR-07.3-irvm-entrypoint-export-emission-for-runtime-loader.md`
### Onda O8 - Canonical Identity and Dense Addressing Hardening
Foco: fechar lacunas estruturais em identidade canonica de intrinsic/modulo/entrypoint e remover riscos de ambiguidade no handoff FE->BE.
1. `PR-08.1-intrinsic-resolution-canonical-identity-keying.md`
2. `PR-08.2-irbackend-moduleid-contract-and-modulepool.md`
3. `PR-08.3-qualified-entrypoint-identity-contract.md`
4. `PR-08.4-call-func-callee-module-identity-correctness.md`
5. `PR-08.5-intrinsic-registry-single-source-sync-with-runtime.md`
### Onda O9 - ModuleId-Only Contract Cutover
Foco: remover definitivamente `moduleKey` textual do contrato estrutural FE->BE, endurecer entrypoint qualificado e alinhar specs/matriz com o modelo `ModuleId`-only.
1. `PR-09.1-irbackend-modulekey-hard-removal-from-contract.md`
2. `PR-09.2-pbs-frontend-moduleid-only-lowering-and-import-surfaces.md`
3. `PR-09.3-lower-to-irvm-moduleid-only-ordering-and-strict-qualified-entrypoint.md`
4. `PR-09.4-specs-refresh-moduleid-only-entrypointref-and-bytecode-alignment.md`
5. `PR-09.5-hard-gates-no-modulekey-regression-and-migration-cleanup.md`
6. `PR-09.6-isa-intrinsic-registry-single-source-artifact.md`
7. `PR-09.7-compiler-normalization-to-isa-registry-artifact.md`
### Onda O10 - Parser Maintainability Refactor (No Functional Change)
Foco: reduzir complexidade estrutural de `PbsParser` sem alterar gramatica, AST, spans ou contrato de diagnosticos observavel.
1. `PR-10.1-pbs-parser-shared-context-and-safe-delegation.md`
2. `PR-10.2-pbs-parser-attribute-and-type-subparsers.md`
3. `PR-10.3-pbs-parser-top-level-declaration-decomposition.md`
4. `PR-10.4-pbs-parser-block-and-statement-decomposition.md`
5. `PR-10.5-pbs-parser-recovery-utilities-and-regression-hardening.md`
### Onda O11 - Expression Parser Maintainability Refactor (No Functional Change)
Foco: reduzir complexidade estrutural de `PbsExprParser` sem alterar precedence, AST, spans, recovery ou diagnosticos observaveis.
1. `PR-11.1-pbs-expr-parser-shared-context-and-precedence-spine.md`
2. `PR-11.2-pbs-expr-parser-control-flow-subparsers.md`
3. `PR-11.3-pbs-expr-parser-postfix-primary-and-construction-decomposition.md`
4. `PR-11.4-pbs-expr-parser-literals-patterns-and-shared-token-utilities.md`
5. `PR-11.5-pbs-expr-parser-regression-hardening-and-final-cleanup.md`
### Onda O12 - Flow Expression Analyzer Maintainability Refactor (No Functional Change)
Foco: reduzir complexidade estrutural de `PbsFlowExpressionAnalyzer` sem alterar inferencia, diagnosticos, matching de tipos ou comportamento observavel da analise semantica.
1. `PR-12.1-flow-expression-analyzer-context-and-dispatch-foundation.md`
2. `PR-12.2-flow-expression-analyzer-literal-and-structural-expression-splitting.md`
3. `PR-12.3-flow-expression-analyzer-call-and-member-resolution-decomposition.md`
4. `PR-12.4-flow-expression-analyzer-switch-and-handle-decomposition.md`
5. `PR-12.5-flow-expression-analyzer-regression-hardening-and-final-cleanup.md`
### Onda O13 - Flow Body Analyzer Maintainability Refactor (No Functional Change)
Foco: reduzir complexidade estrutural de `PbsFlowBodyAnalyzer` sem alterar regras de flow, completion, assignment checking ou diagnosticos observaveis.
1. `PR-13.1-flow-body-analyzer-context-and-entrypoint-foundation.md`
2. `PR-13.2-flow-body-analyzer-callable-body-and-completion-decomposition.md`
3. `PR-13.3-flow-body-analyzer-statement-analysis-splitting.md`
4. `PR-13.4-flow-body-analyzer-assignment-target-resolution-decomposition.md`
5. `PR-13.5-flow-body-analyzer-regression-hardening-and-final-cleanup.md`
### Onda O19 - Globals, Lifecycle, Published Wrapper, and Conformance
Foco: implementar a familia `19` em sequencia executavel, com runtime boot protocol ja alinhado e `learn` deliberadamente postergado para fechamento posterior.
1. `PR-19.1-pbs-topic-19-spec-propagation-and-normative-cutover.md`
2. `PR-19.2-infra-dependencygraphanaliser-extraction-and-module-cutover.md`
3. `PR-19.3-pbs-parser-ast-globals-barrel-and-lifecycle-markers.md`
4. `PR-19.4-pbs-semantics-global-surface-identity-and-collision-validation.md`
5. `PR-19.5-pbs-semantics-global-dependency-graph-and-cycle-validation.md`
6. `PR-19.6-pbs-semantics-lifecycle-init-frame-and-initallowed-validation.md`
7. `PR-19.7-pbs-lowering-irbackend-globals-and-synthetic-callable-model.md`
8. `PR-19.8-pbs-lowering-published-wrapper-entrypoint-zero-and-frame-ret.md`
9. `PR-19.9-pbs-conformance-fixtures-diagnostics-and-gate-closure.md`

View File

@ -1,63 +0,0 @@
# PR-05.0.1 - Frontend Phase Shared NameTable Context
## Briefing
Hoje o frontend PBS cria `NameTable` em componentes diferentes (linking, declarative semantics, rules), o que fragmenta identidade de nome por fase.
Esta PR centraliza `NameTable` no `FrontendPhaseContext` para toda a fase de frontend, com um ciclo de vida unico por compilacao.
## Motivation
### Dor que esta PR resolve
1. Mesma string pode receber `NameId` diferente dependendo da fase.
2. Dificulta evoluir para identidades tipadas cross-phase sem adaptadores de conversao.
3. Complica debug e rastreabilidade de diagnosticos semanticos entre linking e lowering.
## Target
Uniformizar identidade de nomes no FE inteiro, com `NameId` estavel durante a fase de frontend.
## Scope
1. `FrontendPhaseContext` passa a expor `NameTable`.
2. Validators e binders do PBS passam a receber `NameTable` do contexto, sem criar tabela local.
3. Ajuste de testes que dependem de instanciacao direta.
## Non-Goals
1. Nao altera regras semanticas.
2. Nao altera parser/AST.
## Method
### O que deve ser feito explicitamente
1. Adicionar `NameTable` ao contexto da fase de frontend.
2. Remover `new NameTable()` locais em linking/semantics.
3. Injetar o `NameTable` compartilhado em:
- `PbsModuleVisibilityValidator`,
- `PbsDeclarationSemanticsValidator`,
- `PbsDeclarationRuleValidator`,
- `PbsNamespaceBinder`.
4. Garantir que o ciclo de vida da tabela seja por execucao de fase, nao global estatico.
## Acceptance Criteria
1. Nao existe mais alocacao local de `NameTable` nas fases PBS do frontend.
2. Mesmo nome gera mesmo `NameId` em linking e semantica na mesma compilacao.
3. Testes de linking/semantica continuam passando sem regressao comportamental.
## Tests
1. Teste de identidade cruzada (linking vs declaration validation) para nomes iguais.
2. Teste de isolamento entre duas compilacoes diferentes (nao vazar IDs entre runs).
## Affected Documents
1. `docs/pbs/specs/11. AST Specification.md`
2. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,59 +0,0 @@
# PR-05.0.2 - Module Identity Dense Table and ModuleId Wiring
## Briefing
O FE usa `String moduleKey` em varios mapas e no handoff para backend.
Esta PR introduz identidade densa de modulo (`ModuleTable` + `ModuleId`) e faz o FE operar internamente por ID, mantendo string apenas como representacao de borda quando necessario.
## Motivation
### Dor que esta PR resolve
1. Chaves string de modulo sao repetidas e suscetiveis a inconsistencia de normalizacao.
2. Custos de hash/string crescem com o grafo de modulos.
3. Dificuldade de garantir determinismo e joins estaveis em agregacao multi-modulo.
## Target
Substituir identidade interna de modulo baseada em string por `ModuleId` internado.
## Scope
1. Criacao de `ModuleTable` no core.
2. Uso de `ModuleId` em `PBSFrontendPhaseService` para mapas de modulo/dependencias.
3. Adaptacao de pontos de diagnostico e exibição para renderizar nome canônico quando preciso.
## Non-Goals
1. Nao altera sintaxe de import.
2. Nao altera formato de mensagens ao usuario final alem do necessario.
## Method
### O que deve ser feito explicitamente
1. Implementar `ModuleTable extends InternTable<ModuleId, ModuleRef>` (ou valor equivalente canonico).
2. Trocar `Map<String,...>` de modulo em `PBSFrontendPhaseService` por `Map<ModuleId,...>`.
3. Trocar grafo de dependencia de `String` para `ModuleId`.
4. Manter funcao unica de render de modulo para diagnostico.
## Acceptance Criteria
1. Fluxo principal do FE nao depende de `moduleKey` string para joins internos.
2. Dependencias e bloqueios por falha de modulo usam `ModuleId`.
3. Nao ha regressao funcional em linking/import gating.
## Tests
1. Teste de determinismo de IDs de modulo para mesmo grafo admitido.
2. Teste de propagacao de falha por dependencia usando IDs.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,62 +0,0 @@
# PR-05.0.3 - IRBackend Typed Callable and Intrinsic IDs
## Briefing
O contrato `IRBackendExecutableFunction` ainda carrega `callableId`, `calleeCallableId` e `intrinsicId` como `int/Integer`.
Esta PR tipa esses campos com `CallableId` e `IntrinsicId`, alinhando model com Dense Tables e reduzindo erro de classe de ID.
## Motivation
### Dor que esta PR resolve
1. Mistura acidental entre dominios de ID diferentes em tempo de desenvolvimento.
2. Validacoes repetitivas de faixa/semantica por usar primitivo nu.
3. API de backend menos segura para evolucao de lowering/remap.
## Target
Evoluir o contrato de FE->BE para IDs tipados em vez de inteiros crus.
## Scope
1. `IRBackendExecutableFunction` e metadados de instrucao.
2. `IRBackendAggregator` remap de callables e intrinsecos.
3. Ajustes de serializers/tests que assumem `int`.
## Non-Goals
1. Nao muda semantica de chamada.
2. Nao muda ordenacao de remap por si so.
## Method
### O que deve ser feito explicitamente
1. Trocar:
- `int callableId` -> `CallableId`,
- `Integer calleeCallableId` -> `CallableId` (nullable quando aplicavel),
- `int intrinsicId` -> `IntrinsicId`.
2. Atualizar construtores/guards para validar `.isNone()` e nao-negatividade via tipo.
3. Atualizar `IRBackendAggregator` para trabalhar com vetores/tabelas de IDs tipados.
4. Atualizar FE lowering PBS para emitir IDs tipados desde origem.
## Acceptance Criteria
1. Nao ha mais campos de callable/intrinsic ID como inteiro cru no contrato executavel.
2. Tentativas de misturar dominio de ID falham em compile-time.
3. Testes de remap e merge seguem verdes.
## Tests
1. Testes unitarios de construcao de instrucao com tipos corretos/incorretos.
2. Testes de agregacao multi-arquivo validando remap tipado.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,62 +0,0 @@
# PR-05.0.4 - Callable Shape and Signature Interning
## Briefing
O FE ainda monta chaves semanticas por concat string (`name#arity`, `signatureSurface`, `typeShape`).
Esta PR cria internacao para superfícies de assinatura/shape e remove concatenação textual como identidade primaria.
## Motivation
### Dor que esta PR resolve
1. Chave textual e fragil para evolucao de formato.
2. Custo de alocacao/hash desnecessario em caminhos quentes.
3. Risco de colisao logica por normalizacao incompleta.
## Target
Internar shapes de callable e superfícies de assinatura em tabela dedicada, com ID estavel.
## Scope
1. Estruturas de assinatura do linking e lowering.
2. `CallableSignatureRef` com suporte a referencia internada de shape.
3. Remocao gradual de `callableArityKey` e derivados string.
## Non-Goals
1. Nao altera regra de overload.
2. Nao altera formato externo de diagnostico.
## Method
### O que deve ser feito explicitamente
1. Introduzir tabela de shapes (ex.: `CallableShapeTable` / `TypeSurfaceTable`).
2. Representar identidade de callable por tupla tipada (`NameId`, aridade, `ShapeId`).
3. Atualizar:
- linking (`FunctionSymbolKey`),
- FE lowering executavel (`callableIdsByNameAndArity`),
- referencias em `CallableSignatureRef`.
4. Manter conversao para string apenas para logs/debug.
## Acceptance Criteria
1. Fluxo principal de resolução de callable nao depende de concat string.
2. Determinismo de shape/signature comprovado por ID internado.
3. Nenhuma regressao de resolução de overload/documentada.
## Tests
1. Teste de internacao idempotente para shape identico.
2. Testes de distinção para shapes diferentes com mesmo nome/arity.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,59 +0,0 @@
# PR-05.0.5 - Synthetic Stdlib FileId via FileTable
## Briefing
`InterfaceModuleLoader` hoje aloca `FileId` sintetico por `AtomicInteger`.
Esta PR move a alocacao de arquivos sinteticos para o `FileTable`, mantendo uma unica autoridade de identidade de arquivo.
## Motivation
### Dor que esta PR resolve
1. Risco de colisao/deriva de `FileId` fora da infraestrutura oficial.
2. Arquivos sinteticos ficam fora da trilha normal de metadata de source.
3. Diagnosticos e spans de stdlib perdem consistencia de origem no pipeline.
## Target
Fazer todo `FileId` (incluindo sintetico) vir do `FileTable`.
## Scope
1. `InterfaceModuleLoader`.
2. Contexto de carga de stdlib/interface para suportar registro no `FileTable`.
3. Source handle sintetico minimo para parser/diagnostico.
## Non-Goals
1. Nao altera conteudo dos modulos stdlib.
2. Nao altera parse mode de interface.
## Method
### O que deve ser feito explicitamente
1. Criar `SourceHandle` sintetico para fontes carregadas da stdlib/interface.
2. Registrar cada handle no `FileTable` e usar `FileId` retornado.
3. Remover contador `AtomicInteger` de `InterfaceModuleLoader`.
4. Preservar caminho lógico para mensagens (ex.: origem virtual stdlib).
## Acceptance Criteria
1. `InterfaceModuleLoader` nao usa mais `new FileId(...)`.
2. Todo `FileId` de stdlib/interface existe no `FileTable`.
3. Diagnosticos em fontes sinteticas mantem atribuicao consistente.
## Tests
1. Teste de carga de interface garantindo que `FileId` sintetico foi registrado no `FileTable`.
2. Teste de span/diagnostico para arquivo sintetico.
## Affected Documents
1. `docs/pbs/specs/11. AST Specification.md`
2. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,59 +0,0 @@
# PR-05.0.6 - Host Binding Key Interning and Capability Identity
## Briefing
A validacao de host admission ainda usa chave composta em string (`module|method|version`) para deduplicacao e consistencia.
Esta PR troca chave textual por identidade internada de binding host e prepara capacidade para validacoes mais seguras.
## Motivation
### Dor que esta PR resolve
1. Concatenacao textual para chave critica de ABI e fragil.
2. Risco de bug por normalizacao inconsistente de partes da chave.
3. Menor clareza para evoluir validacao de capabilities por dominio tipado.
## Target
Internar identidade canonica de host binding em tabela dedicada e usar ID no validador de host admission.
## Scope
1. `PbsHostAdmissionValidator`.
2. Infra de tabela de binding host no core/frontend.
3. Ajustes em metadados reservados quando necessario.
## Non-Goals
1. Nao altera semantica de capability policy.
2. Nao altera contrato de host ABI no runtime.
## Method
### O que deve ser feito explicitamente
1. Introduzir valor canônico `HostBindingRef(module,name,version)` e tabela internada.
2. Substituir map com chave string por map com `HostBindingId` (ou `HostBindingRef` internado).
3. Manter normalizacao de capability separada da identidade de binding.
4. Preservar diagnosticos com referencias claras ao binding original.
## Acceptance Criteria
1. `PbsHostAdmissionValidator` nao usa mais chave formatada por string para binding.
2. Inconsistencia de capability para mesmo binding continua detectada de forma deterministica.
3. Nao ha regressao em cenarios conhecidos de host admission.
## Tests
1. Teste de deduplicacao de binding por identidade internada.
2. Teste de mismatch de capability para mesmo binding.
## Affected Documents
1. `docs/pbs/specs/6.2. Host ABI Binding and Loader Resolution Specification.md`
2. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,78 +0,0 @@
# PR-05.1 - PBS Frontend Semantic Executable Lowering (CFG)
## Briefing
O frontend PBS ainda gera `IRBackendExecutableFunction` por varredura de callsites no AST, o que perde semântica de execução real.
Esta PR substitui esse caminho por lowering semântico baseado em fluxo de controle (CFG), preservando ordem de execução, terminadores e formas de desvio.
## Motivation
### Dor atual que esta PR resolve
1. Execução divergente entre programa fonte e artefato gerado em cenários com `if`, `while`, `for`, `switch`, `handle` e `return` antecipado.
2. Impossibilidade de elevar o backend para JVM-grade porque o contrato executável nasce semanticamente incompleto.
3. Falsos positivos de conformidade: testes passam para casos lineares, mas o modelo quebra em fluxo real.
## Target
Esta PR altera o frontend PBS para que `IRBackendExecutableFunction.instructions` represente fluxo executável real, não apenas uma lista de chamadas encontradas.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.1` (NameTable compartilhada por fase).
2. `PR-05.0.2` (identidade de modulo por `ModuleId`).
3. `PR-05.0.3` (IDs tipados de callable/intrinseco no contrato).
4. `PR-05.0.4` (internacao de shape/signature).
## Scope
1. Gerador de IR executável no frontend PBS.
2. Emissão de labels e jumps para estruturas de controle.
3. Recalculo de `maxStackSlots` com base no fluxo emitido.
4. Testes de fidelidade semântica do FE para IR executável.
## Non-Goals
1. Não introduz otimizações.
2. Não altera formato binário PBX.
3. Não altera runtime.
## Method
### O que deve ser feito explicitamente
1. Substituir o mecanismo de `collectCallsFrom*` por lowering orientado a nós semânticos de statements/expressions.
2. Emitir instruções de controle (`LABEL`, `JMP`, `JMP_IF_TRUE`, `JMP_IF_FALSE`, `RET`) para cada forma de fluxo suportada.
3. Garantir que `return` termine bloco/caminho e que caminhos alcançáveis terminem em instrução terminadora.
4. Preservar spans de origem em cada instrução emitida para diagnóstico.
5. Manter validação fail-fast quando existir forma semântica não lowerável em v1.
6. Atualizar análise de stack para operar sobre o programa realmente emitido.
7. Emitir referências de chamada via IDs tipados (`CallableId`/`IntrinsicId`) sem chave textual ad-hoc.
## Acceptance Criteria
1. `IRBackendExecutableFunction` deixa de ser construído por varredura cega de callsites.
2. Para casos com ramificação e laço, a ordem de execução no IR executável é semanticamente equivalente ao AST validado.
3. Funções com `return` antecipado não emitem execução espúria após ponto de saída.
4. `maxStackSlots` calculado bate com programa emitido e passa em validação backend.
5. Diagnósticos de lowering preservam fase e span corretamente.
6. Não há lookup de identidade de callsite baseado em concatenação string no caminho principal.
## Tests
1. Testes positivos com fixtures de `if/else`, `while`, `for`, `switch`, `handle`, `return` antecipado.
2. Testes negativos para caminhos sem terminador, labels inválidos e formas não suportadas.
3. Teste de regressão comparando resultado anterior vs novo para provar correção em casos não lineares.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais. Implementação deve seguir decisões já fechadas na Agenda 18.

View File

@ -1,73 +0,0 @@
# PR-05.2 - IRBackend Callsite Classification by Semantic Identity
## Briefing
A classificação de callsites no frontend executável ainda depende de heurística textual de callee.
Esta PR torna obrigatória a classificação por identidade semântica resolvida no binding, eliminando inferência por nome/forma textual.
## Motivation
### Dor atual que esta PR resolve
1. Risco de classificar callsite no bucket errado (`CALL_FUNC`, `CALL_HOST`, `CALL_INTRINSIC`).
2. Ambiguidade em member/bind/group callee com nome coincidente.
3. Falta de robustez em evolução de sintaxe semântica do FE.
## Target
Fronteira `PBS FE -> IRBackend` com identidade de callsite estável e sem heurística textual para decisão de categoria.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.1` (NameTable compartilhada).
2. `PR-05.0.2` (ModuleId no FE).
3. `PR-05.0.3` (CallableId/IntrinsicId tipados no contrato).
4. `PR-05.0.4` (shape/signature internadas).
## Scope
1. Resultado de resolução semântica para chamadas.
2. Estrutura de lowering para carregar identidade resolvida.
3. Diagnósticos quando identidade não estiver resolvida no ponto exigido.
## Non-Goals
1. Não muda política de overload além do já definido em semântica.
2. Não introduz novas categorias de callsite.
## Method
### O que deve ser feito explicitamente
1. Propagar do analisador semântico para lowering um descritor explícito de destino de chamada.
2. O descritor deve carregar identidade canônica tipada (ao menos categoria + id alvo), sem depender de nome textual.
3. Remover dependência de `extractSimpleCalleeName` para classificação.
4. Exigir que cada callsite emitido em `IRBackend` esteja em exatamente uma categoria válida.
5. Emitir erro determinístico quando o FE não possuir identidade semântica suficiente para classificar o callsite.
6. Validar compatibilidade de metadados obrigatórios por categoria no ato de emissão.
## Acceptance Criteria
1. Classificação de callsite não depende de parsing textual de callee.
2. Cada callsite em `IRBackend` possui categoria única e metadados obrigatórios.
3. Casos ambíguos geram diagnóstico estável em fase correta, sem fallback heurístico.
4. Não há regressão em casos já válidos.
5. O payload de callsite no contrato executável é tipado por ID, não por inferência textual.
## Tests
1. Testes positivos para chamadas de função, host e intrínseco com diferentes formas sintáticas.
2. Testes negativos de ambiguidade e callee não resolvido.
3. Testes de estabilidade diagnóstica (code/phase/span).
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,70 +0,0 @@
# PR-05.3 - IRVM Deterministic Function-ID and Entrypoint Policy
## Briefing
A regra de indexação de funções e seleção de entrypoint precisa ficar estritamente alinhada ao contrato normativo para evitar divergência entre builds equivalentes.
Esta PR fecha política determinística de `func_id` e entrypoint único explícito.
## Motivation
### Dor atual que esta PR resolve
1. Possível variação de `func_id` quando ordem de merge muda.
2. Risco de entrypoint implícito ou ambíguo.
3. Dificuldade para gerar artefatos reproduzíveis e goldens estáveis.
## Target
`LowerToIRVMService` com regra única e testável de ordenação/indexação/entrypoint.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.2` (identidade de modulo por `ModuleId`).
2. `PR-05.0.3` (IDs tipados de callable).
## Scope
1. Ordenação determinística de funções.
2. Política explícita de entrypoint.
3. Diagnóstico para ausência ou ambiguidade de entrypoint.
## Non-Goals
1. Não altera ABI de chamada.
2. Não altera layout binário do bytecode.
## Method
### O que deve ser feito explicitamente
1. Definir ordenação canônica apenas pelos campos normativos aprovados.
2. Tornar explícita a ordenação de módulo a partir do `ModuleId` canônico.
3. Exigir exatamente um entrypoint válido no grafo admitido.
4. Atribuir `func_id=0` ao entrypoint e indexar demais por ordem canônica.
5. Rejeitar determinísticamente casos sem entrypoint ou com entrypoint múltiplo.
6. Cobrir cenários de permutação de entrada com mesma saída de indexação.
## Acceptance Criteria
1. Mesma entrada admitida gera mesma tabela de `func_id` em execuções repetidas.
2. Mudança na ordem de merge dos módulos não altera indexação final.
3. Ausência ou ambiguidade de entrypoint falha com diagnóstico estável.
4. A ordenação não depende de string derivada não canônica de módulo.
## Tests
1. Teste de determinismo com permutação de ordem de merge.
2. Teste de entrypoint único válido.
3. Testes negativos para zero entrypoint e múltiplos entrypoints.
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,68 +0,0 @@
# PR-05.4 - IRVM Program Coherence Without Bypass
## Briefing
Existe bypass de coerência no `IRVMProgram` em presença de `RAW_SYSCALL` e derivação com placeholders (`__unknown__`).
Esta PR remove esses atalhos do fluxo canônico e endurece o contrato de coerência `IRVM <-> EmissionPlan`.
## Motivation
### Dor atual que esta PR resolve
1. Programa pode aparentar coerente e mesmo assim carregar informação inválida para emissão.
2. Brecha para mascarar erro estrutural antes do Gate de emissão/verificação.
3. Diagnóstico tardio e pouco preciso para falhas de marshaling.
## Target
`IRVMProgram` com coerência obrigatória, sem exceção silenciosa para formas proibidas no pipeline canônico.
## Dependencies
Prerequisito direto:
1. `PR-05.0.3` (payload de IDs tipados no contrato executável).
## Scope
1. Regras de coerência no construtor e no `coherentEmissionPlan()`.
2. Eliminação de placeholder de syscall desconhecida em caminho de derivação canônico.
3. Taxonomia de erro para incoerência estrutural.
## Non-Goals
1. Não muda verificador runtime.
2. Não muda decisão de proibir `RAW_SYSCALL` em pre-load.
## Method
### O que deve ser feito explicitamente
1. Remover condição que pula validação de coerência quando detecta `RAW_SYSCALL`.
2. Tornar inválido no caminho canônico qualquer plano com operação proibida para pre-load.
3. Remover geração de `HOSTCALL` com `SyscallDecl("__unknown__",...)` em derivação automática.
4. Falhar cedo com erro determinístico e mensagem orientada a ação.
## Acceptance Criteria
1. `IRVMProgram` nunca retorna plano incoerente no fluxo canônico.
2. Não existe mais derivação com placeholders desconhecidos para hostcall.
3. Erros de coerência aparecem antes da emissão binária.
4. Coerência valida vínculos de IDs de call/intrinsic com tipo correto de domínio.
## Tests
1. Testes negativos para `RAW_SYSCALL` no plano e para hostcall sem metadado válido.
2. Testes de regressão para caminhos válidos existentes.
3. Testes de estabilidade de códigos de erro.
## Affected Documents
1. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,70 +0,0 @@
# PR-05.5 - IRVM Validator Real Stack Effects for HOSTCALL and INTRINSIC
## Briefing
O validador IRVM hoje modela `HOSTCALL` e `INTRINSIC` com efeito de stack genérico insuficiente para rigor JVM-grade.
Esta PR passa a validar efeitos reais de stack por assinatura (`arg_slots`/`ret_slots`) nessas operações.
## Motivation
### Dor atual que esta PR resolve
1. Possíveis underflow/overflow não detectados em chamadas host/intrínseco.
2. Retorno efetivo divergente sem falha no precheck.
3. Confiança excessiva na emissão sem validação semântica de pilha completa.
## Target
`IRVMValidator` e metadados de operação com informação suficiente para calcular efeito real de stack.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.3` (IDs tipados de callable/intrinseco).
2. `PR-05.0.6` (identidade canônica de host binding).
## Scope
1. Modelo de metadados para chamadas host e intrínseco no estágio IRVM.
2. Regras de validação de stack baseadas em assinatura.
3. Diagnósticos determinísticos de mismatch.
## Non-Goals
1. Não define política de otimização.
2. Não altera opcode wire format.
## Method
### O que deve ser feito explicitamente
1. Introduzir acesso a `arg_slots`/`ret_slots` efetivos durante validação de `HOSTCALL`.
2. Introduzir contrato equivalente para `INTRINSIC` (a partir de tabela canônica no pipeline).
3. Aplicar stack effect real no data-flow do validador.
4. Rejeitar mismatch de altura de retorno em joins e `RET` final.
5. Preservar mensagens de erro estáveis na taxonomia `MARSHAL_VERIFY_PRECHECK_*`.
6. Consumir metadados canônicos por ID, sem lookup textual ad-hoc.
## Acceptance Criteria
1. `HOSTCALL` e `INTRINSIC` participam do cálculo real de pilha no validador.
2. Casos de mismatch de assinatura falham no precheck com erro determinístico.
3. Casos válidos seguem aprovando sem regressão.
4. O caminho de validação não depende de composição textual de chave de binding.
## Tests
1. Testes positivos com combinações de arg/ret slots para host e intrínsecos.
2. Testes negativos para underflow, overflow e retorno incompatível.
3. Testes de join mismatch com chamadas em blocos ramificados.
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,75 +0,0 @@
# PR-05.6 - OptimizeIRVM Real Deterministic Passes
## Briefing
A etapa `OptimizeIRVM` está corretamente posicionada no pipeline, mas ainda opera como `NoOp`.
Esta PR introduz o primeiro conjunto de passes reais, seguros e determinísticos, mantendo equivalência semântica e compatibilidade de perfil.
## Motivation
### Dor atual que esta PR resolve
1. Etapa de otimização existe formalmente, mas não entrega valor técnico.
2. Difícil sustentar evolução de performance e limpeza de IRVM sem regressão.
3. Falta de contrato de execução de pass manager com evidência forte.
## Target
`OptimizeIRVMService` com pass manager produtivo e baseline de passes v1.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.3` (IDs tipados no contrato executável).
2. `PR-05.0.4` (shape/signature internadas).
## Scope
1. Pass manager determinístico com ordem estável.
2. Passes iniciais semânticamente conservadores.
3. Validação antes/depois de cada pass.
## Non-Goals
1. Não inclui otimizações agressivas interprocedurais.
2. Não inclui JIT/runtime optimization.
## Method
### O que deve ser feito explicitamente
1. Implementar baseline de passes v1:
- eliminação de bloco inalcançável,
- normalização de labels redundantes,
- simplificação de salto para próximo PC.
2. Manter invariantes obrigatórias:
- sem mudança de `vm_profile`,
- sem introdução de opcode fora do perfil,
- sem alteração de contratos de slots/retorno observáveis.
3. Validar programa antes e após cada pass.
4. Registrar nome/ordem de pass para rastreabilidade de regressão.
## Acceptance Criteria
1. `OptimizeIRVM` deixa de ser apenas `NoOp` no caminho padrão.
2. Mesma entrada produz mesma saída otimizada (determinismo).
3. Testes de equivalência semântica passam para fixtures representativas.
4. Nenhum pass viola perfil de VM ou contrato de emissão.
5. Nenhum pass degrada identidade tipada para chave textual ad-hoc.
## Tests
1. Testes unitários por pass com entradas mínimas e edge cases.
2. Testes de pipeline comparando saída otimizada vs não otimizada para equivalência.
3. Testes negativos para pass que tenta alterar perfil/semântica.
## Affected Documents
1. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
## Open Questions
Sem bloqueios arquiteturais para baseline v1.

View File

@ -1,66 +0,0 @@
# PR-05.7 - Gate I Runtime-Backed Mandatory in CI
## Briefing
O harness de compatibilidade runtime-backed pode cair para `local-fallback` quando comando não está configurado.
Esta PR separa modo dev e modo CI, tornando obrigatório runtime-backed real em CI para suportar claim forte de conformidade.
## Motivation
### Dor atual que esta PR resolve
1. Falsa sensação de conformidade quando ambiente cai para fallback local.
2. Regressões de integração com runtime real podem passar despercebidas.
3. Evidência de Gate I fica fraca para suporte externo.
## Target
Pipeline de testes com política explícita: em CI, fallback local não é aceito para Gate I.
## Dependencies
Dependencia recomendada:
1. `PR-05.8` para registrar o status do Gate I na matriz de conformidade.
## Scope
1. Política de execução do adapter runtime-backed.
2. Configuração de CI para `PROMETEU_RUNTIME_CHECK_CMD`.
3. Diagnóstico claro quando runtime-backed obrigatório não está ativo.
## Non-Goals
1. Não altera runtime.
2. Não remove adapter local para uso de desenvolvimento.
## Method
### O que deve ser feito explicitamente
1. Introduzir flag de modo estrito para Gate I em CI.
2. Em modo estrito, falhar teste se adapter entrar em `local-fallback`.
3. Publicar comando e contrato mínimo do check runtime em pipeline.
4. Preservar modo permissivo local para desenvolvimento fora de CI.
## Acceptance Criteria
1. CI falha se Gate I não executar em modo runtime-backed real.
2. Execução local mantém fallback disponível quando não for modo estrito.
3. Resultado de Gate I reporta claramente `adapterMode` e motivo.
## Tests
1. Teste de modo estrito com comando ausente deve falhar.
2. Teste de modo estrito com comando válido deve passar.
3. Regressão local em modo não estrito permanece funcional.
## Affected Documents
1. `docs/general/specs/19. Verification and Safety Checks Specification.md`
2. `docs/general/specs/13. Conformance Test Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,73 +0,0 @@
# PR-05.8 - Backend Spec-to-Test Conformance Matrix
## Briefing
Falta uma matriz única ligando cada MUST normativo de backend aos testes que provam conformidade.
Esta PR cria a matriz de rastreabilidade para `18.1`, `18.2`, `18.3`, specs `19`, `20`, `21` e Gate I/S-U.
## Motivation
### Dor atual que esta PR resolve
1. Dificuldade de provar cobertura de conformidade por requisito.
2. Buracos de teste ficam escondidos por ausência de rastreabilidade.
3. Evolução de arquitetura sem visão clara de impacto em evidência.
## Target
Artefato de conformidade auditável que mapeia requisito -> teste positivo -> teste negativo -> status.
## Dependencies
Prerequisito de conteúdo:
1. Incorporar explicitamente a trilha `PR-05.0.X` como fundação de identidade/IDs.
## Scope
1. Matriz normativa de backend FE/BE.
2. Classificação de status por requisito (`pass`, `missing`, `partial`, `deferred`).
3. Regra de atualização obrigatória da matriz em toda PR backend relevante.
4. Seção dedicada para rastrear requisitos de identidade tipada e Dense Tables.
## Non-Goals
1. Não cria nova semântica de linguagem.
2. Não substitui specs normativas.
## Method
### O que deve ser feito explicitamente
1. Criar documento de matriz em `docs/general/specs` ou `docs/pbs/specs` com tabela por requisito normativo.
2. Para cada MUST, vincular explicitamente:
- teste(s) positivo(s),
- teste(s) negativo(s),
- módulo/classe de teste,
- status atual.
3. Adicionar quality gate de revisão: PR backend sem atualização da matriz deve ser rejeitada quando impactar conformidade.
4. Definir procedimento de manutenção para não deixar entradas órfãs.
## Acceptance Criteria
1. Todo MUST de `19`, `20`, `21` e addendum executável de `13` aparece na matriz.
2. Cada item tem referência concreta a teste ou marcação explícita de ausência.
3. Revisão de PR consegue identificar rapidamente gaps de conformidade.
4. A matriz explicita dependência e cobertura dos itens `PR-05.0.1` a `PR-05.0.6`.
## Tests
1. Não exige testes executáveis novos por si só.
2. Exige checagem de integridade da matriz em revisão CI/lint documental.
## Affected Documents
1. `docs/general/specs/19. Verification and Safety Checks Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
4. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,72 +0,0 @@
# PR-06.1 - Source Attribution and Diagnostics Evidence Hardening
## Briefing
Ha cobertura parcial para preservacao de `source attribution` em rejeicoes backend e no handoff executavel.
Esta PR fecha os gaps de evidencia para requisitos de atribuicao de origem e estabilidade de diagnostico.
## Motivation
### Dor atual que esta PR resolve
1. Falta de prova forte de que erros backend preservam `file/start/end` quando acionaveis pelo usuario.
2. Parte da matriz marca `partial` para requisitos de atribuicao (`G20-11.3`, `PBS13-12.1.4`).
3. Revisao de regressao de spans depende de inspeccao manual.
## Target
Cobertura automatizada para atribuicao de origem em diagnosticos de falha backend e no contrato executavel.
## Dependencies
Prerequisitos recomendados:
1. `PR-05.5` (stack effects reais host/intrinsic).
2. `PR-05.8` (matriz de conformidade existente).
## Scope
1. Testes de atribuicao de origem para falhas deterministicas no `LowerToIRVM`.
2. Testes de atribuicao para falhas de pipeline (`BACKEND_LOWER_IRVM` e `BACKEND_EMIT_BYTECODE`) quando aplicavel.
3. Atualizacao da matriz para migrar `G20-11.3` e `PBS13-12.1.4` de `partial` para `pass` se houver cobertura completa.
## Non-Goals
1. Nao altera semantica de linguagem.
2. Nao introduz novas classes de diagnostico.
## Method
### O que deve ser feito explicitamente
1. Criar fixtures negativas onde erro e claramente source-actionable e verificar:
- `code` estavel,
- `phase` estavel,
- `file/start/end` presentes e coerentes.
2. Garantir que spans de instrucoes/callsites sejam propagadas ativamente para as mensagens de falha.
3. Atualizar a matriz com referencias exatas de teste.
## Acceptance Criteria
1. Falhas source-actionable do backend expõem atribuicao de origem valida.
2. Requisitos `G20-11.3` e `PBS13-12.1.4` saem de `partial` se cobertura completa for atingida.
3. Nenhuma regressao em testes existentes de taxonomia de erro.
## Tests
1. Novos testes unitarios/integracao para spans em diagnosticos de falha.
2. Reexecucao obrigatoria:
- `:prometeu-compiler:prometeu-build-pipeline:test`
- `:prometeu-compiler:prometeu-frontend-api:test`
## Affected Documents
1. `docs/general/specs/19. Verification and Safety Checks Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
4. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,75 +0,0 @@
# PR-06.2 - OptimizeIRVM Semantic Equivalence Harness
## Briefing
A etapa `OptimizeIRVM` ja possui passes reais, mas a prova de equivalencia semantica ainda esta parcial.
Esta PR cria harness sistematico para validar comportamento observavel com `opt on/off`.
## Motivation
### Dor atual que esta PR resolve
1. Evidencia de equivalencia semantica ainda e fixture-level limitada.
2. Itens `G21-6.2`, `G21-7.1` e `G21-9.1` permanecem `partial`.
3. Risco de pass regressivo sem deteccao ampla.
## Target
Harness de equivalencia deterministica com corpus de CFG e chamadas host/intrinsic.
## Dependencies
Prerequisitos diretos:
1. `PR-05.6` (pass manager real).
2. `PR-05.7` (Gate I estrito em CI).
## Scope
1. Framework de comparacao `optimized` vs `non-optimized`.
2. Fixtures representativas:
- sequencias lineares,
- condicional com joins,
- loops simples,
- hostcall/intrinsic.
3. Assercoes de invariantes:
- semantica observavel equivalente,
- determinismo de output,
- contratos de slots preservados.
## Non-Goals
1. Nao inclui prova formal completa.
2. Nao adiciona otimizacoes agressivas interprocedurais.
## Method
### O que deve ser feito explicitamente
1. Expor no teste caminho `optimize on/off` para o mesmo `IRVMProgram`.
2. Comparar resultado observavel em nivel de artefato e checagens Gate I/S-U.
3. Cobrir casos negativos em que pass invalido deve falhar por perfil/contrato.
4. Atualizar a matriz para converter requisitos `partial` quando cobertos.
## Acceptance Criteria
1. Existe harness reutilizavel de equivalencia `opt on/off`.
2. Cobertura de CFG e chamadas host/intrinsic com assercao de equivalencia.
3. `G21-6.2`, `G21-7.1`, `G21-9.1` evoluem para `pass` se cobertura completa.
## Tests
1. Novos testes no pacote `backend/irvm` e/ou `integration`.
2. Reexecucao obrigatoria:
- `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,69 +0,0 @@
# PR-06.3 - IRVM_EXT Contract and Elimination Fixtures
## Briefing
O contrato de `IRVM_EXT` esta parcialmente coberto apenas pelo `INTERNAL_EXT` atual.
Esta PR amplia cobertura para garantir metadados estruturais e eliminacao antes da emissao.
## Motivation
### Dor atual que esta PR resolve
1. Requisito `G20-6.2` permanece `partial`.
2. Falta evidencia para mais de um formato de extensao interna.
3. Dificuldade de evoluir extensoes com seguranca sem regressao de precheck.
## Target
Suite de fixtures para contrato de `IRVM_EXT` e precondicao de eliminacao no caminho de emissao.
## Dependencies
Prerequisitos diretos:
1. `PR-05.6` (otimizador ativo).
2. `PR-05.4` (coerencia de programa sem bypass).
## Scope
1. Fixtures com multiplas op variantes internas (ou metadados distintos equivalentes).
2. Validacao explicita de metadados estruturais (`pops/pushes/branch/terminator`).
3. Prova de rejeicao quando opcode interno residual chega ao emit.
## Non-Goals
1. Nao define novas extensoes de runtime.
2. Nao altera ISA core publicado.
## Method
### O que deve ser feito explicitamente
1. Adicionar cenarios de teste para `IRVM_EXT` alem do caso trivial existente.
2. Verificar que `OptimizeIRVM` elimina extensoes internas em caminho canônico.
3. Verificar que `EmitBytecode` falha deterministicamente quando extensao residual permanece.
4. Atualizar a matriz para `G20-6.2` conforme cobertura final.
## Acceptance Criteria
1. Contrato estrutural de `IRVM_EXT` fica provado por testes dedicados.
2. Caminho de eliminacao pre-emissao e coberto com positivo/negativo.
3. `G20-6.2` evolui para `pass` se cobertura completa.
## Tests
1. `IRVMValidatorTest` e `OptimizeIRVMServiceTest` com novos casos.
2. `EmitBytecodePipelineStageTest` para residual interno.
3. Reexecucao:
- `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,68 +0,0 @@
# PR-06.4 - Gate I Runtime-Line Repeatability in CI
## Briefing
Gate I ja suporta modo estrito runtime-backed, mas a prova de repetibilidade por runtime line ainda esta parcial.
Esta PR endurece CI para validar repetibilidade em mais de uma linha de runtime suportada.
## Motivation
### Dor atual que esta PR resolve
1. `G19-5.2.8` permanece `partial`.
2. Falta evidencia de comportamento repetivel entre linhas de runtime.
3. Claim de integracao forte fica fragil sem execucao multi-line.
## Target
Pipeline CI com Gate I estrito e validacao de repetibilidade em matrix de runtime line.
## Dependencies
Prerequisitos diretos:
1. `PR-05.7` (modo estrito runtime-backed).
2. disponibilidade de pelo menos duas linhas de runtime executaveis no CI.
## Scope
1. Configuracao CI para `PROMETEU_GATE_I_STRICT=true`.
2. Parametrizacao de `PROMETEU_RUNTIME_CHECK_CMD` por runtime line.
3. Registro de evidencia de execucao por linha (log/sumario de job).
## Non-Goals
1. Nao altera implementacao do runtime.
2. Nao define politica de suporte de longo prazo entre linhas.
## Method
### O que deve ser feito explicitamente
1. Adicionar jobs ou matrix de CI para linhas de runtime alvo.
2. Garantir falha obrigatoria quando runtime-backed nao estiver ativo.
3. Adicionar teste/documentacao que explicite `adapterMode`, `runtimeLine` e motivo.
4. Atualizar matriz de conformidade para `G19-5.2.8`.
## Acceptance Criteria
1. CI falha se Gate I cair em fallback em modo estrito.
2. CI executa Gate I em >= 2 linhas de runtime declaradas.
3. `G19-5.2.8` evolui para `pass` se repetibilidade multi-line for comprovada.
## Tests
1. Testes de adapter strict ja existentes continuam verdes.
2. Execucao obrigatoria de Gate I em matrix CI com runtime-backed real.
## Affected Documents
1. `docs/general/specs/13. Conformance Test Specification.md`
2. `docs/general/specs/19. Verification and Safety Checks Specification.md`
3. `docs/general/specs/17. Compatibility and Evolution Policy.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Definir oficialmente quais runtime lines entram na matrix minima obrigatoria.

View File

@ -1,68 +0,0 @@
# PR-06.5 - Conformance Matrix Hard-Gate Policy
## Briefing
A matriz de conformidade existe e possui lint basico, mas ainda nao bloqueia de forma forte PRs que degradam evidencia.
Esta PR transforma a matriz em hard gate processual para mudancas FE/BE com impacto de conformidade.
## Motivation
### Dor atual que esta PR resolve
1. Possibilidade de drift entre comportamento real e status da matriz.
2. Risco de PR alterar pipeline sem atualizar rastreabilidade normativa.
3. Revisao depende demais de disciplina manual.
## Target
Politica automatizada que rejeita PR backend sem atualizacao de matriz quando ha impacto de conformidade.
## Dependencies
Prerequisitos diretos:
1. `PR-05.8` (matriz + lint documental inicial).
## Scope
1. Regra de CI/revisao para detectar mudanca relevante em FE/BE backend.
2. Exigencia de atualizacao da matriz quando requisito normativo e impactado.
3. Politica clara para `partial/missing/deferred` e justificativa obrigatoria.
## Non-Goals
1. Nao substituir julgamento tecnico de revisao.
2. Nao bloquear PR puramente documental sem impacto tecnico.
## Method
### O que deve ser feito explicitamente
1. Definir regra objetiva de impacto (arquivos/pacotes gatilho).
2. Implementar verificacao automatica em CI para forcar update da matriz quando gatilho ocorrer.
3. Exigir no PR referencia explicita aos Requirement IDs alterados.
4. Atualizar docs de contribuicao/qualidade com o novo gate.
## Acceptance Criteria
1. PR com mudanca backend relevante e sem update de matriz e rejeitada.
2. PR que altera status de requisito exige justificativa e testes referenciados.
3. Processo de revisao fica reproduzivel e auditavel.
## Tests
1. Testes de lint/matriz existentes continuam passando.
2. Teste de politica (script/check) com cenarios:
- mudanca relevante sem matriz -> fail,
- mudanca relevante com matriz -> pass.
## Affected Documents
1. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
2. `docs/general/specs/13. Conformance Test Specification.md`
3. `docs/pbs/specs/2. Governance and Versioning.md`
## Open Questions
1. Definir lista final de caminhos de codigo que acionam hard gate de matriz.

View File

@ -1,76 +0,0 @@
# PR-06.6 - SPAWN/YIELD v1 or Claim Rescope
## Briefing
Os requisitos `G20-9.4.2` e `G20-9.4.3` estao `deferred` porque `SPAWN/YIELD` nao fazem parte do surface executavel v1 atual.
Esta PR fecha a pendencia por uma de duas trilhas exclusivas:
1. implementar `SPAWN/YIELD` em v1 com testes; ou
2. ajustar claim/perfil/spec para remover obrigacao deste escopo no v1 claimado.
## Motivation
### Dor atual que esta PR resolve
1. Nota JVM-grade fica penalizada por requisitos deferidos.
2. Claim de conformidade pode ficar ambiguo para auditoria externa.
3. Planejamento tecnico fica travado entre implementacao e re-scope.
## Target
Decisao implementada e test-backed para encerrar `deferred` com status claro.
## Dependencies
Prerequisitos variam por trilha:
1. Trilha A (implementar): depende de extensao do modelo `IRBackend/IRVM` para opcodes e verificacao.
2. Trilha B (re-scope): depende de alinhamento normativo com specs/decision.
## Scope
1. Trilha A:
- adicionar suporte `SPAWN/YIELD`,
- validar aridade e stack constraints,
- cobrir com testes positivos/negativos.
2. Trilha B:
- ajustar documentos para deixar explicito que nao e parte do profile v1 claimado,
- atualizar matriz e policy de claim.
## Non-Goals
1. Nao introduzir modelo completo de concorrencia/corrotina alem do minimo normativo.
2. Nao conflitar com autoridade de runtime/ISA.
## Method
### O que deve ser feito explicitamente
1. Escolher uma trilha oficial (A ou B) por decisao registrada.
2. Executar implementacao ou re-scope end-to-end (codigo + specs + matriz).
3. Garantir que `G20-9.4.2` e `G20-9.4.3` saiam de `deferred` para `pass` (A) ou status normativo explicitamente nao-aplicavel no claim v1 (B).
## Acceptance Criteria
1. Nao existe mais ambiguidade sobre `SPAWN/YIELD` no claim atual.
2. Matriz e specs refletem exatamente o comportamento implementado e claimado.
3. Gate de conformidade nao deixa regressao silenciosa nesses itens.
## Tests
1. Trilha A:
- testes de lowering/validator para `SPAWN` arg count e `YIELD` stack constraint.
2. Trilha B:
- testes de integridade documental/policy com checks de claim.
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
3. `docs/general/specs/17. Compatibility and Evolution Policy.md`
4. `docs/pbs/decisions/*` (decision de escopo, quando aplicavel)
## Open Questions
1. Qual trilha oficial deve ser adotada: implementacao v1 (A) ou re-scope de claim (B)?

View File

@ -1,73 +0,0 @@
# PR-07.1 - OptimizeIRVM Span and Source-Hook Preservation
## Briefing
A matriz de conformidade ainda marca `G21-7.5` como `partial`.
Hoje existe evidencia de spans no lowering, mas falta regressao dedicada provando que passes de `OptimizeIRVM` preservam hooks de atribuicao de origem (spans/source hooks) apos reescritas de instrucoes e remapeamento de saltos.
## Motivation
### Dor atual que esta PR resolve
1. Risco de regressao silenciosa em spans durante otimização.
2. Evidencia insuficiente para fechar `G21-7.5`.
3. Diagnosticos pos-otimizacao podem perder rastreabilidade sem prova dedicada.
## Target
Fechar `G21-7.5` com suite de regressao explicita para preservacao de source hooks/spans no caminho `LowerToIRVM -> OptimizeIRVM -> EmitBytecode`.
## Dependencies
Prerequisitos diretos:
1. `PR-06.2` (harness de equivalencia de otimizacao).
2. `PR-06.3` (passes reais de reescrita/remocao no optimizer).
## Scope
1. Testes dedicados para verificacao de span retention por pass:
- `UnreachableInstructionEliminationPass`,
- `NormalizeRedundantJumpTargetsPass`,
- `SimplifyJumpToNextPcPass`.
2. Assercoes de preservacao de `BytecodeEmitter.Operation.span` para operacoes sobreviventes.
3. Assercoes de preservacao de spans em operacoes de salto apos remapeamento de target.
4. Atualizacao da matriz para converter `G21-7.5` de `partial` para `pass`.
## Non-Goals
1. Nao introduz novo formato de source map.
2. Nao altera contrato de diagnostico fora do backend pipeline.
## Method
### O que deve ser feito explicitamente
1. Criar fixture IRVM com spans distintos por instrucao/op.
2. Executar optimize com passes reais e comparar mapeamento de spans esperado no output.
3. Incluir caso com salto reescrito para validar span do salto apos remap.
4. Incluir caso com eliminacao de instrucoes para validar que operacoes restantes mantem spans originais.
5. Atualizar matriz (`docs/general/specs/22...`) com referencias aos novos testes.
## Acceptance Criteria
1. Existe suite de teste dedicada para preservacao de spans/source hooks no optimizer.
2. Reescritas de salto preservam spans da operacao original.
3. Eliminacao de instrucoes nao corrompe spans das operacoes remanescentes.
4. `G21-7.5` evolui para `pass`.
## Tests
1. Novos testes em `backend/irvm` (ex.: `OptimizeIRVMSourceAttributionTest` ou equivalente).
2. Reexecucao obrigatoria:
- `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/general/specs/21. IRVM Optimization Pipeline Specification.md`
2. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,74 +0,0 @@
# PR-07.2 - PBS Callsite Category Without Textual Heuristics (Regression Fixtures)
## Briefing
A matriz de conformidade ainda marca `PBS13-12.2.2` como `partial`.
Ja existe enforce de metadados no contrato executavel, mas falta fixture regressiva dedicada para provar que o frontend/backend nao classifica callsite por heuristica textual quando identidades entram em colisao.
## Motivation
### Dor atual que esta PR resolve
1. Ambiguidade residual na evidencia de `CALL_FUNC/CALL_HOST/CALL_INTRINSIC`.
2. Risco de regressao para classificacao por nome textual em casos limítrofes.
3. `PBS13-12.2.2` permanece `partial` por falta de caso dedicado de identidade ambigua.
## Target
Fechar `PBS13-12.2.2` com fixtures explicitas de identidade e ambiguidade, garantindo que categoria de callsite e derivada de identidade semantica/admitida, nao de heuristica textual.
## Dependencies
Prerequisitos diretos:
1. `PR-05.2` (classificacao de callsite por identidade semantica).
2. `PR-05.0.1` e `PR-05.0.6` (name/host identity foundation).
## Scope
1. Fixture positiva:
- nome textual com "cara de host", mas identidade resolvida como callable local -> deve lower para `CALL_FUNC`.
2. Fixture positiva:
- nome textual sobreposto entre dominios, com identidade univoca admitida para host ou intrinsic -> deve lower categoria correta.
3. Fixture negativa dedicada:
- colisao real entre categorias (callable/host/intrinsic) para o mesmo callsite -> rejeicao deterministica por ambiguidade.
4. Atualizacao de matriz para converter `PBS13-12.2.2` de `partial` para `pass`.
## Non-Goals
1. Nao altera gramatica PBS.
2. Nao redefine regras de admission de host/intrinsics fora do escopo desta prova.
## Method
### O que deve ser feito explicitamente
1. Adicionar testes em `PbsFrontendCompilerTest` (ou suite semantica correlata) para os tres cenarios acima.
2. Assertar `InstructionKind` resultante (`CALL_FUNC`, `CALL_HOST`, `CALL_INTRINSIC`) em casos positivos.
3. Assertar codigo diagnostico deterministico em caso ambiguo.
4. Garantir que nao ha branch de fallback por string pattern no caminho de lowering executavel.
5. Atualizar matriz de conformidade com referencias dos novos testes.
## Acceptance Criteria
1. Existe fixture dedicada cobrindo ambiguidade de categoria por identidade.
2. Casos positivos provam classificacao correta mesmo quando nome textual engana.
3. Caso ambiguo falha deterministicamente com diagnostico estavel.
4. `PBS13-12.2.2` evolui para `pass`.
## Tests
1. Novos testes no frontend PBS:
- `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
2. Reexecucao obrigatoria de integracao backend:
- `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
Sem bloqueios arquiteturais.

View File

@ -1,77 +0,0 @@
# PR-07.3 - IRVM Entrypoint Export Emission for Runtime Loader Compatibility
## Briefing
Hoje um cartridge pode compilar com `entrypoint: "frame"` no `manifest.json` e `pub fn frame()` no `mod.barrel`, mas ainda falhar em runtime com `EntrypointNotFound`.
A causa observada e que o `program.pbx` pode ser emitido sem secao `exports` (section kind `4`), enquanto o loader resolve entrypoint nominal usando `program.exports`.
## Motivation
### Dor atual que esta PR resolve
1. Build aparentemente valido, mas falha de bootstrap em runtime.
2. Divergencia entre contrato de manifesto (`entrypoint` nominal) e artefato PBX emitido.
3. Falta de evidencia automatizada para evitar regressao de exports no caminho `IRBackend -> IRVM -> Bytecode`.
## Target
Corrigir o pipeline backend para sempre emitir export nominal do entrypoint no PBX de preload, garantindo compatibilidade com o loader quando o `manifest.json` declara entrypoint por nome.
## Dependencies
Prerequisitos diretos:
1. `PR-05.3` (politica deterministica de entrypoint no indice `0`).
2. `PR-05.4` (coerencia unica entre IRVM e EmissionPlan).
## Scope
1. `LowerToIRVMService` deve preencher `EmissionPlan.exports` com o simbolo do entrypoint apontando para `func_idx = 0`.
2. Adicionar regressao dedicada para garantir que `coherentEmissionPlan()` preserva export do entrypoint.
3. Validar serializacao PBX com secao `exports` presente quando houver entrypoint nominal.
4. Cobrir cenario de integracao onde `manifest.entrypoint = "frame"` inicializa VM sem `EntrypointNotFound`.
## Non-Goals
1. Nao exportar toda a superficie de funcoes executaveis neste passo.
2. Nao alterar formato binario PBX alem da presenca correta da secao `exports`.
3. Nao mudar semantica de resolucao por indice numerico de entrypoint.
## Method
### O que deve ser feito explicitamente
1. No `LowerToIRVMService`, construir `BytecodeEmitter.EmissionPlan` com `exports` contendo, no minimo, `Export(entryPointCallableName, 0)`.
2. Garantir determinismo do export do entrypoint a partir da mesma politica que fixa `func_id = 0`.
3. Adicionar teste unitario em `LowerToIRVMServiceTest` para verificar export nominal do entrypoint no plano coerente.
4. Adicionar teste de emissao/link para verificar secao `exports` no modulo serializado.
5. Adicionar teste de integracao runtime-backed para falhar se regressar para `EntrypointNotFound` em cartridge com entrypoint nominal valido.
## Acceptance Criteria
1. Build de projeto PBS com entrypoint `frame` gera PBX com secao `exports`.
2. O simbolo `frame` aponta para `func_idx = 0` no artefato emitido.
3. Execucao de cartridge com `manifest.entrypoint = "frame"` nao falha por `EntrypointNotFound` quando o programa contem o entrypoint admitido.
4. Rebuilds equivalentes produzem mapping de export deterministico.
## Tests
1. Novos testes de backend:
- `:prometeu-compiler:prometeu-build-pipeline:test`
2. Reexecucao de compatibilidade runtime-backed:
- `:prometeu-compiler:prometeu-build-pipeline:test --tests *Runtime*`
3. Smoke local recomendado:
- `./runtime/prometeu build .`
- `./runtime/prometeu run cartridge`
## Affected Documents
1. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/pbs/specs/7. Cartridge Manifest and Runtime Capabilities Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Em evolucao futura, devemos exportar apenas o entrypoint ou tambem funcoes explicitamente marcadas para linking externo?

View File

@ -1,80 +0,0 @@
# PR-08.1 - Intrinsic Resolution by Canonical Identity (Owner+Name+Version)
## Briefing
Hoje a resolucao de intrinsic no frontend PBS ainda depende de chave por `sourceMethodName` simples.
Isso permite ambiguidade quando existem metodos com o mesmo nome em owners diferentes e enfraquece o contrato de canonical addressing.
## Motivation
### Dor atual que esta PR resolve
1. Ambiguidade potencial de resolucao de intrinsic por nome de metodo sem owner.
2. Dependencia implícita de heuristica textual ao inves de identidade canonica.
3. Risco de regressao quando ampliar superficie de builtins/intrinsics stateful.
## Target
Tornar a resolucao de `CALL_INTRINSIC` no frontend semanticamente canonica e nao ambigua, usando chave composta deterministica:
1. `owner canonical`,
2. `intrinsic name canonical`,
3. `canonical version`.
## Dependencies
Prerequisitos diretos:
1. `PR-05.2` (classificacao de callsite sem heuristica textual).
2. `PR-07.2` (regressao contra heuristica textual de categoria).
## Scope
1. Substituir o map por `sourceMethodName` no lowering executavel por indice por identidade canonica.
2. Ajustar `PbsReservedMetadataExtractor`/surface helper para expor owner canonical explicitamente na chave de resolucao.
3. Tornar erro de ambiguidade explicito quando mais de uma intrinsic disputar o mesmo callsite apos resolver receiver/owner.
4. Cobrir cenarios com nomes repetidos em owners diferentes.
## Non-Goals
1. Nao alterar ids finais de intrinsics no bytecode/runtime nesta PR.
2. Nao introduzir novo opcode.
3. Nao expandir parser/sintaxe de `IntrinsicCall`.
## Method
### O que deve ser feito explicitamente
1. Introduzir chave tipada para intrinsic de lowering (ex.: `IntrinsicResolutionKey(ownerCanonical, nameCanonical, version)`).
2. Popular lookup de intrinsics com essa chave em vez de `sourceMethodName`.
3. Resolver owner canonical a partir do receiver sem fallback textual opaco.
4. Rejeitar deterministicamente callsite intrinsic sem mapeamento canonico univoco.
5. Adicionar testes positivos/negativos para:
- owners distintos com mesmo metodo,
- override de versao,
- callsite sem receiver compativel.
## Acceptance Criteria
1. Nenhum callsite intrinsic e resolvido apenas por `sourceMethodName`.
2. Colisao de metodo entre owners diferentes nao gera escolha implicita.
3. Diagnosticos de ambiguidade/nao resolucao sao estaveis e testados.
4. Build equivalente gera mesma classificacao e mesmo `intrinsicPool`.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMServiceTest*`
3. Regressao dedicada para callsites `input.pad.*` vs outros owners com nome coincidente.
## Affected Documents
1. `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
2. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
3. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. O contrato final deve expor owner canonico como campo separado em `IntrinsicSurface`, ou apenas como nome canonico fully-qualified?

View File

@ -1,79 +0,0 @@
# PR-08.2 - IRBackend Module Identity via Dense Table (ModuleId + ModulePool)
## Briefing
`moduleKey` hoje e string no contrato executavel e vira identificador estrutural em multiplos pontos.
Isso funciona, mas ainda nao aproveita plenamente a infraestrutura de dense tables ja existente (`ModuleTable`/`ModuleId`) para identidade canonica de modulo no handoff FE->BE.
## Motivation
### Dor atual que esta PR resolve
1. Identidade de modulo dependente de serializacao textual (`project:path`) no contrato.
2. Maior risco de drift/normalizacao inconsistente entre fronteiras.
3. Custo de comparacao/armazenamento pior do que id tipado em larga escala.
## Target
Evoluir o contrato `IRBackend` para carregar identidade de modulo tipada por dense table:
1. `ModuleId` nas entidades executaveis,
2. `modulePool` canonico no payload,
3. `moduleKey` textual mantido apenas como campo auxiliar/debug no periodo de transicao.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.2` (infra de `ModuleId` e `ModuleTable`).
2. `PR-05.0.3` (migração previa de ids tipados no contrato executavel).
## Scope
1. Introduzir `modulePool` no `IRBackend` e remapeamento na agregacao multi-arquivo.
2. Trocar referencias estruturais de modulo para `ModuleId` em executable/callable surfaces.
3. Adaptar sorting/canonical ordering para usar `ModuleId` + leitura canonica da tabela.
4. Preservar backward compatibility local durante migracao (camada de adaptacao).
## Non-Goals
1. Nao redefinir formato PBX nesta PR.
2. Nao alterar semantica de modulo no parser/linker.
3. Nao remover imediatamente todos os campos textuais de debug.
## Method
### O que deve ser feito explicitamente
1. Adicionar `modulePool: ReadOnlyList<ModuleReference>` em `IRBackend`.
2. Adicionar `moduleId` em `IRBackendExecutableFunction` e `CallableSignatureRef` (ou equivalente de assinatura).
3. Atualizar `IRBackendAggregator` para reindexar modulos via `ModuleTable` (dense table).
4. Atualizar FE PBS para emitir `moduleId` usando tabela canonica de modulos.
5. Atualizar BE (`LowerToIRVMService`) para ordenar por identidade de modulo canonica sem dependencia de concat textual.
6. Incluir testes de determinismo para remapeamento multi-modulo com ids estaveis.
## Acceptance Criteria
1. `IRBackend` possui pool canonico de modulos com ids densos.
2. Caminho estrutural nao depende de `moduleKey` string para identidade.
3. Merges de `IRBackendFile` preservam reindexacao deterministica de modulo.
4. Funcoes equivalentes em builds equivalentes recebem ids de modulo identicos.
## Tests
1. `:prometeu-compiler:prometeu-frontend-api:test`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
3. `:prometeu-compiler:prometeu-build-pipeline:test`
4. Novos testes de agregacao multi-modulo com colisao textual potencial.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Fase de transicao deve manter `moduleKey` como shadow field por quantas ondas?

View File

@ -1,80 +0,0 @@
# PR-08.3 - Qualified Entrypoint Identity (No Name-Only Resolution)
## Briefing
A selecao de entrypoint no backend ainda filtra apenas por `callableName`.
Em projetos multi-modulo isso amplia risco de ambiguidade e cria acoplamento desnecessario a nomes globais.
## Motivation
### Dor atual que esta PR resolve
1. Ambiguidade de entrypoint quando existem callables homonimos.
2. Diagnostico tardio por nome sem contexto de modulo.
3. Divergencia potencial entre contrato de frontend e selecao real no backend.
## Target
Evoluir o contrato para entrypoint qualificado e deterministico:
1. `entryPointCallableName` + `entryPointModuleId` (ou `entryPointCallableId`),
2. resolucao backend por identidade qualificada,
3. politicas de erro claras para mismatch/ausencia.
## Dependencies
Prerequisitos diretos:
1. `PR-08.2` (ModuleId no contrato IRBackend).
2. `PR-05.3` (politica deterministica de indexacao e `func_id=0`).
## Scope
1. Expandir `FrontendSpec` e handoff FE para declarar entrypoint qualificado.
2. Atualizar `IRBackend` para carregar declaracao qualificada de entrypoint.
3. Atualizar `LowerToIRVMService` para selecionar entrypoint por identidade qualificada.
4. Preservar fallback de compatibilidade durante migracao (com warning deterministico).
## Non-Goals
1. Nao alterar semantica de `func_id=0`.
2. Nao mudar contrato de manifesto de cartridge nesta PR.
3. Nao introduzir multiple entrypoints por linguagem.
## Method
### O que deve ser feito explicitamente
1. Introduzir estrutura de entrada qualificada (ex.: `EntrypointRef(moduleId, callableName)`).
2. Popular estrutura no frontend PBS a partir do modulo de `frame`.
3. Modificar `orderFunctions` para usar referencia qualificada.
4. Em caso de fallback por nome, emitir diagnostico de deprecacao controlado.
5. Adicionar testes para:
- homonimos em modulos distintos,
- entrypoint valido qualificado,
- entrypoint ausente com erro estavel.
## Acceptance Criteria
1. Selecao de entrypoint nao depende apenas de nome.
2. Homonimos em modulos distintos nao geram ambiguidade quando entrypoint qualificado existe.
3. `func_id=0` continua pertencendo ao entrypoint declarado.
4. Rebuilds equivalentes mantem func ordering deterministico.
## Tests
1. `:prometeu-compiler:prometeu-frontend-api:test`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMServiceTest*`
3. Testes de integracao com dois modulos contendo `frame`.
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Melhor contrato final: `EntrypointRef(moduleId, callableName)` ou `CallableId` global direto?

View File

@ -1,72 +0,0 @@
# PR-08.4 - CALL_FUNC Callee Module Identity Correctness
## Briefing
No lowering executavel PBS, instrucoes `CALL_FUNC` podem carregar `calleeModuleKey` do contexto local, e nao necessariamente do callable alvo.
Isso compromete rastreabilidade, debug e futuras validacoes de linking por modulo.
## Motivation
### Dor atual que esta PR resolve
1. Metadado de callsite incorreto para chamadas inter-modulo.
2. Dificulta diagnostico e verificacao de integridade no backend.
3. Introduz risco de regressao quando modulo vira identidade tipada no contrato.
## Target
Garantir que todo `CALL_FUNC` preserva identidade real do alvo (`callee module`) de forma deterministica, sem usar contexto local como proxy.
## Dependencies
Prerequisitos diretos:
1. `PR-05.0.4` (assinatura/callable internados).
2. `PR-08.2` (quando `ModuleId` tipado estiver ativo, usar id do alvo).
## Scope
1. Corrigir montagem de callsite para puxar modulo do `calleeCallableId` resolvido.
2. Ajustar modelos auxiliares de resolucao de callable para incluir modulo do alvo.
3. Expandir testes de lowering com chamadas cross-module.
## Non-Goals
1. Nao alterar categoria de callsite.
2. Nao introduzir linking dinamico de funcoes.
3. Nao alterar bytecode emitido para opcodes de chamada.
## Method
### O que deve ser feito explicitamente
1. Enriquecer lookup de callable para retornar identidade completa (`callableId + module identity`).
2. Em `CALL_FUNC`, preencher `callee module` com identidade do alvo real.
3. Adicionar validacao de consistencia em contrato executavel para evitar modulo invalido em chamada.
4. Criar regressao com:
- modulo A chamando funcao em modulo B,
- assert do modulo do callee no IRBackend.
## Acceptance Criteria
1. Nenhuma instrução `CALL_FUNC` usa modulo local quando alvo e externo.
2. Testes cross-module passam com metadado correto de callee.
3. Diagnosticos mantem atribuicao correta em falhas de resolucao.
4. Contrato segue deterministico em rebuilds equivalentes.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsFrontendCompilerTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PBSFrontendPhaseServiceTest*`
3. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMPipelineStageTest*`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Durante a transicao, manter `calleeCallableName` textual para debug ou derivar sempre da assinatura por id?

View File

@ -1,74 +0,0 @@
# PR-08.5 - Intrinsic Registry Single Source of Truth (Compiler <-> Runtime)
## Briefing
O compiler backend hoje possui `IRVMIntrinsicRegistry` hardcoded e o runtime possui registry propio em `builtins.rs`.
Mesmo estando alinhados agora, a manutencao manual em dois lugares cria risco alto de drift.
## Motivation
### Dor atual que esta PR resolve
1. Duplicacao de source-of-truth para ids finais de intrinsic.
2. Risco de regressao silenciosa quando runtime evoluir surface intrinsic.
3. Custo operacional para garantir paridade manual em cada mudanca.
## Target
Estabelecer uma fonte unica versionada para mapeamento canonico de intrinsics (`canonicalName@version -> finalId`) e consumir isso em compiler + runtime com teste de paridade automatizado.
## Dependencies
Prerequisitos diretos:
1. `PR-08.1` (resolucao canonica consistente no frontend).
2. `PR-05.7` (caminho de verificacao runtime-backed robusto).
## Scope
1. Definir artefato de registry canonico (ex.: JSON/TOML) sob controle de versionamento.
2. Gerar/consumir mapeamento no compiler (`IRVMIntrinsicRegistry`) a partir desse artefato.
3. Adicionar checagem de paridade em teste para impedir divergencia com runtime.
4. Documentar fluxo de evolucao de intrinsic id sem quebra de compatibilidade.
## Non-Goals
1. Nao reescrever todas as implementacoes de intrinsic do runtime nesta PR.
2. Nao alterar semantica de execucao de `INTRINSIC`.
3. Nao migrar para discovery dinamico em tempo de execucao.
## Method
### O que deve ser feito explicitamente
1. Introduzir arquivo canonico de registry em local acordado (`docs` ou `shared metadata`).
2. Criar utilitario de leitura/geracao para preencher `IRVMIntrinsicRegistry` no compiler.
3. Adicionar teste no compiler que compara mapeamento esperado com runtime (snapshot/paridade).
4. Adicionar regra de CI para falhar em desvio de paridade.
5. Atualizar docs de contribuicao para fluxo de adicao/upgrade de intrinsics.
## Acceptance Criteria
1. Existe uma unica fonte versionada de mapeamento de intrinsic ids finais.
2. Compiler nao depende de lista manual duplicada para esse mapeamento.
3. CI falha quando runtime e compiler divergem em identidade/ID de intrinsic.
4. Inclusao de nova intrinsic segue workflow documentado e testavel.
## Tests
1. `:prometeu-compiler:prometeu-build-pipeline:test --tests *Intrinsic*`
2. Teste de paridade compiler-runtime dedicado.
3. Smoke runtime-backed com intrinsic valido e id invalido.
## Affected Documents
1. `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
4. `../runtime/docs/runtime/specs/06-input-peripheral.md`
5. `../runtime/docs/runtime/specs/02-vm-instruction-set.md`
## Open Questions
1. Melhor local da fonte unica: repo `runtime`, repo `studio`, ou pacote compartilhado dedicado?

View File

@ -1,81 +0,0 @@
# PR-09.1 - IRBackend Contract Cut: Remove `moduleKey` and `calleeModuleKey` (String)
## Briefing
O contrato executavel ainda carrega `moduleKey` textual como trilha de compatibilidade.
Isso mantem dupla identidade (`ModuleId` + string) em area critica de handoff.
## Motivation
### Dor atual que esta PR resolve
1. Identidade estrutural ainda pode cair em fallback textual.
2. Contrato permite dados redundantes e potencialmente divergentes.
3. A transicao para dense-only ainda nao esta fechada.
## Target
Encerrar a transicao no contrato FE->BE:
1. remover `moduleKey` de `IRBackendExecutableFunction`,
2. remover `calleeModuleKey` de instrucoes executaveis,
3. remover `moduleKey` de `CallableSignatureRef`,
4. eliminar parsing/fallback textual em `IRBackendAggregator`.
## Dependencies
Prerequisitos diretos:
1. `PR-08.2`
2. `PR-08.3`
3. `PR-08.4`
## Scope
1. Atualizar modelos em `prometeu-frontend-api` e `prometeu-compiler-core`.
2. Remover construtores de compatibilidade que aceitam `moduleKey` string.
3. Atualizar agregacao para reindexar apenas por `ModuleId` + `modulePool`.
4. Atualizar todos os testes afetados.
## Non-Goals
1. Nao alterar formato PBX nesta PR.
2. Nao mudar semantica de host/intrinsic callsites.
## Method
### O que deve ser feito explicitamente
1. Em `IRBackendExecutableFunction`:
- remover campo `moduleKey`,
- remover `calleeModuleKey`,
- manter apenas `ModuleId` estrutural.
2. Em `CallableSignatureRef`:
- remover `moduleKey`,
- manter `moduleId` + assinatura.
3. Em `IRBackend` agregador:
- remover `moduleReferenceFromKey(...)` e qualquer fallback textual.
4. Em testes:
- converter fixtures para `ModuleId` + `modulePool`.
## Acceptance Criteria
1. Nao existe mais `moduleKey` string em contratos estruturais FE/BE.
2. Reindexacao multi-file usa somente dense tables.
3. Build/test passam sem camadas de compatibilidade textual.
## Tests
1. `:prometeu-compiler:prometeu-compiler-core:test`
2. `:prometeu-compiler:prometeu-frontend-api:test`
3. `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Nenhuma. Esta PR fecha corte de transicao.

View File

@ -1,68 +0,0 @@
# PR-09.2 - PBS Frontend Lowering: ModuleId-Only (No `moduleKey` in lowering surfaces)
## Briefing
Mesmo apos o contrato aceitar `ModuleId`, o lowering PBS ainda trafega `moduleKey` em estruturas internas (`ImportedCallableSurface`, indices auxiliares e fixtures).
## Motivation
### Dor atual que esta PR resolve
1. FE ainda acopla resolucao de callable/import a string de modulo.
2. A remocao de `moduleKey` no contrato quebra se FE nao migrar totalmente.
3. Risco de divergencia entre metadado textual e identidade internada.
## Target
Migrar lowering PBS para `ModuleId` como identidade unica:
1. `ImportedCallableSurface` sem `moduleKey`,
2. callsite/callable lookup por ids internados,
3. diagnosticos e logs usando renderizacao derivada de `modulePool` apenas quando necessario.
## Dependencies
Prerequisito direto:
1. `PR-09.1`
## Scope
1. Atualizar `PbsFrontendCompiler` para operar com `ModuleId` nas superfices de import/callable.
2. Atualizar `PBSFrontendPhaseService` para fornecer metadados densos sem string estrutural.
3. Atualizar testes PBS e artifacts golden.
## Non-Goals
1. Nao alterar parser PBS.
2. Nao alterar admission de host capabilities.
## Method
### O que deve ser feito explicitamente
1. Remover `moduleKey` de `ImportedCallableSurface`.
2. Em `collect/lower callsites`, propagar `calleeModuleId` via assinatura internada.
3. Ajustar renderizacao de debug para usar `modulePool` quando mostrar modulo.
4. Atualizar golden printer para mostrar `moduleId` (e opcionalmente nome renderizado derivado).
## Acceptance Criteria
1. FE PBS nao depende de `moduleKey` string para resolver/importar/lower callables.
2. Todas as callsites `CALL_FUNC` carregam `calleeModuleId` coerente.
3. Testes PBS passam sem acessos estruturais a chave textual.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
2. `:prometeu-compiler:prometeu-frontend-api:test --tests *IRBackendExecutableContractTest*`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/14. Name Resolution and Module Linking Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Nenhuma. Regra fica `ModuleId`-only para identidade estrutural.

View File

@ -1,72 +0,0 @@
# PR-09.3 - LowerToIRVM: ModuleId-Only Ordering + Strict Qualified Entrypoint
## Briefing
`LowerToIRVMService` ainda possui fallback para `moduleKey` textual e fallback de entrypoint por nome quando `entryPointModuleId` nao e informado.
## Motivation
### Dor atual que esta PR resolve
1. Ordenacao de funcoes ainda pode depender de string legado.
2. Entrypoint pode cair em selecao name-only, mantendo ambiguidade residual.
3. Contrato qualificado existe, mas nao e estrito.
## Target
Tornar lowering estritamente orientado por identidade:
1. ordenacao por `ModuleId -> modulePool` somente,
2. entrypoint obrigatoriamente qualificado (`entryPointModuleId + callableName`),
3. remover fallback textual/heuristico.
## Dependencies
Prerequisitos diretos:
1. `PR-09.1`
2. `PR-09.2`
## Scope
1. Atualizar `LowerToIRVMService` para eliminar `fallbackModuleKey`.
2. Validar presenca obrigatoria de `entryPointModuleId` para entrada executavel.
3. Atualizar testes de ordenacao, ambiguidades e erros deterministas.
## Non-Goals
1. Nao alterar regra `func_id=0` (continua entrypoint).
2. Nao alterar emissao de opcodes.
## Method
### O que deve ser feito explicitamente
1. Substituir `moduleSortKey(...)` textual por leitura canonica direta do `modulePool` indexado por `ModuleId`.
2. Em `orderFunctions`, rejeitar entrada sem `entryPointModuleId`.
3. Remover caminho de erro/controle baseado em entrypoint name-only.
4. Cobrir com testes:
- entrypoint qualificado valido,
- entrypoint qualificado ausente,
- homonimos em modulos distintos com qualificacao.
## Acceptance Criteria
1. Nenhum fallback para `moduleKey` no LowerToIRVM.
2. Entrypoint e sempre resolvido por identidade qualificada.
3. Determinismo preservado em rebuild equivalente.
## Tests
1. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMServiceTest*`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *BackendSafetyGateSUTest*`
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
3. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Nenhuma. Esta PR fecha o fallback de entrypoint name-only.

View File

@ -1,84 +0,0 @@
# PR-09.4 - Specs Refresh: ModuleId-Only + EntrypointRef Normative Alignment
## Briefing
Com a remocao estrutural de `moduleKey`, as specs normativas precisam refletir:
1. identidade de modulo densa (`ModuleId`),
2. entrypoint qualificado (`EntrypointRef`),
3. ausencia de fallback textual.
## Motivation
### Dor atual que esta PR resolve
1. Specs ainda descrevem partes name-only/text-based em pontos criticos.
2. Matriz pode afirmar `pass` sem refletir contratos mais estritos.
3. Risco de regressao por lacuna documento->implementacao.
## Target
Atualizar o baseline normativo para o modelo final:
1. `IRBackend` estrutural sem `moduleKey`,
2. `EntrypointRef(moduleId, callableName)` obrigatorio em handoff executavel,
3. ordenacao/lowering sem dependencias textuais.
## Dependencies
Prerequisitos diretos:
1. `PR-09.1`
2. `PR-09.2`
3. `PR-09.3`
## Scope
1. Revisar e atualizar specs:
- PBS 13 (Lowering IRBackend),
- General 20 (IRBackend -> IRVM),
- General 15 (Bytecode mapping entrypoint linkage),
- General 22 (matriz de conformidade).
2. Registrar decisao de corte definitivo (`moduleKey` removido).
## Non-Goals
1. Nao alterar implementação de runtime nesta PR.
2. Nao introduzir novo formato de arquivo para `program.pbx`.
## Method
### O que deve ser feito explicitamente
1. Em PBS13 e G20:
- trocar obrigacoes name-only por `EntrypointRef` qualificado,
- declarar `ModuleId` como identidade estrutural unica.
2. Em G15:
- manter `func_id=0` como entrypoint selecionado por `EntrypointRef`.
3. Em G22:
- adicionar/ajustar requirement rows para:
- no-moduleKey structural identity,
- strict qualified entrypoint,
- moduleid-only ordering.
## Acceptance Criteria
1. Nenhuma spec normativa relevante menciona `moduleKey` como identidade estrutural.
2. Matriz de conformidade cobre explicitamente obrigações novas.
3. `BackendConformanceMatrixSpecTest` e gate hard-policy permanecem verdes.
## Tests
1. `:prometeu-compiler:prometeu-build-pipeline:test --tests *BackendConformanceMatrixSpecTest*`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *BackendClaimScopeSpecTest*`
## Affected Documents
1. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
2. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
3. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
## Open Questions
1. Nenhuma. Esta PR e de alinhamento normativo.

View File

@ -1,76 +0,0 @@
# PR-09.5 - Hard Gates: No-`moduleKey` Regression + Migration Cleanup
## Briefing
Depois do corte `ModuleId`-only, precisamos impedir reintroducao acidental de `moduleKey` estrutural e limpar residuos de migracao.
## Motivation
### Dor atual que esta PR resolve
1. Sem gate dedicado, regressao textual pode voltar por conveniencia.
2. Testes/golden antigos ainda podem carregar nomenclatura de transicao.
3. Confianca de manutencao cai sem verificacao automatica de proibicao.
## Target
Fechar o ciclo de migracao:
1. adicionar gate anti-regressao (`moduleKey` proibido em contratos estruturais),
2. atualizar fixtures/golden para contrato final,
3. consolidar notas de migracao e contribuicao.
## Dependencies
Prerequisitos diretos:
1. `PR-09.1`
2. `PR-09.2`
3. `PR-09.3`
4. `PR-09.4`
## Scope
1. Criar teste/lint de proibicao para `moduleKey` em pacotes de contrato/lowering.
2. Atualizar `golden` de frontend/backend para `ModuleId`-only.
3. Atualizar docs de contribuicao para adicao de callables/modulos sem chave textual.
## Non-Goals
1. Nao alterar semantica de parser/lexer PBS.
2. Nao introduzir novo gate externo ao gradle test.
## Method
### O que deve ser feito explicitamente
1. Adicionar teste de policy:
- falha se campos/assinaturas estruturais de FE/BE usarem `moduleKey`.
2. Atualizar snapshots golden e testes que assumiam debug key textual.
3. Registrar checklist de migracao final:
- FE lowering,
- IRBackend contract,
- LowerToIRVM,
- docs/matriz.
## Acceptance Criteria
1. Nao existe `moduleKey` em contratos estruturais FE/BE.
2. Gate automatizado falha ao tentar reintroduzir o campo.
3. Testes/golden passam no modo novo sem artefatos legados.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
2. `:prometeu-compiler:prometeu-frontend-api:test`
3. `:prometeu-compiler:prometeu-build-pipeline:test`
## Affected Documents
1. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
2. `docs/pbs/pull-requests/INDEX.md`
3. `docs/pbs/specs/13. Lowering IRBackend Specification.md`
## Open Questions
1. Nenhuma. PR de fechamento e anti-regressao.

View File

@ -1,84 +0,0 @@
# PR-09.6 - ISA-Scoped Intrinsic Registry as Single Source of Truth
## Briefing
Hoje o mapeamento `canonicalName@version -> finalId` ainda e mantido em dois lugares (compiler e runtime), com teste de paridade.
Isso reduz risco, mas ainda nao elimina dual-authoring.
## Motivation
### Dor atual que esta PR resolve
1. Fonte duplicada para IDs finais de intrinsic.
2. Risco operacional de drift entre compiler e runtime.
3. Evolucao de intrinsics depende de sincronizacao manual.
## Target
Definir um artefato unico, versionado e vinculado ao profile ISA para o registry de intrinsics:
1. artefato canonico de registry (`intrinsic-registry-v1`),
2. ownership normativo no boundary ISA/profile,
3. consumo por compiler e runtime a partir da mesma fonte.
## Dependencies
Prerequisitos diretos:
1. `PR-08.5` (paridade compiler-runtime existente)
2. `PR-09.7` (normalizacao de consumo no compiler)
## Scope
1. Definir formato normativo do artefato (CSV/TOML/JSON) no boundary ISA.
2. Definir local canonico e versionamento do artefato.
3. Definir contrato de evolucao:
- adicao de intrinsic,
- deprecacao,
- compatibilidade de IDs.
4. Definir gate de paridade contra consumidores.
## Non-Goals
1. Nao alterar semantica de opcode `INTRINSIC`.
2. Nao redesenhar toda a arquitetura de builtins do runtime nesta PR.
## Method
### O que deve ser feito explicitamente
1. Criar documento de formato canonico do registry:
- chave canonica,
- versao canonica,
- final id,
- constraints de unicidade.
2. Declarar ownership do artefato no profile ISA.
3. Definir pipeline de validacao:
- parser estrito,
- check de unicidade de identity e final id,
- check de ordenacao deterministica.
4. Definir workflow de manutencao para adicao de intrinsic.
## Acceptance Criteria
1. Existe uma unica fonte versionada para IDs finais de intrinsic.
2. Runtime e compiler referenciam formalmente essa fonte.
3. Processo de evolucao de intrinsics fica deterministico e auditavel.
## Tests
1. Testes de parser/validacao do artefato canonico.
2. Testes de paridade de consumidores contra o artefato.
3. Gate de CI que falha em divergia do mapping.
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/15. Bytecode and PBX Mapping Specification.md`
3. `docs/pbs/specs/6.1. Intrinsics and Builtin Types Specification.md`
4. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
5. Runtime specs correspondentes (ajuste posterior no repo runtime).
## Open Questions
1. Local canonico final do artefato: `runtime` (recomendado) ou `shared-metadata` dedicado. runtime

View File

@ -1,76 +0,0 @@
# PR-09.7 - Compiler Normalization to ISA Intrinsic Registry Artifact
## Briefing
Apos estabelecer o artefato unico do registry (PR-09.6), o compiler precisa consumir exclusivamente esse artefato e remover caminhos residuais de dual-authoring.
## Motivation
### Dor atual que esta PR resolve
1. Compiler ainda pode depender de representacao local paralela.
2. Teste de paridade atual com parse de `builtins.rs` e acoplamento fragil de formato.
3. Falta um caminho de consumo unico no pipeline backend.
## Target
Normalizar o lado compiler para source-of-truth unico:
1. `IRVMIntrinsicRegistry` carregando apenas o artefato canonico ISA,
2. remover/encapsular validacoes que dependem de parsing textual de runtime internals,
3. reforcar gate de consistencia do consumidor compiler.
## Dependencies
Prerequisito direto:
1. `PR-09.6`
## Scope
1. Ajustar `IRVMIntrinsicRegistry` para modo canonical-only.
2. Revisar testes de paridade:
- principal: paridade com artefato canonico,
- opcional/informativo: runtime-backed check separado.
3. Garantir mensagens de erro e diagnostico estaveis para registry invalido.
## Non-Goals
1. Nao alterar implementacao de intrinsics no runtime.
2. Nao mover ownership de docs runtime nesta PR.
## Method
### O que deve ser feito explicitamente
1. Consolidar parser/loader do registry no compiler com contrato estrito.
2. Substituir assercoes hardcoded por fixtures derivadas do artefato.
3. Separar teste de compatibilidade runtime:
- nao bloquear desenvolvimento local quando runtime repo ausente,
- bloquear em modo strict/CI quando configurado.
4. Atualizar docs de contribuicao do compiler para fluxo de update de intrinsics.
## Acceptance Criteria
1. Compiler nao tem mais fonte duplicada de mapping de intrinsic IDs.
2. `LowerToIRVMService` resolve IDs finais exclusivamente via artefato canonico.
3. Suite de testes backend cobre:
- carregamento valido,
- invalid registry,
- mismatch detectavel em strict mode.
## Tests
1. `:prometeu-compiler:prometeu-build-pipeline:test --tests *IRVMIntrinsicRegistry*`
2. `:prometeu-compiler:prometeu-build-pipeline:test --tests *LowerToIRVMServiceTest*`
3. `:prometeu-compiler:prometeu-build-pipeline:test --tests *BackendConformanceMatrixSpecTest*`
## Affected Documents
1. `docs/general/specs/20. IRBackend to IRVM Lowering Specification.md`
2. `docs/general/specs/22. Backend Spec-to-Test Conformance Matrix.md`
3. `docs/pbs/pull-requests/INDEX.md`
## Open Questions
1. Nenhuma bloqueante para lado compiler.

View File

@ -1,69 +0,0 @@
# PR-10.1 - PBS Parser Shared Context and Safe Delegation
## Briefing
`PbsParser` concentra estado compartilhado (`cursor`, `diagnostics`, `fileId`, `parseMode`, `loopDepth`) e responsabilidades de parsing em uma unica classe.
Esta PR introduz uma fundacao estrutural para decomposicao, sem alterar comportamento: um contexto compartilhado e pontos de delegacao seguros, mantendo `PbsParser` como fachada publica.
## Motivation
### Dor atual que esta PR resolve
1. Extracoes futuras dependem de copiar estado ou expor detalhes internos do parser.
2. O acoplamento entre navegação, diagnostico e parse impede quebrar a classe sem risco alto.
3. A refatoracao fica mais segura se a infraestrutura de compartilhamento vier antes da movimentacao de logica.
## Target
Estabelecer a base de refactor sem mudar funcionalidade:
1. Introduzir um contexto compartilhado para parser.
2. Encapsular helpers comuns de span/report/consume no contexto ou utilitarios proximos.
3. Permitir delegacao gradual para subparsers mantendo `PbsParser.parse(...)` como API unica.
## Dependencies
Nenhuma.
## Scope
1. Criar `ParserContext` ou equivalente com acesso a `cursor`, `diagnostics`, `fileId`, `parseMode` e `loopDepth`.
2. Mover helpers estruturais triviais para o contexto onde isso nao altere semantica.
3. Adaptar `PbsExprParser` bootstrap para consumir o mesmo contexto, ou uma visao compatível, sem mudar seu comportamento.
## Non-Goals
1. Nao alterar gramatica PBS.
2. Nao mover ainda parsing de tipos, atributos, blocos ou declaracoes para classes separadas.
3. Nao alterar mensagens, codigos de erro ou spans.
## Method
### O que deve ser feito explicitamente
1. Introduzir um objeto de contexto pequeno e explicito.
2. Manter `PbsParser` como orquestrador/fachada durante toda a PR.
3. Preservar o contrato de `parse(...)` e a ordem de consumo de tokens.
4. Validar que a nova camada e puramente estrutural.
## Acceptance Criteria
1. `PbsParser` continua sendo o unico entrypoint publico de parse.
2. Nenhum teste de parser, semantica ou frontend muda comportamento esperado.
3. Nao ha alteracao observavel em AST, spans ou diagnosticos.
4. A PR reduz acoplamento e prepara extracoes futuras sem mover regras complexas ainda.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. O `loopDepth` deve viver no contexto mutavel compartilhado ou em um helper especializado de block parsing? Esta PR pode manter no contexto; a decisao final pode vir na `PR-10.4`.

View File

@ -1,70 +0,0 @@
# PR-10.2 - PBS Parser Attribute and Type Subparsers
## Briefing
`PbsParser` ainda centraliza parsing de atributos, `typeRef` e `returnSpec`, que sao superficies coesas e amplamente reutilizadas.
Esta PR extrai essas responsabilidades para subparsers dedicados, sem alterar sintaxe aceita, AST produzido ou diagnosticos.
## Motivation
### Dor atual que esta PR resolve
1. `PbsParser` mistura topo de arquivo, declaracoes, blocos, atributos e tipos.
2. `parseTypeRef`, `parseAttribute*` e `parseCallableReturnSpec` sao hotspots claros de complexidade e reuso.
3. Sem extrair essa camada, as PRs seguintes continuam dependendo de uma classe central grande demais.
## Target
Separar parsing de tipos e atributos em colaboradores dedicados:
1. `PbsAttributeParser` ou equivalente.
2. `PbsTypeParser` ou equivalente.
3. Delegacao explicita a partir de `PbsParser`.
## Dependencies
Prerequisito direto:
1. `PR-10.1`
## Scope
1. Extrair `parseAttributeList`, `parseAttribute`, `parseAttributeArguments`, `parseAttributeArgument`, `parseAttributeValue`.
2. Extrair `parseTypeRef`, `parseNamedTupleTypeFields`, `parseCallableReturnSpec`, `parseReturnSpecFromMarker`, `isTypeStart`.
3. Preservar integralmente `PbsAst` e `ParseErrors`.
## Non-Goals
1. Nao alterar regras de atributos em modos `ORDINARY` e `INTERFACE_MODULE`.
2. Nao alterar aridade de named tuple.
3. Nao alterar recuperacao de erro alem do necessario para manter equivalencia.
## Method
### O que deve ser feito explicitamente
1. Mover parsing de atributos e tipos para classes pequenas, focadas e package-private.
2. Reusar o contexto compartilhado introduzido na PR anterior.
3. Manter `PbsParser` apenas como delegador nessas superficies.
4. Adicionar regressao para spans e diagnosticos de tipos/atributos se ainda nao houver cobertura suficiente.
## Acceptance Criteria
1. `PbsParser` deixa de implementar diretamente a maior parte do parsing de atributos e tipos.
2. AST e diagnosticos dessas superficies permanecem equivalentes.
3. A cobertura existente de parser continua verde sem mudancas semanticas.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsInterfaceModuleSemanticsTest*`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Se `returnSpec` deve ficar no parser de tipos ou em um parser de callable surface. A recomendacao desta PR e manter em `PbsTypeParser`, porque o contrato de retorno depende diretamente de `typeRef`.

View File

@ -1,73 +0,0 @@
# PR-10.3 - PBS Parser Top-Level Declaration Decomposition
## Briefing
O maior concentrador de branching restante em `PbsParser` e a montagem de topo de arquivo e o dispatch de `declare ...`.
Esta PR extrai o parsing de declaracoes top-level e de corpos declarativos para colaboradores especificos, mantendo a mesma gramatica e o mesmo comportamento observavel.
## Motivation
### Dor atual que esta PR resolve
1. `parseFile` e `parseDeclareTopDecl` acumulam roteamento de muitas formas de declaracao.
2. Declaracoes como `host`, `builtin type`, `struct`, `contract`, `service`, `enum` e `implements` convivem no mesmo arquivo e elevam acoplamento.
3. Essa parte do parser muda com frequencia e hoje tem custo alto de manutencao.
## Target
Separar a camada de declaracoes top-level:
1. parsing de imports,
2. dispatch de `declare`,
3. parsing de corpos declarativos,
4. roteamento por `ParseMode`.
## Dependencies
Prerequisitos diretos:
1. `PR-10.1`
2. `PR-10.2`
## Scope
1. Extrair `parseFile` em conjunto com o dispatch de topo para um colaborador dedicado.
2. Extrair `parseDeclareTopDecl` e parsers correlatos (`host`, `builtin type`, `struct`, `contract`, `service`, `error`, `enum`, `callback`, `const`, `implements`).
3. Preservar o comportamento atual de atributos permitidos/proibidos por tipo de declaracao.
## Non-Goals
1. Nao alterar a ordem de imports/declarations no AST.
2. Nao alterar as regras de `INTERFACE_MODULE`.
3. Nao reescrever `PbsExprParser`.
## Method
### O que deve ser feito explicitamente
1. Criar um `PbsTopLevelParser` e um `PbsDeclarationParser`, ou divisao equivalente.
2. Manter em `PbsParser` apenas a montagem final da fachada e o fio de chamada principal.
3. Extrair por familias coesas de declaracao, evitando uma nova classe monolitica.
4. Preservar sincronia/recovery de topo no mesmo fluxo observavel.
## Acceptance Criteria
1. `parseFile` e `parseDeclareTopDecl` deixam de concentrar o dispatch completo de todas as declaracoes.
2. O parse de topo continua deterministico e equivalente ao estado anterior.
3. Testes de parser e frontend continuam verdes sem necessidade de atualizar fixtures por mudanca funcional.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsBarrelParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsInterfaceModuleSemanticsTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `implements` deve ficar junto de declaracoes top-level gerais ou em um parser especializado de contract/service surfaces? A recomendacao e mantê-lo no parser top-level por depender fortemente do roteamento de arquivo.

View File

@ -1,74 +0,0 @@
# PR-10.4 - PBS Parser Block and Statement Decomposition
## Briefing
Depois de extrair tipos/atributos e declaracoes top-level, o maior hotspot restante de `PbsParser` passa a ser parsing de blocos e statements.
Esta PR separa `block`, `statement`, `assignment`, `loop` e controle de fluxo em um parser dedicado, sem alterar a funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. `parseBlock`, `parseStatement`, `parseIfStatement`, `parseForStatement` e correlatos mantem alta complexidade e forte acoplamento com `loopDepth`.
2. A mistura de statement parsing com helpers de token/erro dificulta evolucao e leitura.
3. O parser de blocos e o ponto mais sensivel para regressao e precisa de uma fronteira estrutural clara.
## Target
Extrair a superficie de blocos e statements para um colaborador dedicado:
1. blocos,
2. statements estruturados,
3. assignment detection,
4. controle de `loopDepth`.
## Dependencies
Prerequisitos diretos:
1. `PR-10.1`
2. `PR-10.2`
3. `PR-10.3`
## Scope
1. Extrair `parseBlock`, `parseStatement`, `parseLetStatement`, `parseAssignStatement`, `parseLValue`.
2. Extrair `parseIfStatement`, `parseForStatement`, `parseWhileStatement`, `parseBreakStatement`, `parseContinueStatement`, `parseReturnStatement`.
3. Extrair `isAssignmentStatementStart` e helpers locais associados.
## Non-Goals
1. Nao alterar regras de tail expression.
2. Nao alterar precedence de expressoes.
3. Nao alterar as mensagens atuais de erro para loop control e assignment targets.
## Method
### O que deve ser feito explicitamente
1. Introduzir um `PbsBlockParser` ou equivalente.
2. Encapsular `loopDepth` dentro do contexto compartilhado ou de uma API pequena de entrada/saida de loop.
3. Reutilizar `PbsExprParser` como dependencia, sem alterar seu contrato.
4. Preservar spans e forma de recovery dentro de blocos.
## Acceptance Criteria
1. `PbsParser` deixa de conter a maior parte do parsing de blocos e statements.
2. `loopDepth` continua correto para `break` e `continue`.
3. Nenhum teste de parser, semantica de flow ou lowering sofre alteracao funcional.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserStatementsTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsFallthroughTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `isAssignmentStatementStart` deve permanecer no parser de bloco ou virar helper de cursor/lookahead. A recomendacao e mantê-lo no parser de bloco nesta PR e avaliar extração posterior apenas se necessário.

View File

@ -1,80 +0,0 @@
# PR-10.5 - PBS Parser Recovery Utilities and Regression Hardening
## Briefing
As PRs anteriores reduzem a complexidade estrutural de `PbsParser`. Esta PR fecha a trilha com consolidacao de recovery/utilitarios e endurecimento de regressao, ainda sem alterar funcionalidade.
O objetivo e evitar que a decomposicao introduza pequenas divergencias em diagnosticos, spans ou pontos de reinicio.
## Motivation
### Dor atual que esta PR resolve
1. Recovery e helpers de consumo sao sensiveis e podem ficar duplicados apos a extracao.
2. Sem cobertura adicional, uma refatoracao estrutural grande pode preservar testes principais e ainda mudar detalhes de parser.
3. O parser precisa terminar menor, mas tambem com fronteiras de manutencao claras.
## Target
Consolidar a etapa final do refactor:
1. recovery de topo e de atributos,
2. helpers de consumo/report,
3. regressao de spans/diagnosticos,
4. limpeza final de `PbsParser`.
## Dependencies
Prerequisitos diretos:
1. `PR-10.1`
2. `PR-10.2`
3. `PR-10.3`
4. `PR-10.4`
## Scope
1. Consolidar `consume`, `consumeForToken`, `consumeDeclarationTerminator`, `consumeBalancedBraces`, `synchronizeTopLevel` e recovery de atributo em utilitarios coesos.
2. Remover duplicacao residual entre subparsers.
3. Adicionar ou endurecer testes de regressao para:
- spans,
- erros esperados,
- recovery em topo e em bloco,
- modos `ORDINARY` e `INTERFACE_MODULE`.
## Non-Goals
1. Nao alterar taxonomia de `ParseErrors`.
2. Nao introduzir novas construcoes sintaticas.
3. Nao reescrever o lexer ou `PbsExprParser`.
## Method
### O que deve ser feito explicitamente
1. Fazer uma passada final de consolidacao estrutural.
2. Eliminar helpers obsoletos ou duplicados apos as extracoes.
3. Verificar equivalencia observavel com foco em spans e recovery.
4. Encerrar a trilha com `PbsParser` como fachada pequena e clara.
## Acceptance Criteria
1. `PbsParser` fica restrito a composicao/orquestracao e nao volta a concentrar logica de parse pesado.
2. Recovery e consumo de token ficam centralizados e sem duplicacao relevante.
3. Suite do frontend PBS passa integralmente.
4. Nao ha mudanca funcional observavel em parse, AST ou diagnosticos.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserStatementsTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma de arquitetura. A partir desta PR, qualquer mudanca adicional deve ser tratada como evolucao funcional separada, nao como parte do refactor estrutural.

View File

@ -1,68 +0,0 @@
# PR-11.1 - PBS Expr Parser Shared Context and Precedence Spine
## Briefing
`PbsExprParser` hoje concentra estado compartilhado, helpers basicos e toda a espinha de precedence em uma unica classe.
Esta PR introduz a fundacao estrutural para decompor o parser de expressoes sem alterar comportamento: contexto compartilhado, helpers comuns e uma organizacao mais clara da cadeia de precedence.
## Motivation
### Dor atual que esta PR resolve
1. Extracoes futuras dependem de duplicar acesso a `cursor`, `diagnostics`, `fileId` e `blockParserDelegate`.
2. A cadeia de precedence existe, mas toda a infraestrutura esta acoplada a uma unica classe.
3. Refatorar primeiro a fundacao reduz risco antes de mover control-flow e postfix/primary.
## Target
Estabelecer uma base segura para o refactor de `PbsExprParser`:
1. contexto compartilhado,
2. helpers de span/report/consume reutilizaveis,
3. espinha de precedence claramente separada do restante.
## Dependencies
Nenhuma.
## Scope
1. Introduzir `ExprParserContext` ou equivalente.
2. Encapsular `cursor`, `diagnostics`, `fileId` e `blockParserDelegate` nessa camada.
3. Reorganizar a espinha de precedence (`parseExpression`, `parseApply`, `parseOr`, `parseAnd`, `parseEquality`, `parseComparison`, `parseAs`, `parseTerm`, `parseFactor`, `parseUnary`) sem mudar a ordem semantica.
## Non-Goals
1. Nao alterar associatividade ou precedence.
2. Nao mover ainda parsing de `if/switch/handle`.
3. Nao alterar `PbsParser` nem `PbsTokenCursor`.
## Method
### O que deve ser feito explicitamente
1. Criar um contexto compartilhado pequeno e explicito.
2. Manter `PbsExprParser` como entrypoint package-private.
3. Preservar a ordem atual de chamadas na chain de precedence.
4. Validar que esta PR e puramente estrutural.
## Acceptance Criteria
1. `PbsExprParser` continua com o mesmo contrato de entrada/saida.
2. Precedence e associatividade permanecem equivalentes.
3. Nao ha mudanca observavel em AST, spans ou diagnosticos de expressoes.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `blockParserDelegate` deve continuar como callback simples ou migrar para interface mais rica de surface parsing? Nesta PR, manter callback simples minimiza risco.

View File

@ -1,72 +0,0 @@
# PR-11.2 - PBS Expr Parser Control-Flow Subparsers
## Briefing
As formas de expressao com maior branching em `PbsExprParser` sao `if`, `switch`, `handle` e `else`.
Esta PR extrai essas construcoes para subparsers dedicados, mantendo a mesma sintaxe, mesmos diagnosticos e o mesmo AST.
## Motivation
### Dor atual que esta PR resolve
1. `if/switch/handle` compartilham recovery, parsing de blocos e recursion, elevando bastante a complexidade local.
2. Essas formas sao semanticamente coesas e podem viver fora do parser principal de precedence.
3. Sem essa extracao, `PbsExprParser` continua grande mesmo apos separar a fundacao.
## Target
Separar parsing de expressoes de controle de fluxo:
1. `handle`,
2. `else`,
3. `if expression`,
4. `switch expression`.
## Dependencies
Prerequisito direto:
1. `PR-11.1`
## Scope
1. Extrair `parseHandle`, `parseHandlePattern`, `parseElse`, `parseIfExpression`, `parseIfExpressionFromToken`, `parseSwitchExpression`, `parseSwitchPattern`.
2. Preservar uso de `parseSurfaceBlock` para blocos de expressao.
3. Manter exatamente a precedence atual dessas superficies.
## Non-Goals
1. Nao alterar a regra de `if expression` exigir `else`.
2. Nao alterar curingas de `switch`.
3. Nao alterar formatos aceitos de `handle` e remapeamento de erro.
## Method
### O que deve ser feito explicitamente
1. Introduzir subparsers pequenos por familia de construcao.
2. Reusar o contexto compartilhado da PR anterior.
3. Garantir que `parseExpression()` continue entrando pela mesma superficie sintatica.
4. Proteger a equivalencia com testes focados em control-flow expressions.
## Acceptance Criteria
1. A logica de `if/switch/handle/else` nao fica mais centralizada em `PbsExprParser`.
2. ASTs gerados para essas construcoes permanecem equivalentes.
3. Diagnosticos de formas invalidas continuam com o mesmo contrato observavel.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserStatementsTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `else` deve viver junto do control-flow parser ou continuar na espinha de precedence. A recomendacao e movê-lo junto porque a associatividade e as mensagens de erro fazem parte do mesmo cluster conceitual.

View File

@ -1,74 +0,0 @@
# PR-11.3 - PBS Expr Parser Postfix, Primary and Construction Decomposition
## Briefing
O segundo grande concentrador de complexidade em `PbsExprParser` esta nas superficies de `postfix` e `primary`: chamadas, membros, propagate, tuplas, blocos, `new`, `bind`, `some/ok/err`.
Esta PR separa essas familias em colaboradores menores, sem alterar a funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. `parsePostfix`, `parsePrimary` e `parseParenthesizedPrimary` misturam muitas formas sintaticas distintas.
2. Tuple literals, grouped expressions e construction surfaces compartilham lookahead delicado.
3. A manutencao dessas regras num unico metodo torna alto o custo de qualquer evolucao futura.
## Target
Separar parsing de superficies primarias e postfix:
1. postfix chaining,
2. primary literals/identifiers/blocks,
3. tuple/group handling,
4. construction/result surfaces (`new`, `bind`, `some`, `ok`, `err`).
## Dependencies
Prerequisitos diretos:
1. `PR-11.1`
2. `PR-11.2`
## Scope
1. Extrair `parsePostfix`.
2. Extrair `parsePrimary`, `parseParenthesizedPrimary`, `parseTupleItems`, `parseTupleItem`.
3. Extrair `parseNewExpression`, `parseBindExpression`, `parseSomeExpression`, `parseOkExpression`, `parseErrExpression`.
4. Preservar recovery atual para `?`, tuple malformed e parens.
## Non-Goals
1. Nao alterar a aridade de tuple literal.
2. Nao alterar mixed labeled/unlabeled tuple validation.
3. Nao alterar o formato aceito de `new Vec.zero(...)` e `bind(ctx, fn)`.
## Method
### O que deve ser feito explicitamente
1. Introduzir subparsers por familia sintatica em vez de criar um novo monolito.
2. Manter a ordem atual de postfix chaining.
3. Preservar lookahead de tuple/group exatamente como hoje.
4. Reforcar testes de tupla, construction e propagate operator invalido.
## Acceptance Criteria
1. `parsePostfix` e `parsePrimary` deixam de concentrar todas as superficies primarias.
2. Tuplas, grupos, constructions e postfix chains continuam equivalentes.
3. Nao ha mudanca funcional em AST, spans ou diagnosticos.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsOptionalResultTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsApplyResolutionTest*`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. O parsing de tuple/group deve ficar junto de primary ou em helper especializado de parenthesized surfaces. A recomendacao e extrair para helper especializado, porque esse e o trecho com lookahead mais sensivel.

View File

@ -1,73 +0,0 @@
# PR-11.4 - PBS Expr Parser Literals, Patterns and Shared Token Utilities
## Briefing
Depois de extrair control-flow e primary/postfix, restam em `PbsExprParser` alguns clusters menores mas sensiveis: parsing de literais/padroes, `error path`, consumo de tokens e utilitarios de parse numerico/string.
Esta PR consolida esses pontos em utilitarios dedicados, ainda sem mudanca funcional.
## Motivation
### Dor atual que esta PR resolve
1. Parsing de literal aparece em mais de um lugar (`primary` e switch pattern).
2. `error path`, `consumeMemberName`, `parseLong/Int/DoubleOrDefault` e `unescapeString` sao infra compartilhada e hoje permanecem acoplados ao parser principal.
3. Sem consolidar essa base, o parser termina menor, mas ainda com detalhes mecanicos espalhados.
## Target
Extrair infra compartilhada de expressao:
1. parsing de literais,
2. parsing de `error path`,
3. parsing de patterns simples,
4. token utilities e decode helpers.
## Dependencies
Prerequisitos diretos:
1. `PR-11.1`
2. `PR-11.2`
3. `PR-11.3`
## Scope
1. Extrair `parseLiteralPatternExpression`, `parseErrorPath`, `parseHandlePattern` e helpers correlatos.
2. Consolidar `consume`, `consumeMemberName`, `span`, `report`.
3. Consolidar `parseLongOrDefault`, `parseIntOrDefault`, `parseDoubleOrDefault`, `unescapeString`.
## Non-Goals
1. Nao alterar as regras de literal recovery.
2. Nao alterar o decode de strings.
3. Nao alterar a estrutura de `PbsAst.ErrorPath`.
## Method
### O que deve ser feito explicitamente
1. Reunir parsing de literal/pattern em componente reutilizavel.
2. Mover utilitarios mecanicos para helpers claros e pequenos.
3. Garantir que toda chamada mantenha a mesma atribuicao de spans e diagnosticos.
4. Evitar criar uma util-class genérica demais; manter helpers focados no dominio de expression parsing.
## Acceptance Criteria
1. `PbsExprParser` deixa de concentrar parsing repetido de literais/padroes e utilitarios basicos.
2. Parsing de strings, numeros e `error path` permanece equivalente.
3. A suite de parser continua verde sem atualizar comportamento esperado.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma de arquitetura. Esta PR e de consolidacao local.

View File

@ -1,75 +0,0 @@
# PR-11.5 - PBS Expr Parser Regression Hardening and Final Cleanup
## Briefing
As PRs anteriores reduzem a complexidade estrutural de `PbsExprParser`. Esta PR fecha a trilha com limpeza final, eliminacao de duplicacao residual e endurecimento de regressao, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. Refactors estruturais em parser de expressao podem mudar detalhes finos sem quebrar imediatamente todos os testes.
2. Ao final da decomposicao, costuma restar duplicacao pequena e helpers obsoletos.
3. O fechamento da trilha precisa garantir equivalencia observavel e uma fachada final pequena.
## Target
Concluir a trilha de refactor do parser de expressoes:
1. limpeza estrutural final,
2. consolidacao dos helpers remanescentes,
3. cobertura de regressao para precedence, postfix, tuples e control-flow expressions.
## Dependencies
Prerequisitos diretos:
1. `PR-11.1`
2. `PR-11.2`
3. `PR-11.3`
4. `PR-11.4`
## Scope
1. Remover codigo duplicado ou caminhos obsoletos apos as extracoes.
2. Garantir que `PbsExprParser` fique reduzido a composicao/orquestracao.
3. Expandir regressao quando necessario para spans, diagnosticos e precedence.
## Non-Goals
1. Nao alterar gramatica de expressoes.
2. Nao introduzir novas formas sintaticas.
3. Nao alterar `PbsAst` ou `ParseErrors`.
## Method
### O que deve ser feito explicitamente
1. Fazer uma passada final de consolidacao.
2. Verificar equivalencia com foco em:
- precedence,
- associatividade,
- tuple/group lookahead,
- control-flow expression recovery.
3. Encerrar a trilha com um `PbsExprParser` pequeno, claro e estavel.
## Acceptance Criteria
1. `PbsExprParser` termina como fachada/orquestrador, nao como concentrador de todas as regras.
2. Nao ha mudanca funcional observavel em AST, spans ou diagnosticos.
3. Suite do frontend PBS passa integralmente.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsParserStatementsTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma. A partir desta PR, qualquer ajuste restante deve ser tratado como mudanca funcional separada.

View File

@ -1,69 +0,0 @@
# PR-12.1 - Flow Expression Analyzer Context and Dispatch Foundation
## Briefing
`PbsFlowExpressionAnalyzer` concentra estado compartilhado e um dispatch grande de `Expression -> semantic analysis` em uma unica classe.
Esta PR introduz a base estrutural para decomposicao sem alterar funcionalidade: contexto compartilhado, helpers comuns e uma fronteira clara entre fachada e implementacoes especializadas.
## Motivation
### Dor atual que esta PR resolve
1. A classe combina orquestracao, recursion, block delegation e regras semanticas detalhadas.
2. Extracoes futuras ficam arriscadas sem um contexto compartilhado explicito.
3. O maior hotspot da classe e o dispatch principal de `analyzeExpressionInternal`, que hoje depende de muitos parametros repetidos.
## Target
Estabelecer uma fundacao segura para o refactor:
1. contexto compartilhado para analise de expressao,
2. encapsulamento de argumentos recorrentes,
3. fachada pequena em `PbsFlowExpressionAnalyzer`.
## Dependencies
Nenhuma.
## Scope
1. Introduzir um contexto/request object para `scope`, `expectedType`, `returnType`, `resultErrorName`, `receiverType`, `model`, `diagnostics`, `use` e `valueContext`.
2. Encapsular a dependencia de `BlockAnalyzer` nessa camada.
3. Reorganizar o dispatch principal sem mover ainda regras complexas para outras classes.
## Non-Goals
1. Nao alterar inferencia de tipos.
2. Nao alterar diagnosticos ou spans.
3. Nao reescrever `PbsFlowTypeOps` ou `PbsFlowBodyAnalyzer`.
## Method
### O que deve ser feito explicitamente
1. Criar um contexto pequeno e explicito para a analise recursiva.
2. Manter `PbsFlowExpressionAnalyzer` como entrypoint package-private.
3. Preservar a ordem atual de recursion e emissao de diagnosticos.
4. Garantir que esta PR seja puramente estrutural.
## Acceptance Criteria
1. `PbsFlowExpressionAnalyzer` continua com o mesmo contrato observavel.
2. A quantidade de parametros repetidos no dispatch recursivo e reduzida.
3. Nao ha mudanca funcional em inferencia, erros ou comportamento da suite.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsApplyResolutionTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. O contexto deve ser imutavel por chamada recursiva ou permitir derivacao incremental. A recomendacao e usar derivacao imutavel leve para reduzir risco de regressao.

View File

@ -1,71 +0,0 @@
# PR-12.2 - Flow Expression Analyzer Literal and Structural Expression Splitting
## Briefing
Grande parte do dispatch de `PbsFlowExpressionAnalyzer` cobre formas literais e estruturais de expressao: literais, `this`, identificadores, grupos, tuplas, blocos, unarios, binarios, `none/some`, `new`, `as`, `ok/err`.
Esta PR extrai essas familias para componentes menores, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. O dispatch principal mistura casos triviais com regras mais complexas de call/member/switch/handle.
2. Formas estruturais simples podem ser separadas com risco baixo e alta reducao de complexidade.
3. Sem esse corte, o dispatch central continua inchado mesmo com contexto compartilhado.
## Target
Separar a analise de expressoes literais e estruturais:
1. literais e identificadores,
2. grupos, tuplas e blocos,
3. unario/binario,
4. `none/some`, `new`, `bind`-independent simple forms, `as`, `ok/err`.
## Dependencies
Prerequisito direto:
1. `PR-12.1`
## Scope
1. Extrair casos simples de `analyzeExpressionInternal` para helpers/colaboradores dedicados.
2. Manter o resultado em `ExprResult` exatamente como hoje.
3. Preservar todas as chamadas a `typeOps` e `blockAnalyzer`.
## Non-Goals
1. Nao alterar regras de callback/bind.
2. Nao alterar member access ou overload resolution.
3. Nao alterar switch/handle/result propagation.
## Method
### O que deve ser feito explicitamente
1. Mover primeiro os casos com menor acoplamento semantico.
2. Manter o dispatch principal apenas como roteador.
3. Preservar a ordem atual de recursion para evitar mudanca em diagnosticos acumulados.
## Acceptance Criteria
1. Casos literais e estruturais deixam de ficar todos dentro do dispatch principal.
2. AST/semantics observados pela suite permanecem equivalentes.
3. O hotspot principal da classe reduz tamanho e branching sem alterar comportamento.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsExprParserTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsOptionalResultTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `BindExpr` deve entrar aqui ou junto de call resolution. A recomendacao e mantê-lo para `PR-12.3`, porque ele depende de matching de callback/callable.

View File

@ -1,72 +0,0 @@
# PR-12.3 - Flow Expression Analyzer Call and Member Resolution Decomposition
## Briefing
`analyzeCallExpression`, `analyzeApplyExpression`, `resolveCallableApplication`, `analyzeMemberExpression` e parte de `BindExpr` concentram a logica de resolucao mais sensivel do analisador.
Esta PR extrai essa superficie para colaboradores menores, sem alterar regras de overload, bare method extraction, acesso a campos ou matching de callback.
## Motivation
### Dor atual que esta PR resolve
1. Member access e callable resolution sao os clusters mais densos depois do dispatch principal.
2. A classe mistura regras de acesso a tuple/struct/service/contract com overload resolution e bind matching.
3. Qualquer ajuste nessas regras hoje exige tocar um arquivo muito central e com alta chance de regressao.
## Target
Separar a analise de resolucao:
1. member access,
2. call/apply overload resolution,
3. bind-to-callback matching,
4. field access permission checks.
## Dependencies
Prerequisitos diretos:
1. `PR-12.1`
2. `PR-12.2`
## Scope
1. Extrair `analyzeCallExpression`, `analyzeApplyExpression`, `resolveCallableApplication`.
2. Extrair `analyzeMemberExpression` e `canReadStructField`.
3. Mover a parte especifica de `BindExpr` para o mesmo cluster de resolucao.
## Non-Goals
1. Nao alterar diagnosticos de overload ambiguous/unresolved.
2. Nao alterar regras de leitura de campo privado/publico.
3. Nao alterar a proibicao de bare method extraction.
## Method
### O que deve ser feito explicitamente
1. Criar um resolver focado em call/member semantics.
2. Preservar o mesmo uso de `TypeView`, `CallableSymbol` e `ExprResult`.
3. Garantir que o order of checks permaneça equivalente, especialmente em erros e narrowing por `expectedType`.
## Acceptance Criteria
1. Call/member resolution deixa de ficar concentrada em `PbsFlowExpressionAnalyzer`.
2. Bare method extraction, field access e overload matching permanecem equivalentes.
3. Suite semantica continua verde sem mudancas funcionais.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsApplyResolutionTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsFrontendCompilerTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `BindExpr` deve compartilhar exatamente o mesmo narrowing path de `call/apply` ou ficar em helper proprio. A recomendacao e helper proprio dentro do mesmo resolver, para evitar acoplamento artificial.

View File

@ -1,73 +0,0 @@
# PR-12.4 - Flow Expression Analyzer Switch and Handle Decomposition
## Briefing
`switch` e `handle` sao as maiores superfices especializadas restantes em `PbsFlowExpressionAnalyzer`, com regras de exaustividade, pattern typing, matching de erro e arm typing.
Esta PR separa essas construcoes em analisadores dedicados, mantendo exatamente o comportamento atual.
## Motivation
### Dor atual que esta PR resolve
1. `analyzeSwitchExpression` e `analyzeHandleExpression` concentram regras de alto branching e recovery semantico.
2. Essas regras sao semanticamente coesas e merecem fronteiras proprias.
3. Sem esse corte, a classe principal continua com os hotspots mais caros de manutencao.
## Target
Extrair a analise especializada de:
1. `switch expression`,
2. `switch pattern typing/keying`,
3. `handle expression`,
4. `handle block arm` e matching de error targets.
## Dependencies
Prerequisitos diretos:
1. `PR-12.1`
2. `PR-12.2`
3. `PR-12.3`
## Scope
1. Extrair `analyzeSwitchExpression`, `switchPatternKey`, `switchPatternType`.
2. Extrair `analyzeHandleExpression`, `analyzeHandleBlockArm`, `matchesTargetError`, `unwrapGroup`.
3. Preservar a interacao com `blockAnalyzer`, `typeOps` e `model`.
## Non-Goals
1. Nao alterar regras de exaustividade de switch em value position.
2. Nao alterar regras de wildcard/default duplication.
3. Nao alterar regras de `handle` para `ok(...)` / `err(...)` terminais.
## Method
### O que deve ser feito explicitamente
1. Criar analisadores especializados por construcao.
2. Preservar ordem de validacoes e diagnosticos.
3. Reusar o contexto compartilhado para evitar nova explosao de parametros.
## Acceptance Criteria
1. `switch` e `handle` deixam de ficar implementados diretamente na classe principal.
2. Exaustividade, arm typing e error matching permanecem equivalentes.
3. Nenhum teste de result flow, control flow ou optional/result muda comportamento esperado.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsOptionalResultTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `switchPatternKey` e `switchPatternType` devem ficar juntos no mesmo colaborador. A recomendacao e sim, porque ambos definem a semantica da superficie de pattern.

View File

@ -1,77 +0,0 @@
# PR-12.5 - Flow Expression Analyzer Regression Hardening and Final Cleanup
## Briefing
As PRs anteriores reduzem a complexidade estrutural de `PbsFlowExpressionAnalyzer`. Esta PR fecha a trilha com consolidacao final, limpeza de duplicacao residual e endurecimento de regressao, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. Refactors estruturais em analise semantica podem preservar casos principais e ainda mudar detalhes finos de diagnostico.
2. Ao final da decomposicao, tendem a restar helpers redundantes ou caminhos duplicados.
3. O fechamento da trilha precisa garantir equivalencia observavel e uma fachada final pequena.
## Target
Concluir a trilha de refactor:
1. limpeza estrutural final,
2. consolidacao dos helpers remanescentes,
3. cobertura de regressao para inferencia e diagnosticos.
## Dependencies
Prerequisitos diretos:
1. `PR-12.1`
2. `PR-12.2`
3. `PR-12.3`
4. `PR-12.4`
## Scope
1. Remover duplicacao residual apos as extracoes.
2. Garantir que `PbsFlowExpressionAnalyzer` fique reduzido a composicao/orquestracao.
3. Reforcar testes de regressao para call/member resolution, result flow, switch e handle.
## Non-Goals
1. Nao alterar taxonomia de `PbsSemanticsErrors`.
2. Nao alterar `TypeView`, `ExprResult` ou `PbsFlowTypeOps`.
3. Nao introduzir novas regras semanticas.
## Method
### O que deve ser feito explicitamente
1. Fazer uma passada final de consolidacao.
2. Verificar equivalencia com foco em:
- inferencia de tipos,
- overload resolution,
- access checks,
- switch/handle exhaustiveness e matching,
- diagnosticos emitidos.
3. Encerrar a trilha com uma fachada pequena e clara.
## Acceptance Criteria
1. `PbsFlowExpressionAnalyzer` termina como orquestrador, nao como concentrador de toda a logica.
2. Nao ha mudanca funcional observavel em analise, tipos inferidos ou diagnosticos.
3. Suite do frontend PBS passa integralmente.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsApplyResolutionTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsOptionalResultTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
5. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma. A partir desta PR, qualquer mudanca adicional deve ser tratada como evolucao funcional separada.

View File

@ -1,67 +0,0 @@
# PR-13.1 - Flow Body Analyzer Context and Entrypoint Foundation
## Briefing
`PbsFlowBodyAnalyzer` concentra montagem de contexto, iteracao de callables e delegacao recursiva de block/statement analysis em uma unica classe.
Esta PR introduz a base estrutural para decomposicao sem alterar funcionalidade: contexto compartilhado, encapsulamento dos argumentos recorrentes e uma fachada mais clara para a classe.
## Motivation
### Dor atual que esta PR resolve
1. A classe repassa muitos parametros repetidos entre `validate`, `validateCallableBody`, `analyzeBlock` e `analyzeStatement`.
2. Extracoes futuras ficam arriscadas sem um contexto comum explicito.
3. A fundacao estrutural reduz risco antes de mover regras de completion, statements e assignment resolution.
## Target
Estabelecer uma base segura para o refactor:
1. contexto compartilhado de body analysis,
2. encapsulamento de `returnType`, `resultErrorName`, `receiverType`, `model` e `diagnostics`,
3. fachada pequena para `validate(...)`.
## Dependencies
Nenhuma.
## Scope
1. Introduzir um contexto/request object para analise de corpo.
2. Reorganizar `validate` e `validateCallableBody` sem mover ainda regras complexas.
3. Preservar a relacao atual com `PbsFlowExpressionAnalyzer`.
## Non-Goals
1. Nao alterar inferencia de tipos ou diagnosticos.
2. Nao alterar `Model.from(...)`.
3. Nao mover ainda completion analysis ou assignment target resolution para classes separadas.
## Method
### O que deve ser feito explicitamente
1. Criar um contexto pequeno e explicito para analise recursiva de blocos/callables.
2. Manter `PbsFlowBodyAnalyzer` como entrypoint package-private.
3. Preservar a ordem atual de validacao e emissao de erros.
## Acceptance Criteria
1. `PbsFlowBodyAnalyzer` continua com o mesmo contrato observavel.
2. A quantidade de parametros repetidos nas chamadas internas e reduzida.
3. Nao ha mudanca funcional em flow analysis, completion ou diagnosticos.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. O contexto deve ser derivado imutavelmente por bloco ou mutado localmente. A recomendacao e derivacao leve para reduzir risco de vazamento entre branches.

View File

@ -1,71 +0,0 @@
# PR-13.2 - Flow Body Analyzer Callable Body and Completion Decomposition
## Briefing
As regras de entrada de callable e de completion/fallthrough em `PbsFlowBodyAnalyzer` formam um cluster coeso, mas hoje ficam misturadas com statement analysis e assignment resolution.
Esta PR extrai essa superficie para colaboradores dedicados, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. `validateCallableBody`, `validateCallableCompletion`, `blockAlwaysReturns`, `statementAlwaysReturns`, `expressionAlwaysReturns`, `switchAlwaysReturns` e `handleAlwaysReturns` concentram regras de completion com alto branching.
2. Completion analysis e statement analysis sao preocupacoes diferentes e hoje dividem a mesma classe.
3. Essa parte e muito sensivel e merece uma fronteira estrutural propria.
## Target
Separar a camada de body entry/completion:
1. bootstrap de callable body,
2. validacao de fallthrough/completion,
3. regras de `always returns`,
4. exaustividade relevante para completion.
## Dependencies
Prerequisito direto:
1. `PR-13.1`
## Scope
1. Extrair `validateCallableBody`.
2. Extrair `validateCallableCompletion`, `blockAlwaysReturns`, `statementAlwaysReturns`, `expressionAlwaysReturns`.
3. Extrair `switchAlwaysReturns`, `switchIsExhaustive`, `handleAlwaysReturns`, `handleArmAlwaysReturns`, `isKnownErrorPath`.
## Non-Goals
1. Nao alterar as regras atuais de fallthrough para result/plain non-unit.
2. Nao alterar a semantica de exaustividade usada apenas para completion.
3. Nao alterar statement analysis ou assignment checks.
## Method
### O que deve ser feito explicitamente
1. Introduzir um analisador de completion ou divisao equivalente.
2. Manter `PbsFlowBodyAnalyzer` como orquestrador do processo.
3. Preservar rigorosamente a ordem atual de checks e codigos de diagnostico.
## Acceptance Criteria
1. A logica de completion/fallthrough deixa de ficar centralizada em `PbsFlowBodyAnalyzer`.
2. As regras de `always returns` permanecem equivalentes.
3. Nenhum teste de fallthrough, control flow ou result flow muda comportamento esperado.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsFallthroughTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `switch`/`handle` completion deve ficar junto do completion analyzer ou reaproveitar colaboradores do expression analyzer. A recomendacao e manter local ao completion analyzer para evitar acoplamento indevido entre analise de tipo e analise de terminacao.

View File

@ -1,72 +0,0 @@
# PR-13.3 - Flow Body Analyzer Statement Analysis Splitting
## Briefing
Depois de separar entry/completion, o maior hotspot restante em `PbsFlowBodyAnalyzer` passa a ser `analyzeBlock` e `analyzeStatement`, com tratamento de `let`, `return`, `if`, `for`, `while`, expression statement e delegacao para `PbsFlowExpressionAnalyzer`.
Esta PR extrai essa superficie para colaboradores menores, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. `analyzeStatement` concentra varias formas de statement com regras semanticas distintas.
2. Loops, `if` e `return` usam os mesmos parametros e diagnosticos, mas pertencem a clusters semanticos diferentes.
3. A manutencao dessa logica em um unico metodo torna a classe dificil de evoluir.
## Target
Separar a analise de statements:
1. blocos e escopos,
2. `let` e expression statements,
3. `return` flow,
4. `if/for/while`.
## Dependencies
Prerequisitos diretos:
1. `PR-13.1`
2. `PR-13.2`
## Scope
1. Extrair `analyzeBlock` e o dispatch de `analyzeStatement`.
2. Extrair regras de `let`, `if`, `for`, `while` e expression statement para helpers/colaboradores dedicados.
3. Deixar `return` bootstrap pronto para corte proprio, sem ainda mexer em assignment target resolution.
## Non-Goals
1. Nao alterar mutabilidade de escopo local.
2. Nao alterar validacao de tipos de condicao ou bounds de loop.
3. Nao alterar assignment resolution.
## Method
### O que deve ser feito explicitamente
1. Introduzir um statement analyzer ou divisao equivalente por familias.
2. Reusar o contexto compartilhado da `PR-13.1`.
3. Preservar a ordem atual de chamadas ao `expressionAnalyzer`.
## Acceptance Criteria
1. `analyzeStatement` deixa de concentrar todas as formas de statement.
2. Scoping, condition checks e loop bound checks permanecem equivalentes.
3. Suite semantica continua verde sem mudanca funcional.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `return` deve ficar no statement analyzer ou em um colaborador proprio de result flow. A recomendacao e deixar o corte final para a PR seguinte se isso simplificar mais a classe.

View File

@ -1,72 +0,0 @@
# PR-13.4 - Flow Body Analyzer Assignment Target Resolution Decomposition
## Briefing
`resolveAssignmentTarget` e a logica correlata de assignment compatibility concentram um dos trechos mais densos e sensiveis de `PbsFlowBodyAnalyzer`.
Esta PR extrai a resolucao de assignment target e as regras de acesso/leitura/escrita de campo para colaboradores dedicados, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. Assignment resolution mistura lookup de locals, `this`, singleton services, consts e navegação em campos de struct.
2. Regras de leitura e escrita de campo estao acopladas ao fluxo do statement analyzer.
3. A superficie e densa e merece um resolver proprio com foco em diagnósticos de assignability.
## Target
Separar a camada de assignment semantics:
1. resolucao de assignment target,
2. assignability de roots conhecidos,
3. leitura/escrita de campos,
4. type compatibility por operador de atribuicao.
## Dependencies
Prerequisitos diretos:
1. `PR-13.1`
2. `PR-13.2`
3. `PR-13.3`
## Scope
1. Extrair `analyzeAssignmentStatement`.
2. Extrair `resolveAssignmentTarget`, `assignmentCompatible`, `canReadStructField`, `canWriteStructField`, `isKnownNonAssignableRoot`.
3. Manter `AssignmentTargetResolution` ou mover para um modelo focado de assignment.
## Non-Goals
1. Nao alterar regras de mutabilidade/local const.
2. Nao alterar regras de acesso a campos privados/publicos.
3. Nao alterar o mapeamento de operadores compostos para inferencia binaria.
## Method
### O que deve ser feito explicitamente
1. Criar um resolver dedicado para assignment targets.
2. Preservar exatamente os mesmos erros emitidos para target nao resolvido, nao assignable ou field access denied.
3. Reusar `PbsFlowTypeOps` sem alterar sua logica.
## Acceptance Criteria
1. Assignment target resolution deixa de ficar centralizada em `PbsFlowBodyAnalyzer`.
2. Regras de assignability e field access permanecem equivalentes.
3. Nenhum teste de assignment ou control flow muda comportamento esperado.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsDeclarationsTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. `AssignmentTargetResolution` deve permanecer como record local ou migrar para um modelo package-private dedicado. A recomendacao e mover para o resolver de assignment para reduzir acoplamento.

View File

@ -1,77 +0,0 @@
# PR-13.5 - Flow Body Analyzer Regression Hardening and Final Cleanup
## Briefing
As PRs anteriores reduzem a complexidade estrutural de `PbsFlowBodyAnalyzer`. Esta PR fecha a trilha com consolidacao final, limpeza de duplicacao residual e endurecimento de regressao, sem alterar funcionalidade.
## Motivation
### Dor atual que esta PR resolve
1. Refactors estruturais em flow/body analysis podem preservar casos principais e ainda mudar detalhes finos de diagnostico ou scoping.
2. Ao final da decomposicao, tendem a restar helpers redundantes ou caminhos duplicados.
3. O fechamento da trilha precisa garantir equivalencia observavel e uma fachada final pequena.
## Target
Concluir a trilha de refactor:
1. limpeza estrutural final,
2. consolidacao dos helpers remanescentes,
3. cobertura de regressao para completion, statements e assignment semantics.
## Dependencies
Prerequisitos diretos:
1. `PR-13.1`
2. `PR-13.2`
3. `PR-13.3`
4. `PR-13.4`
## Scope
1. Remover duplicacao residual apos as extracoes.
2. Garantir que `PbsFlowBodyAnalyzer` fique reduzido a composicao/orquestracao.
3. Reforcar testes de regressao para fallthrough, return flow, loops e assignments.
## Non-Goals
1. Nao alterar taxonomia de `PbsSemanticsErrors`.
2. Nao alterar `PbsFlowTypeOps` ou `PbsFlowExpressionAnalyzer`.
3. Nao introduzir novas regras semanticas.
## Method
### O que deve ser feito explicitamente
1. Fazer uma passada final de consolidacao.
2. Verificar equivalencia com foco em:
- completion/fallthrough,
- scoping local,
- return result flow,
- assignment target resolution,
- field access diagnostics.
3. Encerrar a trilha com uma fachada pequena e clara.
## Acceptance Criteria
1. `PbsFlowBodyAnalyzer` termina como orquestrador, nao como concentrador da logica completa.
2. Nao ha mudanca funcional observavel em flow analysis ou diagnosticos.
3. Suite do frontend PBS passa integralmente.
## Tests
1. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsFallthroughTest*`
2. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsAssignmentTest*`
3. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsControlFlowTest*`
4. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test --tests *PbsSemanticsResultFlowRulesTest*`
5. `:prometeu-compiler:frontends:prometeu-frontend-pbs:test`
## Affected Documents
1. Nenhum documento normativo.
## Open Questions
1. Nenhuma. A partir desta PR, qualquer mudanca adicional deve ser tratada como evolucao funcional separada.

View File

@ -1,98 +0,0 @@
# PR-19.1 - PBS Topic 19 Spec Propagation and Normative Cutover
## Briefing
As decisions `19.1` a `19.5` fecharam a arquitetura de globals, lifecycle markers, published wrapper, lowering e conformance para PBS v1.
Esta PR abre a execucao da familia `19` pela frente editorial normativa:
1. propagar as decisions para specs PBS e specs gerais relevantes;
2. remover lacunas documentais entre source model, lowering e publication contract;
3. alinhar o contrato final com entrypoint fisico `0` e sem autoridade de `entrypoint` no `manifest.json`.
## Target
Atualizar o baseline normativo para o modelo final de topic `19` em:
1. syntax and AST,
2. static semantics,
3. dynamic semantics,
4. diagnostics,
5. lowering,
6. bytecode/publication handoff.
## Dependencies
Prerequisitos diretos:
1. `Globals Surface, Identity, and Module Boundaries Decision.md`
2. `Lifecycle Markers, Program Init, and Frame Root Semantics Decision.md`
3. `Published Entrypoint, Synthetic Wrapper, and FRAME_RET Ownership Decision.md`
4. `Globals and Lifecycle Lowering to IRBackend and IRVM Decision.md`
5. `Diagnostics, Manifest Propagation, and Conformance Coverage Decision.md`
## Scope
1. Atualizar:
- PBS 3,
- PBS 4,
- PBS 7,
- PBS 9,
- PBS 11,
- PBS 12,
- PBS 13.
2. Atualizar:
- General 15,
- General 20.
3. Fixar normativamente:
- `declare global`,
- `[Init]`,
- `[Frame]`,
- `[InitAllowed]`,
- wrapper publicado,
- `FRAME_RET` no wrapper,
- entrypoint fisico `0`,
- `manifest.json` sem `entrypoint`.
## Non-Goals
1. Nao alterar parser, AST classes ou semantics code.
2. Nao implementar lowering.
3. Nao adicionar fixtures executaveis nesta PR.
4. Nao produzir `learn`.
## Method
1. Aplicar as decisions 19.x sem reabrir arquitetura.
2. Escrever os contratos em ingles normativo e com terminologia uniforme.
3. Fazer o corte documental completo do antigo modelo nominal de entrypoint.
4. Nomear explicitamente dependencias cross-domain quando a spec PBS depender do runtime protocol ja aceito.
## Acceptance Criteria
1. Nenhuma spec normativa relevante da linha PBS/general contradiz as decisions 19.x.
2. `declare global`, `[Init]`, `[Frame]` e `[InitAllowed]` aparecem com semantica consistente entre syntax, AST e static semantics.
3. O publication contract normativo aponta para wrapper sintetico em `func_id = 0`.
4. O `manifest.json` deixa de carregar autoridade de entrypoint nas specs PBS.
5. As specs gerais de handoff refletem o wrapper e o entrypoint fisico `0`.
## Tests
1. Revisao editorial integral dos documentos afetados.
2. Se houver harness de spec-to-test matrix para as specs gerais/pbs, mantelo verde.
## Affected Documents
1. `docs/compiler/pbs/specs/3. Core Syntax Specification.md`
2. `docs/compiler/pbs/specs/4. Static Semantics Specification.md`
3. `docs/compiler/pbs/specs/7. Cartridge Manifest and Runtime Capabilities Specification.md`
4. `docs/compiler/pbs/specs/9. Dynamic Semantics Specification.md`
5. `docs/compiler/pbs/specs/11. AST Specification.md`
6. `docs/compiler/pbs/specs/12. Diagnostics Specification.md`
7. `docs/compiler/pbs/specs/13. Lowering IRBackend Specification.md`
8. `docs/compiler/general/specs/15. Bytecode and PBX Mapping Specification.md`
9. `docs/compiler/general/specs/20. IRBackend to IRVM Lowering Specification.md`
## Open Questions
1. Nenhuma. Esta PR e de propagacao normativa.

View File

@ -1,74 +0,0 @@
# PR-19.2 - Infra DependencyGraphAnaliser Extraction and Module Cutover
## Briefing
As decisions da familia `19` fixaram que modules e globals compartilham o mesmo kernel estrutural de analise de dependencias, vindo de um refactor do algoritmo atual de modules para `DependencyGraphAnaliser` em `util.structures`.
Esta PR faz somente esse corte de infra:
1. extrair o kernel estrutural reutilizavel;
2. migrar o uso atual de modules para esse novo componente;
3. deixar a superficie pronta para a futura aplicacao no graph de globals.
## Target
Introduzir um analizador estrutural generico para:
1. topological ordering,
2. deterministic traversal,
3. cycle detection,
4. e, quando util, exposicao de SCC/path para diagnostics.
## Dependencies
Prerequisitos diretos:
1. `Globals Surface, Identity, and Module Boundaries Decision.md`
## Scope
1. Extrair o algoritmo atual de dependency ordering de modules para `DependencyGraphAnaliser`.
2. Definir uma API estrutural baseada em nos canonicos e edges preconstruidas.
3. Migrar a linha atual de modules para usar esse componente comum.
4. Preservar comportamento observavel dos diagnostics de modules.
## Non-Goals
1. Nao introduzir ainda globals no pipeline semantico.
2. Nao misturar semantica de modules com semantica de globals.
3. Nao alterar parser ou AST.
4. Nao alterar diagnostics user-facing da linha de globals nesta PR.
## Method
1. Extrair apenas o kernel estrutural; sem abstrair semantica de descoberta de edges.
2. Manter cada dominio responsavel por:
- nos canonicos,
- edges,
- mapeamento para diagnostics.
3. Garantir regressao zero para a linha atual de dependency ordering de modules.
## Acceptance Criteria
1. Existe um `DependencyGraphAnaliser` reutilizavel em infra `util.structures`.
2. Modules passam a usar esse componente sem mudar o contrato observavel atual.
3. O componente nao carrega conhecimento de modulo, global ou PBS-specific semantics.
4. A futura linha de globals consegue consumir o novo kernel sem novo refactor estrutural.
## Tests
1. Testes atuais de dependency ordering e cycle detection de modules permanecem verdes.
2. Testes unitarios diretos do `DependencyGraphAnaliser` cobrem:
- DAG simples,
- ciclo,
- ordering deterministico,
- graph desconexo.
## Affected Artifacts
1. `prometeu-deps` e/ou infra estrutural equivalente
2. fases atuais que usam o algoritmo de dependency ordering de modules
## Open Questions
1. A exposicao de SCC/path pode ser minima nesta PR, desde que nao force novo refactor na PR-19.5.

View File

@ -1,70 +0,0 @@
# PR-19.3 - PBS Parser and AST for Globals, Barrel, and Lifecycle Markers
## Briefing
Depois do corte normativo e do refactor estrutural do dependency graph, PBS precisa aceitar a nova surface da familia `19` no frontend sintatico e no AST:
1. `declare global`,
2. entradas `global` em `mod.barrel`,
3. atributos `[Init]` e `[Frame]`.
Esta PR faz o corte parser+AST, sem ainda fechar toda a semantica.
## Target
Estender parser e AST para suportar:
1. declaracoes `global`,
2. barrel declarations `mod global` / `pub global`,
3. markers `[Init]` e `[Frame]` sobre `fn name() -> void`.
## Dependencies
Prerequisitos diretos:
1. `PR-19.1`
2. `PR-19.2`
## Scope
1. Atualizar lexer/parser/top-level declaration parsing conforme necessario.
2. Atualizar AST model para representar globals e markers de lifecycle.
3. Atualizar barrel AST para distinguir `global` de `const`.
4. Preservar spans e attribution adequados.
## Non-Goals
1. Nao validar ainda dependency graph de globals.
2. Nao validar ainda `[InitAllowed]` em host methods.
3. Nao implementar lowering.
4. Nao implementar published wrapper.
## Method
1. Introduzir novos nodes/surfaces com identidade explicita no AST.
2. Reusar padroes atuais de attributes/markers sem heuristicas textuais.
3. Preservar recovery e diagnosticos sintaticos existentes.
## Acceptance Criteria
1. Parser aceita `declare global Name: T = expr;`.
2. Parser aceita `mod global Name;` e `pub global Name;`.
3. AST distingue `global` de `const`.
4. AST registra `[Init]` e `[Frame]` como markers explicitos.
5. Spans e recovery permanecem defensaveis.
## Tests
1. Fixtures positivas de parse para `declare global`, barrel `global`, `[Init]` e `[Frame]`.
2. Fixtures negativas de parse para formas claramente malformed.
3. Regressao do conjunto atual de parser/AST.
## Affected Artifacts
1. parser PBS
2. AST model PBS
3. testes de parser/AST
## Open Questions
1. Nenhuma. A semantica fina fica para as PRs 19.4 a 19.6.

View File

@ -1,76 +0,0 @@
# PR-19.4 - PBS Semantics for Global Surface, Identity, and Collision Validation
## Briefing
Com parser e AST aceitando a nova surface, a primeira frente semantica precisa fechar o contrato local de `declare global`:
1. categoria declarativa distinta de `const`,
2. regras de namespace e colisao,
3. barrel/import visibility,
4. admissibilidade local do initializer.
Esta PR nao fecha ainda ordering nem ciclo entre globals.
## Target
Implementar validacao semantica para:
1. `declare global` como categoria propria,
2. barrel `global`,
3. colisao entre `fn`, `service`, `global` e `const`,
4. alias obrigatorio em imports quando houver conflito,
5. formas suportadas e nao suportadas no initializer.
## Dependencies
Prerequisitos diretos:
1. `PR-19.1`
2. `PR-19.3`
## Scope
1. Resolver `global` no value namespace sem colapsar categoria com `const`.
2. Enforcar collisions compile-time entre top-level visible symbols.
3. Validar import through `global` barrel entry.
4. Validar formas proibidas no initializer de `global`.
## Non-Goals
1. Nao construir ainda o dependency graph entre globals.
2. Nao validar lifecycle markers.
3. Nao implementar lowering.
## Method
1. Introduzir validacao de declaracao e linking local antes do graph global.
2. Emitir diagnosticos diretamente nos spans reais do codigo do usuario.
3. Tratar barrel/import como autoridade de visibilidade para globals.
## Acceptance Criteria
1. `global` e `const` permanecem semanticamente distintos.
2. Collisions entre `fn` / `service` / `global` / `const` geram erro compile-time.
3. Alias e exigido quando import criaria shadowing invalido.
4. Initializers proibidos de `global` sao rejeitados com diagnostico especifico.
5. Imports de global so resolvem via barrel `global`.
## Tests
1. Fixtures positivas para globals simples, `new`, member-value e import por barrel `global`.
2. Fixtures negativas para:
- collision cross-category,
- import sem alias quando exigido,
- `fn` no initializer,
- `if` no initializer,
- `some(...)` / `none`.
## Affected Artifacts
1. validadores semanticos PBS
2. linking/import resolution PBS
3. testes de semantics/declarations
## Open Questions
1. Nenhuma. Dependency graph fica para `PR-19.5`.

View File

@ -1,66 +0,0 @@
# PR-19.5 - PBS Semantics for Global Dependency Graph and Cycle Validation
## Briefing
Depois da superficie semantica local de `global`, PBS precisa implementar o ordering deterministico e a deteccao de ciclos entre globals usando o kernel compartilhado `DependencyGraphAnaliser`.
Esta PR fecha a parte de semantica que transforma leituras em initializers no graph canonico de globals.
## Target
Implementar:
1. nos canonicos de globals por owner module,
2. edges derivadas de leitura de globals em initializers,
3. ordering deterministico independente de source-file order,
4. diagnostico de ciclo entre globals.
## Dependencies
Prerequisitos diretos:
1. `PR-19.2`
2. `PR-19.4`
## Scope
1. Construir o graph semantico de globals.
2. Resolver alias/import para owner canonico.
3. Reusar `DependencyGraphAnaliser` como kernel estrutural.
4. Emitir diagnostico de ciclo com caminho canonicamente util quando possivel.
## Non-Goals
1. Nao validar ainda `[Init]` / `[Frame]`.
2. Nao implementar init sintetico de modulo.
3. Nao implementar lowering.
## Method
1. Modelar cada global como no canonico `(module, global_name)` ou equivalente interno estavel.
2. Criar edge quando initializer depende do valor materializado de outro global.
3. Usar ordering deterministico para fixar ordem de materializacao.
4. Manter source-file order fora da semantica.
## Acceptance Criteria
1. Ordering de globals e estavel e independe de ordem textual de arquivos.
2. Imports e aliases nao quebram identidade canonica do storage owner.
3. Ciclos intra-modulo e inter-modulo sao detectados como compile-time error.
4. Diagnostics apontam para globals reais, nao para estrutura sintetica.
## Tests
1. Fixtures positivas para dependency chains intra e inter-modulo.
2. Fixtures que provem mesma ordem mesmo com source-file order trocada.
3. Fixtures negativas para ciclos simples e ciclos via import/alias.
## Affected Artifacts
1. semantica de globals PBS
2. `DependencyGraphAnaliser` consumers
3. testes de dependency ordering/cycle diagnostics
## Open Questions
1. Nenhuma. A integracao com module/project init fica para `PR-19.6`.

View File

@ -1,82 +0,0 @@
# PR-19.6 - PBS Semantics for Lifecycle Markers, Init Ordering, and InitAllowed Validation
## Briefing
Com globals e seu dependency graph fechados, a ultima frente semantica da familia `19` precisa validar a camada de lifecycle:
1. `[Init]`,
2. `[Frame]`,
3. ordenacao por arquivo/modulo/projeto,
4. e admissibilidade de host calls via `[InitAllowed]`.
## Target
Implementar a validacao de:
1. signatures de `[Init]` e `[Frame]`,
2. unicidade e colocacao de `[Frame]`,
3. um `[Init]` por arquivo,
4. elevacao do `[Init]` co-localizado com `[Frame]` para project init,
5. restricao de host calls durante init.
## Dependencies
Prerequisitos diretos:
1. `PR-19.3`
2. `PR-19.5`
## Scope
1. Validar `fn name() -> void` para `[Init]` e `[Frame]`.
2. Validar unicidade de `[Frame]` por projeto executavel.
3. Validar que project init e o `[Init]` no mesmo arquivo do `[Frame]`.
4. Validar que arquivos podem ter no maximo um `[Init]`.
5. Validar host call em init apenas quando o target SDK carregar `[InitAllowed]`.
## Non-Goals
1. Nao implementar ainda wrapper publicado.
2. Nao implementar ainda callables sinteticos de lowering.
3. Nao produzir ainda artifacts de conformance finais.
## Method
1. Construir a semantica de lifecycle em cima do ordering ja definido para globals.
2. Tratar module init e project init como diferenca de ordenacao e papel, nao de syntax.
3. Validar `[InitAllowed]` somente em host methods da SDK.
## Acceptance Criteria
1. `[Init]` e `[Frame]` exigem `fn name() -> void`.
2. Existe exatamente um `[Frame]` por projeto executavel.
3. `project init` e identificado apenas no arquivo do `[Frame]`.
4. Um arquivo nao pode declarar mais de um `[Init]`.
5. Host calls em init sem `[InitAllowed]` sao rejeitadas.
6. Uso invalido de `[InitAllowed]` e rejeitado.
## Tests
1. Fixtures positivas para:
- file `[Init]`,
- project `[Init]`,
- `[Frame]`,
- loops em init,
- host call admissivel com `[InitAllowed]`.
2. Fixtures negativas para:
- assinatura invalida,
- multiplos `[Frame]`,
- project init fora do arquivo do `[Frame]`,
- multiplos `[Init]` no arquivo,
- host call sem `[InitAllowed]`,
- `[InitAllowed]` em target invalido.
## Affected Artifacts
1. validadores semanticos/lifecycle PBS
2. admission de host methods em init
3. testes de lifecycle e diagnostics
## Open Questions
1. Nenhuma. O passo seguinte e lowering.

View File

@ -1,70 +0,0 @@
# PR-19.7 - PBS Lowering for IRBackend Globals and Synthetic Callable Model
## Briefing
As decisions de topic `19` fixaram que globals e artifacts de lifecycle precisam ficar explicitos no `IRBackend`, sem materializacao tardia implicita.
Esta PR faz o primeiro corte de lowering:
1. introduz globals explicitos no handoff,
2. introduz callables sinteticos com kind proprio,
3. introduz origin metadata sintetica suficiente para remapear diagnosticos.
## Target
Implementar no lowering PBS -> `IRBackend`:
1. modelagem explicita de backend globals,
2. distincao entre callables userland e callables sinteticos,
3. kinds sinteticos obrigatorios,
4. attribution/origin metadata para artifacts sinteticos.
## Dependencies
Prerequisitos diretos:
1. `PR-19.1`
2. `PR-19.5`
3. `PR-19.6`
## Scope
1. Introduzir globals explicitos no `IRBackend`.
2. Introduzir `FILE_INIT_FRAGMENT`, `MODULE_INIT`, `PROJECT_INIT` e `PUBLISHED_FRAME_WRAPPER` como identidade estrutural.
3. Introduzir `SyntheticOrigin` ou equivalente.
4. Preservar remap para spans reais quando houver origem defensavel.
## Non-Goals
1. Nao publicar ainda o wrapper final em `func_id = 0`.
2. Nao fechar ainda `FRAME_RET` ownership path.
3. Nao fechar ainda conformance final.
## Method
1. Modelar globals e callables sinteticos como first-class artifacts.
2. Evitar conventions baseadas apenas em nome textual.
3. Garantir que diagnosticos prefiram spans reais em vez de spans sinteticos.
## Acceptance Criteria
1. `IRBackend` passa a carregar globals explicitamente.
2. Callables sinteticos possuem class identity observavel.
3. Artifacts sinteticos carregam attribution suficiente para remap de diagnosticos.
4. O lowering nao depende de magic late-stage para globals/lifecycle.
## Tests
1. Fixtures de lowering com inspecao do `IRBackend`.
2. Verificacao de kinds sinteticos presentes.
3. Verificacao de origin metadata e remap defensavel.
## Affected Artifacts
1. lowering PBS -> `IRBackend`
2. modelo `IRBackend`
3. testes de lowering/attribution
## Open Questions
1. Nenhuma. Wrapper publication fica para `PR-19.8`.

View File

@ -1,70 +0,0 @@
# PR-19.8 - PBS Lowering for Published Wrapper, Entrypoint Zero, and FRAME_RET
## Briefing
Com globals e callables sinteticos explicitos no `IRBackend`, a proxima PR fecha a publicacao executavel da linha `19`:
1. wrapper sintetico publicado,
2. boot guard one-shot,
3. project/module init orchestration,
4. `[Frame]` do usuario como root logico,
5. `FRAME_RET` no wrapper,
6. entrypoint fisico `0`.
## Target
Implementar a publicacao executavel final alinhada as decisions `19.2`, `19.3` e `19.4`.
## Dependencies
Prerequisitos diretos:
1. `PR-19.7`
2. runtime boot protocol ja implementado/alinhado fora deste dominio
## Scope
1. Materializar `BOOT_GUARD` oculto.
2. Compor file init fragments, module init, project init e user `[Frame]` no wrapper final.
3. Publicar o wrapper como root fisico em `func_id = 0`.
4. Mover `FRAME_RET` para o wrapper.
5. Remover qualquer dependencia restante de autoridade de entrypoint em `FrontendSpec` para PBS.
## Non-Goals
1. Nao alterar runtime nesta PR.
2. Nao produzir `learn`.
3. Nao fechar sozinho toda a matriz de conformance final.
## Method
1. Compor o wrapper em ordem semantica fechada nas decisions.
2. Garantir one-shot boot via hidden guard.
3. Tratar `[Frame]` como callable logical-root invocado pelo wrapper, nao como entrypoint fisico publicado.
## Acceptance Criteria
1. O wrapper sintetico publicado existe no artifact executavel.
2. O wrapper ocupa `func_id = 0`.
3. `FRAME_RET` aparece no wrapper path, nao no final do body do user `[Frame]`.
4. Boot/inits executam uma unica vez.
5. O pipeline PBS deixa de depender de autoridade de entrypoint em `FrontendSpec`.
## Tests
1. Fixtures de artifact/lowering provando:
- wrapper publicado,
- boot guard,
- entrypoint `0`,
- `FRAME_RET` no wrapper.
2. Integracao compiler/runtime se o harness local ja estiver disponivel no studio.
## Affected Artifacts
1. lowering PBS -> `IRBackend`/`IRVM`
2. publication contract no pipeline do compiler
3. pontos PBS que ainda assumam `FrontendSpec` como autoridade de entrypoint
## Open Questions
1. Nenhuma. A evidencia final fica para `PR-19.9`.

Some files were not shown because too many files have changed in this diff Show More