File size: 67,489 Bytes
c14ceee
 
 
 
 
8145bee
c14ceee
 
 
 
 
 
 
 
 
 
8145bee
c14ceee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
c14ceee
 
 
 
 
1ad1eea
 
c14ceee
 
1ad1eea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c14ceee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
c14ceee
8145bee
c14ceee
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
8145bee
 
d598032
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
c14ceee
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
c14ceee
 
7f72224
d598032
b2aa446
 
 
8145bee
 
d598032
 
 
 
7f72224
 
d598032
 
 
 
 
 
b2aa446
8145bee
 
c14ceee
8145bee
 
d598032
 
8145bee
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
8145bee
 
 
d598032
 
 
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
 
d598032
 
 
c14ceee
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
c14ceee
 
 
 
 
d598032
 
c14ceee
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
d598032
 
b2aa446
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c14ceee
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
c14ceee
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
 
d598032
 
 
 
1ad1eea
 
c14ceee
 
 
 
 
1ad1eea
c14ceee
 
 
 
609fb78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c14ceee
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
 
 
 
c14ceee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
8145bee
 
 
 
 
 
 
1ad1eea
 
8145bee
7f72224
8145bee
7f72224
1ad1eea
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
8145bee
7f72224
8145bee
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
7f72224
c14ceee
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
c14ceee
7f72224
 
 
c14ceee
 
 
 
7f72224
 
c14ceee
1ad1eea
 
7f72224
d598032
 
 
 
7f72224
d598032
 
c14ceee
 
8145bee
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
1ad1eea
c14ceee
 
 
 
 
 
 
 
8145bee
1ad1eea
c14ceee
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c14ceee
 
 
 
 
 
 
 
4b54047
c14ceee
 
ea7b176
 
 
 
 
7f72224
 
ea7b176
 
c14ceee
 
 
 
 
 
8145bee
c14ceee
 
 
d598032
 
 
 
 
 
 
 
 
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c14ceee
 
8145bee
c14ceee
 
 
8145bee
c14ceee
8145bee
c14ceee
4b54047
c14ceee
 
8145bee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
"""harness/analyst.py β€” the AIOS Analyst loop (OM-4, 2026-07-11).

A CHEAP small model (via OpenRouter, OpenAI-compatible) drives the compounding tool registry
(harness/tools.py) to answer questions, build charts, and spawn dashboards over the semantic
layer. The model NEVER writes SQL β€” it picks registry keys, guided by the in-product SKILL
recipe index and exact on-demand bodies (model/skills/*.skill.yml). Plan: omni-adoption addendum.

Architecture (mirrors the Omni coordinator pattern):
  ask(question) -> bounded tool loop: chat -> tool_calls -> tools.dispatch() -> results -> chat …
  until a plain answer or MAX_ITERS. chat_fn is INJECTABLE: live = OpenRouter POST; tests = a
  scripted double β€” the loop mechanics are provable offline (no key, no tokens).

Correctness posture: bounded iterations (never endless); tool errors go BACK to the model as
readable envelopes (it self-corrects); the final answer carries the tool trace (auditability +
the drill guarantee); exhausted-budget is reported AS exhausted, never as success (loop rules).
Cost posture: DEFAULT_MODEL is a cheap tool-calling model; override per-tenant/env; prompt = the
skill index + topic summary (small, cacheable), NOT raw data.
"""
import json
import os
from pathlib import Path

import harness.tools as T

# Provider LADDER (owner 2026-07-12: "use Groq and Cerebras"): all OpenAI-compatible chat
# endpoints; tried in order, failing over on payment/rate/server errors β€” an exhausted or
# rate-limited provider degrades to the next instead of taking the Analyst down (the
# OpenRouter-402 incident). Pin one with ANALYST_PROVIDER=groq|cerebras|openrouter; override
# its model with ANALYST_MODEL. Every model here must re-pass the eval gate (Β§4b).
PROVIDERS = [
    {"name": "groq", "env": "GROQ_API_KEY",
     "url": "https://api.groq.com/openai/v1/chat/completions",
     "model": "openai/gpt-oss-120b"},
    {"name": "cerebras", "env": "CEREBRAS_API_KEY",
     "url": "https://api.cerebras.ai/v1/chat/completions",
     "model": "gpt-oss-120b"},          # this account's tool-capable model (from /v1/models)
    {"name": "openrouter", "env": "OPENROUTER_API_KEY",
     "url": "https://openrouter.ai/api/v1/chat/completions",
     # The eval measures this default: analyst_golden.yml `measured` names it, open weights only (R11).
     "model": "z-ai/glm-4.7-flash"},
]
DEFAULT_MODEL = None          # None = the selected provider's default model
# A map, YoY or name-resolution ask needs about 8 tool turns with no retry (list, describe,
# recipe, field values, query, transform, chart, answer), so 8 exhausted 7 of 26 items (D-8280).
# 14 leaves room for 6 error-correction turns. ANALYST_MAX_ITERS overrides it per run.
MAX_ITERS = 14


def iter_budget():
    """The tool-loop budget: ANALYST_MAX_ITERS when set to a positive integer, else MAX_ITERS."""
    try:
        value = int(os.environ.get("ANALYST_MAX_ITERS") or MAX_ITERS)
    except ValueError:
        return MAX_ITERS
    return value if value > 0 else MAX_ITERS


#: Working-context byte ceiling per provider. Groq and Cerebras fail near 8k request tokens.
#: OpenRouter tool models take 128k+ tokens. 120000 bytes (about 30k tokens) fits a full
#: discovery run and keeps each request cheap.
REQUEST_BYTES = {"groq": 32000, "cerebras": 32000, "openrouter": 120000}
DEFAULT_REQUEST_BYTES = 32000


def request_budget(provider=None):
    """The request byte ceiling: ANALYST_MAX_REQUEST_BYTES when a positive integer, else per provider."""
    try:
        value = int(os.environ.get("ANALYST_MAX_REQUEST_BYTES") or 0)
    except ValueError:
        value = 0
    if value > 0:
        return value
    return REQUEST_BYTES.get(provider, DEFAULT_REQUEST_BYTES)


#: Set by harness/evals.run to the golden item id, so each ledger line names its item.
CALL_ITEM = None
#: Running totals of ledger lines written by this process (evals.run reads the delta).
CALL_TOTALS = {"calls": 0, "cost": 0.0, "cost_missing": 0}


def _log_call(usage):
    """Append one cost line to ANALYST_CALL_LOG. Never writes message or answer text."""
    path = os.environ.get("ANALYST_CALL_LOG")
    if not path:
        return
    import time as _time

    usage = usage or {}
    cost = usage.get("cost")
    cost = float(cost) if isinstance(cost, (int, float)) and not isinstance(cost, bool) else None
    line = {"ts": _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime()),
            "provider": usage.get("provider"), "model": usage.get("model"),
            "item": CALL_ITEM,
            "prompt_tokens": usage.get("prompt_tokens"),
            "completion_tokens": usage.get("completion_tokens"),
            "cost": cost}
    with open(path, "a", encoding="utf-8", newline="") as fh:
        fh.write(json.dumps(line, separators=(",", ":")) + "\n")
    CALL_TOTALS["calls"] += 1
    if cost is None:
        CALL_TOTALS["cost_missing"] += 1
    else:
        CALL_TOTALS["cost"] += cost


def available_providers():
    pin = os.environ.get("ANALYST_PROVIDER")
    ps = [p for p in PROVIDERS if os.environ.get(p["env"])]
    if pin:
        ps = [p for p in ps if p["name"] == pin] or ps
    return ps


def llm_configured():
    return bool(available_providers())
SKILLS_DIR = Path(__file__).resolve().parents[1] / "model" / "skills"


def _skill_catalog():
    """Read only installed recipes; request arguments never become filesystem paths."""
    import yaml

    return {skill["key"]: skill
            for path in sorted(SKILLS_DIR.glob("*.skill.yml"))
            for skill in [yaml.safe_load(path.read_text(encoding="utf-8"))]}


