This commit is contained in:
bQUARKz 2026-03-11 07:26:05 +00:00
parent f3f689fbef
commit d7c970a3e2
Signed by: bquarkz
SSH Key Fingerprint: SHA256:Z7dgqoglWwoK6j6u4QC87OveEq74WOhFN+gitsxtkf8
17 changed files with 713 additions and 589 deletions

View File

@ -265,3 +265,10 @@ Nao faz:
- `learn` ensina. - `learn` ensina.
Se um artefato comecar a fazer o trabalho do outro, ele esta errado. Se um artefato comecar a fazer o trabalho do outro, ele esta errado.
## Regra de Idioma
- todo conteudo publicado em `docs/runtime/specs/` deve ser escrito em ingles;
- todo conteudo publicado em `docs/runtime/learn/` deve ser escrito em ingles;
- essa regra vale mesmo quando a discussao, agenda, decision, PR ou conversa com o usuario acontecer em portugues;
- ao editar artefatos existentes em `specs` ou `learn`, corrigir para ingles qualquer trecho residual em outro idioma.

View File

@ -1,24 +1,24 @@
# PROMETEU Learn # PROMETEU Learn
Esta área reúne material didático sobre a máquina PROMETEU. This area contains pedagogical material about the PROMETEU machine.
Ela existe para explicar o modelo mental da fantasy handheld, suas influências, tradeoffs e implicações de design sem contaminar as specs normativas com framing pedagógico. It exists to explain the fantasy handheld's mental model, influences, tradeoffs, and design implications without contaminating the normative specs with pedagogical framing.
## Authority ## Authority
- `docs/runtime/learn/` não é fonte canônica de contrato técnico. - `docs/runtime/learn/` is not a canonical source of technical contract.
- As superfícies normativas da máquina vivem em [`../specs/`](../specs/README.md). - The machine's normative surfaces live in [`../specs/`](../specs/README.md).
- As invariantes internas da VM/runtime vivem em [`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md). - The VM/runtime's internal invariants live in [`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md).
## Reading Order ## Reading Order
Se a pessoa esta entrando agora no modelo da maquina, a ordem mais util e: If someone is entering the machine model now, the most useful order is:
1. [`mental-model-time-and-cycles.md`](mental-model-time-and-cycles.md) 1. [`mental-model-time-and-cycles.md`](mental-model-time-and-cycles.md)
2. [`mental-model-portability-and-cross-platform.md`](mental-model-portability-and-cross-platform.md) 2. [`mental-model-portability-and-cross-platform.md`](mental-model-portability-and-cross-platform.md)
3. [`mental-model-observability-and-debugging.md`](mental-model-observability-and-debugging.md) 3. [`mental-model-observability-and-debugging.md`](mental-model-observability-and-debugging.md)
4. [`mental-model-status-first-and-fault-thinking.md`](mental-model-status-first-and-fault-thinking.md) 4. [`mental-model-status-first-and-fault-thinking.md`](mental-model-status-first-and-fault-thinking.md)
5. depois os perifericos e dominios especificos 5. then the peripherals and specific domains
## Core Mental Models ## Core Mental Models
@ -31,13 +31,14 @@ Se a pessoa esta entrando agora no modelo da maquina, a ordem mais util e:
- [`mental-model-gfx.md`](mental-model-gfx.md) - [`mental-model-gfx.md`](mental-model-gfx.md)
- [`mental-model-audio.md`](mental-model-audio.md) - [`mental-model-audio.md`](mental-model-audio.md)
- [`mental-model-asset-management.md`](mental-model-asset-management.md)
- [`mental-model-input.md`](mental-model-input.md) - [`mental-model-input.md`](mental-model-input.md)
- [`mental-model-touch.md`](mental-model-touch.md) - [`mental-model-touch.md`](mental-model-touch.md)
- [`mental-model-save-memory-and-memcard.md`](mental-model-save-memory-and-memcard.md) - [`mental-model-save-memory-and-memcard.md`](mental-model-save-memory-and-memcard.md)
## Historical Snapshots ## Historical Snapshots
Estes arquivos preservam o racional de decisions ja absorvidas por specs e/ou implementacao. Eles sao uteis para contexto, mas nao devem ser lidos como contrato atual primario. These files preserve the rationale of decisions already absorbed by specs and/or implementation. They are useful for context, but they should not be read as the primary current contract.
- [`historical-gfx-status-first-fault-and-return-contract.md`](historical-gfx-status-first-fault-and-return-contract.md) - [`historical-gfx-status-first-fault-and-return-contract.md`](historical-gfx-status-first-fault-and-return-contract.md)
- [`historical-audio-status-first-fault-and-return-contract.md`](historical-audio-status-first-fault-and-return-contract.md) - [`historical-audio-status-first-fault-and-return-contract.md`](historical-audio-status-first-fault-and-return-contract.md)
@ -47,34 +48,34 @@ Estes arquivos preservam o racional de decisions ja absorvidas por specs e/ou im
## Naming Convention ## Naming Convention
- `mental-model-*.md`: ponto de entrada didatico e consolidado. - `mental-model-*.md`: consolidated pedagogical entry point.
- `historical-*.md`: snapshot historico, racional aposentado ou consolidado em outro lugar. - `historical-*.md`: historical snapshot, retired rationale, or material consolidated elsewhere.
- `README.md`: mapa e navegacao da area. - `README.md`: area map and navigation.
## Rules ## Rules
- material em `learn` pode explicar, comparar, ensinar e contextualizar; - material in `learn` may explain, compare, teach, and provide context;
- material em `learn` não deve redefinir o contrato normativo dos specs; - material in `learn` must not redefine the normative contract of the specs;
- quando um tema tiver spec e guia didático, o guia deve apontar para o spec correspondente. - when a topic has both a spec and a pedagogical guide, the guide should point to the corresponding spec;
- quando houver snapshot historico e guia consolidado sobre o mesmo tema, o guia consolidado deve ser o ponto de entrada. - when there is both a historical snapshot and a consolidated guide for the same topic, the consolidated guide should be the entry point;
- snapshots devem deixar claro que sao historicos e apontar para as anchors normativas atuais. - snapshots must make clear that they are historical and point to the current normative anchors.
## When To Create A Pair ## When To Create A Pair
Criar um par `spec` + `learn` quando o tema: Create a `spec` + `learn` pair when the topic:
- precisa de contrato técnico estável e também de modelo mental; - needs a stable technical contract and a mental model;
- tem forte carga histórica, pedagógica ou de design rationale; - has strong historical, pedagogical, or design-rationale weight;
- corre risco de virar manifesto dentro do spec normativo; - risks turning into manifesto text inside the normative spec;
- exige exemplos, comparações ou intuição que não pertencem ao contrato. - requires examples, comparisons, or intuition that do not belong in the contract.
Se o tema for pequeno e estritamente contratual, o capítulo pode nascer só em `specs`. If the topic is small and strictly contractual, the chapter may live only in `specs`.
## Learn Refactoring Rule ## Learn Refactoring Rule
Quando `learn` acumular snapshots demais: When `learn` accumulates too many snapshots:
- consolidar ideias repetidas em guias didaticos maiores; - consolidate repeated ideas into larger pedagogical guides;
- reduzir redundancia cronologica; - reduce chronological redundancy;
- manter snapshots apenas como rastro historico e backlink; - keep snapshots only as historical trace and backlink;
- reorganizar por modelo mental, nao por ordem de decisao. - reorganize by mental model, not by decision order.

View File

