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,282 @@
1
+ """Automated QC reviewer: calls a model to evaluate work output quality.
2
+
3
+ Returns structured verdict (PASS / REJECT) with actionable reasons.
4
+ Used by supervisor after verification passes and qc.required is true.
5
+ """
6
+
7
+ import json
8
+ import math
9
+ import os
10
+ import re
11
+
12
+ from .llm import LLMError, call_llm
13
+ from .models import ModelRegistry
14
+ from .quality_lenses import get_lens
15
+
16
+ QC_STATUS_PASS = "PASS"
17
+ QC_STATUS_REJECT = "REJECT"
18
+ QC_STATUS_INSUFFICIENT_EVIDENCE = "INSUFFICIENT_EVIDENCE"
19
+ QC_STATUS_ERROR = "ERROR"
20
+ VALID_QC_STATUSES = {QC_STATUS_PASS, QC_STATUS_REJECT, QC_STATUS_INSUFFICIENT_EVIDENCE, QC_STATUS_ERROR}
21
+
22
+
23
+ class QCVerdict:
24
+ def __init__(
25
+ self,
26
+ passed: bool,
27
+ reason: str,
28
+ details: str = "",
29
+ status: str = "",
30
+ score: float = 0.0,
31
+ issues: list = None,
32
+ dimension_scores: dict = None,
33
+ dimension_reasoning: dict = None,
34
+ ):
35
+ self.passed = passed
36
+ self.reason = reason
37
+ self.details = details
38
+ self.status = status or (QC_STATUS_PASS if passed else QC_STATUS_REJECT)
39
+ self.score = score
40
+ self.issues = issues or []
41
+ self.dimension_scores = dimension_scores or {}
42
+ self.dimension_reasoning = dimension_reasoning or {}
43
+
44
+ def to_dict(self):
45
+ return {
46
+ "passed": self.passed,
47
+ "reason": self.reason,
48
+ "details": self.details,
49
+ "status": self.status,
50
+ "score": self.score,
51
+ "issues": self.issues,
52
+ "dimension_scores": dict(self.dimension_scores),
53
+ "dimension_reasoning": dict(self.dimension_reasoning),
54
+ }
55
+
56
+
57
+ def _redact_secrets(text: str) -> str:
58
+ """Mask high-entropy credential patterns before external transmission (F8).
59
+
60
+ Conservative: only well-formed credential shapes are masked, so review
61
+ content that legitimately contains such tokens is still lossy for the
62
+ model but the reviewer prompt never leaks raw keys/tokens.
63
+ """
64
+ if not text:
65
+ return ""
66
+ patterns = [
67
+ re.compile(r"(sk-[A-Za-z0-9_-]{16,})"),
68
+ re.compile(r"(github_pat_[A-Za-z0-9_]{22,})"),
69
+ re.compile(r"(gh[pousr]_[A-Za-z0-9]{20,})"),
70
+ re.compile(r"(AIza[0-9A-Za-z-_]{35})"),
71
+ re.compile(r"(hf_[A-Za-z0-9]{34,})"),
72
+ re.compile(r"(xox[baprs]-[0-9A-Za-z-]{10,})"),
73
+ re.compile(r"((?:AKIA|ASIA)[0-9A-Z]{16})"),
74
+ re.compile(r"(gw_sk_[A-Za-z0-9]{16,})"),
75
+ re.compile(r"(api[_-]?key\s*[=:]\s*['\"]?[A-Za-z0-9_-]{16,}['\"]?)", re.IGNORECASE),
76
+ re.compile(r"(token\s*[=:]\s*['\"]?[A-Za-z0-9_.-]{16,}['\"]?)", re.IGNORECASE),
77
+ re.compile(r"(password\s*[=:]\s*['\"]?[^\s'\"]{4,})", re.IGNORECASE),
78
+ re.compile(r"(Bearer\s+[A-Za-z0-9_\-\.~+/]+=*)", re.IGNORECASE),
79
+ re.compile(r"(eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+)"),
80
+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----"),
81
+ ]
82
+ for pat in patterns:
83
+ text = pat.sub(lambda m: m.group(0)[:6] + "[REDACTED]" if len(m.group(0)) > 8 else "[REDACTED]", text)
84
+ return text
85
+
86
+
87
+ def _build_qc_prompt(contract, output_paths, verification_results, quality_spec=None) -> str:
88
+ qc_lens = (
89
+ contract.qc.get("lens", "code_correctness")
90
+ if hasattr(contract, "qc") and isinstance(contract.qc, dict)
91
+ else "code_correctness"
92
+ )
93
+ lens = get_lens(qc_lens)
94
+ dim_scores_json = lens.dim_scores_json()
95
+ dim_reasoning_json = lens.dim_reasoning_json()
96
+
97
+ lines = [
98
+ "You are a strict code/output reviewer. Your job: determine if the delivered work meets the contract requirements.",
99
+ "",
100
+ "You MUST respond with ONLY a JSON object with exactly these fields:",
101
+ ' {"status": "PASS" or "REJECT" or "INSUFFICIENT_EVIDENCE",',
102
+ ' "reason": "short reason",',
103
+ ' "details": "specific issues or affirmation",',
104
+ ' "score": 0.0-1.0,',
105
+ ' "issues": [{"severity": "CRITICAL"|"MAJOR"|"MINOR", "description": "..."}],',
106
+ f' "dimension_scores": {dim_scores_json},',
107
+ f' "dimension_reasoning": {dim_reasoning_json}}}',
108
+ "",
109
+ "=== CONTRACT OBJECTIVE ===",
110
+ contract.objective,
111
+ "",
112
+ "=== ACCEPTANCE CRITERIA ===",
113
+ ]
114
+ for chk in contract.acceptance_checks:
115
+ lines.append(
116
+ f" - {chk.get('kind')}: {chk.get('path', chk.get('command', ''))} expected={chk.get('expected', '?')}"
117
+ )
118
+ lines.append("")
119
+ if quality_spec:
120
+ lines.append("=== QUALITY SPECIFICATION ===")
121
+ if quality_spec.get("required_sections"):
122
+ lines.append(f" Required sections: {quality_spec['required_sections']}")
123
+ if quality_spec.get("quality_dimensions"):
124
+ lines.append(f" Quality dimensions: {json.dumps(quality_spec['quality_dimensions'])}")
125
+ if quality_spec.get("hard_failures"):
126
+ lines.append(f" Hard failures: {quality_spec['hard_failures']}")
127
+ if quality_spec.get("minimum_score"):
128
+ lines.append(f" Minimum score: {quality_spec['minimum_score']}")
129
+ lines.append("")
130
+ lines.append("=== VERIFICATION RESULTS ===")
131
+ for vr in verification_results:
132
+ status = "PASS" if vr.get("passed") else "FAIL"
133
+ lines.append(f" [{status}] {vr.get('check_id')}: {vr.get('message', '')}")
134
+ lines.append("")
135
+ lines.append("=== OUTPUT FILES ===")
136
+ for p in output_paths:
137
+ full = os.path.abspath(p) if not os.path.isabs(p) else p
138
+ if os.path.isfile(full):
139
+ try:
140
+ with open(full, "r", encoding="utf-8", errors="replace") as f:
141
+ content = _redact_secrets(f.read())
142
+ lines.append(f"--- {p} ({len(content)} bytes) ---")
143
+ lines.append(content[:3000])
144
+ if len(content) > 3000:
145
+ lines.append(f"... [truncated, total {len(content)} bytes]")
146
+ except OSError as e:
147
+ lines.append(f"--- {p} --- (read error: {e})")
148
+ else:
149
+ lines.append(f"--- {p} --- (file not found)")
150
+ lines.append(lens.render_evaluation_section(quality_spec))
151
+ # F6: redact the COMPLETE prompt (contract metadata, acceptance checks,
152
+ # verification messages and quality-spec values can all carry secrets),
153
+ # not just embedded file contents.
154
+ return _redact_secrets("\n".join(lines))
155
+
156
+
157
+ def _fake_qc_review(contract, output_paths, verification_results, workspace_root) -> QCVerdict:
158
+ """Deterministic fake QC for testing — controlled by FAKE_QC env var."""
159
+ fake_mode = os.environ.get("FAKE_QC", "")
160
+
161
+ if fake_mode == "PASS":
162
+ return QCVerdict(
163
+ passed=True,
164
+ reason="fake QC PASS",
165
+ details="Deterministic fake QC approval",
166
+ status=QC_STATUS_PASS,
167
+ score=0.95,
168
+ issues=[{"severity": "MINOR", "description": "cosmetic"}],
169
+ )
170
+ elif fake_mode == "REJECT":
171
+ return QCVerdict(
172
+ passed=False,
173
+ reason="fake QC REJECT",
174
+ details="Deterministic fake QC rejection for testing",
175
+ status=QC_STATUS_REJECT,
176
+ score=0.4,
177
+ issues=[{"severity": "MAJOR", "description": "intentional test rejection"}],
178
+ )
179
+ elif fake_mode == "INSUFFICIENT_EVIDENCE":
180
+ return QCVerdict(
181
+ passed=False,
182
+ reason="fake QC INSUFFICIENT_EVIDENCE",
183
+ details="Deterministic fake insufficient evidence for testing",
184
+ status=QC_STATUS_INSUFFICIENT_EVIDENCE,
185
+ score=0.0,
186
+ issues=[],
187
+ )
188
+ elif fake_mode == "ERROR":
189
+ return QCVerdict(
190
+ passed=False,
191
+ reason="fake QC ERROR",
192
+ details="Simulated provider error for testing",
193
+ status=QC_STATUS_ERROR,
194
+ score=0.0,
195
+ issues=[{"severity": "CRITICAL", "description": "provider error"}],
196
+ )
197
+ elif fake_mode == "MALFORMED":
198
+ return QCVerdict(
199
+ passed=False,
200
+ reason="QC reviewer returned unparseable output",
201
+ details="not a valid json response {{{broken",
202
+ status=QC_STATUS_ERROR,
203
+ score=0.0,
204
+ issues=[],
205
+ )
206
+
207
+ return QCVerdict(False, "unknown FAKE_QC mode", status=QC_STATUS_ERROR)
208
+
209
+
210
+ def _select_qc_model(contract) -> str:
211
+ """Select QC model — defaults to the QC model (env QC_MODEL override)."""
212
+ return ModelRegistry.default_qc()
213
+
214
+
215
+ def run_qc_review(contract, output_paths, verification_results, workspace_root) -> QCVerdict:
216
+ """Run automated QC review via the generic LLM transport."""
217
+ if os.environ.get("FAKE_QC", ""):
218
+ return _fake_qc_review(contract, output_paths, verification_results, workspace_root)
219
+
220
+ quality_spec = getattr(contract, "quality_spec", {})
221
+ prompt = _build_qc_prompt(contract, output_paths, verification_results, quality_spec=quality_spec)
222
+
223
+ qc_model = _select_qc_model(contract)
224
+
225
+ try:
226
+ response = call_llm(prompt, qc_model, timeout_s=120)
227
+ stdout = response["text"] or ""
228
+ except LLMError as e:
229
+ return QCVerdict(False, f"QC invocation error: {e}", "")
230
+
231
+ stdout = stdout.strip()
232
+ if stdout.startswith("```"):
233
+ stdout = stdout[3:]
234
+ if stdout.startswith("json"):
235
+ stdout = stdout[4:]
236
+ stdout = stdout.rsplit("```", 1)[0].strip()
237
+ try:
238
+ parsed = json.loads(stdout)
239
+ if isinstance(parsed, dict):
240
+ status = parsed.get("status", QC_STATUS_REJECT)
241
+ if status not in VALID_QC_STATUSES:
242
+ status = QC_STATUS_ERROR
243
+ reason = parsed.get("reason", "no reason given")
244
+ if not isinstance(reason, str):
245
+ reason = str(reason)
246
+ details = parsed.get("details", "")
247
+ if not isinstance(details, str):
248
+ details = str(details)
249
+ try:
250
+ score = float(parsed.get("score", 0.0))
251
+ except (TypeError, ValueError, OverflowError):
252
+ score = 0.0
253
+ if not math.isfinite(score):
254
+ score = 0.0
255
+ score = max(0.0, min(1.0, score))
256
+ issues_raw = parsed.get("issues", [])
257
+ issues = [i for i in issues_raw if isinstance(i, dict)] if isinstance(issues_raw, list) else []
258
+ dimension_scores = parsed.get("dimension_scores", {})
259
+ if not isinstance(dimension_scores, dict):
260
+ dimension_scores = {}
261
+ dimension_reasoning = parsed.get("dimension_reasoning", {})
262
+ if not isinstance(dimension_reasoning, dict):
263
+ dimension_reasoning = {}
264
+ passed = status == QC_STATUS_PASS
265
+ if status == QC_STATUS_INSUFFICIENT_EVIDENCE:
266
+ passed = False
267
+ if not details:
268
+ details = "QC reviewer could not determine quality from available evidence"
269
+ return QCVerdict(
270
+ passed=passed,
271
+ reason=reason,
272
+ details=details,
273
+ status=status,
274
+ score=score,
275
+ issues=issues,
276
+ dimension_scores=dimension_scores,
277
+ dimension_reasoning=dimension_reasoning,
278
+ )
279
+ except (json.JSONDecodeError, ValueError):
280
+ pass
281
+
282
+ return QCVerdict(False, "QC reviewer returned unparseable output", details=stdout[:500], status=QC_STATUS_ERROR)
@@ -0,0 +1,314 @@
1
+ """Lens configurations for the quality plane.
2
+
3
+ Extracts hardcoded branching from qc_review.py into data-driven configs.
4
+ Phase 2: no behavioral change — output must be byte-identical for
5
+ architecture_audit and code_correctness lenses.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from typing import Any, Dict, List, Optional
12
+
13
+
14
+ class LensDimension:
15
+ """A single evaluation dimension for a QC lens."""
16
+
17
+ def __init__(self, name: str, description: str, weight: float = 1.0):
18
+ self.name = name
19
+ self.description = description
20
+ self.weight = weight
21
+
22
+
23
+ class LensConfig:
24
+ """Configuration for a QC evaluation lens.
25
+
26
+ Contains dimension templates, evaluation criteria sections,
27
+ and minimum count defaults for adversarial-style audits.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ name: str,
33
+ dimensions: List[LensDimension],
34
+ criteria_sections: List[str],
35
+ min_counts: Optional[Dict[str, int]] = None,
36
+ strict_reject_rules: Optional[List[str]] = None,
37
+ ):
38
+ self.name = name
39
+ self.dimensions = dimensions
40
+ self.criteria_sections = criteria_sections
41
+ self.min_counts = min_counts or {}
42
+ self.strict_reject_rules = strict_reject_rules or []
43
+
44
+ def dim_scores_json(self) -> str:
45
+ """Render dimension_scores JSON template string."""
46
+ parts = {d.name: "0.0-1.0" for d in self.dimensions}
47
+ return json.dumps(parts)
48
+
49
+ def dim_reasoning_json(self) -> str:
50
+ """Render dimension_reasoning JSON template string."""
51
+ parts = {d.name: "..." for d in self.dimensions}
52
+ return json.dumps(parts)
53
+
54
+ def render_evaluation_section(self, quality_spec: Optional[Dict[str, Any]] = None) -> str:
55
+ """Render the full evaluation criteria section for prompt building."""
56
+ lines: List[str] = []
57
+ qs = quality_spec or {}
58
+
59
+ if self.name == "architecture_audit":
60
+ min_counts = qs.get("minimum_counts", {}) if qs else {}
61
+ min_contradictions = min_counts.get("contradictions", 5)
62
+ min_edge_cases = min_counts.get("edge_cases", 20)
63
+ min_schemas = min_counts.get("schemas", 3)
64
+ min_alternatives = min_counts.get("radical_alternatives", 1)
65
+
66
+ lines.append("")
67
+ lines.append("=== ADVERSARIAL ARCHITECTURE AUDIT EVALUATION ===")
68
+ lines.append("This is an architecture audit. Apply STRICTER criteria:")
69
+ lines.append("")
70
+ for section in self.criteria_sections:
71
+ filled = section.format(
72
+ min_contradictions=min_contradictions,
73
+ min_edge_cases=min_edge_cases,
74
+ min_schemas=min_schemas,
75
+ min_alternatives=min_alternatives,
76
+ )
77
+ lines.append(filled)
78
+ lines.append("")
79
+ for rule in self.strict_reject_rules:
80
+ lines.append(rule)
81
+ lines.append("Score each dimension 0.0-1.0 and include per-dimension reasoning.")
82
+ lines.append("Hard failures from quality spec are non-negotiable — if present, REJECT.")
83
+ else:
84
+ lines.append("")
85
+ lines.append("=== EVALUATION DIMENSIONS ===")
86
+ lines.append(f"Evaluate the output across these {len(self.dimensions)} dimensions:")
87
+ for i, dim in enumerate(self.dimensions, 1):
88
+ lines.append(f"{i}. {dim.name.upper()}: {dim.description}")
89
+ lines.append("")
90
+ for section in self.criteria_sections:
91
+ lines.append(section)
92
+
93
+ return "\n".join(lines)
94
+
95
+
96
+ # ── Lens registry ──────────────────────────────────────────────────────────
97
+
98
+ LENSES: Dict[str, LensConfig] = {}
99
+
100
+
101
+ def register(lens: LensConfig) -> None:
102
+ LENSES[lens.name] = lens
103
+
104
+
105
+ def get_lens(name: str) -> LensConfig:
106
+ if name in LENSES:
107
+ return LENSES[name]
108
+ return LENSES["code_correctness"]
109
+
110
+
111
+ # ── Architecture audit lens ────────────────────────────────────────────────
112
+
113
+ register(
114
+ LensConfig(
115
+ name="architecture_audit",
116
+ dimensions=[
117
+ LensDimension("originality", "Does the output mostly restate the source material?"),
118
+ LensDimension("contradiction_resolution", "Does it identify and resolve internal contradictions?"),
119
+ LensDimension("concrete_artifacts", "Does it produce implementation-level artifacts?"),
120
+ LensDimension("edge_case_coverage", "Are specific failure scenarios enumerated?"),
121
+ LensDimension("intellectual_courage", "Does it challenge assumptions?"),
122
+ LensDimension("actionability", "Are recommendations implementable?"),
123
+ LensDimension("source_fidelity", "Does every claim cite the source?"),
124
+ ],
125
+ criteria_sections=[
126
+ "1. ORIGINALITY: Does the output mostly restate the source material?\n REJECT if it is a well-structured summary with no original analysis.",
127
+ "2. CONTRADICTION RESOLUTION: Does it identify and resolve internal contradictions?\n Target at least {min_contradictions} contradictions identified with concrete resolution proposals.",
128
+ "3. CONCRETE ARTIFACTS: Does it produce implementation-level artifacts (JSON schemas,\n risk tables, test plans, deployment checklists) that do not exist in the source?\n Target at least {min_schemas} schemas or equivalent structured artifacts.",
129
+ "4. EDGE CASES: Are specific failure scenarios enumerated (not just categories)?\n Target at least {min_edge_cases} specific edge cases with per-scenario mitigations.",
130
+ "5. INTELLECTUAL COURAGE: Does it challenge the system's assumptions and propose\n uncomfortable truths? REJECT if it reads like a polite consulting deck.",
131
+ "6. ACTIONABILITY: Are recommendations implementable — targeting specific\n files/modules with concrete implementation shapes?",
132
+ "7. SOURCE FIDELITY: Does every claim cite the specific source file and section?",
133
+ "8. ALTERNATIVE ARCHITECTURES: Does it propose at least {min_alternatives} radical\n alternative architecture that challenges the current design?",
134
+ ],
135
+ min_counts={
136
+ "contradictions": 5,
137
+ "edge_cases": 20,
138
+ "schemas": 3,
139
+ "radical_alternatives": 1,
140
+ },
141
+ strict_reject_rules=[
142
+ "STRICT REJECT if output is primarily a summary with no original contribution.",
143
+ "STRICT REJECT if it has no uncomfortable truths or radical alternatives.",
144
+ ],
145
+ )
146
+ )
147
+
148
+
149
+ # ── Code correctness lens (default) ────────────────────────────────────────
150
+
151
+ register(
152
+ LensConfig(
153
+ name="code_correctness",
154
+ dimensions=[
155
+ LensDimension(
156
+ "contract_adherence",
157
+ "Did the worker produce exactly the declared outputs?\n Check output count, output paths, no undeclared files.",
158
+ ),
159
+ LensDimension(
160
+ "structural_compliance",
161
+ "Does the output contain the required sections,\n headings, and structural elements from the quality spec?",
162
+ ),
163
+ LensDimension(
164
+ "substantive_quality",
165
+ "Source coverage, citation adequacy, factual correctness,\n reasoning depth, and board usefulness.",
166
+ ),
167
+ LensDimension(
168
+ "scope_discipline",
169
+ "Did the worker stay within the contracted step?\n (e.g., step 1 should not produce final audit output)",
170
+ ),
171
+ ],
172
+ criteria_sections=[
173
+ "Evaluate: Does the output FULLY satisfy the objective, quality spec, and all acceptance criteria?",
174
+ "Be strict. If anything is missing, vague, incorrect, or out-of-scope, REJECT with specific reasons.",
175
+ "If you cannot determine quality because evidence is insufficient, return INSUFFICIENT_EVIDENCE.",
176
+ ],
177
+ )
178
+ )
179
+
180
+
181
+ # ── Plan correctness lens ──────────────────────────────────────────────────
182
+
183
+ register(
184
+ LensConfig(
185
+ name="plan_correctness",
186
+ dimensions=[
187
+ LensDimension("goal_alignment", "Does the plan align with the goal?"),
188
+ LensDimension("dependency_correctness", "Are task dependencies correct and complete?"),
189
+ LensDimension("scope_appropriateness", "Is each contract scoped to a single responsibility?"),
190
+ LensDimension("risk_assessment", "Are risk tiers correctly assigned?"),
191
+ ],
192
+ criteria_sections=[
193
+ "Evaluate: Does the plan represent a valid, executable decomposition of the goal?",
194
+ "Reject if any contract has unrealistic scope, missing dependencies, or inappropriate risk tier.",
195
+ ],
196
+ )
197
+ )
198
+
199
+
200
+ # ── Config safety lens ─────────────────────────────────────────────────────
201
+
202
+ register(
203
+ LensConfig(
204
+ name="config_safety",
205
+ dimensions=[
206
+ LensDimension("secret_exposure", "Does the config expose secrets or credentials?"),
207
+ LensDimension("permission_correctness", "Are workspace permissions appropriate?"),
208
+ LensDimension("destructive_actions", "Are there dangerous commands or destructive operations?"),
209
+ LensDimension("validation_quality", "Are there sufficient safety validations?"),
210
+ ],
211
+ criteria_sections=[
212
+ "Evaluate: Is this configuration safe to execute in the workspace?",
213
+ "Any exposed credentials, unsafe permissions, or destructive commands are automatic REJECT.",
214
+ ],
215
+ )
216
+ )
217
+
218
+
219
+ # ── Research quality lens ──────────────────────────────────────────────────
220
+
221
+ register(
222
+ LensConfig(
223
+ name="research_quality",
224
+ dimensions=[
225
+ LensDimension("citation_quality", "Are all claims supported by citations?"),
226
+ LensDimension("source_fidelity", "Do citations accurately represent source content?"),
227
+ LensDimension("coverage", "Does the research cover the required scope?"),
228
+ LensDimension("reasoning_depth", "Is there evidence of critical analysis vs summary?"),
229
+ ],
230
+ criteria_sections=[
231
+ "Evaluate: Is the research thorough, accurate, and properly cited?",
232
+ "Unsupported claims, citation hallucination, or superficial analysis should REJECT.",
233
+ ],
234
+ )
235
+ )
236
+
237
+
238
+ # ── Strategic review lens ──────────────────────────────────────────────────
239
+
240
+ register(
241
+ LensConfig(
242
+ name="strategic_review",
243
+ dimensions=[
244
+ LensDimension("problem_fit", "Does the work solve the actual problem?"),
245
+ LensDimension("opportunity_cost", "Are there better approaches not considered?"),
246
+ LensDimension("wrong_abstraction_risk", "Is the proposed abstraction level appropriate?"),
247
+ LensDimension("simplicity", "Could a simpler approach work?"),
248
+ ],
249
+ criteria_sections=[
250
+ "Evaluate: Is this the right thing to build, at the right level of abstraction?",
251
+ "Challenge the goal, not just the implementation. Identify opportunity cost.",
252
+ "If the objective is solving the wrong problem, say so directly.",
253
+ ],
254
+ )
255
+ )
256
+
257
+
258
+ # ── Migration safety lens ──────────────────────────────────────────────────
259
+
260
+ register(
261
+ LensConfig(
262
+ name="migration_safety",
263
+ dimensions=[
264
+ LensDimension("backward_compatibility", "Are there breaking changes without migration path?"),
265
+ LensDimension("sequencing", "Is the migration order correct and safe?"),
266
+ LensDimension("rollback_readiness", "Can the migration be rolled back?"),
267
+ LensDimension("testing_coverage", "Are migration paths tested?"),
268
+ ],
269
+ criteria_sections=[
270
+ "Evaluate: Is this migration safe to execute?",
271
+ "Any breaking change without documented migration path is a REJECT.",
272
+ "Missing rollback plan for high-risk migrations is a REJECT.",
273
+ ],
274
+ )
275
+ )
276
+
277
+
278
+ # ── Content quality lens ──────────────────────────────────────────────────
279
+
280
+ register(
281
+ LensConfig(
282
+ name="content_quality",
283
+ dimensions=[
284
+ LensDimension("accuracy", "Are factual claims correct and verifiable?"),
285
+ LensDimension("completeness", "Does the content cover the contracted scope fully?"),
286
+ LensDimension("structure", "Is the content organized for its intended use?"),
287
+ LensDimension("tone_appropriateness", "Does the tone match the audience and purpose?"),
288
+ ],
289
+ criteria_sections=[
290
+ "Evaluate: Is the content accurate, complete, and fit for purpose?",
291
+ "Factual errors, unsupported claims, or material omissions should REJECT.",
292
+ "If you cannot verify key claims against the provided files, return INSUFFICIENT_EVIDENCE.",
293
+ ],
294
+ )
295
+ )
296
+
297
+
298
+ # ── Document quality lens ─────────────────────────────────────────────────
299
+
300
+ register(
301
+ LensConfig(
302
+ name="document_quality",
303
+ dimensions=[
304
+ LensDimension("structure", "Are required sections and headings present?"),
305
+ LensDimension("clarity", "Is the document understandable without prior context?"),
306
+ LensDimension("consistency", "Are terms, formats, and references consistent?"),
307
+ LensDimension("completeness", "Are all contracted sections substantively filled?"),
308
+ ],
309
+ criteria_sections=[
310
+ "Evaluate: Is this document well-structured, clear, and complete?",
311
+ "Missing required sections, placeholder content, or internal contradictions should REJECT.",
312
+ ],
313
+ )
314
+ )