def _skills_text():
    """Complete discovery index; exact bodies are loaded by get_recipe on demand."""
    parts = []
    for key, skill in _skill_catalog().items():
        parts.append(f"{key}: {skill['label']}")
        parts.extend(f"{i}: {recipe['ask']}"
                     for i, recipe in enumerate(skill.get("recipes", []), 1))
    return "\n".join(parts) or "(no skills installed)"


def _get_recipe(arguments):
    """Local read-only metadata tool, with a strict fail-closed argument contract."""
    try:
        args = json.loads(arguments) if isinstance(arguments, str) else arguments
        if not isinstance(args, dict) or set(args) - {"skill", "recipe", "section"}:
            raise ValueError("expected an object with skill, optional recipe or section")
        key = args.get("skill")
        catalog = _skill_catalog()
        if not isinstance(key, str) or key not in catalog:
            raise ValueError("unknown installed skill")
        skill = catalog[key]
        data = {k: v for k, v in skill.items() if k != "recipes"}
        if "recipe" in args and "section" in args:
            raise ValueError("select either recipe or section")
        if "recipe" in args:
            number = args["recipe"]
            recipes = skill.get("recipes", [])
            if type(number) is not int or not 1 <= number <= len(recipes):
                raise ValueError("recipe must be an integer from the skill index")
            data = {k: v for k, v in data.items()
                    if k not in ("ops", "kinds", "transforms", "metrics")}
            data["recipe"] = recipes[number - 1]
        elif "section" in args:
            section = args["section"]
            if not isinstance(section, str) or section not in (
                    "ops", "kinds", "transforms", "metrics") or section not in skill:
                raise ValueError("unknown metadata section for this skill")
            data = {"key": key, "context": skill["context"], section: skill[section]}
        return {"ok": True, "data": data}
    except (ValueError, TypeError, KeyError) as error:
        return {"ok": False, "error": str(error)}


def _tool_schemas(data_source=None):
    """Keep complete argument contracts; skill bodies and catalogs load on demand."""
    descriptions = {
        "list_topics": "List topics with metrics, dims and grain. The system prompt's TOPIC "
                       "INDEX already holds this list.",
        "describe_topic": "Full topic schema, scope, definitions, dims and business context.",
        "get_field_values": "Resolve real ids/names BEFORE filtering typed names.",
        "run_semantic_query": "Read governed data using registered measures and dims.",
        "transform_result": "Chain governed analytics ops from the analytics skill; returns a NEW "
                            "result_id. Never compute them yourself. Additivity rules apply.",
        "make_chart": "Render result columns as a chart; follow the charting skill. Map: x=customer "
                      "dim, dot size=y. Heatmap: x/y=dims, value=colour. Histogram bins x, no y.",
        "make_table": "Render exact figures as a drillable, formatted table with totals; columns "
                      "optionally selects/orders columns.",
        "make_kpi_card": "Render a scalar KPI; compare_result_id optionally adds YoY delta.",
        "report_gap": "LAST RESORT after schema/transform/chart checks; follow the GAP PROTOCOL.",
        "save_view": "Save a named chart view. Confirm first.",
        "compose_dashboard": "Compose saved views into a named dashboard. Confirm first.",
        "list_workspace": "List all saved workspace objects and available templates.",
        "instantiate_template": "Stamp a template as NEW objects, never overwrite. Confirm first.",
        "update_view": "Patch an existing view/spec/query, re-query before saving; invalid updates "
                       "rejected. Null removes keys. Confirm first.",
        "update_workbook": "Reorder/add/remove views or rename a dashboard. Confirm first.",
        "delete_object": "Delete a named workspace object. DESTRUCTIVE: confirm first.",
    }
    return [{**tool, "function": {**tool["function"],
             "description": descriptions.get(tool["function"]["name"],
                                              tool["function"]["description"])}}
            for tool in (data_source if data_source is not None else T).openai_tools()] + [{
                "type": "function", "function": {
                    "name": "get_recipe",
                    "description": "Read exact local skill context and recipe/guard by 1-based "
                                   "index. Omit recipe for full skill metadata; section selects "
                                   "ops, kinds, transforms or metrics. Read before using a recipe.",
                    "parameters": {
                        "type": "object", "additionalProperties": False,
                        "properties": {
                            "skill": {"type": "string", "enum": list(_skill_catalog())},
                            "recipe": {"type": "integer", "minimum": 1},
                            "section": {"type": "string", "enum": [
                                "ops", "kinds", "transforms", "metrics"]}},
                        "required": ["skill"]}}}]


def _topic_index(topics):
    """One line per queryable topic with its metrics and dims; grid-only topics on one line."""
    lines = [f"{t['topic']} ({t.get('label') or t['topic']}): {', '.join(t['metrics'])}; "
             f"dims {', '.join(t.get('dims') or []) or 'none'}"
             for t in topics if t.get("metrics")]
    grids = [t["topic"] for t in topics if not t.get("metrics")]
    if grids:
        lines.append("grids with no metrics (no numbers to query): " + ", ".join(grids))
    return "\n".join(lines)


def _ops_index():
    """Every analytics op signature as written in the analytics skill, on one line."""
    import re

    ops = (_skill_catalog().get("analytics") or {}).get("ops") or {}
    text = " ".join(map(str, ops.values())) if isinstance(ops, dict) else str(ops)
    sigs = dict.fromkeys(f"{name}{{{params}}}"
                         for name, params in re.findall(r"\b([a-z_0-9]+)\{([^}]*)\}", text))
    return " ".join(sigs) or "(read get_recipe(skill=analytics, section=ops))"


