Skip to content

Read «Сетевой город» as a second diary, and let a phone in through its own school's diary - #140

Merged
lumenpearson merged 30 commits into
mainfrom
claude/school-diary-api-routes-cc4o1n
Sep 26, 2026
Merged

lumenpearson merged 30 commits into
mainfrom
claude/school-diary-api-routes-cc4o1n

Conversation

@lumenpearson

@lumenpearson lumenpearson commented Sep 24, 2026 •

Copy link
Copy Markdown
Owner

Description

Ready to merge once CI is green on the head. Every review finding is fixed. The last one was #165, which the owner decided on 26 September: corrections are shared per child. It is fixed in e01443d. The migrations this code needs, 0015, 0016 and 0017, are on production since 26 September, 12:26 UTC. They went on in one transaction through the Neon connector, before the merge, and destroyed nothing: production held 0 diary corrections and 0 diary sessions. Until this merges and deploys, /api/v1/warmup answers «База впереди кода…».

1. «Сетевой город» as a second diary, server side (#139, commits 4c34cb5…42fdf0a, answering #135). A class is bound to a diary rather than to Petersburg. The bot writes, the API reads, and families sign in on the same web form.

2. A way in through your own school's diary (#141, from 17c0473). The first run ends in a choice: the class code, as before, or your own school's diary.

  • The diary path, step by step:

    • Region, found by its name or by the school's name, over all 89 regions.
    • School.
    • The region's diary systems, with the recommended one marked and a «Почему?» that explains it.
    • The diary's own sign-in, made from the phone to the diary. The password never reaches this server.
    • An import with a progress bar.
    • A summary of the settings, the class and the pupil.

    Under «Продолжить» is the acceptance line, «Продолжая, вы принимаете Условия использования и Политику конфиденциальности».

  • Server:

    • POST /api/v1/diary/session registers a session the phone opened itself. The server validates it with its own upstream read and seals it with Fernet.
    • GET /api/v1/diary/capabilities.
    • X-Diary-Unavailable: disabled | address-refused | upstream on every diary 503.
    • JoinResponse.diary, the class's diary binding.
    • A catalog of all 89 regions and the systems each runs, generated from docs/diaries/regions.md.
    • GET /api/v1/directory/school-regions, an anonymous school-name search. It is throttled per caller and capped at 4,000 of DaData's 10,000 requests a day, counted in usage_counters (0016).
    • The «Сетевой город» keep-alive runs only in the cron tick.
  • Android:

    • Kotlin ports of both sign-ins, talking only to https origins from the bundled catalog, with no redirects and no cookie jar.
    • diary.db, with write-through under a generation guard.
    • Three shell modes: no class, class, and diary only, the last with a home of its own.
    • The widget's diary-only state.
    • The periodic class sync, armed in class mode only.
  • Legal:

    • docs/legal/{terms,privacy}.{ru,en}.md, bundled in the APK and linked from the first run and «О приложении».
    • LESSONS_LEGAL_BASE_URL becomes BuildConfig.LEGAL_BASE_URL: https only, one per fork, passed by apk.yml and documented in docs/build.md.

3. Corrections shared per child (#165, e01443d). A session registered from a phone names its own login, and nothing upstream vouches for it. Corrections were filed under that login, so another adult whose diary listed the same child could name a family's login and read or rewrite its corrections.

  • The owner's decision: corrections are the child's. They are shared by everyone whose own diary lists the child, both parents and the pupil's own account included, and reached only through that list.
  • The key is CHILD:petersburg, or CHILD:netschool: plus the host of the region's diary server, together with the pupil id. The login is display-only.
  • The upper-case prefix: no key can equal an old one.
  • Pupils outside the diary's own numbering: a Petersburg child listed by a plain id instead of identity.id gets no corrections at all, and «Сетевой город»'s JSON true is no longer pupil 1.
  • 0017 is data only: it files old rows under the child.
  • Texts: the privacy policy, the terms, the phone's correction note and the docs say the same in both languages.

Reviews. Every finding below survived two independent refuters. Each code fix came with a test that failed without it; a fix to documentation was checked against the code instead, because no test can fail on prose.

A finding that already existed on main got its own issue before its fix (#161, #163). The others were in code this branch adds.

Also fixed here, each filed first:

Deliberately excluded:

Closes #136
Closes #137
Closes #138
Closes #139
Closes #141
Closes #145
Closes #146
Closes #147
Closes #148
Closes #149
Closes #150
Closes #151
Closes #152
Closes #153
Closes #154
Closes #155
Closes #157
Closes #158
Closes #159
Closes #160
Closes #161
Closes #162
Closes #163
Closes #164
Closes #165

One stays open: #156 has its fix in ce9c749, but only the XML is tested and it is labelled needs:device.

A correction to commit 6fa1c6e's body: it says rebinding a class to another school expires the class's diary sessions. expire_off_binding expires them when the provider or the region changes, and keeps them for another school in the same region. The documents follow the code.

What is affected

Also new: server/app/providers/{diary,netschool}/, server/app/catalog/, docs/legal/.

Boundaries

  • app/schedule.py still imports neither FastAPI nor aiogram
  • The rule did not appear in two places. /diary/login and /diary/session open their row through one services/diary._open_row, and the region catalog has one source, read by both the server and the phone
  • A model change comes with an Alembic revision: 0015 (eight nullable columns), 0016 (usage_counters), and 0017, which is data only and re-files the corrections under the child. EXPECTED_REVISION is 0017, and there is no create_all after 0001. All three are applied to production: 26 September, 12:26 UTC, one transaction, read before and after.
  • Nothing is scheduled "in process". The keep-alive runs in /api/v1/cron/tick, and the phone does no background diary read
  • "Now" is taken in the class's time zone, and for a diary session in the diary's zone
  • :core:data does not depend on :widget
  • Every new Russian string has its English twin in values-en/
  • There is no token, class code, password or keystore path in the diff

Verification

cd server  && ruff check app tests scripts migrations → All checks passed!
cd server  && python -m mypy                           → Success: no issues found in 100 source files
cd server  && pytest -q -n auto                        → 2024 passed (on SQLAlchemy 2.1.1, as CI installs)
cd android && ./gradlew test                           → 1408 tests, 0 failures (968 on main)
  • ./gradlew assembleDebug
  • ./gradlew assembleRelease
  • Checked on a device or an emulator — no
  • The widget checked at two sizes at least — no

CI: green on e01443d (Server, Android). The run on the head, which changes only documents, decides the merge.

What is NOT covered

  • Nothing has met a live diary. «Сетевой город» has never been signed in to for real, on the server or through the phone's port, and neither has Петербург through the phone. Both follow open-source clients and a shared set of known-answer vectors, run by both the Python and the Kotlin tests. The vectors prove that the two implementations agree, not that either one is right.
  • Whether a session opened on a phone survives being replayed from Frankfurt is open for both diaries. A 409 is the designed failure, and the owner's first live session decides it.
  • Nothing has run on a device. That covers the first run, the swap between the three homes, the browser handoffs, the backup exclusion (Crash reports go into the Google cloud backup although the first run says they «остаётся на телефоне» #156), TLS against the regional servers, and Android's windows-1251.
  • DaData. Its region_kladr_id on company rows, the codes of the four regions admitted in 2022, and its day turning at Moscow midnight are all unverified.
  • The throttles' record-then-count (The join and diary sign-in throttles count before they record, so a burst of parallel requests goes past the limit #163) is proven on SQLite only. No alembic run has been made against a real empty PostgreSQL.
  • Unverified for A diary session registered from a phone names its own login, unchecked, and that login is the key to another family's corrections #165: that a «Сетевой город» pupil id is unique per server rather than per school, and that two parents' accounts see one child under one id. No live answer has ever been seen. 0017's lock was proven on a scratch PostgreSQL 16, not on Neon, where there were no rows to lock against.
  • An APK built from main before this branch still says «Правка меняет только то, что вы видите здесь», while the server now shares corrections per child. Nothing has ever been tagged or released. An APK built on demand by apk.yml from main would carry that sentence until it is replaced.
  • The legal texts have never been read by a lawyer.

Documentation

Milestone: 10, v0.9.0 — NetSchool e-diary, onboarding via the school's diary.

🤖 Generated with Claude Code

https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS

The diary talked to one upstream, Петербург's, through modules that named its
classes directly. This adds the shape a second provider can meet, and the
second provider's core, without changing what Петербург does.

- app/providers/diary/ holds what every provider shares: the models, the error
  family, the DiaryProvider/DiaryConnection protocols and the SignInRequest
  they take, the HTTP client whose cookie jar keeps nothing so two families'
  sessions never meet, and the registry that maps a stored key to an
  implementation and reads a class's binding in one place.
- app/providers/petersburg keeps every public name as a re-export of the very
  objects now defined in diary/, so PetersburgError is DiaryError and nothing
  that imports the old names breaks. Its behaviour is unchanged; a new
  petersburg/provider.py wraps the existing client and mapper behind the
  contract. The dead DiaryAccount is gone (#138).
- app/providers/netschool/ reads «Сетевой город»: a region allow-list that is
  the only source of an origin (so no client input becomes a URL), the
  password sign-in every open client performs (windows-1251 salted md5), the
  weekly diary mapped onto the shared models with homework as assignment type
  3, keep-alive, a working logout, and a credential that holds the session but
  never the password.

Tested against a mock transport and hand-written payloads: a sealed session
carries no password, a wrong password is BadCredentials, a Госуслуги-only
region refuses before any password is sent, a blocked address is its own
error, the token never rides in a URL, and two families' cookies never meet.
Nothing has been tried against a live server (#121, #135).

This is the seam and the core only; the service dispatch, the schema, the bot
binding and the keep-alive follow. Part of #139.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…ther

The diary service built a Petersburg client directly; now it opens whichever
provider the session row names and calls it through the shared connection
contract, re-sealing a rotated credential on the way out (even when the answer
that carried it failed to map, so the next call does not replay the old one).
"today" comes from the provider, so «Сетевой город» gets its region's zone.

Corrections are still keyed by the login, but a «Сетевой город» login is
unique only on its own regional server, so for any provider but Petersburg the
key folds in the provider and region through a hash — Petersburg's key is the
bare case-folded login, unchanged, so every correction filed before stays
matched. Signing out now tells the upstream goodbye where it can be told;
«Сетевой город» has a logout that works without a browser and Petersburg does
not, so its connection's close is a no-op.

- POST /api/v1/diary/login accepts an optional provider, region and school.
  Absent provider is Petersburg, so an older phone is unchanged. A «Сетевой
  город» region must be an allow-listed, password-capable key and the school a
  positive id, both checked before any upstream call; a Госуслуги-only region
  or a blocked address answers 503 and the login limiter does not count it.
- Revision 0015 adds diary_sessions.provider/region and the keep-alive clocks,
  and classes.diary_region/diary_school_id/diary_school_name — seven nullable
  columns, additive, applied before the merge, with a rollback step that
  expires non-Petersburg sessions first. EXPECTED_REVISION is 0015.

Part of #139. The bot binding, the web form's provider text and the cron
keep-alive follow.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
#136: revoking a member left their diary sessions and any unspent sign-in
ticket in the class. A session is reached only by (telegram_id, class_id), so
after revocation nobody could sign it out, and with the coming keep-alive it
would be held live upstream for the family for thirty days. The revoke handler
now signs those sessions out (telling «Сетевой город» goodbye where it can be
told) and drops the tickets, beside the connect codes and subscriptions it
already dropped.

#137: the sign-in form trusted the class's binding from when the ticket was
minted. It now reads the binding at both the GET and the POST, before spending
anything: a class unbound or rebound since the link was made refuses with 410
rather than sending the password to a diary the family is no longer looking at.
The form's subtitle names the provider — and, for «Сетевой город», the region
and school — every part escaped, because the school name comes from the
upstream. Petersburg's page is byte-for-byte what it was.

The web form's error mapping gains «Сетевой город»'s errors: a Госуслуги-only
region or a blocked address hands the ticket back (nothing looked at the
password), and an expired-password message is passed through rather than
flattened to «неверный пароль».

Closes #136
Closes #137
Part of #139.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
A NetSchool session idles out in fifteen minutes to an hour, and this project
stores no password to sign back in with, so the tick pings each live one with
GET /webapi/context — the call every open client keeps a session alive with.

- It claims a batch first, stamping keepalive_attempted_at whatever the
  outcome, so a failing origin cannot sit at the head of the queue and starve
  the healthy ones, and two overlapping ticks never ping the same row (FOR
  UPDATE SKIP LOCKED on Postgres).
- It pings with no database transaction held open, then writes each outcome
  back with a guarded UPDATE that matches nothing if the row was signed out or
  its credential rotated meanwhile — no lost update, no StaleDataError.
- It never touches last_used_at, so the 30-day purge of a session nobody opens
  still fires; a dropped session (401) is expired, a down or blocking origin is
  left for next tick.
- Its deadline counts from the start of the request, and it runs last inside
  its own try/except, so a slow morning of digests shortens it and a diary
  fault never fails the tick (which would redden the fallback clock).

It needs the external cron (#120); GitHub's fallback clock is too sparse to
keep a session alive. The netschool client is closed in the lifespan beside
the others. Part of #139.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
«📒 Привязать дневник» is no longer a single toggle: with a second provider it
opens a chooser. Petersburg binds in one press, as before; «Сетевой город» asks
for the region, then a school. The region step probes the region's sign-in
options first (`login_allowed`) so an admin learns once that a Госуслуги-only
region cannot be bound, rather than every family finding out at sign-in, and the
school step searches the region server by name and offers what it found. The
pick carries an index into the searched list held in FSM data, checked against
that list where it is read — never an id trusted from the client. Every step
re-checks the role, including the school-name message handler, because FSM state
is per-user and attacker-controlled.

The read path is now provider-neutral. `_bound` and the class card read the
registry's `binding()` rather than the raw column, so a class bound to a region
since dropped from the allow-list reads «не привязан» instead of a dead name;
`_session_for` is keyed on the class's *current* provider, so after a rebind a
session opened against the old upstream becomes a clean «войдите снова» rather
than a screen that silently talks to the diary the class left; and the sign-in
card names whichever diary is bound, in the genitive, since a card that always
said Petersburg would be wrong for the other.

Adds `schools_search` to the «Сетевой город» client for the binding flow, and
`diary_provider_menu` / `diary_region_menu` / `diary_school_menu`, capped at one
constant so what is drawn is what can be pressed.

Uncovered: nothing here has been run against a real «Сетевой город» server — the
search endpoint path and the login-options probe are written from research, and
the first live sign-in is the owner's (#121/#135). Part of #139.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
… have

Found while mapping the diary code for the second provider, each checked by
hand (#138):

- `services/diary_link.py` said the bot keeps a type-it-to-the-bot fallback for
  a deployment with no public URL. There is no such path — without
  `PUBLIC_BASE_URL` the bot says the sign-in page cannot be opened and stops —
  and the comment invited someone to «restore» a password in the chat history.
- `main.py` said deferring the provider close-imports keeps all of them off the
  cold-start path. Measured: the API surface already loads Petersburg's and
  DaData's clients at module scope, so the deferral saves nothing for them; only
  «Сетевой город»'s client, loaded lazily through the registry, is genuinely
  kept off a process that never binds a class to it. The comment now says that.
- `bot/diary_keyboard.py` said `offset` is the period index for «marks». «marks»
  ignores `offset` and always shows the last thirty days; «homework» reads a
  fixed window too.
- `models.DiarySession`: `login` is not «for the signed-in-as line and nothing
  else» — a family's corrections are keyed on it (`owner_key`); and `telegram_id`
  is set by the bot's sign-in ticket, not «a linked device», and is NULL for the
  phone's login. The class docstring no longer claims the session is Petersburg's.

The two dead diary names (`DiaryService.lessons`, `providers/petersburg.
DiaryAccount`) were already removed with the seam. Closes #138.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
CLAUDE.md, the migration skill and the providers agent still described a
one-diary world with the head at 0014. They now carry the diary seam
(`providers/diary/` with its registry and `binding()`), «Сетевой город» behind
it (the region allow-list as the SSRF guard, the password sign-in, the cron
keep-alive, and that nothing here has met a live server), and revision `0015`:
additive, seven nullable columns for the provider, region, keep-alive clocks and
the class binding, on before this batch's merge, with a NULL provider meaning
Petersburg. The test count moves from 1634 to 1668.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
Brings the documents into line with the «Сетевой город» batch, in the same
batch as the code the skill on this project requires:

- architecture.md — rewrites "Somebody else's service behind one door" around
  the `providers/diary/` seam: the shared models, errors, contract and registry,
  the two providers behind it, why Petersburg went behind it byte-for-byte, and
  the region allow-list as the SSRF guard. Services count 19 → 21.
- api.md — the electronic diary is provider-neutral; documents the optional
  provider/region/school_id on `POST /diary/login` and the tick's three
  keep-alive counters; warmup schema 0014 → 0015.
- bot.md — the binding chooser (region probe, school search), the sign-in card
  naming the bound diary, the submit-time binding re-check (#137), the logout
  asymmetry.
- deploy.md — 0015 in the chain with its downgrade caveat, head 0015, the
  keep-alive as a dependency of the external cron.
- diaries.md / diaries/netschool.md — the platform decision is made and the
  server side is written, with the "never run live" caveat kept.
- README.md — the electronic diary row and the honest status now name «Сетевой
  город» as written server-side, never run; production head 0015.

Corrects the counts that drift: tests 1634 → 1668, mypy modules 84 → 97, and
the `0015` docstring's summary "Seven" → "Eight" nullable columns (its own
bullet list already named all eight). HANDOVER.md carries the batch's close-out.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
@vercel

vercel Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
lessons Ready Ready Preview Sep 26, 2026 12:29pm UTC

The phone's new first run needs to list every region, find one by a nickname or
a city, say which diary its schools use and which of those can be signed into.
None of that existed outside prose. `scripts/region_catalog.py` now builds
`server/app/catalog/data/regions.json` from the survey's evidence file
(`docs/diaries/regions.md`, cross-checked against the table in `docs/diaries.md`)
plus a hand overlay, `scripts/region_catalog.toml`, for what the survey does not
carry: keys, two-digit subject codes, English names, zones, aliases, cities, and
the spellings DaData uses.

- The 19 «Сетевой город» keys are the allow-list's own, byte for byte: they are
  already stored in `classes.diary_region`, `diary_sessions.region` and the
  sealed credential. Origin, password and verified are copied from
  `regions.py`, never typed, so the phone and the server read one allow-list.
- `action` and the recommendation are worked out here and nowhere else. Only
  Петербург and the 16 password «Сетевой город» regions are `signin`. ТОР «Моя
  школа» and the three Госуслуги-only «Сетевой город» regions are a `handoff`
  to the browser, never a sign-in, because a Госуслуги session is the person's
  whole state-services account (#135). A test fails if any field or text about
  an in-page sign-in reaches the catalog.
- Region names live in the JSON, with `name_en` mandatory and tested, so the
  89 × 2 names do not become string resources; the why-texts will be resources
  keyed by the reason codes this emits.
- `--check` and `test_the_committed_catalog_is_what_the_generator_writes` fail
  when the survey or the allow-list changes without a regeneration.

Unverified: the subject codes 90, 93, 94 and 95 (marked in the overlay), every
DaData spelling, and that each `web_url` host answers on https.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…ink to

The owner asked for a line under the first screen's button saying that
continuing accepts the terms and the privacy policy, linked to documents in the
build's own repository. The documents did not exist. `docs/legal/` now holds
both, Russian first (`*.ru.md`, the source, like `values/`) with English
translations, in the Markdown subset the app's guide reader already parses, plus
`legal.json` with the edition and the date it takes effect. The app will bundle
them as a fallback and open them from the first screen and from «О приложении».

They describe what this code does and nothing more, and say plainly what a
reader would otherwise assume:
- the password goes only to the diary from the app, but still crosses the
  server on the bot's sign-in page and from older apps;
- the operator holds the key the diary sessions are sealed with, so can read the
  diary; hosting is Frankfurt, not Russia;
- leaving a class deletes nothing on the server (the device row goes 180 days
  after it was last seen); corrections, the audit log and tasks have no expiry;
- the «Сетевой город» keep-alive runs for up to 30 days after the last real use,
  and only foreground use counts;
- an `http://` server address carries the diary session in the clear; the app
  warns and does not refuse.

Each passage that describes the upstream deployment sits under a `FORK:` comment
naming the fields a fork must rewrite (operator, contact, hosting, country, …).
Not legal advice: whether naming a GitHub account as operator satisfies 152-ФЗ,
cross-border transfer, the age line and parental consent are for the owner and a
lawyer, and the text claims no compliance with any of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…hat exposed

The phone is about to sign in to Петербург and «Сетевой город» itself, so the
password never reaches this server (#141). What it then needs is a door that
takes the session the diary handed it, instead of the password.

`POST /api/v1/diary/session` is that door. The body is one of two models chosen
by `provider`, with `extra="forbid"` everywhere: a `password` key is a 422. Every
credential value is checked against the one definition of "safe to put in a
header" (`providers/diary/http.py`), because cookie values go straight into
`Cookie:` and a `;` would inject a second one. The server then reads with the
session once from its own address — Петербург's pupils, or «Сетевой город»'s
four bootstrap calls, which fill the year and type fields a sealed credential
cannot work without — seals it through the same `_open_row` as `sign_in`, and
returns our token, the pupils and the diary's zone (`zone_for`, the same rule
`today()` uses). It shares `/login`'s limiter and bucket, so ten wrong passwords
do not buy ten more tries by session. A session the diary refuses from here is a
409, not `/login`'s 401 + reauth: asking for the password again would loop, and
what failed is where the session came from. 422s no longer echo the refused
value back. `GET /api/v1/diary/capabilities` tells the phone, before any
password is typed, whether the diary is on and which regions this server
serves. Every diary 503 now says why in `X-Diary-Unavailable`. `POST /diary/login`
is otherwise unchanged, for older apps.

`JoinResponse` gains `diary`, the class's binding through `registry.binding()`,
so a phone joining a bound class can sign in without searching.

The shared known-answer vectors (`tests/vectors/diary_protocol.json`) pin both
sign-in protocols for the Kotlin port to be tested against; the Python side is
driven over `httpx.MockTransport`. Adopting them forced the fixes below.

- #145 The bot read a «Сетевой город» region its class had left: `_session_for`
  matched the provider only, and rebinding expired nothing. One clause,
  `reads_binding`, now decides; binding another region or school expires the
  sessions it no longer reads (`expire_off_binding`); unbinding does not.
- #146 The keep-alive could overwrite a credential a read rotated while the ping
  was in flight: the write-back now matches only the sealed value it claimed.
  The per-origin breaker its comment promised now exists, per tick.
- #147 A sign-in without `cacheVer` stored and sent the word "None" as `ver`.
- #148 Malformed «Сетевой город» answers — an array from `logindata`/`login`, a
  non-ASCII or null salt, a non-integer `timeOut`, an unreadable role question —
  escaped as 500s. They are diary errors now.
- #149 The school search kept a row whose id was JSON `true`; it also keeps the
  address now.
- #150 (part) `Region.ca_bundle`, read by nothing, is gone; the source-order
  comment and the password-path docstrings are corrected. The user-facing texts
  and docs of that issue follow.

Not linked to the bot (#143): a phone's session carries no Telegram account or
class. Unverified: whether either diary accepts a session opened on a phone
when replayed from this server's address — 409 is the designed answer; and the
four bootstrap calls against Vercel's 30-second ceiling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
… the bot's allowance

The owner asked that typing a school's name on the first run's region screen
list the regions it may be in (#141). DaData is the only nationwide source, and
its key must never be in the APK, so the phone asks the server:
`GET /api/v1/directory/school-regions?q=`, anonymous.

- Each hit is placed by the two-digit code of DaData's `region_kladr_id`, then by
  its region text against the catalog's `dadata_names`; one the catalog cannot
  place comes back with DaData's own label. Hits are grouped by region, best
  rank first, with a few cities and example names each, and a branch in another
  region is no longer folded into its head's row.
- A name that is only a type word and a short number («Школа № 5», «СОШ 12»)
  exists in every region. It is answered `generic` without calling DaData, and
  so is a truncated answer spread over many regions: the phone then says so and
  asks for the region instead. The stop words come from the catalog, so the
  phone and the server read one list.
- Anonymous means two limits. Every call past validation counts against the
  caller (`JoinThrottle.record`, 20 per 15 minutes; the window is 900 s like
  every throttle on that table, because its pruning is global, and a test pins
  it). And a daily allowance: 4,000 of DaData's 10,000 requests, counted per
  Moscow day in the new `usage_counters` table (`services/quota.py`, one atomic
  INSERT … ON CONFLICT … WHERE … RETURNING). The empty-answer retry is charged
  too, and skipped when nothing is left. The bot's and `/manage/schools`'
  searches are unchanged and never charged to it, so onboarding cannot use up
  the search the bot's create-class step depends on.
- Every 503 says which case in `X-Directory-Unavailable: disabled | spent |
  upstream`, with `Retry-After` until Moscow midnight when the day is spent.

Migration `0016` creates `usage_counters` and nothing else: additive, destroys
nothing, and goes on with `0015` before #140 merges. `EXPECTED_REVISION` is
`0016`.

Unverified: whether DaData's party rows carry `region_kladr_id` (the name
fallback exists for that), the codes 90/93/94/95, DaData's own day boundary, and
two requests racing for the last unit on Postgres (checked on SQLite only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…ght to the diary

Three texts people read just before typing a password said it went «прямо в
дневник» and that the bot never saw it (#150). The page posts it to this
server, which passes it to the diary for the sign-in and writes it down
nowhere. The page's note, the signed-out card and the card with the sign-in link
now say exactly that, still in one breath with «не в чате» and «нигде не
сохраняется», which remain true. A test fails on any of the old wording, and the
existing password test now also checks the logs, which that wording relies on.
The texts say nothing about the app's own sign-in, which sends the password
straight to the diary: an older app still posts it here, and the page cannot
tell which one the reader has.

The page's fallback for an answer it cannot read also named dnevnik2 whatever
the class was bound to, so a «Сетевой город» family was sent to Петербург's
diary to see whether theirs was down (#158). It now names the bound diary's own
host, from the allow-list.

`providers/diary/__init__.py`'s docstring describes the package as it now is,
including both ways a session arrives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…og and the anonymous school directory

The server half of #141 is in, and the documents that own each part now say
what it does:

- docs/api.md: `POST /api/v1/diary/session` and `GET /api/v1/diary/capabilities`,
  with both body shapes, every status and why "the diary refused this session
  from our address" is a 409 rather than a 401; `X-Diary-Unavailable` on every
  diary 503, `/diary/login`'s included; `JoinResponse.diary`; and
  `GET /api/v1/directory/school-regions` with its throttle, its share of DaData's
  day and `X-Directory-Unavailable`. The paragraph saying the app never talks to
  either diary is replaced: there are now two ways in and one API after.
  `/diary/login` stays, and says plainly that it receives the password.
- docs/diaries.md: no Госуслуги sign-in and no WebView, and why (a Госуслуги
  session is the whole state-services account); the region catalog as generated
  data, its inputs, and the reason codes. docs/diaries/regions.md says which of
  its lines the generator parses.
- docs/architecture.md, docs/bot.md, docs/deploy.md, docs/README.md: the
  phone-registered session, the catalog, the quota table and why it counts per
  Moscow day; the bot's new sign-in wording (#150), the regional host in the
  unreadable-answer text (#158), rebinding expiring sessions (#145); DaData
  counted at two requests on an empty answer (#150); 0015 and 0016 still to be
  applied before #140 merges.
- README, CLAUDE.md, the migration skill: head 0016, 1915 server tests, 100
  mypy modules, the honest status of registration and the directory. CLAUDE.md
  also names `/diary/session` as a source of the diary token and no longer
  calls the sealed credential Petersburg's alone.

Left for the Android half's documents, because each is true of today's app and
becomes false when native sign-in lands: docs/build.md's «Why HTTP and not
HTTPS» (the wire carries a password today on /diary/login, and will not from
the new app), docs/design.md's «the app does not talk to dnevnik2», and
docs/guide.md's diary section. The Android test count is untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…sion, and keep what it reads

The data half of #141, in :core:data. The password now goes from the phone to
the diary's own origin and nowhere else; our server receives the session the
diary handed back, validates it with a call of its own, seals it, and answers
with our diary bearer. The app no longer calls `POST /api/v1/diary/login`.

Sign-in (wave A1):
- `upstream/`: a provider HTTP client with none of our interceptors, no cookie
  jar and no redirects, whose only hosts are the https origins in the bundled
  region catalog (`OriginGuard`); Kotlin ports of the Petersburg and «Сетевой
  город» sign-ins, the windows-1251 table and the pw/pw2 hash carried in the
  code rather than trusted to the device's ICU; the phone-side school search
  against the region's own server. `UpstreamSession` lives in memory and is spent
  once registered or discarded.
- The region catalog is `server/app/catalog/data/regions.json`, bundled in
  place as an asset, never copied; every case of
  `server/tests/vectors/diary_protocol.json` runs through the Kotlin code from
  the test classpath, over MockWebServer sockets where the case is a request,
  so the two implementations cannot drift apart silently.
- `DiarySignIn` runs preflight (catalog, then `/diary/capabilities`), the diary
  sign-in, then `POST /api/v1/diary/session` with `credential`, and keeps only
  our bearer and a `DiaryTarget` (provider, region, school, login, zone; stored
  as one JSON key). A bare 401 now clears the token only (`clearDiaryToken`);
  signing out forgets the account (`forgetDiary`).
- `DiarySignInProblem` is the one failure type every diary screen will switch
  on. It carries the phone half of #153: a 429 is a throttle, a 503 is read by
  `X-Diary-Unavailable`, a 504 or a socket timeout is a timeout, a 409 is «the
  diary refused this session from our address» with no automatic retry, a 422
  is an app bug. The screen half of #153 is not done: the settings screen still
  draws three of these with one stand-in text.
- The diary bearer is kept off `/diary/login`, `/diary/session` and
  `/diary/capabilities`; the class bearer off `/api/v1/directory/*` and
  `/api/v1/diary/*`. Neither interceptor had a test; both do now.
- Settings → «Дневник» signs in through `DiarySignIn` with the stored target,
  or Petersburg when none is stored. Every :app test now uses one shared
  `FakeDiaryRepository`.

What it keeps (wave A2):
- `diary.db`, a second Room database (schema exported), written only by
  `DiaryRepositoryImpl`'s successful reads, with a generation guard so a read
  in flight during a sign-out is not written back after the clear.
- `DiaryImport`: pupils, choice of pupil, terms, timetable, homework and marks,
  with weighted progress for the import screen, skippable phases and resume
  from the one that failed; `refreshIfStale` with a 30-minute freshness is the
  only refresh, driven by the app coming to the foreground.
- `RegionSearch` over the 89 regions in Russian and English, aliases, cities,
  codes, the wrong keyboard layout and transliteration, and `SchoolDirectory`
  over `GET /api/v1/directory/school-regions` with its own `DirectoryProblem`.
- `ShellMode` (none, class, diary) with the rule that arms periodic class sync
  only in class mode — the data half of #152 — and a diary-only phone as a mode
  of its own rather than the join screen — the data half of #151. Neither issue
  is closed until the app wires them.
- `JoinResponse.diary` is kept on the stored session as the class's binding.
- `SyncWorkerSourceTest` fails if the worker or the widget ever names the
  diary's repository, cache or import: there is no background diary read.

Gates: `./gradlew test` 1187 JVM tests (968 before), `assembleDebug` and
`assembleRelease` green; the only new Cyrillic in Kotlin is `UpstreamMarkers.kt`,
the diaries' own words matched in their answers.

Not covered: nothing has met a live diary or run on a device. Whether a diary
accepts a session opened on a phone when our Frankfurt server replays it is
open; 409 is the designed failure. TLS against the regional servers, Android's
own windows-1251, Room on a device, and a Retry-After given as a date (read as
no wait) are unverified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…ne or not

The first screen is to say «Продолжая, вы принимаете Условия использования и
Политику конфиденциальности», and a sentence like that is only honest if both
documents open wherever the phone is. This adds the pieces for it; placing the
line on the onboarding screen is the onboarding part's.

- LESSONS_LEGAL_BASE_URL / lessons.legal.baseUrl becomes BuildConfig.LEGAL_BASE_URL.
  The build refuses a value that is not https, carries a query or fragment, or
  would break the generated Java string, rather than keeping it: it is the first
  link of every install. With nothing set it defaults to docs/legal on the
  repository's default branch (blob/HEAD), so a fresh clone links a real,
  current document. apk.yml resolves the folder of whichever repository it runs
  in, overridable by a repository variable, checks it before compiling, passes
  it to the build and prints it in the summary. The property and the step land
  together, as BuildPropertyReachTest requires.
- docs/legal/ is mounted as an asset folder of :app, so the APK carries the one
  copy that is published. A small reader in :core:data (core/data/.../legal)
  opens it with the guide's own parser and reads legal.json for the edition and
  date; the "ru, otherwise en" rule is lifted out of DocsRepositoryImpl into
  docsLanguage() so the guide and the policy cannot pick different languages.
- ui/legal: LegalAcceptanceLine (always drawn, small, under the button, both
  names links) and LegalOpener, which opens the current edition in the browser
  when there is an address and a validated network and a browser starts, and
  otherwise the bundled copy in a sheet that names its edition. The links are
  LinkAnnotation.Clickable so every tap can fall back; the sentence is one
  template with placeholders, because aapt2 trims the spaces at a string's
  edges. The sheet draws the sections through the guide's block renderer,
  moved unchanged from DocsScreen.kt into DocsBlocks.kt so the two texts cannot
  be drawn two ways.
- «О приложении» gains two rows for the documents through the same opener.
- #155: the design credit was three strings and aapt2 trimmed the space before
  the link, so the card read «по мотивамEssentials» / "afterEssentials". It is
  one template now, and StringEdgeSpaceTest refuses any string with a bare space
  at its edge in any module or language.
- #156: CrashReporter writes to getExternalFilesDir("crash_reports") (or
  filesDir/crash_reports) and neither backup rule file excluded it, while the
  first run says a report stays on the phone. Both locations are now excluded
  from the pre-12 backup, the cloud backup and a device transfer, and
  BackupRulesTest reads both XML files and the reporter's folder name. The
  privacy policy's paragraph about the phone said crash reports may reach the
  backup; it now says they are excluded. legal.json stays at edition 1:
  nothing has been published.

Tests: LegalDocumentsTest and LegalLinksTest in :core:data (the shipped texts'
parity, links, markers, manifest, and no asset-name collision across docs/app,
docs/legal and the region catalog); LegalAcceptanceLineTest,
LegalDocumentSheetTest (including that the APK's assets really carry all four
files), LegalBuildPropertyTest, BackupRulesTest, StringEdgeSpaceTest and two
AboutCardTest cases in :app.

Not covered: nothing here has run on a device — not the backup exclusion
(#156 needs a phone and bmgr), not the browser handoff or its fallback, not
TalkBack on the inline links, not the sheet with a long document. The line is
not yet on the onboarding screen. docs/build.md, README and the CI path filter
for docs/legal are the docs part's; the build's error message already points
at docs/build.md. The texts were never reviewed by a lawyer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
@lumenpearson
lumenpearson marked this pull request as ready for review September 25, 2026 18:01
@lumenpearson lumenpearson changed the title Read «Сетевой город» as a second electronic diary, server side Read «Сетевой город» as a second diary, and let a phone in through its own school's diary (in progress) Sep 25, 2026
…own folder

The "What changed" filter decides which halves run from the paths a push
touched, and four server tests already on main read documents outside
`server/`: `docs/deploy.md` is compared with the settings by
test_deployment_config, test_database_url and test_roles, and
`docs/build.md` with `.env.example` by test_env_example. A commit touching only
one of those documents ran nothing and came back green (#159) — the failure
`docs/app/` once had, which the Android case already carries a comment about.

This branch widened the gap. `docs/diaries.md` and `docs/diaries/*` feed
test_region_catalog and test_netschool_mapper; `:app` bundles `docs/legal/`;
and the region catalog and the protocol vectors live under `server/` but are
Android inputs — the catalog is the phone's allow-list of diary hosts, bundled
in place, the vectors are DiaryProtocolVectorsTest's resource — so an edit to
either ran the server job alone. Both cases now name every file their tests
read, with the reason beside them.

Closes #159

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…give a diary-only phone a home of its own

The screen half of #141, on top of the data layer in b19e6b2.

The first run (ui/onboarding):
- «Продолжить» on the first screen, with «Продолжая, вы принимаете Условия
  использования и Политику конфиденциальности» under it, always drawn.
- After the introduction and the permissions, two ways in: the class code, as
  today (the real JoinScreen), or your own school's diary. That path is REGION
  (all 89 regions searched on every keystroke from the bundled catalog; a school
  name asks the server's directory after a pause and answers with the regions it
  may be in; «Школа № 5» is too common and asks for the region instead) →
  SCHOOL (for «Сетевой город», searched on the region's own server) → PROVIDER
  (the region's systems, the recommended one highlighted, with «Почему?» keyed
  by the catalog's reason codes; ТОР and the three Госуслуги-only regions open
  the official site; a system the app cannot read says so and offers the class
  code) → SIGN_IN (a card names the host the password goes to; the password lives
  only in the form, the diary's session only in a plain field of the step, never
  in SavedStateHandle) → IMPORT (an animated wavy progress bar over the import's
  weighted phases, a pupil chooser, resume from the phase that failed) → SUMMARY
  (the main settings, the class if any, the pupil).
- The flow is a saved path of steps (OnboardingFlow, pure functions); the shell
  is held on the flow through a join or a registration and released on finish.
- The server address is asked where it is first needed; no default server is
  promised any more — the join screen, settings and ServerUrlSheet no longer say
  «По умолчанию — сервер класса» (#154, app half), and the comments describe the
  flow as it is (#157, code half).

The shell (navigation, settings, ui/diary):
- A pure gate over the shell mode: no class and no diary → the first run; a
  class → the timetable home; a diary and no class → the diary as the home, with
  settings that keep «Дневник» and «Выйти из дневника» (#151). A cold start
  settles the mode once before the gate first reads.
- Periodic class sync is armed only in class mode (#152): LessonsApplication
  collects the shell mode's arming instead of scheduling on every settings
  emission.
- Every diary failure has its own words through one mapping, DiaryProblemText:
  too many attempts, a switched-off diary, a diary that refuses our server, a
  timeout, each naming the host where it has one; «Повторить» only where a retry
  can help (#153, screen half).
- The diary draws what the phone saved first, keeps it when the diary cannot be
  reached and says when it was saved; the one unprompted diary read is the
  refresh when the app comes to the foreground in diary mode.
- The sign-in texts no longer say the password reaches our server or travels in
  the clear over an http:// server — with native sign-in it goes over https to
  the diary only; the network-security comment says what does cross an http
  server (the session and the bearers).
- LessonsWavyProgress is public in :core:designsystem; DiaryZone is gone and
  every diary date is taken in the diary's own zone.

Two things r11 had listed were checked against main before this commit and do
not reproduce there (the first-run acknowledgement's promise, and the motion
setting during the introduction); the new flow honours LocalMotion anyway.

Gates: `./gradlew test` 1350 JVM tests (1236 before), `assembleDebug` and
`assembleRelease` green; no new Russian in Kotlin.

Not covered: nothing composes LessonsApp in a test, so the gate, the hold
through a join, the swap to the right home and the resume after process death
are covered by the pure rules and the view models only. Nothing has run on a
device or against a live diary: not the handoffs, not the import with real
timings, not TalkBack. The in-app guide and docs/design.md still describe the
old first run; they are the documentation's to fix, and #154 and #157 stay open
until they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…s tests able to fail

An adversarial review of the new Android data layer (b19e6b2, ce9c749)
confirmed twelve findings that are this part's. Each is fixed here with a
test that was run against the code before the fix, or against the fix
mutated back, and failed there.

[0] UpstreamHttp.classify called every SSLHandshakeException Untrusted, so
a handshake the network reset («Connection reset by peer», «Connection
closed by peer», the JVM's «Remote host terminated the handshake») told the
person their phone did not trust the diary and offered no retry. Only a
failure that examined the certificate is Untrusted now: a
CertificateException, CertPathValidatorException or CertPathBuilderException
in the cause chain, or SSLPeerUnverifiedException. UpstreamHttpTest's new
«a handshake the network broke is unavailable» failed on the old rule; the
trust cases (Android's shape, the JVM's PKIX, an expired certificate, a
hostname mismatch) are held beside it.

[1] The phone trimmed a login where the server's _clean_login_value also
drops every character Python's isprintable refuses, so a login pasted with
bidi isolates or a zero-width space went upstream as pasted and read as a
wrong password. DiaryLogin.clean is the one port, by code point; both
sign-ins, openUpstream, the registration body and the stored target use it.
The new «login» block of diary_protocol.json (17 cases) is run by
test_login_cleaning_matches_the_vectors (through DiaryLoginIn and
PetersburgSessionIn) and by the Kotlin vectors test, which also asks both
sign-ins what they sent; that and DiarySignInTest's pasted-login test failed
with the sign-ins mutated back to trim().

[2] UpstreamJson.parse took kotlinx's unquoted literals for JSON, so
«<html>» on getdata was «unavailable» and {"at": abc} a wrong password where
the server says «unexpected». It now refuses any literal json.loads refuses
(NaN and Infinity stay, as in Python), walking with its own stack.
netschool.raw_answer_cases (11 cases) is run by both sides; the Kotlin run
failed on {"schoolLogin": False} before the fix.

[3] RegionSearch found nothing for «St Petersburg», «Moscow region»,
«Chuvashia» and the like. Fixed in the catalog data, regenerated with the
generator: [search.synonyms] (st → saint, region → oblast|krai), translit
pairs for the English endings (iya, ia, iy, yy, tsk), and «Zabaikalye»,
«Zabaykalye», «Primorye» as aliases. «oblast» is still not a stop word, and
a test says why. RegionSearchTest's fifteen queries failed on «St
Petersburg» first; test_region_catalog gains the synonyms and translit
checks.

[4]+[8] The Tomsk zone test used an instant Moscow also calls Monday. It
now uses 19:30 UTC on a Sunday and asserts the absent Moscow plan too, and
refreshIfStale has the same test; both failed with the zone hard-coded to
Moscow.

[7] The refresh-during-import test now asks while the import's schedule
request is in flight, with a stored pupil; it failed with the tryLock
removed and with run()'s withLock removed.

[9] SeedingDiarySignIn is tested through a sign-in that clears the cache
first, as the container's does, on both the signIn and register paths; it
failed with the generation taken before the registration and with the seed
a no-op.

[10] DiarySignInTest records forget, select and write in one list and
asserts their order; it failed with the write moved first.

[11] SyncWorkerSourceTest reads every application, receiver and service
the manifests declare, LessonsApplication included, and still passes; it
failed with a diaryImport reference added to LessonsApplication.onCreate.

[12] BackupRulesTest now fails on any storage root in CrashReporter other
than its two known expressions; it failed with a third write to filesDir.

[13] The failing-directory test uses «Казань №», which is both a school
query and a place, and asserts byName and suggested survive; it failed with
RegionLookup dropping the catalog's answer on failure.

Not done here: [5] (the diary strings) and [6] (the CI path filter) belong
to other parts. The phone does not yet refuse a login longer than the
server's 200 characters (a 422 at registration); nothing here has met a
live diary, and the TLS shapes are the ones Conscrypt and the JVM are known
to throw, not ones observed on a device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…e and the join, each with a test that fails without its fix

A second adversarial review of the screens (c032ff2, 9c797a2, fb8a70c) had 31
findings survive two independent refuters each; all 31 are fixed here. One of
them already existed on main and has its own issue (#161); the rest are in
code this pull request adds.

The ones that mattered most:
- Backing out during «Передаём сессию серверу…» cancelled the phone's request
  while our server went on to adopt the session, leaving a sealed diary
  credential nobody could sign out of, and a second sign-in minted another.
  Back, «Не сейчас» and «начать заново» are now refused while a sign-in is
  under way; the diary sign-in and the registration run to their end whatever
  the screen does, a session opened after a leave is ended at the diary, and a
  registration that lands after a cancel keeps its bearer so the server row
  always has a key.
- A join whose screen was gone before it landed left its result behind, and
  the next «Добавить класс» sheet closed itself on it; in the first run the
  stale result could finish the flow and skip the class's diary sign-in
  (#161). Every join now reports under a ticket its own screen keeps; back is
  held while a code is out.
- A diary view model left from an earlier diary home chose the pupil during a
  later import, so a two-child family never saw the chooser. The import now
  asks only while nothing holds the shell.
- The diary home's sign-out sheet promised «сервер забудет свою копию входа»
  unconditionally; offline the logout is skipped. It now says what happens
  offline, and the privacy policy's promise is unchanged because it already
  said so.
- The «Войти ещё раз» sign-in after the diary ended an import had no way out;
  it now offers «Выйти из дневника и начать заново». A restore after process
  death no longer reopens a form over a credential written in the background.

And the smaller ones: «Забыли пароль?» named the region picked earlier rather
than the diary the password goes to, and said nothing on a phone with no
browser; the school step ignored a new name for the same region; the import
and the diary home offered «Повторить» where a retry cannot help (a 502 among
them); «Почему?» for an unreachable region recommended that region's diary;
the summary promised a class family that opening the app keeps the diary
sign-in alive, in a one-line marquee; the login field trimmed on every
keystroke; the generic-name note promised a school step most regions do not
have; a passing directory failure read as «search does not work on this
server»; failures in the first run pointed at «Синхронизация», which the flow
cannot reach; «Вход выполнен» stayed after a lapsed sign-in; a second first
run pre-filled the signed-out login; UpstreamJson still accepted raw control
characters inside strings. Five tests that passed without their feature now
check it (the region row's match, the pupil chooser, the summary's content,
the widget's mode read), and the in-app guide says what the import and the
summary now do, identically in both languages.

Gates: `./gradlew test` 1408 JVM tests (1371 before), `assembleDebug` and
`assembleRelease` green; the shared protocol vectors 128 passed on the server.

Not covered: nothing composes the real shell swap or the sign-in page in a
test, so the join's disposal race and the no-browser line are held by the view
models and pure rules; nothing has run on a device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
… on, each with a test that fails without its fix

An adversarial audit of the server half of #140 and of revisions 0015/0016
had 22 findings survive two independent refuters each; 21 are fixed here. One
of them already existed on main and has its own issue (#163); the rest are in
code this pull request adds. The migrations themselves were compared op by op
with the DDL the models produce and do not change on PostgreSQL.

The ones that mattered most:
- A «Сетевой город» 5xx or 429 error page was read as a dead session, so an
  outage upstream would have signed every family out, through the keep-alive
  and through any read. A status of 500 and above, or 429, is now «the diary is
  down» (503, session kept) whatever the body says; a non-JSON 2xx still means
  the session is gone.
- The keep-alive checked its deadline before waiting for a slot, so pings went
  on starting past it and a hanging region could push the cron tick over
  Vercel's 30 seconds; the deadline is checked after the slot and every ping
  runs under a hard stop, so the results are always written.
- A «Сетевой город» session kept the school year it was opened in and read an
  empty diary after it ended; a read past the sealed year asks for the current
  one again, at most once a diary-day.
- Registrations were never counted, so one real session could mint unlimited
  kept-alive rows; a limiter now counts every session opened through /login or
  /session, and the keep-alive claims the stalest rows first so fresh ones
  cannot starve a family's.
- The throttles counted before they recorded, so a burst of parallel requests
  went past them — 24 wrong passwords reached the diary against a limit of 10
  (#163). Every door now records first and counts after.

And: a weekly answer that is not an object, a body that will not decode, and a
years/current without a usable year were 500s or a 200-then-401 loop; they are
502/503 now, refused at registration where they would loop. The bot's page no
longer tells a family whose account has no pupil that the diary «ответил
непонятно», nor a Госуслуги-only region to «попробуйте ещё раз». 0015 now
works on an existing SQLite database and on an empty PostgreSQL that 0001
already built, and its downgrade no longer leaves a class looking bound to
Petersburg; its PostgreSQL upgrade is unchanged, and a new test pins it to the
model as test_quota does for 0016. Seven tests that could not fail now can: the
cron tick calling the keep-alive, the protocol vectors' credential fields, the
directory's own bucket, the invisible-to-the-bot check, and the Postgres
statements of the quota and the throttle, which are now compiled in tests.

Left open, on purpose, for the owner: a session registered from a phone names
its own login and nothing upstream vouches for it, while corrections are filed
under that login — so a second account that can see the same child could claim
the first account's login and reach its corrections. Every fix is a product
choice (whose corrections a phone sees), and it is put to the owner rather
than decided here.

Gates: ruff clean, mypy clean (100 files), pytest -n auto 1998 passed (1944
before). Not run: alembic against a real empty PostgreSQL (the permission
system refused a local server), and the throttle's atomicity on PostgreSQL,
which rests on READ COMMITTED.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…nstall now gets

The pin is `>=2.0.54` with no ceiling, so CI and Vercel resolve 2.1.1 while
a checkout made before 2.1 was published keeps 2.0.54. Two checks read the
two versions differently (#164).

The Postgres upsert test compared the compiled statement word for word, and
2.1 writes a cast after every bind parameter on that dialect
(`%(used_2)s::INTEGER`). The statement is right on both; the casts are now
taken out before the shape is compared, so the test asks what it meant to:
one insert, one guarded update, one RETURNING.

mypy stopped being clean on main: 2.1 types the rows of a two-entity select,
so `remind_at` reaches the comparison as `datetime | None`. The query's WHERE
already refuses a NULL; the guard says so where the checker can see it, and
changes nothing at run time.

Pinning `<2.1` would test something production no longer runs. The whole
suite passes on 2.1.1: ruff clean, mypy clean over 100 modules, 1998 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…roject filters on

Dependabot asked for `dependencies`, `android`, `server`, `vercel` and `ci`,
none of which exists, and it skips a missing label without a word — so
every bump it ever opened arrived bare. The two issue templates applied
GitHub's untouched `bug` and `enhancement`, so a report filed from the
new-issue page landed outside `type:` and `status:` and no view built on
them listed it (#162).

Bumps now carry `type:chore` and the `area:` their ecosystem lives in; a
bug report `type:bug` and a proposal `type:feature`, both `status:next` so
a new one has a status before anybody reads it. No `area:` on the
templates: the reporter cannot know which half is at fault, and a guess
there is worse than none.

Not covered: whether GitHub's board auto-add picks these up is the
owner's filter, which a session here cannot read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…, and the migrations held for it

HANDOVER's schema paragraph promised to be replaced with a time and an
outcome. The outcome, for now, is that `0015` and `0016` have not run and
are held on purpose. The owner allowed them on the condition that the code
has no known defect, and #165 is one: a session registered from a phone
names its own login, and corrections are filed under it. Its fix is the
owner's product decision, and the first answer was withdrawn before it
touched a file. The opening now says what stands between #140 and the
merge, in order. The defect table carries #161 to #165, and the issue
ranges and the close/stay-open lists follow it.

The counts are the measured ones in all four places that quote them:
server 1998 (run on SQLAlchemy 2.1.1, which CI and Vercel install), and
Android 1408, whose test tasks Gradle found up to date against the current
sources. The per-module split in docs/architecture.md moves with it.

Not covered: the grep for Russian in Kotlin was not re-run, and no Kotlin
has changed since it last was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
@lumenpearson lumenpearson changed the title Read «Сетевой город» as a second diary, and let a phone in through its own school's diary (in progress) Read «Сетевой город» as a second diary, and let a phone in through its own school's diary Sep 26, 2026
…ne names reaches nothing its own diary does not list

A session registered from a phone names its own login, and nothing upstream
vouches for it; the corrections were filed under that login, so another
adult whose diary listed the same child could name the first family's login
and read or rewrite its corrections (#165). The owner decided on 26
September that the corrections are the child's: shared by everyone whose own
diary lists the child — both parents, and the pupil's own account — and
reached only through that list.

- The key is `child_scope(provider, region)`: `CHILD:petersburg`, or
  `CHILD:netschool:` and the host of the region's diary server, since a
  «Сетевой город» pupil is numbered per server — a region that moves server
  loses its corrections rather than handing them to whoever carries the same
  number there. It lives in the column still called `login`; no schema
  change. The upper-case prefix means no key can equal an old one, which is
  always a lowercased login, so code reverted to main can neither read nor
  write a per-child row.
- The routes build the key from the session's diary, never from its login,
  after `_student` has found the child among this session's own pupils; the
  store refuses anything that is not a scope. Reset-all stays bounded by the
  child.
- Two children can no longer share a key: a Petersburg child listed by a
  plain `id` instead of `identity.id` gets no corrections at all (a 422 on
  write, nothing laid over its reads), and «Сетевой город»'s JSON `true` is
  no longer pupil 1 or class 1.
- `0017` is data only. It deletes the branch-only «Сетевой город» hash-keyed
  rows, keeps the newest row where two logins corrected one field of one
  child, and files the rest under the child, after a lock on PostgreSQL.
  Its docstring gives the count of what each step deletes, and why, on a
  deployment that holds corrections, it goes on just after the merge.
  Production held 0 corrections and 0 diary sessions when read on 26
  September, so there it rewrites nothing and goes on with 0015 and 0016.
- The privacy policy and the terms in both languages, the phone's
  correction note, docs/api.md, docs/guide.md, docs/deploy.md, CLAUDE.md,
  README, AGENTS.md and the migration skill say what is now true: shared per
  child, a reset removes it for everyone, the last writer wins, no row says
  who wrote it, and a deletion request can be met per child or per named
  correction. Legal edition 1 was never published, so it is edited in place.

An adversarial review of this change (five lenses, two refuters per finding)
confirmed 17 of 23 findings; all 17 are fixed here, each with a test that
failed without it or, for the documentation ones, with the text made true.

Gates: ruff clean, mypy clean (100 files), pytest -n auto 2024 passed (1998
before) on SQLAlchemy 2.1.1; ./gradlew test 1408, rerun after the last text
edit; the alembic chain from nothing lands on 0017.

Not covered: that a «Сетевой город» pupil id is unique per server rather
than per school, and that two parents' accounts see one child under one id
in either diary, have never been observed live. 0017's lock was proven on a
scratch PostgreSQL 16, not on Neon.

Closes #165

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS
…nds before its merge

The owner allowed the migrations on the condition that the code had no known
defect; with #165 decided and fixed in e01443d and CI green on it, they went
on at 12:26 UTC on 26 September, as one transaction through the Neon
connector, before the merge. The database was read first (head 0014, none of
the eight columns, no usage_counters, 0 corrections, 0 diary sessions, 1
class) and read back after: head 0017 with one stamp, the eight columns
nullable with the declared types, usage_counters keyed (scope, day), and
still 0 corrections and 0 sessions — nothing rewritten, nothing destroyed.
Every statement came from the revisions rendered offline for PostgreSQL,
which matched the models' DDL.

HANDOVER's opening, schema chapter, defect table, gates and cheat-sheet say
so, with #165 closed by e01443d and the counts from the real runs (server
2024, Android 1408). README, CLAUDE.md, docs/deploy.md and the migrations
agent move from «to be applied» to «applied». Until #140 deploys,
/api/v1/warmup answers «База впереди кода…», the window the correct order
creates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XJRt8CRnXdvW7Myc1tvsDS

This branch was successfully deployed

1 active deployment
Preview — 4c1e8c12 Deployed Sep 26, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

2 participants