-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime_commands.py
More file actions
3393 lines (3135 loc) · 126 KB
/
runtime_commands.py
File metadata and controls
3393 lines (3135 loc) · 126 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
"""CLI helpers for runtime/provider compatibility."""
from __future__ import annotations
import asyncio
import json
import logging
from collections.abc import Mapping
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
from agents.runtime.adapters.generic_edit import inspect_generic_edit_resume_artifacts
from agents.runtime.cli_profiles import (
CLI_RUNNER_PROFILES,
cli_runner_profiles_as_dicts,
detect_cli_runner_availability,
select_cli_runner_profiles,
)
from agents.runtime.compatibility import (
PROVIDER_RUNTIME_COMPATIBILITY,
RUNTIME_MODE_INFO,
provider_runtime_compatibility_as_dicts,
runtime_mode_info_as_dicts,
)
from agents.runtime.direct_api_autonomy import (
DIRECT_API_AUTONOMOUS_ENV,
DIRECT_API_AUTONOMOUS_PROVIDERS,
DirectApiAutonomousGate,
resolve_direct_api_autonomous_gate,
resolve_direct_api_autonomous_readiness,
)
from agents.runtime.fallback import (
RuntimePhase,
capabilities_for_runtime_mode,
resolve_runtime_mode_with_fallback,
)
from agents.runtime.mcp_bridge import (
CUSTOM_MCP_SERVERS_CONFIG_KEY,
EXTERNAL_MCP_CLIENT_ENV,
LOCAL_BRIDGE_SERVER,
MCP_ALLOWED_PERMISSIONS_ENV,
MCP_SERVER_CATALOG,
build_external_mcp_health_matrix,
check_external_mcp_contracts,
describe_external_mcp_server_health,
discover_external_mcp_tools,
executable_external_mcp_servers,
executable_external_mcp_tools,
external_mcp_adapter_for,
mcp_server_catalog_entry,
normalize_mcp_allowed_permissions,
normalize_mcp_input_schema,
registered_external_mcp_servers,
resolve_runtime_mcp_support,
)
from agents.runtime.subagents import (
DEFAULT_SUBAGENT_MAX_ATTEMPTS,
DEFAULT_SUBAGENT_MERGE_POLICY,
resolve_runtime_subagent_support,
)
from cli.autonomous_readiness_text import format_autonomous_readiness_requirements
from cli.provider_smoke_commands import (
PROVIDER_AUTONOMOUS_PROMOTION_REQUIRED_E2E_RUNS,
PROVIDER_AUTONOMOUS_READINESS_MAX_HISTORY_AGE_SECONDS,
PROVIDER_AUTONOMOUS_READINESS_MIN_STABLE_RUNS,
PROVIDER_AUTONOMOUS_READINESS_RECOMMENDATION_REASON_BY_SIGNAL,
PROVIDER_AUTONOMOUS_READINESS_REQUIRED_LIVE_FAULT_CASES,
PROVIDER_AUTONOMOUS_READINESS_REQUIRED_LIVE_TASK_FAMILIES,
PROVIDER_RELIABILITY_CASE_ORDER,
PROVIDER_RELIABILITY_DIRECT_API_PROVIDERS,
PROVIDER_SMOKE_HISTORY_RELATIVE_PATH,
)
from core.providers.cost_calculator import MODEL_PRICING, estimate_session_cost
DEFAULT_MCP_DIAGNOSTIC_SERVERS = tuple(MCP_SERVER_CATALOG)
DEFAULT_EXTERNAL_MCP_SMOKE_SERVERS = registered_external_mcp_servers()
logger = logging.getLogger(__name__)
CLI_RUNNER_CONTRACT_FACETS = (
"run",
"cancel",
"resume",
"artifacts",
"event_parser",
"cost_account",
)
CLI_RUNNER_WIRED_CONTRACTS = {
"codex_cli": {
"run": "wired",
"cancel": "wired",
"resume": "wired",
"artifacts": "wired",
"event_parser": "wired",
"cost_account": "wired",
},
}
CLI_RUNNER_CONTRACT_READY_STATUSES = {
"wired",
"generic_core_configurable",
"generic_jsonl_core",
}
CLI_RUNNER_GENERIC_CORE_FACETS = {
"run": "generic_core_configurable",
"cancel": "generic_core_configurable",
"resume": "missing_runner_resume",
"artifacts": "generic_core_configurable",
"event_parser": "generic_jsonl_core",
"cost_account": "generic_jsonl_core",
}
RUNTIME_PROVIDER_AUTONOMOUS_READINESS_RECOMMENDATION_REASON_BY_SIGNAL = {
**PROVIDER_AUTONOMOUS_READINESS_RECOMMENDATION_REASON_BY_SIGNAL,
"provider_history_latest_failed": "latest_provider_smoke_failed",
}
MUTATING_SUBAGENT_REQUIRED_GATES = (
"isolated_child_contexts",
"transaction_boundaries",
"conflict_aware_merge",
"parent_approved_apply_abort",
"child_artifacts",
)
MUTATING_SUBAGENT_SATISFIED_GATES = (
"isolated_child_contexts",
"child_artifacts",
)
MCP_PERMISSION_REQUIRED_GATES = (
"tool_policy_metadata",
"permission_allowlist_check",
"deny_before_execution",
"audit_artifact",
"mutating_tool_classification",
)
RUNTIME_COMPARATIVE_COST_ESTIMATE_INPUT_TOKENS = 10_000
RUNTIME_COMPARATIVE_COST_ESTIMATE_OUTPUT_TOKENS = 2_000
RUNTIME_POLICY_PHASES = (
{
"phase": "planner",
"direct_provider_mode": "blocked",
"fallback_modes": (),
"requires_full_autonomous": True,
"fallback_allowed": False,
"policy": "must_use_full_runtime",
"reason": "planner_requires_workspace_tools",
},
{
"phase": "coder",
"direct_provider_mode": "generic_edit",
"fallback_modes": ("patch_proposal", "analysis_only"),
"requires_full_autonomous": False,
"fallback_allowed": True,
"policy": "prefer_generic_edit",
"reason": "coder_can_use_generic_edit_transactions",
},
{
"phase": "qa_reviewer",
"direct_provider_mode": "analysis_only",
"fallback_modes": (),
"requires_full_autonomous": False,
"fallback_allowed": True,
"policy": "prefer_analysis_only",
"reason": "qa_review_can_run_without_mutation",
},
{
"phase": "qa_fixer",
"direct_provider_mode": "generic_edit",
"fallback_modes": ("patch_proposal", "analysis_only"),
"requires_full_autonomous": False,
"fallback_allowed": True,
"policy": "prefer_generic_edit",
"reason": "qa_fix_needs_transactional_mutations",
},
)
def _format_table(headers: list[str], rows: list[list[str]]) -> str:
"""Format a compact ASCII table."""
widths = [
max(len(str(cell)) for cell in column)
for column in zip(headers, *rows, strict=True)
]
header = " ".join(cell.ljust(width) for cell, width in zip(headers, widths))
divider = " ".join("-" * width for width in widths)
body = [
" ".join(cell.ljust(width) for cell, width in zip(row, widths)) for row in rows
]
return "\n".join([header, divider, *body])
def _format_optional_percent(value: Any) -> str:
"""Format optional percent metrics for text diagnostics."""
if isinstance(value, int) and not isinstance(value, bool):
return f"{value}%"
return "n/a"
def _runner_candidate_ids_by_mode(
runner_candidates: dict[str, Any] | None,
) -> dict[str, list[str]]:
"""Extract compact runner IDs from fallback candidate diagnostics."""
if not runner_candidates:
return {}
modes = runner_candidates.get("modes", {})
if not isinstance(modes, dict):
return {}
return {
mode: list(selection.get("selected_runner_ids", []))
for mode, selection in modes.items()
if isinstance(selection, dict)
}
def build_runtime_fallback_matrix(
*,
phase: RuntimePhase = "coding",
) -> list[dict[str, Any]]:
"""Build fail-fast and opt-in fallback diagnostics for every provider/mode."""
matrix: list[dict[str, Any]] = []
for provider_row in PROVIDER_RUNTIME_COMPATIBILITY:
for mode in RUNTIME_MODE_INFO:
fail_fast = resolve_runtime_mode_with_fallback(
provider_name=provider_row.provider,
requested_mode=mode.mode,
phase=phase,
allow_fallback=False,
)
fallback = resolve_runtime_mode_with_fallback(
provider_name=provider_row.provider,
requested_mode=mode.mode,
phase=phase,
allow_fallback=True,
)
runner_candidates = (
fallback.runner_candidates or fail_fast.runner_candidates
)
matrix.append(
{
"provider": provider_row.provider,
"phase": phase,
"requested_mode": mode.mode,
"fail_fast_selected_mode": fail_fast.selected_mode,
"fallback_selected_mode": fallback.selected_mode,
"fallback_applied": fallback.fallback_applied,
"fallback_reason": fallback.reason,
"missing_capabilities": list(fail_fast.missing_capabilities),
"compatible_fallbacks": list(fail_fast.compatible_fallbacks),
"runner_candidate_ids_by_mode": _runner_candidate_ids_by_mode(
runner_candidates,
),
"selected_mode_runner_candidates": (runner_candidates or {}).get(
"selected_mode_runner_candidates", []
),
}
)
return matrix
def build_cli_runner_contract_matrix() -> list[dict[str, Any]]:
"""Build the shared full-runtime CLI runner contract matrix."""
matrix: list[dict[str, Any]] = []
for profile in CLI_RUNNER_PROFILES:
wired_facets = CLI_RUNNER_WIRED_CONTRACTS.get(
profile.runner_id,
CLI_RUNNER_GENERIC_CORE_FACETS,
)
facets = {
facet: wired_facets.get(facet, "missing_adapter")
for facet in CLI_RUNNER_CONTRACT_FACETS
}
missing_facets = [
facet
for facet, status in facets.items()
if status not in CLI_RUNNER_CONTRACT_READY_STATUSES
]
if not missing_facets:
contract_status = "ready"
elif any(
status in CLI_RUNNER_CONTRACT_READY_STATUSES for status in facets.values()
):
contract_status = "partial"
else:
contract_status = "planned"
matrix.append(
{
"runner_id": profile.runner_id,
"display_name": profile.display_name,
"runner_status": profile.runner_status,
"contract_status": contract_status,
"required_facets": list(CLI_RUNNER_CONTRACT_FACETS),
"missing_contract_facets": missing_facets,
"facets": facets,
"adapter_required": bool(missing_facets),
"supported_runtime_modes": list(profile.supported_runtime_modes),
"artifact_contract": (
f"{profile.runner_id}_result.json, "
f"{profile.runner_id}_timeline.json"
),
}
)
return matrix
def build_mcp_bridge_plan_matrix() -> list[dict[str, Any]]:
"""Build provider/runtime MCP bridge plan diagnostics."""
matrix: list[dict[str, Any]] = []
for provider_row in PROVIDER_RUNTIME_COMPATIBILITY:
for mode in RUNTIME_MODE_INFO:
capabilities = capabilities_for_runtime_mode(
provider_row.provider,
mode.mode,
)
bridge_available = mode.mode == "generic_edit"
available_servers = (LOCAL_BRIDGE_SERVER,) if bridge_available else ()
if bridge_available:
available_servers = (
*available_servers,
*executable_external_mcp_servers(
requested_servers=DEFAULT_MCP_DIAGNOSTIC_SERVERS,
),
)
support = resolve_runtime_mcp_support(
provider_name=provider_row.provider,
runtime_name=mode.mode,
capabilities=capabilities,
bridge_available=bridge_available,
tool_count=1 if bridge_available else 0,
requested_servers=DEFAULT_MCP_DIAGNOSTIC_SERVERS,
available_servers=available_servers,
)
plan = support.bridge_plan.to_dict()
matrix.append(
{
"provider": provider_row.provider,
"runtime_mode": mode.mode,
"strategy": support.strategy,
"available": support.available,
"status": plan["status"],
"action_required": plan["action_required"],
"recommended_runtime_path": plan["recommended_runtime_path"],
"available_servers": plan["available_servers"],
"unavailable_servers": plan["unavailable_servers"],
"native_required_servers": plan["native_required_servers"],
"local_bridge_required_servers": plan[
"local_bridge_required_servers"
],
"external_bridge_required_servers": plan[
"external_bridge_required_servers"
],
"external_bridge_ready_servers": plan[
"external_bridge_ready_servers"
],
"external_bridge_adapter_missing_servers": plan[
"external_bridge_adapter_missing_servers"
],
"external_bridge_unsupported_transport_servers": plan[
"external_bridge_unsupported_transport_servers"
],
"unsupported_servers": plan["unsupported_servers"],
"bridged_servers": plan["bridged_servers"],
"local_bridged_servers": plan["local_bridged_servers"],
"external_bridged_servers": plan["external_bridged_servers"],
"executable_external_tools": list(
executable_external_mcp_tools(
requested_servers=DEFAULT_MCP_DIAGNOSTIC_SERVERS,
)
)
if bridge_available
else [],
}
)
return matrix
def _unique_sorted(values: list[str]) -> list[str]:
"""Return deterministic unique values for diagnostic payloads."""
return sorted({value for value in values if value})
def _mcp_allowlist_fields() -> dict[str, Any]:
"""Return the effective MCP permission allowlist diagnostic fields."""
allowed_permissions = normalize_mcp_allowed_permissions(None)
fields: dict[str, Any] = {
"strict_allowlist_configured": allowed_permissions is not None,
"allowlist_source": (
MCP_ALLOWED_PERMISSIONS_ENV
if allowed_permissions is not None
else "allow_all_default"
),
}
if allowed_permissions is not None:
fields["allowed_permissions"] = sorted(allowed_permissions)
return fields
def build_mcp_bridge_permission_matrix(
*,
project_mcp_config: Mapping[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""Build server-level MCP bridge permission/audit enforcement diagnostics."""
allowlist_fields = _mcp_allowlist_fields()
required_gates = list(MCP_PERMISSION_REQUIRED_GATES)
audit_artifact = ".auto-Codex/specs/<spec>/artifacts/mcp_bridge_audit.jsonl"
matrix: list[dict[str, Any]] = [
{
"server": LOCAL_BRIDGE_SERVER,
"display_name": str(
MCP_SERVER_CATALOG[LOCAL_BRIDGE_SERVER]["display_name"]
),
"bridge_path": "local_bridge",
"status": "enforced",
"permission_enforced": True,
**allowlist_fields,
"audit_required": True,
"audit_artifact": audit_artifact,
"tool_count": None,
"tool_policy_coverage": "dynamic",
"permissions": ["dynamic_auto_claude_tool_policy"],
"mutating_permissions": ["dynamic_mutating_tool_policy"],
"required_gates": required_gates,
"satisfied_gates": required_gates,
"missing_gates": [],
"reason": "local_tools_receive_runtime_policy_before_execution",
}
]
for server in registered_external_mcp_servers(
project_mcp_config=project_mcp_config,
):
adapter = external_mcp_adapter_for(
server,
project_mcp_config=project_mcp_config,
)
catalog_entry = mcp_server_catalog_entry(
server,
project_mcp_config=project_mcp_config,
)
if adapter is None or not adapter.tool_definitions:
matrix.append(
{
"server": server,
"display_name": str(catalog_entry.get("display_name", server)),
"bridge_path": "external_bridge",
"status": "missing_policy",
"permission_enforced": False,
**allowlist_fields,
"audit_required": False,
"audit_artifact": audit_artifact,
"tool_count": 0,
"tool_policy_coverage": "missing",
"permissions": [],
"mutating_permissions": [],
"required_gates": required_gates,
"satisfied_gates": [],
"missing_gates": required_gates,
"reason": "external_adapter_has_no_tool_policy_metadata",
}
)
continue
tool_definitions = adapter.tool_definitions
missing_gates: list[str] = []
if not all(definition.policy.audit_required for definition in tool_definitions):
missing_gates.append("audit_artifact")
satisfied_gates = [gate for gate in required_gates if gate not in missing_gates]
matrix.append(
{
"server": server,
"display_name": str(catalog_entry.get("display_name", server)),
"bridge_path": "external_bridge",
"status": "enforced" if not missing_gates else "partial",
"permission_enforced": True,
**allowlist_fields,
"audit_required": not missing_gates,
"audit_artifact": audit_artifact,
"tool_count": len(tool_definitions),
"tool_policy_coverage": "static",
"permissions": _unique_sorted(
[definition.policy.permission for definition in tool_definitions]
),
"mutating_permissions": _unique_sorted(
[
definition.policy.permission
for definition in tool_definitions
if definition.policy.mutating
]
),
"required_gates": required_gates,
"satisfied_gates": satisfied_gates,
"missing_gates": missing_gates,
"reason": "external_tools_receive_runtime_policy_before_execution",
}
)
return matrix
def _subagent_orchestrator_available(provider: str, runtime_mode: str) -> bool:
"""Return true when the runtime can use Auto Code's child-session orchestrator."""
if provider == "codex":
return runtime_mode == "full_autonomous"
return runtime_mode in {"analysis_only", "generic_edit", "patch_proposal"}
def build_runtime_subagent_matrix() -> list[dict[str, Any]]:
"""Build provider/runtime subagent support diagnostics."""
matrix: list[dict[str, Any]] = []
for provider_row in PROVIDER_RUNTIME_COMPATIBILITY:
for mode in RUNTIME_MODE_INFO:
capabilities = capabilities_for_runtime_mode(
provider_row.provider,
mode.mode,
)
support = resolve_runtime_subagent_support(
provider_name=provider_row.provider,
runtime_name=mode.mode,
capabilities=capabilities,
orchestrator_available=_subagent_orchestrator_available(
provider_row.provider,
mode.mode,
),
)
row = support.to_dict()
row["runtime_mode"] = row.pop("runtime")
row["max_attempts"] = DEFAULT_SUBAGENT_MAX_ATTEMPTS
row["merge_policy"] = DEFAULT_SUBAGENT_MERGE_POLICY
row["artifact_support"] = True
matrix.append(row)
return matrix
def build_runtime_subagent_mutation_policy() -> list[dict[str, Any]]:
"""Build explicit policy gates for mutating subagent support.
The matrix reflects the resolved :class:`ResolvedAutonomySettings`
so ``AUTO_CODE_AUTONOMY=bold`` (or an explicit
``AUTO_CODE_MUTATING_SUBAGENTS=true`` override) flips the status
from ``blocked`` to ``opt_in_experimental``. The conflict-aware
merge protocol is still scaffold-only; the status is intentionally
not ``enabled`` until the parent-approved apply/abort UX lands.
"""
from core.autonomy_level import resolve_autonomy_settings
autonomy_settings = resolve_autonomy_settings()
missing_gates = [
gate
for gate in MUTATING_SUBAGENT_REQUIRED_GATES
if gate not in MUTATING_SUBAGENT_SATISFIED_GATES
]
matrix: list[dict[str, Any]] = []
for provider_row in PROVIDER_RUNTIME_COMPATIBILITY:
for mode in RUNTIME_MODE_INFO:
if mode.mode not in {"full_autonomous", "generic_edit"}:
continue
mutating_enabled = autonomy_settings.mutating_subagents_enabled
if mutating_enabled:
status = "opt_in_experimental"
reason = (
"mutating_subagents_opted_in_via_autonomy_level"
if autonomy_settings.level.value == "bold"
else "mutating_subagents_opted_in_via_env_override"
)
else:
status = "blocked"
reason = "mutating_subagents_require_transactional_merge"
matrix.append(
{
"provider": provider_row.provider,
"runtime_mode": mode.mode,
"mutating_subagents_enabled": mutating_enabled,
"status": status,
"transaction_boundary_required": True,
"parent_approval_required": True,
"merge_protocol": "read_only_until_transactional_merge",
"required_gates": list(MUTATING_SUBAGENT_REQUIRED_GATES),
"satisfied_gates": list(MUTATING_SUBAGENT_SATISFIED_GATES),
"missing_gates": missing_gates,
"reason": reason,
}
)
return matrix
def _runtime_policy_readiness_fields(
readiness: dict[str, Any] | None,
) -> dict[str, Any]:
"""Return readiness fields shared by runtime policy rows."""
if readiness is None:
return {
"autonomous_readiness_required": False,
"autonomous_policy_gate": "not_required",
"autonomous_readiness_status": "not_required",
"autonomous_readiness_recommendation": "not_required",
"autonomous_readiness_recommendation_reasons": [],
"autonomous_readiness_blockers": [],
"autonomous_readiness_warnings": [],
"autonomous_readiness_requirements": {},
"autonomous_readiness_missing_requirements": [],
"autonomous_promotion_gate": "not_required",
"autonomous_promotion_ready": False,
"autonomous_promotion_missing_reliability_cases": [],
"autonomous_promotion_missing_e2e_runs": [],
}
promotion_gate = readiness["promotion_gate"]
return {
"autonomous_readiness_required": True,
"autonomous_policy_gate": readiness["policy_gate"],
"autonomous_readiness_status": readiness["status"],
"autonomous_readiness_recommendation": readiness["recommendation"],
"autonomous_readiness_recommendation_reasons": readiness[
"recommendation_reasons"
],
"autonomous_readiness_blockers": readiness["blockers"],
"autonomous_readiness_warnings": readiness["warnings"],
"autonomous_readiness_requirements": readiness["requirements"],
"autonomous_readiness_missing_requirements": readiness["missing_requirements"],
"autonomous_promotion_gate": promotion_gate["status"],
"autonomous_promotion_ready": promotion_gate["promotion_ready"],
"autonomous_promotion_missing_reliability_cases": promotion_gate[
"missing_reliability_cases"
],
"autonomous_promotion_missing_e2e_runs": promotion_gate["missing_e2e_runs"],
}
def _runtime_policy_decision(
phase: str,
phase_policy: Mapping[str, Any],
has_full_runtime: bool,
readiness: dict[str, Any] | None,
direct_api_gate: DirectApiAutonomousGate | None,
) -> tuple[str, str]:
"""Return policy/reason after applying direct-provider readiness gates."""
if has_full_runtime:
return "use_full_runtime", "provider_has_full_runtime"
if (
direct_api_gate is not None
and direct_api_gate.allowed
and phase in {"coder", "qa_fixer"}
):
return (
"use_direct_api_autonomous_runtime",
"direct_api_autonomous_gate_passed",
)
if (
readiness is not None
and readiness["policy_gate"] != "passed"
and phase in {"coder", "qa_fixer"}
):
promotion_gate = readiness.get("promotion_gate")
if (
isinstance(promotion_gate, dict)
and promotion_gate.get("status") == "blocked"
and readiness["status"] == "full_autonomous_candidate"
):
return "provider_e2e_required", "provider_autonomous_promotion_blocked"
return str(readiness["recommendation"]), str(readiness["status"])
return str(phase_policy["policy"]), str(phase_policy["reason"])
def _runtime_policy_row(
provider_row: Any,
phase_policy: Mapping[str, Any],
full_runtime_runner_candidates: list[str],
readiness: dict[str, Any] | None,
direct_api_gate: DirectApiAutonomousGate | None,
) -> dict[str, Any]:
"""Build one phase/provider runtime policy row."""
phase = str(phase_policy["phase"])
has_full_runtime = provider_row.full_autonomous == "yes"
direct_api_autonomous_allowed = (
direct_api_gate is not None
and direct_api_gate.allowed
and phase in {"coder", "qa_fixer"}
)
selected_mode = (
"full_autonomous"
if has_full_runtime or direct_api_autonomous_allowed
else str(phase_policy["direct_provider_mode"])
)
requires_full_autonomous = bool(phase_policy["requires_full_autonomous"])
requires_cli_runner = requires_full_autonomous and not has_full_runtime
policy, reason = _runtime_policy_decision(
phase,
phase_policy,
has_full_runtime,
readiness,
direct_api_gate,
)
return {
"phase": phase,
"provider": provider_row.provider,
"required_runtime_mode": (
"full_autonomous" if requires_full_autonomous else selected_mode
),
"selected_runtime_mode": selected_mode,
"fallback_allowed": bool(phase_policy["fallback_allowed"])
and selected_mode != "blocked",
"fallback_modes": (
list(phase_policy["fallback_modes"]) if selected_mode != "blocked" else []
),
"requires_full_autonomous": requires_full_autonomous,
"requires_cli_runner": requires_cli_runner,
"runner_candidates": (
full_runtime_runner_candidates if requires_cli_runner else []
),
"policy": policy,
"reason": reason,
**_runtime_policy_readiness_fields(readiness),
}
def build_runtime_policy_matrix(
*,
project_dir: Path | None = None,
) -> list[dict[str, Any]]:
"""Build phase/provider runtime policy diagnostics."""
full_runtime_runner_candidates = list(
select_cli_runner_profiles(
runtime_mode="full_autonomous",
).selected_runner_ids
)
readiness_by_provider = _runtime_provider_autonomous_readiness_by_name(
project_dir=project_dir,
)
direct_api_gates = _runtime_direct_api_autonomous_gates_by_name(
project_dir=project_dir,
)
return [
_runtime_policy_row(
provider_row,
phase_policy,
full_runtime_runner_candidates,
readiness_by_provider.get(provider_row.provider),
direct_api_gates.get(provider_row.provider),
)
for provider_row in PROVIDER_RUNTIME_COMPATIBILITY
for phase_policy in RUNTIME_POLICY_PHASES
]
def _runtime_direct_api_autonomous_gates_by_name(
*,
project_dir: Path | None = None,
) -> dict[str, DirectApiAutonomousGate]:
"""Return direct API autonomous activation gates keyed by provider name."""
base_dir = project_dir or Path.cwd()
return {
provider_row.provider: resolve_direct_api_autonomous_gate(
provider_name=provider_row.provider,
project_dir=base_dir,
phase="coding",
)
for provider_row in PROVIDER_RUNTIME_COMPATIBILITY
}
def _extend_unique(target: list[str], values: list[str]) -> None:
"""Append non-empty unique values to a diagnostic list."""
for value in values:
if value and value not in target:
target.append(value)
def _runtime_capability_readiness_fields(
readiness: dict[str, Any] | None,
) -> dict[str, Any]:
"""Return autonomous readiness fields for capability diagnostics."""
if readiness is None:
return {
"autonomous_readiness_required": False,
"autonomous_policy_gate": "not_required",
"autonomous_readiness_status": "not_required",
"autonomous_readiness_recommendation": "not_required",
"autonomous_readiness_recommendation_reasons": [],
"autonomous_readiness_blockers": [],
"autonomous_readiness_warnings": [],
"autonomous_readiness_evidence": [],
"autonomous_readiness_requirements": {},
"autonomous_readiness_missing_requirements": [],
"autonomous_readiness_next_actions": [],
"autonomous_promotion_gate": "not_required",
"autonomous_promotion_ready": False,
"autonomous_promotion_missing_reliability_cases": [],
"autonomous_promotion_missing_e2e_runs": [],
}
promotion_gate = readiness["promotion_gate"]
return {
"autonomous_readiness_required": True,
"autonomous_policy_gate": readiness["policy_gate"],
"autonomous_readiness_status": readiness["status"],
"autonomous_readiness_recommendation": readiness["recommendation"],
"autonomous_readiness_recommendation_reasons": readiness[
"recommendation_reasons"
],
"autonomous_readiness_blockers": readiness["blockers"],
"autonomous_readiness_warnings": readiness["warnings"],
"autonomous_readiness_evidence": readiness["evidence"],
"autonomous_readiness_requirements": readiness["requirements"],
"autonomous_readiness_missing_requirements": readiness["missing_requirements"],
"autonomous_readiness_next_actions": readiness["next_actions"],
"autonomous_promotion_gate": promotion_gate["status"],
"autonomous_promotion_ready": promotion_gate["promotion_ready"],
"autonomous_promotion_missing_reliability_cases": promotion_gate[
"missing_reliability_cases"
],
"autonomous_promotion_missing_e2e_runs": promotion_gate["missing_e2e_runs"],
}
def _runtime_capability_blockers_and_warnings(
provider_row: Any,
has_full_runtime: bool,
readiness: dict[str, Any] | None,
) -> tuple[list[str], list[str]]:
"""Return capability blockers/warnings after provider readiness gates."""
blockers: list[str] = []
warnings: list[str] = []
gate_passed = readiness is not None and readiness["policy_gate"] == "passed"
if not has_full_runtime and not gate_passed:
blockers.extend(
[
"missing_full_autonomous_runtime",
"live_provider_e2e_required",
"transactional_recovery_required",
]
)
warnings.append("direct_full_autonomous_blocked")
if provider_row.provider in {"litellm", "openrouter"}:
warnings.append("gateway_model_limitations")
if provider_row.provider == "ollama":
warnings.append("local_model_quality_varies")
if readiness is not None:
promotion_gate = readiness.get("promotion_gate")
if (
isinstance(promotion_gate, dict)
and promotion_gate.get("status") == "blocked"
and readiness["status"] == "full_autonomous_candidate"
):
_extend_unique(blockers, ["provider_autonomous_promotion_blocked"])
_extend_unique(blockers, readiness["blockers"])
_extend_unique(warnings, readiness["warnings"])
return blockers, warnings
def _runtime_capability_row(
provider_row: Any,
full_runtime_runner_candidates: list[str],
readiness: dict[str, Any] | None,
direct_api_gate: DirectApiAutonomousGate | None,
) -> dict[str, Any]:
"""Build one provider capability row."""
has_full_runtime = provider_row.full_autonomous == "yes"
readiness_status = "ready" if has_full_runtime else "limited"
if not has_full_runtime and readiness is not None:
readiness_status = str(readiness["status"])
blockers, warnings = _runtime_capability_blockers_and_warnings(
provider_row,
has_full_runtime,
readiness,
)
full_autonomous_ready = has_full_runtime or (
readiness is not None
and isinstance(readiness.get("promotion_gate"), dict)
and readiness["promotion_gate"]["promotion_ready"] is True
)
direct_api_autonomous_allowed = (
direct_api_gate is not None and direct_api_gate.allowed
)
return {
"provider": provider_row.provider,
"readiness": readiness_status,
"full_autonomous_ready": full_autonomous_ready,
"direct_api_autonomous_runtime": (
direct_api_gate.status if direct_api_gate is not None else "not_applicable"
),
"direct_api_autonomous_runtime_allowed": direct_api_autonomous_allowed,
"direct_api_autonomous_runtime_reason": (
direct_api_gate.reason if direct_api_gate is not None else "not_applicable"
),
"direct_api_autonomous_missing_requirements": (
direct_api_gate.missing_requirements if direct_api_gate is not None else []
),
"direct_full_autonomous": provider_row.full_autonomous,
"recommended_runtime_mode": (
"full_autonomous"
if has_full_runtime or direct_api_autonomous_allowed
else "generic_edit"
),
"generic_edit": provider_row.generic_edit,
"analysis_only": provider_row.analysis_only,
"patch_proposal": provider_row.patch_proposal,
"mcp_tools": provider_row.mcp_tools,
"subagents": provider_row.subagents,
"cli_runner_candidates": (
[] if has_full_runtime else full_runtime_runner_candidates
),
**_runtime_capability_readiness_fields(readiness),
"blockers": blockers,
"warnings": warnings,
"notes": provider_row.notes,
}
def build_runtime_capability_matrix(
*,
project_dir: Path | None = None,
) -> list[dict[str, Any]]:
"""Build consolidated provider readiness diagnostics for the control plane."""
full_runtime_runner_candidates = list(
select_cli_runner_profiles(
runtime_mode="full_autonomous",
).selected_runner_ids
)
readiness_by_provider = _runtime_provider_autonomous_readiness_by_name(
project_dir=project_dir,
)
direct_api_gates = _runtime_direct_api_autonomous_gates_by_name(
project_dir=project_dir,
)
return [
_runtime_capability_row(
provider_row,
full_runtime_runner_candidates,
readiness_by_provider.get(provider_row.provider),
direct_api_gates.get(provider_row.provider),
)
for provider_row in PROVIDER_RUNTIME_COMPATIBILITY
]
def build_runtime_eval_matrix() -> list[dict[str, Any]]:
"""Build runtime eval/smoke cases required before declaring full autonomy."""
return [
{
"case_id": "provider_e2e",
"runtime_mode": "provider_e2e",
"required_for_full_autonomous": True,
"providers": list(PROVIDER_RELIABILITY_DIRECT_API_PROVIDERS),
"required_artifacts": [
"provider_e2e_suite",
"provider_e2e_negative_fixtures",
"provider_reliability",
],
},
{
"case_id": "generic_edit_recovery",
"runtime_mode": "generic_edit",
"required_for_full_autonomous": True,
"providers": list(PROVIDER_RELIABILITY_DIRECT_API_PROVIDERS),
"required_artifacts": [
"generic_edit_recovery_checkpoint.json",
"generic_edit_session_state.json",
"generic_edit_transaction_groups.json",
],
},
{
"case_id": "mcp_bridge_contract",
"runtime_mode": "generic_edit",
"required_for_full_autonomous": True,
"providers": list(PROVIDER_RELIABILITY_DIRECT_API_PROVIDERS),
"required_artifacts": ["external_mcp_contract_checks"],
},
{
"case_id": "subagent_orchestrator",
"runtime_mode": "generic_edit",
"required_for_full_autonomous": True,
"providers": list(PROVIDER_RELIABILITY_DIRECT_API_PROVIDERS),
"required_artifacts": [
"runtime_subagents.json",
"runtime_subagents__<child>.json",
],
},
{
"case_id": "cli_full_runtime",
"runtime_mode": "full_autonomous",
"required_for_full_autonomous": True,
"providers": ["codex"],
"required_artifacts": [
"codex_cli_result.json",
"codex_cli_timeline.json",
],
},
]
def _runtime_eval_provider_history_status(provider_stats: dict[str, Any]) -> str:
"""Classify a provider's latest persisted e2e eval evidence."""
if not provider_stats:
return "not_observed"
if (
provider_stats.get("last_status") == "passed"
and provider_stats.get("last_reliability_status") == "complete"
and provider_stats.get("last_provider_e2e_status") == "passed"
):
return "passed"
return "failed"
def _runtime_eval_history_status(provider_rows: list[dict[str, Any]]) -> str:
"""Classify aggregate provider e2e history coverage."""
statuses = {row["status"] for row in provider_rows}