def system_prompt(data_source=None):
    """The small model's standing instructions: the platform rules + the skill recipes.
    Stable content (cache-friendly); per-question content goes in the user turn."""
    topics = (data_source if data_source is not None else T).list_topics()
    topic_summary = _topic_index(topics)
    team_codes = _team_codes() or "none configured"
    team_args = " or ".join(f"team_id={tid} ({label})"
                            for tid, label in _team_labels().items()) or "team_id"
    return f"""AIOS Analyst: wholesale data questions via governed TOOLS. Non-negotiable rules:
1. NEVER write SQL or invent fields/joins/numbers. Use registered schema keys only; recipes
   and tools version together. The TOPIC INDEX below names every metric and dim: pick the
   topic from it, describe_topic it once for its scope rules, then query. Wholesale sales,
   margin, units and distinct customers come from sales_lines; order counts from sales_orders.
   Invoice-line basis, commission agent, allocated or unallocated sales: invoice_lines.
   An explicit revenue ask uses revenue, including a short ask such as "Revenue for June".
   Resolve its stated window and query it even when there is no earlier conversation.
2. Resolve every typed name or place (customer, product, agent, salesperson, city, state) with
   get_field_values BEFORE filtering, even when the spelling looks exact. Every filter value
   of any dim comes from get_field_values or an earlier result, never typed from the ask. A
   metric named for a subset (agent_allocated_sales, unallocated_line_sales) already applies
   that subset: add no filter for it. Once a name is resolved, EVERY query of the ask filters
   on its id: a customer list for an agent is filters {{"agent": [<id>]}}, not the whole book.
   Business units: {team_codes}; never mix them in one series unless explicitly comparing.
3. Every presented number comes from a tool result with drillable result_id. Read tool errors
   and correct calls; never fabricate numbers, including rounded approximate aggregates.
4. Artifact actions (save_view, compose_dashboard, schedule_report, create_alert) need the
   user's explicit confirmation first. Follow every recipe guard, including updates/deletes.
5. Lead plainly with the finding; state scope and the result's 'window', never guess it.
   The final answer names the finding in words with its numbers (for a ranking: the top
   names and values), even when a chart or table is also shown. Never only point to a chart.
   No dates means ALL recorded history, no hidden default. Time-bound asks require date_from/date_to.
6. Single-number asks: give the window/scope TOTAL first, then breakdowns. Consolidated asks:
   query WITHOUT group_by or sum the exact returned rows; never give only monthly/per-BU components.
7. Totals require a scalar query or adding EXACT fetched rows; otherwise show rows without a
   total. NEVER join/diff result sets by hand. transform_result yoy adds <m>_ly/_delta/_yoy_pct;
   if no transform can compute the comparison, say you cannot.
8. GAP PROTOCOL: check list_topics/describe_topic AND transforms/chart kinds first. Only if no
   registered dim/metric/transform/chart can answer, report_gap(kind,missing,question,workaround)
   ONCE; state what is missing in one honest sentence and offer the nearest answerable ask.
   YoY/decline/growth, rankings (top_n/sort/head), shares, running totals and distributions are
   answerable via transform_result. Refusing without report_gap OR reporting supported asks fails.
   Share or concentration of the top N customers is ANSWERABLE (concentration transform).
   Balances at a point in time (stock on hand, units in stock now, inventory level) have NO
   metric: a movement topic such as stock_moves sums flows inside a window and is never a
   balance. For such an ask call report_gap once, then offer the movement figure as the
   nearest ask. Never present a sum of movements as what is on hand.
   A window is never a gap: every dated topic takes date_from/date_to, with no date dim.
9. Charts ONLY via make_chart/make_table; say "the chart below". NEVER emit markdown images,
   data: URIs, chart links, HTML or vega. Derived analytics (top-N/YoY/shares/running totals/
   moving averages/ranks/bins) ONLY via transform_result, never mental arithmetic.
10. Write plain text. Never use an em dash or an en dash; write "to" for a range.

QUERY ARGUMENTS (run_semantic_query; a wrong argument costs a turn):
- Window: date_from and date_to as YYYY-MM-DD, never inside filters.
- Business unit: {team_args} only when the ask names one; omit it
  otherwise. Never filters.team.
- Monthly or weekly series: grain="month" or "week" with NO group_by returns one row per
  period. group_by takes only the topic's dims; there is no date dim to group by.
- filters: {{"<dim>": [values]}} with the exact ids get_field_values returned (agent, partner,
  product). For a city or state pass EVERY matching spelling it returned in one list
  (case and trailing-space variants are separate values).
- sort: "-<measure>" is largest first (top, biggest, most); "<measure>" is smallest first.
- A total: no group_by. Rows: a result shows at most 100 preview rows, and row_count is the
  true count. Never count preview rows. Transforms and charts read every row.
- To count rows that meet a condition (customers in a tier, above a value), apply
  transform_result {{"op":"filter_rows","col":<column>,"cmp":"==","value":<v>}} (cmp: ==, !=,
  >, >=, <, <=, contains) and report the row_count of THAT new result. abc_classify{{of}}
  adds abc_class A/B/C. add_total appends a total row: never count rows after it.
- A map needs no coordinates: group_by the customer dim, then make_chart kind="map" with
  x=the customer dim and y=the measure. The platform places each customer.
- Same window last year, YoY, decline or growth per customer: ONE query of the current window
  with group_by, then transform_result [{{"op":"yoy"}}, {{"op":"sort","by":"revenue_delta",
  "direction":"asc"}}, {{"op":"head","n":10}}]. Never query the prior year yourself: two
  results cannot be joined by hand.
- Share held by the top 1, 5 or 10 customers: query grouped by customer, then
  transform_result [{{"op":"concentration","of":"revenue"}}] ALONE on that full result (no
  sort, head or add_total before it). Report its top1/top5/top10_share_pct as given.
- TRANSFORM OPS, exact names and params (no others exist): {_ops_index()}
- Never repeat a call with the same arguments: read its error, change the call, or answer.

CHART PICKER: trend=line (few periods=bar); seasonal/two-dim intensity=heatmap;
YoY by period=yoy transform then yoy_bars; ranking=top_n then sorted/labeled ranked_bar;
parts=pie/donut <=6 slices (top_n first), over time=stacked_bar, shifting shares=stacked_pct,
hierarchy=treemap; change/contribution=waterfall (signed steps, platform adds Total);
concentration=pareto; correlation=scatter, third measure=bubble size; distribution=histogram
or bin transform then bar; stages=funnel; actual/target=bullet (y=actual,y2=target);
level/rate=combo (y=bars left,y2=line right); small multiples=facet on line/bar/area/scatter;
exact figures/many columns/lists=make_table with totals; customer geography=map. Ties: simpler.

TOPIC INDEX (topic (label): metrics; dims. describe_topic gives definitions and scope;
an ask that no metric here measures, such as stock on hand, is a gap: call report_gap once,
never a prose-only refusal):
{topic_summary}

SKILL RECIPE INDEX (get_recipe(skill,recipe) loads the exact plan, context and guard;
read the relevant recipe BEFORE acting, then adjust its [bracketed] parameters.
get_recipe(skill) loads full metadata; analytics ops and charting kinds are available
via section="ops"/"kinds". Never invent an op or arguments; read definitions on demand.
All skill context/guards remain mandatory, subordinate to the standing rules above):
{_skills_text()}

TOOL CONTEXT: exact_cache receipts replace stale tool bodies in this ask only. To read one,
call its original tool with the EXACT arguments shown: this restores the complete cached
response, without re-querying or repeating an action. Never infer missing fields or numbers
from a receipt. Loaded context, scope and guards remain mandatory in RETAINED RULES.
artifact_receipt confirms rendering: full exact
rows remain in the returned artifact, outside this prompt. Use its spec's result_id for further
tools; use query/transform rows for numbers, never infer totals from a render receipt."""


_DEAD_STATUS = {401, 402, 403}        # payment/auth: skip the provider immediately, no retry
_RETRY_STATUS = {429, 500, 502, 503}  # rate/server: retry with backoff before failing over
_MAX_ANSWER_TOKENS = 1500             # answers are short; also keeps low-credit providers usable
#: Reasoning models spend completion tokens on thought: 1500 cut glm-4.7-flash off mid-answer.
_MAX_TOKENS_BY_PROVIDER = {"openrouter": 6000}
_COOLDOWN = {}                        # provider name -> unix ts until which we skip it (in-proc)
#: Live turns left at which the model is told to stop reading and answer.
_BUDGET_WARN_TURNS = 3


#: Re-asks per ask for an empty reply or a tool call written as text.
_MAX_REPLY_RETRIES = 2
#: An identical successful read may run twice: once, then once to restore its receipt.
_MAX_SAME_READS = 2
_TOOL_MARKUP = ("<tool_call>", "<arg_key>", "<|tool", "<function=")


def _unusable_reply(content):
    """True for an empty reply or one that writes a tool call as text instead of calling it."""
    text = (content or "").strip()
    return not text or any(mark in text for mark in _TOOL_MARKUP)


def _team_labels():
    """{team_id: label} for the active tenant's teams, {} when this process cannot name them."""
    try:
        import core.odoo as _odoo
        return _odoo.active_team_names()
    except Exception:
        return {}


def _team_codes():
    """The active tenant's teams as `<label>=<id>` pairs, comma separated."""
    return ", ".join(f"{label}={tid}" for tid, label in _team_labels().items())


def _bu_filter_error():
    """The tool error for a business unit passed in filters.team instead of team_id."""
    return (f"A business unit is the team_id argument ({_team_codes()}), not filters.team. "
            "Move it to team_id, drop team from filters, and run the query again.")


def _bu_in_filters(arguments):
    """True when a query filters team by a business-unit id instead of passing team_id."""
    try:
        args = json.loads(arguments) if isinstance(arguments, str) else arguments
    except (TypeError, ValueError):
        return False
    filters = args.get("filters") if isinstance(args, dict) else None
    if not isinstance(filters, dict) or "team" not in filters or args.get("team_id") is not None:
        return False
    values = filters["team"] if isinstance(filters["team"], list) else [filters["team"]]
    bu_values = _bu_values()
    return bool(values) and all(str(v).strip().lower() in bu_values for v in values)


