From 74c8504d52deafec7d2de299c5e0855ceb37aa44 Mon Sep 17 00:00:00 2001 From: Sergey Lukashenko Date: Tue, 17 Nov 2026 16:24:02 +0300 Subject: [PATCH] feat: implement game-like LU trainer and companion map --- AGENTS.md | 3 +- LU_TRAINER_PROJECT.md | 10 +- MEMORY.md | 4 +- README.md | 22 +- app/main.py | 3 + docs/staging/plans/2026-11-17-lu-trainer.md | 18 ++ docs/staging/specs/2026-11-17-lu-trainer.md | 14 ++ nginx.conf | 10 + project_mind_map.md | 11 +- structure_and_data.md | 12 +- tests/browser/lu-trainer.cjs | 206 ++++++++++++++++ tests/lu-trainer/engine.test.mjs | 121 ++++++++++ tests/test_lu_trainer.py | 49 ++++ web/index.html | 1 + web/lu-trainer.html | 111 +++++++++ web/lu-trainer/assets/README.md | 16 ++ web/lu-trainer/assets/cat.png | Bin 0 -> 41539 bytes web/lu-trainer/assets/forest.webp | Bin 0 -> 363080 bytes web/lu-trainer/engine.js | 134 +++++++++++ web/lu-trainer/style.css | 182 +++++++++++++++ web/lu-trainer/ui.js | 247 ++++++++++++++++++++ 21 files changed, 1160 insertions(+), 14 deletions(-) create mode 100644 docs/staging/plans/2026-11-17-lu-trainer.md create mode 100644 docs/staging/specs/2026-11-17-lu-trainer.md create mode 100644 tests/browser/lu-trainer.cjs create mode 100644 tests/lu-trainer/engine.test.mjs create mode 100644 tests/test_lu_trainer.py create mode 100644 web/lu-trainer.html create mode 100644 web/lu-trainer/assets/README.md create mode 100644 web/lu-trainer/assets/cat.png create mode 100644 web/lu-trainer/assets/forest.webp create mode 100644 web/lu-trainer/engine.js create mode 100644 web/lu-trainer/style.css create mode 100644 web/lu-trainer/ui.js diff --git a/AGENTS.md b/AGENTS.md index 071198b..d7728e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,8 @@ - Public report lookup is `GET /api/reports?character_id=`; it searches saved report participant IDs, returns at most 100 newest rows without `actor_id`, and is covered by `tests/test_report_lookup.py`. VK `/мои-отчёты` uses the callback sender ID and the same history store; validate with `python -m unittest tests.test_report_lookup tests.test_history tests.test_vk_bot -q`. ## Notes -- LU trainer planning lives in root `LU_TRAINER_PROJECT.md`; the owner requested a game-like interface and a «Минное поле» companion map. The module is not implemented. Keep proposed paths separate from existing routes, distinguish upstream training formulas from verified CatWar rules, and validate both visual render and map/location synchronization when implementation begins. +- LU trainer is implemented at `/lu-trainer` and `/lu-trainer/` through both Python and Nginx. `web/lu-trainer/engine.js` is DOM-free; UI consumes public snapshots without hidden hazards/values. Keep notes separate from facts, map selection separate from jumping, eight-neighbor availability relative to any opened cell, and transition cells outside victory counts. Preserve documented training formulas; do not claim they are verified CatWar rules. Original art provenance is in `web/lu-trainer/assets/README.md`. +- LU checks (prefer remote test-zone MCP when exposed): Node 24 `node --test tests/lu-trainer/engine.test.mjs`; isolated Python `python -m unittest tests.test_lu_trainer tests.test_calculator_web -q`; `node --check web/lu-trainer/ui.js`; `node tests/browser/lu-trainer.cjs` with the same bundled Playwright, loopback server and temporary stores as the calculator suite. No npm install or runtime dependency is needed. Browser coverage includes 1920/1366/768/390 widths, mouse/touch/keyboard, map projection, clear/restart confirmation, result locks, hints/timers, 200% layout and failed images. Inspect screenshots outside Git. Nginx aliases must serve the same HTML and correct asset MIME types; do not deploy to validate a client-only change. - `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint (3-second timeout, 64 KiB bound, 5-minute process cache, 1-minute failure cache). `/api/weather/ulli` exposes only decoration settings; shared CSS/JS live at `/api/weather/effect.css` and `/api/weather/effect.js` so the existing gateway `/api/` route handles them. Keep weather independent of reports/storage, skip trend/remark/vicinity groups, reject observations older than 2 hours, and retain leaves on failure. Do not disable TLS verification. - VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule. - VK Callback API and dialog durability live across `app/belki/vk_bot.py`, `app/belki/vk_callback.py`, and `app/belki/vk_scheduler.py`. The bot listens on callback port 8081; preserve `vk_dialog_states` and `vk_callback_events` when changing dialog steps, attachments, or event dispatch. Validate with `python -m unittest tests.test_vk_bot tests.test_vk_conversation -q`. Production uses `/api/vk/callback` on the existing public host and routes that exact path to the `belki-bot` Service. diff --git a/LU_TRAINER_PROJECT.md b/LU_TRAINER_PROJECT.md index 5091e5b..531e008 100644 --- a/LU_TRAINER_PROJECT.md +++ b/LU_TRAINER_PROJECT.md @@ -1,6 +1,8 @@ # Тренажёр ЛУ: проект интерфейса -Дата: 2026-11-17. Статус: проектная документация; реализация не начата. +Дата: 2026-11-17. Статус: первая версия реализована по последующему запросу владельца «Реализуй LU_TRAINER_PROJECT.md». Публикация и развёртывание не выполнялись. + +Текущая реализация: `/lu-trainer` и `/lu-trainer/`, файлы из таблицы ниже, оригинальные изображения с происхождением в `web/lu-trainer/assets/README.md`. Поддерживаются параметры, прыжки, подсказки, победа/падение, синхронная карта заметок, история и адаптивное управление. Проверки и их границы записаны в `structure_and_data.md`. Подробный текст ниже сохраняет основания первоначального проекта; историческое ограничение «только документация» относилось к предыдущему этапу. ## Цель и подтверждённый объём @@ -122,7 +124,7 @@ ## Предлагаемое устройство реализации -Начать с самостоятельной клиентской страницы в текущем репозитории, без новых runtime-зависимостей и БД. Предварительный публичный путь — `/lu-trainer`; он пока не реализован. Файлы ниже также предлагаемые, не существующий контракт: +В текущем репозитории реализована самостоятельная клиентская страница без новых runtime-зависимостей и БД. Реализованные публичные пути — `/lu-trainer` и `/lu-trainer/`. Файлы первой версии: | Файл/область | Назначение | | --- | --- | @@ -147,7 +149,7 @@ flowchart LR UI --> Map ``` -При реализации проверить раздачу страницы и ассетов одновременно через Python и gateway. Изменение `nginx.conf` подпадает под существующие правила пересборки gateway base image; в рамках документации образы и манифесты не меняются. +Раздача страницы и ассетов проверена через Python и изолированный Nginx gateway. Изменение `nginx.conf` подпадает под существующие правила пересборки gateway base image; registry-образы и манифесты в рамках реализации не менялись; Dockerfile.gateway уже копирует конфигурацию в release image. ## Этапы и критерии приёмки @@ -164,7 +166,7 @@ flowchart LR ## Открытые вопросы перед соответствующими этапами -- Получить или выбрать разрешённые фон, спрайт персонажа и иконки; скриншот использовать как ориентир компоновки, а не как готовую подложку со встроенными текстами. +- Решено для первой версии: оригинальные фон и спрайт созданы через imagegen, происхождение и промпты записаны рядом с ассетами; скриншот использовать как ориентир компоновки, а не как готовую подложку со встроенными текстами. - Сверить игровые формулировки звуков, правила соседства, переходов, вероятности подсказок и формулы сложности. Пока использовать явно обозначенную модель исходника. - Уточнить необходимость нескольких сохраняемых карт, ручного ввода чисел и вкладок «уступы». Само окно «Минное поле» уже входит в подтверждённый объём. - Уточнить масштаб необязательных декоративных блоков после первого макета. Их наличие не должно превращать задачу в симулятор всего CatWar. diff --git a/MEMORY.md b/MEMORY.md index fd78091..5a42a0d 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -1,8 +1,10 @@ # MEMORY +- 2026-11-17: implemented the owner-requested LU trainer at `/lu-trainer` and `/lu-trainer/`. The DOM-free original JS engine preserves the documented upstream training model (not verified CatWar rules); both grids consume snapshots without hidden hazards, with temporary hints disclosed only as action results. One in-memory attempt, separate notes, confirmed resets, terminal action locks and no CatWar account/report integration. Original imagegen forest/cat provenance is in `web/lu-trainer/assets/README.md`. No new runtime dependency. Local Node/Python/Chromium and isolated Nginx checks are recorded in `structure_and_data.md`; no registry push or deployment. + - 2026-11-17: the owner-provided community chat link is maintained in `web/index.html` beside VK: `https://matrix.to/#/!hQAD8j0wKv51OhvyeAPqRBNyBzvzoZsqBIWYR_OgNxw?via=nyan404.ru`. Preserve both the room ID and `via` parameter when editing it. -- 2026-11-17: the owner requested documentation for a LU trainer inspired by `tek1laa/catwar-lu-trainer`, with the interface closer to the supplied real-game screenshot, and explicitly included the «Минное поле» map. See `LU_TRAINER_PROJECT.md`. This is planned work, not an implemented/deployed module. Upstream rules were read at `52f7f6111576f57fa5fe3edf43a38ffe2299f799` but were not validated against CatWar; one active map and the proposed route remain design choices, not additional owner-confirmed requirements. +- 2026-11-17: the owner requested documentation for a LU trainer inspired by `tek1laa/catwar-lu-trainer`, with the interface closer to the supplied real-game screenshot, and explicitly included the «Минное поле» map. See `LU_TRAINER_PROJECT.md`. That documentation stage is superseded by the implementation entry above; deployment remains unverified. Upstream rules were read at `52f7f6111576f57fa5fe3edf43a38ffe2299f799` but were not validated against CatWar; the implementation retains the documented one-map/default-route choices within the owner's subsequent request to implement the plan. - 2026-11-17: the external report integration polls `/api/admin/calculations/pending` and acknowledges through the admin `entered` flag; it shares the admin credential and privileges. A poll starts from the beginning each time to rediscover unmarked or concurrently committed records; clients deduplicate by report ID. The local change is not evidence of deployment. diff --git a/README.md b/README.md index 4b7786f..e6a22a7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Генератор отчётов и калькулятор -Проектируемый тренажёр ЛУ с интерфейсом по игровому референсу и картой «Минное поле» описан в [LU_TRAINER_PROJECT.md](./LU_TRAINER_PROJECT.md). Это документация будущего модуля; страница пока не реализована. +Тренажёр ЛУ «Лесные уступы» доступен по `/lu-trainer` и `/lu-trainer/`: игровая локация, персонаж, журнал и карта «Минное поле». Подробности модели и границы проверки — в [LU_TRAINER_PROJECT.md](./LU_TRAINER_PROJECT.md). Отдельный калькулятор для отчётов по прокачке ЛУ/ЗУ, тренировкам и осмотрам. Старые CatWar userscript-файлы остаются в `web/` и продолжают раздаваться по своим URL. @@ -41,6 +41,25 @@ python3 -m app.belki.vk_bot Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер сохраняет их в приватном S3-совместимом MinIO и возвращает ссылку на собственный маршрут `/api/images/`. Поэтому MinIO не открывается в интернет, а пользователи получают изображение через контейнер Belki. Настройки `BELKI_S3_*` и отдельный Secret `belki-image-store` задаются вне репозитория. Google Sheets пока не подключён. +## Тренажёр ЛУ + +Самостоятельная клиентская тренировка без регистрации, БД и новых runtime-зависимостей. Она не подключается к CatWar и не начисляет ЛУ. Поле, история и заметки существуют до перезагрузки страницы. + +На компьютере клик по локации выполняет выбранный «Прыжок» или «Опасная»; правая кнопка ставит/снимает заметку. На телефоне касание сначала выбирает клетку, затем действие подтверждается отдельной крупной кнопкой. На обеих сетках доступны стрелки, Home / End, Enter и пробел. «Минное поле» выбирает клетку для заметки и автоматически показывает результаты прыжков. «Перенос на игровое поле» меняет только видимость заметок на локации. Очистка заметок и новая игра имеют разные подтверждения. + +Победа — все безопасные клетки, кроме переходов, либо все опасности без лишних отметок. Падение завершает попытку. Настройки высоты, ЛУ, сезона и роста применяются явным началом новой игры. Это модель описанного исходного тренажёра, а не подтверждённые правила CatWar. Оригинальные изображения и промпты перечислены в `web/lu-trainer/assets/README.md`; код и изображения исходного тренажёра не переносились. + +Страница раздаётся и `app.main`, и Nginx gateway. Для изолированных проверок используйте временные SQLite-пути по инструкции в `AGENTS.md`, затем: + +```bash +node --test tests/lu-trainer/engine.test.mjs +python -m unittest tests.test_lu_trainer tests.test_calculator_web -q +# На отдельно запущенном loopback-сервере :8876, с доступным Playwright: +node tests/browser/lu-trainer.cjs +``` + +Браузерный сценарий принимает те же `NODE_PATH`, `CHROMIUM_PATH`, `BELKI_TEST_URL` и `BELKI_SCREENSHOT_DIR`, что и существующий сценарий калькулятора. Для проверок используйте Node 24: он распознаёт ES-модуль `engine.js` без package.json. В production нет Node-зависимости: код исполняется в браузере. Nginx-проверка выполняется отдельно от браузерного сценария; Docker release image уже копирует `nginx.conf` поверх base layer. Перед публикацией соблюдать существующий процесс обновления gateway base; в этой реализации образы в registry не отправлялись. + ## Судоку `/sudoku` — отдельная публичная игра. Ник служит ключом к партии: с тем же ником незавершённое поле откроется на другом устройстве. Это не учётная запись и не пароль, поэтому в нике нельзя указывать личные данные. Сервер хранит исходные цифры, ход, время и факт завершения; новое поле не удаляет предыдущую партию. @@ -88,6 +107,7 @@ python3 -m app.belki.vk_bot - `web/applications.html` — форма подачи заявок; - `web/admin.html` — парольная история расчётов для администраторской проверки; - `web/sudoku.html` — адаптивная игра и восстановление партий по нику; +- `web/lu-trainer.html`, `web/lu-trainer/` — тренажёр ЛУ: независимая модель, интерфейс и оригинальные изображения; - `tests/` — unit-тесты. Спецификация и план находятся в `docs/staging/`. diff --git a/app/main.py b/app/main.py index 6c0c049..9023d5f 100644 --- a/app/main.py +++ b/app/main.py @@ -417,6 +417,9 @@ class Handler(BaseHTTPRequestHandler): if path in ("/sudoku", "/sudoku/"): self._file(WEB_ROOT / "sudoku.html") return + if path in ("/lu-trainer", "/lu-trainer/"): + self._file(WEB_ROOT / "lu-trainer.html") + return if path == "/api/reports": query = parse_qs(urlparse(self.path).query, keep_blank_values=True) raw_character_id = query.get("character_id", [""])[0].strip() diff --git a/docs/staging/plans/2026-11-17-lu-trainer.md b/docs/staging/plans/2026-11-17-lu-trainer.md new file mode 100644 index 0000000..c540ada --- /dev/null +++ b/docs/staging/plans/2026-11-17-lu-trainer.md @@ -0,0 +1,18 @@ +# LU trainer implementation plan + +Spec: ../specs/2026-11-17-lu-trainer.md and root LU_TRAINER_PROJECT.md (owner requested implementation). + +- [x] T1: Pure training engine and deterministic acceptance + goal: preserve documented training rules and hide unknown facts in public snapshots. + files: web/lu-trainer/engine.js, tests/lu-trainer/engine.test.mjs + acceptance: node --test tests/lu-trainer/engine.test.mjs +- [x] T2: Game screen, original art and synchronized companion map + goal: implement three-column forest training with accessible compact controls and dialogs. + files: web/lu-trainer.html, web/lu-trainer/style.css, web/lu-trainer/ui.js, web/lu-trainer/assets + acceptance: browser interaction suite and inspected renders at all four specified sizes, zoom, reduced motion, broken images. +- [x] T3: Routing, documentation and final review + goal: make page available through Python and gateway, document scope and checks, commit without push. + files: app/main.py, nginx.conf, web/index.html, tests/test_lu_trainer.py, tests/browser/lu-trainer.cjs, README.md, AGENTS.md, MEMORY.md, structure_and_data.md, project_mind_map.md, LU_TRAINER_PROJECT.md + acceptance: targeted HTTP tests, Nginx syntax/serving, JS syntax, diff check, spec/diff review; temporary environments cleaned. + +Final review: approved root scope implemented. Spec compliance/consistency review resolved temporary hint disclosure and terminal controls. Source/diff review found and fixed overlapping hint expiry and result-inspection timer advancement. JS syntax, Python source compilation, 9 engine tests, 5 focused HTTP/calculator-page tests, Chromium acceptance and isolated Nginx syntax/alias/MIME checks passed. No runtime dependency, API, storage or production change. Check record and environment limits: root structure_and_data.md. diff --git a/docs/staging/specs/2026-11-17-lu-trainer.md b/docs/staging/specs/2026-11-17-lu-trainer.md new file mode 100644 index 0000000..7b32efc --- /dev/null +++ b/docs/staging/specs/2026-11-17-lu-trainer.md @@ -0,0 +1,14 @@ +# LU trainer implementation + +Authorization: the owner requested implementation of root `LU_TRAINER_PROJECT.md` on 2026-11-17. That existing design is the approved specification; this file records implementation choices within its scope. + +contract: standalone `/lu-trainer` and `/lu-trainer/`, shared HTML/CSS/ES-module assets served by Python and Nginx. No new runtime dependency or storage. Gateway serves the page with `try_files`; assets use the existing static serving. +convention: native buttons/radios/dialogs, CSS tokens, Verdana/Georgia, Russian copy, DOM-independent ES-module engine, no upstream code or asset copying. +state: engine owns 60 cells, hazards, opened set, marks set, last successful position, ready/playing/won/lost status and action log. A public snapshot omits hidden hazards/values. UI owns selection, action mode, map visibility and mark projection. +invariant: 6x10, entrance (5,0), exit (3,9); transition cells do not count toward victory and cannot be opened/marked. Top-row first 5/3 cells are safe and initially available; any other cell requires an opened neighbor. Eight-neighbor counts; safe path connects entrance, base and exit. Preserve documented hazard formula and 0/10/20/30% hint probabilities. Win by all non-transition safe cells or all and only hazards marked; loss ends actions. Repeat safe visits produce feedback and may hint. The character tracks the last successful non-transition visit. +invariant: one click produces one action; map selection never jumps; marks are separate from facts. Projection only changes scene rendering. Confirm clear marks and restart, including settings restart. Ending/restarting cancels hint and timer callbacks. At completion reveal the whole board, including incorrect notes. +contract: desktop direct cell action; compact/coarse-pointer overview selects only and uses >=44px confirm controls. Arrow/Home/End navigation and Enter/Space work. Screen-reader live status excludes timer ticks. Map/history mobile panels restore focus. Native dialogs support Escape/cancel. Failed images leave cells and character fallback usable. +test: deterministic Node tests for generator safety/reachability/counts, all settings combinations, adjacency, transition exclusion, notes, win/loss, hints and public snapshots. HTTP test for aliases and asset MIME/containment. Browser checks at 1920x1080,1366x768,768x1024,390x844; two grids, logs, marks, confirmations, focus, keyboard/touch, reduced motion, 200% layout and image failures. Review real screenshots. Nginx syntax/serving check in isolated container if Docker available; no deployment. +deferred: verification of real CatWar rules, multiple saved maps, audio, server accounts, deployment. Generated original art provenance and prompts live in assets/README.md. + +Review: spec-compliance/consistency review closed the hint and terminal-action gaps. Hints intentionally return a temporary hazard ID in action results only (not hidden snapshot values), last 2000 ms and retain their coordinate in the readable message log. Only unmarked neighboring hazards are candidates. At completion marking/clearing are disabled; selection remains available for inspection. Defaults: height 1, LU 5, growth 12, season 0; growth accepts 12/15/18/22/25 and season -3/0/5. diff --git a/nginx.conf b/nginx.conf index 99e7c87..dd564be 100644 --- a/nginx.conf +++ b/nginx.conf @@ -48,6 +48,16 @@ http { root /usr/share/nginx/html; index index.html index.htm; + # The trainer is entirely client-side; serve both aliases without + # a redirect to the asset directory or a dependency on Belki's API. + location = /lu-trainer { + try_files /lu-trainer.html =404; + } + + location = /lu-trainer/ { + try_files /lu-trainer.html =404; + } + # Belki calculator runs as a separate k3s web service. Keep the # legacy CatWar static site at /, but forward calculator pages and # their root-relative API calls to the Belki MetalLB service. diff --git a/project_mind_map.md b/project_mind_map.md index e835e60..2ae6bc3 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -1,6 +1,6 @@ # Карта проекта «Беличья нора» -Основная карта — состояние на 2026-11-14; 2026-11-17 добавлена отдельная проектируемая ветка тренажёра ЛУ. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур. +Основная карта — состояние на 2026-11-14; 2026-11-17 добавлена реализованная клиентская ветка тренажёра ЛУ (без deployment). Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур. ```mermaid mindmap @@ -8,13 +8,18 @@ mindmap Project context project-info.txt LongMemory catwar - Planned LU trainer — not implemented + LU trainer — client-only implementation LU_TRAINER_PROJECT.md Game-like scene and character Minefield companion map Shared attempt state and action history Client-side rules independent of Belki - Proposed route and asset serving via Python and gateway + engine.js — generation and training rules + ui.js — public snapshots and two grids + Original generated forest and cat assets + No persistence or CatWar account access + /lu-trainer and /lu-trainer/ via Python and Nginx + Node engine and Playwright acceptance Belki Domain domain.py diff --git a/structure_and_data.md b/structure_and_data.md index bc10a21..523d817 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -1,10 +1,14 @@ # Structure and Data -## LU trainer interface planning — 2026-11-17 +## LU trainer implementation — 2026-11-17 -- Root `LU_TRAINER_PROJECT.md` records the owner-requested game-like interface and explicitly requested «Минное поле» companion map. It separates confirmed scope, screenshot observations, upstream code behavior, proposed implementation and unresolved game rules. -- Upstream `tek1laa/catwar-lu-trainer` was statically inspected at commit `52f7f6111576f57fa5fe3edf43a38ffe2299f799`; no upstream code/assets were imported. The owner's screenshot remains a chat attachment; identifying content was not copied into Git. -- Proposed `/lu-trainer` and `web/lu-trainer/` do not exist yet. No runtime, infrastructure, dependencies or deployment changed. GitHub MCP fetch was unavailable; public GitHub API/raw files supplied the source. Token-optimizer and remote test-zone MCP were not exposed; no application tests/builds or background services were run for this documentation task. +- Implemented root `LU_TRAINER_PROJECT.md` after the owner's follow-up request to implement it. `/lu-trainer`, `/lu-trainer/` and `/lu-trainer.html` serve the same standalone page. Python aliases are explicit in `app/main.py`; Nginx aliases use `try_files /lu-trainer.html`. `Dockerfile` and `Dockerfile.gateway` already copy all `web/`; the gateway release Dockerfile also copies `nginx.conf`. Production images, cluster manifests and registry state were not changed. Existing gateway base publishing requirements still apply before a release. +- `web/lu-trainer/engine.js`: original DOM/clock/storage-free ES module with a 6x10 field, reserved safe route, documented height/growth/season formulas, eight-neighbor counts and adjacency relative to any opened cell. Entrance/exit are excluded from victory counts. Immutable settings and copied public snapshots hide unknown hazard/value facts until completion. Notes remain separate from facts; temporary hint IDs are deliberately disclosed by action results. This implements the described upstream model, not verified CatWar mechanics. No upstream source code/assets were imported. +- `web/lu-trainer.html`, `web/lu-trainer/style.css`, `web/lu-trainer/ui.js`: dense ochre/forest three-column desktop view, compact tablet/phone view, fictional character at the last safe visit, messages, history and companion map. Native radios/buttons/dialogs, roving grid focus with geometry-based arrow navigation, large confirmation controls on coarse pointers, map/history modal focus restoration, projection-only note visibility, confirmed clear/restart and terminal action locks. Hints last 2 seconds and retain coordinates in messages. Repeated hints renew their duration; end/restart/pagehide cancels timers. No persistence, backend writes, external game actions or Belki report integration. +- `web/lu-trainer/assets/forest.webp` and `cat.png` are original built-in imagegen outputs, optimized for delivery with the PNG alpha preserved. Provenance and complete generation prompts are in `assets/README.md`. The private reference screenshot was not copied into Git. Forest, grid, labels and character share one coordinate plane; failed images retain the neutral background, interactive grid and text character marker. +- `tests/lu-trainer/engine.test.mjs`: 9 deterministic Node cases including all 75 complexity combinations, generation safety/reachability, edge counts, adjacency, transition exclusion, notes, fall, both victories, hints, unknown-fact visibility and invalid settings. `tests/test_lu_trainer.py`: aliases, asset MIME and missing/escaping paths. `tests/browser/lu-trainer.cjs`: local-only Playwright acceptance for both grids, single-action logs, keyboard/mouse/touch, note projection, clear/restart/settings confirmation, native modal focus/Escape, hints/log/duration, terminal locks, timer cleanup, image failure and 200% layout/magnification. +- Validation: remote test-zone/token-optimizer MCP and Browser skill were not exposed; used bundled Node 24.22.1/Playwright with system Chromium 157.0.8103.38 and temporary Python venv from existing requirements. 9 engine checks and 5 focused Python routing/calculator-page checks passed. Browser scenarios passed at 1920x1080, 1366x768, 768x1024 and 390x844, including reduced motion and an equivalent 200% layout viewport plus CSS magnification. Screenshots were actually inspected; tablet history was collapsed to give the scene more room. No relevant JS console errors. Isolated `nginx:alpine` (`sha256:fed7e14be83cbd2661a75cdc5b872d936cf155d46c327084d30b8df19ae88d72`) passed `nginx -t` and returned 200 with correct MIME for all aliases/assets; both servers served identical page bytes. A real Chromium jump through the Nginx alias also updated the rendered count; the accessibility snapshot exposed named grid/row/gridcell/button semantics. +- The temporary `/tmp/cwshed-lu-check` venv/data/screenshots, guide/reference temp files, Python server and named Nginx container/image were removed/stopped after verification. One reviewed desktop screenshot was retained as a delivery preview outside Git under the task’s Codex visualizations directory. No remote systems were modified. Coverage is local Chromium/Python 3.14 and stock Nginx, not deployed production, physical touch hardware, screen-reader acceptance or other browsers. Design follows the document's retained reference description; the private screenshot was not available for a fresh pixel comparison. ## Homepage Matrix chat — 2026-11-17 diff --git a/tests/browser/lu-trainer.cjs b/tests/browser/lu-trainer.cjs new file mode 100644 index 0000000..9379e28 --- /dev/null +++ b/tests/browser/lu-trainer.cjs @@ -0,0 +1,206 @@ +// Browser plugin not available: use bundled Playwright against an isolated loopback server. +const assert = require('node:assert/strict'); +const path = require('node:path'); +const {pathToFileURL} = require('node:url'); +const {mkdir} = require('node:fs/promises'); +const {chromium} = require('playwright'); +const origin = process.env.BELKI_TEST_URL || 'http://127.0.0.1:8876'; +assert(['127.0.0.1','localhost','[::1]'].includes(new URL(origin).hostname)); +const shotDir = process.env.BELKI_SCREENSHOT_DIR; +function seeded(seed = 19) { return () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; }; } + +async function run() { + const {generateField, DEFAULTS} = await import(pathToFileURL(path.resolve(__dirname,'../../web/lu-trainer/engine.js'))); + const field = generateField(DEFAULTS,seeded()); + const browser = await chromium.launch({headless:true, ...(process.env.CHROMIUM_PATH ? {executablePath:process.env.CHROMIUM_PATH} : {})}); + const captures = []; + try { + if (shotDir) await mkdir(shotDir,{recursive:true}); + for (const [width,height] of [[1920,1080],[1366,768],[768,1024],[390,844]]) { + const context = await browser.newContext({viewport:{width,height}, reducedMotion:'reduce', locale:'ru-RU', ...(width === 390 ? {hasTouch:true,isMobile:true} : {})}); + try { + await context.addInitScript(() => { + let seed = 19; + Math.random = () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; }; + }); + const page = await context.newPage(), errors = []; + page.on('pageerror',error => errors.push(error.message)); + page.on('console',message => { if (message.type() === 'error') errors.push(message.text()); }); + await page.goto(`${origin}/lu-trainer${width === 768 ? '/' : ''}`); + await page.locator('#scene-grid button').last().waitFor(); + assert.equal(await page.title(),'Тренажёр ЛУ — Лесные уступы'); + assert.equal(await page.locator('#scene-grid button').count(),60); + assert.equal(await page.locator('#map-grid button').count(),60); + assert(await page.getByRole('heading',{name:'Тренажёр ЛУ',exact:true}).isVisible()); + const scene = id => page.locator(`#scene-grid button[data-id="${id}"]`); + const map = id => page.locator(`#map-grid button[data-id="${id}"]`); + const noOverflow = async () => assert(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth),`overflow at ${width}`); + const select = async id => { await scene(id).click(); if (width === 390) await page.locator('#jump').click(); }; + await noOverflow(); + assert.equal(await page.locator('#scene-grid .hazard').count(),0); + assert.equal(await page.locator('#scene-grid .opened').count(),0); + // Modal help must not modify the field, and Escape must restore focus. + await page.locator('#help-open').click(); + assert(await page.locator('#help-dialog').isVisible()); + await page.keyboard.press('Escape'); + assert(await page.locator('#help-open').evaluate(n=>n===document.activeElement)); + if (width === 390) { + await scene(0).tap(); + assert.equal(await page.locator('#scene-grid .opened').count(),0,'touch overview must only select'); + const box = await page.locator('#jump').boundingBox(); assert(box.height >= 44 && box.width >= 44); + await page.locator('#jump').tap(); + } else await select(0); + assert.equal(await page.locator('#scene-grid .opened').count(),1); + assert.equal(await page.locator('#map-grid .opened').count(),1); + assert.equal(await page.locator('#history li').count(),1); + assert.match(await scene(0).getAttribute('aria-label'),/персонаж здесь/); + assert.match(await page.locator('#messages').textContent(),/Опасностей рядом/); + // Native button keyboard actions and spatial focus; focus is not character position. + await scene(0).focus(); await page.keyboard.press('ArrowRight'); + assert(await scene(1).evaluate(n=>n===document.activeElement)); + assert.match(await scene(0).getAttribute('aria-label'),/персонаж здесь/); + await page.keyboard.press('Enter'); + assert.equal(await page.locator('#scene-grid .opened').count(),2); + assert.equal(await page.locator('#history li').count(),2); + await page.keyboard.press(' '); + assert.equal(await page.locator('#history li').count(),3,'one keyboard action, one history item'); + await page.keyboard.press('End'); + assert(await scene(9).evaluate(n=>n===document.activeElement)); + await page.keyboard.press('Home'); assert(await scene(0).evaluate(n=>n===document.activeElement)); + // Notes select on the map without jumping. One DOM map is moved into the modal on phone. + if (width === 390) await page.locator('#map-open').click(); + await map(2).click(); + assert.equal(await page.locator('#scene-grid .opened').count(),2); + await page.locator('#map-mark').click(); + assert.equal(await page.locator('#map-grid .marked').count(),1); + assert.equal(await page.locator('#scene-grid .marked').count(),1); + await page.locator('#project-marks').uncheck(); + assert.equal(await page.locator('#scene-grid .marked').count(),0); + assert.equal(await page.locator('#map-grid .marked').count(),1); + assert.equal(await page.locator('#history li').count(),4); + await page.locator('#project-marks').check(); + // Clearing first cancels, then confirms; facts and history remain. + await page.locator('#clear-marks').click(); await page.keyboard.press('Escape'); + assert.equal(await page.locator('#map-grid .marked').count(),1); + await page.locator('#clear-marks').click(); await page.locator('#confirm-action').click(); + assert.equal(await page.locator('#map-grid .marked').count(),0); + assert.equal(await page.locator('#map-grid .opened').count(),2); + assert.equal(await page.locator('#history li').count(),5); + if (width === 390) { + await page.keyboard.press('Escape'); + assert(await page.locator('#map-open').evaluate(n=>n===document.activeElement)); + await page.locator('#history-open').click(); + assert(await page.locator('#panel-dialog #history').isVisible()); + await page.keyboard.press('Escape'); + assert(await page.locator('#history-open').evaluate(n=>n===document.activeElement)); + } else { + await page.locator('#map-toggle').click(); assert(await page.locator('#map-body').isHidden()); + await page.locator('#map-expand').click(); assert(await page.locator('#panel-dialog #map-grid').isVisible()); + await page.keyboard.press('Escape'); assert(await page.locator('#map-body').isHidden()); + await page.locator('#map-toggle').click(); + } + if (shotDir) { const file = `${shotDir}/lu-${width}.png`; await page.screenshot({path:file,fullPage:true}); captures.push(file); } + // Restart confirmations preserve/cancel the existing state; settings are staged until submit. + await page.locator('#new-game').click(); await page.keyboard.press('Escape'); + assert.equal(await page.locator('#scene-grid .opened').count(),2); + await page.locator('#settings-open').click(); await page.locator('#setting-height').selectOption('2'); + await page.keyboard.press('Escape'); assert.match(await page.locator('#height-value').textContent(),/^1/); + await page.locator('#settings-open').click(); + assert.equal(await page.locator('#setting-height').inputValue(),'1'); + await page.locator('#setting-height').selectOption('2'); + await page.getByRole('button',{name:'Начать новую игру',exact:true}).click(); + assert.match(await page.locator('#height-value').textContent(),/^2/); + assert.equal(await page.locator('#scene-grid .opened').count(),0); + assert.equal(await page.locator('#history li').count(),0); + assert.equal(await page.locator('#timer').textContent(),'00:00'); + assert.deepEqual(errors,[]); + console.log(`PASS ${width}x${height}: render, keyboard/touch, synchronized map, notes, dialogs, settings, console`); + } finally { await context.close(); } + } + // Deterministic result/clock/hint lifetime checks at desktop size. + const context = await browser.newContext({viewport:{width:1366,height:768}}); + try { + await context.addInitScript(() => { let seed=19; Math.random=()=>{seed=(Math.imul(seed,1664525)+1013904223)>>>0;return seed/2**32;}; }); + const page = await context.newPage(); + await page.goto(`${origin}/lu-trainer`); + await page.locator('#scene-grid button').last().waitFor(); + const cell = id=>page.locator(`#scene-grid button[data-id="${id}"]`); + // Open safe reachable cells until a known adjacent hazard can be reached. + let hazard; + for (let guard=0;guard<60;guard++) { + const ids = await page.locator('#scene-grid .available:not(.opened):not(.transition) button').evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.id))); + hazard = ids.find(id=>field.hazards.has(id)); + if (hazard !== undefined) break; + const next = ids.find(id=>!field.hazards.has(id)); assert.notEqual(next,undefined); await cell(next).click(); + } + assert.notEqual(hazard,undefined); await cell(hazard).click(); + assert(await page.locator('#result').isVisible()); + assert.match(await page.locator('#result').textContent(),/Падение/); + assert.equal(await page.locator('#scene-grid .hazard').count(),field.hazards.size); + const count = await page.locator('#history li').count(); + await cell(1).click(); assert.equal(await page.locator('#history li').count(),count); + assert(await page.locator('#jump').isDisabled()); assert(await page.locator('#mark').isDisabled()); + const frozen = await page.locator('#timer').textContent(); + await page.waitForTimeout(1100); assert.equal(await page.locator('#timer').textContent(),frozen); + await cell(2).click(); assert.equal(await page.locator('#timer').textContent(),frozen,'result inspection must not advance the stopped clock'); + // Restart must cancel old hints, facts and the clock. + await page.locator('#new-game').click(); await page.locator('#confirm-action').click(); + await page.waitForTimeout(2100); + assert.equal(await page.locator('#timer').textContent(),'00:00'); + assert.equal(await page.locator('#scene-grid .hint').count(),0); + // Equivalent layout viewport at 200% browser zoom; then explicit CSS magnification. + await page.setViewportSize({width:683,height:384}); + assert(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth)); + await page.evaluate(()=>document.documentElement.style.zoom='2'); + assert(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth)); + assert(await page.locator('#new-game').isVisible()); + console.log('PASS terminal state, frozen clock, restart timer cleanup, 200% layout/magnification'); + await page.evaluate(()=>document.documentElement.style.zoom='1'); + await page.setViewportSize({width:1366,height:768}); + await page.reload(); await page.locator('#scene-grid button').last().waitFor(); + await page.evaluate(()=>Math.random=()=>0); + await cell(2).click(); + assert.equal(await page.locator('#scene-grid .hint').count(),1); + assert.equal(await page.locator('#map-grid .hint').count(),1); + assert.match(await page.locator('#messages').textContent(),/Подсказка: Б4/); + await page.waitForTimeout(1100); await cell(2).click(); + await page.waitForTimeout(1100); + assert.equal(await page.locator('#scene-grid .hint').count(),1,'repeat hint renews the full display duration'); + await page.waitForTimeout(1000); + assert.equal(await page.locator('#scene-grid .hint').count(),0); + assert.match(await page.locator('#messages').textContent(),/Подсказка: Б4/); + await cell(2).click(); + assert.equal(await page.locator('#scene-grid .hint').count(),1); + await page.locator('#new-game').click(); await page.locator('#confirm-action').click(); + await page.waitForTimeout(2100); + assert.equal(await page.locator('#scene-grid .hint').count(),0); + assert.equal(await page.locator('#history li').count(),0); + assert.equal(await page.locator('#timer').textContent(),'00:00'); + // Marking is available anywhere; only the exact hazard set wins. + await page.reload(); await page.locator('#scene-grid button').last().waitFor(); + for (const id of field.hazards) await cell(id).click({button:'right'}); + assert.match(await page.locator('#result').textContent(),/Карта готова/); + assert(await page.locator('#clear-marks').isDisabled()); + const wonHistory = await page.locator('#history li').count(); + await cell(0).click({button:'right'}); + assert.equal(await page.locator('#history li').count(),wonHistory); + console.log('PASS hint duration/log persistence, restart cancels active hint, exact-note victory and terminal locks'); + + } finally {await context.close();} + // Image failure is intentional; the forest and cat have independent text/grid fallbacks. + const broken = await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true}); + try { + const page = await broken.newPage(); + await page.route('**/lu-trainer/assets/*',route=>route.abort()); + await page.goto(`${origin}/lu-trainer`); + await page.locator('#scene-grid button').last().waitFor(); + assert(await page.locator('.forest').isHidden()); + assert(await page.locator('#character > span').isVisible()); + await page.locator('#scene-grid button[data-id="0"]').tap(); await page.locator('#jump').tap(); + assert.equal(await page.locator('#scene-grid .opened').count(),1); + console.log('PASS failed-image fallback retains training controls and character marker'); + } finally { await broken.close(); } + console.log(JSON.stringify({screenshots:captures})); + } finally {await browser.close();} +} +run().catch(error=>{console.error(error); process.exitCode=1;}); diff --git a/tests/lu-trainer/engine.test.mjs b/tests/lu-trainer/engine.test.mjs new file mode 100644 index 0000000..7a20985 --- /dev/null +++ b/tests/lu-trainer/engine.test.mjs @@ -0,0 +1,121 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { Training, generateField, neighbors, hintChance, START, EXIT } from '../../web/lu-trainer/engine.js'; + +function seeded(seed = 19) { + return () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed / 2 ** 32; }; +} +const options = {height: 1, lu: 5, growth: 12, season: 0}; +function fixture(settings = options, seed = 19) { + return {field: generateField(settings, seeded(seed)), game: new Training(settings, seeded(seed))}; +} +function openReachableSafe(game, field) { + let progress = true; + while (progress && !['won', 'lost'].includes(game.view().status)) { + progress = false; + for (const cell of game.view().cells) { + if (cell.available && !cell.opened && !cell.transition && !field.hazards.has(cell.id)) { + game.jump(cell.id); progress = true; + } + } + } +} + +test('generation covers every settings combination with safe transitions, base and connecting route', () => { + for (let height = 1; height <= 5; height++) for (const growth of [12,15,18,22,25]) for (const season of [-3,0,5]) { + const field = generateField({...options, height, growth, season}, seeded(height * growth + season)); + assert.equal(field.values.length, 60); + assert(!field.hazards.has(START) && !field.hazards.has(EXIT)); + for (const id of field.base) assert(!field.hazards.has(id)); + assert.equal(field.base.length, height === 1 ? 5 : 3); + assert.equal(field.hazards.size, Math.min(Math.max(5, growth + season + 2 * (height - 1)), 60 - field.reserved.size)); + const reached = new Set([START]); + for (const id of reached) for (const next of neighbors(id)) if (!field.hazards.has(next)) reached.add(next); + assert(reached.has(EXIT)); + for (const id of field.base) assert(reached.has(id)); + for (let id = 0; id < 60; id++) assert.equal(field.values[id], neighbors(id).filter(n => field.hazards.has(n)).length); + } +}); +test('edge neighborhoods do not wrap rows', () => { + assert.deepEqual(neighbors(0).sort((a,b)=>a-b), [1,10,11]); + assert.equal(neighbors(9).length, 3); assert.equal(neighbors(25).length, 8); + assert.deepEqual(neighbors(59).sort((a,b)=>a-b), [48,49,58]); +}); +test('only base or neighbors of any opened cell are available; transitions never count', () => { + const {game} = fixture(); + assert.equal(game.jump(START).code, 'transition'); + assert.equal(game.jump(EXIT).code, 'transition'); + assert.equal(game.jump(25).code, 'unreachable'); + assert.equal(game.mark(START).code, 'transition'); + assert.equal(game.jump(0).code, 'opened'); + game.jump(4); // last position differs: adjacency still belongs to any open cell + assert(game.view().cells[10].available); + assert.equal(game.view().position, 4); +}); +test('notes hide no facts, block jumps, clear independently and reject invalid IDs', () => { + const {game} = fixture(); + game.jump(0); game.mark(1); + const before = game.view(); + assert.equal(game.jump(1).code, 'marked'); + assert.equal(before.cells[1].value, null); + assert(!Object.hasOwn(before.cells[1], 'hazard')); + assert.equal(game.mark(0).code, 'opened'); + game.clearMarks(); + assert(game.view().cells[0].opened); + assert.equal(game.view().marks, 0); + assert.equal(game.view().position, before.position); + assert(game.view().history.length > before.history.length); + for (const id of [-1,60,1.5,'1',null]) assert.equal(game.jump(id).code, 'invalid'); +}); +test('all and only hazards marked wins; terminal actions cannot change state', () => { + const {game,field} = fixture(); + game.mark(0); + for (const id of field.hazards) game.mark(id); + assert.notEqual(game.view().status, 'won'); + game.mark(0); + assert.equal(game.view().status, 'won'); + const ended = game.view(); + for (const cell of ended.cells) assert.equal(typeof cell.hazard, 'boolean'); + assert.equal(game.jump(0).code, 'finished'); + assert.equal(game.mark(1).code, 'finished'); + assert.equal(game.clearMarks().code, 'finished'); + assert.deepEqual(game.view(), ended); +}); +test('opening all safe cells wins without entering either transition', () => { + const {game,field} = fixture(); + openReachableSafe(game, field); + assert.equal(game.view().status, 'won'); + assert.equal(game.view().opened, 58 - field.hazards.size); +}); +test('hazard ends attempt, reveals wrong notes and preserves last safe position', () => { + const {game,field} = fixture(); + game.mark(4); game.jump(0); + while (game.view().status !== 'lost') { + const cell = game.view().cells.find(c => c.available && !c.opened && !c.transition && !c.marked); + assert(cell); game.jump(cell.id); + } + const end = game.view(); + assert(end.cells[4].wrong); + assert(field.hazards.has(end.hit)); + assert(!field.hazards.has(end.position)); +}); +test('LU hint probability, repeated safe visits and hidden information boundary', () => { + assert.deepEqual(Array.from({length:10}, (_,lu)=>hintChance(lu)), [0,0,0,0,.1,.2,.3,.3,.3,.3]); + const {game,field} = fixture(); + openReachableSafe(game, field); + // Separate active game: choose an available safe base cell with adjacent hazards. + const active = fixture(); + const id = active.field.base.find(n => active.field.values[n] > 0); + assert.notEqual(id, undefined); + active.game.jump(id, () => 0); + const revisit = active.game.jump(id, () => 0); + assert.equal(revisit.code, 'revisited'); + assert(active.field.hazards.has(revisit.hint)); + assert.equal(active.game.view().cells[revisit.hint].value, null); + assert.equal(active.game.view().opened, 1); + assert.equal(active.game.view().history.length, 2); + assert.equal(new Training({...options,lu:0}, seeded()).jump(id, () => 0).hint, null); +}); +test('invalid settings are rejected rather than corrupting generation', () => { + for (const bad of [{height:0},{lu:10},{growth:99},{season:7}]) assert.throws(()=>new Training({...options,...bad}), RangeError); +}); diff --git a/tests/test_lu_trainer.py b/tests/test_lu_trainer.py new file mode 100644 index 0000000..edb7fda --- /dev/null +++ b/tests/test_lu_trainer.py @@ -0,0 +1,49 @@ +"""Standalone LU trainer routing must work without any game/session store.""" +import http.client +import threading +import unittest + +from app.main import BelkiHTTPServer, Handler + + +class TrainerRoutesTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = BelkiHTTPServer(('127.0.0.1', 0), Handler) + cls.worker = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.worker.start() + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + cls.worker.join() + + def get(self, path): + connection = http.client.HTTPConnection('127.0.0.1', self.server.server_port, timeout=5) + try: + connection.request('GET', path) + response = connection.getresponse() + return response.status, response.getheader('Content-Type'), response.read() + finally: + connection.close() + + def test_page_aliases_return_the_same_trainer(self): + pages = [self.get(path) for path in ['/lu-trainer', '/lu-trainer/', '/lu-trainer.html']] + for status, content_type, content in pages: + self.assertEqual(status, 200) + self.assertEqual(content_type, 'text/html') + self.assertIn('Тренажёр ЛУ'.encode(), content) + self.assertEqual(pages[0][2], pages[1][2]) + + def test_assets_have_browser_compatible_mime_types(self): + for asset, media_type in [('engine.js', 'javascript'), ('ui.js', 'javascript'), ('style.css', 'text/css'), ('assets/forest.webp', 'image/webp'), ('assets/cat.png', 'image/png')]: + with self.subTest(asset=asset): + status, content_type, content = self.get('/lu-trainer/' + asset) + self.assertEqual(status, 200) + self.assertIn(media_type, content_type) + self.assertGreater(len(content), 0) + + def test_missing_and_escaping_assets_are_not_served(self): + for path in ['/lu-trainer/missing.js', '/lu-trainer/%2e%2e/%2e%2e/project-info.txt']: + self.assertEqual(self.get(path)[0], 404) diff --git a/web/index.html b/web/index.html index 03fd2ed..83d4fbc 100644 --- a/web/index.html +++ b/web/index.html @@ -75,6 +75,7 @@