Skip to Content
Recodocs

Transaction truth before model prose

The model may classify intent and write empathy; it may not choose SQL, scope another customer's order, or promise timelines the tat_policy table does not allow.

8 min read

When a customer asks where their money is, the relevant issue is the transaction they actually mean and what the current records establish. A reassuring reply that guesses the status is not a successful resolution.

Priya Sharma sends POST /v1/support/chat with customer 11111111-1111-1111-1111-111111111101, transaction 33333333-3333-3333-3333-333333333301, and the message “Where is my money? I redeemed 4 days ago.” Before any Codex call, run_chat in app/agent/pipeline.py confirms that transaction belongs to her. classify_intent in app/agent/intent.py returns category withdrawal. gather_grounded_facts in app/agent/tools.py loads the row whose order_ref is WD-PS-2026-001, status bank_credit_initiated, plus masked bank details and a tat_policy range. generate_answer composes a GroundedAnswer. apply_guardrails passes when the rule check is clean, attempts a repair call when it is not, and on a repair exception keeps passed false with the original violations. The JSON bundles intent, answer, guardrail, and the same grounded_facts the model saw.

This is a fixed model-assisted pipeline, not an agent. There is no tool-selection loop: code runs every SQLite query. Category selects the fetch branch, and when the request omits transaction_id the model’s transaction_id selects the row.

The claim is that mutual-fund support stays grounded when SQLite owns facts and ownership, category selects the fetch, a missing request id lets the model’s transaction_id select the row, the model composes from those rows, and guardrails—not politeness—block advice and invented timelines. Customers and orders in data/support.db are synthetic derived seed; the argument below is about structure, not production ticket volume.

The argument

  1. Ownership is decided in Python before Codex. A transaction_id for another customer raises TransactionNotFound and HTTP 404. A model-picked id is cleared only after a scoped get_transaction lookup fails.
  2. Category selects the fetch branch. Withdrawal, lumpsum, sip, and kyc each map to a fixed fetch path in gather_grounded_facts. When the request omits transaction_id, the model’s transaction_id selects the row. The model does not call get_transaction.
  3. Prose must cite rows that were fetched. The responder prompt requires cited_facts copied from grounded_facts; evals additionally require named substrings such as WD-PS-2026-001.
  4. Compliance failures are rule-first. Regex and TAT-number checks in apply_guardrails run before an optional repair call; a failed repair keeps the rule verdict.

Who is allowed to decide

The tempting design hands the model SQL, policies, and tone in one chat loop. This repository deliberately refuses that shape. The README states a fixed model-assisted pipeline, not an agent. In run_chat, category selects the fetch branch, and when the request omits transaction_id the model’s transaction_id selects the row.

Fixed chat pipeline inside run_chat
Grounded support boundaryA customer posts to support chat. Inside run_chat, transaction ownership is checked, classify_intent picks a category, gather_grounded_facts runs deterministic SQL, generate_answer composes text, and apply_guardrails enforces compliance.CustomerPriya Sharmacustomer_id fixedin request bodyStopped hereForeign txn idTransactionNotFoundno model callrun_chatPipelineTransaction gate404 before modelclassify_intentcategory onlygather_grounded_factsfixed SQLite branchgenerate_answerprose from factsapply_guardrailsrules then repairSQLitesupport.dbread-only per queryderived seed rowsCodexcomplete_structuredintent, answer, repairno tool loopPOST /chatResponseSQLrowsintentanswer

The dashed box is labeled run_chat. The orange card reads Stopped here, Foreign txn id, TransactionNotFound, and no model call. When the request body carries a transaction_id, run_chat calls tools.get_transaction with both id and customer_id. A missing or foreign row raises TransactionNotFound with detail Transaction not found: <id>—mapped in app/main.py to 404 before any model route. That is stronger than telling the model not to peek at another customer’s rows: the query appends AND t.customer_id = ? when scoped.

Inside the box, classify_intent receives the user message, optional context transaction, and up to ten recent transactions serialized from SQLite. Its system prompt lists four categories—withdrawal, lumpsum, sip, kyc—and forbids inventing transaction ids. After classification, gather_grounded_facts is deterministic SQL: it walks _category_detail, pulls tat_policy for the row’s status, and for withdrawals attaches get_bank_account_masked. generate_answer is another model call, and guardrails may add a repair call. The responder call sees the system prompt and a user JSON object that includes the message, the proactive flag, the instruction, and grounded_facts.