def _bu_values():
    """Every id and lower-cased label that names one of the active tenant's teams."""
    teams = _team_labels()
    return {str(tid) for tid in teams} | {str(label).strip().lower() for label in teams.values()}


#: Ops whose answer is a share of the WHOLE result, and ops that cut rows away first.
_WHOLE_OPS = {"concentration", "abc_classify", "share_of_total", "cum_share"}
_CUT_OPS = {"head", "top_n", "bottom_n", "filter_rows", "add_total"}
_CUT_BEFORE_WHOLE_ERROR = ("concentration, abc_classify, share_of_total and cum_share measure the "
                           "WHOLE result, so a head, top_n, bottom_n, filter_rows or add_total "
                           "before them gives a wrong share. Run them first, on the full grouped "
                           "result, and cut rows only after them.")


_DATE_FILTER_ERROR = ("A window is the date_from and date_to arguments (YYYY-MM-DD), never a "
                      "filter. Move the dates there, drop them from filters, and run it again.")


def _date_in_filters(arguments):
    """True when a query puts a date or a window inside filters."""
    import re

    try:
        args = json.loads(arguments) if isinstance(arguments, str) else arguments
        filters = args.get("filters")
    except (TypeError, ValueError, AttributeError):
        return False
    if not isinstance(filters, dict):
        return False
    for key, value in filters.items():
        values = value if isinstance(value, list) else [value]
        if ("date" in str(key).lower() or str(key).lower() in ("month", "period", "year")
                or any(re.search(r"\b(19|20)\d\d-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\b", str(v))
                       for v in values)):
            return True
    return False


_RECEIPT_ROWS = 3
_RECEIPT_ROW_BYTES = 800
_WHOLE_ON_CUT_ERROR = ("That result_id holds only part of the rows (a limit, head, top_n, "
                       "bottom_n or filter_rows cut it), so a share or tier on it is wrong. Run "
                       "the grouped query again with no limit, then transform that result_id.")
_YOY_BY_HAND_ERROR = ("This is the same query one year earlier. Never compare two results by "
                      "hand: run transform_result on result_id {result_id} with "
                      "[{{\"op\":\"yoy\"}}, {{\"op\":\"sort\",\"by\":\"<m>_delta\","
                      "\"direction\":\"asc\"}}, {{\"op\":\"head\",\"n\":10}}]. yoy adds <m>_ly, "
                      "<m>_delta and <m>_yoy_pct per row.")


def _note_field_values(name, arguments, res, field_values):
    """Remember the text values get_field_values returned for each (topic, dim)."""
    if name != "get_field_values" or not res.get("ok") or not isinstance(res.get("data"), list):
        return
    args = _parsed(arguments)
    ids = [row.get("id") for row in res["data"] if isinstance(row, dict)]
    key = (args.get("topic"), args.get("dim"))
    # Ids are kept as text too: an id the model echoes as "9959" is still a resolved value.
    field_values.setdefault(key, set()).update(str(v) for v in ids if v is not None)


def _expand_variants(arguments, field_values):
    """Add every returned spelling of a text filter value: 'BROOKLYN' also takes 'Brooklyn '."""
    args = _parsed(arguments)
    filters = args.get("filters")
    if not isinstance(filters, dict):
        return arguments
    fixed = dict(filters)
    for dim, value in filters.items():
        known = field_values.get((args.get("topic"), dim))
        values = value if isinstance(value, list) else [value]
        if not known or not all(isinstance(v, str) for v in values):
            continue
        want = {v.strip().casefold() for v in values}
        extra = sorted(k for k in known if k.strip().casefold() in want and k not in values)
        if extra:
            fixed[dim] = list(values) + extra
    if fixed == filters:
        return arguments
    return json.dumps({**args, "filters": fixed}, ensure_ascii=False)


_YOY_REASK_NOTE = ("\nCHECK: you queried the same grouping for two windows one year apart and "
                   "have not run yoy. Two results are never compared by hand. Call "
                   "transform_result on result_id {result_id} (the LATER window) with "
                   "[{{\"op\":\"yoy\"}}, {{\"op\":\"sort\",\"by\":\"<m>_delta\",\"direction\":\"asc\"}}, "
                   "{{\"op\":\"head\",\"n\":10}}], then answer from that result.")
_GAP_REASK_NOTE = ("\nCHECK: your draft says the data is not available, but report_gap was never "
                   "called. If no registered metric answers the ask, call report_gap now, once, "
                   "then answer. If a listed metric or transform does answer it, call that tool.")
_UNAVAILABLE = (r"\b(not available|unavailable|not tracked|isn't tracked|is not tracked|"
                r"no (metric|topic|data|dim|dimension|field) (for|that|to|on|which)|"
                r"(cannot|can't|can not|unable to) (answer|provide|determine|report|compute|"
                r"calculate|give|tell)|does not (track|hold|record|provide|contain|have a)|"
                r"doesn't (track|hold|record|provide|contain|have a)|not (in|part of) the "
                r"(governed|available|registered))")


_DATE_GROUP_ERROR = ("There is no date dim to group by. A window is date_from and date_to; a "
                     "monthly or weekly series is grain=\"month\" or \"week\" with no group_by.")
_WINDOW_GAP_ERROR = ("A window is never a gap: every dated topic takes date_from and date_to, and "
                     "grain gives months or weeks. Run the query with them instead.")
_TYPED_FILTER_ERROR = ("The filter value for '{dim}' was typed, not resolved. Call get_field_values "
                       "for that dim (with search) first, then filter on the exact values it returns.")
_WORDS_REASK_NOTE = ("\nCHECK: your draft does not state the finding. Write the answer in words "
                     "with the exact names and numbers from the tool results (for a ranking, the "
                     "top names and values). A chart or table alone is not an answer, and "
                     "placeholders such as [Customer 1] are never allowed.")
_DATE_WORDS = ("date", "month", "period", "year", "week", "day", "time")


def _date_group(arguments, topic_dims):
    """True when a query groups by a date-like name that is not a dim of its topic."""
    args = _parsed(arguments)
    group = args.get("group_by") or []
    group = group if isinstance(group, list) else [group]
    dims = topic_dims.get(args.get("topic")) or set()
    return any(str(g) not in dims and any(w in str(g).lower() for w in _DATE_WORDS)
               for g in group)


def _window_gap(arguments):
    """True when a gap report claims a missing date dimension or window."""
    missing = str(_parsed(arguments).get("missing") or "").strip().lower()
    return missing == "date" or any(w in missing for w in ("date dim", "date dimension", "no date", "date field",
                                      "time dimension", "date filter", "filtered by 20",
                                      "filter by year", "by date"))


def _typed_filter(arguments, field_values, entries):
    """The dim whose text filter value no earlier tool result in this ask returned, else None."""
    args = _parsed(arguments)
    filters = args.get("filters")
    if not isinstance(filters, dict):
        return None
    seen = None
    for dim, value in filters.items():
        values = value if isinstance(value, list) else [value]
        texts = [v for v in values if isinstance(v, str)]
        if not texts:
            continue
        known = field_values.get((args.get("topic"), dim)) or set()
        if all(v in known for v in texts):
            continue
        if seen is None:
            seen = " ".join(e["content"] for e in entries if e["response"].get("ok"))
        if not all(json.dumps(v, ensure_ascii=False) in seen for v in texts):
            return dim
    return None


def _answer_lacks_finding(content):
    """True when a reply carries no figure, or fills a template with placeholders."""
    import re

    text = content or ""
    return (not re.search(r"\d", text)
            or bool(re.search(r"\[(customer|amount|name|value|revenue)[^\]]*\]", text, re.I)))


def _says_unavailable(content):
    """True when a reply says the data cannot be had: the case the gap protocol covers."""
    import re

    return bool(re.search(_UNAVAILABLE, content or "", re.IGNORECASE))


