From 0eef72a2c2ac9540320f32f1a39d6f1bc8006cd5 Mon Sep 17 00:00:00 2001 From: sindoring Date: Fri, 10 Jul 2026 18:15:05 +0400 Subject: [PATCH] =?UTF-8?q?=D0=BA=D1=80=D1=83=D0=BF=D0=BD=D0=BE=D0=B5=20?= =?UTF-8?q?=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 23 +- coordination/README.md | 14 + coordination/TASK_TEMPLATE.md | 66 ++++ coordination/claims/README.md | 5 + docs/CLIENT_FEATURES.md | 1 + docs/DOCUMENTATION_STANDARD.md | 278 ++++++++++++++ docs/GODOT_BEST_PRACTICES.md | 120 ++++++ docs/README.md | 6 + docs/REFERENCES.md | 16 + docs/ROADMAP.md | 2 + docs/TEAM_WORKFLOW.md | 343 ++++++++++++++++++ docs/TOOLING_CATALOG.md | 22 ++ docs/modules/README.md | 18 + docs/modules/TEMPLATE.md | 127 +++++++ docs/modules/world-renderer.md | 248 +++++++++++++ targets/12-client-completeness.md | 2 + targets/DEVELOPMENT_ROADMAP.md | 150 ++++++++ targets/README.md | 10 + targets/roadmap/01-foundation-and-data.md | 86 +++++ targets/roadmap/02-rendering-and-graphics.md | 102 ++++++ targets/roadmap/03-network-and-session.md | 94 +++++ targets/roadmap/04-gameplay-systems.md | 112 ++++++ targets/roadmap/05-ui-lua-audio.md | 97 +++++ .../roadmap/06-editor-and-content-tools.md | 109 ++++++ .../roadmap/07-server-emulator-integration.md | 84 +++++ targets/roadmap/08-quality-and-release.md | 113 ++++++ tools/verify_coordination.ps1 | 92 +++++ tools/verify_documentation.ps1 | 101 ++++++ 28 files changed, 2435 insertions(+), 6 deletions(-) create mode 100644 coordination/README.md create mode 100644 coordination/TASK_TEMPLATE.md create mode 100644 coordination/claims/README.md create mode 100644 docs/DOCUMENTATION_STANDARD.md create mode 100644 docs/GODOT_BEST_PRACTICES.md create mode 100644 docs/TEAM_WORKFLOW.md create mode 100644 docs/modules/README.md create mode 100644 docs/modules/TEMPLATE.md create mode 100644 docs/modules/world-renderer.md create mode 100644 targets/DEVELOPMENT_ROADMAP.md create mode 100644 targets/roadmap/01-foundation-and-data.md create mode 100644 targets/roadmap/02-rendering-and-graphics.md create mode 100644 targets/roadmap/03-network-and-session.md create mode 100644 targets/roadmap/04-gameplay-systems.md create mode 100644 targets/roadmap/05-ui-lua-audio.md create mode 100644 targets/roadmap/06-editor-and-content-tools.md create mode 100644 targets/roadmap/07-server-emulator-integration.md create mode 100644 targets/roadmap/08-quality-and-release.md create mode 100644 tools/verify_coordination.ps1 create mode 100644 tools/verify_documentation.ps1 diff --git a/AGENTS.md b/AGENTS.md index 5f64b1b..64f2fbe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,10 +12,13 @@ 1. Прочитать [`targets/README.md`](targets/README.md). 2. Прочитать файл текущей цели, указанный там как `Current target`. -3. Прочитать [`docs/README.md`](docs/README.md) и связанные с задачей нормативные документы. -4. Для renderer-задач прочитать [`RENDER.md`](RENDER.md). -5. Проверить рабочее дерево и не перезаписывать чужие изменения. -6. Перед созданием сложной подсистемы или добавлением dependency проверить [`docs/TOOLING_CATALOG.md`](docs/TOOLING_CATALOG.md), зарегистрировать найденные готовые решения и провести bounded evaluation вместо немедленного вендоринга. +3. Прочитать [`targets/DEVELOPMENT_ROADMAP.md`](targets/DEVELOPMENT_ROADMAP.md) и соответствующий subsystem plan из `targets/roadmap/`. +4. Прочитать [`docs/README.md`](docs/README.md) и связанные с задачей нормативные документы. +5. Прочитать обязательный [`docs/DOCUMENTATION_STANDARD.md`](docs/DOCUMENTATION_STANDARD.md) и определить, какие API docs, module spec и diagrams затрагивает задача. +6. Для renderer-задач прочитать [`RENDER.md`](RENDER.md). +7. Проверить рабочее дерево и не перезаписывать чужие изменения. +8. Перед созданием сложной подсистемы или добавлением dependency проверить [`docs/TOOLING_CATALOG.md`](docs/TOOLING_CATALOG.md), зарегистрировать найденные готовые решения и провести bounded evaluation вместо немедленного вендоринга. +9. При командной работе прочитать [`docs/TEAM_WORKFLOW.md`](docs/TEAM_WORKFLOW.md), проверить активные claims/draft PRs и объявить стабильный Agent ID до изменений. Если задача пользователя противоречит target-порядку, прямое указание пользователя имеет приоритет, но агент обязан сохранить архитектурные границы и отметить влияние на roadmap. @@ -30,10 +33,16 @@ - Любой новый формат, публичный контракт или несовместимое решение требует обновления документации и при необходимости ADR. - Исправление дефекта должно получать regression test, когда это технически возможно. - Не писать крупную подсистему с нуля до поиска готовых libraries, reference implementations, fixtures и tooling; результат исследования фиксируется в `docs/TOOLING_CATALOG.md`. +- Не начинать claimed work package другого агента и не редактировать его exclusive paths без явного handoff. +- Не работать двум агентам в одном worktree. Каждый агент использует собственную ветку и clone/worktree. +- Статус milestone, Evidence и `OPENWC_TARGET_DONE` изменяет только назначенный интегратор. +- Каждый новый/существенно изменённый модуль обязан иметь актуальную specification в `docs/modules/`, inline documentation публичного API и data-flow diagram по `docs/DOCUMENTATION_STANDARD.md`. +- Stateful/async/cross-layer работа обязана документировать state/sequence diagram, ownership, threading, failure и recovery paths. +- Документация обновляется в том же work package, что код. Handoff без обязательной документации имеет статус только `PARTIAL`. ## Метки состояния -В каждом `targets/*.md` присутствует ровно одна метка: +В каждом исполняемом target-файле `targets/[0-9][0-9]-*.md` присутствует ровно одна метка. Справочные документы `targets/DEVELOPMENT_ROADMAP.md` и `targets/roadmap/*.md` меток состояния не имеют: - `` — цель ещё не начата. - `` — единственная текущая цель. @@ -53,6 +62,7 @@ 3. В Evidence записаны команды, результаты и изменённые файлы. 4. Не осталось обязательных незакрытых пунктов или скрытых заглушек. 5. Обновлены `targets/README.md` и матрица функций, если применимо. +6. Публичный API, module spec, input/output tables и обязательные diagrams соответствуют фактической реализации. Агент НЕ ДОЛЖЕН ставить `DONE` только потому, что код компилируется. Если пользователь явно принял частичный результат, статус остаётся `ACTIVE`, а принятое ограничение записывается в Evidence. @@ -64,4 +74,5 @@ - что изменено; - какие проверки выполнены; - fidelity evidence для поведения 3.3.5a; -- оставшиеся риски или следующий незакрытый checklist item. +- оставшиеся риски или следующий незакрытый checklist item; +- какие API/module docs и diagrams созданы или обновлены. diff --git a/coordination/README.md b/coordination/README.md new file mode 100644 index 0000000..357a16f --- /dev/null +++ b/coordination/README.md @@ -0,0 +1,14 @@ +# OpenWC Coordination + +Основные правила находятся в [`../docs/TEAM_WORKFLOW.md`](../docs/TEAM_WORKFLOW.md). + +Предпочтительно вести claims в issue и draft PR/MR общего Git forge. Каталог `claims/` — fallback, если issue tracker недоступен. Один claim — один файл; не использовать общий изменяемый board. + +## Создание fallback claim + +1. Скопировать [`TASK_TEMPLATE.md`](TASK_TEMPLATE.md) в `claims/.md`. +2. Заполнить owner, lease, paths, contracts и tests. +3. Опубликовать claim до production edits. +4. После интеграции заменить состояние на `accepted` или удалить claim отдельным coordination commit, сохранив историю в Git. + +Claim-файлы не заменяют target Evidence и не меняют milestone status. diff --git a/coordination/TASK_TEMPLATE.md b/coordination/TASK_TEMPLATE.md new file mode 100644 index 0000000..adcfddd --- /dev/null +++ b/coordination/TASK_TEMPLATE.md @@ -0,0 +1,66 @@ +# + +<!-- OPENWC_CLAIM:<WORK-PACKAGE-ID>:<AGENT-ID>:<YYYY-MM-DD> --> + +## Ownership + +- Target: +- Program: +- Owner/Agent ID: +- Branch: +- Lease expires UTC: +- Integrator: + +## Outcome + + +## Non-goals + + +## Paths + +- Exclusive: +- Shared/hotspots: +- Generated/ignored: + +## Contracts and data + +- Public API/events: +- Schema/format version: +- Migration/compatibility: +- Consumers: + +## Dependencies + +- Requires: +- Blocks: +- External state: + +## Verification + +- Commands: +- Fixtures: +- Fidelity evidence: +- Performance budget: + +## Documentation deliverables + +- Inline public API docs: +- Module specification: +- Data-flow diagram: +- Sequence/state/dependency diagrams: +- Source map/status updates: + +## Status + +- State: claimed +- Done: +- Next: +- Blocked by: + +## Handoff + +- Commit: +- Results: +- Remaining risks: +- Documentation updated: diff --git a/coordination/claims/README.md b/coordination/claims/README.md new file mode 100644 index 0000000..2c80947 --- /dev/null +++ b/coordination/claims/README.md @@ -0,0 +1,5 @@ +# Fallback claims + +Этот каталог используется только когда общий issue/PR tracker недоступен. Каждый активный work package создаёт отдельный Markdown-файл по [`../TASK_TEMPLATE.md`](../TASK_TEMPLATE.md). + +Файл без валидного `OPENWC_CLAIM` marker не считается claim. Не хранить здесь secrets, credentials, proprietary data или большие логи. diff --git a/docs/CLIENT_FEATURES.md b/docs/CLIENT_FEATURES.md index 9501303..20b3b3a 100644 --- a/docs/CLIENT_FEATURES.md +++ b/docs/CLIENT_FEATURES.md @@ -37,6 +37,7 @@ - Packed GUIDs, update fields, create/update/out-of-range/destroy. - Movement flags, heartbeat, jump/fall/swim/fly, transports, knockback и spline movement. - Server time, tutorial flags, account data и feature capability detection. +- Warden handshake/module compatibility для явно поддерживаемых test/private server profiles с sandbox и без ориентации на official servers. ## Player и camera diff --git a/docs/DOCUMENTATION_STANDARD.md b/docs/DOCUMENTATION_STANDARD.md new file mode 100644 index 0000000..8a48db8 --- /dev/null +++ b/docs/DOCUMENTATION_STANDARD.md @@ -0,0 +1,278 @@ +# OpenWC Documentation Standard + +## Цель + +Документация является частью реализации. Код без актуального объяснения публичного API, данных, ownership и поведения считается незавершённым, даже если компилируется и проходит тесты. + +Документация должна позволить человеку ответить: + +- зачем существует модуль; +- какие данные он получает и откуда; +- что он создаёт или изменяет; +- кто владеет состоянием и ресурсами; +- какие зависимости допустимы; +- что происходит по шагам; +- как модуль завершается, отменяется и восстанавливается после ошибки; +- как проверить fidelity, correctness и performance; +- какие части реализованы, запланированы или известны как gap. + +## Уровни документации + +### 1. Inline API documentation + +Находится рядом с кодом и является источником истины для точной сигнатуры: + +- публичные classes/interfaces; +- public methods/functions; +- signals/events; +- exported properties/configuration; +- commands, events и read models; +- ownership/lifetime/threading requirements; +- error/return semantics; +- non-obvious invariants. + +### 2. Module specification + +Находится в `docs/modules/<module>.md` и объясняет назначение, архитектуру, data flow, state/lifecycle, extension points и verification. Шаблон: [`modules/TEMPLATE.md`](modules/TEMPLATE.md). + +### 3. Data/schema documentation + +Описывает persisted/wire/content formats: fields, types, units, optionality, version, migration, provenance и compatibility. Нельзя объяснять schema только примером JSON или SQL. + +### 4. ADR + +Фиксирует значимое решение, варианты и последствия. ADR не заменяет актуальное описание модуля: после решения module spec обновляется до текущего состояния. + +### 5. Operational documentation + +Команды build/test/import/bake/deploy/recovery, expected outputs и diagnostics. Команда без условий запуска и интерпретации результата недостаточна. + +## Обязательная module specification + +Новый самостоятельный модуль или существенно выделенная подсистема обязаны иметь документ со следующими разделами: + +1. Metadata/status. +2. Purpose и non-goals. +3. Context и architecture boundaries. +4. Public API. +5. Inputs и outputs. +6. Data flow diagram. +7. State/lifecycle или sequence diagram, если применимо. +8. Ownership, threading и resource lifetime. +9. Errors, cancellation и recovery. +10. Configuration/capabilities/profiles. +11. Persistence/cache/migrations. +12. Diagnostics и observability. +13. Tests, fidelity evidence и performance budgets. +14. Extension points. +15. Known gaps. +16. Source map. + +`Status` принимает только: + +- `Planned`; +- `Prototype`; +- `Partial`; +- `Implemented`; +- `Verified`; +- `Deprecated`. + +`Implemented` не означает fidelity; `Verified` требует evidence и ссылок на тесты. + +## Обязательные схемы + +### Data flow diagram + +Обязательна для каждого module spec. Показывает реальные имена contracts и направление данных: + +```mermaid +flowchart LR + Source[ADT bytes] --> Parser[ADTLoader] + Parser --> Data[AdtTileData] + Data --> Planner[StreamingTargetPlanner] + Planner --> Queue[RenderFinalizeCommand] + Queue --> Renderer[TerrainRenderer] +``` + +Диаграмма должна показывать: + +- внешние источники; +- входные contracts; +- преобразования; +- выходные contracts/side effects; +- persistence/cache, если участвует; +- запрещённое направление, если оно является важной границей. + +### Sequence diagram + +Обязательна, если операция пересекает два и более из следующих boundary: + +- thread/job queue; +- network; +- gameplay; +- renderer/UI/audio; +- Editor; +- server/database; +- filesystem/build pipeline. + +```mermaid +sequenceDiagram + participant Net as WorldSession + participant Game as WorldState + participant View as EntityPresenter + participant Render as WorldRenderFacade + Net->>Game: EntityCreated + Game-->>View: EntityReadModel change + View->>Render: spawn_entity(descriptor) +``` + +### State diagram + +Обязательна для lifecycle/state machine с тремя и более состояниями, reconnect/retry или rollback: + +```mermaid +stateDiagram-v2 + [*] --> Disconnected + Disconnected --> Connecting + Connecting --> Authenticated + Connecting --> Failed + Authenticated --> Disconnected + Failed --> Connecting: retry +``` + +### Dependency diagram + +Обязательна при изменении архитектурной границы или модуле с тремя и более downstream consumers. Она показывает compile/runtime dependencies, а не случайное расположение Node в сцене. + +## Public API documentation + +Для каждого public symbol указываются: + +- краткое назначение; +- параметры с единицами и coordinate space; +- return value или emitted event; +- preconditions/postconditions; +- ownership и mutability; +- допустимый thread; +- failure behavior; +- profile/capability restrictions; +- пример только если контракт остаётся неочевидным. + +### GDScript + +- Использовать `##` documentation comments для class, public methods, signals и exported properties. +- Всегда указывать типы аргументов/return, где Godot API позволяет. +- `@export` property объясняет units/range/profile и runtime mutability. +- Signal документирует момент emission, arguments и ordering guarantees. +- Internal helper получает комментарий, если содержит сложный invariant, coordinate conversion, ownership или performance assumption. + +### C++/GDExtension + +- Public headers используют Doxygen-compatible `///`/`/** */`. +- Документировать ownership указателей/references/buffers, thread safety и error transport. +- Binary structs указывают source format/build, packing/endianness и validation. +- Native/Godot boundary описывает allocation и lifetime Variant/PackedArray/Resource. +- Implementation comments объясняют `why` и invariant, а не пересказывают строку кода. + +### Shaders/materials + +- Uniform/global parameter: coordinate/color space, range, units и producer. +- Material profile: supported WoW shader/blend modes и approximations. +- Expensive branch/texture dependency имеет cost/fallback note. +- Blizzlike и Enhanced behavior документируются отдельно. + +### Network codecs + +- Opcode/direction/session phase. +- Exact build/profile. +- Field order/type/endianness/conditional presence. +- Domain events на выходе. +- Malformed/unknown handling. +- Fixture/reference source без sensitive payload. + +### Content/server schemas + +- Canonical field и mapping на каждый core adapter. +- Unit, default, null/optional semantics и flags. +- Numeric ID allocation и references. +- Migration/rollback и unsupported degradation. + +## Документация потока данных + +Inputs/outputs оформляются таблицей: + +| Direction | Contract/data | Producer | Consumer | Ownership | Thread/lifetime | +|---|---|---|---|---|---| +| Input | `EntityMoved` | `WorldSession` | `WorldState` | Immutable event | Game-thread apply | +| Output | `EntityReadModel` | `WorldState` | Presenter/UI | Snapshot | Until next revision | + +Side effects перечисляются отдельно: + +- scene tree mutation; +- RenderingServer RID creation/free; +- filesystem/cache write; +- network send; +- DB query/apply; +- settings/SavedVariables mutation. + +Скрытый side effect является дефектом документации и API. + +## Статус реализации + +Документ не должен выдавать roadmap за существующий код. Каждый важный capability помечается: + +| Capability | Status | Evidence | Gap/next step | +|---|---|---|---| + +После изменения кода статус и `Last verified` обновляются в том же work package. Если документацию нельзя подтвердить, ставится `Unknown`/`Planned`, а не предположение. + +## Documentation change rules + +Документация обновляется в том же work package, если изменились: + +- public API/signal/event; +- data flow или ownership; +- state/lifecycle; +- thread boundary; +- format/schema/cache version; +- configuration/capability; +- diagnostics/error/recovery; +- fidelity или performance behavior; +- extension point. + +Переименование symbol/path требует обновить source map, diagrams и ссылки. Stale documentation считается regression. + +## Code comments + +Хороший комментарий объясняет: + +- почему решение отличается от очевидного; +- форматное или protocol ограничение; +- ownership/thread invariant; +- причину batching/budget; +- источник fidelity behavior; +- временный compatibility path и условие удаления. + +Плохой комментарий: + +- пересказывает код; +- обещает будущую работу без target/work package ID; +- содержит устаревшую сигнатуру; +- маскирует magic number без source/unit; +- утверждает `Blizzlike` без evidence. + +TODO/FIXME должен содержать target/work package или diagnostic code. + +## Review gate + +Reviewer/integrator проверяет: + +- public symbols имеют inline docs; +- module spec существует или обновлён; +- input/output и side effects перечислены; +- diagrams соответствуют реальным contracts; +- state/error/recovery paths показаны; +- tests/evidence и known gaps честны; +- документы не дублируют противоречивые источники истины. + +Если хотя бы один обязательный пункт отсутствует, handoff остаётся `PARTIAL`, а target не может получить `DONE`. diff --git a/docs/GODOT_BEST_PRACTICES.md b/docs/GODOT_BEST_PRACTICES.md new file mode 100644 index 0000000..18da630 --- /dev/null +++ b/docs/GODOT_BEST_PRACTICES.md @@ -0,0 +1,120 @@ +# Godot Best Practices for OpenWC + +## Статус + +Это нормативные правила применения Godot в OpenWC. Они дополняют общую архитектуру и основаны на официальных Godot practices с учётом большого streaming world, native parsers и встроенного Editor tooling. + +## Nodes только на границах + +- Domain, packet codecs, validators, coordinate math, build graph и canonical content не должны быть Nodes. +- Node/Control используются для lifecycle, scene composition, input, rendering/audio presentation и Editor UI. +- Большой объём однородных данных хранится в typed objects/packed arrays/resources, а не в тысячах служебных Nodes. +- Scene не ищет глобально dependency по имени; parent composition передаёт contract/reference явно. + +## Scene organization + +- Каждая scene имеет одну ответственность и может запускаться в isolation с test doubles. +- Parent-child означает ownership: удаление parent логично удаляет child. Иначе системы являются siblings/services. +- Scene наружу публикует небольшой API/signals, а внутренние NodePaths не становятся публичным контрактом. +- Runtime, render sandbox, preview и capture scenes собираются из общих presenters/services. +- Generated world preview не сохраняется как authoring source. + +## Dependency injection и signals + +- Dependencies передаются composition root, initializer или exported interface reference. +- Signals используются для notification; commands/intents вызываются через явные методы/bus contracts. +- Signal connections снимаются симметрично при unload/plugin disable. +- Не использовать SceneTree groups как скрытый service locator для core architecture. + +## Autoload policy + +Autoload разрешён только для действительно process-wide lifecycle: + +- composition/bootstrap coordinator; +- глобальная immutable build/version information; +- crash/diagnostic sink, если ему нужен process lifetime. + +Gameplay state, network session, renderer world, editor session, caches конкретного проекта и audio emitters не должны становиться неявными глобальными managers. Они создаются/освобождаются владельцем режима. + +## Resources and data + +- Resource подходит для immutable/imported descriptors и editor-inspectable configuration. +- Runtime mutable authoritative state не хранится в shared Resource, который может быть случайно разделён сценами. +- Resource schema имеет version и migration, если сохраняется пользователем. +- Original extracted corpus и bulk caches не следует заставлять Godot массово импортировать без необходимости; применять `.gdignore`, custom import staging или native repository. +- Importer проверяет malformed input и записывает dependency/profile metadata. + +## Background work + +- Blocking `load()` не используется в frame-critical streaming path; применяются threaded load/jobs. +- Worker выполняет file I/O, parsing, decompression, grouping и pure data generation. +- SceneTree mutation, Node attach и большинство GPU/RID finalization выполняются main thread budget. +- Один Resource не модифицируется несколькими workers. +- GDScript container resize/mutation между threads защищается mutex или заменяется message passing. +- Все worker tasks ожидаются/очищаются; session cancellation не оставляет orphan work. + +## Rendering performance + +- Сначала измерять SceneTree/CPU/GPU bottleneck, затем переходить к RenderingServer. +- Repeated static M2 группировать spatial MultiMesh cells; один MultiMesh на весь мир ухудшает culling. +- Large transform buffers готовить линейно/в native code и отправлять батчем. +- Visibility ranges/HLOD, occlusion и automatic mesh LOD использовать совместно по профилю. +- Unique materials/textures минимизировать; descriptor/resource counts являются budget metric. +- RenderingServer RIDs имеют явного владельца и освобождаются в deterministic shutdown test. +- Shader/material profiles разделяют Blizzlike и Enhanced; runtime не компилирует тяжёлые варианты при пересечении ADT boundary. + +## EditorPlugin lifecycle + +- Любая регистрация в `_enter_tree()` имеет соответствующее удаление в `_exit_tree()`. +- Docks, inspectors, importers, gizmos, debugger plugins, signals и jobs снимаются при disable/reload. +- Editor UI не пишет файлы/SQL напрямую — только создаёт application commands. +- Mutation интегрирована с EditorUndoRedoManager или общей command history. +- Preview nodes считаются disposable; stable content IDs не равны instance IDs. +- Долгая операция имеет progress, cancellation и staging output. + +## Editor imports and inspectors + +- Custom import plugin применяется для формата, которому действительно нужен first-class Godot Resource lifecycle. +- Один extension/type имеет стабильный importer name и version. +- Platform/profile variants фиксируются явно. +- Custom inspectors редактируют canonical data через commands и показывают field-level validation. +- Gizmos не владеют сущностью и создают одну undoable logical operation на drag/stroke. + +## UI + +- Control tree не читает network packets и не ищет world nodes. +- View models immutable на frame/update boundary. +- Layout использует anchors/containers/theme tokens, а не hardcoded pixel positions вне fidelity backend. +- FrameXML compatibility layout изолирован от modern Godot-native screens. +- Input consumption и focus/modal context тестируются сценами. + +## Profiling and diagnostics + +- Использовать Godot profiler для script/physics и Visual Profiler для render CPU/GPU. +- Headless/CLI runs сохраняют JSON metrics; GPU runs фиксируют backend/device/driver/resolution. +- Performance changes сравниваются cold/warm и p50/p95/p99, а не одним FPS. +- GPU validation, memory tracking и RenderDoc workflow документируются для shader/backend defects. +- Custom monitors публикуют streaming queues, cache hits, entities, materials, RIDs и job latency. + +## Tests + +- Pure logic тестируется без SceneTree. +- Scene runner используется только для lifecycle/input/signals/layout/presentation. +- EditorPlugin имеет enable/disable/reload и undo/save/reload tests. +- Headless является обязательным CI path; visual tests запускаются отдельно на GPU runner. +- GdUnit4 рассматривается как кандидат для GDScript/scene tests; native tests остаются отдельным target. + +## Official references + +- [Godot Best practices](https://docs.godotengine.org/en/stable/tutorials/best_practices/index.html) +- [Scene organization](https://docs.godotengine.org/en/stable/tutorials/best_practices/scene_organization.html) +- [Autoloads versus regular nodes](https://docs.godotengine.org/en/stable/tutorials/best_practices/autoloads_versus_regular_nodes.html) +- [Background loading](https://docs.godotengine.org/en/stable/tutorials/io/background_loading.html) +- [Thread-safe APIs](https://docs.godotengine.org/en/stable/tutorials/performance/thread_safe_apis.html) +- [Optimization using MultiMeshes](https://docs.godotengine.org/en/stable/tutorials/performance/using_multimesh.html) +- [RenderingServer](https://docs.godotengine.org/en/stable/classes/class_renderingserver.html) +- [Import plugins](https://docs.godotengine.org/en/stable/tutorials/plugins/editor/import_plugins.html) +- [Inspector plugins](https://docs.godotengine.org/en/stable/tutorials/plugins/editor/inspector_plugins.html) +- [3D gizmo plugins](https://docs.godotengine.org/en/stable/tutorials/plugins/editor/3d_gizmos.html) +- [Command line tutorial](https://docs.godotengine.org/en/stable/tutorials/editor/command_line_tutorial.html) +- [Debugging tools](https://docs.godotengine.org/en/stable/tutorials/scripting/debug/overview_of_debugging_tools.html) diff --git a/docs/README.md b/docs/README.md index 54d0041..affedd8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,6 +4,8 @@ Исполняемая последовательность текущих целей находится в [`../targets/README.md`](../targets/README.md). Все агенты обязаны следовать корневому [`../AGENTS.md`](../AGENTS.md). +Полная инженерная карта проекта находится в [`../targets/DEVELOPMENT_ROADMAP.md`](../targets/DEVELOPMENT_ROADMAP.md); она раскрывает renderer, protocol, gameplay, UI/Lua/audio, Editor tooling, server emulators и quality/release workstreams. + ## Статус документов Документы описывают целевую архитектуру. Реализованное состояние рендера зафиксировано отдельно в [`../RENDER.md`](../RENDER.md). Если описание целевого решения расходится с кодом, это считается известным архитектурным долгом, а не разрешением обходить границы слоёв. @@ -23,6 +25,10 @@ | [ROADMAP.md](ROADMAP.md) | Последовательность вертикальных срезов и критерии готовности | | [REFERENCES.md](REFERENCES.md) | Использованные локальные reference-проекты и правила работы с ними | | [TOOLING_CATALOG.md](TOOLING_CATALOG.md) | Реестр готовых библиотек, редакторов, test oracles и кандидатов на интеграцию | +| [GODOT_BEST_PRACTICES.md](GODOT_BEST_PRACTICES.md) | Нормативные правила scenes, data, jobs, rendering, EditorPlugin, profiling и tests | +| [TEAM_WORKFLOW.md](TEAM_WORKFLOW.md) | Ветки/worktree, task claims, ownership, handoff, integration и conflict protocol | +| [DOCUMENTATION_STANDARD.md](DOCUMENTATION_STANDARD.md) | Обязательные API docs, module specs, data-flow/state/sequence diagrams и documentation gate | +| [modules/README.md](modules/README.md) | Реестр фактических модулей и шаблон их спецификаций | ## Обязательный workflow изменения функции diff --git a/docs/REFERENCES.md b/docs/REFERENCES.md index f9101e3..fe8bf90 100644 --- a/docs/REFERENCES.md +++ b/docs/REFERENCES.md @@ -67,6 +67,22 @@ Reference-код используется для исследования фор Подробные статусы и evaluation cards ведутся в [`TOOLING_CATALOG.md`](TOOLING_CATALOG.md). +### Godot, GdUnit4 и server tooling + +- [Godot best practices](https://docs.godotengine.org/en/stable/tutorials/best_practices/index.html) — основной источник engine-specific правил; принятые решения собраны в [`GODOT_BEST_PRACTICES.md`](GODOT_BEST_PRACTICES.md). +- [`godot-gdunit-labs/gdUnit4`](https://github.com/godot-gdunit-labs/gdUnit4) — кандидат для GDScript/scene/Editor/CI тестов. +- [`azerothcore/Keira3`](https://github.com/azerothcore/Keira3) — reference существующего редактора world DB и SQL generation. +- [AzerothCore database and module documentation](https://www.azerothcore.org/wiki/documentation-index) — primary reference для AzerothCore adapter/deployment workflow. +- [WowBench](https://sourceforge.net/projects/wowbench/) — исторический offline WoW XML/Lua API emulator и источник addon test ideas. + +### Warcraft format ecosystem + +- [`wowemulation-dev/warcraft-rs`](https://github.com/wowemulation-dev/warcraft-rs) — современный Rust CLI/library set для MPQ/DBC/BLP/ADT/WDT/WDL/M2/WMO и независимый кандидат на format oracle. +- [`wowdev/WoWDBDefs`](https://github.com/wowdev/WoWDBDefs) — versioned definitions client database tables; полезны для schema generation и coverage. +- [`gtker/wow_dbc`](https://github.com/gtker/wow_dbc) — независимый 1.12/2.4.3/3.3.5 DBC reader/writer и converter reference. + +Используем для differential testing текущих native parsers и поиска coverage gaps. Новый Rust dependency не принимается только из-за более широкого списка поддерживаемых форматов: сначала требуются build-specific fixtures и измеренное преимущество. + ## Правила исследования 1. Для protocol semantics приоритет имеют wire fixtures и соответствующая версия server core. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b0323cd..dac7fd1 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2,6 +2,8 @@ > Этот документ объясняет стратегию на высоком уровне. Исполняемый порядок, текущий статус, checklist и доказательства завершения ведутся только в [`../targets/README.md`](../targets/README.md). При расхождении `targets/` имеет приоритет. +Полный roadmap с точки зрения разработки, contracts, subsystem dependencies и gates находится в [`../targets/DEVELOPMENT_ROADMAP.md`](../targets/DEVELOPMENT_ROADMAP.md). + ## Стратегия Работа идёт вертикальными срезами. Каждый срез включает data, domain, adapter, presentation, editor support, diagnostics и tests. Горизонтальная реализация всех opcodes или всех editor-панелей без пользовательского результата не считается milestone. diff --git a/docs/TEAM_WORKFLOW.md b/docs/TEAM_WORKFLOW.md new file mode 100644 index 0000000..0f01cec --- /dev/null +++ b/docs/TEAM_WORKFLOW.md @@ -0,0 +1,343 @@ +# Командная разработка OpenWC + +## Цель + +Этот workflow позволяет нескольким людям и Codex-агентам работать параллельно, не перезаписывая изменения друг друга и не разрушая архитектурные границы. Единица параллельной работы — не milestone целиком, а ограниченный `work package`. + +## Основные правила + +1. Каждый агент работает в отдельном clone или Git worktree и собственной ветке. +2. Никто не разрабатывает напрямую в `master`. +3. До изменений задача получает ID, владельца, claim и список затрагиваемых путей. +4. Один work package имеет только одного активного владельца. +5. Общие contracts согласуются до параллельной реализации producers/consumers. +6. Статус milestone и `OPENWC_TARGET_DONE` изменяет только интегратор. +7. Merge выполняется только после handoff, локальных проверок и синхронизации с актуальным `master`. + +## Идентификаторы + +### Agent ID + +Каждый человек/агент выбирает стабильный ID на весь work package: + +```text +<human>-<machine>-codex +``` + +Примеры: + +```text +sindo-main-codex +alex-laptop-codex +``` + +ID записывается в claim, ветке, PR/MR и handoff. Нельзя использовать просто `codex`, потому что таких агентов несколько. + +### Work Package ID + +```text +<TARGET>-<PROGRAM>-<SHORT-NAME>-<NNN> +``` + +Примеры: + +```text +M01-FND-COORDS-001 +M03-RND-SCHEDULER-001 +M08-NET-SRP-001 +M12-UIA-LUA-SPIKE-001 +``` + +Program codes определены в [`../targets/DEVELOPMENT_ROADMAP.md`](../targets/DEVELOPMENT_ROADMAP.md). + +## Claim protocol + +Предпочтительный канал координации — issue + ранний draft PR/MR на общем Git forge. Если forge недоступен, используется отдельный файл в `coordination/claims/`, который сначала публикуется в общей ветке. + +Claim marker: + +```text +<!-- OPENWC_CLAIM:M01-FND-COORDS-001:sindo-main-codex:2026-07-13 --> +``` + +Последнее поле — дата истечения claim в UTC. Рекомендуемый срок — 48 часов; владелец продлевает его коротким status update. Истёкший claim нельзя забирать молча: сначала оставить сообщение владельцу и интегратору. + +Claim содержит: + +- target и work package; +- owner/agent ID; +- outcome и non-goals; +- exclusive paths; +- shared/hotspot paths; +- contracts/schema/format changes; +- dependencies и blockers; +- verification commands; +- expected fidelity evidence. +- documentation deliverables: inline API, module spec, diagrams и source map. + +## Ветки и worktrees + +Имя ветки: + +```text +work/<agent-id>/<target>-<short-name> +``` + +Пример: + +```text +work/sindo-main-codex/m01-coordinate-mapper +``` + +Начало работы: + +```powershell +git fetch origin +git worktree add ..\open-wc-m01 -b work/sindo-main-codex/m01-coordinate-mapper origin/master +``` + +Правила: + +- один worktree принадлежит одному агенту; +- не запускать двух агентов в одном dirty worktree; +- не менять и не удалять чужой worktree; +- generated caches и proprietary data не переносятся commit/cherry-pick; +- перед handoff ветка синхронизируется с актуальным `origin/master`. + +## Разделение задач + +Хороший work package: + +- даёт один наблюдаемый результат; +- принадлежит преимущественно одной подсистеме; +- имеет явные входы/выходы; +- меняет не более одного публичного contract одновременно; +- имеет собственные tests/diagnostics; +- может быть review и merged независимо либо после одной явно указанной dependency. + +Плохое разделение: + +- «сделать сеть»; +- один агент меняет protocol и UI напрямую; +- два агента одновременно рефакторят один monolithic file; +- задача зависит от незаписанного устного соглашения; +- work package оставляет временный второй источник истины. + +## Parallelization patterns + +### Contract first + +Для cross-layer feature сначала отдельным маленьким work package фиксируются: + +- domain types; +- commands/events/read models; +- version/capabilities; +- failure states; +- contract tests. + +После merge независимо работают producer и consumers. + +Пример: + +```text +WP-A: MovementSnapshot contract + ├─ WP-B: network movement decoder + ├─ WP-C: gameplay reconciliation + └─ WP-D: character/camera presentation +``` + +### Fixtures in parallel + +Пока один агент реализует pure logic, второй может готовить: + +- synthetic fixtures; +- original-client comparison procedure; +- server-core matrix; +- visual checkpoints; +- documentation/reference analysis. + +Fixture agent не изменяет production contract без согласования. + +### Adapter split + +После merge canonical interface допустимо параллельно реализовать TrinityCore и AzerothCore adapters, если у каждого разные файлы и общая contract suite. + +### Hotspot extraction first + +Если работа требует одного большого файла, сначала один владелец извлекает стабильный seam. Параллельная работа начинается только после merge seam, а не внутри разных участков монолита. + +## Hotspot-файлы + +Следующие пути требуют явного указания в claim и согласования с интегратором: + +- `project.godot`; +- `AGENTS.md`, `docs/README.md`, `targets/README.md`; +- текущий `targets/[0-9][0-9]-*.md`; +- `RENDER.md`; +- `src/scenes/streaming/streaming_world_loader.gd` до декомпозиции; +- native registration/CMake/GDExtension manifests; +- editor `plugin.cfg` и root plugin lifecycle; +- shared schema/version/format constants; +- dependency lockfiles и submodules. + +Два активных work packages не должны редактировать один hotspot. При необходимости интегратор выделяет serial integration window. + +## Изменение contracts и форматов + +Contract/schema change обязан иметь: + +- owner и потребителей; +- backward compatibility или migration; +- old/new fixtures; +- version bump policy; +- rollout order; +- ADR для существенного решения. + +Merge order: + +1. contract + compatibility layer; +2. producers; +3. consumers; +4. removal deprecated path отдельным work package. + +Нельзя одновременно удалить старый API и ожидать, что незамердженная ветка другого агента уже использует новый. + +## Commits + +Формат заголовка: + +```text +<program>(<target>): <imperative summary> +``` + +Примеры: + +```text +fnd(M01): add canonical coordinate mapper +net(M08): decode auth challenge safely +rnd(M03): extract streaming target planner +test(M00): add paired checkpoint manifest +``` + +Описание commit/PR содержит: + +```text +Work-Package: M01-FND-COORDS-001 +Agent: sindo-main-codex +Tests: <commands/results> +Fidelity: <evidence/gap> +``` + +Не смешивать formatting unrelated files, generated artifacts и функциональное изменение в одном commit. + +## Handoff protocol + +Готовый work package получает marker: + +```text +<!-- OPENWC_HANDOFF:READY:M01-FND-COORDS-001:<commit> --> +``` + +Handoff обязан содержать: + +- точный commit/branch; +- outcome и изменённые paths; +- публичные contracts/schema changes; +- verification commands и результаты; +- fidelity evidence/known gaps; +- migration/cache/rebuild requirements; +- unresolved risks; +- recommended merge order; +- updated API/module documentation и перечень diagrams. + +Если работа частичная: + +```text +<!-- OPENWC_HANDOFF:PARTIAL:M01-FND-COORDS-001:<commit> --> +``` + +`PARTIAL` не считается завершением и не разрешает ставить target `DONE`. + +## Integration protocol + +Интегратор: + +1. Проверяет claim и отсутствие overlapping ownership. +2. Проверяет diff на unrelated/user changes. +3. Синхронизирует branch с `master` без уничтожения чужой истории. +4. Запускает package verification и затронутые общие gates. +5. Проверяет docs, migrations, cache versions и fidelity statement. +6. Проверяет documentation gate из `docs/DOCUMENTATION_STANDARD.md`: API docs, inputs/outputs, diagrams, ownership и recovery. +7. Merge/squash выполняет в соответствии с историей work package. +8. После merge запускает post-merge smoke. +9. Закрывает claim marker-ом: + +```text +<!-- OPENWC_INTEGRATION:ACCEPTED:M01-FND-COORDS-001:<merge-commit> --> +``` + +Только после интеграции всех обязательных work packages интегратор обновляет target Evidence/status. + +## Конфликты + +При обнаружении overlapping edits агент должен остановить изменение затронутого файла и связаться с владельцем. Запрещено: + +- разрешать конфликт через слепое `ours/theirs`; +- копировать чужой файл поверх своего; +- делать `reset --hard` или checkout чужих изменений; +- «временно» дублировать contract без migration plan. + +Порядок разрешения: + +1. определить semantic owner; +2. выбрать merge order; +3. первый владелец публикует минимальный contract/seam; +4. второй rebase и адаптирует свою ветку; +5. integration tests подтверждают совместимость. + +## Status updates и stale work + +Владелец обновляет claim после значимого результата или не реже срока lease. Status краткий: + +```text +State: active | waiting | ready | partial +Done: ... +Next: ... +Blocked by: ... +Touched paths: ... +``` + +Если работа прекращена, claim явно освобождается. Незавершённую ветку не удаляют до handoff с описанием пригодных commits и известных проблем. + +## Минимальная схема для двух разработчиков + +- Один человек назначается интегратором текущего milestone. +- Второй берёт work package без пересечения файлов либо готовит fixtures/reference/adapter. +- Роль интегратора можно менять после каждого milestone. +- Перед началом дня оба выполняют `git fetch` и сверяют claims/draft PRs. +- Перед merge второй агент не начинает работу поверх непроверенного commit, если dependency не опубликована как contract branch. + +Пример для M01: + +```text +Developer A / integrator: + M01-FND-COORDS-001 — coordinate types and mapper + +Developer B: + M01-QAR-COORD-FIXTURES-001 — known ADT/server points and tests + +После merge contract: + A — StreamingFocus migration + B — placement/SQL conversion audit +``` + +## Автоматическая проверка + +Перед handoff и merge запускать: + +```powershell +.\tools\verify_coordination.ps1 +.\tools\verify_documentation.ps1 +``` + +Первая проверка требует ровно один `ACTIVE` numbered target, соответствие `Current target`, валидные и уникальные fallback claim markers. Вторая проверяет обязательные documentation files, структуру module specs, наличие data-flow diagram и относительные ссылки. Истёкший claim выдаёт warning и требует человеческого решения, но не удаляется автоматически. diff --git a/docs/TOOLING_CATALOG.md b/docs/TOOLING_CATALOG.md index fa28afe..7fcb0b9 100644 --- a/docs/TOOLING_CATALOG.md +++ b/docs/TOOLING_CATALOG.md @@ -47,9 +47,15 @@ Decision/ADR: | wow.export | REFERENCE | Asset conversion | M2/WMO/material/export edge cases | Web-specific pipeline | | Blender WoW Studio | REFERENCE | Authoring/conversion | WMO/M2/ADT authoring knowledge | Blender-specific UI/data model | | [Wowser](https://github.com/wowserhq/wowser) | REFERENCE | 3.3.5a web client | Auth/realm/character/world protocol, binary parsing, asset pipeline и render research | Старый JS/WebGL proof-of-concept, неполный клиент | +| [warcraft-rs](https://github.com/wowemulation-dev/warcraft-rs) | CANDIDATE | WoW formats/CLI | Independent MPQ/DBC/BLP/ADT/WDT/WDL/M2/WMO validation и conversion oracle | Rust/tool duplication; claims require fixtures | +| [WoWDBDefs](https://github.com/wowdev/WoWDBDefs) | REFERENCE | Client DB schemas | Versioned DBC definitions и typed-code generation input | Definitions still require build-specific validation | +| [wow_dbc](https://github.com/gtker/wow_dbc) | REFERENCE | DBC | 1.12/2.4.3/3.3.5 read/write и SQLite conversion ideas | Older release, Rust integration unnecessary by default | | [recast-rs](https://github.com/wowemulation-dev/recast-rs) | CANDIDATE | Navigation | Offline navmesh, reachability и dungeon validation | Server mmap compatibility не доказана | | [rilua](https://github.com/wowemulation-dev/rilua) | CANDIDATE | Lua/addons | Lua 5.1.1 runtime candidate и headless compatibility oracle | Taint/WoW API/FrameXML отсутствуют; Rust bridge | | PUC-Rio Lua 5.1.1 | CANDIDATE | Lua reference/runtime | Authoritative Lua oracle и альтернативный embedded VM | Нужны WoW sandbox, taint и безопасный C++ boundary | +| [GdUnit4](https://github.com/godot-gdunit-labs/gdUnit4) | CANDIDATE | Godot tests | GDScript, scene, Editor и CI test runner для Godot 4.6 | Plugin/toolchain pin и adoption spike | +| [Keira3](https://github.com/azerothcore/Keira3) | REFERENCE | AzerothCore DB editor | Field semantics, SQL generation и DB editor UX | AGPL; schema-specific web architecture | +| [WowBench](https://sourceforge.net/projects/wowbench/) | REFERENCE | WoW UI/API | Offline XML/Lua API emulation и addon test ideas | Старый и неполный implementation | ## rilua — карточка кандидата @@ -79,6 +85,22 @@ Decision/ADR: - **Known gaps:** совместимость `.mmap/.mmtile` и параметров TrinityCore/AzerothCore не доказана. - **Spike:** synthetic + one WoW tile comparison с C++ Recast; затем отдельный server mmap compatibility experiment. +## warcraft-rs — карточка кандидата + +- **Problem solved:** единый CLI/library set для MPQ, DBC, BLP, ADT, WDT, WDL, M2 и WMO версий 1.12.1–5.4.8, включая заявленную full support 3.3.5a. +- **Planned boundary:** сначала внешний pinned CLI как independent parser/validator oracle; не заменять текущий native pipeline автоматически. +- **License:** MIT OR Apache-2.0. +- **Spike:** сравнить OpenWC и warcraft-rs на synthetic/corrupt/real local fixtures: parsed counts, bounds, flags, alpha, materials, animations и diagnostics. +- **Decision policy:** отдельные crates рассматриваются только если дают доказанное преимущество; Rust runtime/toolchain не вводится ради дублирования работающего C++ parser. + +## GdUnit4 — карточка кандидата + +- **Problem solved:** Godot 4 GDScript/scene tests, assertions, mocks, input simulation, command-line and JUnit reports. +- **Planned boundary:** development/test plugin only; production export не зависит от test framework. +- **License:** MIT. +- **Spike:** закрепить совместимую с Godot 4.6.1 версию; проверить pure GDScript, scene lifecycle, input, EditorPlugin и headless CI sample; измерить startup overhead. +- **Decision policy:** ADOPTED только после воспроизводимого Windows/headless run и отсутствия конфликта с project plugins. + ## Процесс добавления инструмента 1. Добавить карточку со статусом `REFERENCE` или `CANDIDATE`. diff --git a/docs/modules/README.md b/docs/modules/README.md new file mode 100644 index 0000000..b1e5873 --- /dev/null +++ b/docs/modules/README.md @@ -0,0 +1,18 @@ +# OpenWC Module Documentation + +Модульные спецификации создаются по [`TEMPLATE.md`](TEMPLATE.md) и правилам [`../DOCUMENTATION_STANDARD.md`](../DOCUMENTATION_STANDARD.md). + +## Registry + +| Module | Current status | Primary specification | +|---|---|---| +| Foundation/data | Planned/Partial | [`../../targets/roadmap/01-foundation-and-data.md`](../../targets/roadmap/01-foundation-and-data.md) | +| Renderer | Partial | [`world-renderer.md`](world-renderer.md), [`../../RENDER.md`](../../RENDER.md) | +| Network/session | Planned | [`../../targets/roadmap/03-network-and-session.md`](../../targets/roadmap/03-network-and-session.md) | +| Gameplay | Prototype/Planned | [`../../targets/roadmap/04-gameplay-systems.md`](../../targets/roadmap/04-gameplay-systems.md) | +| UI/Lua/audio | Prototype/Planned | [`../../targets/roadmap/05-ui-lua-audio.md`](../../targets/roadmap/05-ui-lua-audio.md) | +| Editor/content tools | Prototype/Planned | [`../../targets/roadmap/06-editor-and-content-tools.md`](../../targets/roadmap/06-editor-and-content-tools.md) | +| Server adapters | Planned | [`../../targets/roadmap/07-server-emulator-integration.md`](../../targets/roadmap/07-server-emulator-integration.md) | +| Quality/release | Partial | [`../../targets/roadmap/08-quality-and-release.md`](../../targets/roadmap/08-quality-and-release.md) | + +Roadmap-файл описывает полную целевую программу. При начале реализации самостоятельной подсистемы создаётся отдельный module spec, показывающий фактический статус и текущий data flow. diff --git a/docs/modules/TEMPLATE.md b/docs/modules/TEMPLATE.md new file mode 100644 index 0000000..57e1090 --- /dev/null +++ b/docs/modules/TEMPLATE.md @@ -0,0 +1,127 @@ +# <Module Name> + +## Metadata + +| Field | Value | +|---|---| +| Status | Planned / Prototype / Partial / Implemented / Verified / Deprecated | +| Target/work package | | +| Owners | | +| Last verified | `<commit>, YYYY-MM-DD` | +| Profiles/capabilities | | + +## Purpose + + +## Non-goals + + +## Context and boundaries + +```mermaid +flowchart LR + Input[Input contract] --> Module[Module] + Module --> Output[Output contract] +``` + +Allowed dependencies: + +- + +Forbidden dependencies: + +- + +## Public API + +| Symbol | Kind | Purpose | Thread/lifetime | Errors | +|---|---|---|---|---| + +## Inputs and outputs + +| Direction | Contract/data | Producer | Consumer | Ownership | Thread/lifetime | +|---|---|---|---|---|---| + +Side effects: + +- + +## Data flow + +```mermaid +flowchart LR + Source --> Transform --> Result +``` + +## Lifecycle/state + +```mermaid +stateDiagram-v2 + [*] --> Created + Created --> Ready + Ready --> Stopped + Stopped --> [*] +``` + +## Main sequence + +```mermaid +sequenceDiagram + participant A as Producer + participant M as Module + participant B as Consumer + A->>M: Input + M-->>B: Output +``` + +## Ownership, threading and resources + + +## Errors, cancellation and recovery + +| Failure | Detection | Behavior | Diagnostic | Recovery | +|---|---|---|---|---| + +## Configuration and capabilities + +| Setting/capability | Default | Profile | Runtime mutable | Effect | +|---|---|---|---|---| + +## Persistence, cache and migration + + +## Diagnostics and observability + +- Logs: +- Metrics: +- Debug views: +- Correlation IDs: + +## Verification + +- Unit/contract tests: +- Integration/E2E: +- Fidelity evidence: +- Performance budgets: +- Manual diagnostics: + +## Extension points + + +## Capability status + +| Capability | Status | Evidence | Gap/next step | +|---|---|---|---| + +## Known gaps and risks + + +## Source map + +| Path | Responsibility | +|---|---| + +## Related decisions and references + +- ADR: +- Upstream/reference: diff --git a/docs/modules/world-renderer.md b/docs/modules/world-renderer.md new file mode 100644 index 0000000..3f07527 --- /dev/null +++ b/docs/modules/world-renderer.md @@ -0,0 +1,248 @@ +# World Renderer + +## Metadata + +| Field | Value | +|---|---| +| Status | Partial | +| Target/work package | M00 active; декомпозиция M01–M03 | +| Owners | Renderer workstream / milestone integrator | +| Last verified | `93bfe11` + M00 worktree baseline, 2026-07-10 | +| Profiles/capabilities | `Performance`, `Balanced`, `High`, `Custom`; Blizzlike fidelity incomplete | + +## Purpose + +Загрузить и визуализировать мир WoW 3.3.5a вокруг streaming focus: terrain, ADT placements, M2, WMO, liquids, sky/light и character/world presentation experiments. Система должна скрывать I/O/parsing/finalization latency за prewarm и per-frame budgets. + +## Non-goals + +- Не владеет gameplay/world authoritative state. +- Не читает network packets или server DB. +- Не определяет player input/movement rules. +- Не является Content Project или editor source of truth. +- Текущий module не заявляет визуальное соответствие `1:1`; gaps ведутся в [`../../RENDER.md`](../../RENDER.md). + +## Context and boundaries + +```mermaid +flowchart LR + Focus[Camera/player/editor focus] --> Loader[StreamingWorldLoader] + Assets[Extracted WDT/ADT/M2/WMO/BLP] --> Native[Native loaders] + Cache[Baked terrain/M2/WMO caches] --> Loader + Native --> Parsed[Parsed tile/model data] + Parsed --> Loader + Loader --> Scene[SceneTree nodes] + Loader --> RS[RenderingServer RIDs/MultiMesh] + Sky[DBC sky/light data] --> SkyController[WowSkyController] + SkyController --> Scene +``` + +Allowed dependencies: + +- native format loaders; +- render builders/material helpers; +- immutable/cached render resources; +- renderer configuration and focus; +- Godot rendering/scene APIs. + +Forbidden dependencies: + +- packet codecs/world session; +- gameplay reducers/quest/combat state; +- runtime UI Controls; +- direct TrinityCore/AzerothCore database access. + +## Public API + +Текущая система ещё не имеет стабильного facade. Фактический integration surface — `StreamingWorldLoader` Node3D и exported properties. M03 должен заменить этот surface на `WorldRenderFacade`. + +| Symbol | Kind | Purpose | Thread/lifetime | Errors | +|---|---|---|---|---| +| `map_name` | Exported property | WDT/map directory name | Set before world load | Missing WDT produces diagnostic/empty world | +| `extracted_dir` | Exported property | Root of legally extracted client data | Session lifetime | Missing files reported per loader path | +| `camera_path` | Exported property | Current streaming focus compatibility path | Main thread, scene lifetime | Missing camera prevents normal focus update | +| `quality_preset` | Exported property | Applies renderer budgets/radii | Before/at runtime depending property | Invalid combination should be diagnosed | +| `runtime_stats_enabled` | Exported property | Enables periodic performance snapshot | Runtime mutable | Logging overhead only | +| `hitch_profiler_enabled` | Exported property | Enables named hitch sections | Runtime mutable | Logging overhead only | + +Публичным contract не считаются внутренние dictionaries, queues, job records и generated node names. + +## Inputs and outputs + +| Direction | Contract/data | Producer | Consumer | Ownership | Thread/lifetime | +|---|---|---|---|---|---| +| Input | Map/focus/configuration | Scene/app/editor | `StreamingWorldLoader` | Caller config, copied/read | Main thread/session | +| Input | WDT/ADT/M2/WMO/BLP bytes | Extracted asset repository | Native loaders/builders | Loader result owns parsed data | Worker or controlled load | +| Input | Baked resources | Cache build tools | Streamer/builders | Shared immutable resource/cache entry | Session/cache lifetime | +| Output | Desired tile/detail operations | Streaming planner inside loader | Finalize queues | Loader-owned | Cross-frame | +| Output | Terrain/M2/WMO/liquid instances | Loader/builders | Godot world/renderer | Loader/world owner | Main-thread attach | +| Output | Metrics/diagnostics | Hitch/stat instrumentation | Logs/baseline tools | Immutable records | Periodic/frame | + +Side effects: + +- reads extracted files and generated caches; +- creates/frees scene nodes, meshes, materials, MultiMeshes and RIDs; +- submits worker tasks; +- mutates shader globals/environment through render/sky paths; +- writes logs and baseline captures through tools. + +## Data flow + +```mermaid +flowchart TD + F[Streaming focus] --> T[Compute desired ADT tiles] + WDT[WDT tile catalog] --> T + T --> Q[Tile load queue] + Q --> P[Worker parse/cache load] + P --> R[Result queues] + R --> B[Per-frame budget scheduler] + B --> Terrain[Terrain attach/upgrade] + B --> M2[M2 group/MultiMesh attach] + B --> WMO[WMO instance/group attach] + B --> Liquid[Liquid attach] + Terrain --> World[Godot world] + M2 --> World + WMO --> World + Liquid --> World + F --> E[Eviction/retention decisions] + E --> World +``` + +## Lifecycle/state + +```mermaid +stateDiagram-v2 + [*] --> Initializing + Initializing --> Ready: WDT/catalog/config ready + Initializing --> Degraded: missing loaders/data/cache + Ready --> Streaming: focus update + Streaming --> Streaming: load/finalize/evict ticks + Streaming --> SwitchingMap: map/focus reset + SwitchingMap --> Initializing + Ready --> ShuttingDown + Degraded --> ShuttingDown + Streaming --> ShuttingDown + ShuttingDown --> [*] +``` + +## Main sequence + +```mermaid +sequenceDiagram + participant Focus as Camera/Player/Editor + participant Stream as StreamingWorldLoader + participant Worker as Worker task + participant Budget as Main-thread budget + participant Render as SceneTree/RenderingServer + Focus->>Stream: focus position changed + Stream->>Stream: desired tiles and priorities + Stream->>Worker: parse/load tile and detail data + Worker-->>Stream: immutable result + Stream->>Budget: enqueue finalize operations + Budget->>Render: attach bounded terrain/M2/WMO/liquid work + Stream->>Render: evict outside retention range +``` + +## Ownership, threading and resources + +- `StreamingWorldLoader` владеет tile states, queues, task registries, active world instances и render caches session scope. +- Worker tasks не должны менять SceneTree и shared Resource concurrently. +- Parsed/grouped results передаются обратно через guarded result queues. +- Mesh/material/node/RID finalization выполняется main thread и ограничивается exported budgets. +- Shutdown/map switch обязан отменить/дождаться jobs и освободить RIDs; M00 всё ещё фиксирует leaked-resource risk. +- Cache resources считаются immutable после публикации. + +## Errors, cancellation and recovery + +| Failure | Detection | Behavior | Diagnostic | Recovery | +|---|---|---|---|---| +| Missing WDT/ADT | File/catalog check | Tile/map unavailable | Loader warning/error | Fix extraction/profile, reload | +| Cache version mismatch | Required format constant | Reject stale cache/fallback | Version diagnostic | Rebuild matching cache | +| Worker failure | Task result/empty data | Skip/degrade affected asset | Queue/task warning | Retry/rebuild source | +| Main-thread hitch | Named section timing | Frame spike, work remains queued | `HITCH` log | Lower budget/fix finalize path | +| D3D12 descriptor exhaustion | Rendering backend error | Render failure/fallback backend | Godot error + baseline report | Dedup resources/fix settings | +| Teleport/map change | Focus/session transition | Old jobs become stale | Target/session generation | Cancel/drop stale results | +| Shutdown leak | Godot leak/RID diagnostics | Resource retained | Shutdown report | Ownership cleanup before DONE | + +## Configuration and capabilities + +| Setting/capability | Default | Profile | Runtime mutable | Effect | +|---|---|---|---|---| +| Quality preset | Scene-specific | All | Limited | Applies radii and finalize budgets | +| Terrain control splat | Enabled in current High paths | Render | Limited | Near terrain texture quality | +| M2/WMO/liquids | Scene/profile-specific | Render | Debug/config | Enables asset categories | +| Runtime stats/hitch profiler | Usually debug | Dev/test | Yes | Observability cost | +| Shadow flags | Mostly disabled/limited | Blizzlike/Enhanced | Profile | CPU/GPU cost and visuals | + +Exact exported settings and cache versions remain documented in [`../../RENDER.md`](../../RENDER.md) until extracted services receive individual specs. + +## Persistence, cache and migration + +- Renderer reads caches under `data/cache`; caches are not committed. +- Format changes require `FORMAT_VERSION`/required-version bump and rebuild instructions. +- Atomic cache publication and unified manifest are target-state work from FND/M03. +- Material-only changes may refresh without geometry rebake only when documented safe. + +## Diagnostics and observability + +- Logs: `HITCH`, `PERF`, `TERRAIN_QUALITY`, `SKY_LIGHT`, `SKYBOX_MODEL`. +- Metrics: queue depths, active tiles/assets, named finalize times, frame percentiles and max hitch. +- Debug views: render checkpoint scenes/captures; future streaming/LOD/portal overlays. +- Correlation IDs: currently mostly tile/path keys; target architecture adds session/job IDs. + +## Verification + +- Unit/contract tests: material mapping, unique-ID dedupe, placement probes, baseline manifest. +- Integration/E2E: Eastern Kingdoms/Kalimdor streaming scenes and seven cold/warm checkpoints. +- Fidelity evidence: current fixed-position captures exist; approved original-client paired screenshots are still missing. +- Performance budgets: M00 report records cold/warm p95 and max hitch; no final acceptance threshold yet. +- Manual diagnostics: [`../RENDER_BASELINE.md`](../RENDER_BASELINE.md) and [`../../RENDER.md`](../../RENDER.md). + +## Extension points + +- Target `WorldRenderFacade` for runtime/editor/capture callers. +- Target `StreamingFocus` independent of Camera3D. +- Extracted planner, budget scheduler, terrain, M2, WMO, liquid, sky and character services. +- Separate Blizzlike/Enhanced material and quality profiles. + +## Capability status + +| Capability | Status | Evidence | Gap/next step | +|---|---|---|---| +| ADT streaming/terrain | Partial | M00 checkpoints and current scenes | Fidelity/performance gaps remain | +| Static M2 placement | Partial | MultiMesh/dedupe probes | Full materials/animation/effects | +| WMO rendering | Partial | Cached group rendering | Portals/rooms/material parity | +| Liquids | Partial | MH2O/MLIQ paths | LiquidType/depth/shore fidelity | +| Sky/light | Partial | DBC controller/logs | Zone transition paired validation | +| Character presentation | Prototype | Character creator/player experiment | Full customization/equipment states | +| Stable renderer facade | Planned | M03 | Current caller uses monolithic Node API | + +## Known gaps and risks + +- Monolithic streamer mixes planning, jobs, caches and presentation. +- Direct camera path remains until M01/M03. +- Original-client paired fidelity evidence incomplete. +- D3D12 descriptor and shutdown RID/resource issues remain. +- M2/WMO/material/particle/ribbon/portal parity incomplete. +- Public API is mostly exported configuration rather than stable contracts. + +## Source map + +| Path | Responsibility | +|---|---| +| `src/scenes/streaming/streaming_world_loader.gd` | Current runtime orchestration, queues, caches and attachment | +| `addons/mpq_extractor/loaders/adt_builder.gd` | Terrain/material/liquid construction | +| `addons/mpq_extractor/loaders/m2_builder.gd` | Static M2 mesh/material construction | +| `addons/mpq_extractor/loaders/m2_native_animated_builder.gd` | Native animated M2 experiment | +| `addons/mpq_extractor/loaders/wmo_builder.gd` | WMO groups/doodads/liquids construction | +| `src/scenes/sky/wow_sky_controller.gd` | DBC-driven sky/light/environment | +| `src/native/src/*_loader.cpp` | Native binary parsing | +| `src/tools/build_*cache.gd`, `src/tools/bake_*cache.gd` | Offline cache generation | +| `tools/run_render_baseline.ps1` | Unified M00 baseline runner | + +## Related decisions and references + +- [`../../RENDER.md`](../../RENDER.md) +- [`../RENDER_BASELINE.md`](../RENDER_BASELINE.md) +- [`../../targets/roadmap/02-rendering-and-graphics.md`](../../targets/roadmap/02-rendering-and-graphics.md) +- [`../GODOT_BEST_PRACTICES.md`](../GODOT_BEST_PRACTICES.md) diff --git a/targets/12-client-completeness.md b/targets/12-client-completeness.md index e4e68bb..29e9c2f 100644 --- a/targets/12-client-completeness.md +++ b/targets/12-client-completeness.md @@ -6,6 +6,8 @@ Последовательно закрыть всю матрицу `docs/CLIENT_FEATURES.md` до подтверждённой совместимости. +Работа выполняется completeness waves C1–C8 из [`DEVELOPMENT_ROADMAP.md`](DEVELOPMENT_ROADMAP.md) с обязательным чтением gameplay, UI/audio, server и quality subsystem plans. Этот target не разрешает массово реализовывать все пункты одновременно. + ## Required order - [ ] Combat, spells, casting, cooldowns, auras, death/resurrection. diff --git a/targets/DEVELOPMENT_ROADMAP.md b/targets/DEVELOPMENT_ROADMAP.md new file mode 100644 index 0000000..05d94bc --- /dev/null +++ b/targets/DEVELOPMENT_ROADMAP.md @@ -0,0 +1,150 @@ +# OpenWC Full Development Roadmap + +## Назначение + +Этот документ — полная инженерная карта разработки OpenWC. Статусы и последовательность исполняемых milestones остаются в [`README.md`](README.md); детальные subsystem plans находятся в [`roadmap/`](roadmap/). При расхождении текущий target определяет, что делать сейчас, а этот roadmap — как решение должно развиваться целиком. + +Godot-specific implementation rules обязательны из [`../docs/GODOT_BEST_PRACTICES.md`](../docs/GODOT_BEST_PRACTICES.md). + +## Итоговый продукт + +OpenWC должен предоставить четыре согласованных режима: + +1. `Blizzlike335` — клиент WoW 3.3.5a build 12340 с максимально точным наблюдаемым поведением. +2. `Enhanced` — opt-in графические, UX и accessibility улучшения, не меняющие wire protocol и server authority без отдельного profile. +3. `AuthoringStudio` — инструменты мира, контента, БД и playtest внутри Godot Editor. +4. `HeadlessTools` — import, validation, bake, packet replay, content build и CI без GUI. + +Один кодовый путь должен обслуживать runtime и editor preview через публичные contracts. Generated preview nodes, DB records и caches не являются источником истины. + +## Текущее положение + +- MPQ/BLP/ADT/WDT/M2/WMO native parsing и renderer vertical slice уже существуют. +- Runtime streaming, terrain quality, MultiMesh M2, WMO caches, liquids, sky и character experiments находятся в рабочем состоянии, но сосредоточены в крупных orchestration scripts. +- Renderer baseline M00 создан; до `DONE` не хватает paired comparison с оригинальным клиентом и закрытия известных diagnostic gaps. +- Gameplay domain, network protocol, production UI/Lua, audio orchestration и server adapters в основном предстоит реализовать. +- Editor plugin пока решает extraction/preview задачи, но не является полноценной authoring platform. + +## Инженерные программы + +| Код | Программа | Детальный план | +|---|---|---| +| FND | Foundation, application и data | [01-foundation-and-data.md](roadmap/01-foundation-and-data.md) | +| RND | Renderer и graphics | [02-rendering-and-graphics.md](roadmap/02-rendering-and-graphics.md) | +| NET | Protocol, session и synchronization | [03-network-and-session.md](roadmap/03-network-and-session.md) | +| GMP | Gameplay systems | [04-gameplay-systems.md](roadmap/04-gameplay-systems.md) | +| UIA | UI, Lua, addons, audio | [05-ui-lua-audio.md](roadmap/05-ui-lua-audio.md) | +| EDT | Godot Editor и content authoring | [06-editor-and-content-tools.md](roadmap/06-editor-and-content-tools.md) | +| SRV | TrinityCore/AzerothCore integration | [07-server-emulator-integration.md](roadmap/07-server-emulator-integration.md) | +| QAR | Fidelity, tests, CI и releases | [08-quality-and-release.md](roadmap/08-quality-and-release.md) | + +## Dependency graph + +```text +M00 renderer baseline + └─ M01 coordinates/contracts + └─ M02 input/movement/camera/presentation split + └─ M03 renderer facade + ├─ M04 editor shell → M05 content → M06 server adapters → M07 world editor + └─ M08 network → M09 gameplay domain → M10 playable client + M07 + M10 → M11 quest end-to-end + └─ M12 completeness waves + └─ M13 dungeon authoring +``` + +M12 не является одним большим этапом. Он выполняется последовательными completeness waves: + +1. `C1 Core loop` — combat, spells, auras, death, loot, inventory, quests. +2. `C2 Character` — creation/customization, equipment, animation, pets, mounts. +3. `C3 World` — map/minimap, exploration, taxi, transports, weather, audio. +4. `C4 Services` — gossip, vendors, trainers, bank, mail, auction, professions. +5. `C5 Social` — chat, friends, ignore, party, raid, guild, calendar. +6. `C6 Instances/PvP` — lockouts, LFG, vehicles, battlegrounds, arenas, outdoor PvP. +7. `C7 UI/addons` — FrameXML, Lua 5.1.1, secure execution, default UI, compatibility tiers. +8. `C8 Fidelity/polish` — complete render/material/audio coverage, recovery, accessibility, localization и performance. + +Каждая wave должна завершаться работающим gameplay scenario, а не количеством реализованных opcodes или таблиц. + +## Milestone delivery matrix + +| Milestone | Основные work packages | Обязательный результат | +|---|---|---| +| M00 | RND baseline, QAR metrics/fidelity lab | Воспроизводимые checkpoints и gaps | +| M01 | FND typed coordinates/IDs/contracts | Server/ADT/Godot round-trip и StreamingFocus | +| M02 | FND composition, GMP movement, RND presenters | Player split без visual/control regression | +| M03 | RND facade/planner/scheduler, FND jobs | Renderer доступен через API и сохраняет budgets | +| M04 | EDT plugin shell, QAR editor tests | Reload-safe workspace, commands, undo/recovery | +| M05 | FND content schemas/cache, EDT project | Deterministic Content Project build/migration | +| M06 | SRV environments/snapshots/adapters | Two-core read/diff/dry-run round-trip | +| M07 | EDT world editing/navigation/deploy | NPC placement на dev-core без ручного SQL | +| M08 | NET transport/auth/protocol/entities | Headless auth → world и deterministic replay | +| M09 | GMP world state/movement/targeting | Packet replay → deterministic gameplay snapshot | +| M10 | FND app lifecycle, RND/UIA presentation | Игрок входит, видит entities и перемещается | +| M11 | GMP quests, EDT quest tools, SRV deploy, UIA quest UI | Author → deploy → complete quest своим клиентом | +| M12 C1–C8 | NET/GMP/RND/UIA completeness + QAR | Feature matrix `Compatible/Verified` по waves | +| M13 | EDT dungeon/encounter, SRV modules, GMP instances | Custom dungeon group playtest end-to-end | + +## Recommended implementation rhythm + +Каждая feature внутри milestone проходит один и тот же цикл: + +1. `Research` — original behavior, core expectations, готовые tools/references. +2. `Contract` — owner, types, commands/events, capabilities и error states. +3. `Fixture` — golden input/output или reproducible live scenario до production code. +4. `Pure implementation` — parser/reducer/validator без Node where possible. +5. `Adapter` — network, renderer, UI, Editor или server boundary. +6. `Vertical integration` — минимальный observable player/author outcome. +7. `Failure/recovery` — malformed, cancel, disconnect, rollback, missing asset. +8. `Fidelity/performance` — comparison evidence и budgets. +9. `Documentation` — coverage status, known gaps, tooling decision и target evidence. + +## Cross-cutting contracts + +- `BuildProfile` — `Blizzlike335`, `Enhanced`, authoring и test capabilities. +- `CoordinateMapper` — единственное преобразование WoW/Godot/ADT/server coordinates. +- `AssetRepository` — original assets, overlays, caches и provenance. +- `ProtocolProfile` — build, opcodes, update fields, codecs и server capabilities. +- `WorldState` — authoritative client-side projection без Node dependencies. +- `WorldRenderFacade` — presentation boundary. +- `ViewModel/Intent` — единственная граница UI с gameplay. +- `LuaRuntime` — заменяемый Lua backend. +- `ContentProject` — stable IDs, schemas, dependencies и user-authored source. +- `ServerSchemaAdapter` — canonical content ↔ core schema/change set. +- `JobScheduler` — bounded background work, cancellation, progress и main-thread finalize. +- `Diagnostic` — code, severity, location, context, suggested fix и correlation ID. + +## Архитектурные gates + +Перед переходом между крупными фазами обязательны: + +- `Architecture gate`: запрещённые зависимости отсутствуют. +- `Fidelity gate`: есть comparison evidence, а gaps зарегистрированы. +- `Data gate`: schema/version/migration и deterministic build проверены. +- `Performance gate`: budgets измерены на cold/warm и stress scenarios. +- `Recovery gate`: failure/reconnect/cancel/rollback проверены. +- `Authoring gate`: изменения можно создать, проверить, diff, undo и воспроизвести. +- `Server gate`: обе схемы не предполагаются одинаковыми, capabilities обнаружены явно. + +## Правило улучшений + +Современное улучшение допускается, если: + +1. исходное поведение `Blizzlike335` уже измерено или gap отмечен; +2. улучшение включается отдельным setting/profile; +3. оно не меняет protocol/server authority скрыто; +4. есть before/after visual/performance/accessibility evidence; +5. Content Project указывает required capability и fallback. + +Примеры допустимых opt-in улучшений: modern shadows, higher terrain texture resolution, anisotropy, enhanced water, longer draw distance, FSR/upscaling, color-blind palettes, scalable UI, richer editor diagnostics. Новые gameplay rules требуют server module/profile, а не только client toggle. + +## Definition of complete client + +Клиент считается полным не тогда, когда перечислены все packet handlers, а когда: + +- все строки [`../docs/CLIENT_FEATURES.md`](../docs/CLIENT_FEATURES.md) имеют evidence-backed статус; +- основные сценарии оригинального клиента воспроизводятся end-to-end; +- default UI и выбранные addons проходят compatibility tiers; +- supported TrinityCore/AzerothCore profiles проходят contract matrix; +- renderer, audio, input, localization и recovery имеют утверждённые gaps/budgets; +- AuthoringStudio может создать, проверить, развернуть и протестировать новый quest/location/dungeon package; +- release не содержит proprietary assets и требует легально полученную установку клиента. diff --git a/targets/README.md b/targets/README.md index c94eaa1..44d35e0 100644 --- a/targets/README.md +++ b/targets/README.md @@ -4,12 +4,18 @@ Этот каталог задаёт обязательную последовательность реализации. Архитектура описана в `docs/`, фактическое состояние renderer — в `RENDER.md`, а здесь находятся исполняемые milestones. +Полная инженерная декомпозиция всех подсистем находится в [`DEVELOPMENT_ROADMAP.md`](DEVELOPMENT_ROADMAP.md). Перед работой над milestone агент читает соответствующий subsystem plan из `targets/roadmap/`, но статус меняет только в исполняемом target-файле M00–M13. + +Параллельная командная работа выполняется по [`../docs/TEAM_WORKFLOW.md`](../docs/TEAM_WORKFLOW.md): отдельные worktrees, claims, exclusive paths, contract-first и интегратор milestone. + ## Current target `M00` — [00-render-baseline.md](00-render-baseline.md) Одновременно `ACTIVE` может быть только одна цель. Следующая цель становится `ACTIVE` после появления валидной `OPENWC_TARGET_DONE` метки у предыдущей. +Статусные метки применяются только к исполняемым файлам `targets/[0-9][0-9]-*.md`. `DEVELOPMENT_ROADMAP.md` и `targets/roadmap/` являются нормативной декомпозицией, но не создают параллельную систему статусов. + ## Definition of fidelity 1:1 `1:1` означает совпадение наблюдаемого поведения с оригинальным клиентом WoW 3.3.5a build 12340 для выбранного сценария: @@ -42,6 +48,8 @@ | M12 | [WoW 3.3.5a completeness](12-client-completeness.md) | M11 | OPEN | | M13 | [Dungeon authoring](13-dungeon-authoring.md) | M12 foundation | OPEN | +M12 выполняется восемью completeness waves, определёнными в [`DEVELOPMENT_ROADMAP.md`](DEVELOPMENT_ROADMAP.md), а не одной массовой реализацией. + M07 и M08 могут выполняться параллельными командами только после M06/M03 соответственно и только если пользователь явно разрешил параллельную работу. Их результаты сходятся в M11. `recast-rs` запланирован как optional navigation backend в M05, исследовательский CLI spike и world validation в M07, затем полноценная dungeon navigation validation в M13. Он не блокирует M00–M04 и не считается автоматически совместимым с server `mmaps`. @@ -59,6 +67,8 @@ Wowser зарегистрирован как независимый MIT referenc - renderer checkpoints при изменении рендера; - отсутствие новых нарушений dependency rules; - обновлённые документы и diagnostics; +- выполнен documentation gate: inline public API, module spec, inputs/outputs и обязательные diagrams; +- проходят `tools/verify_coordination.ps1` и `tools/verify_documentation.ps1`; - воспроизводимость без proprietary данных в Git. ## Evidence format diff --git a/targets/roadmap/01-foundation-and-data.md b/targets/roadmap/01-foundation-and-data.md new file mode 100644 index 0000000..2947e32 --- /dev/null +++ b/targets/roadmap/01-foundation-and-data.md @@ -0,0 +1,86 @@ +# FND — Foundation, Application and Data + +## Цель + +Создать стабильную платформу, на которой renderer, client runtime и Godot Editor могут развиваться независимо, используя одинаковые типы и build artifacts. + +## FND-1. Project profiles и configuration + +- Ввести `BuildProfile` и `CapabilitySet`. +- Отделить user settings, developer settings, server connection profiles и content project settings. +- Secrets хранить вне Git/Resource; поддержать environment/OS credential provider. +- Настройки иметь schema version, defaults, validation, migration и reset-by-section. +- `Blizzlike335` сделать неизменяемым базовым профилем; enhanced settings наследуют его явно. + +## FND-2. Application lifecycle + +- Реализовать state machine `Boot → DataCheck → Login → Realm → Character → Loading → InWorld → Disconnect/Recovery`. +- Editor, sandbox и headless modes запускать разными composition roots. +- Dependency injection выполнять composition layer; не использовать scene lookup как service locator. +- Autoload ограничить действительно process-wide lifecycle services. Gameplay, renderer и editor sessions должны инстанцироваться и освобождаться явно. +- Каждое состояние иметь cancellation, timeout, diagnostics и deterministic cleanup. + +## FND-3. Domain primitives + +- Typed IDs: content, server entry, entity, GUID, map, area, spell, item, quest, display и sound. +- Typed coordinates и orientation; запретить `Vector3` как межслойный wire/domain contract. +- Value objects для locale, money, duration, percentage, level, power type и flags. +- Commands/events/read models не наследуют Node/Resource. +- Serialization version и unknown-field policy определить до сохранения snapshots/replays. + +## FND-4. Asset repository + +- Описать archive chain/locale/patch precedence для 3.3.5a. +- Отделить `original source → parsed canonical data → imported Godot resource → runtime cache`. +- Ввести provenance: source archive/path/hash, parser version, import profile и dependency hashes. +- Не изменять extracted upstream files; custom content подключать ordered overlays. +- Dedup textures/materials/meshes по canonical key, а не по случайной Node lifetime. +- Missing/corrupt asset policy: placeholder только в dev profile, structured error в fidelity runs. + +## FND-5. Binary formats и typed tables + +- MPQ: archive ordering, locale, listfile absence, encrypted/compressed entries. +- BLP: paletted/DXT, alpha depths, mip chains, color space и wrap/filter metadata. +- DBC: schema descriptors, localized strings, relationships, hot reload только в authoring mode. +- WDT/WDL/ADT: tile existence, terrain, holes, layers, placements, liquids, distant data. +- M2/SKIN/WMO: versioned structs, bounds, batches, materials, animation, attachments, portals. +- Audio/interface assets: MP3/WAV, fonts, XML, Lua, TOC и SavedVariables formats. +- Parser API возвращает typed result + diagnostics; partial parse не маскируется как success. +- Differential tests сравнивают текущие parsers с независимыми implementations (`warcraft-rs`, `wow_dbc`, WowDBDefs-driven schemas) на одинаковых fixtures; reference disagreement регистрируется, а не выбирается по большинству. + +## FND-6. Cache and build pipeline + +- Единый content-addressed cache manifest для terrain/M2/WMO/characters/audio/navigation/UI. +- Atomic staging → verify → publish; crash не оставляет валидно выглядящий partial artifact. +- Cache version включает schema, parser, shader/material contract и profile. +- Headless commands используют те же services, что Editor actions. +- Добавить dependency graph и incremental rebuild по hash. +- Папки generated/cache исключить из Git и при необходимости из Godot import через `.gdignore`. + +## FND-7. Native boundary + +- GDExtension использовать для binary parsing, compression/crypto, large buffer transforms и измеренных hot paths. +- GDScript использовать для orchestration, Editor UI и presentation composition. +- Перед добавлением Rust/C/C++ dependency фиксировать ABI boundary и ownership. +- Через native boundary передавать packed arrays/immutable result objects, избегать вызова на каждый vertex/instance. +- Версию Godot/GDExtension API закрепить; обновление проходит compatibility matrix. + +## FND-8. Jobs and concurrency + +- Общий `JobScheduler`: priority, bounded capacity, cancellation, progress, correlation ID. +- Pure CPU work выполняется workers; scene tree и GPU resources финализируются main thread budget. +- Один resource не модифицируется конкурентно; shared mutable collections защищаются. +- Каждый submitted worker task дожидается completion/cleanup. +- Session/world unload отменяет jobs и освобождает RIDs/resources детерминированно. + +## Deliverables + +- Foundation package без renderer/network dependencies. +- Headless data probe и cache inspector. +- Coordinate/parser/cache fixtures. +- Architecture dependency checker. +- Документированные memory/thread ownership rules. + +## Gate + +Одинаковые входы дают одинаковые manifests; application modes собираются разными roots; domain тестируется без SceneTree; cancellation и shutdown не оставляют jobs/RIDs. diff --git a/targets/roadmap/02-rendering-and-graphics.md b/targets/roadmap/02-rendering-and-graphics.md new file mode 100644 index 0000000..0b4f32c --- /dev/null +++ b/targets/roadmap/02-rendering-and-graphics.md @@ -0,0 +1,102 @@ +# RND — Rendering and Graphics + +## Цель + +Воспроизвести визуальные правила WoW 3.3.5a и дать opt-in улучшения, сохранив frame pacing на больших мирах Godot. + +## RND-1. Renderer architecture + +- `WorldRenderFacade` принимает focus, environment snapshot и entity presentation commands. +- `StreamingTargetPlanner` вычисляет desired state без Node creation. +- `RenderBudgetScheduler` ограничивает main-thread finalize по типам операций. +- Terrain, M2, WMO, liquid, sky, character, effects и debug overlays — отдельные services. +- RenderingServer/RIDs применяются только там, где profiler доказал overhead scene tree. +- Ownership каждого RID и cache entry документируется; world unload проверяет leaks. + +## RND-2. World streaming + +- WDT-driven tile catalog, priority по position/direction/velocity/camera frustum. +- Prewarm, retain и hysteresis исключают churn на ADT boundaries. +- Separate budgets для I/O, parse, mesh/material load, main-thread attach и eviction. +- Cold/warm cache scenarios, teleport, rapid flight и camera rotation stress. +- Cancellation stale jobs при teleport/map change. +- Streaming focus не обязан быть Camera3D: player, spectator, editor viewport, capture tool. + +## RND-3. Terrain + +- Точная 145-vertex MCNK topology, holes, normals и coordinate seams. +- Texture layer order, MCAL alpha variants, animation flags, repeat и mip behavior. +- Control-splat/array implementation как Godot optimization с fidelity tests. +- WDL/distant terrain и hierarchical LOD. +- Terrain collision/query representation отдельно от visual mesh. +- Editing path: sculpt, smooth, flatten, holes, texture paint, seam repair и rebake. + +## RND-4. M2 + +- Static geometry, SKIN batches, blend modes, flags, UV transforms и texture lookup. +- Native pivot-based skeletal animation, bone palettes, global sequences и animation lookup. +- Billboards, attachments, key bones, events, cameras и bounding volumes. +- Particles, ribbons, texture animation и material combiners. +- Static doodads группировать spatial MultiMesh cells; animated/interactive entities не смешивать со static batching. +- MultiMesh buffer updates выполнять батчем; cell size выбирать по culling, а не только draw-call minimum. + +## RND-5. WMO + +- Root/group materials, batches, vertex colors, multiple UV sets и doodad sets. +- Portals/rooms, indoor/outdoor, BSP/collision, fog и group visibility. +- MLIQ, skybox, lights и ambient color semantics. +- Lightweight render cache для больших WMO и incremental group attach. +- Editor tools для group/portal/doodad validation. + +## RND-6. Characters and creatures + +- Race/gender/customization from DBC. +- Geosets, skin regions, hair/facial features и composited textures. +- Equipment component models/textures, attachment points, sheath, enchant visuals. +- Animation state resolver: locomotion, combat, casting, emotes, death, swim, mount, vehicle. +- CreatureDisplayInfo/Extra/ModelData, NPC equipment, pets и shapeshift. +- Character preview uses same presenter as world runtime. + +## RND-7. Liquids + +- MH2O/MCLQ layers, existence masks, heights, depth и liquid type. +- Отдельные profiles water/ocean/magma/slime. +- Blizzlike material: texture animation, alpha, lighting и fog behavior. +- Enhanced material: normals, reflections, depth/shore blending — opt-in. +- Liquid collision/swim state принадлежит gameplay/physics query, не shader. + +## RND-8. Environment + +- DBC-driven Light/LightParams/LightIntBand/LightFloatBand interpolation. +- Server time, day/night, zone/subzone transitions. +- Skyboxes, fog, ambient/directional light, weather visual state. +- Blizzlike cheap shadow policy; enhanced selective character/object shadows отдельно. +- Camera far plane, fog и streaming distances согласованы профилем. + +## RND-9. Effects and presentation + +- SpellVisual/SpellVisualKit-driven cast/impact/aura effects. +- Projectiles, decals, dynamic objects, combat text и selection circles. +- Weather particles и world emitters. +- Cinematic/model cameras и loading transitions. +- Effects have pooling, lifetime, visibility и per-frame budgets. + +## RND-10. Graphical extensions + +- Higher-resolution content overlays без модификации originals. +- Anisotropy, extended draw distance, improved water/shadows, post-processing и upscaling. +- Optional PBR approximation only when it does not replace Blizzlike material profile. +- Graphics settings expose measurable cost and fallback. +- Editor comparison viewport: Blizzlike/Enhanced side-by-side, screenshot и metric capture. + +## Verification + +- Paired checkpoints с original 3.3.5a по position/time/weather/camera. +- Material/animation fixtures from independent references. +- Perceptual diff плюс human approval для intentional deviations. +- p50/p95/p99, max hitch, draw calls, visible objects, GPU/CPU memory и RID leak checks. +- D3D12/Vulkan and quality profile matrix. + +## Gate + +Видимый мир не деградирует при декомпозиции; under-foot/near-field quality готова до появления в кадре; long traversal не создаёт recurring hitches/leaks; Enhanced всегда отключаем. diff --git a/targets/roadmap/03-network-and-session.md b/targets/roadmap/03-network-and-session.md new file mode 100644 index 0000000..d255bee --- /dev/null +++ b/targets/roadmap/03-network-and-session.md @@ -0,0 +1,94 @@ +# NET — Network, Protocol and Session + +## Цель + +Реализовать точный клиентский протокол WoW 3.3.5a build 12340, изолировав транспорт и packet layout от gameplay/UI. + +## NET-1. Transport + +- Native TCP auth/world connections, DNS/IPv4/IPv6 policy и configurable endpoints. +- Non-blocking read/write, bounded buffers, packet fragmentation/coalescing. +- Cancellation, connect/read/write timeouts, keepalive и orderly shutdown. +- Network thread работает с bytes; domain events применяются game thread. +- Proxy mode только как explicit development adapter, не основной transport. + +## NET-2. Authentication + +- Logon challenge/proof SRP6 values и exact endian/normalization rules. +- Realm list parsing, build/locale/platform fields и error mapping. +- World auth digest, session key и header encryption state. +- Credentials не логируются; session material очищается при disconnect. +- Golden vectors и сравнение с TrinityCore/AzerothCore/Wowser/Whoa implementations. + +## NET-3. Packet framework + +- `PacketReader/Writer` с checked boundaries и explicit endianness. +- Typed opcode registry generated/validated для build 12340. +- Header framing, ARC4/drop policy, zlib compressed packets. +- Packed GUID, bit masks, CString/fixed strings и localized text. +- Unknown/unsupported opcode telemetry rate-limited; policy зависит от criticality. +- Packet handlers возвращают domain events, не меняют scenes/UI. + +## NET-4. Update fields and entity lifecycle + +- Generated object/item/container/unit/player/gameobject/dynamicobject/corpse field descriptors. +- `SMSG_UPDATE_OBJECT` blocks: values, movement, create, create2, out-of-range, near objects. +- Partial mask application сохраняет неизвестные/необновлённые поля корректно. +- Entity type/entry/display/faction/health/power/flags/ownership relationships. +- Despawn/out-of-range/map transfer не оставляют presentation entities. + +## NET-5. Movement synchronization + +- Полный movement flags set, timestamps, position/orientation, pitch, fall/jump, spline elevation. +- Start/stop/strafe/turn/pitch/jump/fall/land/swim/fly/heartbeat packets. +- Transport GUID/seat/relative coordinates и server spline movement. +- Client prediction history, acknowledgements и reconciliation metrics. +- Teleport/worldport handshake и map transfer. +- Anti-cheat-sensitive fields формируются строго по profile; client не симулирует authoritative NPC path. + +## NET-6. Session domains + +- Character enum/create/delete/rename/login/logout. +- Time/account data/tutorial/action bars/initial spells. +- Chat/channel/social/group/guild. +- Combat/spells/auras/threat. +- Items/inventory/loot/trade/vendor/mail/auction. +- Quests/gossip/POI/taxi. +- Instances/LFG/PvP/vehicles/calendar. +- Каждый domain имеет отдельный handler module, fixtures и unsupported coverage report. + +## NET-7. Reliability and diagnostics + +- State-aware disconnect reason и recovery path. +- Reconnect только когда protocol/server допускает; иначе безопасный возврат к login. +- Packet trace modes: metadata-only default, redacted payload для tests, encrypted secrets never. +- Correlation IDs session/request/entity. +- Replay transport воспроизводит timing или deterministic step mode. +- Network impairment harness: latency, jitter, loss, duplication, fragmentation и abrupt close. + +## NET-8. Core compatibility + +- Baseline protocol один, но server capabilities/quirks задаются adapter profile. +- Не ветвить handlers по строке `if azerothcore` без documented capability. +- Test matrix фиксирует core commit, DB revision, modules и config. +- Custom opcodes располагаются в namespaced extension profile и не включены в Blizzlike335. + +## NET-9. Warden compatibility + +- Зафиксировать фактические требования Warden у supported TrinityCore/AzerothCore profiles. +- Реализовывать только compatibility с тестовыми/private server environments и документированным build 12340 flow; OpenWC не предназначен для official/retail servers. +- Module challenge/response, crypto/state и platform behavior изолировать в optional security adapter. +- Любое исполнение загружаемого module code sandboxed, size/hash checked и отключаемо в development profile. +- Добавить fixtures и failure UX для unsupported/invalid challenge; не использовать subsystem для обхода чужих защитных механизмов. + +## Tools and references + +- TrinityCore/AzerothCore source — authoritative server-side packet expectations. +- Whoa — reverse-engineered client semantics. +- Wowser — независимый auth/world proof-of-concept и test ideas. +- WoWee/WowUnreal — coverage и lifecycle comparison. +- Packet captures используются только легально, минимально и с redaction. + +## Gate + +Headless client проходит auth → realm → character → world; replay создаёт одинаковые domain events; malformed packets не читаются за границы; secrets отсутствуют в logs; обе core configurations проходят contract suite. diff --git a/targets/roadmap/04-gameplay-systems.md b/targets/roadmap/04-gameplay-systems.md new file mode 100644 index 0000000..a01cc78 --- /dev/null +++ b/targets/roadmap/04-gameplay-systems.md @@ -0,0 +1,112 @@ +# GMP — Gameplay Systems + +## Цель + +Создать детерминированную клиентскую проекцию серверного gameplay и полный набор player intents WoW 3.3.5a без переноса authoritative правил на клиент. + +## GMP-1. World model + +- Typed entity registry и object hierarchy. +- Components/read models: identity, transform, unit, player, item, gameobject, corpse, dynamic object. +- Ownership, charm, pet, target, creator, transport и group relationships. +- Reducers применяют domain events; presentation подписывается на changesets. +- Snapshot/replay позволяют восстановить состояние без live socket. + +## GMP-2. Input and movement + +- Remappable action layer, keyboard/mouse и optional gamepad/accessibility mappings. +- Walk/run/backpedal/strafe/turn/jump/fall/swim/fly/autorun. +- Camera-relative или character-relative policy строго по original behavior. +- Ground/collision query abstraction, slopes, water transition и falling. +- Prediction/reconciliation только локального movement; corrections имеют smoothing/snap thresholds. +- Debug flight/speed отделены от production profile. + +## GMP-3. Selection and interaction + +- Mouse/world picking, tab target, target/focus и target-of-target. +- Hostility/faction/dead/visibility/selectability filters. +- Facing, range, line-of-sight и interaction intents. +- NPC flags определяют available services; client не выдумывает доступную функцию. +- Gameobject use, gossip, trainer, vendor, mailbox, auctioneer, binder и flight master. + +## GMP-4. Combat + +- Auto attack/auto shot, swing state и attack stop. +- Damage/heal/miss/absorb/resist/block/crit feedback. +- Threat presentation, combat state, evade и unit flags. +- Resources, regeneration presentation и combo points/runes where applicable. +- Combat log canonical events отделены от floating text/UI formatting. +- Server validates hit, damage и death; client показывает pending/cast state. + +## GMP-5. Spells and auras + +- Spellbook, ranks, passive/active, known/disabled spells. +- Target requirements, range, facing, resource и client-predictable validation messages. +- Cast/channel/interrupt/pushback, GCD и cooldowns. +- Aura add/update/remove, stacks, duration, caster, dispel type и visibility. +- Totems, shapeshift, pets, tracking, tradeskill casts. +- Spell visual/audio descriptors separate from spell mechanics state. + +## GMP-6. Death and recovery + +- Death/release spirit, ghost, corpse, graveyard, reclaim delay. +- Resurrection request/accept, spirit healer penalties. +- Durability loss/repair и instance wipe/reset presentation. +- Failure during map transfer/reconnect does not duplicate corpse/player state. + +## GMP-7. Items and economy + +- Inventory slots, bags, bank, keyring, equipment, ammo и currencies. +- Stack/split/swap/equip/use/destroy with pending/server-confirmed states. +- Loot windows, group rolls, master loot, disenchant и loot release. +- Item fields, random properties, enchants, gems, durability, sets и cooldowns. +- Vendor/buyback/repair, trade, mail, auction и guild bank. +- Money formatting/display separated from authoritative transaction. + +## GMP-8. Quests and progression + +- Quest availability, accept, abandon, track, objectives, complete и reward choice. +- Kill, item, gameobject, explore, spell, escort, timed, reputation objectives. +- Chains, prerequisites, exclusive groups, repeatable/daily/weekly и conditions. +- XP/rested/level, reputation, honor, achievements. +- Skills, talents, glyphs, professions, recipes и trainers. +- Quest state drives view models; authoring graph compiles to server-supported representation. + +## GMP-9. World activities + +- Area/subzone/exploration state и rest areas. +- Taxi discovery/routes/flight, transports, elevators и boats. +- Fishing, gathering, tracking, world events и scripted gameobjects. +- Weather/time events feed render/audio but are owned by world state. +- Minimap/world map POI and quest markers are projections, not quest logic. + +## GMP-10. Social + +- Chat types, channels, whispers, system messages и links. +- Friends, ignore, who, AFK/DND. +- Party/raid invites, leader, roles, loot rules, ready check, raid targets. +- Guild roster, ranks, notes, MOTD, event/calendar. +- Presence/reconnect updates and privacy/error handling. + +## GMP-11. Instances, PvP and vehicles + +- Difficulty, instance binds, lockouts, encounters, reset и transfer aborted. +- LFG queue/proposal/roles/teleport/vote kick/rewards. +- Duel, PvP flags, battleground queue/status/score/resurrection и arena teams. +- Outdoor PvP objectives. +- Vehicle seats, enter/exit/switch, possession action bar и transport-relative movement. + +## GMP-12. Cinematics and scripted presentation + +- Cinematic/movie start/stop, camera control и skippability. +- Server-driven scripted sequences reflected as safe presentation commands. +- Loading screens and map transitions preserve session state. +- Gameplay input contexts prevent actions during restricted states. + +## Testing order + +Для каждой системы: reducer unit tests → packet/domain contract → offline scenario → live core integration → original-client comparison → latency/reconnect scenario. + +## Gate + +Gameplay state воспроизводим replay-ом; UI/render не владеют authoritative values; все intents имеют pending/confirmed/rejected lifecycle; core gameplay loop проходит end-to-end без оригинального клиента. diff --git a/targets/roadmap/05-ui-lua-audio.md b/targets/roadmap/05-ui-lua-audio.md new file mode 100644 index 0000000..2cb9559 --- /dev/null +++ b/targets/roadmap/05-ui-lua-audio.md @@ -0,0 +1,97 @@ +# UIA — UI, Lua, Addons and Audio + +## Цель + +Воспроизвести UI/addon semantics клиента 3.3.5a, сохранив возможность modern UI overlays и полноценную audio presentation. + +## UIA-1. UI architecture + +- Screen flow отделён от in-world HUD. +- UI читает immutable view models и отправляет intents. +- Godot Control tree является presentation backend, а не gameplay model. +- Input contexts: login, character, world, chat, modal, targeting, vehicle, cinematic. +- Scale, safe area, resolution, font и localization учитываются на уровне layout system. + +## UIA-2. Frontend screens + +- Data/license check, login, realm list и connection errors. +- Character selection/create/delete/rename. +- Race/class/customization previews тем же character renderer. +- Loading screens по map/instance, progress и cancellation policy. +- Disconnect/reconnect dialogs и account/server notices. + +## UIA-3. FrameXML + +- TOC parser: metadata, dependencies, optional deps, SavedVariables и load order. +- XML includes, templates, `virtual`, inheritance и named/anonymous objects. +- Frames, Regions, Textures, FontStrings, Layers и Scripts. +- Anchors, dimensions, strata, frame level, draw layers, clipping и scale. +- Widget types: Button, CheckButton, EditBox, Slider, StatusBar, ScrollFrame, MessageFrame, Tooltip, Cooldown, Model и Minimap. +- Handler scripts: OnLoad, OnEvent, OnUpdate, mouse/keyboard/drag/show/hide/value events. + +## UIA-4. Lua runtime + +- Внутренний `LuaRuntime` позволяет сравнить/заменить PUC-Rio 5.1.1 и `rilua`. +- Restricted libraries, byte strings, number semantics, globals, `bit` и error formatting. +- VM lifetime: one UI environment per client session/profile with controlled reset. +- Incremental GC имеет frame budget и metrics. +- Native functions возвращают stable Lua values, а не Godot/Rust/C++ objects напрямую. +- VM backend выбирается ADR после official + WoW-specific corpus. + +## UIA-5. WoW API and event system + +- API inventory строится из 3.3.5a FrameXML/Lua usage и независимых references. +- Реализация группируется: unit, spell, aura, item, quest, group, chat, map, CVar, bindings, frames. +- Event dispatcher имеет deterministic ordering, argument contracts и registration lifecycle. +- `OnUpdate` throttling не меняет original semantics в Blizzlike335. +- API, требующий server state, читает gameplay read model или создаёт intent; raw packets недоступны. +- Missing API выдаёт диагностируемую ошибку/coverage report, а не silent nil where incompatible. + +## UIA-6. Security, taint and addons + +- Secure/insecure execution origins. +- Protected functions/actions, secure templates и combat lockdown. +- Taint propagation through variables/tables/functions в пределах подтверждённой 3.3.5a модели. +- Addon memory/CPU/error isolation и configurable script limits без скрытого изменения default behavior. +- SavedVariables account/character scopes, serialization, corruption recovery и atomic writes. +- Addon compatibility tiers: loads, renders, functional, secure-combat verified. +- Headless addon runner и UI inspector входят в AuthoringStudio/Test Center. + +## UIA-7. Default UI coverage + +- Unit/player/target/focus/party/raid frames. +- Action bars, stance/pet/vehicle bars, cooldowns и keybindings. +- Buffs/debuffs, cast bars, combat text и errors. +- Bags, character, spellbook, talents, glyphs, skills, professions. +- Quest log/tracker/gossip, map/minimap/taxi. +- Chat, social, guild, calendar, LFG, PvP score. +- Vendor, trainer, bank, mail, auction, trade, loot и roll. +- Game menu, settings, macros, addons и help. + +## UIA-8. Audio + +- Typed DBC wrappers for SoundEntries, ZoneMusic, IntroMusic, Ambience and related tables. +- Decoder/streaming/cache for MP3/WAV with category budgets. +- Music day/night/zone transitions and crossfade. +- Ambient loops, random emitters, indoor/outdoor и weather. +- Positional world sounds, footsteps, water, spells, combat, NPC voice и UI feedback. +- Audio events come from presentation descriptors; UI/gameplay do not manipulate players directly. +- Device change, focus/mute policy, category volumes и missing sound diagnostics. + +## UIA-9. Localization and accessibility + +- Locale-aware fonts, fallback, text encoding и layout expansion. +- Keybindings fully remappable; mouse sensitivity/inversion and optional gamepad. +- UI scale, contrast/color-blind profiles, subtitle/text alternatives where possible. +- Critical state does not rely only on color/audio. +- Enhanced accessibility remains compatible with server and can coexist with Blizzlike visuals. + +## References + +- Original 3.3.5a FrameXML/Lua extracted from legally owned data is primary behavior corpus. +- `rilua`/PUC-Rio are VM candidates/oracles, not complete WoW UI. +- WowBench/Wowser/WowUnreal/WoWee provide API/event/loader test ideas. + +## Gate + +Default UI boots deterministically; selected real addons pass declared tiers; secure actions fail correctly during combat; Lua GC/OnUpdate remain within budgets; UI is replaceable without changing gameplay/network. diff --git a/targets/roadmap/06-editor-and-content-tools.md b/targets/roadmap/06-editor-and-content-tools.md new file mode 100644 index 0000000..1244d04 --- /dev/null +++ b/targets/roadmap/06-editor-and-content-tools.md @@ -0,0 +1,109 @@ +# EDT — Godot Editor and Content Authoring + +## Цель + +Превратить Godot Editor в единую среду расширения мира, gameplay, UI, audio и graphics с безопасным build/deploy/playtest workflow. + +## EDT-1. Plugin platform + +- `addons/openwc_editor` регистрирует workspace, docks, inspector/import/gizmo/debugger plugins. +- `_enter_tree/_exit_tree` симметричны: все controls/plugins/signals/jobs снимаются без leaks. +- UI вызывает authoring application services; не пишет SQL/files/scene tree напрямую. +- Editor selection отделена от runtime preview nodes. +- Shared services получают context через dependency injection, не global editor singleton. + +## EDT-2. Workspace and UX + +- World viewport, Content Browser, Outliner, Inspector, Validation, History, Build, Database, Test Center. +- Search/filter/favorites/recent items и stable links между сущностями. +- Multi-selection и bulk edits показывают scope/diff. +- Diagnostics имеют severity/code/location/fix; double-click открывает field/node/world position. +- Layout/workspace preferences сохраняются отдельно от Content Project. + +## EDT-3. Commands, undo and recovery + +- Любая mutation — command с execute/undo/description/affected IDs. +- Terrain strokes агрегируются в bounded deltas; большие операции используют snapshots/chunks. +- Autosave recovery journal атомарный и имеет schema version. +- External changes обнаруживаются через hashes; merge/overwrite требует решения пользователя. +- Quick Fix всегда previewable и undoable. + +## EDT-4. Import and asset browser + +- MPQ/archive browser, locale/patch source provenance и extraction jobs. +- Preview BLP, DBC rows, M2 animations/materials, WMO groups/portals, ADT layers и audio. +- Godot import plugins применяются только к authoring source formats, где lifecycle `.import` полезен. +- Raw extracted corpus не должен вызывать неконтролируемый массовый Godot reimport. +- Batch conversion использует staging, cancellation, cache hash и report. + +## EDT-5. World editing + +- Map/tile/chunk navigation и coordinate overlays. +- Terrain sculpt/smooth/flatten/noise/stamps/holes. +- Texture layers, alpha painting, shading и liquids. +- M2/WMO placement, snapping, transforms, doodad sets и unique ID allocation. +- Creature/gameobject spawns, groups, formations, patrol/escort paths. +- Areas, triggers, graveyards, teleports, taxi/transport points, sound/weather volumes. +- Collision/navmesh/streaming/render-cost visualization. + +## EDT-6. Data editors + +- Creature/gameobject templates, models, equipment, movement and text. +- Item/loot/vendor/trainer/profession editors. +- Quest form + dependency/progression graph + localization. +- Gossip/conditions/SmartAI graph with raw representation inspector. +- Spawn/pool/game event/phase editor. +- Dungeon package, encounter state graph, doors/triggers/lockouts/loot. +- UI/addon manifest, CVar/keybinding и audio zone configuration. + +## EDT-7. Navigation + +- `recast-rs` optional offline backend behind navigation build interface. +- Bake profiles: agent size/climb/slope/cell/region/tile parameters. +- Walkability, disconnected islands, path cost, off-mesh links и dynamic door states. +- Quest giver/objective/turn-in reachability; patrol/escort validation. +- OpenWC cache отделён от server mmap until compatibility proven. + +## EDT-8. Graphics extension tools + +- Material/shader profile editor с Blizzlike/Enhanced comparison. +- Texture replacement/upscale overlays и mip/alpha/color-space validation. +- Water/sky/weather/light preview with fixed time and reference capture. +- Character/equipment/animation/attachment preview. +- Spell visual/particle/ribbon authoring where formats permit. +- Quality preset cost preview и automatic render checkpoint generation. + +## EDT-9. Content Project + +- Git-friendly files, schema version, symbolic IDs, dependencies и capability requirements. +- Original data referenced, never copied silently. +- Overlay priority/conflict report и semantic merges. +- Deterministic numeric ID allocation per server profile. +- Localization bundles, scripts, client assets, tests и package manifests. +- Schema migrations with backup, fixture and loss policy. + +## EDT-10. Build, deploy and playtest + +```text +Validate → Compile → Bake → Diff → Package → Dry-run +→ Apply dev DB/module/assets → Start/reload core → Launch client at context +→ Collect logs/results → Roll back disposable environment +``` + +- Jobs cancellable, progress-aware and identical to headless CI services. +- Production target physically/logically separated and disabled by default. +- Server reload used only for tables known to support it; otherwise restart. +- Playtest bundle records content/core/client revisions and profile. +- One-click convenience never hides SQL/module/client artifact diff. + +## EDT-11. Extensibility + +- `ContentTypeDescriptor`: schema, icon, inspector, validator, compiler, presenter. +- `EditorTool`: selection contract, command factory, gizmo/overlay. +- `BuildStep`: inputs/outputs/cache key/cancellation/diagnostics. +- Plugin declares API version, dependencies, permissions and migrations. +- User plugins cannot mutate production DB or original assets outside approved services. + +## Best-practice gate + +Plugin reload clean; undo/save/reload deterministic; long jobs do not block Editor; preview nodes disposable; every deployment reproducible headless; common scenarios require no manual SQL. diff --git a/targets/roadmap/07-server-emulator-integration.md b/targets/roadmap/07-server-emulator-integration.md new file mode 100644 index 0000000..8550034 --- /dev/null +++ b/targets/roadmap/07-server-emulator-integration.md @@ -0,0 +1,84 @@ +# SRV — TrinityCore and AzerothCore Integration + +## Цель + +Поддержать server emulators как versioned backends: protocol-compatible runtime, безопасное редактирование данных и расширение mechanics через modules/scripts. + +## SRV-1. Environment model + +- `ServerEnvironment`: family, core commit, DB revision, modules, config profile, endpoints и data artifact versions. +- Отдельные disposable, local-dev, shared-test, staging и production classes. +- Credentials/secrets вне Content Project. +- Capability discovery проверяет schema fingerprint и optional modules/tables/hooks. +- Unknown environment всегда read-only. + +## SRV-2. Database snapshots + +- Read-only import world schema subsets с provenance/checksum. +- Auth/characters DB открываются только для нужных test/admin сценариев и никогда не становятся content source. +- Snapshot filters reproducible; personal/account data excluded. +- Canonical entities preserve supported fields and explicitly record unsupported/raw extras. +- Incremental snapshot возможен, но full consistency snapshot остаётся verification path. + +## SRV-3. Canonical mappings + +- Creature/gameobject templates, models, spawns, addons, formations, movement, texts. +- Quests, relations, objectives, POI, conditions, gossip. +- Loot/reference loot, vendors, trainers, items, reputation. +- SmartAI, script names, waypoint/script tables. +- Instances, encounters, LFG, graveyards, teleports, game events, weather, transports. +- Каждая mapping имеет per-core capability table и round-trip tests. + +## SRV-4. Change sets and SQL + +- Immutable change set: target fingerprint, preconditions, ordered operations, checksum. +- SQL generation соответствует conventions целевого core/profile. +- Custom SQL хранится в version control и compatible custom/module directory, не только применяется напрямую. +- Dry-run на disposable DB, targeted post-apply queries, core startup smoke. +- Idempotent migration или безопасное precondition failure. +- Rollback где возможен; destructive/irreversible operations требуют backup и явного подтверждения. + +## SRV-5. Scripts and modules + +- DB/SmartAI для выразимых data-driven mechanics. +- C++ module/script skeleton для mechanics, требующих server hooks. +- AzerothCore modules namespaced config/SQL/hooks; core patch — только если hook принципиально отсутствует. +- TrinityCore adapter следует его текущим script/customization conventions отдельно. +- Build artifact включает source, config.dist, SQL, tests и compatibility manifest. +- Client extension capability договаривается явно; hidden custom opcode запрещён. + +## SRV-6. Server data artifacts + +- DBC/maps/vmaps/mmaps versions связываются с ContentBundleManifest. +- Custom map требует согласованного client terrain, server maps/collision/pathfinding и DB Map/Area data. +- OpenWC navmesh не объявляется mmap до binary/query/live behavior compatibility. +- Asset/map IDs распределяются стабильно и проверяются на collision. +- Client/server package mismatch блокирует playtest с actionable diagnostic. + +## SRV-7. Protocol compatibility + +- Baseline 3.3.5a build 12340 остаётся общим. +- Core-specific quirks описываются named capabilities и fixtures. +- Custom extensions используют versioned handshake/profile и fallback/rejection. +- Server authority одинаково соблюдается для обеих families. +- Compatibility matrix закрепляет tested commits, а не расплывчатое «поддерживает AzerothCore». + +## SRV-8. Test environments + +- Docker/managed local environment для repeatable DB/core setup, где поддерживается. +- Seed accounts/characters synthetic и не содержат реальные credentials. +- Reset DB через assembler/base + project migrations. +- Logs world/auth/database/client собираются с correlation metadata. +- DB-only change test, module build test, startup smoke, scripted client scenario и cleanup. + +## SRV-9. Existing tools + +- Keira3 — reference для field semantics, SQL generation и AzerothCore DB UX. +- AzerothCore wiki/schema/module template — primary backend documentation. +- TrinityCore source/schema/tools — primary для Trinity profile. +- Noggit/WoW modding tools — client-world authoring reference, но не server schema oracle. +- OpenWC Editor объединяет workflow, но сохраняет raw SQL preview и ссылки на upstream docs. + +## Gate + +Одна canonical сущность проходит import → edit → diff → dry-run → apply → reimport на каждом supported profile без silent loss; module/content packages воспроизводимы; production write disabled by default; test environment очищается. diff --git a/targets/roadmap/08-quality-and-release.md b/targets/roadmap/08-quality-and-release.md new file mode 100644 index 0000000..90295fd --- /dev/null +++ b/targets/roadmap/08-quality-and-release.md @@ -0,0 +1,113 @@ +# QAR — Fidelity, Quality, CI and Release + +## Цель + +Сделать точность, производительность и расширяемость проверяемыми свойствами, а не обещаниями. + +## QAR-1. Fidelity lab + +- Каталог сценариев original client 3.3.5a: setup, input, server state, expected output. +- Paired screenshots/video/log/packet/state evidence с provenance. +- Поведение классифицируется: `Unknown`, `Observed`, `Matched`, `Intentional deviation`, `Blocked`. +- Independent references могут подсказать hypothesis, но не повышают статус без evidence. +- Blizzlike bugs/exploits обрабатываются policy decision: protocol compatibility отдельно от harmful behavior. + +## QAR-2. Test layers + +- Native unit tests: parsers, crypto, compression, coordinates, math, caches. +- GDScript/domain unit tests: reducers, validators, commands, view models. +- Contract tests: packets, DB adapters, Lua API, content schemas, renderer facade. +- Scene tests: lifecycle, input, UI, renderer attachment, EditorPlugin reload. +- Integration: disposable core/DB, import/build/deploy, login/world/gameplay. +- E2E: leveling loop, dungeon, PvP/service flows и authoring vertical slices. +- Visual/performance and exploratory design tests complement automation. + +## QAR-3. Godot testing stack + +- Оценить GdUnit4 как candidate для Godot 4.6 GDScript/scene/CI tests. +- Native GDExtension tests используют подходящий C++ test runner отдельно от engine-internal doctest unless Godot itself is rebuilt. +- Headless commands возвращают non-zero и machine-readable JUnit/JSON reports. +- Scene tests не зависят от proprietary assets: synthetic fixtures or locally resolved optional corpus. +- Flaky retries не превращают failure в success; instability измеряется и исправляется. + +## QAR-4. Golden and property testing + +- Golden binary structures and exact-byte packet vectors. +- Parser round-trip where format permits; malformed/truncated/fuzz corpus. +- Coordinate transform property tests and known world points. +- Deterministic content manifests, SQL diff and migration before/after fixtures. +- Lua oracle corpus, navmesh reference counts/queries, material descriptor mappings. + +## QAR-5. Performance budgets + +- Startup/data check/login/world entry. +- Streaming cold/warm traversal and teleport. +- CPU/GPU frame p50/p95/p99/max hitch, draw calls, memory и descriptors. +- Network decode/apply queues and reconciliation error. +- UI `OnUpdate`, event fan-out, Lua allocations/GC. +- Editor import/bake/validation latency and cancellation responsiveness. +- Server deployment/playtest turnaround. +- Budgets hardware/profile-specific and trend tracked. + +## QAR-6. Observability + +- Structured logging categories and stable diagnostic codes. +- Correlation IDs session/job/entity/content change set. +- Runtime metrics: queues, entities, cache hit, resource counts, RIDs, packet rate. +- Editor metrics: jobs, diagnostics, artifact hashes, DB operations. +- Debug overlays and Godot profiler/visual profiler capture workflow. +- Payload, credentials, chat/personal content redacted by default. + +## QAR-7. CI pipeline + +Pull request gates: + +1. formatting/static analysis/document links/target marker validation; +2. native build and unit tests; +3. headless Godot load and GDScript tests; +4. affected parser/protocol/content/adapter contracts; +5. deterministic artifact check; +6. renderer smoke if visual code changed; +7. license/dependency audit. + +Nightly/weekly: + +- disposable TrinityCore/AzerothCore integration; +- full packet/Lua/parser replay corpus; +- visual checkpoints on available GPU runners; +- long traversal, reconnect, cache migration and soak; +- previous schema/Godot/core compatibility matrix. + +## QAR-8. Security and robustness + +- Bounds checked binary parsing and fuzzing. +- Lua sandbox/taint/protected actions. +- DB least privilege, read-only default, production protection. +- Untrusted addon/content/plugin permission model. +- Dependency license/advisory/source pin audit. +- Atomic files, backup, recovery and rollback. +- No proprietary assets, secrets or production dumps in repository/artifacts. + +## QAR-9. Documentation and decisions + +- Architecture/API/schema changes update docs and ADR в том же work package. +- Каждый самостоятельный module имеет specification по `docs/DOCUMENTATION_STANDARD.md`: purpose, boundaries, public API, inputs/outputs, data flow, ownership, errors, tests и source map. +- Data-flow diagram обязательна всегда; state/sequence/dependency diagrams обязательны по сложности/lifecycle rules стандарта. +- Inline docs являются источником точной сигнатуры, module spec — источником концепции и фактического статуса. +- Tooling candidates tracked in `docs/TOOLING_CATALOG.md` with status and pinned version. +- Feature coverage links implementation, tests, fidelity evidence and known gaps. +- Generated API docs for documented GDScript/GDExtension public surface включаются в quality gate, когда pipeline подготовлен. +- Contributor workflow describes smallest reproducible diagnostic commands. + +## QAR-10. Packaging and release + +- Client ships without Blizzard data and guides user to select legally owned install. +- Import/cache first-run is resumable and reports disk/time requirements. +- Platform packages include matching GDExtension libraries and dependency notices. +- Content package and server module releases version independently with compatibility manifest. +- Save/settings/content schema migrations tested from supported previous versions. +- Release channels: developer, preview, stable; fidelity gaps visible in notes. + +## Exit gate + +Release candidate passes required core/platform/profile matrix; no critical unowned diagnostic; performance regression within approved bounds; artifacts reproducible and license-clean; known fidelity deviations documented. diff --git a/tools/verify_coordination.ps1 b/tools/verify_coordination.ps1 new file mode 100644 index 0000000..bc64cfa --- /dev/null +++ b/tools/verify_coordination.ps1 @@ -0,0 +1,92 @@ +param( + [string]$Root = (Split-Path -Parent $PSScriptRoot) +) + +$ErrorActionPreference = 'Stop' +$failures = [System.Collections.Generic.List[string]]::new() +$warnings = [System.Collections.Generic.List[string]]::new() + +$targetsDir = Join-Path $Root 'targets' +$targetIndex = Join-Path $targetsDir 'README.md' +$targetFiles = Get-ChildItem -LiteralPath $targetsDir -File | + Where-Object { $_.Name -match '^\d\d-.*\.md$' } | + Sort-Object Name + +$activeTargets = [System.Collections.Generic.List[object]]::new() +$statusPattern = '<!-- OPENWC_TARGET:(OPEN|ACTIVE|BLOCKED|DONE) -->' + +foreach ($file in $targetFiles) { + $content = Get-Content -Raw -Encoding UTF8 -LiteralPath $file.FullName + $matches = [regex]::Matches($content, $statusPattern) + if ($matches.Count -ne 1) { + $failures.Add("$($file.Name): expected exactly one target status marker, found $($matches.Count)") + continue + } + if ($matches[0].Groups[1].Value -eq 'ACTIVE') { + $activeTargets.Add($file) + } +} + +if ($activeTargets.Count -ne 1) { + $failures.Add("Expected exactly one ACTIVE target, found $($activeTargets.Count)") +} + +if (-not (Test-Path -LiteralPath $targetIndex)) { + $failures.Add('targets/README.md is missing') +} else { + $indexContent = Get-Content -Raw -Encoding UTF8 -LiteralPath $targetIndex + $currentMatch = [regex]::Match($indexContent, '(?s)## Current target\s+`(M\d\d)`[^\r\n]*\[[^\]]+\]\(([^)]+)\)') + if (-not $currentMatch.Success) { + $failures.Add('Could not parse Current target from targets/README.md') + } elseif ($activeTargets.Count -eq 1) { + $expectedId = $currentMatch.Groups[1].Value + $expectedFile = $currentMatch.Groups[2].Value + $activeFile = $activeTargets[0].Name + $activeId = 'M' + $activeFile.Substring(0, 2) + if ($expectedId -ne $activeId -or $expectedFile -ne $activeFile) { + $failures.Add("Current target points to $expectedId/$expectedFile but ACTIVE is $activeId/$activeFile") + } + } +} + +$claimsDir = Join-Path $Root 'coordination\claims' +$claimIds = @{} +$claimPattern = '<!-- OPENWC_CLAIM:([A-Z0-9-]+):([a-z0-9-]+):(\d{4}-\d{2}-\d{2}) -->' + +if (Test-Path -LiteralPath $claimsDir) { + $claimFiles = Get-ChildItem -LiteralPath $claimsDir -Filter '*.md' -File | + Where-Object { $_.Name -ne 'README.md' } + foreach ($file in $claimFiles) { + $content = Get-Content -Raw -Encoding UTF8 -LiteralPath $file.FullName + $matches = [regex]::Matches($content, $claimPattern) + if ($matches.Count -ne 1) { + $failures.Add("coordination/claims/$($file.Name): expected exactly one valid OPENWC_CLAIM marker") + continue + } + $claimId = $matches[0].Groups[1].Value + if ($claimIds.ContainsKey($claimId)) { + $failures.Add("Duplicate claim ID $claimId in $($claimIds[$claimId]) and $($file.Name)") + } else { + $claimIds[$claimId] = $file.Name + } + $expiryText = $matches[0].Groups[3].Value + $expiry = [datetime]::ParseExact($expiryText, 'yyyy-MM-dd', [Globalization.CultureInfo]::InvariantCulture) + if ($expiry.Date -lt (Get-Date).ToUniversalTime().Date) { + $warnings.Add("Claim $claimId expired on $expiryText") + } + } +} + +foreach ($warning in $warnings) { + Write-Warning $warning +} + +if ($failures.Count -gt 0) { + foreach ($failure in $failures) { + Write-Error $failure + } + exit 1 +} + +Write-Output "Coordination check passed: targets=$($targetFiles.Count) active=$($activeTargets.Count) fallback_claims=$($claimIds.Count) warnings=$($warnings.Count)" +exit 0 diff --git a/tools/verify_documentation.ps1 b/tools/verify_documentation.ps1 new file mode 100644 index 0000000..41ac787 --- /dev/null +++ b/tools/verify_documentation.ps1 @@ -0,0 +1,101 @@ +param( + [string]$Root = (Split-Path -Parent $PSScriptRoot) +) + +$ErrorActionPreference = 'Stop' +$failures = [System.Collections.Generic.List[string]]::new() + +$requiredFiles = @( + 'AGENTS.md', + 'docs\README.md', + 'docs\DOCUMENTATION_STANDARD.md', + 'docs\modules\README.md', + 'docs\modules\TEMPLATE.md', + 'targets\DEVELOPMENT_ROADMAP.md' +) + +foreach ($relative in $requiredFiles) { + if (-not (Test-Path -LiteralPath (Join-Path $Root $relative))) { + $failures.Add("Missing required documentation file: $relative") + } +} + +$agentGuide = Join-Path $Root 'AGENTS.md' +if (Test-Path -LiteralPath $agentGuide) { + $agentContent = Get-Content -Raw -Encoding UTF8 -LiteralPath $agentGuide + if ($agentContent -notmatch 'DOCUMENTATION_STANDARD\.md') { + $failures.Add('AGENTS.md does not reference docs/DOCUMENTATION_STANDARD.md') + } +} + +$requiredHeadings = @( + '## Metadata', + '## Purpose', + '## Non-goals', + '## Context and boundaries', + '## Public API', + '## Inputs and outputs', + '## Data flow', + '## Ownership, threading and resources', + '## Errors, cancellation and recovery', + '## Verification', + '## Known gaps and risks', + '## Source map' +) + +$modulesDir = Join-Path $Root 'docs\modules' +$moduleCount = 0 +if (Test-Path -LiteralPath $modulesDir) { + $moduleFiles = Get-ChildItem -LiteralPath $modulesDir -Filter '*.md' -File | + Where-Object { $_.Name -notin @('README.md', 'TEMPLATE.md') } + foreach ($file in $moduleFiles) { + ++$moduleCount + $content = Get-Content -Raw -Encoding UTF8 -LiteralPath $file.FullName + foreach ($heading in $requiredHeadings) { + if (-not $content.Contains($heading)) { + $failures.Add("docs/modules/$($file.Name): missing heading '$heading'") + } + } + if ($content -notmatch '(?s)```mermaid\s+flowchart') { + $failures.Add("docs/modules/$($file.Name): missing Mermaid data-flow diagram") + } + if ($content -notmatch '\| Status \|') { + $failures.Add("docs/modules/$($file.Name): missing Status metadata") + } + if ($content -notmatch '\| Last verified \|') { + $failures.Add("docs/modules/$($file.Name): missing Last verified metadata") + } + } +} + +$documentationRoots = @('docs', 'targets', 'coordination') +foreach ($relativeRoot in $documentationRoots) { + $path = Join-Path $Root $relativeRoot + if (-not (Test-Path -LiteralPath $path)) { + continue + } + foreach ($file in Get-ChildItem -LiteralPath $path -Recurse -Filter '*.md' -File) { + $content = Get-Content -Raw -Encoding UTF8 -LiteralPath $file.FullName + foreach ($match in [regex]::Matches($content, '\[[^\]]+\]\(([^)#]+)(?:#[^)]+)?\)')) { + $target = $match.Groups[1].Value + if ($target -match '^(https?:|mailto:)') { + continue + } + $resolved = Join-Path $file.DirectoryName $target + if (-not (Test-Path -LiteralPath $resolved)) { + $relativeFile = Resolve-Path -LiteralPath $file.FullName -Relative + $failures.Add("$relativeFile`: broken relative link '$target'") + } + } + } +} + +if ($failures.Count -gt 0) { + foreach ($failure in $failures) { + Write-Error $failure + } + exit 1 +} + +Write-Output "Documentation check passed: module_specs=$moduleCount required_files=$($requiredFiles.Count)" +exit 0