docs: add current Belki project map

This commit is contained in:
nyan404 committed 2026-08-25 03:43:52 +03:00
1 parent 586693dc72
commit 71fa4d0571
3 files changed
+109 -239

No files matched your search

+1
View File
@@ -39,6 +39,7 @@
- 2026-08-25: VK attachment mirroring has a strict 15 MiB transfer cap, including a Content-Length precheck and bounded read. - 2026-08-25: VK attachment mirroring has a strict 15 MiB transfer cap, including a Content-Length precheck and bounded read.
- 2026-08-25: the web service uses `BelkiHTTPServer` with 15-second socket reads and a 32-request semaphore in addition to the bounded JSON body reader. - 2026-08-25: the web service uses `BelkiHTTPServer` with 15-second socket reads and a 32-request semaphore in addition to the bounded JSON body reader.
- 2026-08-25: natural bulk parsing prioritizes explicit Russian mentor/student labels, then falls back to the original pair order when labels are absent. - 2026-08-25: natural bulk parsing prioritizes explicit Russian mentor/student labels, then falls back to the original pair order when labels are absent.
- 2026-08-25: `project_mind_map.md` is the current source-controlled project map for Belki and deployment/security boundaries; update it when a data flow, service, or integration changes.
# 2026-08-16 — несколько котят в прокачке # 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+107 -239
View File
@@ -1,245 +1,113 @@
# 🐿️ Беличья нора — Mind Map # Карта проекта «Беличья нора»
``` Актуально на 2026-08-25. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур.
🐿️ Беличья нора (cwshed-clone)
│ ```mermaid
│── 📖 Описание mindmap
│ ├── Калькулятор отчётов для игры CatWar root((cwshed-clone))
│ ├── Прокачка ЛУ (лазание) / ЗУ (зоркость) Belki
│ ├── Тренировки Domain
│ ├── Осмотры дупла/расщелины domain.py
│ ├── VK-бот для создания отчётов и заявок ЛУ и ЗУ
│ └── Админ-панель для истории расчётов и заявок Тренировки
│ Осмотры
│── 🏗️ Архитектура Калькулятор цели
│ ├── Python 3.12 (backend) reports.py
│ ├── Vanilla JS + HTML (frontend) Web
│ ├── PostgreSQL / SQLite (хранилище) app/main.py
│ ├── Docker + Kubernetes (продакшн) Public API
│ └── NGINX (gateway) calculate
│ inspect bulk
│── 📂 Структура проекта resolve identity
│ │ applications
│ ├── 📁 app/ — бэкенд-сервис Upload boundary
│ │ ├── main.py — HTTP-сервер (BaseHTTPRequestHandler) PNG JPEG WebP
│ │ └── belki/ — бизнес-логика JSON 20 MiB
│ │ ├── domain.py — ядро расчётов (без зависимостей) image 15 MiB
│ │ ├── api.py — JSON API (расчёт, bulk, identity) Admin API
│ │ ├── reports.py — шаблоны сообщений (render_*) password session
│ │ ├── vk_bot.py — VK Bots Long Poll API history
│ │ ├── history.py — CalculationStore (PG/SQLite) applications
│ │ ├── applications.py — ApplicationStore и валидация заявок web/calculator.html
│ │ ├── google_sheets_export.py — выключенный outbox-экспорт в Google Sheets Reports
│ │ ├── identity.py — IdentityDirectory (имя↔ID котёнка) Goal calculator
│ │ └── image_host.py — ImageHostClient (зеркалирование фото) Applications
│ │ web/admin.html
│ ├── 📁 web/ — фронтенд + userscripts Review and accept
│ │ ├── index.html — редирект-страница web/applications.html
│ │ ├── calculator.html — форма калькулятора (LU/ZU/training/inspection) VK bot
│ │ ├── applications.html — форма заявок (перья и роли) vk_bot.py
│ │ ├── admin.html — админ-панель истории расчётов Long Poll
│ │ ├── cw.js — UserScript v1.54 (CatWar enhancements) Step dialogs
│ │ ├── cw-lite.js — облегчённая версия Natural one-line parser
│ │ ├── CatWarMod.js — мод-файл Mentor and student labels
│ │ ├── CatWarModLite.js — лёгкий мод Attachment mirroring
│ │ ├── webfonts/ — кастомные шрифты Applications dialog
│ │ └── data/ — статические ассеты Data
│ │ ├── *.css (all.min.css) PostgreSQL production
│ │ ├── *.js (jQuery 3.4.1, jquery-ui, scrollintoview, core) calculations
│ │ ├── item_names.json — имена предметов applications
│ │ ├── river_achievements.json — достижения export outbox
│ │ ├── CatWar_Mod.user.js — userscript пользователя identities and profiles
│ │ ├── CW_Shed.meta.js — meta-заголовок Tampermonkey SQLite local fallback
│ │ └── *.mp3 / *.png — звуки и иконки Image host
│ │ API nyan.nyan404.ru
│ ├── 📁 tests/ — unit-тесты (unittest) Viewer img.nyan404.ru
│ │ ├── test_api.py — тесты API Integrations
│ │ ├── test_belki.py — тесты домена VK API
│ │ ├── test_history.py — тесты хранилища Optional Google Sheets export
│ │ └── test_vk_bot.py, test_vk_conversation.py — тесты бота Deployment
│ │ Docker
│ ├── 📁 deploy/k8s/ — Kubernetes манифесты Immutable Belki base image
│ │ ├── namespace.yaml — namespace: belki Python 3.12
│ │ ├── app.yaml — deployment service (бэкенд) GitLab CI
│ │ ├── gateway.yaml — deployment service (NGINX) test
│ │ ├── production.yaml — продакшн конфиг build
│ │ ├── rbac.yaml — RBAC политики deploy main
│ │ └── secret.example.yaml — шаблон Secret Kubernetes namespace belki
│ │ belki-web
│ ├── 📁 docs/ belki-bot
│ │ ├── ROADMAP.md — план развития belki-postgres
│ │ ├── GITLAB_CI_CD.md — CI/CD документация cwshed gateway
│ │ └── staging/ — спеки и планы Security boundaries
│ │ ├── plans/ Public input
│ │ └── specs/ bounded JSON
│ │ bounded worker pool
│ ├── 📁 data/ validated web attachments
│ │ └── belki.sqlite3 — локальная БД (development) Admin
│ │ HttpOnly SameSite session
│ ├── 📁 .vscode/ password comparison
│ │ └── settings.json Persistence
│ │ parameterized SQL
│ ├── 📄 Конфигурация public identity input is ephemeral
│ │ ├── Dockerfile.base — immutable Python + runtime dependencies base Follow-up deployment control
│ │ ├── Dockerfile — финальный образ бэкенда поверх base TLS and edge rate limiting
│ │ ├── Dockerfile.gateway-base — immutable Nginx + nginx.conf base
│ │ ├── Dockerfile.gateway — финальный gateway поверх base
│ │ ├── nginx.conf — конфиг NGINX
│ │ ├── requirements.txt → psycopg[binary]==3.3.4
│ │ │ └── изменение зависимости → пересборка и новый тег base-образа
│ │ ├── .env.example → .env (локальные переменные)
│ │ └── .dockerignore
│ │
│ ├── 📄 CI/CD
│ │ ├── .gitlab-ci.yml — GitLab CI/CD (build + deploy)
│ │ ├── .gitlab.variables.env
│ │ └── Makefile → test, run, build
│ │
│ └── 📄 Документация
│ ├── README.md — описание, запуск, структура
│ ├── CHANGELOG.md — история версий
│ ├── MEMORY.md — заметки
│ ├── AGENTS.md — инструкции для AI-агентов
│ └── structure_and_data.md
│
│── 🔌 API Endpoints
│ │
│ ├── GET
│ │ ├── /health → {"status": "ok"}
│ │ ├── / → calculator.html
│ │ ├── /belki → calculator.html
│ │ ├── /calculator.html → форма калькулятора
│ │ ├── /admin → admin.html
│ │ ├── /applications → applications.html
│ │ ├── /api/admin/calculations
│ │ │ └→ X-Admin-Password → список расчётов (PG или SQLite)
│ │ ├── /api/admin/applications → очередь заявок
│ │ └── /web/* → статика (JS, CSS, шрифты)
│ │
│ ├── POST
│ │ ├── /api/calculate → расчёт отчёта
│ │ ├── /api/inspect-bulk → bulk-инспекция JSON-payload
│ │ └── /api/resolve-identity → разрешение name↔ID
│ │ └── /api/applications → создание веб-заявки
│ │
│ └── DELETE
│ └── /api/admin/calculations/{id}
│ └→ X-Admin-Password → удаление записи
│
│ └── PATCH /api/admin/applications/{id}/accept → принятие заявки
│
│── 🤖 VK-бот
│ ├── Команды: /лу, /зу, /урок, /осмотр, /заявка, /перо, /бельчонок, /летяга, /куратор, /help, /отмена
│ ├── VK Bots Long Poll API
│ ├── Контекстные сценарии (state machine)
│ ├── Клавиатура (keyboard buttons)
│ ├── Парсинг строковых команд
│ ├── Распознавание скриншотов
│ ├── Сохранение профилей пользователей
│ ├── Автоподстановка связок персонажей (имя↔ID)
│ └── Зеркалирование фото (ImageHost API)
│
│── 🧮 Бизнес-логика (domain.py)
│ ├── CoachingSession → прокачка ЛУ/ЗУ
│ ├── TrainingSession → тренировка
│ ├── InspectionReport → осмотр
│ ├── calculate_coaching() → расчёт прокачки
│ ├── calculate_training() → расчёт тренировки
│ ├── calculate_inspection() → расчёт осмотра
│ │ ├── 2 балла за осмотр
│ │ ├── 7 баллов за паутину
│ │ ├── 3 балла за обычный мох
│ │ ├── 2 балла за водяной мох
│ │ ├── 1 балл за остальные ресурсы
│ │ └── 0 баллов за надпись и ядовитую дичь
│ ├── Independence = "сам"|"несам"
│ ├── Skill = "ЛУ"|"ЗУ"
│ ├── Place = "дупло"|"расщелина"
│ └── Форматирование/парсинг времени
│
│── 💾 Хранилище
│ ├── PostgreSQL (production)
│ │ ├── BELKI_DATABASE_URL
│ │ ├── Таблица: calculations
│ │ ├── Таблица: belki_applications
│ │ ├── Таблица: belki_application_export_events
│ │ └── Таблица: identities
│ ├── SQLite (development)
│ │ ├── data/belki.sqlite3
│ │ ├── Калькуляции
│ │ ├── Заявки
│ │ ├── Очередь экспорта заявок
│ │ ├── Связки персонажей
│ │ └── Профили пользователей
│ └── ImageHost API
│ └── BELKI_IMAGE_HOST_API_URL
│
│── 🔐 Безопасность
│ ├── BELKI_ADMIN_PASSWORD → защита админ-панели
│ ├── VK_GROUP_TOKEN → токен группы VK
│ ├── .env игнорируется Git
│ ├── K8s Secrets
│ └── RBAC в Kubernetes
│
│── 🔧 CI/CD Pipeline
│ ├── Build
│ │ ├── docker build (app + gateway)
│ │ ├── Docker Registry
│ │ ├── Теги: commit SHA + latest
│ │ └── Push в registry
│ ├── Deploy
│ │ ├── kubectl apply
│ │ ├── namespace: belki
│ │ └── Kubernetes manifests
│ └── GitLab CI (stages: build → deploy)
│
│── 🧪 Тесты
│ ├── unittest discover
│ ├── test_api.py
│ ├── test_belki.py
│ ├── test_history.py
│ ├── test_vk_bot.py
│ └── test_vk_conversation.py
│
│── 🚀 Запуск
│ ├── Локально:
│ │ ├── make test → тесты
│ │ ├── make run → python -m app.main
│ │ ├── make build → docker build
│ │ └── VK-бот: python -m app.belki.vk_bot
│ │
│ └── Production:
│ ├── Docker image → Docker registry
│ └── K8s deploy → namespace: belki
│
└── 🔗 Внешние интеграции
├── VK Bots Long Poll API
├── Google Apps Script Web App (готово к включению; выключено)
├── Image Host API (зеркалирование фото)
├── PostgreSQL / SQLite
├── Tampermonkey / GreasyFork (userscripts)
└── CatWar (catwar.su / catwar.net)
``` ```
## Ключевые компоненты ## Потоки данных
### Бэкенд (`app/`) ```mermaid
- **main.py** — HTTP-сервер на `http.server.BaseHTTPRequestHandler` + `ThreadingHTTPServer` flowchart LR
- **belki/domain.py** — чистое расчётное ядро (no infra dependencies) Browser[Публичный браузер] --> Web[BelkiHTTPServer]
- **belki/api.py** — адаптер API → domain VK[VK Long Poll] --> Bot[BelkiDialog]
- **belki/vk_bot.py** — VK Bot Long Poll (898 строк, state machine) Web --> Domain[Расчётное ядро]
- **belki/history.py** — CalculationStore (PG/SQLite dual backend) Bot --> Domain
- **belki/identity.py** — IdentityDirectory (имя↔ID lookup) Web --> Store[(PostgreSQL or SQLite)]
- **belki/image_host.py** — ImageHostClient (mirror VK photos) Bot --> Store
- **belki/reports.py** — render templates для сообщений Web --> ImageHost[Image-host API]
Bot --> ImageHost
Admin[Администратор] -->|session cookie| Web
Web --> Admin
Bot -. when enabled .-> Sheets[Google Apps Script]
```
### Фронтенд (`web/`) ## Проверочные точки
- **calculator.html** — SPA-форма с табами (LU/ZU/training/inspection/bulk)
- **admin.html** — защищённая админка для расчётов
- **cw.js** — UserScript v1.54 (категории: чат, уведомления, UI, анимации, поиск, профиль)
- **data/** — статика (jQuery 3.4.1, jquery-ui, JSON-данные, звуки)
### Инфраструктура - Изменение доменной формулы проверяется в `tests/test_belki.py` и `tests/test_api.py`.
- **Docker** → Python 3.12-slim + NGINX Alpine - Диалоги, команды и естественный ввод проверяются в `tests/test_vk_conversation.py`.
- **Kubernetes** → 2 deployment (app + gateway), namespace belki - Границы image-host и HTTP-предохранители проверяются в `tests/test_image_host.py`.
- **GitLab CI** → build images + kubectl deploy - Перед CI используйте Python 3.12 в Docker: `docker run --rm -v "$PWD:/work" -w /work python:3.12-slim sh -lc 'python -m compileall -q app tests && python -m unittest discover -s tests -q'`.
## Ограничения развёртывания
Исходники ограничивают размер и параллелизм запросов, но TLS и сетевой rate limit должны обеспечиваться на внешнем прокси. Перед следующим production rollout необходимо убедиться, что админский путь недоступен по plaintext HTTP и что `belki-web` не публикуется в обход этого прокси.
+1
View File
@@ -12,6 +12,7 @@
- [`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. - [`.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.
- [`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 ## Runtime / Deployment
- GitLab CI runs the build job. - GitLab CI runs the build job.