86 lines
18 KiB
Markdown
86 lines
18 KiB
Markdown
# Structure and Data
|
||
|
||
## 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.
|
||
- [`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.
|
||
|
||
## Runtime / Deployment
|
||
- GitLab CI runs the build job.
|
||
- 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 prebuilt and stored in the private registry: `reg.nyan404.ru/cwshed-clone/belki-base:py312-d6c42c4497ce` contains Python 3.12, `pip 26.2.1`, and the current `requirements.txt`; `reg.nyan404.ru/cwshed/cwshed-base:nginx-c2431df29ccc` contains Nginx plus `nginx.conf`. Adding, removing, or updating a runtime dependency requires rebuilding/pushing and retagging the matching base image before CI; ordinary CI builds only copy application or static files.
|
||
- 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.
|
||
- 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-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: 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: 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: 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: `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: 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: 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: 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: 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-16: несколько котят
|
||
|
||
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|