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,287 @@
1
+ """Strict response parsing layer for the quality plane.
2
+
3
+ Extracted verbatim from the former flat orchestrator/quality_plane.py:
4
+ path normalization, issue-evidence normalization, fail-closed raw-response
5
+ to ReviewArtifact conversion, plan wall-clock deadlines, and arbitration
6
+ verdict normalization.
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 math
15
+ import re
16
+ import time
17
+ from typing import Any, List, Optional
18
+
19
+ from orchestrator import quality_plane as qp
20
+
21
+ from ..quality_plan import QualityPlan
22
+ from ..review_artifact import (
23
+ VERDICT_CONDITIONAL_PASS,
24
+ VERDICT_ERROR,
25
+ VERDICT_INSUFFICIENT_EVIDENCE,
26
+ VERDICT_PASS,
27
+ VERDICT_REJECT,
28
+ ArbitrationVerdict,
29
+ EvidenceRead,
30
+ ReviewArtifact,
31
+ ReviewIssue,
32
+ )
33
+
34
+
35
+ def _norm_path(path: str) -> str:
36
+ """Normalize separators + drive letter without altering UNC shares (r2)."""
37
+ if not isinstance(path, str):
38
+ return ""
39
+ normalized = path.replace("\\", "/")
40
+ if normalized.startswith("//"):
41
+ return normalized
42
+ if re.match(r"^[A-Za-z]:", normalized):
43
+ return normalized[0].lower() + normalized[1:]
44
+ return normalized
45
+
46
+
47
+ def _normalize_issue_evidence(value: Any) -> str:
48
+ """Normalize structured and legacy reviewer evidence to ReviewIssue text."""
49
+ if isinstance(value, str):
50
+ return value
51
+ if not isinstance(value, dict):
52
+ return str(value) if value is not None else ""
53
+
54
+ path = value.get("path") or value.get("file") or ""
55
+ symbol = value.get("symbol") or value.get("function") or value.get("class") or value.get("function_or_class") or ""
56
+ line_range = value.get("line_range") or value.get("lines") or value.get("line") or ""
57
+ excerpt = value.get("excerpt") or value.get("quote") or value.get("code") or ""
58
+ evidence_type = value.get("type") or value.get("evidence_type") or ""
59
+
60
+ fields = []
61
+ if path:
62
+ fields.append(f"path={path}")
63
+ if symbol:
64
+ fields.append(f"symbol={symbol}")
65
+ if line_range:
66
+ fields.append(f"lines={line_range}")
67
+ if evidence_type:
68
+ fields.append(f"type={evidence_type}")
69
+ if excerpt:
70
+ fields.append(f"excerpt={excerpt}")
71
+ return "; ".join(str(field) for field in fields)
72
+
73
+
74
+ def _parse_reviewer_response(
75
+ raw,
76
+ reviewer_id: str,
77
+ role: str,
78
+ model: str,
79
+ component_id: str,
80
+ component_files: Optional[List[str]] = None,
81
+ ) -> ReviewArtifact:
82
+ """Strictly normalize a raw reviewer response into a ReviewArtifact.
83
+
84
+ Fail-closed: malformed input NEVER raises and NEVER produces a PASS.
85
+ Every schema violation yields a typed ERROR artifact.
86
+ """
87
+ try:
88
+ if not isinstance(raw, dict):
89
+ return qp._error_artifact(
90
+ reviewer_id,
91
+ role,
92
+ model,
93
+ component_id,
94
+ "malformed reviewer response",
95
+ )
96
+
97
+ status = raw.get("status")
98
+ valid_statuses = {
99
+ VERDICT_PASS,
100
+ VERDICT_REJECT,
101
+ VERDICT_CONDITIONAL_PASS,
102
+ VERDICT_INSUFFICIENT_EVIDENCE,
103
+ VERDICT_ERROR,
104
+ }
105
+ if not isinstance(status, str) or status not in valid_statuses:
106
+ return qp._error_artifact(
107
+ reviewer_id,
108
+ role,
109
+ model,
110
+ component_id,
111
+ "unknown status",
112
+ )
113
+
114
+ issues_raw = raw.get("issues", [])
115
+ if not isinstance(issues_raw, list) or any(not isinstance(issue, dict) for issue in issues_raw):
116
+ return qp._error_artifact(
117
+ reviewer_id,
118
+ role,
119
+ model,
120
+ component_id,
121
+ "malformed issues",
122
+ )
123
+
124
+ severity_map = {
125
+ "CRITICAL": "P0",
126
+ "MAJOR": "P1",
127
+ "MINOR": "P2",
128
+ "P0": "P0",
129
+ "P1": "P1",
130
+ "P2": "P2",
131
+ }
132
+ issues = []
133
+ for item in issues_raw:
134
+ raw_severity = item.get("severity")
135
+ if raw_severity not in severity_map:
136
+ # R2-strict: an unknown severity token is a malformed
137
+ # response — fail closed rather than silently downgrading
138
+ # a potential blocker to non-blocking P3.
139
+ return qp._error_artifact(
140
+ reviewer_id,
141
+ role,
142
+ model,
143
+ component_id,
144
+ f"unknown severity: {raw_severity!r}",
145
+ )
146
+ severity = severity_map[raw_severity]
147
+ line_value = item.get("line", 0)
148
+ try:
149
+ line = int(line_value)
150
+ except (TypeError, ValueError, OverflowError):
151
+ line = 0
152
+
153
+ claim = item.get("description") or item.get("claim") or ""
154
+ issues.append(
155
+ ReviewIssue(
156
+ severity=severity,
157
+ path=item.get("path", "") if isinstance(item.get("path", ""), str) else "",
158
+ line=line,
159
+ claim=claim if isinstance(claim, str) else str(claim),
160
+ evidence=_normalize_issue_evidence(item.get("evidence", "")),
161
+ recommended_action=(
162
+ item.get("recommended_action", "")
163
+ if isinstance(item.get("recommended_action", ""), str)
164
+ else ""
165
+ ),
166
+ )
167
+ )
168
+
169
+ try:
170
+ score = float(raw.get("score", 0.0))
171
+ except (TypeError, ValueError, OverflowError):
172
+ score = 0.0
173
+ if not math.isfinite(score) or score < 0.0 or score > 1.0:
174
+ score = 0.0
175
+
176
+ evidence_read = [EvidenceRead(path=f) for f in (component_files or [])]
177
+ # F7: an issue that names a component file counts as a cited
178
+ # evidence read; plain file inclusion stays origin="provided".
179
+ cited_paths = {
180
+ _norm_path(p)
181
+ for issue in issues
182
+ for p in ([issue.path] if issue.path else []) + ([issue.evidence] if issue.evidence else [])
183
+ if p
184
+ }
185
+ # F5: an explicit structured "files_reviewed" assertion from the
186
+ # reviewer is also cited evidence (demonstrates engagement).
187
+ files_reviewed = raw.get("files_reviewed", [])
188
+ if isinstance(files_reviewed, list):
189
+ cited_paths.update(_norm_path(p) for p in files_reviewed if isinstance(p, str) and p.strip())
190
+ for er in evidence_read:
191
+ base = _norm_path(er.path)
192
+ # N5/F-NEW-1: "*" is not a file and substring matches are not
193
+ # evidence. A citation counts only when it is an exact path or
194
+ # an exact basename of a real component file.
195
+ if any(cite == base or base.endswith("/" + cite) for cite in cited_paths):
196
+ er.origin = "cited"
197
+ # 0.9 QC evidence gate: PASS requires at least one cited evidence read
198
+ if status == VERDICT_PASS:
199
+ has_cited = any(er.origin == "cited" for er in evidence_read)
200
+ if not has_cited:
201
+ status = VERDICT_INSUFFICIENT_EVIDENCE
202
+ score = 0.0
203
+ if status == VERDICT_PASS and not issues:
204
+ score = max(score, 0.9)
205
+
206
+ return ReviewArtifact(
207
+ reviewer_id=reviewer_id,
208
+ role=role,
209
+ model=model,
210
+ component_id=component_id,
211
+ verdict=status,
212
+ confidence=score,
213
+ evidence_read=evidence_read,
214
+ issues=issues,
215
+ )
216
+ except Exception:
217
+ return qp._error_artifact(
218
+ reviewer_id,
219
+ role,
220
+ model,
221
+ component_id,
222
+ "normalization failure",
223
+ )
224
+
225
+
226
+ def _raw_to_artifact(
227
+ raw: dict,
228
+ reviewer_id: str,
229
+ role: str,
230
+ model: str,
231
+ component_id: str,
232
+ component_files: Optional[List[str]] = None,
233
+ ) -> ReviewArtifact:
234
+ """Convert a raw model response dict into a ReviewArtifact (strict)."""
235
+ return _parse_reviewer_response(
236
+ raw,
237
+ reviewer_id,
238
+ role,
239
+ model,
240
+ component_id,
241
+ component_files,
242
+ )
243
+
244
+
245
+ def _deadline_for(quality_plan: QualityPlan) -> Optional[float]:
246
+ """Compute the wall-clock deadline for a plan's quality review (F3).
247
+
248
+ max_wall_clock_sec == 0 means "exhausted immediately" (fail-closed).
249
+ Returns None when the budget is negative (unbounded per validation is
250
+ >= 0, so this only occurs for direct callers bypassing validation).
251
+ """
252
+ budget = quality_plan.budget.max_wall_clock_sec
253
+ if not isinstance(budget, (int, float)):
254
+ return None
255
+ if budget == 0:
256
+ return time.monotonic()
257
+ if budget > 0:
258
+ return time.monotonic() + budget
259
+ return None
260
+
261
+
262
+ def _raw_to_arbitration_verdict(raw: dict) -> ArbitrationVerdict:
263
+ """Convert a raw model response dict into an ArbitrationVerdict (strict)."""
264
+ if not isinstance(raw, dict):
265
+ raw = {}
266
+ status = raw.get("status", VERDICT_REJECT)
267
+ if status not in ("PASS", "REJECT", "CONDITIONAL_PASS", "INSUFFICIENT_EVIDENCE"):
268
+ status = VERDICT_REJECT
269
+
270
+ def _claim_list(value):
271
+ if not isinstance(value, list):
272
+ return []
273
+ return [c for c in value if isinstance(c, str)]
274
+
275
+ try:
276
+ confidence = float(raw.get("confidence", 0.0))
277
+ except (TypeError, ValueError, OverflowError):
278
+ confidence = 0.0
279
+ if not math.isfinite(confidence) or confidence < 0.0 or confidence > 1.0:
280
+ confidence = 0.0
281
+ return ArbitrationVerdict(
282
+ status=status,
283
+ winning_claims=_claim_list(raw.get("winning_claims")),
284
+ discarded_claims=_claim_list(raw.get("discarded_claims")),
285
+ reason=raw.get("reason", "") if isinstance(raw.get("reason", ""), str) else "",
286
+ confidence=confidence,
287
+ )
@@ -0,0 +1,242 @@
1
+ """Reviewer persona layer for the quality plane.
2
+
3
+ Extracted verbatim from the former flat orchestrator/quality_plane.py:
4
+ reviewer invocation transport (hook / FAKE_QC / real LLM), persona prompt
5
+ building, typed ERROR artifacts, and model-policy resolution.
6
+
7
+ Shared collaborators are resolved through the ``orchestrator.quality_plane``
8
+ compat namespace (``qp``) at call time so patches applied there stay live.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import re
16
+ from typing import Callable, List, Optional
17
+
18
+ from orchestrator import quality_plane as qp
19
+
20
+ from ..llm import LLMError
21
+ from ..models import ModelRegistry
22
+ from ..qc_review import _redact_secrets
23
+ from ..quality_plan import PERSONA_DESCRIPTIONS, ReviewerRole
24
+ from ..review_artifact import VERDICT_ERROR, ReviewArtifact
25
+
26
+ MIN_REVIEWER_TIMEOUT_SEC = 15
27
+
28
+
29
+ _REVIEWER_HOOK: Optional[Callable] = None
30
+
31
+ _PAID_MODEL_MARKERS = (
32
+ "kimi-k2",
33
+ "kimi-k3",
34
+ "claude-opus-5",
35
+ "claude-sonnet-5",
36
+ "claude-fable-5",
37
+ "claude-3-opus",
38
+ "claude-3-7-sonnet",
39
+ "claude-3-5-sonnet",
40
+ "gpt-5.6-sol",
41
+ "gpt-5.6-terra",
42
+ "gpt-5.6-luna",
43
+ "gpt-5.6-cyber",
44
+ "o1",
45
+ "o3",
46
+ "o3-mini",
47
+ "o4-mini",
48
+ "deepseek-v4-pro",
49
+ "deepseek-reasoner",
50
+ "gemini-3.1-pro",
51
+ "gemini-2.5-pro",
52
+ "gemini-1.5-pro",
53
+ )
54
+
55
+
56
+ def _invoke_reviewer(
57
+ prompt: str,
58
+ model: str,
59
+ workspace_root: str,
60
+ timeout_sec: Optional[int] = None,
61
+ ) -> dict:
62
+ """Call the generic LLM transport with the given prompt, return parsed JSON dict.
63
+
64
+ Returns {"status": "ERROR", "reason": ...} on any failure so callers
65
+ never need to handle exceptions from this function.
66
+ """
67
+ hook = qp._REVIEWER_HOOK
68
+ if hook is not None:
69
+ try:
70
+ import inspect
71
+
72
+ signature = inspect.signature(hook)
73
+ accepts_timeout = "timeout_sec" in signature.parameters or any(
74
+ parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in signature.parameters.values()
75
+ )
76
+ except (TypeError, ValueError):
77
+ accepts_timeout = False
78
+ if accepts_timeout:
79
+ return hook(prompt, model, workspace_root, timeout_sec=timeout_sec)
80
+ return hook(prompt, model, workspace_root)
81
+
82
+ fake = os.environ.get("FAKE_QC", "")
83
+ if fake:
84
+ return _fake_raw_response(fake, prompt)
85
+
86
+ timeout = timeout_sec if timeout_sec is not None else 120
87
+
88
+ # Paid routes still receive the prepared master-context payload: the
89
+ # complete review context as one payload, no external file reads.
90
+ normalized_model = str(model or "").strip().lower()
91
+ if any(marker in normalized_model for marker in _PAID_MODEL_MARKERS) and "gpt-4o-mini" not in normalized_model:
92
+ prompt = (
93
+ "[MASTER_CONTEXT]\n"
94
+ "[CONTEXT_COMPLETE]\n"
95
+ "The following payload is the complete review context. Do not read "
96
+ "additional files to reconstruct missing context.\n\n" + prompt
97
+ )
98
+
99
+ try:
100
+ response = qp.call_llm(prompt, model, timeout_s=timeout)
101
+ except LLMError as e:
102
+ return {"status": "ERROR", "reason": f"QC invocation error: {e}", "score": 0.0, "issues": []}
103
+
104
+ stdout = (response.get("text") or "").strip()
105
+ if stdout.startswith("```"):
106
+ stdout = stdout[3:]
107
+ if stdout.startswith("json"):
108
+ stdout = stdout[4:]
109
+ stdout = stdout.rsplit("```", 1)[0].strip()
110
+ try:
111
+ parsed = json.loads(stdout)
112
+ if isinstance(parsed, dict):
113
+ return parsed
114
+ except (json.JSONDecodeError, ValueError):
115
+ pass
116
+
117
+ return {"status": "ERROR", "reason": "unparseable output", "score": 0.0, "issues": []}
118
+
119
+
120
+ def _fake_raw_response(fake_mode: str, prompt: str = "") -> dict:
121
+ """Deterministic fake reviewer response — parity with FAKE_QC modes in qc_review.py.
122
+
123
+ Enables deterministic testing of the panel/component paths without
124
+ spawning a real model subprocess.
125
+ """
126
+ if fake_mode == "PASS":
127
+ # N5: the fake reviewer claims it examined the actual files named in
128
+ # the prompt (``--- path ---`` markers). A "*" glob is never accepted
129
+ # as cited evidence, so the fake must name real files like a model.
130
+ paths = _extract_prompt_paths(prompt)
131
+ return {"status": "PASS", "score": 0.95, "issues": [], "files_reviewed": paths}
132
+ if fake_mode == "REJECT":
133
+ return {
134
+ "status": "REJECT",
135
+ "score": 0.4,
136
+ # CRITICAL maps to P0 so synthesis yields a true REJECT,
137
+ # matching the legacy FAKE_QC=REJECT semantics.
138
+ "issues": [{"severity": "CRITICAL", "description": "intentional test rejection"}],
139
+ }
140
+ if fake_mode == "INSUFFICIENT_EVIDENCE":
141
+ return {"status": "INSUFFICIENT_EVIDENCE", "score": 0.0, "issues": []}
142
+ if fake_mode == "ERROR":
143
+ return {"status": "ERROR", "reason": "simulated provider error", "score": 0.0, "issues": []}
144
+ return {"status": "ERROR", "reason": f"unknown FAKE_QC mode: {fake_mode}", "score": 0.0, "issues": []}
145
+
146
+
147
+ def _extract_prompt_paths(prompt: str) -> List[str]:
148
+ """Extract file paths embedded as ``--- <path> (N bytes) ---`` markers."""
149
+ paths = []
150
+ for m in re.finditer(
151
+ r"^--- (.+?)(?: ---)? \((?:read error: .*|file not found|\d+ bytes)\)(?: ---)?$", prompt, re.MULTILINE
152
+ ):
153
+ p = m.group(1).strip()
154
+ if p and p not in paths:
155
+ paths.append(p)
156
+ return paths
157
+
158
+
159
+ # ── Persona prompt building ───────────────────────────────────────────────
160
+
161
+
162
+ def _build_persona_prompt(base_prompt: str, role: ReviewerRole) -> str:
163
+ """Append persona-specific instructions to a base review prompt."""
164
+ desc = PERSONA_DESCRIPTIONS.get(role.role, "")
165
+ parts = [base_prompt]
166
+ parts.append("")
167
+ parts.append(f"=== REVIEW PERSPECTIVE: {role.role} ===")
168
+ if desc:
169
+ parts.append(f"Focus on: {desc}")
170
+ if role.focus:
171
+ parts.append(f"Specific concerns: {', '.join(role.focus)}")
172
+ parts.append("")
173
+ parts.extend(
174
+ [
175
+ "=== EVIDENCE REQUIREMENTS ===",
176
+ "Every implementation or verification claim MUST include all of:",
177
+ "1. repository-relative file path;",
178
+ "2. function or class name;",
179
+ "3. exact line range;",
180
+ "4. a quoted code excerpt from that line range;",
181
+ "5. evidence type: implementation, verification, or observation.",
182
+ "Filename-only, keyword-only, and source-file-present claims are invalid "
183
+ "and cannot support an implementation or verification conclusion.",
184
+ "Use this evidence shape when reporting an issue:",
185
+ '{"path":"orchestrator/example.py","symbol":"run_task",'
186
+ '"line_range":"120-136","excerpt":"...exact source text...",'
187
+ '"type":"implementation"}',
188
+ "",
189
+ ]
190
+ )
191
+ # NEW-5: the base prompt was redacted by _build_qc_prompt, but the
192
+ # persona section (desc/focus) is appended AFTER — a secret in a
193
+ # configured persona would leak. Redact the complete joined prompt.
194
+ return _redact_secrets("\n".join(parts))
195
+
196
+
197
+ # ── Component review dispatch ─────────────────────────────────────────────
198
+
199
+
200
+ def _error_artifact(
201
+ reviewer_id: str,
202
+ role: str,
203
+ model: str,
204
+ component_id: str,
205
+ reason: str,
206
+ ) -> ReviewArtifact:
207
+ """Build a typed ERROR artifact. Never raises."""
208
+ return ReviewArtifact(
209
+ reviewer_id=reviewer_id,
210
+ role=role,
211
+ model=model,
212
+ component_id=component_id,
213
+ verdict=VERDICT_ERROR,
214
+ confidence=0.0,
215
+ evidence_read=[],
216
+ issues=[],
217
+ reason=reason,
218
+ )
219
+
220
+
221
+ def _resolve_reviewer_model(role) -> str:
222
+ """Map a ReviewerRole's model_policy to a concrete model ID."""
223
+ policy = role.model_policy if hasattr(role, "model_policy") else "default"
224
+ mapping = {
225
+ "default": ModelRegistry.default_qc(),
226
+ "premium": ModelRegistry.OPUS,
227
+ "cheap_cross_family": ModelRegistry.FALLBACK,
228
+ "deep": ModelRegistry.KIMI,
229
+ }
230
+ return mapping.get(policy, ModelRegistry.default_qc())
231
+
232
+
233
+ def _resolve_arbitration_model(arb_policy) -> str:
234
+ """Map ArbitrationPolicy.model_policy to a concrete model ID."""
235
+ policy = arb_policy.model_policy if hasattr(arb_policy, "model_policy") else "default"
236
+ mapping = {
237
+ "default": ModelRegistry.default_qc(),
238
+ "premium": ModelRegistry.OPUS,
239
+ "cheap_cross_family": ModelRegistry.FALLBACK,
240
+ "deep": ModelRegistry.KIMI,
241
+ }
242
+ return mapping.get(policy, ModelRegistry.default_qc())