Codex enters through app/llm.complete_structured: strict JSON schema, Pydantic validation, one repair attempt on schema failure, and at most two route attempts before ModelUnavailable becomes HTTP 503. Receipts append to data/local/model-usage.jsonl. Queries are read-only; initialize can write schema and seed once when support.db is created.

HTTP serves the chat handler twice: demo.py calls POST /v1/support/chat, and legacy POST /chat is a second mount of the same handler, behind the same bearer. Proactive landing uses run_proactive, which already knows the transaction’s category from SQLite yet still calls classify_intent because removing it would change the intent value returned, not the response schema—an intentional duplication noted in docs/kit-migration.md.

The authority split is also visible in types. IntentResult in app/agent/schemas.py carries category, sub_intent, optional transaction_id, and confidence as a float from 0 to 1. The pipeline does not use confidence to skip SQL. GroundedAnswer separates empathy from factual fields so guardrails can scan a single blob built from context, current_status, next_step, and cited_facts. When category and transaction disagree—asking SIP questions while pointing at a lumpsum id—_transaction_detail returns a structured error such as not_a_sip rather than letting the model improvise a reconciliation story.

Runtime identity is equally host-owned. GET /health exposes status, runtime, session_id, and runtime_generation; GET /v1/capabilities advertises capabilities: ["support"]. Those endpoints describe the deployment, not the customer’s portfolio. The support routes themselves never mutate ledger rows: initialize may bootstrap schema and seed once per fresh support.db file, after which every handler only opens read-only connections through recohut_kit.storage.sqlite.connect.

What the evidence shows

Mechanisms are easy to confuse with measurements. The repo separates guards encoded in code from golden-set runs that need a live model grant.

From cited_facts back to the transaction row
Grounded answer chainThe composed answer lists cited_facts including order_ref WD-PS-2026-001. That reference resolves to transaction 333333333301 with status bank_credit_initiated and a tat_policy row for withdrawal timing.cited_factsempathy_openercurrent_statusWD-PS-2026-001order_refbank_credit_initiated125000.00 INRtat_policybusiness daysmin–max rangeGroundedAnswercomposed fieldsorder_refin cited_factstransactionsprimary rowtat_policyallowed timelines

The figure cards are GroundedAnswer, order_ref, transactions, and tat_policy, with labels cited_facts, WD-PS-2026-001, bank_credit_initiated, 125000.00 INR, and a min–max business-days range. Eval case wd-001 in evals/dataset.jsonl expects the answer to touch substrings WD-PS-2026-001 and bank_credit_initiated, matching Priya’s seed row in seed/seed_data.sql. Those strings should appear because RESPONDER_SYSTEM in app/agent/responder.py demands cited_facts list short verbatim strings copied from grounded_facts, and because timeline language must come from tat_policy min/max business days—not invented calendar promises unless expected_credit_at is in facts.

Guardrail path in apply_guardrails
Rule gate before optional repair_rule_checkregex + TAT numsviolationsadvice / timelinerepaircomplete_structuredpassed=True when violations emptyonly if rules fail first

Guardrails combine deterministic rules with a conditional repair. _rule_check scans context, current_status, next_step, and cited_facts, not empathy_opener, for investment-advice regexes (buy, recommend, redeem now, and similar) and for \d+ business days phrases whose numbers are not present in allowed TAT text extracted from grounded_facts. Violations trigger a third model call, the repair inside apply_guardrails, after intent and answer. If repair fails, GuardrailResult.passed stays false with the original violation list.

Cross-customer isolation is likewise testable in principle without a model: get_transaction(transaction_id, customer_id=customer_id) is how every gather path loads primary_transaction. The migration note records the before/after: previously an unscoped lookup could leak another customer’s name and email; now a foreign id is indistinguishable from missing at the HTTP layer.