@ -11,69 +11,69 @@ Current normative anchors:
Accepted Accepted
## Contexto ## Context
A agenda `006-asset-fault-semantics-and-surface.md` evidenciou inconsistencia no dominio `asset`: Agenda `006-asset-fault-semantics-and-surface.md` exposed inconsistency in the `asset` domain:
- `asset.status` ja usa status numerico; - `asset.status` already used numeric status;
- `asset.load` ainda escalava erro operacional para `Panic`; - `asset.load` was still escalating operational failure to `Panic`;
- `asset.commit`/`asset.cancel` eram `void` com no-op silencioso para varios casos. - `asset.commit`/`asset.cancel` were `void` with silent no-op in several cases.
Para alinhar o dominio com `16a`, foi fechado contrato status-first para `asset`. To align the domain with `16a`, a status-first contract was adopted for `asset`.
## Decisao ## Decision
### 1. Fronteira de fault class em `asset` ### 1. Fault-class boundary in `asset`
`asset` segue: `asset` follows:
- `Trap`: violacao estrutural de ABI/chamada (tipo, aridade, capability, shape). - `Trap`: structural ABI/call violation (type, arity, capability, shape).
- `status` (inteiro): erro operacional recuperavel de dominio. - `status` (integer): recoverable operational domain error.
- `Panic`: apenas quebra de invariante interna de runtime/host. - `Panic`: internal runtime/host invariant break only.
### 2. Surface canonica do dominio ### 2. Canonical domain surface
A surface final do MVP fica: The final MVP surface is:
- `asset.load(name, kind, slot) -> (status:int, handle:int)` - `asset.load(name, kind, slot) -> (status:int, handle:int)`
- `asset.status(handle) -> status:int` - `asset.status(handle) -> status:int`
- `asset.commit(handle) -> status:int` - `asset.commit(handle) -> status:int`
- `asset.cancel(handle) -> status:int` - `asset.cancel(handle) -> status:int`
Regras: Rules:
- `handle` so e valido quando `status == ASSET_OK`; - `handle` is only valid when `status == ASSET_OK`;
- em falha de `load`, `handle` deve ser `0`. - on `load` failure, `handle` must be `0`.
### 3. No-op silencioso proibido ### 3. Silent no-op forbidden
No-op silencioso nao e permitido para operacoes com erro operacional possivel. Silent no-op is not allowed for operations with possible operational error.
Casos como: Cases such as:
- handle desconhecido; - unknown handle;
- transicao invalida de lifecycle; - invalid lifecycle transition;
- slot invalido; - invalid slot;
- asset ausente; - missing asset;
devem retornar `status` explicito. must return explicit `status`.
### 4. `asset.load` (request path) ### 4. `asset.load` (request path)
Falhas operacionais de request devem virar `status`, incluindo: Operational request failures must become `status`, including:
- `ASSET_NOT_FOUND`; - `ASSET_NOT_FOUND`;
- `SLOT_KIND_MISMATCH`; - `SLOT_KIND_MISMATCH`;
- `SLOT_INDEX_INVALID`; - `SLOT_INDEX_INVALID`;
- `BACKEND_ERROR`. - `BACKEND_ERROR`.
`Panic` nao deve ser usado para falha operacional de `load`. `Panic` must not be used for operational `load` failure.
### 5. `asset.status` (lifecycle path) ### 5. `asset.status` (lifecycle path)
`asset.status` permanece a fonte de verdade do lifecycle assíncrono. `asset.status` remains the source of truth for the asynchronous lifecycle.
Codigos de lifecycle devem cobrir: Lifecycle codes should cover:
- `PENDING` - `PENDING`
- `LOADING` - `LOADING`
@ -83,47 +83,47 @@ Codigos de lifecycle devem cobrir:
- `ERROR` - `ERROR`
- `UNKNOWN_HANDLE` - `UNKNOWN_HANDLE`
### 6. `asset.commit` e `asset.cancel` ### 6. `asset.commit` and `asset.cancel`
Ambas operacoes devem retornar `status`. Both operations must return `status`.
Tabela minima de resposta: Minimum response table:
- `ASSET_OK` (acao aceita/concluida para o estado atual) - `ASSET_OK` (action accepted/completed for the current state)
- `UNKNOWN_HANDLE` - `UNKNOWN_HANDLE`
- `INVALID_STATE` - `INVALID_STATE`
### 7. Relacao com dominio `bank` ### 7. Relationship with the `bank` domain
Erros de residency/slot permanecem no dominio `asset`. Residency/slot errors remain in the `asset` domain.
`bank` permanece dominio de inspecao (`info`, `slot_info`) e nao absorve erros operacionais de mutacao de asset lifecycle. `bank` remains an inspection domain (`info`, `slot_info`) and does not absorb operational errors from asset lifecycle mutation.
### 8. Compatibilidade e migracao ### 8. Compatibility and migration
Nao ha requisito de compatibilidade retroativa para esta mudanca. There is no backward-compatibility requirement for this change.
E permitido: It is allowed to:
- alterar `ret_slots` de `asset.load`, `asset.commit`, `asset.cancel`; - change `ret_slots` for `asset.load`, `asset.commit`, and `asset.cancel`;
- ajustar registry/loader/dispatch/runtime com o novo contrato; - adjust registry/loader/dispatch/runtime to the new contract;
- regenerar stress test com as assinaturas novas. - regenerate the stress test with the new signatures.
## Consequencias ## Consequences
### Positivas ### Positive
- remove `Panic` operacional indevido do dominio `asset`; - removes improper operational `Panic` from the `asset` domain;
- torna fluxo de lifecycle observavel e consistente; - makes lifecycle flow observable and consistent;
- elimina ambiguidade de no-op em `commit`/`cancel`. - eliminates no-op ambiguity in `commit`/`cancel`.
### Custos ### Costs
- exige migracao de ABI das syscalls `asset`; - requires ABI migration of `asset` syscalls;
- exige atualizacao de testes e artefatos gerados. - requires updates to tests and generated artifacts.
## Follow-up Obrigatorio ## Required Follow-up
- agenda `006-asset-fault-semantics-and-surface.md` deve ser considerada absorvida e removida; - agenda `006-asset-fault-semantics-and-surface.md` should be considered absorbed and removed;
- specs `15` e `16a` devem absorver o contrato final quando a implementacao estiver estavel; - specs `15` and `16a` should absorb the final contract when implementation is stable;
- registry de syscall deve refletir o shape final (`ret_slots`) das operacoes `asset`. - the syscall registry should reflect the final operation shape (`ret_slots`) for `asset`.

View File

@ -11,107 +11,107 @@ Current normative anchors:
Accepted Accepted
## Contexto ## Context
A agenda `005-audio-fault-semantics-and-surface.md` mostrou ambiguidade no dominio `audio`: Agenda `005-audio-fault-semantics-and-surface.md` exposed ambiguity in the `audio` domain:
- no-op/fallback silencioso para falhas operacionais; - silent no-op/fallback for operational failures;
- operacoes `void` mesmo quando ha possibilidade real de falha; - `void` operations even when real failure is possible;
- risco de escalar erro de app para `Panic`. - risk of escalating app errors to `Panic`.
Para alinhar com `16a`, o dominio `audio` adota politica status-first. To align with `16a`, the `audio` domain adopts a status-first policy.
## Decisao ## Decision
### 1. Fronteira de fault class em `audio` ### 1. Fault-class boundary in `audio`
`audio` segue a taxonomia: `audio` follows this taxonomy:
- `Trap`: violacao estrutural de ABI/chamada (tipo, aridade, capability, shape). - `Trap`: structural ABI/call violation (type, arity, capability, shape).
- `status` (inteiro): erro operacional recuperavel de dominio. - `status` (integer): recoverable operational domain error.
- `Panic`: apenas quebra de invariante interna de runtime/host. - `Panic`: internal runtime/host invariant break only.
### 2. Politica de retorno por operacao ### 2. Per-operation return policy
Nem toda syscall precisa retornar `status`. Not every syscall needs to return `status`.
Regra canonica: Canonical rule:
- se a operacao pode falhar operacionalmente, deve retornar `status: int` (`ret_slots >= 1`); - if the operation can fail operationally, it should return `status: int` (`ret_slots >= 1`);
- se a operacao nao possui via real de erro operacional, pode permanecer `void`. - if the operation has no real operational error path, it may remain `void`.
Para o MVP atual: For the current MVP:
- `audio.play` deve retornar `status`; - `audio.play` should return `status`;
- `audio.play_sample` deve retornar `status`. - `audio.play_sample` should return `status`.
### 3. No-op e fallback ### 3. No-op and fallback
No-op silencioso nao e permitido em operacoes com possibilidade de erro operacional. Silent no-op is not allowed in operations with possible operational error.
Fallback implicito tambem nao e permitido quando mascara erro de dominio. Implicit fallback is also not allowed when it masks a domain error.
Exemplos proibidos: Forbidden examples:
- fallback implicito para `bank_id` default quando asset nao e encontrado; - implicit fallback to default `bank_id` when the asset is not found;
- ignorar `voice_id` invalido sem retorno explicito. - ignoring invalid `voice_id` without explicit return.
### 4. Tabela de status por operacao ### 4. Per-operation status table
Cada operacao `audio` que retorna `status` deve declarar codigos inteiros de forma normativa. Each `audio` operation that returns `status` must define integer codes normatively.
Tabela minima para `play`/`play_sample` deve cobrir, quando aplicavel: The minimum table for `play`/`play_sample` should cover, when applicable:
- `OK`; - `OK`;
- `VOICE_INVALID`; - `VOICE_INVALID`;
- `ASSET_NOT_FOUND`; - `ASSET_NOT_FOUND`;
- `SAMPLE_NOT_FOUND`; - `SAMPLE_NOT_FOUND`;
- `ARG_RANGE_INVALID`; - `ARG_RANGE_INVALID`;
- `NO_EFFECT` (somente quando houver sem efeito operacional valido e explicito). - `NO_EFFECT` (only when a valid and explicit no-effect case exists).
### 5. Faixas numericas ### 5. Numeric ranges
Entradas numericas com faixa normativa (`volume`, `pan`, `pitch`) devem ter politica explicita. Numeric inputs with normative ranges (`volume`, `pan`, `pitch`) must have explicit policy.
Quando fora da faixa aceita: When outside the accepted range:
- retornar `status` de erro de faixa; - return range-error `status`;
- nao mascarar como sucesso silencioso. - do not mask it as silent success.
### 6. Higiene de panic ### 6. Panic hygiene
Erros de argumento de app nao devem escalar para `Panic`. App argument errors must not escalate to `Panic`.
Esses casos devem ser classificados como: These cases should be classified as:
- `Trap` (estrutural); ou - `Trap` (structural); or
- `status` (operacional, conforme a operacao). - `status` (operational, according to the operation).
### 7. Compatibilidade e migracao ### 7. Compatibility and migration
Nao ha requisito de compatibilidade retroativa para esta mudanca. There is no backward-compatibility requirement for this change.
E permitido: It is allowed to:
- ajustar assinaturas de syscall `audio` (incluindo `ret_slots`); - adjust `audio` syscall signatures (including `ret_slots`);
- atualizar registry/loader/runtime com o contrato novo; - update registry/loader/runtime with the new contract;
- regenerar o stress test com as assinaturas finais. - regenerate the stress test with the final signatures.
## Consequencias ## Consequences
### Positivas ### Positive
- reduz comportamento silencioso em erros operacionais de audio; - reduces silent behavior in audio operational errors;
- torna chamadas de audio observaveis e testaveis; - makes audio calls observable and testable;
- alinha `audio` com o modelo geral de `16a`. - aligns `audio` with the general `16a` model.
### Custos ### Costs
- exige mudanca de ABI das syscalls de audio; - requires ABI changes to audio syscalls;
- exige atualizacao de testes e artefatos de stress. - requires updates to tests and stress artifacts.
## Follow-up Obrigatorio ## Required Follow-up
- agenda `005-audio-fault-semantics-and-surface.md` deve ser considerada absorvida e removida; - agenda `005-audio-fault-semantics-and-surface.md` should be considered absorbed and removed;
- specs `05` e `16a` devem absorver o contrato final quando a implementacao estiver estavel; - specs `05` and `16a` should absorb the final contract when implementation is stable;
- registry de syscall deve refletir `ret_slots` e codigos de status finais para `audio`. - the syscall registry should reflect the final `ret_slots` and status codes for `audio`.

