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,569 @@
1
+ """Strategy dispatch layer for the quality plane.
2
+
3
+ Extracted verbatim from the former flat orchestrator/quality_plane.py:
4
+ per-component reviewer dispatch, the run_quality_plane gateway (single /
5
+ panel / component-panel strategy selection with plan validation and
6
+ budget degradation), explicit-component validation, and deterministic
7
+ quality_spec gates for the legacy path.
8
+
9
+ Shared collaborators are resolved through the ``orchestrator.quality_plane``
10
+ compat namespace (``qp``) at call time so patches applied there stay live.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import concurrent.futures
16
+ import time
17
+ from typing import Any, Dict, List, Optional
18
+
19
+ from orchestrator import quality_plane as qp
20
+
21
+ from ..component_slicer import ComponentSlice, slice_components
22
+ from ..provider_scheduler import CallSpec, ProviderScheduler
23
+ from ..qc_review import _build_qc_prompt, _select_qc_model
24
+ from ..quality_plan import (
25
+ MODE_COMPONENT_PANEL,
26
+ MODE_PANEL,
27
+ MODE_SINGLE,
28
+ QualityPlan,
29
+ ReviewerRole,
30
+ validate_quality_plan,
31
+ )
32
+ from ..review_artifact import (
33
+ VERDICT_CONDITIONAL_PASS,
34
+ VERDICT_ERROR,
35
+ VERDICT_REJECT,
36
+ QualityPlaneVerdict,
37
+ ReviewArtifact,
38
+ )
39
+
40
+ _MAX_COMPONENT_WORKERS = 4
41
+
42
+
43
+ def _run_component_reviews(
44
+ contract,
45
+ components: List[ComponentSlice],
46
+ verification_results: List[Dict[str, Any]],
47
+ workspace_root: str,
48
+ quality_plan: QualityPlan,
49
+ scheduler: Optional[ProviderScheduler] = None,
50
+ deadline: Optional[float] = None,
51
+ max_workers: Optional[int] = None,
52
+ ) -> List[ReviewArtifact]:
53
+ """Dispatch reviewers per component, return artifacts.
54
+
55
+ Phase 4: one reviewer per component (uses reviewers[0] role).
56
+ Phase 5: up to max_reviewers_per_component reviewers, each with a
57
+ different persona from the quality_plan's reviewer list.
58
+ Phase 7: uses ProviderScheduler to respect per-provider concurrency.
59
+ """
60
+ quality_spec = getattr(contract, "quality_spec", {})
61
+
62
+ reviewers = list(quality_plan.reviewers) if quality_plan.reviewers else [ReviewerRole("reviewer")]
63
+ max_per_component = max(quality_plan.budget.max_reviewers_per_component, 1)
64
+ active_reviewers = reviewers[:max_per_component]
65
+
66
+ # Build call specs
67
+ all_calls: List[CallSpec] = []
68
+ call_map: dict = {} # call_id -> (index, role, component, prompt)
69
+ call_idx = 0
70
+ for i, component in enumerate(components):
71
+ base_prompt = _build_qc_prompt(
72
+ contract,
73
+ component.files,
74
+ verification_results,
75
+ quality_spec=quality_spec,
76
+ )
77
+ if getattr(component, "description", ""):
78
+ base_prompt = base_prompt + (f"\n=== COMPONENT DESCRIPTION ===\n{component.description}\n")
79
+ for role in active_reviewers:
80
+ persona_prompt = qp._build_persona_prompt(base_prompt, role)
81
+ call_id = f"comp_{i}_{role.role}_{call_idx}"
82
+ all_calls.append(
83
+ CallSpec(
84
+ call_id=call_id,
85
+ prompt=persona_prompt,
86
+ model=qp._resolve_reviewer_model(role),
87
+ reviewer_id=f"component_{i}_{role.role}",
88
+ role=role.role,
89
+ component_id=component.id,
90
+ component_files=component.files,
91
+ )
92
+ )
93
+ call_map[call_id] = (i, role, component, persona_prompt)
94
+ call_idx += 1
95
+
96
+ # Schedule and execute waves (Phase 7: per-provider concurrency)
97
+ scheduler = scheduler or ProviderScheduler()
98
+ waves = scheduler.schedule(all_calls)
99
+
100
+ artifacts: List[ReviewArtifact] = []
101
+ if deadline is None:
102
+ deadline = qp._deadline_for(quality_plan)
103
+
104
+ max_workers = max_workers or _MAX_COMPONENT_WORKERS
105
+
106
+ def _timeout_for_spec() -> Optional[int]:
107
+ if deadline is None:
108
+ return None
109
+ # F-NEW-3: the wall-clock deadline must constrain the subprocess
110
+ # itself — a call started at t=0.9 must not run the full 120s
111
+ # default. Shrink the timeout to the remaining budget
112
+ # (MIN_REVIEWER_TIMEOUT_SEC floor, 120s ceiling).
113
+ return min(120, max(qp.MIN_REVIEWER_TIMEOUT_SEC, int(deadline - time.monotonic())))
114
+
115
+ def _invoke_one(spec: CallSpec) -> ReviewArtifact:
116
+ if deadline is not None and (deadline - time.monotonic()) < qp.MIN_REVIEWER_TIMEOUT_SEC:
117
+ return qp._error_artifact(
118
+ spec.reviewer_id,
119
+ spec.role,
120
+ spec.model,
121
+ spec.component_id,
122
+ "insufficient remaining wall clock budget",
123
+ )
124
+ try:
125
+ raw = qp._invoke_reviewer(
126
+ spec.prompt,
127
+ spec.model,
128
+ workspace_root,
129
+ timeout_sec=_timeout_for_spec(),
130
+ )
131
+ return qp._raw_to_artifact(
132
+ raw,
133
+ reviewer_id=spec.reviewer_id,
134
+ role=spec.role,
135
+ model=spec.model,
136
+ component_id=spec.component_id,
137
+ component_files=spec.component_files,
138
+ )
139
+ except Exception:
140
+ return qp._error_artifact(
141
+ spec.reviewer_id,
142
+ spec.role,
143
+ spec.model,
144
+ spec.component_id,
145
+ "reviewer invocation failure",
146
+ )
147
+
148
+ # Phase 7: calls grouped into waves by ProviderScheduler (per-provider
149
+ # concurrency). Within a wave, run independent reviewer invocations
150
+ # concurrently (bounded by _MAX_COMPONENT_WORKERS), then collect results
151
+ # in deterministic spec order so aggregation/arbitration is stable.
152
+ for wave in waves:
153
+ order = list(wave.calls)
154
+ results: Dict[str, ReviewArtifact] = {}
155
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as pool:
156
+ futures = {spec.call_id: pool.submit(_invoke_one, spec) for spec in wave.calls}
157
+ for call_id, future in futures.items():
158
+ try:
159
+ results[call_id] = future.result()
160
+ except Exception:
161
+ spec = next(s for s in wave.calls if s.call_id == call_id)
162
+ results[call_id] = qp._error_artifact(
163
+ spec.reviewer_id,
164
+ spec.role,
165
+ spec.model,
166
+ spec.component_id,
167
+ "reviewer invocation failure",
168
+ )
169
+ artifacts.extend(results[spec.call_id] for spec in order)
170
+
171
+ return artifacts
172
+
173
+
174
+ # ── Public API ────────────────────────────────────────────────────────────
175
+
176
+
177
+ def _apply_quality_spec_gates(verdict, quality_spec):
178
+ """Enforce deterministic quality_spec gates on a legacy-path verdict.
179
+
180
+ NEW-4: synthesize_artifacts enforces hard_failures/minimum_score/
181
+ minimum_counts for panel/component dispatch, but a budget-degraded plan
182
+ routes to legacy run_qc_review which never synthesizes. Apply the same
183
+ fail-closed gates here so degradation cannot bypass them.
184
+ """
185
+ if not isinstance(quality_spec, dict) or not quality_spec:
186
+ return verdict
187
+ issues = verdict.issues if isinstance(verdict.issues, list) else []
188
+
189
+ hard = quality_spec.get("hard_failures") or []
190
+ if isinstance(hard, list):
191
+ for hf in hard:
192
+ if (
193
+ isinstance(hf, str)
194
+ and hf
195
+ and any(
196
+ hf.lower() in str(i.get("description") or i.get("claim") or "").lower()
197
+ or hf.lower() in str(i.get("path") or "").lower()
198
+ for i in issues
199
+ if isinstance(i, dict)
200
+ )
201
+ ):
202
+ verdict.passed = False
203
+ verdict.status = VERDICT_REJECT
204
+ verdict.reason = f"quality_spec hard failure: {hf}"
205
+ return verdict
206
+
207
+ try:
208
+ min_score = float(quality_spec.get("minimum_score", 0.0) or 0.0)
209
+ except (TypeError, ValueError, OverflowError):
210
+ min_score = 0.0
211
+ min_counts = quality_spec.get("minimum_counts") or {}
212
+ if not isinstance(min_counts, dict):
213
+ min_counts = {}
214
+ try:
215
+ required_issues = int(min_counts.get("issues", 0) or 0)
216
+ except (TypeError, ValueError):
217
+ required_issues = 0
218
+
219
+ unmet = []
220
+ if min_score > 0 and verdict.score < min_score:
221
+ unmet.append(f"score {verdict.score:.2f} below minimum_score {min_score}")
222
+ if required_issues > 0 and len(issues) < required_issues:
223
+ unmet.append(f"issues {len(issues)} below minimum_counts.issues {required_issues}")
224
+ if unmet:
225
+ # Downgrade PASS to CONDITIONAL_PASS — same semantics as synthesis.
226
+ verdict.passed = False
227
+ verdict.status = VERDICT_CONDITIONAL_PASS
228
+ verdict.reason = "; ".join(unmet)
229
+ return verdict
230
+
231
+
232
+ def run_quality_plane(
233
+ contract,
234
+ output_paths: List[str],
235
+ verification_results: List[Dict[str, Any]],
236
+ workspace_root: str,
237
+ quality_plan=None,
238
+ ) -> QualityPlaneVerdict:
239
+ """Evaluate output quality. Gateway for all quality review paths.
240
+
241
+ Phase 1: delegates to legacy run_qc_review(), wraps result in
242
+ QualityPlaneVerdict. Phase 4: when quality_plan.mode is
243
+ COMPONENT_PANEL, uses component slicing dispatch.
244
+
245
+ Returns a QualityPlaneVerdict with fields matching what supervisor
246
+ expects: .passed, .status, .score, .issues, .reason, .to_dict().
247
+ """
248
+ qp_ = quality_plan
249
+ if qp_ is not None:
250
+ errors = validate_quality_plan(qp_)
251
+ if errors:
252
+ return QualityPlaneVerdict(
253
+ passed=False,
254
+ status=VERDICT_ERROR,
255
+ reason="invalid quality plan: " + "; ".join(errors),
256
+ budget_used={"llm_calls": 0, "elapsed_sec": 0.0},
257
+ )
258
+ # Gateway-authoritative budget: degrade here so direct callers get
259
+ # the same protection as the supervisor path (F3).
260
+ max_calls = qp_.budget.max_llm_calls
261
+ if max_calls is not None and qp_.estimate_calls() > max_calls:
262
+ _pre_degrade_mode = qp_.mode
263
+ qp_ = qp_.degraded_copy()
264
+ # An EXPLICIT panel/component-panel plan
265
+ # must not silently degrade at all — that is a mandatory-panel
266
+ # downgrade. Hard block instead.
267
+ if (
268
+ qp_.degraded
269
+ and _pre_degrade_mode in (MODE_PANEL, MODE_COMPONENT_PANEL)
270
+ and getattr(contract, "quality_plan", None)
271
+ ):
272
+ return QualityPlaneVerdict(
273
+ passed=False,
274
+ status=VERDICT_ERROR,
275
+ reason=(
276
+ "mandatory QC panel cannot be degraded "
277
+ f"({_pre_degrade_mode} -> {qp_.mode}; budget {max_calls} insufficient: {qp_.degrade_reason})"
278
+ ),
279
+ budget_used={"llm_calls": 0, "elapsed_sec": 0.0},
280
+ )
281
+
282
+ # F-NEW-6: the effective (possibly degraded) plan state must reach the
283
+ # emitted verdict — a silent degradation to legacy single-reviewer QC
284
+ # must be auditable.
285
+ degraded = bool(getattr(qp_, "degraded", False)) if qp_ is not None else False
286
+ degrade_reason = getattr(qp_, "degrade_reason", "") if qp_ is not None else ""
287
+
288
+ if qp_ is not None and qp_.mode == MODE_COMPONENT_PANEL:
289
+ verdict = _run_component_quality_plane(
290
+ contract,
291
+ output_paths,
292
+ verification_results,
293
+ workspace_root,
294
+ qp_,
295
+ )
296
+ elif qp_ is not None and qp_.mode == MODE_PANEL:
297
+ verdict = _run_panel_quality_plane(
298
+ contract,
299
+ output_paths,
300
+ verification_results,
301
+ workspace_root,
302
+ qp_,
303
+ )
304
+ elif qp_ is not None and qp_.mode != MODE_SINGLE:
305
+ # Any other non-None mode is an unsupported configuration error:
306
+ # never silently fall back to legacy QC (F1).
307
+ return QualityPlaneVerdict(
308
+ passed=False,
309
+ status=VERDICT_ERROR,
310
+ reason=f"unsupported mode: {qp_.mode}",
311
+ budget_used={"llm_calls": 0, "elapsed_sec": 0.0},
312
+ )
313
+ else:
314
+ # Legacy path (SINGLE or no plan)
315
+ qc_result = qp.run_qc_review(contract, output_paths, verification_results, workspace_root)
316
+ qc_model = _select_qc_model(contract)
317
+ worker_model = contract.worker.get("model", "unknown") if hasattr(contract, "worker") else "unknown"
318
+
319
+ verdict = QualityPlaneVerdict.from_qc_verdict(qc_result)
320
+ verdict.add_model_metadata(qc_model=qc_model, worker_model=worker_model)
321
+ # NEW-4: a budget-degraded plan can route to legacy single QC, which
322
+ # never runs synthesize_artifacts — enforce the deterministic
323
+ # quality_spec gates here so degradation cannot bypass them.
324
+ _apply_quality_spec_gates(verdict, getattr(contract, "quality_spec", None))
325
+
326
+ verdict.degraded = degraded
327
+ verdict.degrade_reason = degrade_reason
328
+ return verdict
329
+
330
+
331
+ def _run_panel_quality_plane(
332
+ contract,
333
+ output_paths: List[str],
334
+ verification_results: List[Dict[str, Any]],
335
+ workspace_root: str,
336
+ quality_plan: QualityPlan,
337
+ ) -> QualityPlaneVerdict:
338
+ """Run the panel review path: the full output set as one component,
339
+ reviewed by up to max_reviewers_per_component persona reviewers.
340
+
341
+ Phase 5 semantics: distinct personas over the same files, synthesis,
342
+ and optional arbitration on disagreement.
343
+ """
344
+ scheduler = ProviderScheduler()
345
+
346
+ component = ComponentSlice(id="component_0", files=list(output_paths))
347
+
348
+ deadline = qp._deadline_for(quality_plan)
349
+ artifacts = _run_component_reviews(
350
+ contract,
351
+ [component],
352
+ verification_results,
353
+ workspace_root,
354
+ quality_plan,
355
+ scheduler=scheduler,
356
+ deadline=deadline,
357
+ )
358
+
359
+ return qp._component_verdict_to_qp_verdict(
360
+ artifacts,
361
+ [component],
362
+ quality_plan,
363
+ workspace_root,
364
+ scheduler=scheduler,
365
+ deadline=deadline,
366
+ quality_spec=getattr(contract, "quality_spec", {}),
367
+ )
368
+
369
+
370
+ def _validate_explicit_components(
371
+ declared_components,
372
+ output_paths,
373
+ workspace_root,
374
+ max_components,
375
+ ):
376
+ """Validate explicit components as an exact, workspace-confined output partition.
377
+
378
+ Returns (list[ComponentSlice], list[str] errors). On any error the slices
379
+ list is empty (fail-closed) so callers cannot proceed with a partial or
380
+ escaping partition. Confinement uses realpath + commonpath against the
381
+ workspace root and is independent of contract scope allow-lists.
382
+ """
383
+ import os
384
+
385
+ errors = []
386
+ if not isinstance(declared_components, list) or not declared_components:
387
+ return [], ["explicit components must be a non-empty list"]
388
+
389
+ if not isinstance(max_components, int) or max_components < 1:
390
+ return [], ["max_components must be a positive integer"]
391
+
392
+ if len(declared_components) > max_components:
393
+ return [], [f"explicit component count {len(declared_components)} exceeds max_components {max_components}"]
394
+
395
+ canonical_workspace_root = os.path.normcase(os.path.realpath(workspace_root))
396
+
397
+ def canonicalize_and_confine(path, label):
398
+ try:
399
+ canonical_path = os.path.normcase(os.path.realpath(path))
400
+ if os.path.commonpath([canonical_path, canonical_workspace_root]) != canonical_workspace_root:
401
+ errors.append(f"{label} outside workspace root: {path!r}")
402
+ return None
403
+ return canonical_path
404
+ except ValueError:
405
+ errors.append(f"{label} cannot compare with workspace root (different drives or invalid path): {path!r}")
406
+ return None
407
+
408
+ canonical_outputs = {}
409
+ for output_path in output_paths:
410
+ canonical_output = canonicalize_and_confine(
411
+ output_path,
412
+ "output path",
413
+ )
414
+ if canonical_output is None:
415
+ continue
416
+ if canonical_output in canonical_outputs:
417
+ errors.append(f"duplicate declared output after canonicalization: {output_path!r}")
418
+ continue
419
+ canonical_outputs[canonical_output] = output_path
420
+
421
+ if errors:
422
+ return [], errors
423
+
424
+ seen_component_ids = set()
425
+ seen_files = {}
426
+ slices = []
427
+
428
+ for index, component in enumerate(declared_components):
429
+ if not isinstance(component, dict):
430
+ errors.append(f"component {index} must be a dict")
431
+ continue
432
+
433
+ component_id = component.get("id")
434
+ files = component.get("files")
435
+ description = component.get("description", "")
436
+
437
+ if not isinstance(component_id, str) or not component_id.strip():
438
+ errors.append(f"component {index} has invalid id")
439
+ continue
440
+ if component_id in seen_component_ids:
441
+ errors.append(f"duplicate component id: {component_id!r}")
442
+ continue
443
+ seen_component_ids.add(component_id)
444
+
445
+ if not isinstance(files, list) or not files:
446
+ errors.append(f"component {component_id!r} must declare a non-empty files list")
447
+ continue
448
+ if not isinstance(description, str):
449
+ errors.append(f"component {component_id!r} description must be a string")
450
+ continue
451
+
452
+ slice_files = []
453
+ component_seen = set()
454
+ for declared_file in files:
455
+ if not isinstance(declared_file, str) or not declared_file:
456
+ errors.append(f"component {component_id!r} contains an invalid file path")
457
+ continue
458
+
459
+ resolved_file = (
460
+ declared_file if os.path.isabs(declared_file) else os.path.join(workspace_root, declared_file)
461
+ )
462
+ canonical_file = canonicalize_and_confine(
463
+ resolved_file,
464
+ f"component {component_id!r} file",
465
+ )
466
+ if canonical_file is None:
467
+ continue
468
+
469
+ if canonical_file not in canonical_outputs:
470
+ errors.append(f"component {component_id!r} references unknown output: {declared_file!r}")
471
+ continue
472
+
473
+ if canonical_file in component_seen:
474
+ errors.append(f"component {component_id!r} repeats file: {declared_file!r}")
475
+ continue
476
+ component_seen.add(canonical_file)
477
+
478
+ previous_component = seen_files.get(canonical_file)
479
+ if previous_component is not None:
480
+ errors.append(
481
+ f"output {canonical_outputs[canonical_file]!r} appears in both "
482
+ f"{previous_component!r} and {component_id!r}"
483
+ )
484
+ continue
485
+
486
+ seen_files[canonical_file] = component_id
487
+ slice_files.append(canonical_outputs[canonical_file])
488
+
489
+ if slice_files:
490
+ slices.append(
491
+ ComponentSlice(
492
+ id=component_id,
493
+ files=slice_files,
494
+ description=description,
495
+ )
496
+ )
497
+ else:
498
+ errors.append(f"component {component_id!r} is empty")
499
+
500
+ missing_outputs = [
501
+ output_path for canonical_output, output_path in canonical_outputs.items() if canonical_output not in seen_files
502
+ ]
503
+ if missing_outputs:
504
+ errors.append("explicit components omit outputs: " + ", ".join(repr(path) for path in missing_outputs))
505
+
506
+ if errors:
507
+ return [], errors
508
+ return slices, []
509
+
510
+
511
+ def _run_component_quality_plane(
512
+ contract,
513
+ output_paths: List[str],
514
+ verification_results: List[Dict[str, Any]],
515
+ workspace_root: str,
516
+ quality_plan: QualityPlan,
517
+ ) -> QualityPlaneVerdict:
518
+ """Run the component-sliced quality review path."""
519
+ scheduler = ProviderScheduler()
520
+
521
+ if quality_plan.components == "explicit":
522
+ declared_components = getattr(contract, "components", None)
523
+ if not declared_components:
524
+ return QualityPlaneVerdict(
525
+ status=VERDICT_ERROR,
526
+ passed=False,
527
+ reason="invalid explicit components: contract declares no components",
528
+ issues=["contract declares no components for components=explicit"],
529
+ )
530
+ components, component_errors = _validate_explicit_components(
531
+ declared_components,
532
+ output_paths,
533
+ workspace_root,
534
+ quality_plan.budget.max_components,
535
+ )
536
+ if component_errors:
537
+ return QualityPlaneVerdict(
538
+ status=VERDICT_ERROR,
539
+ passed=False,
540
+ reason="invalid explicit components: " + "; ".join(component_errors),
541
+ issues=component_errors,
542
+ )
543
+ else:
544
+ components = slice_components(
545
+ output_paths,
546
+ max_components=quality_plan.budget.max_components,
547
+ base_dir=workspace_root,
548
+ )
549
+
550
+ deadline = qp._deadline_for(quality_plan)
551
+ artifacts = _run_component_reviews(
552
+ contract,
553
+ components,
554
+ verification_results,
555
+ workspace_root,
556
+ quality_plan,
557
+ scheduler=scheduler,
558
+ deadline=deadline,
559
+ )
560
+
561
+ return qp._component_verdict_to_qp_verdict(
562
+ artifacts,
563
+ components,
564
+ quality_plan,
565
+ workspace_root,
566
+ scheduler=scheduler,
567
+ deadline=deadline,
568
+ quality_spec=getattr(contract, "quality_spec", {}),
569
+ )
@@ -0,0 +1,87 @@
1
+ """Verified QC overrule — tamper-evidence binding to already-recorded output.
2
+
3
+ The verifier does NOT re-execute any command and does not touch the
4
+ workspace. It binds operator-supplied overrule evidence to the
5
+ verification evidence the supervisor already recorded
6
+ (<task_dir>/verification_evidence.json). Pure function, no side effects.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import hmac
13
+ from typing import List, Tuple
14
+
15
+
16
+ def verify_overrule(
17
+ evidence: dict,
18
+ secret: str,
19
+ verification_evidence: dict,
20
+ ) -> Tuple[bool, List[str]]:
21
+ """Verify operator overrule evidence against recorded verification output.
22
+
23
+ The out-of-band secret is validated by the caller (supervisor) against
24
+ the run-scoped secret hash BEFORE this function is invoked; here we only
25
+ require the evidence to carry a non-empty secret field so the binding is
26
+ structurally complete. The following must all hold:
27
+
28
+ 1. evidence is a dict with a non-empty string 'secret' field.
29
+ 2. verification_evidence is a dict with a verification_results list.
30
+ 3. evidence.check_id references an existing verification result.
31
+ 4. sha256(recorded stdout) == evidence.stdout_hash (64 hex chars).
32
+ 5. evidence.assertions is a non-empty list of non-empty strings.
33
+
34
+ Returns (True, []) on success, else (False, errors).
35
+ """
36
+ errors: List[str] = []
37
+
38
+ if not isinstance(evidence, dict):
39
+ return False, ["evidence must be a dict"]
40
+ if not isinstance(secret, str) or not secret.strip():
41
+ return False, ["secret must be a non-empty string"]
42
+
43
+ if not isinstance(verification_evidence, dict):
44
+ return False, ["verification_evidence must be a dict"]
45
+ results = verification_evidence.get("verification_results")
46
+ if not isinstance(results, list):
47
+ return False, ["verification_evidence.verification_results must be a list"]
48
+
49
+ check_id = evidence.get("check_id")
50
+ if not isinstance(check_id, str) or not check_id:
51
+ errors.append("evidence.check_id must be a non-empty string")
52
+
53
+ recorded_result = None
54
+ for result in results:
55
+ if isinstance(result, dict) and result.get("check_id") == check_id:
56
+ recorded_result = result
57
+ break
58
+ if recorded_result is None:
59
+ errors.append(f"check_id {check_id!r} not found in verification results")
60
+
61
+ stdout_hash = evidence.get("stdout_hash")
62
+ if not isinstance(stdout_hash, str) or len(stdout_hash) != 64:
63
+ errors.append("evidence.stdout_hash must be a 64-char sha256 hex digest")
64
+ else:
65
+ try:
66
+ bytes.fromhex(stdout_hash)
67
+ except ValueError:
68
+ errors.append("evidence.stdout_hash is not valid hex")
69
+ stdout_hash = None
70
+
71
+ assertions = evidence.get("assertions")
72
+ if not isinstance(assertions, list) or not assertions:
73
+ errors.append("evidence.assertions must be a non-empty list")
74
+ elif not all(isinstance(a, str) and a.strip() for a in assertions):
75
+ errors.append("every assertion must be a non-empty string")
76
+
77
+ if recorded_result is not None and stdout_hash:
78
+ recorded_stdout = recorded_result.get("stdout", "")
79
+ if not isinstance(recorded_stdout, str):
80
+ recorded_stdout = str(recorded_stdout)
81
+ recorded_hash = hashlib.sha256(recorded_stdout.encode("utf-8")).hexdigest()
82
+ if not hmac.compare_digest(recorded_hash, stdout_hash):
83
+ errors.append("stdout_hash does not match recorded verification stdout")
84
+
85
+ if errors:
86
+ return False, errors
87
+ return True, []