forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/ai/mod.rsClear filter

2026-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)

2026-09-17

✨ 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.
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.
✨ 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.

2026-09-05

✨ feat: rag_output table + rag.index dispatch for course notesAhmet Kaan Gümüş · d42a1c3
✨ feat: rag_output table + rag.index dispatch for course notes

The backend now owns the RAG side of a course note: a new `rag_output`
table stores whatever an AI service produced for a note, and the backend
asks for it — the AI service still writes no human data, and the api-read
bridge stays GET-only.

`rag.index` is dispatched fire-and-forget (tokio::spawn) after a note is
created, edited, or gains/loses a file, so no HTTP handler waits on, or
fails because of, an AI service; with no worker carrying the capability
the trigger is a silent no-op. The request carries the note's text plus
attachment METADATA only (file bytes deliberately off the wire — open
with the service owner). Rows are derived data, so they cascade: the note
delete drops its outputs, and a file delete drops every output built from
it even when no service is connected.

HTTP GET/DELETE routes over the rows are part 2.

Ref #27

2026-08-12

🤖 feat: allowlist the GET paths ai services may readAhmet Kaan Gümüş · 317ef9c
🤖 feat: allowlist the GET paths ai services may read

Deny-by-default: the bridge will only ever dispatch a service's read into
the router when the path matches AI_API_ALLOWLIST segment for segment. No
prefix match, no wildcard tail, so a new route family is unreachable to
the services until it is listed on purpose.

v1 is JSON-only and scoped to what a study companion needs: identity and
profile, notes, homework reads, and the marks/attendance/pomodoro
reports. Byte-serving routes (note files, submission files, avatars,
question images) are left out — the frames carry JSON.

The entries are router paths kept by hand, so integration.rs pins each
one to a GET in the emitted OpenAPI document: a route rename now breaks
the test instead of silently shrinking the services' scope.

2026-07-30

chore: 🧹 drop the coordination for replicas we never runAhmet Kaan Gümüş · a9cfe7b
chore: 🧹 drop the coordination for replicas we never run

The backend runs as one process against one database, deployed
stop-the-world. The machinery that let several of them agree was built
ahead of a multi-replica rollout that stayed parked, so none of it was
ever load-bearing: the boot lease elected a leader out of a field of
one, the ai_worker table announced a worker to nobody, and the chat
claim queue only ever claimed its own writes.

Boot now migrates and seeds straight-line; a chat turn is dispatched by
the handler that accepted it; the 503 gate reads the in-process
registry. The retired columns and tables are unset and removed in
separate batches, repair before REMOVE.

What stays, with its reason corrected rather than removed: cap.rs,
field_update.rs, the refcounts, the CAS retry loops and the in-process
locks. Those close write skew between concurrent requests inside one
process, which two replicas made worse but never caused.

A turn orphaned by a restart or a panic is no longer reclaimed. It
settles as timed_out within CHATBOT_PENDING_STALE_SECS.

The design survives in the ledger if a second process is ever wanted.

2026-07-26

feat: 🗳️ elect the boot, and make a chat turn a claimed jobAhmet Kaan Gümüş · 0787b14
feat: 🗳️ elect the boot, and make a chat turn a claimed job

Two things assumed there was only ever one process. Both stop assuming it,
and both pay off on a single replica today, where a rolling restart already
overlaps two containers.

**The boot is elected.** Every process ran the whole migration, backfill and
admin seed on startup, so two overlapping ones raced all three. A process now
claims `migration_lock:boot` with a deterministic-id CREATE, renews a lease
while it works, and stamps a sha256 of the SQL it applied; the others wait for
that stamp and only trust it when the fingerprint is their own, so a new binary
never serves on the previous one's schema. A leader that loses its lease fails
its boot rather than reporting a success it no longer owns, and an abandoned
lock is taken over once the lease lapses.

Seeding the admin was two writes — create as a student, then promote — and a
process killed between them left a student holding ADMIN_USERNAME that no later
boot would ever promote, because nothing can tell that row from a stranger who
registered the name. The role is now minted with the row.

**A chat turn is a claimed job.** The answer used to ride on a `tokio::spawn`
belonging to whichever process took the POST, so a restart orphaned it and the
turn only settled at the stale horizon. The POST now just writes the pending
row; a replica holding a `chat.reply` worker claims it with a conditional
update and answers over its own socket. A claim left behind by a dead process
expires and is retried, and a configured AI timeout is capped below that
horizon so a slow inference is never reclaimed out from under itself.

The gate and the dispatcher are deliberately separate: `ai_worker` is a
heartbeated table that only answers "could anything, anywhere, serve this",
may be stale, and never guards a write; the in-process registry owns the
socket and is the only thing that decides who dispatches.

hab/1 is untouched. Verified on two live replicas against one SurrealDB: a
turn posted to a worker-less replica was answered by its peer, survived a
restart of the other replica mid-flight, and was dispatched exactly once.

2026-07-23

🎨 style(chatbot): rename thread/message off the mail collisionAhmet Kaan Gümüş · 92b232b
🎨 style(chatbot): rename thread/message off the mail collision

The AI chatbot's storage and web layer reused "conversation" and
"chat_message", the latter one underscore away from the human-to-human
mail `message` feature — every reader had to disambiguate two unrelated
tables by eye.

