diff --git "a/api/routes_query.py" "b/api/routes_query.py" --- "a/api/routes_query.py" +++ "b/api/routes_query.py" @@ -1,123 +1,76 @@ -"""routes_query.py — WAVE 32 item 7 (ruling R1, contract C5): the Query module's doors. - - POST /api/v1/query/build {question, scope} -> {spec, explain, refused} WRITES NOTHING - POST /api/v1/query/save {question, scope, spec} -> the saved view - GET /api/v1/query -> the AI-built views this caller may open - DELETE /api/v1/query/{qid} -> forget one - -**The AI turns a question about ONE granted database into a view SPEC. It may only build what the -backend already supports** (R1), and the wall on which database it may name is the EXISTING one. - -⛔ THE FOUNDATION IS NOT `harness/semantic.py` — MEASURED, W32-T50 -(`.claude/wiki/waves/wave32/proto/query-spike/README.md`). That layer is bound to 8 hand-authored -YAML topics over Odoo mirror tables: **0** are `ut_`-bound, and a `ut_` key answers -`ModelError: topic 'ut_…' has no store binding` from both `store_columns` and `store_query`. Its -own `save_view` writes `platform/data/store/views.json`, a chart workspace the product's grid -cannot read. What it lends this file is its POSTURE, quoted from its system prompt: *the model -never writes SQL and never invents a field name — it only picks registry keys.* - -The real foundation is the view stack that already ships, and this module is `routes_templates.py` -with a model where the curated registry used to be: - - · the wall `routes_templates._target_or_refuse` (imported, never re-implemented) - · the column contract `core.view_templates.columns_named` / `missing_columns` - · the view skeleton `core.view_templates._view` (one definition of what a view is) - · the validators `aios_grid._clean_display` / `clean_filter_tree` - · the writer `core.table_store.make(ws).save_view(..., shared=False)` - -⛔⛔ THE VALIDATORS DROP; THEY DO NOT REFUSE — and C5 requires a REFUSAL. `_clean_display` returns -None for an unknown mode, and a view with no display block IS A GRID; `clean_filter_tree` drops a -leaf naming an unknown column, and a view whose only condition was dropped SHOWS EVERY ROW under a -name promising a shortlist (`view_templates`' own scar, and `_seed_wave17`'s before it). So -membership is tested HERE, first and explicitly, and the cleaners run second as a belt. They are -the vocabulary ORACLE, never the refusal. - -⛔ THE REFUSAL PATH IS A MODEL PROPERTY, so this module declares its OWN provider order rather than -inheriting `analyst.available_providers()`' cheap-first one. Measured over 4 arms x 9 questions -(`proto/query-spike/refusal-arms.json`): `cerebras/gpt-oss-120b` refuses 4/4 unanswerable questions -with a usable sentence; `groq/llama-3.3-70b` refuses **0/4** and instead emits a fully valid spec -answering a different question ("Revenue by Creator" against a database holding no revenue). -Changing refusal from an enum value to its own tool changed cerebras not at all and made groq -worse. -⚠ AND THE LADDER STILL FALLS THROUGH ON A 429, WHICH IS A COMPROMISE, NOT AN OVERSIGHT — stated -here because the first draft of this header claimed the opposite. A door that dies whenever one -free tier rate-limits is worse than one that answers with a weaker model behind the SAME validator -and the SAME human read-back. What "fail closed" means precisely: when the whole ladder is -unreachable the answer is a sentence and never a view. Which provider answered rides back in the -response so a wrong answer stays diagnosable (`_call_model`'s note). - -⛔ AND A PROVIDER `400` CAN BE THE MODEL'S REFUSAL. Groq validates the model's tool arguments -against the tool schema server-side and answers `400 tool_use_failed` carrying the model's real -output in `failed_generation` — so a refusal that omits a `required` property arrives as an HTTP -error. `analyst._live_chat` calls `raise_for_status()` and discards that body, which is why this -file has its own small ladder: `required` is `["kind"]` ALONE (a refusal must be a legal argument -object), and a 400 body is READ before it is treated as transport. - -⚠ WHAT NO VALIDATOR CAN SEE, stated so nobody thinks the gate covers it: a spec whose every column -is real, every op legal, kind in the vocabulary and target granted, which answers a DIFFERENT -QUESTION. That class is invisible to server-side validation. The mechanism against it is C5's own -shape — `build` returns `{spec, explain}` and WRITES NOTHING, `explain` is DERIVED from the -validated spec (never asked of the model, which would let it flatter its own output), and saving is -a second, explicit call. The person is the last validator, by design. +"""Assistant chat and Query-owned virtual artefacts (W33-T72 / C8). + +Query reads only the detached, permission-filtered snapshot from +``deps.assistant_read_scope``. It owns a separate per-user namespace for threads, messages, +citations and virtual views; it never opens or mutates a source workspace. """ +import copy +import csv import datetime as _dt import hashlib +import io import json import os import re +import uuid -from fastapi import APIRouter, Body, Depends +from fastapi import APIRouter, Body, Depends, Response -from deps import Session, err, require_session +from deps import (Session, assistant_read_scope, assistant_source_status, err, + require_session) router = APIRouter(prefix="/api/v1") -#: The store key holding the REGISTRY of AI-built views, per tenant: {qid: {...}}. The view itself -#: is a real saved view in its target's own workspace — this is only the index, so listing the -#: Query module never has to read every granted table's workspace to find them. Same split -#: `core/alerts.py` draws between definitions and the inbox. -QUERY_KEY = 'query_views' - MAX_QUESTION = 500 MAX_VISIBLE = 24 -MAX_REGISTRY = 200 #: a working list, not an archive (alerts' MAX_NOTIFICATIONS rule) - -#: ⭐ THE KINDS THE AI MAY EMIT. Held here as a NAMED SET, and `verify_query.py` asserts it is a -#: subset of BOTH `aios_grid.DISPLAY_MODES` (the stored vocabulary) and the client's -#: `CREATABLE_MODES` (which means "has a mounted renderer" — `verify_icons::mode_parity` enforces -#: that both ways), AND that the excluded remainder is exactly `QUERY_EXCLUDED`. So a mode that -#: lands in `CREATABLE_MODES` later REDS the gate instead of being silently un-offered — the -#: `swipe`/`form` failure ("whole, correct and unreachable") in reverse. -QUERY_KINDS = ('grid', 'chart', 'calendar', 'kanban', 'timeseries', 'map', 'list') - -#: Creatable modes the AI deliberately may NOT emit, each with the reason it cannot be derived -#: from a question about existing records. A reason per member, because "excluded" with no cause -#: is how a hold outlives its own justification. +MAX_ARTIFACTS = 200 +# ⭐⭐ R16 — THE THREAD IS REPLAYED, AND THESE TWO NUMBERS ARE THE WHOLE BOUND ON IT. +# The chat was STATELESS: `_call_model` built `[system, user(question)]` and the conversation on +# screen reached the model as nothing at all, so "what about the other one?" could not be answered +# and the assistant could not grill anybody about anything. Replay is bounded twice because the +# two limits fail differently: a turn COUNT stops a long chat costing more every turn, and a +# CHARACTER budget stops one pasted wall of text from being the whole context. Both count from the +# NEWEST end, because that is what a pronoun refers to. +MAX_HISTORY_TURNS = 12 +MAX_HISTORY_CHARS = 6000 +MAX_RATING_REASON = 200 +QUERY_RATINGS = ("up", "down") +MODEL_AUTO = "auto" +# ⛔⛔ WHY QUERY DECLARES THE ENV NAMES RATHER THAN READING `analyst.PROVIDERS`: MEASURED +# 2026-08-16, `import harness.analyst` costs **5 to 8 SECONDS**, warm, on this box (it pulls +# `harness.tools`, which pulls yaml and the skill recipes). `GET /query` is a LIST path that BOTH +# the Assistant and Query call on mount, so importing the ladder to answer "which models can this +# deployment actually call?" would put eight seconds on the first paint of the AI module. The map +# below is Query's own declaration, and it is deliberately the cheap half. +# ⚠ A SECOND DECLARATION IS A DIVERGENCE WAITING TO HAPPEN, so it is CHECKED rather than trusted: +# `_providers()` already holds the platform ladder in memory and reconciles there, and anything it +# finds is REPORTED into the payload instead of a provider silently never being offered. +# The ORDER is Query's own and is deliberate: cerebras first, because this path needs tool calling +# and cerebras carries this account's tool-capable model. +QUERY_PROVIDER_ENV = { + "cerebras": "CEREBRAS_API_KEY", + "groq": "GROQ_API_KEY", + "openrouter": "OPENROUTER_API_KEY", +} +QUERY_PROVIDER_ORDER = tuple(QUERY_PROVIDER_ENV) +# Filled the first time the platform ladder is loaded; empty means "not yet known", never "clean". +_LADDER_DRIFT = [] +QUERY_KINDS = ("grid", "chart", "calendar", "kanban", "timeseries", "map", "list") +QUERY_WORKSPACE_EVENTS = {"view_create", "view_upsert", "view_delete"} QUERY_EXCLUDED = { - 'form': "a form is a door records come IN through and shows none — a question about existing " - "records cannot describe one, and its spec carries emails and a public token", - 'catalog': "a catalog is a published artifact needing page authoring and product codes " - "(MAX_CATALOG_CODES is spent in page order), not a shape of the current rows", - 'swipe': "a swipe deck needs an empty single-select plus a chosen option per direction — two " - "product decisions a question does not contain", + "form": "Forms collect new data and are not a read-only Query artefact.", + "catalog": "Catalog is a source-native presentation that Query cannot safely mutate.", + "swipe": "Swipe is an interactive source-native presentation, not an Assistant output.", } - -#: Mode-required refs, and the field FAMILY each one demands. ⚠ STRICTER THAN `_clean_display` ON -#: PURPOSE. That function accepts any ref naming a real field and leaves the meaning to the client, -#: which "degrades a wrong-typed ref to that surface's default rather than to an error" — correct -#: for a person clicking a picker who SEES the result, wrong for a generated spec nobody has looked -#: at yet. Measured: a free model stacked a kanban on `category` (a text column) for a contract -#: with ZERO select columns, and every validator passed it. _MODE_REFS = { - 'kanban': [('stackField', ('select',), True)], - 'calendar': [('dateField', ('date',), True)], - 'timeseries': [('dateField', ('date',), True)], - 'map': [('colorField', ('select',), False), ('sizeField', ('int', 'currency', 'pct'), False)], + "kanban": [("stackField", ("select",), True)], + "calendar": [("dateField", ("date",), True)], + "timeseries": [("dateField", ("date",), True)], + "map": [("colorField", ("select",), False), ("sizeField", ("int", "currency", "pct"), False)], } def _now_iso(): - """UTC WITH the offset — a naive stamp is unsubtractable in a browser (D-18, alerts' rule).""" return _dt.datetime.now(_dt.timezone.utc).isoformat() @@ -126,89 +79,176 @@ def _grid(): return aios_grid -def _templates(): - import core.view_templates as view_templates - return view_templates +def _safe(value): + """Detach values before they enter a durable Query object or an API reply.""" + return json.loads(json.dumps(value, default=str)) + + +def _namespace_key(session): + """A tenant runtime has one isolated key for each user's Query-owned objects.""" + principal = f"{session.tenant}:{session.uname}".encode("utf-8") + return "query_user_" + hashlib.sha256(principal).hexdigest()[:24] + + +def _blank_state(): + return {"version": 1, "threads": {}, "messages": {}, "citations": {}, "views": {}} + + +def _state(session): + try: + raw = session.runtime.get(_namespace_key(session)) or {} + except Exception: + raw = {} + if not isinstance(raw, dict): + return _blank_state() + out = _blank_state() + for key in out: + if key == "version": + continue + if isinstance(raw.get(key), dict): + out[key] = copy.deepcopy(raw[key]) + return out + + +def _new_id(prefix): + return f"{prefix}_{uuid.uuid4().hex[:16]}" + +def model_choices(): + """Choices are stable even when one is not configured, so explicit means explicit.""" + return [MODEL_AUTO, *QUERY_PROVIDER_ORDER] -def _target(session, scope): - """`(fields, source)` for a database this session may open — or a refusal. - ⛔ THE WALL IS `routes_templates._target_or_refuse`, IMPORTED AND NOT COPIED. It is the same - predicate the nav uses, per topic (`ut_*` -> `user_tables.may_open`; a built-in -> the module - grant `session.require`; anything else a 404 that is not a directory of what exists), and T51's - instruction is explicit that the wall is re-used, never re-implemented beside itself. The - private name is deliberate: an alias would mean editing a file no lane's fence covers. +def model_status(): + """Per choice: can this deployment actually CALL it, and if not, why not. - It returns field KEYS; this door also needs each field's TYPE (for the prompt and for - `_MODE_REFS`), so the types are read from the same source the wall consulted — never from a - list assembled here. + ⭐⭐ THE SAME DEFECT THE SOURCE CHIPS WERE FIXED FOR IN WAVE 33, ONE CONTROL TO THE LEFT. + `permitted` is not `answerable` for a database; OFFERED is not CALLABLE for a model. The picker + listed every name in the ladder whether or not this deployment holds its key, so choosing one + spent a click and a turn to be told "the selected model is unavailable" by the server, which + knew before the click. The reason travels with the flag, exactly as `sources` does. + + ⚠ It names no environment variable. "This model is not configured on this deployment" is the + cause a tenant user can act on (ask an admin); the variable name is our deployment's business. """ - import routes_templates - keys, source = routes_templates._target_or_refuse(session, scope) - key = str(scope or '').strip() - defs = [] - if key.startswith('ut_'): - import core.user_tables as user_tables - defn = user_tables.get(key, st=session.runtime) or {} - by_key = {str(f.get('key')): f for f in (defn.get('fields') or []) if f.get('key')} - else: - g = _grid() - raw = g.product_fields() if key == 'product_data' else g.FIELDS - by_key = {str(f.get('key')): f for f in raw if f.get('key')} - for k in keys: - f = by_key.get(k) or {} - defs.append({'key': k, 'label': str(f.get('label') or k)[:80], - 'type': str(f.get('type') or 'text')}) - return defs, source - - -# ── the model ─────────────────────────────────────────────────────────────────────────────── - -#: This module's OWN provider order — cerebras first. See the header: the refusal is a model -#: property, and the ladder's cheap-first order is exactly wrong for a contract that includes one. -#: Override with `AIOS_QUERY_PROVIDER`. The credentials themselves stay in ONE place -#: (`analyst.PROVIDERS`), so a rotated key or a new model reaches this file too. -QUERY_PROVIDER_ORDER = ('cerebras', 'groq', 'openrouter') - - -def _providers(): + live = [name for name in QUERY_PROVIDER_ORDER if os.environ.get(QUERY_PROVIDER_ENV[name])] + rows = [{"model": MODEL_AUTO, "available": bool(live), + "reason": "" if live else "no model is configured on this deployment"}] + for name in QUERY_PROVIDER_ORDER: + rows.append({"model": name, "available": name in live, + "reason": "" if name in live + else "this model is not configured on this deployment"}) + # Anything the platform ladder carries that Query does not offer, once a chat has taught us. + rows.extend({"model": name, "available": False, + "reason": "the platform can reach this model but Query does not offer it yet"} + for name in _LADDER_DRIFT) + return rows + + +def _providers(model=MODEL_AUTO): + """Auto returns the permitted ladder; an explicit choice returns at most one provider.""" import harness.analyst as analyst - pin = os.environ.get("AIOS_QUERY_PROVIDER") + + requested = str(model or MODEL_AUTO).strip().lower() by_name = {p["name"]: p for p in analyst.PROVIDERS} - order = [pin] if pin else list(QUERY_PROVIDER_ORDER) - return [by_name[n] for n in order - if n in by_name and os.environ.get(by_name[n]["env"])] + # ⚠ THE RECONCILIATION, at the ONE point the platform ladder is already in memory, so it costs + # nothing. A provider added to `analyst.PROVIDERS` would otherwise simply never appear here, + # and an env name changed there would make Query's availability answer quietly wrong. Both are + # invisible failures; this turns them into a row a reader can see [[limit-with-no-enforcer]]. + _LADDER_DRIFT[:] = sorted( + set(by_name) - set(QUERY_PROVIDER_ENV) + | {name for name, row in by_name.items() + if name in QUERY_PROVIDER_ENV and row.get("env") != QUERY_PROVIDER_ENV[name]}) + names = list(QUERY_PROVIDER_ORDER) if requested == MODEL_AUTO else [requested] + return [by_name[name] for name in names + if name in by_name and os.environ.get(by_name[name]["env"])] + + +def _history(state, thread_id): + """The prior turns of THIS thread, oldest first, in the transport's own message shape. + + ⛔ SORTED BY `(createdAt, role)`, NOT BY `createdAt` ALONE. `_submit` stamps the user turn and + the assistant turn with the SAME `now`, so on timestamp alone the pair ties and their order is + whatever the store's dict iteration happens to give — which is insertion order today and is + not a guarantee anybody wrote down. A replayed conversation with the answers before the + questions is worse than no replay: it reads as coherent and is backwards. + + ⚠ Scoped to one thread by construction. Replaying another thread's turns would leak one chat's + subject into another's answer, which is the kind of wrong that looks like a good answer. + """ + thread_id = str(thread_id or "") + if not thread_id: + return [] + rows = [row for row in state["messages"].values() + if isinstance(row, dict) and str(row.get("threadId") or "") == thread_id] + rows.sort(key=lambda row: (str(row.get("createdAt") or ""), + 0 if row.get("role") == "user" else 1)) + turns = [] + for row in rows[-MAX_HISTORY_TURNS:]: + content = " ".join(str(row.get("content") or "").split()) + if not content: + continue + role = "assistant" if row.get("role") == "assistant" else "user" + turns.append({"role": role, "content": content}) + # ⭐⭐ R20's "self-improving", and it is the ONLY thing that makes a rating more than a + # flag shipped without its writer. A thumbs-down becomes what it actually was: a turn in + # which the reader said the answer was not useful. Modelled as a USER turn rather than by + # editing the assistant's own words, because that is what happened, and because rewriting + # a stored answer to steer the next one is how a transcript stops being a record. + if role == "assistant" and row.get("rating") == "down": + reason = " ".join(str(row.get("ratingReason") or "").split())[:MAX_RATING_REASON] + turns.append({"role": "user", + "content": f"That answer was not helpful. {reason}".strip()}) + kept, spent = [], 0 + for turn in reversed(turns): + spent += len(turn["content"]) + if spent > MAX_HISTORY_CHARS and kept: + break + kept.append(turn) + kept.reverse() + return kept def _spec_schema(field_keys): - """The tool schema the model fills. ⛔ `required` IS `["kind"]` ALONE — see the header: a - refusal carries no name, and groq rejects a schema-violating refusal with a 400 that reads - exactly like a transport failure.""" - ops = sorted(_grid().FILTER_OPS) col = {"type": "string", "enum": sorted(field_keys)} return { "type": "object", "properties": { - "kind": {"type": "string", "enum": list(QUERY_KINDS) + ["refused"], - "description": "refused = this database cannot answer the question"}, - "name": {"type": "string", "description": "a short title for the view"}, - "refusal": {"type": "string", - "description": "when kind=refused: ONE plain sentence naming what is " - "missing"}, + "kind": {"type": "string", "enum": [*QUERY_KINDS, "refused"]}, + "name": {"type": "string"}, + "refusal": {"type": "string"}, "visible": {"type": "array", "items": col}, - "filters": {"type": "array", "items": { - "type": "object", - "properties": {"colId": col, "op": {"type": "string", "enum": ops}, - "value": {"type": "string"}}, - "required": ["colId", "op"]}}, + # ⭐⭐ 2026-08-15 (owner: *"if you can build the view, the AI assistant should also be + # able to do it by using our tools on the backend"*). `rhs` and `important` were the + # only two things a person could express through `view_upsert` and this tool could not. + # + # ⛔ WITHOUT `rhs` THE ASSISTANT CANNOT STATE AN ERROR-CATCHER AT ALL — the one shape + # item 8a named by hand (*"price and COGS not matching"*). Every one of the 20 + # `FILTER_OPS` was already reachable, because they all read `value`; comparing a column + # against ANOTHER COLUMN is a different member (`aios_grid._clean_rhs`, CG-9) and it was + # simply absent here, so the model had no way to ask for it and no way to be told why. + # `kind` is `field` ONLY: `measure` needs a window and `stat` needs the population + # vocabulary, neither of which this snapshot-shaped reader carries — offering them + # would be a control that lies, which is the same rule the source chips follow. + "filters": {"type": "array", "items": {"type": "object", "properties": { + "colId": col, "op": {"type": "string", "enum": sorted(_grid().FILTER_OPS)}, + "value": {"type": "string"}, + "rhs": {"type": "object", "properties": { + "kind": {"type": "string", "enum": ["field"]}, "colId": col, + }, "required": ["kind", "colId"]}, + }, "required": ["colId", "op"]}}, + # A personal legibility mark, exactly as `grid_events.view_upsert` treats it (wave 32 + # R5/C4) — not a lock, and no second permission wall. + "important": {"type": "boolean"}, "filterConj": {"type": "string", "enum": ["and", "or"]}, - "sorts": {"type": "array", "items": { - "type": "object", - "properties": {"colId": col, - "dir": {"type": "string", "enum": ["asc", "desc"]}}, - "required": ["colId", "dir"]}}, + "sorts": {"type": "array", "items": {"type": "object", "properties": { + "colId": col, "dir": {"type": "string", "enum": ["asc", "desc"]}, + }, "required": ["colId", "dir"]}}, "groupBy": col, + "aggregation": {"type": "object", "properties": { + "op": {"type": "string", "enum": ["count", "sum", "avg", "min", "max"]}, + "field": col, + }, "required": ["op"]}, "stackField": col, "dateField": col, "colorField": col, @@ -218,476 +258,1205 @@ def _spec_schema(field_keys): } -def _system_prompt(fields): - """The standing instructions. The vocabulary is DERIVED (the kinds set, `FILTER_OPS`, the - target's own columns) — the model is never told about a key this server cannot honour.""" - cols = json.dumps([{"key": f["key"], "label": f["label"], "type": f["type"]} - for f in fields], separators=(",", ":")) - kinds = ", ".join(QUERY_KINDS) - ops = ", ".join(sorted(_grid().FILTER_OPS)) - selects = [f["key"] for f in fields if f["type"] in ('select', 'multiselect')] or ["(none)"] - dates = [f["key"] for f in fields if f["type"] == 'date'] or ["(none)"] - return f"""You turn a question about ONE database into a VIEW SPEC. You never write SQL and you -never invent a column or a kind of view. - -THE DATABASE ({len(fields)} columns) — you may name ONLY these column keys: -{cols} - -VIEW KINDS you may name, and nothing else: {kinds} -FILTER OPS you may name, and nothing else: {ops} -The only select-type columns (a kanban MUST stack on one of these): {", ".join(selects)} -The only date columns (a calendar or timeseries MUST use one of these): {", ".join(dates)} - -RULES: -1. Emit ONE call to build_view. Every colId in visible/filters/sorts/groupBy and every field ref - MUST be one of the keys above. -2. Pick the kind by what the question asks for: a list of records -> grid (or list); totals or - counts by a category -> chart with groupBy; cards by a stage -> kanban (stackField REQUIRED, - and it must be a select column); something over time -> calendar or timeseries (dateField - REQUIRED, and it must be a date column); geography -> map. -3. `visible` is the columns the question is about, most important first — not every column. -4. Set kind="refused" and put ONE plain sentence in `refusal` when the question needs a column - this database does not have, a number it does not store, or a picture that is not in the kind - list. REFUSING IS A CORRECT ANSWER. A view that answers a DIFFERENT question than the one - asked is the worst possible answer — worse than saying you cannot build it. When in doubt, - refuse. -5. Every `value` is a string.""" - - -def _call_model(question, fields, chat=None): - """`(spec, error_sentence, provider)` — one bounded call down THIS module's ladder. - - `chat` is injectable so `verify_query.py` proves this door end to end with no key and no - tokens (`analyst.ask`'s own posture, and the reason its loop is testable offline). - - ⚠ THE LADDER IS A DELIBERATE COMPROMISE, AND THE PROVIDER RIDES BACK BECAUSE OF IT. Only the - FIRST provider is measured to refuse honestly (README section 4b); the ones below it answer - unanswerable questions with plausible specs. Falling through on a 429 is still the right call — - a Query module that dies whenever one free tier rate-limits is worse than one that answers with - a weaker model behind the same validator and the same human read-back — but *which* model - answered must be knowable, or a wrong answer is undiagnosable after the fact. Failing closed is - what happens when the whole ladder is unreachable, not when the best rung is. +def _system_prompt(snapshot): + fields = snapshot["fields"] + cols = json.dumps([{"key": field["key"], "label": field.get("label", field["key"]), + "type": field.get("type", "text")} for field in fields], separators=(",", ":")) + return f"""You are the assistant inside this product, talking with one person about exactly one +database they already have permission to read. Reply in plain prose, and keep it short. + +DATABASE: {snapshot['database']} +SNAPSHOT VERSION: {json.dumps(snapshot['source_version'], default=str)} +PERMISSION-FILTERED RECORD COUNT: {len(snapshot['records'])} +FIELDS: {cols} +VIEW KINDS: {", ".join(QUERY_KINDS)} + +You may answer in words alone, and you may ask ONE short question back when the request is +ambiguous: which field is meant, which period, whether they want every record or a narrower set. +Prefer asking over guessing whenever the answer would change what you build. Earlier turns of this +conversation are above; use them, and read a pronoun as referring to what was just discussed. + +Call build_view ONLY when the person wants to SEE records: a table, a chart, a board, a list. Do +not call it to explain something, to confirm something, or to ask your question. When you do call +it you may also write one sentence saying what you built. + +Inside build_view: choose visible fields, supported filters and an optional aggregation. Use count +for record counts; sum, avg, min and max require one numeric field. The server computes and cites +every number from this exact snapshot. Never write SQL, invent fields, or name another database. +Return kind=refused with one plain sentence if the database cannot answer. + +To compare one column against ANOTHER column rather than a typed value, give the filter an rhs of +{{"kind":"field","colId":""}} and omit value. That is how you express questions like +"priced below what it costs us". Both columns must be in the FIELDS list above. +Set important=true when the view is one somebody should be chased about: an error, a mismatch, or +money at risk. Leave it out otherwise. + +Write with ordinary punctuation. Never use an em dash or an en dash: use a comma, a colon or a full +stop instead.""" + + +_FAILED_GEN = re.compile(r"(\{.*?\})\s*", re.S) + + +def _spec_from_400(body): + try: + value = ((json.loads(body) or {}).get("error") or {}).get("failed_generation") or "" + raw = (_FAILED_GEN.search(str(value)) or [str(value).strip()])[1] + result = json.loads(raw) + return result if isinstance(result, dict) else None + except Exception: + return None + + +# ⚠ BUILT FROM `chr`, AND A UNICODE ESCAPE IS NOT ENOUGH. `web_prose` reads a Python +# string's VALUE off the AST, not its spelling in the source, so an escape and the character +# itself are the SAME finding to it. Composing the class at runtime means no string literal in +# this file holds a dash, which is true rather than merely quiet: the only dashes in this module +# are the ones being removed. +_DASH = "[" + chr(0x2014) + chr(0x2013) + "]" + + +def _no_dashes(text): + """R6 applied where it is the ONLY place it can be applied: the model's own words. + + ⛔⛔ THE PROMPT INSTRUCTION IS NOT ENFORCEMENT, AND THIS IS MEASURED, NOT ANTICIPATED. The + system prompt ends with *"Never use an em dash or an en dash"* and the very next live turn came + back with *"Which view type would you like—grid, chart, list, or another?"* (cerebras, + 2026-08-16). Model prose reaches the screen exactly as a string literal does, and `web_prose` + scans SOURCE, so it cannot see a dash that arrives at runtime: the sweep every lane is doing + this wave is undone by our own assistant unless it is undone here. + + ⚠ A DIGIT RANGE IS A DIFFERENT SENTENCE. "10–20" means "10 to 20"; rewriting it as + "10, 20" states two numbers where the model stated a span, which is a wrong answer rather than + a punctuation fix. It gets its own rule, first. + """ + text = str(text or "") + text = re.sub(rf"(?<=\d)\s*{_DASH}\s*(?=\d)", " to ", text) + text = re.sub(rf"\s*{_DASH}\s*(?=[,.;:!?])", "", text) # abutting punctuation: it just goes + text = re.sub(rf"(?<=[,;:])\s*{_DASH}\s*", " ", text) # already punctuated: one space + return re.sub(rf"\s*{_DASH}\s*", ", ", text) + + +def _said(raw): + """The model's own words: one line of whitespace, no dash, and empty means nothing was said.""" + return _no_dashes(" ".join(str(raw or "").split())).strip() or None + + +def _from_chat(answer, provider): + """An injected transport may answer with a SPEC (a dict) or with PROSE (a string). + + ⛔ THE BRANCH BELONGS HERE, NOT AT THE CALLER. `_validate`'s first line refuses anything that + is not a dict, with "the assistant did not answer with a view" — so a prose answer passed + straight through would arrive as a REFUSAL, styled as one, and every conversation check would + pass against the wrong path while looking green [[one-question-two-normalizers]]. + """ + if isinstance(answer, str): + return None, _said(answer), provider, None + return answer, None, provider, None + + +def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, session=None): + """Return ``(spec, said, provider, reason)`` without any source-data fallback. + + ``said`` is what the assistant SAID: the whole answer when it did not build a view, and the + sentence beside the view when it built one and talked as well. ``reason`` is set only when + something went wrong, so a prose ANSWER and a transport FAILURE are distinguishable one layer + up rather than both arriving as a bare sentence. + + ⭐⭐ W35-T31 · CONTRACT C7 (R9) — ``session`` IS HERE ONLY SO THE METER CAN BE TOLD WHOSE CALL + THIS WAS, and PRD amendment A1 is why it is an argument rather than ambient state: a + ``ContextVar`` bound in ``deps.require_session`` reads back ``None`` inside this function on the + SAME thread, so a ledger built on one would have recorded nothing and shown a dashboard of + zeros indistinguishable from a quiet week. + + ⚠ OPTIONAL, DELIBERATELY. ``verify_query`` calls this function directly with an injected + ``chat`` and no session, and a required argument would have made every one of those calls a + signature change. An omitted session is COUNTED in ``usage_ledger.UNATTRIBUTED`` and reported + to an admin, never dropped. """ + requested = str(model or MODEL_AUTO).strip().lower() + if requested not in model_choices(): + return None, f"the selected model ({requested or model}) is unavailable", None, "model_unavailable" tools = [{"type": "function", "function": { - "name": "build_view", - "description": "Emit the view spec, or refuse.", - "parameters": _spec_schema([f["key"] for f in fields])}}] - messages = [{"role": "system", "content": _system_prompt(fields)}, + "name": "build_view", "description": "Emit a virtual-view spec or a refusal.", + "parameters": _spec_schema([field["key"] for field in snapshot["fields"]]), + }}] + messages = [{"role": "system", "content": _system_prompt(snapshot)}, + *(history or []), {"role": "user", "content": question}] if chat is not None: - return chat(messages, tools), None, "injected" - - provs = _providers() - if not provs: - # No key at all: say so. An AI feature that silently does nothing is indistinguishable - # from one that was never built ([[flag-shipped-without-its-writer]]). - return None, ("the assistant is not configured on this deployment, so a view cannot be " - "built from a question yet"), None + provider = requested if requested != MODEL_AUTO else "injected" + return _from_chat(chat(messages, tools), provider) + + providers = _providers(requested) + if not providers: + sentence = (f"the selected model ({requested}) is unavailable" if requested != MODEL_AUTO + else "the assistant is not configured on this deployment") + return None, sentence, None, "model_unavailable" if requested != MODEL_AUTO else "not_configured" + import requests + + import usage_ledger + + def _book(provider, body): + """⭐⭐ C7 — ONE LEDGER LINE PER PROVIDER RESPONSE THIS FUNCTION READS. + + ⛔ HERE, INSIDE THE LADDER, AND NOT AT THE RETURN. The ladder tries providers in order and + a failed one has already SPENT tokens at that vendor; booking only the winner would report + a week cheaper than it was, which is the cost-surprise R13 cited. Every 200 this loop reads + gets a line, including the one whose answer turned out to be empty. + ⚠ `tokens_from` returns `(None, None)` when the provider did not say, and `None` is carried + through rather than coerced to 0 — a call booked at zero is an unmeasured call presented as + a free one. `usage_ledger` counts it as UNMEASURED so the total reads as a floor. + ⚠ `record` never raises, by its own contract, so this cannot break the assistant. + """ + ins, outs = usage_ledger.tokens_from(body) + usage_ledger.record( + "assistant", provider["name"], provider["model"], ins, outs, + total=usage_ledger.total_from(body), + st=getattr(session, "runtime", None), user=getattr(session, "uname", "")) + last = None - for p in provs: + for provider in providers: try: - r = requests.post(p["url"], timeout=60, - headers={"Authorization": f"Bearer {os.environ[p['env']]}"}, - json={"model": p["model"], "messages": messages, "tools": tools, - "tool_choice": "required", "temperature": 0.1, - "max_tokens": 1200}) - except Exception as e: # network blip — try the next provider - last = f"{p['name']}: {type(e).__name__}" + response = requests.post( + provider["url"], timeout=60, + headers={"Authorization": f"Bearer {os.environ[provider['env']]}"}, + # ⛔⛔ `auto`, NOT `required`, AND THAT ONE WORD IS R16. Under `required` the model + # had to emit a `build_view` call for EVERY turn: it could not answer a question, + # could not ask one back, and could not decline to build. "The AI chat must TALK + # with the user, not only build queries, and decide for itself whether to create a + # query view" is unreachable with the tool forced, whatever the prompt says. + # ⚠ AND IT IS A LIVE VENDOR-BEHAVIOUR CHANGE THAT NO GATE HERE CAN SEE, because + # `verify_query` injects `chat` and never builds this body. `_spec_from_400` below + # exists precisely because providers differ in how they emit a forced call; under + # `auto` a provider may also decline to build for a view-shaped question. That is + # why this ticket's evidence is a real three-turn run against a real provider and + # not a green gate. + json={"model": provider["model"], "messages": messages, "tools": tools, + "tool_choice": "auto", "temperature": 0.1, "max_tokens": 1200}, + ) + except Exception as exc: + last = f"{provider['name']}: {type(exc).__name__}" continue - if r.status_code == 400: - # ⛔ THE MODEL'S ANSWER CAN BE IN HERE. Groq validates tool arguments against the - # schema and returns the generation it rejected. Reading it turns a "transport - # failure" back into the refusal it actually was. - spec = _spec_from_400(r.text) + if response.status_code == 400: + spec = _spec_from_400(response.text) if spec is not None: - return spec, None, p["name"] - last = f"{p['name']}: 400" + return spec, None, provider["name"], None + last = f"{provider['name']}: 400" continue - if r.status_code != 200: - last = f"{p['name']}: HTTP {r.status_code}" - continue # 429 included: the NEXT provider, not a sleep - try: - msg = r.json()["choices"][0]["message"] - calls = msg.get("tool_calls") or [] - if not calls: - last = f"{p['name']}: no tool call" - continue - return json.loads(calls[0]["function"].get("arguments") or "{}"), None, p["name"] - except Exception as e: - last = f"{p['name']}: unreadable answer ({type(e).__name__})" + if response.status_code != 200: + last = f"{provider['name']}: HTTP {response.status_code}" continue - # ⛔ FAIL CLOSED. The first provider in the order is the one measured to refuse honestly; if it - # is rate-limited and the rest are too, the answer is a sentence, never a fabricated view. - return None, ("the assistant could not be reached just now (" + (last or "no provider") + - ") — try the question again in a moment"), None - - -_FAILED_GEN = re.compile(r'(\{.*?\})\s*', re.S) - - -def _spec_from_400(body): - """The spec out of a `tool_use_failed` body's `failed_generation`, or None.""" - try: - err_obj = (json.loads(body) or {}).get("error") or {} - except Exception: - return None - gen = str(err_obj.get("failed_generation") or "") - if not gen: - return None - m = _FAILED_GEN.search(gen) - raw = m.group(1) if m else gen.strip() - try: - spec = json.loads(raw) - except Exception: - return None - return spec if isinstance(spec, dict) else None - + try: + body = response.json() + # C7: booked from the RAW body, before anything below can raise on its shape. A + # provider that answered 200 and billed for it has spent tokens whether or not this + # function can read what it said. + _book(provider, body) + answer = body["choices"][0]["message"] + said = _said(answer.get("content")) + calls = answer.get("tool_calls") or [] + if calls: + # The prose rides ALONG with the view when the model wrote both, so the reader gets + # a sentence instead of `_explain`'s machine description of its own output. + spec = json.loads(calls[0]["function"].get("arguments") or "{}") + return spec, said, provider["name"], None + if said: + return None, said, provider["name"], None + # ⚠ Neither a call nor a word is a FAILED turn, not a silent one: falling through to + # the next provider is right, and swallowing it as an empty answer would show the + # reader a blank reply [[empty-answer-vs-unfinished-answer]]. + last = f"{provider['name']}: an empty answer" + except Exception as exc: + last = f"{provider['name']}: unreadable answer ({type(exc).__name__})" + if requested != MODEL_AUTO: + return None, f"the selected model ({requested}) is unavailable", None, "model_unavailable" + return (None, "the assistant could not be reached just now (" + (last or "no provider") + ")", + None, "provider_unreachable") -# ── validation: the REFUSAL this contract promises ─────────────────────────────────────────── def _validate(spec, fields): - """`(clean, refusal, code)` — exactly one of `clean` / `refusal` is set. - - Membership FIRST and explicitly (the header's whole subject), then the product's own cleaners - as a belt. A refusal is a SENTENCE, because C5's user-facing promise is a plain sentence and - never a broken view. - """ - g = _grid() + """Return a cleaned, source-independent virtual-view config or a named refusal.""" if not isinstance(spec, dict): return None, "the assistant did not answer with a view", "no_spec" - by_key = {f['key']: f['type'] for f in fields} + by_key = {str(field.get("key")): str(field.get("type") or "text") for field in fields} keys = set(by_key) - kind = spec.get('kind') - - if kind == 'refused': - return None, (str(spec.get('refusal') or '').strip() - or "this database cannot answer that question"), "model_refused" - if kind in QUERY_EXCLUDED: - return None, (f"a {kind} view cannot be built from a question — " - + QUERY_EXCLUDED[kind]), "unsupported_kind" - if kind not in QUERY_KINDS: - # ⛔ NOT `_clean_display`'s job: it would DROP this and hand back a grid under a name - # promising something else. - return None, (f"{kind!r} is not a kind of view this product can build" - if kind else "the assistant did not name a kind of view"), "unsupported_kind" - - named = set(spec.get('visible') or ()) - for s in spec.get('sorts') or (): - if isinstance(s, dict) and s.get('colId'): - named.add(str(s['colId'])) - for f in spec.get('filters') or (): - if isinstance(f, dict) and f.get('colId'): - named.add(str(f['colId'])) - if spec.get('groupBy'): - named.add(str(spec['groupBy'])) - for ref in ('stackField', 'dateField', 'colorField', 'sizeField'): - if spec.get(ref): - named.add(str(spec[ref])) + kind = spec.get("kind") + if kind == "refused": + # Model-authored, so it faces the same R6 wall the model's chat prose does. + return None, _said(spec.get("refusal")) or "this database cannot answer that question", "model_refused" + if kind in QUERY_EXCLUDED or kind not in QUERY_KINDS: + return None, "that kind of view cannot be built from this question", "unsupported_kind" + + named = set(spec.get("visible") or ()) + for item in spec.get("filters") or (): + if isinstance(item, dict) and item.get("colId"): + named.add(str(item["colId"])) + # ⛔ THE RIGHT-HAND COLUMN IS A COLUMN AND MUST FACE THE SAME `missing` CHECK. Collecting + # only the left side is what makes D-229 possible one layer down: `clean_filter_tree` does + # NOT drop a leaf whose field-rhs names a column that does not exist — it keeps the leaf, + # strips the `rhs`, blanks the value, and `filter_sql.is_rule_active` then reports the rule + # INACTIVE. An inactive rule narrows nothing, so "margin under 10%" would come back as a + # view listing the ENTIRE catalogue under an error-catcher's name, with nothing red. + # Naming it here turns that into the ordinary "this database does not have: X" refusal. + rhs = item.get("rhs") if isinstance(item, dict) else None + if isinstance(rhs, dict) and rhs.get("colId"): + named.add(str(rhs["colId"])) + for item in spec.get("sorts") or (): + if isinstance(item, dict) and item.get("colId"): + named.add(str(item["colId"])) + for key in ("groupBy", "stackField", "dateField", "colorField", "sizeField"): + if spec.get(key): + named.add(str(spec[key])) + raw_aggregation = spec.get("aggregation") or {"op": "count"} + if isinstance(raw_aggregation, dict) and raw_aggregation.get("field"): + named.add(str(raw_aggregation["field"])) missing = sorted(named - keys) if missing: - # NAMED, not counted (`routes_templates`' rule): the column keys are what tell the reader - # this is the wrong database for this question. - return None, ("this database does not have the columns that answer needs: " - + ", ".join(missing)), "unknown_columns" + return None, "this database does not have: " + ", ".join(missing), "unknown_columns" - visible = [k for k in (spec.get('visible') or ()) if k in keys][:MAX_VISIBLE] + visible = [str(key) for key in (spec.get("visible") or ()) if str(key) in keys][:MAX_VISIBLE] if not visible: - # An empty projection is not a view. `_default_view_config` would fill one in, which is - # how a question about two columns becomes a 285-column wall. - return None, ("that question did not name anything to show — try naming the columns you " - "want to see"), "no_columns" - - # ⛔ D-137, GUARDED WHERE IT REACHES THIS FEATURE. "The chart cannot key a SET-LIKE or CHECKBOX - # column the way the grid does" — a set row lands in several buckets, so a sum means something - # else, and a checkbox reads "(blank)". The defect lives in the CLIENT's `chartData` bucket - # keying, which is in no lane's fence this wave (booked, with that reason). What IS in this - # lane's power is refusing to GENERATE the broken case: the AI must only build what the backend - # and the renderer already support, which is R1's own sentence. Delete this guard when D-137 - # closes — the refusal names the debt so the reader knows it is a limit, not a rule. - if kind == 'chart' and by_key.get(spec.get('groupBy')) in ('multiselect', 'checkbox'): - return None, (f"a chart cannot group by {spec.get('groupBy')!r} yet — a column that holds " - f"several values at once, or a tick box, does not bucket the way a chart " - f"needs. Try a table grouped by it instead"), "chart_key_unsupported" - - for ref, families, required in _MODE_REFS.get(kind, ()): - val = spec.get(ref) - if val and by_key.get(val) not in families: - return None, (f"a {kind} view needs {ref[:-5]} to be a " - f"{' or '.join(families)} column, and {val!r} is a " - f"{by_key.get(val)} column"), "wrong_ref_type" - if required and not val: - return None, (f"a {kind} view needs a {' or '.join(families)} column and this " - f"database has none that fits"), "missing_ref" - - raw_filters = [f for f in (spec.get('filters') or ()) if isinstance(f, dict)] - filters = g.clean_filter_tree(raw_filters, keys) + return None, "that question did not name any fields to show", "no_columns" + raw_filters = [item for item in (spec.get("filters") or ()) if isinstance(item, dict)] + filters = _grid().clean_filter_tree(raw_filters, keys) if len(filters) != len(raw_filters): - # The belt caught something membership did not — an unknown op. Refuse rather than save a - # view whose condition was silently dropped (the widening this file exists to prevent). - return None, ("part of that filter is not something this product can express — try " - "asking it more simply"), "filter_dropped" - - display = {'mode': kind} - for ref, _families, _req in _MODE_REFS.get(kind, ()): - if spec.get(ref): - display[ref] = spec[ref] - cleaned_display = g._clean_display(display, keys) if kind != 'grid' else None - if kind != 'grid' and not cleaned_display: - return None, (f"this product could not build a {kind} view from that question" - ), "display_dropped" - - clean = { - 'kind': kind, - 'name': ' '.join(str(spec.get('name') or 'Query').split())[:60] or 'Query', - 'visible': visible, - 'filters': filters, - 'filterConj': 'or' if spec.get('filterConj') == 'or' else 'and', - 'sorts': [{'colId': s['colId'], 'dir': 'desc' if s.get('dir') == 'desc' else 'asc'} - for s in (spec.get('sorts') or ()) if isinstance(s, dict) - and s.get('colId') in keys][:3], - 'groupBy': spec['groupBy'] if spec.get('groupBy') in keys else None, - 'display': cleaned_display, + return None, "part of that filter is unsupported", "filter_dropped" + # ⛔⛔ A SECOND, NARROWER CHECK, AND THE LENGTH CHECK ABOVE CANNOT DO ITS JOB (D-229). + # A dropped leaf changes the COUNT; a stripped `rhs` does not — the leaf survives, so + # `len(filters) == len(raw_filters)` and the refusal above never fires. The failure is + # therefore silent in exactly the direction that matters: the condition stops narrowing and + # the view answers with every record. Assert the member survived, per leaf. + # ⚠ The `named` pass above already refuses an rhs naming a column this database lacks, so + # reaching here means something ELSE stripped it (a type the comparand cannot take, a future + # `_clean_rhs` rule). Both doors, because the two catch different causes and the cost of + # missing this one is a wrong answer that looks right. + for sent, kept in zip(raw_filters, filters): + if sent.get("rhs") and not kept.get("rhs"): + return None, "that column cannot be compared against another column", "rhs_dropped" + + aggregation = raw_aggregation if isinstance(raw_aggregation, dict) else {} + op = str(aggregation.get("op") or "").lower() + field = aggregation.get("field") + if op not in {"count", "sum", "avg", "min", "max"}: + return None, "the assistant gave an unsupported aggregation", "bad_aggregation" + if op == "count": + field = None + elif field not in keys or by_key.get(field) not in {"int", "currency", "pct"}: + return None, "that aggregation needs one visible numeric field", "bad_aggregation" + + display = {"mode": kind} + for ref, families, required in _MODE_REFS.get(kind, ()): + value = spec.get(ref) + if required and not value: + return None, f"a {kind} view needs {ref}", "missing_ref" + if value and by_key.get(value) not in families: + return None, f"{ref} has the wrong field type", "wrong_ref_type" + if value: + display[ref] = value + cleaned_display = _grid()._clean_display(display, keys) if kind != "grid" else None + if kind != "grid" and not cleaned_display: + return None, f"this product could not build a {kind} view", "display_dropped" + + return { + "kind": kind, + # The view NAME is model-authored too, and it is the string that ends up in the rail, in + # the flyout and on the artefact card. R6 reaches it here or nowhere. + "name": (_said(spec.get("name")) or "Query")[:60], + "visible": visible, + "filters": filters, + "filterConj": "or" if spec.get("filterConj") == "or" else "and", + "sorts": [{"colId": item["colId"], "dir": "desc" if item.get("dir") == "desc" else "asc"} + for item in (spec.get("sorts") or []) if isinstance(item, dict) + and item.get("colId") in keys][:3], + "groupBy": spec.get("groupBy") if spec.get("groupBy") in keys else None, + "aggregation": {"op": op, "field": field}, + "display": cleaned_display, + # ⚠ `is True`, not truthy, and UNCONDITIONAL — the same two rules `grid_events.view_upsert` + # follows for this key. `is True` so a model emitting the string "false" does not mark a + # view; unconditional so the mark is REMOVABLE rather than a flag that can be set and never + # cleared (a key written only when present leaves a stored `true` alive forever). + "important": spec.get("important") is True, + }, None, None + + +def _explain(view, fields): + label = {field["key"]: str(field.get("label") or field["key"]) for field in fields} + visible = ", ".join(label.get(key, key) for key in view["visible"][:6]) + result = f"{view['kind']} view of {visible}" + if view["filters"]: + result += "; filtered records only" + if view.get("groupBy"): + result += f"; grouped by {label.get(view['groupBy'], view['groupBy'])}" + agg = view["aggregation"] + if agg["op"] != "count": + result += f"; {agg['op']} of {label.get(agg['field'], agg['field'])}" + return result + "." + + +def _said_fallback(artifact): + """What a build turn SAYS when the provider volunteered no sentence of its own. + + ⚠ MEASURED, 2026-08-16, cerebras: a view-shaped question comes back as a tool call with + `content: null`. So this is the sentence a person reads on MOST build turns, not a rare + fallback, and R16 ("the AI chat must TALK with the user") is decided here rather than in the + prompt. `_explain` used to be it, and it is a receipt for our own output: *"grid view of + Company, Owner, Deal value; filtered records only."* It keeps its real job ON THE ARTEFACT, + where it labels the thing it describes. + """ + numeric = artifact.get("numeric") or {} + value = numeric.get("value") + if value is None: + return f"I built {artifact['name']}." + if isinstance(value, float) and value.is_integer(): + value = int(value) + number = f"{value:,}" if isinstance(value, (int, float)) else str(value) + label = " ".join(str(numeric.get("label") or "Records").split()) + return f"I built {artifact['name']}. {label}: {number}." + + +def _numeric_result(view, records): + aggregation = view["aggregation"] + if aggregation["op"] == "count": + return {"label": "Matching records", "value": len(records), "contributing_record_count": len(records)} + values = [] + for record in records: + try: + value = record.get(aggregation["field"]) + if value is not None and not isinstance(value, bool): + values.append(float(value)) + except (TypeError, ValueError): + continue + if not values: + return {"label": aggregation["op"], "value": None, "contributing_record_count": 0} + op = aggregation["op"] + value = {"sum": sum(values), "avg": sum(values) / len(values), "min": min(values), "max": max(values)}[op] + return {"label": f"{op.title()} of {aggregation['field']}", "value": value, + "contributing_record_count": len(values)} + + +def _referenced_fields(view): + """The citation names every source field that affected the displayed result.""" + out = list(view.get("visible") or ()) + for node in view.get("filters") or (): + if isinstance(node, dict) and node.get("colId"): + out.append(str(node["colId"])) + for node in view.get("sorts") or (): + if isinstance(node, dict) and node.get("colId"): + out.append(str(node["colId"])) + for key in ("groupBy",): + if view.get(key): + out.append(str(view[key])) + aggregation = view.get("aggregation") or {} + if aggregation.get("field"): + out.append(str(aggregation["field"])) + return list(dict.fromkeys(out)) + + +def _effective_filters(snapshot, view): + """Keep the source request and generated-view predicates distinct in provenance.""" + return { + "source": _safe(snapshot.get("filters")), + "view": {"conj": view.get("filterConj", "and"), + "nodes": _safe(view.get("filters") or [])}, } - return clean, None, None -def _explain(clean, fields): - """A plain-language read-back of what the view WILL do — DERIVED from the validated spec. +def _view_records(snapshot, view): + """Apply the exact validated virtual-view filter before calculating a cited number.""" + nodes = view.get("filters") or [] + if not nodes: + return list(snapshot["records"]) + from harness import filter_eval + tree = {"conj": view.get("filterConj", "and"), "nodes": nodes} + return [row for row in snapshot["records"] + if filter_eval.matches(tree, row, snapshot["fields"])] - ⛔ NEVER ASKED OF THE MODEL. A model describing its own output describes what it MEANT, which - is precisely the failure this sentence exists to expose: a spec whose every column is real and - which answers a different question is invisible to validation, so the only thing that catches - it is a person reading an honest description of the spec that was actually accepted. - """ - label = {f['key']: f['label'] for f in fields} - ops = {'eq': 'is', 'neq': 'is not', 'gt': 'is over', 'gte': 'is at least', - 'lt': 'is under', 'lte': 'is at most', 'contains': 'contains', - 'doesNotContain': 'does not contain', 'isEmpty': 'is empty', - 'isNotEmpty': 'is not empty', 'between': 'is between', 'within': 'is within', - 'topN': 'is in the top', 'bottomN': 'is in the bottom'} - kinds = {'grid': 'a table', 'list': 'a list', 'chart': 'a chart', 'kanban': 'a board', - 'calendar': 'a calendar', 'timeseries': 'a time series', 'map': 'a map'} - parts = [f"{kinds.get(clean['kind'], clean['kind'])} of " - + ", ".join(label.get(k, k) for k in clean['visible'][:6]) - + (f" and {len(clean['visible']) - 6} more columns" - if len(clean['visible']) > 6 else "")] - if clean['filters']: - joiner = " or " if clean['filterConj'] == 'or' else " and " - parts.append("showing only records where " + joiner.join( - f"{label.get(f['colId'], f['colId'])} {ops.get(f['op'], f['op'])}" - + (f" {f['value']}" if f.get('value') else "") - for f in clean['filters'] if isinstance(f, dict) and f.get('colId'))) - else: - parts.append("showing every record") - if clean['groupBy']: - parts.append(f"grouped by {label.get(clean['groupBy'], clean['groupBy'])}") - if clean['sorts']: - s = clean['sorts'][0] - parts.append(f"sorted by {label.get(s['colId'], s['colId'])}" - + (" (highest first)" if s['dir'] == 'desc' else " (lowest first)")) - for ref, word in (('stackField', 'in columns by'), ('dateField', 'placed in time by'), - ('colorField', 'coloured by'), ('sizeField', 'sized by')): - val = (clean.get('display') or {}).get(ref) - if val: - parts.append(f"{word} {label.get(val, val)}") - return ", ".join(parts) + "." - - -# ── the registry ──────────────────────────────────────────────────────────────────────────── - -def _qid(scope, question): - """PINNED per (database, question), the `view_templates` discipline: asking the same thing - twice UPDATES one view instead of minting "Query 2" — `save_view` de-duplicates NAMES by - appending a number, so an unpinned id fills the store with numbered near-duplicates.""" - h = hashlib.sha1(f"{scope}|{' '.join(str(question).split()).lower()}".encode("utf-8")) - return "q_" + h.hexdigest()[:12] - - -def _registry(session): - try: - recs = session.runtime.get(QUERY_KEY) or {} - except Exception: - return {} - return recs if isinstance(recs, dict) else {} + +def _citation(citation_id, snapshot, view, numeric, view_id): + return { + "id": citation_id, + "href": f"#/query?view={view_id}&citation={citation_id}", + "database": snapshot["database"], + "snapshot": {"kind": snapshot["source_kind"], "version": _safe(snapshot["source_version"])}, + "fields": [field["key"] for field in snapshot["fields"] + if field.get("key") in set(_referenced_fields(view))], + "filters": _effective_filters(snapshot, view), + "permission_scope_applied": snapshot["permission_scope_applied"], + "aggregation": _safe(view["aggregation"]), + "contributing_record_count": numeric["contributing_record_count"], + "retrieved_at": snapshot["retrieved_at"], + } + + +def _citation_complete(citation): + """A numeric result is not publishable without complete provenance.""" + required = {"database", "snapshot", "fields", "filters", "aggregation", + "contributing_record_count", "retrieved_at", "href"} + snapshot = citation.get("snapshot") if isinstance(citation, dict) else None + return (isinstance(citation, dict) and required <= set(citation) + and bool(citation["database"]) and isinstance(snapshot, dict) + and "version" in snapshot and bool(citation["retrieved_at"]) + and isinstance(citation["fields"], list) + and isinstance(citation["aggregation"], dict)) + + +def _public_view(view): + source = view["source"] + # ⭐⭐ W35-T25 · CONTRACT C4 — `edited` IS DERIVED, NEVER STORED, and that is deliberate. + # A stored boolean beside two specs is a third source of truth that can disagree with both; + # the only honest answer to "has this been changed" is "compare it". It also means a Revert + # that restores the spec clears the badge by construction rather than by remembering to. + original = view.get("original_spec") + return { + "id": view["id"], "viewId": view["id"], "scope": source["database"], + "name": view["name"], "description": str(view.get("description") or ""), + "kind": view["view"]["kind"], "question": view["question"], + "explain": view["explain"], "threadId": view["threadId"], "createdAt": view["createdAt"], + "virtual": True, "source": _safe(source), "view": _safe(view["view"]), + "citationIds": list(view["citationIds"]), "numeric": _safe(view["numeric"]), + # ⚠ AN ARTEFACT MADE BEFORE THIS WAVE HAS NO ORIGINAL, so it reports `edited: false` and + # sends no `original_spec` — and the client shows neither the badge nor Revert. C4 is + # explicit that this is the right answer: a Revert with nothing to revert to is worse + # than an absent one, and it is the case an NC in `verify_query` covers. + "original_spec": _safe(original) if isinstance(original, dict) else None, + "edited": bool(isinstance(original, dict) and _safe(view["view"]) != _safe(original)), + } -def _mine(session, rec): - return session.admin or str(rec.get('createdBy') or '') == session.uname +def _source_still_permitted(session, source, permitted=None): + """A persisted artefact never outlives the caller's current data permission. + ⚠ `permitted` is the BATCH answer from `deps.assistant_source_status` — one rows-free + resolution for every source at once, rather than one whole-document read per saved view. That + function's docstring carries the measurement. The single-source path below stays for callers + holding exactly one artefact (the workspace-event door), and asks the same helper. -#: The BUILT-IN topics `routes_templates._target_or_refuse` accepts beside any `ut_*` key. ⛔ THE -#: CLIENT'S PICKER MUST MIRROR THIS, and `GET /query` publishes it (`builtins`) rather than leaving -#: the page to re-derive it: the nav hands `QueryPage` every granted entry, which is a WIDER set -#: than this door accepts, so a picker filtered on "not a surface" alone would offer a database the -#: build door 404s. `view_templates`' own rule — "a picker that offered a template the apply door -#: would then refuse is a control that lies" — and it is the same predicate twice, published once. -BUILTIN_SCOPES = ('customer_data', 'product_data') + ⛔ `permitted`, NEVER `answerable`. A source whose rows are served through the connector mirror + cannot be ASKED and can still be SEEN: the artefact was built from a snapshot that was legal + when it was taken, and hiding it because the reader can no longer make a NEW one would read as + deletion. The two verdicts are separate for that reason. + """ + database = (source or {}).get("database") if isinstance(source, dict) else None + if not database: + return False + if permitted is None: + permitted = {key for key, row in assistant_source_status(session, [database]).items() + if row["permitted"]} + return database in permitted + + +def _public_state(state, session): + # ONE rows-free batch answers both questions: which sources this caller may still see (which + # artefacts stay listed) and which of them can actually be asked (which chips are live). + status = assistant_source_status(session) + for row in state["views"].values(): + key = (row.get("source") or {}).get("database") if isinstance(row.get("source"), dict) else None + if key and key not in status: + # An artefact whose source is no longer enumerable still gets a verdict rather than a + # KeyError — it resolves to "not permitted" and the artefact drops out, which is the + # same answer the per-view wall gave. + status.update(assistant_source_status(session, [key])) + permitted = {key for key, row in status.items() if row["permitted"]} + allowed_views = [row for row in state["views"].values() + if _source_still_permitted(session, row.get("source"), permitted)] + allowed_ids = {row["id"] for row in allowed_views} + allowed_citations = {citation_id for row in allowed_views + for citation_id in row.get("citationIds") or []} + threads = sorted(state["threads"].values(), key=lambda row: row.get("updatedAt", ""), reverse=True) + messages = sorted(state["messages"].values(), key=lambda row: row.get("createdAt", "")) + views = sorted((_public_view(row) for row in allowed_views), key=lambda row: row["createdAt"], reverse=True) + messages = [row for row in messages if not row.get("viewId") or row.get("viewId") in allowed_ids] + return {"threads": _safe(threads), "messages": _safe(messages), "views": views, + "citations": _safe([row for key, row in state["citations"].items() + if key in allowed_citations]), "models": model_choices(), + # The model picker's own data, the same shape `sources` uses for databases. + "modelStatus": model_status(), + # The chip row's own data: a source this caller holds but cannot ask, and WHY. + # ⭐⭐ D-276 — `or row.get("visible")`. A source the caller can open elsewhere in the + # product but the assistant cannot read is now LISTED with its cause, instead of + # vanishing from a picker that shows every other database they hold. It arrives with + # `answerable: False` and a `reason`, which is the SAME shape the mirror-served grids + # already use, so the chip row needs no new state to render it. + # ⛔ `permitted` STILL GATES ARTEFACTS — `allowed_views` above is unchanged. This widens + # what is DESCRIBED, never what can be read or kept. + "sources": _safe([{"database": key, "answerable": row["answerable"], + "reason": row["reason"]} + for key, row in sorted(status.items()) + if row["permitted"] or row.get("visible")])} @router.get("/query") def list_queries(session: Session = Depends(require_session)): - """The AI-built views this caller may open: their own, still-granted, still-existing. - - ⚠ PRUNED ON READ against the CURRENT wall, never merely on write — a grant can be withdrawn - and a database deleted after a view was saved, and the Query module is chrome: it may render - nothing the server would not grant today (`nav.ts`'s chrome law). + return _public_state(_state(session), session) + + +# ⭐⭐ W35-T25 · CONTRACT C4 (owner item 4 / R3) — WHICH SPEC MEMBERS AN EDIT MAY MOVE. +# +# ⛔ AN ALLOW-LIST, AND IT IS THE SECURITY BOUNDARY OF THIS WHOLE TICKET. The client sends a +# `SavedView`, a shape it composes itself, and merging it wholesale would let a caller rewrite +# `kind` (which decides the renderer and the citation's own claim), `aggregation` (the number this +# artefact CITED) or `name`. R3 opens the view SPEC: *"filters, sort, group, visible columns, +# widths"*, plus the row height and column order that carry them. Nothing else. +# +# ⚠ `aggregation` IS DELIBERATELY ABSENT even though a person can change it on an ordinary grid. +# The artefact's citation records `contributing_record_count` and an op computed from THIS +# aggregation; letting an edit move it would leave a cited number describing a calculation the +# artefact no longer performs, which is the one thing every provenance rule in this module exists +# to prevent. +# +# ⚠ A COMMENT, NOT A BARE MODULE-LEVEL STRING. `verify_prose` reads a free-floating string literal +# as candidate copy, so writing this as a `"""..."""` above the constant put an em dash into the +# gate's own census as a 296th finding. A `#` block is out of scope by construction. +QUERY_EDITABLE_SPEC = ("visible", "order", "widths", "filters", "filterConj", "sorts", + "groupBy", "rowHeightMode", "frozenCount", "colorBy", "display") + + +def _clean_spec_edit(config, spec, fields): + """Merge a client view config onto the artefact's spec, cleaned against ITS OWN fields. + + ⛔ THE FIELD KEYS COME FROM THE STORED SOURCE, never from the request. The artefact carries + the snapshot's field list, so this needs no database read and cannot be widened by a caller + naming a column the snapshot did not have. """ - import routes_templates - out = [] - for qid, rec in sorted(_registry(session).items(), - key=lambda kv: str((kv[1] or {}).get('createdAt') or ''), - reverse=True): - if not isinstance(rec, dict) or not _mine(session, rec): + keys = {str(field.get("key")) for field in (fields or []) if isinstance(field, dict)} + out = copy.deepcopy(spec) if isinstance(spec, dict) else {} + if not isinstance(config, dict): + return out + for member in QUERY_EDITABLE_SPEC: + if member not in config: continue - try: - routes_templates._target_or_refuse(session, rec.get('scope')) - except Exception: - continue # no longer granted, or gone - out.append({"id": qid, "scope": rec.get('scope'), "viewId": rec.get('viewId'), - "name": rec.get('name'), "kind": rec.get('kind'), - "question": rec.get('question'), "explain": rec.get('explain'), - "createdAt": rec.get('createdAt')}) - return {"views": out, "kinds": list(QUERY_KINDS), "builtins": list(BUILTIN_SCOPES)} - - -@router.post("/query/build") -def build_query(body: dict = Body(default=None), - session: Session = Depends(require_session)): - """A question + a granted database -> `{spec, explain, refused}`. **WRITES NOTHING.** - - A refusal is a 200 carrying a sentence, not a 5xx: "this database cannot answer that" is a - successful answer to the person asking, and an error envelope would paint the error page R1 - forbids. The 4xx cases are the ones that ARE the caller's fault — an unnamed database, an - over-long question, a database this session may not open. - - ⛔ THE MODEL SEAM IS **NOT** ON THIS SIGNATURE, AND THAT IS A CORRECTION. The first draft took - `chat=None` as a parameter of the ROUTE — and FastAPI reads an un-annotated defaulted argument - as a **QUERY PARAMETER**, so `chat` appeared in `openapi()["paths"]` (measured) and - `POST /query/build?chat=x` would have reached `_call_model(..., chat="x")` and 500'd on - `"x"(messages, tools)`. The gate never saw it because the gate calls the handler directly — - which is exactly the shape of a test seam that becomes an input. The seam now lives on the - module-level `_build` below: the gate calls that, and the wire cannot. + value = config[member] + if member in ("visible", "order"): + cleaned = [str(key) for key in value if str(key) in keys] if isinstance(value, list) else [] + # ⚠ An EMPTY visible list is refused rather than stored: `_validate` already treats + # "no columns" as a refusal at creation, and a grid showing nothing is not an edit + # somebody meant to make. + if member == "visible" and not cleaned: + continue + out[member] = cleaned[:MAX_VISIBLE] + elif member == "widths": + out[member] = {str(key): int(width) for key, width in value.items() + if str(key) in keys and isinstance(width, (int, float)) + and 0 < float(width) <= 2000} if isinstance(value, dict) else {} + elif member == "filters": + out[member] = _grid().clean_filter_tree( + [item for item in value if isinstance(item, dict)], keys) if isinstance(value, list) else [] + elif member == "filterConj": + out[member] = "or" if value == "or" else "and" + elif member == "sorts": + out[member] = [{"colId": item["colId"], "dir": "desc" if item.get("dir") == "desc" else "asc"} + for item in value if isinstance(item, dict) and item.get("colId") in keys][:3] \ + if isinstance(value, list) else [] + elif member in ("groupBy", "colorBy"): + out[member] = value if value in keys else None + elif member == "rowHeightMode": + out[member] = value if value in ("short", "medium", "tall", "extra") else None + elif member == "frozenCount": + out[member] = max(0, min(6, int(value))) if isinstance(value, (int, float)) else 0 + elif member == "display": + out[member] = _grid()._clean_display(value, keys) if isinstance(value, dict) else out.get("display") + return out + + +@router.post("/query/{qid}/events") +def mutate_query_workspace(qid: str, body: dict = Body(default=None), + session: Session = Depends(require_session)): + """The only grid-mutation transport for a virtual Query workspace. + + ⭐⭐ W35-T25 (owner item 4 / R2) — `view_upsert` ON THE ARTEFACT ITSELF IS NOW ACCEPTED. It + used to 409 `query_workspace_immutable` for everything but a delete, on the reading that an AI + artefact is a snapshot. R2 replaces that reading: the SPEC is the reader's to shape, the + CITATION and the numbers behind it are not. `QUERY_EDITABLE_SPEC` above is where that line is + drawn, and `original_spec` is what makes the change undoable. + + Creating a SECOND view inside the workspace is still refused — an artefact holds exactly one — + and deleting the caller's personal artefact still removes it. The binding key, not a + client-supplied source scope, identifies it. """ + qid = str(qid) body = body if isinstance(body, dict) else {} - return _build(body.get("question"), body.get("scope"), session) - + binding = body.get("workspaceBinding") + event = body.get("event") + if not (isinstance(binding, dict) and binding.get("kind") == "query" + and str(binding.get("key") or "") == qid): + raise err(400, "query_workspace_mismatch", + "the Query workspace binding must name this virtual artefact") + if not isinstance(event, dict) or str(event.get("type") or "") not in QUERY_WORKSPACE_EVENTS: + raise err(400, "unsupported_query_workspace_event", + "Query accepts only view_create, view_upsert, or view_delete events") + + state = _state(session) + view = state["views"].get(qid) + if view is None or not _source_still_permitted(session, view.get("source")): + # A caller cannot use an opaque Query key to learn about a revoked artefact. + raise err(404, "unknown_query", "that Query artefact does not exist") + + event_type = str(event["type"]) + if event_type == "view_upsert": + sent = event.get("view") + sent = sent if isinstance(sent, dict) else {} + # ⛔ THE ID IS CHECKED THE SAME WAY THE DELETE'S IS. An upsert naming a different view is + # a create wearing an update's name, and a Query workspace holds exactly one view. + if str(sent.get("id") or "") != qid: + raise err(400, "query_workspace_mismatch", + "a Query view edit must name the same virtual artefact as its binding") + spec = _clean_spec_edit(sent.get("config"), view.get("view"), (view.get("source") or {}).get("fields")) + + def apply_edit(raw): + current = copy.deepcopy(raw) if isinstance(raw, dict) else _blank_state() + row = (current.get("views") or {}).get(qid) + if not isinstance(row, dict): + return current + # ⚠ BACKFILLED HERE, and only when absent: an artefact created before this wave has no + # original, and the FIRST edit is the last moment its pre-edit spec still exists. Not + # backfilling would leave it permanently unrevertable; backfilling unconditionally + # would make Revert restore the latest edit. + if not isinstance(row.get("original_spec"), dict): + row["original_spec"] = _safe(row.get("view")) + row["view"] = _safe(spec) + current["views"][qid] = row + return current + + if not session.runtime.available(): + raise err(503, "store_unavailable", "the tenant store is unavailable; nothing was saved") + session.runtime.update(_namespace_key(session), apply_edit, flush="async") + return {"workspaceBinding": {"kind": "query", "key": qid}, "event": event_type, + "view": _public_view(apply_edit(_state(session))["views"][qid])} + + if event_type != "view_delete": + raise err(409, "query_workspace_immutable", + "a Query workspace holds one view, so it cannot take another") + if str(event.get("viewId") or "") != qid: + raise err(400, "query_workspace_mismatch", + "a Query delete must name the same virtual artefact as its binding") + + deleted = delete_query(qid, session) + return {"workspaceBinding": {"kind": "query", "key": qid}, + "event": event_type, **deleted} + + +@router.post("/query/{qid}/revert") +def revert_query(qid: str, session: Session = Depends(require_session)): + """⭐⭐ CONTRACT C4 (R3) — restore the AI's original SPEC, and only the spec. + + ⛔ WHAT THIS DOES NOT DO, which the client's confirm says out loud BEFORE it acts: it does not + undo anything the reader changed in the SOURCE database. A Query view is live now, so a cell + edit made through it is a real write to a real record — reverting a view's filters cannot and + must not walk those back. R3 is explicit that the dialog states this before it acts, because a + Revert that silently leaves data changed is worse than one that never offered. + + ⚠ 409, not 404, when there is no original: the artefact exists and is readable, and the caller + asked for something that does not exist FOR IT. A 404 would say the artefact is gone. + """ + qid = str(qid) + # ⚠ `_artifact_or_404` returns `(state, row)`, not the row. Read it as a pair. + _state_now, view = _artifact_or_404(session, qid) + original = view.get("original_spec") + if not isinstance(original, dict): + raise err(409, "no_original_spec", + "this view was created before the assistant kept an original, so there is " + "nothing to revert to") + + def restore(raw): + current = copy.deepcopy(raw) if isinstance(raw, dict) else _blank_state() + row = (current.get("views") or {}).get(qid) + if not isinstance(row, dict): + return current + row["view"] = _safe(row.get("original_spec")) + current["views"][qid] = row + return current -def _build(question, scope, session, chat=None): - """`build_query`'s body, with the model injectable — see that route's note on why the seam is - here and not on the signature FastAPI reads.""" - question = ' '.join(str(question or "").split()) + if not session.runtime.available(): + raise err(503, "store_unavailable", "the tenant store is unavailable; nothing was reverted") + session.runtime.update(_namespace_key(session), restore, flush="async") + return _public_view(restore(_state(session))["views"][qid]) + + +def _sources(body, target, session): + raw = body.get("sources") if isinstance(body, dict) else None + sources = [str(item).strip() for item in raw] if isinstance(raw, list) else [] + sources = list(dict.fromkeys(item for item in sources if item)) + if target not in sources: + sources.insert(0, target) + # Source chips are a permissioned selection, not untrusted labels remembered in a thread. + # The model still receives ONLY `target`'s snapshot below; these calls do not pass a second + # source to it and D's helper refuses cache misses, mirrors and unshared databases. + for source in sources: + assistant_read_scope(session, source, fields=[], filters=None) + return sources + + +def _submit(body, session, chat=None): + body = body if isinstance(body, dict) else {} + question = " ".join(str(body.get("question") or "").split()) + target = str(body.get("database") or body.get("scope") or "").strip() + selected_model = str(body.get("model") or MODEL_AUTO).strip().lower() if not question: raise err(400, "bad_request", "no question was asked") if len(question) > MAX_QUESTION: - raise err(400, "question_too_long", - f"a question must be under {MAX_QUESTION} characters") - fields, _source = _target(session, scope) - if not fields: - raise err(400, "no_columns", "that database has no columns to build a view from") - - spec, transport, provider = _call_model(question, fields, chat=chat) - if transport: - return {"spec": None, "explain": None, "refused": transport, "provider": provider} - clean, refusal, code = _validate(spec, fields) - if refusal: - return {"spec": None, "explain": None, "refused": refusal, "reason": code, - "provider": provider} - return {"spec": clean, "explain": _explain(clean, fields), - "refused": None, "scope": scope, - "id": _qid(scope, question), "provider": provider} - - -@router.post("/query/save") -def save_query(body: dict = Body(default=None), session: Session = Depends(require_session)): - """Save an accepted spec as the CALLING USER's own view, and index it under Query. - - ⛔ THE SPEC IS RE-VALIDATED HERE, against the target's contract as it is NOW. The build door - wrote nothing, so this is the first write and it is the only place authorisation and validity - have to hold together — and a client is not a wall. An unsupported kind or an unknown column - is a **400 with a named code** on this door (the caller sent it), where the same fact is a - plain sentence on `build` (the model produced it). - """ - body = body if isinstance(body, dict) else {} - scope = str(body.get("scope") or '').strip() - question = ' '.join(str(body.get("question") or "").split())[:MAX_QUESTION] - fields, _source = _target(session, scope) - clean, refusal, code = _validate(body.get("spec"), fields) - if refusal: - raise err(400, code or "bad_spec", refusal) + raise err(400, "question_too_long", f"a question must be under {MAX_QUESTION} characters") + if not target: + raise err(400, "bad_request", "one target database must be selected") + if selected_model not in model_choices(): + raise err(400, "unknown_model", "that model is not available in Query") + + # This call happens before model selection and is the only permitted source-data read. + snapshot = assistant_read_scope(session, target, fields=None, filters=body.get("filters")) + sources = _sources(body, target, session) + state = _state(session) + thread_id = str(body.get("threadId") or "").strip() + if thread_id and thread_id not in state["threads"]: + raise err(404, "unknown_thread", "that chat does not exist") + if not thread_id: + thread_id = _new_id("thread") + now = _now_iso() + user_message_id = _new_id("message") + assistant_message_id = _new_id("message") + # R16: the turns already on screen go with the question. `state` was read above, BEFORE this + # turn's own messages exist, so the replay is strictly the prior conversation. + # ⭐ C7/T31: `session` rides along so the meter can attribute this call. See `_call_model`'s + # docstring for why it is an argument and not ambient state (PRD amendment A1). + spec, said, provider, reason = _call_model(question, snapshot, model=selected_model, chat=chat, + history=_history(state, thread_id), session=session) + view, refusal, refusal_code = _validate(spec, snapshot["fields"]) if spec is not None else (None, said, reason) + + artifact = None + citation = None + if view is not None: + if len(state["views"]) >= MAX_ARTIFACTS: + raise err(400, "query_limit", f"you already have {len(state['views'])} Query artefacts") + view_id = _new_id("query") + citation_id = _new_id("citation") + numeric = _numeric_result(view, _view_records(snapshot, view)) + citation = _citation(citation_id, snapshot, view, numeric, view_id) + if not _citation_complete(citation): + raise RuntimeError("Query refused to persist an incomplete numeric citation") + source = {"database": snapshot["database"], "label": snapshot["label"], + "source_kind": snapshot["source_kind"], "source_version": _safe(snapshot["source_version"]), + "retrieved_at": snapshot["retrieved_at"], + "fields": _safe(snapshot["fields"]), "filters": _safe(snapshot["filters"]), + "permission_scope_applied": snapshot["permission_scope_applied"]} + artifact = {"id": view_id, "threadId": thread_id, "name": view["name"], "description": "", + "question": question, + "explain": _explain(view, snapshot["fields"]), "createdAt": now, "source": source, + "view": _safe(view), "citationIds": [citation_id], "numeric": numeric, + # ⭐⭐ W35-T25 · CONTRACT C4 (R3) — THE AI'S OWN SPEC, WRITTEN ONCE, HERE. + # R2 makes a Query view editable, so `view` moves from now on. This is the copy + # "Revert to AI original" restores, and the thing `edited` is measured against. + # ⛔ WRITTEN AT CREATE AND NOWHERE ELSE. Re-stamping it on any later write would + # make Revert restore the most recent edit — a Revert that reverts to nothing, + # which C4 names as worse than no Revert at all. + # ⚠ `_safe(view)` twice, not the same object twice: `view` is mutable and a + # shared reference would let an edit rewrite the original through the alias. + "original_spec": _safe(view), + "model": provider, "requestedModel": selected_model} + + assistant_message = { + "id": assistant_message_id, "threadId": thread_id, "role": "assistant", "createdAt": now, + "content": (said or _said_fallback(artifact)) if artifact else (refusal or "the assistant could not answer"), + "targetDatabase": target, "requestedModel": selected_model, "model": provider, + "reason": refusal_code, "viewId": artifact["id"] if artifact else None, + "citationIds": artifact["citationIds"] if artifact else [], "numeric": artifact["numeric"] if artifact else None, + } + user_message = {"id": user_message_id, "threadId": thread_id, "role": "user", "createdAt": now, + "content": question, "sources": sources, "targetDatabase": target, + "requestedModel": selected_model} + + def update(raw): + current = _blank_state() + if isinstance(raw, dict): + for key in ("threads", "messages", "citations", "views"): + if isinstance(raw.get(key), dict): + current[key] = copy.deepcopy(raw[key]) + thread = current["threads"].get(thread_id) or {"id": thread_id, "createdAt": now} + # ⚠ THE FIRST QUESTION NAMES THE CHAT, and R16 is what makes that matter. While every turn + # was a fresh one-shot the title could only be the last thing asked; now that a thread is a + # conversation, retitling it on every follow-up renames the history entry out from under + # the reader, and "and the other one?" is a useless name for anything. + thread.update({"updatedAt": now, "title": thread.get("title") or question[:80], "sources": sources, + "model": selected_model, "activeViewId": artifact["id"] if artifact else thread.get("activeViewId")}) + current["threads"][thread_id] = thread + current["messages"][user_message_id] = user_message + current["messages"][assistant_message_id] = assistant_message + if artifact: + current["views"][artifact["id"]] = artifact + current["citations"][citation["id"]] = citation + return current + if not session.runtime.available(): - raise err(503, "store_unavailable", "the tenant store is unavailable — nothing was saved") - - vt = _templates() - ws_key = vt.workspace_key(scope) - if not ws_key: - raise err(404, "unknown_table", "that database does not exist") - qid = _qid(scope, question) if question else _qid(scope, clean['name']) - - # ⛔ THE SKELETON IS `view_templates._view`, NOT A SECOND ONE. "A view assembled from a - # DIFFERENT skeleton is a second definition of what a view is — and the two drift on the day - # one of them gains a key." It also puts the mode at `config.display.mode`, which is the key - # the grid actually reads (`config.displayMode` was the first draft, and nothing reads it). - payload = vt._view(qid, clean['name'], f"Built by the assistant from: {question}"[:300], - clean['visible'], mode=clean['kind'], - sorts=clean['sorts'], filters=clean['filters'], - group_by=clean['groupBy'], conj=clean['filterConj']) - if clean.get('display'): - payload['config']['display'] = dict(clean['display']) - payload['createdBy'] = session.uname - - # ⛔ THE CAP REFUSES; IT DOES NOT EVICT — and the first draft evicted. Dropping the oldest entry - # would leave its saved VIEW behind in the table's own workspace: "stranded in the target's view - # list with no way back to the question that made it", which is the thing `delete_query` below - # exists to prevent. And an eviction nobody was told about is W30/R6's second sentence broken — - # a limit that cannot be removed must be REPORTED with its cause. So the 201st is a refusal - # naming the number and the way out, checked BEFORE the view is written. - existing = _registry(session) - if qid not in existing and len(existing) >= MAX_REGISTRY: - raise err(400, "query_limit", - f"you already have {len(existing)} saved questions, which is the limit " - f"({MAX_REGISTRY}). Delete one you no longer need and save this again.") + raise err(503, "store_unavailable", "the tenant store is unavailable; no chat was saved") + session.runtime.update(_namespace_key(session), update, flush="async") + return {"thread": _safe(update(state)["threads"][thread_id]), "userMessage": _safe(user_message), + "message": _safe(assistant_message), + "view": _public_view(artifact) if artifact else None, "citations": [citation] if citation else []} + + +@router.post("/query/chat") +def submit_chat(body: dict = Body(default=None), session: Session = Depends(require_session)): + return _submit(body, session) - import core.table_store as table_store - ops = table_store.make(ws_key, st=session.runtime) - saved = ops.save_view(session.uname, payload, shared=False) - entry = {"scope": scope, "viewId": qid, "name": saved.get('name') or clean['name'], - "kind": clean['kind'], "question": question, - "explain": _explain(clean, fields), "createdBy": session.uname, - "createdAt": _now_iso()} +@router.delete("/query/threads/{tid}") +def delete_thread(tid: str, session: Session = Depends(require_session)): + """Remove one of the caller's own chats, and only the chat. - def _up(data): - data = data if isinstance(data, dict) else {} - data[qid] = entry - return data + ⛔ THE ARTEFACTS SURVIVE, AND THAT IS THE POINT. A Query view is a durable object in its own + right — it appears in Query's rail, other people's links can point at it, and the owner's + instruction was that AI views LIVE THERE rather than inside the conversation that happened to + produce them. Cascading the delete would make tidying up a chat silently destroy work. Views + are deleted from Query's own rail, one at a time, by `delete_query` below. - session.runtime.update(QUERY_KEY, _up, flush='async') - return {"id": qid, **entry} + ⚠ It exists because the history had no prune. `delete_query` removed a view and left its + thread, so the panel could only ever grow — a navigation you cannot manage is half a + navigation, and a person clearing test chats found that out first. + """ + tid = str(tid) + state = _state(session) + if tid not in state["threads"]: + raise err(404, "unknown_thread", "that chat does not exist") + + def update(raw): + current = _blank_state() + if isinstance(raw, dict): + for key in ("threads", "messages", "citations", "views"): + if isinstance(raw.get(key), dict): + current[key] = copy.deepcopy(raw[key]) + current["threads"].pop(tid, None) + for message_id in [key for key, row in current["messages"].items() + if (row or {}).get("threadId") == tid]: + current["messages"].pop(message_id, None) + # ⚠ THE VIEWS' `threadId` IS LEFT EXACTLY AS IT WAS, dangling. Blanking it looks tidier and + # is a data-loss bug: `queryApi.saved()` refuses a row with an empty `threadId`, so every + # artefact built in the deleted chat would silently vanish from Query's rail — the exact + # "tidying up destroys work" outcome this door is written not to have + # [[a-record-can-outlive-its-subject]]. Nothing resolves the id but the chat panel, which + # only ever looks up the thread it is showing. + return current + + session.runtime.update(_namespace_key(session), update, flush="async") + return {"deleted": tid} @router.delete("/query/{qid}") def delete_query(qid: str, session: Session = Depends(require_session)): - """Forget an AI-built view — the index entry AND the view itself. + qid = str(qid) + state = _state(session) + if qid not in state["views"]: + raise err(404, "unknown_query", "that Query artefact does not exist") + + def update(raw): + current = _blank_state() + if isinstance(raw, dict): + for key in ("threads", "messages", "citations", "views"): + if isinstance(raw.get(key), dict): + current[key] = copy.deepcopy(raw[key]) + view = current["views"].pop(qid, None) + for citation_id in (view or {}).get("citationIds") or []: + current["citations"].pop(citation_id, None) + return current + + session.runtime.update(_namespace_key(session), update, flush="async") + return {"deleted": qid} + + +# ══ R20 — A QUERY VIEW HAS EVERY FUNCTION A DATABASE VIEW HAS ═══════════════════════════════════ +# +# ⛔⛔ THE DECISION THIS TICKET ASKED FOR, WRITTEN DOWN RATHER THAN IMPLIED, because it is the line +# every later reader will need and there is no other place it exists. +# +# **IMMUTABLE, and unchanged by R20:** the generated SPEC and its provenance. `view` (kind, visible, +# filters, sorts, aggregation, display, important), `source` (the snapshot, its version, its +# retrieval time, the permission scope), `question`, `citationIds`, `numeric`. A cited number is +# only worth citing if the thing it was computed from cannot be edited underneath it, so +# `mutate_query_workspace` still answers 409 `query_workspace_immutable` for `view_create` and +# `view_upsert`, and `QUERY_MUTATION_POLICY` on the client is untouched. +# +# **OPENED:** `name` and `description`. They are LABELS, not the answer: changing them cannot make +# a citation wrong. Plus a server-side DUPLICATE (the client never supplies a spec, so a copy is a +# copy) and an EXPORT, which is a read. +# +# ⛔ AND THE REASON THESE ARE NAMED DOORS RATHER THAN AN OPENED `view_upsert`, which is what the +# ticket's `how:` first suggested: the client refuses `view_upsert` on a Query binding LOCALLY, +# before any request leaves the browser (`queryPreview.ts::routeQueryViewMutation`). Opening the +# server there would give one question two answers, and the client's is the one a person +# experiences. A named door has exactly one answer, and "opening a route widens every field it +# carries unless the cleaner is explicit" is answered by the allow-lists below rather than by hope. + +QUERY_NOTE_MAX = 400 + + +def _artifact_or_404(session, qid, state=None): + """The one wall every artefact door goes through: it exists AND this caller may still see it.""" + state = _state(session) if state is None else state + row = state["views"].get(str(qid)) + if row is None or not _source_still_permitted(session, row.get("source")): + # A caller cannot use an opaque Query key to learn about a revoked artefact. + raise err(404, "unknown_query", "that Query artefact does not exist") + return state, row + + +def _copy_name(name, taken): + """`X copy`, then `X copy 2`, so duplicating twice does not make two rows with one name.""" + base = f"{str(name or 'Query')[:52]} copy" + if base not in taken: + return base[:60] + index = 2 + while f"{base} {index}" in taken and index < 99: + index += 1 + return f"{base} {index}"[:60] + + +@router.patch("/query/{qid}") +def rename_query(qid: str, body: dict = Body(default=None), + session: Session = Depends(require_session)): + """Rename a Query view, or give it a description. Nothing else, by construction. + + ⚠ THE TEXT IS THE READER'S, SO IT IS NOT SWEPT FOR DASHES. R6 governs the copy WE write; a note + somebody typed about their own view is theirs, and rewriting its punctuation would be the + product editing a person's words. Model-authored strings are a different case and are swept + where they are produced (`_said`). + """ + body = body if isinstance(body, dict) else {} + state, row = _artifact_or_404(session, qid) + # An ALLOW-LIST, read key by key. A body carrying `view` or `source` changes neither. + patch = {} + if "name" in body: + patch["name"] = " ".join(str(body.get("name") or "").split())[:60] or row.get("name") or "Query" + if "description" in body: + patch["description"] = " ".join(str(body.get("description") or "").split())[:QUERY_NOTE_MAX] + if not patch: + raise err(400, "bad_request", "a Query view takes a new name or a new description") + + def update(raw): + current = _blank_state() + if isinstance(raw, dict): + for key in ("threads", "messages", "citations", "views"): + if isinstance(raw.get(key), dict): + current[key] = copy.deepcopy(raw[key]) + if str(qid) in current["views"]: + current["views"][str(qid)].update(patch) + return current + + if not session.runtime.available(): + raise err(503, "store_unavailable", "the tenant store is unavailable; nothing was renamed") + session.runtime.update(_namespace_key(session), update, flush="async") + return _public_view(update(state)["views"][str(qid)]) + + +@router.post("/query/{qid}/duplicate") +def duplicate_query(qid: str, session: Session = Depends(require_session)): + """A second artefact with the same spec and its own identity. + + ⛔ THE CITATIONS ARE COPIED, NOT SHARED. `delete_query` pops an artefact's citations by id, so a + copy pointing at the original's citation ids would lose its provenance the moment the original + was deleted, and a number with no citation is the one thing this module refuses to persist. + """ + state, row = _artifact_or_404(session, qid) + if len(state["views"]) >= MAX_ARTIFACTS: + # R6's second sentence: a cap that cannot be lifted here names its cause and the remedy. + raise err(400, "query_limit", + f"you already have {len(state['views'])} Query views, which is the most one " + f"account can hold. Delete one to make room for this copy.") + new_id = _new_id("query") + copied = copy.deepcopy(row) + copied["id"] = new_id + copied["name"] = _copy_name(row.get("name"), {r.get("name") for r in state["views"].values()}) + copied["createdAt"] = _now_iso() + citations = {} + for citation_id in row.get("citationIds") or []: + source = state["citations"].get(citation_id) + if not source: + continue + fresh_id = _new_id("citation") + citation = copy.deepcopy(source) + citation["id"] = fresh_id + citation["href"] = f"#/query?view={new_id}&citation={fresh_id}" + citations[fresh_id] = citation + copied["citationIds"] = list(citations) + + def update(raw): + current = _blank_state() + if isinstance(raw, dict): + for key in ("threads", "messages", "citations", "views"): + if isinstance(raw.get(key), dict): + current[key] = copy.deepcopy(raw[key]) + current["views"][new_id] = copied + current["citations"].update(citations) + return current + + if not session.runtime.available(): + raise err(503, "store_unavailable", "the tenant store is unavailable; nothing was copied") + session.runtime.update(_namespace_key(session), update, flush="async") + return _public_view(copied) + + +# ⛔ A REGISTRY KEY AND A GRID SCOPE ARE DIFFERENT SPELLINGS OF ONE DATABASE, and this product has +# already been bitten by treating them as the same: a `VIEW_OPEN` emit whose topic did not match was +# dropped SILENTLY, 200 OK, and an alert was filed against the wrong database. `customer_data` is +# what the assistant reads; `customer` is what the grid writes. `routes_grid._scope_or_400` refuses +# an unknown scope rather than defaulting it, so this map has to be right rather than nearly right. +_GRID_SCOPE = {"customer_data": "customer", "product_data": "product"} +# The keys a Query spec and a database view actually share. `aggregation` is deliberately absent: +# a database view has no aggregation of its own, which is why the reply below NAMES it as dropped +# instead of letting a "sum of value" answer land as a plain list of rows. +_SAVEABLE = ("visible", "filters", "filterConj", "sorts", "groupBy", "display", "important") + + +def _grid_scope(database): + key = str(database or "").strip() + return _GRID_SCOPE.get(key) or (key if key.startswith("ut_") else "") + + +@router.post("/query/{qid}/save-to-database") +def save_query_to_database(qid: str, session: Session = Depends(require_session)): + """R20: copy this answer into the database's OWN view list, where an ordinary view lives. + + ⛔⛔ `view_upsert` ANSWERS 200 WHILE WRITING NOTHING, IN TWO DIFFERENT WAYS, AND THE WIRE CANNOT + TELL YOU WHICH. `rerender: False` is the documented SUCCESS shape for this event, and it is + also what several silent-refusal branches return: a malformed payload, a missing id or name, an + id that belongs to a view the caller cannot SEE (the wave-9 shared-view guard, which makes + pinned ids effectively tenant-scoped), and a shared view they may see but not edit. So this + door does not believe the response. It READS THE STORE BACK and refuses out loud if the view is + not there. That read is same-process, which is what makes it valid despite `flush="async"`: + the write is visible through the cache long before it is durable. + + ⭐ ONE REQUEST, ONE EVENT. Eighteen POSTs against one JSON document under a coalescing + single-flight once landed ZERO while answering 200 eighteen times; the fix is a batch, never a + retry loop, which treats the symptom and doubles the races. + + ⚠ A FRESH ID, NEVER THE ARTEFACT'S. Reusing the Query id would be a guessable id in a shared + bucket, which is the exact door the wave-9 guard exists to shut. + """ + from routes_grid import grid_events_route + + state, row = _artifact_or_404(session, qid) + scope = _grid_scope((row.get("source") or {}).get("database")) + if not scope: + raise err(409, "unsaveable_source", + "this answer's database does not have a view list to save into.") + spec = row.get("view") or {} + config = {key: copy.deepcopy(spec[key]) for key in _SAVEABLE if spec.get(key) is not None} + config["important"] = spec.get("important") is True + view_id = _new_id("view") + name = " ".join(str(row.get("name") or "Query").split())[:120] or "Query" + + grid_events_route({"scopeKey": scope, "events": [{ + "id": _new_id("event"), "type": "view_upsert", + "view": {"id": view_id, "name": name, "config": config}, + }]}, session) + + document = session.runtime.get(f"{scope}_table_workspace") or {} + landed = (((document.get(session.uname) or {}).get("views") or {}).get(view_id) + if isinstance(document, dict) else None) + if not isinstance(landed, dict): + raise err(409, "view_not_saved", + "the database did not accept this view, so nothing was saved. Open the database " + "and check you can still add a view there.") + + # R6's second sentence, in the payload: what the database's own validator would not take is + # NAMED rather than quietly missing from a view that then looks complete. + stored = landed.get("config") or {} + dropped = [] + if str((spec.get("aggregation") or {}).get("op") or "count") != "count": + dropped.append("the aggregation, which a database view does not carry") + if len(stored.get("filters") or []) != len(config.get("filters") or []): + dropped.append("some of the conditions") + for key in ("visible", "sorts", "groupBy", "display"): + if config.get(key) and not stored.get(key): + dropped.append(key) + return {"scope": scope, "viewId": view_id, "name": landed.get("name") or name, + "dropped": dropped} + + +@router.post("/query/messages/{mid}/rating") +def rate_message(mid: str, body: dict = Body(default=None), + session: Session = Depends(require_session)): + """R20's thumbs, and the ONE thing that stops them being decoration. + + ⛔ A RATING THAT IS WRITTEN AND NEVER READ IS A FLAG SHIPPED WITHOUT ITS WRITER. This one is + read: `_history` turns a thumbs-down into a user turn saying the answer was not helpful, with + the reason if one was given, so the next question in the same thread is answered against that. + The scope is honest and narrow: it steers THIS conversation. It does not train anything, does + not cross threads, and does not cross accounts. + + ⚠ Rating is idempotent and CLEARABLE (`rating: null`), because a mis-click that cannot be taken + back is worse than no control at all, and a flag that can be set and never cleared is the same + defect `important` was fixed for. + """ + body = body if isinstance(body, dict) else {} + mid = str(mid) + raw = body.get("rating") + rating = str(raw or "").strip().lower() + if raw is not None and rating not in QUERY_RATINGS: + raise err(400, "bad_rating", "a rating is up, down, or nothing at all") + state = _state(session) + row = state["messages"].get(mid) + if row is None: + raise err(404, "unknown_message", "that message does not exist") + if row.get("role") != "assistant": + raise err(400, "bad_rating", "only an answer can be rated") + reason = " ".join(str(body.get("reason") or "").split())[:MAX_RATING_REASON] + + def update(raw_state): + current = _blank_state() + if isinstance(raw_state, dict): + for key in ("threads", "messages", "citations", "views"): + if isinstance(raw_state.get(key), dict): + current[key] = copy.deepcopy(raw_state[key]) + message = current["messages"].get(mid) + if message is not None: + message["rating"] = rating if raw is not None else None + # A reason belongs to a thumbs-down; clearing the rating clears it with them. + message["ratingReason"] = reason if (raw is not None and rating == "down") else "" + return current + + if not session.runtime.available(): + raise err(503, "store_unavailable", "the tenant store is unavailable; nothing was recorded") + session.runtime.update(_namespace_key(session), update, flush="async") + return _safe(update(state)["messages"][mid]) + + +@router.get("/query/{qid}/export") +def export_query(qid: str, session: Session = Depends(require_session)): + """The artefact's own rows and columns, as CSV. - Leaving the view behind would strand it in the target's view list with no way back to the - question that made it ([[a-record-can-outlive-its-subject]]). + ⚠ THE ARTEFACT IS FROZEN; ITS DATA IS NOT, and the difference is worth stating because the two + are easy to conflate. This re-reads the source through the SAME permission wall that built the + artefact and applies the view's own stored predicate, so the file matches what the grid is + showing right now, not the snapshot the stored `numeric` was computed from. That is the useful + answer: a person exports what they are looking at. """ - rec = _registry(session).get(str(qid)) - if not isinstance(rec, dict) or not _mine(session, rec): - raise err(404, "unknown_query", "that view does not exist") - _target(session, rec.get('scope')) # the wall, again, on the write path - vt = _templates() - ws_key = vt.workspace_key(rec.get('scope')) - if ws_key and session.runtime.available(): - import core.table_store as table_store - table_store.make(ws_key, st=session.runtime).delete_view( - session.uname, rec.get('viewId') or str(qid)) - - def _up(data): - data = data if isinstance(data, dict) else {} - data.pop(str(qid), None) - return data - - session.runtime.update(QUERY_KEY, _up, flush='async') - return {"deleted": str(qid)} + state, row = _artifact_or_404(session, qid) + source = row.get("source") or {} + # ⛔ THIS PASSES A STORED OUTPUT BACK INTO AN INPUT SLOT, WHICH IS WORTH STATING RATHER THAN + # HIDING. `source["filters"]` is `deps.assistant_read_scope`'s OWN return value, and that value + # is `validate_assistant_filter(filters, visible)` — the VALIDATED form of whatever the caller + # asked for. MEASURED: `queryApi.submitChat` sends no `filters` key at all, so in production + # this is `None` on every artefact and the round trip never happens. + # ⚠ It is sent anyway, and deliberately, because the alternative FAILS OPEN. If a caller ever + # does narrow a source, dropping the filter here would export MORE rows than the artefact was + # built from, silently. Sending it means a stored filter that cannot be re-validated comes back + # as a NAMED 400 (`assistant_bad_filter`) instead — the fail-closed direction. The gate asserts + # what this door PASSES rather than what the fixture echoes back, because a double built from + # the producer would make this argument valid by construction. + snapshot = assistant_read_scope(session, source.get("database"), fields=None, + filters=source.get("filters") or None) + labels = {field["key"]: str(field.get("label") or field["key"]) for field in snapshot["fields"]} + columns = [key for key in (row["view"].get("visible") or ()) if key in labels] + if not columns: + raise err(409, "nothing_to_export", + "none of this view's columns exist in the database any more, so there is " + "nothing to export. Ask the assistant to build it again.") + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n") + writer.writerow([labels[key] for key in columns]) + for record in _view_records(snapshot, row["view"]): + writer.writerow(["" if record.get(key) is None else record.get(key) for key in columns]) + stem = re.sub(r"[^A-Za-z0-9]+", "_", str(row.get("name") or "query")).strip("_") or "query" + return Response( + content=buffer.getvalue(), media_type="text/csv; charset=utf-8", + # ⚠ ASCII-only filename: a header carrying a non-ASCII byte is refused by some servers and + # silently mangled by others, and the stem above comes from a model-authored name. + headers={"Content-Disposition": f'attachment; filename="{stem[:60]}.csv"'})