DESIGN GUIDE — dashboards that look finished, not generated (schema 1.14; follow unless the user asks otherwise)

0. BEFORE YOU BUILD — reuse what this deployment already has
  - MODULES FIRST. Each installed module's manual (MODULE CONTEXT, llm_context) lists the Lambda
    functions it already runs: inputs, the result's columns, the blocks it suits. When one already
    computes what a tile needs (a forecast, a scoring model, a summary, an API lookup), call it —
    "exec": {"type": "lambda", "module_id": "<id>", "lambda_index": <n>} plus the inputs its manual
    names — instead of re-deriving it in SQL or proposing a new service or async job. Build new only
    when no installed function fits, and say so.
  - HOUSE STYLE. When pinned or favorited dashboards are available, read one or two first and follow
    their conventions (card colors, KPI wording, units, naming, how they filter, their SQL patterns
    and tables) unless the user asks for something else.

0b. NATIVE, EXTENDED, EMBEDDED OR STANDALONE — choose the pattern before you build
  Reuse (native)  an existing block reaches parity: plotly (every Plotly trace type), table (AG Grid
                  Community, as the table block's config exposes it: the TABLE GUIDE), markdown, image,
                  the inputs. KPI bands, trends, ranked tables, status colours.
  Extend          native cannot show it, or a richer view adds real value:
                    - Markdown with "html": "basic" on the markdown block: formatting and layout (columns,
                      callouts, badges) through a fixed set of classes; nothing executes, no permission
                      needed. Two-column notes, callouts.
                    - a custom block: installed, hash-checked, reusable, no network
                      ({"type": "raw_html", "config": {"extension": {"module_id", "block"}}}). A
                      collapsible org chart; a calendar heatmap. A block whose block.json says
                      "bridge": ["params"] may set and read the page's inputs (filter the page on click).
                    - inline raw_html: one-off, needs the Raw HTML permission.
  Embed           it is an application, not a view: several screens, forms that change state, a backend
                  of its own. An html_app module, shown as one tile ({"type": "html_app", "config":
                  {"module_id": "<id>"}}) that talks to its own module through the host bridge; its
                  operations run as tile runs for the viewer. A report scheduler, a query workbench.
  Externalize     it needs a runtime StrataBI cannot host: long-lived processes, a terminal, websockets,
                  heavy compute. A standalone_service module beside StrataBI.
  Rules:
    1. Start native. Check the native catalogue first, including what the table block's AG Grid does
       (TABLE GUIDE: sorting, filters, pinning, sizing, wrap, cellClassRules / rowClassRules, formats,
       tooltips, pagination) and Plotly's trace types (sankey, treemap, sunburst, funnel, heatmap,
       indicator, ...).
    2. Use an HTML extension when the existing blocks cannot reach parity, when it adds a view or
       interaction they cannot offer and the reader gains from it, or when the developer explicitly
       overrides the choice. Never use one to restyle or rebuild what a native block already does. Say
       which reason applies.
       For formatting prefer Markdown "html": "basic" over raw_html; once the same raw_html is used
       twice, make it a custom block.
    3. Embed (html_app) when it is an application.
    4. Externalize (standalone_service) only for a runtime StrataBI cannot host.
    5. Whenever the choice is not native, say which pattern and why, in one line.

1. PAGE SKELETON — pick one, then fill it
  Explorer (the user filters):        Monitor (no filters):
    row 0  intro (12)                   row 0  intro (12)
    row 1  LEFT RAIL (3): the controls, row 1  KPI BAND: 4 KPI cards, width 3 each
           then the KPI cards they drive row 2  main trend (8) | ranking or KPI stack (4)
           | main chart + note (9)      row 3  breakdowns (6 | 6)
    row 2  supporting charts (6 | 6)    last   detail / exceptions table (12)
    row 3  detail table (12)
  VERTICAL STACKS: tiles in the same row with the same "position": {"stack": "<name>"} form ONE
  column, one under another (in "order"); the column is as wide as its widest tile and sits where
  its first tile is ordered. A row's columns (a stack counts once) add up to 12. Use stacks to put
  several small tiles — inputs, KPI cards, notes — beside one tall chart instead of making more rows.
  CONTROLS ALWAYS STACK: every input on a page goes in one vertical column on the left
  ("position": {"row": 1, "order": 0..n, "width": 3, "stack": "rail"}), never one per row and
  never spread across the page. 4+ inputs, or tight controls asked for: the compact group (section 6).
  BALANCE THE ROW: a row's columns should end at about the same height, or the short one leaves an
  empty hole. Rough card heights: an input ~110px, a KPI card ~195px, a chart or table its
  config.height + ~120px, a 2-3 line note ~150px (+16px between stacked tiles). Two controls alone
  (~240px) beside a 450px chart leave a hole: put the KPI cards under the controls in the same rail,
  or add a note under the short column, or size the charts to match.

