Commits
Commits on
69d4295dd558b3b2b267ec4b040ae0effce52e372026-09-18
✨ feat(rag): relay rag.summarize and rag.questions over the bridgeAhmet Kaan Gümüş · 69d4295
✨ feat(rag): relay rag.summarize and rag.questions over the bridge The RAG service has had two study features the backend never dispatched: a scope summary and a set of generated practice questions, each one-shot and addressed to exactly one (sınıf, ders) corpus. - constant.rs: AI_RAG_SUMMARIZE_CAPABILITY / AI_RAG_QUESTIONS_CAPABILITY with 25 s deadlines — a waiting door must finish under the 30 s request envelope; MAX_RAG_QUESTIONS is published at /limits. - ai/rag_study.rs: the two payload/reply contracts and their dispatch, wire-key pinned. - web/rag.rs: POST /rag/summarize and POST /rag/questions over the same QUIC bridge and the same 503 capability gate as the rest of the nest. The asker's (sınıf, ders) pairs come from their memberships; the body only names a target inside them (403/400 otherwise). An abstention is a complete 200; only role_required/scope_mismatch — the backend's own bug — is a 502. README endpoints table regenerated; AI bridge prose extended with both contracts and the honest RAG-side limits. Local-Gate: 852ea13260383ac5c071fce412db110becbcbdde (1505 passed, 473s)
✨ feat(insight): send the school's class names with the report payloadAhmet Kaan Gümüş · 49f9665
✨ feat(insight): send the school's class names with the report payload
The live document printed raw class UUIDs under its Şube header: the
summaries' own evidence carries class ids, so the renderer had nothing else
to print. A machine identifier on the most human-facing artifact we ship is
exactly the defect the report exists to remove.
Additive payload key `classes: [{id, name}]` — a sibling of `school`, not a
member of it: it is a lookup for the rows, not part of the school's identity.
Read whole from the school's own `class_group` in name order (tens of rows);
a class a row names but the list does not carry is absent on purpose, and the
renderer falls back to an honest label rather than a name invented here. The
row lists are untouched.
Pinned in the payload contract test (the encoded JSON carries `classes`) and
in the round-trip test (a class created through `POST /classes` arrives with
its name).
Local-Gate: c07c6c1e530a9d2924068b3471ee5dbc2c98fd93 (1497 passed, 451s)🐛 fix(insight): size the report deadline under the request envelopeAhmet Kaan Gümüş · 8ce2e1d
🐛 fix(insight): size the report deadline under the request envelope Two verifier flags, one cause: the report door waits on its dispatch inside one HTTP request, and the request-timeout middleware (30 s) drops the handler future wherever it stands — mid-write included — answering its own 503 whose "the write may or may not have applied" prose is wrong for a door that knows nothing was stored, while a drop inside the store window stranded a `.report-<uuid>.tmp`. `AI_INSIGHT_REPORT_TIMEOUT_SECS` drops 300 → 25, so the service loses the race on purpose and the door's own error path fires first: the honest "nothing was stored" 503, and no temp is ever opened. The constant's comment now states the relationship and that raising it needs the ceiling raised with it; the row reads before the dispatch share the same envelope, which is why the margin is not spent elsewhere. Pinned as a compile-time assertion beside the report contract tests: a raised deadline without a raised ceiling fails the build, proven by flipping the value to 30 (E0080, the message) and reverting. Local-Gate: c92220e9d9b886dc45b86b88c2ff7ecc6a54ce7a (1497 passed, 443s)
📄 feat(insight): render and serve a school-level report documentAhmet Kaan Gümüş · 541d9b7
📄 feat(insight): render and serve a school-level report document
`insight.report` is the third outbound ZEKA dispatch, and the first that
carries its data: the service may not read a school database, so the backend
reads its own `zeka_*` rows (four new school-wide bulk reads, projected
straight into the serde rows the storage surface already writes) and sends
them in the request. The service renders, the backend stores.
* `POST /insights/runs/{run_day}/report` — manager+, synchronous: build the
payload, dispatch with `AI_INSIGHT_REPORT_TIMEOUT_SECS`, store the returned
HTML under the school's own blob directory (`zeka_report/<day>.html`, temp
name + rename, never a partial file), answer `200` with what was stored.
A run day with no ledger row is a legal request; the service's `notes` say
what it found. Its typed refusals map per class: `bad_request` 400,
`insufficient_rows` 409 `report_empty`, `document_too_large` 413,
`internal` 500, anything else 409 `report_refused`. An empty document is
refused, never persisted — a blank page must not read as a report.
* `GET /insights/runs/{run_day}/report` — manager+, streams the stored
document (`text/html; charset=utf-8`, nosniff, private no-store);
`409 report_missing` when nothing was generated, a day the ledger has never
heard of included.
Both doors share one path (one `routes!(generate_report, serve_report)`), so
no nest or `MODULE_PREFIXES` change; `MIN_PROTECTED` 338 → 340 (derived).
`pump` moves from the podcast nest to `web` as a shared blob-stream helper.
Known gap, reported rather than widened here: the wire `RecommendationRow`
carries no `dismissed_at`, so the service's dismissal gate cannot fire on
this payload.✨ feat(insight): name the requester and fill a school-wide refresh rosterAhmet Kaan Gümüş · 0f55f34
✨ feat(insight): name the requester and fill a school-wide refresh roster
Every `insight.*` dispatch now carries `requested_by` — the caller the door
authenticated, which the service passes as `on_behalf_of` so its per-student
reads (`/marks/{user}` and the rest) answer as that teacher or manager instead
of the synthetic `ai` principal those reads refuse with a 403.
`insight.refresh` also always fills `user_ids`: a caller-named list passes
through exactly as given, while an empty body is filled from the school's own
student roster (every user holding the `student` role), because the service's
own roster discovery reads homework `assigned` lists, which a live school
rarely fills — so an empty body used to sweep nobody. The payload's new
`roster_source` records which roster the list was, and the refresh log names it
so the run ledger's counts are explainable. A school with no students dispatches
an empty list and answers 0 honestly; a roster past
`MAX_INSIGHT_REFRESH_STUDENTS` is refused rather than clipped.
Local-Gate: 644eaaee78ddae2e35af223da2719c3a55697a86 (1488 passed, 466s)🐛 fix(ai): withdraw a capability a service refuses as unknownAhmet Kaan Gümüş · 0eb20f9
🐛 fix(ai): withdraw a capability a service refuses as unknown A service that advertises `insight.refresh` in its `Hello` and then answers the dispatch with `unknown_capability` has contradicted its own handshake. The door read that advertisement as availability, queued the work with a `202`, and the refusal could only ever be a WARN — the user saw success and nothing happened. `rag.index`, `insight.refresh` and `insight.student` have each bitten this way. Now the registry withdraws the contradicted claim (`Registry::withdraw`): `Worker::offers` — what `pick`, `has_capability` and the snapshots read — is false for it, so routing drops the name and `GET /ai/capabilities` stops listing it. Every door already branches on `has_capability`, so the next call takes the `503` path it already had instead of queuing work nobody will do. The WARN names the service, the capability and the refusal code. Only a permanent, self-contradictory refusal does this. `unknown_capability` is the one code the protocol defines for "no operation by this name" — its example service-defined code (`unsupported_image`) is a verdict about a payload, not a claim about what the worker serves. Transient verdicts (`unavailable`, `timed_out`, `internal`, `capacity`) leave the claim standing, so a busy or restarting service keeps getting the next request. The withdrawal is per connection, never durable: every reconnect inserts a fresh worker built from its `Hello` alone, so a service that fixes itself restores the capability with no operator action. Tests: a refused refresh flips the next `POST /insights/refresh` to 503 and drops the capability from discovery (proved failing before the change); an `unavailable` refusal keeps both the 202 and the listing; a reconnect restores it — plus two registry unit tests. Local-Gate: 8718d07b6fbc70148eebea518febeb7bba764a46 (1486 passed, 474s)
🎧 feat(podcast): the history can be scoped to one course noteAhmet Kaan Gümüş · 81a8384
🎧 feat(podcast): the history can be scoped to one course note `GET /podcast/jobs` gains an optional `?source_id=` filter, so the studio panel can list one note's own episodes instead of the caller's whole history. The filter is part of the paging statement's `from_where`, so the page and the count run the same predicate and `total` stays the filtered count; the compare is `lower(source_id) = $2` against the canonical key, so an equivalently-spelled note id still matches every row it names. Omitted, the door answers exactly what it always did. A `source_id` that is not a uuid is a `400` naming the field rather than a nil id answering a silently empty page. School scoping, ordering and the staleness projection are untouched: a foreign note id is an empty page, not a window across schools. The param is published on the route (`IntoParams` + `params(...)`); the README endpoint table is unchanged.
🎧 feat(podcast): the history lists the caller's own episodesAhmet Kaan Gümüş · 6ed7e12
🎧 feat(podcast): the history lists the caller's own episodes GET /podcast/jobs answers the caller's own jobs, newest first, paged via ?limit=&offset= with the shared page envelope — the door a produced episode was missing: without it a finished job is reachable only by remembering which note produced it. Every row is the backend's own podcast_job record plus the title of the course note it narrates, read over the page alone (a second statement, not a join inside the paging statement: the count that pages the list must count jobs). A note that is gone leaves source_title null; duration_secs and finished_at stay null until the episode finishes. The read-side staleness projection applies here exactly as it does on the per-id door, and writes nothing. Tenant scoping is the door's own school database; nobody reads anyone else's jobs.
2026-09-17
🎧 feat(podcast): the submit door resolves the note's PDF and hands the service its blob keyAhmet Kaan Gümüş · 5f9e97c
🎧 feat(podcast): the submit door resolves the note's PDF and hands the service its blob key `podcast.submit` now carries `source_key` — the blob key of the note's newest `application/pdf` attachment, resolved by the backend before the job row is written. The service extracts the source with pymupdf, so it needs the file itself: a note id alone names nothing it can open. - `db::course_note_file::newest_pdf` reads the note's newest PDF (UUIDv7 id order is mint order), and the key it hands on is the row's own id — the same key the attachment's blob is stored under in the school's blob directory. - `POST /podcast/jobs` refuses `409 source_missing` before anything is written when the note has no PDF attachment, or when that attachment's blob is not present on this host — instead of queueing a job the service can only fail later in its `kaynak` stage. - The payload keeps `source_id` for the record and the report echo; a report now matches the row's note id, never a fixed literal. - `tests/podcast.rs`: the submitting tests mint a real course note with a PDF (teacher cookie, real doors) and witness the dispatch's `source_key`, both refusal shapes (no row written, nothing dispatched), and that the newest PDF — not the newest file — is the source. Pre-fix those four witnesses fail with `202` + a queued row, which is the behaviour this change removes. - `.sqlx`: one new query entry, regenerated on a scratch prepare DB. Local-Gate: 5d93323e202eaafb074ee46e3eaa1c0b38229725 (1473 passed, 443s)
🐛 fix(tenant): the boot sweeps every school database to the school-schema headAhmet Kaan Gümüş · ee72900
🐛 fix(tenant): the boot sweeps every school database to the school-schema head
A school database is migrated exactly twice in its life — at mint (`bring_up`,
through the create path and the provisioning finish) and at boot (the
template, and now this sweep). Nothing else ever touches its schema: a re-dial
applies no migrations, and the boot's reconcile only reaches rows still marked
`provisioning`. A school minted before a migration landed therefore kept
yesterday's tables for good — which is how the live deployment answered
relation "podcast_job" does not exist
on POST /podcast/jobs while the template already carried the podcast migration.
The missing half of the boot is now there: after the control database and the
template are ensured, every school database in the registry is dialled,
brought to the school-schema head and closed again. Nothing about a school no
request has reached is cached, so no pool for an unserved school survives the
sweep. The invariant it restores: **every school database in the control
database is at the school-schema head after boot.**
- Failure policy: one school failing never takes the boot down. It is logged
at ERROR with its id and slug and left exactly as it stood — the sweep
writes no registry row and no status, so a failed school is as usable (or
unusable) as it was and the next boot retries it; sqlx's tracking table is
what makes a retry of a half-applied migration safe.
- Observability: one INFO line per boot (`school schema sweep: N schools,
M migrated`) plus one line per school, only when it actually applied
something — the pending count comes off `_sqlx_migrations` before the
migrator runs, so a school already at head costs one connection and no line.
- `migrate_school`, not the bare migrator: the chatbot/RAG interrupted-turn
sweep is exactly as due on a school being swept as on one being minted.
The witness is in tests/persistence.rs: a school created through the normal
path, then rolled back to what an older head left behind — the table a later
migration created dropped and its `_sqlx_migrations` row deleted — reads
`relation "podcast_job" does not exist` before the sweep, and after it the
table is back, empty and recorded as applied, so the next boot is a no-op.
Every persistence test's second boot runs the sweep too (reboot()).
cargo check --all-targets and clippy -D warnings clean; persistence 11/11.
Local-Gate: 05ce93b5c478baa9a9ae80dd0bc8f99044a31f53 (1470 passed, 450s)🐛 fix(deploy): the operator-secret assertion named an unbound variableAhmet Kaan Gümüş · c2ac4f8
🐛 fix(deploy): the operator-secret assertion named an unbound variable The post-up env assertion aborted the deploy script with 'container: unbound variable' AFTER the new stack was already healthy, so every deploy reported failure while the correct build stayed live. Bind the container name before the inspect, and translate the block's comments (this repo is English-only). Local-Gate: 6992a743739affc85cebb7777608ffc3eb73a386 (1469 passed, 542s)
🚀 ci: a local full-suite gate lets a verified push skip the runner suiteAhmet Kaan Gümüş · 125a9b4
🚀 ci: a local full-suite gate lets a verified push skip the runner suite
The suite is 565s on this machine and ~55min on a 4-core runner, so the
default path is unchanged (GitHub runs Clippy, the suite, the release build,
the pack and the deploy) and a second path runs the suite here instead:
- scripts/gate-local.sh: clippy + the whole nextest suite + the doc gate with
CI's env, then a stamp in .git/local-gate/<tree>.ok and a
`Local-Gate: <tree> (<n> passed, <t>s)` trailer. --scope is quick iteration
and never produces the trailer; Postgres and cargo-nextest are checked first
with the exact command that fixes each.
- .github/workflows/main.yml: a 'Decide test gate' step verifies that trailer
against HEAD^{tree} and skips the test steps only when it matches, so a
stale or copy-pasted trailer falls back to running the suite. The job-level
if and the Deploy gate accept the skipped-dispatch variants, and the
dispatch gains a `tests` input (auto/skip/force).
- .githooks/pre-push: refuses a forged or stale trailer; an ordinary untested
push stays legitimate. SKIP_LOCAL_GATE=1 bypasses it loudly.
- AGENTS.md documents both paths.
Local-Gate: 76d42499f683a9315fd9daa3325dde5c859676c8 (1469 passed, 536s)📝 docs: rewrite the Turkish comments and doc comments in EnglishAhmet Kaan Gümüş · 7fec874
📝 docs: rewrite the Turkish comments and doc comments in English The Rust repo's own language is English; Turkish had leaked in from the sibling AI services. Translate every comment and doc comment to English using the code's own vocabulary (şube -> class section, dönem -> term, sınıf öğretmeni -> homeroom teacher, ortak sınav -> shared exam, karne -> report card, …). Quoted Turkish letters/words that are themselves the data under test (the text-fold examples in `text_fold`/`settings`, the non-ASCII filename sample) are kept. The README endpoint table is generated from those doc comments, so it is regenerated. AGENTS.md records the convention going forward: Turkish survives only where it is the data under test or user-visible content.
⏱️ ci: a stalled run now fails in ninety minutes and names its testAhmet Kaan Gümüş · a39278e
⏱️ ci: a stalled run now fails in ninety minutes and names its test The Build-and-test job gets a 90-minute timeout-minutes (default 360 min, since the run holds the serial deploy lock) and the Test step gets a shell-level timeout --foreground 4200 - above the 41m18s/60m25s green Test steps, below the job limit. Before Test: df/free/nproc/nextest version/.config/nextest.toml + show-config test-groups; then, via if: always(), the docker log, df/free, docker system df and the pg_stat_activity breakdown + the 20 longest queries: if the stall is on the DB side, its name stays in the log.
🧪 test: a hang names itself - bounded frame waits + nextest slow-timeoutAhmet Kaan Gümüş · b7a8017
🧪 test: a hang names itself - bounded frame waits + nextest slow-timeout One unbounded await in a bridge test held CI's Test step for 3h38m (run 35251780342), and because Deploy is serialized behind that job every later push queued behind it. Two bounds, both naming the culprit: * .config/nextest.toml: slow-timeout 120s, terminate-after 2 — a test that makes no progress is terminated and reported by name instead of hanging. * every frame read and client handshake in the bridge tests (ai_bridge, ai_protocol, podcast) goes through frame_or_fail/connect_or_fail, which panic with the wait's name after 10s instead of blocking forever. Local evidence: cargo nextest run --test ai_bridge --test podcast -j 16 -> 110 tests run: 110 passed in 41.2s.
🧪 test(bridge): the podcast report/upload handshake over a real QUIC streamAhmet Kaan Gümüş · 61960a5
🧪 test(bridge): the podcast report/upload handshake over a real QUIC stream Three bridge-level tests for the podcast job's own rows, driven through real client-initiated frames against a live bridge: the running/done/refused report sequence with the row re-read after each refusal, the upload landing the exact bytes under the school's own blob directory and stamping audio_key + duration_secs (done accepted only after it), and the two-school test proving the frame's school — not the payload — decides which database a report or an upload can touch (no bytes under the other school, its row untouched). `an_upload_past_the_audio_ceiling_is_refused_before_a_byte_is_read` sends no body on purpose: the refusal must come off the frame alone.
✨ feat: the podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the serviceAhmet Kaan Gümüş · c44f362
✨ feat: the podcast job's row and audio now live in the backend - backend-owned row, mp3 ingest, read gates without the service
The job record lived only in the podcast service's own volume, so a restart
or a wiped volume lost every in-flight job a caller was polling and the mp3 it
was about to download. The backend now owns both ends of that state:
* `migrations/school/20260917000003_podcast.sql` — `podcast_job`, the job's
own row (user/source/format/state/stage/progress/error_code/audio_*/
duration/eta/created/updated). No `school` column: the school IS the
database, and the row's tenancy is (this database, user_id).
* `POST /podcast/jobs` mints the id, writes the row, THEN dispatches
`podcast.submit` with `{job_id, source_id, format, user_id}`; the service
echoes that id in its receipt (mismatch = 502 + a failed/bad_reply row).
No worker = 503 and no row; a refusal or transport failure tombstones the
row with the reason code — nothing is left claiming `queued`.
* The service reports every transition back through `podcast.report` (the new
client-initiated capability call, School-scoped, wired through
`src/ai/capability.rs`), which validates the echo, the jobs.py transition
table, the retention window and the done-means-audio rule before one
conditional UPDATE keyed on the state it read.
* The finished mp3 arrives as a `BlobUploadRequest` stream (exactly `size`
raw bytes), lands under the school's own blob root at
`podcast/<job-id>.<ext>` (temp+rename, row stamped in the same act, file
removed again if the row write finds the job gone), and `POST`ing a done
report before it is refused `audio_missing`.
* The read doors — `GET /podcast/jobs/{id}`, `.../result`,
`.../audio` — answer from the row with no service round trip: 404 for an
unknown or foreign job (foreign ids read as absent), 409 `not_ready` /
`audio_missing`, 410 past PODCAST_JOB_RETENTION_SECS, and a read-side-only
projection that presents a queued/running row nobody has updated inside its
ETA-scaled window as failed/interrupted — the GET writes nothing and a real
report overwrites it. `podcast.status`/`podcast.result` capabilities are
deleted with their payloads; the old `GET /podcast/audio?path=…` door is
gone (it named a cross-volume path and could not be owner-scoped).
Also: `AppError::Expired` (410) + the two room matches that needed it,
MIN_PROTECTED 323 -> 337 (real swept count), the three clippy fixes on the
committed tree, README regenerated, and the .sqlx entries for both lanes'
queries. This commit completes the tree that 7c96e47 half-staged: that commit
took the shared files (server/protocol/constant/db-mod/ai-capability) while
leaving `src/ai/podcast.rs`, `src/web/podcast.rs` and `tests/podcast.rs` at
their old versions, so main did not compile until this one.✨ feat: ZEKA no longer touches the database directly - the insight.* storage surfaceAhmet Kaan Gümüş · 7c96e47
✨ feat: ZEKA no longer touches the database directly - the insight.* storage surface No AI service may hold a school database credential, so the nine reads and writes ZEKA performed against its own zeka_* tables become named operations the backend serves: insight.summary|recommendation|segment|profile|run.upsert, insight.pending.list, insight.retention.sweep, insight.departed.purge and the deployment-scoped insight.schools.list. They ride a new client-initiated capability call (CapabilityRequest -> CapabilityResponse, mirroring Request/Response field for field) and are mounted as HTTP doors on the same functions (manager+; the school directory is the builder's, outside the school gate). Every statement runs inside the school the frame named, in one transaction per batch.
fix(deploy): a two-file --env-file dropped the operator file; single channel + envZekaDeploy · 4a2411d
fix(deploy): a two-file --env-file dropped the operator file; single channel + env In podman-compose 1.6.0, `--env-file` is a SINGLE-valued argument and only the LAST file is resolved (podman_compose.py:2941-2946, :2559). The unit's and the deploy's two-file call (operator first, then stack.env) therefore never read the operator file at all: the stack ran with the compose defaults (DATABASE_URL password `hezarfen`, bridge token `change-me`) and the deploy's "cannot be empty" gate only inspected the file, so nothing went red (hit in production, 2026-09-17). - unit: the operator file enters the unit's environment via `EnvironmentFile=`, and the single `--env-file` passed to compose is stack.env (ExecStart + ExecStop). - deploy remote script: the operator file is read line by line into the process (no shell expansion), and the compose calls use a single `--env-file`. - new gate: once the stack is up, the container's environment must carry the operator file's VALUES verbatim (AI_SHARED_TOKEN, POSTGRES_PASSWORD, AI_QUIC_ADDR, BUILDER_USERNAME); otherwise rollback. - AI_SHARED_TOKEN and AI_QUIC_ADDR were added to the required-key list. The environment variable overrides --env-file values (podman_compose.py:2562), so the two channels cannot clash; Docker Compose v2's "the later file wins on a clashing key" behaviour does not apply to this provider.
fix(clippy): then_some in the insight about-drop, small refusal enum in worker_forAhmet Kaan Gümüş · 5bb7de4
fix(clippy): then_some in the insight about-drop, small refusal enum in worker_for CI Clippy red with -D warnings: unnecessary_lazy_evaluations at src/web/insights.rs:694 and result_large_err at src/web/podcast.rs:476 (the Err half was a 128-byte axum Response). worker_for now returns a small NoWorker enum and the four doors build the 503 at the call site via NoWorker::refusal(), so status and body are unchanged.
docs: correct the bridge's tenancy claim — school is stamped, echo not verifiedAhmet Kaan Gümüş · ee1f8f9
docs: correct the bridge's tenancy claim — school is stamped, echo not verified The bridge correlates replies by frame id only (ai::server dispatch matches Response.id and never compares the school field), so the docs' claim that it 'refuses an answer that does not echo the school' was false. State the true posture: request-side stamping plus the service's own honesty.
fix: 🧪 [TEST] the podcast capability constants are declared, not published limits - limits_completeness demands every pub const in constant.rs be either in GET /limits or in EXCLUDED with a reason; the podcast lane never owned this fileAhmet Kaan Gümüş · d079eff
fix: 🧪 [TEST] the podcast capability constants are declared, not published limits - limits_completeness demands every pub const in constant.rs be either in GET /limits or in EXCLUDED with a reason; the podcast lane never owned this file
merge: 🔀 lane/insight + lane/podcast — the zeka insight nest and the podcast relayAhmet Kaan Gümüş · e66cef0
merge: 🔀 lane/insight + lane/podcast — the zeka insight nest and the podcast relay Both lanes append to constant.rs/lib.rs/ai+web mod.rs in disjoint regions; the two conflicts were adjacent-line appends, resolved by keeping both sides. tests/integration.rs MODULE_PREFIXES carries both new nest rows (renamed 23 -> 25) from lane/insight.
✨ feat: ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nestAhmet Kaan Gümüş · b0b5e0c
✨ feat: ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nest
`hezarfen_zeka` already dials the QUIC bridge correctly and declares three
capabilities the backend did not know (`insight.student`, `insight.class`,
`insight.refresh`), and it writes nine `zeka_*` tables the school schema did
not contain — so nothing could route to it and nothing could read what it
computed. This lands all three missing pieces.
* the migration: `migrations/school/20260917000002_zeka.sql`, the service's
DDL copied verbatim (every FK resolved against the existing school schema:
`app_user`, `course`, `subject` and `exam_question (exam, id)`).
* `src/ai/insight.rs`: the payload contract for the three capabilities,
mirroring the service's TypedDicts, plus the two dispatches the backend can
route today — `compute_student` and `refresh`. `insight.class` stays
contract-only: its request names a course the service would have to
enumerate a roster for, and the bridge's read allowlist carries no member
listing yet (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md` item 3).
* `src/web/insights.rs`: the nest. `POST /insights/students/{id}` and
`POST /insights/refresh` (manager+) queue a detached dispatch and answer
`202` — the service writes its own rows, so a client polls the read routes;
`503` when no worker offers the capability and nothing is queued.
`GET /insights/me`, `GET /insights/students/{id}` (teacher+ narrowed to the
students they reach through a shared instance, or a parent holding a live
link; anyone else reads `404`, never `403`) and `GET /insights/runs`
(manager+) read the tables back. The service's output contract's own gates
hold on the read side: the attention list never reaches the student it is
about, a card's `about` never reaches a student caller, dismissed/expired
cards and `confidence: none` segments are filtered out.
Gated on `Module::Chatbot` like the other two AI nests, with its tag prose in
`src/lib.rs`, the README endpoints table regenerated, and the `.sqlx` cache
refreshed for the seven new statements.✨ feat: the podcast relay — four podcast.* capabilities and their audio streamAhmet Kaan Gümüş · 5a5a483
✨ feat: the podcast relay — four podcast.* capabilities and their audio stream
The backend had no dispatch site for podcast.submit/status/result/cancel, so the service's registration was unreachable. New AI_PODCAST_*_CAPABILITY constants, ai::podcast payload types + dispatch, and a /podcast nest gated on the chatbot module: POST /podcast/jobs (202 receipt), GET /podcast/jobs/{id}, GET /podcast/jobs/{id}/result, POST /podcast/jobs/{id}/cancel. Each door answers 503 with no worker declaring its capability, and relays the service's own refusal code as a status (not_found → 404, not_ready/llm_unavailable → 409, busy → 503, timed_out → 504, transport/protocol/bad_reply → 502).
The produced audio never crosses the bridge: podcast.result answers audio_id as a path relative to PODCAST_OUTPUT_ROOT, which the deployment points at the school's own directory under FILES_PATH, and GET /podcast/audio?path= streams it in bounded 64 KiB chunks out of the school-scoped State's files_path. That door refuses absolute paths, ./.. segments, backslashes, colons and symlinks resolving out of the school's directory with 400, and 401 without a session.
tests/podcast.rs drives all four capabilities over a real QUIC bridge against a fake service, plus the 503s (no worker and no bridge), the refusal→status mapping, the module gate, the session gate, and every audio-door refusal against a file that really exists. README endpoints table regenerated with UPDATE_DOCS=1.
Known pending, owned by lane/insight: tests/integration.rs's hand-written MODULE_PREFIXES needs a (Module::Chatbot, "/podcast") row, so the route-mount gate stays red for /podcast until that row lands.fix: 🌙 two clock-dependent assertions in the suiteAhmet Kaan Gümüş · 1675e73
fix: 🌙 two clock-dependent assertions in the suite - the rate-limit outage test asserted a single-shot read of a row a parked fold may write the instant the table returns; it now asserts the arithmetic (never folded twice, nothing lost) after two round barriers. This is the failure that reddened CI run 35170750886. - the cross-tenant search probe matched a username as a substring of the raw JSON, which also hits the hex of a UUIDv7 id: "ada" rides inside 01a0adad-…, so a correctly scoped response failed for a slice of every ~17.5-minute wall-clock window and passed outside it. It compares the parsed username/display_name now.
🧪 test(ai_bridge): cover the RAG page cap, send-path 429, and the SSE streamAhmet Kaan Gümüş · 4a8829eBrowse files
fix: 🧪 the three gates the merged /rag tree left redAhmet Kaan Gümüş · ebffd41
fix: 🧪 the three gates the merged /rag tree left red - the rag.chat byte pin now expects serde's real field order (the wave-1 test was compiled but never executed) - /rag joins the gated-nest list the route guard checks by name - README's endpoint table regenerated after the /ai/capabilities security annotation landed - ignore src/graphify-out, where the graphify hook writes inside the tree
✨ feat: the /rag nest — threads, answers with citations, and scope derived from the caller's instancesAhmet Kaan Gümüş · 39f97e4
✨ feat: the /rag nest — threads, answers with citations, and scope derived from the caller's instances Merges lane/rag-nest. A separate nest and tables (rag_thread, rag_message) over a new rag.chat capability: every answer is stored verbatim (abstained, reason, citations resolved to the course-note file the asker may view), the scope sent to the service is the caller's (sinif, ders) pairs, and the school's existing AI caps and a new per-user tier govern it. course_note_file gains rag_doc_id so a citation's corpus doc id finds its PDF.
✨ feat: add the /rag nest over the course-note RAG bridgeAhmet Kaan Gümüş · a61e0a6
✨ feat: add the /rag nest over the course-note RAG bridge A separate rag_thread/rag_message pair of tables and a Module::Chatbot gated /rag nest, mirroring the chatbot's asynchronous send: POST answers 202 with a pending assistant row, an in-process task settles it, and both the poll read and the SSE stream project a stale pending row as failed. Every question is scoped server-side to the asker's own (sinif, ders) pairs — class-section instances, a linked parent's children, school-wide club/study memberships — never from the body. Each citation's corpus doc_id is resolved per candidate to a course-note file the asker may view, and the two storage caps refuse an over-bound reply whole rather than clipping it. rag.index replies now stamp each file's rag_doc_id, the missing link between a citation and its file. The chatbot's SSE helpers move to web/mod.rs so both nests stream through one implementation, and the instance/course visibility gates move from web to service so the scope deriver and the routes share one rule. Gates: cargo check --all-targets, clippy -D warnings, limits_completeness, spec_bounds, doc_sync (README regenerated), protected_routes_require_session (MIN_PROTECTED 269 -> 318, the real swept count), ai_bridge (75 tests).
fix: 🔌 one routes! per path in the ai nest (two GETs cannot share one)Ahmet Kaan Gümüş · 712ff31Browse files
✨ feat: publish the rag.chat payloads and a GET /ai/capabilities probeAhmet Kaan Gümüş · 94cffa0
✨ feat: publish the rag.chat payloads and a GET /ai/capabilities probe Add the rag.chat capability's wire contract (scoped question -> answer with citations), the max-scope-pairs and rate-limit constants, and an authenticated discovery route listing each capability's connected worker fleet. Document the payloads and the rag.index reply's file<->doc_id echo in the README.
🔧 chore: give ResolvedTenant its core home and make constant.rs a leafAhmet Kaan Gümüş · d0dce85
🔧 chore: give ResolvedTenant its core home and make constant.rs a leaf Two structural defects a knowledge-graph pass over src/+tests/+migrations surfaced. Both were verified against the real `use` lines before being called defects — a module cycle is legal Rust, so only the layering facts count. No behavior change: every moved item is byte-identical in name, type, value, element order and doc text. - `ResolvedTenant` was *declared* in `src/web/tenant_state.rs` but *built and returned* by `Tenants::resolve` (`src/tenant.rs`), so the core tenant registry imported the web layer. The struct moves to `src/tenant.rs`; its `impl FromRequestParts` stays in the web module (same crate, local type). That deletes the crate's only core→web import edge, and with it the three module cycles running through `state.rs` and `ai::server`. - `constant.rs` is documented "Validation limits, in one place" but imported four domain enums to hold non-limit vocabularies: `ROLES` → `domain/role.rs`, `THEMES`/`LANGUAGES` → `domain/preferences.rs`, `SENDER_FOLDERS`/ `RECIPIENT_FOLDERS` → `domain/message.rs`, and the 34-row `BADGES` catalogue → `domain/badge.rs`. Each now lives in the module that owns its type, so `constant.rs` imports nothing from `crate::domain` and ten `constant ↔ domain` cycles disappear. `AI_PRINCIPAL_KEY` and `PALETTE_COLOR_*` stayed put. Measured on the same corpus: 20 → 7 reported import cycles — all ten constant↔domain and all three tenant↔web cycles gone. The surviving seven are intra-layer domain cycles plus the ai↔web pair; the AI bridge is a peer front-end reusing web authorization helpers, which is deliberate, not an inversion. Tests: the published-or-excluded guard in `limits_completeness` read only `src/constant.rs`, so the five moved tables silently left its scan — the one place this move weakened coverage. It now covers them by name, and its `references()` check no longer counts a bare `use` line as "published", which the first witness attempt proved had made the guard vacuous. Witnessed by mutating BADGES and then ROLES out of `/limits`: each FAILs naming the moved table, and each restore is sha256-identical. Gates: no SQL touched (.sqlx and migrations clean), prepare DB unchanged; SQLX_OFFLINE=true cargo check --all-targets, clippy -D warnings, limits_completeness, spec_bounds all green; cargo nextest run 1386/1386 across 47 binaries (doc_sync included).
2026-09-16
✨ feat: announce an exam to sibling instances (shared-exam write surface)Ahmet Kaan Gümüş · 1824c34
✨ feat: announce an exam to sibling instances (shared-exam write surface)
b3f7395 gave `exam_audience` a read role; this gives it its writes. An exam
is owned by the instance it was created on and can now be addressed to
further instances — one sitting, one mark, standing in every addressed
section's exam list, marks report and the report card.
- `POST /exams/{id}/audience` announces the exam to another instance: the
target must teach the exam's own catalog course and sit under the same
academic year (400 otherwise), the owner itself is refused (400), an
archived target year is a 409, and a repeat announce is a no-op 200.
The write needs management rights over the exam's **owner** instance —
the target instance's teachers have no say.
- `GET /exams/{id}/audience` lists the set (owner first, then announcement
order), visible exactly as the exam is; drafts stay a 404 to everyone but
an addressed instance's manager. `DELETE /exams/{id}/audience/{instance}`
withdraws one; the owner's pair is not withdrawable (400) and a pair that
holds no row is a 404.
- Grading, statistics, results and the live monitor now accept teacher+
rights over any instance the exam is addressed to, so an announced-to
section's teacher grades its own students; the monitor's roster read is
deduped by student and ordered, so a sitter in two addressed sections
appears once.
- `sweep_instance_subtree` clears both directions of `exam_audience` before
the rows they name — an exam a sibling announced *here* referenced the
`class_course` row the caller deletes and refused the delete with a 23503.
Tests: regress_exam_delete.rs pins the announce/withdraw surface end to end
(owner-first order, the same-year and same-course 400s, the 409, the no-op)
and the sweep's answer-image blobs — the drawing row's bytes land on disk
and are gone with the row, with a mutation witness.
Gates: prepare_db, SQLX_OFFLINE=true check --all-targets (cache: 1 dropped,
7 added, all audience-shaped), doc_sync, spec_bounds, limits_completeness,
clippy -D warnings all green; cargo nextest run 1385/1385 across 47 binaries.✨ feat: archive an academic year, attribute shared-exam marks, index the new FKsAhmet Kaan Gümüş · b3f7395
✨ feat: archive an academic year, attribute shared-exam marks, index the new FKs
Follow-ups on the K12 remodel:
- `POST /academic-years/{id}/archive` (Manager+): stamps `archived_at`
idempotently, making the existing `academic_year_archived` guard reachable —
every write into an archived year now 409s while reads stay 200. No
unarchive; no PUT.
- Marks and the report card attribute an exam via its `exam_audience` rows, not only its
owner instance: a shared exam's mark now stands in every addressed class section's
report instead of vanishing when the owner instance isn't in the student's
list. Owner-only exams are unchanged (the owner audience row always exists).
- `GET /instances/me` now serves the full visibility set (live member ∪
instance teacher ∪ class-section homeroom), so a teacher's own list is meaningful.
- Migration `20260916000002_k12_indexes.sql` adds the indexes the remodel's
drop/recreate left out: `enrollment(app_user)` (dropped with its table),
`course_membership(app_user)`, and `exam_audience(class_course)` (read by
every per-instance exam read).
Tests: the archived-year e2e now archives via the route; new regressions pin
the sweep's `term.exam_count` release (the term becomes deletable) and the
blueprint sweep's blob unlink, each with a mutation witness; new shared-exam
attribution tests (fail-pre-fix/pass-post-fix for both reads) and the
`/instances/me` union.
Gates: check --all-targets (offline cache regenerated), doc_sync,
spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1376/1376.✨ feat: the class×course instance is the academic anchor (K-12 remodel)Ahmet Kaan Gümüş · ae84034
✨ feat: the class×course instance is the academic anchor (K-12 remodel)
`course` was a school-wide singleton: enrollment, exams, sessions,
roll-call and homework all keyed on it, so two class sections teaching the same
course shared one roster, one exam set and one timetable. This moves the
academic anchor to `class_course` — the per-class instance — and rebuilds
the academic model around Turkish K-12.
Schema (migrations/school/20260916000001_k12_remodel.sql): `class_course`
becomes an instance (ders_saati, counts_toward_karne, enrollment_count,
class_course_teacher); enrollment re-keys to (class_course, app_user);
exam carries class_course + term (+ exam_audience for shared exams);
course_session / session_attendance / homework re-key; `class_member` is a
soft-leave history table (uuid PK, joined_at/left_at, partial unique index
on the live stint); `academic_year` sits above `term`; `class_group` links
a year, not a term; new `course_membership` (clubs/study), `karne_snapshot`;
settings gain branches/excuse_kinds/absence limits/timezone; profile gains
branch. Drops/recreates the identity-changing tables (pre-customer; the
migration resets every counter on a kept table that pointed at a dropped
one).
Layers: domain/db/service/web rewritten to the instance seam, with
`ensure_instance_teacher` gating instance writes (D10), the report card computed per
instance and weighted by ders_saati, an absence report, `/instances`
and `/academic-years` nests, and `/classes/{id}/instances`. Capacity and
the seat-claim 409 are gone; detach sweeps the whole instance subtree and
unlinks its blob keys.
Gates: cargo check --all-targets, SQLX_OFFLINE check (cache regenerated),
doc_sync, spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1370/1370.✨ feat: an empty user search lists everyone the caller may seeAhmet Kaan Gümüş · 6cf8640
✨ feat: an empty user search lists everyone the caller may see GET /users/search no longer refuses a blank `q`. Omitted, empty and whitespace-only are the same input now: each returns the caller's visible directory, which is what a receiver picker opens with — staff see the school, while a student or parent still see only the staff they may write to, and naming a role outside that set is still a 403. `role` still narrows, an unknown role is still a 400, and `limit`/`offset` bounds are unchanged. The store already treated a blank needle as "no clause"; this drops the web-layer guard that contradicted it and pins the behavior on both sides (blank == omitted == whitespace-only, and blank still narrowed below staff).
✨ feat: an admin mints a school account directlyAhmet Kaan Gümüş · 57de5b3
✨ feat: an admin mints a school account directly POST /users creates the person plus the school's app_user in one call, born with the role the caller names (student by default) — no self-registration and no register-then-promote two-step. Reuses the register credential rules: a username new everywhere mints the person, an existing person attaches only when the password matches (409 otherwise), a name already taken in the school is a 409, and the reserved staff-reading names are a 400.
2026-09-15
🆔 fix: one id convention — every id is a v7 uuid, none is a v4Ahmet Kaan Gümüş · d40e4c9
🆔 fix: one id convention — every id is a v7 uuid, none is a v4 The crate mints UUIDv7 from the process-wide monotonic generator, but four sites still minted a v4: - ChoiceId (an exam choice's stable id) and the blob names of answer images, bank-question images and homework files: now next_uuid(), like their siblings (question_image already was) - test_suffix()'s 5-hex tail is not an id — it is the random half of a test database's name — so it draws from the OS rng: a v7's leading hex digits *are* the mint time, which is exactly what two processes minting in the same millisecond share - the request-id layer installed tower-http's MakeRequestUuid (a v4); it now mints through the crate's own generator, same wire shape The manifest drops uuid's v4 feature, and a guard test scans src/ so a stray v4 fails the suite. (tower-http's request-id feature still enables uuid/v4 in the dependency graph; nothing here calls it.)
🐛 fix: a school's registry row and its database are never one writeAhmet Kaan Gümüş · 8e58afe
🐛 fix: a school's registry row and its database are never one write
Three consequences of that one fact — partial states the code could leave
behind and nothing could repair.
**A school is `provisioning` until its schema exists** (new control
migration). The row commits before the database does (`CREATE DATABASE` cannot
join that transaction), so a boot cut short in between used to advertise a
school that answered every request with a `500`; the next boot's
`reconcile_provisioning` now finishes it. While it is being made, the school's
own doors refuse it (`403`) and the two builder routes that need its database
(`enter`, `admin-password`) answer `409` instead of a table-less 500.
`provisioning` is the boot's word alone — the PATCH parser still refuses it,
and a client can never ask for it.
**`Tenants::drop` dropped the database last**, after destroying the memberships
and the entitlements: a transient failure left a school that still stood with
every one of its people locked out and nothing able to put them back. The
database goes first (it is the half that can fail on its own — `DROP DATABASE`
cannot join a transaction either) and everything after it is one transaction,
so a failure leaves "database gone, registry rows intact", which re-running the
same call completes.
**`PATCH /schools/{slug}` wrote name and status as two statements**; a failure
between them left half a patch. Both fields are one statement now, with
`COALESCE` over the row being written — an omitted field keeps its stored value
and a concurrent patch of the other field cannot be reverted.
Local: cargo nextest run --no-fail-fast → 1375 passed. clippy clean.
Live: a seeded `provisioning` row comes back `active` with a 70-table database
and the boot logs the finish; lifecycle probe 200/400/201/204 on the running
server; 8-boot template race 8/8 up, 0 refusals; 4-boot race on a fresh control
database 4/4 up.🐛 fix: the boot seed survives a rival boot; a failed create drops its databaseAhmet Kaan Gümüş · f8d7a2d
🐛 fix: the boot seed survives a rival boot; a failed create drops its database Two more members of the class the template fix opened — a statement issued where a rival process may already have written the same row. `service::builder::ensure` raced on `builder_username`: find-then-insert is not a guard, and the loser's raw `23505` killed the boot (measured: four boots racing a fresh control database, three died, only the winner stayed up). The insert is now `INSERT … ON CONFLICT (username) DO NOTHING`, so the loser neither raises nor logs — a refused insert is logged by the server even when the client handles it — and the winner's credential stands. The same 4-way probe now reports 4/4 up with zero server-side error lines. `Tenants::create`'s rollback deleted the registry rows but left the database it had just created: names are minted per create and never replayed, so that is an unreachable 70-table database nothing can name again. The rollback now drops it best-effort and warns when even that fails, so the one leak this path can produce is at least visible. `.sqlx` regenerated for the changed statement (scripts/prepare_db.sh + cargo sqlx prepare).
🐛 fix: idempotent school-template create across bootsAhmet Kaan Gümüş · 331ae93
🐛 fix: idempotent school-template create across boots The boot template was created by an unconditional `CREATE DATABASE` whose `already exists` refusal was swallowed, so every restart logged a server-side `ERROR: database "…" already exists`. Worse, two boots racing on a missing template killed each other: Postgres reports the *losing* create as `23505 duplicate key value violates unique constraint "pg_database_datname_index"`, never `42P04`, and the guard matched only `42P04` (measured: four boots racing, three died). `CREATE DATABASE` has no `IF NOT EXISTS` in Postgres (syntax error), so the create now probes `pg_database` first, the swallow accepts both SQLSTATEs (`is_database_exists`), and the boot's create-and-migrate runs under its own advisory lock — the pattern the test harness already uses for its template. `scripts/boot_race.sh` is the reproduction. Local: cargo nextest run --no-fail-fast → 1373 passed. clippy clean. N=8 bash scripts/boot_race.sh → 8/8 boots up, 0 create-refusal lines.
2026-09-14
🔧 chore: nextest never fail-fastAhmet Kaan Gümüş · 5ea87b2
🔧 chore: nextest never fail-fast One load-luck assert must not skip the rest of the suite. Deploy still requires the Test job green.
🐛 fix: load-luck asserts in pomodoro race and rate-limit outageAhmet Kaan Gümüş · b6d7046
🐛 fix: load-luck asserts in pomodoro race and rate-limit outage Streak==round is not the concurrent-finish claim. Down-database empty-row assert waited out parked folds (RATE_SYNC_TIMEOUT) before restore. Local: cargo nextest run --no-fail-fast → 1373 passed. rate_limit binary ×3 passed. pomodoro concurrent ×20 passed.
🐛 fix: shared rate-limit tests wait a second sync roundAhmet Kaan Gümüş · 7c429b6
🐛 fix: shared rate-limit tests wait a second sync round Each limiter's fold is its own statement. One round leaves the first finisher with a stale remote total (CI: expected 0 admits, got 3). Local: cargo nextest run --no-fail-fast → 1373 passed. rate_limit binary ×3 passed.
🐛 fix: junction-era test pins and homework audience recheckAhmet Kaan Gümüş · fa1529a
🐛 fix: junction-era test pins and homework audience recheck class_course.source and board_participant are uuids, not grade text / participants[]. Submission upsert locks homework then re-reads assignment, so a narrowing PATCH cannot land a 201 for a dropped student. Local: cargo nextest run --no-fail-fast → 1373 passed.
📝 docs: drop stale process-lock commentsAhmet Kaan Gümüş · 5ff42c5
📝 docs: drop stale process-lock comments PRESENCE_LOCK and the other named process locks are gone. Comments and README still talked as if they serialized writes.