def _has_op(arguments, op):
    """True when a transform_result chain contains `op`."""
    ops = _parsed(arguments).get("transforms") or []
    return any(isinstance(t, dict) and t.get("op") == op for t in ops)


def _parsed(arguments):
    """Tool arguments as a dict, or {} when they do not parse."""
    try:
        args = json.loads(arguments) if isinstance(arguments, str) else arguments
    except (TypeError, ValueError):
        return {}
    return args if isinstance(args, dict) else {}


def _note_result(name, arguments, res, cut_results, queries):
    """Record which results are cut, and each query's window, for the guards in ask()."""
    data = res.get("data") if res.get("ok") else None
    rid = data.get("result_id") if isinstance(data, dict) else None
    if not rid:
        return
    args = _parsed(arguments)
    if name == "run_semantic_query":
        limit = args.get("limit")
        if isinstance(limit, int) and isinstance(data.get("row_count"), int) \
                and data["row_count"] >= limit:
            cut_results.add(rid)
        rest = {k: v for k, v in args.items() if k not in ("date_from", "date_to", "limit", "sort")}
        queries.append((json.dumps(rest, sort_keys=True, default=str),
                        args.get("date_from"), args.get("date_to"), rid))
    elif name == "transform_result":
        ops = [str(t.get("op")) for t in args.get("transforms") or [] if isinstance(t, dict)]
        if args.get("result_id") in cut_results or any(op in _CUT_OPS for op in ops):
            cut_results.add(rid)


def _whole_on_cut(arguments, cut_results):
    """True when a whole-result share op runs on a result that a limit or cut made partial."""
    args = _parsed(arguments)
    ops = [str(t.get("op")) for t in args.get("transforms") or [] if isinstance(t, dict)]
    return args.get("result_id") in cut_results and bool(ops) and ops[0] in _WHOLE_OPS


def _prior_year_of(arguments, queries, years=-1):
    """The result_id of an earlier query that this one repeats exactly `years` years off, else None.

    years=-1 finds an earlier query one year later than this one; years=1 one year earlier.
    """
    args = _parsed(arguments)
    lo, hi = args.get("date_from"), args.get("date_to")
    if not (isinstance(lo, str) and isinstance(hi, str) and args.get("group_by")):
        return None
    rest = json.dumps({k: v for k, v in args.items()
                       if k not in ("date_from", "date_to", "limit", "sort")},
                      sort_keys=True, default=str)

    def shift(day, years):
        return f"{int(day[:4]) + years:04d}{day[4:]}" if len(day) >= 4 and day[:4].isdigit() else None

    for sig, qlo, qhi, rid in queries:
        if sig == rest and isinstance(qlo, str) and isinstance(qhi, str) and \
                ((shift(qlo, years), shift(qhi, years)) == (lo, hi)):
            return rid
    return None


def _cut_before_whole(arguments):
    """True when a transform chain cuts rows away before a whole-result share op."""
    try:
        args = json.loads(arguments) if isinstance(arguments, str) else arguments
        ops = [str(t.get("op")) for t in args.get("transforms") or [] if isinstance(t, dict)]
    except (TypeError, ValueError, AttributeError):
        return False
    cut = next((i for i, op in enumerate(ops) if op in _CUT_OPS), None)
    return cut is not None and any(op in _WHOLE_OPS for op in ops[cut + 1:])


def _coerce_args(name, arguments, tools):
    """Repair array parameters the model sent as a string, such as "[opex]" or "opex"."""
    try:
        args = json.loads(arguments) if isinstance(arguments, str) else arguments
    except (TypeError, ValueError):
        return arguments
    schema = next((t["function"].get("parameters") or {} for t in tools
                   if t.get("function", {}).get("name") == name), {})
    props = schema.get("properties") or {}
    if not isinstance(args, dict):
        return arguments
    fixed = dict(args)
    for key, value in args.items():
        if (props.get(key) or {}).get("type") != "array" or not isinstance(value, str):
            continue
        text = value.strip()
        try:
            parsed = json.loads(text)
        except ValueError:
            parsed = None
        if isinstance(parsed, list):
            fixed[key] = parsed
        else:
            items = [x.strip().strip("'\"") for x in text.strip("[]").split(",")]
            fixed[key] = [x for x in items if x]
    if fixed == args:
        return arguments
    return json.dumps(fixed, ensure_ascii=False)
_EMPTY_REPLY_NOTE = ("\nYour last reply was empty or wrote a tool call as text. Write the final "
                     "answer in plain words from the tool results above, or make a real tool call.")
_REPEAT_ERROR = ("repeat: this exact call already ran in this ask and its result is above. "
                 "Change the arguments, or write the final answer from the results you have.")


def _budget_note(left):
    """The working-context note that tells the model how many turns it has left."""
    if left <= 1:
        return ("\nBUDGET: this is your LAST turn and tools are off. Write the final answer now "
                "from the tool results above, with the exact numbers and names they returned.")
    return (f"\nBUDGET: {left} turns left including the final answer. Call only a tool the ask "
            "still needs (its query, transform or requested chart), then answer. Skip re-reads, "
            "schema lookups and tables nobody asked for.")


def _live_chat(messages, tools, model, tool_choice="auto"):
    """POST down the provider ladder with LATENCY-FIRST failover (a chat user is waiting):
    a rate-limited provider is SKIPPED IMMEDIATELY in favor of the next one β€” we only sleep
    when the ENTIRE ladder is limited (then short ladder-level backoffs). A LONG Retry-After
    (daily quota, e.g. Groq TPD) puts the provider in an in-process COOLDOWN; 401/402/403 skip
    the provider outright."""
    import time as _time

    import requests
    provs = available_providers()
    if not provs:
        raise RuntimeError("no LLM provider configured; set GROQ_API_KEY / CEREBRAS_API_KEY / "
                           "OPENROUTER_API_KEY in platform/.env")
    last_err = None
    # Two patience profiles: CHAT (default) fails over fast β€” a user is waiting; BATCH
    # (ANALYST_PATIENT=1, set by the eval gate / insight runner) waits out per-minute rate
    # windows across more ladder rounds instead of exhausting the ladder in seconds.
    patient = os.environ.get("ANALYST_PATIENT") == "1"
    round_sleeps = (5, 10, 20, 30, 45, 60) if patient else (2, 6, 12)
    for rnd in range(len(round_sleeps)):                   # ladder rounds
        saw_retryable = False
        for p in provs:
            if _COOLDOWN.get(p["name"], 0) > _time.time():
                last_err = RuntimeError(f"{p['name']}: cooling down (quota)")
                continue
            sent_model = model or os.environ.get("ANALYST_MODEL") or p["model"]
            body = {"model": sent_model, "messages": messages, "tools": tools,
                    "tool_choice": tool_choice, "temperature": 0.1,
                    "max_tokens": _MAX_TOKENS_BY_PROVIDER.get(p["name"], _MAX_ANSWER_TOKENS)}
            if tools is None:                         # an answer-only turn sends no tool list
                body.pop("tools")
                body.pop("tool_choice")
            if p["name"] == "openrouter":
                body["usage"] = {"include": True}     # OpenRouter returns usage.cost in USD
            try:
                r = requests.post(p["url"], timeout=120,
                                  headers={"Authorization": f"Bearer {os.environ[p['env']]}",
                                           "HTTP-Referer": "https://aios.local",
                                           "X-Title": "AIOS Analyst"},
                                  json=body)
                if r.status_code in _DEAD_STATUS:
                    last_err = RuntimeError(f"{p['name']}: HTTP {r.status_code}")
                    _COOLDOWN[p["name"]] = _time.time() + 300   # don't re-poke dead auth/payment
                    continue
                if r.status_code == 400:
                    # β›” WAVE 32 (W32-T50/T54) β€” A 400 FROM THIS LADDER IS NOT A TRANSPORT FACT,
                    # AND THIS FUNCTION USED TO THROW ITS EXPLANATION AWAY. Groq validates the
                    # model's tool ARGUMENTS against the tool schema server-side and answers
                    # `400 tool_use_failed` with the generation it rejected in `failed_generation`.
                    # Measured 2026-08-13: a correct refusal that omitted a `required` property
                    # arrived here, `raise_for_status()` turned it into "400 Client Error", and the
                    # caller was told `all LLM providers failed` β€” for a request the model had
                    # answered. The control flow is unchanged (still fail over); what changes is
                    # that the message NAMES the cause, because a schema this ladder sent is the
                    # one thing the operator can actually fix.
                    detail = ""
                    try:
                        e400 = (r.json() or {}).get("error") or {}
                        detail = str(e400.get("message") or "")[:300]
                        if e400.get("failed_generation"):
                            detail += f" | rejected generation: " \
                                      f"{str(e400['failed_generation'])[:300]}"
                    except Exception:
                        detail = (r.text or "")[:300]
                    last_err = RuntimeError(f"{p['name']}: HTTP 400 {detail}")
                    continue
                if r.status_code in _RETRY_STATUS:
                    last_err = RuntimeError(f"{p['name']}: HTTP {r.status_code}")
                    try:
                        wait = float(r.headers.get("retry-after") or 0)
                    except ValueError:
                        wait = 0
                    if wait > 60:                          # daily/long quota β€” cool down
                        _COOLDOWN[p["name"]] = _time.time() + wait
                    else:
                        saw_retryable = True               # NO sleep β€” next provider NOW
                    continue
                r.raise_for_status()
                payload = r.json()
                usage = dict(payload.get("usage") or {})
                usage["provider"] = p["name"]
                usage["model"] = payload.get("model") or sent_model
                return payload["choices"][0]["message"], usage
            except requests.RequestException as e:
                last_err = e
                continue                                   # network blip β€” next provider
        if not saw_retryable:
            break                                          # nothing retryable left anywhere
        _time.sleep(round_sleeps[rnd])                     # whole ladder limited β€” pause a round
    raise RuntimeError(f"all LLM providers failed (last: {last_err})")


