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,153 @@
1
+ """orchestrator.qc — quality-plane package.
2
+
3
+ Extracted from the former flat orchestrator/quality_plane.py (~1350 lines)
4
+ as a pure structural refactor with an identical public surface:
5
+
6
+ personas reviewer invocation transport, persona prompts, typed ERROR
7
+ artifacts, model-policy resolution
8
+ parsing strict raw-response -> ReviewArtifact normalization, path and
9
+ evidence normalization, plan wall-clock deadlines
10
+ aggregator artifact synthesis into QualityPlaneVerdict, component
11
+ ranking, arbitration policy/prompt/execution
12
+ runner run_quality_plane strategy gateway (single / panel /
13
+ component-panel), reviewer dispatch, explicit-component
14
+ validation, quality_spec gates
15
+
16
+ QualityPlane is the only NEW symbol: a facade over the runner entrypoints.
17
+ Backward compatibility flows through orchestrator.quality_plane, which
18
+ lazily resolves names into this package while remaining the live patch
19
+ target for monkeypatched tests.
20
+ """
21
+
22
+ from typing import Any, Dict, List
23
+
24
+ from .aggregator import (
25
+ _build_arbitration_prompt,
26
+ _component_verdict_to_qp_verdict,
27
+ _run_arbitration,
28
+ _should_arbitrate,
29
+ _synthesis_reason,
30
+ )
31
+ from .parsing import (
32
+ _deadline_for,
33
+ _norm_path,
34
+ _normalize_issue_evidence,
35
+ _parse_reviewer_response,
36
+ _raw_to_arbitration_verdict,
37
+ _raw_to_artifact,
38
+ )
39
+ from .personas import (
40
+ _PAID_MODEL_MARKERS,
41
+ _REVIEWER_HOOK,
42
+ MIN_REVIEWER_TIMEOUT_SEC,
43
+ _build_persona_prompt,
44
+ _error_artifact,
45
+ _extract_prompt_paths,
46
+ _fake_raw_response,
47
+ _invoke_reviewer,
48
+ _resolve_arbitration_model,
49
+ _resolve_reviewer_model,
50
+ )
51
+ from .runner import (
52
+ _MAX_COMPONENT_WORKERS,
53
+ _apply_quality_spec_gates,
54
+ _run_component_quality_plane,
55
+ _run_component_reviews,
56
+ _run_panel_quality_plane,
57
+ _validate_explicit_components,
58
+ run_quality_plane,
59
+ )
60
+
61
+
62
+ class QualityPlane:
63
+ """Facade over the quality-plane runner entrypoints.
64
+
65
+ Provided for backward compatibility and object-shaped access to the
66
+ review strategies; it adds no behavior of its own and delegates every
67
+ call to the module-level functions in orchestrator.qc.runner. New code
68
+ may use either this facade or the runner entrypoints directly.
69
+ """
70
+
71
+ @staticmethod
72
+ def run(
73
+ contract,
74
+ output_paths: List[str],
75
+ verification_results: List[Dict[str, Any]],
76
+ workspace_root: str,
77
+ quality_plan=None,
78
+ ):
79
+ """Evaluate output quality via run_quality_plane (any plan mode)."""
80
+ return run_quality_plane(
81
+ contract,
82
+ output_paths,
83
+ verification_results,
84
+ workspace_root,
85
+ quality_plan=quality_plan,
86
+ )
87
+
88
+ @staticmethod
89
+ def run_panel(
90
+ contract,
91
+ output_paths: List[str],
92
+ verification_results: List[Dict[str, Any]],
93
+ workspace_root: str,
94
+ quality_plan,
95
+ ):
96
+ """Force the multi-persona panel review path."""
97
+ return _run_panel_quality_plane(
98
+ contract,
99
+ output_paths,
100
+ verification_results,
101
+ workspace_root,
102
+ quality_plan,
103
+ )
104
+
105
+ @staticmethod
106
+ def run_component(
107
+ contract,
108
+ output_paths: List[str],
109
+ verification_results: List[Dict[str, Any]],
110
+ workspace_root: str,
111
+ quality_plan,
112
+ ):
113
+ """Force the component-sliced panel review path."""
114
+ return _run_component_quality_plane(
115
+ contract,
116
+ output_paths,
117
+ verification_results,
118
+ workspace_root,
119
+ quality_plan,
120
+ )
121
+
122
+
123
+ __all__ = [
124
+ "MIN_REVIEWER_TIMEOUT_SEC",
125
+ "QualityPlane",
126
+ "run_quality_plane",
127
+ "_MAX_COMPONENT_WORKERS",
128
+ "_PAID_MODEL_MARKERS",
129
+ "_REVIEWER_HOOK",
130
+ "_apply_quality_spec_gates",
131
+ "_build_arbitration_prompt",
132
+ "_build_persona_prompt",
133
+ "_component_verdict_to_qp_verdict",
134
+ "_deadline_for",
135
+ "_error_artifact",
136
+ "_extract_prompt_paths",
137
+ "_fake_raw_response",
138
+ "_invoke_reviewer",
139
+ "_norm_path",
140
+ "_normalize_issue_evidence",
141
+ "_parse_reviewer_response",
142
+ "_raw_to_arbitration_verdict",
143
+ "_raw_to_artifact",
144
+ "_resolve_arbitration_model",
145
+ "_resolve_reviewer_model",
146
+ "_run_arbitration",
147
+ "_run_component_quality_plane",
148
+ "_run_component_reviews",
149
+ "_run_panel_quality_plane",
150
+ "_should_arbitrate",
151
+ "_synthesis_reason",
152
+ "_validate_explicit_components",
153
+ ]
@@ -0,0 +1,330 @@
1
+ """Synthesis and arbitration layer for the quality plane.
2
+
3
+ Extracted verbatim from the former flat orchestrator/quality_plane.py:
4
+ per-component artifact synthesis into a QualityPlaneVerdict, worst-case
5
+ component ranking, arbitration trigger policy, arbiter prompt building,
6
+ and arbitration execution.
7
+
8
+ Shared collaborators are resolved through the ``orchestrator.quality_plane``
9
+ compat namespace (``qp``) at call time so patches applied there stay live.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import time
15
+ from typing import List, Optional
16
+
17
+ from orchestrator import quality_plane as qp
18
+
19
+ from ..component_slicer import ComponentSlice
20
+ from ..provider_scheduler import ProviderScheduler
21
+ from ..qc_review import _redact_secrets
22
+ from ..quality_plan import QualityPlan
23
+ from ..review_artifact import (
24
+ VERDICT_CONDITIONAL_PASS,
25
+ VERDICT_ERROR,
26
+ VERDICT_INSUFFICIENT_EVIDENCE,
27
+ VERDICT_PASS,
28
+ VERDICT_REJECT,
29
+ ArbitrationVerdict,
30
+ QualityPlaneVerdict,
31
+ ReviewArtifact,
32
+ synthesize_artifacts,
33
+ )
34
+
35
+
36
+ def _component_verdict_to_qp_verdict(
37
+ artifacts: List[ReviewArtifact],
38
+ components: List[ComponentSlice],
39
+ quality_plan: QualityPlan,
40
+ workspace_root: str = "",
41
+ scheduler: Optional[ProviderScheduler] = None,
42
+ deadline: Optional[float] = None,
43
+ quality_spec: Optional[dict] = None,
44
+ ) -> QualityPlaneVerdict:
45
+ """Synthesize per-component artifacts into a single QualityPlaneVerdict.
46
+
47
+ Phase 6: optionally runs arbitration when enabled in quality_plan.
48
+ Phase 7: attaches scheduler usage to budget_used.
49
+ """
50
+ synthesis = synthesize_artifacts(artifacts, quality_spec=quality_spec)
51
+
52
+ arbitration_result = None
53
+ arbitration_skipped = False
54
+ arbitration_skip_reason = "budget exhausted"
55
+ budget_calls = len(artifacts)
56
+ resolved_component_ids = set()
57
+
58
+ if qp._should_arbitrate(artifacts, synthesis, quality_plan.arbitration):
59
+ max_calls = quality_plan.budget.max_llm_calls
60
+ if max_calls is None or budget_calls + 1 <= max_calls:
61
+ if deadline is not None and time.monotonic() + 1 >= deadline:
62
+ # F3/N3: arbitration must not run past the plan's wall-clock
63
+ # budget — skip when fewer than 1s remains (an invocation
64
+ # needs at least a full second to be safe).
65
+ arbitration_skipped = True
66
+ arbitration_skip_reason = "wall-clock deadline exhausted"
67
+ else:
68
+ arbitration_result = qp._run_arbitration(
69
+ artifacts,
70
+ synthesis,
71
+ quality_plan.arbitration,
72
+ workspace_root,
73
+ deadline=deadline,
74
+ )
75
+ # A failed reviewer call (ERROR artifact) is never curable by
76
+ # arbitration: the synthesis ERROR verdict must stand. Both the
77
+ # PASS and REJECT overrides are inert in that case.
78
+ has_error = any(a.verdict == VERDICT_ERROR for a in artifacts)
79
+ if arbitration_result is None:
80
+ pass # arbitration skipped (deadline or budget exhausted)
81
+ elif arbitration_result.status == VERDICT_PASS:
82
+ # Claim-scoped override: an arbiter PASS may only clear P0
83
+ # blockers whose claims it explicitly addresses in
84
+ # winning_claims. Uncovered blockers stay active (fail-closed).
85
+ # F-NEW-4: an arbiter PASS must never promote a non-REJECT
86
+ # synthesis state (INSUFFICIENT_EVIDENCE, CONDITIONAL_PASS) to
87
+ # PASS — it only resolves an actual P0-based rejection.
88
+ if not has_error and synthesis.status == VERDICT_REJECT and synthesis.p0_blockers:
89
+ blocker_claims = [b.claim for b in synthesis.p0_blockers if b.claim]
90
+ winning_claims = arbitration_result.winning_claims or []
91
+ # Claim-scoped containment (N4): an arbiter PASS may only
92
+ # clear P0 blockers whose claims it explicitly addresses in
93
+ # winning_claims. No confidence-based blanket override.
94
+ covered = all(
95
+ any(
96
+ winning.lower() in claim.lower() or claim.lower() in winning.lower()
97
+ for winning in winning_claims
98
+ if isinstance(winning, str)
99
+ )
100
+ for claim in blocker_claims
101
+ )
102
+ if covered:
103
+ synthesis.status = VERDICT_PASS
104
+ synthesis.p0_blockers = []
105
+ # N4: only components whose artifacts contributed a
106
+ # covered claim are resolved by the arbiter PASS;
107
+ # unrelated components keep their own verdicts.
108
+ winning_lower = [w.lower() for w in winning_claims if isinstance(w, str)]
109
+ for a in artifacts:
110
+ if not a.component_id or a.verdict == VERDICT_PASS:
111
+ continue
112
+ if any(
113
+ isinstance(i.claim, str)
114
+ and i.claim
115
+ and any(i.claim.lower() in w for w in winning_lower)
116
+ for i in a.issues
117
+ ):
118
+ resolved_component_ids.add(a.component_id)
119
+ elif synthesis.p0_blockers:
120
+ synthesis.status = VERDICT_REJECT
121
+ elif arbitration_result.status == VERDICT_REJECT and synthesis.status not in (
122
+ VERDICT_REJECT,
123
+ VERDICT_ERROR,
124
+ ):
125
+ synthesis.status = VERDICT_REJECT
126
+ # N4: the arbiter REJECT resolves the disputed components
127
+ # (any component with a non-PASS artifact); components that
128
+ # passed cleanly keep their own verdicts.
129
+ resolved_component_ids = {
130
+ a.component_id for a in artifacts if a.component_id and a.verdict != VERDICT_PASS
131
+ }
132
+ else:
133
+ arbitration_skipped = True
134
+
135
+ # Group artifacts by component_id for component-level summaries
136
+ comp_artifacts: dict = {}
137
+ for a in artifacts:
138
+ cid = a.component_id
139
+ comp_artifacts.setdefault(cid, []).append(a)
140
+
141
+ # Order-independent worst-case verdict ranking (permutation-invariant)
142
+ rank = {
143
+ VERDICT_ERROR: 5,
144
+ VERDICT_REJECT: 4,
145
+ VERDICT_CONDITIONAL_PASS: 3,
146
+ VERDICT_INSUFFICIENT_EVIDENCE: 2,
147
+ VERDICT_PASS: 1,
148
+ }
149
+
150
+ component_verdicts = []
151
+ for c in components:
152
+ c_artifacts = comp_artifacts.get(c.id, [])
153
+ if c_artifacts:
154
+ statuses = [a.verdict for a in c_artifacts]
155
+ raw_worst = max(statuses, key=lambda s: rank.get(s, 0))
156
+ scores = [a.confidence for a in c_artifacts if a.confidence > 0]
157
+ avg_score = sum(scores) / len(scores) if scores else 0.0
158
+ all_issues = []
159
+ for a in c_artifacts:
160
+ all_issues.extend(i.to_dict() for i in a.issues)
161
+ entry = {
162
+ "component_id": c.id,
163
+ # N4: arbitration resolution is component-scoped. Only
164
+ # components whose claims the arbiter resolved receive the
165
+ # global synthesis status; unrelated components keep their
166
+ # own worst-case verdict (component-level truth preserved).
167
+ "status": synthesis.status if (arbitration_result and c.id in resolved_component_ids) else raw_worst,
168
+ "raw_status": raw_worst,
169
+ "score": round(avg_score, 4),
170
+ "issues": all_issues,
171
+ "files": c.files,
172
+ "reviewers": [a.role for a in c_artifacts],
173
+ }
174
+ if arbitration_result and c.id in resolved_component_ids:
175
+ # Resolved status reflects arbitration when it ran (F2):
176
+ # a top-level PASS with component-level REJECT is a
177
+ # contradictory audit record. raw_status preserves the
178
+ # pre-arbitration worst-case for audit.
179
+ entry["arbitrated"] = True
180
+ component_verdicts.append(entry)
181
+
182
+ passed = synthesis.status == VERDICT_PASS
183
+ if arbitration_result:
184
+ budget_calls += 1
185
+ provider_usage = scheduler.usage_summary() if scheduler else {}
186
+ budget_used = {"llm_calls": budget_calls, "elapsed_sec": 0.0}
187
+ if provider_usage:
188
+ budget_used["provider_usage"] = provider_usage
189
+ reason = _synthesis_reason(synthesis.status, passed, synthesis.p0_blockers, synthesis.p1_required_fixes)
190
+ if arbitration_skipped:
191
+ # NEW-8: report the ACTUAL skip cause — deadline exhaustion is not
192
+ # the same audit signal as budget exhaustion.
193
+ reason += f"; arbitration skipped: {arbitration_skip_reason}"
194
+ return QualityPlaneVerdict(
195
+ passed=passed,
196
+ status=synthesis.status,
197
+ score=synthesis.score,
198
+ reason=reason,
199
+ issues=[i.to_dict() for i in synthesis.merged_issues],
200
+ component_verdicts=component_verdicts,
201
+ review_artifacts=[a.to_dict() for a in artifacts],
202
+ synthesis_result=synthesis.to_dict(),
203
+ arbitration_result=arbitration_result.to_dict() if arbitration_result else None,
204
+ budget_used=budget_used,
205
+ )
206
+
207
+
208
+ def _synthesis_reason(status: str, passed: bool, p0_blockers: list, p1_fixes: list) -> str:
209
+ """Build a one-line reason string from synthesis results."""
210
+ if status == VERDICT_ERROR:
211
+ return "quality review failed"
212
+ if status == VERDICT_INSUFFICIENT_EVIDENCE:
213
+ return "No reviewer examined evidence"
214
+ if p0_blockers:
215
+ return f"{len(p0_blockers)} P0 blocker(s) found"
216
+ if p1_fixes:
217
+ return f"{len(p1_fixes)} P1 required fix(es) found"
218
+ return "All components passed review"
219
+
220
+
221
+ # ── Arbitration ─────────────────────────────────────────────────────────────
222
+
223
+
224
+ def _should_arbitrate(
225
+ artifacts: List[ReviewArtifact],
226
+ synthesis,
227
+ arbitration_policy,
228
+ ) -> bool:
229
+ """Check if arbitration should be triggered based on synthesis results."""
230
+ if not arbitration_policy.enabled:
231
+ return False
232
+ triggers = set(arbitration_policy.trigger)
233
+
234
+ if "p0_disagreement" in triggers and synthesis.p0_blockers:
235
+ # P0 found — check if reviewers disagree on which issues are P0
236
+ return True
237
+
238
+ if "low_confidence" in triggers:
239
+ avg_conf = sum(a.confidence for a in artifacts) / max(len(artifacts), 1)
240
+ if avg_conf < 0.5:
241
+ return True
242
+ # Also trigger if any reviewer confidence is below threshold
243
+ if any(a.confidence < 0.3 for a in artifacts if a.has_evidence()):
244
+ return True
245
+
246
+ if "any_reject" in triggers:
247
+ if any(a.verdict in (VERDICT_REJECT, "ERROR") for a in artifacts):
248
+ return True
249
+
250
+ return False
251
+
252
+
253
+ def _build_arbitration_prompt(
254
+ artifacts: List[ReviewArtifact],
255
+ synthesis,
256
+ ) -> str:
257
+ """Build a prompt asking the arbiter to resolve reviewer disagreements."""
258
+ lines = [
259
+ "You are an impartial arbitration reviewer. Multiple reviewers have evaluated the same work",
260
+ "and disagree. Review the disagreements below and determine the correct outcome.",
261
+ "",
262
+ "Respond with ONLY a JSON object:",
263
+ ' {"status": "PASS" or "REJECT" or "CONDITIONAL_PASS",',
264
+ ' "reason": "short explanation of your decision",',
265
+ ' "confidence": 0.0-1.0,',
266
+ ' "winning_claims": ["claim1", ...],',
267
+ ' "discarded_claims": ["claim2", ...]}',
268
+ "",
269
+ "=== REVIEWER DISAGREEMENTS ===",
270
+ ]
271
+
272
+ for i, a in enumerate(artifacts):
273
+ lines.append(f"\n--- Reviewer {i + 1}: {a.role} (confidence={a.confidence}) ---")
274
+ lines.append(f" Verdict: {a.verdict}")
275
+ for issue in a.issues:
276
+ lines.append(f" [{issue.severity}] {issue.claim} (evidence: {issue.evidence or 'none'})")
277
+ if a.dissent:
278
+ lines.append(f" Dissent: {'; '.join(a.dissent)}")
279
+
280
+ if synthesis.p0_blockers:
281
+ lines.append("\n=== P0 BLOCKERS FROM SYNTHESIS ===")
282
+ for b in synthesis.p0_blockers:
283
+ lines.append(f" [{b.severity}] {b.claim}")
284
+
285
+ if synthesis.p1_required_fixes:
286
+ lines.append("\n=== P1 REQUIRED FIXES ===")
287
+ for f in synthesis.p1_required_fixes:
288
+ lines.append(f" [{f.severity}] {f.claim}")
289
+
290
+ lines.append("")
291
+ lines.append("Based on the above, what is the correct final verdict?")
292
+ # N7: reviewer claims/evidence/dissent can surface secrets — redact the
293
+ # complete arbitration prompt before it is transmitted externally.
294
+ return _redact_secrets("\n".join(lines))
295
+
296
+
297
+ def _run_arbitration(
298
+ artifacts: List[ReviewArtifact],
299
+ synthesis,
300
+ arbitration_policy,
301
+ workspace_root: str,
302
+ deadline: Optional[float] = None,
303
+ ) -> ArbitrationVerdict:
304
+ """Run arbitration over conflicting artifacts, return an ArbitrationVerdict."""
305
+ model = qp._resolve_arbitration_model(arbitration_policy)
306
+ prompt = _build_arbitration_prompt(artifacts, synthesis)
307
+
308
+ timeout_sec = None
309
+ if deadline is not None:
310
+ remaining = deadline - time.monotonic()
311
+ if remaining < qp.MIN_REVIEWER_TIMEOUT_SEC:
312
+ return ArbitrationVerdict(
313
+ status=VERDICT_REJECT,
314
+ reason="insufficient remaining wall clock budget for arbitration",
315
+ confidence=0.0,
316
+ )
317
+ timeout_sec = min(120, int(remaining))
318
+
319
+ try:
320
+ raw = qp._invoke_reviewer(prompt, model, workspace_root, timeout_sec=timeout_sec)
321
+ return qp._raw_to_arbitration_verdict(raw)
322
+ except Exception as exc:
323
+ # N1: arbitration must never crash the quality plane — any
324
+ # invocation/parse failure becomes a fail-closed REJECT verdict so
325
+ # the supervisor sees a structured QC outcome, not a task exception.
326
+ return ArbitrationVerdict(
327
+ status=VERDICT_REJECT,
328
+ reason=f"arbitration failure: {exc}",
329
+ confidence=0.0,
330
+ )