For model behaviour, the stored evals/report.json records one completed golden run on the Codex route with model gpt-6-luna: six cases, six passed, thresholds accuracy ≥ 4, empathy ≥ 3, compliance ≥ 4. Case wd-001 shows grounded_ok, category_ok, and guardrail_passed all true with judge scores 5/5/5. That file is evidence of one eval sweep, not a continuous monitor. docs/kit-migration.md states that no pytest suite exists in this project.

Seed breadth matters for falsification. The README lists six customers, ten transactions, and seventeen tat_policy rows; categories cover withdrawal anxiety, SIP pending, lumpsum failure, and KYC under_review. sip-001 passes a transaction id; only kyc-001 leaves it null, which is the path that can pick a recent row or call get_kyc_case. That path still never delegates SQL text to the model.

What would weaken the claim is an eval pass where cited substrings are absent yet grounded_ok is true, or a chat where guardrails pass while _rule_check would flag an unlisted business-day count. What would strengthen it is the same golden set re-run after prompt edits, with failures pinned to grounding_check before invoking the judge.

The turn we traced

The scripted HTTP demo in demo.py includes the same Priya withdrawal scenario as golden case wd-001. The sequence is:

  1. Client supplies customer_id, message, and transaction_id 33333333-3333-3333-3333-333333333301.
  2. run_chat validates ownership via get_transaction.
  3. list_customer_transactions supplies recent rows for intent context.
  4. classify_intent returns IntentResult with category and sub_intent. The recorded result for this message is withdrawal / where_is_my_money.
  5. If the model proposes another customer’s transaction id, pipeline nulls it when get_transaction fails the scope check.
  6. gather_grounded_facts sets primary_transaction and category_detail including tat_policy for bank_credit_initiated.
  7. generate_answer fills GroundedAnswer fields: empathy opener, context, status, next step, cited_facts.
  8. apply_guardrails returns a GuardrailResult that may be a clean pass, a repair payload, or a failed verdict with the original violations.
  9. SupportResponse echoes grounded_facts for auditing and for evals/judge.py.
  10. Optional proactive twin: run_proactive on the same transaction id primes status before the user types. It uses the same gather and guardrail functions, but it takes the category from SQLite and classifies after the fetch.

The withdrawal row’s order_ref WD-PS-2026-001, amount_inr 125000.00, fund HDFC Flexi Cap Fund, and expected_credit_at relative timestamp all live in seed SQL. The pipeline reads seed columns such as amount_inr. The README v2 mapping is authoritative rows, model prose from those facts, and guardrails.

The one check to copy

Copy the eval substring gate, not the mutual-fund nouns. In evals/run_eval.py, grounding_check is the named function every golden case must satisfy:

def grounding_check(answer_blob: str, must_cite: list[str]) -> bool:
    lower = answer_blob.lower()
    return all(s.lower() in lower for s in must_cite)

Case wd-001 pairs that helper with must_cite_substrings ["WD-PS-2026-001", "bank_credit_initiated"] and expected_category withdrawal. A pass requires those literals to appear in the formatted answer text, the intent category to match, guardrails to pass, and judge scores to meet the PASS_ACCURACY, PASS_EMPATHY, and PASS_COMPLIANCE constants (4, 3, and 4) in the same file. That is the closest thing this repo names as an automated grounding test: not pytest, but a deterministic substring intersection over composed prose.

The judge (evals/judge.py) is a separate structured call scoring accuracy, empathy, and compliance 1–5. It does not replace grounding_check; both must succeed in case_pass. Treat the substring list as the host’s citation intersection—the analogue of keeping only evidence ids a tool returned on a prior turn.

The same pattern ports to any ticket desk where session state fixes the customer, SQL returns canonical ids, and the model only narrates. Swap order refs for claim numbers; keep the host-owned set of strings that must survive into the final message.

Close

Grounded customer support is easy to mislabel as an “agent” because a clean path calls the model twice, for intent and the answer; repair runs only when _rule_check finds violations. The code describes something narrower—a pipeline where classify_intent chooses among four categories, tools.gather_grounded_facts owns every join, and guardrails enforce compliance before the API returns. Priya’s withdrawal story works when WD-PS-2026-001 and bank_credit_initiated in the answer trace back to the same SQLite row the host already fetched. Extend the system by adding SQL branches and seed rows, not by giving the model another tool.

How is this page?

Last updated on