letitloop 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,263 @@
1
+ """Provenance graph — tracks contract output lineage and dependency chains."""
2
+
3
+ import os
4
+ from datetime import datetime, timezone
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from .contract import load_contract
8
+ from .state import load_state
9
+
10
+
11
+ class ProvenanceNode:
12
+ """A node in the provenance graph — a contract with its I/O and state."""
13
+
14
+ def __init__(
15
+ self,
16
+ task_id: str,
17
+ title: str,
18
+ status: str,
19
+ objective: str,
20
+ outputs: List[str],
21
+ inputs: List[str],
22
+ evidence: Dict[str, str],
23
+ attempt: int,
24
+ failure_class: str = "",
25
+ ):
26
+ self.task_id = task_id
27
+ self.title = title
28
+ self.status = status
29
+ self.objective = objective
30
+ self.outputs = outputs
31
+ self.inputs = inputs
32
+ self.evidence = evidence
33
+ self.attempt = attempt
34
+ self.failure_class = failure_class
35
+
36
+ def to_dict(self) -> Dict[str, Any]:
37
+ return {
38
+ "task_id": self.task_id,
39
+ "title": self.title,
40
+ "status": self.status,
41
+ "objective": self.objective,
42
+ "outputs": list(self.outputs),
43
+ "inputs": list(self.inputs),
44
+ "evidence": dict(self.evidence),
45
+ "attempt": self.attempt,
46
+ "failure_class": self.failure_class,
47
+ }
48
+
49
+
50
+ class ProvenanceEdge:
51
+ """An edge — dependency or evidence flow between two contracts."""
52
+
53
+ def __init__(self, source: str, target: str, edge_type: str, paths: Optional[List[str]] = None):
54
+ self.source = source
55
+ self.target = target
56
+ self.edge_type = edge_type
57
+ self.paths = paths or []
58
+
59
+ def to_dict(self) -> Dict[str, Any]:
60
+ return {
61
+ "source": self.source,
62
+ "target": self.target,
63
+ "edge_type": self.edge_type,
64
+ "paths": list(self.paths),
65
+ }
66
+
67
+
68
+ class ProvenanceGraph:
69
+ """Full provenance graph for a goal execution."""
70
+
71
+ def __init__(self, goal_id: str, goal_title: str):
72
+ self.goal_id = goal_id
73
+ self.goal_title = goal_title
74
+ self.nodes: Dict[str, ProvenanceNode] = {}
75
+ self.edges: List[ProvenanceEdge] = []
76
+ self.created_at = datetime.now(timezone.utc).isoformat()
77
+
78
+ def add_node(self, node: ProvenanceNode) -> None:
79
+ self.nodes[node.task_id] = node
80
+
81
+ def add_edge(self, edge: ProvenanceEdge) -> None:
82
+ self.edges.append(edge)
83
+
84
+ def to_dict(self) -> Dict[str, Any]:
85
+ return {
86
+ "goal_id": self.goal_id,
87
+ "goal_title": self.goal_title,
88
+ "created_at": self.created_at,
89
+ "nodes": [n.to_dict() for n in self.nodes.values()],
90
+ "edges": [e.to_dict() for e in self.edges],
91
+ }
92
+
93
+ def resolve_output(self, output_path: str) -> List[ProvenanceNode]:
94
+ """Find all nodes that produced a given output path."""
95
+ abs_path = os.path.abspath(output_path) if not os.path.isabs(output_path) else output_path
96
+ matches = []
97
+ for node in self.nodes.values():
98
+ for out in node.outputs:
99
+ out_abs = os.path.abspath(out) if not os.path.isabs(out) else out
100
+ if out_abs == abs_path or out == output_path:
101
+ matches.append(node)
102
+ return matches
103
+
104
+ def resolve_input_source(self, input_path: str) -> List[ProvenanceNode]:
105
+ """Find which upstream nodes produced a given input path."""
106
+ abs_path = os.path.abspath(input_path) if not os.path.isabs(input_path) else input_path
107
+ matches = []
108
+ for node in self.nodes.values():
109
+ for out in node.outputs:
110
+ out_abs = os.path.abspath(out) if not os.path.isabs(out) else out
111
+ if out_abs == abs_path or out == input_path:
112
+ matches.append(node)
113
+ return matches
114
+
115
+ def trace_path(self, output_path: str) -> Dict[str, Any]:
116
+ """Trace full provenance chain for an output — which contract, its inputs, and their sources."""
117
+ producers = self.resolve_output(output_path)
118
+ chain = {
119
+ "output_path": output_path,
120
+ "producers": [],
121
+ }
122
+ for p in producers:
123
+ producer_info = p.to_dict()
124
+ input_sources = {}
125
+ for inp in p.inputs:
126
+ sources = self.resolve_input_source(inp)
127
+ input_sources[inp] = [s.task_id for s in sources]
128
+ producer_info["input_sources"] = input_sources
129
+ chain["producers"].append(producer_info)
130
+ return chain
131
+
132
+
133
+ def build_provenance(goal_id: str, goal_title: str, plan, workspace_root: str, run_dir: str) -> ProvenanceGraph:
134
+ """Build provenance graph from on-disk state for a completed/partial goal."""
135
+ graph = ProvenanceGraph(goal_id, goal_title)
136
+
137
+ from .failure import classify_failure
138
+
139
+ def _as_dict(c):
140
+ return c if isinstance(c, dict) else c._raw if hasattr(c, "_raw") else {}
141
+
142
+ # Collect all edges first (from plan dependencies)
143
+ dep_edges = {} # target -> list of source task_ids
144
+ for c in plan.contracts:
145
+ c = _as_dict(c)
146
+ tid = c["task_id"]
147
+ deps = c.get("depends_on", [])
148
+ if deps:
149
+ dep_edges[tid] = deps
150
+
151
+ # Build nodes from disk state
152
+ for c in plan.contracts:
153
+ c = _as_dict(c)
154
+ tid = c["task_id"]
155
+ task_dir = os.path.join(run_dir, tid)
156
+ state_file = os.path.join(task_dir, "state.json")
157
+
158
+ title = c.get("title", tid)
159
+ contract_raw = c.get("contract") or {}
160
+ objective = contract_raw.get("objective", "") or c.get("objective", "")
161
+
162
+ if os.path.isfile(state_file):
163
+ state = load_state(state_file)
164
+ status = state.status
165
+ attempt = state.attempt
166
+ evidence = dict(state.evidence)
167
+
168
+ # Get failure class if applicable
169
+ fclass = ""
170
+ if status in ("VERIFICATION_FAILED", "BLOCKED", "PREFLIGHT_FAILED"):
171
+ contract_path = os.path.join(task_dir, "contract.json")
172
+ contract, _ = load_contract(contract_path, workspace_root=workspace_root)
173
+ fclass = classify_failure(state, contract)
174
+ else:
175
+ status = c.get("status", "DRAFTED")
176
+ attempt = 0
177
+ evidence = {}
178
+ fclass = ""
179
+
180
+ # Collect outputs and inputs from contract
181
+ contract_dict = c.get("contract") or {}
182
+ outputs = [o["path"] if isinstance(o, dict) else o for o in contract_dict.get("outputs", [])]
183
+ inputs = [i["path"] if isinstance(i, dict) else i for i in contract_dict.get("inputs", [])]
184
+
185
+ node = ProvenanceNode(
186
+ task_id=tid,
187
+ title=title,
188
+ status=status,
189
+ objective=objective,
190
+ outputs=outputs,
191
+ inputs=inputs,
192
+ evidence=evidence,
193
+ attempt=attempt,
194
+ failure_class=fclass,
195
+ )
196
+ graph.add_node(node)
197
+
198
+ # Build edges from plan dependencies
199
+ for target, sources in dep_edges.items():
200
+ for source in sources:
201
+ edge = ProvenanceEdge(
202
+ source=source,
203
+ target=target,
204
+ edge_type="dependency",
205
+ )
206
+ # Attach evidence paths if source node has outputs listed as target inputs
207
+ if source in graph.nodes:
208
+ source_outputs = set(graph.nodes[source].outputs)
209
+ if target in graph.nodes:
210
+ target_inputs = graph.nodes[target].inputs
211
+ for inp in target_inputs:
212
+ if inp in source_outputs:
213
+ edge.paths.append(inp)
214
+ graph.add_edge(edge)
215
+
216
+ # Build evidence-flow edges from actual evidence injection
217
+ # (evidence_store in supervisor can be reconstructed from state)
218
+ for node in graph.nodes.values():
219
+ for ev_key, ev_path in node.evidence.items():
220
+ graph.add_edge(
221
+ ProvenanceEdge(
222
+ source=node.task_id,
223
+ target=node.task_id,
224
+ edge_type="evidence",
225
+ paths=[ev_path],
226
+ )
227
+ )
228
+
229
+ return graph
230
+
231
+
232
+ def format_provenance(graph: ProvenanceGraph) -> str:
233
+ """Format provenance graph as human-readable string."""
234
+ lines = [
235
+ f"=== Provenance: {graph.goal_id} ===",
236
+ f"Goal: {graph.goal_title}",
237
+ f"Nodes: {len(graph.nodes)}, Edges: {len(graph.edges)}",
238
+ "",
239
+ ]
240
+
241
+ for tid in sorted(graph.nodes.keys()):
242
+ node = graph.nodes[tid]
243
+ lines.append(f" [{node.status}] {tid} (attempt {node.attempt})")
244
+ if node.failure_class:
245
+ lines.append(f" Failure: {node.failure_class}")
246
+ if node.objective:
247
+ lines.append(f" Objective: {node.objective[:80]}")
248
+ if node.inputs:
249
+ lines.append(f" Inputs: {', '.join(node.inputs)}")
250
+ if node.outputs:
251
+ lines.append(f" Outputs: {', '.join(node.outputs)}")
252
+ if node.evidence:
253
+ lines.append(f" Evidence: {len(node.evidence)} file(s)")
254
+ lines.append("")
255
+
256
+ if graph.edges:
257
+ lines.append(" Edges:")
258
+ for e in graph.edges:
259
+ path_info = f" [{', '.join(e.paths[:3])}]" if e.paths else ""
260
+ lines.append(f" {e.source} -> {e.target} ({e.edge_type}){path_info}")
261
+ lines.append("")
262
+
263
+ return "\n".join(lines)
@@ -0,0 +1,394 @@
1
+ """Provider-aware scheduling for the quality plane.
2
+
3
+ Prevents concurrent calls to the same model provider (rate-limit
4
+ avoidance). Groups calls by provider into waves; the current runtime
5
+ executes them serially (H2) — this module only structures calls.
6
+
7
+ Zero LLM calls. Deterministic ordering.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from dataclasses import dataclass, field
14
+ from typing import Any, Dict, List, Optional, Set
15
+
16
+ from .models import _bare_model_id, classify_model, escalation_ladder
17
+
18
+
19
+ @dataclass
20
+ class CallSpec:
21
+ """A single model invocation request."""
22
+
23
+ call_id: str
24
+ prompt: str
25
+ model: str
26
+ reviewer_id: str = ""
27
+ role: str = ""
28
+ component_id: str = ""
29
+ component_files: Optional[List[str]] = None
30
+
31
+ def to_dict(self) -> dict:
32
+ return {
33
+ "call_id": self.call_id,
34
+ "model": self.model,
35
+ "reviewer_id": self.reviewer_id,
36
+ "role": self.role,
37
+ "component_id": self.component_id,
38
+ }
39
+
40
+
41
+ @dataclass
42
+ class ScheduleWave:
43
+ """A set of calls grouped for concurrency-safe execution (see H2 note)."""
44
+
45
+ calls: List[CallSpec] = field(default_factory=list)
46
+
47
+
48
+ @dataclass
49
+ class UsageRecord:
50
+ """Per-provider usage snapshot."""
51
+
52
+ provider: str
53
+ model: str
54
+ calls: int = 0
55
+
56
+
57
+ def _extract_provider(model: str) -> str:
58
+ """Extract provider name from a model ID (matches ``orchestrator.llm`` prefixes)."""
59
+ lower = model.lower()
60
+ if lower.startswith("hybrid:"):
61
+ return _extract_provider(model[7:])
62
+ if lower.startswith("any:"):
63
+ return "any"
64
+ for prefix in ("openai:", "anthropic:", "gemini:", "deepseek:"):
65
+ if lower.startswith(prefix):
66
+ return prefix[:-1]
67
+ if ":" in lower:
68
+ return lower.split(":", 1)[0]
69
+ return "any"
70
+
71
+
72
+ class ProviderScheduler:
73
+ """Schedules model calls respecting per-provider concurrency limits.
74
+
75
+ Groups calls by provider, then builds waves where calls to different
76
+ providers can run in parallel.
77
+ """
78
+
79
+ def __init__(self, max_concurrent: Optional[Dict[str, int]] = None):
80
+ self.max_concurrent = max_concurrent or {
81
+ "openai": 1,
82
+ "anthropic": 1,
83
+ "gemini": 1,
84
+ "deepseek": 1,
85
+ "any": 3,
86
+ }
87
+ self.usage: Dict[str, UsageRecord] = {}
88
+
89
+ def schedule(self, calls: List[CallSpec]) -> List[ScheduleWave]:
90
+ """Build execution waves from a list of call specs.
91
+
92
+ Within a wave, every call targets a different provider and MAY run
93
+ concurrently under the current executor; waves execute sequentially.
94
+ A provider's max_concurrent limit is enforced by the executor layer
95
+ (one call per provider per wave — the executor never receives two
96
+ calls to the same provider in one wave), which makes the contract
97
+ valid whether or not the executor parallelizes.
98
+
99
+ NOTE (H2): the current runtime (_run_component_reviews) executes
100
+ calls strictly serially. This scheduler only *structures* calls
101
+ into concurrency-safe groups — it does not execute them. Callers
102
+ must not assume parallel execution until an executor is added.
103
+
104
+ Returns a list of ScheduleWave objects.
105
+ """
106
+ calls = list(calls)
107
+ if not calls:
108
+ return []
109
+
110
+ # Group by provider
111
+ provider_groups: dict = {}
112
+ for c in calls:
113
+ prov = _extract_provider(c.model)
114
+ provider_groups.setdefault(prov, []).append(c)
115
+ if prov not in self.usage:
116
+ self.usage[prov] = UsageRecord(provider=prov, model=c.model, calls=0)
117
+
118
+ # Build waves: round-robin across providers, one call per provider
119
+ # per wave (F4 — wave semantics now match the documented contract).
120
+ waves: List[ScheduleWave] = []
121
+ remaining = {p: list(cs) for p, cs in provider_groups.items()}
122
+ active_providers = {p for p, cs in remaining.items() if cs}
123
+
124
+ while active_providers:
125
+ wave = ScheduleWave()
126
+ for prov in list(active_providers):
127
+ if not remaining[prov]:
128
+ active_providers.discard(prov)
129
+ continue
130
+ c = remaining[prov].pop(0)
131
+ wave.calls.append(c)
132
+ self.usage[prov].calls += 1
133
+ if wave.calls:
134
+ waves.append(wave)
135
+
136
+ return waves
137
+
138
+ def usage_summary(self) -> Dict[str, Any]:
139
+ """Return per-provider and total usage as a dict."""
140
+ total = sum(r.calls for r in self.usage.values())
141
+ return {
142
+ "per_provider": {k: v.calls for k, v in self.usage.items()},
143
+ "total": total,
144
+ }
145
+
146
+
147
+ # ---------------------------------------------------------------------------
148
+ # Risk-aware dynamic routing (issue #19): cost/risk-tiered model selection.
149
+
150
+ # Projected (prompt_tokens, completion_tokens) per tier for budget pre-flight.
151
+ _PROJECTED_TOKENS_BY_TIER: Dict[int, tuple] = {
152
+ 1: (4_000, 1_000),
153
+ 2: (8_000, 2_000),
154
+ 3: (16_000, 4_000),
155
+ }
156
+
157
+ _BUDGET_LOW_RATIO = 0.25
158
+
159
+
160
+ @dataclass
161
+ class RoutingDecision:
162
+ """Outcome of a risk-aware routing decision.
163
+
164
+ escalate_context is True when capability failure evidence should be
165
+ attached to the retry brief (tier escalations), not for pure transport
166
+ rotation (rate limits / timeouts).
167
+ """
168
+
169
+ model: str
170
+ tier: int
171
+ reason: str
172
+ escalate_context: bool = False
173
+ skip_providers: Set[str] = field(default_factory=set)
174
+
175
+
176
+ def _error_status(error: Any) -> Optional[int]:
177
+ status = getattr(error, "status", None)
178
+ return status if isinstance(status, int) else None
179
+
180
+
181
+ def _is_rate_limit(error: Any) -> bool:
182
+ if isinstance(error, TimeoutError):
183
+ return True
184
+ return _error_status(error) == 429
185
+
186
+
187
+ def _failure_class(error: Any) -> str:
188
+ if error is None:
189
+ return "unknown"
190
+ if isinstance(error, TimeoutError):
191
+ return "timeout"
192
+ if _error_status(error) == 429:
193
+ return "rate-limit"
194
+ return type(error).__name__.lower()
195
+
196
+
197
+ def _budget_pressure(budget_state: Any) -> str:
198
+ """Classify a duck-typed budget snapshot: '' | 'low' | 'exhausted'."""
199
+ if budget_state is None:
200
+ return ""
201
+ exhausted = getattr(budget_state, "exhausted", None)
202
+ if exhausted is None and hasattr(budget_state, "get"):
203
+ exhausted = budget_state.get("exhausted")
204
+ if exhausted:
205
+ return "exhausted"
206
+ ratio: Optional[float] = None
207
+ if hasattr(budget_state, "remaining_pct"):
208
+ try:
209
+ ratio = float(budget_state.remaining_pct())
210
+ except (TypeError, ValueError):
211
+ ratio = None
212
+ elif hasattr(budget_state, "get"):
213
+ raw = budget_state.get("remaining_pct")
214
+ if isinstance(raw, (int, float)):
215
+ ratio = float(raw)
216
+ if ratio is None:
217
+ return ""
218
+ if ratio <= 0.0:
219
+ return "exhausted"
220
+ if ratio < _BUDGET_LOW_RATIO:
221
+ return "low"
222
+ return ""
223
+
224
+
225
+ def _first_affordable(ladder: List[str], tier_of: Dict[str, int], guard: Any) -> Optional[str]:
226
+ """First ladder candidate whose projected call passes the guard, else None."""
227
+ seen_tiers: Set[int] = set()
228
+ max_tier = max(_PROJECTED_TOKENS_BY_TIER)
229
+ for candidate in ladder:
230
+ tier = tier_of[candidate]
231
+ if tier in seen_tiers:
232
+ continue
233
+ seen_tiers.add(tier)
234
+ prompt_tokens, completion_tokens = _PROJECTED_TOKENS_BY_TIER.get(tier, _PROJECTED_TOKENS_BY_TIER[max_tier])
235
+ try:
236
+ guard.check_before_call(prompt_tokens, completion_tokens)
237
+ except Exception:
238
+ continue
239
+ return candidate
240
+ return None
241
+
242
+
243
+ def _decide(
244
+ start_model: Optional[str] = None,
245
+ attempt: int = 1,
246
+ last_error: Any = None,
247
+ budget_state: Any = None,
248
+ ladder: Optional[List[str]] = None,
249
+ budget_guard: Any = None,
250
+ ) -> RoutingDecision:
251
+ """Pure routing core (no side effects): map inputs to a RoutingDecision."""
252
+ ladder = list(ladder) if ladder else escalation_ladder(start_model)
253
+ if not ladder:
254
+ ladder = escalation_ladder()
255
+ # Merge the full default ladder so budget floors can reach lower tiers
256
+ # even when a custom/start-scoped ladder omits them.
257
+ seen_names = {_bare_model_id(c) for c in ladder}
258
+ for candidate in escalation_ladder():
259
+ if _bare_model_id(candidate) not in seen_names:
260
+ seen_names.add(_bare_model_id(candidate))
261
+ ladder.append(candidate)
262
+ tier_of = {candidate: classify_model(candidate) for candidate in ladder}
263
+ current = (start_model or "").strip() or ladder[0]
264
+ current_tier = tier_of.get(current, classify_model(current))
265
+
266
+ def decision(
267
+ model: str, tier: int, reason: str, escalate: bool = False, skip: Set[str] = frozenset()
268
+ ) -> RoutingDecision:
269
+ return RoutingDecision(
270
+ model=model,
271
+ tier=int(tier),
272
+ reason=reason,
273
+ escalate_context=bool(escalate),
274
+ skip_providers=set(skip),
275
+ )
276
+
277
+ pressure = _budget_pressure(budget_state)
278
+
279
+ if pressure:
280
+ floor_tier = min(tier_of.values()) if tier_of else 1
281
+ floor_candidates = [c for c in ladder if tier_of.get(c) == floor_tier]
282
+ chosen = floor_candidates[0] if floor_candidates else ladder[0]
283
+ return decision(
284
+ chosen,
285
+ floor_tier,
286
+ f"budget: budget_state {pressure}; preferring lowest tier",
287
+ escalate=attempt > 1,
288
+ )
289
+
290
+ if attempt <= 1:
291
+ return decision(current, current_tier, "first-attempt")
292
+
293
+ skip_providers: Set[str] = set()
294
+ if _is_rate_limit(last_error):
295
+ same_tier = [c for c in ladder if tier_of[c] == current_tier]
296
+ idx = same_tier.index(current) if current in same_tier else -1
297
+ nxt = same_tier[idx + 1] if 0 <= idx < len(same_tier) - 1 else None
298
+ skip_providers = {_extract_provider(current)} - {"any"}
299
+ if nxt is not None:
300
+ return decision(
301
+ nxt,
302
+ current_tier,
303
+ f"rate-limit: rotating within tier {current_tier} (failure class: {_failure_class(last_error)})",
304
+ skip=skip_providers,
305
+ )
306
+ # Same tier exhausted -> escalate to the next tier below.
307
+
308
+ steps = max(1, int(attempt) - 1)
309
+ max_tier = max(tier_of.values())
310
+ target_tier = min(current_tier + steps, max_tier)
311
+ target = next((c for c in ladder if tier_of[c] == target_tier), current)
312
+ fail_class = _failure_class(last_error)
313
+ if _is_rate_limit(last_error):
314
+ reason = (
315
+ f"rate-limit: no same-tier candidate left; escalating past tier "
316
+ f"{current_tier} (failure class: {fail_class})"
317
+ )
318
+ else:
319
+ reason = f"escalation: attempt {attempt} after {fail_class} failure; tier {current_tier} -> {target_tier}"
320
+
321
+ if budget_guard is not None:
322
+ affordable = _first_affordable(ladder, tier_of, budget_guard)
323
+ if affordable is None:
324
+ floor_tier = min(tier_of.values())
325
+ fallback = [c for c in ladder if tier_of[c] == floor_tier][0]
326
+ return decision(
327
+ fallback,
328
+ floor_tier,
329
+ f"budget: guard rejects projected cost for tier {target_tier}; downgraded to lowest tier",
330
+ escalate=True,
331
+ )
332
+ if tier_of[affordable] != target_tier:
333
+ return decision(
334
+ affordable,
335
+ tier_of[affordable],
336
+ f"budget: guard caps tier {target_tier}; downgraded to tier {tier_of[affordable]}",
337
+ escalate=True,
338
+ )
339
+
340
+ return decision(target, target_tier, reason, escalate=True)
341
+
342
+
343
+ class RiskAwareRouter:
344
+ """Maps (start model, attempt, last error, budget) to a RoutingDecision.
345
+
346
+ Pure policy over the escalation ladder; performs no LLM calls and mutates
347
+ nothing. Default runtime behavior is unchanged — callers must opt in via
348
+ ``next_retry_model`` / LETITLOOP_TIERED_ROUTING.
349
+ """
350
+
351
+ def __init__(self, ladder: Optional[List[str]] = None, budget_guard: Any = None):
352
+ self._ladder = list(ladder) if ladder else None
353
+ self.budget_guard = budget_guard
354
+
355
+ def ladder_for(self, start_model: Optional[str]) -> List[str]:
356
+ if self._ladder is not None:
357
+ return list(self._ladder)
358
+ return escalation_ladder(start_model)
359
+
360
+ def route(
361
+ self,
362
+ start_model: Optional[str],
363
+ attempt: int,
364
+ last_error: Any = None,
365
+ budget_state: Any = None,
366
+ ) -> RoutingDecision:
367
+ return _decide(
368
+ start_model=start_model,
369
+ attempt=attempt,
370
+ last_error=last_error,
371
+ budget_state=budget_state,
372
+ ladder=self.ladder_for(start_model),
373
+ budget_guard=self.budget_guard,
374
+ )
375
+
376
+
377
+ def next_retry_model(
378
+ contract_worker: dict,
379
+ attempt: int,
380
+ last_error: Any = None,
381
+ budget_guard: Any = None,
382
+ ) -> Optional[RoutingDecision]:
383
+ """Integration hook for the supervisor wave (issue #19).
384
+
385
+ Returns a RoutingDecision only when tiered routing is opted in via
386
+ ``contract_worker["escalate_on_retry"]`` or LETITLOOP_TIERED_ROUTING=1;
387
+ otherwise returns None so default runtime behavior stays unchanged.
388
+ """
389
+ worker = contract_worker or {}
390
+ enabled = bool(worker.get("escalate_on_retry")) or os.environ.get("LETITLOOP_TIERED_ROUTING") == "1"
391
+ if not enabled:
392
+ return None
393
+ router = RiskAwareRouter(budget_guard=budget_guard)
394
+ return router.route(worker.get("model"), attempt, last_error=last_error)