2. KPI CARDS — live numbers from data, never a one-row table, never hard-coded
  - A KPI tile runs a query (or cache) that returns ONE row and shows it with a markdown TEMPLATE:
      "block": {"type": "markdown", "config": {"template": "### {revenue_ytd:,.0f}\n{yoy_pct:+.1f}% vs last year", "content": "…"}}
    Fields are the result's columns; Python format specs: {x:,.0f} 12,345 · {x:,.2f} · ${x:,.0f} ·
    {x:.1f}% · {x:+.1f} (signed delta) · {x:,} (integer). Missing values show as —. "content" shows
    until the data arrives. {_rows} is the row count.
  - Or a Plotly indicator: {"type": "indicator", "mode": "number+delta", "value": "@revenue_ytd",
    "number": {"valueformat": "$,.0f"}, "delta": {"reference": "@revenue_target_ytd", "relative": true,
    "valueformat": ".1%"}} — a value bound to a column shows its LAST value; "@col[0]" binds the first row.
  - Width 3, a "title" naming the metric ("Revenue YTD"), card color primary (warning only for an
    exception count). Several KPIs: a KPI band (4 across) or a KPI stack (stack "kpis") beside the
    main chart. Each KPI tile may run the same one-row query.

3. CHARTS (plotly) — "theme_colors": true, "height": "300px"-"380px" (same height across a row)
  - One line / bar series per entity from long-format rows (one row per entity per date): ONE trace
    with "split_by": "<entity column>" — {"type": "scatter", "mode": "lines", "x": "@date",
    "y": "@oil_bbl", "split_by": "well_id"}. Plotly "transforms" (filter, groupby, aggregate, sort)
    also work and are applied by StrataBI: {"type": "filter", "target": "@state", "operation": "=", "value": "open"}.
  - Trend over time: lines (or bars per day/week). Composition over time: bars, split_by,
    "barmode": "stack". Ranking: horizontal bar, sorted ({"type": "sort", "target": "x", "order":
    "ascending"} with "orientation": "h"). Many entities over time (8+): a heatmap (x date, y entity,
    z value) instead of 8+ lines. Distribution: histogram or box. Relationship: scatter.
  - Axis titles with units ("yaxis": {"title": "bbl/d"}); number formats ("tickformat": ",.0f",
    "$,.2s", ".0%"); readable "hovertemplate". No figure title (the card title is the title).
    Legend on top, horizontal ("legend": {"orientation": "h", "y": 1.12}); none for one series.
    Margins {"t": 10, "r": 10, "b": 40, "l": 50}. Leave backgrounds unset (transparent).
  - Avoid: pies with more than 5 slices (use a sorted bar), 3D, dual y-axes unless asked, text
    labels inside many bars, more than 8 lines on one chart, bubbles without "sizemode": "area".

4. TABLES — always column_defs, readable and formatted
  "column_defs": [{"field": "order_date", "headerName": "Date", "format": "date"},
                  {"field": "amount", "headerName": "Amount", "format": "currency", "sort": "desc"}]
  formats: integer · number[:n] · currency[:n] · percent[:n] (value already in %) · ratio[:n]
  (0-1 shown as %) · compact (26.5M) · date · datetime. 5-8 columns, the useful sort first,
  "page_size": 10-15, "height": "420px". Exceptions (open incidents, wells down, breaches): card
  warning or danger. Exportable lists: "artifact": {"download": true}.
  The grid is AG Grid 35.3 Community: status colours with cellClassRules / rowClassRules, filters,
  pinning, sizing and tooltips work (TABLE GUIDE); grouping, pivot, set filter, master/detail and Excel
  export are Enterprise and do nothing here: group and pivot in SQL instead.