View File

@ -13,30 +13,30 @@ Current normative anchors:
Accepted Accepted
## Contexto ## Context
Jogos precisam de persistencia previsivel e portavel para save/config/blob, sem acesso amplo ao filesystem. Games need predictable, portable persistence for save/config/blob data without broad filesystem access.
A agenda `013-game-memcard-slots-surface-and-semantics.md` consolidou os inputs de produto: Agenda `013-game-memcard-slots-surface-and-semantics.md` consolidated the product inputs:
- `game` usa `32` slots por jogo; - `game` uses `32` slots per game;
- payload maximo por slot de `32KB`; - maximum payload per slot is `32KB`;
- jogo acessa somente slots do proprio `app_id`; - the game accesses only slots owned by its own `app_id`;
- persistencia explicita com `commit` atomico por slot; - persistence is explicit, with atomic `commit` per slot;
- copia/export/import de saves ocorre fora do jogo (Hub/OS). - save copy/export/import happens outside the game (Hub/OS).
Esta decisao fecha o contrato v1 do perfil `game` usando a decisao `003` como data plane de bytes. This decision closes the v1 contract for the `game` profile while using decision `003` as the byte data plane.
## Decisao ## Decision
### 1. Contrato base de capacidade e ownership ### 1. Base capacity and ownership contract
- cada jogo possui exatamente `32` slots logicos (`0..31`); - each game has exactly `32` logical slots (`0..31`);
- cada slot oferece payload util de ate `32 * 1024` bytes; - each slot offers up to `32 * 1024` bytes of usable payload;
- acesso em userland e restrito ao `app_id` dono do cart carregado; - userland access is restricted to the `app_id` that owns the loaded cart;
- nao existe acesso por path para jogos no v1. - there is no path-based access for games in v1.
### 2. Surface minima de memcard (status-first) ### 2. Minimum memcard surface (status-first)
- `slot_count() -> (status:int, count:int)` - `slot_count() -> (status:int, count:int)`
- `slot_stat(slot:int) -> (status:int, state:int, used_bytes:int, generation:int, checksum:int)` - `slot_stat(slot:int) -> (status:int, state:int, used_bytes:int, generation:int, checksum:int)`
@ -45,17 +45,17 @@ Esta decisao fecha o contrato v1 do perfil `game` usando a decisao `003` como da
- `slot_commit(slot:int) -> status:int` - `slot_commit(slot:int) -> status:int`
- `slot_clear(slot:int) -> status:int` - `slot_clear(slot:int) -> status:int`
Regras: Rules:
- `status` e sempre o primeiro retorno; - `status` is always the first return value;
- operacoes de bytes usam `HeapRef<Bytes>` + janela explicita (`offset`, `max_bytes`/`len`); - byte operations use `HeapRef<Bytes>` plus an explicit window (`offset`, `max_bytes`/`len`);
- shape segue politica de `16a`. - shape follows the policy in `16a`.
### 3. Envelope digital runtime-owned por slot ### 3. Runtime-owned digital envelope per slot
Cada slot mantem metadados canonicos runtime-owned: Each slot keeps canonical runtime-owned metadata:
- `app_id` dono; - owning `app_id`;
- `slot_index`; - `slot_index`;
- `save_uuid`; - `save_uuid`;
- `generation`; - `generation`;
@ -63,36 +63,36 @@ Cada slot mantem metadados canonicos runtime-owned:
- `checksum`; - `checksum`;
- `state` (`EMPTY`, `STAGED`, `COMMITTED`, `CORRUPT`). - `state` (`EMPTY`, `STAGED`, `COMMITTED`, `CORRUPT`).
`generation` e `checksum` nao sao controlados manualmente pela userland: `generation` and `checksum` are not manually controlled by userland:
- `generation` incrementa a cada `slot_commit` bem-sucedido; - `generation` increments on each successful `slot_commit`;
- `checksum` e recalculado pelo runtime no payload persistido. - `checksum` is recalculated by the runtime on the persisted payload.
### 4. Envelope visual para Hub/OS ### 4. Visual envelope for Hub/OS
O slot expoe metadados visuais para UX fora do jogo: The slot exposes visual metadata for UX outside the game:
- `label`; - `label`;
- `subtitle`; - `subtitle`;
- `updated_at` (ou contador logico equivalente); - `updated_at` (or equivalent logical counter);
- `icon_ref` (v1 estatico, formato extensivel para animacao futura). - `icon_ref` (static in v1, extensible to future animation).
### 5. Politica de escrita e atomicidade ### 5. Write policy and atomicity
- `slot_write` altera staging (nao persiste no destino final); - `slot_write` changes staging (it does not persist to the final destination);
- `slot_commit` aplica persistencia atomica por slot; - `slot_commit` applies per-slot atomic persistence;
- sucesso parcial silencioso e proibido; - silent partial success is forbidden;
- em falha de commit, retorna `status` de erro e preserva invariante de atomicidade. - on commit failure, it returns error `status` and preserves the atomicity invariant.
### 6. Fronteira de fault class ### 6. Fault-class boundary
`memcard(game)` segue `16a`: `memcard(game)` follows `16a`:
- `Trap`: erro estrutural (slot fora da faixa, `HeapRef` invalido/dead, janela invalida, shape ABI invalido); - `Trap`: structural error (slot out of range, invalid/dead `HeapRef`, invalid window, invalid ABI shape);
- `status`: erro operacional de dominio; - `status`: operational domain error;
- `Panic`: apenas quebra de invariante interna. - `Panic`: internal invariant break only.
Catalogo minimo de status do dominio: Minimum domain status catalog:
- `OK`; - `OK`;
- `EMPTY`; - `EMPTY`;
@ -104,35 +104,35 @@ Catalogo minimo de status do dominio:
- `UNAVAILABLE`; - `UNAVAILABLE`;
- `INVALID_STATE`. - `INVALID_STATE`.
### 7. Politica de copia/export/import (fora do jogo) ### 7. Copy/export/import policy (outside the game)
- copia/export/import e responsabilidade do Hub/OS; - copy/export/import is a Hub/OS responsibility;
- jogo nao recebe API para copiar slots entre apps; - the game does not receive an API to copy slots between apps;
- v1 valida ownership por `app_id` no import; - v1 validates ownership by `app_id` on import;
- conflito e corrupcao devem ser refletidos por status do dominio e UX do Hub. - conflict and corruption must be reflected through domain status and Hub UX.
### 8. Integracao com storage host ### 8. Integration with host storage
- namespace fisico isolado por `app_id`; - physical namespace isolated by `app_id`;
- representacao fisica por slot e interna ao runtime/host; - physical per-slot representation is internal to the runtime/host;
- persistencia deve usar estrategia atomica (arquivo temporario + flush + rename equivalente da plataforma). - persistence should use an atomic strategy (temporary file + flush + platform-equivalent rename).
## Consequencias ## Consequences
### Positivas ### Positive
- fecha o contrato de save de `game` sem abrir FS amplo; - closes the `game` save contract without opening broad FS access;
- torna copy/export/import um fluxo de sistema (Hub/OS), nao de userland; - makes copy/export/import a system flow (Hub/OS), not a userland flow;
- padroniza integridade/versionamento de slot com `generation` + `checksum`. - standardizes slot integrity/versioning through `generation` + `checksum`.
### Custos ### Costs
- exige implementacao de staging/commit atomico por slot; - requires per-slot staging/atomic commit implementation;
- exige especificacao explicita do formato de export/import no Hub/OS; - requires explicit specification of the export/import format in Hub/OS;
- exige alinhamento com specs de memcard e ABI. - requires alignment with memcard and ABI specs.
## Follow-up Obrigatorio ## Required Follow-up
- a agenda `013-game-memcard-slots-surface-and-semantics.md` deve ser considerada fechada e removida; - agenda `013-game-memcard-slots-surface-and-semantics.md` should be considered closed and removed;
- `specs/08-save-memory-and-memcard.md` deve absorver este contrato (`32 x 32KB`, slots por `app_id`, commit atomico); - `specs/08-save-memory-and-memcard.md` should absorb this contract (`32 x 32KB`, slots by `app_id`, atomic commit);
- `specs/16-host-abi-and-syscalls.md` e `specs/16a-syscall-policies.md` devem absorver a surface e matriz de fault/status. - `specs/16-host-abi-and-syscalls.md` and `specs/16a-syscall-policies.md` should absorb the surface and fault/status matrix.

View File