Rename the whole chatbot feature to a `chatbot_*` vocabulary:

  conversation  -> chatbot_thread    (ChatbotThread*, CHATBOT_THREAD_*)
  chat_message  -> chatbot_message   (ChatbotMessage*, CHATBOT_MESSAGE_*)
  /chat/conversations -> /chatbot/threads
  max_chat_conversations -> max_chatbot_threads
  max_chat_message_len   -> max_chatbot_message_len
  chat_history_turns     -> chatbot_history_turns
  RATE_LIMIT_CHAT_PER_MINUTE -> RATE_LIMIT_CHATBOT_PER_MINUTE
  DTO conversation_id -> thread_id

The out-of-process AI-service wire contract is deliberately untouched:
ai/chat.rs payload types, AI_CHAT_CAPABILITY ("chat.reply"), the serde
field names and the hab/1 ALPN stay as-is — other-language services
match on those literals. ai/chat.rs remains "the chat.reply payloads",
a separate concern from the chatbot feature it feeds.

Clean break, no row migration (pre-customer, FE not yet synced): old
conversation/chat_message rows in the volume are abandoned. Frontend
must adopt the new routes, the thread_id field, and the renamed
settings keys.
✅ test(ai): cover the bridge's boot wiringAhmet Kaan Gümüş · 266e175
✅ test(ai): cover the bridge's boot wiring

`start_ai_bridge` sat in main.rs, so the branches an operator actually
hits had no test: unset address boots fine, bad address fails the boot,
and a set address with no token refuses rather than listening
unauthenticated. Moved to `ai::start_bridge` and tested there, including
a real dial-in against what it returns — a constructed value proves
nothing, a completed handshake does.

The token assertion pins this layer's wording. `AiBridge::bind` rejects
an empty token too, so matching only on "AI_SHARED_TOKEN" passed with
the branch deleted; the test now names AI_QUIC_ADDR and fails without it.

Returns AiError rather than anyhow::Error, keeping anyhow to the binary.
✨ feat(chat): relay chatbot over the AI bridgeAhmet Kaan Gümüş · b0aa0a1
✨ feat(chat): relay chatbot over the AI bridge

The backend relays between the frontend and an out-of-process AI service:
it owns auth, rate limiting, persistence and payload format, and may
inspect an answer before the frontend sees it. No rule or intent tables —
conversation is free-form.

Two-phase by design. POST persists the pending assistant row *before*
dispatching, then returns 202, so a reload never loses an answer; the
client either polls the message or opens an SSE stream. Both read the
same DTO, so they cannot disagree. Deltas are sliced from the finished
text because hab/1 is unary — the event shape exists so real streaming
drops in later without a client change.

A turn always settles. Every failure after the rows are written marks the
row failed with a machine-readable code, a boot sweep flips rows orphaned
by a restart, and a pending row older than five minutes reads as timed
out — projected at read, never written back, so a slow-but-alive answer
is not raced. An over-long answer is clipped and flagged rather than
dropped; an empty one fails.

Message ids come from a monotonic ULID generator: the two rows one POST
writes share a millisecond routinely, and a random tie-break rendered the
answer above its own question and handed the service [assistant, user],
breaking the documented oldest-first history contract.

The conversation cap counts and creates under a lock — SurrealDB
BEGIN/COMMIT does not serialize cross-record counts, and 16 concurrent
creators over-admitted a cap of 5 to 20 without it.

Every authenticated role may chat, parents included. Foreign threads are
404, never 403.
✨ feat(ai): QUIC bridge for out-of-process AI servicesAhmet Kaan Gümüş · dc49954
✨ feat(ai): QUIC bridge for out-of-process AI services

The AI features live in separate projects, so they need a transport. QUIC:
each request rides its own bidirectional stream on the service's single
long-lived connection, which puts multiplexing in the transport — no
correlation-id bookkeeping, no head-of-line blocking between concurrent
requests, one handshake instead of one per request.

The backend listens and the services dial in, so a service can sit behind
NAT, restart without the backend knowing its address, and scale out by
opening a second connection (each connection is an independent worker).

Protocol "hab/1", also the ALPN so an incompatible service is refused at the
TLS handshake rather than one frame later. Frames are length-prefixed JSON
(u32 big-endian) because the services will not be Rust; the length is checked
against an 8 MiB cap before any buffer is allocated. The control stream
carries Hello/Greeting and then stays open — its closure is the goodbye, so
there is no heartbeat frame, and a silent death is caught by the QUIC idle
timeout.

Routing is least-inflight rather than round-robin: AI request costs are
wildly uneven, and taking turns would pile a second long inference onto a
busy worker while an idle one sits next to it. Selection and the in-flight
increment happen under one lock so concurrent dispatches cannot overshoot a
worker's declared max_concurrent, which a Lease releases on drop.

Services authenticate with a shared token (constant-time compare); the
certificate only proves the backend, and is self-signed at boot unless a PEM
pair is configured. Since that regenerates per boot, GET /ai/certificate
publishes it (PEM + sha256) for a service to pin — public because a server
certificate is handed to every peer in the TLS handshake anyway, and 404 when
the bridge is off. A service must re-fetch on every reconnect, not once at
startup.

Off unless AI_QUIC_ADDR is set, so the API is unchanged for deployments
without AI. Set without AI_SHARED_TOKEN it refuses to boot rather than listen
unauthenticated.