4b. SQL (Athena = Trino dialect) — the query shapes the result; the tile only binds columns
  - Return exactly the columns the block binds, aliased to the names it uses ("@revenue" needs
    "... AS revenue"); aggregate in SQL (GROUP BY), never ship raw rows for a chart to count.
  - Never SELECT *. Filter early: WHERE on partition/date columns first (Athena scans what you
    read); a detail table gets ORDER BY + LIMIT (100-500).
  - Dates: date_trunc('month', ts), date_add('day', -30, current_date), DATE '2026-01-01',
    format_datetime(ts, 'yyyy-MM') only for labels. Ratios: 100.0 * a / NULLIF(b, 0). Casts:
    CAST(x AS double), TRY_CAST for dirty text. approx_percentile(ms, 0.95) for p95.
  - Windows for running totals, ranks and period-over-period: sum(x) OVER (ORDER BY month),
    rank() OVER (ORDER BY revenue DESC), lag(revenue) OVER (PARTITION BY region ORDER BY month).
    WITH (CTE) blocks keep a multi-step query readable.
  - Inputs: ":name" in the SQL + "query": {"params": {"name": "<input_id>"}}; every :name must be
    in params, and every params value must be an input's config.input_id. An "all" option:
    WHERE (:region = 'ALL' OR region = :region). Numbers typed into a text box: CAST(:min AS bigint).
    A multi-select value is a list: region IN :regions.
  - One-row KPI queries return named scalars (SELECT sum(x) AS total, ...); a "vs last period"
    delta is computed in the same query (conditional sums or a CTE per period).

5. CARDS AND COLOR — every tile gets an OUTLINED card: "card": {"color": "<c>", "outline": true}
    secondary = controls and context (inputs, filters, reference lists)
    primary   = the headline numbers (KPI cards)
    info      = supporting charts (success too, and primary/secondary, when charts carry notes: 7)
    warning / danger = ONLY exceptions, alerts, SLA breaches, things down
  3-4 colors per page at most (one more when charts carry color-coded notes). The intro tile has
  no chrome: "card": {"show_header": false}.

6. CONTROLS
  - Input tiles: a "title" (or config.label) and a sensible default "value". Tiles they drive list
    them in "triggered_by" (the input tile id) and use "load": {"mode": "input", "keep_previous": true};
    SQL takes them through "query": {"params": {"name": "<input_id>"}}.
  - COMPACT GROUP (4+ inputs, a filter form, or when asked): the controls become ONE box. Every
    tile of the group: same row, same "stack", same color, NO card of its own —
    "card": {"color": "secondary", "outline": true, "visible": false, "border": "top"} on the first,
    "middle" on the ones between, "bottom" on the last. No "title": the label goes in config,
    beside the control ("label": "Region", "label_position": "left", "label_width": "6rem"); a
    slider keeps its label on top ("label_position": "top"); a one-line text box
    "multiline": false. End the group with an Apply row that the data tiles listen to:
      {"id": "apply", "position": {"row": 1, "order": 4, "width": 3, "stack": "rail"},
       "card": {"color": "secondary", "outline": true, "visible": false, "border": "bottom"},
       "controls": {"run_button": true, "run_position": "left"},
       "block": {"type": "markdown", "config": {"content": "**Apply filters**"}}}
    Data tiles: "triggered_by": ["apply"] (they run on load, then on Apply — not on every change),
    "load": {"mode": "input", "keep_previous": true}, "controls": {"run_button": false}. Put the
    KPI cards they drive under the group in the same rail (reference: order_explorer).
  - Re-read buttons: "controls": {"run_button": true, "run_icon": "refresh"}; actions keep ▷ and a
    "placeholder" saying what ▷ does.

7. EXPLAINING THE DASHBOARD — when the user asks for explanations / annotations / a narrative
  - Put a short markdown NOTE next to the chart it explains: stacked directly under it (same row,
    same "stack" as the chart) or a 3-wide note beside it, with a short title ("Reading the trend",
    "About this chart").
  - COLOR-CODE each chart with its note: the note takes THE SAME CARD COLOR as its chart, and charts
    side by side take DIFFERENT colors, so a reader sees which note belongs to which chart. Cycle
    info, success, primary, secondary across the explained charts of a row (warning/danger stay
    for exceptions):
      row 2: chart "info" + note "info"    |  chart "success" + note "success"
      row 3: chart "primary" + note "primary" | chart "info" + note "info"
  - 2-4 sentences: what the chart shows, how to read it, what to look for / act on. Quote live numbers
    with a template on the same query ("{open_tickets:,} tickets are open; …"). No notes unless asked
    (an intro line is always fine).

8. REFRESH
  Async tiles that refresh in place: "load": {"keep_previous": true}. On a timer: "load": {"mode":
  "interval", "interval_ms": 60000, "keep_previous": true} and "card": {"timestamp": true}.
  A tile that is slow to load (seconds, not a blink) says so in its header: "card": {"badge": {"text":
  "Slow · ~20 s", "level": "warning", "detail": "Scans 40 GB per run; a cache module would make it instant"}}.
  Fix the cause when you can (narrower SQL, exec.async, a cache tile) and remove the badge.

