chore: add runtime configuration and deployment docs
This commit is contained in:
1 parent
c86d077f9f
commit
4dab6e8624
13 files changed
+430
-13
No files matched your search
@@ -0,0 +1,9 @@
|
|||||||
|
# Copy to .env and fill in the test community credentials.
|
||||||
|
VK_GROUP_TOKEN=
|
||||||
|
VK_GROUP_ID=
|
||||||
|
VK_API_VERSION=5.199
|
||||||
|
|
||||||
|
# PostgreSQL is the production history store. Leave empty for local SQLite fallback.
|
||||||
|
BELKI_DATABASE_URL=postgresql://belki:change-me@postgres:5432/belki
|
||||||
|
# SQLite fallback/runtime identity database when BELKI_DATABASE_URL is empty.
|
||||||
|
BELKI_IDENTITIES_DB=data/belki.sqlite3
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
# Python bytecode and local interpreter caches
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
.python-version
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
env/
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
data/*.sqlite3
|
||||||
|
data/*.db
|
||||||
|
|
||||||
|
# Test, type-checker and coverage output
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
htmlcov/
|
||||||
|
|
||||||
|
# Local tooling and OS noise
|
||||||
|
.DS_Store
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
+1
-1
@@ -2,7 +2,7 @@ stages:
|
|||||||
- build
|
- build
|
||||||
|
|
||||||
variables:
|
variables:
|
||||||
DOCKER_IMAGE: $DOCKER_REGISTRY/cwshed:latest
|
DOCKER_IMAGE: $DOCKER_REGISTRY/belki:latest
|
||||||
DOCKER_HOST: tcp://docker:2375
|
DOCKER_HOST: tcp://docker:2375
|
||||||
build:
|
build:
|
||||||
stage: build
|
stage: build
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
# AGENTS.md
|
# AGENTS.md
|
||||||
|
|
||||||
## Scope
|
## Scope
|
||||||
- This repository packages a static web app with Nginx and a GitLab CI pipeline.
|
- This repository contains the Belki calculator/VK bot plus legacy CatWar userscript assets.
|
||||||
- Key files: [`.gitlab-ci.yml`](./.gitlab-ci.yml), [`Dockerfile`](./Dockerfile), [`nginx.conf`](./nginx.conf), and [`web/`](./web).
|
- Key files: [`app/`](./app), [`web/calculator.html`](./web/calculator.html), [`Dockerfile`](./Dockerfile), and [`deploy/k8s/`](./deploy/k8s).
|
||||||
|
|
||||||
## Working Rules
|
## Working Rules
|
||||||
- Keep changes minimal and focused on the CI file unless new project files are intentionally being added.
|
- Keep the calculation domain independent from HTTP, VK, and Kubernetes.
|
||||||
- Prefer `docker:dind` for this project unless the target runner is explicitly pinned and known to expose `/var/run/docker.sock`.
|
- Keep VK tokens and group IDs out of the repository; use environment variables or Kubernetes Secrets.
|
||||||
- If the runner setup changes, update the CI file and this document together.
|
- Do not apply `deploy/k8s/` until the bot commands, report wording, registry image name, service exposure, and Secret handoff are explicitly confirmed.
|
||||||
|
- Prefer `docker:dind` for CI unless the target runner is explicitly pinned and known to expose `/var/run/docker.sock`.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
- For CI-only changes, prefer a targeted YAML parse and a diff review.
|
- For CI-only changes, prefer a targeted YAML parse and a diff review.
|
||||||
- For image/runtime changes, check the `Dockerfile`, Nginx config, and the CI job together.
|
- For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together.
|
||||||
|
- For k3s changes, validate YAML and current cluster inventory first; deployment is currently deferred.
|
||||||
- Do not add unnecessary local build artifacts or temporary files to the repository.
|
- Do not add unnecessary local build artifacts or temporary files to the repository.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|||||||
@@ -1,8 +1,20 @@
|
|||||||
# MEMORY
|
# MEMORY
|
||||||
|
|
||||||
- The repository packages a static site under `web/` with an Nginx-based `Dockerfile`.
|
- The repository packages a static site under `web/` with an Nginx-based `Dockerfile`.
|
||||||
- The GitLab pipeline builds and pushes `cwshed:latest` from `.gitlab-ci.yml`.
|
- The GitLab pipeline builds and pushes the Belki image from `.gitlab-ci.yml`; current target is `$DOCKER_REGISTRY/belki:latest`.
|
||||||
- Docker builds are expected to run through `docker:dind` with `DOCKER_HOST=tcp://docker:2375` and `DOCKER_TLS_CERTDIR=""`.
|
- Docker builds are expected to run through `docker:dind` with `DOCKER_HOST=tcp://docker:2375` and `DOCKER_TLS_CERTDIR=""`.
|
||||||
- The build job now waits for `docker info` before running `docker login` and `docker build` because `docker:29.6.1-dind` can take ~20 seconds to finish initialization on `docker-03`.
|
- The build job now waits for `docker info` before running `docker login` and `docker build` because `docker:29.6.1-dind` can take ~20 seconds to finish initialization on `docker-03`.
|
||||||
- Current CI image: `docker:29.6.1-cli`.
|
- Current CI image: `docker:29.6.1-cli`.
|
||||||
- The runner host at `root@10.3.1.236` is `docker-03.homelab.local`; its GitLab Runner is `stage-zone-runner` and successfully reaches `docker:29.6.1-dind`.
|
- The runner host at `root@10.3.1.236` is `docker-03.homelab.local`; its GitLab Runner is `stage-zone-runner` and successfully reaches `docker:29.6.1-dind`.
|
||||||
|
- 2026-08-16: the repository now contains a local-only Belki calculator MVP under `app/` with a standard-library Python HTTP service, shared calculation/report domain, browser form at `/`, and VK Bots Long Poll adapter.
|
||||||
|
- Confirmed local acceptance: 28 unittest cases pass; local browser smoke generated a 20-minute ЛУ report; `belki-calculator:test` built and its `/health`, `/api/calculate`, `/api/inspect-bulk`, and `/api/resolve-identity` endpoints responded.
|
||||||
|
- Draft k3s manifests live under `deploy/k8s/` but have not been applied. No VK token, group ID, service IP, or cluster Secret is stored in the repository.
|
||||||
|
- VK input is now conversational: `BelkiDialog` stores per-peer state, supports `/лу`/`/зу` step-by-step prompts, detects bulk messages, asks for missing skill/status or confirmation, and clears with `/отмена`.
|
||||||
|
- The preferred bulk input is a natural line without pipes, such as `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140`; `/api/inspect-bulk` and the web form fill recognized fields and show only missing questions.
|
||||||
|
- `/урок` and `/осмотр` use the same dialog; character name/ID may be entered separately and resolved from the persistent SQLite directory at `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`), otherwise the dialog asks for the missing half and remembers the completed pair.
|
||||||
|
- `.gitignore` now excludes Python bytecode/cache and local test/editor artifacts; generated `__pycache__` directories were removed from the working tree.
|
||||||
|
- `prevent-eol` checked `Dockerfile` and `.gitlab-ci.yml`: Python 3.12 is maintained through 2028-10-31; Docker 29.6.1 was unknown to the lifecycle catalog, with no EOL finding. Images are not digest-pinned yet.
|
||||||
|
- VK onboarding asks first-time authors for `Имя [ID]`, stores the profile by `from_id` in SQLite, greets by name on later conversations, and accepts `сам`/`несам` as independence shortcuts.
|
||||||
|
- VK `/help` is a neutral FAQ: it explains step-by-step entry, complete commands, separator-free one-line input, confirmation, screenshots, and `/отмена` without audience-specific wording.
|
||||||
|
- Confirmed calculations are persisted through `BELKI_DATABASE_URL` by `app/belki/history.py`; PostgreSQL is the intended production store and SQLite is only a local fallback.
|
||||||
|
- The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas.
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: belki-web
|
||||||
|
namespace: belki
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: belki-web
|
||||||
|
app.kubernetes.io/part-of: belki-calculator
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app.kubernetes.io/name: belki-web
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: belki-web
|
||||||
|
app.kubernetes.io/part-of: belki-calculator
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: web
|
||||||
|
image: reg.nyan404.ru/cwshed-clone/belki:latest
|
||||||
|
imagePullPolicy: Always
|
||||||
|
command: ["python", "-m", "app.main"]
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
containerPort: 8080
|
||||||
|
env:
|
||||||
|
- name: BELKI_PORT
|
||||||
|
value: "8080"
|
||||||
|
- name: BELKI_DATABASE_URL
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: belki-vk
|
||||||
|
key: BELKI_DATABASE_URL
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: http
|
||||||
|
initialDelaySeconds: 2
|
||||||
|
periodSeconds: 10
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: http
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
periodSeconds: 20
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 10001
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: belki-web
|
||||||
|
namespace: belki
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/part-of: belki-calculator
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
selector:
|
||||||
|
app.kubernetes.io/name: belki-web
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
port: 8080
|
||||||
|
targetPort: http
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: belki-bot
|
||||||
|
namespace: belki
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: belki-bot
|
||||||
|
app.kubernetes.io/part-of: belki-calculator
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app.kubernetes.io/name: belki-bot
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: belki-bot
|
||||||
|
app.kubernetes.io/part-of: belki-calculator
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: bot
|
||||||
|
image: reg.nyan404.ru/cwshed-clone/belki:latest
|
||||||
|
imagePullPolicy: Always
|
||||||
|
command: ["python", "-m", "app.belki.vk_bot"]
|
||||||
|
env:
|
||||||
|
- name: VK_GROUP_TOKEN
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: belki-vk
|
||||||
|
key: VK_GROUP_TOKEN
|
||||||
|
- name: VK_GROUP_ID
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: belki-vk
|
||||||
|
key: VK_GROUP_ID
|
||||||
|
- name: VK_API_VERSION
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: belki-vk
|
||||||
|
key: VK_API_VERSION
|
||||||
|
optional: true
|
||||||
|
- name: BELKI_DATABASE_URL
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: belki-vk
|
||||||
|
key: BELKI_DATABASE_URL
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 10001
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: Namespace
|
||||||
|
metadata:
|
||||||
|
name: belki
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/part-of: belki-calculator
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: belki-vk
|
||||||
|
namespace: belki
|
||||||
|
type: Opaque
|
||||||
|
stringData:
|
||||||
|
VK_GROUP_TOKEN: replace-out-of-band
|
||||||
|
VK_GROUP_ID: replace-out-of-band
|
||||||
|
VK_API_VERSION: "5.199"
|
||||||
|
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Roadmap
|
||||||
|
|
||||||
|
- [ ] M1: Калькулятор баллов и генератор сообщений для прокачки ЛУ/ЗУ
|
||||||
|
- [ ] M2: Форма и генератор отчётов по осмотрам
|
||||||
|
- [ ] M3: VK-бот, веб-сайт и k3s-деплой с общей логикой расчётов
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
topology: single-module
|
||||||
|
change-set: belki-calculator
|
||||||
|
coordinator: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
repos: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
module-plans: this file
|
||||||
|
integration-task: T6
|
||||||
|
|
||||||
|
goal: Реализовать отдельный калькулятор белок, веб-форму, VK Long Poll adapter и k3s-ready контейнер.
|
||||||
|
spec: docs/staging/specs/2026-08-16-belki-calculator.md
|
||||||
|
|
||||||
|
- [x] T1: Расчётное ядро и строковые шаблоны
|
||||||
|
repository: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
module: app/belki
|
||||||
|
files: app/belki/domain.py, app/belki/reports.py, tests/test_belki.py
|
||||||
|
acceptance: python -m unittest discover -s tests -v
|
||||||
|
spec: docs/staging/specs/2026-08-16-belki-calculator.md#calculation
|
||||||
|
|
||||||
|
- [x] T2: HTTP API и веб-форма
|
||||||
|
repository: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
module: app/web
|
||||||
|
files: app/belki/api.py, app/main.py, web/calculator.html, tests/test_api.py
|
||||||
|
acceptance: python -m unittest discover -s tests -v и ручная проверка GET / и POST /api/calculate
|
||||||
|
spec: docs/staging/specs/2026-08-16-belki-calculator.md#web-contract
|
||||||
|
|
||||||
|
- [x] T3: VK Bots Long Poll adapter
|
||||||
|
repository: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
module: app/vk
|
||||||
|
files: app/belki/vk_bot.py, tests/test_vk_bot.py
|
||||||
|
acceptance: python -m unittest discover -s tests -v; тесты покрывают пошаговый диалог, bulk-детекцию, уточнение и подтверждение и не используют реальный VK-токен
|
||||||
|
spec: docs/staging/specs/2026-08-16-belki-calculator.md#vk-contract
|
||||||
|
|
||||||
|
- [x] T4: Runtime packaging and CI
|
||||||
|
repository: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
module: runtime
|
||||||
|
files: app/requirements.txt, Dockerfile, .dockerignore, .gitlab-ci.yml, Makefile, README.md, CHANGELOG.md
|
||||||
|
acceptance: docker build -t belki-calculator:test . и запуск контейнера с health endpoint
|
||||||
|
spec: docs/staging/specs/2026-08-16-belki-calculator.md#convention
|
||||||
|
|
||||||
|
- [ ] T5: k3s manifests and runtime documentation
|
||||||
|
repository: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
module: deploy/k8s
|
||||||
|
files: deploy/k8s/namespace.yaml, deploy/k8s/app.yaml, structure_and_data.md, MEMORY.md, project_mind_map.md
|
||||||
|
acceptance: kubectl apply --dry-run=client -f deploy/k8s/ и проверка манифестов без секретных значений
|
||||||
|
spec: docs/staging/specs/2026-08-16-belki-calculator.md#vk-contract
|
||||||
|
|
||||||
|
- [ ] T6: Integration acceptance
|
||||||
|
repository: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
module: workspace
|
||||||
|
files: current workspace revision set
|
||||||
|
acceptance: полный unittest, сборка контейнера, HTTP smoke и проверка k3s YAML; результат записан в документации
|
||||||
|
spec: docs/staging/specs/2026-08-16-belki-calculator.md#acceptance
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
topology: single-module
|
||||||
|
change-set: belki-calculator
|
||||||
|
coordinator: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
repos: /Users/nyan404/Documents/Git New/cwshed-clone
|
||||||
|
milestone: M1 (see docs/ROADMAP.md)
|
||||||
|
|
||||||
|
# Бот и калькулятор для белок
|
||||||
|
|
||||||
|
## Contract
|
||||||
|
|
||||||
|
Сервис предоставляет одну общую предметную логику для веб-формы и VK-бота:
|
||||||
|
|
||||||
|
- расчёт баллов за один отдельный заход прокачки;
|
||||||
|
- генерацию текста отчёта для `ЛУ` (лазание) или `ЗУ` (зоркость);
|
||||||
|
- отдельный расчёт и текст для тренировки;
|
||||||
|
- расчёт и текст отчёта по осмотрам дупла/расщелины;
|
||||||
|
- валидацию времени, ID и обязательных полей до генерации сообщения.
|
||||||
|
|
||||||
|
Первый production-вариант принимает входные данные через веб-форму и через VK Bots Long Poll. Callback API и распознавание скриншотов не входят в M1.
|
||||||
|
|
||||||
|
## Calculation
|
||||||
|
|
||||||
|
`minutes = (end - start) mod 24h`, результатом является длительность одного захода в минутах. Переход через полночь разрешён. Отчёт относится только к одному заходу.
|
||||||
|
|
||||||
|
Базовые правила, подтверждённые формулами Google-таблицы и текущим описанием:
|
||||||
|
|
||||||
|
- 5 минут дают 1 балл сопровождающему/взрослому;
|
||||||
|
- 5 минут дают 2 балла котёнку;
|
||||||
|
- самостоятельный основной котёнок: сопровождающий получает `minutes / 5`;
|
||||||
|
- несамостоятельный основной котёнок: сопровождающий получает `minutes * 1.5 / 5`;
|
||||||
|
- каждый дополнительный несамостоятельный котёнок добавляет сопровождающему `minutes * 0.5 / 5`;
|
||||||
|
- самостоятельный дополнительный котёнок не добавляет баллов сопровождающему;
|
||||||
|
- котёнок получает `minutes / 5 * 2` согласно пользовательской разбалловке;
|
||||||
|
- тренировка не смешивается с прокачкой и даёт фиксированные 25 баллов отдельной записью.
|
||||||
|
|
||||||
|
Баллы не округляются в расчётном ядре. Форматирование отчёта использует компактное представление без лишних знаков после запятой; правило округления для дробных значений должно быть закреплено до M1 acceptance.
|
||||||
|
|
||||||
|
## Report formats
|
||||||
|
|
||||||
|
Основной формат прокачки:
|
||||||
|
|
||||||
|
```text
|
||||||
|
15.08 [ЛУ]
|
||||||
|
Время: 11:00–11:20 [20 минут]
|
||||||
|
Сопровождающий: Дикая Вишня [1604614]
|
||||||
|
Котёнок: Серолап [1617140]
|
||||||
|
Баллы белки: 4
|
||||||
|
Баллы бельчонка: 8
|
||||||
|
|
||||||
|
Не забудьте приложить скриншот Игровой с персонажем на Небесном Дубе/Тропе Смелости или лазалках, где видны время и дата начала и конца.
|
||||||
|
```
|
||||||
|
|
||||||
|
Для несамостоятельного котёнка добавляется напоминание приложить историю с подтверждением махинации. Скриншоты бот не принимает как доказательство и не анализирует автоматически.
|
||||||
|
|
||||||
|
Формат тренировки:
|
||||||
|
|
||||||
|
```text
|
||||||
|
#урок
|
||||||
|
Сопровождающий [ID] провёл(а) тренировку котёнка [ID].
|
||||||
|
Баллы: 25
|
||||||
|
```
|
||||||
|
|
||||||
|
Формат осмотра:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Имя персонажа [ID] осмотрел(а) дупло/расщелину N раз.
|
||||||
|
- 2 вьюнок, +1 паук
|
||||||
|
|
||||||
|
Не забудьте приложить скриншот истории и рта.
|
||||||
|
```
|
||||||
|
|
||||||
|
Для осмотра поддерживаются конкретные ресурсы с количеством добытого (`+`) и потерянного/отрицательного результата (`-`). Ничего или ядовитая дичь записывается как `0`. Съедобная дичь может быть объединена в одну категорию.
|
||||||
|
|
||||||
|
## VK contract
|
||||||
|
|
||||||
|
- VK-бот работает через Bots Long Poll API.
|
||||||
|
- Токен сообщества и `group_id` приходят только через окружение/Secret.
|
||||||
|
- Входящее событие нормализуется в общий command DTO: sender, peer, command, payload.
|
||||||
|
- Ответ отправляется через `messages.send` с `peer_id`, `message`, `random_id`, `access_token` и `v`.
|
||||||
|
- Команды должны быть пригодны для текстового чата: основной UX — `/лу` или `/зу` с вопросами по одному полю.
|
||||||
|
- Для быстрого ввода принимается обычная строка без `|` и скобок-разделителей; бот распознаёт дату, время, две пары «имя + ID», а затем спрашивает навык/статус, если их нет.
|
||||||
|
- Такой же bulk/step-by-step сценарий доступен для `/урок` и `/осмотр`; детектор сообщает, какой режим и какие поля он нашёл.
|
||||||
|
- Имя и ID персонажа в осмотре — отдельные интерактивные поля: разрешён ввод только одного значения. Опциональный справочник `BELKI_IDENTITIES_JSON` подставляет второе; если связка не найдена, UI/VK предлагают ввести недостающее значение и сохранить связь в текущем процессе.
|
||||||
|
- Старый pipe-формат сохраняется как совместимый вариант. Перед расчётом бот показывает распознанные данные и просит подтверждение; `/отмена` очищает состояние peer.
|
||||||
|
- Диалоговый слой хранит незавершённый сценарий отдельно для каждого `peer_id`.
|
||||||
|
- Пользователь может начать `/лу` или `/зу` без аргументов и заполнить дату, время, участников и самостоятельность по одному сообщению за раз.
|
||||||
|
- При вводе скопом бот детектирует команду, даты, время, имена и ID; пропущенные или неоднозначные поля уточняет, а перед расчётом показывает распознанную сводку и просит `да`/`нет`.
|
||||||
|
- `/отмена` очищает незавершённый сценарий.
|
||||||
|
- Ошибки VK, неизвестные команды и невалидные поля отвечают понятным сообщением без traceback и без раскрытия секретов.
|
||||||
|
|
||||||
|
## Web contract
|
||||||
|
|
||||||
|
Сайт и бот используют один расчётный модуль и одинаковые шаблоны. Веб-форма должна иметь минимум два режима: `Прокачка` и `Осмотры`, а для прокачки — переключатель `ЛУ`/`ЗУ` и признак самостоятельности котёнка.
|
||||||
|
|
||||||
|
## Invariants
|
||||||
|
|
||||||
|
- Отрицательная или нулевая длительность запрещена, кроме корректного перехода через полночь.
|
||||||
|
- Один отчёт никогда не объединяет несколько заходов.
|
||||||
|
- ID должны быть положительными целыми числами.
|
||||||
|
- Время должно быть в формате `HH:MM`, с ведущим нулём для минут.
|
||||||
|
- `ЛУ` и `ЗУ` меняют только тип/хэштег отчёта, а не формулу баллов.
|
||||||
|
- Скриншотные требования выводятся как напоминание и не считаются автоматически подтверждёнными.
|
||||||
|
- Токены VK не попадают в репозиторий, клиентский JS, логи или Docker image layers.
|
||||||
|
|
||||||
|
## Acceptance
|
||||||
|
|
||||||
|
- unit-тесты подтверждают обычный интервал, переход через полночь, 5/60 минут, самостоятельного и несамостоятельного котёнка, тренировку 25 баллов и валидацию ошибок;
|
||||||
|
- snapshot/строковые тесты подтверждают отдельные тексты для ЛУ, ЗУ, тренировки и осмотра;
|
||||||
|
- веб-форма вручную проверяется в браузере на тех же входных данных;
|
||||||
|
- VK adapter проверяется на нормализацию входного события и формирование `messages.send` без реального токена;
|
||||||
|
- контейнер собирается, запускается в k3s test namespace и отвечает health endpoint.
|
||||||
|
|
||||||
|
## Convention
|
||||||
|
|
||||||
|
- Простая модульная реализация без зависимости от старых userscript-файлов.
|
||||||
|
- Расчётное ядро не знает о VK, HTTP, HTML или Kubernetes.
|
||||||
|
- Runtime-конфигурация только через environment variables и Kubernetes Secret.
|
||||||
|
- Для первого сервиса предпочтителен один backend-процесс, который одновременно обслуживает HTTP и VK Long Poll.
|
||||||
|
- Данные справочника котят/ID должны быть редактируемыми отдельно от кода.
|
||||||
|
|
||||||
|
## Deferred
|
||||||
|
|
||||||
|
- название бота в UI и справке: «Беличья нора»; игровые роли «белка», «бельчонок», «мотылёк», «крылан» сохраняются в текстах отчётов;
|
||||||
|
- правило округления дробных баллов;
|
||||||
|
- точный набор VK-команд и кнопок;
|
||||||
|
- постоянное хранение истории отчётов и авторизация пользователей сайта;
|
||||||
|
- OCR/проверка скриншотов;
|
||||||
|
- перенос или удаление старых CatWar userscript-файлов;
|
||||||
|
- выделение отдельного репозитория/манифестов в `/Users/nyan404/Documents/Git New/k3s`.
|
||||||
|
|
||||||
|
## Working notes
|
||||||
|
|
||||||
|
- Google Sheets export подтверждает формулы `MOD(F6-F4,1)*24*60`, `G6/5` и коэффициенты самостоятельности. В старой таблице есть дополнительные колонки «надбавка за несамост», «кол-во людей», «баллы мотыльков» и «баллы крылана»; новая пользовательская форма должна явно назвать их по актуальной терминологии.
|
||||||
|
- Визуальный пример содержит поля начала/конца, числа/месяца, итоговых минут, баллов и данных сопровождающего/котёнка.
|
||||||
|
- Текущий репозиторий является статическим сайтом и не содержит backend runtime; реализация потребует нового приложения, Dockerfile/CI и k8s manifests.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Project mind map
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
repo[cwshed-clone / Belki]
|
||||||
|
repo --> domain[app/belki/domain.py\ncalculation rules]
|
||||||
|
repo --> reports[app/belki/reports.py\nmessage templates]
|
||||||
|
repo --> api[app/belki/api.py\nJSON adapter]
|
||||||
|
repo --> webapp[app/main.py + web/calculator.html\nlocal web form]
|
||||||
|
repo --> vk[app/belki/vk_bot.py\nVK Bots Long Poll]
|
||||||
|
domain --> api
|
||||||
|
reports --> api
|
||||||
|
api --> webapp
|
||||||
|
api --> vk
|
||||||
|
repo --> legacy[web/cw.js, CatWarMod.js\nlegacy userscripts]
|
||||||
|
repo --> tests[tests/\nunit and adapter tests]
|
||||||
|
repo --> k8s[deploy/k8s/\ndraft only]
|
||||||
|
k8s --> webpod[belki-web Deployment]
|
||||||
|
k8s --> botpod[belki-bot Deployment]
|
||||||
|
webpod --> service[ClusterIP belki-web]
|
||||||
|
botpod --> secret[belki-vk Secret\nout-of-band]
|
||||||
|
```
|
||||||
|
|
||||||
|
The current phase is local implementation and validation. The k3s branch of the map is intentionally not live.
|
||||||
+21
-5
@@ -1,11 +1,15 @@
|
|||||||
# Structure and Data
|
# Structure and Data
|
||||||
|
|
||||||
## Repository Layout
|
## Repository Layout
|
||||||
- [`.gitlab-ci.yml`](./.gitlab-ci.yml): single-stage GitLab pipeline that builds and pushes the `cwshed` Docker image.
|
- [`.gitlab-ci.yml`](./.gitlab-ci.yml): existing single-stage GitLab pipeline targeting the Belki image.
|
||||||
- [`Dockerfile`](./Dockerfile): Nginx-based runtime image that copies the static site into `/usr/share/nginx/html`.
|
- [`Dockerfile`](./Dockerfile): Python 3.12 runtime image for the calculator web service and shared static assets.
|
||||||
- [`nginx.conf`](./nginx.conf): custom Nginx config for serving the static app.
|
- [`app/`](./app): calculation domain, report templates, JSON API, HTTP server, and VK Bots Long Poll adapter.
|
||||||
- [`web/`](./web): static frontend assets shipped into the container.
|
- [`web/`](./web): calculator frontend plus legacy CatWar userscript assets.
|
||||||
|
- [`deploy/k8s/`](./deploy/k8s): not-yet-applied namespace, web/bot Deployments, ClusterIP Service, and Secret example.
|
||||||
|
- [`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.
|
- [`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.
|
- [`MEMORY.md`](./MEMORY.md): durable notes about the current CI/runtime decision.
|
||||||
|
|
||||||
## Runtime / Deployment
|
## Runtime / Deployment
|
||||||
@@ -13,9 +17,21 @@
|
|||||||
- The job builds through `docker:dind` with `DOCKER_HOST=tcp://docker:2375` and `DOCKER_TLS_CERTDIR=""`.
|
- The job builds through `docker:dind` with `DOCKER_HOST=tcp://docker:2375` and `DOCKER_TLS_CERTDIR=""`.
|
||||||
- The job waits for `docker info` to succeed before starting the build, because the daemon may need a few seconds to come up.
|
- The job waits for `docker info` to succeed before starting the build, because the daemon may need a few seconds to come up.
|
||||||
- The runner does not need the host Docker socket mounted for this repo.
|
- The runner does not need the host Docker socket mounted for this repo.
|
||||||
- The resulting image is `cwshed:latest` in `$DOCKER_REGISTRY`.
|
- The local image is currently `belki-calculator:test`; the CI target is now `$DOCKER_REGISTRY/belki:latest`.
|
||||||
|
- Local validation was performed with `python3 -m unittest discover -s tests -v` (28 tests), `compileall`, JavaScript syntax check, a local browser/API smoke test, and container health/API smoke.
|
||||||
|
- 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.
|
||||||
|
- No k3s deployment or cluster state change has been made. The SSH tunnel used for read-only service inventory was stopped.
|
||||||
- Remote runner host: `root@10.3.1.236` (`docker-03.homelab.local`), GitLab Runner `stage-zone-runner`, Docker executor, privileged, with `docker:29.6.1-dind` as the service image.
|
- Remote runner host: `root@10.3.1.236` (`docker-03.homelab.local`), GitLab Runner `stage-zone-runner`, Docker executor, privileged, with `docker:29.6.1-dind` as the service image.
|
||||||
|
- 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
|
## 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: 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-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.
|
||||||
Reference in new issue
Block a user