#: Wave 15 R2 β€” what a restricted account is told instead of an answer.
ANALYST_DENIED = ("The Analyst is not available on your account. It answers from the full "
                  "governed model, which is wider than what your account is permitted to see.")


def may_ask(user):
    """β›” R2 β€” THE AI WALL, AND IT IS DELIBERATELY BLUNT.

    Owner, verbatim: *"If the AI is triggered by a user, the AI ITSELF should not be able to see
    the data."* Today the Analyst's tools run UNSCOPED β€” `harness/tools.run_semantic_query` takes
    no subject and no filter, so every question it answers is answered over the whole tenant.
    A restricted account asking "what were our top customers?" would therefore receive, in prose,
    precisely the rows the grid's permanent filter exists to withhold. Prose is not a lesser leak
    than a table; it is a harder one to notice.

    So the wall is REFUSAL, not narrowing: an account with ANY declared restriction β€” or any
    non-admin on a migrated record β€” does not reach the model at all. An AI that never runs
    cannot leak what it never read. Fail-closed on an unreadable record for the same reason.

    β­’ NAMED DEBT, owner-mandated (R2, doc Β§Debt, log 2026-08-02). The RIGHT answer is to thread
    the subject's permanent filter into every semantic query the Analyst runs β€” `filter_sql`
    already compiles that tree to SQL, so the shape exists; what does not exist is a per-subject
    query path through `harness/semantic.py`, which takes `team_id` and nothing else. Until that
    lands this refusal is the whole enforcement, and it must NOT be relaxed into "narrow the
    prompt" or "tell the model what it may not say" β€” a prompt is not a permission boundary.
    """
    import core.perms as perms
    import core.perm_scope as perm_scope

    if not isinstance(user, dict):
        return False                       # no identity resolved -> no Analyst
    if perms.is_admin(user):
        return True
    if perm_scope.is_migrated(user):
        # Migrated and not an admin: the account is governed by a wall the Analyst cannot honour.
        return False
    # Legacy record: restricted the old way is still restricted.
    return (perms.allowed_modules(user) is None
            and perms.scope_team_id(user) is None
            and not perms.scope_agent(user))


_PREVIEW_NOTE = ("rows holds only the first {shown} of {total} rows. Never count, rank or total "
                 "from it. Count rows with transform_result filter_rows and read its row_count; "
                 "find the largest or smallest with sort{{by,direction}} then head{{n}}; get "
                 "shares and totals from a transform or a query with no group_by.")


def _tool_content(name, response, tool_call_id, metadata, artifact_index=None):
    """Lossless JSON and receipts for retained renders.

    Working-context retrieval is owned by _AskContext, never an earlier message pointer.
    Rendering keeps the full artifact in ask's return;
    replaying its rows into the model would duplicate query data (or expand a 100-row query
    preview into thousands of rows). Errors, warnings, exact numbers and query scope stay intact.
    """
    def serialize(value):
        return json.dumps(value, default=str, ensure_ascii=False, separators=(",", ":"))

    data = response.get("data") if isinstance(response, dict) else None
    if (name in ("run_semantic_query", "transform_result") and isinstance(data, dict)
            and isinstance(data.get("rows"), list)
            and isinstance(data.get("row_count"), int) and data["row_count"] > len(data["rows"])):
        # A preview read as the whole result gave wrong counts and totals: label it in place.
        response = {**response, "data": {**data, "preview": _PREVIEW_NOTE.format(
            shown=len(data["rows"]), total=data["row_count"])}}
    content = serialize(response)
    if artifact_index is not None and name in ("make_chart", "make_table"):
        data = response["data"]
        kind = "chart" if name == "make_chart" else "table"
        spec = data.get(kind)
        if isinstance(spec, dict) and isinstance(spec.get("rows"), list):
            # Keep every other spec/envelope field, including notes and warnings. The exact
            # original data object has already been retained in artifacts before this call.
            receipt = {"artifact_index": artifact_index, "result_id": spec.get("result_id"),
                       "row_count": len(spec["rows"]),
                       "note": "Full exact rows retained in the returned rendered artifact; "
                               "this receipt is not a numeric total."}
            content = serialize({**response, "data": {
                **data, kind: {k: v for k, v in spec.items() if k != "rows"},
                "artifact_receipt": receipt}})
    return content


