World Editor / Stage Editor Sync

This commit is contained in:
Nilton Constantino 2026-06-20 17:08:26 +01:00
parent 3612d00cdc
commit d0777cf2ba
No known key found for this signature in database
7 changed files with 989 additions and 1 deletions

View File

@ -1,2 +1,3 @@
{"type":"meta","next_id":{"DSC":2,"AGD":2,"DEC":2,"PLN":5,"LSN":2,"CLSN":1}} {"type":"meta","next_id":{"DSC":3,"AGD":3,"DEC":3,"PLN":9,"LSN":2,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"world-editor-journey-spec","title":"World Editor / Journey Spec","created_at":"2026-06-19","updated_at":"2026-06-20","tags":["world-editor","journey","stage-contract","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-world-editor-journey-spec/LSN-0001-editor-authoring-runtime-publication.md","status":"done","created_at":"2026-06-20","updated_at":"2026-06-20"}]} {"type":"discussion","id":"DSC-0001","status":"done","ticket":"world-editor-journey-spec","title":"World Editor / Journey Spec","created_at":"2026-06-19","updated_at":"2026-06-20","tags":["world-editor","journey","stage-contract","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-world-editor-journey-spec/LSN-0001-editor-authoring-runtime-publication.md","status":"done","created_at":"2026-06-20","updated_at":"2026-06-20"}]}
{"type":"discussion","id":"DSC-0002","status":"accepted","ticket":"world-stage-editor-sync","title":"World Editor / Stage Editor Sync","created_at":"2026-06-20","updated_at":"2026-06-21","tags":["world-editor","stage-editor","sync","stage-definition"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-world-stage-editor-sync.md","status":"accepted","created_at":"2026-06-20","updated_at":"2026-06-20"}],"decisions":[{"id":"DEC-0002","file":"DEC-0002-world-stage-editor-sync-v1.md","status":"accepted","created_at":"2026-06-20","updated_at":"2026-06-21","ref_agenda":"AGD-0002"}],"plans":[{"id":"PLN-0005","file":"PLN-0005-stage-world-sync-data.md","status":"open","created_at":"2026-06-21","updated_at":"2026-06-21","ref_decisions":["DEC-0002"]},{"id":"PLN-0006","file":"PLN-0006-world-editor-stage-definition-sync-action.md","status":"open","created_at":"2026-06-21","updated_at":"2026-06-21","ref_decisions":["DEC-0002"]},{"id":"PLN-0007","file":"PLN-0007-world-stage-sync-validation.md","status":"open","created_at":"2026-06-21","updated_at":"2026-06-21","ref_decisions":["DEC-0002"]},{"id":"PLN-0008","file":"PLN-0008-stage-editor-world-sync-underlay.md","status":"open","created_at":"2026-06-21","updated_at":"2026-06-21","ref_decisions":["DEC-0002"]}],"lessons":[]}

View File

@ -0,0 +1,220 @@
---
id: AGD-0002
ticket: world-stage-editor-sync
title: World Editor / Stage Editor Sync
status: accepted
created: 2026-06-20
resolved: 2026-06-20
decision: DEC-0002
tags:
- world-editor
- stage-editor
- sync
- stage-definition
---
## Contexto
O World Editor ja possui `WorldLayoutSO` como asset editorial de macro-mundo e consegue criar stages, save points, footprints, sockets, anchors, lifts e connections. O Stage Editor ja possui `StageDefinition`, atualmente em `Assets/Scripts/Editor/GON/StageEditor/StageDefinition.cs`, com floors, cells e objetos internos de stage.
Na decisao anterior, o World Editor ficou responsavel por publicar apenas dados logicos de Journey em `JGraphSO`. O bake e a geometria interna continuam sendo responsabilidade do Stage Editor. Agora existe uma nova necessidade: o World Editor deve ajudar a criar ou sincronizar um `StageDefinition` que o Stage Editor consiga abrir e usar sem configuracao manual repetitiva.
Hoje o `WorldStageAuthoring` ja tem uma referencia opcional para `StageDefinition`, mas essa referencia e manual. Falta definir qual botao/fluxo cria, atualiza, valida ou abre o asset correspondente.
Atualizacao de direcao em 2026-06-20: o usuario prefere que o botao fique dentro do inspector do stage selecionado no World Editor, nao na topbar nem em uma acao global inicial. Esse botao deve operar como **create-or-sync**: se o stage ainda nao possui `StageDefinition`, cria um asset herdando valores relevantes do World Editor; se ja possui, sincroniza os dados de contrato.
## Problema
O designer cria e posiciona stages no World Editor, mas ainda precisa criar ou associar manualmente um `StageDefinition` para trabalhar no Stage Editor. Isso cria friccao e risco de divergencia:
- stage existe no World Editor mas nao tem `StageDefinition`;
- `StageDefinition` existe mas nao sabe de qual world stage veio;
- endpoints declarados no World Editor nao tem markers correspondentes no Stage Editor;
- mudancas no footprint ou no tipo especial do stage podem nao ser refletidas no Stage Editor;
- validacoes entre os dois editores ainda nao tem contrato claro.
Precisamos discutir se o World Editor deve gerar `StageDefinition`, sincronizar metadados, criar markers, abrir o Stage Editor, ou apenas manter referencias.
## Pontos Criticos
- `StageDefinition` e editor-only; nao deve virar runtime Journey.
- `WorldLayoutSO` tambem e editor-only, mas e a fonte autoral do macro-mundo.
- O Stage Editor deve continuar dono da geometria interna, floors, objetos, bake e cena.
- O World Editor sabe o footprint macro, endpoints e tipo do stage, mas nao sabe paredes internas, layout jogavel nem objetos finais.
- Gerar conteudo interno demais a partir do World Editor pode invadir a responsabilidade do Stage Editor.
- Sincronizacao destrutiva pode apagar trabalho manual do Stage Editor.
- Endpoints precisam de algum vinculo futuro com markers internos do stage para validar implementacao.
- Save points podem exigir template inicial especial no Stage Editor.
- O local do botao importa para UX: no inspector do stage selecionado, a acao fica contextual e reduz risco de sincronizar o stage errado.
- Os dados sincronizados precisam ser claramente identificados como "contrato herdado do World Editor", nao como geometria interna autoral do Stage Editor.
## Opcoes
### Opcao A - World Editor apenas cria e associa StageDefinition vazio
- **Abordagem:** adicionar botao no World Editor para criar um `StageDefinition` se o stage selecionado ainda nao tiver um. O asset recebe id/nome derivados do world stage e fica referenciado no `WorldStageAuthoring.stageDefinition`.
- **Pro:** simples, pouco invasivo, reduz friccao imediata.
- **Contra:** nao sincroniza endpoints, footprint, save point ou revisoes.
- **Manutencao:** baixa complexidade, mas pode virar insuficiente rapidamente.
### Opcao B - World Editor cria/atualiza StageDefinition com metadados de sync
- **Abordagem:** `StageDefinition` passa a guardar metadados editoriais de origem: `worldStageId`, world layer, footprint macro, endpoints esperados e possivelmente uma versao/hash de sync. O botao `Sync Stage Definition` fica no inspector do stage selecionado no World Editor e cria ou atualiza esses dados sem mexer na geometria interna.
- **Pro:** cria contrato rastreavel entre editores e permite validacao cruzada.
- **Contra:** exige alterar `StageDefinition` e definir o que e autoritativo em cada campo.
- **Manutencao:** boa se os campos forem claramente de contrato/sync e nao de geometria final.
### Opcao C - World Editor gera templates internos iniciais no StageDefinition
- **Abordagem:** alem de metadados, o World Editor cria floors/cells/markers iniciais no Stage Editor baseados no footprint e endpoints. Save point poderia gerar um stage 1x1 com estrutura minima.
- **Pro:** acelera prototipagem e cria um primeiro layout jogavel.
- **Contra:** alto risco de sobrescrever trabalho autoral; mistura macro footprint com geometria interna real; exige regras de merge.
- **Manutencao:** mais caro, porque cada evolucao do Stage Editor precisa considerar geracao/merge.
### Opcao D - Criar um asset intermediario de contrato StageSync
- **Abordagem:** World Editor gera um asset separado de sync por stage, e o Stage Editor le esse asset. `StageDefinition` referencia esse contrato ou importa dele manualmente.
- **Pro:** separa ainda mais contrato de geometria interna.
- **Contra:** cria mais um asset e mais fluxo de authoring; pode ser excesso para V1.
- **Manutencao:** boa para sistemas grandes, pesada para a fase atual.
## Sugestao / Recomendacao
Recomendacao inicial: seguir a **Opcao B** de forma conservadora, com o botao localizado no **inspector do stage selecionado** no World Editor.
O World Editor deve ter um botao contextual de sync para o stage selecionado:
```text
World Stage selecionado
Inspector do Stage
Create/Sync StageDefinition
se nao existir StageDefinition: criar asset
se existir: atualizar somente metadados de contrato/sync
associar StageDefinition ao WorldStageAuthoring
opcionalmente abrir Stage Editor com esse StageDefinition
```
O sync nao deve gerar geometria interna nem objetos finais na V1. Ele deve apenas garantir que o Stage Editor saiba:
- qual `worldStageId` originou o stage;
- qual e o nome/display name esperado;
- qual e o footprint macro;
- qual e o `WorldLayer`;
- quais endpoints o stage deve implementar;
- qual e a versao/hash do contrato sincronizado;
- se o stage e especial, como `SavePoint`.
Isso cria base para validacao futura sem invadir o Stage Editor.
### Dados Relevantes para Sync
Dados que parecem relevantes para gravar no `StageDefinition` como contrato herdado do World Editor:
- `worldLayoutId`: identifica o layout autoral de origem.
- `worldStageId`: id estavel do stage no World Editor.
- `worldStageDisplayName`: nome esperado no macro-mundo.
- `worldStageKind`: stage comum, `SavePoint`, ou futuros tipos especiais.
- `worldLayer`: camada macro onde o stage vive.
- `worldTileSize`: tamanho do WorldTile no momento do sync.
- `worldLayerHeight`: altura macro do layer no momento do sync.
- `worldTiles`: footprint macro ocupado pelo stage.
- `worldBounds`: bounds derivados do footprint, util para visualizacao/validacao.
- `endpoints`: lista dos endpoints esperados para esse stage.
- `connections`: opcionalmente ids das conexoes relacionadas, apenas como contexto de validacao.
- `syncedAt`: timestamp editorial.
- `syncVersion` ou `contractVersion`: versao do formato de sync.
- `contractHash`: hash dos dados herdados para detectar divergencia.
Dados de endpoint relevantes:
- `endpointId`: id estavel do endpoint no World Editor/Journey.
- `kind`: socket, anchor ou lift.
- `worldTile`: tile macro dentro do world layout.
- `socketFace`: apenas para sockets.
- `required`: se a implementacao no Stage Editor deve ser obrigatoria.
- `connectedEndpointIds` ou `connectionIds`: contexto para validacao e debug.
### Representacao no Stage Editor
Ha duas camadas possiveis:
1. **Contrato sincronizado passivo:** uma lista serializada no `StageDefinition`, por exemplo `StageWorldSyncData`, contendo footprint e endpoints esperados. O Stage Editor mostra essa informacao e valida implementacao, mas nao cria objetos jogaveis automaticamente.
2. **Markers internos implementaveis:** objetos/markers no layer `Markers` associados a `endpointId`, indicando onde o designer implementou a porta, portal, lift ou save point dentro do stage real.
Recomendacao atual: comecar pela camada 1 e preparar a arquitetura para a camada 2. O contrato passivo evita sobrescrever trabalho autoral e permite que os markers sejam introduzidos depois com uma decisao menor.
Para V1, o Stage Editor poderia exibir:
- uma secao "World Sync" no inspector do stage;
- status "Not Synced / Synced / Outdated";
- lista de endpoints esperados;
- warnings quando endpoint obrigatorio ainda nao tem marker interno associado;
- destaque especial para `SavePoint`.
Markers internos podem vir depois como extensao de `StageObjectDefinition` ou como uma nova lista especifica de markers. Usar `StageObjectDefinition` agora pode ser conveniente, mas talvez misture objeto jogavel com contrato editorial. Uma lista especifica como `StageEndpointMarkerDefinition` tende a deixar a fronteira mais clara.
## Perguntas em Aberto
- [x] O `StageDefinition` deve guardar diretamente `worldStageId`, footprint e endpoints esperados, ou isso deve ficar em uma sub-struct como `StageWorldSyncData`?
- [x] O botao inicial deve ser contextual, dentro do inspector do stage selecionado no World Editor.
- [x] Tambem deve existir futuramente `Sync All Stage Definitions`, ou isso fica fora da V1?
- [x] Onde os assets gerados devem ser salvos por padrao?
- [x] O sync deve criar pastas automaticamente por world/stage?
- [x] O sync deve abrir o Stage Editor automaticamente apos criar/associar o asset?
- [x] Como representar endpoints esperados no Stage Editor: lista passiva de contrato, markers internos, ou ambos?
- [x] Se houver markers internos, eles devem ser `StageObjectDefinition`, nova lista `StageEndpointMarkerDefinition`, ou outro modelo?
- [x] Se um endpoint for removido no World Editor, o sync remove o marker no StageDefinition ou apenas marca como stale?
- [x] Save Point deve gerar algum template inicial no StageDefinition ou apenas metadata `stageKind = SavePoint`?
- [x] Como detectar alteracao manual no StageDefinition desde o ultimo sync?
- [x] O Stage Editor deve validar "endpoint esperado ainda nao implementado" como warning ou erro?
- [x] O sync deve copiar apenas ids/dados estaveis ou tambem dados visuais como cor/nome do World Stage?
- [x] O `contractHash` deve considerar somente footprint/endpoints ou tambem nome/tipo/layer?
## Criterio para Encerrar
A agenda pode virar decisao quando fecharmos:
- o escopo do botao de sync;
- quais dados o `StageDefinition` deve receber;
- como esses dados sao agrupados no `StageDefinition`;
- quais dados o sync nunca pode sobrescrever;
- comportamento para criar asset novo versus atualizar asset existente;
- comportamento de abertura do Stage Editor;
- validacoes minimas entre World Editor e Stage Editor;
- tratamento inicial de Save Point e endpoints.
## Discussion
Entrada inicial em 2026-06-20: o usuario solicitou uma agenda para discutir um botao no World Editor capaz de sincronizar ou gerar um `StageDefinition` legivel pelo Stage Editor, cobrindo dados de sync, comportamento e validacao entre editores.
Atualizacao em 2026-06-20: o usuario definiu preferencia de UX para o botao dentro do inspector do stage selecionado. O botao deve criar o `StageDefinition` com valores herdados do World Editor quando ainda nao existir, ou sincronizar o asset existente quando ja houver referencia. A discussao deve focar quais dados sao relevantes e como representa-los no Stage Editor.
## Resolution
Resolucao em 2026-06-20: a V1 de integracao World Editor / Stage Editor deve seguir a Opcao B conservadora.
Decisoes aceitas para emissao da decisao:
- O botao inicial deve ficar no inspector do stage selecionado no World Editor.
- O botao deve operar como `Create/Sync StageDefinition`.
- Se o stage nao tiver `StageDefinition`, o botao cria um asset novo e associa ao `WorldStageAuthoring`.
- Se o stage ja tiver `StageDefinition`, o botao atualiza apenas dados de contrato/sync herdados do World Editor.
- Os dados herdados devem ficar agrupados em uma sub-struct clara no `StageDefinition`, chamada inicialmente de `StageWorldSyncData`.
- Assets gerados devem ser salvos por padrao em uma pasta `Stages` ao lado do `WorldLayoutSO`, criando a pasta automaticamente quando necessario.
- V1 nao precisa de `Sync All Stage Definitions`.
- O botao principal nao deve abrir automaticamente o Stage Editor. Um segundo botao contextual, `Open Stage Editor`, pode existir no inspector.
- V1 deve representar endpoints esperados como lista passiva de contrato em `StageWorldSyncData`.
- Markers internos de endpoint ficam fora da V1, mas a arquitetura deve permitir uma lista futura especifica como `StageEndpointMarkerDefinition`.
- Sync nao deve remover dados autorais nem markers futuros automaticamente; endpoints removidos no World Editor devem sair do contrato sincronizado, e implementacoes futuras podem ser marcadas como stale.
- Save Point deve sincronizar apenas metadata/contrato (`stageKind = SavePoint`, footprint 1x1 e endpoints esperados), sem gerar template interno de geometria na V1.
- Alteracao/desatualizacao deve ser detectada por `contractHash` calculado sobre os dados herdados do World Editor.
- O hash deve considerar dados de contrato estavel: world layout id, world stage id, display name, stage kind, world layer, tile/layer sizes, footprint e endpoints esperados. Cor visual nao deve fazer parte do hash.
- `StageDefinition` ausente no World stage deve ser warning.
- `StageDefinition` sincronizado com outro `worldStageId` deve ser error.
- Sync desatualizado deve ser warning.
- Endpoint obrigatorio sem implementacao interna deve ser warning na V1, pois markers internos ainda nao sao parte do contrato.

View File

@ -0,0 +1,225 @@
---
id: DEC-0002
ticket: world-stage-editor-sync
title: World Editor / Stage Editor Sync V1
status: accepted
created: 2026-06-20
accepted: 2026-06-20
agenda: AGD-0002
plans:
- PLN-0005
- PLN-0006
- PLN-0007
- PLN-0008
tags:
- world-editor
- stage-editor
- sync
- stage-definition
---
## Status
Accepted.
This decision defines the V1 contract for synchronizing a World Editor stage with a Stage Editor `StageDefinition`.
## Contexto
The World Editor owns macro-world authoring through `WorldLayoutSO`: stage placement, WorldLayer, WorldTile footprint, special stage kind, Journey endpoints, and Journey connections.
The Stage Editor owns internal stage authoring through `StageDefinition`: floors, cells, internal objects, markers, scene bake, and generated scene content.
`WorldStageAuthoring` already contains an optional `StageDefinition` reference, but the reference is currently manual. Designers need a contextual way to create or synchronize a `StageDefinition` from the selected World Editor stage without turning the World Editor into a Stage Editor.
## Decisao
The World Editor SHALL provide a contextual `Create/Sync StageDefinition` action inside the inspector for the selected world stage.
The action SHALL be create-or-sync:
- If the selected world stage has no `StageDefinition`, the action MUST create a new `StageDefinition` asset and assign it to `WorldStageAuthoring.stageDefinition`.
- If the selected world stage already has a `StageDefinition`, the action MUST update only world-sync contract data on that asset.
The sync data MUST be stored in a dedicated `StageWorldSyncData` structure inside `StageDefinition`. Sync data MUST NOT be scattered as unrelated top-level fields unless a later decision explicitly revises this model.
The sync action MUST NOT generate internal stage geometry, floor cells, props, enemies, puzzles, baked scene content, or final gameplay objects in V1.
## Rationale
The chosen model reduces authoring friction while preserving editor ownership boundaries.
Keeping sync metadata inside `StageDefinition` gives the Stage Editor enough context to show what the World Editor expects, while still letting the Stage Editor remain responsible for internal playable content.
A contextual inspector button avoids accidental global sync and keeps the operation tied to the selected world stage. A passive sync contract avoids destructive merge problems, keeps V1 focused on read-only guidance, and leaves a clear place for a future explicit endpoint marker model.
## Invariantes / Contrato
### Button Placement
The initial sync button MUST live in the World Editor inspector for the selected stage.
The button label SHOULD be `Create StageDefinition` when no asset is assigned and `Sync StageDefinition` when an asset is already assigned.
The World Editor MAY also expose a contextual `Open Stage Editor` button for the assigned `StageDefinition`.
V1 MUST NOT include `Sync All Stage Definitions`.
### Asset Creation
Generated `StageDefinition` assets MUST be saved by default under a `Stages` folder next to the source `WorldLayoutSO`.
The editor MUST create that `Stages` folder automatically when needed.
Generated assets SHOULD use stable, readable names derived from the world stage display name or id.
### StageWorldSyncData
`StageDefinition` MUST contain a dedicated sync structure named `StageWorldSyncData` or an equivalent clearly named type.
The sync structure MUST contain the world-derived contract data. At minimum it MUST support:
- `worldLayoutId`;
- `worldStageId`;
- `worldStageDisplayName`;
- `worldStageKind`;
- `worldLayer`;
- `worldTileSize`;
- `worldLayerHeight`;
- `worldTiles`;
- derived `worldBounds` or enough data to compute it;
- expected endpoints for the stage;
- `syncedAt`;
- `contractVersion`;
- `contractHash`.
Expected endpoint records MUST support:
- `endpointId`;
- endpoint kind;
- WorldTile coordinate;
- socket face when the endpoint is a socket;
- required flag;
- related connection ids or connected endpoint ids as debug/validation context.
Visual-only world data, such as stage color, MUST NOT be part of `contractHash`.
### Contract Hash
The `contractHash` MUST be computed from stable world contract data:
- world layout id;
- world stage id;
- world stage display name;
- stage kind;
- world layer;
- world tile size;
- world layer height;
- footprint tiles;
- expected endpoint data.
The hash is used to detect whether a `StageDefinition` is out of date relative to the selected world stage.
### Non-Destructive Sync
Sync MUST NOT overwrite Stage Editor authored floors, cells, internal objects, markers, or bake data.
If an endpoint is removed from the World Editor, sync MUST remove it from the passive expected-endpoints contract.
V1 has no compatibility requirement for temporary test stages or prototype `StageDefinition` assets already created during editor development. Those assets MAY be recreated, manually updated, or discarded.
### Stage Editor Representation
V1 MUST represent World Editor expectations as passive contract data in `StageWorldSyncData`.
The Stage Editor SHALL render a passive World Sync underlay derived from `StageWorldSyncData`.
Endpoint implementation markers are out of scope for V1. The sync data model SHOULD keep endpoint identity explicit enough to support a later dedicated marker model, preferably a `StageEndpointMarkerDefinition`-style list rather than overloading gameplay `StageObjectDefinition` records.
### World Sync Underlay
The World Sync underlay MUST be read-only visual guidance. It MUST NOT create, edit, delete, or block interaction with Stage Editor cells, objects, markers, floors, or bake data.
The underlay MUST be drawn beneath authored Stage Editor content so it guides the designer without obscuring cells, objects, selections, or editing handles.
The underlay SHOULD be toggleable.
The underlay MUST convert World Editor `WorldTile` coordinates into Stage Editor space using the synced world tile size. With the current V1 defaults, one WorldTile corresponds to a `24x24` cell block when `StageDefinition.cellSize` is `1m`.
The underlay visual language SHALL be:
- WorldTile footprint from the World Editor: magenta hatching.
- WorldTile containing an expected anchor: cyan hatching.
- WorldTile containing an expected lift: red hatching.
- Expected socket: yellow highlight on the corresponding face of the WorldTile block.
Socket face hints MUST be drawn on the face where the World Editor expects the socket, not as a filled tile.
Save points MUST NOT have special visual treatment in the underlay. A save point SHALL be shown like a normal stage: magenta hatching for its footprint and yellow socket face hints when sockets exist. The designer remains responsible for knowing that the synced stage is a save point through metadata, inspector state, and validation, not through a special underlay symbol.
### Save Point
Save points MUST sync as contract metadata only:
- `worldStageKind = SavePoint`;
- footprint `1x1`;
- expected endpoints.
V1 MUST NOT generate a special internal save point template, floor layout, or object set in `StageDefinition`.
### Validation
The World Editor SHOULD warn when a world stage has no assigned `StageDefinition`.
The World Editor MUST treat a `StageDefinition` synced to a different `worldStageId` as an error.
The World Editor or Stage Editor SHOULD warn when `contractHash` is out of date.
## Impactos
### World Editor
The World Editor inspector must gain contextual actions for the selected stage:
- create/sync `StageDefinition`;
- optionally open the assigned `StageDefinition` in the Stage Editor.
The World Editor validator must understand missing, mismatched, and outdated `StageDefinition` sync state.
### Stage Editor
`StageDefinition` must gain sync data that is editor-only and separate from internal geometry.
The Stage Editor must render the passive World Sync underlay beneath authored content. V1 does not require endpoint marker authoring.
### Runtime / Journey
No runtime Journey contract changes are required by this decision.
`StageWorldSyncData` remains editor-only. Runtime code MUST continue to consume `JGraphSO`, not `StageDefinition` or `WorldLayoutSO`.
### Tooling
Asset creation needs deterministic default paths based on the source `WorldLayoutSO` asset location.
## Referencias
- Agenda: `discussion/workflow/agendas/AGD-0002-world-stage-editor-sync.md`
- Existing World Editor / Journey spec: `specs/world-editor-journey-v1.md`
- Lesson from previous decision: `discussion/lessons/DSC-0001-world-editor-journey-spec/LSN-0001-editor-authoring-runtime-publication.md`
- Stage Editor source: `Assets/Scripts/Editor/GON/StageEditor/StageDefinition.cs`
- World Editor source: `Assets/Scripts/Editor/GON/WorldEditor/WorldLayoutSO.cs`
## Propagacao Necessaria
- Add `StageWorldSyncData` and endpoint sync records to `StageDefinition`.
- Add create/sync and open actions to the World Editor stage inspector.
- Implement deterministic StageDefinition asset creation under a `Stages` folder next to the `WorldLayoutSO`.
- Add sync hash generation and stale/mismatch validation.
- Update Stage Editor UI to show passive sync state and render the World Sync underlay.
## Revision Log
- 2026-06-20: Initial accepted decision from AGD-0002.
- 2026-06-21: Added read-only Stage Editor World Sync underlay rules, including hatching colors, socket face hints, and save point visual behavior.
- 2026-06-21: Clarified that V1 has no compatibility requirement for temporary test StageDefinitions while still keeping endpoint identity suitable for a future explicit marker model.

View File

@ -0,0 +1,121 @@
---
id: PLN-0005
ticket: world-stage-editor-sync
title: Stage World Sync Data Model
status: open
created: 2026-06-21
completed:
tags:
- stage-editor
- sync
- data-model
---
## Objective
Add the passive World Editor sync contract data model to `StageDefinition` so a Stage Editor asset can store the world-derived contract required by `DEC-0002`.
## Background
`DEC-0002` requires `StageDefinition` to contain a dedicated `StageWorldSyncData` structure. The data must be editor-only, passive, and separate from authored stage geometry.
## Decisions of Origin
- `DEC-0002`: World Editor / Stage Editor Sync V1.
## Scope
### Included
- Add `StageWorldSyncData` to `StageDefinition`.
- Add endpoint sync record types for expected sockets, anchors, and lifts.
- Add enough data to compute or store world bounds.
- Add `contractVersion`, `syncedAt`, and `contractHash`.
- Keep endpoint ids stable and explicit for future marker work.
### Excluded
- World Editor UI button implementation.
- StageDefinition asset creation path logic.
- Stage Editor underlay rendering.
- Runtime Journey changes.
- Endpoint implementation markers.
- Migration compatibility for temporary prototype stage assets.
## Execution Steps
### Step 1 - Add sync data serializable types
**What:** Add serializable editor-only sync structures.
**How:** Extend `Assets/Scripts/Editor/GON/StageEditor/StageDefinition.cs` with:
- `StageWorldSyncData`;
- `StageWorldSyncEndpoint`;
- optional helper enum or fields needed to represent stage kind and endpoint kind using existing world/Journey enums when accessible from editor code.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageDefinition.cs`
### Step 2 - Add sync field to StageDefinition
**What:** Store the world sync contract in `StageDefinition`.
**How:** Add a public serialized field such as `public StageWorldSyncData worldSync = new();`. Update `EnsureDefaults()` to initialize `worldSync`, endpoint lists, and footprint lists.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageDefinition.cs`
### Step 3 - Add derived bounds support
**What:** Support derived world bounds for underlay and validation.
**How:** Implement a method or property on `StageWorldSyncData` that computes `RectInt` bounds from synced `worldTiles`, or store a serialized bounds field that is refreshed by sync.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageDefinition.cs`
### Step 4 - Preserve authored data isolation
**What:** Ensure sync data remains separate from authored geometry.
**How:** Do not modify `StageFloorDefinition`, `LogicalCell`, or existing `StageObjectDefinition` semantics as part of this plan.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageDefinition.cs`
## Test Requirements
### Unit Tests
- None required for this plan unless an existing editor test framework is present.
### Integration Tests
- Compile `Assembly-CSharp-Editor`.
### Manual Verification
- Create or select a `StageDefinition` asset and confirm Unity serializes the new world sync field.
- Confirm existing `StageDefinition` assets still load.
## Acceptance Criteria
- [ ] `StageDefinition` contains a dedicated `StageWorldSyncData` field.
- [ ] `StageWorldSyncData` stores world layout id, world stage id, display name, kind, layer, tile size, layer height, footprint, endpoints, sync timestamp, contract version, and contract hash.
- [ ] Expected endpoint records store endpoint id, kind, world tile, socket face, required flag, and connection/debug context.
- [ ] Authored floors, cells, and objects are not changed by adding the data model.
- [ ] `Assembly-CSharp-Editor` compiles.
## Dependencies
- `DEC-0002`.
## Risks
- Referencing World Editor-only types too directly from Stage Editor data may create coupling. Keep fields serializable and editor-only.
- Field naming churn can make assets noisy; use stable names before implementation proceeds.

View File

@ -0,0 +1,148 @@
---
id: PLN-0006
ticket: world-stage-editor-sync
title: World Editor StageDefinition Sync Action
status: open
created: 2026-06-21
completed:
tags:
- world-editor
- stage-definition
- sync
---
## Objective
Implement the contextual `Create/Sync StageDefinition` action in the World Editor stage inspector.
## Background
`DEC-0002` requires a create-or-sync action inside the inspector for the selected world stage. It must create a `StageDefinition` if missing, or update only passive sync contract data if present.
## Decisions of Origin
- `DEC-0002`: World Editor / Stage Editor Sync V1.
## Scope
### Included
- Add a contextual `Create StageDefinition` / `Sync StageDefinition` button to the World Editor stage inspector.
- Create generated assets under a `Stages` folder next to the source `WorldLayoutSO`.
- Assign generated assets to `WorldStageAuthoring.stageDefinition`.
- Populate `StageWorldSyncData` from `WorldLayoutSO` and the selected stage.
- Compute `contractHash` from stable world contract data.
- Add optional contextual `Open Stage Editor` button for assigned assets.
### Excluded
- Stage Editor underlay rendering.
- Stage Editor validation UI.
- Runtime Journey changes.
- `Sync All Stage Definitions`.
- Compatibility migration for temporary prototype assets.
## Execution Steps
### Step 1 - Add sync helper
**What:** Create a helper responsible for converting a selected `WorldStageAuthoring` into `StageWorldSyncData`.
**How:** Add an editor class such as `StageDefinitionSyncer` under World Editor or shared editor tooling. It should:
- collect world layout id;
- collect stage id, display name, kind, layer, footprint, tile size, and layer height;
- collect endpoints owned by the stage;
- collect related connection ids or connected endpoint ids;
- compute `contractHash` excluding visual-only color.
**File(s):**
- `Assets/Scripts/Editor/GON/WorldEditor/StageDefinitionSyncer.cs`
- `Assets/Scripts/Editor/GON/WorldEditor/WorldLayoutSO.cs`
- `Assets/Scripts/Editor/GON/StageEditor/StageDefinition.cs`
### Step 2 - Implement deterministic asset path
**What:** Generate new `StageDefinition` assets in the required default location.
**How:** Resolve `AssetDatabase.GetAssetPath(worldLayout)`, create a sibling `Stages` folder if missing, sanitize a readable asset filename from stage display name or id, and create the asset there.
**File(s):**
- `Assets/Scripts/Editor/GON/WorldEditor/StageDefinitionSyncer.cs`
### Step 3 - Add inspector actions
**What:** Add contextual buttons to the selected stage inspector.
**How:** In `WorldInspectorPanel.BuildStageInspector`, add:
- `Create StageDefinition` when `stage.stageDefinition` is null;
- `Sync StageDefinition` when assigned;
- optional `Open Stage Editor` when assigned.
Use `owner.MutateLayout` or an equivalent undo-safe mutation for assignment and dirty state.
**File(s):**
- `Assets/Scripts/Editor/GON/WorldEditor/WorldInspectorPanel.cs`
- `Assets/Scripts/Editor/GON/WorldEditor/WorldEditorWindow.cs`
### Step 4 - Sync only contract data
**What:** Ensure sync does not mutate authored Stage Editor data.
**How:** Sync must only update `StageDefinition.worldSync` and asset metadata necessary for identification. It must not edit floors, cells, objects, markers, or bake data.
**File(s):**
- `Assets/Scripts/Editor/GON/WorldEditor/StageDefinitionSyncer.cs`
### Step 5 - Open Stage Editor
**What:** Add a button to open the assigned `StageDefinition`.
**How:** Expose a safe Stage Editor entry point if one does not already exist, or set `Selection.activeObject` and open the existing Stage Editor window with the selected asset.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageEditorWindow.cs`
- `Assets/Scripts/Editor/GON/WorldEditor/WorldInspectorPanel.cs`
## Test Requirements
### Unit Tests
- None required unless an editor test harness exists.
### Integration Tests
- Compile `Assembly-CSharp-Editor`.
### Manual Verification
- Select a world stage with no `StageDefinition`, click create, and confirm an asset appears under sibling `Stages`.
- Confirm the world stage now references the created asset.
- Change the world stage footprint/endpoints, click sync, and confirm only `worldSync` changes.
- Confirm floors/cells/objects remain unchanged after sync.
- Open the assigned Stage Editor asset from the inspector.
## Acceptance Criteria
- [ ] World stage inspector contains contextual create/sync action.
- [ ] Missing `StageDefinition` is created under `<WorldLayoutFolder>/Stages`.
- [ ] Existing `StageDefinition` receives updated `StageWorldSyncData`.
- [ ] Sync does not change authored floors, cells, objects, markers, or bake data.
- [ ] Contract hash excludes visual-only stage color.
- [ ] Optional `Open Stage Editor` action opens the assigned asset.
- [ ] `Assembly-CSharp-Editor` compiles.
## Dependencies
- `PLN-0005` must be implemented first.
## Risks
- Asset path generation can produce duplicate names; implementation must avoid overwriting existing assets.
- Opening the Stage Editor may require a small public API on `StageEditorWindow`.

View File

@ -0,0 +1,129 @@
---
id: PLN-0007
ticket: world-stage-editor-sync
title: World Stage Sync Validation
status: open
created: 2026-06-21
completed:
tags:
- validation
- world-editor
- stage-editor
---
## Objective
Add validation for missing, mismatched, and outdated `StageDefinition` sync state.
## Background
`DEC-0002` requires warnings for missing `StageDefinition`, errors for assets synced to another world stage id, and warnings for outdated contract hash.
## Decisions of Origin
- `DEC-0002`: World Editor / Stage Editor Sync V1.
## Scope
### Included
- World Editor validation for missing `StageDefinition`.
- World Editor validation for mismatched `worldStageId`.
- World Editor validation for stale `contractHash`.
- Stage Editor display of passive sync state if the sync data is present.
### Excluded
- Endpoint implementation marker validation.
- Runtime Journey validation changes.
- Migration of temporary prototype assets.
## Execution Steps
### Step 1 - Add hash recomputation entry point
**What:** Make contract hash recomputation reusable by validation.
**How:** Expose a method on `StageDefinitionSyncer` or a related helper that computes the expected hash for a world stage without mutating the `StageDefinition`.
**File(s):**
- `Assets/Scripts/Editor/GON/WorldEditor/StageDefinitionSyncer.cs`
### Step 2 - Extend WorldLayoutValidator
**What:** Validate StageDefinition sync state from the World Editor.
**How:** In `WorldLayoutValidator.ValidateStages`, check each world stage:
- if `stageDefinition` is null, emit warning;
- if assigned sync data has a non-empty `worldStageId` different from the world stage id, emit error;
- if assigned sync data hash differs from recomputed hash, emit warning.
**File(s):**
- `Assets/Scripts/Editor/GON/WorldEditor/WorldLayoutValidator.cs`
### Step 3 - Improve validation messages
**What:** Make validation messages actionable.
**How:** Include the world stage id as `objectId` and message text that says whether the fix is create, sync, or reassign the `StageDefinition`.
**File(s):**
- `Assets/Scripts/Editor/GON/WorldEditor/WorldValidation.cs`
- `Assets/Scripts/Editor/GON/WorldEditor/WorldLayoutValidator.cs`
### Step 4 - Show sync state in Stage Editor inspector
**What:** Show passive sync state on `StageDefinition`.
**How:** In `StageInspectorPanel.BuildStageInspector`, add a read-only `World Sync` section showing:
- not synced;
- synced world stage id and display name;
- world stage kind;
- sync timestamp;
- contract hash or short hash.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageInspectorPanel.cs`
## Test Requirements
### Unit Tests
- None required unless editor tests are available.
### Integration Tests
- Compile `Assembly-CSharp-Editor`.
### Manual Verification
- Validate a world stage with no `StageDefinition`; confirm warning.
- Assign a `StageDefinition` synced to a different stage id; confirm error.
- Modify a world stage after sync; confirm stale hash warning.
- Re-sync; confirm stale warning disappears.
- Open Stage Editor and confirm sync state is visible.
## Acceptance Criteria
- [ ] Missing `StageDefinition` emits warning.
- [ ] Mismatched `worldStageId` emits error.
- [ ] Outdated hash emits warning.
- [ ] Stage Editor inspector shows passive sync state.
- [ ] No marker implementation validation is introduced.
- [ ] `Assembly-CSharp-Editor` compiles.
## Dependencies
- `PLN-0005` must be implemented first.
- `PLN-0006` should be implemented before full manual validation.
## Risks
- If hash computation is not deterministic, stale warnings will be noisy.
- Existing prototype assets may warn or error; DEC-0002 allows discarding or recreating temporary assets.

View File

@ -0,0 +1,144 @@
---
id: PLN-0008
ticket: world-stage-editor-sync
title: Stage Editor World Sync Underlay
status: open
created: 2026-06-21
completed:
tags:
- stage-editor
- world-sync
- underlay
---
## Objective
Render the passive World Sync underlay in the Stage Editor using `StageWorldSyncData`.
## Background
`DEC-0002` requires the Stage Editor to render read-only guidance under authored content. The underlay must show World Editor footprint and expected endpoints without changing cells, objects, markers, floors, or bake data.
## Decisions of Origin
- `DEC-0002`: World Editor / Stage Editor Sync V1.
## Scope
### Included
- Draw synced WorldTile footprint as magenta hatching.
- Draw WorldTiles containing expected anchors as cyan hatching.
- Draw WorldTiles containing expected lifts as red hatching.
- Draw expected socket faces as yellow highlights on the correct WorldTile block face.
- Draw under authored cells, objects, selections, and editing handles.
- Add a toggle for the underlay.
- Treat save points like normal stages in the underlay.
### Excluded
- Creating stage cells from the underlay.
- Creating endpoint markers.
- Special save point symbol/template in Stage Editor.
- Runtime Journey changes.
## Execution Steps
### Step 1 - Add underlay toggle state
**What:** Add a UI/state flag controlling underlay visibility.
**How:** Add a bool to `StageEditorState` or `StageEditorWindow`, defaulting to visible when sync data exists. Add a compact toggle in the Stage Editor UI.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageEditorState.cs`
- `Assets/Scripts/Editor/GON/StageEditor/StageEditorWindow.cs`
- `Assets/Scripts/Editor/GON/StageEditor/StageInspectorPanel.cs`
### Step 2 - Convert WorldTile blocks to stage cells
**What:** Compute underlay rectangles in Stage Editor cell space.
**How:** Use `StageDefinition.worldSync.worldTileSize / StageDefinition.cellSize` to derive cells per WorldTile. With defaults this is `24`. Convert each synced world tile into a `RectInt` block.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageMapCanvas.cs`
### Step 3 - Draw underlay before authored content
**What:** Render guidance beneath existing stage content.
**How:** In `StageMapCanvas.OnGenerateVisualContent`, draw the underlay after background/grid if appropriate but before cells, objects, selection, and handles.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageMapCanvas.cs`
### Step 4 - Implement hatching and face hints
**What:** Add visual primitives for hatching and socket face highlights.
**How:** Add helper methods to draw diagonal hatching inside `Rect` blocks and thick yellow lines on block faces. Use:
- magenta for footprint;
- cyan for anchor tiles;
- red for lift tiles;
- yellow for socket faces.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageMapCanvas.cs`
- `Assets/Scripts/Editor/GON/StageEditor/StageEditorColors.cs`
### Step 5 - Keep save point visual behavior normal
**What:** Ensure save point has no special Stage Editor symbol.
**How:** Do not draw `S`, special color, or special geometry for `worldStageKind = SavePoint`. It uses normal footprint hatching and socket face hints.
**File(s):**
- `Assets/Scripts/Editor/GON/StageEditor/StageMapCanvas.cs`
## Test Requirements
### Unit Tests
- None required unless an editor test harness exists.
### Integration Tests
- Compile `Assembly-CSharp-Editor`.
### Manual Verification
- Open a synced `StageDefinition` in Stage Editor and confirm underlay appears below authored content.
- Confirm `24m` world tile maps to `24x24` cells when `cellSize = 1`.
- Confirm footprint, anchor, lift, and socket face colors match DEC-0002.
- Confirm underlay does not block selection, painting, moving, or resizing authored stage objects.
- Confirm save point sync shows no special symbol.
- Toggle underlay off and on.
## Acceptance Criteria
- [ ] Underlay renders beneath authored cells and objects.
- [ ] Magenta hatching appears for synced footprint.
- [ ] Cyan hatching appears for expected anchor tiles.
- [ ] Red hatching appears for expected lift tiles.
- [ ] Yellow socket face hints appear on correct block faces.
- [ ] Save points have no special underlay symbol or color.
- [ ] Underlay is toggleable.
- [ ] Underlay does not mutate `StageDefinition` authored content.
- [ ] `Assembly-CSharp-Editor` compiles.
## Dependencies
- `PLN-0005` must be implemented first.
- `PLN-0006` is needed to produce real synced data for manual verification.
## Risks
- Underlay can become visually noisy; draw it beneath content and keep colors translucent/hatch-based.
- Cell-size conversions must avoid fractional rendering ambiguity. Use stable integer or float conversion rules and document the behavior.