diff --git a/.env.example b/.env.example index 5f8ec9b..46852da 100644 --- a/.env.example +++ b/.env.example @@ -5,6 +5,8 @@ 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 +# Local Sudoku-game fallback when PostgreSQL is unavailable. Production reuses BELKI_DATABASE_URL. +SUDOKU_DB=data/sudoku.sqlite3 # SQLite fallback/runtime identity database when BELKI_DATABASE_URL is empty. BELKI_IDENTITIES_DB=data/belki.sqlite3 # Required to access /admin and /api/admin/calculations. diff --git a/MEMORY.md b/MEMORY.md index d15ed83..4e0feb8 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -59,3 +59,7 @@ # 2026-08-25: production container architecture Production Belki images and Kubernetes workloads require `linux/amd64`. CI sets `DOCKER_DEFAULT_PLATFORM` and passes `--platform linux/amd64`; Dockerfiles and workload node selectors carry the same constraint. The previous private Python base tag `py312-d6c42c4497ce` was published only for arm64 and must not be used for the application image. + +# 2026-08-25: standalone Sudoku + +`/sudoku` is a separate public route, backed by `app/sudoku.py` and `web/sudoku.html`. A supplied nickname (case-insensitive) is intentionally only a resume key, not authentication; never present it as private storage. Games persist in `sudoku_games` through `BELKI_DATABASE_URL` in production or `SUDOKU_DB` locally. The public API must never return the saved solution, and it must keep original clues immutable. The generator is the explicitly requested `dokusan==0.1.0`; it is GPL-3.0-only, Alpha, and last released in 2023, so retain the `NOTICE`/README license disclosure and revalidate it before future runtime upgrades. diff --git a/NOTICE b/NOTICE index 6a9e5c5..2726b17 100644 --- a/NOTICE +++ b/NOTICE @@ -6,3 +6,11 @@ This repository includes legacy CatWar userscript assets and bundled third-party - `web/data/jquery-3.4.1.min.js`, `web/data/jquery-ui.js`, and `web/data/jquery.scrollintoview.min.js` are third-party files with retained upstream notices. The MIT license in [`LICENSE`](./LICENSE) applies to this project's original code and documentation. It does not replace notices or grant rights beyond the licenses of third-party and legacy files. +# Third-party runtime dependency for /sudoku + +The Sudoku generator and solver uses dokusan 0.1.0 by Aleksei Maslakov +(https://github.com/unmade/dokusan), licensed under GNU GPL version 3.0. +It is installed as a runtime dependency; its source and licence are available +from the upstream project and PyPI. This dependency introduces GPL-3.0-only +terms for the distributed application image; review those obligations before +redistributing an image containing it. diff --git a/README.md b/README.md index 0315cc3..2f0d8cb 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,14 @@ python3 -m app.belki.vk_bot Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер загружает их через API `https://nyan.nyan404.ru` и сохраняет ссылки вместе с отчётом. Пользовательский интерфейс image-host доступен на `https://img.nyan404.ru`. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же API. Google Sheets пока не подключён. +## Судоку + +`/sudoku` — отдельная публичная игра. Ник служит ключом к партии: с тем же ником незавершённое поле откроется на другом устройстве. Это не учётная запись и не пароль, поэтому в нике нельзя указывать личные данные. Сервер хранит исходные цифры, ход, время и факт завершения; новое поле не удаляет предыдущую партию. + +Сложность задаётся рангом логических техник генератора `dokusan`: лёгкая использует в основном одиночные кандидаты, а сложные уровни допускают более сложные техники. Ответ хранится только на сервере, поэтому клиент не может получить решение через API. + +Для генерации используется `dokusan==0.1.0` под GNU GPL-3.0-only. Это осознанно вводит GPL-3.0-only зависимость в распространяемый образ; подробная оговорка и ссылка на исходники приведены в [`NOTICE`](./NOTICE). Последний релиз пакета датирован 2023 годом и имеет статус Alpha, поэтому при обновлении Python или сборочного образа его нужно отдельно перепроверить. + ## Заявки `/applications` — открытая форма для пожертвования перьев, бельчонка, белки-летяги и куратора; эти же формы находятся на вкладке «Заявки» в `/belki`. Она сохраняет структурированные данные в очередь модерации, а не генерирует форумную отпись. В VK используйте `/заявка`: виртуальная клавиатура проводит через выбор типа, пропуск VK-ссылки, ответы «да/нет», «готово» и отмену; вручную вводятся только свободные данные, например ссылки и источники перьев. @@ -58,12 +66,14 @@ python3 -m app.belki.vk_bot - `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей; - `app/belki/reports.py` — шаблоны сообщений; - `app/belki/api.py` — JSON API; +- `app/sudoku.py` — генерация, валидация и PostgreSQL/SQLite-хранилище партий Sudoku; - `app/belki/applications.py` — валидация и хранилище заявок; - `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды; - `app/main.py` — веб-сервис и раздача сайта/userscript-файлов; - `web/calculator.html` — форма калькулятора; - `web/applications.html` — форма подачи заявок; - `web/admin.html` — парольная история расчётов для администраторской проверки; +- `web/sudoku.html` — адаптивная игра и восстановление партий по нику; - `tests/` — unit-тесты. Спецификация и план находятся в `docs/staging/`. diff --git a/app/main.py b/app/main.py index 62c3ca3..00ddf55 100644 --- a/app/main.py +++ b/app/main.py @@ -18,6 +18,7 @@ from .belki.applications import ApplicationError, ApplicationStore, validate_app from .belki.google_sheets_export import GoogleSheetsExportService from .belki.identity import IdentityDirectory from .belki.image_host import ImageHostClient, ImageHostError +from .sudoku import SudokuError, SudokuStore ROOT = Path(__file__).resolve().parents[1] @@ -25,6 +26,7 @@ WEB_ROOT = ROOT / "web" _HISTORY_STORE: CalculationStore | None = None _IDENTITY_DIR: IdentityDirectory | None = None _APPLICATION_STORE: ApplicationStore | None = None +_SUDOKU_STORE: SudokuStore | None = None _ADMIN_SESSIONS: dict[str, float] = {} _ADMIN_SESSIONS_LOCK = threading.Lock() _ISSUED_WEB_UPLOAD_URLS: dict[str, float] = {} @@ -166,6 +168,19 @@ def history_store() -> CalculationStore: return _HISTORY_STORE +def sudoku_store() -> SudokuStore: + """Return the lazily initialized store for resumable Sudoku games.""" + global _SUDOKU_STORE + if _SUDOKU_STORE is None: + _SUDOKU_STORE = SudokuStore.from_environment() + return _SUDOKU_STORE + + +def public_sudoku_game(game: dict) -> dict: + """Keep the answer key on the server while returning a playable game.""" + return {key: value for key, value in game.items() if key != "solution"} + + def identity_dir() -> IdentityDirectory: """Лениво создаёт справочник персонажей из окружения.""" global _IDENTITY_DIR @@ -311,6 +326,17 @@ class Handler(BaseHTTPRequestHandler): if path in ("/applications", "/applications/"): self._file(WEB_ROOT / "applications.html") return + if path in ("/sudoku", "/sudoku/"): + self._file(WEB_ROOT / "sudoku.html") + return + if path == "/api/sudoku/games": + try: + nickname = parse_qs(urlparse(self.path).query).get("nickname", [""])[0] + game = sudoku_store().current(nickname) + self._json(200, {"game": public_sudoku_game(game) if game else None}) + except SudokuError as exc: + self._json(400, {"error": str(exc)}) + return if path == "/api/admin/session": self._json(200, {"authenticated": self._admin_session_authorized()}) return @@ -374,13 +400,22 @@ class Handler(BaseHTTPRequestHandler): def do_POST(self) -> None: # noqa: N802 """Обрабатывает вход, авторизацию и создание заявок через POST API.""" + parsed = urlparse(self.path) + is_sudoku_create = parsed.path == "/api/sudoku/games" + is_sudoku_regenerate = parsed.path.startswith("/api/sudoku/games/") and parsed.path.endswith("/regenerate") if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity", - "/api/applications"): + "/api/applications") and not is_sudoku_create and not is_sudoku_regenerate: self._json(404, {"error": "Не найдено"}) return try: payload = self._read_json_body() - if self.path == "/api/admin/auth": + if is_sudoku_create: + self._json(201, {"game": public_sudoku_game(sudoku_store().create(payload.get("nickname"), payload.get("difficulty")))}) + elif is_sudoku_regenerate: + game_id = parsed.path.removeprefix("/api/sudoku/games/").removesuffix("/regenerate").strip("/") + sudoku_store().get(game_id, payload.get("nickname")) + self._json(201, {"game": public_sudoku_game(sudoku_store().create(payload.get("nickname"), payload.get("difficulty")))}) + elif self.path == "/api/admin/auth": client_ip = self.client_address[0] if not allow_admin_auth_attempt(client_ip): self._json(429, {"error": "Слишком много попыток. Повторите через 15 минут."}) @@ -435,13 +470,29 @@ class Handler(BaseHTTPRequestHandler): else: payload["attachments"] = validate_web_attachments(payload.get("attachments", [])) self._json(200, calculate_and_store(payload, actor_id=None, source="web")) - except (ApiError, ApplicationError) as exc: + except (ApiError, ApplicationError, SudokuError) as exc: self._json(400, {"error": str(exc)}) except (ValueError, json.JSONDecodeError) as exc: self._json(400, {"error": str(exc)}) except Exception: self._json(500, {"error": "Внутренняя ошибка калькулятора"}) + def do_PUT(self) -> None: # noqa: N802 + """Save an in-progress Sudoku board for resuming on another device.""" + parsed = urlparse(self.path) + prefix = "/api/sudoku/games/" + if not parsed.path.startswith(prefix) or not parsed.path.removeprefix(prefix): + self._json(404, {"error": "Не найдено"}) + return + try: + payload = self._read_json_body() + game = sudoku_store().save(parsed.path.removeprefix(prefix), payload.get("nickname"), payload.get("board"), payload.get("elapsedSeconds")) + self._json(200, {"game": public_sudoku_game(game)}) + except (ApiError, SudokuError) as exc: + self._json(400, {"error": str(exc)}) + except Exception: + self._json(500, {"error": "Не удалось сохранить игру"}) + def do_DELETE(self) -> None: # noqa: N802 """Удаляет заявку после проверки административной авторизации.""" parsed = urlparse(self.path) diff --git a/app/sudoku.py b/app/sudoku.py new file mode 100644 index 0000000..c62fa23 --- /dev/null +++ b/app/sudoku.py @@ -0,0 +1,179 @@ +"""Sudoku generation, validation, and persistent cross-device game storage.""" + +from __future__ import annotations + +import json +import os +import re +import sqlite3 +import uuid +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from dokusan import generators, solvers +from dokusan.boards import BoxSize, Sudoku + + +class SudokuError(ValueError): + """Raised when a public Sudoku request cannot be accepted.""" + + +DIFFICULTIES = {"easy": 70, "medium": 120, "hard": 180, "expert": 260} +NICKNAME_PATTERN = re.compile(r"^[^\s]{2,32}$") + + +def normalize_nickname(value: object) -> str: + """Validate the deliberately simple nickname used to resume a game.""" + nickname = str(value or "").strip() + if not NICKNAME_PATTERN.fullmatch(nickname): + raise SudokuError("Ник должен состоять из 2–32 символов без пробелов") + return nickname + + +def validate_difficulty(value: object) -> str: + """Return one supported difficulty identifier.""" + difficulty = str(value or "medium") + if difficulty not in DIFFICULTIES: + raise SudokuError("Выберите сложность: лёгкая, средняя, сложная или экспертная") + return difficulty + + +def generate_game(difficulty: object) -> dict[str, Any]: + """Create a ranked, uniquely solvable puzzle and keep its answer server-side.""" + selected_difficulty = validate_difficulty(difficulty) + puzzle_model = generators.random_sudoku(avg_rank=DIFFICULTIES[selected_difficulty]) + puzzle = [int(cell) for cell in str(puzzle_model)] + solution_model = solvers.backtrack(Sudoku.from_string(str(puzzle_model), box_size=BoxSize(3, 3))) + solution = [int(cell) for cell in str(solution_model)] + return {"difficulty": selected_difficulty, "puzzle": puzzle, "solution": solution} + + +def _validate_board(value: object, puzzle: list[int], solution: list[int]) -> tuple[list[int], bool]: + """Accept only a legal player board that preserves initial clues.""" + if not isinstance(value, list) or len(value) != 81 or any(type(cell) is not int or not 0 <= cell <= 9 for cell in value): + raise SudokuError("Поле должно содержать 81 цифру от 0 до 9") + board = list(value) + for index, clue in enumerate(puzzle): + if clue and board[index] != clue: + raise SudokuError("Исходные цифры нельзя изменять") + for unit in ([row * 9 + column for column in range(9)] for row in range(9)): + digits = [board[index] for index in unit if board[index]] + if len(digits) != len(set(digits)): + raise SudokuError("В строке не должно быть повторяющихся цифр") + for unit in ([row * 9 + column for row in range(9)] for column in range(9)): + digits = [board[index] for index in unit if board[index]] + if len(digits) != len(set(digits)): + raise SudokuError("В столбце не должно быть повторяющихся цифр") + for box_row in range(0, 9, 3): + for box_column in range(0, 9, 3): + unit = [(box_row + row_offset) * 9 + box_column + column_offset for row_offset in range(3) for column_offset in range(3)] + digits = [board[index] for index in unit if board[index]] + if len(digits) != len(set(digits)): + raise SudokuError("В квадрате 3×3 не должно быть повторяющихся цифр") + return board, board == solution + + +class SudokuStore: + """Persist Sudoku games in PostgreSQL or a local SQLite fallback.""" + + def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None: + self.database_url = database_url or "" + self.sqlite_path = Path(sqlite_path) if sqlite_path else None + if self.database_url.startswith(("postgres://", "postgresql://")): + import psycopg + self._psycopg = psycopg + self._ensure_postgres_schema() + else: + self.sqlite_path = self.sqlite_path or Path("data/sudoku.sqlite3") + self.sqlite_path.parent.mkdir(parents=True, exist_ok=True) + self._ensure_sqlite_schema() + + @classmethod + def from_environment(cls) -> "SudokuStore": + """Reuse production PostgreSQL while retaining a local SQLite fallback.""" + return cls(os.getenv("BELKI_DATABASE_URL"), os.getenv("SUDOKU_DB", "data/sudoku.sqlite3")) + + def _ensure_sqlite_schema(self) -> None: + with sqlite3.connect(self.sqlite_path) as connection: + connection.execute("""CREATE TABLE IF NOT EXISTS sudoku_games ( + id TEXT PRIMARY KEY, nickname TEXT NOT NULL, nickname_key TEXT NOT NULL, + difficulty TEXT NOT NULL, puzzle_json TEXT NOT NULL, solution_json TEXT NOT NULL, + board_json TEXT NOT NULL, elapsed_seconds INTEGER NOT NULL DEFAULT 0, + completed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL + )""") + connection.execute("CREATE INDEX IF NOT EXISTS sudoku_games_active ON sudoku_games(nickname_key, completed_at, updated_at DESC)") + + def _ensure_postgres_schema(self) -> None: + with self._psycopg.connect(self.database_url) as connection: + connection.execute("""CREATE TABLE IF NOT EXISTS sudoku_games ( + id UUID PRIMARY KEY, nickname TEXT NOT NULL, nickname_key TEXT NOT NULL, + difficulty TEXT NOT NULL, puzzle_json JSONB NOT NULL, solution_json JSONB NOT NULL, + board_json JSONB NOT NULL, elapsed_seconds INTEGER NOT NULL DEFAULT 0, + completed_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )""") + connection.execute("CREATE INDEX IF NOT EXISTS sudoku_games_active ON sudoku_games(nickname_key, completed_at, updated_at DESC)") + + @staticmethod + def _record(row: tuple[Any, ...]) -> dict[str, Any]: + game_id, nickname, difficulty, puzzle, solution, board, elapsed, completed_at, created_at, updated_at = row + decode = lambda item: json.loads(item) if isinstance(item, str) else item + return {"id": str(game_id), "nickname": nickname, "difficulty": difficulty, "puzzle": decode(puzzle), "solution": decode(solution), "board": decode(board), "elapsedSeconds": elapsed, "completedAt": completed_at.isoformat() if hasattr(completed_at, "isoformat") else completed_at, "createdAt": created_at.isoformat() if hasattr(created_at, "isoformat") else created_at, "updatedAt": updated_at.isoformat() if hasattr(updated_at, "isoformat") else updated_at} + + def create(self, nickname: object, difficulty: object) -> dict[str, Any]: + nickname = normalize_nickname(nickname) + generated = generate_game(difficulty) + game_id, now = str(uuid.uuid4()), datetime.now(timezone.utc).isoformat() + values = (game_id, nickname, nickname.casefold(), generated["difficulty"], json.dumps(generated["puzzle"]), json.dumps(generated["solution"]), json.dumps(generated["puzzle"]), 0, now, now) + if self.database_url.startswith(("postgres://", "postgresql://")): + from psycopg.types.json import Jsonb + with self._psycopg.connect(self.database_url) as connection: + connection.execute("INSERT INTO sudoku_games (id, nickname, nickname_key, difficulty, puzzle_json, solution_json, board_json, elapsed_seconds, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())", (game_id, nickname, nickname.casefold(), generated["difficulty"], Jsonb(generated["puzzle"]), Jsonb(generated["solution"]), Jsonb(generated["puzzle"]), 0)) + else: + with sqlite3.connect(self.sqlite_path) as connection: + connection.execute("INSERT INTO sudoku_games VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)", values) + return self.get(game_id, nickname) + + def get(self, game_id: str, nickname: object) -> dict[str, Any]: + nickname = normalize_nickname(nickname) + query = "SELECT id, nickname, difficulty, puzzle_json, solution_json, board_json, elapsed_seconds, completed_at, created_at, updated_at FROM sudoku_games WHERE id = %s AND nickname_key = %s" if self.database_url.startswith(("postgres://", "postgresql://")) else "SELECT id, nickname, difficulty, puzzle_json, solution_json, board_json, elapsed_seconds, completed_at, created_at, updated_at FROM sudoku_games WHERE id = ? AND nickname_key = ?" + if self.database_url.startswith(("postgres://", "postgresql://")): + with self._psycopg.connect(self.database_url) as connection: + row = connection.execute(query, (game_id, nickname.casefold())).fetchone() + else: + with sqlite3.connect(self.sqlite_path) as connection: + row = connection.execute(query, (game_id, nickname.casefold())).fetchone() + if row is None: + raise SudokuError("Игра не найдена") + return self._record(row) + + def current(self, nickname: object) -> dict[str, Any] | None: + nickname = normalize_nickname(nickname) + placeholder = "%s" if self.database_url.startswith(("postgres://", "postgresql://")) else "?" + query = f"SELECT id, nickname, difficulty, puzzle_json, solution_json, board_json, elapsed_seconds, completed_at, created_at, updated_at FROM sudoku_games WHERE nickname_key = {placeholder} ORDER BY (completed_at IS NULL) DESC, updated_at DESC LIMIT 1" + if self.database_url.startswith(("postgres://", "postgresql://")): + with self._psycopg.connect(self.database_url) as connection: + row = connection.execute(query, (nickname.casefold(),)).fetchone() + else: + with sqlite3.connect(self.sqlite_path) as connection: + row = connection.execute(query, (nickname.casefold(),)).fetchone() + return self._record(row) if row else None + + def save(self, game_id: str, nickname: object, board: object, elapsed_seconds: object) -> dict[str, Any]: + game = self.get(game_id, nickname) + if game["completedAt"]: + return game + saved_board, complete = _validate_board(board, game["puzzle"], game["solution"]) + if type(elapsed_seconds) is not int or not 0 <= elapsed_seconds <= 86_400: + raise SudokuError("Некорректное игровое время") + completed_at = datetime.now(timezone.utc).isoformat() if complete else None + params = (json.dumps(saved_board), elapsed_seconds, completed_at, game_id) + if self.database_url.startswith(("postgres://", "postgresql://")): + from psycopg.types.json import Jsonb + with self._psycopg.connect(self.database_url) as connection: + connection.execute("UPDATE sudoku_games SET board_json = %s, elapsed_seconds = %s, completed_at = COALESCE(completed_at, %s), updated_at = NOW() WHERE id = %s", (Jsonb(saved_board), elapsed_seconds, completed_at, game_id)) + else: + with sqlite3.connect(self.sqlite_path) as connection: + connection.execute("UPDATE sudoku_games SET board_json = ?, elapsed_seconds = ?, completed_at = COALESCE(completed_at, ?), updated_at = ? WHERE id = ?", (*params[:-1], datetime.now(timezone.utc).isoformat(), game_id)) + return self.get(game_id, nickname) diff --git a/nginx.conf b/nginx.conf index 02a73ef..09a4255 100644 --- a/nginx.conf +++ b/nginx.conf @@ -96,6 +96,24 @@ http { proxy_pass http://10.12.0.212/applications/; } + location = /sudoku { + proxy_intercept_errors on; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_pass http://10.12.0.212/sudoku; + } + + location = /sudoku/ { + proxy_intercept_errors on; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_pass http://10.12.0.212/sudoku/; + } + location ^~ /api/ { proxy_http_version 1.1; proxy_set_header Host $host; diff --git a/project_mind_map.md b/project_mind_map.md index da541e6..da5bd0b 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -53,10 +53,16 @@ mindmap Attachment mirroring bounded verified raster bytes Applications dialog + Sudoku + /sudoku adaptive game UI + nickname-only resume key + dokusan ranked generator + server-side solution key Data PostgreSQL production calculations applications + sudoku_games export outbox identities and profiles SQLite local fallback @@ -107,6 +113,7 @@ flowchart LR Web --> Store[(PostgreSQL or SQLite)] Bot --> Store Web --> ImageHost[Image-host API] + Web --> Sudoku[Sudoku game store] Bot --> ImageHost Admin[Администратор] -->|session cookie| Web Web --> Admin diff --git a/requirements.txt b/requirements.txt index afab966..18f71fc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,4 @@ # PostgreSQL driver used by production stores; SQLite remains the local fallback. psycopg[binary]==3.3.4 +# GPL-3.0-only Sudoku generator/solver, selected explicitly for /sudoku. +dokusan==0.1.0 diff --git a/structure_and_data.md b/structure_and_data.md index 233fe04..13a6146 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -47,6 +47,9 @@ - 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-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`; publishing them requires rebuilding the immutable `Dockerfile.gateway-base` image and updating `Dockerfile.gateway` to its resulting tag before CI/deployment. +- 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. diff --git a/tests/test_sudoku.py b/tests/test_sudoku.py new file mode 100644 index 0000000..1ff3239 --- /dev/null +++ b/tests/test_sudoku.py @@ -0,0 +1,51 @@ +"""Regression tests for generated and resumable Sudoku games.""" + +from __future__ import annotations + +from tempfile import TemporaryDirectory +from pathlib import Path +import unittest + +from app.sudoku import SudokuError, SudokuStore, generate_game + + +class SudokuTests(unittest.TestCase): + def test_generated_puzzle_has_a_complete_solution(self) -> None: + game = generate_game("easy") + self.assertEqual(len(game["puzzle"]), 81) + self.assertEqual(len(game["solution"]), 81) + self.assertTrue(any(cell == 0 for cell in game["puzzle"])) + self.assertTrue(all(1 <= cell <= 9 for cell in game["solution"])) + + def test_game_can_be_resumed_with_same_nickname(self) -> None: + with TemporaryDirectory() as directory: + store = SudokuStore(sqlite_path=Path(directory) / "sudoku.sqlite3") + created = store.create("Лис_7", "easy") + board = created["board"].copy() + empty_cell = board.index(0) + board[empty_cell] = created["solution"][empty_cell] + saved = store.save(created["id"], "лис_7", board, 42) + current = store.current("ЛИС_7") + self.assertEqual(saved["board"][empty_cell], created["solution"][empty_cell]) + self.assertEqual(current["id"], created["id"]) + self.assertEqual(current["elapsedSeconds"], 42) + + def test_given_cells_and_conflicting_moves_are_rejected(self) -> None: + with TemporaryDirectory() as directory: + store = SudokuStore(sqlite_path=Path(directory) / "sudoku.sqlite3") + created = store.create("Белка", "easy") + changed_clue = created["board"].copy() + clue_cell = next(index for index, value in enumerate(created["puzzle"]) if value) + changed_clue[clue_cell] = 0 + with self.assertRaisesRegex(SudokuError, "Исходные"): + store.save(created["id"], "Белка", changed_clue, 0) + conflict = created["board"].copy() + empty_cell = conflict.index(0) + row_start = empty_cell // 9 * 9 + conflict[empty_cell] = next(value for value in conflict[row_start:row_start + 9] if value) + with self.assertRaisesRegex(SudokuError, "строке"): + store.save(created["id"], "Белка", conflict, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/sudoku.html b/web/sudoku.html new file mode 100644 index 0000000..06f1468 --- /dev/null +++ b/web/sudoku.html @@ -0,0 +1,61 @@ + + + + + + + Судоку + + + + +
+

Судоку

Одна партия — там, где вы её оставили.

+
+

Спокойная задача на 9×9

Введите один и тот же ник на телефоне, планшете или компьютере. Незавершённая партия откроется автоматически.

Ник — это способ найти игру, а не пароль: не используйте личные данные.

+

2–32 символа, без пробелов.

+
+ +
+ + +