0064. "Ask your coach": the chat engine
Source:
docs/decisions/0064-ask-your-coach-chat.md. Generated at build time; edit the source file.
Date: 2026-11-22. Status: accepted (Task 23). Builds on ADR 0060 (facts by reference) and ADR 0062 (the Agent SDK sidecar and its chat sessions).
Context
Section titled “Context”The player can ask their coach questions about their own games. The answer is model text shown to a player who may be a minor, so it must meet the same bar as the report: every chess fact by reference, checked before it is shown, no promises and no marketing. Unlike a report section it streams, it can call tools (including fresh engine checks), and it runs inside an SDK session that keeps the conversation (ADR 0062 Amendment 1).
Decision
Section titled “Decision”- Where it runs. The chat runs in the worker (
coach-chatjob, Task 25). One turn is onestream_turnwith the chat tools: the sidecar runs up tomax_tool_rounds + 1= 7 model rounds and calls each tool back through a per-turn handler (chat::engine). Rust owns the prompts, the tools, the validation, budgets and metering. - Anchors. A conversation or a message can be opened from a report section, a weakness, a
position, a move, an opening line or a game. The anchor is resolved for the account
server-side and injected as an
<anchor>block (conversation anchors in message 1, message anchors before the question). Its ids feed the tools; a position anchor’s FEN feedsanalyse_position, and its position joins the turn’s evidence. - Validate before publish. The streamed text is split on blank lines. Each paragraph is
validated (
validate_textwith implicit citations, no required citation, and the rulesbanned_phrases,no_marketing,engine_claimsandno_quantity_words) againstbuild_evidence(input)plus the anchors plus this turn’s tool evidence, all in oneToolSession. A passing paragraph is published while the stream is not held; the first failure holds the stream. A held answer gets ONE repair turn (no tools, nothing published); paragraphs that still fail are dropped and the repaired answer replaces the streamed one. When nothing is left, the answer is the fixed fallback sentence. Dropped statements and an engine-check limit are noted in fixed server copy. - Off-topic. The model answers anything that is not chess or the player’s games with
exactly
{{offtopic}}, which the engine turns into a fixed reply. From that point the turn’s tool handler refuses every further call ({"error":"the answer is complete"}), so nothing more is looked up or charged. The prompt file never contains the marker (T13’s template renderer would read{{offtopic}}as a placeholder); the marker line is appended tosystem[1]in code. - Tools. Tools are scoped to the account server-side (the data source and the engine), and
every input is validated before anything is read. The stored analysis cache (
get_eval, read-only) is kept apart from interactive checks (analyse_position, charged to the engine-check quota). - Engine pending. An engine check still running after the 5 s inline wait streams one
interim line (“Checking that position with the engine, one moment.”,
interim: true, at most once per turn) and waits up to 45 s in all, inside the tool call (under the tool endpoint’s 50 s per-call timeout). A check still pending then is abandoned (its quota refunded) and the model getsengine busy. - History. Our Postgres conversation is the record (ADR 0062 Amendment 1); the SDK
session carries the model’s view, and it may only be resumed while the two agree.
- Every outcome carries
session_in_sync. It is true only for anAnsweredturn with no repair, no max-turns follow-up, no retracted message and nothing replaced, so the stored paragraphs are exactly what the session recorded (the server’s drop and limit notes aside, which are never in the session). Off-topic, refusal and fallback replies are not in sync: the session holds the model’s text, the record the fixed copy. - The next turn resumes only when the previous answer was in sync and the history does not
roll over (
resume_next_turn). It then sends only the question, with the earlier messages, flattened, as the rebuild context. - Otherwise it sends the full Postgres history (
VerbatimorRollover) withresume: falseand no previous session usage. The sidecar deletes the stale session rows and starts a clean session under the same id, and metering uses the turn’s ownmodel_usage(pathnew). - Every
replay_turns(6) turns the history rolls over into a summary plus a plain transcript of the recent turns. A rollover turn always starts a new session, since a resumed session would still hold the full verbatim history. - Session entries are never edited, and no earlier assistant (or thinking) block is ever edited or replayed.
- Tool-call indexes are unique across the conversation: a turn starts at the previous
outcome’s
next_call_index(ToolSession::starting_at), which the caller stores with the conversation. Atools.<k>token copied from an earlier turn then fails closed instead of resolving to another result.
- Every outcome carries
- Prompts. The chat’s prompts are registered T13 files (
CHAT_PROMPT_SET,chat@1):system[0]is the sharedrules_block()(core/rules+core/tokens, byte-identical to the report’s, so one cache entry serves both);system[1]ischat/system, whose “Output in this chat” section asks for plain paragraphs, with positions cited by their own tokens and no JSON, schema orcitationsfield; the repair renderschat/repairwith T13’s- path: code: detaillines, the path naming the paragraph (chat.<n>). The report’sreport/outputandrepair/repairare never sent in a chat. - Follow-ups. The round-cap follow-up (“Answer now with what you have.”) and the repair run
as one-round turns without tools under a fresh session id, with the flattened transcript and
the tool results as data. They never enter the conversation’s session; their session-store
rows are swept as orphans (Task 21). Only the main turn’s
Donegives the storedsessionModelUsage. A turn with a follow-up or a repair is never in sync (§7), so the next turn rebuilds the session from our record rather than resuming the unrepaired one. The repair is not run inside the conversation’s session: that session would then hold the invalid answer, the repair prompt and the repaired answer. A paragraph cut off bymax_tokensis never shown; it holds the stream and is repaired. The follow-up never sees the main turn’s streamed text, so its answer stands alone: the main turn’s paragraphs are dropped (and the stream replaced) instead of being said twice. - Quotas. Free and Pro chat quotas come from
entitlements::chat_quotas(free: 3 a week; Pro: 30 a day and 300 a month); a conversation holds at most 40 turns and a question at most 2000 characters. Denials use fixed copy with no upsell. - Web hand-off.
chat.chunkcarriesseq, the paragraph’s token text, its renderedsegmentsandinterim;chat.message.readycarries the final segments andreplace(the streamed chunks must be discarded: a repair, a refusal, an off-topic or fallback reply after something was streamed, or a retracted message).
Consequences
Section titled “Consequences”- The player only ever sees validated paragraphs, at the cost of a held stream when a paragraph fails, and one extra call for the repair.
- The turn after a repair, follow-up, refusal, off-topic or fallback reply pays a full uncached prefix, because it starts a new session from our record. That is rare, and in exchange the model never sees a rejected answer as accepted history.
- Stricter rules than the brief’s two (
engine_claims,no_quantity_words) follow Task 8’s fix rounds, which made them universal for the report: more chat paragraphs may be repaired or dropped, never fewer checked.
Interface (Task 23)
Section titled “Interface (Task 23)”run_chat_turn(ai, before_call, deps: &OwnedToolDeps, args: ChatTurnArgs, on_chunk) departs
from the plan’s signature:
OwnedToolDeps(T22’sArchandles) instead of&ToolDeps, becausestream_turntakes anArc<dyn ToolHandler>, which must be'static;ChatTurnArgs { evidence, messages, conversation_id, resume, previous_session_usage, first_call_index }instead ofinputandmessages: the SDK session (id, resume), metering and the conversation-wide call indexes need these.evidenceisbuild_evidence(input)plus the anchors throughanchor_details; the caller must build it from the same input and anchors asmessages.
Hand-offs
Section titled “Hand-offs”- Task 25 stores
session_in_syncon the assistant row andnext_call_indexon the conversation, and usesresume_next_turn. A chat turn makes up to three sequentialstream_turncalls (main, follow-up, repair), so the per-calltimeoutMsmust be at mostCHAT_TURN_TIMEOUT / 3, or the reconcile sweep fails a live turn. Count and reserve the chat quota atomically (two concurrent questions can both pass the pure pre-check). - Task 24. If a turn is cancelled while a tool call waits on the engine, the check may never be abandoned; the reconciler must expire stale pending checks and refund them.
The coach-chat job (Task 25)
Section titled “The coach-chat job (Task 25)”Decisions made when the job, the DB data source and the threads were built:
- One turn per conversation. The job holds a session advisory lock (class 30003, the
conversation id) on a dedicated connection that is closed, never pooled, when the handler
ends; a dropped handler or a crashed worker frees it with the connection. A second handler
(a redelivered job, or another answer of the thread) is released and retried. Under the lock,
an answer waits while an earlier answer of the thread is unfinished, so turns run in
seqorder.post_user_messagealso refuses a question while an answer is pending or streaming (Busy, under a row lock on the conversation). The finish transaction runs on the lock connection, so a lost lock fails the write rather than interleaving it. - The chat allowance is reserved atomically (hand-off above). Under a transaction lock per
account of the budget scope (class 30004), the job counts the scope’s assistant answers per
window and moves the message to
streamingin the same transaction. Counted:streaminganswers, anddoneanswers that carry an AI disclosure. The fixed no-data copy has none, so it does not use the allowance. The reservation happens before the no-data and no-AI checks (the brief’s order of the checks is kept). - State that survives restarts lives in Postgres (migration
20261121030200):coach_conversations.next_call_index(the next turn’s first tool-call index; raised withgreatestin the finish transaction),coach_messages.session_in_syncandcoach_messages.turn_attempts. The next turn resumes only when the previous assistant row isdonewithsession_in_sync = trueand the history did not roll over. A failed or lost turn is never in sync, so the turn after it sends the full Postgres history withresume: falseand the sidecar replaces the partial session. - Unavailable retries. A
Releasegives its queue attempt back, so the job cannot count attempts from the queue.turn_attemptscounts the turn’s AI attempts: the first unavailable attempt puts the message back topending(the retry reserves again) and releases for 60 s; the second fails withunavailable. The whole turn runs underCHAT_TURN_TIMEOUT(600 s); a timeout counts as unavailable. - Timeouts (amended by fix round 1, review I2). A turn is the rollover summary plus up to
three sequential chat calls (main, follow-up, repair), all inside
CHAT_TURN_TIMEOUT(600 s):SUMMARY_CALL_TIMEOUT(60 s) bounds the summary call, andCHAT_CALL_TIMEOUT(180 s, whichSidecarConfig::chat_timeoutmust not exceed) bounds each chat call; 60 + 3 × 180 = 600, which a test pins. A summary that runs over is skipped (the old summary is kept, and the turn still starts a new session). The title call after the turn has the same 60 s bound. This supersedes the earlier note to passCHAT_TURN_TIMEOUTitself astimeoutMs. - History after a rollover. Once a summary exists, later turns (until the next rollover) use
Rollover { stored summary, the last replay_turns turns }without a new summary call. Only a turn that writes a new summary counts as a rollover forresume_next_turn, so the session started by the rollover turn is resumed afterwards. - Deleted mid-turn. The finish transaction re-checks the conversation with
FOR SHARE(waiting for a delete in progress). If it is gone, the paid calls are still metered (usage rows have no content) and the conversation’s orphaned session entries are deleted. - Titles. After the first answered turn,
summarise_thread(metered as chat) gives the title, or the anchor’s fallback title when the call fails or the title does not pass. Refusal, off-topic and fallback turns get the fallback title without a call. - The data source reads weaknesses, openings and exemplars from the conversation’s coaching
input (the newest report-run snapshot of the account and time class), and positions, games,
cached evals and report sections from Postgres, always filtered on the account.
get_gamesis limited to the conversation’s time class.openingContainsmatches literally (\,%and_escaped). Position tags come from the matching exemplars until R2’s per-move tags exist. - Threads belong to the user (fix round 1, review I3; supersedes “threads take the
account”). Linked accounts are shared between users (M4
account_links), socoach_conversations.user_idis NOT NULL (migration20261121030300, with an index on(user_id, account_id, last_message_at); the FK to"user"is added by Task 26’s integration migration, and the tests create real users withtestkit::insert_user). Every read, post, list and delete is scoped byuser_id; the account is the context. A thread is created, and posted to, only for an account the user is currently linked to (AccountAccess;LegacyAccountAccessreads M1’slinked_accounts.user_id, and Task 26 wires theaccount_linkslookup). A user may still read and delete their threads after unlinking. Quotas and budgets stay per account (ruling Q3). - Task 18 stand-ins. T18 is not on this base.
jobs/budget.rsholds minimal versions ofBudgetConfig,budget_guardandmeter, andChatDepscarries aPricingTable. At merge, T18’s file replaces them and the call sites inchat/job.rsare adapted. - Every paid call is metered (coordinator ruling, the T14 class of bug).
run_chat_turnreturnsChatTurnError { error, calls }, like T14’sSectionError:callsholds the calls already paid for when a later call (a follow-up or repair) fails or the budget hook stops it. The job meters them (chat, ref = the message id) on every error path, includingUnavailableandBudget. A call that fails mid-stream reports no usage, so it cannot be metered. - Retries are never in sync (fix round 1, review I1). A retried AI attempt of the same
message (
turn_attempts > 1: an unavailable release, a timeout or a worker crash) sends the full Postgres history withresume: false, because the SDK session may hold the failed attempt’s question, answer and tool results; the sidecar replaces it. A failed attempt stores its call-index counter before it is retried; a redelivery after a crash (nobody stored it) skips the counter byCALL_INDEX_RETRY_GAP(1000). So atools.<k>path is never reused. - Idempotent metering (fix round 1, review I1 and m1).
ai_usage.idempotency_keyis unique. A chat call is keyedchat:<message>:<attempt>:<n>(summary calls…:summary:<n>, the titlechat:<message>:title:<n>), so metering the same calls again (a finish that rolled back after metering, a retried write) adds nothing, while a retry’s own calls, paid again, get new keys. The turn’s calls are collected in aTurnSinkoutside the timed future, so a timeout meters them too (review I2). A call whose response never arrived reports no usage and cannot be metered. An unpriced model is metered at the most expensive known rate, never at zero. - Known gaps (review m3): the windows count an answer by its message’s
created_at(the post time), not the reservation time, so a question posted just before a window boundary counts in the old window; and a turn that fails after paid calls uses no chat allowance (the budget guard bounds the spend). - Chat events belong to the thread owner (fix round 2, review N1; binding hand-off to M4
and the R3 integration).
user_events.user_id(nullable, migration20261121030400): an event with a non-nulluser_idis for that user only. Every chat event (chat.chunkwith answer text,chat.message.ready,chat.message.failed, including the reconciler’s lost-chat failure) is written with the conversation’suser_id(events::emit_for_user, R1’sinsert_owned_event; the NOTIFY JSON carriesuserId). The web SSE hub and the poll route MUST deliver an event to a user only whenuser_id IS NULL OR user_id = <that user>; account events keepuser_idNULL. Chat must not be exposed before that filter lands. - The link is re-checked at the reservation (fix round 2).
ChatDeps.accessis the sameAccountAccessas the thread API. If the thread owner is no longer linked to the account when the job runs, the message fails withnot_linked(its event to the owner), before the allowance, with no AI call and nothing metered. An unlinked owner can still read, list and delete their own threads, but not post (§10).
Integration (Task 26)
Section titled “Integration (Task 26)”- The filter landed on
main(commit c00f469,fix(events)): the SSE hub, the replay and the/api/eventspoll route deliver an owned event only to its user. In Rust the rule is now enforced at the source:events::EVENT_KINDSgives every kind itsAudience, andemitrefuses aUserkind (EmitError::NeedsOwner), so a chat event can only be written withemit_for_user. A kind missing from the table is refused too (UnknownKind, deny by default; fix round 1). The kinds that are about one user’s thread arechat.chunk(the only one carrying model text),chat.message.readyandchat.message.failed. Report, weekly-review and change-note events carry ids and codes only: their text lives in the account’s own rows, which every user linked to the account reads, so they stay account events (user_idNULL).tests/integration.rslists every kind, checks that each declared kind is classified, and that any kind whose payload carries free text is user-owned and stored with its owner. - Account access is M4’s
account_links. The worker wiresAccountLinksAccess: a user may start or post to a thread for an account they hold any link to, verified or not, exactly as the web’suserAccountIdsreads it (ADR-WEB-3, ADR-WEB-8).LegacyAccountAccess(linked_accounts.user_id) stays for the CLI-era owner and tests. Follow-up for M4: an unverified link reaches the account’s reports and chat; if that should need a verified link, both the web and this lookup change together. - Threads belong to
"user"rows. Migration20261121030500_integration_user_fks.sqladdscoach_conversations.user_id REFERENCES "user"(id) ON DELETE CASCADEwhere M4’s table exists (M4’s20261121010000sorts first on the integrated schema; R3 alone has no such table, and there it adds nothing). Deleting a user deletes their threads, messages and, by T17’s trigger, their Agent SDK session entries.user_events.user_idgets no FK (an owned event of a deleted user is unreadable anyway).