class _AskContext:
    """Per-ask exact read cache; only whole bodies leave the working conversation.

    Discovery is not an append-only prompt. Keep the current topic schema, newly requested
    metadata body and newest data response, plus every loaded rule. Older bodies remain
    retrievable by their original tool/arguments. No process-global or cross-user cache.
    The byte ceiling bounds requests even without a tokenizer; it is set per provider by
    request_budget(), below each provider's measured request limit. Oversize protected material
    stops explicitly rather than being truncated. Artifacts/results are never row-capped.
    """
    _READS = frozenset(("list_topics", "describe_topic", "get_recipe", "get_field_values",
                       "run_semantic_query", "transform_result"))
    _METADATA = frozenset(("list_topics", "describe_topic", "get_recipe"))
    # Corpus: initial prompt/tools ~3.2k tokens; schema ~1.8k. Groq's observed 8k
    # request limit counts input, not max_tokens. Leave room for exact ops/schema together.
    # The default only. ask() passes the provider's ceiling from request_budget().
    MAX_REQUEST_BYTES = DEFAULT_REQUEST_BYTES

    def __init__(self, messages, tools, max_request_bytes=None, data_source=None):
        self.messages, self.tools = messages, tools
        self.data_source = data_source if data_source is not None else T
        if max_request_bytes:
            self.MAX_REQUEST_BYTES = max_request_bytes
        self.cache, self.entries, self.rules, self.results = {}, [], {}, {}
        self.current_topic = None

    @staticmethod
    def _json(value):
        return json.dumps(value, default=str, ensure_ascii=False, separators=(",", ":"))

    @classmethod
    def _key(cls, name, args):
        try:
            parsed = json.loads(args) if isinstance(args, str) else args
            return name, json.dumps(parsed, sort_keys=True, ensure_ascii=False,
                                    separators=(",", ":"))
        except (TypeError, ValueError):
            return name, cls._json(args)

    @staticmethod
    def _rules(value):
        """Exact rule fields at every depth, including metric/field and recipe cautions."""
        if isinstance(value, dict):
            out = {}
            for key, item in value.items():
                if key in ("context", "ai_context", "scope", "guard", "warning", "note"):
                    out[key] = item
                else:
                    nested = _AskContext._rules(item)
                    if nested:
                        out[key] = nested
            return out
        if isinstance(value, list):
            return {str(i): rules for i, item in enumerate(value)
                    if (rules := _AskContext._rules(item))}
        return {}

    def dispatch(self, name, args):
        from copy import deepcopy

        key = self._key(name, args)
        if name in self._READS and key in self.cache:
            return deepcopy(self.cache[key])
        res = (_get_recipe(args) if name == "get_recipe"
               else self.data_source.dispatch(name, args))
        if name in self._READS and res.get("ok"):
            self.cache[key] = deepcopy(res)
        return res

    def append(self, name, args, response, tool_call_id, artifact_index):
        from copy import deepcopy

        key = self._key(name, args)
        content = _tool_content(name, response, tool_call_id, {}, artifact_index)
        message = {"role": "tool", "tool_call_id": tool_call_id, "content": content}
        self.messages.append(message)
        entry = {"tool": name, "args": args, "response": deepcopy(response),
                 "message": message, "content": content, "key": key, "shown": False}
        self.entries.append(entry)
        if response.get("ok"):
            if name in self._METADATA:
                rules = self._rules(response)
                if rules:
                    self.rules[key] = rules
            data = response.get("data")
            if isinstance(data, dict) and data.get("result_id") in self.data_source._RESULTS:
                rid = data["result_id"]
                self.results[rid] = deepcopy(self.data_source._RESULTS[rid])
            if name in ("describe_topic", "run_semantic_query"):
                parsed = json.loads(args) if isinstance(args, str) else args
                self.current_topic = parsed.get("topic")

    def _receipt(self, entry):
        receipt = {"ok": True, "exact_cache": {
            "tool": entry["tool"], "arguments": json.loads(entry["key"][1])}}
        data = entry["response"].get("data")
        if isinstance(data, dict):
            # Scope/warnings and result identity survive; receipts never assert totals.
            receipt.update({k: v for k, v in data.items()
                            if k in ("result_id", "row_count", "window", "warning", "note")})
            rows = data.get("rows")
            # A small result keeps its exact rows, so a later turn never loses an earlier figure.
            if (isinstance(rows, list) and len(rows) <= _RECEIPT_ROWS
                    and data.get("row_count", len(rows)) == len(rows)
                    and len(self._json(rows)) <= _RECEIPT_ROW_BYTES):
                receipt["rows"] = rows
        return self._json(receipt)

    def working_messages(self):
        schema = next((e for e in reversed(self.entries)
                       if e["tool"] == "describe_topic" and e["response"].get("ok")
                       and e["response"]["data"].get("topic") == self.current_topic), None)
        metadata = next((e for e in reversed(self.entries)
                         if e["tool"] in self._METADATA - {"describe_topic"}
                         and e["response"].get("ok")), None)
        if metadata is not None and metadata["shown"]:
            metadata = None
        data = next((e for e in reversed(self.entries)
                     if e["tool"] in self._READS - self._METADATA
                     and e["response"].get("ok")), None)
        keep = {id(e) for e in (schema, metadata, data) if e is not None}
        for entry in self.entries:
            if entry["tool"] in self._READS and entry["response"].get("ok"):
                entry["message"]["content"] = (entry["content"] if id(entry) in keep
                                                 else self._receipt(entry))
        working = [dict(m) for m in self.messages]
        retained = [{"tool": k[0], "arguments": json.loads(k[1]), "rules": v}
                    for k, v in self.rules.items()
                    if not any(id(e) in keep and e["key"] == k for e in self.entries)]
        if retained:
            # Add to the existing system message: no tool-role adjacency is disturbed.
            working[0]["content"] += "\nRETAINED RULES (exact, still mandatory):\n" + self._json(retained)

        def fits():
            return len(self._json({"messages": working, "tools": self.tools}).encode("utf-8")) \
                <= self.MAX_REQUEST_BYTES

        if not fits():
            raise ValueError("complete current schema, result, rules or history exceed the "
                             "working-context budget; no content was truncated")
        for entry in self.entries:
            if any(m.get("tool_call_id") == entry["message"]["tool_call_id"]
                   and m.get("content") == entry["content"] for m in working):
                entry["shown"] = True
        return working

    def retained(self):
        return {"tool_results": [{k: e[k] for k in ("tool", "args", "response")}
                                 for e in self.entries], "results": self.results}