@ -11,101 +11,101 @@ Current normative anchors:
Accepted Accepted
## Contexto ## Context
A agenda `004-gfx-fault-semantics-and-command-contract.md` consolidou que o dominio `gfx` estava com ambiguidade entre: Agenda `004-gfx-fault-semantics-and-command-contract.md` consolidated that the `gfx` domain had ambiguity between:
- `Trap`/`Panic` desnecessarios para erro operacional; - unnecessary `Trap`/`Panic` for operational errors;
- no-op silencioso; - silent no-op;
- chamadas `void` em operacoes que podem falhar operacionalmente. - `void` calls in operations that may fail operationally.
Para alinhar com `16a`, foi decidido fechar uma politica status-first no dominio `gfx`. To align with `16a`, a status-first policy was adopted for the `gfx` domain.
## Decisao ## Decision
### 1. Fronteira de fault class em `gfx` ### 1. Fault-class boundary in `gfx`
`gfx` segue a taxonomia: `gfx` follows this taxonomy:
- `Trap`: violacao estrutural de ABI/chamada (tipo, aridade, capability, shape). - `Trap`: structural ABI/call violation (type, arity, capability, shape).
- `status` (inteiro): erro operacional recuperavel de dominio. - `status` (integer): recoverable operational domain error.
- `Panic`: apenas quebra de invariante interna de runtime/host. - `Panic`: internal runtime/host invariant break only.
### 2. Politica de retorno por operacao ### 2. Per-operation return policy
Nem toda syscall `gfx` precisa retornar `status`. Not every `gfx` syscall needs to return `status`.
Regra canonica: Canonical rule:
- se a operacao pode produzir erro operacional observavel, deve retornar `status: int` (`ret_slots >= 1`); - if the operation can produce observable operational error, it should return `status: int` (`ret_slots >= 1`);
- se a operacao nao possui via real de erro operacional, pode permanecer `void`. - if the operation has no real operational error path, it may remain `void`.
### 3. Tabela de status por operacao ### 3. Per-operation status table
Cada operacao `gfx` que retorna `status` deve declarar tabela de codigos inteiros propria. Each `gfx` operation that returns `status` must declare its own integer code table.
A tabela deve cobrir, quando aplicavel: The table should cover, when applicable:
- recurso ausente (`asset_not_found`); - missing resource (`asset_not_found`);
- indice invalido (`invalid_sprite_index`); - invalid index (`invalid_sprite_index`);
- argumento fora de faixa (`invalid_arg_range`); - out-of-range argument (`invalid_arg_range`);
- sem efeito operacional (`no_effect`), quando houver. - no operational effect (`no_effect`), when applicable.
### 4. Politica de no-op ### 4. No-op policy
No-op silencioso nao e permitido para operacoes com possibilidade de erro operacional. Silent no-op is not allowed in operations that can fail operationally.
Quando houver falha/ignoracao operacional: When there is operational failure/ignoring:
- a chamada deve retornar `status` explicito; - the call must return explicit `status`;
- o resultado nao pode ser mascarado como sucesso implicito. - the result must not be disguised as implicit success.
### 5. Contrato de `gfx.set_sprite` ### 5. `gfx.set_sprite` contract
`set_sprite` nao deve depender de fallback implicito para banco default. `set_sprite` must not depend on implicit fallback to a default bank.
Casos como: Cases such as:
- `asset_name` ausente/nao encontrado; - missing/not-found `asset_name`;
- `sprite_index` fora de faixa; - `sprite_index` out of range;
- `palette_id`/`priority` fora da faixa; - `palette_id`/`priority` out of range;
devem ser reportados por `status` conforme a tabela da operacao. must be reported via `status` according to the operation table.
### 6. Higiene de panic ### 6. Panic hygiene
Erros de argumento de app nao devem escalar para `Panic`. App argument errors must not escalate to `Panic`.
Helpers e dispatch devem mapear esses casos para: Helpers and dispatch must map those cases to:
- `Trap` (quando estrutural); ou - `Trap` (when structural); or
- `status` (quando operacional, para operacoes com retorno de status). - `status` (when operational, for operations with status return).
### 7. Compatibilidade e migracao ### 7. Compatibility and migration
Nao ha requisito de compatibilidade retroativa para esta mudanca. There is no backward-compatibility requirement for this change.
E permitido: It is allowed to:
- ajustar assinaturas de syscall `gfx` (especialmente `ret_slots`); - adjust `gfx` syscall signatures (especially `ret_slots`);
- atualizar registry/loader/runtime em linha com a matriz final; - update registry/loader/runtime in line with the final matrix;
- regenerar artefatos de stress test com o contrato novo. - regenerate stress-test artifacts with the new contract.
## Consequencias ## Consequences
### Positivas ### Positive
- reduz `Trap`/`Panic` indevidos no dominio grafico; - reduces improper `Trap`/`Panic` in the graphics domain;
- elimina comportamento silencioso em comandos com erro operacional; - eliminates silent behavior in commands with operational error;
- torna contratos de retorno mais consistentes e testaveis. - makes return contracts more consistent and testable.
### Custos ### Costs
- exige atualizacao de metadata de syscall e dispatch; - requires updates to syscall metadata and dispatch;
- exige atualizacao dos testes e do gerador de stress. - requires updates to tests and the stress generator.
## Follow-up Obrigatorio ## Required Follow-up
- agenda `004-gfx-fault-semantics-and-command-contract.md` deve ser considerada absorvida e removida; - agenda `004-gfx-fault-semantics-and-command-contract.md` should be considered absorbed and removed;
- specs `04` e `16a` devem absorver o contrato final quando a implementacao estiver estavel; - specs `04` and `16a` should absorb the final contract when implementation is stable;
- a matriz final por syscall (`void` vs `status`) e a tabela de codigos devem ser refletidas no registry de syscalls. - the final per-syscall matrix (`void` vs `status`) and code table should be reflected in the syscall registry.

View File

@ -0,0 +1,116 @@
# Asset Management Mental Model
Status: pedagogical
Companion specs:
- [`../specs/13-cartridge.md`](../specs/13-cartridge.md)
- [`../specs/15-asset-management.md`](../specs/15-asset-management.md)
Origin decision: [`../decisions/011-assets-pa-autocontained-runtime-contract.md`](../decisions/011-assets-pa-autocontained-runtime-contract.md)
PROMETEU treats assets as a self-contained cart artifact, not as metadata scattered across `manifest.json`, the loader, and the runtime.
## One Runtime Artifact
The right mental model is:
- `manifest.json` identifies the cart and its capabilities;
- `assets.pa` carries the runtime-facing asset contract;
- the runtime consumes that contract without depending on auxiliary tooling artifacts.
That avoids mixing:
- cart editorial metadata;
- internal packer details;
- runtime loading policy.
## Why `assets.pa` Owns The Asset Contract
`assets.pa` puts into the same binary:
- a fixed prelude to locate the header;
- a JSON header that is easy to inspect;
- the cold binary payload of the assets.
That split exists to preserve two properties at the same time:
- fixed cost to open and validate the artifact;
- a readable header that is simple to debug.
The important point is not the format by itself. The important point is that the runtime finds everything it needs for assets behind one stable boundary.
## `preload` Is Not `asset_table`
Both live in the header, but they serve different roles:
- `asset_table` is the live asset-resolution index for the entire execution;
- `preload` is only a boot-time instruction for initial residency.
A short way to think about it:
- `asset_table` stays;
- `preload` passes.
That prevents the runtime from treating preload as permanent metadata when, in practice, it is only an initial loading impulse.
## Payload-Relative Thinking
`AssetEntry` offsets are relative to the start of the payload, not to the start of the whole file.
That choice preserves the semantics of the `asset` domain:
- `AssetEntry` describes where content sits inside the cold-byte region;
- the outer envelope can evolve without contaminating each entry with container details.
The runtime only needs to resolve:
```text
payload_base + entry.offset
```
## Slice-First Loading
The correct loading mental model is not:
```text
ROM -> load the whole assets.pa into RAM -> look up asset
```
The correct flow is:
```text
ROM -> open_slice -> CODEX/decode -> Bank
```
or, when the codec requires it:
```text
ROM -> open_slice -> temporary blob -> CODEX/decode -> Bank
```
That matters because PROMETEU was designed for low-cost hardware. Keeping the whole payload resident as a baseline wastes memory, couples IO to a monolithic blob, and weakens the runtime's real boundary.
## `OP_MODE` Belongs To The Runtime
The cart describes the asset. The runtime decides how to consume the slice.
In v1, that decision comes from the `codec`/CODEX:
- some assets can be read directly from the limited view;
- others require temporary materialization before decode.
The key point is to separate:
- the asset storage contract;
- the operational strategy for reading and decode.
## Why This Fits PROMETEU
This model fits the project well because:
- it reduces dependence on metadata scattered through `manifest.json`;
- it separates `packer`, `shipper`, and runtime more cleanly;
- it allows early failure when `Capability::Asset` requires `assets.pa`;
- it preserves a runtime that can run on desktop and on low-cost dedicated hardware.
When thinking about assets in PROMETEU, think less in terms of "a manifest with attachments" and more in terms of "a cart with an asset artifact that explains itself".

View File

