Skip to content

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

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

  1. Where it runs. The chat runs in the worker (coach-chat job, Task 25). One turn is one stream_turn with the chat tools: the sidecar runs up to max_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.
  2. 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 feeds analyse_position, and its position joins the turn’s evidence.
  3. Validate before publish. The streamed text is split on blank lines. Each paragraph is validated (validate_text with implicit citations, no required citation, and the rules banned_phrases, no_marketing, engine_claims and no_quantity_words) against build_evidence(input) plus the anchors plus this turn’s tool evidence, all in one ToolSession. 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.
  4. 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 to system[1] in code.
  5. 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).
  6. 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 gets engine busy.
  7. 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 an Answered turn 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 (Verbatim or Rollover) with resume: false and 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 own model_usage (path new).
    • 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. A tools.<k> token copied from an earlier turn then fails closed instead of resolving to another result.
  8. Prompts. The chat’s prompts are registered T13 files (CHAT_PROMPT_SET, chat@1): system[0] is the shared rules_block() (core/rules + core/tokens, byte-identical to the report’s, so one cache entry serves both); system[1] is chat/system, whose “Output in this chat” section asks for plain paragraphs, with positions cited by their own tokens and no JSON, schema or citations field; the repair renders chat/repair with T13’s - path: code: detail lines, the path naming the paragraph (chat.<n>). The report’s report/output and repair/repair are never sent in a chat.
  9. 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 Done gives the stored sessionModelUsage. 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 by max_tokens is 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.
  10. 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.
  11. Web hand-off. chat.chunk carries seq, the paragraph’s token text, its rendered segments and interim; chat.message.ready carries the final segments and replace (the streamed chunks must be discarded: a repair, a refusal, an off-topic or fallback reply after something was streamed, or a retracted message).
  • 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.

run_chat_turn(ai, before_call, deps: &OwnedToolDeps, args: ChatTurnArgs, on_chunk) departs from the plan’s signature:

  • OwnedToolDeps (T22’s Arc handles) instead of &ToolDeps, because stream_turn takes an Arc<dyn ToolHandler>, which must be 'static;
  • ChatTurnArgs { evidence, messages, conversation_id, resume, previous_session_usage, first_call_index } instead of input and messages: the SDK session (id, resume), metering and the conversation-wide call indexes need these. evidence is build_evidence(input) plus the anchors through anchor_details; the caller must build it from the same input and anchors as messages.
  • Task 25 stores session_in_sync on the assistant row and next_call_index on the conversation, and uses resume_next_turn. A chat turn makes up to three sequential stream_turn calls (main, follow-up, repair), so the per-call timeoutMs must be at most CHAT_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.

Decisions made when the job, the DB data source and the threads were built:

  1. 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 seq order. post_user_message also 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.
  2. 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 streaming in the same transaction. Counted: streaming answers, and done answers 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).
  3. State that survives restarts lives in Postgres (migration 20261121030200): coach_conversations.next_call_index (the next turn’s first tool-call index; raised with greatest in the finish transaction), coach_messages.session_in_sync and coach_messages.turn_attempts. The next turn resumes only when the previous assistant row is done with session_in_sync = true and 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 with resume: false and the sidecar replaces the partial session.
  4. Unavailable retries. A Release gives its queue attempt back, so the job cannot count attempts from the queue. turn_attempts counts the turn’s AI attempts: the first unavailable attempt puts the message back to pending (the retry reserves again) and releases for 60 s; the second fails with unavailable. The whole turn runs under CHAT_TURN_TIMEOUT (600 s); a timeout counts as unavailable.
  5. 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, and CHAT_CALL_TIMEOUT (180 s, which SidecarConfig::chat_timeout must 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 pass CHAT_TURN_TIMEOUT itself as timeoutMs.
  6. 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 for resume_next_turn, so the session started by the rollover turn is resumed afterwards.
  7. 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.
  8. 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.
  9. 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_games is limited to the conversation’s time class. openingContains matches literally (\, % and _ escaped). Position tags come from the matching exemplars until R2’s per-move tags exist.
  10. Threads belong to the user (fix round 1, review I3; supersedes “threads take the account”). Linked accounts are shared between users (M4 account_links), so coach_conversations.user_id is NOT NULL (migration 20261121030300, 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 with testkit::insert_user). Every read, post, list and delete is scoped by user_id; the account is the context. A thread is created, and posted to, only for an account the user is currently linked to (AccountAccess; LegacyAccountAccess reads M1’s linked_accounts.user_id, and Task 26 wires the account_links lookup). A user may still read and delete their threads after unlinking. Quotas and budgets stay per account (ruling Q3).
  11. Task 18 stand-ins. T18 is not on this base. jobs/budget.rs holds minimal versions of BudgetConfig, budget_guard and meter, and ChatDeps carries a PricingTable. At merge, T18’s file replaces them and the call sites in chat/job.rs are adapted.
  12. Every paid call is metered (coordinator ruling, the T14 class of bug). run_chat_turn returns ChatTurnError { error, calls }, like T14’s SectionError: calls holds 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, including Unavailable and Budget. A call that fails mid-stream reports no usage, so it cannot be metered.
  13. 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 with resume: 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 by CALL_INDEX_RETRY_GAP (1000). So a tools.<k> path is never reused.
  14. Idempotent metering (fix round 1, review I1 and m1). ai_usage.idempotency_key is unique. A chat call is keyed chat:<message>:<attempt>:<n> (summary calls …:summary:<n>, the title chat:<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 a TurnSink outside 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.
  15. 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).
  16. 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, migration 20261121030400): an event with a non-null user_id is for that user only. Every chat event (chat.chunk with answer text, chat.message.ready, chat.message.failed, including the reconciler’s lost-chat failure) is written with the conversation’s user_id (events::emit_for_user, R1’s insert_owned_event; the NOTIFY JSON carries userId). The web SSE hub and the poll route MUST deliver an event to a user only when user_id IS NULL OR user_id = <that user>; account events keep user_id NULL. Chat must not be exposed before that filter lands.
  17. The link is re-checked at the reservation (fix round 2). ChatDeps.access is the same AccountAccess as the thread API. If the thread owner is no longer linked to the account when the job runs, the message fails with not_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).
  1. The filter landed on main (commit c00f469, fix(events)): the SSE hub, the replay and the /api/events poll route deliver an owned event only to its user. In Rust the rule is now enforced at the source: events::EVENT_KINDS gives every kind its Audience, and emit refuses a User kind (EmitError::NeedsOwner), so a chat event can only be written with emit_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 are chat.chunk (the only one carrying model text), chat.message.ready and chat.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_id NULL). tests/integration.rs lists 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.
  2. Account access is M4’s account_links. The worker wires AccountLinksAccess: a user may start or post to a thread for an account they hold any link to, verified or not, exactly as the web’s userAccountIds reads 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.
  3. Threads belong to "user" rows. Migration 20261121030500_integration_user_fks.sql adds coach_conversations.user_id REFERENCES "user"(id) ON DELETE CASCADE where M4’s table exists (M4’s 20261121010000 sorts 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_id gets no FK (an owned event of a deleted user is unreadable anyway).