Files
cwshed-clone/structure_and_data.md
T

230 lines
53 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Structure and Data
## Trainer sound and manual ratings — 2026-11-22
- `audio.js` synthesizes counted rustles using Web Audio; no media downloads or runtime dependencies. The sound and simplified views share one `min(7, neighbors)` level. Switching modes preserves the field and ratings and updates prior messages without showing verified numbers in sound mode during play.
- `Training.rate()` stores separate ratings 0–7, including on opened cells. Ratings render as badges and do not affect moves or victory. One map serves mouse, keyboard, and touch controls.
## Trainer controls — 2026-11-22
- `/trainer` no longer has a separate action panel or mode toggle. The scene handles mouse and keyboard actions directly; narrow and coarse-pointer layouts use selection and explicit buttons below the grid. The inline status is short, and detailed jumps and hints remain in the message journal.
## Trainer movement and exit edges — 2026-11-22
- Jumps and the grids’ availability indicators use the eight neighbors of the current character position, including from the entrance. An opened cell can be revisited only from an adjacent cell; selecting or marking a cell on the map does not move the character.
- Each field reserves one exit from the right edge (`x10 y2–y6`) or the bottom edge (`y6 x6–x10`), counting the shared corner once. Both transitions are still markers, not actions that change height.
- Verified with 10 engine tests, 6 targeted HTTP/calculator-page tests and the Chrome browser suite at 1920/1366/768/390 px. No push or deployment.
## Gateway Nginx security update (2026-11-21)
- The previous registry base contained Nginx 1.31.4. The rebuilt Linux amd64 gateway uses Nginx 1.31.9 on Alpine, the mainline security release from 2026-11-18. `Dockerfile.gateway-base` pins the upstream digest. `Dockerfile.gateway` pins the verified private registry digest so the next CI build picks up the new binary. [NGINX security advisories](https://nginx.org/en/security_advisories.html)
- The base was published to the private registry under a new tag. The release image passed `nginx -t` and isolated smoke checks for the homepage, trainer aliases, WebP MIME type, Belki web/API proxy, and the exact VK callback POST route with loopback upstreams. The production rollout is pending.
## Trainer entrance and variable exit — 2026-11-17
- Applied the owner correction: entrance always `x1 y1`, exit can vary. `engine.js` sets start index 0 and chooses an exit per field from the other 59 cells. The fixed global exit constant is removed; `view()` exposes transition coordinates and per-cell entrance/exit flags. The generator reserves both transitions and a safe connecting path, preserving hazard formulas and 5/3 initially playable safe cells in the top row excluding transitions.
- One-based coordinates use X right/Y down and x1 y1 at the top-left. Random placement implements variability; its distribution and allowed positions are not independently verified CatWar rules. `ui.js` uses snapshot flags for both grids, arrows, selection labels and logs; current transition coordinates are shown above the scene. HTML help and regression fixtures no longer hard-code the upstream positions. No route, runtime dependency or server change.
- Validation passed: 10 Node model tests (all 59 exit positions, all 75 setting combinations, generation and victory invariants), 4 Python trainer HTTP tests, JS syntax and diff checks; Chromium scenarios at 1920/1366/768/390 widths including regenerated transition identities, XY labels, keyboard/touch, hints/timers and image fallback. Desktop/mobile screenshots were inspected. No new UI patterns were needed after the modern-web-guidance grid-label search. Remote test-zone/token-optimizer MCP are unavailable. The isolated server was stopped and temporary venv/data/screenshots removed. No push/deployment.
## Portable WebP MIME response — 2026-11-17
- Reproduced the reported CI mismatch in stock `python:3.12-slim` (Python 3.12.16): strict `mimetypes.guess_type("forest.webp")` returns `(None, None)` while the non-strict common table contains `image/webp`. The workstation MIME database masked this during the original checks.
- `app/main.py` `Handler._file` now explicitly sets `image/webp` for `.webp` (case-insensitive); all other formats keep the existing lookup/fallback. No dependency, image definition, route, game logic or gateway configuration change. `tests/test_lu_trainer.py` adds an HTTP regression check with MIME guessing unavailable.
- Validation passed: 4 focused trainer HTTP tests locally; all 178 Python discovery tests in disposable `python:3.12-slim` (Python 3.12.16), with source mounted read-only and test stores under container `/tmp`; Python source compilation and diff checks. The container, pulled image and temporary local venv/data were removed. Remote test-zone/token-optimizer MCP are unavailable. No push/deployment.
## Trainer public route — 2026-11-17
- Owner requested `/trainer` instead of `/lu-trainer`. Python and Nginx now expose `/trainer` and `/trainer/`; the homepage link and browser entry URLs use `/trainer`. Internal `web/lu-trainer.html` and `/lu-trainer/` asset URLs are retained. No game mechanics, runtime dependencies or deployment changes.
- Validation passed: 3 targeted Python routing/asset tests, Nginx syntax check, JS test-script syntax and diff checks, plus Chromium navigation from the homepage to `/trainer`, one rendered jump and the `/trainer/` alias. The gameplay suite changed only its entry URLs. Remote test-zone/token-optimizer MCP remain unavailable. Temporary venv/data and Nginx container/image were removed after verification. No push or deployment.
## LU trainer implementation — 2026-11-17
- 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
- `web/index.html` links to the owner-provided Matrix room beside the VK community link, using the existing homepage styling and a decorative chat icon. The link opens in a new tab with `noopener noreferrer`; the room ID and `via=nyan404.ru` routing hint are preserved. No runtime dependencies or deployment changes.
- Validation: local Chromium render at 1280/390 px, exact link destination, keyboard focus and no horizontal overflow; screenshots reviewed and removed. Remote test-zone and token-optimizer MCP were unavailable. No push or deployment.
## External report polling — 2026-11-17
- `GET /api/admin/calculations/pending` reads unentered history directly from SQLite/PostgreSQL in ascending ID order with cursor pagination. `PATCH /api/admin/calculations/{id}/entered` updates the same flag as the admin UI and returns the actual row regardless of history size. The existing admin password/session authorizes both; no separate integration identity exists. See README for the contract and polling semantics. Changes are local until deployed.
## Calculator and related UI guidance pass — 2026-11-14
- `web/calculator.html` keeps the existing warm palette and typography. Section navigation now uses real links with `aria-current` and browser history; calculation mode uses a native radio group with built-in arrow-key behavior. File inputs, repeatable kitten fields, quick input and output have accessible labels/focus; dialogs retain native modal focus and Escape handling. No new runtime dependencies or polyfills were required.
- Prepared reports/results are invalidated by edits, helper actions and mode changes. An incrementing version discards stale async responses; calculation/application submit guards prevent concurrent duplicate requests in the current page. Clipboard denial selects the output and gives manual-copy instructions. This does not provide server-side idempotency for retries after an uncertain network failure.
- Fixed the existing training-points display: `/api/calculate` returns `kitten_points: 25` for training, while coaching uses an array. The UI now accepts both and renders score text with DOM nodes. Inactive points fields cannot block native form validation; “Без ресурсов” clears inspection resources. Application practice-link visibility/disabled state is recomputed when changing type and after reset.
- `web/applications.html` keeps the standalone form, exposes the native file picker to keyboard users, reports pressed selection/success, snapshots application data before uploads and guards submission. `web/admin.html` gives password/gallery accessible names, uses `aria-pressed` for ordinary selection buttons, adds solid focus outlines and preserves native dialog dismissal. Existing current-month defaults, sorting and history persistence are retained.
- `tests/browser/calculator.cjs` uses external Playwright against an isolated loopback server, checks 1280/390 px flows and closes browser resources. Python dependencies and SQLite fixtures were kept in `/tmp/cwshed-ui-review`; no remote test-zone or token-optimizer MCP was exposed. Validation used Python 3.14.9 and Chromium 157 on Linux (the production Python 3.12 image was not rebuilt): 49 focused Python tests (calculator web, API, applications, history, lookup and admin/export), Python compilation, JS syntax, browser interactions and screenshot inspection. The temporary server, environment and artifacts are removed after review. No push/deployment.
- `chrome-extensions` was checked for applicability: the retained CatWar files are userscripts (`@match` / `@grant`), not an MV3 extension; no Chrome extension manifest or `chrome.*` integration exists in the inspected entry points. No manifest conversion or third-party asset updates were warranted. This is not a comprehensive audit of the legacy bundled code or installed browser extensions.
- Root `project-info.txt` records the owner-selected LongMemory namespace `catwar`; it is a literal identifier, never executable configuration. Project context and targeted recall were empty at the start of this pass.
## PHP CVE applicability review — 2026-10-21
- Static review of revision `765d4023605b2cf56c81e2027f5def606e45637f`: CVE-2026-109618 and CVE-2026-109619 are not actionable for the declared project stack because it has no PHP request runtime. Both concern PHP core; see the [PHP advisory](https://www.php.net/archive/2026.php).
- Evidence: `Dockerfile.base` installs Python 3.12 and `requirements.txt`; `Dockerfile` starts `app.main`. `Dockerfile.gateway-base` uses Nginx; `nginx.conf` serves static files and proxies to the Python web/bot services, with no PHP/FastCGI handler. Production manifests declare Python web/bot services and PostgreSQL. CI builds those images. No PHP source or Composer manifest was found; the PHP text match in the existing assets was a Font Awesome icon name.
- This is source/configuration evidence, not a live deployment attestation: running pods, private image contents, external proxies and other hosts were not inspected. Reassess if PHP is added or the deployed stack differs. No application changes, builds, tests or deployment were needed.
## ULLI weather easter egg — 2026-10-18
- `app/belki/weather.py` fetches the fixed `https://weather.nyan404.ru/api/v1/metar/raw/ulli` endpoint and extracts observed wind (MPS/KT/KMH, including gusts), rain/drizzle, snow and mixed precipitation. Trend, remark and vicinity groups are ignored. Light, moderate, heavy/shower/blowing-snow effects change particle density; wind changes speed and drift.
- `/api/weather/ulli` returns only `{mode, intensity, wind_mps}`. A 5-minute in-memory cache, nonblocking refresh lock, 3-second upstream timeout, 64 KiB response cap and 1-minute failure cache bound the work. Missing, invalid, future (>10 min) or stale (>2 h) observations restore leaves. No database, credentials or new dependencies are involved.
- `web/weather-effect.js` and `.css` are shared by calculator/admin and served through explicit `/api/weather/effect.js` and `.css` routes. This keeps them behind the existing gateway `/api/` proxy without a gateway/base-image change. Browser refreshes every 5 minutes, pauses animation/polling in hidden tabs, and respects reduced motion. Existing seven-leaf markup remains the no-JS fallback.
- Validation used an isolated local server because no remote test-zone MCP was exposed. Weather/parser/cache/HTTP tests, calculator/admin checks and browser fixtures cover desktop (1280 px), mobile (390 px), rain/snow/mixed/leaves, wind acceleration, reduced motion and failed API fallback. Screenshots/scripts and temporary SQLite data live under `/tmp`, outside Git; stop the test server/browser after use. macOS Python needed `SSL_CERT_FILE=/etc/ssl/cert.pem` for the live weather smoke check; TLS verification stays enabled. No push or deployment.
## Repository Layout
- [`.gitlab-ci.yml`](./.gitlab-ci.yml): existing single-stage GitLab pipeline targeting the Belki image.
- [`Dockerfile`](./Dockerfile): Python 3.12 runtime image for the calculator web service and shared static assets.
- [`app/`](./app): calculation domain, report templates, JSON API, HTTP server, and VK Bots Long Poll adapter.
- [`web/`](./web): calculator frontend plus legacy CatWar userscript assets.
- [`deploy/k8s/`](./deploy/k8s): namespace, production web/bot/PostgreSQL manifests, and namespace-scoped CI deploy RBAC.
- [`docs/GITLAB_CI_CD.md`](./docs/GITLAB_CI_CD.md): GitLab variables and CI/CD handoff.
- [`tests/`](./tests): standard-library unit tests for calculation, reports, API, and VK parsing.
- [`docs/staging/`](./docs/staging): working specification and implementation plan for the Belki calculator.
- [`docs/Новая Крыланы. [Памятка].md`](./docs/%D0%9D%D0%BE%D0%B2%D0%B0%D1%8F%20%D0%9A%D1%80%D1%8B%D0%BB%D0%B0%D0%BD%D1%8B.%20%5B%D0%9F%D0%B0%D0%BC%D1%8F%D1%82%D0%BA%D0%B0%5D.md): searchable Markdown wiki for Krylan community rules, report templates, escalation paths, and source links; it excludes embedded illustrative image data.
- [`docs/Памятка-и-бот-расхождения.md`](./docs/%D0%9F%D0%B0%D0%BC%D1%8F%D1%82%D0%BA%D0%B0-%D0%B8-%D0%B1%D0%BE%D1%82-%D1%80%D0%B0%D1%81%D1%85%D0%BE%D0%B6%D0%B4%D0%B5%D0%BD%D0%B8%D1%8F.md): verified comparison of the Krylan memo and the current bot calculator, including deliberate product boundaries and items requiring a rules decision.
- [`AGENTS.md`](./AGENTS.md): repo-specific instructions for future coding agents.
- [`.gitignore`](./.gitignore): ignores Python bytecode/caches, virtual environments, test output, and local editor noise.
- [`MEMORY.md`](./MEMORY.md): durable notes about the current CI/runtime decision.
- [`project_mind_map.md`](./project_mind_map.md): current Mermaid map of the Belki domain, public/admin/VK data flows, storage, deployment, and security boundaries.
- [`LICENSE`](./LICENSE): MIT license for the project's original code and documentation.
- [`NOTICE`](./NOTICE): retained license and attribution boundary for bundled third-party and legacy userscript files.
- [`CONTRIBUTING.md`](./CONTRIBUTING.md): contribution and verification rules.
## Runtime / Deployment
- 2026-10-10: admin report history now defaults to `created_at` descending (newest first) in both the browser table and API request. The history store accepts `created_at` as a safe sort key; the existing alternate sort controls remain available.
- 2026-10-10: rotated `BELKI_ADMIN_PASSWORD` in the existing namespace Secret from ignored `.secrets/BELKI_ADMIN_PASSWORD`, restarted `belki-web` and `belki-bot`, and verified the admin API returned HTTP 200 with the current value and HTTP 401 with an invalid value. The password itself is not stored in Git.
- 2026-10-10: deployed the clickable points activity menu and inflected activity aliases as image tag `67d505f`; `belki-bot`, web, and gateway rollouts completed successfully with new pods at zero restarts. Runtime verification inside the new bot pod exposed buttons `Прокачка`, `Тренировка`, `Осмотр` with `points:*` payloads.
- 2026-10-10: the VK points calculator now shows clickable `Прокачка`, `Тренировка`, and `Осмотр` buttons at the activity prompt. Text input accepts both nominative and accusative forms (`прокачка`/`прокачку`, `тренировка`/`тренировку`).
- 2026-10-10: performed a manual production rollout from the local checkout. The amd64 images `reg.nyan404.ru/cwshed-clone/belki:df5dd4e` (digest `sha256:bd0abf5ef86565534e9455a628c276fe49a39eca28c0581d581ea2c5a4b0dcf1`) and `reg.nyan404.ru/cwshed:df5dd4e` (digest `sha256:b274cfd43710fa7def9048601ad4de3da0895e2744e230cb0348f19b347a6eaa`) were built on `root@10.3.1.168` and applied to namespace `belki`. `VK_CALLBACK_SECRET` and `VK_CALLBACK_CONFIRMATION` came from ignored `.secrets/` files and were applied to `Secret/belki-runtime`; their values are not stored here. Direct callback and the cwshed `/api/vk/callback` proxy both returned HTTP 200 for the confirmation payload through an admin port-forward. The old bot ReplicaSet pod was still terminating during the final snapshot; the new pod was Running with zero restarts.
- 2026-10-08: hardened `belki-bot` VK Long Poll against transient `OSError`/SSL/timeout failures. The poll loop logs the failure, waits, obtains a fresh `groups.getLongPollServer` lease, and continues without exiting the process.
- 2026-10-08: `BelkiDialog` now persists unfinished per-actor state and queued VK photos in `vk_dialog_states` through the existing `BELKI_DATABASE_URL`/`BELKI_HISTORY_DB` store. State is written after each text/photo event and restored lazily after a bot restart; completed/cancelled dialogs are deleted.
- 2026-10-10: added pod-template label `qos.dscp=cs1` to `belki-bot`; the k3s
`pod-dscp-marker` DaemonSet follows the Deployment's current pod IP and node.
- 2026-10-08: deployed only `belki-bot` image `reg.nyan404.ru/cwshed-clone/belki:2d9aa21` (amd64 digest `sha256:899fcb5a91618a0b2f657a96f7fdf2f1686423bba6a95f13e431d589e629d401`). The previous Pod had 9 restarts and exited with an SSL handshake timeout in VK Long Poll; the replacement Pod reached Ready with restart count 0 during the follow-up check.
- 2026-09-08: report screenshots and VK attachment mirrors use private distributed MinIO through the `minio==7.2.20` SDK. `belki-image-store` is a separate, out-of-band Kubernetes Secret containing the internal S3 endpoint, a bucket-scoped `GetObject`/`PutObject` account plus required `GetBucketLocation`, and `belki-images`; it is deliberately separate from CI-managed `belki-runtime` so normal deploys cannot remove it. `belki-web` and `belki-bot` return/retain `https://cat.nyan404.ru/api/images/<128-bit-random-id>.<extension>` while `Handler` proxies reads from MinIO. MinIO has no public exposure.
- 2026-09-24: switched the live Belki S3 endpoint from the five direct MinIO nodes to the in-cluster HAProxy front door `10.43.30.146:9000` (`minio-haproxy` in namespace `minio-proxy`). The cluster Secret was updated out-of-band and `belki-web`/`belki-bot` were restarted; the repository example mirrors this endpoint. HAProxy remains responsible for balancing the healthy MinIO nodes.
- `Dockerfile.base` is rebuilt and pushed with the immutable `py312-<commit>` tag before the final Belki image; `Dockerfile` accepts that base through `BELKI_BASE_IMAGE`, leaving only application sources in the final layer.
- GitLab CI runs the build job.
- Production container architecture is explicitly `linux/amd64`: CI sets `DOCKER_DEFAULT_PLATFORM` and passes `--platform linux/amd64`, Dockerfiles pin the platform, and Kubernetes workloads select nodes labeled `kubernetes.io/arch: amd64`. The former private Python base tag was arm64-only and is no longer used by the application image.
- The job targets GitLab runner tag `fast` and builds through a privileged `docker:29.6.1-dind` service at `DOCKER_HOST=tcp://docker:2375`, with an explicit `alias: docker` and `DOCKER_TLS_CERTDIR=""`.
- Runtime dependency layers are stored in the private registry. CI builds the Belki base from `Dockerfile.base`. For Nginx version upgrades, build and publish a new gateway base under `reg.nyan404.ru/cwshed/cwshed-base`, then set its tag and digest in `Dockerfile.gateway` before running CI. The final gateway image copies both `nginx.conf` and static assets so routing changes ship in an ordinary release.
- The `ryzen-runner-dind` service on `root@10.3.1.168` has a valid Runner registration and its helper container can reach `https://git.nyan404.ru/`. On 2026-08-21 its malformed `DOCKER_AUTH_CONFIG` was removed and the pre-change configuration was backed up on the host as `/etc/gitlab-runner/config.toml.bak-20260821-1334`.
- The job waits for the DinD daemon and runs `docker info` before starting the build.
- GitLab Runner retries source checkout up to three times (`GET_SOURCES_ATTEMPTS=3`) to absorb transient connectivity failures before the job script starts. A persistent inability to reach `git.nyan404.ru:443` still requires repair on the selected runner host.
- The local image is currently `belki-calculator:test`; the CI target is now `$DOCKER_REGISTRY/belki:latest`.
- GitLab CI runs `python -m compileall -q app tests` and `python -m unittest discover -s tests -q` in a dedicated `test` stage before build/deploy. The job explicitly clears `BELKI_DATABASE_URL` and uses `/tmp/belki-test-identities.sqlite3`, preventing unit tests from reaching the Kubernetes PostgreSQL service. Local validation was performed with the same tests, JavaScript syntax check, a local browser/API smoke test, and container health/API smoke.
- `/belki` is the single public workspace: its “Отчёты” and “Заявки” tabs, screenshot uploads, and the legacy `/applications` direct route require no password. `/admin` is the only password-protected surface.
- The VK dialog layer is covered by tests for step-by-step entry, bulk detection, clarification, confirmation, and cancellation.
- Bulk input accepts a natural one-line format without pipes, e.g. `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140`; the web form calls `/api/inspect-bulk` and fills recognized fields.
- Training and inspection have the same stepwise/bulk flow. Character identity can be resolved through `/api/resolve-identity` and the persistent SQLite directory; missing pairs produce an explicit prompt instead of guessed data.
- Character name/ID pairs are persisted automatically in the SQLite file from `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`); the database is local runtime data and ignored by Git.
- The VK dialog onboards each author once, stores their profile by `from_id`, greets them by name, and keeps the profile in the same SQLite database across bot restarts.
- Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp.
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. The bot mirrors each photo through image-hosting-web (default API `https://nyan.nyan404.ru`, overridable with `BELKI_IMAGE_HOST_API_URL`) and stores `mirror_url`; Google Sheets export remains deferred.
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI.
- `/admin` exchanges `BELKI_ADMIN_PASSWORD` for a server-memory `HttpOnly`, `SameSite=Lax` session cookie. The page restores that session after a refresh; it does not persist the password in browser storage. Authenticated browsers connect to `/api/admin/updates` over WebSocket and receive a `refresh` event every 25 seconds, which reloads report and application data. The cwshed Nginx `/api/` proxy upgrades WebSocket connections.
- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. The “Заявки” tab within `/belki` and `/applications` are public and use the upload endpoint; `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one.
- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`; its context keyboard drives every selectable application branch, while users type only free-form values. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient.
- Google Sheets export is pre-wired but disabled by `BELKI_GOOGLE_EXPORT_ENABLED=0`. `ApplicationStore` records `application_created` and `application_accepted` snapshots in the PostgreSQL `belki_application_export_events` or SQLite `application_export_events` outbox. `GoogleSheetsExportService` sends FIFO JSON events only to an explicitly configured Google Apps Script Web App URL, retains failed events for retry, and is polled by the bot every 15 seconds when enabled.
- The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API.
- 2026-10-07: admin report history defaults to the calendar current month (`current_month`), with older reports still available through the existing period/date controls. Each report has a persisted `entered` flag in PostgreSQL/SQLite; the admin table exposes an accessible checkbox in the leftmost column, adds a checkmark, and dims entered rows. `PATCH /api/admin/calculations/{id}/entered` updates the flag without changing sort order.
- 2026-10-03: public calculator and `/admin` share an autumn visual layer: warm paper/ground tokens, amber-brown accents, subtle radial atmosphere, and seven CSS leaves with staggered fall motion. Leaves are decorative (`aria-hidden`, pointer-events disabled), stay behind content, and become static/faint under `prefers-reduced-motion`; no image or runtime dependency was added.
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
- Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace.
- The previously inspected `stage-zone-runner` at `10.3.1.236` is not the runner used by the current pipeline. Runner `#2` (`Ryzen-builder`) at `10.3.1.168` is a privileged Docker executor and supports the DinD service used by `.gitlab-ci.yml`.
- 2026-08-16 `prevent-eol` check: `python:3.12-slim` is currently maintained through 2028-10-31; Docker `29.6.1-cli` was `unknown` to the EOL catalog (no finding). Docker/CI references remain tag-pinned rather than digest-pinned.
## Change Log
- 2026-09-01: converted the supplied 1.5 MiB visual Krylan memo into a structured, AI-friendly Markdown wiki. Preserved operational rules, schedules, templates, score/reward policy, incident playbooks, and source links; omitted redundant embedded image payloads.
- 2026-08-25: made the active `/sudoku` game screen viewport-bound on phones. The board and keypad scale to the available dynamic viewport; the save/new/user actions are fixed above the safe area, avoiding vertical document scrolling. Added `sudoku.webmanifest` and `sudoku-sw.js` for standalone installation, with network-first navigation so deploys do not become stuck on a cached shell.
- 2026-08-25: added an in-app `/sudoku` install action. Android uses a saved `beforeinstallprompt` event after a tap; iOS/iPadOS displays explicit Safari add-to-home-screen instructions because that event is not supported there.
- 2026-08-25: added `/sudoku`: a standalone mobile-first game with nickname-based cross-device resume, server-side answer keys, automatic save, new-board generation, and four ranked difficulty presets. `app/sudoku.py` stores `sudoku_games` in the same production PostgreSQL database as Belki, or `SUDOKU_DB` SQLite locally. The API returns no solution data; it validates clues and Sudoku constraints before saving.
- 2026-08-25: added `/sudoku` and `/sudoku/` gateway proxies in `nginx.conf`. The final gateway image copies this configuration after its Nginx base, so routing changes are delivered by the standard CI build without requiring a separate base-image release.
- 2026-08-25: added `dokusan==0.1.0` as the explicitly selected Sudoku generator/solver. It is GPL-3.0-only and Alpha/last released in 2023; the image's distribution obligations and upstream source are recorded in `NOTICE` and `README.md`. The lifecycle check found the pinned PyPI release available; that is not a security assessment.
- 2026-06-27: updated the Docker CI image to `docker:29.6.1-cli` and aligned the pipeline to `docker:dind` with `DOCKER_HOST=tcp://docker:2375`.
- 2026-06-27: verified the working runner on `docker-03.homelab.local` and confirmed `docker:29.6.1-dind` is reachable from the job network.
- 2026-08-16: added the Belki calculator domain, report templates, local web form, VK Long Poll adapter, and draft k3s manifests. Deployment remains intentionally deferred.
- 2026-08-16: made bulk entry conversational and separator-free; added API/web inspection and clarification flow.
- 2026-08-16: rewrote VK help, welcome, and web hints as a concise neutral FAQ; command behavior is unchanged.
- 2026-08-16: added the calculator/VK links to the CatWar home page and deployed the calculator stack to k3s; MetalLB assigned `10.12.0.212`.
- 2026-08-16: added GitLab build/deploy stages, namespace-scoped `gitlab-deploy` RBAC, and the ignored local variables handoff `.gitlab.variables.env`.
- 2026-08-16: switched the image build back to explicit aliased DinD after confirming runner `#2` has no host socket but can start `docker:29.6.1-dind` successfully.
- 2026-08-16: replaced the unavailable `bitnami/kubectl:1.34` CI image with `alpine/k8s:1.36.2`, which matches the cluster minor version and includes the shell required by GitLab Runner.
- 2026-08-16: corrected coaching payout direction for non-self-sufficient kittens. The escort receives the 1-per-5-minutes base rate or 1.5x for non-self-sufficient ЛУ; kitten points are not reported. Added a 30-minute regression case.
- 2026-08-16: adopted `2026-08-16-krylany-calculator-rules.md`: Krylan is the Belka/escort role, kittens always receive 1 point per 5 minutes, non-self-sufficient ЛУ multiplies escort points by 1.5, and ZU forces self-sufficient calculation.
- 2026-08-17: aligned `web/calculator.html` status controls with the VK bot and shared domain: LU allows at most one non-self-sufficient kitten, while ZU forces all kittens to self-sufficient; extra-kitten status controls are synchronized and validated before submission.
- 2026-08-17: web-selected screenshots are sent through `/api/web/upload` to `BELKI_IMAGE_HOST_API_URL` (production API `https://nyan.nyan404.ru`, viewer `https://img.nyan404.ru`) and persisted as report attachments. The image-host API requires an explicit Belki `User-Agent`; the default Python `urllib` header is rejected with HTTP 403.
- 2026-08-21: added structured community applications for feathers, kitten, flying-squirrel, and curator roles across VK, `/applications`, and the top-level `/admin` "Заявки" tab; acceptance is a status transition, not a generated forum post.
- 2026-08-21: added a disabled durable Google Sheets export outbox for application-created and application-accepted events; no external request is attempted until an approved Apps Script URL and `BELKI_GOOGLE_EXPORT_ENABLED=1` are configured.
- 2026-08-25: the optional Google Sheets export considers a configured endpoint ready only when it is a valid HTTPS URL, preventing its optional bearer token from crossing plaintext HTTP.
- 2026-08-25: fixed separator-free bulk parsing around time ranges, scoped web quick input to coaching, changed web inspection resources to `+N name`, corrected Russian inspection-count grammar, enabled VK image mirroring fallback, and added the standalone goal calculator mode/API.
- 2026-08-25: added the goal calculator to the VK menu as `/цель` and `/калькулятор`; the bot now runs the same goal calculation interactively with step prompts, choice buttons, and confirmation without report attachments.
- 2026-08-25: hardened the public goal calculator: point values must be finite, one session is limited to 1–1440 minutes, and one calculation to 1–50 kittens. The same validation is applied by the domain, JSON API, and VK dialogue, with regression tests for `NaN`, infinity, and excessive values.
- 2026-08-25: added the separate `points` calculator mode for earned points. It reuses the domain formulas without report identities or attachments; web and VK cover coaching, training, and inspections, with coaching results split between curator and up to three kittens.
- 2026-08-25: CI deployment validates PostgreSQL by ready pod rather than deployment rollout status. PostgreSQL is applied for desired-state reconciliation but its image/template is not replaced by application releases; web, bot, and gateway retain rollout checks.
- 2026-08-25: hardened public JSON and screenshot uploads. The web handler caps encoded JSON at 20 MiB before parsing, decodes at most 15 MiB of image bytes, accepts only PNG/JPEG/WebP signatures, rejects MIME mismatches, and strips path components from upload names. The public UI advertises the same supported formats.
- 2026-08-25: removed unused public web-profile endpoints and made `/api/resolve-identity` stateless for submitted pairs. A browser can fill its current inspection form, but cannot overwrite the persistent identity directory shared with VK users.
- 2026-08-25: persistent identity and profile pairs now require a non-empty name up to 100 characters and a positive integer ID. VK input and public identity lookup reject zero, negative, and boolean IDs before lookup or persistence.
- 2026-08-25: web calculations and applications now accept attachment URLs only when the same web process received them from the image-host upload endpoint. This prevents public JSON from planting arbitrary browser-fetchable URLs in the admin interface; the in-memory authorization is capped at 1000 URLs and expires after 30 minutes, matching the active upload-and-submit flow.
- 2026-08-25: VK image mirroring checks the advertised byte length and reads at most 15 MiB plus a one-byte sentinel before uploading. Oversized upstream photos no longer allocate unbounded memory in the bot process.
- 2026-08-25: VK photo mirroring also verifies PNG/JPEG/WebP byte signatures and derives the upload MIME type and extension from those bytes, never from an upstream HTTP header.
- 2026-08-25: `BelkiHTTPServer` supersedes the unbounded standard threaded server. It rejects oversized declared JSON before reading, times out a slow client after 15 seconds, and serves at most 32 concurrent connections.
- 2026-08-25: long-lived authenticated admin refresh WebSockets now have a separate eight-connection pool, so they cannot consume all 32 request workers; additional connections receive an explicit temporary-unavailable response.
- 2026-08-25: application validation now bounds names, attachment and feather rows, and descriptive text for both web and VK submissions. Stored attachment and review links must be HTTPS; the optional profile link is restricted to a real VK host.
- 2026-08-25: application numeric fields explicitly reject JSON booleans, which Python would otherwise coerce to `1` or `0`.
- 2026-08-25: admin history sorting now tolerates legacy records whose IDs were stored as strings, preserving numeric order for valid IDs instead of failing the complete history view.
- 2026-08-25: coaching sessions now validate a real calendar date in `ДД.ММ` form before any calculation or persistence; free-form dates remain accepted after parser normalization.
- 2026-08-25: coaching and training reports reject a repeated participant ID, including an escort submitted as their own kitten, so duplicate input cannot inflate a result.
- 2026-08-25: direct domain calls with non-text participant names now return the same clear validation errors as API and VK input, rather than an implementation-level attribute error.
- 2026-08-25: corrected Russian grammatical agreement in user-facing ID validation messages (`ID … должен быть`), including shared application and API helpers.
- 2026-08-25: one-line VK/web recognition now gives explicit role labels priority over position. `сопровождающий`/`наставник`/`учитель` identify the escort, while `ученик`/`котёнок`/`бельчонок`/`подопечный` identify the ward; unlabeled pairs retain the original order-based fallback.
- 2026-08-25: a self-sufficiency marker directly beside a labelled ward now belongs to that ward, so one natural line can describe different statuses for several kittens.
- 2026-08-25: corrected Russian UX copy in the VK help and attachment flow; the web identity hint now accurately says that a manually completed pair applies only to the current calculation.
- 2026-08-25: natural input normalizes Unicode spaces, dash variants, `ID`/`№` prefixes, spaced IDs, common date/time separators, and close role-label typos before extracting structured fields. Natasha was evaluated for Russian NER through Context7 but not added: game nicknames are better anchored by user-provided IDs and local role context than a generic person model.
- 2026-08-25: impossible status combinations discovered in free text (for example, non-self-sufficient ЗУ) now remain a repairable clarification in the dialogue instead of raising out of the VK handler.
- 2026-08-25: shared domain limits now bound public calculation fan-out: at most 50 coaching kittens, 100 inspection resource rows, 100000 inspections, and 100000 units of one resource. API and VK reject oversized kitten lists before calculation.
- 2026-08-25: nested public API values now use the same strict numeric conversion as top-level fields: booleans cannot become IDs or amounts, malformed resources are rejected, and resource rows are bounded before conversion.
- 2026-08-25: report copy now uses a plural construction for several kittens, normative `провёл(-ла)` for lessons, and a readable empty-resource line instead of a standalone `0`.
- 2026-08-25: free-form inspection parsing now distinguishes a labelled count (or a count immediately after the place) from date fragments and character IDs; it also understands explicit character labels and both `+N ресурс` and legacy `ресурс=N` loot notation.
- 2026-08-25: the explicit `/осмотр` command now accepts both natural orders for its first fields: `дупло 6` and `6 дупло`.
- 2026-08-25: the legacy `/applications` page now disables inactive type-specific controls, matching the embedded `/belki` form and preventing hidden previously selected files from being uploaded after a type switch.
- 2026-08-25: explicit `/лу` and `/зу` commands accept a time range with a dash and written Russian dates in their schedule segment, while still requiring exactly two valid clock values.
- 2026-08-25: free-form coaching input additionally normalizes Russian written month names and common abbreviations (for example, `24 августа` and `1-го сент`) into the existing `ДД.ММ` date field.
- 2026-08-25: `/api/admin/auth` now permits five password attempts per source in a rolling 15-minute window and clears that local budget after a successful sign-in. Edge rate limiting and TLS remain required deployment controls.
- 2026-08-25: server-memory admin sessions now expire after 12 hours and are capped at 100 active tokens; the browser cookie carries the same maximum age.
- 2026-08-25: the deploy job waits for `deployment/belki-postgres` to become `Available`, rather than waiting for every Pod with the shared PostgreSQL label. Historical ReplicaSet Pods can remain during cleanup and must not fail a release after the current database replica is ready.
- 2026-08-25: coaching reports allow an independence status for every kitten in both ЛУ and ЗУ. Natural input attaches `сам`/`не сам` written after a participant ID to that participant, and web ID fields use numeric-text input instead of spinner controls.
- 2026-08-25: the earned-points calculator groups coaching start and end times in one responsive time-range row.
- 2026-09-01: authenticated `/admin` report and application views share named (all/year/month/week/day/12–1 h) and explicit date-range filters with their XLSX links. `app/belki/admin_filters.py` is the single UTC-boundary parser; `xlsx_export.py` writes a styled one-sheet workbook with typed dates, column filters, and a frozen header.
- 2026-09-01: web-facing timestamps and calendar ranges use UTC+3. The database still stores UTC moments; `WEB_TIMEZONE` converts visible admin/XLSX dates, while date-only filters are converted from UTC+3 boundaries before querying records.
- 2026-09-01: the public report form now requires screenshots only for inspections (and validates that rule server-side). Web lessons collect a `ДД.ММ` date and generate the dated `#урок` format; bot-only forms such as `#выход` and `#помощь` remain outside the public calculator.
- 2026-08-25: web reports use a two-step flow: `/api/calculate` prepares the message without saving it, then `/api/reports` stores it only after the user explicitly selects «Отправить отчёт». The UI disables that action while it is in progress and after success.
- 2026-08-25: shared two-column form grids align controls at the start of their row, preventing a date field with its helper button from stretching the adjacent skill select.
- 2026-08-25: mobile adaptation is a required acceptance criterion for all frontend changes; validate narrow-width layout, touch usability, focus/error states, and absence of horizontal overflow alongside desktop rendering.
- 2026-08-25: `/belki` now applies a dedicated narrow-width layout: single-column forms and application types, full-width actions, compact panels/dialogs, 16px form text to avoid mobile browser zoom, and responsive tabs without horizontal overflow.
- 2026-08-25: removed unreferenced root-level legacy BBCode copies `belki.md`, `belki2.md`, and `belkifix.md`; the first two were byte-identical and the third differed only by a closing BBCode tag. They were neither served nor referenced by the calculator, bot, or documentation.
- 2026-09-21: `InspectionResult` now keeps the base inspection score and per-resource score entries alongside the total. The `/admin` report table renders these values in a dedicated `Баллы` column; older history rows still show their stored total when detailed fields are absent. The public report message remains unchanged.
- 2026-09-26: inspection scoring now has an explicit `EDIBLE_CATCHES` catalogue in `app/belki/domain.py`; `Ящерица` and `Летучая мышь` are documented as one-point catches and covered by regression tests.
- 2026-10-10: VK input migrated from Long Poll to Callback API. `app/belki/vk_bot.py` now serves `/api/vk/callback` on port 8081, validates the callback secret and group ID, handles `message_new`/`message_event`, and keeps scheduler/notifier threads in the bot process. `vk_callback_events` deduplicates callback event IDs for seven days and releases failed claims for VK retry. `deploy/k8s/*` adds the `belki-bot` ClusterIP Service and callback probes; `nginx.conf` routes only the exact callback path to the bot while other `/api/` requests remain on `belki-web`. Public registration and live VK confirmation are still a deployment-stage action.
- 2026-10-13: added persistent cat-name changes. `IdentityDirectory.rename_existing()` updates the existing `identities` row, all `profiles` rows for that character, and both in-memory indexes; unknown IDs are rejected. VK exposes the separate `Изменить имя кота` menu flow, while `/belki` adds the `Имя кота` tab backed by `/api/rename-identity` after a current-name lookup through `/api/resolve-identity`.
- 2026-10-18: sent-report history reuses the calculations table. VK `Мои отчёты` filters by callback `actor_id` and `source='vk'`; `/belki` adds `Отчёты по ID кота`, backed by `GET /api/reports?character_id=...`, which searches participant IDs across coaching, training, and inspection rows from all sources. The public response returns the latest 100 reports and excludes `actor_id`; it exposes only local `/api/images/<id>` proxy paths for stored screenshots.
- 2026-10-18: edited Russian copy in `web/calculator.html`, `web/applications.html`, `web/admin.html`, `web/index.html`, and the VK/identity API responses. Game rules, commands, calculation logic, stored data, and report templates are unchanged. Humanizer-ru scored the selected before/after editing fragments 92/100 and 97/100; the remaining «напоминает о» hit is a false positive inside «напоминание об еженедельном отчёте». The schedule examples 09:00 and 18:30 already existed in the adjacent input placeholder. Validation ran locally because no remote test-zone MCP was exposed: 111 focused unittest cases, Python AST/syntax comparison, JavaScript syntax checks, and browser inspection at mobile/desktop widths. Temporary scanner dependencies and browser artifacts were kept outside the repository; no deployment or push.
# Обновление 2026-08-16: несколько котят
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
- 2026-09-06: добавлен `app/belki/vk_scheduler.py` — реестр VK-бесед, шаблоны, ежедневные/недельные расписания и уникальные delivery-attempts; scheduler запускается daemon-потоком `belki-bot`, админские API доступны под `/api/admin/vk/*`.
- Browser validation used a temporary static server on 127.0.0.1:8765; the admin page used empty mocked API responses to inspect copy without production credentials or writes. This validates layout and navigation, not a live VK delivery or production session.
### Production weather validation — 2026-10-18, 20:19 MSK
Read-only validation after the operator deployed `98182c17`: `belki-web`, `belki-bot`, and `cwshed` were 1/1 Ready with zero restarts; namespace `belki` had no Warning events. Web/bot imageID was `sha256:96cbd18f5e4ab601810e9c3920e91973948ce9921232be50c6933cc964cbdd41`; gateway imageID was `sha256:3768ec6de05d0882b98726c5ef063e20f40861d8cba50cb26e1fc0b07c6df1d2`. Public `https://cat.nyan404.ru/api/weather/ulli` returned leaves/intensity 1/wind 3 m/s, matching the live ULLI 17:00Z METAR (`34003MPS CAVOK`). Public effect CSS/JS matched local files byte for byte. Browser checks of `/belki` and `/admin` confirmed seven animated leaves, pointer-transparent decoration, mobile layout and reduced-motion support, with no console errors. The last 140 gateway log lines had no 5xx or error markers; web logs were empty. Actual rain/snow were not present during this production check; their rendering was previously fixture-tested. No cluster configuration or application code changed; the temporary SSH API tunnel and browser session were closed after inspection.