@ -3,25 +3,25 @@
Status: pedagogical Status: pedagogical
Companion spec: [`../specs/05-audio-peripheral.md`](../specs/05-audio-peripheral.md) Companion spec: [`../specs/05-audio-peripheral.md`](../specs/05-audio-peripheral.md)
O modelo mental correto para áudio em PROMETEU é o de um periférico ativo com orçamento, não o de “som automático”. The right mental model for audio in PROMETEU is an active peripheral with a budget, not "automatic sound".
## Philosophy ## Philosophy
Som: Sound:
- consome tempo; - consumes time;
- consome memória; - consumes memory;
- usa canais finitos; - uses finite channels;
- depende de comandos explícitos. - depends on explicit commands.
Isso aproxima PROMETEU de consoles e arcades clássicos em que o jogo “conversa” com um bloco de áudio com regras próprias. That brings PROMETEU closer to classic consoles and arcades where the game "talks" to an audio block with its own rules.
## Audio CPU Metaphor ## Audio CPU Metaphor
Uma metáfora útil é pensar em: A useful metaphor is:
```text ```text
[Game CPU] -> envia comandos em 60 Hz -> [AUDIO Peripheral] [Game CPU] -> sends commands at 60 Hz -> [AUDIO Peripheral]
| |
v v
Voices + Mixer Voices + Mixer
@ -30,26 +30,26 @@ Uma metáfora útil é pensar em:
PCM Output PCM Output
``` ```
Essa metáfora não exige um thread dedicado. Ela só separa responsabilidades: This metaphor does not require a dedicated thread. It only separates responsibilities:
- a máquina define o modelo lógico; - the machine defines the logical model;
- o host decide como entregar buffers contínuos; - the host decides how to deliver continuous buffers;
- o jogo fala em comandos, não em manipulação direta do backend. - the game speaks in commands, not direct backend manipulation.
## Good Habits ## Good Habits
- reutilizar samples; - reuse samples;
- limitar vozes simultâneas; - limit simultaneous voices;
- tratar som como evento intencional; - treat sound as an intentional event;
- separar música e efeitos; - separate music and effects;
- evitar disparar o mesmo som todo frame. - avoid triggering the same sound every frame.
## Historical Direction ## Historical Direction
As influências principais aqui são: The main influences here are:
- NES, pela clareza de canais limitados; - NES, for the clarity of limited channels;
- SNES, por playback de sample e mistura; - SNES, for sample playback and mixing;
- CPS-2 e Neo Geo, pela sensação de folga e presença de sample playback. - CPS-2 and Neo Geo, for the feeling of headroom and sample presence.
PROMETEU abstrai essas referências. Ele não tenta reproduzir nenhum desses sistemas literalmente. PROMETEU abstracts those references. It does not try to reproduce any of those systems literally.

View File

@ -3,63 +3,63 @@
Status: pedagogical Status: pedagogical
Companion spec: [`../specs/04-gfx-peripheral.md`](../specs/04-gfx-peripheral.md) Companion spec: [`../specs/04-gfx-peripheral.md`](../specs/04-gfx-peripheral.md)
PROMETEU trata gráficos como um periférico explícito, não como uma GPU moderna. PROMETEU treats graphics as an explicit peripheral, not as a modern GPU.
O modelo mental correto é o de uma máquina 2D retro com: The right mental model is a retro 2D machine with:
- framebuffer; - framebuffer;
- tile banks; - tile banks;
- tile layers; - tile layers;
- sprites por ordem de desenho; - sprites por ordem de desenho;
- composição determinística por frame. - deterministic composition per frame.
## Why This Exists ## Why This Exists
O objetivo não é imitar hardware histórico byte a byte. O objetivo é capturar a família de restrições e de linguagem visual de consoles como SNES, CPS-2 e Neo Geo, mas em um contrato pequeno, portátil e implementável em desktop e hardware DIY. The goal is not to imitate historical hardware byte for byte. The goal is to capture the family of constraints and visual language of consoles such as SNES, CPS-2, and Neo Geo in a small, portable contract that can run on desktop and DIY hardware.
Isso produz algumas consequências importantes: That produces some important consequences:
- desenho por ordem importa mais do que “efeitos”; - draw order matters more than "effects";
- paletas importam como parte do asset design; - palettes matter as part of asset design;
- o programador pensa em rasterização, não em shaders; - the programmer thinks in terms of rasterization, not shaders;
- o custo visual fica mais observável. - visual cost becomes more observable.
## What The GFX Is Not ## What The GFX Is Not
PROMETEU GFX não é: PROMETEU GFX is not:
- pipeline moderno de GPU; - a modern GPU pipeline;
- framebuffer RGBA com alpha arbitrário; - an RGBA framebuffer with arbitrary alpha;
- sistema de shaders; - a shader system;
- composição automática pós-processada. - automatic post-processed composition.
Essas ausências são deliberadas. Elas forçam uma linguagem visual mais próxima de console clássico e mantêm o contrato executável em ambientes modestos. Those absences are deliberate. They force a visual language closer to classic consoles and keep the contract executable in modest environments.
## Practical Intuition ## Practical Intuition
- Tile layers existem para mundo e cenário. - Tile layers exist for world and scenery.
- HUD existe para informação fixa e deve permanecer desacoplado da câmera. - HUD exists for fixed information and should remain decoupled from the camera.
- Sprites existem para entidades móveis e sua profundidade depende da ordem e da prioridade. - Sprites exist for moving entities, and their depth depends on order and priority.
- Paletas existem para variar estado visual sem duplicar tile art. - Palettes exist to vary visual state without duplicating tile art.
- Fade existe como efeito especial discreto, não como alpha genérico. - Fade exists as a discrete special effect, not as generic alpha.
## Palette Thinking ## Palette Thinking
Uma boa maneira de pensar PROMETEU é: arte e cor não são a mesma coisa. A good way to think about PROMETEU is that art and color are not the same thing.
O tile é a forma. A paleta é o estado visual. The tile is the shape. The palette is the visual state.
Isso habilita: That enables:
- variação de inimigos; - enemy variation;
- mudança de bioma; - biome changes;
- dano, gelo, veneno, power-up; - damage, ice, poison, power-up states;
- temas de HUD; - HUD themes;
- ciclos de dia e noite. - day and night cycles.
## Use Cases ## Use Cases
- troca de área com `Scene Fade`; - area transition with `Scene Fade`;
- troca de HUD com `HUD Fade`; - HUD transition with `HUD Fade`;
- flash de dano ou teleporte; - damage flash or teleport flash;
- swap global de paleta para clima ou estado de mundo. - global palette swap for weather or world state.

View File

@ -3,41 +3,41 @@
Status: pedagogical Status: pedagogical
Companion spec: [`../specs/06-input-peripheral.md`](../specs/06-input-peripheral.md) Companion spec: [`../specs/06-input-peripheral.md`](../specs/06-input-peripheral.md)
PROMETEU trata input como estado amostrado, não como evento assíncrono. PROMETEU treats input as sampled state, not as an asynchronous event.
## State Versus Event ## State Versus Event
O modelo mais importante para entender é: The most important model to understand is:
- botão não “dispara” uma ação sozinho; - a button does not "fire" an action by itself;
- botão muda de estado; - a button changes state;
- o jogo consulta esse estado durante o frame. - the game reads that state during the frame.
Isso se parece muito mais com polling de registrador em console clássico do que com callbacks de UI moderna. That looks much more like classic console register polling than like modern UI callbacks.
## Why This Matters ## Why This Matters
Esse modelo: This model:
- melhora determinismo; - improves determinism;
- simplifica replay; - simplifies replay;
- facilita depuração; - makes debugging easier;
- torna o frame loop mais legível. - makes the frame loop easier to read.
Também encaixa melhor na identidade de PROMETEU como máquina com forte inspiração em hardware retro e em construção DIY. It also fits PROMETEU's identity better as a machine strongly inspired by retro hardware and DIY construction.
## Good Habits ## Good Habits
- ler input em `UPDATE`; - read input in `UPDATE`;
- mapear ações, não teclas físicas; - map actions, not physical keys;
- separar leitura de input de lógica pesada; - separate input reading from heavy logic;
- tratar polling como parte do frame budget. - treat polling as part of the frame budget.
## Teaching Value ## Teaching Value
O periférico de input ajuda a ensinar: The input peripheral helps teach:
- diferença entre estado e evento; - the difference between state and event;
- amostragem temporal; - temporal sampling;
- sincronização entre input e lógica; - synchronization between input and logic;
- determinismo em sistemas interativos. - determinism in interactive systems.

View File

@ -3,31 +3,31 @@
Status: pedagogical Status: pedagogical
Companion spec: [`../specs/10-debug-inspection-and-profiling.md`](../specs/10-debug-inspection-and-profiling.md) Companion spec: [`../specs/10-debug-inspection-and-profiling.md`](../specs/10-debug-inspection-and-profiling.md)
PROMETEU foi desenhado para ser observável. PROMETEU was designed to be observable.
## Debug Philosophy ## Debug Philosophy
Há três ideias centrais aqui: There are three central ideas here:
1. estado vem antes de abstração; 1. state comes before abstraction;
2. tempo é cidadão de primeira classe; 2. time is a first-class citizen;
3. observar não deve alterar o resultado lógico. 3. observing must not alter the logical result.
Isso puxa o projeto para um estilo de depuração mais próximo de máquina e menos próximo de “tentativa e erro”. That pushes the project toward a debugging style that is closer to machine reasoning and farther from "trial and error".
## Why This Matters ## Why This Matters
Quando a máquina expõe pilhas, heap, ciclos, buffers e faults de forma consistente, o programador consegue: When the machine exposes stacks, heap, cycles, buffers, and faults consistently, the programmer can:
- localizar custo real; - locate real cost;
- correlacionar tempo e memória; - correlate time and memory;
- justificar decisão técnica; - justify technical decisions;
- depurar sem inventar explicações mágicas. - debug without inventing magical explanations.
## Teaching Value ## Teaching Value
Essa superfície didática existe porque PROMETEU quer ensinar também como sistemas são analisados: This pedagogical surface exists because PROMETEU also wants to teach how systems are analyzed:
- debugging como observação informada; - debugging as informed observation;
- profiling como leitura de evidência; - profiling as evidence reading;
- certification como relatório técnico reproduzível. - certification as a reproducible technical report.

View File

