-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_runtime_settings.py
More file actions
3554 lines (3197 loc) · 149 KB
/
Copy pathtest_runtime_settings.py
File metadata and controls
3554 lines (3197 loc) · 149 KB
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
from __future__ import annotations
import importlib.util
import copy
import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
MODULE_PATH = ROOT / "python" / "scripts" / "runtime_settings.py"
SPEC = importlib.util.spec_from_file_location("runtime_settings", MODULE_PATH)
runtime_settings = importlib.util.module_from_spec(SPEC)
assert SPEC.loader is not None
sys.modules[SPEC.name] = runtime_settings
SPEC.loader.exec_module(runtime_settings)
SWITCH_MODULE_PATH = ROOT / "python" / "scripts" / "build_runtime_switch.py"
SWITCH_SPEC = importlib.util.spec_from_file_location("build_runtime_switch", SWITCH_MODULE_PATH)
build_runtime_switch = importlib.util.module_from_spec(SWITCH_SPEC)
assert SWITCH_SPEC.loader is not None
sys.modules[SWITCH_SPEC.name] = build_runtime_switch
SWITCH_SPEC.loader.exec_module(build_runtime_switch)
PLATFORM_CONFIG_MODULE_PATH = ROOT / "python" / "scripts" / "build_platform_config.py"
PLATFORM_CONFIG_SPEC = importlib.util.spec_from_file_location("build_platform_config", PLATFORM_CONFIG_MODULE_PATH)
build_platform_config = importlib.util.module_from_spec(PLATFORM_CONFIG_SPEC)
assert PLATFORM_CONFIG_SPEC.loader is not None
sys.modules[PLATFORM_CONFIG_SPEC.name] = build_platform_config
PLATFORM_CONFIG_SPEC.loader.exec_module(build_platform_config)
BUILD_CONFIG_MODULE_PATH = ROOT / "python" / "scripts" / "build_config.py"
BUILD_CONFIG_SPEC = importlib.util.spec_from_file_location("build_config", BUILD_CONFIG_MODULE_PATH)
build_config = importlib.util.module_from_spec(BUILD_CONFIG_SPEC)
assert BUILD_CONFIG_SPEC.loader is not None
sys.modules[BUILD_CONFIG_SPEC.name] = build_config
BUILD_CONFIG_SPEC.loader.exec_module(build_config)
class RuntimeSettingsTest(unittest.TestCase):
NOT_EVIDENCED_PROFILES = (
"tqqq_growth_income",
"soxl_soxx_trend_income",
"nasdaq_sp500_smart_dca",
"ibit_smart_dca",
"russell_top50_leader_rotation",
"hk_low_vol_dividend_quality_snapshot",
"cn_industry_etf_rotation",
"crypto_live_pool_rotation",
)
def setUp(self):
def synthetic_live_switch_config():
config = build_config.load_config()
for profile in self.NOT_EVIDENCED_PROFILES:
config["strategies"][profile].update(
{
"runtime_enabled": True,
"can_switch_live": True,
"lifecycle_stage": "runtime_enabled",
"allowed_execution_modes": ["live", "paper", "dry_run"],
"blocked_live_reason": "",
}
)
return config
self.enterContext(
patch.object(build_runtime_switch, "_load_platform_config", side_effect=synthetic_live_switch_config)
)
self.enterContext(
patch.object(runtime_settings, "load_platform_config", side_effect=synthetic_live_switch_config)
)
def test_manual_strategy_switch_workflow_stays_within_dispatch_input_limit(self):
workflow = (ROOT / ".github/workflows/manual-strategy-switch.yml").read_text(encoding="utf-8")
input_names: list[str] = []
in_inputs = False
for line in workflow.splitlines():
if line.strip() == "inputs:":
in_inputs = True
continue
if in_inputs and line.startswith("concurrency:"):
break
match = re.match(r" ([A-Za-z0-9_]+):$", line)
if in_inputs and match:
input_names.append(match.group(1))
self.assertLessEqual(len(input_names), 25)
self.assertNotIn("dca_mode", input_names)
self.assertNotIn("dca_base_investment_usd", input_names)
self.assertNotIn("income_threshold_usd", input_names)
self.assertNotIn("qqqi_income_ratio", input_names)
def test_platform_health_monitor_workflow_creates_codex_ready_issue(self):
workflow = (ROOT / ".github/workflows/platform-health-monitor.yml").read_text(encoding="utf-8")
self.assertIn("schedule:", workflow)
self.assertIn("python3 python/scripts/build_config.py --platform-health-report", workflow)
self.assertIn("python3 python/scripts/runtime_settings.py validate", workflow)
self.assertIn("platform-health-report", workflow)
self.assertIn("codex-repair-ready", workflow)
self.assertIn("Do not enable live switching", workflow)
def test_runtime_artifact_evidence_gate_is_read_only_and_uses_registry(self):
workflow = (ROOT / ".github/workflows/runtime-artifact-evidence-gate.yml").read_text(
encoding="utf-8"
)
self.assertIn("id-token: write", workflow)
self.assertIn("--runtime-artifact-evidence-registry", workflow)
self.assertIn("verify_runtime_artifact_evidence.py", workflow)
self.assertIn("qsl-artifact-evidence@", workflow)
self.assertIn("no publishing, runtime change, or order submission", workflow)
self.assertIn("Keep affected routes parked", workflow)
self.assertNotIn("gcloud storage cp", workflow)
self.assertNotIn("Manual Strategy Switch", workflow)
def test_manual_switch_platform_choices_cover_supported_platforms(self):
workflow = (ROOT / ".github/workflows/manual-strategy-switch.yml").read_text(encoding="utf-8")
platform_choices: list[str] = []
in_platform_options = False
for line in workflow.splitlines():
if line.strip() == "platform:":
in_platform_options = False
continue
if line.strip() == "options:" and not platform_choices:
in_platform_options = True
continue
if in_platform_options:
match = re.match(r"\s+- ([A-Za-z0-9_-]+)$", line)
if match:
platform_choices.append(match.group(1))
continue
if platform_choices and line.strip() and not line.strip().startswith("-"):
break
self.assertEqual(set(platform_choices), set(runtime_settings.SUPPORTED_PLATFORMS))
def test_platform_deployment_topology_matches_runtime_hosts(self):
config = build_config.load_config()
cloud_run_platforms = {"longbridge", "ibkr", "schwab", "firstrade"}
for platform in cloud_run_platforms:
deployment = config["platforms"][platform]["deployment"]
self.assertEqual(deployment["runtime_model"], "cloud_run")
self.assertEqual(deployment["settings_activation"], "cloud_run_sync_workflow")
self.assertTrue(deployment["live_configured"])
binance = config["platforms"]["binance"]["deployment"]
self.assertEqual(binance["runtime_model"], "oracle_vps_self_hosted")
self.assertEqual(binance["settings_activation"], "next_runtime_workflow_dispatch")
self.assertTrue(binance["live_configured"])
qmt = config["platforms"]["qmt"]["deployment"]
self.assertEqual(qmt["runtime_model"], "not_configured")
self.assertEqual(qmt["settings_activation"], "not_wired")
self.assertFalse(qmt["live_configured"])
def test_runtime_authority_status_does_not_grant_p0_p6_runtime_authority(self):
config = build_config.load_config()
authority = config["meta"]["runtime_authority"]
self.assertEqual(authority["schema_version"], "qsl.runtime_authority_status.v1")
self.assertEqual(authority["scope"], "p0_p6_control_plane")
self.assertEqual(authority["status"], "P0_CONTROL_PLANE_NOT_RUNTIME_WIRED")
self.assertFalse(authority["active_preauthorized_autonomy_policy"])
self.assertFalse(authority["execution_metadata_is_runtime_authority"])
self.assertEqual(authority["p1_p3_non_live_data_acquisition_authority"], "INDEPENDENT_CONTRACT_REQUIRED")
self.assertEqual(authority["p4_p6_definition"], "UNDEFINED")
invalid = copy.deepcopy(config)
invalid["meta"]["runtime_authority"]["execution_metadata_is_runtime_authority"] = True
self.assertIn(
"meta.runtime_authority.execution_metadata_is_runtime_authority must be False",
build_config.validate(invalid),
)
def test_notification_route_is_runtime_reference_only(self):
config = build_config.load_config()
sentinel = config["notifications"]["quant_sentinel"]
self.assertNotIn("telegram_chat_id", sentinel)
self.assertEqual(
sentinel["telegram_chat_id_ref"],
{
"source": "runtime_environment",
"preferred_env": "QSL_GLOBAL_TELEGRAM_CHAT_ID",
"fallback_envs": [
"GLOBAL_TELEGRAM_CHAT_ID",
"STRATEGY_PLUGIN_ALERT_TELEGRAM_CHAT_IDS",
],
},
)
self.assertEqual(
sentinel["env_aliases"]["chat_id"],
[
"QSL_GLOBAL_TELEGRAM_CHAT_ID",
"GLOBAL_TELEGRAM_CHAT_ID",
"STRATEGY_PLUGIN_ALERT_TELEGRAM_CHAT_IDS",
],
)
self.assertEqual(build_config.validate(config), [])
def test_notification_route_rejects_public_literal(self):
config = build_config.load_config()
config["notifications"]["quant_sentinel"]["telegram_chat_id"] = "test-chat-id"
self.assertIn(
"notifications.quant_sentinel must not contain telegram_chat_id; "
"use telegram_chat_id_ref",
build_config.validate(config),
)
def test_notification_route_guard_applies_to_future_plugin(self):
config = build_config.load_config()
plugin_alert = copy.deepcopy(config["notifications"]["quant_sentinel"])
config["notifications"]["future_strategy_plugin"] = plugin_alert
self.assertEqual(build_config.validate(config), [])
plugin_alert["telegram_chat_id"] = "test-chat-id"
self.assertIn(
"notifications.future_strategy_plugin must not contain telegram_chat_id; "
"use telegram_chat_id_ref",
build_config.validate(config),
)
def test_manual_switch_rejects_unsupported_sync_before_variable_write(self):
workflow = (ROOT / ".github" / "workflows" / "manual-strategy-switch.yml").read_text(encoding="utf-8")
self.assertIn('runtime_settings.py settings-activation "${PLATFORM}"', workflow)
self.assertIn("Oracle/VPS runtime activates settings on its next externally scheduled", workflow)
self.assertIn("QMT has no live runtime configuration", workflow)
self.assertLess(
workflow.index('runtime_settings.py settings-activation "${PLATFORM}"'),
workflow.index("Apply GitHub variable updates"),
)
def test_manual_switch_rejects_inventory_bypass_before_variable_write(self):
workflow = (ROOT / ".github" / "workflows" / "manual-strategy-switch.yml").read_text(encoding="utf-8")
self.assertIn("env.APPLY_SWITCH == 'true' ||", workflow)
self.assertIn(
"existing CLOUD_RUN_SERVICE_TARGETS_JSON requires "
"service_targets_mode=patch or allow_create",
workflow,
)
self.assertLess(
workflow.index(
"existing CLOUD_RUN_SERVICE_TARGETS_JSON requires "
"service_targets_mode=patch or allow_create"
),
workflow.index("Apply GitHub variable updates"),
)
def test_manual_switch_preflights_ibkr_plan_before_variable_write(self):
workflow = (ROOT / ".github" / "workflows" / "manual-strategy-switch.yml").read_text(encoding="utf-8")
self.assertIn("Preflight IBKR deployment plan", workflow)
self.assertIn("python/scripts/preflight_ibkr_switch.py", workflow)
self.assertIn("uv sync --frozen --no-dev", workflow)
self.assertLess(
workflow.index("Preflight IBKR deployment plan"),
workflow.index("Apply GitHub variable updates"),
)
def test_preflight_ibkr_switch_uses_candidate_inventory_without_printing_plan(self):
with tempfile.TemporaryDirectory(dir=ROOT) as temp_dir:
temp = Path(temp_dir)
existing_path = temp / "existing.json"
existing_path.write_text(
runtime_settings.compact_json(
{
"targets": [
{
"service": "interactive-brokers-live-service",
"ACCOUNT_GROUP": "live",
"runtime_target": {
"platform_id": "ibkr",
"strategy_profile": "soxl_soxx_trend_income",
"dry_run_only": True,
"deployment_selector": "live",
"account_selector": ["LIVE"],
"account_scope": "live",
"service_name": "interactive-brokers-live-service",
"execution_mode": "dry_run",
},
}
]
}
),
encoding="utf-8",
)
args = build_runtime_switch.build_parser().parse_args(
[
"--platform",
"ibkr",
"--target-name",
"live",
"--strategy-profile",
"tqqq_growth_income",
"--execution-mode",
"dry_run",
"--account-selector",
"LIVE",
"--service-name",
"interactive-brokers-live-service",
"--plugin-mode",
"none",
"--existing-service-targets-json-file",
str(existing_path),
]
)
target_path = temp / "target.json"
target = build_runtime_switch.build_switch_target(args)
target_path.write_text(
runtime_settings.compact_json(target),
encoding="utf-8",
)
variables_path = temp / "variables.json"
variables_path.write_text(
json.dumps(
[
{"name": "CLOUD_RUN_SERVICE_TARGETS_JSON", "value": '{"targets":[]}'},
{"name": "UNCHANGED_SETTING", "value": "preserved"},
]
),
encoding="utf-8",
)
platform_root = temp / "platform"
planner_path = platform_root / "scripts" / "build_cloud_run_env_sync_plan.py"
planner_path.parent.mkdir(parents=True)
capture_path = temp / "capture.json"
planner_path.write_text(
"""
import json
import os
from pathlib import Path
inventory = json.loads(os.environ["CLOUD_RUN_SERVICE_TARGETS_JSON"])
Path(os.environ["CAPTURE_PATH"]).write_text(
json.dumps(
{
"profile": inventory["targets"][0]["runtime_target"]["strategy_profile"],
"unchanged": os.environ.get("UNCHANGED_SETTING"),
}
),
encoding="utf-8",
)
print('{"candidate_inventory":"must-not-be-forwarded"}')
""".strip(),
encoding="utf-8",
)
python_path = platform_root / ".venv" / "bin" / "python"
python_path.parent.mkdir(parents=True)
python_path.symlink_to(sys.executable)
result = subprocess.run(
[
sys.executable,
str(ROOT / "python" / "scripts" / "preflight_ibkr_switch.py"),
"--target-file",
str(target_path),
"--platform-root",
str(platform_root),
"--repository-variables-file",
str(variables_path),
],
capture_output=True,
text=True,
env={**os.environ, "CAPTURE_PATH": str(capture_path)},
check=False,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, "IBKR deployment plan preflight passed.\n")
self.assertNotIn("candidate_inventory", result.stdout + result.stderr)
self.assertEqual(
json.loads(capture_path.read_text(encoding="utf-8")),
{"profile": "tqqq_growth_income", "unchanged": "preserved"},
)
def test_settings_activation_comes_from_platform_config(self):
self.assertEqual(
runtime_settings.platform_settings_activation("binance"),
"next_runtime_workflow_dispatch",
)
self.assertEqual(runtime_settings.platform_settings_activation("qmt"), "not_wired")
def test_manual_switch_reads_ibkr_targets_from_selected_environment_scope(self):
workflow = (ROOT / ".github/workflows/manual-strategy-switch.yml").read_text(encoding="utf-8")
assert (
'if [ "${PLATFORM}" = "ibkr" ] && [ "${VARIABLE_SCOPE}" = "environment" ]; then'
in workflow
)
assert 'target_environment="${GITHUB_ENVIRONMENT_NAME:-${TARGET_NAME}}"' in workflow
assert 'command.extend(["--env", environment])' in workflow
assert 'handle.write("{}")' in workflow
assert 'contains(fromJSON(\'["longbridge","ibkr","schwab","firstrade"]\'), env.PLATFORM)' in workflow
assert 'if [ -f "${output_file}" ]; then' in workflow
def test_live_candidate_queue_lists_profiles_needing_promotion_review(self):
catalog = [
{
"profile": "ready_next",
"label_zh": "候选",
"domain": "cn_equity",
"lifecycle_stage": "live_candidate",
"can_switch_live": False,
"allowed_execution_modes": ["paper", "dry_run"],
"blocked_live_reason": "live_candidate_requires_evidence_package",
},
{
"profile": "shadow_next",
"label": "Shadow",
"domain": "crypto",
"lifecycle_stage": "shadow_candidate",
"can_switch_live": False,
"blocked_live_reason": "shadow_candidate_requires_evidence_package",
},
{
"profile": "live_now",
"domain": "us_equity",
"lifecycle_stage": "runtime_enabled",
"can_switch_live": True,
},
]
queue = build_config.build_live_candidate_queue(catalog)
self.assertEqual([item["profile"] for item in queue], ["ready_next", "shadow_next"])
self.assertEqual(queue[0]["recommended_action"], "verify_preauthorized_policy_and_evidence")
self.assertEqual(queue[0]["label"], "候选")
self.assertTrue(queue[0]["operating_policy_required"])
self.assertEqual(queue[0]["operating_policy_status"], "UNVERIFIED")
self.assertEqual(queue[1]["recommended_action"], "collect_shadow_evidence")
def test_live_candidate_queue_cli_outputs_json_only(self):
with (
patch.object(sys, "argv", ["build_config.py", "--live-candidate-queue"]),
patch.object(build_config, "load_config", return_value={"platforms": {}, "strategies": {}}),
patch.object(build_config, "validate", return_value=[]),
patch.object(build_config, "build_live_candidate_queue", return_value=[{"profile": "candidate"}]),
patch("builtins.print") as printed,
):
self.assertEqual(build_config.main(), 0)
printed.assert_called_once()
self.assertEqual(json.loads(printed.call_args.args[0]), [{"profile": "candidate"}])
def test_strategy_automation_registry_classifies_lanes(self):
registry = build_config.build_strategy_automation_registry(
{
"strategies": {
"live": {
"label": "Live",
"domain": "us_equity",
"runtime_enabled": True,
"lifecycle_stage": "runtime_enabled",
"can_switch_live": True,
"features": {"option_overlay": True},
},
"candidate": {
"label": "Candidate",
"domain": "cn_equity",
"runtime_enabled": False,
"lifecycle_stage": "live_candidate",
"can_switch_live": False,
"features": {},
},
"shadow": {
"label": "Shadow",
"domain": "us_equity",
"runtime_enabled": False,
"lifecycle_stage": "shadow_candidate",
"can_switch_live": False,
"features": {},
},
"research": {
"label": "Research",
"domain": "crypto",
"runtime_enabled": False,
"lifecycle_stage": "research_backtest_only",
"can_switch_live": False,
"features": {},
},
},
}
)
profiles = {item["profile"]: item for item in registry["profiles"]}
lanes = {profile: item["automation_lane"] for profile, item in profiles.items()}
self.assertEqual(registry["schema_version"], "strategy_automation_registry.v2")
self.assertEqual(lanes["live"], "live_equivalent_optimization")
self.assertEqual(lanes["candidate"], "promotion_review")
self.assertEqual(profiles["candidate"]["triggers"], ["evidence_package_ready"])
self.assertTrue(profiles["candidate"]["operating_policy_required"])
self.assertEqual(profiles["candidate"]["operating_policy_status"], "UNVERIFIED")
self.assertEqual(
profiles["candidate"]["evidence_required"],
["live_candidate_evidence", "preauthorized_operating_policy_receipt"],
)
self.assertFalse(profiles["candidate"]["can_switch_live"])
self.assertEqual(lanes["shadow"], "shadow_research")
self.assertEqual(
profiles["shadow"]["evidence_required"],
["shadow_metrics", "preauthorized_operating_policy_receipt"],
)
self.assertTrue(profiles["shadow"]["operating_policy_required"])
self.assertFalse(profiles["shadow"]["can_switch_live"])
self.assertEqual(lanes["research"], "research_backlog")
self.assertTrue(profiles["live"]["position_control_sensitive"])
def test_automation_registry_cli_outputs_json(self):
with (
patch.object(sys, "argv", ["build_config.py", "--automation-registry"]),
patch.object(build_config, "load_config", return_value={"strategies": {}}),
patch("builtins.print") as printed,
):
self.assertEqual(build_config.main(), 0)
printed.assert_called_once()
self.assertEqual(json.loads(printed.call_args.args[0])["schema_version"], "strategy_automation_registry.v2")
def test_platform_health_report_summarizes_current_config(self):
config = json.loads((ROOT / "platform-config.json").read_text(encoding="utf-8"))
catalog = json.loads(
(ROOT / "web" / "strategy-switch-console" / "strategy-profiles.example.json").read_text(encoding="utf-8")
)
report = build_config.build_platform_health_report(config, catalog)
self.assertEqual(report["status"], "attention_required")
self.assertEqual(report["schema_version"], "platform_health_report.v1")
self.assertEqual(report["summary"]["runtime_enabled_switchable_count"], 0)
self.assertIn("codex_repair_context", report)
self.assertIn("automation_registry", report)
self.assertIn("automation_lane_counts", report["summary"])
self.assertEqual(report["summary"]["dry_run_uncovered_strategy_count"], 0)
self.assertEqual(report["summary"]["dry_run_covered_strategy_count"], 26)
self.assertGreater(report["summary"]["dry_run_route_count"], 0)
self.assertEqual(
report["summary"]["declared_dry_run_route_count"],
report["summary"]["buildable_dry_run_route_count"],
)
self.assertEqual(report["summary"]["artifact_blocked_strategy_count"], 0)
coverage_check = next(
item for item in report["checks"] if item["name"] == "strategy_platform_dry_run_coverage"
)
self.assertEqual(coverage_check["status"], "pass")
self.assertEqual(report["recommended_action"], "review_candidates")
self.assertFalse(report["codex_repair_context"]["safe_to_attempt"])
self.assertIn("python3 python/scripts/build_config.py --check", report["codex_repair_context"]["suggested_commands"])
def test_strategy_platform_dry_run_coverage_fails_closed_when_domain_route_is_removed(self):
config = build_config.load_config()
config["platforms"]["qmt"]["supported_domains"] = []
coverage = build_config.build_strategy_platform_dry_run_coverage(config)
report = build_config.build_platform_health_report(config, [])
self.assertIn("cn_industry_etf_rotation", coverage["uncovered_profiles"])
coverage_check = next(
item for item in report["checks"] if item["name"] == "strategy_platform_dry_run_coverage"
)
self.assertEqual(coverage_check["status"], "fail")
def test_strategy_platform_dry_run_coverage_uses_verified_snapshot_artifact(self):
coverage = build_config.build_strategy_platform_dry_run_coverage(build_config.load_config())
route = next(
item
for item in coverage["profiles"]
if item["profile"] == "hk_low_vol_dividend_quality_snapshot"
)
self.assertEqual(route["declared_dry_run_platforms"], ["ibkr", "longbridge"])
self.assertEqual(route["buildable_dry_run_platforms"], ["ibkr", "longbridge"])
self.assertEqual(route["blocked_reason"], "")
self.assertNotIn("hk_low_vol_dividend_quality_snapshot", coverage["artifact_blocked_profiles"])
self.assertEqual(coverage["summary"]["declared_dry_run_route_count"], 59)
self.assertEqual(coverage["summary"]["buildable_dry_run_route_count"], 59)
def test_feature_snapshot_platform_coverage_matches_runtime_injection(self):
self.assertEqual(
build_config.FEATURE_SNAPSHOT_RUNTIME_PLATFORMS,
set(build_runtime_switch.PLATFORM_FEATURE_SNAPSHOT_VARIABLES),
)
def test_platform_health_report_cli_outputs_json(self):
report = {
"schema_version": "platform_health_report.v1",
"status": "attention_required",
"recommended_action": "review_candidates",
}
with (
patch.object(sys, "argv", ["build_config.py", "--platform-health-report"]),
patch.object(build_config, "load_config", return_value={"platforms": {}, "strategies": {}}),
patch.object(build_config, "build_platform_health_report", return_value=report),
patch("builtins.print") as printed,
):
self.assertEqual(build_config.main(), 0)
printed.assert_called_once()
self.assertEqual(json.loads(printed.call_args.args[0])["schema_version"], "platform_health_report.v1")
def test_runtime_target_rejects_live_switch_for_non_runtime_profile(self):
_, target = self.load_target("examples/targets/qmt/cn_combo.example.json")
target["runtime_target"]["execution_mode"] = "live"
target["runtime_target"]["dry_run_only"] = False
errors = runtime_settings.validate_target(target)
self.assertIn(
"runtime_target.strategy_profile cn_equity_combo is not runtime_enabled",
errors,
)
self.assertIn(
"runtime_target.strategy_profile cn_equity_combo cannot switch live",
errors,
)
def test_runtime_target_never_infers_live_permission_from_catalog_status(self):
config = build_config.load_config()
config["strategies"]["global_etf_rotation"] = {
**config["strategies"]["global_etf_rotation"],
"runtime_enabled": True,
"lifecycle_stage": "runtime_enabled",
}
config["strategies"]["global_etf_rotation"].pop("can_switch_live", None)
config["strategies"]["global_etf_rotation"].pop(
"allowed_execution_modes", None
)
errors = []
with patch.object(
runtime_settings, "load_platform_config", return_value=config
):
runtime_settings.validate_runtime_target_strategy_policy(
{
"platform_id": "ibkr",
"strategy_profile": "global_etf_rotation",
"execution_mode": "live",
},
errors,
)
self.assertIn(
"runtime_target.strategy_profile global_etf_rotation cannot switch live",
errors,
)
self.assertIn(
"runtime_target.strategy_profile global_etf_rotation must explicitly allow live execution",
errors,
)
def load_target(self, relative_path: str):
path = ROOT / relative_path
return path, runtime_settings.load_target(path)
def test_all_targets_validate(self):
for path in sorted((ROOT / "examples" / "targets").glob("*/*.json")):
with self.subTest(path=path):
self.assertEqual(runtime_settings.validate_target(runtime_settings.load_target(path), path), [])
def test_runtime_target_json_is_canonical_source_for_strategy_profile(self):
_, target = self.load_target("examples/targets/schwab/live.example.json")
assignments = {item.name: item.value for item in runtime_settings.build_assignments(target)}
self.assertIn("RUNTIME_TARGET_JSON", assignments)
self.assertEqual(assignments["STRATEGY_PROFILE"], target["runtime_target"]["strategy_profile"])
self.assertNotIn("STRATEGY_PROFILE", target["extra_variables"])
def test_runtime_target_accepts_complete_optional_strategy_release_identity(self):
_, target = self.load_target("examples/targets/schwab/live.example.json")
digest = "a" * 64
target["runtime_target"]["strategy_release"] = {
"release_id": "soxl-p2-v3.20260824",
"manifest_sha256": digest,
"strategy_revision": "2e3bb51",
"config_sha256": digest,
"risk_policy_sha256": digest,
"evidence_sha256": digest,
"plugin_bundle_sha256": digest,
"effective_session": "2026-08-25",
}
self.assertEqual(runtime_settings.validate_target(target), [])
def test_runtime_target_rejects_partial_or_invalid_strategy_release_identity(self):
_, target = self.load_target("examples/targets/schwab/live.example.json")
target["runtime_target"]["strategy_release"] = {
"release_id": "not valid",
"manifest_sha256": "not-a-digest",
}
errors = runtime_settings.validate_target(target)
self.assertIn("runtime_target.strategy_release.release_id has invalid characters", errors)
self.assertIn(
"runtime_target.strategy_release.manifest_sha256 must be a SHA-256 digest",
errors,
)
self.assertIn("runtime_target.strategy_release.strategy_revision is required", errors)
def test_live_continuity_keeps_an_existing_baseline_separate_from_candidate_gate(self):
_, target = self.load_target("examples/targets/schwab/live.example.json")
runtime_target = target["runtime_target"]
runtime_target.update(
{
"strategy_profile": "soxl_soxx_trend_income",
"deployment_selector": "default",
"account_selector": ["default"],
"account_scope": "default",
"service_name": "charles-schwab-quant-service",
}
)
runtime_target["live_continuity"] = {
"state": "ACTIVE_LKG",
"baseline_kind": "legacy_authorized",
"baseline_id": "soxl-schwab-lkg-20260830",
"baseline_target_sha256": runtime_settings.runtime_target_fingerprint(runtime_target),
"captured_at": "2026-08-30",
}
self.assertEqual(runtime_settings.validate_target(target), [])
def test_confirmed_legacy_ibkr_profiles_are_continuity_eligible(self):
"""Candidate policy must not strand an explicitly frozen IBKR incumbent."""
parser = build_runtime_switch.build_parser()
for profile in (
"tqqq_growth_income",
"global_etf_rotation",
"russell_top50_leader_rotation",
):
with self.subTest(profile=profile):
target = build_runtime_switch.build_switch_target(
parser.parse_args(
[
"--platform",
"ibkr",
"--target-name",
f"legacy-{profile}",
"--strategy-profile",
profile,
"--execution-mode",
"live",
"--live-continuity-state",
"RECONCILE_ONLY",
"--live-continuity-baseline-id",
f"ibkr-{profile}-legacy-20260830",
"--live-continuity-captured-at",
"2026-08-30",
]
)
)
strategy = build_config.load_config()["strategies"][profile]
self.assertFalse(strategy["runtime_enabled"])
self.assertFalse(strategy["can_switch_live"])
self.assertEqual(runtime_settings.validate_target(target), [])
def test_live_continuity_rejects_baseline_drift(self):
_, target = self.load_target("examples/targets/schwab/live.example.json")
runtime_target = target["runtime_target"]
runtime_target.update(
{
"strategy_profile": "soxl_soxx_trend_income",
"live_continuity": {
"state": "ACTIVE_LKG",
"baseline_kind": "legacy_authorized",
"baseline_id": "soxl-schwab-lkg-20260830",
"baseline_target_sha256": "a" * 64,
"captured_at": "2026-08-30",
},
}
)
errors = runtime_settings.validate_target(target)
self.assertIn(
"runtime_target.live_continuity.baseline_target_sha256 does not match the runtime target",
errors,
)
def test_example_targets_have_matching_plugin_mount(self):
for relative_path in (
"examples/targets/schwab/live.example.json",
"examples/targets/longbridge/sg.example.json",
"examples/targets/firstrade/live.example.json",
):
with self.subTest(relative_path=relative_path):
_, target = self.load_target(relative_path)
profile = target["runtime_target"]["strategy_profile"]
self.assertTrue(
any(mount["strategy"] == profile and mount["enabled"] is True for mount in target["plugin_mounts"])
)
def test_plugin_mount_schema_version_is_rendered_for_platform_parser(self):
_, target = self.load_target("examples/targets/schwab/live.example.json")
assignments = {item.name: item.value for item in runtime_settings.build_assignments(target)}
self.assertIn(
'"expected_schema_version":"example_notification_plugin.v1"',
assignments["SCHWAB_STRATEGY_PLUGIN_MOUNTS_JSON"],
)
def test_published_legacy_strategy_artifacts_are_not_auto_mounted(self):
strategy_profiles = {
item["profile"]
for item in json.loads(
(ROOT / "web/strategy-switch-console/strategy-profiles.example.json").read_text(encoding="utf-8")
)
}
published_strategy_artifact_profiles = {
"tqqq_growth_income",
"soxl_soxx_trend_income",
}
self.assertLessEqual(published_strategy_artifact_profiles, strategy_profiles)
for profile in published_strategy_artifact_profiles:
with self.subTest(profile=profile):
self.assertEqual(
build_runtime_switch._auto_plugin_mounts(
profile,
"gs://qsl-runtime-logs-shared",
),
[],
)
def test_build_config_strategy_to_json_compat_includes_strategy_gate_fields(self):
strategies = {
"sample": {
"label": "样例策略",
"domain": "us_equity",
"runtime_enabled": False,
"lifecycle_stage": "beta",
"can_switch_live": False,
"allowed_execution_modes": ["paper", "dry_run"],
"blocked_live_reason": "manual-review",
"features": {},
},
}
payload = build_config.strategy_to_json_compat(strategies)
profile = payload[0]
self.assertEqual(profile["runtime_enabled"], False)
self.assertEqual(profile["lifecycle_stage"], "beta")
self.assertFalse(profile["can_switch_live"])
self.assertEqual(profile["allowed_execution_modes"], ["paper", "dry_run"])
self.assertEqual(profile["blocked_live_reason"], "manual-review")
def test_runtime_catalog_projection_is_exact_and_never_claims_observed_runtime(self):
config = build_config.load_config()
projection_path = ROOT / "web" / "strategy-switch-console" / "runtime-catalog-projection.json"
projection = json.loads(projection_path.read_text(encoding="utf-8"))
self.assertEqual(projection, build_platform_config.build_runtime_catalog_projection(config))
self.assertEqual(projection["schema_version"], "qsl.runtime_catalog_projection.v1")
self.assertEqual(projection["data_status"], "catalog_only")
self.assertFalse(projection["policy"]["catalog_is_runtime_observation"])
self.assertFalse(projection["policy"]["catalog_can_authorize_promotion_or_trading"])
self.assertFalse(projection["policy"]["historical_lifecycle_inventory_is_authoritative"])
self.assertEqual(
projection["summary"]["strategy_profile_count"],
len(config["strategies"]),
)
self.assertEqual(projection["summary"]["live_switchable_count"], 0)
self.assertEqual(
projection["source"]["content_sha256"],
build_platform_config._config_content_sha256(config),
)
def test_historical_lifecycle_inventory_is_explicitly_non_authoritative(self):
matrix = json.loads(
(ROOT / "web" / "strategy-switch-console" / "lifecycle-matrix.json").read_text(encoding="utf-8")
)
self.assertEqual(matrix["schema_version"], "qsl.historical_lifecycle_inventory.v1")
self.assertEqual(matrix["record_status"], "historical_reference_only")
self.assertEqual(matrix["superseded_by"]["catalog_gates"], "runtime-catalog-projection.json")
self.assertEqual(matrix["superseded_by"]["candidate_lifecycle"], "GET /api/control-plane")
self.assertEqual(matrix["superseded_by"]["target_execution_evidence"], "GET /api/execution-evidence")
def test_global_and_hk_global_etf_rotation_profiles_are_research_only(self):
expected = {
"lifecycle_stage": "research_active",
"runtime_enabled": False,
"can_switch_live": False,
"allowed_execution_modes": ["dry_run"],
"blocked_live_reason": "research_backtest_only_requires_evidence_package",
}
config = build_config.load_config()
profiles = {
item["profile"]: item
for item in json.loads(
(ROOT / "web/strategy-switch-console/strategy-profiles.example.json").read_text(encoding="utf-8")
)
}
for profile in ("global_etf_rotation", "hk_global_etf_tactical_rotation"):
with self.subTest(profile=profile):
self.assertEqual(
{field: config["strategies"][profile][field] for field in expected},
expected,
)
self.assertEqual({field: profiles[profile][field] for field in expected}, expected)
for execution_mode in ("live", "paper"):
args = build_runtime_switch.build_parser().parse_args(
[
"--platform",
"ibkr",
"--target-name",
"live",
"--strategy-profile",
profile,
"--execution-mode",
execution_mode,
"--plugin-mode",
"none",
]
)
with self.subTest(execution_mode=execution_mode):
with self.assertRaisesRegex(ValueError, f"does not allow {execution_mode} execution"):
build_runtime_switch.build_switch_target(args)
def test_not_evidenced_profiles_are_catalog_demoted_fail_closed(self):
expected = {
"runtime_enabled": False,
"can_switch_live": False,
"lifecycle_stage": "research_active",
"allowed_execution_modes": ["paper", "dry_run"],
"blocked_live_reason": "missing_current_promotion_evidence_and_preauthorized_autonomy_policy",
}
config = build_config.load_config()["strategies"]
generated = {
item["profile"]: item
for item in json.loads(
(ROOT / "web" / "strategy-switch-console" / "strategy-profiles.example.json").read_text(
encoding="utf-8"
)
)
}
app_source = (ROOT / "web" / "strategy-switch-console" / "app.js").read_text(encoding="utf-8")
fallback_match = re.search(
r"const defaultStrategyProfiles = window\.__DEFAULT_STRATEGY_PROFILES__ \|\| (\[.*?\n \]);",
app_source,
re.DOTALL,
)
self.assertIsNotNone(fallback_match)
fallback = {item["profile"]: item for item in json.loads(fallback_match.group(1))}
platform_by_domain = {
"us_equity": "ibkr",
"hk_equity": "ibkr",
"cn_equity": "qmt",
"crypto": "binance",
}
actual_config = build_config.load_config()
for profile in self.NOT_EVIDENCED_PROFILES:
with self.subTest(profile=profile):
for catalog in (config, generated, fallback):
self.assertEqual({field: catalog[profile][field] for field in expected}, expected)
errors = []
with patch.object(runtime_settings, "load_platform_config", return_value=actual_config):
runtime_settings.validate_runtime_target_strategy_policy(
{
"platform_id": platform_by_domain[config[profile]["domain"]],
"strategy_profile": profile,
"execution_mode": "live",
},
errors,
)
self.assertIn(f"runtime_target.strategy_profile {profile} does not allow live execution", errors)
self.assertIn(f"runtime_target.strategy_profile {profile} is not runtime_enabled", errors)
self.assertIn(f"runtime_target.strategy_profile {profile} cannot switch live", errors)
errors = []
with patch.object(runtime_settings, "load_platform_config", return_value=actual_config):
runtime_settings.validate_runtime_target_strategy_policy(
{
"platform_id": platform_by_domain[config[profile]["domain"]],
"strategy_profile": profile,
"execution_mode": "paper",
"dry_run_only": True,
},
errors,
)
self.assertEqual(errors, [])
def test_strategy_switch_console_normalizes_dry_run_and_keeps_non_live_profiles_selectable(self):
source = (ROOT / "web" / "strategy-switch-console" / "app.js").read_text(encoding="utf-8")
normalize = re.search(