9. BEFORE YOU ANSWER, CHECK
  [ ] every row's widths add to 12; controls in ONE stacked column (4+: one compact group with an
      Apply row); KPIs as cards (band or stack); a row's columns end at about the same height
  [ ] each KPI is live (template / indicator on a one-row query), never a table or a typed number
  [ ] per-entity series use split_by (or a heatmap for many); every chart has height + axis titles
  [ ] every table has column_defs with headerName + format; exceptions colored warning/danger
  [ ] 3-4 card colors; notes (when asked) share their chart's color, charts side by side differ
  [ ] an installed module's function is used wherever one already computes what a tile needs
  [ ] native blocks first; any HTML extension or app says, in one line, which pattern and why (0b)
  [ ] SQL returns only the columns bound (aliased), aggregates in SQL; every :param is in params,
      every params value is an input_id, and the tile is triggered by those inputs (or Apply)
  [ ] valid against the schema: "card" is an object, heights are strings, no invented fields

EXAMPLE (valid; a balanced row: left rail = controls then the KPI cards they drive, chart + note stacked
  beside it; split_by; live KPIs; formatted table):
{"name": "Fleet Operations", "description": "Fuel economy, utilization and the units that need attention, by region.", "layout": [
 {"id": "intro", "position": {"row": 0, "order": 0, "width": 12}, "card": {"show_header": false}, "block": {"type": "markdown", "config": {"content": "## Fleet Operations\nFuel economy, utilization and the units that need attention. Pick a region and a period on the left."}}},
 {"id": "region_input", "title": "Region", "position": {"row": 1, "order": 0, "width": 3, "stack": "rail"}, "card": {"color": "secondary", "outline": true}, "block": {"type": "input_select", "config": {"input_id": "region", "component": "dropdown", "value": "ALL", "clearable": false, "options": [{"label": "All regions", "value": "ALL"}, {"label": "West", "value": "West"}, {"label": "Gulf", "value": "Gulf"}]}}},
 {"id": "weeks_input", "title": "Weeks shown", "position": {"row": 1, "order": 1, "width": 3, "stack": "rail"}, "card": {"color": "secondary", "outline": true}, "block": {"type": "input_range", "config": {"input_id": "weeks", "label": "Weeks shown", "min": 4, "max": 26, "step": 1, "value": 14}}},
 {"id": "fuel_trend", "title": "Fuel economy by week (mpg)", "position": {"row": 1, "order": 5, "width": 9, "stack": "main"}, "card": {"color": "info", "outline": true}, "triggered_by": ["region_input", "weeks_input"], "load": {"mode": "input", "keep_previous": true}, "exec": {"type": "athena", "database": "fleet", "async": true, "result_kind": "dataframe", "result_format": "parquet"}, "query": {"sql": ["SELECT week, region, mpg FROM fuel_weekly", "WHERE (:region = 'ALL' OR region = :region)", "  AND week >= date_add('week', -:weeks, current_date)", "ORDER BY week"], "params": {"region": "region", "weeks": "weeks"}}, "block": {"type": "plotly", "config": {"theme_colors": true, "height": "520px", "figure": {"data": [{"type": "scatter", "mode": "lines+markers", "x": "@week", "y": "@mpg", "split_by": "region", "hovertemplate": "%{x|%b %d}: %{y:.2f} mpg<extra>%{fullData.name}</extra>"}], "layout": {"margin": {"t": 10, "r": 10, "b": 40, "l": 50}, "yaxis": {"title": "mpg"}, "legend": {"orientation": "h", "y": 1.12}}}}}},
 {"id": "fuel_note", "title": "Reading the trend", "position": {"row": 1, "order": 6, "width": 9, "stack": "main"}, "card": {"color": "info", "outline": true}, "block": {"type": "markdown", "config": {"content": "One line per region. A line sliding down means trucks are burning more fuel per mile - check idle time and service history in the table below."}}},
 {"id": "kpi_mpg", "title": "Fuel economy", "position": {"row": 1, "order": 2, "width": 3, "stack": "rail"}, "card": {"color": "primary", "outline": true}, "triggered_by": ["region_input"], "load": {"mode": "input", "keep_previous": true}, "exec": {"type": "athena", "database": "fleet", "result_kind": "dataframe", "result_format": "parquet"}, "query": {"sql": "SELECT mpg_avg, mpg_delta, utilization_pct, units_active, exceptions_open FROM fleet_kpis_by_region WHERE region = :region", "params": {"region": "region"}}, "block": {"type": "markdown", "config": {"template": "### {mpg_avg:.1f} mpg\n{mpg_delta:+.1f} vs last week", "content": "…"}}},
 {"id": "kpi_util", "title": "Utilization", "position": {"row": 1, "order": 3, "width": 3, "stack": "rail"}, "card": {"color": "primary", "outline": true}, "triggered_by": ["region_input"], "load": {"mode": "input", "keep_previous": true}, "exec": {"type": "athena", "database": "fleet", "result_kind": "dataframe", "result_format": "parquet"}, "query": {"sql": "SELECT mpg_avg, mpg_delta, utilization_pct, units_active, exceptions_open FROM fleet_kpis_by_region WHERE region = :region", "params": {"region": "region"}}, "block": {"type": "markdown", "config": {"template": "### {utilization_pct:.1f}%\n{units_active:,} units active", "content": "…"}}},
 {"id": "kpi_exceptions", "title": "Needs attention", "position": {"row": 1, "order": 4, "width": 3, "stack": "rail"}, "card": {"color": "warning", "outline": true}, "triggered_by": ["region_input"], "load": {"mode": "input", "keep_previous": true}, "exec": {"type": "athena", "database": "fleet", "result_kind": "dataframe", "result_format": "parquet"}, "query": {"sql": "SELECT mpg_avg, mpg_delta, utilization_pct, units_active, exceptions_open FROM fleet_kpis_by_region WHERE region = :region", "params": {"region": "region"}}, "block": {"type": "markdown", "config": {"template": "### {exceptions_open} units\nwith open exceptions", "content": "…"}}},
 {"id": "miles_by_region", "title": "Miles driven by region", "position": {"row": 2, "order": 0, "width": 6}, "card": {"color": "info", "outline": true}, "triggered_by": ["weeks_input"], "load": {"mode": "input", "keep_previous": true}, "exec": {"type": "athena", "database": "fleet", "async": true, "result_kind": "dataframe", "result_format": "parquet"}, "query": {"sql": "SELECT region, miles FROM region_miles WHERE weeks = :weeks", "params": {"weeks": "weeks"}}, "block": {"type": "plotly", "config": {"theme_colors": true, "height": "300px", "figure": {"data": [{"type": "bar", "orientation": "h", "x": "@miles", "y": "@region", "transforms": [{"type": "sort", "target": "x", "order": "ascending"}], "hovertemplate": "%{y}: %{x:,.0f} miles<extra></extra>"}], "layout": {"margin": {"t": 10, "r": 20, "b": 40, "l": 70}, "xaxis": {"title": "miles", "tickformat": ",.2s"}}}}}},
 {"id": "util_by_region", "title": "Utilization by region (%)", "position": {"row": 2, "order": 1, "width": 6}, "card": {"color": "info", "outline": true}, "triggered_by": ["weeks_input"], "load": {"mode": "input", "keep_previous": true}, "exec": {"type": "athena", "database": "fleet", "async": true, "result_kind": "dataframe", "result_format": "parquet"}, "query": {"sql": "SELECT region, utilization_pct FROM region_miles WHERE weeks = :weeks", "params": {"weeks": "weeks"}}, "block": {"type": "plotly", "config": {"theme_colors": true, "height": "300px", "figure": {"data": [{"type": "bar", "x": "@region", "y": "@utilization_pct", "text": "@utilization_pct", "texttemplate": "%{text:.1f}%", "textposition": "outside", "hovertemplate": "%{x}: %{y:.1f}%<extra></extra>"}], "layout": {"margin": {"t": 20, "r": 10, "b": 40, "l": 50}, "yaxis": {"title": "%", "range": [80, 100]}}}}}},
 {"id": "exceptions", "title": "Units needing attention", "position": {"row": 3, "order": 0, "width": 12}, "card": {"color": "warning", "outline": true}, "triggered_by": ["region_input"], "load": {"mode": "input"}, "exec": {"type": "athena", "database": "fleet", "async": true, "result_kind": "dataframe", "result_format": "parquet"}, "query": {"sql": "SELECT unit_id, region, issue, since, severity, miles_since_service FROM fleet_exceptions WHERE (:region = 'ALL' OR region = :region) ORDER BY miles_since_service DESC", "params": {"region": "region"}}, "controls": {"run_button": true, "run_icon": "refresh"}, "artifact": {"download": true}, "block": {"type": "table", "config": {"page_size": 10, "height": "420px", "column_defs": [{"field": "unit_id", "headerName": "Unit", "pinned": "left", "width": 120}, {"field": "region", "headerName": "Region"}, {"field": "issue", "headerName": "Issue", "flex": 2}, {"field": "since", "headerName": "Since", "format": "date"}, {"field": "severity", "headerName": "Severity"}, {"field": "miles_since_service", "headerName": "Miles since service", "format": "integer", "sort": "desc"}]}}}
]}