@ -3,50 +3,50 @@
Status: pedagogical Status: pedagogical
Companion spec: [`../specs/11-portability-and-cross-platform-execution.md`](../specs/11-portability-and-cross-platform-execution.md) Companion spec: [`../specs/11-portability-and-cross-platform-execution.md`](../specs/11-portability-and-cross-platform-execution.md)
PROMETEU trata portabilidade como propriedade arquitetural da máquina, não como adaptação posterior. PROMETEU treats portability as an architectural property of the machine, not as an after-the-fact adaptation.
## Core Idea ## Core Idea
O ponto principal é simples: The main point is simple:
- a máquina define a semântica; - the machine defines the semantics;
- o host realiza apresentação e integração física; - the host performs presentation and physical integration;
- o cartridge não negocia comportamento com o sistema operacional. - the cartridge does not negotiate behavior with the operating system.
Isso evita a noção comum de que cada plataforma “tem sua versão” da lógica do jogo. That avoids the common notion that each platform has "its own version" of game logic.
## Why This Matters ## Why This Matters
Quando tempo, memória, input, áudio e gráficos são definidos pela máquina, ficam mais fáceis: When time, memory, input, audio, and graphics are defined by the machine, the following become easier:
- replay determinístico; - deterministic replay;
- certification reproduzível; - reproducible certification;
- execução em desktop, mobile e hardware DIY; - execution on desktop, mobile, and DIY hardware;
- separação limpa entre semântica e adaptação. - clean separation between semantics and adaptation.
## Practical Separation ## Practical Separation
Uma forma útil de pensar é: A useful way to think about it is:
- cartridge carrega programa e assets; - the cartridge carries program and assets;
- a VM/runtime executa a lógica; - the VM/runtime executes the logic;
- o host mostra pixels, entrega áudio e coleta input físico; - the host shows pixels, delivers audio, and collects physical input;
- o host não redefine as regras do jogo. - the host does not redefine the game's rules.
## What Portability Does Not Mean ## What Portability Does Not Mean
PROMETEU não promete: PROMETEU does not promise:
- a mesma latência física; - the same physical latency;
- o mesmo consumo energético; - the same power consumption;
- o mesmo throughput bruto do host. - the same raw host throughput.
Ele promete consistência lógica. Isso é o que importa para a identidade da máquina. It promises logical consistency. That is what matters to the machine's identity.
## Teaching Value ## Teaching Value
Esse modelo ajuda a ensinar: This model helps teach:
- diferença entre lógica e apresentação; - the difference between logic and presentation;
- por que engines modernas frequentemente perdem determinismo; - why modern engines often lose determinism;
- como projetar software portátil sem depender de sorte. - how to design portable software without relying on luck.

View File

@ -4,104 +4,104 @@ Status: pedagogical
Companion spec: [`../specs/08-save-memory-and-memcard.md`](../specs/08-save-memory-and-memcard.md) Companion spec: [`../specs/08-save-memory-and-memcard.md`](../specs/08-save-memory-and-memcard.md)
Historical snapshot: [`historical-game-memcard-slots-surface-and-semantics.md`](historical-game-memcard-slots-surface-and-semantics.md) Historical snapshot: [`historical-game-memcard-slots-surface-and-semantics.md`](historical-game-memcard-slots-surface-and-semantics.md)
PROMETEU trata persistência como hardware explícito, não como save invisível. PROMETEU treats persistence as explicit hardware, not as invisible save behavior.
## Mental Model ## Mental Model
O MEMCARD não é save state. Ele é um dispositivo de persistência controlado pelo jogo. MEMCARD is not save state. It is a persistence device controlled by the game.
Isso implica: That implies:
- tamanho conhecido; - known size;
- custo observável; - observable cost;
- necessidade de `commit()`; - the need for `commit()`;
- possibilidade de falha; - the possibility of failure;
- formato de dados sob controle do jogo. - a data format under the game's control.
## Slot Thinking ## Slot Thinking
O modelo certo nao e "o jogo salva arquivos". O modelo certo e "o jogo conversa com slots". The right model is not "the game saves files". The right model is "the game talks to slots".
Isso muda o jeito de pensar persistencia: That changes how you think about persistence:
- capacidade e finita e conhecida; - capacity is finite and known;
- cada slot tem identidade e estado; - each slot has identity and state;
- ownership pertence ao `app_id` do cart; - ownership belongs to the cart's `app_id`;
- o jogo nao ganha acesso amplo ao filesystem do host. - the game does not get broad access to the host filesystem.
Essa escolha existe para manter: That choice exists to preserve:
- portabilidade; - portability;
- isolamento entre apps; - isolation between apps;
- UX previsivel de save; - predictable save UX;
- contrato executavel em desktop e hardware dedicado. - a contract that runs on desktop and dedicated hardware.
## Staged Versus Committed ## Staged Versus Committed
Uma intuicao importante em MEMCARD e a diferenca entre: An important MEMCARD intuition is the difference between:
- mexer no conteudo em staging; - changing content in staging;
- tornar a escrita persistida de fato. - making the write actually persistent.
`commit()` existe para separar essas duas fases. `commit()` existe para separar essas duas fases.
Isso ensina um modelo de persistencia mais honesto: That teaches a more honest model of persistence:
- escrever ainda nao e persistir; - writing is not yet persisting;
- persistir tem custo; - persisting has a cost;
- persistir pode falhar; - persisting can fail;
- atomicidade importa. - atomicity matters.
## Why Explicit Commit Matters ## Why Explicit Commit Matters
O `commit()` existe para tornar persistência uma decisão técnica visível. `commit()` exists to make persistence a visible technical decision.
Sem ele, não há ilusão de que “salvar simplesmente aconteceu”. O jogo precisa assumir quando quer: Without it, there is no illusion that "saving simply happened". The game must decide when it wants to:
- materializar escrita; - materialize a write;
- aceitar custo; - accept the cost;
- lidar com risco de perda ou corrupção. - deal with the risk of loss or corruption.
## Runtime-Owned Metadata ## Runtime-Owned Metadata
Mesmo quando o payload pertence ao jogo, alguns aspectos do slot pertencem a maquina: Even when the payload belongs to the game, some aspects of the slot belong to the machine:
- integridade; - integrity;
- geracao/versionamento; - generation/versioning;
- estado do slot; - slot state;
- isolamento por ownership. - ownership isolation.
Isso evita que cada jogo reinvente sua propria semantica basica de persistencia e permite que tooling e Hub/OS apresentem save de forma coerente. That prevents each game from reinventing its own basic persistence semantics and lets tooling and Hub/OS present save data coherently.
## Hub/OS Role ## Hub/OS Role
PROMETEU separa claramente: PROMETEU separates clearly:
- o jogo grava e le seus slots; - the game writes and reads its own slots;
- o Hub/OS faz export, import, copia e apresentacao de saves. - the Hub/OS handles export, import, copy, and save presentation.
Essa separacao impede que userland vire um mini-gerenciador de arquivos e mantem as operacoes de sistema na camada certa. That separation prevents userland from becoming a mini file manager and keeps system operations in the right layer.
## Tooling Surface ## Tooling Surface
Ferramentas externas podem expor utilidades como: External tools may expose utilities such as:
- criar ou resetar MEMCARD; - create or reset MEMCARD;
- importar e exportar `.mem`; - import and export `.mem`;
- inspecionar tamanho e uso; - inspect size and usage;
- associar cartões a projetos. - associate cards with projects.
Essas superfícies são auxiliares. Elas não mudam o contrato da máquina. Those surfaces are auxiliary. They do not change the machine contract.
## Why This Is Better Than Broad FS For Games ## Why This Is Better Than Broad FS For Games
Para perfil `game`, o modelo de slot e melhor que abrir um filesystem geral porque: For the `game` profile, the slot model is better than exposing a broad filesystem because:
- reduz ambiguidade de path, permissao e ownership; - it reduces ambiguity around path, permission, and ownership;
- facilita import/export controlado; - it makes controlled import/export easier;
- melhora compatibilidade entre hosts; - it improves compatibility across hosts;
- deixa mais claro o que significa "save valido" para a maquina. - it makes it clearer what a "valid save" means to the machine.
## Why This Fits PROMETEU ## Why This Fits PROMETEU
Esse modelo conversa bem com a herança de console e com o foco DIY do projeto: persistência é parte do design da máquina, não conveniência escondida do host. This model fits well with the project's console heritage and DIY focus: persistence is part of the machine design, not convenience hidden inside the host.

View File

