diff --git a/.claude/agents/server-tests.md b/.claude/agents/server-tests.md index 2bbc8d09..e15911b0 100644 --- a/.claude/agents/server-tests.md +++ b/.claude/agents/server-tests.md @@ -4,7 +4,7 @@ description: Integrity of the server test suite itself. Use to check that a test tools: Read, Glob, Grep, Bash, Edit, Write --- -You own `server/tests/`. 3916 tests; `pytest -q -n auto`, bare, is exactly what CI runs. +You own `server/tests/`. 3926 tests; `pytest -q -n auto`, bare, is exactly what CI runs. Not `python -m pytest` for the gate: the `-m` form puts the current directory on `sys.path`, so a test that leans on it passes here and fails at collection on CI (`CLAUDE.md`, «Commands»; #310, #314). diff --git a/.claude/settings.json b/.claude/settings.json index ba862ce4..57aa57c8 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -12,6 +12,7 @@ "Bash(pytest)", "Bash(python -m mypy *)", "Bash(python -m mypy)", + "Bash(python -m scripts.check_openapi_v1 --pull-request)", "Bash(python scripts/check_test_counts.py *)", "Bash(python ../server/scripts/check_test_counts.py *)", "Bash(git status *)", diff --git a/.claude/skills/gates/SKILL.md b/.claude/skills/gates/SKILL.md index 30aa9d6d..f2168958 100644 --- a/.claude/skills/gates/SKILL.md +++ b/.claude/skills/gates/SKILL.md @@ -27,7 +27,7 @@ that happens and names both trees (#312). after ruff — the owner asked for it through that day's audit (#210) — and still worth running before a push: seconds here, minutes there. It is the thing that reproduces the «🗓 Четверти» crash. -3. `pytest -q -n auto`, bare, from `server/` with its venv active — 3916 tests today, six of +3. `pytest -q -n auto`, bare, from `server/` with its venv active — 3926 tests today, six of them skipped unless a host is running (`-m host`, CI's «Host» job), plus eleven PostgreSQL-only lock checks skipped on SQLite, and **the exact command CI runs**. Not `python -m pytest`: the `-m` form puts the current @@ -44,7 +44,7 @@ Narrower while iterating: `python -m pytest -q tests/test_schedule.py -k parity` ## Android, from `android/` -1. `./gradlew test` — all JVM unit tests across the six modules, 2232 today. +1. `./gradlew test` — all JVM unit tests across the six modules, 2246 today. 2. `./gradlew assembleDebug` 3. `./gradlew assembleRelease` — **not optional.** CI builds both on every push, because R8 and resource shrinking are where "worked in debug" stops being true. diff --git a/.claude/skills/migration/SKILL.md b/.claude/skills/migration/SKILL.md index ea302fe9..b1f3ed30 100644 --- a/.claude/skills/migration/SKILL.md +++ b/.claude/skills/migration/SKILL.md @@ -7,6 +7,9 @@ description: Write and apply an Alembic revision for this project — including Head is **`0019`**. Nothing after `0001` may use `create_all`. +The [Alembic revision history](../../../docs/history.md#the-alembic-chain-through-0019) +records why each revision was written and how it was applied. + ## 1. Decide the direction - **Additive** (a new column, table, index, nullable default) → run it **before** the merge. @@ -18,9 +21,9 @@ Head is **`0019`**. Nothing after `0001` may use `create_all`. breaks against the constraint, with an `IntegrityError` nobody catches. Write the service so it is correct with or without the constraint, so the window behaves like production did before. `0013` is this shape and says so in its own docstring. -- **A rewrite of a key** (rows moved from one key to another, no schema change) → **free** - where there are no rows to move, so it goes on with the additive revisions; **after** the - merge where there are. Old and new code file the same rows under different keys, so each +- **A rewrite of a key** (rows moved from one key to another, no schema change) → run new + revisions **after** the merge. Earlier revisions sometimes ran before merge after proving + the affected tables empty. Old and new code file the same rows under different keys, so each order loses what the window makes: before the merge, what the old code writes is filed where the new code never reads; after it, nothing typed is lost but a reset made in the window is undone when the rewrite runs — keep that window to minutes, and expect @@ -30,6 +33,17 @@ Head is **`0019`**. Nothing after `0001` may use `create_all`. ## 2. Read the database first +After revision `0019`, declare a literal `MERGE_SIDE = "before"` or +`MERGE_SIDE = "after"` at module level. An operation that can remove rows or +their stored values also needs a nonempty `DESTROYS` explanation. The server +suite checks upgrade operations and refuses a mix of both sides in one revision. +When an existing table needs a new column and a constraint, split the nullable +column and the constraint into revisions applied on the appropriate sides. +Write the nullable column with a literal name and an explicit built-in scalar +type. Put foreign keys and checks in separate Alembic operations. +Use explicit Alembic operations so the check can classify them. A literal SQL +data rewrite is treated as after-merge because the check cannot see live rows. + Do not assume a revision is a no-op. `0011` was one; `0012` was not — all eight columns really were nullable, and all eight held zero nulls, so it tightened them and rewrote nothing. @@ -65,9 +79,9 @@ A revision that does not move it fails there. ## 5. Apply it -**Twice: the Neon branch `preview` first, when the pull request is pushed, and production -before the merge.** `0018` was the first to go that way; a preview whose database is behind -its code answers `degraded`. +**Apply to the Neon branch `preview` first, then apply to production on the +declared side of the merge.** `0018` was the first to use preview. A preview +whose database is behind its code answers `degraded`. Through the **Neon connector**, from the session. The owner does not run `alembic upgrade head` by hand and a session has no `DATABASE_URL`. The project is the one diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index df7116df..5fd09048 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -43,11 +43,13 @@ field, not against the app in this diff (`docs/engineering.md`, «Contracts»). - [ ] An installed app of the previous version still reads every answer it reads today: no field removed or renamed in `/api/v1`, no enum value it does not know sent to it, no new required field in what it posts + (a deliberate break needs `V1-OpenAPI-Break: MIN_CLIENT_VERSION=` + on its own line and a rollout plan that covers installed v1 clients) - [ ] A v2 change passed `buf breaking`, or it says here why the break is safe - [ ] If the change can go wrong in production, it says how it is switched off without a revert (a setting, `MIN_CLIENT_VERSION`, a feature the tick skips) — or that it cannot be -- [ ] The migration's side of the merge is stated (additive before, constraint after), or - there is no migration +- [ ] The migration's `MERGE_SIDE` is quoted here, along with `DESTROYS` when the change + can remove stored data, or there is no migration ## Verification diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1bf580b5..a5e319e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,8 @@ on: push: branches: [master, dev] pull_request: + # The v1 compatibility declaration is part of the PR body. + types: [opened, reopened, synchronize, edited] # Lets you build from the Actions tab without pushing anything. workflow_dispatch: @@ -225,6 +227,8 @@ jobs: working-directory: server steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - uses: actions/setup-python@v7 with: python-version: "3.12" @@ -256,6 +260,9 @@ jobs: # on a laptop. - name: Type check run: python -m mypy + - name: Check v1 OpenAPI compatibility + if: github.event_name == 'pull_request' + run: python -m scripts.check_openapi_v1 --pull-request # `-n auto`, because this step was the whole run. It was twelve and a # half minutes of a twenty-one minute CI run and is now three and a # half: that started as a bill to cut and stayed for the feedback. The diff --git a/AGENTS.md b/AGENTS.md index bb564094..7a25e066 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,10 +34,15 @@ From `server/` (Python 3.12): ``` ruff check app tests scripts migrations python -m mypy +python -m scripts.check_openapi_v1 --pull-request pytest -q -n auto python scripts/check_test_counts.py server --junit work/pytest.xml ``` +The `--pull-request` comparison requires GitHub's pull request event JSON. For a +local comparison, use `python -m scripts.check_openapi_v1 --base` with the +snapshot from the target commit. + From `android/` (JDK 21, compileSdk 37, wrapper Gradle; Python 3.12 for the report check): ``` @@ -48,7 +53,7 @@ From `android/` (JDK 21, compileSdk 37, wrapper Gradle; Python 3.12 for the repo python ../server/scripts/check_test_counts.py android --root . ``` -CI is exactly: ruff, `python -m mypy`, pytest `-n auto`, `./gradlew test`, both assembles, +CI runs ruff, mypy, the v1 OpenAPI comparison on pull requests, pytest `-n auto`, `./gradlew test`, both assembles, `./gradlew detekt`, the two completed-report count checks above, and the path-filtered «Contract (Buf)» job when `proto/`, `buf.*` or `server/app/contract/` changed (or the workflow, or an unknown commit range). `./gradlew lint` is **not** a gate. diff --git a/CLAUDE.md b/CLAUDE.md index 2a00c2a0..ea64420a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,1065 +1,174 @@ # CLAUDE.md -Guidance for Claude Code when working in this repository. +Read [HANDOVER.md](HANDOVER.md) first and verify its current PR, CI and resource state before acting. Read [architecture](docs/architecture.md) for cross-cutting changes, [engineering](docs/engineering.md) for new tests or build rules, and [the documentation index](docs/README.md) for the area you are changing. The [agent and skill index](.claude/README.md) points to operating procedures. The [historical guidance](docs/history.md#agent-guidance-before-the-648-compaction) preserves the earlier incidents and examples. ## Project overview -"Дневник" (`lessons`) is a school diary for Russian schools: an Android app with a -resizable home-screen widget, a FastAPI read API, and a Telegram bot that **is** the admin -panel. One class is edited from the bot or from a linked phone, and the same rules apply to -both. **The product speaks Russian; everything written about the project is English.** -User-facing strings live in `values/` (Russian, the source) and `values-en/` (the -translation), and the reader chooses the language in the app. The documentation, the code, -the identifiers, the comments, the commit messages and the pull request descriptions are -English, so that anybody can read them — and where any of those quotes a button, a menu path -or an error the user will see, it quotes it in Russian, in guillemets, because that is what -is on the screen. +«Дневник» is a school diary for Russian schools. The repository has an Android app and Glance widget, a FastAPI and aiogram server, the Vercel entry point in `api/`, a native HTTP/2 host, and a local Textual console in `tools/console/`. -Three deliverables in one repository: +The bot is the admin panel. Bot and linked-phone writes share `server/app/services/`. The server serves v1 beside v2 REST, Connect and native gRPC. The standalone Android flavor owns its class, timetable, homework and tasks in Room. It uses the same calendar resolution rules as the standard app but has its own application identity and authored storage. -``` -android/ Kotlin / Compose / Glance, six Gradle modules; logo/ beside them holds - the logo's generators, which write the launcher icons into - app/src/main/res (its README says how) -server/ FastAPI + aiogram in one process, one database, Alembic migrations -tools/console/ Python 3.12 / Textual developer console; its own uv lock and environment, - independent of the server package and Android runtime -api/ thin Vercel entry point that re-exports server/app/main.py -Dockerfile the host target's image (server/app/host.py), built from the root: - the whole app over HTTP/2, chosen instead of Vercel; server/Dockerfile - is docker-compose.yml's -proto/ the v2 contract (package lessons.v2), checked and generated by Buf from - buf.yaml and buf.gen.yaml at the root; its Python is committed under - server/app/contract/, and app/rpc and app/rest serve it beside v1 -docs/ eleven documents plus an index (docs/README.md), all English; ten are current, - and history.md is the record of every batch HANDOVER.md has handed on; - docs/diaries/ holds the per-platform reference pages of diaries.md; - docs/specs/ holds designs agreed with the owner before they are built, - and each sub-project's implementation plan beside its design; - docs/app/ (the in-app guide) and docs/legal/ (the terms and the privacy - policy) are product text the APK bundles, Russian source and English twin -``` - -There is no npm, no Node and no web frontend — with **one** deliberate exception: -`server/app/api/diary_web.py` serves a single server-rendered sign-in form at `/diary/signin`, -because a password typed into a Telegram chat is in the chat history, on Telegram's servers -and in that phone's backup, and deleting the message undoes none of it. No JavaScript, no -cookie, no build step. Do not grow it into a second admin surface: anything the bot can -express belongs in the bot. - -`requirements.txt` at the root exists only because Vercel's Python builder does not read -`pyproject.toml` from a subdirectory. It is a lock (#192) — every package the function can -import, at one exact version, for CPython 3.12 on Linux — compiled by `uv pip compile` from -`requirements.in`, which must stay level with `pyproject.toml`. The lock's header is the -command; never edit a pin by hand. CI installs the lock too, so the tests run on what deploys. -`server/requirements-host.txt` is the host target's lock: its server and nothing else, -compiled from `requirements-host.in` against `requirements.txt` by the command in its -header, for every platform, so the two cannot disagree (`test_host_image.py`); the root -`Dockerfile` and CI's «Host» job install both, and Vercel neither sees nor imports it. - -- Serialize pyvoy receive delivery and keep ASGI Future completions valid across cancellation; observe abandoned sends and stop only idle WatchClass on disconnect (`test_host.py`, #728). +The product speaks Russian. Use Russian `values/` as the source and English `values-en/` as its translation. Write documentation, code comments, commits and PR descriptions in English. Quote on-screen Russian text in guillemets. ## Commands -Python 3.11+ (`.python-version` says 3.12, CI runs 3.12), JDK 21, Android SDK with -compileSdk 37. Gradle comes from the wrapper — `./gradlew` works on a fresh clone. +Use Python 3.12 for CI parity, JDK 21 and Android compileSdk 37. Run Gradle through the wrapper. Use offline Gradle where the sandbox requires it. Install dependencies in the worktree's own editable server environment. Server, from `server/`: -- `python3 -m venv .venv && .venv/bin/pip install -r ../requirements.txt -e ".[dev]"` — setup, - CI's own install (#192), in each working tree's own `server/`, a `git worktree` included: - the install is editable, so a borrowed venv tests the tree it was made in, and - `conftest.py` refuses to start when it would (#312) -- **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from - `server/` covers the same tree -- **`pytest -q -n auto`** — 3916 tests, six of them skipped unless a - host is running (`-m host`, CI's «Host» job), plus eleven PostgreSQL-only lock - checks skipped on SQLite, and **the exact command - CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` - form puts the current directory on `sys.path` and the bare one does not, so a - `from tests.test_api import …` in a test file passes locally and fails at - *collection* on CI with «No module named 'tests'» about a directory that is plainly - there. That shipped once. `tests/test_test_imports.py` now refuses a test module - that imports another one at all — a shared fixture belongs in `conftest.py`, which - pytest loads by path rather than by import -- **`python -m mypy`** — one question, of all 242 modules, in seconds: does anything reach - for an attribute its type does not have? Configured in `pyproject.toml`, where every - other error code is switched off by name with its count and its reason. A CI step since - 27 September 2026, right after ruff, because the owner asked for it through that day's - audit (#210) — and still worth running before you push: seconds here, minutes there -- **`python scripts/check_test_counts.py server --junit work/pytest.xml`** — compare the - completed suite's default JUnit report with the measured facts in `docs/counts.json` -- `python -m pytest -q tests/test_schedule.py -k parity` — one file, one test -- `python -m uvicorn app.main:app --reload` — run it; add `--host 0.0.0.0` for a phone to - reach it -- `python -m app.host` — the host target: the same app over HTTP/2 under pyvoy, with native - gRPC and, with `LESSONS_STREAMING=true`, `WatchClass`; `--server hypercorn` is the - fallback. Needs `pip install -r requirements-host.txt` beside the dev install. Without - `LESSONS_TARGET`, which only the root `Dockerfile` sets, it runs on the local defaults -- `LESSONS_HOST_URL=http://127.0.0.1:8000 LESSONS_HOST_DATABASE_URL=sqlite+aiosqlite:///… - pytest -q -p no:xdist -m host` — the tests of a running host (`tests/test_host_live.py`, - with grpcio from `.[host-check]`), which every other run skips; CI's «Host» job runs them -- `python -m scripts.seed_demo` — demo class, join code `DEMO24` -- `DATABASE_URL='postgresql+asyncpg://…' .venv/bin/alembic upgrade head` — schema; never - from inside a request - -Contract, from the repository root, with Buf 1.73.0 fetched by hand (`docs/build.md`, «The -v2 contract and Buf»; the binary never enters the repository): - -- `buf lint`: the STANDARD rules, as CI's «Contract» job runs them -- `buf generate`: rewrites `server/app/contract/` and - `android/core/data/src/main/contract/java/` from `proto/` and the locked google.rpc input. - Commit both generated trees with their inputs; CI regenerates and diffs both -- `python -m pytest -q tests/test_contract.py` (from `server/`): what Buf cannot check. - Every method's REST binding, credential, least role and idempotency, against the resource - map of `docs/specs/2026-10-04-contract-v2-design.md`. Buf reads no options, so an edit to - that map **is** a breaking change (#299). Beside it, `test_contract_json.py` holds the - documented JSON against the runtime and `test_contract_mirror.py` holds the messages level - with the v1 schemas they mirror +- `python3 -m venv .venv && .venv/bin/pip install -r ../requirements.txt -e ".[dev]"` prepares this checkout. +- **`ruff check app tests scripts migrations`** +- **`python -m mypy`** +- **`python -m scripts.check_openapi_v1 --pull-request`** compares the v1 schema with the pinned base in the GitHub pull request event (#638). +- **`pytest -q -n auto`** — 3926 tests. Six host cases and eleven PostgreSQL lock cases have their own runtime requirements. +- **`python scripts/check_test_counts.py server --junit work/pytest.xml`** +- For a narrow run, use `pytest -q tests/test_schedule.py -k parity`. The bare entry point matches CI. +- `python -m uvicorn app.main:app --reload` runs the local API. `python -m scripts.seed_demo` creates the demo class with code `DEMO24`. +- `python -m app.host` runs the HTTP/2 target after installing `requirements-host.txt`. Pyvoy is the default, and `--server hypercorn` selects the fallback. See [host tests and deployment](docs/deploy.md#option-3-the-host-target). Android, from `android/`: -- **`./gradlew test`** — all JVM unit tests across the six modules -- `./gradlew :core:model:test --tests '*ScheduleEngineTest*'` — one module, one class -- **`./gradlew assembleDebug`** and **`./gradlew assembleRelease`** — CI builds both on every - push, because R8 and resource shrinking are where "worked in debug" stops being true -- **`./gradlew detekt`** — static analysis of the Kotlin in all six modules (#210), without - type resolution; fails on any finding the module's `detekt-baseline.xml` does not hold. - Fix a new finding, or `@Suppress` it in place with the reason — the baseline is the past -- **`python ../server/scripts/check_test_counts.py android --root .`** — compare the completed - JVM reports with the measured module totals, counting variant copies once -- `./gradlew detektBaseline` — rewrites all five baselines from the code as it stands; use - it for reviewed moves/removals and refresh sibling budgets in the same pull request. - `docs/build.md`, "detekt", has the rest -- `./gradlew lint` runs the AGP Android lint; CI does not, so do not report it as a gate -- `./gradlew :core:designsystem:connectedDebugAndroidTest` — the one instrumented source set - (#110), on a running emulator or a connected phone. Not a CI gate: CI has no device, and a - gate that cannot run is worse than none - -The app is set in **two** bundled faces, both under -`core/designsystem/src/main/res/font/` and both carrying one axis, `wght`: -`google_sans_flex.ttf` draws Latin and digits, `onest.ttf` draws Cyrillic, and -`FallbackTypeface.kt` chains them with `Typeface.CustomFallbackBuilder` because neither a -Compose `FontFamily` nor a font-family XML chooses by coverage. API 26–28 cannot express a -custom chain and get Onest alone. Google Sans Flex has **no Cyrillic at all**, which is why -the second file exists: while it was alone, every Russian word came from the device's -fallback beside digits from the bundle. `FontAxisTest` holds all three halves — the pair -draws Russian, neither carries an axis nothing varies, and no file is bundled unnamed. +- **`./gradlew test`** +- **`./gradlew assembleDebug`** and **`./gradlew assembleRelease`** +- **`./gradlew detekt`** +- **`python ../server/scripts/check_test_counts.py android --root .`** +- `./gradlew :core:model:test --tests '*ScheduleEngineTest*'` selects one class. Keep `lessons.nativeCheck=true` for native packaging only. The instrumented tests require a running device or emulator. +- Gradle lint is available locally. The Android CI gate runs Detekt. -- **Match late authentication refusals to the address and bearer actually sent, and compare before removal inside the persistence boundary** (`ManageMembershipTest`, `DiaryTokenOwnershipTest`, #747/#753). +Contract and console: -- **Keep current agent paths and test names resolvable** (`test_instruction_references.py`, #661); Server runs for every changed path because this guard inventories the whole tree. -- **Baseline rewrites keep or lower their sibling budget, refreshing accepted IDs in the same reviewed PR** (`DetektBaselineBudgetTest`, #635); both manual and current IDs consume it. - -- **Keep primary gate declarations level with CI and allowed command prefixes** (`test_gate_lists.py`, #659). - -The local console starts with `uv run --project tools/console lessons-console`. -From `tools/console/`, its independent gates are `uv run --locked ruff check lessons_console tests` -and `uv run --locked pytest -q`; fake processes and a headless pilot require no SDK. -See [its README](tools/console/README.md) for preparation, cancellation and scope. - -- Serialize Host startup with queued/running preparation or generation, and guard the post-queue/prelaunch boundary too (`test_console_6c.py`, #784). -- Revalidate the Host session and generation after an asynchronous listener probe so Stop cannot leave a marker check eligible to start (`test_host_check_race.py`, #787). - -CI (`.github/workflows/ci.yml`) is: ruff, mypy, pytest (`-n auto`), `./gradlew test`, both -assembles, and `./gradlew detekt` after them; and, when `proto/`, `buf.*` or -`server/app/contract/` changed, the «Contract» job: `buf lint`, `buf breaking` against the base, -and the check that the committed generated code is what `buf generate` writes; and, -whenever the server job runs, «Host», under pyvoy and under hypercorn: `python -m app.host` -started on SQLite, asked over native gRPC by `tests/test_host_live.py`; the path-filtered -«Console» job runs its lint and fake-process tests on Linux and Windows; and last, «CI», which -needs every job before it, runs whatever they ended as, and passes only when each one -succeeded or was skipped. It is the one check `master` requires, through the repository -ruleset that requires it, which the repository admin role can bypass (#424). The gates are -not required by their own names because «Host» is a matrix: a job its `if:` skips is reported -once, under the unexpanded `Host (${{ matrix.server }})`, so naming a skipped matrix leg -as required would leave «Expected» forever. Server and Host currently run on every changed -path; the aggregate also covers future conditional jobs (`docs/build.md`, «The check -`master` requires»). Nothing else. `apk.yml` builds an installable APK on demand or on a `v*` tag; -`reminders.yml` is a fallback clock, not the clock (see below). The workflows work — do -not edit them casually. The repository is public, so standard runners cost nothing; what -the workflows still carry from the months it was private is in `docs/build.md`, "Actions -minutes", and it is worth reading before undoing any of it — `-n auto` is there because a -full run was twenty-one billed minutes, and a short artifact retention because a full -artifact store reported a passing build as red. **Retention is no longer asked for in any -workflow**: this repository's own setting is lower than anything they requested, so every -`retention-days:` was silently reduced under a warning while three documents went on -quoting the number that had been asked for. +- Use Buf 1.73.0 as described in [the build guide](docs/build.md#the-v2-contract-and-buf). Run `buf lint`, `buf breaking` against the base, and `buf generate` when the contract changes. Commit both generated trees with their inputs. +- Start the console with `uv run --project tools/console lessons-console`. From its directory use `uv run --locked ruff check lessons_console tests` and `uv run --locked pytest -q`. The [console guide](tools/console/README.md) describes operation ownership and cancellation. +- CI runs Server and both Host variants on every path. Pull requests also check v1 OpenAPI compatibility against their base. Android runs its JVM suite, assemblies, Detekt, and report-count check. Contract and Console are path-filtered. The aggregate CI check accepts success or an actual skip. The APK workflow handles signed artifacts separately. ## Architecture -Read `docs/architecture.md` before any cross-cutting change; it is current and it explains -the decisions, not just the layout. - -**Two shells write, over one set of services.** The bot is the admin panel, and a linked -phone runs the same class through the API: the edit routes (`/api/v1/homework`, `/overrides`, -`/events`, `/days` — homework, substitutions, events, special days, editor and above; there -is no `/api/v1/edit` prefix) and `/api/v1/manage` (subjects, bells, the timetable, -devices, access requests, terms, the class itself — admin, and owner to delete it). Both -take the **device token** and ask `linking.effective_role` for the linked account's role on -every request, so an unlinked phone changes nothing of the class's. The rest of what the -API writes is personal (`public.py`: the linked account's own tasks and ticked-off -homework, whatever its role, and a phone unlinking itself; `/join` mints the device token) -and a family's diary (`/api/v1/diary`, with the **diary token**). That is the API. Of its -writes, the app itself makes only `/join`, `/me/unlink`, `/manage` and the diary's today, so -homework, substitutions, events, special days, personal tasks and ticked-off homework come -from the bot or another client of the API (#324, #331). `docs/architecture.md` has -the table. -Telegram already solved identity, so there is still no admin web panel, no session cookies -and no password reset — a phone has no rights of its own, only its account's — and the cost -is still real: anything the bot cannot express does not exist. `server/app/services/` holds -the rules both shells call — two thin shells over one implementation, because two -implementations of "rename a subject" disagree within a month — and **nothing under -`services/` may import `app.bot`**, directly or through another `app/` module: a rule that -lives in the bot is a rule the phone does not get, and a service that pulls aiogram in puts -it on the API's cold start. The role ladder lives in `services/roles.py` (`bot/roles.py` -re-exports it) and the wording both shells print in `app/wording.py`; -`tests/test_service_layering.py` holds the rule. - -Server modules: +### Server -- `models.py` — the whole SQLAlchemy 2.0 domain in one file -- `schedule.py` — template + overrides → concrete days. No FastAPI, no aiogram imports, and - it must stay that way: that is why its tests run in seconds -- `di.py` — the dishka container both shells draw from: `Settings` and the session - factory at app scope, one `AsyncSession` per HTTP request or Telegram update. An - endpoint asks with `session: FromDishka[AsyncSession]`; the bot's `ContextMiddleware` - opens the update's scope itself — **not** `setup_dishka`, which registers one middleware - on every observer and so opened two *sibling* scopes per message, either of which could - hand out a second session nothing commits — and it reads `container()` per update rather - than capturing one, because `api/telegram.py` caches the dispatcher for the life of the - process. It still commits there, because for a handler that is the finish line — but - only for one whose reply cannot lose its write. A handler that writes through a service - and then replies commits right after the write instead: the middleware's own commit runs - only once the handler returns, and rolls back when it raises, and a reply Telegram - refuses — an edit that changes nothing, a message already deleted — raises. It is - built with - `STRICT_VALIDATION`, so a second provider for a type is an error rather than a silent - shadowing. Do **not** import `dishka.integrations.aiogram` from it — that pulls aiogram - onto the cold-start path of every request, which is the thing `main.py` and - `api/telegram.py` already go out of their way to defer -- `services/` — the rules, as async functions over a session, and nothing may import - `app.bot`. A write leaves the commit to its caller, which commits it together with its - audit line, and a v2 handler cannot commit at all (`invoke` does). What still commits - inside itself does so either because its write has to stand whatever the caller does next - — a counted attempt, a spent unit, a phone's last call, a dead diary credential, a tick's - claim; `rpc/call.py` names those a v2 call meets — or because only the bot or the tick - calls it, as `linking.link_device` and `calendar.rotate_calendar_token`; v2 calls none of - those until its commit moves out, as 3b-4 moved the tasks', the ticks', the link code's and - the feed secret's, as 3b-7 moved a diary session's opening and closing, and as 3b-8 moved - the diary corrections'. - `services/manage/` is running a class, one module per screen named like the shells' - (`subjects`, `bells`, `devices`, `classes`, `requests`, `journal`, `terms`, `timetable`, - `special_days`, `search`): each does the check, the write and the audit line with its - Russian wording, and a refusal is an exception carrying facts, never a sentence, so each - shell keeps its own words — «Предмет … уже есть» in a chat, a `409` on the wire. The rules - v2 shares with v1 live here too: `join.py` (the join flow, refusing with facts), - `window.py` (the year's window and its tag), `clock.py` (the class's clock, the date - bounds, a list's `window`, and `wall`, a stored stamp on the class's clock), - `manage/classes.py`'s - `member_names` and `update` (the card's patch, the name recomposed), `manage/subjects.py`'s - `dictionary_of` (the read that adopts nothing) and `update` (the rename-then-details - patch), `manage/bells.py`'s `update` (the rename, the rows, then the default), - `manage/timetable.py`'s `import_paste` (the parse, the conflicts, and a preview that writes - nothing), `manage/requests.py`'s `approve` (the role sent or the one asked for, through - `access.approve_request`, whose `GrantRefused` says `why`), `directory.py`'s - `school_regions` (the anonymous directory's order of checks, one bucket for both - versions), `tasks.py`'s `create_task`, `update_task` and `set_homework_done` (a task's - homework of this class only, its reminder on the class's clock, a patch with `done`, a - tick set rather than toggled), `homework.py`'s `homework_of`, `due_between`, `put`, - `create`, `update` and `delete` (one assignment per subject per day, its line and its - notice), `events.py` (what an event stands in for when nobody says, its line and its - notice), `manage/special_days.py`'s `put_day` (the one write of a day's mark, which v1, - v2 and the bot make, its line and its notice through `set_day` and `update_day`), - `substitutions.py` (the three questions a substitution is asked, as facts, its line and - its notice), `diary.py`'s `register` (a phone's session kept and counted on both diary - limiters, refusing with facts), `target`, `sealed_form`, `window` (a diary read's days, - from the diary's own today) and `DiaryService`'s `student`, `child` and reads of one pupil, - `diary_corrections.py`'s `listed`, `correct`, `reset` and `clear` (what a child with no scope - may do, every correction checked before any is written, nothing committed, over - `diary_overrides.check_correction`), - `linking.py`'s `link_code_for`, `deep_link` and `unlink_self`, `calendar.py`'s - `feed_url`, and `audit.py`'s `older_than` (a page keyed on its last line); the limiters - are `security.py`'s, one instance each, and the sentences both versions answer with (the - join's four, the diary's «disabled», its sessions' three, its unknown pupil and its - corrections' four, and the - subjects', the devices', the bells', the - import's, the zone's, the access requests', the directory's, the tasks', the ticks', the - homework's, the events', the days' and the substitutions' refusals, and the notices to the - class) are - `app/wording.py`'s. - `gone.py` is what a row another writer deleted between a write's read and its commit - means to every shell (#384): «not found», never a server error and never a reason to make - the row again; its `committed` is the bot's commit, which rolls back and answers `False` - on a `StaleDataError` rather than raising out of the handler. - A class update flushes before its audit entry, including a journalled same-value write (#662). - Parent references lock before children; schedule deletion locks exclusively, rechecks references, then cascades (`test_stale_writes.py`, #677/#678). - The tick runs `health.py`'s self-check after the digests and the sweeps and before the - diary keep-alive: four fixed checks and one per «Сетевой город» region in use, each by its - route, what each said last in `health_checks`, and the owner's alerts on a change; the - owner's «📊 Проект» reads `project_stats.py`, which writes nothing. -- `api/` — `public.py` (the phone's reads and its own writes), `edit.py` (the day-to-day - writes), `manage/` (running the class, one module per resource over - `services/manage/`, with `_common.py` holding `Actor` and the one role dependency per - level), `diary.py`, `cron.py`, - `telegram.py` (webhook), `deps.py` (device-token auth), `routing.py` (the route class - every router here is built with: dishka's wrapper carries its own globals, so under - `from __future__ import annotations` FastAPI could not resolve an endpoint's - `-> Response` and took the name for a response model — a 204 route made that an - `AssertionError` at import, and every route without an explicit `response_model=` would - have had a schema built from a string; it also rolls back a write whose row another writer - deleted mid-write and answers the `404` its own `GONE` names for that path, #384) -- `bot/` — aiogram routers, roles, keyboards, renderers. «⚙️ Класс» is `handlers/manage/`, - one module per screen, each with a router of its own included in one written-down order - by the package's `__init__`. `handlers/start/` and `handlers/content/` are packages the - same way, and `manage_render/` and `manage_keyboards/` mirror the screens; each feature - outside «⚙️ Класс» has its own `*_render.py` and `*_keyboard.py` beside - `render.py` (which re-exports `app/wording.py`) and `keyboards.py`. - Every handler there says what it needs with - `@needs(Role.X)` (`handlers/manage/_common.py`) under its `@router…` line — one decorator - instead of seventy-two copies of the check, and a decorator rather than a filter or a - middleware flag because the check has to travel with the function: a failed filter hands - the update on instead of refusing it, and the tests that press every step as a - наблюдатель call the handlers directly. A refusal is an alert for a press, a sentence for - a command, and a dropped form with no answer for a step (`step=True`). - The weekly template has **two** editors and both are wanted: `handlers/timetable.py` pastes a whole weekday (fastest way - to enter a term), `handlers/editor.py` changes one lesson with buttons. They share one - grammar (`services/timetable_io.py`) and one set of mutations - (`services/timetable_edit.py`) — the editor's ‹ › pager and «⏱ Перемены» switch live in - the callback payload, never in FSM state -- `providers/` — the two foreign services, each behind `client.py` / `mapper.py` / - `models.py`. `petersburg/` is the electronic diary: nothing above `models.py` knows the - words `p_educations[]` or `X-JWT-Token`. `dadata/` is the school directory, a search over - the ЕГРЮЛ company register, because no downloadable register of Russian schools exists; - without `DADATA_TOKEN` - it refuses at the door and the bot asks for the name to be typed, exactly as the diary - refuses without `DIARY_SECRET`. The diaries are one table, `providers/diary/registry.py`'s - `TABLE`, a row per provider, which every question about a provider key reads — the binding, - the features, the corrections' scope, the keep-alive, the route through the proxy or - direct — and a session whose key no row answers is read by nobody -- `contract/` — the Python `buf generate` writes from `proto/lessons/v2/` (and googleapis' - `google/api` and `google/rpc`). Never edited by hand, since every regeneration deletes and - rewrites it. Skipped by ruff and mypy, and on the API's cold path on purpose since v2 is - served: `tests/test_contract.py` holds that in a fresh interpreter -- `rpc/` — v2's handlers, one module per proto service, over `services/`, and what every - method shares: `methods.py` (each method's facts, read from the descriptors), `gate.py` - (client version, then the bearer, the link and the role), `call.py` (`invoke`: the gate, - one dishka scope, the handler, the one commit, then the effects; and `stream`, which serves - `WatchClass` with the gate in a scope of its own for every check and no session held - between; and `GONE`, which answers a row deleted mid-write `RESOURCE_NOT_FOUND`, #384), - `caching.py` (`NEVER_STORED`, the one table of answers no cache may keep, which the REST - transcoder and the Connect adapters both read, so a Connect answer says - `private, no-store` exactly where its REST twin does, #357, #652), `errors.py` (the one error - table), `masks.py` (one reading of an `update_mask`, AIP-134), `dates.py` (a list's window, - a written date's bound, and the date a day is named by, read as v1 reads them) and - `handlers.py` (which methods are served, and `STREAMS`). A handler never commits and never - checks a credential; `rpc_app()` mounts the seventeen Connect apps at `/api/rpc`, refusing - native gRPC over HTTP/1.1 with `415`. May import `services/`, `models`, `schedule`, - `wording`, `security`, `schemas`, `config`, `crypto`, `di`, `api/deps.py`, the diary - registry and the diary's error family (`providers/diary/errors`, which the table words), - the school directory's provider (`providers/dadata`, whose refusals the error table maps), - `telegram_send` and the contract — never `app.bot` - or a v1 router, `api/directory.py` among them; `tests/test_service_layering.py` walks it -- `rest/` — the transcoder: one Starlette route per unary method from its `google.api.http` - rule, under `/api/v2`, calling the same `invoke`; `errors.py` writes Google's error body. - `main.mount_v2` mounts both and answers `503` under their prefixes if v2 will not import -- `telegram_send.py` — a bot built for one job and closed after it (`build_bot`, `close_bot`, - `send`, and `notify_class` for a class's subscribers), for the code that is not the bot: - the tick, v1's notices, v2's (an effect run after the commit) and the self-check's alerts. - aiogram is imported inside its functions and - never at the top, so it costs a cold - start nothing; `app.bot.bot` imports `build_bot` back from it, and - `tests/test_service_layering.py` holds that it reaches neither the bot nor a shell -- `observability.py` — Sentry's start and its scrubbing hooks, imported only where - `SENTRY_DSN` is set (`app.main` and the bot's error handler ask first). Every event is - rebuilt from a list of what may leave: an exception's type and stack, the route template, - the release and the environment; never a body, a header, a query, a message or a local - (152-ФЗ), which `tests/test_observability.py` proves on an event built from a real request -- `watch.py` — the class-changed bus `WatchClass` streams from: before each flush it collects - the class of every row written to a window table, a bell period through its schedule; - `touch` says the same for a bulk statement; the outermost commit publishes, a savepoint's - release never does, a rollback forgets. Attached by `app.main` only where streaming is on - (`Settings.streaming_enabled`, never on Vercel); neutral, so services import it -- `host.py` — the host target, `python -m app.host`: the app under pyvoy (or hypercorn) over - HTTP/2, native gRPC answered at the root too, pyvoy's Envoy told to take the client from - the connection. It reads the settings before any server starts and never sets - `LESSONS_TARGET`; nothing on the API's path imports it, pyvoy or hypercorn +- Keep the schedule resolver independent of FastAPI and aiogram. The domain is in `server/app/models.py`, the resolver in `server/app/schedule.py`, and the shared text in `server/app/wording.py`. +- `server/app/api/` supplies v1 routes. The editor's paths are `/api/v1/homework`, `/api/v1/overrides`, `/api/v1/events` and `/api/v1/days`. Class administration lives under `/api/v1/manage`. Read [the v1 and v2 contracts](docs/api.md) before changing either API. +- `server/app/rpc/` serves v2 handlers and gates. `server/app/rest/` maps `google.api.http` onto the same calls. Handlers return domain outcomes and register post-commit effects. Keep authorization, commit and structured refusals at the shared boundary. +- `server/app/bot/` owns routers, role-aware screens and renderers. Bot class settings live under `server/app/bot/handlers/manage/`. Put reusable rules in services and re-use their facts in both shells. +- `server/app/providers/diary/registry.py` owns provider capabilities and route choice. Keep upstream wire shapes within providers. The daemon-style host uses `server/app/host.py`; the serverless entry does not import pyvoy or hypercorn. +- Runtime dependencies are locked in `requirements.txt` for Vercel and `server/requirements-host.txt` for the host. Keep those locks aligned with the project metadata, and regenerate from the matching input. [Build and deployment](docs/deploy.md) describes the owners of environment configuration. -Android modules (`android/settings.gradle.kts`): +### Android -``` -:core:model pure JVM — domain types, ScheduleEngine, AlertPlanner -:core:designsystem theme, typography, Compose components -:core:data Room, domain remotes, REST/Connect, repositories, sync, notifications -:widget Glance home-screen widget -:app screens, navigation, ViewModels -``` +- `:core:model` holds pure JVM types, schedule resolution and alert planning. `:core:designsystem` owns themes and Compose components. `:core:data` owns transport, Room, repositories and sync. `:core:standalone` owns the local authored store. `:widget` renders with Glance and `:app` owns screens and navigation. +- The standard app reads Room as its source of truth. The dependency from data to the widget is a broadcast of `com.lumenpearson.lessons.action.DATA_SYNCED`. The graph belongs to the application even when a worker enters first. +- Keep wire DTOs and generated messages out of domain remotes and repository consumers. Supply the selected transport and version to the graph and sign with the identity captured at send time. +- The standard schedule keeps per-class school-year windows in Room. A recorded window distinguishes «нет уроков» from a year that has not been fetched. The diary has its own cache and can be the app's home without a class. Standalone authored storage has a separate schema and lifecycle. -Room is the single source of truth; the network only fills it. `:core:data` must **not** -depend on `:widget` — the timetable repository's `onDataChanged` tells the widget it has new -data, after the background sync and an in-app refresh alike, by broadcasting -`com.lumenpearson.lessons.action.DATA_SYNCED`, precisely so the dependency does not have to -be circular. +## Working rules -There are **two** Room databases: `lessons.db`, the class cache, and `diary.db`, the -family's own diary, which nothing writes but `DiaryRepositoryImpl`'s successful reads, under -a generation guard that drops a read landing after a sign-out. A phone is in one of three -shell modes — `CLASS`, `DIARY` (a diary and no class, whose home is the diary) or `NONE` (the -first run) — and the periodic class sync is armed in `CLASS` only (#152): -`LessonsApplication` collects `shellMode.syncArming` rather than scheduling on every settings -emission. - -**A window is one school year, and a class holds several of them.** `synced_window` says -which years this phone has fetched, `replaceWindow` replaces one and leaves the rest, and -`syncedYears` is what the screens read to tell «нет уроков» from «ещё не загружено». The -table exists because those two cannot be told apart by counting rows — a class made in -March has none before it either way. Three years are kept per class; what goes is the one -furthest from the year holding today, never that year, and its `ETag` goes with its rows. -Only the sync of the current year writes the lookahead row, and the ranged deletes spare -it — but **nothing writes it today**, and the claim that used to stand here is what sent an -audit looking. The server resolves `next_school_day` at most 21 days past the last lesson -*inside the window that was asked for*, and a window running to the school year's end -leaves only June, which is out of season for every class — `services/terms.py` refuses a -term past 31 May, so there is no class it could be in season for. What answers «what is -next» across a gap is `TimetableDao.firstTeachingDayAfter` over the cached year, which is -now a whole year rather than a fortnight; the row's residue is the last days of May. -`docs/architecture.md` says what a server change would have to be, and why it was not made. - -There is no Hilt. `Graph` is a small hand-written container a test can swap wholesale. -The application implements GraphOwner and supplies the required transport/version/streaming -configuration to the same container even when a worker or notification initializes first. -Schedule, Join, Me, management, directory and diary expose domain-valued v2 remotes; -strict DTOs/generated lite messages stay below repositories, with v1 retained for -compatibility fixtures. The shared server client signs at send time, and each call -retains its own refusal status or original no-answer exception. - -- Only DEVICE_TOKEN_INVALID revokes v2 membership; bare401/CLIENT_TOO_OLD retain cache and tags (`V2MembershipLifecycleTest`, `V2SyncRepositoryTest`). -- Run the complete JVM gate without the release AndroidTest target property; apply `lessons.nativeCheck=true` only to native APK packaging (`test_ci_required.py`, #737). -- Parse apksigner certificate identities across numbered and scheme-labelled output, excluding source stamps and refusing distinct signer identities (`test_ci_required.py`, #740). -- Schedule applies and revocations validate the sent server/token under the membership gate; completed exit/replacement wins (`V2InFlightMembershipTest`, `ScheduleObservationTest`). -- Capture the displayed server/class/bearer before queuing management or unlink actions; generation alone cannot hold the IO-dispatch gap (`ManagementInitiatingOwnerTest`, `DeviceLinkInitiatingOwnerTest`, #758, #761). -- Bind role caches and active Account refreshes to server/class/bearer, treating legacy unowned roles as unknown (`CachedRoleOwnerTest`, `SettingsViewModelTest`, #760). -- Diary cache commits need sent credentials and generation under the local identity gate; complete owned logout cleanup after credential commit (`DiaryAccountTransitionTest`, #762, #763). -- DIARY_CREDENTIALS_REJECTED refuses an already-open session, not its password (`DiarySignInRemainingFailureTest`, `DiarySignInTest`, #759). - -## Conventions already true in this codebase - -- **Comments explain why, not what.** Read almost any file here: the comment above a - decision says what would break without it. A comment that restates the line below it does - not survive review. -- **Russian in user-facing strings, English in everything written about them.** Both halves - are load bearing. `values/` is Russian and is the source; `values-en/` is the translation; - documentation, comments, commit messages and pull request descriptions are English. A - quotation of product text keeps its Russian and goes in guillemets — «⏱ Сокращённые - уроки», «Алгебра», «9А» — so a reader can tell a quotation from prose. -- **Every Russian string has an English twin.** `app/src/test/.../ResourceTranslationTest.kt` - reads both folders out of the source tree and fails on a name missing from `values-en/`, - on a name only in English, on mismatched format arguments, and on an English `` - that is not exactly `one` + `other`. Android resolves names one by one, so a missing - translation is not a missing screen — it is one Russian line in the middle of an English - one, with nothing logged. -- **No commit without lint and tests green.** `ruff check` and `pytest -q` for the server, - `./gradlew test` for Android; touch both halves and run both. -- **Versions are copied from a project that builds, never guessed.** The header of - `android/gradle/libs.versions.toml` names where each one came from. The first CI run of - this project failed on four invented versions that exist in no repository. -- **Commit messages are English sentences that say what the change makes the project do** — - "Let the class be run from the phone, by the same rules as from the bot". No Conventional - Commits prefix (none of the 288 commits has one), and the body explains the reasoning and - names what is left uncovered. No attribution trailer: commits up to 6 October 2026 mostly - carry a `Co-Authored-By: Claude …` line, none since does, and a new commit adds none - (`AI_USAGE_POLICY.md`, «Attribution in commits»). -- **Every pull request carries a milestone**, set when it is opened, and so does every - issue. A remote session can neither create a milestone nor list one, and a local one with - `gh` could, but creating one is the owner's decision either way — when none of the - thirteen fits, ask the owner and hand over the title and description already written, - rather than inventing a version or leaving the pull request bare. The `github-pr` skill - has the numbers, the one tool that sets them, and the two ways this was got wrong first. - **Four version milestones are open:** the ninth, `v0.8.0 — On-device checks, 89-region e-diary - survey`, holds #109–#117 and what #186's walk on an emulator found, the first work that - needs an emulator or a phone; the tenth, `v0.9.0 — NetSchool e-diary, onboarding via the - school's diary`, holds PR #140 and its issues, and the external audit of 27 September - (#190–#213); the eleventh, `v0.10.0 — One contract: REST v2, Connect and native gRPC, - build console`, holds the programme of `docs/specs/2026-10-03-one-contract-design.md` - (epic #273), and is the one being worked on; the twelfth, `v1.0.0 — A build somebody - else can install`, holds epic #127 and the open steps it names. Beside them stand two - buckets that are deliberately not versions: the seventh, `Dependencies — dependabot - bumps`, and the thirteenth, `Backlog — not scheduled`, for known gaps and decisions no - release is waiting for. The first ten were renamed on 25 September 2026, so a title quoted - from before then finds nothing when searched. -- **A defect that is found gets an issue, always, and before it gets a fix.** The rule is - new and it is not optional: the moment an audit, a review, a CI failure or a reader finds - something wrong, it becomes an issue of its own — title saying what is broken rather than - what to do about it, body carrying the failure scenario, `type:bug`, the `area:` it lives - in, a `status:`, and the milestone the fix will land in. **Then** the fix. A defect fixed - inside a batch and described only in a commit body is invisible the day somebody asks - «has this happened before», and eight bug sweeps' worth of that had to be back-filled by - hand in #128 to make this repository answerable at all. - - **The issue and the pull request are tied together**, and the tie goes in the pull - request: `Closes #NN` (or `Fixes #NN`) in its body. GitHub then links them both ways and - closes the issue when the pull request merges, so neither side can be left behind. One - pull request may close several; say each on its own line. - - **Labels are created by using them** — `issue_write` with `method="create"` makes a - label that does not exist yet. It does **not** when `parent_issue_number` is passed: - that path validates the labels first and fails on an unknown one. Create the issue - plainly, then link it. - - **The Project board is project 6, «lessons», and it holds every issue and pull - request.** A remote session cannot reach it — Projects v2 is GraphQL-only and that - toolset is REST — so there a session controls the labels and never reports an issue as - «added to the project» on the strength of having labelled it. A local session has `gh` - with the `project` scope, and there putting the item on the board and setting its - Priority, Size, Estimate and dates is part of filing it: no rule on the board sets those. - Its «Auto-add to project» has filtered on `is:issue,pr`, closed items included, since 4 - October, but #294's item, which it did add, showed in neither the board's views nor its - item list until it was deleted and added again, so read the board back after filing. The rule for every field is the project's README; the `github-pr` skill, «The - board», has the commands. -- **There are issues now, and until #85 there were none.** Forty-two were opened in one go - to give the history and the backlog a shape the milestones alone could not: twenty-three - closed, describing what was built and what each bug sweep found, and nineteen open, which - were then the whole of what was left. Read the open ones before planning a batch — several say - what was *deliberately* left and why, so that a later session does not re-discover a - decision as if it were an oversight. The labels are `type:` (feature, bug, chore, - research, decision, epic), `area:` (android, widget, server, bot, db, ci, docs, design, - data), `status:` (now, next, someday, done) and `needs:` (device, owner). The board - is the owner's (project 6, above); these labels are what its saved views filter on, and - its fields are what a local session keeps filled. -- **A release explains itself, fix by fix.** When a version is tagged, the notes name every - change in it with **its issue and its pull request** — «what was wrong, what it does now, - #NN / #MM» — rather than a list of commit subjects. The milestone is what says which - changes belong to the release, so it is set before the tag rather than after, and the tag - is the version the milestone is named for. The `release` skill has the order and what the - notes may not claim. Nothing in this repository has ever been tagged or released, so the - first one sets the pattern for every one after it. -- **Say what is not covered.** The README has an "Honest status" section and it is honest on - purpose. "Written, never run" is a legitimate status; a claim that something was - verified when it was not is not. -- **A new kind of test, a new CI check or a new shape of the build starts from - `docs/engineering.md`.** It reads this project against the engineering practice Airbnb has - published under one standard — a practice is taken only where it beats what is already - here — and says where this project is already ahead, what is left under epic #626, and - what was dropped and why. A proposal that brings back a dropped one says why its reason no - longer holds. -- **A trap that a test or a lint rule holds is one line here, naming what holds it.** Only a - trap nothing holds gets its paragraph, and the pull request that fixes a defect says «what - holds it» — a test, a rule, or «nothing can, because …» (the template). #648 is the cut of - this file to that rule. -- **Test at the cheapest layer that can hold the question.** `:core:model` before a view - model, a view model before a screen, a screen at a state built by hand before an - interaction, and never a Compose test for arithmetic. The `android-tests` agent has the - Android half, `server-tests` the server's. -- **A server change is read against the APKs already installed.** A merge to `master` deploys - itself and an installed app updates when its owner says so: nothing is removed or renamed - in what `/api/v1` answers, no new required field appears in what it is sent, and a v2 change - passes `buf breaking` or says why the break is safe. The pull request template asks it. +- Inspect `git status` before editing and read every caller of a changed function. Keep foreign worktrees, indexes and evidence intact. Run the touched area's documented gates before committing. +- File a defect with its failure scenario, labels and milestone before fixing it. Set a milestone when opening the PR and give each closed issue its own `Closes #NN` line. If no milestone fits, give the owner a proposed title and description. Follow [the PR procedure](.claude/skills/github-pr/SKILL.md) and verify Project 6 separately from labels. +- Use an English sentence that describes the change for each commit. Leave attribution trailers out as directed by [the attribution policy](AI_USAGE_POLICY.md). Comments explain the reason for a decision. +- Send work to `dev` on a temporary branch and promote reviewed `dev` to `master`. Merge your own PR after exact-head CI, local gates, milestone, clean merge state and review all pass. Pin the head SHA. Leave somebody else's PR, unsettled migrations and explicit owner reviews to their owners. +- Update [HANDOVER.md](HANDOVER.md) inside the open batch PR as its last edit. Archive the displaced batch in [history](docs/history.md) using [the handover procedure](.claude/skills/handover/SKILL.md). A close-out does not need its own close-out. Record what ran, what passed, and what still needs evidence. +- Preserve what installed clients receive from v1 and what their requests can omit. Check v2 compatibility with Buf and the contract suite. Build versions come from the repository's verified version catalog. +- Test at the cheapest layer that holds the behavior. Start new test or CI designs in [engineering](docs/engineering.md). State what holds a fix in its PR. Keep one source line per held trap, naming its current holder. Describe any gap in automatic coverage. +- Release notes connect changes to their issues and PRs, using the milestone before tagging. Follow [the release procedure](.claude/skills/release/SKILL.md). ## What will bite you -- **Current suite totals agree with `docs/counts.json`, regenerated only from complete successful reports** (`test_counts.py` and both CI post-run checks, #660). - -- **PostgreSQL test clusters need Unicode case conversion** (`test_search_folds_case_for_cyrillic_too`); the `C` locale does not satisfy it. - -- **The server has no clock.** On Vercel nothing runs between requests, so there is no - scheduler, no background task and no `asyncio` loop that survives a response. The morning - and evening digests are driven from outside by whoever calls `GET /api/v1/cron/tick` - with `X-Cron-Secret`. The endpoint marks a digest sent **before** sending it, and works - from "what is due and not yet sent today" rather than "did the last tick fire" — so a - tick that dies halfway does not send twice and a tick ten minutes late still sends. - Anything you are tempted to schedule in-process belongs in that tick instead. - The tick runs the self-check (`services/health.py`) after the digests and the sweeps and - before the diary keep-alive, which writes to `OWNER_IDS` when a check changes; when the - whole server is down, only the external cron's own failure email can say so - (`docs/deploy.md`, «The external cron»). - **The caller is an external cron service, not GitHub.** `.github/workflows/reminders.yml` - asked for a tick every five minutes and delivered 6.7 a day over five days of - measurement, in gaps of two to six and a half hours — GitHub runs schedules on a - best-effort basis and that is what the effort came to on a private repository. It still - asks for five minutes, because public runners cost nothing and the throttling may well - differ, but until that has been measured again it is the fallback: the promise the bot - makes («в течение примерно пяти минут») is kept by the external cron in - `docs/deploy.md`. -- **A deployment refuses to start rather than keep a local default.** `get_settings()` - raises `DeploymentNotConfigured` when `VERCEL` is set, or `LESSONS_TARGET` (the host - image's marker, `host` and nothing else), and any of `DATABASE_URL`, - `BOT_TOKEN`, `WEBHOOK_SECRET` or `RUN_BOT` is missing or unusable, or `OWNER_IDS` or - `TIMEZONE` is set to a value that cannot be used — an `OWNER_IDS` with no readable id, a - `TIMEZONE` that is not a zone. An empty `OWNER_IDS` is left alone on purpose - (`test_an_empty_owner_ids_is_left_alone`) and an unset `TIMEZONE` takes `Europe/Moscow`. - It lists every problem at once, because finding the next costs another deploy — with one - exception: `WEBHOOK_SECRET` is asked about only once `BOT_TOKEN` is set, since without a - token there is no webhook to protect (#331). This is - not tidiness: `DATABASE_URL` set for one Vercel environment and not the other left the - SQLite default standing, and the only thing anybody saw was - `ModuleNotFoundError: No module named 'aiosqlite'` out of SQLAlchemy's sqlite dialect — - a message naming neither the setting, nor the environment it was missing from, nor this - project. The check hangs on `VERCEL` and `LESSONS_TARGET` because each is a deployment's - statement about itself, and a `LESSONS_TARGET` that names no target is refused; guessing - "this looks like production" anywhere else would one day refuse to start on somebody's - laptop. **Do not add an optional setting to that list.** `DIARY_SECRET`, `DADATA_TOKEN`, - `PUBLIC_BASE_URL`, `BOT_USERNAME` and `CRON_SECRET` are empty by design and each already - refuses in view of whoever it concerns; `SENTRY_DSN` (nothing reaches Sentry) and - `GITHUB_READ_TOKEN` (the `deploy` check asks GitHub anonymously instead) are two more, - neither ever a reason to refuse to start. All are logged as switched off at startup - (`Settings.disabled_features`), which is a different decision from making them mandatory. - `DIARY_PROXY_URL` (#334) is optional too, and empty is not a switch but a route: no diary - goes through a proxy, which is right inside Russia. Only an unusable value is announced, - and never quoted, because it can carry the proxy's password. `DIARY_EGRESS` (#406) beside - it is optional as well, and best left unset: unset, or `proxy`, means the proxy where the - URL is usable — for Petersburg and the twelve «Сетевой город» regions marked `via_proxy` in - `regions.py`, every other region direct — and direct otherwise; `direct` sends nothing - through it; `relay` is read as `direct` until the relay exists (#408). Only what does not - take effect as written is announced, never a value. `providers/diary/registry.route` is the - one place that answers which way a server is reached. - `MIN_CLIENT_VERSION` is optional as well — empty means no minimum, and a request without - `X-Lessons-Client` is never refused — and it is not a feature switched off, so it is in - neither list. `LESSONS_STREAMING` is optional too — off unless `true`, and never on - Vercel whatever it says. What Vercel says about the running deployment — `VERCEL_ENV`, - `VERCEL_GIT_COMMIT_SHA`, `VERCEL_GIT_REPO_OWNER`, `VERCEL_GIT_REPO_SLUG` and - `VERCEL_REGION` — is no setting at all: `config.deployment()` reads it from the environment - alone, never from `.env`, and off Vercel it is empty. -- **A bulk statement on a window table must touch the bus.** `WatchClass` hears a class - change through the session (`app/watch.py`), and an `update`, `delete` or `insert` - executed directly never passes through the unit of work. Whoever writes one on a table a - schedule window is read from calls `watch.touch(session, class_id)` in the same function, - or a phone watching the class never learns of the change; `tests/test_watch.py` walks all - of `app/` for them, the bot included, and names the function that forgot. -- **The widget's size ladder has twelve rungs, and the count is the point.** - `WidgetSizeClass` (in `:widget`) declares twelve breakpoints because the launcher and - Glance both pick the **nearest** breakpoint by squared distance, not the largest that - fits. With five rungs, a 4-cell-wide widget taller than about 471 dp landed on the narrow - 110×300 column and drew half a screen of one column. Do not remove an intermediate rung to - tidy the enum; `WidgetSizeClassTest` reproduces the launcher's rule and will say so. -- **A phone gets into a class two ways, and one of them is not read-only.** The - class code (eight characters) buys an anonymous, read-only token. A personal - code from the bot's «📱 Подключить телефон» (ten characters, fifteen minutes, - one phone) buys a token already linked to the account that minted it, so it - writes with that account's role — checked per request, never cached. Both go - into the same `code` field of the same `POST /api/v1/join`; they cannot - collide because the lengths differ, and the class code is looked up first. - `SchoolClass.join_mode` decides whether the class code opens anything at all; - switching it revokes no device, in either direction, and three screens promise - that out loud. A `403` from `/join` means the class takes invites only — it is - deliberately *not* counted against the throttle, because that caller had a - real code. -- **There are two independent bearer tokens.** The device token from `POST /api/v1/join` - (`api/deps.py:current_device`) and the diary session token from - `POST /api/v1/diary/session` — a session the phone opened with the diary itself — or the - older `POST /api/v1/diary/login` (`api/diary.py:current_diary`). A phone can be joined to a class - without a diary account and signed in to a diary without a class; neither implies the - other, and one token meaning both would have to be re-minted whenever either half changed. - They go in the same `Authorization: Bearer` header on different endpoint families — check - which one an endpoint depends on before moving it. -- Petersburg sessions stay in request-local Cookie headers; named httpx/HTTP 422 deprecations fail pytest (`test_a_call_carries_its_own_session_in_the_request`, `filterwarnings`, #391). -- **The diary needs `DIARY_SECRET` or it does not run.** The upstream session — Petersburg's - token or «Сетевой город»'s bearer and cookies, however it arrived — is - the one stored credential that cannot be a hash (it is replayed upstream on every call), - so it is sealed with Fernet — `app/crypto.py`. No key means the feature refuses at the - door rather than falling back to plaintext, because a silent fallback is invisible and - deployments stay in that state for years. Refusing at the door also means touching nothing - behind it: with no key every seal reads as unreadable, so `services/diary.unusable` expires a - session only when a configured key cannot open it, and a request with a diary token is - answered «disabled» before the token is looked at. Until #302, a lost key expired every - session it was asked about, for good. `tests/conftest.py` sets one; a test that wants the - feature *off* patches it away. -- **Run the migration BEFORE the merge that needs it.** A merge to `master` deploys itself; - `alembic upgrade head` is run by hand. Between them is a window where the code knows a - column the database does not, and that window has already taken production down: the new - columns on `classes` landed first, nothing failed at startup, and the first ORM read of a - class did — which for the bot is the middleware, so every update died. Every revision - after `0001` is additive, so applying it to the *running* code is safe; the other order - never is. `GET /api/v1/warmup` answers `{"status": "degraded", ...}` when the database is - behind and names both revisions (`app/db.py:EXPECTED_REVISION`, pinned to the real head by - `tests/test_schema_version.py`), and `{"status": "degraded", "detail": "База впереди - кода…"}` in the window the correct order creates. `/api/v1/health` deliberately opens no - connection, so it cannot tell you this. -- **Apply migrations through the Neon connector, from here.** The owner does not run - `alembic upgrade head` by hand and this session has no `DATABASE_URL`; the project is the - one named `lessons` on the Neon MCP server — the account has two, so read the name rather - than guessing an id, and the id itself stays out of the repository — and `0005` through - `0019` were all applied that way, and from `0018` on each went to the Neon branch `preview` - first, when its pull request was pushed, and to production before the merge; every revision - now goes that way. It is not alembic running — it is the revision's DDL executed as one - transaction, with `alembic_version` stamped in the same transaction — so three things - follow. Take the DDL from the model rather than writing it out: `CreateTable(...).compile( - dialect=postgresql.dialect())` prints exactly what `create_all` would build, which is what - the revision is supposed to produce. Read the database's state first and stamp it last, so - a half-applied revision cannot claim to be whole. And say what a revision destroys before - running it — `0006` deletes every row of `diary_sessions` on purpose, and that is a - sentence the owner needs *before* the transaction, not after. -- **Migrations are Alembic and the head is `0019`, applied before the merge of the monitoring pull request, as `0018` was before stage 3b-1's; `0015` to `0017` were applied on 26 September 2026, before #140's merge.** `0001` is a guarded - `create_all`, `0002` widens Telegram ids to 64 bits, `0003` adds tasks/reminders/links, - `0004` adds diary sessions, `0005` adds `bell_schedules.canteen_after_index`, `0006` - encrypts the diary credential (and **deletes** the existing sessions, on purpose) and adds - the per-member diary columns, `0007` adds the two class foreign keys `0006` left out, - `0008` gives a class a number (1–11) and cuts its year into quarters or half-years, - `0009` adds the corrections a family lays over the diary, `0010` gives a class its join - mode and adds the personal connect codes, and `0011` tightens two `diary_overrides` - timestamps `0009` left nullable while the model builds them `NOT NULL` — a no-op on this - database, because the DDL for `0009` came from the model, and not one on a deployment - that ran the chain through alembic. `0012` does the same for eight more timestamps in - seven tables that `0003`, `0004` and `0006` left loose — and on this database it was - **not** a no-op: all eight really were nullable, and all eight held zero nulls, so it - tightened them and rewrote nothing. `0013` adds `uq_homework_per_subject_per_day` - and was **applied after the merge, not before** — see the constraint rule - below; on this database it deleted nothing, because `homework` held no rows - and therefore no duplicates. `0014` widens `day_overrides.kind` from - `VARCHAR(9)` to `VARCHAR(10)`, because `DayKind` gained `SELF_STUDY` and a - `SAEnum` stores the member **name** — the column is exactly as wide as the - longest one, so adding a kind is a migration rather than a line. It is the - ordinary additive shape and went on **before** the merge; it rewrites no row - and every existing value stays what it was. `0015` adds the second diary - provider's columns: `diary_sessions.provider` and `region` (which diary and - which regional server a session is on, so a session can be matched to its - class's binding and grouped per origin for the keep-alive without unsealing - the credential), three keep-alive clocks (`kept_alive_at`, - `keepalive_attempted_at`, `upstream_ok_at`), and on `classes` the binding - `diary_region`, `diary_school_id` and `diary_school_name`. All eight are - nullable and additive — the ordinary shape, on **before** the merge — and - rewrite no row; a NULL `provider` on an existing session means Petersburg, the - only diary before the column. Its downgrade expires every non-Petersburg - session before dropping the columns that tell one apart, so reverted code - cannot replay a credential at the wrong upstream. `0016` creates - `usage_counters`: one row per counter per Moscow day, which is how the - anonymous school directory's share of DaData's daily allowance is spent - without touching the share the bot's create-class search needs — a table of - its own, because `join_attempts` is pruned to fifteen minutes on every - recorded attempt and would cut a day's count to a quarter of an hour. It - creates a table and nothing else — additive, the ordinary shape, rewrites - and destroys no row — and goes on **before** the merge, together with - `0015`; its downgrade drops the table and with it nothing but the counts. - `0017` changes no schema: it files the corrections over the diary under the - **child** rather than under a login (#165, the owner's decision of 26 - September) — `diary_overrides.login` keeps its name and holds the scope - `services/diary_corrections.child_scope` builds, `CHILD:petersburg` or `CHILD:netschool:` - and the regional server's host and no other shape (a child the diary lists - outside its own numbering gets no corrections at all), upper case so that - no casefolded login can ever equal one. It **destroys rows**: every legacy - «Сетевой город» key (a hash whose region is recoverable at best for authors - still signed in; only where #140's branch ran), and, wherever two logins — - or a legacy and a per-child row — corrected the same field of the same - child, all but the newest (`updated_at`, then `id`); the rest of the old - Petersburg rows are rewritten to `CHILD:petersburg`. Its docstring carries a - count per destructive step to read before the transaction, and on - PostgreSQL it locks the table against writes first. On this database, with - no correction in it on 26 September, that was nothing, and it went on with - `0015` and `0016` **before** the merge. On a deployment that holds - corrections it is better applied just **after** the merge — a key rewrite, - a third shape beside the column and the constraint: before it, whatever the - old code writes in the window is filed under a login the new code never - reads; after it, the rewrite folds the old rows into what was typed - meanwhile, but a reset made in the window comes back, so the window is - minutes. Its downgrade is a no-op, and a revert is **not** lossless: after - any window of older code, run its statements again, or - `alembic downgrade 0016 && alembic upgrade head`. - `0018` adds `device_tokens.client_version`, the app version each phone last sent - to v2 (the server-v2 design, decision 15): one nullable integer column, the - ordinary additive shape, on **before** the merge. Its downgrade drops the column - and with it nothing but the versions. - `0019` creates `health_checks`, one row per check of the tick's self-check - (`services/health.py`): what it said last, since when, and when the owner was last - told. One new table and nothing else, the ordinary additive shape, on **before** the - merge; its downgrade drops the table and with it nothing but what the checks remembered. - Nothing after `0001` may use `create_all`. - Beware the enum: `SAEnum(SomeStrEnum)` stores the member **name**, so a `server_default` - written as `.value` is a string the ORM cannot read back — which on `classes` is a - `LookupError` in the bot's middleware, i.e. every update at once. `0010` nearly shipped - exactly that. A model change needs - a revision — a live database will not grow a column on its own, and lifespan `create_all` - runs only for local SQLite. -- **A constraint migrates in the opposite direction from a column.** The rule - above — migration first, merge second — is about code that knows a column the - database does not, and it is right for every additive revision in this chain. - A `UNIQUE` or a `NOT NULL` is the other way round: it is the **old** code that - breaks against it, with an `IntegrityError` nobody catches where a moment - earlier there was a duplicate. `0013` is that shape and says so in its own - docstring — it went on *after* the merge of PR #45, and `services/homework.py` - is written to be correct with or without it so the window in between behaved - exactly like production did before. `0012` is the safe shape (eight timestamps that already - hold no nulls) and was applied the usual way, before the merge. Read the - database before either: `0012` turned out to be a real fix rather than the - no-op `0011` was, because all eight columns really were nullable there. -- **The weekly template stops when the school says it stops, and twice it did - not.** `SCHOOL_YEAR_END_MONTH` is 5 and `schedule.py`'s comment says June - onwards must not repeat the template; nothing read it, so every summer weekday - drew a full day on the phone, in the widget, in the calendar feed and in the - morning digest — whose own rule about staying silent on an empty day could - never fire, because the day was never empty. That was the first half, and - `_resolve_day` started asking `school_year_bounds`. - The second half is that **the constant is not the school's answer — the terms - are.** A class whose «🗓 Четверти» said the half-year ended on 28 May still - drew lessons on the 29th, the 30th and the 31st, because the dates an admin - typed decided the term's *name* and nothing else, and 31 May is what - `SCHOOL_YEAR_END_MONTH` will always mean. `_resolve_day` now asks - `schedule.off_reason_for`, which reads the class's own terms for - that year and falls back to `school_year_bounds` only when the year has none. - The gaps **between** terms are out of season by the same rule, which is how - the autumn holidays get marked by moving two dates rather than nine days: the - conventional bounds are contiguous, so a class that never touched them is - unaffected. A day somebody marked by hand keeps its kind and note, and events - and homework are kept either way: it is the lessons that are out of season, - not the day. -- **Committed v1 replies are frozen before optional notices; bot construction and close failures cannot undo them** (`test_a_saved_event_survives_notice_lifecycle_failures`, `test_committed_edit_reply_survives_notification_session_expiry`, #377). -- **Notice warnings keep exception types, never exception values or tracebacks: Telegram request URLs can contain credentials** (`test_a_saved_decision_survives_notice_lifecycle_failures`, `test_a_saved_event_survives_notice_lifecycle_failures`, #723). -- **Class administration retains its parent before writes; diary cleanup, phone-code minting and calendar rotation leave commit to the complete caller transaction** (`test_access_member_parent_races.py`, `test_class_settings_parent_races.py`, #702, #703). -- **Device join retains Class before burning an invite or inserting a token; a known valid code losing its Class is forgiven, not counted as a guess** (`test_join_parent_races.py`, #705). -- **Timetable writes retain Class, canteen writes refresh and retain Class then Bell, and bot lesson input guards service execution with audit and commit** (`test_editor_parent_races.py`, #707). -- **Phone linking retains Class and leaves claim/audit/commit to both bot callers before Telegram success** (`test_phone_link_parent_races.py`, #708). -- **Task writes retain Class then recheck and retain linked Homework through commit; deleting Homework still keeps the task with a NULL link** (`test_task_homework_parent_races.py`, #710). -- **New personal tasks retain Class before INSERT, and bot add/commit share the stale boundary** (`test_task_parent_races.py`, #699). -- **Access requests retain Class before submission or the pending row lock; bot request writes and commits share the stale boundary** (`test_access_request_parent_races.py`, `test_access_request_submission_parent.py`, #697, #700). -- **Audited device revoke/unlink retain Class before mutation; already-revoked retries stay read-only** (`test_device_parent_races.py`, #696). -- **Nonempty subject collection and explicit deletion retain Class before DML; empty collection stays read-only** (`test_subject_collection_delete_races.py`, #695). -- **Subject creation retains Class after its name check and before either Subject or audit is staged** (`test_subject_create_parent_races.py`, #692). -- **Subject renames and audited details retain Class before Subject; repeated details still UPDATE their row** (`test_subject_detail_races.py`, #690). -- **Explicit term writes force row-count checks, and bounds retain Class before Term to match cascades** (`test_term_stale_audits.py`, #688). -- **An audited unchanged retry still forces a row-counting UPDATE; v2 silent no-ops skip it** (`test_unchanged_audit_races.py`, #686). -- **Homework creates and upserts retain their Class through commit** (`test_homework_parent_races.py`, #684). -- **Special-day writes retain their Class and selected BellSchedule through commit; only v2's silent unchanged result skips the guard** (`test_stale_writes.py`, #682). -- **A lesson number needs a bell of its own number, everywhere a lesson is - written.** The resolver takes a lesson's times from the bell row of the same - number and drops what has none, so a row at a number the day does not ring is - stored, logged, announced and drawn nowhere. Three ways in had to learn this - separately: the week import, the button editor, and — later — the substitution - (`api/edit.py` and `bot/handlers/content/overrides.py` then, and - `services/substitutions.py`, which v1, v2 and the bot all ask, now) and the bot's single-day - paste, which used to write the template itself instead of going through - `services/structure.apply_timetable`. Check with `timetable_edit.can_ring`, - and for a dated write use `rung_indexes_on`, because a shortened day points - at a shorter schedule than the class's usual. Two more ways in were closed - later: **deleting** a lesson closed the gap in the numbering whatever it - landed on (bells at 1, 2, 4 lost the fourth lesson onto a third slot that - rings nothing — `remove_lesson` now renumbers only when every moved lesson - still rings), and a day could be pointed at a bell schedule with **no rows**, - which draws nothing at all under a card saying «⏱ Сокращённые уроки» — - `special_days.put_day`, the one write v1, v2 and the bot mark a day through, - refuses that now. And when you report what was - dropped, count the **rows**, not the numbers: `apply_timetable` hands back - (weekday, number) pairs, because one number under two weekdays — or under - «чёт» and «нечёт» in one day — is two lessons nobody will see. -- **The diary sign-in ticket pays for an attempt, and an unreadable answer is - one.** `api/diary_web` spends the ticket before the sign-in so that whoever - holds the URL cannot sit and guess against the upstream from our address. Only - `UpstreamUnavailable` — a transport failure or a 5xx, where nothing ever - looked at what was typed — hands it back. A 200 of HTML must not: a login form - on Yii refuses a password with the same bytes a captcha arrives in, and this - diary has never been opened for real, so from here the two are - indistinguishable. The page says «дневник ответил непонятно» instead of - blaming the password, which is the part that was actually broken. -- **Time is naive local wall time, in the class's zone, not the server's.** A bell rings at - 08:30 whether or not the clocks changed. `SchoolClass.timezone` carries the zone; the - server decides "today" through `school_class.tz` and the client through - `Timetable.nowAtSchool()`. `LocalDateTime.now()` and `ZoneId.systemDefault()` on the - Android side are almost always a bug — that pair was two of the fourteen defects the audit - confirmed. -- **`Modifier.pointerInput(Unit)` keeps the lambdas it started with, for ever.** The - element compares equal on its keys alone, so a recomposition never even hands the node the - newer block, and the coroutine reading the finger goes on calling whatever it closed over - on the composition that created it. A state read through a delegate survives that; a plain - `val` computed in the caller's composition does not. The toolbar's reorder drag computed - its landing slot as such a `val`, so every drop asked where the tab had been *before* the - finger moved — `moveItem` refused the out-of-range index and the order came back unchanged. - It looked right the whole way, because the icons slide from a value recomputed every frame; - only the drop was stale, and the drop is the part that is remembered. Wrap every callback a - gesture detector will call in `rememberUpdatedState` — `text/Corrections.kt` already did, - which is what makes it a rule rather than a discovery. Do **not** key the `pointerInput` on - something that changes instead: that cancels the gesture under the finger. And a test that - only asks which callback fires, or only asks the arithmetic, will not see it — the question - is whether the number the gesture computes is the number it reports, and the way to ask it - without measuring Robolectric's densities is a drag so long it parks at the end under any - of them (`ToolbarDragTest`). -- **A Compose test that holds the clock must also send the snapshot notification.** - `MarqueeText` runs `Int.MAX_VALUE` iterations, so Compose's clock is never idle and - `waitForIdle` — which every assertion calls into — **hangs rather than fails**. The - answer is `mainClock.autoAdvance = false` and advancing frames by hand, and that buys a - second trap: a write made from the test thread (`ScrollState.dispatchRawDelta`, or a - `mutableStateOf` the composition reads) lands in the global snapshot and **nothing sends - the apply notification**, so neither the recomposer nor `snapshotFlow` ever wakes and the - value arrives after the last assertion has read it. Advancing frames does not help at any - count — twenty still read zero. Every `settle()` here calls - `Snapshot.sendApplyNotifications()` first. `LazyListState.scrollToItem` happens to escape - it, because `forceRemeasure` runs a measure pass inside a snapshot of its own, which is - exactly why the ribbon half of one test looked right while the list half did not. - The third trap in the same family: `performScrollTo` drives the scrollable's animation, so - with the clock held it moves nothing and every node below the fold reports «not - displayed», which is indistinguishable from the element being absent. Give the test a tall - window instead. -- **`compose-stability.conf` is a promise, and a `var` in `:core:model` breaks it.** The file - tells the Compose compiler that `java.time.*` and the whole domain package are stable, - because neither is compiled by the Compose plugin and one unknown field makes every class - holding it unstable — that one field was `LocalDate`, and it condemned `TodayUiState`, - `WeekDayUi`, `HomeworkUiState` and the diary's day and range along with it. What a false - promise costs is invisible: nothing fails to build and nothing throws, Compose simply stops - comparing the value and the screen keeps the old one. `StabilityPromiseTest` reads - `:core:model`'s own source and fails on the first `var`; if a type there has to become - mutable, move it out of the module and take the package off that file rather than leaving - both standing. The file itself says at length what is deliberately *not* promised — - `kotlin.collections.List` and `:core:data`'s value types — and why each would be a lie. - Re-measure with `reportsDestination` in a module's `composeCompiler` block and a - `--rerun-tasks` compile; it is left out of the build on purpose, because it writes reports - on every build and the question is asked rarely. -- **AGP 9 compiles Kotlin itself.** Applying `org.jetbrains.kotlin.android` in an Android - module is a hard build failure, not a warning. Pure-JVM modules still use `kotlin.jvm`. -- **The bot runs two ways from one dispatcher.** Long polling inside the API process - (`app/main.py` lifespan) locally, webhook on serverless, `build_dispatcher()` shared. FSM - state lives in the database (`app/fsm_storage.py`), not in memory, because each update may - hit a fresh process. `RUN_BOT=false` starts the API alone — that is what the tests use. - -- **On SQLite, a savepoint opens a transaction that keeps its lock until it ends** (#373). - `app/db.py` begins the transaction a `begin_nested()` assumes, so a refused write is rolled - back on the test suite's and a developer's SQLite as it is on Postgres. The price is a lock: - a bot handler that writes through a savepoint commits before it touches conversation state, - because the FSM storage commits on a connection of its own and would wait out the busy - timeout behind it. That is thirty seconds of a hung local bot, which no test sees, since the - handler tests hand the handlers a fake state. Production is Postgres and takes no such lock. - -## Notes - -- **A message Telegram will not deliver is a screen that says nothing.** The - ceiling is 4096 characters after entity parsing, and the whole message is - refused rather than clipped: the homework digest had no bound and a fortnight - of three assignments a day came to 5371, so «📝 Домашнее задание» answered «что-то - пошло не так» and `/homework` — a plain `answer`, with no callback to - apologise on — answered nothing at all. Every renderer that grows with the - data carries a budget (`WEEK_TEXT_LIMIT`, `TASK_LINES_MAX`, - `HOMEWORK_DIGEST_LIMIT`, `render.clamp`) and says «… и ещё N». Cut a - string **before** escaping it: cutting after can leave «&am», which is a - refused message of its own. -- **Everything from outside is escaped before it goes into a message.** The bot sends - HTML, and Telegram refuses the **whole message** on a stray `<` rather than damaging one - row — so an unescaped string does not produce a broken line, it produces a blank screen - and no error anybody sees. The strings that come from outside are: anything the - Petersburg diary sends (subject, room, teacher, topic, homework), anything typed into - the bot or pasted into the timetable grammar (a subject really can be «Алгебра <7>»), - and anything out of the schools registry. `render.py`, and the per-screen renderers split - out of it (`week_render`, `homework_render`, `tasks_render`, `access_render`), always did this; - `diary_render.py` and `editor_render.py` never did, and both shipped that way. - Two related traps in the same family: `plural(n, …)` already contains the number, so - `f"{n} {plural(n, …)}"` prints «10 10 минут» — three callers had it, and one had a test - that passed because «10 минут» is a substring. And `answerCallbackQuery` takes no parse - mode, so a card built for a message shows its own tags in an alert; run it through - `editor_render.as_alert` instead — which also cuts at 200 characters, because past - that Telegram answers 400 and the press answers nothing at all. -- **A list page and the keyboard under it read the same number.** `manage_render` - declares `SUBJECTS_MAX`, `BELLS_MAX`, `DEVICES_MAX` and `LIST_MAX` beside each page's - renderer, and `manage_keyboards` builds that page's rows from the same names. While there were two - numbers, three pages of four drew rows no button could reach and «… и ещё N» said - nothing, because it counted from the renderer's number. The values differ on - purpose — a bell schedule's row carries three buttons and twelve lines of times, a - subject's one of each — so do not "tidy" them into one constant; the rule is that - what is drawn is what can be pressed, and - `test_no_list_page_draws_a_row_the_keyboard_cannot_reach` holds it. Nothing - paginates, so past the cap a row is only a number. -- **Callback data is whatever the client sent, and a bare conversion on it is not - a small bug.** `int(callback_data.value)` does not refuse a press it cannot parse - — it raises out of the handler, so `callback.answer()` is never reached and the - button keeps its spinner until Telegram gives up. Every handler module carries a - guard for this: `_int_or_none` in `manage/_common.py`, `tasks.py`, `content/homework.py` and `access.py`, - `_date_or_none` in `calendar.py` and `content/_common.py`, `_role_or_none` in - `access.py`, `_kind_or_none` and `_index_or_none` in `content/_common.py`, and - `shift_days`/`shift_weeks` in `keyboards.py` for the offsets (`timedelta( - days=999999999)` is an OverflowError, not a far-away day). Check the value - **where it is picked**, not where it is finally read: a value carried through - three questions raises in front of somebody who has just typed a time and a - title, and looks like their answer was the problem. -- **Two screens can match one press.** Both role pickers send a `RolePick`, and the - only thing telling them apart is that the invite flow leaves `target` empty. While - the invite handler's filter was a bare `RolePick.filter()` it swallowed both, - because it is registered first — so a role pressed on an older «Новая роль» card - created a phone invite and said so in a sentence about the number. Split a shared - payload on a field, never on registration order; - `test_the_two_role_pickers_never_match_the_same_press` holds it. - The pairs that predate the rule — `/start link_…` and `/start`, a shared - contact and the create-a-class wizard's text steps, the two `TimezonePick` - handlers — are held in their order by `test_bot_commands.py`, so a router - split cannot reorder them quietly. -- **`ResourceTranslationTest` covers every module that ships strings**, not just - `:app` — `:core:data`, `:core:designsystem` and `:widget` have their own - `values/` and went unguarded for a long time, which is how the countdown on the - home screen stayed Russian under an English caption. It discovers the modules - rather than listing them, and counts a ``' arguments per form (Russian - has four forms and English two; over the concatenated text they can never agree). - What it cannot see is a Russian string written into Kotlin, because that word is - in neither folder. The check for that, run from `android/`, is - `LC_ALL=C.UTF-8 grep -rnP --include='*.kt' '^(?!\s*(\*|//|/\*)).*"[^"]*[\x{0400}-\x{04FF}]' */src/main core/*/src/main`. - Each part is there for a reason (#315): - - `core/*/src/main` because `*/src/main` alone never reaches the three core modules; - - the comment guard because KDoc here quotes Russian on purpose and would bury a finding; - - the locale because Git Bash's `grep -P` refuses to run without it. - - Today it finds only `@Preview` data, maintainer-facing report bodies, the timezone list, - whose file documents the choice, and `core/data/.../upstream/UpstreamMarkers.kt` — the - diaries' own words, matched in their answers, which is the one documented exception on the - diary's side. -- **A renderer is written against the type it is handed, and nothing checks that but you.** - «🗓 Четверти» crashed on every press in production because the card printed `term.days` - and `days` lived on a flattened copy of a term that nothing ever constructed. There is - no compiler here. `python -m mypy` is: it reproduces that exact failure when the property - is removed, and it is clean today. If you add a «view» dataclass beside a model, check - that something builds it — an unused twin is how a renderer ends up written against the - one it will never receive. -- **An enum column stores the member NAME.** `SAEnum(SomeStrEnum)` writes - `OPEN`, not `open` — check `bot_users.role` in the live database if you doubt - it. A `server_default` spelled as `.value` therefore lands an unreadable - string on every existing row, and the first ORM read of one raises - `LookupError` — which on `classes` is the bot's middleware, i.e. every update - at once. `0010` was written that way and caught before it was applied; - `tests/test_join_modes.py` now holds all three sides of it. -- **The developer mode's gate is not a lock** (#237). Seven taps on the version reveal - «Для разработчиков», and a GitHub account with push to this repository opens it, but an - APK can be patched past any check on the phone. So nothing behind it may unlock what the - server would refuse or show a secret. Its network record keeps a list of what it may keep - (`NetworkRedaction`): a header, a body or a query value added later stays out unless - somebody adds it to that list on purpose. Its request console reaches our server and the - catalog's diaries only — `planConsole` judges the resolved URL, and the console's own client - follows no redirect and guards the origin again — and puts a bearer on our server alone, - read as the request leaves. `docs/architecture.md` has the rest. -- **Work enters dev through one temporary branch; only reviewed dev is promoted to master** (#724). Both persistent branches run Actions; remove a working ref after its dev merge, never its worktree files or unique work. -- **A diary session deleted while changing pupils is signed out, with rollback before any reply** (`test_the_bots_diary_says_a_session_signed_out_meanwhile_is_signed_out`, #725). -- **Another agent may be working in this tree.** Check `git status` before you touch a file - you did not open, and do not revert someone else's uncommitted work. -- **`HANDOVER.md` at the root says where the work stands** — the branches, what the last - session finished, what it deliberately left alone and what nothing has verified. It is - working state, not part of `docs/`, so it is stale the moment it stops being updated: - re-check the PR and CI before trusting it. It carries the last two batches; every batch - before them is in `docs/history.md`, newest first, verbatim. -- **A pull request of this session's own work is merged without asking.** The owner asked for - that on 20 September 2026; it is their standing instruction, recorded in the `github-pr` - skill with the five things to check first — CI green on the exact head, `mergeable_state` - clean, the gates run locally before the push, a milestone attached, and no review waiting - on an answer. The merge pins `expectedHeadSha` to the SHA that was checked, which is what - makes it safe. A migration whose side of the merge is unsettled, somebody else's pull - request, and «I want to look at this one» are outside it. -- **Updating it is the last step of every batch, and nobody should have to ask for it.** The - trigger is the merge: once a pull request is in `master`, that batch is not finished until - this file describes it. Write the close-out **while that pull request is still open** — it - is then one pull request rather than two, and the file is true at the moment it merges. - **A close-out never gets a close-out of its own:** it names itself as the only thing open, - and the SHA of its own merge is written by the next batch. A pull request whose only - content is correcting that SHA is the recursion rather than the cure. It has had to be asked for twice, and each time a batch had been - reported as done while the one document the next session starts from still described the - batch before. If the batch's own pull request has already merged, the update is its own - commit and its own pull request — with a milestone, like every other. What drifts every - time, and is not a judgement call, is listed in the `handover` skill: the opening - paragraph, the chain of batch sections — the new one on top, and the one that falls off - the last two moved to the top of `docs/history.md` — the milestone table, the test counts - in the seven places the skill names, and sections 5 and 7. -- **`.claude/` holds the agent configuration, and it describes the shape rather than - repeating this file.** `.claude/agents/` has one agent per area that has produced a defect - here, carrying the fact that would have prevented it; `.claude/skills/` has the procedures - (`gates`, `audit`, `migration`, `release`, `strings`, `bot-message`, `steward`, - `github-pr`, `handover`, `large-refactor`); `.claude/commands/` has `/where-are-we` and `/pre-push`; - `.claude/README.md` says what is deliberately absent — there is no `.mcp.json`, because - the Neon and Vercel connections need credentials. `AGENTS.md` and - `.github/copilot-instructions.md` are the same pointer for agents that read those instead. -- **Read a file before editing it; grep every caller before changing a function.** The - audits in `docs/design.md` exist because a conclusion drawn from call sites was wrong. -- Secrets never enter the repository: `BOT_TOKEN`, `OWNER_IDS`, `WEBHOOK_SECRET`, - `CRON_SECRET` live in `server/.env` or the host's environment; the release keystore and - its passwords come from the `LESSONS_KEYSTORE_FILE`, `LESSONS_KEYSTORE_PASSWORD`, - `LESSONS_KEY_ALIAS` and `LESSONS_KEY_PASSWORD` environment variables (in Actions, from the - secrets `KEYSTORE_BASE64`, `KEYSTORE_PASSWORD`, `KEY_ALIAS` and `KEY_PASSWORD`; #309) or from - `~/.gradle/gradle.properties`. **Never read or print that file**: on 5 October 2026 an agent - looking in it for a Gradle setting put a signing password into its transcript. Redact them as - `` in issues, logs and reports. -- The documentation index is `docs/README.md`. If a change makes a document wrong, fix it in - the same batch — `docs/widget.md` and `docs/bot.md` were each rewritten once because they - had drifted from the code, and that is more expensive than keeping up. +### Deployment and schema + +- Reject hosted configuration that would inherit local defaults. Keep optional features optional and log unusable settings without their values (`test_deployment_config.py`). +- Route diary traffic through the provider registry. An unset proxy means direct traffic, and an unavailable relay currently falls back to direct (`test_diary_egress.py`). +- The external tick claims a digest before sending. Health budgets reserve time for owner alerts (`test_cron_tick_delivers_a_morning_digest_once`, `test_health.py`). +- Head is `0019`. Keep `app/db.py:EXPECTED_REVISION` level with the Alembic chain and its current references. Diagnose drift through `/api/v1/warmup` (`test_schema_version.py`). +- Declare each new revision's merge side and potential data loss. Apply additive changes before merge and incompatible changes afterward (`test_migrations_declare_the_side_their_upgrade_requires`, #642). +- Generate Alembic DDL from the model and store string-enum member names in defaults, as SQLAlchemy does (`test_join_modes.py`, `test_quota.py`). +- Begin the real SQLite transaction before opening a savepoint so rollback can undo its writes (`test_sqlite_transactions.py`). +- Roll back a still-open SQLite transaction before its pooled connection can be reused after a refused commit (`test_sqlite_transactions.py`, #378). +- Keep gate declarations and command permissions level with CI (`test_gate_lists.py`, #659). +- Run the server check whenever anything it reads changes, including agent instructions and paths they refer to (`test_ci_paths.py`). +- Regenerate `docs/counts.json` only from completed successful test reports and keep current declarations in sync (`test_counts.py`, #660). +- Keep instruction file references and test names current (`test_instruction_references.py`, #661). Server runs for every changed path because the guard inventories the whole tree. + +### Server composition and access + +- Keep shared services clear of `app.bot` and v2 clear of both the bot and v1 routers. Import aiogram lazily on request paths (`test_service_layering.py`, `test_cold_start.py`). +- Keep one request or Telegram-update session per unit of work. Commit v2 writes before effects and skip effects after refusal (`test_di.py`, `test_rpc_call.py`). +- Take locks on parent rows before dependent writes. Schedule deletion locks exclusively, rechecks references and then cascades (`test_stale_writes.py`, #677/#678). +- Return the existing resource-not-found response when a row is deleted during a write (`test_stale_writes.py`, #384). +- Share v2 cache policy between REST and Connect, including `private, no-store` for sensitive answers (`test_v2_no_store.py`). +- Stream `WatchClass` without an open database session between gates. Call `watch.touch(session, class_id)` from bulk writes on window tables (`test_watch.py`). +- The class code admits a read-only phone. A one-use personal invitation links its phone to the issuer. Invite-only mode does not revoke existing phones (`test_join_modes.py`, `test_join_parent_races.py`). +- Keep class/device bearers separate from diary/session bearers and check the current link and role per write (`test_rpc_gate.py`, `test_v2_diary_sessions.py`). +- Make diary access fail closed when `DIARY_SECRET` is unset and keep existing records intact (`test_v2_diary_sessions.py`, `test_diary_session.py`). +- Spend a diary sign-in ticket per attempt, including an unreadable answer. A transport outage gives it back (`test_diary_web.py`). +- Petersburg sessions stay in request-local Cookie headers. Keep the named httpx and HTTP 422 deprecations enforced by pytest (`test_a_call_carries_its_own_session_in_the_request`, #391). +- NetSchool search prefers non-blank `address` and falls back to `addressString` on both runtimes (`diary_protocol.json`, #412). +- Sentry sends only allowlisted fields from scrubbed events (`test_observability.py`). +- Serve v2 from the generated contract and regenerate both outputs. Keep the REST/auth map, JSON examples and v1 mirror checked (`test_contract.py`, `test_contract_json.py`, `test_contract_mirror.py`). + +### Server writes + +- Freeze committed v1 replies before optional messages. A failed send or close must leave the saved answer usable (`test_a_saved_event_survives_notice_lifecycle_failures`, `test_committed_edit_reply_survives_notification_session_expiry`, #377). +- Bound post-commit notices and cron delivery. Ticks leave later reminders due while keeping the claim for the row already being processed (`test_a_hung_cron_send_and_close_leave_later_reminders_due`, #371). +- Log only the exception type in v1 notice warnings. Telegram request URLs can contain credentials (`test_a_saved_decision_survives_notice_lifecycle_failures`, `test_a_saved_event_survives_notice_lifecycle_failures`, #723). +- Class administration retains its parent before writes. Diary cleanup, phone-code minting and calendar rotation leave commit to the caller's complete transaction (`test_access_member_parent_races.py`, `test_class_settings_parent_races.py`, #702/#703). +- Device join retains Class before consuming an invite or inserting a token. Losing the class after a valid code does not count as a guess (`test_join_parent_races.py`, #705). +- Timetable writes retain Class before Bell. Bot lesson input rolls back the service write and audit together (`test_editor_parent_races.py`, #707). +- Phone linking retains Class, and both bot callers commit the claim and its audit before sending success (`test_phone_link_parent_races.py`, #708). +- Task writes retain Class before linked Homework. Removing Homework leaves the task with a null link (`test_task_homework_parent_races.py`, #710). +- New tasks retain Class before inserting. Bot task add guards both the service call and the commit (`test_task_parent_races.py`, #699). +- Access requests retain Class before submission or locking the pending row, including bot writes and commits (`test_access_request_parent_races.py`, `test_access_request_submission_parent.py`, #697/#700). +- Device revoke and unlink retain Class before mutation. Already-revoked retries are read-only (`test_device_parent_races.py`, #696). +- Nonempty subject collection and explicit deletion retain Class before DML. An empty collection stays read-only (`test_subject_collection_delete_races.py`, #695). +- Subject creation retains Class after the name check and before staging the subject or audit (`test_subject_create_parent_races.py`, #692). +- Subject renames and audited detail writes retain Class before Subject. A same-value detail update still checks its row count (`test_subject_detail_races.py`, #690). +- Explicit term writes check affected rows and retain Class before Term (`test_term_stale_audits.py`, #688). +- Journalled replays with unchanged values still update to check the row count. Silent v2 no-ops skip this update (`test_unchanged_audit_races.py`, #686). +- Homework creates and upserts retain Class through commit (`test_homework_parent_races.py`, #684). +- Special-day writes retain Class and the selected bell schedule. Only silent v2 no-ops omit the guard (`test_stale_writes.py`, #682). +- A written lesson needs a bell of its number. Use the bell schedule actually effective on the date for substitutions (`test_timetable_edit.py`, `test_api_extended.py`, `test_schedule.py`). +- The weekly template stops outside the class's terms, or the default school year if it has no terms. Keep dated homework, events and day metadata (`test_schedule.py`, `LocalScheduleResolverTest`). +- When a bot diary session disappears during a change of pupil, roll back before replying that it is signed out (`test_the_bots_diary_says_a_session_signed_out_meanwhile_is_signed_out`, #725). + +### Android and console + +- Keep the widget's twelve size classes. The launcher chooses the nearest breakpoint (`WidgetSizeClassTest`). +- Keep both bundled font families with their intended `wght` axis and script coverage (`FontAxisTest`). +- Use `rememberUpdatedState` for callbacks invoked by a long-lived `pointerInput(Unit)` gesture. Changing the key cancels that gesture (`ToolbarDragTest`). +- Keep `:core:model` immutable when it is declared stable in `compose-stability.conf` (`StabilityPromiseTest`). +- Match late auth refusals to the address and bearer sent before removing persisted membership or diary credentials (`ManageMembershipTest`, `DiaryTokenOwnershipTest`, #747/#753). +- Only `DEVICE_TOKEN_INVALID` revokes v2 membership. A generic 401 or `CLIENT_TOO_OLD` keeps cache and tags (`V2MembershipLifecycleTest`, `V2SyncRepositoryTest`). +- Guard schedule application and revocation under the membership gate with the sent server and token (`V2InFlightMembershipTest`, `ScheduleObservationTest`). +- Capture displayed server, class and bearer before queueing a management or unlink action (`ManagementInitiatingOwnerTest`, `DeviceLinkInitiatingOwnerTest`, #758/#761). +- Scope persisted roles and active Account refresh to server, class and bearer. Legacy ownerless roles are unknown (`CachedRoleOwnerTest`, `SettingsViewModelTest`, #760). +- Guard diary cache writes with sent credentials and generation. Finish owned cleanup after committing logout credentials (`DiaryAccountTransitionTest`, #762/#763). +- Map `DIARY_CREDENTIALS_REJECTED` on an already-open session to server refusal, separately from password rejection (`DiarySignInRemainingFailureTest`, `DiarySignInTest`, #759). +- Keep the opt-in instrumented APK separate from the full JVM gate. Verify real signer identities in apksigner output across number and scheme labels, excluding source stamps (`test_ci_required.py`, #737/#740). +- Keep each changed Detekt baseline within its reviewed sibling budget and update the accepted IDs in the same PR (`DetektBaselineBudgetTest`, #635). +- Keep standalone migration proofs through Room and preserve the ID and revision of authored changes (`LocalHomeworkMigrationTest`, `LocalPersonalTaskStoreTest`). +- Serialize Host startup against preparatory and generation commands, including the queue-to-launch window (`test_console_6c.py`, #784). +- Revalidate the Host session and generation after the asynchronous listener probe before starting its marker check (`test_host_check_race.py`, #787). + +### Rendering and input + +- Keep every shipping Russian resource paired with English, including format arguments and each locale's plural forms (`ResourceTranslationTest`). +- Budget growing Telegram messages for the 4096-character limit. Cut user data before escaping HTML (`test_bot_message_limits.py`, `test_announcements.py`, `test_a_day_escapes_the_room_the_note_and_the_event_somebody_typed`). +- Build rendered management rows and buttons from the same page cap (`test_no_list_page_draws_a_row_the_keyboard_cannot_reach`). +- Split shared role-picker payloads by field. Keep the tested command routing order when moving routers (`test_the_two_role_pickers_never_match_the_same_press`, `test_bot_commands.py`). +- Run server tests from their own checkout's editable install and share fixtures through `conftest.py` (`test_test_imports.py`, `pytest_configure`). + +### Rules without a complete automated holder + +**Live migrations.** Apply additive migrations before deployment, new restrictive constraints afterward, and key rewrites afterward where rows need rewriting. Verify existing rows and migration order first. Use the Neon project named `lessons`, apply to preview then production, and stamp `alembic_version` last in the same transaction. State what will be destroyed before running SQL. Read [migration procedure](.claude/skills/migration/SKILL.md) and [deployment checks](docs/deploy.md#a-migration-goes-before-the-deploy-not-after). Programmatic guards cover the schema head, while the order and real database readback require an operator. + +**Secrets and privileges.** Keep credentials and signing keys outside the repository. Never read or print the Gradle user properties file. Redact secrets as `` in reports. Treat app developer mode as a convenience and enforce privileges on the server. Keep console requests on approved origins and put the app bearer on its own server only. Targeted scrubber and request-console tests cover selected paths; no automated check holds the full operating rule. + +**Vercel and bot lifecycle.** Run periodic work from the external cron. A smoke check of the scheduler and failure emails requires a current service receipt. Keep bot FSM state in the database so another process can resume a flow. A bot handler that owns a SQLite savepoint must commit before writing FSM state on its separate connection. Unit tests using fake state do not hold this lock ordering. + +**School time and input.** Store naive wall time in the class's own zone, and use it for today's date, terms and alerts. Android's system default zone is rarely the class's zone. Validate callback data at the picker, before carrying it through a form. Selected schedule and handler tests do not guard every call site. + +**Compose test clock.** Infinite animations keep automatic idle from settling. With the clock held, send `Snapshot.sendApplyNotifications()` before advancing frames after a test-thread state change. Use a tall layout for below-fold assertions that cannot drive an animation. No lint rule holds how every test sets up the clock. + +**Translation literals and Telegram formatting.** The resource parity test does not see Cyrillic literals in Kotlin. Check new UI text manually and use the [strings procedure](.claude/skills/strings/SKILL.md). Render callback alerts as plain text and stay within Telegram's separate 200-character ceiling. Use [the message procedure](.claude/skills/bot-message/SKILL.md) for HTML, plural helpers and bounded output. Coverage is per renderer and cannot guarantee the wording of every future caller. + +**Android build and review.** AGP 9 provides Kotlin for Android modules; leave the Kotlin JVM plugin for pure JVM modules. Static build checks cannot prove installed behavior, widget rendering on a launcher, or physical-device timing. Record the exact source and artifact and the acceptance check that actually ran. + +**Production and shared resources.** Read before writing. Use current owner authorization for shared test resources, live access and controlled migrations. Record what was verified and preserve the evidence even when a narrow check fails. Repository CI and a local artifact cannot establish that another deployment, device or account was exercised. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 11dfd0e7..6104bc19 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,7 +44,7 @@ cp .env.example .env # BOT_TOKEN and OWNER_IDS are your own | --- | --- | | `ruff check app tests scripts migrations` | lints the server — exactly what CI runs | | `python -m mypy` | one question of all 242 modules: does anything reach for an attribute its type does not have? | -| `pytest -q -n auto` | the server tests, 3916 of them — the exact command CI runs. Not `python -m pytest`: the `-m` form puts the current directory on `sys.path`, so a test that imports another passes locally and fails on CI | +| `pytest -q -n auto` | the server tests, 3926 of them — the exact command CI runs. Not `python -m pytest`: the `-m` form puts the current directory on `sys.path`, so a test that imports another passes locally and fails on CI | | `python -m pytest -q tests/test_schedule.py -k parity` | one file, one test | | `python scripts/check_test_counts.py server --junit work/pytest.xml` | compare the completed full server report with `docs/counts.json` | | `python -m uvicorn app.main:app --reload` | run the server | diff --git a/HANDOVER.md b/HANDOVER.md index f0eb4a54..0ed55e8e 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -6,42 +6,58 @@ place without reopening or redoing anything. What every batch before the last two added is in [docs/history.md](docs/history.md), newest first. +**30 November 2026 — Maintenance and compatibility checks.** + +Event, homework and access changes finish promptly after commit when Telegram +stops answering. The tick leaves later reminders due when the send budget +expires. SQLite rolls back a failed commit before returning the connection to +the pool. Diary diagnostics identify a refused proxy tunnel, and NetSchool +school search reads the address field in both supported forms. + +On Android, reopening the audit sheet starts a fresh visit, and issuing a link +code while Telegram finishes linking reconciles with one read for the same +device. The repository checks installed v1 API compatibility against the PR base, +classifies new Alembic revisions by rollout order and keeps historical incident +detail in the docs archive. The [data residency comparison](docs/specs/2026-10-11-data-in-russia-design.md) +records the options an operator can choose and the work a move needs. + +The full server run passed 3,909 tests with 17 expected skips. Ruff and mypy +passed. Android passed 2,246 unique JVM cases across six modules, both assemblies +and Detekt. Moving the test scratch directory corrected Windows Room's path +failure. Independent review verified the final fixes to v1 request constraints +and Alembic inline constraints. Console CI caught the new server comparison +missing from its reviewed workflow inventory. The corrected inventory records +the pull request comparison, and local pytest checks snapshot freshness. +The complete Console suite passed 59 tests and Ruff. Record integrated CI and +the deployed source in this batch's promotion PR. + **29 November 2026 — Combined Console, Android transport and standalone delivery.** -The current delivery candidate in [#786](https://github.com/lumenpearson/lessons/pull/786) -combines Console 6c and its Stop-race correction (#784, #785, #787) with the -reviewed Android 5c, shared schedule resolver, authored Room store and standalone -calendar, homework and personal-task work. The controlled source handoff is -`b0ec0918`; the Console correction is `c16ece2`. Later work in the source owner's -checkout is separate and must not enter this candidate. - -Android, server and shared runtime inputs match the accepted source cohort. -The retained final Android check passed 2,232 unique JVM cases across six modules, -both assemblies for standard and standalone, six Detekt reports and the report -count check. The full server report contains 3,899 passes and 17 expected skips; -Ruff and mypy passed. Two exported Room schemas acquired CRLF during checkout; -their contents were equal and their bytes were restored to the frozen LF inputs. -The final composed Console suite passed all 59 cases in 21.76 seconds and locked -offline Ruff passed. Both owned command jobs ended with no pending operations; -all 34 frozen inputs still matched. Independent final composition review found -no P1/P2 blocker, including the flavor/build interfaces, migration chain and -Host Stop/check ownership. Exact-head CI, dev/master promotion and new-source -production observation remain delivery gates; record their actual results in -this batch's PR description. - -The predecessor is delivered: #783 merged as master `13d7200`, whose push CI -passed all nine jobs. Production source and all four aliases were checked, eight -health/warmup requests passed, and deployment/project runtime queries both -returned zero errors and fatals for the same fixed 30-minute window on -29 November. The legacy alias was repaired once with independent readback. -Main accepted that evidence and owns #769, #771 and #776 closeout. Earlier dated -notes below describe consumed attempts and are superseded by these receipts. - -The VPS recipe (#407) is written and reviewed; a live VPS trial is still a -programme acceptance step. Native streaming/device acceptance (#770), Console -Host/device acceptance (#782), standalone signed installation and remaining -reminder/diary scenarios (#409), relay provider evidence (#408), family trials -and v1 retirement remain open. The locally built APKs use development signing. -No production or installed-device acceptance is inferred from builds or tests. + +Working PR #786 passed all nine CI jobs on `9690443b` and merged into persistent +`dev` as `72661172`. Its promotion PR #788 passed all nine CI jobs and merged +normally into `master` as `6cadc08a`, with the reviewed tree `03324912`. +Master push CI 46264157674 also passed every job. + +The exact production deployment is READY for `6cadc08a`. The 29 November +observation verified all four service bindings. The legacy alias was converged +once and read back. Eight unique health and warmup requests returned HTTP 200 +with API version 1. Warmup confirmed schema `0019` and v2 enabled. Both complete +runtime queries covered 12:44:16–13:14:16 UTC and returned zero errors and fatals. +The programme owner independently checked the receipt and released both scopes. + +#407, #773, #774, #775, #777, #778, #779, #784, #785 and #787 are closed on GitHub +with completed reasons and linked to #788. #273 carries the current programme +checkpoint. Project 6 recorded all ten issues and the promotion as Done on +29 November. The operator matched their 66 field values after reloading the +project and released the browser slot. + +The VPS trial, foreground stream and Console Host device checks, +signed standalone installation, live diary and relay acceptance, family tests, +and v1 retirement retain their existing tracking issues. + +[Working PR #786](https://github.com/lumenpearson/lessons/pull/786) · +[Promotion #788](https://github.com/lumenpearson/lessons/pull/788) · +[Master CI](https://github.com/lumenpearson/lessons/actions/runs/46264157674) **29 November 2026 — Personal tasks from standalone homework.** From the calendar day actions, choose a homework assignment to create a @@ -2863,9 +2879,9 @@ The gates, both halves (`CLAUDE.md` requires running both if you touched both): ```bash cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 3916 tests, ~15 min on the last Windows run +cd server && pytest -q -n auto # 3926 tests, ~15 min on the last Windows run cd server && python -m mypy # clean, 242 modules -cd android && ./gradlew test # 2232 tests across the six modules +cd android && ./gradlew test # 2246 tests across the six modules cd android && ./gradlew detekt # no findings beyond the module baselines cd android && ./gradlew assembleDebug assembleRelease # both assembles ``` diff --git a/README.md b/README.md index 0f1630d2..f7665fff 100644 --- a/README.md +++ b/README.md @@ -221,12 +221,12 @@ Read this before planning a release. | --- | --- | | `ruff check app tests scripts migrations` | clean | | `python -m mypy` | clean, 242 modules — asks whether anything reaches for an attribute that does not exist | -| `pytest -q -n auto` | 3916 tests, green — the command CI runs, on SQLite; on PostgreSQL by hand only (below) | +| `pytest -q -n auto` | 3926 tests, green — the command CI runs, on SQLite; on PostgreSQL by hand only (below) | | buf lint, buf breaking, the generated-code check | CI's «Contract (Buf)» job, only when the contract changes. Its first run was this sub-project's pull request, where breaking was skipped because main had no contract yet | | v2 over REST and Connect | seventy-five methods served beside v1, every unary one: `GetScheduleWindow`, `GetMe`, `GetDiaryCapabilities` and `CreateDevice` (3a), the journal, the class's phones and the subjects (3b-1), the bells, the timetable and the class with its terms (3b-2), the access requests, whose Telegram notice goes out after the commit, and the school directory (3b-3), a phone's own: its link, the calendar feed, its tasks and its homework ticks (3b-4), the homework and the events, whose notices to the class go out after the commit (3b-5), the days and the substitutions, told to the class the same way (3b-6), a diary session and the reads of one pupil, with what each diary has declared from the registry's table (3b-7), and the family's corrections over the diary, a batch at a time, all or none (3b-8), each tested both ways in-process and against v1's own answer where v1 has one; 5a moved Schedule and Join, and 5b moves Me/link codes, management, directory and diary to domain-valued remotes over the selected v2 transport (Connect by default); installed APKs keep the unchanged server v1 API, and no family rollout or live streaming acceptance is claimed | | The host target and `WatchClass` | `python -m app.host`, under pyvoy and under hypercorn, started on SQLite by CI's «Host» job and asked over native gRPC: a unary call, a method the contract lacks, `WatchClass` hearing an ORM write, a bulk write and a bell change, a revoked phone cut off, and a forged `X-Forwarded-For` throttled all the same; the bus and the stream are tested in-process too. The image was built and run by hand once (at `261450e`, with a throwaway PostgreSQL 18: the same six live tests passed under both servers, and grpcurl was answered over native gRPC), and nothing builds it routinely; the host is deployed nowhere, and no phone streams yet | | Monitoring | the tick's self-check of the schema, v2, the diary's proxy and the deploy, and of each «Сетевой город» region in use by its own route (#406, deployed on 11 October 2026 with no region in use, so no region has been probed live yet), the owner's alerts on a change, Sentry's scrubbing and «📊 Проект» — tested in-process with the outside world faked, and the scrubbing on an event built from a real request in a fresh interpreter. In production since 6 October 2026, where a real failure reached the owner's chat; Sentry has received a transaction, and no error event has been seen arriving | -| `./gradlew test` | 2232 tests, green, all six modules | +| `./gradlew test` | 2246 tests, green, all six modules | | `./gradlew detekt` | no finding beyond each module's baseline, all six modules | | `./gradlew assembleDebug` | the APK builds | | `./gradlew assembleRelease` | the APK builds; R8 and resource shrinking pass | diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/AdminRows.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/AdminRows.kt index df736a15..a3df0d1b 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/AdminRows.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/AdminRows.kt @@ -202,8 +202,11 @@ private fun ManagementRows(role: ClassRole?) { } ManagementScreen.LOG -> { - LoadOnOpen(viewModel) { viewModel.loadLog() } - LogSheet(state = state, viewModel = viewModel, onDismiss = { open = null }) + LoadOnOpen(viewModel) { viewModel.openLog() } + LogSheet(state = state, viewModel = viewModel, onDismiss = { + viewModel.closeLog() + open = null + }) } ManagementScreen.STATS -> { diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/LogActions.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/LogActions.kt index 93ec8fc5..bdc691be 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/LogActions.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/LogActions.kt @@ -7,6 +7,17 @@ internal class LogActions( private val plumbing: ManagementPlumbing, private val repository: ManageRepository, ) { + private var visit = 0L + + fun openLog() { + visit++ + load(LogPosition(), emptyList(), opening = true) + } + + fun closeLog() { + visit++ + } + fun loadLog() = load(LogPosition(), emptyList()) fun showNextLogPage() { @@ -26,10 +37,17 @@ internal class LogActions( load(target, previous.dropLast(1)) } - private fun load(position: LogPosition, previous: List) { - if (plumbing.state.value.log.loading) return - plumbing.read({ it.copy(log = it.log.copy(loading = true, failure = null)) }) { + private fun load(position: LogPosition, previous: List, opening: Boolean = false) { + if (!opening && plumbing.state.value.log.loading) return + val requestVisit = visit + plumbing.read({ + if (opening) it.copy(log = Remote(loading = true), logNavigation = LogNavigation()) + else it.copy(log = it.log.copy(loading = true, failure = null)) + }) { + if (requestVisit != visit) return@read val result = request(repository) { log(pageToken = position.token) } + // An old visit can receive even a session-ending refusal after the sheet reopens. + if (requestVisit != visit) return@read finish(result) { current, value, failure -> current.copy( log = Remote(value ?: current.log.value, false, failure), diff --git a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/ManagementViewModel.kt b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/ManagementViewModel.kt index 972d2991..deaa17ae 100644 --- a/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/ManagementViewModel.kt +++ b/android/app/src/main/kotlin/com/lumenpearson/lessons/ui/admin/ManagementViewModel.kt @@ -181,6 +181,10 @@ class ManagementViewModel( // -- the log ------------------------------------------------------------ + fun openLog() = logActions.openLog() + + fun closeLog() = logActions.closeLog() + fun loadLog() = logActions.loadLog() /** @see LogActions.showNextLogPage */ diff --git a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/admin/LogNavigationTest.kt b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/admin/LogNavigationTest.kt index 4eebe65c..c9959098 100644 --- a/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/admin/LogNavigationTest.kt +++ b/android/app/src/test/kotlin/com/lumenpearson/lessons/ui/admin/LogNavigationTest.kt @@ -142,6 +142,41 @@ class LogNavigationTest { assertEquals(listOf("", "A", ""), fixture.requests) } + @Test + fun `reopening starts at the first page while the old page is pending`() = runTest { + val scope = CoroutineScope(backgroundScope.coroutineContext + UnconfinedTestDispatcher(testScheduler)) + val fixture = Fixture(ManagementPlumbing(scope)) + fixture.actions.openLog() + fixture.answer(0, page(100, "old-cursor")) + fixture.actions.showNextLogPage() + + fixture.actions.openLog() + + assertEquals(listOf("", "old-cursor", ""), fixture.requests) + fixture.answer(2, page(101, "new-cursor")) + fixture.answer(1, page(80, "older-cursor")) + assertEquals(101L, fixture.plumbing.state.value.log.value?.entries?.single()?.id) + assertEquals(LogNavigation(), fixture.plumbing.state.value.logNavigation) + } + + @Test + fun `a late refusal from the previous visit does not replace the reopened sheet`() = runTest { + val scope = CoroutineScope(backgroundScope.coroutineContext + UnconfinedTestDispatcher(testScheduler)) + val fixture = Fixture(ManagementPlumbing(scope)) + fixture.actions.openLog() + fixture.answer(0, page(100, "old-cursor")) + fixture.actions.showNextLogPage() + + fixture.actions.closeLog() + fixture.pending[1].complete(Result.failure(ManageFailure.NotLinked)) + assertEquals(null, fixture.plumbing.state.value.gone) + + fixture.actions.openLog() + assertEquals(true, fixture.plumbing.state.value.log.loading) + fixture.answer(2, page(101, "new-cursor")) + assertEquals(101L, fixture.plumbing.state.value.log.value?.entries?.single()?.id) + } + @Test fun `an empty next page retains the path to the visible previous page`() = runTest { val scope = CoroutineScope(backgroundScope.coroutineContext + UnconfinedTestDispatcher(testScheduler)) diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/MeMappings.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/MeMappings.kt index 82857eff..7fd7696b 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/MeMappings.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/MeMappings.kt @@ -12,3 +12,6 @@ internal fun DeviceLink.withLinkCode(code: String?, deepLink: String?): DeviceLi ?: throw malformedV2Payload("The unlinked phone received no link code"), botDeepLink = deepLink?.trim()?.ifBlank { null }, ) + +internal fun DeviceLink.requireReconciledLink(): DeviceLink = takeIf { it.linked } + ?: throw malformedV2Payload("The unlinked phone received no link code") diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/RestMeRemote.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/RestMeRemote.kt index 8ee24a80..904b44e2 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/RestMeRemote.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/RestMeRemote.kt @@ -6,23 +6,30 @@ import com.lumenpearson.lessons.core.data.network.v2.dto.UnlinkMeRequestDto import com.lumenpearson.lessons.core.data.repository.DeviceLink internal class RestMeRemote(private val api: V2Api) : MeRemote { - override suspend fun refresh(observation: CallObservation): DeviceLink { - val body = RestRefusals.body(RestRefusals.request(observation) { api.getMe(it) }) - return linked(body.me, observation) - } + override suspend fun refresh(observation: CallObservation): DeviceLink = + completeLink(getMe(observation), observation) override suspend fun unlink(observation: CallObservation): DeviceLink { val body = RestRefusals.body(RestRefusals.request(observation) { api.unlinkMe(UnlinkMeRequestDto(), it) }) - return linked(body.me, observation) + return completeLink(body.me.toDeviceLink(), observation) } - private suspend fun linked(me: MeDto?, observation: CallObservation): DeviceLink { - val value = me ?: throw malformedV2Payload("The response has no device identity") - val link = deviceLink(value.deviceName, value.linked, value.role, value.canEdit) + private suspend fun getMe(observation: CallObservation): DeviceLink = + RestRefusals.body(RestRefusals.request(observation) { api.getMe(it) }).me.toDeviceLink() + + private suspend fun completeLink(link: DeviceLink, observation: CallObservation): DeviceLink { if (link.linked) return link - val code = RestRefusals.body(RestRefusals.request(observation.followUp()) { + val codeRequest = observation.followUp() + val code = RestRefusals.body(RestRefusals.request(codeRequest) { api.createLinkCode(CreateLinkCodeRequestDto(), it) }).linkCode - return link.withLinkCode(code?.code, code?.botDeepLink) + // The response omits the code when Telegram linked the device between calls. + return if (code == null) getMe(codeRequest.followUp()).requireReconciledLink() + else link.withLinkCode(code.code, code.botDeepLink) + } + + private fun MeDto?.toDeviceLink(): DeviceLink { + val value = this ?: throw malformedV2Payload("The response has no device identity") + return deviceLink(value.deviceName, value.linked, value.role, value.canEdit) } } diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/RpcMeRemote.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/RpcMeRemote.kt index 35639786..2d2049f0 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/RpcMeRemote.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/network/v2/RpcMeRemote.kt @@ -13,24 +13,30 @@ import com.lumenpearson.lessons.core.data.network.v2.dto.RoleWireSerializer import com.lumenpearson.lessons.core.data.repository.DeviceLink internal class RpcMeRemote(private val rpc: RpcCalls) : MeRemote { - override suspend fun refresh(observation: CallObservation): DeviceLink { - val answer = rpc.unary(Get, GetMeRequest.getDefaultInstance(), observation) - return linked(answer.me.takeIf { answer.hasMe() }, observation) - } + override suspend fun refresh(observation: CallObservation): DeviceLink = + completeLink(getMe(observation), observation) override suspend fun unlink(observation: CallObservation): DeviceLink { val answer = rpc.unary(Unlink, UnlinkMeRequest.getDefaultInstance(), observation) - return linked(answer.me.takeIf { answer.hasMe() }, observation) + return completeLink(answer.me.takeIf { answer.hasMe() }.toDeviceLink(), observation) } - private suspend fun linked(me: Me?, observation: CallObservation): DeviceLink { - val value = me ?: throw malformedV2Payload("The response has no device identity") - val link = deviceLink(value.deviceName, value.linked, - RoleWireSerializer.wireName(value.roleValue), value.canEdit) + private suspend fun getMe(observation: CallObservation): DeviceLink { + val answer = rpc.unary(Get, GetMeRequest.getDefaultInstance(), observation) + return answer.me.takeIf { answer.hasMe() }.toDeviceLink() + } + + private suspend fun completeLink(link: DeviceLink, observation: CallObservation): DeviceLink { if (link.linked) return link - val answer = rpc.unary(CreateCode, CreateLinkCodeRequest.getDefaultInstance(), observation.followUp()) - val code = answer.linkCode.takeIf { answer.hasLinkCode() } - return link.withLinkCode(code?.code, code?.botDeepLink) + val codeRequest = observation.followUp() + val answer = rpc.unary(CreateCode, CreateLinkCodeRequest.getDefaultInstance(), codeRequest) + return if (answer.hasLinkCode()) link.withLinkCode(answer.linkCode.code, answer.linkCode.botDeepLink) + else getMe(codeRequest.followUp()).requireReconciledLink() + } + + private fun Me?.toDeviceLink(): DeviceLink { + val value = this ?: throw malformedV2Payload("The response has no device identity") + return deviceLink(value.deviceName, value.linked, RoleWireSerializer.wireName(value.roleValue), value.canEdit) } private companion object { diff --git a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearch.kt b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearch.kt index f33e9135..17628ca0 100644 --- a/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearch.kt +++ b/android/core/data/src/main/kotlin/com/lumenpearson/lessons/core/data/upstream/NetSchoolSchoolSearch.kt @@ -134,7 +134,8 @@ internal class NetSchoolSchoolSearch( ?: return@mapNotNull null val name = UpstreamJson.string(row["name"])?.trim()?.takeIf { it.isNotEmpty() } ?: return@mapNotNull null - val address = UpstreamJson.string(row["addressString"])?.trim()?.takeIf { it.isNotEmpty() } + val address = UpstreamJson.string(row["address"])?.trim()?.takeIf { it.isNotEmpty() } + ?: UpstreamJson.string(row["addressString"])?.trim()?.takeIf { it.isNotEmpty() } DiarySchool(id = id, name = name, address = address) } } diff --git a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/v2/MeRemoteTest.kt b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/v2/MeRemoteTest.kt index 05ee72a2..086cb345 100644 --- a/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/v2/MeRemoteTest.kt +++ b/android/core/data/src/test/kotlin/com/lumenpearson/lessons/core/data/network/v2/MeRemoteTest.kt @@ -51,6 +51,62 @@ class MeRemoteTest(private val transport: String) { } } + @Test + fun `an absent code after a concurrent link rereads the same device`() = runBlocking { + V2BindingFixture(transport).use { fixture -> + unlinked(fixture) + fixture.success("{}", CreateLinkCodeResponse.getDefaultInstance()) + fixture.success( + """{"me":{"deviceName":" linked phone ","linked":true,"role":"ROLE_OWNER","canEdit":true}}""", + GetMeResponse.newBuilder().setMe(Me.newBuilder().setDeviceName(" linked phone ") + .setLinked(true).setRole(Role.ROLE_OWNER).setCanEdit(true)).build(), + ) + assertEquals(DeviceLink("linked phone", true, ClassRole.OWNER, true, null, null), + repository(fixture).refresh().getOrNull()) + assertCalls(fixture, listOf("GET" to "me", "POST" to "me/linkCodes", "GET" to "me"), + listOf("GetMe", "CreateLinkCode", "GetMe")) + } + } + + @Test + fun `a present but blank code is malformed without an extra GetMe`() = runBlocking { + V2BindingFixture(transport).use { fixture -> + unlinked(fixture) + fixture.success("""{"linkCode":{"code":" "}}""", + CreateLinkCodeResponse.newBuilder().setLinkCode(LinkCode.newBuilder().setCode(" ")).build()) + assertTrue(repository(fixture).refresh().exceptionOrNull() is RemoteError) + assertCalls(fixture, listOf("GET" to "me", "POST" to "me/linkCodes"), + listOf("GetMe", "CreateLinkCode")) + } + } + + @Test + fun `a reconciliation that still finds no link fails without issuing another code`() = runBlocking { + V2BindingFixture(transport).use { fixture -> + unlinked(fixture) + fixture.success("{}", CreateLinkCodeResponse.getDefaultInstance()) + unlinked(fixture) + assertTrue(repository(fixture).refresh().exceptionOrNull() is RemoteError) + assertCalls(fixture, listOf("GET" to "me", "POST" to "me/linkCodes", "GET" to "me"), + listOf("GetMe", "CreateLinkCode", "GetMe")) + } + } + + @Test + fun `a changed membership before reconciliation never receives the third call`() = runBlocking { + V2BindingFixture(transport).use { fixture -> + unlinked(fixture) + fixture.success("{}", CreateLinkCodeResponse.getDefaultInstance()) + var responses = 0 + fixture.afterResponse = { + if (++responses == 2) fixture.credentials = fixture.credentials.copy(classToken = "replacement") + } + assertTrue(repository(fixture).refresh().exceptionOrNull() is IOException) + assertCalls(fixture, listOf("GET" to "me", "POST" to "me/linkCodes"), + listOf("GetMe", "CreateLinkCode")) + } + } + @Test fun `unlink uses its returned Me and obtains the replacement code explicitly`() = runBlocking { V2BindingFixture(transport).use { fixture -> @@ -115,6 +171,11 @@ class MeRemoteTest(private val transport: String) { ioDispatcher = Dispatchers.Unconfined, ) + private fun unlinked(fixture: V2BindingFixture) = fixture.success( + """{"me":{"deviceName":"phone"}}""", + GetMeResponse.newBuilder().setMe(Me.newBuilder().setDeviceName("phone")).build(), + ) + private fun assertCalls( fixture: V2BindingFixture, rest: List>, diff --git a/docs/README.md b/docs/README.md index 083ca300..78ec2a8c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ neighbour — if the answer is not here it is in the code, and there is usually | want to run the whole thing locally | [build.md](build.md), "From a clone to a working pair" | | want to build the APK | [build.md](build.md) | | are deploying the server | [deploy.md](deploy.md) | +| are comparing hosting locations and data flows | [Data residency choices](specs/2026-10-11-data-in-russia-design.md) | | are writing code | [architecture.md](architecture.md), then [CLAUDE.md](../CLAUDE.md) and [CONTRIBUTING.md](../CONTRIBUTING.md) | | are proposing a new kind of test, a new check in CI or a new shape of the build | [engineering.md](engineering.md) | | are writing a client for the API | [api.md](api.md) | @@ -35,6 +36,7 @@ neighbour — if the answer is not here it is in the code, and there is usually | [design.md](design.md) | the design system: what was taken from Essentials, what was fixed, and the reasoning behind every visible decision in the interface | | [diaries.md](diaries.md) | which electronic diary every region of Russia runs in September 2026, how a client signs in to each platform, and what that means for a second provider; **not about this project's own code** — the survey a future provider is written from — except for one section, the region catalog the server and the app read, which is generated from this survey | | [history.md](history.md) | **not a reference — the record.** Every batch [HANDOVER.md](../HANDOVER.md) no longer carries, newest first, in the words of its close-out, and what `HANDOVER.md`'s numbered sections no longer need. True of the commit each section names and never brought up to date, so it is the one document here that is not checked against today's code | +| [Earlier agent guidance](history.md#agent-guidance-before-the-648-compaction) | incident histories and examples from the guide that preceded the current [CLAUDE.md](../CLAUDE.md), including the [Alembic revision history](history.md#the-alembic-chain-through-0019) | | [diaries/](diaries/) | **the reference pages of [diaries.md](diaries.md)**: one page per platform with its hosts, sign-in flows, headers and the full route table read out of the open-source clients, and one page with the evidence for every region. Nothing in them has been tried against a live diary | | [specs/](specs/) | **not a reference — designs agreed with the owner before they were built**, one file per programme, dated, and the implementation plan of each sub-project beside its design (`*-plan.md`, task by task, with the tests and commands it is checked by). A design says what was decided and why; once the work lands, the reference documents above describe what is true and the spec and its plans stay as the record of the decision | | [legal/](legal/) | **not a document — the terms of use and the privacy policy the app links and bundles.** `*.ru.md` is the source, `*.en.md` the translation, `legal.json` names the edition and the date it applies from. They describe what this code does, and a fork that runs its own server rewrites the passages marked `FORK` — [build.md](build.md#the-terms-and-the-privacy-policy-the-app-links) | diff --git a/docs/architecture.md b/docs/architecture.md index e6067126..2ae4d538 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1104,10 +1104,10 @@ with the host. ## Testing -3916 tests on the server, 2232 on Android; `pytest -q -n auto` and `./gradlew test`, both -offline, both in CI. Android covers `:core:model` 151, `:core:data` 998, +3926 tests on the server, 2246 on Android; `pytest -q -n auto` and `./gradlew test`, both +offline, both in CI. Android covers `:core:model` 151, `:core:data` 1010, `:core:designsystem` 205, `:core:standalone` 11, -`:widget` 130 and `:app` 737 (#325, #777). +`:widget` 130 and `:app` 739 (#325, #777). The table below is the load-bearing part of that rather than the whole of it: diff --git a/docs/counts.json b/docs/counts.json index 175d38e8..5a240430 100644 --- a/docs/counts.json +++ b/docs/counts.json @@ -1,14 +1,14 @@ { "android": { "modules": { - ":app": 737, - ":core:data": 998, + ":app": 739, + ":core:data": 1010, ":core:designsystem": 205, ":core:model": 151, ":core:standalone": 11, ":widget": 130 }, - "total": 2232 + "total": 2246 }, - "server": 3916 + "server": 3926 } diff --git a/docs/deploy.md b/docs/deploy.md index 50bc2ae1..6cd4bd37 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -522,6 +522,9 @@ both run, and a second run finds nothing to do. `0018` asks per column, as `0015 ### A migration goes BEFORE the deploy, not after +The [Alembic revision history](history.md#the-alembic-chain-through-0019) records the previous +schema changes and the order in which they were applied. + This is not a matter of taste. A merge to `master` deploys to Vercel by itself, while the migration is run by hand — and between them is a window in which the code knows about a column the database does not have. Production has already been taken down that way: code diff --git a/docs/diaries/netschool.md b/docs/diaries/netschool.md index a22567a4..b1b059da 100644 --- a/docs/diaries/netschool.md +++ b/docs/diaries/netschool.md @@ -51,7 +51,11 @@ paths and unknown parameters. *Password login (loginType=1) — the flow every open-source client uses; switched off in ESIA-only regions* — token carried as header `at` (numeric string ~26 digits, from the login response field `at`) + session cookie `NSSESSIONID` (and `ESRNSec` on asurso.ru / servers with the ESRN security module); alternative `Authorization: Bearer `. Lifetime: Session-bound: `timeOut` in the login response (900000 ms = 15 min in the 5.10 swagger example, 3600000 ms on asurso.ru); idle limit is the server setting `maxSessionIdleTime` (GET /webapi/settings/maxSessionIdleTime). netschoolpy keeps it alive with GET /webapi/context every 300 s. Validity can be asked with GET /webapi/context/expired?token= (bool) and remaining life with UserContextController.GetLifetime.. Refresh: No refresh endpoint is used by any client: on HTTP 401 every client simply repeats the whole password login (nm17 `_request_with_optional_relogin`, netschoolpy `_authed_get`, netcitybot `sendRequest` also on 500). The login response carries `refreshToken` but nothing consumes it.. 1. GET {origin}/webapi/logindata (no auth). Response sets the `NSSESSIONID` cookie and returns a JSON with login options: `schoolLogin` (bool, password login allowed), `esiaLogin`, `esiaMainAuth` (ESIA is the primary/only way in), `esiaButton`, `version` (server version string, e.g. "5.47.0"), plus windows/irtech/esa auth flags. -2. Resolve the school id: GET {origin}/webapi/schools/search?name= → [{id, name, shortName, inn, ogrn, cityId, provinceId, addressString}] (the server requires at least one character; nm17 sends `name=У` to list everything). Older/other clients instead call GET /webapi/prepareloginform (→ {countries, cid, states, sid, provinces, pid, cities, cn, funcs, sft, schools, scid}) and GET /webapi/loginform?cid&sid&pid&cn&sft&LASTNAME=sft to walk country → state → province → city → school type → school. AdminAPI_SGO uses GET /webapi/addresses/schools?id= → [{id, name, countryId, stateId, municipalityDistrictId, cityId}] to fill cid/sid/pid/cn. +2. Resolve the school id: GET {origin}/webapi/schools/search?name= → [{id, name, shortName, inn, ogrn, cityId, provinceId, address}] (the server requires at least one character; nm17 sends `name=У` to list everything). Older/other clients instead call GET /webapi/prepareloginform (→ {countries, cid, states, sid, provinces, pid, cities, cn, funcs, sft, schools, scid}) and GET /webapi/loginform?cid&sid&pid&cn&sft&LASTNAME=sft to walk country → state → province → city → school type → school. AdminAPI_SGO uses GET /webapi/addresses/schools?id= → [{id, name, countryId, stateId, municipalityDistrictId, cityId}] to fill cid/sid/pid/cn. + In the four-region sample recorded in [#412](https://github.com/lumenpearson/lessons/issues/412), every row had an + `address` field and all values were null. The server and Android use a non-blank `address` and accept `addressString` as a + compatibility fallback. Linking a class to its school registry record using an identifier such as OGRN belongs to + [#124](https://github.com/lumenpearson/lessons/issues/124). 3. POST {origin}/webapi/auth/getdata (no body, cookie NSSESSIONID) → {lt, ver, salt} — all three are numeric strings; `salt` is one-shot. 4. Hash the password: `pw2 = md5(salt + md5(password encoded in windows-1251))` (hex, lower-case); `pw = pw2[:len(password)]`. Old servers sent the salt inside the login HTML (npanuhin regex 'salt') and the form went to /asp/postlogin.asp. 5. POST {origin}/webapi/login, Content-Type application/x-www-form-urlencoded, fields: loginType=1, scid= (optionally cid, sid, pid, cn, sft=2 as in the swagger `login_body`), un=, pw=, pw2=, lt=, ver=; optional rolegroup= when the first answer has `entryPoint` containing `choose-session-role` (accounts that are both staff and parent). Header `Referer: {origin}/` (asurso: `https://asurso.ru/about.html`), `X-Requested-With: XMLHttpRequest`. Response: {at, timeOut (ms, 900000 or 3600000), accessToken, refreshToken, tokenType:"Bearer", accountInfo:{user:{id,name}, userRoles:[{role:{id,name}, schoolId, userId}], organizations:[{id,name}], currentOrganization, loginTime, active, canLogin, storeTokens, accessToken, secureActiveToken}, entryPoint (e.g. "/asp/SecurityWarning.asp"), requestData:{warnType}, errorMessage, code}. Wrong credentials → HTTP 409 with {message}. Response also sets cookie `ESRNSec` (asurso.ru) which the SignalR endpoints require. diff --git a/docs/engineering.md b/docs/engineering.md index c05c3b50..0f06ff12 100644 --- a/docs/engineering.md +++ b/docs/engineering.md @@ -133,13 +133,16 @@ that remedy. **Here.** v2 is a proto contract checked by `buf lint` and `buf breaking` against the base on every pull request that touches it, with `test_contract.py` holding what Buf cannot read -(#299). **v1 has no such check.** Its schema is whatever FastAPI builds from -`server/app/schemas/`, nothing compares it with the previous one, and the app's JSON tests -decode payloads copied by hand from those schemas (`BundleJsonTest`), so a field renamed on -the server and in that copy passes both suites while every installed APK stops reading it. -`MIN_CLIENT_VERSION` can refuse an old client, which is a lock, not a compatibility rule. -The pull request template now asks the question; a check would answer it. Left: v1's schema -against the base's (#638), and payloads both halves read instead of copies (#639). +(#299). The server checks that `openapi-v1.json` matches FastAPI's v1 phone API and compares it +against the pull request's pinned base (#638). From `server/`, regenerate it with +`python -m scripts.check_openapi_v1 --write`. The check catches removed operations and +response fields, narrower schema constraints, and new required request inputs. Document an +intentional break in the pull request with its required minimum Android version code and +rollout. The current minimum-client gate applies to v2. Explain how the rollout protects +clients that still call v1 before approving an exception. This comparison checks defined +schema properties. Untyped dictionaries such as health and warmup still rely on explicit +behavior tests. The server and Android app need shared response fixtures in place of hand-written JSON +copies (#639). ### One service, two versions, compared on the same data @@ -290,9 +293,10 @@ deployment within the next tick, but only once an external cron has called it an what the self-check covers. A failed deployment is undone by promoting the previous one by hand. Left: #641. -The migration rule — additive before the merge, a constraint after — is the same lesson as -Airbnb's compatibility checks, written for a schema: the side a revision goes on is declared -in prose today and checked by nobody (#642). +The migration rule follows the same compatibility principle. Revisions after `0019` +declare `MERGE_SIDE` and document any removal of stored data in `DESTROYS`. The server suite +compares those declarations with the source of the upgrade operations without importing +revisions or connecting to a database (#642). ### Switches, not reverts @@ -432,9 +436,9 @@ plan per sub-project; every defect gets an issue before its fix; the agent confi one agent per area that has produced a defect; and the server's tests read the documents — the migration head in every one of them (`test_schema_version.py`), the CI paths against what the suite reads (`test_ci_paths.py`). None of that is in anything Airbnb has published. The -cost this repository pays that a company does not is context: `CLAUDE.md` is read by every -session and is long enough that a third of it is the record of how a rule was learnt rather -than the rule. +cost this repository pays that a company does not is context. Every session reads +`CLAUDE.md`. #648 shortened the active guide and moved its earlier examples and incident +history to the [guidance archive](history.md#agent-guidance-before-the-648-compaction). **Where this goes past Airbnb.** Airbnb's Swift skill keeps the rules a formatter cannot fix. The rule here is sharper and checkable: **a trap that a test or a lint rule holds is one line @@ -444,8 +448,7 @@ can, because …» — so the answer exists when the paragraph is cut. And the d agents read get the tests the other documents already have: that every file, test and command an agent names exists (#661), that the gate commands are one list across `CLAUDE.md`, `settings.json` and `ci.yml` (#659; bare `pytest` was in two of the three), and that the test -counts are one generated fact rather than seven hand-edited copies (#660). Left: the cut -itself (#648). +counts are one generated fact rather than seven hand-edited copies (#660). For #661, `test_instruction_references.py` now holds current inline navigation in CLAUDE/AGENTS and every Markdown document under .claude against public source names diff --git a/docs/history.md b/docs/history.md index c5d53295..9015dc6e 100644 --- a/docs/history.md +++ b/docs/history.md @@ -11905,3 +11905,1078 @@ These claims in HANDOVER.md's section 5 are now historical, preserved as written `UPDATE` matching nothing, never by PostgreSQL's. - **FastAPI 0.143.0, SQLAlchemy 2.1.4 and asyncpg 0.32.0 have not met PostgreSQL**: CI and the local run are SQLite, and #411's PostgreSQL run was not repeated. + + +## Agent guidance before the #648 compaction + +This is the guide at `9690443bf60e151b6c02137cb3d29db064b8ad38`. It preserves +the incidents and explanations that led to the active rules in [CLAUDE.md](../CLAUDE.md). +Its commands, counts, line references and deployment state belong to that snapshot. + +### CLAUDE.md + +Guidance for Claude Code when working in this repository. + +#### Project overview + +"Дневник" (`lessons`) is a school diary for Russian schools: an Android app with a +resizable home-screen widget, a FastAPI read API, and a Telegram bot that **is** the admin +panel. One class is edited from the bot or from a linked phone, and the same rules apply to +both. **The product speaks Russian; everything written about the project is English.** +User-facing strings live in `values/` (Russian, the source) and `values-en/` (the +translation), and the reader chooses the language in the app. The documentation, the code, +the identifiers, the comments, the commit messages and the pull request descriptions are +English, so that anybody can read them — and where any of those quotes a button, a menu path +or an error the user will see, it quotes it in Russian, in guillemets, because that is what +is on the screen. + +Three deliverables in one repository: + +``` +android/ Kotlin / Compose / Glance, six Gradle modules; logo/ beside them holds + the logo's generators, which write the launcher icons into + app/src/main/res (its README says how) +server/ FastAPI + aiogram in one process, one database, Alembic migrations +tools/console/ Python 3.12 / Textual developer console; its own uv lock and environment, + independent of the server package and Android runtime +api/ thin Vercel entry point that re-exports server/app/main.py +Dockerfile the host target's image (server/app/host.py), built from the root: + the whole app over HTTP/2, chosen instead of Vercel; server/Dockerfile + is docker-compose.yml's +proto/ the v2 contract (package lessons.v2), checked and generated by Buf from + buf.yaml and buf.gen.yaml at the root; its Python is committed under + server/app/contract/, and app/rpc and app/rest serve it beside v1 +docs/ eleven documents plus an index (docs/README.md), all English; ten are current, + and history.md is the record of every batch HANDOVER.md has handed on; + docs/diaries/ holds the per-platform reference pages of diaries.md; + docs/specs/ holds designs agreed with the owner before they are built, + and each sub-project's implementation plan beside its design; + docs/app/ (the in-app guide) and docs/legal/ (the terms and the privacy + policy) are product text the APK bundles, Russian source and English twin +``` + +There is no npm, no Node and no web frontend — with **one** deliberate exception: +`server/app/api/diary_web.py` serves a single server-rendered sign-in form at `/diary/signin`, +because a password typed into a Telegram chat is in the chat history, on Telegram's servers +and in that phone's backup, and deleting the message undoes none of it. No JavaScript, no +cookie, no build step. Do not grow it into a second admin surface: anything the bot can +express belongs in the bot. + +`requirements.txt` at the root exists only because Vercel's Python builder does not read +`pyproject.toml` from a subdirectory. It is a lock (#192) — every package the function can +import, at one exact version, for CPython 3.12 on Linux — compiled by `uv pip compile` from +`requirements.in`, which must stay level with `pyproject.toml`. The lock's header is the +command; never edit a pin by hand. CI installs the lock too, so the tests run on what deploys. +`server/requirements-host.txt` is the host target's lock: its server and nothing else, +compiled from `requirements-host.in` against `requirements.txt` by the command in its +header, for every platform, so the two cannot disagree (`test_host_image.py`); the root +`Dockerfile` and CI's «Host» job install both, and Vercel neither sees nor imports it. + +- Serialize pyvoy receive delivery and keep ASGI Future completions valid across cancellation; observe abandoned sends and stop only idle WatchClass on disconnect (`test_host.py`, #728). + +#### Commands + +Python 3.11+ (`.python-version` says 3.12, CI runs 3.12), JDK 21, Android SDK with +compileSdk 37. Gradle comes from the wrapper — `./gradlew` works on a fresh clone. + +Server, from `server/`: + +- `python3 -m venv .venv && .venv/bin/pip install -r ../requirements.txt -e ".[dev]"` — setup, + CI's own install (#192), in each working tree's own `server/`, a `git worktree` included: + the install is editable, so a borrowed venv tests the tree it was made in, and + `conftest.py` refuses to start when it would (#312) +- **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from + `server/` covers the same tree +- **`pytest -q -n auto`** — 3916 tests, six of them skipped unless a + host is running (`-m host`, CI's «Host» job), plus eleven PostgreSQL-only lock + checks skipped on SQLite, and **the exact command + CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` + form puts the current directory on `sys.path` and the bare one does not, so a + `from tests.test_api import …` in a test file passes locally and fails at + *collection* on CI with «No module named 'tests'» about a directory that is plainly + there. That shipped once. `tests/test_test_imports.py` now refuses a test module + that imports another one at all — a shared fixture belongs in `conftest.py`, which + pytest loads by path rather than by import +- **`python -m mypy`** — one question, of all 242 modules, in seconds: does anything reach + for an attribute its type does not have? Configured in `pyproject.toml`, where every + other error code is switched off by name with its count and its reason. A CI step since + 27 September 2026, right after ruff, because the owner asked for it through that day's + audit (#210) — and still worth running before you push: seconds here, minutes there +- **`python scripts/check_test_counts.py server --junit work/pytest.xml`** — compare the + completed suite's default JUnit report with the measured facts in `docs/counts.json` +- `python -m pytest -q tests/test_schedule.py -k parity` — one file, one test +- `python -m uvicorn app.main:app --reload` — run it; add `--host 0.0.0.0` for a phone to + reach it +- `python -m app.host` — the host target: the same app over HTTP/2 under pyvoy, with native + gRPC and, with `LESSONS_STREAMING=true`, `WatchClass`; `--server hypercorn` is the + fallback. Needs `pip install -r requirements-host.txt` beside the dev install. Without + `LESSONS_TARGET`, which only the root `Dockerfile` sets, it runs on the local defaults +- `LESSONS_HOST_URL=http://127.0.0.1:8000 LESSONS_HOST_DATABASE_URL=sqlite+aiosqlite:///… + pytest -q -p no:xdist -m host` — the tests of a running host (`tests/test_host_live.py`, + with grpcio from `.[host-check]`), which every other run skips; CI's «Host» job runs them +- `python -m scripts.seed_demo` — demo class, join code `DEMO24` +- `DATABASE_URL='postgresql+asyncpg://…' .venv/bin/alembic upgrade head` — schema; never + from inside a request + +Contract, from the repository root, with Buf 1.73.0 fetched by hand (`docs/build.md`, «The +v2 contract and Buf»; the binary never enters the repository): + +- `buf lint`: the STANDARD rules, as CI's «Contract» job runs them +- `buf generate`: rewrites `server/app/contract/` and + `android/core/data/src/main/contract/java/` from `proto/` and the locked google.rpc input. + Commit both generated trees with their inputs; CI regenerates and diffs both +- `python -m pytest -q tests/test_contract.py` (from `server/`): what Buf cannot check. + Every method's REST binding, credential, least role and idempotency, against the resource + map of `docs/specs/2026-10-04-contract-v2-design.md`. Buf reads no options, so an edit to + that map **is** a breaking change (#299). Beside it, `test_contract_json.py` holds the + documented JSON against the runtime and `test_contract_mirror.py` holds the messages level + with the v1 schemas they mirror + +Android, from `android/`: + +- **`./gradlew test`** — all JVM unit tests across the six modules +- `./gradlew :core:model:test --tests '*ScheduleEngineTest*'` — one module, one class +- **`./gradlew assembleDebug`** and **`./gradlew assembleRelease`** — CI builds both on every + push, because R8 and resource shrinking are where "worked in debug" stops being true +- **`./gradlew detekt`** — static analysis of the Kotlin in all six modules (#210), without + type resolution; fails on any finding the module's `detekt-baseline.xml` does not hold. + Fix a new finding, or `@Suppress` it in place with the reason — the baseline is the past +- **`python ../server/scripts/check_test_counts.py android --root .`** — compare the completed + JVM reports with the measured module totals, counting variant copies once +- `./gradlew detektBaseline` — rewrites all five baselines from the code as it stands; use + it for reviewed moves/removals and refresh sibling budgets in the same pull request. + `docs/build.md`, "detekt", has the rest +- `./gradlew lint` runs the AGP Android lint; CI does not, so do not report it as a gate +- `./gradlew :core:designsystem:connectedDebugAndroidTest` — the one instrumented source set + (#110), on a running emulator or a connected phone. Not a CI gate: CI has no device, and a + gate that cannot run is worse than none + +The app is set in **two** bundled faces, both under +`core/designsystem/src/main/res/font/` and both carrying one axis, `wght`: +`google_sans_flex.ttf` draws Latin and digits, `onest.ttf` draws Cyrillic, and +`FallbackTypeface.kt` chains them with `Typeface.CustomFallbackBuilder` because neither a +Compose `FontFamily` nor a font-family XML chooses by coverage. API 26–28 cannot express a +custom chain and get Onest alone. Google Sans Flex has **no Cyrillic at all**, which is why +the second file exists: while it was alone, every Russian word came from the device's +fallback beside digits from the bundle. `FontAxisTest` holds all three halves — the pair +draws Russian, neither carries an axis nothing varies, and no file is bundled unnamed. + +- **Match late authentication refusals to the address and bearer actually sent, and compare before removal inside the persistence boundary** (`ManageMembershipTest`, `DiaryTokenOwnershipTest`, #747/#753). + +- **Keep current agent paths and test names resolvable** (`test_instruction_references.py`, #661); Server runs for every changed path because this guard inventories the whole tree. +- **Baseline rewrites keep or lower their sibling budget, refreshing accepted IDs in the same reviewed PR** (`DetektBaselineBudgetTest`, #635); both manual and current IDs consume it. + +- **Keep primary gate declarations level with CI and allowed command prefixes** (`test_gate_lists.py`, #659). + +The local console starts with `uv run --project tools/console lessons-console`. +From `tools/console/`, its independent gates are `uv run --locked ruff check lessons_console tests` +and `uv run --locked pytest -q`; fake processes and a headless pilot require no SDK. +See [its README](../tools/console/README.md) for preparation, cancellation and scope. + +- Serialize Host startup with queued/running preparation or generation, and guard the post-queue/prelaunch boundary too (`test_console_6c.py`, #784). +- Revalidate the Host session and generation after an asynchronous listener probe so Stop cannot leave a marker check eligible to start (`test_host_check_race.py`, #787). + +CI (`.github/workflows/ci.yml`) is: ruff, mypy, pytest (`-n auto`), `./gradlew test`, both +assembles, and `./gradlew detekt` after them; and, when `proto/`, `buf.*` or +`server/app/contract/` changed, the «Contract» job: `buf lint`, `buf breaking` against the base, +and the check that the committed generated code is what `buf generate` writes; and, +whenever the server job runs, «Host», under pyvoy and under hypercorn: `python -m app.host` +started on SQLite, asked over native gRPC by `tests/test_host_live.py`; the path-filtered +«Console» job runs its lint and fake-process tests on Linux and Windows; and last, «CI», which +needs every job before it, runs whatever they ended as, and passes only when each one +succeeded or was skipped. It is the one check `master` requires, through the repository +ruleset that requires it, which the repository admin role can bypass (#424). The gates are +not required by their own names because «Host» is a matrix: a job its `if:` skips is reported +once, under the unexpanded `Host (${{ matrix.server }})`, so naming a skipped matrix leg +as required would leave «Expected» forever. Server and Host currently run on every changed +path; the aggregate also covers future conditional jobs (`docs/build.md`, «The check +`master` requires»). Nothing else. `apk.yml` builds an installable APK on demand or on a `v*` tag; +`reminders.yml` is a fallback clock, not the clock (see below). The workflows work — do +not edit them casually. The repository is public, so standard runners cost nothing; what +the workflows still carry from the months it was private is in `docs/build.md`, "Actions +minutes", and it is worth reading before undoing any of it — `-n auto` is there because a +full run was twenty-one billed minutes, and a short artifact retention because a full +artifact store reported a passing build as red. **Retention is no longer asked for in any +workflow**: this repository's own setting is lower than anything they requested, so every +`retention-days:` was silently reduced under a warning while three documents went on +quoting the number that had been asked for. + +#### Architecture + +Read `docs/architecture.md` before any cross-cutting change; it is current and it explains +the decisions, not just the layout. + +**Two shells write, over one set of services.** The bot is the admin panel, and a linked +phone runs the same class through the API: the edit routes (`/api/v1/homework`, `/overrides`, +`/events`, `/days` — homework, substitutions, events, special days, editor and above; there +is no `/api/v1/edit` prefix) and `/api/v1/manage` (subjects, bells, the timetable, +devices, access requests, terms, the class itself — admin, and owner to delete it). Both +take the **device token** and ask `linking.effective_role` for the linked account's role on +every request, so an unlinked phone changes nothing of the class's. The rest of what the +API writes is personal (`public.py`: the linked account's own tasks and ticked-off +homework, whatever its role, and a phone unlinking itself; `/join` mints the device token) +and a family's diary (`/api/v1/diary`, with the **diary token**). That is the API. Of its +writes, the app itself makes only `/join`, `/me/unlink`, `/manage` and the diary's today, so +homework, substitutions, events, special days, personal tasks and ticked-off homework come +from the bot or another client of the API (#324, #331). `docs/architecture.md` has +the table. +Telegram already solved identity, so there is still no admin web panel, no session cookies +and no password reset — a phone has no rights of its own, only its account's — and the cost +is still real: anything the bot cannot express does not exist. `server/app/services/` holds +the rules both shells call — two thin shells over one implementation, because two +implementations of "rename a subject" disagree within a month — and **nothing under +`services/` may import `app.bot`**, directly or through another `app/` module: a rule that +lives in the bot is a rule the phone does not get, and a service that pulls aiogram in puts +it on the API's cold start. The role ladder lives in `services/roles.py` (`bot/roles.py` +re-exports it) and the wording both shells print in `app/wording.py`; +`tests/test_service_layering.py` holds the rule. + +Server modules: + +- `models.py` — the whole SQLAlchemy 2.0 domain in one file +- `schedule.py` — template + overrides → concrete days. No FastAPI, no aiogram imports, and + it must stay that way: that is why its tests run in seconds +- `di.py` — the dishka container both shells draw from: `Settings` and the session + factory at app scope, one `AsyncSession` per HTTP request or Telegram update. An + endpoint asks with `session: FromDishka[AsyncSession]`; the bot's `ContextMiddleware` + opens the update's scope itself — **not** `setup_dishka`, which registers one middleware + on every observer and so opened two *sibling* scopes per message, either of which could + hand out a second session nothing commits — and it reads `container()` per update rather + than capturing one, because `api/telegram.py` caches the dispatcher for the life of the + process. It still commits there, because for a handler that is the finish line — but + only for one whose reply cannot lose its write. A handler that writes through a service + and then replies commits right after the write instead: the middleware's own commit runs + only once the handler returns, and rolls back when it raises, and a reply Telegram + refuses — an edit that changes nothing, a message already deleted — raises. It is + built with + `STRICT_VALIDATION`, so a second provider for a type is an error rather than a silent + shadowing. Do **not** import `dishka.integrations.aiogram` from it — that pulls aiogram + onto the cold-start path of every request, which is the thing `main.py` and + `api/telegram.py` already go out of their way to defer +- `services/` — the rules, as async functions over a session, and nothing may import + `app.bot`. A write leaves the commit to its caller, which commits it together with its + audit line, and a v2 handler cannot commit at all (`invoke` does). What still commits + inside itself does so either because its write has to stand whatever the caller does next + — a counted attempt, a spent unit, a phone's last call, a dead diary credential, a tick's + claim; `rpc/call.py` names those a v2 call meets — or because only the bot or the tick + calls it, as `linking.link_device` and `calendar.rotate_calendar_token`; v2 calls none of + those until its commit moves out, as 3b-4 moved the tasks', the ticks', the link code's and + the feed secret's, as 3b-7 moved a diary session's opening and closing, and as 3b-8 moved + the diary corrections'. + `services/manage/` is running a class, one module per screen named like the shells' + (`subjects`, `bells`, `devices`, `classes`, `requests`, `journal`, `terms`, `timetable`, + `special_days`, `search`): each does the check, the write and the audit line with its + Russian wording, and a refusal is an exception carrying facts, never a sentence, so each + shell keeps its own words — «Предмет … уже есть» in a chat, a `409` on the wire. The rules + v2 shares with v1 live here too: `join.py` (the join flow, refusing with facts), + `window.py` (the year's window and its tag), `clock.py` (the class's clock, the date + bounds, a list's `window`, and `wall`, a stored stamp on the class's clock), + `manage/classes.py`'s + `member_names` and `update` (the card's patch, the name recomposed), `manage/subjects.py`'s + `dictionary_of` (the read that adopts nothing) and `update` (the rename-then-details + patch), `manage/bells.py`'s `update` (the rename, the rows, then the default), + `manage/timetable.py`'s `import_paste` (the parse, the conflicts, and a preview that writes + nothing), `manage/requests.py`'s `approve` (the role sent or the one asked for, through + `access.approve_request`, whose `GrantRefused` says `why`), `directory.py`'s + `school_regions` (the anonymous directory's order of checks, one bucket for both + versions), `tasks.py`'s `create_task`, `update_task` and `set_homework_done` (a task's + homework of this class only, its reminder on the class's clock, a patch with `done`, a + tick set rather than toggled), `homework.py`'s `homework_of`, `due_between`, `put`, + `create`, `update` and `delete` (one assignment per subject per day, its line and its + notice), `events.py` (what an event stands in for when nobody says, its line and its + notice), `manage/special_days.py`'s `put_day` (the one write of a day's mark, which v1, + v2 and the bot make, its line and its notice through `set_day` and `update_day`), + `substitutions.py` (the three questions a substitution is asked, as facts, its line and + its notice), `diary.py`'s `register` (a phone's session kept and counted on both diary + limiters, refusing with facts), `target`, `sealed_form`, `window` (a diary read's days, + from the diary's own today) and `DiaryService`'s `student`, `child` and reads of one pupil, + `diary_corrections.py`'s `listed`, `correct`, `reset` and `clear` (what a child with no scope + may do, every correction checked before any is written, nothing committed, over + `diary_overrides.check_correction`), + `linking.py`'s `link_code_for`, `deep_link` and `unlink_self`, `calendar.py`'s + `feed_url`, and `audit.py`'s `older_than` (a page keyed on its last line); the limiters + are `security.py`'s, one instance each, and the sentences both versions answer with (the + join's four, the diary's «disabled», its sessions' three, its unknown pupil and its + corrections' four, and the + subjects', the devices', the bells', the + import's, the zone's, the access requests', the directory's, the tasks', the ticks', the + homework's, the events', the days' and the substitutions' refusals, and the notices to the + class) are + `app/wording.py`'s. + `gone.py` is what a row another writer deleted between a write's read and its commit + means to every shell (#384): «not found», never a server error and never a reason to make + the row again; its `committed` is the bot's commit, which rolls back and answers `False` + on a `StaleDataError` rather than raising out of the handler. + A class update flushes before its audit entry, including a journalled same-value write (#662). + Parent references lock before children; schedule deletion locks exclusively, rechecks references, then cascades (`test_stale_writes.py`, #677/#678). + The tick runs `health.py`'s self-check after the digests and the sweeps and before the + diary keep-alive: four fixed checks and one per «Сетевой город» region in use, each by its + route, what each said last in `health_checks`, and the owner's alerts on a change; the + owner's «📊 Проект» reads `project_stats.py`, which writes nothing. +- `api/` — `public.py` (the phone's reads and its own writes), `edit.py` (the day-to-day + writes), `manage/` (running the class, one module per resource over + `services/manage/`, with `_common.py` holding `Actor` and the one role dependency per + level), `diary.py`, `cron.py`, + `telegram.py` (webhook), `deps.py` (device-token auth), `routing.py` (the route class + every router here is built with: dishka's wrapper carries its own globals, so under + `from __future__ import annotations` FastAPI could not resolve an endpoint's + `-> Response` and took the name for a response model — a 204 route made that an + `AssertionError` at import, and every route without an explicit `response_model=` would + have had a schema built from a string; it also rolls back a write whose row another writer + deleted mid-write and answers the `404` its own `GONE` names for that path, #384) +- `bot/` — aiogram routers, roles, keyboards, renderers. «⚙️ Класс» is `handlers/manage/`, + one module per screen, each with a router of its own included in one written-down order + by the package's `__init__`. `handlers/start/` and `handlers/content/` are packages the + same way, and `manage_render/` and `manage_keyboards/` mirror the screens; each feature + outside «⚙️ Класс» has its own `*_render.py` and `*_keyboard.py` beside + `render.py` (which re-exports `app/wording.py`) and `keyboards.py`. + Every handler there says what it needs with + `@needs(Role.X)` (`handlers/manage/_common.py`) under its `@router…` line — one decorator + instead of seventy-two copies of the check, and a decorator rather than a filter or a + middleware flag because the check has to travel with the function: a failed filter hands + the update on instead of refusing it, and the tests that press every step as a + наблюдатель call the handlers directly. A refusal is an alert for a press, a sentence for + a command, and a dropped form with no answer for a step (`step=True`). + The weekly template has **two** editors and both are wanted: `handlers/timetable.py` pastes a whole weekday (fastest way + to enter a term), `handlers/editor.py` changes one lesson with buttons. They share one + grammar (`services/timetable_io.py`) and one set of mutations + (`services/timetable_edit.py`) — the editor's ‹ › pager and «⏱ Перемены» switch live in + the callback payload, never in FSM state +- `providers/` — the two foreign services, each behind `client.py` / `mapper.py` / + `models.py`. `petersburg/` is the electronic diary: nothing above `models.py` knows the + words `p_educations[]` or `X-JWT-Token`. `dadata/` is the school directory, a search over + the ЕГРЮЛ company register, because no downloadable register of Russian schools exists; + without `DADATA_TOKEN` + it refuses at the door and the bot asks for the name to be typed, exactly as the diary + refuses without `DIARY_SECRET`. The diaries are one table, `providers/diary/registry.py`'s + `TABLE`, a row per provider, which every question about a provider key reads — the binding, + the features, the corrections' scope, the keep-alive, the route through the proxy or + direct — and a session whose key no row answers is read by nobody +- `contract/` — the Python `buf generate` writes from `proto/lessons/v2/` (and googleapis' + `google/api` and `google/rpc`). Never edited by hand, since every regeneration deletes and + rewrites it. Skipped by ruff and mypy, and on the API's cold path on purpose since v2 is + served: `tests/test_contract.py` holds that in a fresh interpreter +- `rpc/` — v2's handlers, one module per proto service, over `services/`, and what every + method shares: `methods.py` (each method's facts, read from the descriptors), `gate.py` + (client version, then the bearer, the link and the role), `call.py` (`invoke`: the gate, + one dishka scope, the handler, the one commit, then the effects; and `stream`, which serves + `WatchClass` with the gate in a scope of its own for every check and no session held + between; and `GONE`, which answers a row deleted mid-write `RESOURCE_NOT_FOUND`, #384), + `caching.py` (`NEVER_STORED`, the one table of answers no cache may keep, which the REST + transcoder and the Connect adapters both read, so a Connect answer says + `private, no-store` exactly where its REST twin does, #357, #652), `errors.py` (the one error + table), `masks.py` (one reading of an `update_mask`, AIP-134), `dates.py` (a list's window, + a written date's bound, and the date a day is named by, read as v1 reads them) and + `handlers.py` (which methods are served, and `STREAMS`). A handler never commits and never + checks a credential; `rpc_app()` mounts the seventeen Connect apps at `/api/rpc`, refusing + native gRPC over HTTP/1.1 with `415`. May import `services/`, `models`, `schedule`, + `wording`, `security`, `schemas`, `config`, `crypto`, `di`, `api/deps.py`, the diary + registry and the diary's error family (`providers/diary/errors`, which the table words), + the school directory's provider (`providers/dadata`, whose refusals the error table maps), + `telegram_send` and the contract — never `app.bot` + or a v1 router, `api/directory.py` among them; `tests/test_service_layering.py` walks it +- `rest/` — the transcoder: one Starlette route per unary method from its `google.api.http` + rule, under `/api/v2`, calling the same `invoke`; `errors.py` writes Google's error body. + `main.mount_v2` mounts both and answers `503` under their prefixes if v2 will not import +- `telegram_send.py` — a bot built for one job and closed after it (`build_bot`, `close_bot`, + `send`, and `notify_class` for a class's subscribers), for the code that is not the bot: + the tick, v1's notices, v2's (an effect run after the commit) and the self-check's alerts. + aiogram is imported inside its functions and + never at the top, so it costs a cold + start nothing; `app.bot.bot` imports `build_bot` back from it, and + `tests/test_service_layering.py` holds that it reaches neither the bot nor a shell +- `observability.py` — Sentry's start and its scrubbing hooks, imported only where + `SENTRY_DSN` is set (`app.main` and the bot's error handler ask first). Every event is + rebuilt from a list of what may leave: an exception's type and stack, the route template, + the release and the environment; never a body, a header, a query, a message or a local + (152-ФЗ), which `tests/test_observability.py` proves on an event built from a real request +- `watch.py` — the class-changed bus `WatchClass` streams from: before each flush it collects + the class of every row written to a window table, a bell period through its schedule; + `touch` says the same for a bulk statement; the outermost commit publishes, a savepoint's + release never does, a rollback forgets. Attached by `app.main` only where streaming is on + (`Settings.streaming_enabled`, never on Vercel); neutral, so services import it +- `host.py` — the host target, `python -m app.host`: the app under pyvoy (or hypercorn) over + HTTP/2, native gRPC answered at the root too, pyvoy's Envoy told to take the client from + the connection. It reads the settings before any server starts and never sets + `LESSONS_TARGET`; nothing on the API's path imports it, pyvoy or hypercorn + +Android modules (`android/settings.gradle.kts`): + +``` +:core:model pure JVM — domain types, ScheduleEngine, AlertPlanner +:core:designsystem theme, typography, Compose components +:core:data Room, domain remotes, REST/Connect, repositories, sync, notifications +:widget Glance home-screen widget +:app screens, navigation, ViewModels +``` + +Room is the single source of truth; the network only fills it. `:core:data` must **not** +depend on `:widget` — the timetable repository's `onDataChanged` tells the widget it has new +data, after the background sync and an in-app refresh alike, by broadcasting +`com.lumenpearson.lessons.action.DATA_SYNCED`, precisely so the dependency does not have to +be circular. + +There are **two** Room databases: `lessons.db`, the class cache, and `diary.db`, the +family's own diary, which nothing writes but `DiaryRepositoryImpl`'s successful reads, under +a generation guard that drops a read landing after a sign-out. A phone is in one of three +shell modes — `CLASS`, `DIARY` (a diary and no class, whose home is the diary) or `NONE` (the +first run) — and the periodic class sync is armed in `CLASS` only (#152): +`LessonsApplication` collects `shellMode.syncArming` rather than scheduling on every settings +emission. + +**A window is one school year, and a class holds several of them.** `synced_window` says +which years this phone has fetched, `replaceWindow` replaces one and leaves the rest, and +`syncedYears` is what the screens read to tell «нет уроков» from «ещё не загружено». The +table exists because those two cannot be told apart by counting rows — a class made in +March has none before it either way. Three years are kept per class; what goes is the one +furthest from the year holding today, never that year, and its `ETag` goes with its rows. +Only the sync of the current year writes the lookahead row, and the ranged deletes spare +it — but **nothing writes it today**, and the claim that used to stand here is what sent an +audit looking. The server resolves `next_school_day` at most 21 days past the last lesson +*inside the window that was asked for*, and a window running to the school year's end +leaves only June, which is out of season for every class — `services/terms.py` refuses a +term past 31 May, so there is no class it could be in season for. What answers «what is +next» across a gap is `TimetableDao.firstTeachingDayAfter` over the cached year, which is +now a whole year rather than a fortnight; the row's residue is the last days of May. +`docs/architecture.md` says what a server change would have to be, and why it was not made. + +There is no Hilt. `Graph` is a small hand-written container a test can swap wholesale. +The application implements GraphOwner and supplies the required transport/version/streaming +configuration to the same container even when a worker or notification initializes first. +Schedule, Join, Me, management, directory and diary expose domain-valued v2 remotes; +strict DTOs/generated lite messages stay below repositories, with v1 retained for +compatibility fixtures. The shared server client signs at send time, and each call +retains its own refusal status or original no-answer exception. + +- Only DEVICE_TOKEN_INVALID revokes v2 membership; bare401/CLIENT_TOO_OLD retain cache and tags (`V2MembershipLifecycleTest`, `V2SyncRepositoryTest`). +- Run the complete JVM gate without the release AndroidTest target property; apply `lessons.nativeCheck=true` only to native APK packaging (`test_ci_required.py`, #737). +- Parse apksigner certificate identities across numbered and scheme-labelled output, excluding source stamps and refusing distinct signer identities (`test_ci_required.py`, #740). +- Schedule applies and revocations validate the sent server/token under the membership gate; completed exit/replacement wins (`V2InFlightMembershipTest`, `ScheduleObservationTest`). +- Capture the displayed server/class/bearer before queuing management or unlink actions; generation alone cannot hold the IO-dispatch gap (`ManagementInitiatingOwnerTest`, `DeviceLinkInitiatingOwnerTest`, #758, #761). +- Bind role caches and active Account refreshes to server/class/bearer, treating legacy unowned roles as unknown (`CachedRoleOwnerTest`, `SettingsViewModelTest`, #760). +- Diary cache commits need sent credentials and generation under the local identity gate; complete owned logout cleanup after credential commit (`DiaryAccountTransitionTest`, #762, #763). +- DIARY_CREDENTIALS_REJECTED refuses an already-open session, not its password (`DiarySignInRemainingFailureTest`, `DiarySignInTest`, #759). + +#### Conventions already true in this codebase + +- **Comments explain why, not what.** Read almost any file here: the comment above a + decision says what would break without it. A comment that restates the line below it does + not survive review. +- **Russian in user-facing strings, English in everything written about them.** Both halves + are load bearing. `values/` is Russian and is the source; `values-en/` is the translation; + documentation, comments, commit messages and pull request descriptions are English. A + quotation of product text keeps its Russian and goes in guillemets — «⏱ Сокращённые + уроки», «Алгебра», «9А» — so a reader can tell a quotation from prose. +- **Every Russian string has an English twin.** `app/src/test/.../ResourceTranslationTest.kt` + reads both folders out of the source tree and fails on a name missing from `values-en/`, + on a name only in English, on mismatched format arguments, and on an English `` + that is not exactly `one` + `other`. Android resolves names one by one, so a missing + translation is not a missing screen — it is one Russian line in the middle of an English + one, with nothing logged. +- **No commit without lint and tests green.** `ruff check` and `pytest -q` for the server, + `./gradlew test` for Android; touch both halves and run both. +- **Versions are copied from a project that builds, never guessed.** The header of + `android/gradle/libs.versions.toml` names where each one came from. The first CI run of + this project failed on four invented versions that exist in no repository. +- **Commit messages are English sentences that say what the change makes the project do** — + "Let the class be run from the phone, by the same rules as from the bot". No Conventional + Commits prefix (none of the 288 commits has one), and the body explains the reasoning and + names what is left uncovered. No attribution trailer: commits up to 6 October 2026 mostly + carry a `Co-Authored-By: Claude …` line, none since does, and a new commit adds none + (`AI_USAGE_POLICY.md`, «Attribution in commits»). +- **Every pull request carries a milestone**, set when it is opened, and so does every + issue. A remote session can neither create a milestone nor list one, and a local one with + `gh` could, but creating one is the owner's decision either way — when none of the + thirteen fits, ask the owner and hand over the title and description already written, + rather than inventing a version or leaving the pull request bare. The `github-pr` skill + has the numbers, the one tool that sets them, and the two ways this was got wrong first. + **Four version milestones are open:** the ninth, `v0.8.0 — On-device checks, 89-region e-diary + survey`, holds #109–#117 and what #186's walk on an emulator found, the first work that + needs an emulator or a phone; the tenth, `v0.9.0 — NetSchool e-diary, onboarding via the + school's diary`, holds PR #140 and its issues, and the external audit of 27 September + (#190–#213); the eleventh, `v0.10.0 — One contract: REST v2, Connect and native gRPC, + build console`, holds the programme of `docs/specs/2026-10-03-one-contract-design.md` + (epic #273), and is the one being worked on; the twelfth, `v1.0.0 — A build somebody + else can install`, holds epic #127 and the open steps it names. Beside them stand two + buckets that are deliberately not versions: the seventh, `Dependencies — dependabot + bumps`, and the thirteenth, `Backlog — not scheduled`, for known gaps and decisions no + release is waiting for. The first ten were renamed on 25 September 2026, so a title quoted + from before then finds nothing when searched. +- **A defect that is found gets an issue, always, and before it gets a fix.** The rule is + new and it is not optional: the moment an audit, a review, a CI failure or a reader finds + something wrong, it becomes an issue of its own — title saying what is broken rather than + what to do about it, body carrying the failure scenario, `type:bug`, the `area:` it lives + in, a `status:`, and the milestone the fix will land in. **Then** the fix. A defect fixed + inside a batch and described only in a commit body is invisible the day somebody asks + «has this happened before», and eight bug sweeps' worth of that had to be back-filled by + hand in #128 to make this repository answerable at all. + - **The issue and the pull request are tied together**, and the tie goes in the pull + request: `Closes #NN` (or `Fixes #NN`) in its body. GitHub then links them both ways and + closes the issue when the pull request merges, so neither side can be left behind. One + pull request may close several; say each on its own line. + - **Labels are created by using them** — `issue_write` with `method="create"` makes a + label that does not exist yet. It does **not** when `parent_issue_number` is passed: + that path validates the labels first and fails on an unknown one. Create the issue + plainly, then link it. + - **The Project board is project 6, «lessons», and it holds every issue and pull + request.** A remote session cannot reach it — Projects v2 is GraphQL-only and that + toolset is REST — so there a session controls the labels and never reports an issue as + «added to the project» on the strength of having labelled it. A local session has `gh` + with the `project` scope, and there putting the item on the board and setting its + Priority, Size, Estimate and dates is part of filing it: no rule on the board sets those. + Its «Auto-add to project» has filtered on `is:issue,pr`, closed items included, since 4 + October, but #294's item, which it did add, showed in neither the board's views nor its + item list until it was deleted and added again, so read the board back after filing. The rule for every field is the project's README; the `github-pr` skill, «The + board», has the commands. +- **There are issues now, and until #85 there were none.** Forty-two were opened in one go + to give the history and the backlog a shape the milestones alone could not: twenty-three + closed, describing what was built and what each bug sweep found, and nineteen open, which + were then the whole of what was left. Read the open ones before planning a batch — several say + what was *deliberately* left and why, so that a later session does not re-discover a + decision as if it were an oversight. The labels are `type:` (feature, bug, chore, + research, decision, epic), `area:` (android, widget, server, bot, db, ci, docs, design, + data), `status:` (now, next, someday, done) and `needs:` (device, owner). The board + is the owner's (project 6, above); these labels are what its saved views filter on, and + its fields are what a local session keeps filled. +- **A release explains itself, fix by fix.** When a version is tagged, the notes name every + change in it with **its issue and its pull request** — «what was wrong, what it does now, + #NN / #MM» — rather than a list of commit subjects. The milestone is what says which + changes belong to the release, so it is set before the tag rather than after, and the tag + is the version the milestone is named for. The `release` skill has the order and what the + notes may not claim. Nothing in this repository has ever been tagged or released, so the + first one sets the pattern for every one after it. +- **Say what is not covered.** The README has an "Honest status" section and it is honest on + purpose. "Written, never run" is a legitimate status; a claim that something was + verified when it was not is not. +- **A new kind of test, a new CI check or a new shape of the build starts from + `docs/engineering.md`.** It reads this project against the engineering practice Airbnb has + published under one standard — a practice is taken only where it beats what is already + here — and says where this project is already ahead, what is left under epic #626, and + what was dropped and why. A proposal that brings back a dropped one says why its reason no + longer holds. +- **A trap that a test or a lint rule holds is one line here, naming what holds it.** Only a + trap nothing holds gets its paragraph, and the pull request that fixes a defect says «what + holds it» — a test, a rule, or «nothing can, because …» (the template). #648 is the cut of + this file to that rule. +- **Test at the cheapest layer that can hold the question.** `:core:model` before a view + model, a view model before a screen, a screen at a state built by hand before an + interaction, and never a Compose test for arithmetic. The `android-tests` agent has the + Android half, `server-tests` the server's. +- **A server change is read against the APKs already installed.** A merge to `master` deploys + itself and an installed app updates when its owner says so: nothing is removed or renamed + in what `/api/v1` answers, no new required field appears in what it is sent, and a v2 change + passes `buf breaking` or says why the break is safe. The pull request template asks it. + +#### What will bite you + +- **Current suite totals agree with `docs/counts.json`, regenerated only from complete successful reports** (`test_counts.py` and both CI post-run checks, #660). + +- **PostgreSQL test clusters need Unicode case conversion** (`test_search_folds_case_for_cyrillic_too`); the `C` locale does not satisfy it. + +- **The server has no clock.** On Vercel nothing runs between requests, so there is no + scheduler, no background task and no `asyncio` loop that survives a response. The morning + and evening digests are driven from outside by whoever calls `GET /api/v1/cron/tick` + with `X-Cron-Secret`. The endpoint marks a digest sent **before** sending it, and works + from "what is due and not yet sent today" rather than "did the last tick fire" — so a + tick that dies halfway does not send twice and a tick ten minutes late still sends. + Anything you are tempted to schedule in-process belongs in that tick instead. + The tick runs the self-check (`services/health.py`) after the digests and the sweeps and + before the diary keep-alive, which writes to `OWNER_IDS` when a check changes; when the + whole server is down, only the external cron's own failure email can say so + (`docs/deploy.md`, «The external cron»). + **The caller is an external cron service, not GitHub.** `.github/workflows/reminders.yml` + asked for a tick every five minutes and delivered 6.7 a day over five days of + measurement, in gaps of two to six and a half hours — GitHub runs schedules on a + best-effort basis and that is what the effort came to on a private repository. It still + asks for five minutes, because public runners cost nothing and the throttling may well + differ, but until that has been measured again it is the fallback: the promise the bot + makes («в течение примерно пяти минут») is kept by the external cron in + `docs/deploy.md`. +- **A deployment refuses to start rather than keep a local default.** `get_settings()` + raises `DeploymentNotConfigured` when `VERCEL` is set, or `LESSONS_TARGET` (the host + image's marker, `host` and nothing else), and any of `DATABASE_URL`, + `BOT_TOKEN`, `WEBHOOK_SECRET` or `RUN_BOT` is missing or unusable, or `OWNER_IDS` or + `TIMEZONE` is set to a value that cannot be used — an `OWNER_IDS` with no readable id, a + `TIMEZONE` that is not a zone. An empty `OWNER_IDS` is left alone on purpose + (`test_an_empty_owner_ids_is_left_alone`) and an unset `TIMEZONE` takes `Europe/Moscow`. + It lists every problem at once, because finding the next costs another deploy — with one + exception: `WEBHOOK_SECRET` is asked about only once `BOT_TOKEN` is set, since without a + token there is no webhook to protect (#331). This is + not tidiness: `DATABASE_URL` set for one Vercel environment and not the other left the + SQLite default standing, and the only thing anybody saw was + `ModuleNotFoundError: No module named 'aiosqlite'` out of SQLAlchemy's sqlite dialect — + a message naming neither the setting, nor the environment it was missing from, nor this + project. The check hangs on `VERCEL` and `LESSONS_TARGET` because each is a deployment's + statement about itself, and a `LESSONS_TARGET` that names no target is refused; guessing + "this looks like production" anywhere else would one day refuse to start on somebody's + laptop. **Do not add an optional setting to that list.** `DIARY_SECRET`, `DADATA_TOKEN`, + `PUBLIC_BASE_URL`, `BOT_USERNAME` and `CRON_SECRET` are empty by design and each already + refuses in view of whoever it concerns; `SENTRY_DSN` (nothing reaches Sentry) and + `GITHUB_READ_TOKEN` (the `deploy` check asks GitHub anonymously instead) are two more, + neither ever a reason to refuse to start. All are logged as switched off at startup + (`Settings.disabled_features`), which is a different decision from making them mandatory. + `DIARY_PROXY_URL` (#334) is optional too, and empty is not a switch but a route: no diary + goes through a proxy, which is right inside Russia. Only an unusable value is announced, + and never quoted, because it can carry the proxy's password. `DIARY_EGRESS` (#406) beside + it is optional as well, and best left unset: unset, or `proxy`, means the proxy where the + URL is usable — for Petersburg and the twelve «Сетевой город» regions marked `via_proxy` in + `regions.py`, every other region direct — and direct otherwise; `direct` sends nothing + through it; `relay` is read as `direct` until the relay exists (#408). Only what does not + take effect as written is announced, never a value. `providers/diary/registry.route` is the + one place that answers which way a server is reached. + `MIN_CLIENT_VERSION` is optional as well — empty means no minimum, and a request without + `X-Lessons-Client` is never refused — and it is not a feature switched off, so it is in + neither list. `LESSONS_STREAMING` is optional too — off unless `true`, and never on + Vercel whatever it says. What Vercel says about the running deployment — `VERCEL_ENV`, + `VERCEL_GIT_COMMIT_SHA`, `VERCEL_GIT_REPO_OWNER`, `VERCEL_GIT_REPO_SLUG` and + `VERCEL_REGION` — is no setting at all: `config.deployment()` reads it from the environment + alone, never from `.env`, and off Vercel it is empty. +- **A bulk statement on a window table must touch the bus.** `WatchClass` hears a class + change through the session (`app/watch.py`), and an `update`, `delete` or `insert` + executed directly never passes through the unit of work. Whoever writes one on a table a + schedule window is read from calls `watch.touch(session, class_id)` in the same function, + or a phone watching the class never learns of the change; `tests/test_watch.py` walks all + of `app/` for them, the bot included, and names the function that forgot. +- **The widget's size ladder has twelve rungs, and the count is the point.** + `WidgetSizeClass` (in `:widget`) declares twelve breakpoints because the launcher and + Glance both pick the **nearest** breakpoint by squared distance, not the largest that + fits. With five rungs, a 4-cell-wide widget taller than about 471 dp landed on the narrow + 110×300 column and drew half a screen of one column. Do not remove an intermediate rung to + tidy the enum; `WidgetSizeClassTest` reproduces the launcher's rule and will say so. +- **A phone gets into a class two ways, and one of them is not read-only.** The + class code (eight characters) buys an anonymous, read-only token. A personal + code from the bot's «📱 Подключить телефон» (ten characters, fifteen minutes, + one phone) buys a token already linked to the account that minted it, so it + writes with that account's role — checked per request, never cached. Both go + into the same `code` field of the same `POST /api/v1/join`; they cannot + collide because the lengths differ, and the class code is looked up first. + `SchoolClass.join_mode` decides whether the class code opens anything at all; + switching it revokes no device, in either direction, and three screens promise + that out loud. A `403` from `/join` means the class takes invites only — it is + deliberately *not* counted against the throttle, because that caller had a + real code. +- **There are two independent bearer tokens.** The device token from `POST /api/v1/join` + (`api/deps.py:current_device`) and the diary session token from + `POST /api/v1/diary/session` — a session the phone opened with the diary itself — or the + older `POST /api/v1/diary/login` (`api/diary.py:current_diary`). A phone can be joined to a class + without a diary account and signed in to a diary without a class; neither implies the + other, and one token meaning both would have to be re-minted whenever either half changed. + They go in the same `Authorization: Bearer` header on different endpoint families — check + which one an endpoint depends on before moving it. +- Petersburg sessions stay in request-local Cookie headers; named httpx/HTTP 422 deprecations fail pytest (`test_a_call_carries_its_own_session_in_the_request`, `filterwarnings`, #391). +- **The diary needs `DIARY_SECRET` or it does not run.** The upstream session — Petersburg's + token or «Сетевой город»'s bearer and cookies, however it arrived — is + the one stored credential that cannot be a hash (it is replayed upstream on every call), + so it is sealed with Fernet — `app/crypto.py`. No key means the feature refuses at the + door rather than falling back to plaintext, because a silent fallback is invisible and + deployments stay in that state for years. Refusing at the door also means touching nothing + behind it: with no key every seal reads as unreadable, so `services/diary.unusable` expires a + session only when a configured key cannot open it, and a request with a diary token is + answered «disabled» before the token is looked at. Until #302, a lost key expired every + session it was asked about, for good. `tests/conftest.py` sets one; a test that wants the + feature *off* patches it away. +- **Run the migration BEFORE the merge that needs it.** A merge to `master` deploys itself; + `alembic upgrade head` is run by hand. Between them is a window where the code knows a + column the database does not, and that window has already taken production down: the new + columns on `classes` landed first, nothing failed at startup, and the first ORM read of a + class did — which for the bot is the middleware, so every update died. Every revision + after `0001` is additive, so applying it to the *running* code is safe; the other order + never is. `GET /api/v1/warmup` answers `{"status": "degraded", ...}` when the database is + behind and names both revisions (`app/db.py:EXPECTED_REVISION`, pinned to the real head by + `tests/test_schema_version.py`), and `{"status": "degraded", "detail": "База впереди + кода…"}` in the window the correct order creates. `/api/v1/health` deliberately opens no + connection, so it cannot tell you this. +- **Apply migrations through the Neon connector, from here.** The owner does not run + `alembic upgrade head` by hand and this session has no `DATABASE_URL`; the project is the + one named `lessons` on the Neon MCP server — the account has two, so read the name rather + than guessing an id, and the id itself stays out of the repository — and `0005` through + `0019` were all applied that way, and from `0018` on each went to the Neon branch `preview` + first, when its pull request was pushed, and to production before the merge; every revision + now goes that way. It is not alembic running — it is the revision's DDL executed as one + transaction, with `alembic_version` stamped in the same transaction — so three things + follow. Take the DDL from the model rather than writing it out: `CreateTable(...).compile( + dialect=postgresql.dialect())` prints exactly what `create_all` would build, which is what + the revision is supposed to produce. Read the database's state first and stamp it last, so + a half-applied revision cannot claim to be whole. And say what a revision destroys before + running it — `0006` deletes every row of `diary_sessions` on purpose, and that is a + sentence the owner needs *before* the transaction, not after. +##### The Alembic chain through 0019 + +- **Migrations are Alembic and the head is `0019`, applied before the merge of the monitoring pull request, as `0018` was before stage 3b-1's; `0015` to `0017` were applied on 26 September 2026, before #140's merge.** `0001` is a guarded + `create_all`, `0002` widens Telegram ids to 64 bits, `0003` adds tasks/reminders/links, + `0004` adds diary sessions, `0005` adds `bell_schedules.canteen_after_index`, `0006` + encrypts the diary credential (and **deletes** the existing sessions, on purpose) and adds + the per-member diary columns, `0007` adds the two class foreign keys `0006` left out, + `0008` gives a class a number (1–11) and cuts its year into quarters or half-years, + `0009` adds the corrections a family lays over the diary, `0010` gives a class its join + mode and adds the personal connect codes, and `0011` tightens two `diary_overrides` + timestamps `0009` left nullable while the model builds them `NOT NULL` — a no-op on this + database, because the DDL for `0009` came from the model, and not one on a deployment + that ran the chain through alembic. `0012` does the same for eight more timestamps in + seven tables that `0003`, `0004` and `0006` left loose — and on this database it was + **not** a no-op: all eight really were nullable, and all eight held zero nulls, so it + tightened them and rewrote nothing. `0013` adds `uq_homework_per_subject_per_day` + and was **applied after the merge, not before** — see the constraint rule + below; on this database it deleted nothing, because `homework` held no rows + and therefore no duplicates. `0014` widens `day_overrides.kind` from + `VARCHAR(9)` to `VARCHAR(10)`, because `DayKind` gained `SELF_STUDY` and a + `SAEnum` stores the member **name** — the column is exactly as wide as the + longest one, so adding a kind is a migration rather than a line. It is the + ordinary additive shape and went on **before** the merge; it rewrites no row + and every existing value stays what it was. `0015` adds the second diary + provider's columns: `diary_sessions.provider` and `region` (which diary and + which regional server a session is on, so a session can be matched to its + class's binding and grouped per origin for the keep-alive without unsealing + the credential), three keep-alive clocks (`kept_alive_at`, + `keepalive_attempted_at`, `upstream_ok_at`), and on `classes` the binding + `diary_region`, `diary_school_id` and `diary_school_name`. All eight are + nullable and additive — the ordinary shape, on **before** the merge — and + rewrite no row; a NULL `provider` on an existing session means Petersburg, the + only diary before the column. Its downgrade expires every non-Petersburg + session before dropping the columns that tell one apart, so reverted code + cannot replay a credential at the wrong upstream. `0016` creates + `usage_counters`: one row per counter per Moscow day, which is how the + anonymous school directory's share of DaData's daily allowance is spent + without touching the share the bot's create-class search needs — a table of + its own, because `join_attempts` is pruned to fifteen minutes on every + recorded attempt and would cut a day's count to a quarter of an hour. It + creates a table and nothing else — additive, the ordinary shape, rewrites + and destroys no row — and goes on **before** the merge, together with + `0015`; its downgrade drops the table and with it nothing but the counts. + `0017` changes no schema: it files the corrections over the diary under the + **child** rather than under a login (#165, the owner's decision of 26 + September) — `diary_overrides.login` keeps its name and holds the scope + `services/diary_corrections.child_scope` builds, `CHILD:petersburg` or `CHILD:netschool:` + and the regional server's host and no other shape (a child the diary lists + outside its own numbering gets no corrections at all), upper case so that + no casefolded login can ever equal one. It **destroys rows**: every legacy + «Сетевой город» key (a hash whose region is recoverable at best for authors + still signed in; only where #140's branch ran), and, wherever two logins — + or a legacy and a per-child row — corrected the same field of the same + child, all but the newest (`updated_at`, then `id`); the rest of the old + Petersburg rows are rewritten to `CHILD:petersburg`. Its docstring carries a + count per destructive step to read before the transaction, and on + PostgreSQL it locks the table against writes first. On this database, with + no correction in it on 26 September, that was nothing, and it went on with + `0015` and `0016` **before** the merge. On a deployment that holds + corrections it is better applied just **after** the merge — a key rewrite, + a third shape beside the column and the constraint: before it, whatever the + old code writes in the window is filed under a login the new code never + reads; after it, the rewrite folds the old rows into what was typed + meanwhile, but a reset made in the window comes back, so the window is + minutes. Its downgrade is a no-op, and a revert is **not** lossless: after + any window of older code, run its statements again, or + `alembic downgrade 0016 && alembic upgrade head`. + `0018` adds `device_tokens.client_version`, the app version each phone last sent + to v2 (the server-v2 design, decision 15): one nullable integer column, the + ordinary additive shape, on **before** the merge. Its downgrade drops the column + and with it nothing but the versions. + `0019` creates `health_checks`, one row per check of the tick's self-check + (`services/health.py`): what it said last, since when, and when the owner was last + told. One new table and nothing else, the ordinary additive shape, on **before** the + merge; its downgrade drops the table and with it nothing but what the checks remembered. + Nothing after `0001` may use `create_all`. + Beware the enum: `SAEnum(SomeStrEnum)` stores the member **name**, so a `server_default` + written as `.value` is a string the ORM cannot read back — which on `classes` is a + `LookupError` in the bot's middleware, i.e. every update at once. `0010` nearly shipped + exactly that. A model change needs + a revision — a live database will not grow a column on its own, and lifespan `create_all` + runs only for local SQLite. +- **A constraint migrates in the opposite direction from a column.** The rule + above — migration first, merge second — is about code that knows a column the + database does not, and it is right for every additive revision in this chain. + A `UNIQUE` or a `NOT NULL` is the other way round: it is the **old** code that + breaks against it, with an `IntegrityError` nobody catches where a moment + earlier there was a duplicate. `0013` is that shape and says so in its own + docstring — it went on *after* the merge of PR #45, and `services/homework.py` + is written to be correct with or without it so the window in between behaved + exactly like production did before. `0012` is the safe shape (eight timestamps that already + hold no nulls) and was applied the usual way, before the merge. Read the + database before either: `0012` turned out to be a real fix rather than the + no-op `0011` was, because all eight columns really were nullable there. +- **The weekly template stops when the school says it stops, and twice it did + not.** `SCHOOL_YEAR_END_MONTH` is 5 and `schedule.py`'s comment says June + onwards must not repeat the template; nothing read it, so every summer weekday + drew a full day on the phone, in the widget, in the calendar feed and in the + morning digest — whose own rule about staying silent on an empty day could + never fire, because the day was never empty. That was the first half, and + `_resolve_day` started asking `school_year_bounds`. + The second half is that **the constant is not the school's answer — the terms + are.** A class whose «🗓 Четверти» said the half-year ended on 28 May still + drew lessons on the 29th, the 30th and the 31st, because the dates an admin + typed decided the term's *name* and nothing else, and 31 May is what + `SCHOOL_YEAR_END_MONTH` will always mean. `_resolve_day` now asks + `schedule.off_reason_for`, which reads the class's own terms for + that year and falls back to `school_year_bounds` only when the year has none. + The gaps **between** terms are out of season by the same rule, which is how + the autumn holidays get marked by moving two dates rather than nine days: the + conventional bounds are contiguous, so a class that never touched them is + unaffected. A day somebody marked by hand keeps its kind and note, and events + and homework are kept either way: it is the lessons that are out of season, + not the day. +- **Committed v1 replies are frozen before optional notices; bot construction and close failures cannot undo them** (`test_a_saved_event_survives_notice_lifecycle_failures`, `test_committed_edit_reply_survives_notification_session_expiry`, #377). +- **Notice warnings keep exception types, never exception values or tracebacks: Telegram request URLs can contain credentials** (`test_a_saved_decision_survives_notice_lifecycle_failures`, `test_a_saved_event_survives_notice_lifecycle_failures`, #723). +- **Class administration retains its parent before writes; diary cleanup, phone-code minting and calendar rotation leave commit to the complete caller transaction** (`test_access_member_parent_races.py`, `test_class_settings_parent_races.py`, #702, #703). +- **Device join retains Class before burning an invite or inserting a token; a known valid code losing its Class is forgiven, not counted as a guess** (`test_join_parent_races.py`, #705). +- **Timetable writes retain Class, canteen writes refresh and retain Class then Bell, and bot lesson input guards service execution with audit and commit** (`test_editor_parent_races.py`, #707). +- **Phone linking retains Class and leaves claim/audit/commit to both bot callers before Telegram success** (`test_phone_link_parent_races.py`, #708). +- **Task writes retain Class then recheck and retain linked Homework through commit; deleting Homework still keeps the task with a NULL link** (`test_task_homework_parent_races.py`, #710). +- **New personal tasks retain Class before INSERT, and bot add/commit share the stale boundary** (`test_task_parent_races.py`, #699). +- **Access requests retain Class before submission or the pending row lock; bot request writes and commits share the stale boundary** (`test_access_request_parent_races.py`, `test_access_request_submission_parent.py`, #697, #700). +- **Audited device revoke/unlink retain Class before mutation; already-revoked retries stay read-only** (`test_device_parent_races.py`, #696). +- **Nonempty subject collection and explicit deletion retain Class before DML; empty collection stays read-only** (`test_subject_collection_delete_races.py`, #695). +- **Subject creation retains Class after its name check and before either Subject or audit is staged** (`test_subject_create_parent_races.py`, #692). +- **Subject renames and audited details retain Class before Subject; repeated details still UPDATE their row** (`test_subject_detail_races.py`, #690). +- **Explicit term writes force row-count checks, and bounds retain Class before Term to match cascades** (`test_term_stale_audits.py`, #688). +- **An audited unchanged retry still forces a row-counting UPDATE; v2 silent no-ops skip it** (`test_unchanged_audit_races.py`, #686). +- **Homework creates and upserts retain their Class through commit** (`test_homework_parent_races.py`, #684). +- **Special-day writes retain their Class and selected BellSchedule through commit; only v2's silent unchanged result skips the guard** (`test_stale_writes.py`, #682). +- **A lesson number needs a bell of its own number, everywhere a lesson is + written.** The resolver takes a lesson's times from the bell row of the same + number and drops what has none, so a row at a number the day does not ring is + stored, logged, announced and drawn nowhere. Three ways in had to learn this + separately: the week import, the button editor, and — later — the substitution + (`api/edit.py` and `bot/handlers/content/overrides.py` then, and + `services/substitutions.py`, which v1, v2 and the bot all ask, now) and the bot's single-day + paste, which used to write the template itself instead of going through + `services/structure.apply_timetable`. Check with `timetable_edit.can_ring`, + and for a dated write use `rung_indexes_on`, because a shortened day points + at a shorter schedule than the class's usual. Two more ways in were closed + later: **deleting** a lesson closed the gap in the numbering whatever it + landed on (bells at 1, 2, 4 lost the fourth lesson onto a third slot that + rings nothing — `remove_lesson` now renumbers only when every moved lesson + still rings), and a day could be pointed at a bell schedule with **no rows**, + which draws nothing at all under a card saying «⏱ Сокращённые уроки» — + `special_days.put_day`, the one write v1, v2 and the bot mark a day through, + refuses that now. And when you report what was + dropped, count the **rows**, not the numbers: `apply_timetable` hands back + (weekday, number) pairs, because one number under two weekdays — or under + «чёт» and «нечёт» in one day — is two lessons nobody will see. +- **The diary sign-in ticket pays for an attempt, and an unreadable answer is + one.** `api/diary_web` spends the ticket before the sign-in so that whoever + holds the URL cannot sit and guess against the upstream from our address. Only + `UpstreamUnavailable` — a transport failure or a 5xx, where nothing ever + looked at what was typed — hands it back. A 200 of HTML must not: a login form + on Yii refuses a password with the same bytes a captcha arrives in, and this + diary has never been opened for real, so from here the two are + indistinguishable. The page says «дневник ответил непонятно» instead of + blaming the password, which is the part that was actually broken. +- **Time is naive local wall time, in the class's zone, not the server's.** A bell rings at + 08:30 whether or not the clocks changed. `SchoolClass.timezone` carries the zone; the + server decides "today" through `school_class.tz` and the client through + `Timetable.nowAtSchool()`. `LocalDateTime.now()` and `ZoneId.systemDefault()` on the + Android side are almost always a bug — that pair was two of the fourteen defects the audit + confirmed. +- **`Modifier.pointerInput(Unit)` keeps the lambdas it started with, for ever.** The + element compares equal on its keys alone, so a recomposition never even hands the node the + newer block, and the coroutine reading the finger goes on calling whatever it closed over + on the composition that created it. A state read through a delegate survives that; a plain + `val` computed in the caller's composition does not. The toolbar's reorder drag computed + its landing slot as such a `val`, so every drop asked where the tab had been *before* the + finger moved — `moveItem` refused the out-of-range index and the order came back unchanged. + It looked right the whole way, because the icons slide from a value recomputed every frame; + only the drop was stale, and the drop is the part that is remembered. Wrap every callback a + gesture detector will call in `rememberUpdatedState` — `text/Corrections.kt` already did, + which is what makes it a rule rather than a discovery. Do **not** key the `pointerInput` on + something that changes instead: that cancels the gesture under the finger. And a test that + only asks which callback fires, or only asks the arithmetic, will not see it — the question + is whether the number the gesture computes is the number it reports, and the way to ask it + without measuring Robolectric's densities is a drag so long it parks at the end under any + of them (`ToolbarDragTest`). +- **A Compose test that holds the clock must also send the snapshot notification.** + `MarqueeText` runs `Int.MAX_VALUE` iterations, so Compose's clock is never idle and + `waitForIdle` — which every assertion calls into — **hangs rather than fails**. The + answer is `mainClock.autoAdvance = false` and advancing frames by hand, and that buys a + second trap: a write made from the test thread (`ScrollState.dispatchRawDelta`, or a + `mutableStateOf` the composition reads) lands in the global snapshot and **nothing sends + the apply notification**, so neither the recomposer nor `snapshotFlow` ever wakes and the + value arrives after the last assertion has read it. Advancing frames does not help at any + count — twenty still read zero. Every `settle()` here calls + `Snapshot.sendApplyNotifications()` first. `LazyListState.scrollToItem` happens to escape + it, because `forceRemeasure` runs a measure pass inside a snapshot of its own, which is + exactly why the ribbon half of one test looked right while the list half did not. + The third trap in the same family: `performScrollTo` drives the scrollable's animation, so + with the clock held it moves nothing and every node below the fold reports «not + displayed», which is indistinguishable from the element being absent. Give the test a tall + window instead. +- **`compose-stability.conf` is a promise, and a `var` in `:core:model` breaks it.** The file + tells the Compose compiler that `java.time.*` and the whole domain package are stable, + because neither is compiled by the Compose plugin and one unknown field makes every class + holding it unstable — that one field was `LocalDate`, and it condemned `TodayUiState`, + `WeekDayUi`, `HomeworkUiState` and the diary's day and range along with it. What a false + promise costs is invisible: nothing fails to build and nothing throws, Compose simply stops + comparing the value and the screen keeps the old one. `StabilityPromiseTest` reads + `:core:model`'s own source and fails on the first `var`; if a type there has to become + mutable, move it out of the module and take the package off that file rather than leaving + both standing. The file itself says at length what is deliberately *not* promised — + `kotlin.collections.List` and `:core:data`'s value types — and why each would be a lie. + Re-measure with `reportsDestination` in a module's `composeCompiler` block and a + `--rerun-tasks` compile; it is left out of the build on purpose, because it writes reports + on every build and the question is asked rarely. +- **AGP 9 compiles Kotlin itself.** Applying `org.jetbrains.kotlin.android` in an Android + module is a hard build failure, not a warning. Pure-JVM modules still use `kotlin.jvm`. +- **The bot runs two ways from one dispatcher.** Long polling inside the API process + (`app/main.py` lifespan) locally, webhook on serverless, `build_dispatcher()` shared. FSM + state lives in the database (`app/fsm_storage.py`), not in memory, because each update may + hit a fresh process. `RUN_BOT=false` starts the API alone — that is what the tests use. + +- **On SQLite, a savepoint opens a transaction that keeps its lock until it ends** (#373). + `app/db.py` begins the transaction a `begin_nested()` assumes, so a refused write is rolled + back on the test suite's and a developer's SQLite as it is on Postgres. The price is a lock: + a bot handler that writes through a savepoint commits before it touches conversation state, + because the FSM storage commits on a connection of its own and would wait out the busy + timeout behind it. That is thirty seconds of a hung local bot, which no test sees, since the + handler tests hand the handlers a fake state. Production is Postgres and takes no such lock. + +#### Notes + +- **A message Telegram will not deliver is a screen that says nothing.** The + ceiling is 4096 characters after entity parsing, and the whole message is + refused rather than clipped: the homework digest had no bound and a fortnight + of three assignments a day came to 5371, so «📝 Домашнее задание» answered «что-то + пошло не так» and `/homework` — a plain `answer`, with no callback to + apologise on — answered nothing at all. Every renderer that grows with the + data carries a budget (`WEEK_TEXT_LIMIT`, `TASK_LINES_MAX`, + `HOMEWORK_DIGEST_LIMIT`, `render.clamp`) and says «… и ещё N». Cut a + string **before** escaping it: cutting after can leave «&am», which is a + refused message of its own. +- **Everything from outside is escaped before it goes into a message.** The bot sends + HTML, and Telegram refuses the **whole message** on a stray `<` rather than damaging one + row — so an unescaped string does not produce a broken line, it produces a blank screen + and no error anybody sees. The strings that come from outside are: anything the + Petersburg diary sends (subject, room, teacher, topic, homework), anything typed into + the bot or pasted into the timetable grammar (a subject really can be «Алгебра <7>»), + and anything out of the schools registry. `render.py`, and the per-screen renderers split + out of it (`week_render`, `homework_render`, `tasks_render`, `access_render`), always did this; + `diary_render.py` and `editor_render.py` never did, and both shipped that way. + Two related traps in the same family: `plural(n, …)` already contains the number, so + `f"{n} {plural(n, …)}"` prints «10 10 минут» — three callers had it, and one had a test + that passed because «10 минут» is a substring. And `answerCallbackQuery` takes no parse + mode, so a card built for a message shows its own tags in an alert; run it through + `editor_render.as_alert` instead — which also cuts at 200 characters, because past + that Telegram answers 400 and the press answers nothing at all. +- **A list page and the keyboard under it read the same number.** `manage_render` + declares `SUBJECTS_MAX`, `BELLS_MAX`, `DEVICES_MAX` and `LIST_MAX` beside each page's + renderer, and `manage_keyboards` builds that page's rows from the same names. While there were two + numbers, three pages of four drew rows no button could reach and «… и ещё N» said + nothing, because it counted from the renderer's number. The values differ on + purpose — a bell schedule's row carries three buttons and twelve lines of times, a + subject's one of each — so do not "tidy" them into one constant; the rule is that + what is drawn is what can be pressed, and + `test_no_list_page_draws_a_row_the_keyboard_cannot_reach` holds it. Nothing + paginates, so past the cap a row is only a number. +- **Callback data is whatever the client sent, and a bare conversion on it is not + a small bug.** `int(callback_data.value)` does not refuse a press it cannot parse + — it raises out of the handler, so `callback.answer()` is never reached and the + button keeps its spinner until Telegram gives up. Every handler module carries a + guard for this: `_int_or_none` in `manage/_common.py`, `tasks.py`, `content/homework.py` and `access.py`, + `_date_or_none` in `calendar.py` and `content/_common.py`, `_role_or_none` in + `access.py`, `_kind_or_none` and `_index_or_none` in `content/_common.py`, and + `shift_days`/`shift_weeks` in `keyboards.py` for the offsets (`timedelta( + days=999999999)` is an OverflowError, not a far-away day). Check the value + **where it is picked**, not where it is finally read: a value carried through + three questions raises in front of somebody who has just typed a time and a + title, and looks like their answer was the problem. +- **Two screens can match one press.** Both role pickers send a `RolePick`, and the + only thing telling them apart is that the invite flow leaves `target` empty. While + the invite handler's filter was a bare `RolePick.filter()` it swallowed both, + because it is registered first — so a role pressed on an older «Новая роль» card + created a phone invite and said so in a sentence about the number. Split a shared + payload on a field, never on registration order; + `test_the_two_role_pickers_never_match_the_same_press` holds it. + The pairs that predate the rule — `/start link_…` and `/start`, a shared + contact and the create-a-class wizard's text steps, the two `TimezonePick` + handlers — are held in their order by `test_bot_commands.py`, so a router + split cannot reorder them quietly. +- **`ResourceTranslationTest` covers every module that ships strings**, not just + `:app` — `:core:data`, `:core:designsystem` and `:widget` have their own + `values/` and went unguarded for a long time, which is how the countdown on the + home screen stayed Russian under an English caption. It discovers the modules + rather than listing them, and counts a ``' arguments per form (Russian + has four forms and English two; over the concatenated text they can never agree). + What it cannot see is a Russian string written into Kotlin, because that word is + in neither folder. The check for that, run from `android/`, is + `LC_ALL=C.UTF-8 grep -rnP --include='*.kt' '^(?!\s*(\*|//|/\*)).*"[^"]*[\x{0400}-\x{04FF}]' */src/main core/*/src/main`. + Each part is there for a reason (#315): + - `core/*/src/main` because `*/src/main` alone never reaches the three core modules; + - the comment guard because KDoc here quotes Russian on purpose and would bury a finding; + - the locale because Git Bash's `grep -P` refuses to run without it. + + Today it finds only `@Preview` data, maintainer-facing report bodies, the timezone list, + whose file documents the choice, and `core/data/.../upstream/UpstreamMarkers.kt` — the + diaries' own words, matched in their answers, which is the one documented exception on the + diary's side. +- **A renderer is written against the type it is handed, and nothing checks that but you.** + «🗓 Четверти» crashed on every press in production because the card printed `term.days` + and `days` lived on a flattened copy of a term that nothing ever constructed. There is + no compiler here. `python -m mypy` is: it reproduces that exact failure when the property + is removed, and it is clean today. If you add a «view» dataclass beside a model, check + that something builds it — an unused twin is how a renderer ends up written against the + one it will never receive. +- **An enum column stores the member NAME.** `SAEnum(SomeStrEnum)` writes + `OPEN`, not `open` — check `bot_users.role` in the live database if you doubt + it. A `server_default` spelled as `.value` therefore lands an unreadable + string on every existing row, and the first ORM read of one raises + `LookupError` — which on `classes` is the bot's middleware, i.e. every update + at once. `0010` was written that way and caught before it was applied; + `tests/test_join_modes.py` now holds all three sides of it. +- **The developer mode's gate is not a lock** (#237). Seven taps on the version reveal + «Для разработчиков», and a GitHub account with push to this repository opens it, but an + APK can be patched past any check on the phone. So nothing behind it may unlock what the + server would refuse or show a secret. Its network record keeps a list of what it may keep + (`NetworkRedaction`): a header, a body or a query value added later stays out unless + somebody adds it to that list on purpose. Its request console reaches our server and the + catalog's diaries only — `planConsole` judges the resolved URL, and the console's own client + follows no redirect and guards the origin again — and puts a bearer on our server alone, + read as the request leaves. `docs/architecture.md` has the rest. +- **Work enters dev through one temporary branch; only reviewed dev is promoted to master** (#724). Both persistent branches run Actions; remove a working ref after its dev merge, never its worktree files or unique work. +- **A diary session deleted while changing pupils is signed out, with rollback before any reply** (`test_the_bots_diary_says_a_session_signed_out_meanwhile_is_signed_out`, #725). +- **Another agent may be working in this tree.** Check `git status` before you touch a file + you did not open, and do not revert someone else's uncommitted work. +- **`HANDOVER.md` at the root says where the work stands** — the branches, what the last + session finished, what it deliberately left alone and what nothing has verified. It is + working state, not part of `docs/`, so it is stale the moment it stops being updated: + re-check the PR and CI before trusting it. It carries the last two batches; every batch + before them is in `docs/history.md`, newest first, verbatim. +- **A pull request of this session's own work is merged without asking.** The owner asked for + that on 20 September 2026; it is their standing instruction, recorded in the `github-pr` + skill with the five things to check first — CI green on the exact head, `mergeable_state` + clean, the gates run locally before the push, a milestone attached, and no review waiting + on an answer. The merge pins `expectedHeadSha` to the SHA that was checked, which is what + makes it safe. A migration whose side of the merge is unsettled, somebody else's pull + request, and «I want to look at this one» are outside it. +- **Updating it is the last step of every batch, and nobody should have to ask for it.** The + trigger is the merge: once a pull request is in `master`, that batch is not finished until + this file describes it. Write the close-out **while that pull request is still open** — it + is then one pull request rather than two, and the file is true at the moment it merges. + **A close-out never gets a close-out of its own:** it names itself as the only thing open, + and the SHA of its own merge is written by the next batch. A pull request whose only + content is correcting that SHA is the recursion rather than the cure. It has had to be asked for twice, and each time a batch had been + reported as done while the one document the next session starts from still described the + batch before. If the batch's own pull request has already merged, the update is its own + commit and its own pull request — with a milestone, like every other. What drifts every + time, and is not a judgement call, is listed in the `handover` skill: the opening + paragraph, the chain of batch sections — the new one on top, and the one that falls off + the last two moved to the top of `docs/history.md` — the milestone table, the test counts + in the seven places the skill names, and sections 5 and 7. +- **`.claude/` holds the agent configuration, and it describes the shape rather than + repeating this file.** `.claude/agents/` has one agent per area that has produced a defect + here, carrying the fact that would have prevented it; `.claude/skills/` has the procedures + (`gates`, `audit`, `migration`, `release`, `strings`, `bot-message`, `steward`, + `github-pr`, `handover`, `large-refactor`); `.claude/commands/` has `/where-are-we` and `/pre-push`; + `.claude/README.md` says what is deliberately absent — there is no `.mcp.json`, because + the Neon and Vercel connections need credentials. `AGENTS.md` and + `.github/copilot-instructions.md` are the same pointer for agents that read those instead. +- **Read a file before editing it; grep every caller before changing a function.** The + audits in `docs/design.md` exist because a conclusion drawn from call sites was wrong. +- Secrets never enter the repository: `BOT_TOKEN`, `OWNER_IDS`, `WEBHOOK_SECRET`, + `CRON_SECRET` live in `server/.env` or the host's environment; the release keystore and + its passwords come from the `LESSONS_KEYSTORE_FILE`, `LESSONS_KEYSTORE_PASSWORD`, + `LESSONS_KEY_ALIAS` and `LESSONS_KEY_PASSWORD` environment variables (in Actions, from the + secrets `KEYSTORE_BASE64`, `KEYSTORE_PASSWORD`, `KEY_ALIAS` and `KEY_PASSWORD`; #309) or from + `~/.gradle/gradle.properties`. **Never read or print that file**: on 5 October 2026 an agent + looking in it for a Gradle setting put a signing password into its transcript. Redact them as + `` in issues, logs and reports. +- The documentation index is `docs/README.md`. If a change makes a document wrong, fix it in + the same batch — `docs/widget.md` and `docs/bot.md` were each rewritten once because they + had drifted from the code, and that is more expensive than keeping up. diff --git a/docs/specs/2026-10-11-data-in-russia-design.md b/docs/specs/2026-10-11-data-in-russia-design.md new file mode 100644 index 00000000..bacc701d --- /dev/null +++ b/docs/specs/2026-10-11-data-in-russia-design.md @@ -0,0 +1,252 @@ +# Data residency choices for a Lessons deployment + +The owner recorded the design decision on 11 October 2026. This specification +records the choices available to a deployer and the implementation still needed +to offer them. It describes a Russian hosting option for an operator who chooses +it. The operator identifies its own deployment, selects the providers and +determines its obligations. [Owner's technical decision][owner-c] · +[Owner's deployment choice][owner-choice] · [Deployment scenarios][scenarios] + +## Compare the choices + +The **core** is the Lessons API, bot handlers and PostgreSQL. The selected +databases, replicas, backups, log stores and third-party services determine +where personal data goes. Choosing a region for the core answers only part of +that inventory. + +| Choice | Core and persistent data | Telegram and the school diaries | Cost and latency | +| --- | --- | --- | --- | +| **Vercel + Neon** | The documented baseline runs Vercel Functions in Frankfurt (`fra1`) and uses Neon PostgreSQL in Frankfurt. | The core uses Telegram's Bot API from Vercel. The foreign core may need the separate Russian diary proxy for Petersburg and the configured NetSchool regions. | Vercel plan, requests, function resources and transfer, plus Neon compute, storage, restore history and transfer. The app-to-core trip goes to Frankfurt. Co-location keeps the normal database trip short, while cold starts and database wake-ups can still add delay. | +| **A · Russian database only** | Vercel stays in Frankfurt and connects to PostgreSQL in a verified Russian region. Request handling and any such logging, caching or tracing remain on the foreign side. **Stopgap.** | Telegram still runs from Vercel. Diary routing is unchanged because the application origin stays abroad. | Keep the Vercel bill and add the Russian database, backups, connectivity and any fixed egress or allowlisting the two providers require. Each application/database round trip crosses Frankfurt–Russia, including connection establishment and sequential queries. A cross-border path failure can make an otherwise healthy database unavailable to the core. | +| **B · Russian core, direct Telegram** | A Russian VPS runs the reviewed Host image and same-VPS PostgreSQL. The database is on the private network. The operator chooses Russian locations for backups and any other required stores. | The bot calls Telegram directly when the chosen network can reach it. The October RUVDS observation rules out assuming this route works there. The Host can call Petersburg directly when that path is verified, and each used NetSchool route needs its own check. | One always-on VPS with CPU, memory, disk, public address and transfer, plus backup storage and operator time. The database path stays on the VPS. Client and diary timings depend on routing, and the Host and database contend for the same resources. One VPS is one failure domain. | +| **C · Russian core, scoped Telegram egress** | Same Russian Host, PostgreSQL and backup placement as B. The foreign endpoint forwards only Bot API traffic. | An SSH tunnel carries outbound Telegram HTTPS to an operator-chosen machine abroad. The incoming Telegram webhook still goes to the Russian Host. The diary uses the same route as B. | B's costs plus an existing or separately rented egress machine, traffic, supervision and monitoring. The extra hop affects Telegram calls. API-to-database traffic stays on the VPS. Loss of the tunnel affects Telegram-dependent operations. | + +Use the providers' current metering and quote the chosen configuration, +including network, snapshots and restores. Compare the same synthetic workload +on all candidates. Record warm and cold API p50/p95, pooled database connect +and sequential query timings, Telegram send time and webhook delivery, diary +response times and the tick's total duration. The latency statements in the +table follow the network paths. They are estimates until measured on the +operator's configuration. [Vercel Functions usage][vercel-cost] · +[Neon plans][neon-cost] · [Selectel prices][selectel-cost] · +[RUVDS pricing drivers][ruvds-cost] · [Current hosting guide][hosting] + +On 11 October 2026 the owner observed three 15-second HTTPS timeouts from the +RUVDS VPS to `api.telegram.org`, despite DNS resolution. Petersburg's diary +responded in about 0.2 seconds from the same VPS. This is a dated observation +from one source network. It supplies the reason for C and a test to repeat on a +future trial. [Owner's measurements][owner-c] + +## What the server and console need + +### A · Database compatibility + +The released URL normalizer supports a CA **file** through `sslrootcert` with +verified TLS modes. Its pooler detection uses the endpoint's hostname. The +owner wants an explicit pooler setting and a CA supplied as PEM configuration +so a deployment can describe any provider endpoint and use verified TLS on a +fileless host. These are implementation follow-ups even if nobody deploys A. +A needs a verified server certificate and hostname, a network access policy +the operator can enforce, pooler compatibility under load and a suitable +direct connection for backup, restore and schema migration. Keep credentials +in the operator's secret store. [Database URL normalization][db-url] · +[Owner's technical decision][owner-c] + +### B and C · Host and Telegram + +Use the accepted Selectel/RUVDS recipe for a pinned Host image, private +PostgreSQL, public TLS, webhook and an external tick. B leaves the proposed +Telegram egress setting empty. C needs a future per-bot HTTP session +configuration at the shared bot constructor so webhook replies, cron +reminders, alerts and post-commit notices take the same route. The current +constructor creates a direct Bot API client. The existing `DIARY_PROXY_URL` +and `DIARY_EGRESS` concern diary requests. They cannot select the Telegram +route. [Accepted Host recipe][vps] · [Shared bot constructor][bot] · +[Diary routing guide][diary] + +C's forwarder should accept only the dedicated Host route and the required +Bot API destinations. The Host's configured client keeps HTTPS certificate +and hostname validation through the tunnel. The SSH endpoint can see +connection metadata such as origin, destination and timing. It does not +terminate the HTTPS session, hold the bot token or receive readable Bot API +contents by design. Telegram terminates its own HTTPS and processes the +associated updates and message data. Keep the tunnel local to the Host or its +private network, authenticate both SSH endpoints, and give its service only +the forwarding access it needs. A configured C route should report delivery +failure when the tunnel is down, without switching to direct Telegram or +rerouting database, diary or other API traffic. Record that behavior using a +trial bot before a cutover. [Owner's technical decision][owner-c] · +[Telegram Bot API][telegram] + +### Deploy tab + +Today the Console reads credential-free warmup at an explicit HTTPS origin +and compares readiness with the checkout's expected schema. It can prepare +and run an isolated local Host backed by disposable SQLite, and check the +pyvoy and hypercorn backend markers. The warmup and local Host checks establish +different things. [Console Deploy README][console] + +The planned Deploy selection should show Vercel + Neon, A as a stopgap, +and the Russian Host with **direct** (B) or **scoped SSH** (C) Telegram. +For each choice, show its required configuration, where the data goes and the +relevant operator-run checks. Vercel should keep its existing reviewed release +path. A should report verified database connectivity, certificate trust and +pooler compatibility. B/C should offer Host/TLS/schema, the intended diary +route, Telegram in both directions and cron readbacks as distinct results. +The operator approves and executes the cutover. Provisioning, secret handling, +database moves, webhook/scheduler changes and regulator submissions remain +outside the current Console. [Console design][console-design] · +[Owner's deployment choice][owner-choice] + +## Move an existing deployment + +This is a proposed sequence for an authorized operator. Demonstrate it on +synthetic data with a separate database, bot and cron secret. No production +data, webhook or scheduler was moved for this design. + +1. **Prepare.** Confirm target region, backup and restore location, PostgreSQL + versions and extensions, recovery limits and the reviewed release SHA. + Rehearse a portable logical backup and restore using a supported PostgreSQL + major version. Check schema, constraints, per-table counts and sequences + without exposing row contents. Keep the relevant secret material private. + Preserve the configured `DIARY_SECRET` if encrypted diary sessions must + survive the move. Use the production origin already configured in the APK + where the operator can move it safely, or complete the client-origin + migration before going live. Review the notification changes before + operating the new route. [PostgreSQL logical backup][pg] · + [Hosting and schema upgrade order][schema] +2. **Stop writes at the old origin.** Arrange a maintenance window. Pause the + main tick and GitHub fallback, block old API and bot writes, and let in-flight + writes finish. Preserve pending Telegram updates. Check that the old + database has no remaining writers before taking and verifying the final + encrypted backup. Keep the source write fence in effect throughout restore + and cutover. Make it apply to the old runtime's database access as well as + the public origin, so legacy aliases, provider URLs, cached clients and + processes coming back online cannot bypass it. Use separate access for the + export and read-only verification. A rehearsal backup can be consistent + and still miss later commits. Keep every transfer and staging + location in the operator's approved inventory. Preview and trial use + independent synthetic data. +3. **Restore and check before opening writes.** For A, switch the Vercel + environment and advance the release using the existing reviewed process. + For B/C, restore into the private Russian database and start the pinned + Host behind TLS. Apply any needed Alembic revisions in the documented + order. With user writes and the target scheduler still closed, check + schema/readiness, a database read, TLS and intended client transports. + Reconcile the recovered state including reminder delivery markers, task + reminder state and audit records. In A the origin, webhook and cron can + keep their URLs if the origin and secrets are unchanged. Confirm they now + reach only the chosen database. [VPS recipe and cutover][vps] +4. **Make the new route the sole writer.** Keep target writes closed while + moving the public origin or automatic provider aliases. Check read-only + access at the routed origin and verify again that every old runtime, alias, + bot and tick remains unable to write to the source database. Then open + target writes, register the webhook with `drop_pending_updates=false` and + verify it with `getWebhookInfo`. Ensure there is one active Telegram + consumer, with polling off in webhook mode. Activate one five-minute tick + with the correct `X-Cron-Secret`, and read back a scheduled response and + failure alert configuration. A VPS timer or an external scheduling service + can supply the clock. If retaining the GitHub fallback, leave it paused + until its target and function are explicitly reverified. Verify that the + old origin, bot and tick cannot write. [Telegram's webhook methods][telegram] · + [External cron and fallback][cron] +5. **Keep a coherent rollback.** Before target writes, the previous compatible + image and verified old database can be restored to service after taking the + target offline. After target writes, treat the target as authoritative. + Rolling back the image against its current data needs schema compatibility. + Moving the database again needs a new stopped-writer export and approval + for its destination. Retain or retire old databases, snapshots and keys + according to the operator's documented recovery and retention decisions. + +## Facts for Roskomnadzor notices and counsel + +Federal Law No. 152-FZ Article 18(5), as amended by No. 23-FZ, addresses the +listed database operations while collecting Russian citizens' personal data, +including collection on the Internet. It bars using databases outside Russia +for those operations subject to the listed statutory exceptions. Article 22 +provides for a processing notice before processing, subject to Article 22(2), +and asks for the actual location of relevant databases and whether +cross-border transfer occurs. Under Article 22(7), report changes to required +details by the 15th of the following month. Roskomnadzor Order No. 180 provides +the initial, change and cessation forms. [152-FZ, Ministry of Labour text][law] · +[No. 23-FZ, official publication][law23] · +[Order No. 180, signed text][order180] + +Article 12(3) calls for a **separate** notice before starting a cross-border +transfer. Parts 4 and 5 describe the facts and recipient information the +operator needs, including purpose and legal basis, categories, destination +countries and recipient safeguards. The July 2026 amendment, No. 265-FZ, +changed how the current Roskomnadzor country list is used under Article 12. +Have counsel check the applicable list, timing and restrictions for each +confirmed destination and when a changed route needs additional filing. +A notification describes an activity. It does not settle which activities +the operator may lawfully undertake. [152-FZ, Articles 3, 12 and 22][law] · +[No. 265-FZ, official publication][law265] · +[152-FZ as amended through July 2026][law-current] + +| Choice | Facts the operator should have ready for the notice review | +| --- | --- | +| **Vercel + Neon** | Document the actual German database and application regions and any other replica, backup, log, tracing or support access locations. Identify the foreign processing and each recipient. Ask how Article 18(5) applies to collection on that deployment before using it for those records. | +| **A** | Record the Russian location of the primary database and the actual replica and backup locations. Frankfurt still handles requests and the data returned from the database. Include these foreign processing paths in the Article 12 assessment, along with the bot and optional integrations. A database move alone leaves these flows in place. | +| **B** | Record the Russian core, database and backup locations actually chosen. Assess Telegram as an external service even if the VPS connects directly. Confirm where any monitoring and support receive data. | +| **C** | Record the same Russian core footprint. Add the egress service and its country, what it can observe and retain, and the verified data and recipients at Telegram. Determine with counsel which recipients and territories belong in the Article 12 notice. The SSH relay country is separate from Telegram's actual processing locations. | + +Give counsel the application and provider data-flow inventory with the +operator's name, purposes, categories of people and data, actual +recipients and access, locations, retention and safeguards. Include what +Telegram updates and outbound messages carry, such as account and chat +identifiers, class information and user-entered text. Review host and provider +logs, encrypted backups and key custody, migration intermediaries, optional +Sentry and other integrations, and any support access from abroad. Establish +whether TLS transit metadata at the relay is itself personal data in the +operator's circumstances and how to treat Telegram's processing and geography. +For operators such as a public institution, also ask whether any separate +restrictions on use of foreign messaging services apply. Record provider +answers and counsel's decisions for the chosen deployment. [Foreign messenger +law, No. 41-FZ][law41] · [Roskomnadzor list][rkn-messengers] + +## Acceptance and follow-ups + +This design delivers the operator comparison called for by #435. The accepted +[#407 recipe][issue407] supplies the Host instructions. An operator-owned trial +still needs public TLS, usable APK origins, a native gRPC and applicable stream +check, Telegram webhook and outbound delivery, and a scheduled tick. The scope +of C also calls for the Telegram egress implementation and a trial of its +failure behavior. A's explicit pooler and PEM inputs and the Deploy choice +remain future implementation. A legal review, regulator filings and use of +personal data belong to the chosen operator and need deployment facts. + +The remaining [#438 programme][issue438] covers separate processing consent +(#431), retention (#432), hashed/expiring invitations (#433), provider-side +sign-in (#434), operator-filled legal texts (#436), the operator guide (#437) +and approved devices and scoped access (#442). Each has its own acceptance. +The deployment scenario for a phone relay still depends on [#408][issue408]. + +[owner-c]: https://github.com/lumenpearson/lessons/issues/435#issuecomment-6110862411 +[owner-choice]: https://github.com/lumenpearson/lessons/issues/435#issuecomment-6111267677 +[scenarios]: 2026-10-10-deployment-scenarios-design.md +[hosting]: ../deploy.md#option-1-vercel--neon +[vps]: ../deploy.md#a-single-host-on-selectel-or-ruvds +[schema]: ../deploy.md#a-migration-goes-before-the-deploy-not-after +[diary]: ../deploy.md#the-electronic-diary +[cron]: ../deploy.md#the-external-cron +[db-url]: ../../server/app/database_url.py +[bot]: ../../server/app/telegram_send.py +[console]: ../../tools/console/README.md +[console-design]: 2026-10-05-build-console-design.md +[issue407]: https://github.com/lumenpearson/lessons/issues/407 +[issue408]: https://github.com/lumenpearson/lessons/issues/408 +[issue438]: https://github.com/lumenpearson/lessons/issues/438 +[vercel-cost]: https://vercel.com/docs/functions/usage-and-pricing +[neon-cost]: https://neon.com/docs/introduction/plans +[selectel-cost]: https://selectel.ru/prices/ +[ruvds-cost]: https://ruvds.com/ru/ruvds_price_2026_jul/ +[telegram]: https://core.telegram.org/bots/api#setwebhook +[pg]: https://www.postgresql.org/docs/16/app-pgdump.html +[law]: https://mintrud.gov.ru/docs/laws/130 +[law23]: https://publication.pravo.gov.ru/document/0001202502280034 +[law265]: https://publication.pravo.gov.ru/document/0001202607260024 +[law-current]: https://www.tfoms18.ru/media/files/fz_152.pdf +[order180]: https://minjust.consultant.ru/files/33819 +[law41]: https://publication.pravo.gov.ru/document/0001202504010010 +[rkn-messengers]: https://rkn.gov.ru/docs/Perechen6_informacionnykh_sistem_05052023.pdf diff --git a/server/app/api/cron.py b/server/app/api/cron.py index 7aacb727..821b906d 100644 --- a/server/app/api/cron.py +++ b/server/app/api/cron.py @@ -35,6 +35,9 @@ router = APIRouter(route_class=DishkaAnnotatedRoute, prefix="/api/v1", tags=["cron"]) +# Shared by all reminder sends, counted from tick start to leave time for the sweeps and checks. +REMINDER_SEND_SECONDS = 12.0 + # Failed join attempts older than the throttle's window count for nothing. # The limiter prunes them itself on every failure it records; this sweep is # for the quiet weeks in which nobody mistypes a code and nothing prunes. @@ -158,9 +161,14 @@ async def tick( bot = _build_bot() try: - counts = await reminders.send_due(session, bot, datetime.now(UTC)) + counts = await reminders.send_due( + session, bot, datetime.now(UTC), deadline=started + REMINDER_SEND_SECONDS + ) finally: - await telegram_send.close_bot(bot) + try: + await telegram_send.close_bot(bot, timeout=telegram_send.POST_COMMIT_CLOSE_SECONDS) + except Exception as error: # noqa: BLE001 - closing cannot undo a send or fail the tick + log.warning("could not close the reminder bot: %s", type(error).__name__) # Ended before the FSM sweep, the one step here on a connection of its # own. Every claim has committed already, so on Postgres this ends diff --git a/server/app/api/edit.py b/server/app/api/edit.py index 5d6cad7d..8ed2e50f 100644 --- a/server/app/api/edit.py +++ b/server/app/api/edit.py @@ -15,6 +15,7 @@ from __future__ import annotations +import asyncio import logging from datetime import date as Date from typing import Any @@ -23,6 +24,7 @@ from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession +from app import telegram_send from app.api.deps import current_class, current_device from app.api.public import _homework_out from app.api.routing import DishkaAnnotatedRoute @@ -114,9 +116,7 @@ def _build_bot() -> Any | None: """ if not get_settings().bot_token: return None - from app.telegram_send import build_bot - - return build_bot() + return telegram_send.build_bot() async def _tell( @@ -140,14 +140,15 @@ async def _tell( if bot is None: return try: - await notify.notify_subscribers(session, bot, school_class, text, kind=kind, exclude=author) + async with asyncio.timeout(telegram_send.POST_COMMIT_NOTICE_SECONDS): + await notify.notify_subscribers( + session, bot, school_class, text, kind=kind, exclude=author + ) except Exception as error: # noqa: BLE001 - see the docstring log.warning("could not notify class %s: %s", class_id, type(error).__name__) finally: try: - bot_session = getattr(bot, "session", None) - if bot_session is not None: - await bot_session.close() + await telegram_send.close_bot(bot, timeout=telegram_send.POST_COMMIT_CLOSE_SECONDS) except Exception as error: # noqa: BLE001 - closing cannot undo delivery or the write log.warning( "could not close notice bot for class %s: %s", class_id, type(error).__name__ diff --git a/server/app/api/manage/requests.py b/server/app/api/manage/requests.py index 56b33019..95a61879 100644 --- a/server/app/api/manage/requests.py +++ b/server/app/api/manage/requests.py @@ -9,6 +9,7 @@ from __future__ import annotations +import asyncio import logging from typing import Any @@ -16,7 +17,7 @@ from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession -from app import wording +from app import telegram_send, wording from app.api.deps import current_class from app.api.manage._common import Actor, admin_actor from app.api.routing import DishkaAnnotatedRoute @@ -43,9 +44,7 @@ def _build_bot() -> Any | None: """ if not get_settings().bot_token: return None - from app.telegram_send import build_bot - - return build_bot() + return telegram_send.build_bot() async def _tell(telegram_id: int, text: str) -> None: @@ -61,14 +60,13 @@ async def _tell(telegram_id: int, text: str) -> None: if bot is None: return try: - await bot.send_message(telegram_id, text) + async with asyncio.timeout(telegram_send.POST_COMMIT_NOTICE_SECONDS): + await bot.send_message(telegram_id, text) except Exception as error: # noqa: BLE001 - see the docstring log.warning("could not tell %s about the decision: %s", telegram_id, type(error).__name__) finally: try: - bot_session = getattr(bot, "session", None) - if bot_session is not None: - await bot_session.close() + await telegram_send.close_bot(bot, timeout=telegram_send.POST_COMMIT_CLOSE_SECONDS) except Exception as error: # noqa: BLE001 - closing cannot undo the decision log.warning( "could not close decision notice bot for %s: %s", telegram_id, type(error).__name__ diff --git a/server/app/db.py b/server/app/db.py index 6f803ee4..5590b07b 100644 --- a/server/app/db.py +++ b/server/app/db.py @@ -78,6 +78,17 @@ def _sqlite_enforce_foreign_keys(dbapi_connection, connection_record) -> None: dbapi_connection.create_function("lower", 1, _unicode_lower) dbapi_connection.create_function("upper", 1, _unicode_upper) + @event.listens_for(engine.sync_engine, "reset") + def _sqlite_rollback_failed_commit(dbapi_connection, _connection_record, reset_state) -> None: + """A refused COMMIT can leave a write open despite SQLAlchemy's reset (#378).""" + if ( + reset_state.asyncio_safe + and not reset_state.terminate_only + and reset_state.transaction_was_reset + and dbapi_connection.driver_connection.in_transaction + ): + dbapi_connection.rollback() + @event.listens_for(engine.sync_engine, "savepoint") def _sqlite_savepoint_inside_a_transaction(conn, name) -> None: """Begin the transaction a savepoint assumes, when nothing has yet (#373). diff --git a/server/app/providers/netschool/client.py b/server/app/providers/netschool/client.py index ec56217f..3f8cecad 100644 --- a/server/app/providers/netschool/client.py +++ b/server/app/providers/netschool/client.py @@ -599,8 +599,8 @@ async def schools_search(self, query: str) -> list[dict[str, Any]]: A row is kept only with an ``id`` that is a JSON integer and a name that is non-blank text. ``isinstance(True, int)`` is true in Python, so a row whose id was ``true`` used to be kept as the school with id 1. - ``address`` is the server's ``addressString`` where it gave one: it is - what tells apart the many «Школа № 5» of one region. The phone's own + The upstream sends nullable ``address``. Use non-blank text there + before checking the legacy ``addressString`` key. The phone's own search reads the same rows by the same rule (``tests/vectors/diary_protocol.json``). """ @@ -618,13 +618,13 @@ async def schools_search(self, query: str) -> list[dict[str, Any]]: name = row.get("name") if school_id is None or not isinstance(name, str) or not name.strip(): continue - address = row.get("addressString") + address = row.get("address") if not isinstance(address, str) or not address.strip(): - address = None + address = row.get("addressString") out.append({ "id": school_id, "name": name.strip(), - "address": address.strip() if address else None, + "address": (address.strip() or None) if isinstance(address, str) else None, }) return out diff --git a/server/app/rpc/call.py b/server/app/rpc/call.py index b88f7a7b..505b50e4 100644 --- a/server/app/rpc/call.py +++ b/server/app/rpc/call.py @@ -61,6 +61,7 @@ from __future__ import annotations +import asyncio import logging import re from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence @@ -74,7 +75,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm.exc import StaleDataError -from app import di, wording +from app import di, telegram_send, wording from app.api.deps import caller_bucket from app.config import Settings from app.contract.lessons.v2.errors_pb import ErrorReason @@ -271,11 +272,19 @@ async def stream( async def _run_effects(call: Call) -> None: - for effect in call.effects: - try: - await effect() - except Exception: - log.warning("an effect of %s failed after its commit", call.method.key, exc_info=True) + if not call.effects: + return + try: + async with asyncio.timeout(telegram_send.POST_COMMIT_NOTICE_SECONDS): + for effect in call.effects: + try: + await effect() + except Exception: + log.warning( + "an effect of %s failed after its commit", call.method.key, exc_info=True + ) + except TimeoutError: + log.warning("the post-commit notice budget for %s expired", call.method.key) async def invoke( diff --git a/server/app/services/health.py b/server/app/services/health.py index 9f239abf..1b88357e 100644 --- a/server/app/services/health.py +++ b/server/app/services/health.py @@ -124,6 +124,10 @@ "Регион мог закрыть доступ с адреса прокси — переведите его на прямой маршрут " "(via_proxy в regions.py)." ) +HINT_PROXY_REFUSAL = ( + "Прокси отказал в установлении туннеля. Проверьте правила доступа (ACL) " + "и авторизацию на прокси." +) HINT_DIRECT = ( "Регион мог закрыть доступ с адреса сервера — проверьте его через прокси и, " "если отвечает, включите via_proxy в regions.py." @@ -175,9 +179,8 @@ class Result: #: and ``round_trip_ms`` are. timed_out: bool = False #: What the owner can do, for a check whose remedy depends on how it - #: failed: a region's check sets it from the route its probe took, never - #: from the reason's wording, which is free to change. Never written to - #: ``health_checks``. + #: failed: a region's check sets it from the route and the kind of + #: failure. Never written to ``health_checks``. hint: str = "" @@ -433,6 +436,8 @@ async def check_diary_region( FAILING, f"no answer {way}: {type(failure).__name__}", timed_out=True, hint=hint ) except httpx.HTTPError as failure: + if proxy is not None and isinstance(failure, httpx.ProxyError): + return Result(FAILING, "proxy refused the tunnel: ProxyError", hint=HINT_PROXY_REFUSAL) return Result(FAILING, f"no answer {way}: {type(failure).__name__}", hint=hint) round_trip = round((loop.time() - started) * 1000) if looks_refused(response): diff --git a/server/app/services/reminders.py b/server/app/services/reminders.py index b1780c1e..0db950ef 100644 --- a/server/app/services/reminders.py +++ b/server/app/services/reminders.py @@ -18,6 +18,7 @@ from __future__ import annotations +import asyncio import logging import re from datetime import UTC, datetime, timedelta @@ -406,14 +407,28 @@ async def _digest_text( return render_evening(next_day, today, done_subjects) -async def send_due(session: AsyncSession, bot: Any, now_utc: datetime) -> dict[str, int]: - """One tick: send everything due and account for it. Safe to repeat.""" +def _has_send_time(deadline: float | None) -> bool: + return deadline is None or asyncio.get_running_loop().time() < deadline + + +async def send_due( + session: AsyncSession, bot: Any, now_utc: datetime, *, deadline: float | None = None +) -> dict[str, int]: + """Send due reminders within the tick's monotonic send window. + + Each delivery uses the same deadline. Later rows remain due if it expires. + A row already claimed for delivery retains its mark even if its send times out. + """ from aiogram.exceptions import TelegramForbiddenError counts = {"morning": 0, "evening": 0, "tasks": 0, "failed": 0} cache: dict[tuple[Any, ...], Any] = {} + if not _has_send_time(deadline): + return counts for settings, school_class, kind in await due_digests(session, now_utc): + if not _has_send_time(deadline): + return counts today = local_now(now_utc, school_class).date() # Claimed before the send, and the claim is what decides whether this # tick may send at all: a crash between here and the send loses one @@ -442,7 +457,8 @@ async def send_due(session: AsyncSession, bot: Any, now_utc: datetime) -> dict[s if text is None: continue try: - await bot.send_message(settings.telegram_id, text) + async with asyncio.timeout_at(deadline): + await bot.send_message(settings.telegram_id, text) except TelegramForbiddenError: # They blocked the bot. Nothing will ever reach them again, so # stop trying rather than fail on every tick for the rest of time. @@ -456,7 +472,11 @@ async def send_due(session: AsyncSession, bot: Any, now_utc: datetime) -> dict[s else: counts[kind] += 1 + if not _has_send_time(deadline): + return counts for task, school_class in await due_task_reminders(session, now_utc): + if not _has_send_time(deadline): + return counts today = local_now(now_utc, school_class).date() # Claimed the same way a digest is, and for the same reason: marking # before sending answers the tick that dies, only the database answers @@ -464,7 +484,8 @@ async def send_due(session: AsyncSession, bot: Any, now_utc: datetime) -> dict[s if not await claim_task(session, task): continue try: - await bot.send_message(task.telegram_id, render_task_reminder(task, today)) + async with asyncio.timeout_at(deadline): + await bot.send_message(task.telegram_id, render_task_reminder(task, today)) except Exception: # noqa: BLE001 - same reasoning as above log.warning("could not send task reminder to %s", task.telegram_id, exc_info=True) counts["failed"] += 1 diff --git a/server/app/telegram_send.py b/server/app/telegram_send.py index 7bb69a9b..d89e21fb 100644 --- a/server/app/telegram_send.py +++ b/server/app/telegram_send.py @@ -21,6 +21,7 @@ from __future__ import annotations +import asyncio import logging from collections.abc import Sequence from typing import TYPE_CHECKING, Any @@ -37,6 +38,11 @@ log = logging.getLogger(__name__) +# A single window for the whole post-commit notification, including all recipients. +POST_COMMIT_NOTICE_SECONDS = 5.0 +# Closing can start while an expired notice unwinds, so it gets a separate grace period. +POST_COMMIT_CLOSE_SECONDS = 1.0 + def build_bot() -> Bot: """The bot every sender uses: this deployment's token, and HTML as its parse mode.""" @@ -50,7 +56,7 @@ def build_bot() -> Bot: ) -async def close_bot(bot: Any) -> None: +async def close_bot(bot: Any, *, timeout: float | None = None) -> None: """Close the HTTP session a bot built for one job opened. ``getattr`` because the tests hand the callers fakes, and a fake without a @@ -58,7 +64,8 @@ async def close_bot(bot: Any) -> None: """ bot_session = getattr(bot, "session", None) if bot_session is not None: - await bot_session.close() + async with asyncio.timeout(timeout): + await bot_session.close() async def send(messages: Sequence[tuple[int, str]]) -> list[bool]: @@ -93,7 +100,7 @@ async def send(messages: Sequence[tuple[int, str]]) -> list[bool]: delivered.append(True) finally: try: - await close_bot(bot) + await close_bot(bot, timeout=POST_COMMIT_CLOSE_SECONDS) except Exception as error: # noqa: BLE001 - see the docstring # A close that raises after delivery must not lose `delivered`: # the caller (`health._tell`) would read the exception as nobody @@ -146,6 +153,6 @@ async def notify_class( return 0 finally: try: - await close_bot(bot) + await close_bot(bot, timeout=POST_COMMIT_CLOSE_SECONDS) except Exception as error: # noqa: BLE001 - see the docstring log.warning("could not close the bot: %s", type(error).__name__) diff --git a/server/openapi-v1.json b/server/openapi-v1.json new file mode 100644 index 00000000..5a0fdeba --- /dev/null +++ b/server/openapi-v1.json @@ -0,0 +1,7674 @@ +{ + "components": { + "schemas": { + "AccessRequestOut": { + "properties": { + "created_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Created At" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "message": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Message" + }, + "requested_role": { + "enum": [ + "viewer", + "editor", + "admin", + "owner" + ], + "title": "Requested Role", + "type": "string" + }, + "who": { + "title": "Who", + "type": "string" + } + }, + "required": [ + "id", + "who", + "requested_role" + ], + "title": "AccessRequestOut", + "type": "object" + }, + "AuditEntryOut": { + "properties": { + "action": { + "title": "Action", + "type": "string" + }, + "at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "At" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "summary": { + "title": "Summary", + "type": "string" + }, + "who": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Who" + } + }, + "required": [ + "id", + "action", + "summary" + ], + "title": "AuditEntryOut", + "type": "object" + }, + "AuditPageOut": { + "description": "``has_more`` rather than a total: the log is append-only and unbounded,\nand a count of it would be a full scan on every page turn.", + "properties": { + "entries": { + "default": [], + "items": { + "$ref": "#/components/schemas/AuditEntryOut" + }, + "title": "Entries", + "type": "array" + }, + "has_more": { + "default": false, + "title": "Has More", + "type": "boolean" + }, + "limit": { + "title": "Limit", + "type": "integer" + }, + "offset": { + "title": "Offset", + "type": "integer" + } + }, + "required": [ + "limit", + "offset" + ], + "title": "AuditPageOut", + "type": "object" + }, + "BellPeriodIn": { + "properties": { + "ends_at": { + "format": "time", + "title": "Ends At", + "type": "string" + }, + "index": { + "maximum": 20.0, + "minimum": 1.0, + "title": "Index", + "type": "integer" + }, + "starts_at": { + "format": "time", + "title": "Starts At", + "type": "string" + } + }, + "required": [ + "index", + "starts_at", + "ends_at" + ], + "title": "BellPeriodIn", + "type": "object" + }, + "BellPeriodOut": { + "properties": { + "ends_at": { + "format": "time", + "title": "Ends At", + "type": "string" + }, + "index": { + "title": "Index", + "type": "integer" + }, + "starts_at": { + "format": "time", + "title": "Starts At", + "type": "string" + } + }, + "required": [ + "index", + "starts_at", + "ends_at" + ], + "title": "BellPeriodOut", + "type": "object" + }, + "BellPeriodsIn": { + "description": "At least one row, always.\n\nThe stored schedule is the thing a class runs on, and an empty list is far\nmore likely to be a client bug than somebody meaning \"no bells at all\" -\nwhich is what the bot's «пустой присылкой звонки не стереть» says too.", + "properties": { + "periods": { + "items": { + "$ref": "#/components/schemas/BellPeriodIn" + }, + "maxItems": 20, + "minItems": 1, + "title": "Periods", + "type": "array" + } + }, + "required": [ + "periods" + ], + "title": "BellPeriodsIn", + "type": "object" + }, + "BellScheduleIn": { + "properties": { + "name": { + "maxLength": 64, + "minLength": 1, + "title": "Name", + "type": "string" + }, + "periods": { + "default": [], + "items": { + "$ref": "#/components/schemas/BellPeriodIn" + }, + "maxItems": 20, + "title": "Periods", + "type": "array" + } + }, + "required": [ + "name" + ], + "title": "BellScheduleIn", + "type": "object" + }, + "BellScheduleOut": { + "properties": { + "id": { + "title": "Id", + "type": "integer" + }, + "is_default": { + "default": false, + "title": "Is Default", + "type": "boolean" + }, + "name": { + "title": "Name", + "type": "string" + }, + "periods": { + "default": [], + "items": { + "$ref": "#/components/schemas/BellPeriodOut" + }, + "title": "Periods", + "type": "array" + }, + "silenced_lessons": { + "default": 0, + "title": "Silenced Lessons", + "type": "integer" + } + }, + "required": [ + "id", + "name" + ], + "title": "BellScheduleOut", + "type": "object" + }, + "BellSchedulePatch": { + "properties": { + "is_default": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Is Default" + }, + "name": { + "anyOf": [ + { + "maxLength": 64, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name" + } + }, + "title": "BellSchedulePatch", + "type": "object" + }, + "BundleOut": { + "description": "One response holds everything the widget needs to run offline for two weeks.", + "properties": { + "api_version": { + "default": 1, + "title": "Api Version", + "type": "integer" + }, + "days": { + "items": { + "$ref": "#/components/schemas/DayOut" + }, + "title": "Days", + "type": "array" + }, + "device": { + "anyOf": [ + { + "$ref": "#/components/schemas/DeviceOut" + }, + { + "type": "null" + } + ] + }, + "generated_at": { + "title": "Generated At", + "type": "string" + }, + "next_school_day": { + "anyOf": [ + { + "$ref": "#/components/schemas/DayOut" + }, + { + "type": "null" + } + ] + }, + "school_class": { + "$ref": "#/components/schemas/ClassOut" + } + }, + "required": [ + "school_class", + "generated_at", + "days" + ], + "title": "BundleOut", + "type": "object" + }, + "CalendarOut": { + "properties": { + "url": { + "title": "Url", + "type": "string" + } + }, + "required": [ + "url" + ], + "title": "CalendarOut", + "type": "object" + }, + "ClassDeleteIn": { + "description": "The class's own name, typed back.\n\nThe same confirmation the bot asks for, and for the same reason: a «вы\nуверены?» button is pressed by the same thumb that pressed the one before\nit, while a name has to be read off the screen first.", + "properties": { + "confirm_name": { + "maxLength": 64, + "minLength": 1, + "title": "Confirm Name", + "type": "string" + } + }, + "required": [ + "confirm_name" + ], + "title": "ClassDeleteIn", + "type": "object" + }, + "ClassOut": { + "properties": { + "city": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "City" + }, + "grade": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Grade" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "letter": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Letter" + }, + "name": { + "title": "Name", + "type": "string" + }, + "school": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "School" + }, + "term_kind": { + "anyOf": [ + { + "enum": [ + "quarter", + "semester" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Term Kind" + }, + "terms": { + "items": { + "$ref": "#/components/schemas/TermOut" + }, + "title": "Terms", + "type": "array" + }, + "timezone": { + "title": "Timezone", + "type": "string" + } + }, + "required": [ + "id", + "name", + "timezone" + ], + "title": "ClassOut", + "type": "object" + }, + "ClassPatch": { + "description": "Only the fields present are changed; ``null`` clears a nullable one.\n\n``name`` and ``timezone`` are not nullable: the name is what every message\ncalls this class and what the delete confirmation is typed against, and a\nclass with no zone would have no \"today\".", + "properties": { + "city": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "City" + }, + "grade": { + "anyOf": [ + { + "maximum": 11.0, + "minimum": 1.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Grade" + }, + "join_mode": { + "anyOf": [ + { + "enum": [ + "open", + "invite" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Join Mode" + }, + "letter": { + "anyOf": [ + { + "maxLength": 8, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Letter" + }, + "name": { + "anyOf": [ + { + "maxLength": 64, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name" + }, + "school": { + "anyOf": [ + { + "maxLength": 200, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "School" + }, + "timezone": { + "anyOf": [ + { + "maxLength": 64, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Timezone" + } + }, + "title": "ClassPatch", + "type": "object" + }, + "DayIn": { + "properties": { + "bell_schedule_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Bell Schedule Id" + }, + "date": { + "format": "date", + "title": "Date", + "type": "string" + }, + "kind": { + "enum": [ + "normal", + "holiday", + "shortened", + "remote" + ], + "title": "Kind", + "type": "string" + }, + "note": { + "anyOf": [ + { + "maxLength": 500, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Note" + } + }, + "required": [ + "date", + "kind" + ], + "title": "DayIn", + "type": "object" + }, + "DayOut": { + "properties": { + "date": { + "format": "date", + "title": "Date", + "type": "string" + }, + "events": { + "default": [], + "items": { + "$ref": "#/components/schemas/EventOut" + }, + "title": "Events", + "type": "array" + }, + "holiday": { + "anyOf": [ + { + "$ref": "#/components/schemas/HolidayOut" + }, + { + "type": "null" + } + ] + }, + "homework": { + "default": [], + "items": { + "$ref": "#/components/schemas/HomeworkOut" + }, + "title": "Homework", + "type": "array" + }, + "kind": { + "title": "Kind", + "type": "string" + }, + "lessons": { + "default": [], + "items": { + "$ref": "#/components/schemas/LessonOut" + }, + "title": "Lessons", + "type": "array" + }, + "note": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Note" + }, + "off_reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Off Reason" + }, + "weekday": { + "title": "Weekday", + "type": "integer" + } + }, + "required": [ + "date", + "weekday", + "kind" + ], + "title": "DayOut", + "type": "object" + }, + "DayOverrideOut": { + "properties": { + "bell_schedule_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Bell Schedule Id" + }, + "date": { + "format": "date", + "title": "Date", + "type": "string" + }, + "kind": { + "enum": [ + "normal", + "holiday", + "shortened", + "remote" + ], + "title": "Kind", + "type": "string" + }, + "note": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Note" + } + }, + "required": [ + "date", + "kind" + ], + "title": "DayOverrideOut", + "type": "object" + }, + "DeletedOut": { + "properties": { + "deleted": { + "default": true, + "title": "Deleted", + "type": "boolean" + }, + "id": { + "title": "Id", + "type": "integer" + } + }, + "required": [ + "id" + ], + "title": "DeletedOut", + "type": "object" + }, + "DeviceOut": { + "description": "What this device may do. Never carries the Telegram id it is linked to:\nthe app shows a name and a role, and the id is nobody's business.", + "properties": { + "can_edit": { + "default": false, + "title": "Can Edit", + "type": "boolean" + }, + "linked": { + "default": false, + "title": "Linked", + "type": "boolean" + }, + "role": { + "anyOf": [ + { + "enum": [ + "viewer", + "editor", + "admin", + "owner" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Role" + } + }, + "title": "DeviceOut", + "type": "object" + }, + "DiaryAttendanceOut": { + "properties": { + "at": { + "format": "date-time", + "title": "At", + "type": "string" + }, + "direction": { + "title": "Direction", + "type": "string" + } + }, + "required": [ + "at", + "direction" + ], + "title": "DiaryAttendanceOut", + "type": "object" + }, + "DiaryBindingOut": { + "description": "Which diary a class reads, so a phone that joined it can sign in there\nwithout searching for its school.\n\nDefined here rather than in the diary block below because\n:class:`JoinResponse` carries it. Built only through ``of`` from\n`registry.binding`, so a class bound to a region since dropped from the\nallow-list, one that takes no password, or a «Сетевой город» binding with\nno school all read as no binding at all — the phone is never pointed at a\ndiary this server would refuse.", + "properties": { + "provider": { + "enum": [ + "petersburg", + "netschool" + ], + "title": "Provider", + "type": "string" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Region" + }, + "school_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "School Id" + }, + "school_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "School Name" + } + }, + "required": [ + "provider" + ], + "title": "DiaryBindingOut", + "type": "object" + }, + "DiaryCapabilitiesOut": { + "description": "What this server's diary can do, asked before the phone takes a password.\n\n``enabled`` is false without ``DIARY_SECRET``; ``registration`` says the\nserver takes a session the phone opened (a server from before this answers\n404 here instead).", + "properties": { + "enabled": { + "title": "Enabled", + "type": "boolean" + }, + "providers": { + "$ref": "#/components/schemas/DiaryProvidersOut" + }, + "registration": { + "default": true, + "title": "Registration", + "type": "boolean" + } + }, + "required": [ + "enabled" + ], + "title": "DiaryCapabilitiesOut", + "type": "object" + }, + "DiaryEditOut": { + "description": "One field a family has corrected, as the client needs to draw it.\n\n``original`` is what the diary says **now**, not what it said when the\ncorrection was written — the client shows it as «в дневнике: …», and the\nquestion it answers is what is currently being covered up.", + "properties": { + "changed_upstream": { + "default": false, + "title": "Changed Upstream", + "type": "boolean" + }, + "field": { + "title": "Field", + "type": "string" + }, + "original": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Original" + }, + "value": { + "title": "Value", + "type": "string" + } + }, + "required": [ + "field", + "value" + ], + "title": "DiaryEditOut", + "type": "object" + }, + "DiaryHomeworkOut": { + "properties": { + "ambiguous": { + "default": false, + "title": "Ambiguous", + "type": "boolean" + }, + "due_date": { + "format": "date", + "title": "Due Date", + "type": "string" + }, + "edits": { + "items": { + "$ref": "#/components/schemas/DiaryEditOut" + }, + "title": "Edits", + "type": "array" + }, + "id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Id" + }, + "subject": { + "title": "Subject", + "type": "string" + }, + "target": { + "default": "", + "title": "Target", + "type": "string" + }, + "teacher": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + }, + "text": { + "title": "Text", + "type": "string" + } + }, + "required": [ + "due_date", + "subject", + "text" + ], + "title": "DiaryHomeworkOut", + "type": "object" + }, + "DiaryLessonOut": { + "properties": { + "ambiguous": { + "default": false, + "title": "Ambiguous", + "type": "boolean" + }, + "date": { + "format": "date", + "title": "Date", + "type": "string" + }, + "edits": { + "items": { + "$ref": "#/components/schemas/DiaryEditOut" + }, + "title": "Edits", + "type": "array" + }, + "ends_at": { + "anyOf": [ + { + "format": "time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Ends At" + }, + "homework": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Homework" + }, + "number": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Number" + }, + "room": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Room" + }, + "starts_at": { + "anyOf": [ + { + "format": "time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Starts At" + }, + "subject": { + "title": "Subject", + "type": "string" + }, + "target": { + "default": "", + "title": "Target", + "type": "string" + }, + "teacher": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + }, + "topic": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Topic" + } + }, + "required": [ + "date", + "subject" + ], + "title": "DiaryLessonOut", + "type": "object" + }, + "DiaryLoginIn": { + "description": "Credentials, used once and never stored.\n\n``login`` rather than ``email`` because the upstream accepts more than one\nkind of identifier and calling it an email would be a promise this project\ncannot keep.", + "properties": { + "login": { + "maxLength": 200, + "minLength": 3, + "title": "Login", + "type": "string" + }, + "password": { + "maxLength": 200, + "minLength": 1, + "title": "Password", + "type": "string" + }, + "provider": { + "anyOf": [ + { + "maxLength": 32, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Provider" + }, + "region": { + "anyOf": [ + { + "maxLength": 32, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Region" + }, + "school_id": { + "anyOf": [ + { + "maximum": 2000000000.0, + "minimum": 1.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "School Id" + } + }, + "required": [ + "login", + "password" + ], + "title": "DiaryLoginIn", + "type": "object" + }, + "DiaryLoginOut": { + "properties": { + "login": { + "title": "Login", + "type": "string" + }, + "token": { + "title": "Token", + "type": "string" + } + }, + "required": [ + "token", + "login" + ], + "title": "DiaryLoginOut", + "type": "object" + }, + "DiaryMarkOut": { + "description": "One register entry.\n\n``value`` is what belongs in the cell and ``kind`` says what it means, so a\nclient can colour an absence differently without knowing that upstream it\nwas type code 30000.", + "properties": { + "comment": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Comment" + }, + "date": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Date" + }, + "id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Id" + }, + "kind": { + "title": "Kind", + "type": "string" + }, + "reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Reason" + }, + "subject": { + "title": "Subject", + "type": "string" + }, + "subject_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Subject Id" + }, + "value": { + "title": "Value", + "type": "string" + } + }, + "required": [ + "subject", + "value", + "kind" + ], + "title": "DiaryMarkOut", + "type": "object" + }, + "DiaryOverrideIn": { + "description": "A correction being written. The target came from a read; it is echoed.", + "properties": { + "field": { + "maxLength": 40, + "minLength": 1, + "title": "Field", + "type": "string" + }, + "original": { + "anyOf": [ + { + "maxLength": 4000, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Original" + }, + "target": { + "maxLength": 300, + "minLength": 1, + "title": "Target", + "type": "string" + }, + "value": { + "maxLength": 4000, + "title": "Value", + "type": "string" + } + }, + "required": [ + "target", + "field", + "value" + ], + "title": "DiaryOverrideIn", + "type": "object" + }, + "DiaryOverrideOut": { + "description": "A stored correction, for the screen that lists and resets them.", + "properties": { + "field": { + "title": "Field", + "type": "string" + }, + "original_when_written": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Original When Written" + }, + "target": { + "title": "Target", + "type": "string" + }, + "updated_at": { + "format": "date-time", + "title": "Updated At", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + }, + "required": [ + "target", + "field", + "value", + "updated_at" + ], + "title": "DiaryOverrideOut", + "type": "object" + }, + "DiaryPeriodOut": { + "properties": { + "ends_on": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Ends On" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "is_current": { + "default": false, + "title": "Is Current", + "type": "boolean" + }, + "name": { + "title": "Name", + "type": "string" + }, + "starts_on": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Starts On" + } + }, + "required": [ + "id", + "name" + ], + "title": "DiaryPeriodOut", + "type": "object" + }, + "DiaryProvidersOut": { + "properties": { + "netschool": { + "$ref": "#/components/schemas/NetSchoolCapabilitiesOut" + }, + "petersburg": { + "$ref": "#/components/schemas/PetersburgCapabilitiesOut" + } + }, + "title": "DiaryProvidersOut", + "type": "object" + }, + "DiaryResetIn": { + "description": "Which correction to take off.\n\nA body rather than a query string, and a POST rather than a DELETE, because\na target is free text: a subject named «Физика & астрономия» produces a key\nwith an ampersand in it, and a caller that encodes it a shade imperfectly\nresets nothing while being told 204. The value that has to match byte for\nbyte does not travel in a URL.", + "properties": { + "field": { + "maxLength": 40, + "minLength": 1, + "title": "Field", + "type": "string" + }, + "target": { + "maxLength": 300, + "minLength": 1, + "title": "Target", + "type": "string" + } + }, + "required": [ + "target", + "field" + ], + "title": "DiaryResetIn", + "type": "object" + }, + "DiarySessionOut": { + "description": "Our bearer for a session the phone opened, and what the phone needs to\nkeep reading it. Never the upstream credential: that stays here, sealed.\n\n``token`` and ``login`` sit where ``DiaryLoginOut`` has them, so an app\ndecodes both answers the same way.", + "properties": { + "login": { + "title": "Login", + "type": "string" + }, + "provider": { + "enum": [ + "petersburg", + "netschool" + ], + "title": "Provider", + "type": "string" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Region" + }, + "school_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "School Id" + }, + "school_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "School Name" + }, + "students": { + "items": { + "$ref": "#/components/schemas/DiaryStudentOut" + }, + "title": "Students", + "type": "array" + }, + "token": { + "title": "Token", + "type": "string" + }, + "zone": { + "title": "Zone", + "type": "string" + } + }, + "required": [ + "token", + "login", + "provider", + "zone" + ], + "title": "DiarySessionOut", + "type": "object" + }, + "DiaryStudentOut": { + "properties": { + "class_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Class Name" + }, + "first_name": { + "title": "First Name", + "type": "string" + }, + "full_name": { + "title": "Full Name", + "type": "string" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "last_name": { + "title": "Last Name", + "type": "string" + }, + "middle_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Middle Name" + }, + "school": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "School" + } + }, + "required": [ + "id", + "first_name", + "last_name", + "full_name" + ], + "title": "DiaryStudentOut", + "type": "object" + }, + "DiarySubjectOut": { + "properties": { + "id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Id" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "DiarySubjectOut", + "type": "object" + }, + "DiaryTeacherOut": { + "properties": { + "id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Id" + }, + "name": { + "title": "Name", + "type": "string" + }, + "position": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Position" + }, + "subjects": { + "default": [], + "items": { + "type": "string" + }, + "title": "Subjects", + "type": "array" + } + }, + "required": [ + "name" + ], + "title": "DiaryTeacherOut", + "type": "object" + }, + "DoneIn": { + "properties": { + "done": { + "title": "Done", + "type": "boolean" + } + }, + "required": [ + "done" + ], + "title": "DoneIn", + "type": "object" + }, + "DoneOut": { + "properties": { + "done": { + "title": "Done", + "type": "boolean" + }, + "id": { + "title": "Id", + "type": "integer" + } + }, + "required": [ + "id", + "done" + ], + "title": "DoneOut", + "type": "object" + }, + "EventCreatedOut": { + "properties": { + "id": { + "title": "Id", + "type": "integer" + } + }, + "required": [ + "id" + ], + "title": "EventCreatedOut", + "type": "object" + }, + "EventIn": { + "properties": { + "covers_lesson": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Covers Lesson" + }, + "date": { + "format": "date", + "title": "Date", + "type": "string" + }, + "ends_at": { + "format": "time", + "title": "Ends At", + "type": "string" + }, + "kind": { + "default": "event", + "enum": [ + "event", + "canteen", + "exam", + "trip", + "meeting" + ], + "title": "Kind", + "type": "string" + }, + "location": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Location" + }, + "starts_at": { + "format": "time", + "title": "Starts At", + "type": "string" + }, + "title": { + "maxLength": 200, + "minLength": 1, + "title": "Title", + "type": "string" + } + }, + "required": [ + "date", + "starts_at", + "ends_at", + "title" + ], + "title": "EventIn", + "type": "object" + }, + "EventOut": { + "properties": { + "covers_lesson": { + "default": false, + "title": "Covers Lesson", + "type": "boolean" + }, + "ends_at": { + "format": "time", + "title": "Ends At", + "type": "string" + }, + "kind": { + "title": "Kind", + "type": "string" + }, + "location": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Location" + }, + "starts_at": { + "format": "time", + "title": "Starts At", + "type": "string" + }, + "title": { + "title": "Title", + "type": "string" + } + }, + "required": [ + "title", + "kind", + "starts_at", + "ends_at" + ], + "title": "EventOut", + "type": "object" + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "title": "Detail", + "type": "array" + } + }, + "title": "HTTPValidationError", + "type": "object" + }, + "HolidayOut": { + "description": "A named date, whether or not it stops the lessons.\n\n``code`` is stable and ``title`` is Russian, the way every other string the\nserver puts on a screen is. A client that wants the name in its own\nlanguage matches the code and falls back to the title, so a date this\nserver learns before that client does still has something to draw.", + "properties": { + "code": { + "title": "Code", + "type": "string" + }, + "stops_lessons": { + "title": "Stops Lessons", + "type": "boolean" + }, + "title": { + "title": "Title", + "type": "string" + } + }, + "required": [ + "code", + "title", + "stops_lessons" + ], + "title": "HolidayOut", + "type": "object" + }, + "HomeworkIn": { + "properties": { + "attachment_url": { + "anyOf": [ + { + "maxLength": 500, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Attachment Url" + }, + "due_date": { + "format": "date", + "title": "Due Date", + "type": "string" + }, + "subject": { + "maxLength": 120, + "minLength": 1, + "title": "Subject", + "type": "string" + }, + "text": { + "maxLength": 4000, + "minLength": 1, + "title": "Text", + "type": "string" + } + }, + "required": [ + "due_date", + "subject", + "text" + ], + "title": "HomeworkIn", + "type": "object" + }, + "HomeworkItemOut": { + "description": "A homework row on its own, outside a day: the list and the ticks need\nthe id and the date that the bundle's per-day shape carries implicitly.", + "properties": { + "attachment_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Attachment Url" + }, + "done": { + "default": false, + "title": "Done", + "type": "boolean" + }, + "due_date": { + "format": "date", + "title": "Due Date", + "type": "string" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "subject": { + "title": "Subject", + "type": "string" + }, + "text": { + "title": "Text", + "type": "string" + } + }, + "required": [ + "subject", + "text", + "id", + "due_date" + ], + "title": "HomeworkItemOut", + "type": "object" + }, + "HomeworkOut": { + "properties": { + "attachment_url": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Attachment Url" + }, + "subject": { + "title": "Subject", + "type": "string" + }, + "text": { + "title": "Text", + "type": "string" + } + }, + "required": [ + "subject", + "text" + ], + "title": "HomeworkOut", + "type": "object" + }, + "ImportConflictOut": { + "description": "One weekday the paste would overwrite: what is there now, what would\nreplace it. Weekday is 1=Monday .. 7=Sunday, as everywhere else.", + "properties": { + "existing": { + "title": "Existing", + "type": "integer" + }, + "incoming": { + "title": "Incoming", + "type": "integer" + }, + "weekday": { + "title": "Weekday", + "type": "integer" + } + }, + "required": [ + "weekday", + "existing", + "incoming" + ], + "title": "ImportConflictOut", + "type": "object" + }, + "JoinRequest": { + "properties": { + "code": { + "maxLength": 16, + "minLength": 4, + "title": "Code", + "type": "string" + }, + "device_name": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Device Name" + } + }, + "required": [ + "code" + ], + "title": "JoinRequest", + "type": "object" + }, + "JoinResponse": { + "properties": { + "class_id": { + "title": "Class Id", + "type": "integer" + }, + "class_name": { + "title": "Class Name", + "type": "string" + }, + "diary": { + "anyOf": [ + { + "$ref": "#/components/schemas/DiaryBindingOut" + }, + { + "type": "null" + } + ] + }, + "school": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "School" + }, + "timezone": { + "title": "Timezone", + "type": "string" + }, + "token": { + "title": "Token", + "type": "string" + } + }, + "required": [ + "token", + "class_id", + "class_name", + "timezone" + ], + "title": "JoinResponse", + "type": "object" + }, + "LessonOut": { + "properties": { + "color": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Color" + }, + "ends_at": { + "format": "time", + "title": "Ends At", + "type": "string" + }, + "index": { + "title": "Index", + "type": "integer" + }, + "is_cancelled": { + "default": false, + "title": "Is Cancelled", + "type": "boolean" + }, + "is_replaced": { + "default": false, + "title": "Is Replaced", + "type": "boolean" + }, + "note": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Note" + }, + "room": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Room" + }, + "starts_at": { + "format": "time", + "title": "Starts At", + "type": "string" + }, + "subject": { + "title": "Subject", + "type": "string" + }, + "teacher": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + } + }, + "required": [ + "index", + "subject", + "starts_at", + "ends_at" + ], + "title": "LessonOut", + "type": "object" + }, + "ManagedClassOut": { + "description": "The class card the bot draws under «⚙️ Класс», as data.\n\n``join_code`` is in here because the card shows it: this endpoint is\nadmin-only, and the code is what an admin reads out to the class.", + "properties": { + "bell_schedule_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Bell Schedule Id" + }, + "calendar_ready": { + "default": false, + "title": "Calendar Ready", + "type": "boolean" + }, + "city": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "City" + }, + "devices": { + "title": "Devices", + "type": "integer" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "join_code": { + "title": "Join Code", + "type": "string" + }, + "join_mode": { + "default": "open", + "title": "Join Mode", + "type": "string" + }, + "members": { + "title": "Members", + "type": "integer" + }, + "name": { + "title": "Name", + "type": "string" + }, + "pending_requests": { + "title": "Pending Requests", + "type": "integer" + }, + "school": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "School" + }, + "timezone": { + "title": "Timezone", + "type": "string" + }, + "timezone_label": { + "title": "Timezone Label", + "type": "string" + } + }, + "required": [ + "id", + "name", + "timezone", + "timezone_label", + "join_code", + "members", + "devices", + "pending_requests" + ], + "title": "ManagedClassOut", + "type": "object" + }, + "ManagedDeviceOut": { + "description": "One phone on the class's list.\n\n``owner`` is a display name, never the Telegram id: an admin needs to know\nwhose phone this is, and that is the whole of what they need.", + "properties": { + "created_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Created At" + }, + "device_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Device Name" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "last_seen_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Last Seen At" + }, + "linked": { + "default": false, + "title": "Linked", + "type": "boolean" + }, + "linked_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Linked At" + }, + "owner": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Owner" + }, + "revoked": { + "default": false, + "title": "Revoked", + "type": "boolean" + }, + "role": { + "anyOf": [ + { + "enum": [ + "viewer", + "editor", + "admin", + "owner" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Role" + } + }, + "required": [ + "id" + ], + "title": "ManagedDeviceOut", + "type": "object" + }, + "ManagedSubjectOut": { + "description": "A subject with its id. The read-only dictionary in ``GET /subjects`` is\nkeyed by name because that is what a lesson stores; management addresses a\nrow, which needs the id.", + "properties": { + "color": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Color" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "name": { + "title": "Name", + "type": "string" + }, + "short_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Short Name" + }, + "teacher": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + } + }, + "required": [ + "name", + "id" + ], + "title": "ManagedSubjectOut", + "type": "object" + }, + "MeOut": { + "properties": { + "bot_deep_link": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Bot Deep Link" + }, + "can_edit": { + "title": "Can Edit", + "type": "boolean" + }, + "device_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Device Name" + }, + "link_code": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Link Code" + }, + "linked": { + "title": "Linked", + "type": "boolean" + }, + "role": { + "anyOf": [ + { + "enum": [ + "viewer", + "editor", + "admin", + "owner" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Role" + } + }, + "required": [ + "linked", + "can_edit" + ], + "title": "MeOut", + "type": "object" + }, + "NetSchoolCapabilitiesOut": { + "properties": { + "regions": { + "items": { + "type": "string" + }, + "title": "Regions", + "type": "array" + } + }, + "title": "NetSchoolCapabilitiesOut", + "type": "object" + }, + "NetSchoolCookiesIn": { + "additionalProperties": false, + "description": "The two session cookies «Сетевой город» sets, and no other — an unknown\nname is refused rather than carried, since it would be sent on every read.", + "properties": { + "ESRNSec": { + "anyOf": [ + { + "maxLength": 2048, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Esrnsec" + }, + "NSSESSIONID": { + "maxLength": 128, + "minLength": 1, + "title": "Nssessionid", + "type": "string" + } + }, + "required": [ + "NSSESSIONID" + ], + "title": "NetSchoolCookiesIn", + "type": "object" + }, + "NetSchoolCredentialIn": { + "additionalProperties": false, + "description": "What the phone's «Сетевой город» sign-in ended holding.", + "properties": { + "at": { + "maxLength": 512, + "minLength": 8, + "title": "At", + "type": "string" + }, + "cookies": { + "$ref": "#/components/schemas/NetSchoolCookiesIn" + }, + "time_out": { + "anyOf": [ + { + "maximum": 2147483647.0, + "minimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Time Out" + }, + "ver": { + "anyOf": [ + { + "maxLength": 32, + "pattern": "^[A-Za-z0-9._-]+$", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Ver" + } + }, + "required": [ + "at", + "cookies" + ], + "title": "NetSchoolCredentialIn", + "type": "object" + }, + "NetSchoolSessionIn": { + "additionalProperties": false, + "properties": { + "credential": { + "$ref": "#/components/schemas/NetSchoolCredentialIn" + }, + "login": { + "maxLength": 200, + "minLength": 3, + "title": "Login", + "type": "string" + }, + "provider": { + "const": "netschool", + "title": "Provider", + "type": "string" + }, + "region": { + "pattern": "^[a-z0-9-]{2,32}$", + "title": "Region", + "type": "string" + }, + "school_id": { + "maximum": 2000000000.0, + "minimum": 1.0, + "title": "School Id", + "type": "integer" + } + }, + "required": [ + "login", + "provider", + "region", + "school_id", + "credential" + ], + "title": "NetSchoolSessionIn", + "type": "object" + }, + "NowOut": { + "description": "The server's answer to \"what is happening right now\", in the class's zone.\n\nThe widget normally computes this from the bundle itself; the endpoint is\nfor clients that would rather ask than carry the resolver, and it is what\nthe bundle's own maths is checked against.", + "properties": { + "current": { + "anyOf": [ + { + "$ref": "#/components/schemas/LessonOut" + }, + { + "type": "null" + } + ] + }, + "date": { + "format": "date", + "title": "Date", + "type": "string" + }, + "next": { + "anyOf": [ + { + "$ref": "#/components/schemas/LessonOut" + }, + { + "type": "null" + } + ] + }, + "next_school_day": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Next School Day" + }, + "state": { + "enum": [ + "before_school", + "lesson", + "break", + "after_school", + "day_off", + "no_data" + ], + "title": "State", + "type": "string" + }, + "time": { + "format": "time", + "title": "Time", + "type": "string" + }, + "until_next_seconds": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Until Next Seconds" + } + }, + "required": [ + "date", + "time", + "state" + ], + "title": "NowOut", + "type": "object" + }, + "OverrideIn": { + "properties": { + "action": { + "enum": [ + "replace", + "cancel", + "clear" + ], + "title": "Action", + "type": "string" + }, + "date": { + "format": "date", + "title": "Date", + "type": "string" + }, + "index": { + "maximum": 20.0, + "minimum": 1.0, + "title": "Index", + "type": "integer" + }, + "note": { + "anyOf": [ + { + "maxLength": 500, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Note" + }, + "room": { + "anyOf": [ + { + "maxLength": 32, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Room" + }, + "subject": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject" + }, + "teacher": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + } + }, + "required": [ + "date", + "index", + "action" + ], + "title": "OverrideIn", + "type": "object" + }, + "OverrideOut": { + "properties": { + "action": { + "enum": [ + "replace", + "cancel", + "clear" + ], + "title": "Action", + "type": "string" + }, + "date": { + "format": "date", + "title": "Date", + "type": "string" + }, + "index": { + "title": "Index", + "type": "integer" + }, + "note": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Note" + }, + "room": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Room" + }, + "subject": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject" + }, + "teacher": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + } + }, + "required": [ + "date", + "index", + "action" + ], + "title": "OverrideOut", + "type": "object" + }, + "PetersburgCapabilitiesOut": { + "description": "Nothing to say yet about Petersburg beyond that it is served.", + "properties": {}, + "title": "PetersburgCapabilitiesOut", + "type": "object" + }, + "PetersburgCredentialIn": { + "additionalProperties": false, + "description": "The session Petersburg handed the phone: the ``X-JWT-Token`` cookie, or\n``data.token`` when the answer carried no cookie.", + "properties": { + "token": { + "maxLength": 4096, + "minLength": 16, + "title": "Token", + "type": "string" + } + }, + "required": [ + "token" + ], + "title": "PetersburgCredentialIn", + "type": "object" + }, + "PetersburgSessionIn": { + "additionalProperties": false, + "properties": { + "credential": { + "$ref": "#/components/schemas/PetersburgCredentialIn" + }, + "login": { + "maxLength": 200, + "minLength": 3, + "title": "Login", + "type": "string" + }, + "provider": { + "const": "petersburg", + "title": "Provider", + "type": "string" + } + }, + "required": [ + "login", + "provider", + "credential" + ], + "title": "PetersburgSessionIn", + "type": "object" + }, + "RequestDecisionIn": { + "description": "The role to grant. Absent means the one that was asked for, which is\nwhat pressing «Выдать» in the bot does. Ignored when declining.", + "properties": { + "role": { + "anyOf": [ + { + "enum": [ + "viewer", + "editor", + "admin", + "owner" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Role" + } + }, + "title": "RequestDecisionIn", + "type": "object" + }, + "RequestDecisionOut": { + "properties": { + "id": { + "title": "Id", + "type": "integer" + }, + "role": { + "anyOf": [ + { + "enum": [ + "viewer", + "editor", + "admin", + "owner" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Role" + }, + "status": { + "enum": [ + "approved", + "declined" + ], + "title": "Status", + "type": "string" + }, + "who": { + "title": "Who", + "type": "string" + } + }, + "required": [ + "id", + "status", + "who" + ], + "title": "RequestDecisionOut", + "type": "object" + }, + "SchoolOut": { + "description": "One row of the school directory, as the picker shows it.", + "properties": { + "active": { + "default": true, + "title": "Active", + "type": "boolean" + }, + "address": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Address" + }, + "city": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "City" + }, + "full_name": { + "title": "Full Name", + "type": "string" + }, + "inn": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Inn" + }, + "name": { + "title": "Name", + "type": "string" + }, + "ogrn": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Ogrn" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Region" + } + }, + "required": [ + "name", + "full_name" + ], + "title": "SchoolOut", + "type": "object" + }, + "SchoolRegionOut": { + "description": "One region the search found schools in.", + "properties": { + "cities": { + "items": { + "type": "string" + }, + "title": "Cities", + "type": "array" + }, + "code": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Code" + }, + "examples": { + "items": { + "type": "string" + }, + "title": "Examples", + "type": "array" + }, + "label": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Label" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Region" + }, + "schools": { + "title": "Schools", + "type": "integer" + } + }, + "required": [ + "schools" + ], + "title": "SchoolRegionOut", + "type": "object" + }, + "SchoolRegionsOut": { + "description": "What ``GET /api/v1/directory/school-regions`` answers.\n\nPicking the region from the list always works; this only saves the\nscrolling. So every failure of it is a 503 that says «выберите регион из\nсписка», and an answer that places nothing is an empty list rather than\nan error.", + "properties": { + "generic": { + "default": false, + "title": "Generic", + "type": "boolean" + }, + "query": { + "title": "Query", + "type": "string" + }, + "regions": { + "items": { + "$ref": "#/components/schemas/SchoolRegionOut" + }, + "title": "Regions", + "type": "array" + }, + "truncated": { + "default": false, + "title": "Truncated", + "type": "boolean" + } + }, + "required": [ + "query" + ], + "title": "SchoolRegionsOut", + "type": "object" + }, + "SchoolSearchOut": { + "description": "One page of results, and whether there is more behind it.\n\n``truncated`` is not «есть ещё страницы» — those are ``pages``. It means\nthe directory's own ceiling of twenty was reached, so this is the first\ntwenty of an unknown number and the way forward is a longer query, not a\nnext page. A client that ignores it will show «найдено 20» for a search\nmatching three hundred schools.", + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/SchoolOut" + }, + "title": "Items", + "type": "array" + }, + "page": { + "title": "Page", + "type": "integer" + }, + "pages": { + "title": "Pages", + "type": "integer" + }, + "total": { + "title": "Total", + "type": "integer" + }, + "truncated": { + "default": false, + "title": "Truncated", + "type": "boolean" + } + }, + "required": [ + "page", + "pages", + "total" + ], + "title": "SchoolSearchOut", + "type": "object" + }, + "StatsOut": { + "properties": { + "devices_active": { + "title": "Devices Active", + "type": "integer" + }, + "events_upcoming": { + "title": "Events Upcoming", + "type": "integer" + }, + "homework_open": { + "title": "Homework Open", + "type": "integer" + }, + "homework_total": { + "title": "Homework Total", + "type": "integer" + }, + "lessons_per_week": { + "title": "Lessons Per Week", + "type": "number" + }, + "members_by_role": { + "additionalProperties": { + "type": "integer" + }, + "default": {}, + "propertyNames": { + "enum": [ + "viewer", + "editor", + "admin", + "owner" + ] + }, + "title": "Members By Role", + "type": "object" + }, + "overrides_upcoming": { + "title": "Overrides Upcoming", + "type": "integer" + }, + "subjects": { + "default": [], + "items": { + "$ref": "#/components/schemas/SubjectHoursOut" + }, + "title": "Subjects", + "type": "array" + }, + "subjects_count": { + "title": "Subjects Count", + "type": "integer" + }, + "today": { + "format": "date", + "title": "Today", + "type": "string" + } + }, + "required": [ + "today", + "lessons_per_week", + "subjects_count", + "homework_open", + "homework_total", + "devices_active", + "overrides_upcoming", + "events_upcoming" + ], + "title": "StatsOut", + "type": "object" + }, + "SubjectHoursOut": { + "description": "Lessons a week. A subject that alternates weeks counts a half, which is\nhow a school's own paperwork writes «часов в неделю».", + "properties": { + "hours": { + "title": "Hours", + "type": "number" + }, + "name": { + "title": "Name", + "type": "string" + } + }, + "required": [ + "name", + "hours" + ], + "title": "SubjectHoursOut", + "type": "object" + }, + "SubjectIn": { + "properties": { + "color": { + "anyOf": [ + { + "maxLength": 9, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Color" + }, + "name": { + "maxLength": 120, + "minLength": 1, + "title": "Name", + "type": "string" + }, + "short_name": { + "anyOf": [ + { + "maxLength": 16, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Short Name" + }, + "teacher": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + } + }, + "required": [ + "name" + ], + "title": "SubjectIn", + "type": "object" + }, + "SubjectOut": { + "properties": { + "color": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Color" + }, + "name": { + "title": "Name", + "type": "string" + }, + "short_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Short Name" + }, + "teacher": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + } + }, + "required": [ + "name" + ], + "title": "SubjectOut", + "type": "object" + }, + "SubjectPatch": { + "description": "Only the fields present are changed; ``null`` clears a nullable one.\n``name`` is the rename, and it carries the timetable with it.", + "properties": { + "color": { + "anyOf": [ + { + "maxLength": 9, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Color" + }, + "name": { + "anyOf": [ + { + "maxLength": 120, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name" + }, + "short_name": { + "anyOf": [ + { + "maxLength": 16, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Short Name" + }, + "teacher": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Teacher" + } + }, + "title": "SubjectPatch", + "type": "object" + }, + "SubjectSavedOut": { + "description": "``moved`` is how many timetable, homework and substitution rows a rename\ncarried with it - zero for every other kind of edit, and the number an\nadmin needs to believe the rename actually happened.", + "properties": { + "moved": { + "default": 0, + "title": "Moved", + "type": "integer" + }, + "subject": { + "$ref": "#/components/schemas/ManagedSubjectOut" + } + }, + "required": [ + "subject" + ], + "title": "SubjectSavedOut", + "type": "object" + }, + "TaskIn": { + "properties": { + "due_date": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Due Date" + }, + "due_time": { + "anyOf": [ + { + "format": "time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Due Time" + }, + "homework_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Homework Id" + }, + "notes": { + "anyOf": [ + { + "maxLength": 2000, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Notes" + }, + "priority": { + "default": 1, + "maximum": 2.0, + "minimum": 0.0, + "title": "Priority", + "type": "integer" + }, + "remind_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Remind At" + }, + "subject_name": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Name" + }, + "title": { + "maxLength": 200, + "minLength": 1, + "title": "Title", + "type": "string" + } + }, + "required": [ + "title" + ], + "title": "TaskIn", + "type": "object" + }, + "TaskOut": { + "properties": { + "created_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Created At" + }, + "done": { + "title": "Done", + "type": "boolean" + }, + "done_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Done At" + }, + "due_date": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Due Date" + }, + "due_time": { + "anyOf": [ + { + "format": "time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Due Time" + }, + "homework_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Homework Id" + }, + "id": { + "title": "Id", + "type": "integer" + }, + "notes": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Notes" + }, + "priority": { + "title": "Priority", + "type": "integer" + }, + "remind_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Remind At" + }, + "subject_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Name" + }, + "title": { + "title": "Title", + "type": "string" + }, + "updated_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Updated At" + } + }, + "required": [ + "id", + "title", + "priority", + "done" + ], + "title": "TaskOut", + "type": "object" + }, + "TaskPatch": { + "description": "Every field optional; only the ones sent are changed. ``null`` clears a\nnullable field, which is why \"absent\" and \"null\" are told apart.", + "properties": { + "done": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Done" + }, + "due_date": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Due Date" + }, + "due_time": { + "anyOf": [ + { + "format": "time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Due Time" + }, + "homework_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Homework Id" + }, + "notes": { + "anyOf": [ + { + "maxLength": 2000, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Notes" + }, + "priority": { + "anyOf": [ + { + "maximum": 2.0, + "minimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Priority" + }, + "remind_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Remind At" + }, + "subject_name": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Subject Name" + }, + "title": { + "anyOf": [ + { + "maxLength": 200, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Title" + } + }, + "title": "TaskPatch", + "type": "object" + }, + "TermBoundsIn": { + "description": "Both edges of one term. Validated against the year in the service, not\nhere: «пересекается с периодом 2» is a rule about the other rows, and\npydantic can only see this one.", + "properties": { + "ends_on": { + "format": "date", + "title": "Ends On", + "type": "string" + }, + "starts_on": { + "format": "date", + "title": "Starts On", + "type": "string" + } + }, + "required": [ + "starts_on", + "ends_on" + ], + "title": "TermBoundsIn", + "type": "object" + }, + "TermOut": { + "description": "One quarter or half-year, as the class actually runs it.", + "properties": { + "ends_on": { + "format": "date", + "title": "Ends On", + "type": "string" + }, + "index": { + "title": "Index", + "type": "integer" + }, + "kind": { + "enum": [ + "quarter", + "semester" + ], + "title": "Kind", + "type": "string" + }, + "starts_on": { + "format": "date", + "title": "Starts On", + "type": "string" + } + }, + "required": [ + "index", + "kind", + "starts_on", + "ends_on" + ], + "title": "TermOut", + "type": "object" + }, + "TermSchemeIn": { + "description": "Switch the class between quarters and half-years.", + "properties": { + "kind": { + "enum": [ + "quarter", + "semester" + ], + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "TermSchemeIn", + "type": "object" + }, + "TermsOut": { + "properties": { + "kind": { + "enum": [ + "quarter", + "semester" + ], + "title": "Kind", + "type": "string" + }, + "terms": { + "items": { + "$ref": "#/components/schemas/TermOut" + }, + "title": "Terms", + "type": "array" + }, + "year": { + "title": "Year", + "type": "integer" + } + }, + "required": [ + "kind", + "year" + ], + "title": "TermsOut", + "type": "object" + }, + "TickOut": { + "properties": { + "device_invites_purged": { + "default": 0, + "title": "Device Invites Purged", + "type": "integer" + }, + "device_tokens_purged": { + "default": 0, + "title": "Device Tokens Purged", + "type": "integer" + }, + "diary_keepalive_failed": { + "default": false, + "title": "Diary Keepalive Failed", + "type": "boolean" + }, + "diary_links_purged": { + "default": 0, + "title": "Diary Links Purged", + "type": "integer" + }, + "diary_sessions_kept_alive": { + "default": 0, + "title": "Diary Sessions Kept Alive", + "type": "integer" + }, + "diary_sessions_lost": { + "default": 0, + "title": "Diary Sessions Lost", + "type": "integer" + }, + "diary_sessions_purged": { + "default": 0, + "title": "Diary Sessions Purged", + "type": "integer" + }, + "evening": { + "title": "Evening", + "type": "integer" + }, + "failed": { + "title": "Failed", + "type": "integer" + }, + "fsm_purged": { + "title": "Fsm Purged", + "type": "integer" + }, + "join_attempts_purged": { + "title": "Join Attempts Purged", + "type": "integer" + }, + "morning": { + "title": "Morning", + "type": "integer" + }, + "tasks": { + "title": "Tasks", + "type": "integer" + } + }, + "required": [ + "morning", + "evening", + "tasks", + "failed", + "fsm_purged", + "join_attempts_purged" + ], + "title": "TickOut", + "type": "object" + }, + "TimetableExportOut": { + "description": "The whole weekly template in the bot's paste format.\n\nByte-for-byte what «📤 Экспорт» sends, so a text saved from the bot can be\nimported by the app and the other way round.", + "properties": { + "lessons": { + "title": "Lessons", + "type": "integer" + }, + "text": { + "title": "Text", + "type": "string" + } + }, + "required": [ + "text", + "lessons" + ], + "title": "TimetableExportOut", + "type": "object" + }, + "TimetableImportIn": { + "properties": { + "replace": { + "default": false, + "title": "Replace", + "type": "boolean" + }, + "text": { + "maxLength": 20000, + "minLength": 1, + "title": "Text", + "type": "string" + } + }, + "required": [ + "text" + ], + "title": "TimetableImportIn", + "type": "object" + }, + "TimetableImportOut": { + "description": "``applied: false`` means nothing was written - either the paste held no\nday the parser recognised, or it collided and ``replace`` was not set.", + "properties": { + "applied": { + "title": "Applied", + "type": "boolean" + }, + "bells": { + "default": 0, + "title": "Bells", + "type": "integer" + }, + "conflicts": { + "default": [], + "items": { + "$ref": "#/components/schemas/ImportConflictOut" + }, + "title": "Conflicts", + "type": "array" + }, + "days": { + "default": [], + "items": { + "type": "integer" + }, + "title": "Days", + "type": "array" + }, + "lessons": { + "default": 0, + "title": "Lessons", + "type": "integer" + }, + "rejected": { + "default": [], + "items": { + "type": "string" + }, + "title": "Rejected", + "type": "array" + } + }, + "required": [ + "applied" + ], + "title": "TimetableImportOut", + "type": "object" + }, + "UnlinkOut": { + "properties": { + "linked": { + "title": "Linked", + "type": "boolean" + } + }, + "required": [ + "linked" + ], + "title": "UnlinkOut", + "type": "object" + }, + "ValidationError": { + "properties": { + "ctx": { + "title": "Context", + "type": "object" + }, + "input": { + "title": "Input" + }, + "loc": { + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "title": "Location", + "type": "array" + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + }, + "required": [ + "loc", + "msg", + "type" + ], + "title": "ValidationError", + "type": "object" + } + } + }, + "info": { + "description": "School diary API and Telegram admin bot", + "title": "Lessons", + "version": "0.1.0" + }, + "openapi": "3.1.0", + "paths": { + "/api/v1/bundle": { + "get": { + "description": "Everything the client caches in one round trip.\n\nThe client computes the current lesson/break state locally from this\npayload, so the widget keeps ticking with no network.\n\nAnswers 304 to a matching ``If-None-Match``: the widget polls on a timer\nand nearly every poll finds nothing changed, so nearly every poll should\ncost a hash comparison rather than a two-week payload over mobile data.", + "parameters": [ + { + "description": "First day, defaults to today", + "in": "query", + "name": "start", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "description": "First day, defaults to today", + "title": "Start" + } + }, + { + "in": "query", + "name": "days", + "required": false, + "schema": { + "default": 14, + "maximum": 280, + "minimum": 1, + "title": "Days", + "type": "integer" + } + }, + { + "in": "header", + "name": "if-none-match", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "If-None-Match" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BundleOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Bundle", + "tags": [ + "client" + ] + } + }, + "/api/v1/calendar": { + "get": { + "description": "The subscription URL for this class, minting the feed secret on first ask.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CalendarOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Calendar Url", + "tags": [ + "client" + ] + } + }, + "/api/v1/calendar/{calendar_token}.ics": { + "get": { + "description": "The class as iCalendar. No bearer: calendar apps cannot send one.\n\nThe token in the path is the whole of the authentication, which is why it\nis a secret of its own rather than the join code (see the model). Shared\nper class, so it carries no personal tasks - those are one person's and\nthe feed is everybody's.", + "parameters": [ + { + "in": "path", + "name": "calendar_token", + "required": true, + "schema": { + "title": "Calendar Token", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Calendar Feed", + "tags": [ + "client" + ] + } + }, + "/api/v1/cron/tick": { + "get": { + "description": "Verify the caller, then run one tick.\n\nMirrors the webhook: unset secret means the endpoint does not exist,\nbecause a tick anybody can trigger is a way to make the bot message every\nsubscriber at will. The comparison is constant-time for the same reason\nthe webhook's is.", + "parameters": [ + { + "in": "header", + "name": "x-cron-secret", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "X-Cron-Secret" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TickOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Tick", + "tags": [ + "cron" + ] + }, + "post": { + "description": "Verify the caller, then run one tick.\n\nMirrors the webhook: unset secret means the endpoint does not exist,\nbecause a tick anybody can trigger is a way to make the bot message every\nsubscriber at will. The comparison is constant-time for the same reason\nthe webhook's is.", + "parameters": [ + { + "in": "header", + "name": "x-cron-secret", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "X-Cron-Secret" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TickOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Tick", + "tags": [ + "cron" + ] + } + }, + "/api/v1/days": { + "put": { + "description": "Mark a date as a holiday / shortened / remote day. ``normal`` deletes\nthe mark, so a day never carries a row that says nothing. The checks, the\nmark, its line and its notice are ``special_days.set_day``'s, over the one\nwrite the bot's «🏖 Особые дни» and v2's ``UpdateDay`` make too.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DayIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DayOverrideOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Day Put", + "tags": [ + "edit" + ] + } + }, + "/api/v1/diary/capabilities": { + "get": { + "description": "What this server's diary can do, before the phone takes a password.\n\nAnonymous and database-free, so it is cheap to ask on every sign-in\nscreen: whether the diary runs here at all, and which «Сетевой город»\nregions this server signs in to — a region missing from the list is one\nthe phone should not send a password to, since the session it opened could\nnot be kept. A server from before registration answers 404 here.", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiaryCapabilitiesOut" + } + } + }, + "description": "Successful Response" + } + }, + "summary": "Capabilities", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/login": { + "post": { + "description": "Signs in to the diary and opens a session of ours.\n\nThe password is used for this one call and is never stored. When the\nupstream session eventually expires, requests answer 401 with\n``X-Diary-Reauth: required`` and the app asks for it again.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiaryLoginIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiaryLoginOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Login", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/logout": { + "post": { + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Logout", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/session": { + "post": { + "description": "Keep a session the phone opened itself, and hand back a token of ours.\n\nThe phone signed in with the diary directly, so the password never came\nhere; what arrives is the session the diary gave it. It is read with once,\nfrom this server's address — that read is the check — then sealed, and the\nphone forgets its copy. Nothing here stores or accepts a password: a\n``password`` key anywhere in the body is a 422.\n\nShares ``/login``'s limiters **and buckets**, so a caller who spent ten\nwrong passwords does not get ten more tries by session. Counted as a\nfailure: a session the upstream refused (409), an account with no pupil\n(403), an answer nobody can read (502). Counted as a session opened: a 200,\ntwenty to a caller in fifteen minutes across both doors. Not counted:\nanything that never reached the upstream (422), the feature being off, or\nthe upstream not answering (503).\n\n409 rather than ``/login``'s 401 + ``X-Diary-Reauth``, because asking for\nthe password again would loop: the session was good on the phone seconds\nago, and it is *this server* the diary will not take it from.\n\nThe rules, the order and the counting are `services/diary.register`'s,\nwhich v2's ``CreateDiarySession`` calls too; this words its facts.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "discriminator": { + "mapping": { + "netschool": "#/components/schemas/NetSchoolSessionIn", + "petersburg": "#/components/schemas/PetersburgSessionIn" + }, + "propertyName": "provider" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/PetersburgSessionIn" + }, + { + "$ref": "#/components/schemas/NetSchoolSessionIn" + } + ], + "title": "Payload" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiarySessionOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Register Session", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students": { + "get": { + "description": "Every pupil this account may see. One for most parents.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiaryStudentOut" + }, + "title": "Response Students Api V1 Diary Students Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Students", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/attendance": { + "get": { + "description": "Turnstile records, newest first.", + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiaryAttendanceOut" + }, + "title": "Response Attendance Api V1 Diary Students Student Id Attendance Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Attendance", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/grades": { + "get": { + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "query", + "name": "from", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "From" + } + }, + { + "in": "query", + "name": "to", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "To" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiaryMarkOut" + }, + "title": "Response Grades Api V1 Diary Students Student Id Grades Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Grades", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/homework": { + "get": { + "description": "Homework as its own resource.\n\nUpstream it is a field on a lesson; the client should not have to know\nthat, so the provider pulls it out and this endpoint exists.", + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "query", + "name": "from", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "From" + } + }, + { + "in": "query", + "name": "to", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "To" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiaryHomeworkOut" + }, + "title": "Response Homework Api V1 Diary Students Student Id Homework Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Homework", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/overrides": { + "get": { + "description": "Every correction anybody who sees this child has made for them —\nthis account's and, say, the other parent's alike; no row says whose. None\nfor a child who can have none (`diary_corrections.listed`).", + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiaryOverrideOut" + }, + "title": "Response List Overrides Api V1 Diary Students Student Id Overrides Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "List Overrides", + "tags": [ + "diary" + ] + }, + "put": { + "description": "Writes or replaces one correction.\n\nThe target is the string the read endpoints handed down; it is not parsed\nbeyond the check that it names something correctable. A target this server\nwould never produce is refused rather than stored: a row no read path can\nmatch would sit in the table looking like a correction somebody made, with\nno way to reset it, because the button that resets it only appears next to\nthe value it changed.\n\nReplaces whatever was there, whoever wrote it: the last writer wins,\n``original`` included.\n\nA child that can have no corrections is a ``422``, the status the app\nalready reads on this route as «Это поле нельзя исправить» — true of every\nfield of that child.\n\nThe rules and their order are `services/diary_corrections.correct`'s,\nwhich v2's ``BatchUpdateCorrections`` calls too; this words its facts.", + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiaryOverrideIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiaryOverrideOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Put Override", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/overrides/all": { + "delete": { + "description": "Resets every correction for this child, whoever wrote it, for everyone\nwho sees the child — and nothing of any other child's. The diary answers\nfor itself again.", + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Reset All Overrides", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/overrides/reset": { + "post": { + "description": "Resets one field back to what the diary says.\n\nA POST with a body rather than a DELETE with a query string: the target is\nfree text and can carry an ampersand, and a reset that quietly matched\nnothing while answering 204 is worse than one that is awkward to spell.\n\nIdempotent, and answers 204 whether or not there was a row: \"there is no\ncorrection here\" is the state the caller asked for, and a 404 would make\nthe client decide whether to show an error for having got what it wanted.\nIt takes the correction off for everyone who sees the child.", + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiaryResetIn" + } + } + }, + "required": true + }, + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Reset Override", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/periods": { + "get": { + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiaryPeriodOut" + }, + "title": "Response Periods Api V1 Diary Students Student Id Periods Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Periods", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/schedule": { + "get": { + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "query", + "name": "from", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "From" + } + }, + { + "in": "query", + "name": "to", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "To" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiaryLessonOut" + }, + "title": "Response Schedule Api V1 Diary Students Student Id Schedule Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Schedule", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/subjects": { + "get": { + "description": "Subjects studied in a period; the current one when none is named.", + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "query", + "name": "period_id", + "required": false, + "schema": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Period Id" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiarySubjectOut" + }, + "title": "Response Subjects Api V1 Diary Students Student Id Subjects Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Subjects", + "tags": [ + "diary" + ] + } + }, + "/api/v1/diary/students/{student_id}/teachers": { + "get": { + "parameters": [ + { + "in": "path", + "name": "student_id", + "required": true, + "schema": { + "title": "Student Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/DiaryTeacherOut" + }, + "title": "Response Teachers Api V1 Diary Students Student Id Teachers Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Teachers", + "tags": [ + "diary" + ] + } + }, + "/api/v1/directory/school-regions": { + "get": { + "description": "The regions a school called ``q`` may be in, best-ranked first.\n\nIn this order, and the order is the contract\n(``services/directory.school_regions`` keeps it):\n\n1. a caller over its limit is 429 with ``Retry-After``;\n2. a query under three characters is 422, **not counted** — nothing was\n asked of anybody;\n3. everything after that is counted against the caller;\n4. no directory key on this deployment is 503 ``disabled``;\n5. a name that is only a kind of school and a small number («школа № 5»)\n is 200 with ``generic`` and no upstream call; anything else spends from\n today's anonymous share, and a spent share is 503 ``spent`` with\n ``Retry-After`` until the next day;\n6. the directory failing, in any way, is 503 ``upstream``.\n\nNot per keystroke: the phone asks on submit or after a pause in typing.", + "parameters": [ + { + "description": "Название школы, как его пишут люди", + "in": "query", + "name": "q", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Название школы, как его пишут люди", + "title": "Q" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SchoolRegionsOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "School Regions", + "tags": [ + "directory" + ] + } + }, + "/api/v1/events": { + "put": { + "description": "Events have no natural key - two «Обед» rows on one day are two breaks\n- so this always creates; ``DELETE`` is how one goes away. The row, its\nline and its notice are ``events.create``'s, which v2's ``CreateEvent``\ncalls too.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EventIn" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EventCreatedOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Event Put", + "tags": [ + "edit" + ] + } + }, + "/api/v1/events/{event_id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "event_id", + "required": true, + "schema": { + "title": "Event Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Event Delete", + "tags": [ + "edit" + ] + } + }, + "/api/v1/health": { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "title": "Response Health Api V1 Health Get", + "type": "object" + } + } + }, + "description": "Successful Response" + } + }, + "summary": "Health", + "tags": [ + "client" + ] + } + }, + "/api/v1/homework": { + "get": { + "description": "Homework due in a window, each row with this person's own tick. The\nwindow is ``clock.window`` and the rows ``homework.due_between``, which\nv2's ``ListHomework`` reads too.", + "parameters": [ + { + "in": "query", + "name": "from", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "From" + } + }, + { + "in": "query", + "name": "to", + "required": false, + "schema": { + "anyOf": [ + { + "format": "date", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "To" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/HomeworkItemOut" + }, + "title": "Response Homework List Api V1 Homework Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Homework List", + "tags": [ + "client" + ] + }, + "put": { + "description": "Upsert by (date, subject), exactly as the bot does: one assignment per\nsubject per day, and sending it again replaces the text. The line and the\nnotice are ``homework.put``'s, which v2's writes share.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HomeworkIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HomeworkItemOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Homework Put", + "tags": [ + "edit" + ] + } + }, + "/api/v1/homework/{homework_id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "homework_id", + "required": true, + "schema": { + "title": "Homework Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Homework Delete", + "tags": [ + "edit" + ] + } + }, + "/api/v1/homework/{homework_id}/done": { + "post": { + "description": "Set (not toggle) this person's tick: the app sends the state it shows,\nso a retried request lands on the same answer (``tasks.set_homework_done``,\nwhich v2's homework ticks call too).", + "parameters": [ + { + "in": "path", + "name": "homework_id", + "required": true, + "schema": { + "title": "Homework Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DoneIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DoneOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Homework Done", + "tags": [ + "client" + ] + } + }, + "/api/v1/join": { + "post": { + "description": "Exchange a code for a long-lived device token.\n\nThe flow is ``services/join.py``'s, which v2's ``CreateDevice`` calls too,\nover the same limiter and the same bucket; this endpoint keeps v1's words\nfor each refusal (``app/wording.py``'s, which v2 answers with too), and\nits statuses.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/JoinRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/JoinResponse" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Join", + "tags": [ + "client" + ] + } + }, + "/api/v1/manage/bells": { + "get": { + "description": "Every schedule the class keeps - «Обычное», «Сокращённое», «Суббота» -\nwith the class default marked.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/BellScheduleOut" + }, + "title": "Response Bells List Api V1 Manage Bells Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Bells List", + "tags": [ + "manage" + ] + }, + "post": { + "description": "A new named schedule, with its rows if they came with it.\n\nIt does not become the class default: a shortened schedule is created in\norder to be pointed at by particular days, and making it the default the\nmoment it exists would move every day onto it.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BellScheduleIn" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BellScheduleOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Bells Create", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/bells/{schedule_id}": { + "delete": { + "description": "Refused for the class default and for anything a day still points at.\n\nBoth are a ``SET NULL`` at the database level, which would silently move\nthose days onto the default schedule - a change nobody asked for, on dates\nan admin is not looking at.", + "parameters": [ + { + "in": "path", + "name": "schedule_id", + "required": true, + "schema": { + "title": "Schedule Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Bells Delete", + "tags": [ + "manage" + ] + }, + "patch": { + "description": "Rename a schedule, or make it the one the class runs on by default.\n\n``is_default: false`` is refused: a class with no default schedule has no\ntimes for an ordinary day, so the way to stop using this one is to make\nanother one the default. A schedule that rings nothing cannot become it,\nfor the reason ``ScheduleEmpty`` gives, and making the default what it\nalready is writes nothing. The patch is ``services/manage/bells.update``,\nwhich ``PUT …/periods`` and v2's ``UpdateBellSchedule`` apply too.", + "parameters": [ + { + "in": "path", + "name": "schedule_id", + "required": true, + "schema": { + "title": "Schedule Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BellSchedulePatch" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BellScheduleOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Bells Update", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/bells/{schedule_id}/periods": { + "put": { + "description": "Replace a schedule's rows wholesale.\n\nWholesale rather than row by row because that is what editing bells is:\nthe times of the lessons after the one that moved all shift with it, and\nsending the six rows that are now true is one intention, not six.", + "parameters": [ + { + "in": "path", + "name": "schedule_id", + "required": true, + "schema": { + "title": "Schedule Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BellPeriodsIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BellScheduleOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Bells Periods", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/class": { + "delete": { + "description": "Delete the class and everything hanging off it. Owner only.\n\n``confirm_name`` must be the class's name, exactly as the bot makes an\nowner type it back: a confirmation dialog is answered by the same thumb\nthat opened it, while a name has to be read off the screen first. The app\nwill show its own «вы уверены» sheet, but the check that matters is this\none, because the endpoint is reachable without the sheet.\n\nNothing is written to the audit log: the log lives in the class and goes\nwith it. Every device token goes too, so the caller's own token stops\nworking - which is correct, there is nothing left for it to read.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ClassDeleteIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Class Delete", + "tags": [ + "manage" + ] + }, + "get": { + "description": "What «⚙️ Класс» shows, as data.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ManagedClassOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Class Card", + "tags": [ + "manage" + ] + }, + "patch": { + "description": "Rename the class, re-home it, move its time zone, or change who may join.\n\nOne audit line per field changed rather than one for the request, because\nthat is what the log is read for: «что изменилось», not «кто открыл\nнастройки». The patch is ``services/manage/classes.update``, which v2's\n``UpdateClass`` applies too: the letter read by the bot's rule, the zone\nasked about before anything is written, the name recomposed from the grade\nand the letter unless the request names the class, and the join mode last.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ClassPatch" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ManagedClassOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Class Update", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/devices": { + "get": { + "description": "The phones on the class's list, oldest first.\n\nThe role is a lookup, not a stored field: a device acts with whatever role\nits owner holds right now, so revoking somebody in the bot has already\nchanged this list by the time it is drawn. ``include_revoked`` brings back\nthe ones that were switched off, which the bot's page leaves out.", + "parameters": [ + { + "in": "query", + "name": "include_revoked", + "required": false, + "schema": { + "default": false, + "title": "Include Revoked", + "type": "boolean" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/ManagedDeviceOut" + }, + "title": "Response Devices List Api V1 Manage Devices Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Devices List", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/devices/{device_id}/revoke": { + "post": { + "description": "Switch a phone off. Revoked, not deleted: the row is what a token is\nchecked against, and keeping it is what makes the refusal instant and\npermanent. Revoking an already revoked device changes nothing and adds no\nsecond line to the log.\n\nAn admin may do this to the phone they are holding, and then the next\nrequest from it is a 401. That is the point - it is how a lost phone is\ndealt with from the one that is still in a pocket.", + "parameters": [ + { + "in": "path", + "name": "device_id", + "required": true, + "schema": { + "title": "Device Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ManagedDeviceOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Device Revoke", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/devices/{device_id}/unlink": { + "post": { + "description": "Back to read-only, without taking the phone off the class.\n\nThe device keeps reading the timetable and loses the role it borrowed from\nits owner's account. A device that is not linked has nothing to unlink,\nwhich is a 409 rather than a silent success: the admin pressed it expecting\nsomething to change.", + "parameters": [ + { + "in": "path", + "name": "device_id", + "required": true, + "schema": { + "title": "Device Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ManagedDeviceOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Device Unlink", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/log": { + "get": { + "description": "Who changed what, newest first; ``has_more`` says whether a page follows.", + "parameters": [ + { + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 30, + "maximum": 100, + "minimum": 1, + "title": "Limit", + "type": "integer" + } + }, + { + "in": "query", + "name": "offset", + "required": false, + "schema": { + "default": 0, + "minimum": 0, + "title": "Offset", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuditPageOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Audit Log", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/requests": { + "get": { + "description": "Everybody waiting for a role, oldest first.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/AccessRequestOut" + }, + "title": "Response Requests List Api V1 Manage Requests Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Requests List", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/requests/{request_id}/approve": { + "post": { + "description": "Grant the role, through the same rules as «👥 Доступ» in the bot.\n\nLiterally the same rules: `services/manage/requests.approve`, over\n`services/access.approve_request`, is what the bot's «✅ Одобрить» calls,\nand v2's `ApproveAccessRequest`, so the surfaces cannot drift apart. The\nonly thing this one does differently from the bot is let an admin answer\nwith a role other than the one asked for - which `can_grant` still\ngates, inside the service.\n\nThe requester is told in Telegram, because that is where they asked.", + "parameters": [ + { + "in": "path", + "name": "request_id", + "required": true, + "schema": { + "title": "Request Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/RequestDecisionIn" + }, + { + "type": "null" + } + ], + "title": "Payload" + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestDecisionOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Request Approve", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/requests/{request_id}/decline": { + "post": { + "description": "Say no. The person keeps whatever role they already had, and is told -\nsilence would leave them asking again.", + "parameters": [ + { + "in": "path", + "name": "request_id", + "required": true, + "schema": { + "title": "Request Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestDecisionOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Request Decline", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/schools": { + "get": { + "description": "Search the school directory, the same way «⚙️ Класс» does in the bot.\n\nReads nothing and writes nothing: it is a lookup the app needs before it\ncan `PATCH /class` with a school name, and the name is all that is stored.\nAdmin-only despite being read-only, because every call spends part of a\ndaily allowance somebody else pays for, and the class's own members are the\nonly people with a reason to spend it.\n\n503 rather than 500 when the directory is not configured or not answering:\nnothing here is broken, the feature is simply unavailable right now, and\nthe client's answer to that is to let the name be typed.\n\n**Every call is one upstream search**, whatever ``page`` says — the\ndirectory has no offset to page with, so there is nothing to resume. A\nclient that pages should therefore ask once with ``page_size=20`` and cut\nthe answer up itself, which is what the bot and the app both do; asking for\nfour pages of five is four searches for one question.", + "parameters": [ + { + "description": "Название или номер школы", + "in": "query", + "name": "q", + "required": true, + "schema": { + "description": "Название или номер школы", + "title": "Q", + "type": "string" + } + }, + { + "in": "query", + "name": "page", + "required": false, + "schema": { + "default": 1, + "minimum": 1, + "title": "Page", + "type": "integer" + } + }, + { + "description": "Строк на странице; 20 отдаёт всё найденное за один запрос", + "in": "query", + "name": "page_size", + "required": false, + "schema": { + "default": 5, + "description": "Строк на странице; 20 отдаёт всё найденное за один запрос", + "maximum": 20, + "minimum": 1, + "title": "Page Size", + "type": "integer" + } + }, + { + "in": "query", + "name": "region", + "required": false, + "schema": { + "anyOf": [ + { + "maxLength": 120, + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Region" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SchoolSearchOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Schools Search", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/stats": { + "get": { + "description": "The numbers «📊 Статистика» shows, without the sentence around them.\n\nAn editor may read them, as in the bot: they say whether the timetable is\ncomplete and whether homework is being entered, which is exactly what the\nperson entering it wants to know.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StatsOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Stats", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/subjects": { + "get": { + "description": "The dictionary with ids, for a screen that edits it. An editor may\nread it - it is the same list ``GET /api/v1/subjects`` gives any device.\n\nAdopts whatever the timetable already uses on the way, so this list is\nnever emptily lying about a class with thirty-five lessons in it. Free once\nthe two agree, which after the first read they do. v2's ``ListSubjects``\ndoes not adopt (the server-v2 design, decision 10); this read keeps doing\nit until v1 is retired.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/ManagedSubjectOut" + }, + "title": "Response Subjects List Api V1 Manage Subjects Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Subjects List", + "tags": [ + "manage" + ] + }, + "post": { + "description": "Add a subject. The name is unique within the class - that uniqueness is\nthe whole point of the dictionary, so a duplicate is a 409, not a silent\nsecond «Алгебра».", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectIn" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectSavedOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Subject Create", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/subjects/{subject_id}": { + "delete": { + "description": "Deleting a subject the timetable still uses is refused.\n\nIt used to be allowed, and it left the lessons alone: the timetable stores\nthe name as well as the link, so the class kept its timetable and lost\nonly the colour and the teacher. That stopped being true when the\ndictionary started keeping itself. The name is still in the template, so\nthe next read adopts it again - the entry returns within one poll, without\nits colour, its short name or its teacher, and the admin is left believing\nthey deleted something.\n\nSo the two halves of one list are deleted in one order: take the subject\nout of the weekly template, and then out of the dictionary. A subject\nnothing teaches still deletes in one step, which is the case this endpoint\nwas really for.", + "parameters": [ + { + "in": "path", + "name": "subject_id", + "required": true, + "schema": { + "title": "Subject Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletedOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Subject Delete", + "tags": [ + "manage" + ] + }, + "patch": { + "description": "Rename a subject, or set its short name, teacher or colour.\n\nA rename is a cascade: the timetable, the homework and the substitutions store the\nsubject as text, so all three move with it in this one transaction, and\n``moved`` says how many rows did. Renaming onto a name the class already\nuses is refused - merging two subjects is a different operation, and doing\nit by accident cannot be undone. The patch itself is\n``services/manage/subjects.update``, which v2's ``UpdateSubject`` applies too.", + "parameters": [ + { + "in": "path", + "name": "subject_id", + "required": true, + "schema": { + "title": "Subject Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectPatch" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SubjectSavedOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Subject Update", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/terms": { + "get": { + "description": "This class's terms, seeding the conventional set if it has none.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TermsOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Terms List", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/terms/scheme": { + "put": { + "description": "Switch between quarters and half-years, reseeding the year.\n\nA replacement rather than an edit: four quarters and two halves do not map\nonto each other, and a leftover third quarter inside a year that has two is\nnot a state worth keeping.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TermSchemeIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TermsOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Terms Set Scheme", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/terms/{index}": { + "put": { + "description": "Move one term's edges.\n\n422 with the service's own Russian sentence rather than a field-shaped\nerror: what is wrong is the relationship between this term and the year or\nits neighbours, and «конец периода раньше его начала» is the thing worth\nputting on the screen.", + "parameters": [ + { + "in": "path", + "name": "index", + "required": true, + "schema": { + "title": "Index", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TermBoundsIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TermsOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Terms Set Bounds", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/timetable": { + "get": { + "description": "The weekly template as the text «📤 Экспорт» sends.\n\nThe same format in both directions, which is what makes it a backup: a\ntext saved out of the bot goes back in through the app, and the other way\nround. An empty timetable is an empty string, not a 404 - there is nothing\nwrong with a class that has not filled one in yet.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TimetableExportOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Timetable Export", + "tags": [ + "manage" + ] + } + }, + "/api/v1/manage/timetable/import": { + "post": { + "description": "Parse a paste and replace exactly the weekdays it names.\n\nThe bot shows a preview and asks «Применить»; an API has no screen to show\none on, so the preview is the refusal: if a weekday in the paste already\nhas lessons, nothing is written and the response lists what stands to be\noverwritten. Sending it again with ``replace: true`` is the second tap.\n\nDays the paste does not mention are left alone, so importing one day's\nblock is a legitimate thing to do, and a day named with nothing under it is\nemptied - that is how a paste says «в четверг уроков нет». A\n``== Звонки ==`` block replaces the default schedule's rows outright, as it\ndoes in the bot; it is a schedule, not a day, and nothing else points at it.\nThe rules are ``services/manage/timetable.import_paste``.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TimetableImportIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TimetableImportOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Timetable Import", + "tags": [ + "manage" + ] + } + }, + "/api/v1/me": { + "get": { + "description": "Who this device is, and the code to type into the bot if it is nobody yet.\n\nThe code is issued here rather than at join time so that a device that\nnever opens the link screen never holds one, and re-issued after an\nunlink for the same reason.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MeOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Me", + "tags": [ + "client" + ] + } + }, + "/api/v1/me/unlink": { + "post": { + "description": "Back to read-only. Idempotent: unlinking an unlinked device is fine, and\nchanges nothing (``linking.unlink_self``, which v2's ``UnlinkMe`` calls).", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnlinkOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Unlink", + "tags": [ + "client" + ] + } + }, + "/api/v1/now": { + "get": { + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NowOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Now", + "tags": [ + "client" + ] + } + }, + "/api/v1/overrides": { + "put": { + "description": "One row per (date, lesson number). ``clear`` removes it, which is how\na lesson goes back to the timetable. The three questions a substitution\nis asked, the row, its line and its notice are\n``services/substitutions.py``'s, which the bot's «🔄 Замены» and v2's\n``SubstitutionService`` ask and write through too.", + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OverrideIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OverrideOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Override Put", + "tags": [ + "edit" + ] + } + }, + "/api/v1/subjects": { + "get": { + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/SubjectOut" + }, + "title": "Response Subjects Api V1 Subjects Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Subjects", + "tags": [ + "client" + ] + } + }, + "/api/v1/tasks": { + "get": { + "parameters": [ + { + "in": "query", + "name": "include_done", + "required": false, + "schema": { + "default": false, + "title": "Include Done", + "type": "boolean" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "items": { + "$ref": "#/components/schemas/TaskOut" + }, + "title": "Response Tasks List Api V1 Tasks Get", + "type": "array" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Tasks List", + "tags": [ + "client" + ] + }, + "post": { + "parameters": [ + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TaskIn" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TaskOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Tasks Create", + "tags": [ + "client" + ] + } + }, + "/api/v1/tasks/{task_id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "task_id", + "required": true, + "schema": { + "title": "Task Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Tasks Delete", + "tags": [ + "client" + ] + }, + "patch": { + "parameters": [ + { + "in": "path", + "name": "task_id", + "required": true, + "schema": { + "title": "Task Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TaskPatch" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TaskOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Tasks Update", + "tags": [ + "client" + ] + } + }, + "/api/v1/tasks/{task_id}/done": { + "post": { + "parameters": [ + { + "in": "path", + "name": "task_id", + "required": true, + "schema": { + "title": "Task Id", + "type": "integer" + } + }, + { + "in": "header", + "name": "authorization", + "required": false, + "schema": { + "default": "", + "title": "Authorization", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DoneIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TaskOut" + } + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Tasks Done", + "tags": [ + "client" + ] + } + }, + "/api/v1/warmup": { + "get": { + "description": "Same as `/health`, plus one round trip to the database.\n\n`/health` deliberately never opens a connection, so pinging it keeps the\nserverless function loaded but leaves a Neon compute that has scaled to\nzero asleep - the query that finally wakes it is then the user's own\n`/start`, or a device's own sync. This endpoint exists to be pinged\ninstead, by an external scheduler: see docs/deploy.md for how the two\ncold starts stack and why hitting this one on a timer is the free\nmitigation for both.", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "title": "Response Warmup Api V1 Warmup Get", + "type": "object" + } + } + }, + "description": "Successful Response" + } + }, + "summary": "Warmup", + "tags": [ + "client" + ] + } + } + } +} diff --git a/server/scripts/check_migration_merge_side.py b/server/scripts/check_migration_merge_side.py new file mode 100644 index 00000000..532dccf6 --- /dev/null +++ b/server/scripts/check_migration_merge_side.py @@ -0,0 +1,230 @@ +"""Check Alembic rollout declarations without importing revisions.""" + +import ast + +_HISTORIC_REVISIONS = {f"{number:04d}" for number in range(1, 20)} +_READ_ONLY = {"f", "get_bind", "get_context", "inline_literal"} +_AFTER = { + "create_check_constraint", + "create_foreign_key", + "create_primary_key", + "create_unique_constraint", + "drop_column", + "drop_constraint", + "drop_index", + "drop_table", + "rename_table", +} +_ROW_LOSS = {"drop_column", "drop_table"} +_SQL_AFTER = {"DELETE", "DROP", "LOCK", "TRUNCATE", "UPDATE"} +_SQL_ROW_LOSS = {"DELETE", "DROP", "TRUNCATE"} +_PLAIN_COLUMN_TYPES = { + "BigInteger", "Boolean", "Date", "DateTime", "Double", "Float", "Integer", "Interval", + "JSON", "JSONB", "LargeBinary", "Numeric", "SmallInteger", "String", "Text", "Time", + "Unicode", "UnicodeText", "Uuid", +} + + +def _literal(node: ast.expr | None) -> object: + return node.value if isinstance(node, ast.Constant) else None + + +def _module_values(tree: ast.Module) -> dict[str, ast.expr]: + values = {} + for node in tree.body: + if isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name): + values[target.id] = node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + if node.value is not None: + values[node.target.id] = node.value + return values + + +def _upgrade_calls(tree: ast.Module) -> list[ast.Call]: + functions = {node.name: node for node in tree.body if isinstance(node, ast.FunctionDef)} + pending = ["upgrade"] + visited: set[str] = set() + calls = [] + while pending: + name = pending.pop() + if name in visited: + continue + visited.add(name) + for node in ast.walk(functions[name]): + if isinstance(node, ast.Call): + calls.append(node) + if isinstance(node.func, ast.Name) and node.func.id in functions: + pending.append(node.func.id) + return sorted(calls, key=lambda call: (call.lineno, call.col_offset)) + + +def _operation_names(tree: ast.Module) -> tuple[set[str], dict[str, str]]: + names = {"alembic.op", "op"} + direct: dict[str, str] = {} + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module == "alembic": + names.update(item.asname or item.name for item in node.names if item.name == "op") + if isinstance(node, ast.ImportFrom) and node.module == "alembic.op": + direct.update((item.asname or item.name, item.name) for item in node.names) + if isinstance(node, ast.Import): + names.update( + f"{item.asname}.op" for item in node.names if item.name == "alembic" and item.asname + ) + names.update( + item.asname for item in node.names if item.name == "alembic.op" and item.asname + ) + return names, direct + + +def _keyword(call: ast.Call, name: str) -> ast.expr | None: + return next((item.value for item in call.keywords if item.arg == name), None) + + +def _flag(call: ast.Call, name: str, *, default: bool) -> bool | None: + if any(item.arg is None for item in call.keywords): + return None + node = _keyword(call, name) + if node is None: + return default + value = _literal(node) + return value if isinstance(value, bool) else None + + +def _plain_column_type(node: ast.expr | None) -> bool: + constructor = node.func if isinstance(node, ast.Call) else node + name = getattr(constructor, "attr", getattr(constructor, "id", None)) + if name not in _PLAIN_COLUMN_TYPES: + return False + if name == "Boolean" and isinstance(node, ast.Call): + # Boolean's first parameter can create an implicit CHECK constraint. + return not node.args and _flag(node, "create_constraint", default=False) is False + return True + + +def _column_side(call: ast.Call) -> tuple[str, bool] | None: + column = call.args[1] if len(call.args) > 1 else _keyword(call, "column") + if not isinstance(column, ast.Call): + return None + function = column.func + name = getattr(function, "attr", getattr(function, "id", None)) + if name != "Column": + return None + if len(column.args) > 2 or any(isinstance(arg, ast.Starred) for arg in column.args): + return None + keyword_name = _keyword(column, "name") + if column.args and keyword_name is not None: + return None + column_name = column.args[0] if column.args else keyword_name + if not isinstance(_literal(column_name), str): + return None + positional_type = column.args[1] if len(column.args) == 2 else None + keyword_type = _keyword(column, "type_") + # SQLAlchemy accepts schema items in either apparent name/type slot. + if positional_type is not None and keyword_type is not None: + return None + if not _plain_column_type(positional_type or keyword_type): + return None + nullable = _flag(column, "nullable", default=True) + unique = _flag(column, "unique", default=False) + key = _flag(column, "primary_key", default=False) + # A constrained column combines a new reader dependency with a new writer constraint. + return ("before", False) if nullable is True and unique is False and key is False else None + + +def _sql_side(call: ast.Call, values: dict[str, ast.expr]) -> tuple[str, bool] | None: + sql = call.args[0] if call.args else _keyword(call, "sqltext") + if isinstance(sql, ast.Name): + sql = values.get(sql.id) + if isinstance(sql, ast.Call) and ast.unparse(sql.func) in {"text", "sa.text"}: + sql = sql.args[0] if sql.args else None + statement = _literal(sql) + # A SQL parser and the target data would be needed to infer arbitrary scripts. + if not isinstance(statement, str): + return None + statement = statement.strip().removesuffix(";") + tokens = statement.split(maxsplit=1) + if ";" in statement or not tokens or tokens[0].upper() not in _SQL_AFTER: + return None + return "after", tokens[0].upper() in _SQL_ROW_LOSS + + +def _classify( + name: str, + call: ast.Call, + values: dict[str, ast.expr], +) -> tuple[str, bool] | None: + if name == "create_table": + return "before", False + if name in _AFTER: + return "after", name in _ROW_LOSS + if name == "add_column": + return _column_side(call) + if name == "create_index": + unique = _flag(call, "unique", default=False) + if unique is not None: + return ("after" if unique else "before", False) + if name == "alter_column" and all( + item.arg in {"nullable", "schema"} or (item.arg or "").startswith("existing_") + for item in call.keywords + ): + nullable = _literal(_keyword(call, "nullable")) + if isinstance(nullable, bool): + return ("before" if nullable else "after", False) + if name == "execute": + return _sql_side(call, values) + return None + + +def migration_side_errors(source: str) -> list[str]: + tree = ast.parse(source) + values = _module_values(tree) + revision = _literal(values.get("revision")) + if isinstance(revision, str) and revision in _HISTORIC_REVISIONS: + return [] + side = _literal(values.get("MERGE_SIDE")) + destroys = _literal(values.get("DESTROYS")) + errors = [] + if side not in ("before", "after"): + errors.append('declare a literal MERGE_SIDE = "before" or "after"') + if not any(isinstance(node, ast.FunctionDef) and node.name == "upgrade" for node in tree.body): + return [*errors, "declare an upgrade() function"] + + sides: dict[str, list[str]] = {} + names, direct = _operation_names(tree) + if "*" in direct: + errors.append("Import Alembic operations by name so their merge side can be checked.") + for call in _upgrade_calls(tree): + operation = call.func + name = None + if isinstance(operation, ast.Name): + name = direct.get(operation.id) + elif isinstance(operation, ast.Attribute) and ast.unparse(operation.value) in names: + name = operation.attr + raw_sql = ( + isinstance(operation, ast.Attribute) + and operation.attr in {"execute", "exec_driver_sql"} + ) + if (name is None and not raw_sql) or name in _READ_ONLY: + continue + label = f"line {call.lineno} ({ast.unparse(operation)})" + classification = _classify(name, call, values) if name is not None else None + if classification is None: + errors.append(f"{label}: cannot classify this operation. Use explicit Alembic DDL.") + continue + required, row_loss = classification + sides.setdefault(required, []).append(label) + if row_loss and not (isinstance(destroys, str) and destroys.strip()): + errors.append(f"{label} needs a non-empty DESTROYS explanation") + + if len(sides) > 1: + before, after = ", ".join(sides["before"]), ", ".join(sides["after"]) + errors.append( + f"mixed merge sides: before ({before}) and after ({after}). Split the revision." + ) + elif side in ("before", "after"): + for required, operations in sides.items(): + if required != side: + errors.extend(f"{op} requires MERGE_SIDE = {required!r}" for op in operations) + return errors diff --git a/server/scripts/check_openapi_v1.py b/server/scripts/check_openapi_v1.py new file mode 100644 index 00000000..848effaf --- /dev/null +++ b/server/scripts/check_openapi_v1.py @@ -0,0 +1,258 @@ +"""Keep the v1 OpenAPI contract readable by installed clients (#638).""" + +import argparse +import json +import os +import re +import subprocess +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +SNAPSHOT = Path(__file__).resolve().parent.parent / "openapi-v1.json" +_SCHEMA_REF = "#/components/schemas/" +_METHODS = {"delete", "get", "head", "options", "patch", "post", "put", "trace"} +_OVERRIDE = re.compile(r"V1-OpenAPI-Break: MIN_CLIENT_VERSION=([1-9][0-9]{0,9})") +_MAX_ANDROID_VERSION_CODE = 2_100_000_000 +_COMPOSITIONS = ("allOf", "anyOf", "oneOf", "prefixItems") +_MINIMUMS = ("minimum", "exclusiveMinimum", "minLength", "minItems", "minProperties") +_MAXIMUMS = ("maximum", "exclusiveMaximum", "maxLength", "maxItems", "maxProperties") + + +def _references(value: Any) -> Iterator[str]: + if isinstance(value, dict): + ref = value.get("$ref") + if isinstance(ref, str) and ref.startswith(_SCHEMA_REF): + yield ref.removeprefix(_SCHEMA_REF) + for child in value.values(): + yield from _references(child) + elif isinstance(value, list): + for child in value: + yield from _references(child) + + +def v1_snapshot(document: dict) -> str: + paths = { + name: _wire_operations(path) + for name, path in document["paths"].items() + if (name == "/api/v1" or name.startswith("/api/v1/")) and name != "/api/v1/telegram/webhook" + } + components = document.get("components", {}) + all_schemas = components.get("schemas", {}) + remaining = {key: value for key, value in components.items() if key != "schemas"} + selected: dict[str, Any] = {} + pending = list(_references(paths)) + list(_references(remaining)) + while pending: + name = pending.pop().replace("~1", "/").replace("~0", "~") + if name not in selected: + selected[name] = all_schemas[name] + pending.extend(_references(selected[name])) + snapshot = {**document, "paths": paths, "components": {**remaining, "schemas": selected}} + return json.dumps(snapshot, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + + +def _wire_operations(path: dict) -> dict: + # FastAPI can derive a multi-method route's ID from either member of a set. + return { + key: {name: value for name, value in item.items() if name != "operationId"} + if key in _METHODS else item + for key, item in path.items() + } + + +def _resolve(value: dict, document: dict) -> dict: + seen = set() + while (reference := value.get("$ref")) is not None: + if not reference.startswith("#/") or reference in seen: + raise ValueError("Expected an acyclic local OpenAPI reference") + seen.add(reference) + value = document + for key in reference[2:].split("/"): + value = value[key.replace("~1", "/").replace("~0", "~")] + return value + + +class _Comparison: + def __init__(self, old: dict, new: dict) -> None: + self.old = old + self.new = new + self.errors: list[str] = [] + + def schema( + self, old: Any, new: Any, where: str, *, request: bool, ancestors=frozenset(), + ) -> None: + if not isinstance(old, dict) or not isinstance(new, dict): + if old != new: + self.errors.append(f"{where} changed its schema") + return + old, new = _resolve(old, self.old), _resolve(new, self.new) + pair = (id(old), id(new)) + if pair in ancestors: + return + ancestors = ancestors | {pair} + + def compare(left: Any, right: Any, label: str) -> None: + self.schema(left, right, label, request=request, ancestors=ancestors) + + for keyword in ("type", "format", "nullable", "enum", "const", "pattern", "multipleOf"): + if old.get(keyword) != new.get(keyword): + if keyword in new or not request: + self.errors.append(f"{where} changed {keyword}") + for keyword in _MINIMUMS + _MAXIMUMS: + if keyword not in new: + continue + before, after = old.get(keyword), new[keyword] + stricter = before is None or ( + after > before if keyword in _MINIMUMS else after < before + ) + if stricter: + self.errors.append(f"{where} narrowed {keyword}") + + old_props, new_props = old.get("properties", {}), new.get("properties", {}) + old_required, new_required = set(old.get("required", [])), set(new.get("required", [])) + if request: + for field in sorted(new_required - old_required): + self.errors.append(f"{where} added required request field {field}") + if new.get("additionalProperties") is False: + for field in sorted(old_props.keys() - new_props.keys()): + self.errors.append(f"{where}.{field} is no longer accepted in the request") + else: + for field in sorted(old_props.keys() - new_props.keys()): + self.errors.append(f"{where}.{field} was removed from the response") + for field in sorted((old_required - new_required) & new_props.keys()): + self.errors.append(f"{where}.{field} is no longer guaranteed in the response") + for field in sorted(old_props.keys() & new_props.keys()): + compare(old_props[field], new_props[field], f"{where}.{field}") + for keyword in ("items", "additionalProperties"): + if keyword in old or keyword in new: + compare(old.get(keyword, True), new.get(keyword, True), f"{where}.{keyword}") + for keyword in _COMPOSITIONS: + left, right = old.get(keyword, []), new.get(keyword, []) + if len(left) != len(right): + self.errors.append(f"{where} changed {keyword} alternatives") + else: + for index, (old_item, new_item) in enumerate(zip(left, right, strict=True)): + compare(old_item, new_item, f"{where}.{keyword}[{index}]") + + def media(self, old: dict, new: dict, where: str, *, request: bool) -> None: + for kind, old_media in old.get("content", {}).items(): + new_media = new.get("content", {}).get(kind) + if new_media is None: + self.errors.append(f"{where} removed media type {kind}") + elif "schema" in old_media or "schema" in new_media: + self.schema( + old_media.get("schema", True), new_media.get("schema", True), + f"{where} {kind}", request=request, + ) + + def operation(self, old: dict, new: dict, where: str, old_path: dict, new_path: dict) -> None: + left = _parameters(old_path, old, self.old) + right = _parameters(new_path, new, self.new) + for (location, name), parameter in right.items(): + previous = left.get((location, name), {}) + label = f"{where} {location} parameter {name}" + if parameter.get("required") and not previous.get("required"): + self.errors.append(f"{label} became required") + if previous and "schema" in parameter and "schema" in previous: + self.schema(previous["schema"], parameter["schema"], label, request=True) + + old_body = _resolve(old.get("requestBody", {}), self.old) + new_body = _resolve(new.get("requestBody", {}), self.new) + if new_body.get("required") and not old_body.get("required"): + self.errors.append(f"{where} request body became required") + self.media(old_body, new_body, f"{where} request", request=True) + for code, response in old.get("responses", {}).items(): + next_response = new.get("responses", {}).get(code) + if next_response is None: + self.errors.append(f"{where} response {code} was removed") + else: + self.media( + _resolve(response, self.old), _resolve(next_response, self.new), + f"{where} response {code}", request=False, + ) + + +def _parameters(path: dict, operation: dict, document: dict) -> dict[tuple[str, str], dict]: + result = {} + for raw in path.get("parameters", []) + operation.get("parameters", []): + parameter = _resolve(raw, document) + result[parameter["in"], parameter["name"]] = parameter + return result + + +def breaking_changes(old: dict, new: dict) -> list[str]: + check = _Comparison(old, new) + for path, old_path in old["paths"].items(): + new_path = new["paths"].get(path) + if new_path is None: + check.errors.append(f"{path} was removed") + continue + old_path, new_path = _resolve(old_path, old), _resolve(new_path, new) + for method in sorted(_METHODS & old_path.keys()): + label = f"{method.upper()} {path}" + if method not in new_path: + check.errors.append(f"{label} was removed") + else: + check.operation(old_path[method], new_path[method], label, old_path, new_path) + return check.errors + + +def required_client_version(body: str) -> str | None: + versions = [match[1] for line in body.splitlines() if (match := _OVERRIDE.fullmatch(line))] + if len(versions) == 1 and int(versions[0]) <= _MAX_ANDROID_VERSION_CODE: + return versions[0] + return None + + +def _pull_request_snapshot(event: dict) -> dict | None: + sha = event["pull_request"]["base"]["sha"] + if re.fullmatch(r"[0-9a-f]{40}", sha) is None: + raise ValueError("Expected the pinned base commit SHA from GitHub") + subprocess.run(["git", "cat-file", "-e", f"{sha}^{{commit}}"], check=True) + snapshot_path = "server/openapi-v1.json" + entry = subprocess.check_output(["git", "ls-tree", "--full-tree", sha, "--", snapshot_path]) + if not entry: + return None + return json.loads(subprocess.check_output(["git", "show", f"{sha}:{snapshot_path}"])) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument("--write", action="store_true", help="regenerate the v1 snapshot") + mode.add_argument("--base", type=Path, help="compare against a pinned base snapshot") + mode.add_argument("--pull-request", action="store_true", help="read GitHub's PR event") + args = parser.parse_args() + if args.write: + from app.main import app + + SNAPSHOT.write_text(v1_snapshot(app.openapi()), encoding="utf-8", newline="\n") + return 0 + + body = "" + if args.pull_request: + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_bytes()) + old = _pull_request_snapshot(event) + if old is None: + print("The pinned base predates the v1 OpenAPI snapshot.") + return 0 + body = event["pull_request"].get("body") or "" + else: + old = json.loads(args.base.read_bytes()) + + errors = breaking_changes(old, json.loads(SNAPSHOT.read_bytes())) + if not errors: + return 0 + + print(*errors, sep="\n") + version = required_client_version(body) + if version is not None: + print(f"Declared break requires MIN_CLIENT_VERSION={version}") + print("Verify that the rollout accounts for installed v1 clients before merging.") + return 0 + print("Add a V1-OpenAPI-Break declaration only for a deliberate rollout.") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/server/tests/test_announcements.py b/server/tests/test_announcements.py index af662fef..e6f7e6d3 100644 --- a/server/tests/test_announcements.py +++ b/server/tests/test_announcements.py @@ -31,6 +31,7 @@ from __future__ import annotations import ast +import asyncio import importlib from dataclasses import dataclass, field from datetime import date as Date @@ -43,6 +44,7 @@ import pytest from httpx import ASGITransport from sqlalchemy import delete as sa_delete +from sqlalchemy import select from app import telegram_send from app.api import edit @@ -51,8 +53,9 @@ from app.bot.handlers.content.overrides import override_cancel, override_clear, override_subject from app.config import get_settings from app.contract.lessons.v2 import homework_pb +from app.db import SessionLocal from app.main import app -from app.models import BotUser, DeviceToken, Homework, ReminderSettings, Role +from app.models import AuditEntry, BotUser, DeviceToken, Homework, ReminderSettings, Role from app.rpc import day as rpc_day from app.rpc import event as rpc_event from app.rpc import homework as rpc_homework @@ -369,6 +372,76 @@ async def create(text: str) -> str: assert FLOOD not in flooded +@pytest.mark.parametrize("transport", ["v1", "v2"]) +async def test_a_hung_subscriber_does_not_hold_the_committed_edit_open( + transport, api, v2, v2_tokens, session, school_class, monkeypatch +): + class_id = school_class.id + due = _tomorrow(school_class).isoformat() + for telegram_id in (7005, 7006): + session.add( + ReminderSettings(class_id=class_id, telegram_id=telegram_id, notify_homework=True) + ) + await session.commit() + + class SlowNotice(_Bot): + attempted = 0 + interrupted = False + closed = False + + async def send_message(self, chat_id: int, text: str, **kwargs: Any) -> None: + self.attempted += 1 + if self.attempted == 2: + try: + await asyncio.Event().wait() + finally: + self.interrupted = True + await super().send_message(chat_id, text, **kwargs) + + async def close(self) -> None: + self.closed = True + + bot = SlowNotice() + monkeypatch.setattr(edit, "_build_bot", lambda: bot) + monkeypatch.setattr(telegram_send, "build_bot", lambda: bot) + monkeypatch.setattr(telegram_send, "POST_COMMIT_NOTICE_SECONDS", 1.0, raising=False) + + async def save() -> int: + if transport == "v1": + response = await api.client.put( + "/api/v1/homework", + json={"due_date": due, "subject": "Алгебра", "text": "Page 12"}, + headers={"Authorization": f"Bearer {api.token}"}, + ) + return response.status_code + response = await v2.rest( + "HomeworkService/CreateHomework", + homework_pb.CreateHomeworkRequest( + homework=homework_pb.Homework(due_date=due, subject="Алгебра", text="Page 12") + ), + token=v2_tokens["editor"], + ) + return response.status + + try: + status = await asyncio.wait_for(save(), timeout=3.0) + except TimeoutError: + status = None + + async with SessionLocal() as fresh: + saved = await fresh.scalar(select(Homework).where(Homework.class_id == class_id)) + audit = await fresh.scalar( + select(AuditEntry).where( + AuditEntry.class_id == class_id, AuditEntry.action == "homework.add" + ) + ) + assert saved is not None and saved.text == "Page 12" + assert audit is not None + assert status == (200 if transport == "v1" else 201), "the request waited on Telegram" + assert bot.attempted == 2 and bot.interrupted and bot.closed + assert len(bot.sent) == 1 and "Page 12" in bot.sent[0][1] + + # -------------------------------------------------------------------------- # And nothing announces without being read here # -------------------------------------------------------------------------- diff --git a/server/tests/test_api_extended.py b/server/tests/test_api_extended.py index a5780727..22ab4c19 100644 --- a/server/tests/test_api_extended.py +++ b/server/tests/test_api_extended.py @@ -1631,6 +1631,77 @@ def now(cls, tz=None): assert settings.last_morning_sent == MONDAY +async def test_a_hung_cron_send_and_close_leave_later_reminders_due( + client, session, school_class, monkeypatch +): + _configure_cron(monkeypatch) + await _subscriber(session, school_class, 42, morning_at=time(7, 30)) + await _subscriber(session, school_class, 43, morning_at=time(7, 30)) + task = PersonalTask( + class_id=school_class.id, telegram_id=44, title="Notebook", + remind_at=datetime(2026, 9, 7, 7, 30), + ) + session.add(task) + await session.commit() + + class MondayMorning(datetime): + @classmethod + def now(cls, tz=None): + return datetime(2026, 9, 7, 4, 45, tzinfo=tz) + + close_released = asyncio.Event() + + @dataclass + class HungBot(FakeBot): + attempted: list[int] = field(default_factory=list) + close_interrupted: bool = False + + async def send_message(self, chat_id: int, text: str, **kwargs: Any) -> None: + self.attempted.append(chat_id) + await asyncio.Event().wait() + + async def close(self) -> None: + try: + await close_released.wait() + except asyncio.CancelledError: + self.close_interrupted = True + raise + + hung, healthy = HungBot(), FakeBot() + bots = iter((hung, healthy)) + monkeypatch.setattr(cron, "datetime", MondayMorning) + monkeypatch.setattr(cron, "REMINDER_SEND_SECONDS", 1.0, raising=False) + monkeypatch.setattr(cron.telegram_send, "POST_COMMIT_CLOSE_SECONDS", 0.2) + monkeypatch.setattr(cron, "_build_bot", lambda: next(bots)) + headers = {"X-Cron-Secret": CRON_SECRET} + request = asyncio.create_task(client.post("/api/v1/cron/tick", headers=headers)) + try: + first = await asyncio.wait_for(asyncio.shield(request), timeout=4.0) + except TimeoutError: + pytest.fail("the tick waited on Telegram") + finally: + if not request.done(): + close_released.set() + request.cancel() + await asyncio.gather(request, return_exceptions=True) + + assert first.status_code == 200, first.text + body = first.json() + assert (body["morning"], body["evening"], body["tasks"], body["failed"]) == (0, 0, 0, 1) + assert len(hung.attempted) == 1 and hung.close_interrupted + attempted = hung.attempted[0] + assert attempted in {42, 43} + waiting, = {42, 43} - {attempted} + await session.refresh(task) + assert task.remind_at == datetime(2026, 9, 7, 7, 30) + + second = await client.post("/api/v1/cron/tick", headers=headers) + assert second.status_code == 200, second.text + assert second.json()["morning"] == second.json()["tasks"] == 1 + assert [recipient for recipient, _ in healthy.sent] == [waiting, 44] + assert healthy.closed + + async def test_cron_tick_sweeps_stale_rows(client, session, school_class, monkeypatch, tick_bot): _configure_cron(monkeypatch) old = datetime.utcnow() - timedelta(days=3) diff --git a/server/tests/test_health.py b/server/tests/test_health.py index 19ae58b4..47c1c238 100644 --- a/server/tests/test_health.py +++ b/server/tests/test_health.py @@ -828,19 +828,30 @@ async def test_a_region_that_refuses_this_address_is_failing(monkeypatch, refusa assert result.hint == health.HINT_DIRECT -async def test_a_region_that_does_not_answer_is_failing_and_the_proxy_s_password_is_never_said( - monkeypatch, -): +async def test_a_refused_region_tunnel_tells_the_owner_to_check_the_proxy(session, monkeypatch): + session.add(_live("zabaikalsky")) + await session.commit() + _fake_proxy(monkeypatch, lambda request: httpx.Response(200)) + def refuse(proxy, request): raise httpx.ProxyError(f"403 Forbidden from {PROXY}") - _fake_routes(monkeypatch, refuse) - result = await health.check_diary_region( - regions.get("zabaikalsky"), Settings(DIARY_PROXY_URL=PROXY) + asked = _fake_routes(monkeypatch, refuse) + sent = Sent() + statuses = await health.run( + session, Settings(DIARY_PROXY_URL=PROXY), v2_mounted=True, send=sent ) - assert (result.status, result.reason) == (FAILING, "no answer through the proxy: ProxyError") - assert result.hint == health.HINT_PROXIED - assert "hunter2" not in result.reason + + assert (statuses["diary_proxy"], statuses["diary_region:zabaikalsky"]) == (OK, FAILING) + ((proxy, _),) = asked + assert proxy == PROXY + (alert,) = sent.texts + assert "Проверьте правила доступа (ACL) и авторизацию на прокси" in alert + assert "via_proxy" not in alert + assert "proxy refused the tunnel: ProxyError" in alert + reason = (await _rows(session))["diary_region:zabaikalsky"].reason + assert reason == "proxy refused the tunnel: ProxyError" + assert "hunter2" not in alert async def test_a_region_slower_than_its_budget_is_failing_and_says_it_timed_out(monkeypatch): diff --git a/server/tests/test_migration_merge_side.py b/server/tests/test_migration_merge_side.py new file mode 100644 index 00000000..1ea34ae6 --- /dev/null +++ b/server/tests/test_migration_merge_side.py @@ -0,0 +1,98 @@ +"""Keep new Alembic revisions on the compatible side of the merge (#642).""" + +from pathlib import Path +from textwrap import indent + +from scripts.check_migration_merge_side import migration_side_errors + +VERSIONS = Path(__file__).resolve().parents[1] / "migrations" / "versions" + + +def test_migrations_declare_the_side_their_upgrade_requires(): + errors = [ + f"{path.name}: {error}" + for path in sorted(VERSIONS.glob("*.py")) + if not path.name.startswith("_") + for error in migration_side_errors(path.read_text(encoding="utf-8")) + ] + assert not errors, "\n".join(errors) + + +def test_merge_side_policy_rejects_mixed_or_misdeclared_operations(): + create_table = 'op.create_table("new", sa.Column("id", sa.Integer, nullable=False))' + add_column = 'op.add_column("existing", sa.Column("optional", sa.Integer))' + add_required = 'op.add_column("existing", sa.Column("required", sa.Integer, nullable=False))' + not_null = 'op.alter_column("existing", "old", nullable=False)' + inline_check = ( + 'op.add_column("existing", sa.Column("optional", sa.Integer, ' + 'sa.CheckConstraint("optional IS NOT NULL")))' + ) + foreign_key_as_type = ( + 'op.add_column("existing", sa.Column("optional", sa.ForeignKey("parent.id")))' + ) + foreign_key_with_type = ( + 'op.add_column("existing", sa.Column("optional", ' + 'sa.ForeignKey("parent.id"), type_=sa.Integer))' + ) + foreign_key_as_name = ( + 'op.add_column("existing", sa.Column(sa.ForeignKey("parent.id"), ' + 'name="optional", type_=sa.Integer))' + ) + checked_boolean = ( + 'op.add_column("existing", sa.Column("optional", sa.Boolean(create_constraint=True)))' + ) + keyword_type = ( + 'op.add_column("existing", sa.Column(name="optional", type_=sa.String(length=80)))' + ) + unique = 'op.create_index("unique_old", "existing", ["old"], unique=True)' + drop = 'op.drop_table("obsolete")' + rewrite = 'op.execute("UPDATE existing SET old = 123")' + cases = [ + ("", create_table, ["MERGE_SIDE"]), + ('MERGE_SIDE = "after"', add_column, ["op.add_column", "before"]), + ('MERGE_SIDE = "after"', add_required, ["op.add_column", "classify"]), + ('MERGE_SIDE = "before"', inline_check, ["op.add_column", "classify"]), + ('MERGE_SIDE = "before"', foreign_key_as_type, ["op.add_column", "classify"]), + ('MERGE_SIDE = "before"', foreign_key_with_type, ["op.add_column", "classify"]), + ('MERGE_SIDE = "before"', foreign_key_as_name, ["op.add_column", "classify"]), + ('MERGE_SIDE = "before"', checked_boolean, ["op.add_column", "classify"]), + ('MERGE_SIDE = "before"', keyword_type, []), + ('MERGE_SIDE = "before"', unique, ["op.create_index", "after"]), + ( + 'MERGE_SIDE = "before"', + f"{create_table}\n{not_null}", + ["mixed", "op.create_table", "op.alter_column"], + ), + ('MERGE_SIDE = "after"', drop, ["op.drop_table", "DESTROYS"]), + ('MERGE_SIDE = "before"', "op.execute(make_sql())", ["op.execute", "classify"]), + ( + 'MERGE_SIDE = "before"\nfrom alembic.op import alter_column as tighten', + 'tighten("existing", "old", nullable=False)', + ["tighten", "after"], + ), + ( + 'MERGE_SIDE = "before"\nimport alembic as migration', + f"migration.{not_null}", + ["migration.op.alter_column", "after"], + ), + ( + 'MERGE_SIDE = "before"', + 'connection = op.get_bind()\n' + 'connection.exec_driver_sql("ALTER TABLE existing ALTER COLUMN old SET NOT NULL")', + ["connection.exec_driver_sql", "classify"], + ), + ('MERGE_SIDE = "before"', create_table, []), + ('MERGE_SIDE = "after"', rewrite, []), + ('MERGE_SIDE = "after"\nSQL = "UPDATE existing SET old = 123;"', "op.execute(SQL)", []), + ('MERGE_SIDE = "after"\nDESTROYS = "Removes the obsolete table and its rows."', drop, []), + ] + for metadata, upgrade, expected in cases: + source = ( + f"{metadata}\ndef upgrade():\n{indent(upgrade, ' ')}\n" + f"\ndef downgrade():\n {drop}\n" + ) + errors = migration_side_errors(source) + if expected: + assert all(fragment in "\n".join(errors) for fragment in expected), (source, errors) + else: + assert not errors, (source, errors) diff --git a/server/tests/test_openapi_v1.py b/server/tests/test_openapi_v1.py new file mode 100644 index 00000000..aad65512 --- /dev/null +++ b/server/tests/test_openapi_v1.py @@ -0,0 +1,76 @@ +"""The snapshot is generated from the app, and incompatible changes go red.""" + +from copy import deepcopy + +from scripts import check_openapi_v1 as contract + + +def test_v1_openapi_snapshot_matches_the_app(): + from app.main import app + + assert contract.SNAPSHOT.read_text(encoding="utf-8") == contract.v1_snapshot(app.openapi()), ( + "Regenerate with python -m scripts.check_openapi_v1 --write from server/" + ) + + +def test_openapi_v1_detects_breaks_in_a_request_and_referenced_response(): + request = { + "type": "object", + "properties": {"term": {"type": "integer"}, "school": {"type": "string"}}, + "additionalProperties": False, + } + schema_ref = {"$ref": "#/components/schemas/Bundle"} + operation = { + "requestBody": {"content": {"application/json": {"schema": request}}}, + "parameters": [{"in": "query", "name": "year", "schema": {"type": "integer"}}], + "responses": {"200": {"content": {"application/json": {"schema": schema_ref}}}}, + } + old = { + "paths": {"/api/v1/bundle": {"post": operation}, "/api/v1/removed": {"get": {}}}, + "components": { + "schemas": { + "Bundle": { + "type": "object", + "properties": {"name": {"type": "string"}, "score": {"type": "number"}}, + }, + }, + }, + } + new = deepcopy(old) + del new["paths"]["/api/v1/removed"] + changed = new["paths"]["/api/v1/bundle"]["post"] + changed_input = changed["requestBody"]["content"]["application/json"]["schema"] + changed_input["required"] = ["term"] + changed_input["properties"]["term"]["multipleOf"] = 2 + del changed_input["properties"]["school"] + changed["parameters"][0]["required"] = True + fields = new["components"]["schemas"]["Bundle"]["properties"] + fields["renamed"] = fields.pop("name") + fields["score"] = {"type": "integer"} + + errors = "\n".join(contract.breaking_changes(old, new)) + expected = ( + "/api/v1/removed", "request field term", "query parameter year", + ".name", ".score", ".school", "multipleOf", + ) + for text in expected: + assert text in errors, errors + + compatible = deepcopy(old) + compatible["components"]["schemas"]["Bundle"]["properties"]["extra"] = {"type": "string"} + assert not contract.breaking_changes(old, compatible) + + +def test_openapi_break_declaration_is_data_and_requires_one_positive_version_code(): + declaration = "V1-OpenAPI-Break: MIN_CLIENT_VERSION=123" + assert contract.required_client_version(f"Notes\n{declaration}\n") == "123" + assert contract.required_client_version("V1-OpenAPI-Break: MIN_CLIENT_VERSION=2100000000") + for body in ( + declaration + " && anything", + f"{declaration}\n{declaration}", + "V1-OpenAPI-Break: MIN_CLIENT_VERSION=0", + "V1-OpenAPI-Break: MIN_CLIENT_VERSION=2100000001", + "V1-OpenAPI-Break: MIN_CLIENT_VERSION=34567890123456789012", + "V1-OpenAPI-Break: MIN_CLIENT_VERSION=$(anything)", + ): + assert contract.required_client_version(body) is None diff --git a/server/tests/test_sqlite_transactions.py b/server/tests/test_sqlite_transactions.py index 74d4f7b9..478a416c 100644 --- a/server/tests/test_sqlite_transactions.py +++ b/server/tests/test_sqlite_transactions.py @@ -2,8 +2,7 @@ The suite and a local development server run on SQLite; production runs on Postgres, and ``app/db.py`` is where the two are kept agreeing on whatever the -code depends on. These tests hold the two places where the driver's own -transaction handling did not. +code depends on. These tests hold the transaction behavior the app relies on. pysqlite, and aiosqlite over it, begins a transaction before an INSERT, an UPDATE or a DELETE and before nothing else. A ``SAVEPOINT`` sent while no @@ -37,18 +36,22 @@ from __future__ import annotations +import sqlite3 +from contextlib import closing from datetime import UTC, datetime, time, timedelta from types import SimpleNamespace from typing import Any import httpx +import pytest from aiogram.fsm.storage.base import StorageKey from sqlalchemy import func, select +from sqlalchemy.exc import OperationalError from app.api import cron from app.bot.middlewares import ContextMiddleware from app.config import Settings, get_settings -from app.db import SessionLocal +from app.db import SessionLocal, engine from app.fsm_storage import DatabaseStorage, FsmRecord from app.main import app from app.models import AuditEntry, BotUser, DeviceToken, ReminderSettings, Role @@ -90,6 +93,51 @@ async def test_a_rollback_takes_back_a_savepoint_that_opened_the_transaction( assert await _committed(stored) is None, "a rollback kept a savepoint's write" +@pytest.mark.parametrize("explicit_rollback", [True, False], ids=["rollback", "context-close"]) +async def test_a_refused_commit_cannot_leak_into_a_reused_sqlite_connection( + school_class, explicit_rollback +) -> None: + if engine.dialect.name != "sqlite": + pytest.skip("SQLite's rollback-journal lock is needed") + database = engine.url.database + assert database is not None + refused = hash_token("refused-commit") + unrelated = hash_token("unrelated-commit") + + # The raw reader takes no slot in the app pool. With an empty pool the + # next session must receive the writer's connection. + await engine.dispose() + try: + with closing(sqlite3.connect(database, timeout=0)) as reader: + async with SessionLocal() as failed: + connection = await failed.connection() + await connection.exec_driver_sql("PRAGMA journal_mode=DELETE") + await connection.exec_driver_sql("PRAGMA busy_timeout=0") + driver = (await connection.get_raw_connection()).driver_connection + + reader.execute("BEGIN") + reader.execute("SELECT id FROM device_tokens").fetchall() + failed.add(DeviceToken(token_hash=refused, class_id=school_class.id)) + await failed.flush() + with pytest.raises(OperationalError, match="database is locked"): + await failed.commit() + if explicit_rollback: + await failed.rollback() + reader.rollback() + + async with SessionLocal() as fresh: + connection = await fresh.connection() + assert (await connection.get_raw_connection()).driver_connection is driver + fresh.add(DeviceToken(token_hash=unrelated, class_id=school_class.id)) + await fresh.commit() + + stored = reader.execute("SELECT token_hash FROM device_tokens").fetchall() + assert stored == [(unrelated,)] + finally: + # Drop the connection whose busy timeout the test shortened. + await engine.dispose() + + async def test_an_update_s_conversation_is_written_after_the_middleware_has_read( session, school_class ) -> None: diff --git a/server/tests/vectors/diary_protocol.json b/server/tests/vectors/diary_protocol.json index f71326db..7577e669 100644 --- a/server/tests/vectors/diary_protocol.json +++ b/server/tests/vectors/diary_protocol.json @@ -140,7 +140,28 @@ ], "cases": [ {"body": [{"id": 1, "name": "Школа № 5", "addressString": "ул. Ленина, 1"}, {"id": true, "name": "x"}, {"id": "5", "name": "y"}, {"id": 2}], "expect": [{"id": 1, "name": "Школа № 5", "address": "ул. Ленина, 1"}]}, - {"body": [{"id": 3, "name": " Лицей № 2 ", "addressString": " "}, {"id": 4, "name": " "}, {"id": 5, "name": 7}, {"id": 6.0, "name": "z"}, "row"], "expect": [{"id": 3, "name": "Лицей № 2", "address": null}]}, + { + "body": [ + {"id": 3, "name": " Лицей № 2 ", "address": " ", "addressString": " "}, + {"id": 4, "name": " "}, + {"id": 5, "name": 7}, + {"id": 6.0, "name": "z"}, + "row", + {"id": 7, "name": "Школа № 7", "address": " ул. Мира, 3 ", "addressString": "старый адрес"}, + {"id": 8, "name": "Школа № 8", "address": " ", "addressString": " ул. Мира, 4 "}, + {"id": 9, "name": "Школа № 9", "address": 17, "addressString": "ул. Мира, 5"}, + {"id": 10, "name": "Школа № 10", "address": null, "addressString": "ул. Мира, 6"}, + {"id": 11, "name": "Школа № 11", "address": " ул. Мира, 7 ", "ogrn": "0000000000000"} + ], + "expect": [ + {"id": 3, "name": "Лицей № 2", "address": null}, + {"id": 7, "name": "Школа № 7", "address": "ул. Мира, 3"}, + {"id": 8, "name": "Школа № 8", "address": "ул. Мира, 4"}, + {"id": 9, "name": "Школа № 9", "address": "ул. Мира, 5"}, + {"id": 10, "name": "Школа № 10", "address": "ул. Мира, 6"}, + {"id": 11, "name": "Школа № 11", "address": "ул. Мира, 7"} + ] + }, {"body": {"error": 1}, "expect": "unexpected"} ] } diff --git a/tools/console/README.md b/tools/console/README.md index 24398bb6..71a1effe 100644 --- a/tools/console/README.md +++ b/tools/console/README.md @@ -91,6 +91,10 @@ for pyvoy and hypercorn; a single backend is not a matrix pass. Local isolated c absolute test/config paths and private reports replace CI's background process and log-file shell mechanics. The CI inventory records those equivalents explicitly. +GitHub's v1 OpenAPI comparison uses the pull request event and its exact base +revision. The local server suite checks that the stored snapshot matches the +current application. + Signing status runs only the safe `:app:releaseSigningStatus` task through the heavy queue. It reports presence and missing setting names, never credentials or paths. The action captures a safe immutable string from the already-resolved four signing diff --git a/tools/console/lessons_console/ci_contract.json b/tools/console/lessons_console/ci_contract.json index d922c6d7..8bdbd9d1 100644 --- a/tools/console/lessons_console/ci_contract.json +++ b/tools/console/lessons_console/ci_contract.json @@ -116,7 +116,9 @@ { "identity": "step-0", "action": "actions/checkout@v7", - "with": {}, + "with": { + "fetch-depth": 0 + }, "if": "success()", "cwd": "server", "env": {}, @@ -159,6 +161,15 @@ "env": {}, "continue-on-error": false }, + { + "identity": "Check v1 OpenAPI compatibility", + "run_sha256": "1bd60ce928b78bbc6386b1addc6692382d5ddb693158f414e343b3fd64bf048c", + "if": "github.event_name == 'pull_request'", + "cwd": "server", + "env": {}, + "continue-on-error": false, + "reason": "GitHub supplies the pull request event and exact base revision. Local pytest checks snapshot freshness." + }, { "identity": "Test", "run_sha256": "20d6767ac1118a16905b6987ad1a889b7bd08df730eac42f9b1e4ee14347da27", diff --git a/tools/console/lessons_console/parity.py b/tools/console/lessons_console/parity.py index deadf607..59af6421 100644 --- a/tools/console/lessons_console/parity.py +++ b/tools/console/lessons_console/parity.py @@ -16,7 +16,12 @@ "ci": "Aggregates remote job results; there is no equivalent local remote-results gate.", "console": "The console's own tests; never recursively launch the console suite.", } -SKIPPED_STEPS = {("host", "The host's log"): "Owned Runner streams the Host output instead of reading CI's background log file."} +SKIPPED_STEPS = { + ("host", "The host's log"): "Owned Runner streams the Host output instead of reading CI's background log file.", + ("server", "Check v1 OpenAPI compatibility"): ( + "GitHub supplies the pull request event and exact base revision. Local pytest checks snapshot freshness." + ), +} def inventory(root: Path) -> dict: