From 15615f3b54616444923fdaa0b62b0a35c9248dcc Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Fri, 15 May 2026 10:29:24 +0100 Subject: [PATCH] housekeeping --- discussion/index.ndjson | 6 +- .../LSN-0041-systemos-lifecycle-authority.md | 95 +++++ ...042-systemos-service-ownership-boundary.md | 89 +++++ ...stem-os-lifecycle-process-task-contract.md | 347 ------------------ ...-os-service-ownership-and-module-layout.md | 199 ---------- ...mos-service-ownership-and-module-layout.md | 133 ------- ...cycle-authority-for-tasks-and-processes.md | 203 ---------- .../PLN-0051-move-vm-runtime-into-services.md | 103 ------ ...mote-window-manager-to-systemos-service.md | 85 ----- ...0053-move-logging-ownership-to-systemos.md | 88 ----- ...ve-fs-and-memcard-ownership-to-systemos.md | 95 ----- .../PLN-0055-systemos-lifecycle-core-api.md | 121 ------ .../PLN-0056-firmware-lifecycle-delegation.md | 119 ------ ...PLN-0057-lifecycle-tests-and-invariants.md | 110 ------ 14 files changed, 187 insertions(+), 1606 deletions(-) create mode 100644 discussion/lessons/DSC-0032-system-os-lifecycle-process-task-contract/LSN-0041-systemos-lifecycle-authority.md create mode 100644 discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md delete mode 100644 discussion/workflow/agendas/AGD-0032-system-os-lifecycle-process-task-contract.md delete mode 100644 discussion/workflow/agendas/AGD-0033-system-os-service-ownership-and-module-layout.md delete mode 100644 discussion/workflow/decisions/DEC-0024-systemos-service-ownership-and-module-layout.md delete mode 100644 discussion/workflow/decisions/DEC-0025-systemos-lifecycle-authority-for-tasks-and-processes.md delete mode 100644 discussion/workflow/plans/PLN-0051-move-vm-runtime-into-services.md delete mode 100644 discussion/workflow/plans/PLN-0052-promote-window-manager-to-systemos-service.md delete mode 100644 discussion/workflow/plans/PLN-0053-move-logging-ownership-to-systemos.md delete mode 100644 discussion/workflow/plans/PLN-0054-move-fs-and-memcard-ownership-to-systemos.md delete mode 100644 discussion/workflow/plans/PLN-0055-systemos-lifecycle-core-api.md delete mode 100644 discussion/workflow/plans/PLN-0056-firmware-lifecycle-delegation.md delete mode 100644 discussion/workflow/plans/PLN-0057-lifecycle-tests-and-invariants.md diff --git a/discussion/index.ndjson b/discussion/index.ndjson index fbd229b4..45e474a3 100644 --- a/discussion/index.ndjson +++ b/discussion/index.ndjson @@ -1,4 +1,4 @@ -{"type":"meta","next_id":{"DSC":35,"AGD":35,"DEC":27,"PLN":59,"LSN":41,"CLSN":1}} +{"type":"meta","next_id":{"DSC":35,"AGD":35,"DEC":27,"PLN":59,"LSN":43,"CLSN":1}} {"type":"discussion","id":"DSC-0034","status":"in_progress","ticket":"system-os-domain-facades","title":"Agenda - SystemOS Domain Facades","created_at":"2026-05-15","updated_at":"2026-05-15","tags":["runtime","os","services","api-surface","lifecycle","fs"],"agendas":[{"id":"AGD-0034","file":"AGD-0034-agenda-systemos-domain-facades.md","status":"accepted","created_at":"2026-05-15","updated_at":"2026-05-15"}],"decisions":[{"id":"DEC-0026","file":"DEC-0026-systemos-domain-facades.md","status":"accepted","created_at":"2026-05-15","updated_at":"2026-05-15","ref_agenda":"AGD-0034"}],"plans":[{"id":"PLN-0058","file":"PLN-0058-systemos-domain-facades-first-wave.md","status":"open","created_at":"2026-05-15","updated_at":"2026-05-15","ref_decisions":["DEC-0026"]}],"lessons":[]} {"type":"discussion","id":"DSC-0023","status":"done","ticket":"perf-full-migration-to-atomic-telemetry","title":"Agenda - [PERF] Full Migration to Atomic Telemetry","created_at":"2026-04-10","updated_at":"2026-04-10","tags":["perf","runtime","telemetry"],"agendas":[{"id":"AGD-0021","file":"AGD-0021-full-migration-to-atomic-telemetry.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}],"decisions":[{"id":"DEC-0008","file":"DEC-0008-full-migration-to-atomic-telemetry.md","status":"accepted","created_at":"2026-04-10","updated_at":"2026-04-10"}],"plans":[{"id":"PLN-0007","file":"PLN-0007-full-migration-to-atomic-telemetry.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}],"lessons":[{"id":"LSN-0028","file":"discussion/lessons/DSC-0023-perf-full-migration-to-atomic-telemetry/LSN-0028-converging-to-single-atomic-telemetry-source.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]} {"type":"discussion","id":"DSC-0020","status":"done","ticket":"jenkins-gitea-integration","title":"Jenkins Gitea Integration and Relocation","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["ci","jenkins","gitea"],"agendas":[{"id":"AGD-0018","file":"AGD-0018-jenkins-gitea-integration-and-relocation.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}],"decisions":[{"id":"DEC-0003","file":"DEC-0003-jenkins-gitea-strategy.md","status":"accepted","created_at":"2026-04-07","updated_at":"2026-04-07"}],"plans":[{"id":"PLN-0003","file":"PLN-0003-jenkins-gitea-execution.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}],"lessons":[{"id":"LSN-0021","file":"discussion/lessons/DSC-0020-jenkins-gitea-integration/LSN-0021-jenkins-gitea-integration.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]} @@ -31,5 +31,5 @@ {"type":"discussion","id":"DSC-0019","status":"done","ticket":"jenkinsfile-correction","title":"Jenkinsfile Correction and Relocation","created_at":"2026-04-07","updated_at":"2026-04-07","tags":["ci","jenkins"],"agendas":[{"id":"AGD-0017","file":"AGD-0017-jenkinsfile-correction.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}],"decisions":[{"id":"DEC-0002","file":"DEC-0002-jenkinsfile-strategy.md","status":"accepted","created_at":"2026-04-07","updated_at":"2026-04-07"}],"plans":[{"id":"PLN-0002","file":"PLN-0002-jenkinsfile-execution.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}],"lessons":[{"id":"LSN-0020","file":"discussion/lessons/DSC-0019-jenkins-ci-standardization/LSN-0020-jenkins-standard-relocation.md","status":"done","created_at":"2026-04-07","updated_at":"2026-04-07"}]} {"type":"discussion","id":"DSC-0030","status":"done","ticket":"internal-viewport-270p","title":"Agenda - Internal Viewport 270p (480x270)","created_at":"2026-04-27","updated_at":"2026-04-28","tags":["gfx","runtime","viewport","resolution","frame-composer","host"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0039","file":"discussion/lessons/DSC-0030-internal-viewport-270p/LSN-0039-resolution-baseline-changes-are-runtime-wide-contracts.md","status":"done","created_at":"2026-04-28","updated_at":"2026-04-28"}]} {"type":"discussion","id":"DSC-0031","status":"done","ticket":"runtime-mode-separation-game-system","title":"Agenda - Runtime Mode Separation: Game and System","created_at":"2026-05-11","updated_at":"2026-05-14","tags":["runtime","firmware","hub","system-apps","game-mode","scheduler"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0040","file":"discussion/lessons/DSC-0031-runtime-mode-separation-game-system/LSN-0040-system-pipeline-separation.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14"}]} -{"type":"discussion","id":"DSC-0032","status":"in_progress","ticket":"system-os-lifecycle-process-task-contract","title":"Agenda - SystemOS Lifecycle, Process and Task Contract","created_at":"2026-05-14","updated_at":"2026-05-15","tags":["runtime","os","lifecycle","process","task","shell","firmware"],"agendas":[{"id":"AGD-0032","file":"AGD-0032-system-os-lifecycle-process-task-contract.md","status":"accepted","created_at":"2026-05-14","updated_at":"2026-05-15"}],"decisions":[{"id":"DEC-0025","file":"DEC-0025-systemos-lifecycle-authority-for-tasks-and-processes.md","status":"accepted","created_at":"2026-05-15","updated_at":"2026-05-15","ref_agenda":"AGD-0032"}],"plans":[{"id":"PLN-0055","file":"PLN-0055-systemos-lifecycle-core-api.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15","ref_decisions":["DEC-0025"]},{"id":"PLN-0056","file":"PLN-0056-firmware-lifecycle-delegation.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15","ref_decisions":["DEC-0025"]},{"id":"PLN-0057","file":"PLN-0057-lifecycle-tests-and-invariants.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15","ref_decisions":["DEC-0025"]}],"lessons":[]} -{"type":"discussion","id":"DSC-0033","status":"in_progress","ticket":"system-os-service-ownership-and-module-layout","title":"Agenda - SystemOS Service Ownership and Module Layout","created_at":"2026-05-14","updated_at":"2026-05-14","tags":["runtime","os","services","module-layout","vm","window-manager","logging"],"agendas":[{"id":"AGD-0033","file":"AGD-0033-system-os-service-ownership-and-module-layout.md","status":"accepted","created_at":"2026-05-14","updated_at":"2026-05-14"}],"decisions":[{"id":"DEC-0024","file":"DEC-0024-systemos-service-ownership-and-module-layout.md","status":"accepted","created_at":"2026-05-14","updated_at":"2026-05-14","ref_agenda":"AGD-0033"}],"plans":[{"id":"PLN-0051","file":"PLN-0051-move-vm-runtime-into-services.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14","ref_decisions":["DEC-0024"]},{"id":"PLN-0052","file":"PLN-0052-promote-window-manager-to-systemos-service.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14","ref_decisions":["DEC-0024"]},{"id":"PLN-0053","file":"PLN-0053-move-logging-ownership-to-systemos.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14","ref_decisions":["DEC-0024"]},{"id":"PLN-0054","file":"PLN-0054-move-fs-and-memcard-ownership-to-systemos.md","status":"done","created_at":"2026-05-14","updated_at":"2026-05-14","ref_decisions":["DEC-0024"]}],"lessons":[]} +{"type":"discussion","id":"DSC-0032","status":"done","ticket":"system-os-lifecycle-process-task-contract","title":"Agenda - SystemOS Lifecycle, Process and Task Contract","created_at":"2026-05-14","updated_at":"2026-05-15","tags":["runtime","os","lifecycle","process","task","shell","firmware"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0041","file":"discussion/lessons/DSC-0032-system-os-lifecycle-process-task-contract/LSN-0041-systemos-lifecycle-authority.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]} +{"type":"discussion","id":"DSC-0033","status":"done","ticket":"system-os-service-ownership-and-module-layout","title":"Agenda - SystemOS Service Ownership and Module Layout","created_at":"2026-05-14","updated_at":"2026-05-15","tags":["runtime","os","services","module-layout","vm","window-manager","logging"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]} diff --git a/discussion/lessons/DSC-0032-system-os-lifecycle-process-task-contract/LSN-0041-systemos-lifecycle-authority.md b/discussion/lessons/DSC-0032-system-os-lifecycle-process-task-contract/LSN-0041-systemos-lifecycle-authority.md new file mode 100644 index 00000000..682fc042 --- /dev/null +++ b/discussion/lessons/DSC-0032-system-os-lifecycle-process-task-contract/LSN-0041-systemos-lifecycle-authority.md @@ -0,0 +1,95 @@ +--- +id: LSN-0041 +ticket: system-os-lifecycle-process-task-contract +title: SystemOS Lifecycle Authority +created: 2026-05-15 +tags: [runtime, os, lifecycle, process, task, firmware] +--- + +## Context + +Prometeu moved from firmware-driven cartridge execution toward a console OS +model with explicit tasks and processes. That created two related but distinct +state dimensions: + +- `TaskState`: user-visible presence and navigation. +- `ProcessState`: technical execution. + +Letting firmware, `TaskManager`, and `ProcessManager` each mutate those states +independently would make suspend, resume, close and crash behavior drift over +time. + +## Key Decisions + +### SystemOS owns lifecycle semantics + +**What:** `SystemOS` became the semantic lifecycle authority for task/process +coordination. `TaskManager` and `ProcessManager` remain storage and simple +transition mechanisms, not the public lifecycle policy boundary. + +**Why:** Lifecycle operations must update user-visible and technical execution +state together. A firmware call sequence like "mark task suspended, then mark +process suspended" is too easy to duplicate, forget or partially apply. + +**Trade-offs:** This adds an OS-level API layer, but it keeps lifecycle policy +in one place and makes future suspend/resume behavior easier to reason about. + +### The first lifecycle wave is intentionally small + +**What:** The first wave covers only foreground, suspend, resume, close and +crash: + +```text +Foreground -> Running +Suspended -> Suspended +Closed -> Stopped +Crashed -> Crashed +``` + +`Background` remains reserved and non-normative. + +**Why:** Background execution has unresolved implications around docked apps, +services, app switching and capabilities. Keeping it out of the first contract +prevents premature semantics from leaking into firmware and tests. + +**Trade-offs:** The model cannot yet express every desired app lifecycle state, +but it gives the runtime a stable base without freezing background behavior too +early. + +## Patterns and Algorithms + +Use `SystemOS` operations for semantic lifecycle changes: + +```text +set_foreground_task +suspend_task +resume_task +close_task +crash_task +``` + +Each operation should resolve the task, validate its associated process, and +return a typed lifecycle error for missing or invalid state instead of a bare +boolean. + +`resume_task` in this wave means "return to active foreground execution", not +"wake in any possible state". If a future service needs to wake without +foregrounding, it should be modeled separately. + +## Pitfalls + +- Do not let firmware coordinate task and process state manually. +- Do not treat `Background` as semantically defined just because the enum value + exists. +- Do not remove closed/stopped entities as part of `close_task`; marking and + collection are different responsibilities. +- Do not hide lifecycle policy inside manager-level tests. Domain behavior + belongs at the OS lifecycle boundary. + +## Takeaways + +- `TaskState` and `ProcessState` are separate concepts, but lifecycle operations + must coordinate them atomically at the OS boundary. +- A small lifecycle contract is better than a broad but ambiguous one. +- Reserved states are useful only if callers are prevented from treating them as + normative before their semantics are decided. diff --git a/discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md b/discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md new file mode 100644 index 00000000..c19ab0d8 --- /dev/null +++ b/discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md @@ -0,0 +1,89 @@ +--- +id: LSN-0042 +ticket: system-os-service-ownership-and-module-layout +title: SystemOS Service Ownership Boundary +created: 2026-05-15 +tags: [runtime, os, services, module-layout, vm, window-manager, logging] +--- + +## Context + +Prometeu's runtime started with VM execution as the center of gravity. As the +system evolved toward a console OS, services such as logging, filesystem, +memcard and window management needed a clearer owner. + +The important shift was to stop treating `VirtualMachineRuntime` and +`PrometeuHub` as implicit owners of OS services. + +## Key Decisions + +### SystemOS owns shared OS services + +**What:** `SystemOS` became the owner or mediator for shared OS services: +logging, filesystem, memcard, VM runtime and window management. + +**Why:** VM execution is a service of the OS, not the OS itself. If filesystem, +memcard, logging and windows remain owned by the VM runtime or Hub, the +architecture keeps pulling policy back into the wrong layer. + +**Trade-offs:** Moving ownership into `SystemOS` increases the breadth of the OS +object, but it makes service boundaries explicit and prepares the system for +facades, permissions and lifecycle coordination. + +### PrometeuHub is Shell/Home, not the OS + +**What:** `PrometeuHub` should consume OS services through `SystemOS` rather +than owning services such as window management. + +**Why:** The Hub is a visual Shell/Home program. Treating it as the service +owner makes UI structure and OS infrastructure hard to separate. + +**Trade-offs:** Hub callsites may become slightly more explicit, but service +ownership becomes visible and testable. + +### VM runtime is execution, not a service container + +**What:** `VirtualMachineRuntime` moved into the service layout and stopped +owning shared services such as logging, filesystem and memcard. + +**Why:** The VM runtime should execute VM code and use OS services through +explicit boundaries. It should not silently become the container for every +runtime facility. + +**Trade-offs:** VM execution now receives more explicit service references, but +the ownership model is cleaner. + +## Patterns and Algorithms + +When a capability is shared by game, shell, firmware or diagnostics, default to +OS ownership or OS mediation. The VM may use the capability, but use is not +ownership. + +Keep module layout aligned with meaning: + +```text +services/vm_runtime +services/window_manager +services/fs +services/memcard +``` + +Avoid compatibility reexports for old internal paths when the boundary is still +private to the workspace. Updating callsites directly keeps architectural +direction visible. + +## Pitfalls + +- Do not move files into `services/` while leaving semantic ownership unchanged. +- Do not let UI programs such as Hub own OS infrastructure just because they are + the first consumer. +- Do not let `VirtualMachineRuntime` become a general-purpose service bag. +- Do not confuse "VM needs access" with "VM owns the service". + +## Takeaways + +- OS service ownership should follow policy authority, not first caller. +- VM runtime is a service under the OS boundary. +- Shell/Home programs consume OS services; they are not the OS. +- A cleaner ownership boundary can make the root object wider temporarily, so a + later domain-facade pass is expected rather than optional. diff --git a/discussion/workflow/agendas/AGD-0032-system-os-lifecycle-process-task-contract.md b/discussion/workflow/agendas/AGD-0032-system-os-lifecycle-process-task-contract.md deleted file mode 100644 index 913f6184..00000000 --- a/discussion/workflow/agendas/AGD-0032-system-os-lifecycle-process-task-contract.md +++ /dev/null @@ -1,347 +0,0 @@ ---- -id: AGD-0032 -ticket: system-os-lifecycle-process-task-contract -title: Agenda - SystemOS Lifecycle, Process and Task Contract -status: accepted -created: 2026-05-14 -resolved: 2026-05-15 -decision: DEC-0025 -tags: [runtime, os, lifecycle, process, task, shell, firmware] ---- - -# Agenda - SystemOS Lifecycle, Process and Task Contract - -## Contexto - -Prometeu deu o primeiro passo concreto para deixar de ser apenas um firmware que -roda cartuchos e passar a ter um modelo de sistema operacional de console. - -Antes, o cartucho era representado quase exclusivamente pelo fluxo do firmware: - -```text -LoadCartridgeStep - -> initialize_vm - -> GameRunningStep / SystemRunningStep -``` - -Esse modelo permitia executar jogos e apps de sistema, mas não dava ao OS uma -entidade própria para representar processo, task, foreground, background, -suspensão, fechamento ou crash. O firmware sabia que algo estava rodando; o -Prometeu OS ainda não possuía um contrato próprio de execução e presença de -usuário. - -Agora existe um `SystemOS` em `prometeu-system`, agregando: - -```text -SystemOS - VirtualMachineRuntime - ProcessManager - TaskManager -``` - -Isso estabelece uma fronteira importante: a VM continua sendo a VM, e não a dona -do sistema. O `SystemOS` passa a ser o lugar natural para concentrar serviços de -OS, lifecycle, permissões e coordenação entre execução técnica e experiência de -usuário. - -Os conceitos iniciais são: - -```text -Process - execução técnica: - VmGame, VmShell, NativeShell - -Task - presença navegável do usuário: - Game ou Shell em Foreground, Background, Suspended, Closed ou Crashed -``` - -O carregamento de cartucho começou a registrar entidades de sistema: - -```text -AppMode::Game - -> cria processo VmGame - -> cria task Game - -> marca task como Foreground - -> entra em GameRunningStep com TaskId - -AppMode::Shell - -> cria processo VmShell - -> cria task Shell - -> marca task como Foreground - -> entra em SystemRunningStep com TaskId -``` - -`GameRunningStep` agora executa uma task específica e valida se ela ainda está em -`Foreground` antes de avançar o frame. Essa é a primeira ponte real entre o -firmware atual e um OS com lifecycle. - -## Problema - -O código já tem os primeiros tipos e fluxos, mas o contrato arquitetural ainda -não está fechado: - -- quem é a autoridade para mover uma task entre `Foreground`, `Background`, - `Suspended`, `Closed` e `Crashed`; -- como `TaskState` e `ProcessState` devem evoluir juntos; -- quais transições pertencem ao `SystemOS` e quais continuam nos managers - internos; -- como o firmware deve reagir quando uma task deixa de estar executável; -- quando o `WindowManager` deixa de ser parte do `PrometeuHub` e vira serviço - real do OS; -- se o nome público do perfil de sistema deve continuar `System` ou convergir - para `Shell` no contrato de cartucho/runtime. - -Sem esse contrato, o risco é o sistema crescer em duas direções ruins: - -1. o firmware continuar acumulando decisões de lifecycle que pertencem ao OS; -2. `TaskManager`, `ProcessManager`, `PrometeuHub` e `VirtualMachineRuntime` - criarem regras paralelas e inconsistentes. - -## Pontos Criticos - -- `SystemOS` deve ser a API de coordenação de lifecycle, não apenas um struct - agregador de managers. -- `ProcessManager` e `TaskManager` devem continuar guardando estado local, mas - não devem, sozinhos, definir o contrato semântico completo entre task e - processo. -- `Task` representa presença navegável e foco do usuário; `Process` representa - execução técnica. -- `Foreground` não é apenas uma flag visual: no modelo atual, ele autoriza o - `GameRunningStep` a executar frame. -- `Suspended`, `Closed` e `Crashed` precisam mover `TaskState` e `ProcessState` - de forma coordenada. -- `Background` precisa ser distinguido de `Suspended`: background pode existir - como presença navegável não focada, mas ainda não implica que o processo possa - executar. -- `PrometeuHub` deve evoluir para Shell/Home visual, não permanecer como - sinônimo de OS. -- `WindowManager` provavelmente deve virar serviço de `SystemOS`, mas talvez - isso precise esperar a primeira API de lifecycle estabilizar. -- A inspiração de UX é console/Switch; a inspiração interna é mais Android-like: - processos, tasks, lifecycle, surfaces/janelas, serviços e permissões. - -## Dependencia / Agenda Paralela - -`AGD-0033` trata a limpeza de ownership e layout de serviços do `SystemOS` antes -ou em paralelo a esta agenda. - -Essa separação é intencional: `AGD-0032` deve decidir lifecycle de -`Task`/`Process`, enquanto `AGD-0033` deve decidir se `VirtualMachineRuntime`, -`LogService`, `WindowManager` e outros serviços pertencem ao root, ao Hub ou à -camada `services` do `SystemOS`. - -Se `AGD-0033` concluir que `LogService` e outros serviços precisam sair da VM -antes do lifecycle, a decisão de `AGD-0032` deve tratar essa mudança como -pré-requisito de implementação, não como parte do contrato de lifecycle em si. - -## Opcoes - -### Opcao A - Manter lifecycle distribuido nos managers e no firmware - -**Abordagem:** -`TaskManager` muda tasks, `ProcessManager` muda processos, e o firmware chama -ambos diretamente quando precisar. - -**Vantagens:** -- menor mudança imediata; -- preserva managers simples; -- fácil de encaixar incrementalmente no código atual. - -**Custos / Riscos:** -- espalha regra de lifecycle por vários chamadores; -- torna mais provável esquecer de mover `ProcessState` junto com `TaskState`; -- mantém firmware como conhecedor de detalhes internos do OS; -- dificulta introduzir Shell/Home, suspensão e retomada sem duplicação. - -**Manutenibilidade:** -Aceitável no curto prazo, fraca como modelo de OS. - -### Opcao B - Centralizar lifecycle no SystemOS - -**Abordagem:** -`SystemOS` vira a API semântica para operações como: - -```text -suspend_task -resume_task -close_task -crash_task -foreground_task -background_task -``` - -Essas operações coordenam `TaskManager` e `ProcessManager` juntas. - -Exemplos de contrato: - -```text -jogo rodando: - TaskState::Foreground - ProcessState::Running - -jogo suspenso: - TaskState::Suspended - ProcessState::Suspended - -jogo fechado: - TaskState::Closed - ProcessState::Stopped - -jogo crashado: - TaskState::Crashed - ProcessState::Crashed -``` - -**Vantagens:** -- estabelece `SystemOS` como autoridade de lifecycle; -- mantém firmware mais fino; -- reduz inconsistência entre task e processo; -- cria base natural para Home/Shell, suspend/resume, close/crash e permissões. - -**Custos / Riscos:** -- exige definir transições inválidas e retorno/erro de cada operação; -- pode expor API cedo demais se tentarmos modelar todas as regras finais agora; -- precisa decidir se `Background` implica processo running, suspended ou apenas - presença não focada. - -**Manutenibilidade:** -Forte. É o caminho mais alinhado com transformar Prometeu em console OS. - -### Opcao C - Promover WindowManager a servico do OS antes do lifecycle - -**Abordagem:** -Mover primeiro o `WindowManager` para dentro de `SystemOS` e depois organizar -tasks/processos em torno de janelas/surfaces. - -**Vantagens:** -- aproxima rapidamente o modelo de Shell/Home e apps gerenciados; -- evita `PrometeuHub` continuar parecendo o sistema inteiro; -- abre caminho para surfaces e composição de apps de sistema. - -**Custos / Riscos:** -- pode misturar lifecycle de execução com lifecycle visual; -- força decisões de janela/surface antes de fechar Process/Task; -- pode congelar um WindowManager ainda experimental. - -**Manutenibilidade:** -Boa como passo futuro, mas arriscada como próximo passo se o lifecycle base -ainda não estiver normativo. - -## Sugestao / Recomendacao - -A recomendação inicial é seguir a **Opção B**. - -O próximo contrato deve declarar `SystemOS` como autoridade para lifecycle de -tasks e processos. `TaskManager` e `ProcessManager` continuam existindo, mas -devem ser mecanismos internos de armazenamento/transição, não a API semântica -principal do sistema. - -O primeiro corte deve ser pequeno: - -- adicionar métodos de lifecycle em `SystemOS`; -- coordenar `TaskState` e `ProcessState` nesses métodos; -- definir comportamento para task inexistente e process inexistente; -- preservar `GameRunningStep` como consumidor de `TaskId`, validando - foreground; -- evitar mover `WindowManager` neste mesmo corte. - -O `WindowManager` deve ser a agenda/decisão seguinte: promovê-lo a serviço real -do sistema quando a base `Task/Process/Lifecycle` estiver fechada. - -`AppMode::System` já foi renomeado para `AppMode::Shell`. A nomenclatura pública -fica alinhada com o modelo atual: `AppMode::Game` executa cartuchos como -jogo/session fullscreen, enquanto `AppMode::Shell` executa cartuchos como apps -gerenciados pela Shell do Prometeu OS. - -## Perguntas em Aberto - -- [x] `SystemOS` deve expor `suspend_task`, `resume_task`, `close_task` e - `crash_task` já no próximo corte? Sim. Eles são a próxima API semântica de - lifecycle e evitam que firmware ou outros chamadores manipulem - `TaskManager` e `ProcessManager` separadamente. -- [x] `foreground_task` e `background_task` devem ser operações explícitas do - `SystemOS`, ou apenas detalhe do `TaskManager`? `set_foreground_task(task_id)` - deve ser operação explícita do `SystemOS`. `background_task` fica fora da - primeira wave. -- [x] Qual é a semântica exata de `Background`: processo ainda `Running`, - processo `Suspended`, ou estado de presença sem garantia de execução? - Fora de escopo nesta wave. `Background` permanece estado reservado sem - semântica normativa no primeiro contrato. -- [x] `resume_task` deve sempre mover a task para `Foreground`, ou pode retomar - para `Background`? Nesta wave, `resume_task` sempre move para - `Foreground` e move o processo associado para `Running`. -- [x] O que acontece quando a task existe mas o processo associado não existe? - Isso é erro de lifecycle e deve retornar erro tipado, não `bool`. -- [x] `close_task` remove imediatamente entidades fechadas ou apenas marca - `Closed`/`Stopped` para coleta posterior? Apenas marca `TaskState::Closed` e - `ProcessState::Stopped`; coleta é operação futura separada. -- [x] `crash_task` deve receber/armazenar `CrashReport`, ou isso fica em outro - serviço de diagnóstico? A operação deve aceitar ou preparar o contrato para - `CrashReport`, mas a primeira wave pode apenas coordenar estados e deixar o - armazenamento para diagnóstico/logging futuro. -- [x] `GameRunningStep` deve transicionar para Hub/Home quando sua task deixa de - estar `Foreground`, ou apenas não executar frame? Nesta wave, mantém a - invariant forte: `GameRunningStep` só suporta game task em `Foreground`; outro - estado é inválido e deve gerar diagnóstico/crash claro. -- [x] O perfil de manifesto continua `AppMode::System`, ou abrimos uma migração - formal para `AppMode::Shell`? Resolvido: `AppMode::System` já virou - `AppMode::Shell`. -- [x] A decisão de ownership/layout em `AGD-0033` deve ser pré-requisito para o - primeiro plan de lifecycle, ou pode ser executada em paralelo? Pode executar - em paralelo e não bloqueia esta wave. O plan de lifecycle deve evitar mover - `WindowManager`, `VirtualMachineRuntime`, Hub ou background services. - -## Resolucao - -A agenda fecha pela **Opcao B**: centralizar lifecycle no `SystemOS`. - -`SystemOS` deixa de ser apenas um agregador de serviços e passa a ser a -autoridade normativa para coordenar `TaskState` e `ProcessState`. `TaskManager` -e `ProcessManager` continuam existindo, mas como mecanismos internos de -armazenamento e transição simples. O firmware não deve decidir diretamente como -task e processo mudam juntos. - -A primeira wave deve cobrir apenas: - -- `set_foreground_task(task_id)` -- `suspend_task(task_id)` -- `resume_task(task_id)` -- `close_task(task_id)` -- `crash_task(task_id, report?)` - -O mapeamento inicial é: - -```text -TaskState::Foreground -> ProcessState::Running -TaskState::Suspended -> ProcessState::Suspended -TaskState::Closed -> ProcessState::Stopped -TaskState::Crashed -> ProcessState::Crashed -``` - -`Background` permanece reservado e explicitamente fora da primeira wave. - -O primeiro plan recomendado é `PLAN-0032-A: SystemOS Lifecycle API`, com escopo -limitado a erro tipado, métodos de lifecycle em `SystemOS`, coordenação de -`TaskState`/`ProcessState`, testes unitários no nível `SystemOS` e nenhuma -mudança em `WindowManager`, `PrometeuHub`, background services ou UX completa de -suspensão/retomada. - -## Criterio para Encerrar - -Esta agenda pode virar decisão quando houver resposta para: - -- qual entidade é autoridade normativa de lifecycle; -- quais métodos mínimos entram no primeiro contrato de `SystemOS`; -- como cada método move `TaskState` e `ProcessState`; -- qual semântica inicial de `Background` e `Suspended`; -- como o firmware deve reagir a task não-foreground/não-executável; -- qual nomenclatura será usada para `System` versus `Shell`; -- como a dependência com `AGD-0033` será tratada nos plans. - -## Proximo Passo - -Revisar esta agenda e fechar as perguntas principais. Se a direção for aceita, -o próximo estágio deve ser uma decisão normativa para `SystemOS` como autoridade -de lifecycle de `Task`/`Process`, seguida de uma família curta de plans para -implementação. diff --git a/discussion/workflow/agendas/AGD-0033-system-os-service-ownership-and-module-layout.md b/discussion/workflow/agendas/AGD-0033-system-os-service-ownership-and-module-layout.md deleted file mode 100644 index 5dad3dc5..00000000 --- a/discussion/workflow/agendas/AGD-0033-system-os-service-ownership-and-module-layout.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -id: AGD-0033 -ticket: system-os-service-ownership-and-module-layout -title: Agenda - SystemOS Service Ownership and Module Layout -status: accepted -created: 2026-05-14 -resolved: -decision: -tags: [runtime, os, services, module-layout, vm, window-manager, logging] ---- - -# Agenda - SystemOS Service Ownership and Module Layout - -## Contexto - -Antes de avançar o contrato de lifecycle do `SystemOS`, há uma limpeza de -fronteira que precisa ser discutida separadamente. - -O `SystemOS` começou como agregador de: - -```text -SystemOS - VirtualMachineRuntime - ProcessManager - TaskManager -``` - -Mas o código ainda carrega sinais do modelo anterior, em que a VM concentrava -coisas que hoje parecem serviços de sistema. O exemplo mais claro é -`LogService` dentro de `VirtualMachineRuntime`. A mesma dúvida aparece em torno -de outros serviços e estados associados a filesystem, memcard, diagnóstico, -telemetria e identidade do cartucho. - -Há também uma questão de layout: - -- `VirtualMachineRuntime` está no root de `prometeu-system`, embora conceitualmente - agora seja um serviço do OS; -- `WindowManager` está dentro de `programs/prometeu_hub`, embora a direção de - arquitetura seja transformar o Hub em Shell/Home visual, não no sistema; -- `ProcessManager` e `TaskManager` já vivem em `services`, o que torna a posição - da VM e do WindowManager inconsistente com o desenho novo. - -## Problema - -Misturar ownership de serviços com execução da VM dificulta a evolução do OS. -Se `VirtualMachineRuntime` continuar parecendo dona de logging, filesystem, -memcard, diagnóstico e janela, o `SystemOS` vira apenas um wrapper, e não a -autoridade natural para coordenar serviços do console. - -Ao mesmo tempo, nem tudo aqui é puramente mecânico: - -- mover arquivos para `services` pode ser uma alteração sem mudança funcional; -- mover `LogService` para `SystemOS` altera ownership e pode exigir uma API de - serviço ou passagem explícita de dependência para a VM; -- promover `WindowManager` a serviço do OS antecipa uma fronteira arquitetural, - mesmo que a implementação continue mínima. - -Por isso, este assunto não deve ser escondido dentro da agenda de lifecycle -(`AGD-0032`). Ele é uma agenda de pré-requisito ou paralela: primeiro precisamos -limpar a fronteira entre "VM como executor" e "OS como dono de serviços". - -## Pontos Criticos - -- `VirtualMachineRuntime` deve representar execução VM, não ser o container - geral de serviços do sistema. -- `SystemOS` deve ser o lugar natural para serviços compartilhados por jogos, - Shell/Home, firmware e processos nativos futuros. -- `LogService` provavelmente pertence ao `SystemOS`, mas a forma de acesso pela - VM precisa respeitar as restrições de borrow e o desenho de `NativeInterface`. -- `VirtualFS` e `MemcardService` também parecem serviços de OS, mas movê-los no - mesmo corte pode aumentar demais o risco. -- `WindowManager` deve sair de `PrometeuHub` porque o Hub deve virar consumidor - visual do OS, não proprietário de serviço de janela. -- A mudança de layout de módulo deve preservar comportamento, mas não precisa - preservar caminhos antigos de import; callsites devem ser atualizados - diretamente. -- A decisão precisa separar explicitamente "relocação de módulo" de "mudança de - ownership". - -## Opcoes - -### Opcao A - Agregar tudo na agenda de lifecycle - -**Abordagem:** -Usar `AGD-0032` para decidir lifecycle, ownership de serviços, layout de módulos -e promoção do `WindowManager`. - -**Vantagens:** -- uma única discussão cobre toda a direção do `SystemOS`; -- menos artefatos de workflow. - -**Custos / Riscos:** -- mistura semântica de lifecycle com limpeza estrutural; -- aumenta a chance de uma decisão grande demais; -- dificulta transformar a discussão em plans pequenos e verificáveis; -- pode bloquear lifecycle por causa de detalhes de módulo e borrow. - -### Opcao B - Separar uma agenda de service ownership e layout - -**Abordagem:** -Manter `AGD-0032` focada em lifecycle de `Task`/`Process` e usar esta agenda -para decidir onde vivem os serviços do OS, quais módulos devem ir para -`services`, e quais extrações são mecânicas ou semânticas. - -**Vantagens:** -- mantém a agenda principal limpa; -- permite um primeiro plan mecânico de relocação sem reabrir lifecycle; -- torna explícito que `LogService` sair da VM é mudança de ownership; -- cria base melhor para promover `WindowManager` sem confundir Hub e OS. - -**Custos / Riscos:** -- cria uma dependência a mais antes da implementação do lifecycle; -- pode revelar que alguns serviços exigem desenho de API antes do refactor; -- exige cuidado para atualizar callsites diretamente sem deixar caminhos antigos - exportados. - -### Opcao C - Fazer apenas os moves mecanicos direto no codigo - -**Abordagem:** -Mover `VirtualMachineRuntime` e `WindowManager` para `services` sem decisão -formal, deixando `LogService` para depois. - -**Vantagens:** -- rápido; -- baixo risco se for realmente só path/reexport; -- reduz ruído visual do layout atual. - -**Custos / Riscos:** -- não resolve a dúvida central de ownership; -- pode mascarar uma decisão arquitetural como refactor mecânico; -- viola a política do repositório se a mudança alterar fronteiras sem agenda e - decisão. - -## Sugestao / Recomendacao - -A recomendação é seguir a **Opção B**. - -Esta agenda deve ser separada da `AGD-0032`, mas tratada como pré-requisito ou -agenda paralela para ela. O primeiro contrato deve dividir o trabalho em dois -tipos: - -1. **Relocação mecânica sem mudança funcional** - - mover `VirtualMachineRuntime` para `services`; - - mover `WindowManager` para `services`; - - não manter reexports ou aliases de compatibilidade para os caminhos antigos; - - atualizar callsites diretamente para os caminhos novos; - - provar que o comportamento não mudou. - -2. **Correção de ownership de serviços** - - mover `LogService` para `SystemOS` se aceitarmos que logging é serviço do - OS; - - decidir se `VirtualFS`, `MemcardService`, diagnóstico, telemetria e - certificação ficam na VM, no OS, ou em serviços próprios; - - definir como a VM acessa serviços de OS sem voltar a ser dona deles. - -Para o primeiro corte, a inclinação é: - -- `VirtualMachineRuntime` deve ficar em `services`, como serviço de execução VM; -- `WindowManager` deve ficar em `services`, mesmo que ainda seja mínimo; -- `LogService` deve ser tratado como serviço de `SystemOS`, não detalhe interno - da VM; -- `VirtualFS` e `MemcardService` devem ser avaliados em seguida, sem mover tudo - junto automaticamente. - -## Perguntas em Aberto - -- [x] O path deve ser `services/vm_runtime` ou - `services/virtual_machine_runtime`? vm_runtime -- [x] `VirtualMachineRuntime` continua sendo o nome correto depois de virar - serviço, ou devemos introduzir um nome menor apenas no módulo? Podemos manter o mesmo nome -- [x] `LogService` deve sair da VM no mesmo plan do move mecânico, ou em um - plan separado de ownership? pode ser em um plan separado -- [x] A VM deve receber referência explícita ao logging do `SystemOS`, ou deve - chamar uma API de serviço mais estreita? A VM pode ter uma referência explícita ao logging do `SystemOS` para seu uso -- [x] `VirtualFS` e `MemcardService` pertencem ao `SystemOS` já, ou continuam na - VM até existir uma camada de permissões e mount por processo? podemos move-los para systemos jah -- [x] `WindowManager` deve virar campo do `SystemOS` imediatamente, ou primeiro - apenas sair de `PrometeuHub` em termos de módulo? eu diria que ele jah deve nascer em system os a partir de jah, mesmo que sem implementar nada -- [x] O `PrometeuHub` deve continuar expondo `window_manager` enquanto a Shell - visual ainda depende dele, ou isso deve ser mediado pelo `SystemOS` desde já? o prometeu hub eh um shell especial, ou seja, o window manager deve mediado pelo system os desde jah - -## Criterio para Encerrar - -Esta agenda pode virar decisão quando houver resposta para: - -- quais serviços pertencem ao `SystemOS` no primeiro corte; -- qual layout canônico de módulo será usado em `services`; -- quais mudanças são relocação mecânica e quais são ownership semântico; -- como `VirtualMachineRuntime` acessa `LogService` depois da extração; -- se `WindowManager` será apenas movido de módulo ou também promovido a campo do - `SystemOS`; -- como os callsites serão atualizados sem reexports temporários. - -## Proximo Passo - -Revisar esta agenda antes de fechar `AGD-0032`. Se a direção for aceita, o -próximo estágio deve ser uma decisão curta para fronteira de serviços do -`SystemOS`, seguida de plans pequenos: primeiro relocação mecânica, depois -extração de ownership onde houver contrato suficiente. diff --git a/discussion/workflow/decisions/DEC-0024-systemos-service-ownership-and-module-layout.md b/discussion/workflow/decisions/DEC-0024-systemos-service-ownership-and-module-layout.md deleted file mode 100644 index 50679e50..00000000 --- a/discussion/workflow/decisions/DEC-0024-systemos-service-ownership-and-module-layout.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -id: DEC-0024 -ticket: system-os-service-ownership-and-module-layout -title: SystemOS Service Ownership and Module Layout -status: accepted -created: 2026-05-14 -ref_agenda: AGD-0033 -tags: [runtime, os, services, module-layout, vm, window-manager, logging] ---- - -## Status - -Accepted. Esta decisão foi aceita em 2026-05-14 e passa a ser referência -normativa para os plans de ownership e layout de serviços do `SystemOS`. - -## Contexto - -`SystemOS` está se tornando o dono dos serviços de console em -`prometeu-system`. O formato atual ainda deixa responsabilidades de OS dentro ou -perto de `VirtualMachineRuntime` e `PrometeuHub`: - -- `VirtualMachineRuntime` vive no root do crate, embora agora seja um serviço de - execução VM do OS; -- `LogService` é owned por `VirtualMachineRuntime`, embora logging seja serviço - de observabilidade do OS; -- `VirtualFS` e `MemcardService` também ficam dentro de - `VirtualMachineRuntime`, embora representem serviços do sistema; -- `WindowManager` vive em `programs/prometeu_hub`, embora `PrometeuHub` deva ser - Shell/Home visual, não dono de serviços do OS. - -Esta decisão é separada da `AGD-0032`, que trata lifecycle de `Task`/`Process`. -Aqui o contrato é ownership de serviços e layout de módulos. - -## Decisao - -`SystemOS` SHALL ser o owner dos serviços do Prometeu OS. - -`VirtualMachineRuntime` SHALL representar somente execução VM. Ele MUST NOT ser -usado como container geral de serviços do sistema. - -O layout canônico da VM runtime SHALL ser: - -```text -crates/console/prometeu-system/src/services/vm_runtime/ -``` - -O nome público do tipo SHALL continuar `VirtualMachineRuntime`. - -`WindowManager` SHALL sair de `programs/prometeu_hub` e ir para a árvore -`services`. Ele SHALL ser owned ou mediado por `SystemOS` desde este estágio, -mesmo que a implementação continue mínima. - -`PrometeuHub` SHALL ser tratado como uma Shell/Home especial. Ele MUST NOT ser -owner do window manager como serviço de OS. O acesso do Hub a window management -MUST passar por `SystemOS` ou por uma superfície mediada pelo OS. - -`LogService` SHALL sair de `VirtualMachineRuntime` e virar serviço owned por -`SystemOS`. `VirtualMachineRuntime` MAY receber referência ou handle explícito -para o logging do OS quando precisar registrar eventos de execução VM, mas esse -acesso MUST NOT transformar a VM em owner de logging. - -`VirtualFS` e `MemcardService` SHALL mover para `SystemOS` neste cleanup de -ownership. A VM pode continuar usando capacidades de filesystem e memcard, mas -o ownership pertence ao boundary do OS. - -Esta decisão MUST NOT introduzir reexports ou aliases de compatibilidade para -os paths antigos. Os plans de implementação MUST atualizar callsites -diretamente. Novos imports MUST usar os paths canônicos de `services` e o -boundary de ownership do `SystemOS`. - -## Rationale - -O runtime está saindo de um runner de firmware para um console OS. Nesse modelo, -execução VM é um serviço do sistema, não o centro proprietário do sistema. Se -logging, filesystem, memcard, window management e futuramente lifecycle -continuarem dentro ou ao redor de `VirtualMachineRuntime`, a VM permanece como -owner de fato do OS. - -Mover `VirtualMachineRuntime` para `services/vm_runtime` alinha layout com -arquitetura: execução VM é serviço, não root. - -Mover `WindowManager` para `services` evita que `PrometeuHub` continue parecendo -o sistema inteiro. O Hub é Shell/Home e deve consumir serviços do OS. - -Mover `LogService`, `VirtualFS` e `MemcardService` para `SystemOS` cria uma base -mais limpa para permissões, processo/task ownership, mount policy, diagnóstico e -mediação da Shell. - -Não manter compatibilidade por reexport é aceitável agora porque esses paths são -internos e não há necessidade de janela longa de migração. Atualizar callsites -diretamente mantém o boundary claro. - -## Invariantes / Contrato - -- `SystemOS` MUST ser o ponto de ownership para serviços compartilhados do OS. -- `VirtualMachineRuntime` MUST NOT own `LogService`, `VirtualFS`, - `MemcardService` ou `WindowManager` depois dos plans correspondentes. -- `VirtualMachineRuntime` MAY usar serviços do OS por referência, handle ou API - estreita, mas MUST permanecer semanticamente executor VM. -- `PrometeuHub` MUST ser consumidor de OS services, não owner desses serviços. -- Paths antigos MUST NOT permanecer disponíveis por reexport ou alias. -- Mudanças de path MUST preservar comportamento observável. -- Esta decisão MUST NOT definir lifecycle de `Task`/`Process`; isso pertence à - `AGD-0032` e à decisão futura correspondente. - -## Impactos - -- `prometeu-system` deve ganhar layout de serviço mais coerente em `services`. -- `SystemOS` deve concentrar ownership de `LogService`, `VirtualFS`, - `MemcardService` e `WindowManager`. -- `VirtualMachineRuntime` deve reduzir escopo para execução VM. -- `PrometeuHub` deve começar a depender de mediação do OS para window - management. -- Firmware e testes podem precisar atualizar imports e construtores. -- Não há mudança exigida de ABI pública de cartucho. - -## Referencias - -- Agenda: `AGD-0033` -- Agenda relacionada: `AGD-0032` - -## Propagacao Necessaria - -- Plans: criar plans pequenos para relocação da VM runtime, promoção do - WindowManager e extração de ownership de serviços. -- Code: atualizar `prometeu-system`, `SystemOS`, `VirtualMachineRuntime`, - `PrometeuHub`, callsites de firmware e testes afetados. -- Tests: rodar a suíte Rust afetada e adicionar cobertura se ownership mudar - construtores ou caminhos de acesso. -- Specs: sem update obrigatório neste momento, salvo se plans futuros expuserem - o boundary em contrato público. -- Discussion: manter `AGD-0032` dependente desta decisão antes de planejar - lifecycle. diff --git a/discussion/workflow/decisions/DEC-0025-systemos-lifecycle-authority-for-tasks-and-processes.md b/discussion/workflow/decisions/DEC-0025-systemos-lifecycle-authority-for-tasks-and-processes.md deleted file mode 100644 index de7fe393..00000000 --- a/discussion/workflow/decisions/DEC-0025-systemos-lifecycle-authority-for-tasks-and-processes.md +++ /dev/null @@ -1,203 +0,0 @@ ---- -id: DEC-0025 -ticket: system-os-lifecycle-process-task-contract -title: SystemOS Lifecycle Authority for Tasks and Processes -status: accepted -created: 2026-05-15 -ref_agenda: AGD-0032 -tags: [runtime, os, lifecycle, process, task, shell, firmware] ---- - -## Status - -Accepted. Esta decisão foi aceita em 2026-05-15 e passa a ser referência -normativa para a primeira wave de lifecycle de `Task` e `Process` no -`SystemOS`. - -## Contexto - -`SystemOS` já agrega serviços centrais do Prometeu OS, incluindo runtime VM, -processos e tasks. A arquitetura anterior ainda permitia que firmware, -`TaskManager` e `ProcessManager` decidissem transições de lifecycle de forma -distribuída. - -Esse arranjo é insuficiente para um console OS: `Task` representa presença -navegável e experiência do usuário, enquanto `Process` representa execução -técnica. Essas duas dimensões precisam mudar juntas por uma autoridade -semântica única. - -`DEC-0024` já separou ownership/layout de serviços do `SystemOS`. Esta decisão -é focada apenas em lifecycle de `Task`/`Process` e não reabre a migração de -serviços, `WindowManager`, Hub ou ownership da VM. - -`AppMode::System` já foi renomeado para `AppMode::Shell`. O contrato público -fica: - -- `AppMode::Game`: cartucho executado como jogo/session fullscreen. -- `AppMode::Shell`: cartucho executado como app gerenciado pela Shell do - Prometeu OS. - -## Decisao - -`SystemOS` SHALL ser a autoridade normativa de lifecycle para `Task` e -`Process`. - -`TaskManager` e `ProcessManager` SHALL continuar existindo como mecanismos -internos de armazenamento e transição local, mas MUST NOT ser a API semântica -principal para lifecycle coordenado. Firmware e outros chamadores MUST delegate -transições semânticas de lifecycle para `SystemOS`. - -A primeira wave de lifecycle SHALL expor o contrato mínimo: - -```text -set_foreground_task(task_id) -suspend_task(task_id) -resume_task(task_id) -close_task(task_id) -crash_task(task_id, report?) -``` - -Essas operações SHALL coordenar `TaskState` e `ProcessState` juntos. - -O mapeamento normativo inicial SHALL ser: - -```text -TaskState::Foreground -> ProcessState::Running -TaskState::Suspended -> ProcessState::Suspended -TaskState::Closed -> ProcessState::Stopped -TaskState::Crashed -> ProcessState::Crashed -``` - -`Background` SHALL remain reserved and MUST NOT guide any public lifecycle API -in the first wave. - -`resume_task` SHALL mean resuming active user-perceived execution. In this first -wave, it MUST move a suspended task to `TaskState::Foreground` and its associated -process to `ProcessState::Running`. - -`close_task` SHALL mark task/process state only. It MUST NOT remove task or -process entities immediately. Collection of closed/stopped entities is a future -separate operation. - -`crash_task` SHALL be the semantic crash operation for a task. The first wave MAY -only coordinate `TaskState::Crashed` and `ProcessState::Crashed`, but the -signature SHOULD either accept or remain compatible with a future `CrashReport` -handoff to diagnostics/logging. - -`GameRunningStep` SHALL keep the strong invariant that an active game execution -step only supports a game task in `TaskState::Foreground`. In this wave, any -non-foreground game task observed by `GameRunningStep` is invalid and should -produce clear diagnostic/crash behavior rather than silently running frames. - -## Rationale - -Centralizing lifecycle in `SystemOS` prevents firmware from becoming the de -facto OS policy layer. Firmware should remain a boot/execution state machine; it -should not know how to update `TaskState` and `ProcessState` in lockstep. - -Keeping `TaskManager` and `ProcessManager` as internal mechanisms preserves -simple storage and local transition responsibilities while giving the OS a -single semantic boundary for suspend, resume, close, crash and foreground -selection. - -Leaving `Background` out of the first wave avoids freezing an incomplete model -for docked apps, background services, non-focused shell apps or capability-gated -execution. The reserved enum state can remain, but no normative public lifecycle -API should depend on it yet. - -Making `resume_task` return to `Foreground` keeps the first contract simple and -matches the user-perceived meaning of resume. Future background wake/service -semantics should be introduced as separate concepts rather than overloading -`resume_task`. - -Marking closed/stopped entities instead of removing them immediately preserves -room for diagnostics, crash handling, system UI history and later collection -policy. - -## Invariantes / Contrato - -- `SystemOS` MUST coordinate lifecycle operations that affect both task and - process state. -- Firmware MUST NOT call separate task/process manager transitions to implement - semantic lifecycle operations such as suspend, resume, close or crash. -- `set_foreground_task(task_id)` MUST set the task to `TaskState::Foreground` - and its associated process to `ProcessState::Running`. -- `suspend_task(task_id)` MUST set the task to `TaskState::Suspended` and its - associated process to `ProcessState::Suspended`. -- `resume_task(task_id)` MUST move from suspended user-visible execution back to - foreground execution: `TaskState::Foreground` and `ProcessState::Running`. -- `close_task(task_id)` MUST set `TaskState::Closed` and - `ProcessState::Stopped`. -- `crash_task(task_id, report?)` MUST set `TaskState::Crashed` and - `ProcessState::Crashed`. -- A missing task MUST return a typed lifecycle error such as - `LifecycleError::TaskNotFound(TaskId)`. -- A task whose associated process is missing MUST return a typed lifecycle error - such as `LifecycleError::ProcessNotFound(ProcessId)`. -- Invalid lifecycle transitions SHOULD return a typed error carrying the task, - source state and requested operation. -- `Background` MUST NOT have normative first-wave semantics. -- This decision MUST NOT move `WindowManager`, redesign `PrometeuHub`, introduce - background services, implement docking, implement app switching, or make - `ProcessManager` own the VM. - -The expected first-wave error shape is: - -```rust -pub enum LifecycleError { - TaskNotFound(TaskId), - ProcessNotFound(ProcessId), - InvalidTransition { - task_id: TaskId, - from: TaskState, - operation: LifecycleOperation, - }, -} -``` - -`LifecycleOperation` SHOULD identify at least: - -```text -SetForeground -Suspend -Resume -Close -Crash -``` - -## Impactos - -- `prometeu-system` must expose lifecycle methods on `SystemOS`. -- `TaskManager` and `ProcessManager` may need smaller internal transition - helpers, but not public semantic ownership of lifecycle. -- Firmware code should call `system_os.suspend_task(...)`, - `system_os.resume_task(...)`, `system_os.close_task(...)`, - `system_os.crash_task(...)` and `system_os.set_foreground_task(...)` instead - of coordinating task/process managers directly. -- Tests should move lifecycle assertions to the `SystemOS` level. -- Specs do not need to change before the first code plan unless the lifecycle - API is promoted to a public external contract. -- `DEC-0024` remains valid and complementary; ownership/layout work can execute - in parallel and does not block this first lifecycle wave. - -## Referencias - -- Agenda: `AGD-0032` -- Related decision: `DEC-0024` - -## Propagacao Necessaria - -- Plan: create `PLAN-0032-A: SystemOS Lifecycle API`. -- Code: update `prometeu-system` `SystemOS`, task/process lifecycle helpers, - firmware callsites if they currently coordinate managers directly, and unit - tests. -- Tests: add unit coverage for successful lifecycle mappings, missing task, - missing process and invalid transition handling. -- Discussion: keep `Background` reserved for a future agenda covering dock, - services, non-focused shell apps and capability-gated execution. -- Learn: after implementation is complete, write or update lessons only from the - published state. - -## Revisao - -- 2026-05-15: Initial accepted decision from `AGD-0032`. diff --git a/discussion/workflow/plans/PLN-0051-move-vm-runtime-into-services.md b/discussion/workflow/plans/PLN-0051-move-vm-runtime-into-services.md deleted file mode 100644 index a2f5a77e..00000000 --- a/discussion/workflow/plans/PLN-0051-move-vm-runtime-into-services.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -id: PLN-0051 -ticket: system-os-service-ownership-and-module-layout -title: Move VM Runtime Into Services -status: done -created: 2026-05-14 -ref_decisions: [DEC-0024] -tags: [runtime, os, services, module-layout, vm, window-manager, logging] ---- - -## Briefing - -Implement the mechanical module relocation required by `DEC-0024`: move -`VirtualMachineRuntime` from the `prometeu-system` crate root into the services -tree at `services/vm_runtime`. - -This plan is intentionally behavior-preserving. It prepares the service layout -for later ownership plans without moving logging, filesystem, or memcard state. - -## Source Decisions - -- `DEC-0024`: `VirtualMachineRuntime` SHALL move to - `services/vm_runtime`; old root paths MUST NOT remain available through - compatibility reexports. - -## Target - -Make `VirtualMachineRuntime` a service module while keeping the public type name -unchanged and preserving current VM behavior. - -The canonical implementation path after this plan is: - -```text -crates/console/prometeu-system/src/services/vm_runtime/ -``` - -## Dependencies - -- Source decision: `DEC-0024`. -- No prior plan is required. -- This plan should run before `PLN-0052`, `PLN-0053`, and `PLN-0054`. - -## Scope - -- Move `crates/console/prometeu-system/src/virtual_machine_runtime.rs` to - `crates/console/prometeu-system/src/services/vm_runtime.rs` or equivalent - module root under `services/vm_runtime`. -- Move the existing `virtual_machine_runtime/` child modules under - `services/vm_runtime/`. -- Update `crates/console/prometeu-system/src/services/mod.rs` to expose - `vm_runtime`. -- Update `crates/console/prometeu-system/src/lib.rs` to export - `VirtualMachineRuntime` from `services::vm_runtime`. -- Update internal module paths and tests directly. - -## Out of Scope - -- Do not move `LogService` ownership. -- Do not move `VirtualFS` or `MemcardService` ownership. -- Do not move `WindowManager`. -- Do not introduce reexports or aliases for the old root module path. -- Do not change VM runtime behavior, syscalls, telemetry, logging semantics, or - cartridge execution behavior. - -## Execution Plan - -1. Move the VM runtime module files into `src/services/vm_runtime/`. -2. Register `pub mod vm_runtime;` from `src/services/mod.rs`. -3. Remove the root `mod virtual_machine_runtime;` declaration from `src/lib.rs`. -4. Export `VirtualMachineRuntime` through the services path. -5. Update `SystemOS`, tests, and any internal imports to use the new module - location. -6. Run formatting and the affected Rust tests. - -## Acceptance Criteria - -- `VirtualMachineRuntime` implementation lives under `services/vm_runtime`. -- No root `virtual_machine_runtime` module remains in `prometeu-system`. -- No compatibility reexport preserves the old root module path. -- Public type name `VirtualMachineRuntime` remains available where the crate API - intentionally exposes it. -- Runtime behavior remains unchanged. - -## Tests / Validation - -- Run `cargo test -p prometeu-system`. -- If workspace constraints make that too broad, run the narrowest available - `prometeu-system` test target and record the exact command in implementation - evidence. - -## Risks - -- Module move churn can hide accidental import compatibility. Review must check - that no old root module remains. -- Test modules may need path updates because they currently live under the VM - runtime module tree. - -## Affected Artifacts - -- `crates/console/prometeu-system/src/lib.rs` -- `crates/console/prometeu-system/src/services/mod.rs` -- `crates/console/prometeu-system/src/services/vm_runtime/**` -- Existing VM runtime tests moved with the module diff --git a/discussion/workflow/plans/PLN-0052-promote-window-manager-to-systemos-service.md b/discussion/workflow/plans/PLN-0052-promote-window-manager-to-systemos-service.md deleted file mode 100644 index 1202fb39..00000000 --- a/discussion/workflow/plans/PLN-0052-promote-window-manager-to-systemos-service.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -id: PLN-0052 -ticket: system-os-service-ownership-and-module-layout -title: Promote Window Manager To SystemOS Service -status: done -created: 2026-05-14 -ref_decisions: [DEC-0024] -tags: [runtime, os, services, module-layout, vm, window-manager, logging] ---- - -## Briefing - -Promote `WindowManager` from a `PrometeuHub` private module into an OS service -owned or mediated by `SystemOS`, as required by `DEC-0024`. - -## Source Decisions - -- `DEC-0024`: `WindowManager` SHALL move to the services tree and SHALL be - owned or mediated by `SystemOS`; `PrometeuHub` MUST NOT own it as an OS - service. - -## Target - -Make `WindowManager` part of the `services` tree and stop treating -`PrometeuHub` as the owner of window management. - -## Dependencies - -- Source decision: `DEC-0024`. -- Depends on `PLN-0051` only for the general service layout convention. - -## Scope - -- Move `crates/console/prometeu-system/src/programs/prometeu_hub/window_manager.rs` - into the `services` tree. -- Expose the service from `crates/console/prometeu-system/src/services/mod.rs`. -- Add a `WindowManager` field or OS-mediated access path on `SystemOS`. -- Remove `window_manager` ownership from `PrometeuHub`. -- Update `PrometeuHub` to access window management through `SystemOS`. -- Update tests and imports directly. - -## Out of Scope - -- Do not implement new windowing behavior. -- Do not define surface/window lifecycle beyond the existing minimal behavior. -- Do not introduce old-path compatibility reexports. -- Do not change task/process lifecycle semantics. - -## Execution Plan - -1. Move the `WindowManager` module into `src/services/`. -2. Register the new service module in `services/mod.rs`. -3. Add `WindowManager` initialization to `SystemOS::new`. -4. Remove `WindowManager` storage from `PrometeuHub`. -5. Update Hub methods so their window manager access is mediated by `SystemOS`. -6. Update tests for the new module path and ownership location. -7. Run formatting and the affected tests. - -## Acceptance Criteria - -- `WindowManager` no longer lives under `programs/prometeu_hub`. -- `PrometeuHub` does not own a `WindowManager` field. -- `SystemOS` owns or mediates access to `WindowManager`. -- No old `programs::prometeu_hub::window_manager` path remains available. -- Existing Hub behavior remains unchanged. - -## Tests / Validation - -- Run `cargo test -p prometeu-system`. -- Include any focused tests for `WindowManager` after the move. - -## Risks - -- `PrometeuHub` currently owns its `WindowManager`; moving ownership may require - method signatures to pass through `SystemOS` cleanly. -- The implementation must not accidentally introduce new window/surface - semantics while moving ownership. - -## Affected Artifacts - -- `crates/console/prometeu-system/src/programs/prometeu_hub/mod.rs` -- `crates/console/prometeu-system/src/programs/prometeu_hub/prometeu_hub.rs` -- `crates/console/prometeu-system/src/services/mod.rs` -- `crates/console/prometeu-system/src/services/window_manager.rs` or equivalent -- `crates/console/prometeu-system/src/os/system_os.rs` diff --git a/discussion/workflow/plans/PLN-0053-move-logging-ownership-to-systemos.md b/discussion/workflow/plans/PLN-0053-move-logging-ownership-to-systemos.md deleted file mode 100644 index b5bea105..00000000 --- a/discussion/workflow/plans/PLN-0053-move-logging-ownership-to-systemos.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -id: PLN-0053 -ticket: system-os-service-ownership-and-module-layout -title: Move Logging Ownership To SystemOS -status: done -created: 2026-05-14 -ref_decisions: [DEC-0024] -tags: [runtime, os, services, module-layout, vm, window-manager, logging] ---- - -## Briefing - -Move `LogService` ownership from `VirtualMachineRuntime` to `SystemOS`, while -allowing VM execution code to use OS logging through an explicit reference or -handle. - -## Source Decisions - -- `DEC-0024`: `LogService` SHALL move from `VirtualMachineRuntime` to - `SystemOS`; VM execution MAY use an explicit OS logging reference or handle - but MUST NOT own logging. - -## Target - -Make logging an OS-owned service and reduce `VirtualMachineRuntime` to a user of -logging rather than its owner. - -## Dependencies - -- Source decision: `DEC-0024`. -- Depends on `PLN-0051`. -- May run after or alongside `PLN-0052`, but code integration is simpler after - `SystemOS` service ownership is established. - -## Scope - -- Add `LogService` ownership to `SystemOS`. -- Remove `log_service: LogService` from `VirtualMachineRuntime`. -- Update VM runtime methods that read/write logs to receive logging access from - `SystemOS` or a narrow explicit handle. -- Update construction paths so `LogService::new(4096)` is owned by `SystemOS`. -- Update tests that currently inspect runtime-owned logs. - -## Out of Scope - -- Do not change log capacity or log record semantics. -- Do not change VM syscall behavior except for the ownership path. -- Do not introduce compatibility accessors that imply VM ownership. -- Do not move filesystem or memcard ownership in this plan. - -## Execution Plan - -1. Add a `LogService` field to `SystemOS` and initialize it in `SystemOS::new`. -2. Remove `LogService` initialization and storage from - `VirtualMachineRuntime::new`. -3. Update VM logging call paths in `dispatch`, `tick`, lifecycle, and tests to - use OS-owned logging. -4. If borrow constraints require it, introduce a narrow logging handle/reference - parameter at the call boundary instead of giving the VM ownership. -5. Update all tests that assert logging behavior. -6. Run formatting and tests. - -## Acceptance Criteria - -- `VirtualMachineRuntime` no longer stores `LogService`. -- `SystemOS` owns `LogService`. -- VM execution can still emit and expose logs through the existing behavior. -- No compatibility API suggests that logging remains VM-owned. -- Existing logging tests pass or are updated to assert OS ownership. - -## Tests / Validation - -- Run `cargo test -p prometeu-system`. -- Include focused tests covering VM log writes and reads after ownership moves - to `SystemOS`. - -## Risks - -- Borrowing constraints around `NativeInterface` may require a narrow access - pattern rather than simply borrowing all of `SystemOS`. -- Tests that currently construct only `VirtualMachineRuntime` may need to move - to `SystemOS` construction to reflect the new owner. - -## Affected Artifacts - -- `crates/console/prometeu-system/src/os/system_os.rs` -- `crates/console/prometeu-system/src/services/vm_runtime/**` -- Tests under the VM runtime module diff --git a/discussion/workflow/plans/PLN-0054-move-fs-and-memcard-ownership-to-systemos.md b/discussion/workflow/plans/PLN-0054-move-fs-and-memcard-ownership-to-systemos.md deleted file mode 100644 index b76d8581..00000000 --- a/discussion/workflow/plans/PLN-0054-move-fs-and-memcard-ownership-to-systemos.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -id: PLN-0054 -ticket: system-os-service-ownership-and-module-layout -title: Move FS And Memcard Ownership To SystemOS -status: done -created: 2026-05-14 -ref_decisions: [DEC-0024] -tags: [runtime, os, services, module-layout, vm, window-manager, logging] ---- - -## Briefing - -Move `VirtualFS` and `MemcardService` ownership from `VirtualMachineRuntime` to -`SystemOS`, preserving current VM filesystem and memcard behavior. - -## Source Decisions - -- `DEC-0024`: `VirtualFS` and `MemcardService` SHALL move from - `VirtualMachineRuntime` to `SystemOS`; VM execution may use them, but OS owns - the service state. - -## Target - -Make filesystem and memcard OS-owned services while keeping VM syscalls and -tests behaviorally equivalent. - -## Dependencies - -- Source decision: `DEC-0024`. -- Depends on `PLN-0051`. -- Should run after `PLN-0053` so the pattern for VM access to OS-owned services - is already established. - -## Scope - -- Add `VirtualFS`, `FsState`, `MemcardService`, open file handle state, and - related handle allocation state to `SystemOS` if they are currently VM-owned - service state. -- Remove direct ownership of `VirtualFS` and `MemcardService` from - `VirtualMachineRuntime`. -- Update FS and memcard syscall paths so VM execution uses OS-owned services. -- Update tests that currently create a bare `VirtualMachineRuntime` when they - need filesystem or memcard services. -- Keep service modules under `services/fs` and `services/memcard`. - -## Out of Scope - -- Do not redesign filesystem semantics, path normalization, memcard slot - semantics, or persistence policy. -- Do not introduce process permissions or mount namespaces. -- Do not change cartridge ABI. -- Do not move unrelated telemetry, certification, asset, or debug state unless - required by compilation and explicitly documented in implementation evidence. - -## Execution Plan - -1. Identify the complete set of FS/memcard-owned fields currently stored in - `VirtualMachineRuntime`. -2. Add the OS-owned fields to `SystemOS` and initialize them in `SystemOS::new`. -3. Remove those service fields from `VirtualMachineRuntime`. -4. Update VM dispatch/syscall code to operate on OS-owned FS and memcard state - through explicit references or narrow access methods. -5. Update tests to construct `SystemOS` when testing FS/memcard behavior through - VM execution. -6. Run formatting and the affected Rust tests. - -## Acceptance Criteria - -- `VirtualMachineRuntime` no longer owns `VirtualFS` or `MemcardService`. -- `SystemOS` owns filesystem and memcard service state needed by VM execution. -- Existing FS and memcard behavior is preserved. -- No compatibility path implies VM ownership of FS or memcard services. -- Any remaining VM-owned fields are execution-specific and justified by the - implementation evidence. - -## Tests / Validation - -- Run `cargo test -p prometeu-system`. -- Include focused FS and memcard tests after updating constructors/access paths. - -## Risks - -- FS and memcard syscalls are stateful and may be coupled to open handle fields - in `VirtualMachineRuntime`; the implementation must move the whole service - state coherently. -- Bare VM tests may need broader OS fixtures, which can reveal unrelated setup - assumptions. - -## Affected Artifacts - -- `crates/console/prometeu-system/src/os/system_os.rs` -- `crates/console/prometeu-system/src/services/fs/**` -- `crates/console/prometeu-system/src/services/memcard.rs` -- `crates/console/prometeu-system/src/services/vm_runtime/**` -- FS/memcard runtime tests diff --git a/discussion/workflow/plans/PLN-0055-systemos-lifecycle-core-api.md b/discussion/workflow/plans/PLN-0055-systemos-lifecycle-core-api.md deleted file mode 100644 index 51bfd989..00000000 --- a/discussion/workflow/plans/PLN-0055-systemos-lifecycle-core-api.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -id: PLN-0055 -ticket: system-os-lifecycle-process-task-contract -title: SystemOS Lifecycle Core API -status: done -created: 2026-05-15 -ref_decisions: [DEC-0025] -tags: [runtime, os, lifecycle, process, task, shell, firmware] ---- - -## Briefing - -Implement the first-wave `SystemOS` lifecycle API required by `DEC-0025`. -`SystemOS` becomes the semantic coordinator for `TaskState` and `ProcessState`; -`TaskManager` and `ProcessManager` remain storage and simple transition -mechanisms. - -## Source Decisions - -- `DEC-0025`: `SystemOS` is the lifecycle authority for tasks and processes. - -## Target - -Add typed lifecycle operations to `prometeu-system` without changing firmware -behavior, WindowManager ownership, Hub UI, background services, docking, app -switching, or VM ownership. - -## Scope - -- Add `LifecycleError` and `LifecycleOperation` in `prometeu-system`. -- Add lifecycle methods on `SystemOS`: - - `set_foreground_task(task_id)` - - `suspend_task(task_id)` - - `resume_task(task_id)` - - `close_task(task_id)` - - `crash_task(task_id, report?)` -- Coordinate task and process state changes inside `SystemOS`. -- Preserve `TaskManager` and `ProcessManager` as internal state managers. -- Keep `Background` reserved and out of public lifecycle semantics. - -## Out of Scope - -- Background semantics. -- Docking. -- Background services. -- App switcher. -- WindowManager migration. -- PrometeuHub redesign. -- Game suspend/resume UX. -- ProcessManager owning VM execution. -- Collection/removal of closed or stopped entities. - -## Execution Plan - -1. Add lifecycle types. - - Create a lifecycle module or colocate the types under - `crates/console/prometeu-system/src/os/`. - - Define `LifecycleOperation` with `SetForeground`, `Suspend`, `Resume`, - `Close`, and `Crash`. - - Define `LifecycleError` with `TaskNotFound(TaskId)`, - `ProcessNotFound(ProcessId)`, and `InvalidTransition { task_id, from, - operation }`. - - Re-export the types through `prometeu-system` only if the existing public - module style requires it. - -2. Add the `SystemOS` coordination helpers. - - Target file: `crates/console/prometeu-system/src/os/system_os.rs`. - - Resolve the task first through `task_manager`. - - Extract the task's associated `ProcessId`. - - Validate that the process exists before mutating state. - - Return typed errors instead of `bool`. - -3. Implement first-wave operations. - - `set_foreground_task`: call `task_manager.set_foreground(task_id)` and - `process_manager.mark_running(process_id)`. - - `suspend_task`: set `TaskState::Suspended` and - `ProcessState::Suspended`. - - `resume_task`: require a suspended task, then set - `TaskState::Foreground` and `ProcessState::Running`. - - `close_task`: set `TaskState::Closed` and `ProcessState::Stopped`. - - `crash_task`: set `TaskState::Crashed` and `ProcessState::Crashed`. - -4. Keep manager APIs mechanical. - - Target files: - `crates/console/prometeu-system/src/services/task/task_manager.rs` and - `crates/console/prometeu-system/src/services/process/process_manager.rs`. - - Do not remove existing manager methods in this plan. - - Add only narrow helpers if needed to support the `SystemOS` API cleanly. - -5. Update task creation to use the lifecycle API internally. - - In `SystemOS::create_vm_game_task`, `create_vm_shell_task`, and - `create_native_shell_task`, replace direct foreground manager calls with - `set_foreground_task`. - - Keep the constructors returning `TaskId`; handle impossible internal - errors with explicit debug/assert behavior or an internal helper that - cannot fail after creation. - -## Acceptance Criteria - -- `SystemOS` exposes all five first-wave lifecycle methods from `DEC-0025`. -- All five methods coordinate both task and process state. -- Missing task returns `LifecycleError::TaskNotFound`. -- Missing associated process returns `LifecycleError::ProcessNotFound`. -- Invalid resume from a non-suspended task returns `InvalidTransition`. -- `Background` is not exposed through a new lifecycle API. -- Closed and stopped entities are not removed by `close_task`. - -## Tests / Validation - -- Add or update unit tests in `prometeu-system` for each lifecycle mapping. -- Add tests for missing task, missing process, and invalid resume transition. -- Run the affected Rust test suite for `prometeu-system`. - -## Risks - -- Existing direct manager access is public enough that callsites may keep using - it. This plan does not remove those methods; enforcement continues in - `PLN-0056`. -- `TaskManager::set_foreground` currently moves the previous foreground task to - `Background`. Since `Background` is out of first-wave semantics, tests must - avoid treating that transition as normative lifecycle policy. diff --git a/discussion/workflow/plans/PLN-0056-firmware-lifecycle-delegation.md b/discussion/workflow/plans/PLN-0056-firmware-lifecycle-delegation.md deleted file mode 100644 index 5c2500d9..00000000 --- a/discussion/workflow/plans/PLN-0056-firmware-lifecycle-delegation.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -id: PLN-0056 -ticket: system-os-lifecycle-process-task-contract -title: Firmware Lifecycle Delegation -status: done -created: 2026-05-15 -ref_decisions: [DEC-0025] -tags: [runtime, os, lifecycle, process, task, shell, firmware] ---- - -## Briefing - -Move firmware lifecycle callsites to the `SystemOS` semantic API introduced by -`PLN-0055`. Firmware remains a boot and execution state machine; it must not -coordinate task/process lifecycle by calling `TaskManager` and `ProcessManager` -separately. - -## Source Decisions - -- `DEC-0025`: firmware must delegate semantic lifecycle transitions to - `SystemOS`. - -## Target - -Replace direct lifecycle manipulation in firmware with `SystemOS` lifecycle -methods while preserving current observable behavior. - -## Scope - -- Update cartridge launch paths to use `SystemOS` lifecycle authority when - placing newly created tasks in foreground. -- Update crash paths where a task crash is detected so task/process state moves - through `SystemOS::crash_task`. -- Preserve the strong `GameRunningStep` invariant: a running game step only - supports a game task in `TaskState::Foreground`. -- Keep `SystemRunningStep`, Hub, and WindowManager behavior unchanged except for - lifecycle delegation required by `DEC-0025`. - -## Out of Scope - -- Full game suspend/resume UX. -- Returning to Hub/Home on suspend or close. -- Shell UI redesign. -- App switcher. -- Background task API. -- WindowManager migration. -- Diagnostics service or crash report persistence. - -## Execution Plan - -1. Audit direct lifecycle manager usage. - - Target files: - `crates/console/prometeu-firmware/src/firmware/*.rs`, - `crates/console/prometeu-system/src/os/system_os.rs`. - - Search for direct calls to `task_manager.set_foreground`, - `task_manager.mark_suspended`, `task_manager.close_task`, - `task_manager.mark_crashed`, `process_manager.mark_suspended`, - `process_manager.mark_stopped`, and `process_manager.mark_crashed`. - -2. Keep launch construction inside `SystemOS`. - - Target file: - `crates/console/prometeu-system/src/os/system_os.rs`. - - Ensure `create_vm_game_task`, `create_vm_shell_task`, and - `create_native_shell_task` coordinate foreground/running state through the - lifecycle core API from `PLN-0055`. - -3. Update game crash handling. - - Target file: - `crates/console/prometeu-firmware/src/firmware/firmware_step_game_running.rs`. - - When the task is missing, preserve current crash-screen behavior. If the - task does not exist, `SystemOS::crash_task` cannot attach state and the - firmware should continue producing a clear crash report. - - When a foreground invariant fails for an existing task, call - `ctx.os.crash_task(task_id, report?)` before transitioning to - `AppCrashesStep`. - - When `tick_vm` returns a crash report for the active task, call - `ctx.os.crash_task(task_id, report?)` before transitioning to - `AppCrashesStep`. - -4. Keep shell launch behavior unchanged. - - Target file: - `crates/console/prometeu-firmware/src/firmware/firmware_step_load_cartridge.rs`. - - Do not move `WindowManager` logic. - - Do not change shell window creation or focus behavior. - - Rely on `SystemOS::create_vm_shell_task` to coordinate task/process - foreground state. - -5. Avoid introducing background lifecycle. - - Do not add `background_task`. - - Do not treat `TaskState::Background` as a public lifecycle result in - firmware. - -## Acceptance Criteria - -- Firmware does not coordinate task/process lifecycle by manually changing both - managers. -- Game VM crash results in `SystemOS::crash_task` for the active task when the - task still exists. -- Foreground invariant violation in `GameRunningStep` crashes the task through - `SystemOS`. -- Launch behavior for `AppMode::Game` and `AppMode::Shell` remains unchanged. -- WindowManager and Hub behavior are not redesigned or moved. - -## Tests / Validation - -- Run firmware tests that cover cartridge launch for `AppMode::Game` and - `AppMode::Shell`. -- Add or update tests for `GameRunningStep` crash delegation if the existing - test harness supports firmware step testing. -- Run the affected Rust test suite for `prometeu-firmware`. - -## Risks - -- Crash report ownership is not final. This plan should pass the report through - the lifecycle API only to the extent supported by `PLN-0055`; persistence - remains out of scope. -- `GameRunningStep` currently reads task state directly. This is acceptable for - enforcing the foreground invariant, but it must not become a place that - coordinates lifecycle state across managers. diff --git a/discussion/workflow/plans/PLN-0057-lifecycle-tests-and-invariants.md b/discussion/workflow/plans/PLN-0057-lifecycle-tests-and-invariants.md deleted file mode 100644 index 99a4b181..00000000 --- a/discussion/workflow/plans/PLN-0057-lifecycle-tests-and-invariants.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -id: PLN-0057 -ticket: system-os-lifecycle-process-task-contract -title: Lifecycle Tests and Invariants -status: done -created: 2026-05-15 -ref_decisions: [DEC-0025] -tags: [runtime, os, lifecycle, process, task, shell, firmware] ---- - -## Briefing - -Add focused test coverage and invariant checks for the lifecycle contract -introduced by `PLN-0055` and consumed by `PLN-0056`. - -## Source Decisions - -- `DEC-0025`: first-wave lifecycle maps task states to process states through - `SystemOS` and keeps `Background` outside the public lifecycle contract. - -## Target - -Make the lifecycle contract executable through unit tests and regression tests, -without expanding scope into background execution, UI behavior, or service -ownership. - -## Scope - -- Add `SystemOS` unit tests for all first-wave lifecycle operations. -- Add negative tests for missing task, missing process, and invalid transition. -- Add firmware-level regression coverage for lifecycle delegation where the - existing test harness can observe it. -- Keep manager tests focused on local storage and simple transitions. - -## Out of Scope - -- End-to-end UX tests for suspend/resume. -- Hub/Home navigation after lifecycle changes. -- Background services. -- Docking. -- App switching. -- Diagnostics persistence. -- WindowManager behavior changes. - -## Execution Plan - -1. Add core lifecycle mapping tests. - - Target file: `crates/console/prometeu-system/src/os/system_os.rs` or a - dedicated `os` test module following existing crate style. - - Verify: - - `set_foreground_task`: task becomes `Foreground`, process becomes - `Running`. - - `suspend_task`: task becomes `Suspended`, process becomes `Suspended`. - - `resume_task`: suspended task becomes `Foreground`, process becomes - `Running`. - - `close_task`: task becomes `Closed`, process becomes `Stopped`. - - `crash_task`: task becomes `Crashed`, process becomes `Crashed`. - -2. Add error tests. - - Verify missing task returns `LifecycleError::TaskNotFound`. - - Verify a task whose process no longer exists returns - `LifecycleError::ProcessNotFound`. - - Verify invalid resume from non-suspended task returns - `LifecycleError::InvalidTransition` with operation `Resume`. - -3. Add non-removal tests. - - Verify `close_task` leaves the closed task available through - `TaskManager::get`. - - Verify `close_task` leaves the stopped process available through - `ProcessManager::get`. - - Do not call `remove_closed` or `remove_stopped` as part of lifecycle API - tests. - -4. Add background exclusion tests. - - Assert there is no `SystemOS::background_task` API added by this wave. - - Keep any existing `TaskState::Background` behavior in manager-level tests - documented as manager behavior, not first-wave lifecycle semantics. - -5. Add firmware regression tests after `PLN-0056`. - - Target file: `crates/console/prometeu-firmware/src/firmware/firmware.rs` - or the relevant step test module. - - Verify game launch still enters `GameRunningStep`. - - Verify shell launch still enters `SystemRunningStep`. - - Verify a game crash path marks the active task as crashed when the test - harness can observe `ctx.os.task_manager`. - -## Acceptance Criteria - -- Every lifecycle method from `DEC-0025` has a positive `SystemOS` test. -- Missing task and missing process return typed lifecycle errors. -- Invalid resume transition is covered by a test. -- `close_task` is tested as mark-only, not removal. -- No test encodes `Background` as a normative first-wave lifecycle operation. -- Firmware regression tests still pass for game and shell launch. - -## Tests / Validation - -- Run `cargo test -p prometeu-system`. -- Run `cargo test -p prometeu-firmware`. -- If workspace-level tests are practical after these changes, run the relevant - workspace command used by this repository. - -## Risks - -- Some negative tests may require test-only helpers to create an inconsistent - task/process relationship. Prefer narrow test fixtures over making corruption - APIs public. -- Compile-time absence of `background_task` may not be directly testable - without compile-fail infrastructure. In that case, validate it by code review - and keep runtime tests focused on the exposed first-wave methods.