def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=None,
        telemetry_kind="analyst", user=None, data_source=None):
    """Run one Analyst turn. Returns {answer, artifacts, tool_trace, iterations, exhausted,
    usage}. chat_fn(messages, tools, model) -> (assistant_message_dict, usage_dict).

    `user` is the SUBJECT asking. Passing it engages the R2 wall (`may_ask`); omitting it keeps
    the unscoped behaviour that `harness/evals.py` and `harness/routines.py` rely on β€” those run
    as the SYSTEM, not on behalf of a person, and gating them on a user record they do not have
    would break the eval ladder to no security benefit. Every call that IS on behalf of somebody
    passes it, and `app.py`'s chat entry point does.
    """
    if user is not None and not may_ask(user):
        return {"answer": ANALYST_DENIED, "artifacts": [], "tool_trace": [],
                "iterations": 0, "exhausted": False, "denied": True,
                "usage": {"prompt_tokens": 0, "completion_tokens": 0}}
    if max_iters is None:
        max_iters = iter_budget()
    chat = chat_fn or _live_chat
    backend = data_source if data_source is not None else T
    tools = _tool_schemas(data_source)
    messages = [{"role": "system", "content": system_prompt(data_source)}]
    messages += list(history or [])
    # The model has no clock: anchor relative windows ("last week", "this month") to today.
    # Lives in the USER turn so the system prompt stays byte-stable (prompt-cache friendly).
    import datetime as _dt
    today = backend.today if data_source is not None else _dt.date.today().isoformat()
    messages.append({"role": "user", "content": f"(today is {today})\n{question}"})
    trace, artifacts, usage_total = [], [], {"prompt_tokens": 0, "completion_tokens": 0}
    # The live ladder's first provider sets the ceiling. An injected chat_fn has no provider.
    provider = (available_providers() or [{}])[0].get("name") if chat is _live_chat else None
    context = _AskContext(messages, tools, request_budget(provider), data_source)
    calls, failed_calls, retries = {}, set(), 0
    cut_results, queries, field_values = set(), [], {}
    yoy_pending, yoy_done, reasked = set(), False, set()
    try:
        topic_dims = {t["topic"]: set(t.get("dims") or []) for t in backend.list_topics()}
    except Exception:                                      # noqa: BLE001 - guard only
        topic_dims = {}

    for i in range(max_iters):
        try:
            working = context.working_messages()
        except ValueError:
            return {"answer": "(stopped: complete required context exceeds the working-context "
                              "budget; narrow the question or history; no data was truncated)",
                    "artifacts": artifacts, "tool_trace": trace, "iterations": i,
                    "exhausted": True, "context_exhausted": True, "usage": usage_total,
                    **context.retained()}
        left = max_iters - i
        final_turn = chat is _live_chat and left == 1 and bool(trace)
        if chat is _live_chat and left <= _BUDGET_WARN_TURNS and trace:
            # Working copy only: the stored system message stays byte-stable.
            working[0] = dict(working[0], content=working[0]["content"] + _budget_note(left))
        if final_turn:
            # The last turn answers from the results already read, so a long ask ends in an answer.
            msg, usage = _live_chat(working, tools, model, tool_choice="none")
        else:
            msg, usage = chat(working, tools, model)
        _log_call({"provider": "chat_fn", "model": model, **(usage or {})})
        for k in usage_total:
            usage_total[k] += usage.get(k, 0) or 0
        tool_calls = msg.get("tool_calls") or []
        # Free-tier models INTERMITTENTLY answer a data question without calling any tool
        # (~1 in 4 observed on gpt-oss-120b β€” the "no chart" defect). Deterministic fix: if
        # the VERY FIRST turn used no tools, redo it once with tool_choice='required'. Meta
        # questions just get a harmless schema lookup before answering.
        if i == 0 and not tool_calls and chat is _live_chat:
            msg, usage = _live_chat(working, tools, model, tool_choice="required")
            _log_call(usage)
            for k in usage_total:
                usage_total[k] += usage.get(k, 0) or 0
            tool_calls = msg.get("tool_calls") or []
        while (chat is _live_chat and retries < _MAX_REPLY_RETRIES
               and not tool_calls and _unusable_reply(msg.get("content"))):
            # An empty reply, or a tool call written as text, is a broken turn: ask again.
            retries += 1
            nudge = dict(working[0], content=working[0]["content"] + _EMPTY_REPLY_NOTE)
            msg, usage = _live_chat([nudge] + working[1:], None if final_turn else tools, model)
            _log_call(usage)
            for k in usage_total:
                usage_total[k] += usage.get(k, 0) or 0
            tool_calls = msg.get("tool_calls") or []
        if chat is _live_chat and not tool_calls and not final_turn:
            # A final answer that skipped a required step gets one corrected re-ask.
            note = None
            if yoy_pending and not yoy_done and "yoy" not in reasked:
                reasked.add("yoy")
                note = _YOY_REASK_NOTE.format(result_id=sorted(yoy_pending)[-1])
            elif ("gap" not in reasked and _says_unavailable(msg.get("content"))
                  and not any(t["tool"] == "report_gap" for t in trace)):
                reasked.add("gap")
                note = _GAP_REASK_NOTE
            elif artifacts and "words" not in reasked and _answer_lacks_finding(msg.get("content")):
                reasked.add("words")
                note = _WORDS_REASK_NOTE
            if note:
                nudge = dict(working[0], content=working[0]["content"] + note)
                msg, usage = _live_chat([nudge] + working[1:], tools, model)
                _log_call(usage)
                for k in usage_total:
                    usage_total[k] += usage.get(k, 0) or 0
                tool_calls = msg.get("tool_calls") or []
        messages.append({"role": "assistant", "content": msg.get("content") or "",
                         **({"tool_calls": tool_calls} if tool_calls else {})})
        if not tool_calls:
            answer = (msg.get("content") or "").strip()
            if not answer:
                # A model occasionally returns NO content and NO tool calls (observed live
                # 2026-07-16: the reply bubble was simply empty and the next turn hallucinated).
                # Never surface silence β€” report the failure honestly instead.
                answer = ("(the model returned an empty answer; nothing was computed; "
                          "please rephrase or ask again)")
            import harness.telemetry as _tel
            # Wave 19 (R4): ATTRIBUTED. The token count was previously logged against nobody, so
            # "which customer is spending model budget, and who inside it?" had no answer even in
            # principle. Read defensively off `user` because this function is deliberately
            # callable WITHOUT one β€” `harness/evals.py` and `harness/routines.py` run as the
            # system, and telemetry omits both keys for them rather than inventing a subject.
            log = data_source.log if data_source is not None else _tel.log
            log(telemetry_kind, question=question[:200],
                     user=(user or {}).get("username") if isinstance(user, dict) else None,
                     tenant=(user or {}).get("tenant") if isinstance(user, dict) else None,
                     model=model or (available_providers() or [{}])[0].get("name", "auto"),
                     iterations=i + 1,
                     tools=[t["tool"] for t in trace],
                     tokens=usage_total["prompt_tokens"] + usage_total["completion_tokens"])
            return {"answer": answer, "artifacts": artifacts,
                    "tool_trace": trace, "iterations": i + 1, "exhausted": False,
                    "usage": usage_total, **context.retained()}
        for tc in tool_calls:
            name = tc["function"]["name"]
            args = tc["function"].get("arguments") or "{}"
            args = _coerce_args(name, args, tools)
            if name == "run_semantic_query":
                args = _expand_variants(args, field_values)
            key = _AskContext._key(name, args)
            seen = calls.get(key, 0)
            if key in failed_calls or (seen and name not in _AskContext._READS) \
                    or seen >= _MAX_SAME_READS:
                # A repeat cannot change the outcome: say so instead of running it again.
                res = {"ok": False, "error": _REPEAT_ERROR}
            elif name == "run_semantic_query" and _bu_in_filters(args):
                res = {"ok": False, "error": _bu_filter_error()}
            elif name == "run_semantic_query" and _date_in_filters(args):
                res = {"ok": False, "error": _DATE_FILTER_ERROR}
            elif name == "run_semantic_query" and _date_group(args, topic_dims):
                res = {"ok": False, "error": _DATE_GROUP_ERROR}
            elif name == "report_gap" and _window_gap(args):
                res = {"ok": False, "error": _WINDOW_GAP_ERROR}
            elif name == "run_semantic_query" and (dim := _typed_filter(args, field_values,
                                                                        context.entries)):
                res = {"ok": False, "error": _TYPED_FILTER_ERROR.format(dim=dim)}
            elif name == "transform_result" and _cut_before_whole(args):
                res = {"ok": False, "error": _CUT_BEFORE_WHOLE_ERROR}
            elif name == "transform_result" and _whole_on_cut(args, cut_results):
                res = {"ok": False, "error": _WHOLE_ON_CUT_ERROR}
            elif name == "run_semantic_query" and (prior := _prior_year_of(args, queries)):
                res = {"ok": False, "error": _YOY_BY_HAND_ERROR.format(result_id=prior)}
                yoy_pending.add(prior)
            else:
                earlier = (_prior_year_of(args, queries, years=1)
                           if name == "run_semantic_query" else None)
                res = context.dispatch(name, args)
                if earlier and res.get("ok") and isinstance(res.get("data"), dict) \
                        and res["data"].get("result_id"):
                    # The prior year ran first: point the model at yoy on THIS result.
                    rid = res["data"]["result_id"]
                    res = {**res, "data": {**res["data"],
                                           "yoy_note": _YOY_BY_HAND_ERROR.format(result_id=rid)}}
                    yoy_pending.add(rid)
                if name == "transform_result" and res.get("ok") and _has_op(args, "yoy"):
                    yoy_pending.clear()
                    yoy_done = True
                _note_result(name, args, res, cut_results, queries)
                _note_field_values(name, args, res, field_values)
            calls[key] = seen + 1
            if not res.get("ok"):
                failed_calls.add(key)
            trace.append({"tool": name, "args": args if isinstance(args, str) else json.dumps(args),
                          "ok": res["ok"], "error": res.get("error")})
            artifact_index = None
            if res["ok"] and isinstance(res["data"], dict) and (
                    "chart" in res["data"] or "kpi" in res["data"] or "table" in res["data"]
                    or "dashboard" in res["data"]):
                artifact_index = len(artifacts)
                artifacts.append(res["data"])
            context.append(name, args, res, tc.get("id", name), artifact_index)
    # budget exhausted β€” report honestly (never as success)
    return {"answer": "(stopped: tool-call budget exhausted before a final answer; "
                      "narrow the question or raise max_iters)",
            "artifacts": artifacts, "tool_trace": trace, "iterations": max_iters,
            "exhausted": True, "usage": usage_total, **context.retained()}