@ -9,117 +9,117 @@ Companion specs:
- [`../specs/08-save-memory-and-memcard.md`](../specs/08-save-memory-and-memcard.md) - [`../specs/08-save-memory-and-memcard.md`](../specs/08-save-memory-and-memcard.md)
- [`../specs/15-asset-management.md`](../specs/15-asset-management.md) - [`../specs/15-asset-management.md`](../specs/15-asset-management.md)
PROMETEU usa um modelo status-first para impedir que a borda host/runtime esconda erro operacional como silencio, `Trap` indevido ou `Panic` acidental. PROMETEU uses a status-first model so the host/runtime boundary does not hide operational errors as silence, improper `Trap`, or accidental `Panic`.
## Core Split ## Core Split
O modelo mental certo e: The right mental model is:
- `Trap` para violacao estrutural de contrato; - `Trap` for structural contract violations;
- `status` para resultado operacional observavel; - `status` for observable operational results;
- `Panic` para quebra de invariante interna. - `Panic` for internal invariant breaks.
Uma forma curta de pensar: A short way to think about it:
- guest chamou errado: `Trap`; - the guest called it wrong: `Trap`;
- guest chamou certo, mas o dominio nao conseguiu concluir: `status`; - the guest called it correctly, but the domain could not complete it: `status`;
- runtime quebrou por dentro: `Panic`. - the runtime broke internally: `Panic`.
## Why This Exists ## Why This Exists
Sem essa separacao, sistemas host-backed tendem a degradar para uma mistura ruim de: Without that separation, host-backed systems tend to degrade into a bad mix of:
- `void` em operacoes que falham de verdade; - `void` in operations that can really fail;
- fallback implicito; - implicit fallback;
- no-op silencioso; - silent no-op;
- escalacao de erro de app para `Panic`. - escalation of app errors into `Panic`.
Status-first existe para tornar o comportamento: Status-first exists to make behavior:
- observavel; - observable;
- deterministico; - deterministic;
- testavel; - testable;
- documentavel por dominio. - documentable per domain.
## Return Shape Rule ## Return Shape Rule
A regra pratica mais importante e simples: The most important practical rule is simple:
- se a operacao pode falhar operacionalmente, ela deve retornar `status`; - if the operation can fail operationally, it should return `status`;
- se a operacao nao tem caminho real de falha operacional, ela pode ser `void`. - if the operation has no real operational failure path, it may be `void`.
Isso impede contratos em que o guest nao consegue distinguir: That prevents contracts in which the guest cannot distinguish:
- sucesso; - success;
- rejeicao; - rejection;
- ausencia de efeito; - absence of effect;
- backend indisponivel; - backend unavailable;
- asset ou recurso ausente. - missing asset or resource.
## Silent Failure Is Not Allowed ## Silent Failure Is Not Allowed
Em PROMETEU, erro operacional nao pode ser maquiado como: In PROMETEU, an operational error cannot be disguised as:
- sucesso implicito; - implicit success;
- ignorar a chamada; - ignoring the call;
- fallback automatico para outro recurso; - automatic fallback to another resource;
- `Trap`, quando o problema nao e estrutural; - `Trap`, when the problem is not structural;
- `Panic`, quando o problema nao e interno. - `Panic`, when the problem is not internal.
Se o guest pode perceber a diferenca, essa diferenca deve aparecer como `status`. If the guest can perceive the difference, that difference should appear as `status`.
## Reading The Boundary ## Reading The Boundary
Quando estiver lendo ou desenhando uma syscall, use esta sequencia: When reading or designing a syscall, use this sequence:
1. A chamada esta estruturalmente correta? 1. Is the call structurally correct?
2. O guest tem permissao/capability para usar a surface? 2. Does the guest have permission/capability to use the surface?
3. O dominio consegue executar a operacao com os recursos atuais? 3. Can the domain execute the operation with the current resources?
4. Ha payload adicional que so faz sentido quando o `status` indica sucesso? 4. Is there additional payload that only makes sense when `status` indicates success?
Essa leitura tende a produzir contratos mais limpos, por exemplo: That reading tends to produce cleaner contracts, for example:
- `asset.load(...) -> (status, handle)` - `asset.load(...) -> (status, handle)`
- `mem.slot_read(...) -> (status, payload, bytes_read)` - `mem.slot_read(...) -> (status, payload, bytes_read)`
- operacoes sem falha real continuam `void` - operations without a real failure path remain `void`
## Domain Intuition ## Domain Intuition
### GFX ### GFX
Em `gfx`, o problema tipico nao e "a syscall explodiu". O problema tipico e: In `gfx`, the typical problem is not "the syscall exploded". The typical problem is:
- sprite inexistente; - missing sprite;
- indice fora da faixa operacional; - index outside the operational range;
- argumento invalido para a operacao; - invalid argument for the operation;
- chamada sem efeito real. - a call with no real effect.
Esses casos pedem `status`, nao silencio. Those cases call for `status`, not silence.
### Audio ### Audio
Em `audio`, o modelo impede coisas como: In `audio`, the model prevents things like:
- voz invalida ser ignorada; - an invalid voice being ignored;
- sample ausente virar fallback mudo; - a missing sample turning into silent fallback;
- parametro fora de faixa parecer sucesso. - an out-of-range parameter looking like success.
Audio deve se comportar como periferico finito e explicito, nao como "som automatico". Audio should behave like a finite, explicit peripheral, not like "automatic sound".
### Asset ### Asset
Em `asset`, status-first separa melhor: In `asset`, status-first better separates:
- erro de request; - request errors;
- lifecycle assíncrono; - asynchronous lifecycle;
- commit/cancel invalido; - invalid commit/cancel;
- handle desconhecido. - unknown handle.
Isso combina com o modelo de request + poll + commit, em vez de fingir que carregamento e instantaneo. That fits the request + poll + commit model instead of pretending loading is instantaneous.
### FS / MEMCARD ### FS / MEMCARD
Em persistencia, status-first impede a pior categoria de erro: "pareceu salvar". In persistence, status-first prevents the worst category of error: "it seemed to save".
Casos como: Casos como:
@ -129,22 +129,22 @@ Casos como:
- corrupcao; - corrupcao;
- backend indisponivel; - backend indisponivel;
precisam aparecer como estado observavel, porque o jogo e o Hub/OS precisam reagir a isso. must appear as observable state because the game and the Hub/OS need to react to them.
## Design Smells ## Design Smells
Sinais de que o contrato ainda esta ruim: Signs that the contract is still weak:
- a operacao pode falhar, mas retorna `void`; - the operation can fail, but returns `void`;
- existe fallback implicito para recurso default; - there is implicit fallback to a default resource;
- a documentacao depende de "na pratica nao deve acontecer"; - the documentation depends on "in practice this should not happen";
- `Panic` aparece para erro de input do app; - `Panic` appears for app input errors;
- o mesmo dominio mistura no-op silencioso e status explicito; - the same domain mixes silent no-op and explicit status;
- payload de retorno nao deixa claro quando e valido. - return payload does not make clear when it is valid.
## Historical Anchors ## Historical Anchors
Este guia consolida a intuicao que apareceu primeiro nestes snapshots historicos: This guide consolidates the intuition that first appeared in these historical snapshots:
- [`historical-gfx-status-first-fault-and-return-contract.md`](historical-gfx-status-first-fault-and-return-contract.md) - [`historical-gfx-status-first-fault-and-return-contract.md`](historical-gfx-status-first-fault-and-return-contract.md)
- [`historical-audio-status-first-fault-and-return-contract.md`](historical-audio-status-first-fault-and-return-contract.md) - [`historical-audio-status-first-fault-and-return-contract.md`](historical-audio-status-first-fault-and-return-contract.md)
@ -152,4 +152,4 @@ Este guia consolida a intuicao que apareceu primeiro nestes snapshots historicos
- [`historical-game-memcard-slots-surface-and-semantics.md`](historical-game-memcard-slots-surface-and-semantics.md) - [`historical-game-memcard-slots-surface-and-semantics.md`](historical-game-memcard-slots-surface-and-semantics.md)
- [`historical-retired-fault-and-input-decisions.md`](historical-retired-fault-and-input-decisions.md) - [`historical-retired-fault-and-input-decisions.md`](historical-retired-fault-and-input-decisions.md)
Use os snapshots para contexto historico. Use as specs para o contrato normativo atual. Use the snapshots for historical context. Use the specs for the current normative contract.

View File

@ -3,48 +3,48 @@
Status: pedagogical Status: pedagogical
Companion spec: [`../specs/01-time-model-and-cycles.md`](../specs/01-time-model-and-cycles.md) Companion spec: [`../specs/01-time-model-and-cycles.md`](../specs/01-time-model-and-cycles.md)
PROMETEU trata tempo como parte explícita da máquina. PROMETEU treats time as an explicit part of the machine.
## Core Idea ## Core Idea
Nada acontece “de graça” ou “instantaneamente”. O programador deve pensar em: Nothing happens "for free" or "instantly". The programmer should think in terms of:
- ritmo da máquina; - machine rhythm;
- custo por frame; - cost per frame;
- distribuição de trabalho ao longo do tempo; - distribution of work over time;
- impacto arquitetural de quando cada sistema roda. - the architectural impact of when each system runs.
## Why Cycles Instead of Milliseconds ## Why Cycles Instead of Milliseconds
Milissegundos variam com plataforma, jitter e hardware real. Cycles dão uma métrica de custo que pertence à máquina PROMETEU, não ao host. Milliseconds vary with platform, jitter, and real hardware. Cycles provide a cost metric that belongs to the PROMETEU machine rather than to the host.
Isso torna mais fácil comparar soluções, ensinar custo e raciocinar sobre performance sem esconder a conta atrás do sistema operacional. That makes it easier to compare solutions, teach cost, and reason about performance without hiding the bill behind the operating system.
## Temporal Distribution As Design ## Temporal Distribution As Design
Uma das intuições mais importantes em PROMETEU é: otimização não é só “fazer menos”, é decidir **quando** fazer. One of the most important intuitions in PROMETEU is that optimization is not only about "doing less", it is about deciding **when** to do it.
Exemplos úteis: Useful examples:
- IA em 30 Hz; - AI at 30 Hz;
- pathfinding em 15 Hz; - pathfinding at 15 Hz;
- timers dirigidos por frame count; - frame-count-driven timers;
- separação entre atualização pesada e apresentação. - separation between heavy update work and presentation.
## Why CAP Fits Here ## Why CAP Fits Here
O CAP reforça essa leitura de tempo como evidência técnica. Ele não existe para bloquear execução, e sim para tornar visíveis: CAP reinforces this reading of time as technical evidence. It does not exist to block execution, but to make visible:
- picos; - spikes;
- gargalos; - bottlenecks;
- distribuição de custo; - cost distribution;
- decisões de arquitetura temporal. - temporal architecture decisions.
## Teaching Value ## Teaching Value
Esse modelo ajuda a ensinar: This model helps teach:
- planejamento de execução; - execution planning;
- trade-offs técnicos; - technical tradeoffs;
- leitura de perfil real; - reading real profiling evidence;
- organização temporal como ferramenta arquitetural. - temporal organization as an architectural tool.

View File

@ -3,38 +3,38 @@
Status: pedagogical Status: pedagogical
Companion spec: [`../specs/07-touch-peripheral.md`](../specs/07-touch-peripheral.md) Companion spec: [`../specs/07-touch-peripheral.md`](../specs/07-touch-peripheral.md)
PROMETEU usa TOUCH como um ponteiro absoluto e determinístico, não como uma superfície rica em gestos. PROMETEU uses TOUCH as an absolute, deterministic pointer, not as a gesture-rich surface.
## Design Intuition ## Design Intuition
O princípio central é simples: The central principle is simple:
- um único ponteiro ativo; - a single active pointer;
- sem gestos implícitos; - no implicit gestures;
- sem aceleração; - no acceleration;
- sem heurística; - no heuristics;
- mesmo comportamento em desktop, mobile e hardware dedicado. - the same behavior on desktop, mobile, and dedicated hardware.
Se o comportamento não puder ser garantido de forma portátil, ele não entra na máquina. If a behavior cannot be guaranteed portably, it does not enter the machine.
## Why Single Pointer ## Why Single Pointer
Multitouch físico pode existir no host, mas a máquina escolhe um único ponteiro lógico para evitar: Physical multitouch may exist on the host, but the machine chooses a single logical pointer to avoid:
- ambiguidades de captura; - capture ambiguities;
- diferenças entre plataformas; - differences between platforms;
- mudanças semânticas entre mouse, touch real e touchscreen embutido. - semantic shifts between mouse, real touch, and built-in touchscreen.
## Good Uses ## Good Uses
TOUCH funciona bem para: TOUCH works well for:
- UI; - UI;
- seleção direta; - direct selection;
- drag-and-drop; - drag-and-drop;
- puzzles de apontamento; - pointing puzzles;
- trilhas, cortes e mecânicas baseadas em contato. - trails, cuts, and contact-based mechanics.
## What Games Must Do Themselves ## What Games Must Do Themselves
Se um jogo quiser gesto, swipe, long-press ou smoothing, ele deve construir isso por cima do estado bruto por frame. O periférico não interpreta intenção. If a game wants gestures, swipe, long-press, or smoothing, it must build that on top of the raw per-frame state. The peripheral does not interpret intent.

View File

@ -1,41 +1,41 @@
# PROMETEU Machine Specs # PROMETEU Machine Specs
Este diretório reúne as specs técnicas da máquina PROMETEU. This directory contains the technical specs for the PROMETEU machine.
PROMETEU é uma fantasy handheld / fantasy console. A VM é apenas um subsistema dessa máquina. Por isso, esta superfície documental cobre mais do que bytecode e runtime: ela cobre tempo, hardware virtual, firmware, cartridge, assets e ABI com o host. PROMETEU is a fantasy handheld / fantasy console. The VM is only one subsystem of that machine. Because of that, this documentation surface covers more than bytecode and runtime: it covers timing, virtual hardware, firmware, cartridge packaging, assets, and the host ABI.
A organização aqui é intencionalmente plana. A taxonomia é conceitual, não estrutural. The organization here is intentionally flat. The taxonomy is conceptual, not structural.
## Scope Boundary ## Scope Boundary
Pertence a `docs/runtime/specs/`: Belongs in `docs/runtime/specs/`:
- contrato técnico da máquina PROMETEU; - the technical contract of the PROMETEU machine;
- hardware virtual e seus periféricos; - virtual hardware and its peripherals;
- envelope de firmware e boot; - the firmware and boot envelope;
- cartridge, assets e superfícies de carga; - cartridge, asset, and load surfaces;
- ABI da VM com o host. - the VM-to-host ABI.
Não pertence a `docs/runtime/specs/` como fonte canônica principal: Does not belong in `docs/runtime/specs/` as the primary canonical source:
- invariantes arquiteturais internas da VM/runtime: - internal architectural invariants of the VM/runtime:
[`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md); [`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md);
- ISA em nível de bytecode: - bytecode-level ISA:
[`../virtual-machine/ISA_CORE.md`](../virtual-machine/ISA_CORE.md); [`../virtual-machine/ISA_CORE.md`](../virtual-machine/ISA_CORE.md);
- guias didáticos e material de aprendizagem: - pedagogical guides and learning material:
[`../learn/README.md`](../learn/README.md); [`../learn/README.md`](../learn/README.md);
- agendas, propostas e planos: - agendas, proposals, and plans:
`docs/runtime/agendas/` e `docs/runtime/pull-requests/`. `docs/runtime/agendas/` and `docs/runtime/pull-requests/`.
## Organization Rules ## Organization Rules
- estrutura plana; - flat structure;
- sem pasta `topics/`; - no `topics/` folder;
- sem navegação embutida `Back` / `Next` / `Summary`; - no embedded `Back` / `Next` / `Summary` navigation;
- nomes de arquivos semânticos; - semantic filenames;
- cada capítulo deve poder ser aberto isoladamente; - each chapter must stand on its own;
- cada capítulo deve declarar seu domínio e sua função documental no topo do arquivo; - each chapter must declare its domain and documentary function at the top of the file;
- a taxonomia deve viver no `README`, não em uma árvore de diretórios artificial. - taxonomy should live in the `README`, not in an artificial directory tree.
## Taxonomy ## Taxonomy
@ -48,16 +48,16 @@ Não pertence a `docs/runtime/specs/` como fonte canônica principal:
| `12` and `14` | firmware and boot orchestration | | `12` and `14` | firmware and boot orchestration |
| `13` and `15` | cartridge package and asset surface | | `13` and `15` | cartridge package and asset surface |
Hardware, aqui, não é um saco genérico para tudo. No pacote atual, “hardware” significa os periféricos virtuais da máquina: GFX, AUDIO, INPUT, TOUCH e MEMCARD/save memory. VM, firmware, cartridge e ABI ficam em categorias irmãs, não dentro da categoria de hardware. Here, hardware is not a generic bucket for everything. In the current package, "hardware" means the machine's virtual peripherals: GFX, AUDIO, INPUT, TOUCH, and MEMCARD/save memory. VM, firmware, cartridge, and ABI sit in sibling categories rather than inside hardware.
## Document Functions ## Document Functions
- `normative`: define contrato técnico, comportamento esperado ou superfície compatível com implementação. - `normative`: defines the technical contract, expected behavior, or implementation-facing surface.
- `mixed (normative + explanatory)`: contém contrato técnico, mas preserva framing didático para explicar o modelo da máquina. - `mixed (normative + explanatory)`: contains technical contract material but preserves explanatory framing to clarify the machine model.
- `historical`: material arquivado; não é autoridade para implementação nova. - `historical`: archived material; not the authority for new implementation work.
- `pedagogical`: material de ensino; não define sozinho contrato técnico. - `pedagogical`: teaching material; does not define the technical contract on its own.
No estado atual, nenhum capítulo sob a raiz ativa de `docs/runtime/specs/` é `historical` puro. Se material histórico surgir, ele não deve competir com a superfície normativa principal. In the current state, no chapter under the active `docs/runtime/specs/` root is purely `historical`. If historical material appears, it must not compete with the primary normative surface.
## Current Chapter Map ## Current Chapter Map
@ -86,31 +86,31 @@ No estado atual, nenhum capítulo sob a raiz ativa de `docs/runtime/specs/` é `
## Authority Model ## Authority Model
- `docs/runtime/specs/` define a máquina PROMETEU e suas superfícies externas de execução. - `docs/runtime/specs/` defines the PROMETEU machine and its external execution surfaces.
- [`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md) continua sendo a autoridade canônica das invariantes internas da VM/runtime. - [`../virtual-machine/ARCHITECTURE.md`](../virtual-machine/ARCHITECTURE.md) remains the canonical authority for internal VM/runtime invariants.
- [`../virtual-machine/ISA_CORE.md`](../virtual-machine/ISA_CORE.md) continua sendo a autoridade para a ISA de bytecode. - [`../virtual-machine/ISA_CORE.md`](../virtual-machine/ISA_CORE.md) remains the authority for the bytecode ISA.
- Quando um capítulo daqui tocar a VM, ele pode complementar, mas não contradizer, a arquitetura canônica da VM/runtime. - When a chapter here touches the VM, it may complement but must not contradict the canonical VM/runtime architecture.
## Rules for Future Chapters ## Rules for Future Chapters
- o nome do arquivo deve comunicar o domínio; - the filename should communicate the domain;
- o capítulo deve declarar `Domain` e `Function` no topo; - the chapter should declare `Domain` and `Function` at the top;
- capítulos sobre hardware devem tratar de periféricos ou superfícies de máquina observáveis, não de qualquer tema técnico solto; - hardware chapters should cover peripherals or observable machine surfaces, not arbitrary technical topics;
- capítulos históricos ou puramente pedagógicos não devem disputar autoridade com capítulos normativos; - historical or purely pedagogical chapters must not compete with normative chapters for authority;
- links internos devem agregar contexto real, não servir como navegação obrigatória. - internal links should add real context rather than act as mandatory navigation.
## Pairing Rule ## Pairing Rule
Um tema deve nascer como par `spec` + `learn` quando: A topic should be created as a `spec` + `learn` pair when:
- o contrato normativo é importante, mas o modelo mental também é; - the normative contract matters, but the mental model matters too;
- o texto precisa de contexto histórico, comparação com hardware clássico ou design rationale extenso; - the text needs historical context, comparison with classic hardware, or extensive design rationale;
- o material didático ameaça inflar ou confundir o capítulo normativo; - the pedagogical material risks bloating or confusing the normative chapter;
- o assunto serve tanto como superfície técnica quanto como ferramenta de ensino. - the subject serves both as a technical surface and as a teaching tool.
Nesses casos: In those cases:
- `docs/runtime/specs/` define o contrato; - `docs/runtime/specs/` defines the contract;
- `docs/runtime/learn/` explica o porquê, a intuição e os exemplos; - `docs/runtime/learn/` explains the why, the intuition, and the examples;
- o spec deve apontar para o companion didático no topo; - the spec should point to the pedagogical companion near the top;
- o guia didático deve apontar de volta para o spec canônico. - the pedagogical guide should point back to the canonical spec.