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.
- letitloop-0.2.0.dist-info/METADATA +232 -0
- letitloop-0.2.0.dist-info/RECORD +175 -0
- letitloop-0.2.0.dist-info/WHEEL +5 -0
- letitloop-0.2.0.dist-info/entry_points.txt +4 -0
- letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
- letitloop-0.2.0.dist-info/top_level.txt +1 -0
- orchestrator/SKILL.md +292 -0
- orchestrator/__init__.py +151 -0
- orchestrator/anti_ouroboros.py +78 -0
- orchestrator/approval.py +139 -0
- orchestrator/ast_node_splicer.py +130 -0
- orchestrator/ast_splicer.py +94 -0
- orchestrator/audit.py +88 -0
- orchestrator/budget.py +195 -0
- orchestrator/checkpoint.py +248 -0
- orchestrator/cli.py +1971 -0
- orchestrator/codebase_introspector.py +66 -0
- orchestrator/component_slicer.py +185 -0
- orchestrator/config.py +152 -0
- orchestrator/contract.py +404 -0
- orchestrator/dag_validator.py +172 -0
- orchestrator/elasticity_governor.py +80 -0
- orchestrator/env_doctor.py +166 -0
- orchestrator/errors.py +211 -0
- orchestrator/events.py +120 -0
- orchestrator/evidence.py +203 -0
- orchestrator/exceptions.py +37 -0
- orchestrator/experimental/arena_arbiter.py +260 -0
- orchestrator/experimental/fuzz_engine.py +206 -0
- orchestrator/experimental/mutation_tester.py +382 -0
- orchestrator/failure.py +226 -0
- orchestrator/fast_sandbox.py +126 -0
- orchestrator/feasibility_gate.py +115 -0
- orchestrator/feedback.py +302 -0
- orchestrator/fixtures/__init__.py +0 -0
- orchestrator/fixtures/example_contract.json +50 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
- orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
- orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
- orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
- orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
- orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
- orchestrator/fixtures/generated/perf-step-1.json +61 -0
- orchestrator/fixtures/generated/perf-step-2.json +62 -0
- orchestrator/fixtures/generated/perf-step-3.json +62 -0
- orchestrator/fixtures/generated/perf-step-4.json +62 -0
- orchestrator/fixtures/generated/perf-step-5.json +63 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
- orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
- orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
- orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
- orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
- orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
- orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
- orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
- orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
- orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
- orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
- orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
- orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
- orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
- orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
- orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
- orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
- orchestrator/fixtures/run_proofs.py +299 -0
- orchestrator/fixtures/test_normalizer.py +16 -0
- orchestrator/generator.py +239 -0
- orchestrator/goal.py +245 -0
- orchestrator/handoff.py +86 -0
- orchestrator/hybrid_worker.py +840 -0
- orchestrator/impossibility.py +162 -0
- orchestrator/limits.py +60 -0
- orchestrator/live_evolution_engine.py +247 -0
- orchestrator/llm.py +291 -0
- orchestrator/local_tool_calling.py +285 -0
- orchestrator/lock.py +404 -0
- orchestrator/mcp_client.py +571 -0
- orchestrator/mcp_server.py +344 -0
- orchestrator/memory_bridge.py +182 -0
- orchestrator/metrics.py +159 -0
- orchestrator/micro_epoch.py +42 -0
- orchestrator/models.py +350 -0
- orchestrator/parsing.py +237 -0
- orchestrator/patch_applier.py +154 -0
- orchestrator/plan_preview.py +138 -0
- orchestrator/plan_quality.py +357 -0
- orchestrator/planner.py +532 -0
- orchestrator/preferences.py +115 -0
- orchestrator/preflight.py +141 -0
- orchestrator/process_guard.py +357 -0
- orchestrator/prometheus_exporter.py +207 -0
- orchestrator/prompts.py +275 -0
- orchestrator/proposal_ledger.py +194 -0
- orchestrator/provenance.py +263 -0
- orchestrator/provider_scheduler.py +394 -0
- orchestrator/qc/__init__.py +153 -0
- orchestrator/qc/aggregator.py +330 -0
- orchestrator/qc/parsing.py +287 -0
- orchestrator/qc/personas.py +242 -0
- orchestrator/qc/runner.py +569 -0
- orchestrator/qc_overrule.py +87 -0
- orchestrator/qc_review.py +282 -0
- orchestrator/quality_lenses.py +314 -0
- orchestrator/quality_plan.py +449 -0
- orchestrator/quality_plane.py +103 -0
- orchestrator/reconcile.py +191 -0
- orchestrator/replanner.py +433 -0
- orchestrator/research.py +176 -0
- orchestrator/review_artifact.py +672 -0
- orchestrator/safety.py +271 -0
- orchestrator/schemas.py +230 -0
- orchestrator/scope.py +466 -0
- orchestrator/sensory_radar.py +79 -0
- orchestrator/skill_installer.py +140 -0
- orchestrator/sse_server.py +160 -0
- orchestrator/state.py +871 -0
- orchestrator/subprocess_helper.py +131 -0
- orchestrator/supervisor/__init__.py +184 -0
- orchestrator/supervisor/_shared.py +164 -0
- orchestrator/supervisor/cleanup.py +185 -0
- orchestrator/supervisor/core.py +1680 -0
- orchestrator/supervisor/recovery.py +367 -0
- orchestrator/supervisor/reporting.py +251 -0
- orchestrator/surgical_extractor.py +119 -0
- orchestrator/telemetry.py +61 -0
- orchestrator/templates.py +268 -0
- orchestrator/token_gate.py +245 -0
- orchestrator/tui.py +649 -0
- orchestrator/verifier.py +1103 -0
- orchestrator/webhooks.py +168 -0
- orchestrator/worker.py +469 -0
- orchestrator/worker_adapters.py +815 -0
- orchestrator/worker_pool.py +121 -0
- orchestrator/worktree.py +364 -0
|
@@ -0,0 +1,840 @@
|
|
|
1
|
+
"""Bounded hybrid worker: Implementer -> Critic -> Verifier loop.
|
|
2
|
+
|
|
3
|
+
Two modes:
|
|
4
|
+
- Profile mode (hybrid_profile set): deterministic topology test path.
|
|
5
|
+
- LLM mode (no hybrid_profile): real model calls with budget/parser/verifier.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
15
|
+
|
|
16
|
+
from .contract import check_path_allowed
|
|
17
|
+
from .llm import LLMError, call_llm
|
|
18
|
+
from .token_gate import TokenGateError, check_usage_authoritative, preflight
|
|
19
|
+
|
|
20
|
+
HYBRID_DEFAULT_MAX_TURNS = 3
|
|
21
|
+
HYBRID_ROLES = ("Implementer", "Critic", "Verifier")
|
|
22
|
+
|
|
23
|
+
# Paid-model routing guard: paid/premium models must NEVER be invoked with a
|
|
24
|
+
# bare prompt through the hybrid worker path — the guard lives in the
|
|
25
|
+
# orchestrator routing layer, not the transport.
|
|
26
|
+
PAID_MODELS = {
|
|
27
|
+
"kimi-k2",
|
|
28
|
+
"kimi-k3",
|
|
29
|
+
"claude-opus-5",
|
|
30
|
+
"claude-sonnet-5",
|
|
31
|
+
"claude-fable-5",
|
|
32
|
+
"claude-3-opus",
|
|
33
|
+
"claude-3-7-sonnet",
|
|
34
|
+
"claude-3-5-sonnet",
|
|
35
|
+
"gpt-5.6-sol",
|
|
36
|
+
"gpt-5.6-terra",
|
|
37
|
+
"gpt-5.6-luna",
|
|
38
|
+
"gpt-5.6-cyber",
|
|
39
|
+
"o1",
|
|
40
|
+
"o3",
|
|
41
|
+
"o3-mini",
|
|
42
|
+
"o4-mini",
|
|
43
|
+
"deepseek-v4-pro",
|
|
44
|
+
"deepseek-reasoner",
|
|
45
|
+
"gemini-3.1-pro",
|
|
46
|
+
"gemini-2.5-pro",
|
|
47
|
+
"gemini-1.5-pro",
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
_MASTER_CONTEXT_MARKER = "MASTER_CONTEXT:"
|
|
51
|
+
_COMPLETE_MARKER = "[CONTEXT_COMPLETE]"
|
|
52
|
+
_MASTER_CONTEXT_MIN_CHARS = 12_000
|
|
53
|
+
_MAX_PAID_CONTEXT_CHARS = 200_000
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _guard_paid_model(model: str, prompt: str) -> None:
|
|
57
|
+
"""Fail closed when a paid route is given an unprepared prompt.
|
|
58
|
+
|
|
59
|
+
Prefer an explicit completeness marker over a length heuristic — a
|
|
60
|
+
truncated context can still be long. The length floor remains as a
|
|
61
|
+
fallback so existing prepared payloads keep working. Even a MARKED prompt
|
|
62
|
+
is capped — an enormous context still burns tokens.
|
|
63
|
+
"""
|
|
64
|
+
# Canonicalize model name by matching known paid model substrings
|
|
65
|
+
resolved_model = model.strip().lower()
|
|
66
|
+
is_paid = any(paid_id in resolved_model for paid_id in PAID_MODELS)
|
|
67
|
+
if not is_paid:
|
|
68
|
+
return
|
|
69
|
+
if len(prompt) > _MAX_PAID_CONTEXT_CHARS:
|
|
70
|
+
raise RuntimeError(
|
|
71
|
+
f"Paid model route '{resolved_model}' prompt exceeds hard cap "
|
|
72
|
+
f"{_MAX_PAID_CONTEXT_CHARS} chars ({len(prompt)}); refusing."
|
|
73
|
+
)
|
|
74
|
+
has_marker = _MASTER_CONTEXT_MARKER in prompt or _COMPLETE_MARKER in prompt
|
|
75
|
+
allow_legacy = os.environ.get("ORCH_ALLOW_PAID_LENGTH_FALLBACK") == "1"
|
|
76
|
+
has_legacy_length = allow_legacy and len(prompt) >= _MASTER_CONTEXT_MIN_CHARS
|
|
77
|
+
if not (has_marker or has_legacy_length):
|
|
78
|
+
raise RuntimeError(
|
|
79
|
+
f"Paid model route '{resolved_model}' requires a prepared master-context "
|
|
80
|
+
f"payload ({_COMPLETE_MARKER} marker or {_MASTER_CONTEXT_MARKER} marker); refusing bare prompt."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class HybridStep:
|
|
86
|
+
turn: int
|
|
87
|
+
role: str
|
|
88
|
+
action: str
|
|
89
|
+
status: str
|
|
90
|
+
message: str
|
|
91
|
+
parser_tier: str = ""
|
|
92
|
+
budget: Dict[str, Any] = field(default_factory=dict)
|
|
93
|
+
|
|
94
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
95
|
+
d: Dict[str, Any] = {
|
|
96
|
+
"turn": self.turn,
|
|
97
|
+
"role": self.role,
|
|
98
|
+
"action": self.action,
|
|
99
|
+
"status": self.status,
|
|
100
|
+
"message": self.message,
|
|
101
|
+
}
|
|
102
|
+
if self.parser_tier:
|
|
103
|
+
d["parser_tier"] = self.parser_tier
|
|
104
|
+
if self.budget:
|
|
105
|
+
d["budget"] = self.budget
|
|
106
|
+
return d
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _output_path(workspace_root: str, path: str) -> str:
|
|
110
|
+
return os.path.join(workspace_root, path) if not os.path.isabs(path) else path
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _write_outputs(contract, workspace_root: str, turn: int, repaired: bool = False) -> List[str]:
|
|
114
|
+
artifact_paths: List[str] = []
|
|
115
|
+
for out in contract.outputs:
|
|
116
|
+
rel_path = out["path"]
|
|
117
|
+
full_path = _output_path(workspace_root, rel_path)
|
|
118
|
+
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
|
119
|
+
content = (
|
|
120
|
+
f"HYBRID_OUTPUT\n"
|
|
121
|
+
f"task_id={contract.task_id}\n"
|
|
122
|
+
f"title={contract.title}\n"
|
|
123
|
+
f"objective={contract.objective}\n"
|
|
124
|
+
f"turn={turn}\n"
|
|
125
|
+
f"repaired={str(repaired).lower()}\n"
|
|
126
|
+
)
|
|
127
|
+
with open(full_path, "w", encoding="utf-8") as f:
|
|
128
|
+
f.write(content)
|
|
129
|
+
artifact_paths.append(full_path)
|
|
130
|
+
return artifact_paths
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _write_llm_outputs(
|
|
134
|
+
contract,
|
|
135
|
+
workspace_root: str,
|
|
136
|
+
artifacts: List[Any],
|
|
137
|
+
) -> List[str]:
|
|
138
|
+
artifact_paths: List[str] = []
|
|
139
|
+
for art in artifacts:
|
|
140
|
+
rel_path = art.path
|
|
141
|
+
full_path = _output_path(workspace_root, rel_path)
|
|
142
|
+
os.makedirs(os.path.dirname(full_path), exist_ok=True)
|
|
143
|
+
with open(full_path, "w", encoding="utf-8") as f:
|
|
144
|
+
f.write(art.content)
|
|
145
|
+
artifact_paths.append(full_path)
|
|
146
|
+
return artifact_paths
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _validate_outputs(contract, workspace_root: str) -> Tuple[bool, str]:
|
|
150
|
+
allowed = contract.allowed_paths()
|
|
151
|
+
denied = contract.denied_paths()
|
|
152
|
+
for out in contract.outputs:
|
|
153
|
+
path = out["path"]
|
|
154
|
+
ok, err = check_path_allowed(path, allowed, denied, workspace_root)
|
|
155
|
+
if not ok:
|
|
156
|
+
return False, f"scope_violation: {err}"
|
|
157
|
+
full_path = _output_path(workspace_root, path)
|
|
158
|
+
if not os.path.isfile(full_path):
|
|
159
|
+
return False, f"missing_output: {path}"
|
|
160
|
+
try:
|
|
161
|
+
with open(full_path, "r", encoding="utf-8") as f:
|
|
162
|
+
data = f.read().strip()
|
|
163
|
+
except OSError as e:
|
|
164
|
+
return False, f"read_error: {path}: {e}"
|
|
165
|
+
if not data:
|
|
166
|
+
return False, f"empty_output: {path}"
|
|
167
|
+
return True, "ok"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _write_trace(run_dir: str, trace: List[HybridStep]) -> str:
|
|
171
|
+
path = os.path.join(run_dir, "hybrid_trace.json")
|
|
172
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
173
|
+
json.dump([step.to_dict() for step in trace], f, indent=2, ensure_ascii=False)
|
|
174
|
+
return path
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _call_llm(
|
|
178
|
+
role: str,
|
|
179
|
+
model: str,
|
|
180
|
+
prompt: str,
|
|
181
|
+
workspace_root: str,
|
|
182
|
+
timeout_sec: int,
|
|
183
|
+
) -> Dict[str, Any]:
|
|
184
|
+
"""Call an LLM via the generic transport and return structured result.
|
|
185
|
+
|
|
186
|
+
Supports every provider prefix from ``orchestrator.llm`` (openai,
|
|
187
|
+
anthropic, gemini, deepseek, any). The token gate runs pre-flight and
|
|
188
|
+
post-hoc (authoritative usage check).
|
|
189
|
+
|
|
190
|
+
Returns dict with ok, raw, stderr, exit_code, prompt_tokens, completion_tokens.
|
|
191
|
+
"""
|
|
192
|
+
_guard_paid_model(model, prompt)
|
|
193
|
+
estimated_prompt = max(1, len(prompt) // 4)
|
|
194
|
+
|
|
195
|
+
# TOKEN GATE: pre-flight refusal before any bytes leave.
|
|
196
|
+
try:
|
|
197
|
+
preflight(len(prompt), None, caller=f"hybrid_worker:{model}")
|
|
198
|
+
except TokenGateError as e:
|
|
199
|
+
return {
|
|
200
|
+
"ok": False,
|
|
201
|
+
"raw": "",
|
|
202
|
+
"stderr": str(e),
|
|
203
|
+
"exit_code": 3,
|
|
204
|
+
"prompt_tokens": estimated_prompt,
|
|
205
|
+
"completion_tokens": 0,
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
try:
|
|
209
|
+
from .models import ThinkingBudget
|
|
210
|
+
|
|
211
|
+
tb = ThinkingBudget.budget_for(role)
|
|
212
|
+
resp = call_llm(prompt, model, thinking_budget=tb, timeout_s=timeout_sec)
|
|
213
|
+
except LLMError as e:
|
|
214
|
+
return {
|
|
215
|
+
"ok": False,
|
|
216
|
+
"raw": "",
|
|
217
|
+
"stderr": str(e),
|
|
218
|
+
"exit_code": -1,
|
|
219
|
+
"prompt_tokens": estimated_prompt,
|
|
220
|
+
"completion_tokens": 0,
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
raw = resp["text"]
|
|
224
|
+
# TOKEN GATE authoritative: the API reported actual usage over the cap.
|
|
225
|
+
over_cap = check_usage_authoritative(
|
|
226
|
+
resp.get("usage", {}) or {},
|
|
227
|
+
estimated_prompt,
|
|
228
|
+
caller=f"hybrid_worker:{model}",
|
|
229
|
+
model=model,
|
|
230
|
+
)
|
|
231
|
+
if over_cap:
|
|
232
|
+
return {
|
|
233
|
+
"ok": False,
|
|
234
|
+
"raw": raw,
|
|
235
|
+
"stderr": (
|
|
236
|
+
"TOKEN GATE HARD STOP: provider-reported usage over cap. See scratch/token_gate_violations.jsonl."
|
|
237
|
+
),
|
|
238
|
+
"exit_code": 3,
|
|
239
|
+
"prompt_tokens": estimated_prompt,
|
|
240
|
+
"completion_tokens": max(1, len(raw) // 4),
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return {
|
|
244
|
+
"ok": True,
|
|
245
|
+
"raw": raw,
|
|
246
|
+
"stderr": "",
|
|
247
|
+
"exit_code": 0,
|
|
248
|
+
"prompt_tokens": estimated_prompt,
|
|
249
|
+
"completion_tokens": max(1, len(raw) // 4),
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ---------------------------------------------------------------
|
|
254
|
+
# Profile-based deterministic path (existing tests depend on this)
|
|
255
|
+
# ---------------------------------------------------------------
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _run_deterministic_loop(
|
|
259
|
+
contract,
|
|
260
|
+
workspace_root: str,
|
|
261
|
+
run_dir: str,
|
|
262
|
+
profile: str,
|
|
263
|
+
max_turns: int,
|
|
264
|
+
repair_budget: int,
|
|
265
|
+
timeout_sec: int,
|
|
266
|
+
brief_text: str,
|
|
267
|
+
) -> Dict[str, Any]:
|
|
268
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
269
|
+
start = time.time()
|
|
270
|
+
artifact_paths: List[str] = []
|
|
271
|
+
trace: List[HybridStep] = []
|
|
272
|
+
repaired = False
|
|
273
|
+
final_status = "failure"
|
|
274
|
+
stderr_parts: List[str] = []
|
|
275
|
+
|
|
276
|
+
def _fail(exit_code: int, reason: str) -> Dict[str, Any]:
|
|
277
|
+
trace_path = _write_trace(run_dir, trace)
|
|
278
|
+
output_log_path = os.path.join(run_dir, "worker_output.log")
|
|
279
|
+
with open(output_log_path, "w", encoding="utf-8") as f:
|
|
280
|
+
f.write("HYBRID MODE (deterministic)\n")
|
|
281
|
+
f.write(f"BRIEF\n{brief_text}\n\n")
|
|
282
|
+
for step in trace:
|
|
283
|
+
f.write(json.dumps(step.to_dict(), ensure_ascii=False) + "\n")
|
|
284
|
+
f.write(f"FINAL: {reason}\n")
|
|
285
|
+
elapsed = time.time() - start
|
|
286
|
+
return {
|
|
287
|
+
"success": False,
|
|
288
|
+
"stdout": "",
|
|
289
|
+
"stderr": reason,
|
|
290
|
+
"exit_code": exit_code,
|
|
291
|
+
"elapsed_sec": elapsed,
|
|
292
|
+
"artifact_paths": artifact_paths + [trace_path, output_log_path],
|
|
293
|
+
"hybrid_trace_path": trace_path,
|
|
294
|
+
"turns": len(trace),
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
for turn in range(1, max_turns + 1):
|
|
298
|
+
if profile == "budget_exhausted" and turn == max_turns:
|
|
299
|
+
trace.append(HybridStep(turn, "Implementer", "write_outputs", "pass", "budget pressure mode"))
|
|
300
|
+
return _fail(2, "hybrid budget exhausted before completion")
|
|
301
|
+
|
|
302
|
+
if profile == "repair_then_success" and not repaired and turn == 1:
|
|
303
|
+
artifact_paths = _write_outputs(contract, workspace_root, turn, repaired=False)
|
|
304
|
+
if artifact_paths:
|
|
305
|
+
with open(artifact_paths[0], "w", encoding="utf-8") as f:
|
|
306
|
+
f.write("")
|
|
307
|
+
trace.append(HybridStep(turn, "Implementer", "write_outputs", "pass", "initial artifact produced"))
|
|
308
|
+
else:
|
|
309
|
+
artifact_paths = _write_outputs(contract, workspace_root, turn, repaired=repaired)
|
|
310
|
+
trace.append(HybridStep(turn, "Implementer", "write_outputs", "pass", "artifact set written"))
|
|
311
|
+
|
|
312
|
+
ok, reason = _validate_outputs(contract, workspace_root)
|
|
313
|
+
if profile == "repair_then_success" and not repaired and turn == 1:
|
|
314
|
+
ok = False
|
|
315
|
+
reason = "missing_output: forced first-pass repair path"
|
|
316
|
+
|
|
317
|
+
if not ok:
|
|
318
|
+
trace.append(HybridStep(turn, "Critic", "validate_outputs", "fail", reason))
|
|
319
|
+
stderr_parts.append(reason)
|
|
320
|
+
if repair_budget <= 0:
|
|
321
|
+
return _fail(3, "hybrid repair budget exhausted")
|
|
322
|
+
repair_budget -= 1
|
|
323
|
+
repaired = True
|
|
324
|
+
trace.append(HybridStep(turn, "Verifier", "repair_outputs", "pass", "bounded repair applied"))
|
|
325
|
+
artifact_paths = _write_outputs(contract, workspace_root, turn, repaired=True)
|
|
326
|
+
continue
|
|
327
|
+
|
|
328
|
+
trace.append(HybridStep(turn, "Critic", "validate_outputs", "pass", "artifact set accepted"))
|
|
329
|
+
verifier_ok, verifier_reason = _validate_outputs(contract, workspace_root)
|
|
330
|
+
trace.append(
|
|
331
|
+
HybridStep(turn, "Verifier", "check_artifacts", "pass" if verifier_ok else "fail", verifier_reason)
|
|
332
|
+
)
|
|
333
|
+
if verifier_ok:
|
|
334
|
+
final_status = "success"
|
|
335
|
+
break
|
|
336
|
+
|
|
337
|
+
if final_status != "success":
|
|
338
|
+
return _fail(2, "hybrid turn budget exhausted")
|
|
339
|
+
|
|
340
|
+
trace_path = _write_trace(run_dir, trace)
|
|
341
|
+
output_log_path = os.path.join(run_dir, "worker_output.log")
|
|
342
|
+
with open(output_log_path, "w", encoding="utf-8") as f:
|
|
343
|
+
f.write("HYBRID MODE (deterministic)\n")
|
|
344
|
+
f.write(f"BRIEF\n{brief_text}\n\n")
|
|
345
|
+
for step in trace:
|
|
346
|
+
f.write(json.dumps(step.to_dict(), ensure_ascii=False) + "\n")
|
|
347
|
+
f.write("FINAL: success\n")
|
|
348
|
+
elapsed = time.time() - start
|
|
349
|
+
return {
|
|
350
|
+
"success": True,
|
|
351
|
+
"stdout": "hybrid worker completed",
|
|
352
|
+
"stderr": "\n".join(stderr_parts),
|
|
353
|
+
"exit_code": 0,
|
|
354
|
+
"elapsed_sec": elapsed,
|
|
355
|
+
"artifact_paths": artifact_paths + [trace_path, output_log_path],
|
|
356
|
+
"hybrid_trace_path": trace_path,
|
|
357
|
+
"turns": len(trace),
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# ---------------------------------------------------------------
|
|
362
|
+
# Real LLM loop path (production)
|
|
363
|
+
# ---------------------------------------------------------------
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _finalize_hybrid_run(
|
|
367
|
+
run_dir: str,
|
|
368
|
+
brief_text: str,
|
|
369
|
+
trace: List[HybridStep],
|
|
370
|
+
artifact_paths: List[str],
|
|
371
|
+
start: float,
|
|
372
|
+
success: bool,
|
|
373
|
+
exit_code: int,
|
|
374
|
+
stdout: str,
|
|
375
|
+
stderr: str,
|
|
376
|
+
final_message: str,
|
|
377
|
+
) -> Dict[str, Any]:
|
|
378
|
+
trace_path = _write_trace(run_dir, trace)
|
|
379
|
+
output_log_path = os.path.join(run_dir, "worker_output.log")
|
|
380
|
+
with open(output_log_path, "w", encoding="utf-8") as f:
|
|
381
|
+
f.write("HYBRID MODE (llm)\n")
|
|
382
|
+
f.write(f"BRIEF\n{brief_text}\n\n")
|
|
383
|
+
for step in trace:
|
|
384
|
+
f.write(json.dumps(step.to_dict(), ensure_ascii=False) + "\n")
|
|
385
|
+
f.write(f"FINAL: {final_message}\n")
|
|
386
|
+
elapsed = time.time() - start
|
|
387
|
+
return {
|
|
388
|
+
"success": success,
|
|
389
|
+
"stdout": stdout,
|
|
390
|
+
"stderr": stderr,
|
|
391
|
+
"exit_code": exit_code,
|
|
392
|
+
"elapsed_sec": elapsed,
|
|
393
|
+
"artifact_paths": artifact_paths + [trace_path, output_log_path],
|
|
394
|
+
"hybrid_trace_path": trace_path,
|
|
395
|
+
"turns": len(trace),
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
@dataclass
|
|
400
|
+
class _LLMLoopContext:
|
|
401
|
+
contract: Any
|
|
402
|
+
workspace_root: str
|
|
403
|
+
run_dir: str
|
|
404
|
+
inner_model: str
|
|
405
|
+
critic_model: str
|
|
406
|
+
max_turns: int
|
|
407
|
+
repair_budget: int
|
|
408
|
+
timeout_sec: int
|
|
409
|
+
brief_text: str
|
|
410
|
+
supervisor_attempt: int
|
|
411
|
+
ledger: Any
|
|
412
|
+
budget_guard: Any
|
|
413
|
+
loop_detector: Any
|
|
414
|
+
acceptance_summary: str
|
|
415
|
+
expected_paths: List[str]
|
|
416
|
+
artifact_paths: List[str] = field(default_factory=list)
|
|
417
|
+
trace: List[HybridStep] = field(default_factory=list)
|
|
418
|
+
stderr_parts: List[str] = field(default_factory=list)
|
|
419
|
+
prior_failures: List[Dict[str, Any]] = field(default_factory=list)
|
|
420
|
+
critic_feedback: Optional[str] = None
|
|
421
|
+
verifier_feedback: Optional[str] = None
|
|
422
|
+
parse_failure_count: int = 0
|
|
423
|
+
max_parse_failures: int = 2
|
|
424
|
+
turn: int = 1
|
|
425
|
+
final_status: str = "failure"
|
|
426
|
+
start: float = field(default_factory=time.time)
|
|
427
|
+
|
|
428
|
+
def budget_snapshot(self) -> Dict[str, Any]:
|
|
429
|
+
return {
|
|
430
|
+
"total_tokens": self.ledger.total_tokens,
|
|
431
|
+
"total_cost_usd": round(self.ledger.total_cost_usd, 6),
|
|
432
|
+
"calls": self.ledger.call_count,
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
def record_step(
|
|
436
|
+
self,
|
|
437
|
+
role: str,
|
|
438
|
+
action: str,
|
|
439
|
+
status: str,
|
|
440
|
+
message: str,
|
|
441
|
+
parser_tier: str = "",
|
|
442
|
+
turn: Optional[int] = None,
|
|
443
|
+
) -> None:
|
|
444
|
+
step = HybridStep(
|
|
445
|
+
turn=self.turn if turn is None else turn,
|
|
446
|
+
role=role,
|
|
447
|
+
action=action,
|
|
448
|
+
status=status,
|
|
449
|
+
message=message,
|
|
450
|
+
parser_tier=parser_tier,
|
|
451
|
+
budget=self.budget_snapshot(),
|
|
452
|
+
)
|
|
453
|
+
self.trace.append(step)
|
|
454
|
+
|
|
455
|
+
def fail(self, exit_code: int, reason: str) -> Dict[str, Any]:
|
|
456
|
+
return _finalize_hybrid_run(
|
|
457
|
+
run_dir=self.run_dir,
|
|
458
|
+
brief_text=self.brief_text,
|
|
459
|
+
trace=self.trace,
|
|
460
|
+
artifact_paths=self.artifact_paths,
|
|
461
|
+
start=self.start,
|
|
462
|
+
success=False,
|
|
463
|
+
exit_code=exit_code,
|
|
464
|
+
stdout="",
|
|
465
|
+
stderr=reason,
|
|
466
|
+
final_message=reason,
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
def succeed(self) -> Dict[str, Any]:
|
|
470
|
+
return _finalize_hybrid_run(
|
|
471
|
+
run_dir=self.run_dir,
|
|
472
|
+
brief_text=self.brief_text,
|
|
473
|
+
trace=self.trace,
|
|
474
|
+
artifact_paths=self.artifact_paths,
|
|
475
|
+
start=self.start,
|
|
476
|
+
success=True,
|
|
477
|
+
exit_code=0,
|
|
478
|
+
stdout="hybrid worker completed",
|
|
479
|
+
stderr="\n".join(self.stderr_parts),
|
|
480
|
+
final_message="success",
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
@dataclass
|
|
485
|
+
class _StageOutcome:
|
|
486
|
+
action: str
|
|
487
|
+
data: Any = None
|
|
488
|
+
exit_dict: Optional[Dict[str, Any]] = None
|
|
489
|
+
|
|
490
|
+
@classmethod
|
|
491
|
+
def continue_with(cls, data: Any = None) -> _StageOutcome:
|
|
492
|
+
return cls("continue", data=data)
|
|
493
|
+
|
|
494
|
+
@classmethod
|
|
495
|
+
def retry(cls) -> _StageOutcome:
|
|
496
|
+
return cls("retry")
|
|
497
|
+
|
|
498
|
+
@classmethod
|
|
499
|
+
def pass_loop(cls) -> _StageOutcome:
|
|
500
|
+
return cls("pass")
|
|
501
|
+
|
|
502
|
+
@classmethod
|
|
503
|
+
def fail(cls, exit_dict: Dict[str, Any]) -> _StageOutcome:
|
|
504
|
+
return cls("fail", exit_dict=exit_dict)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _init_llm_loop_context(
|
|
508
|
+
contract,
|
|
509
|
+
workspace_root: str,
|
|
510
|
+
run_dir: str,
|
|
511
|
+
inner_model: str,
|
|
512
|
+
max_turns: int,
|
|
513
|
+
repair_budget: int,
|
|
514
|
+
timeout_sec: int,
|
|
515
|
+
brief_text: str,
|
|
516
|
+
supervisor_attempt: int,
|
|
517
|
+
) -> _LLMLoopContext:
|
|
518
|
+
from .budget import BudgetGuard, LoopDetector, UsageLedger
|
|
519
|
+
from .prompts import summarize_acceptance
|
|
520
|
+
|
|
521
|
+
max_tokens = int(contract.worker.get("hybrid_max_tokens", 100_000))
|
|
522
|
+
max_cost_usd = float(contract.worker.get("hybrid_max_cost_usd", 0.50))
|
|
523
|
+
critic_model = contract.worker.get("hybrid_critic_model", inner_model)
|
|
524
|
+
if critic_model.startswith("hybrid:"):
|
|
525
|
+
critic_model = critic_model[7:]
|
|
526
|
+
|
|
527
|
+
ledger = UsageLedger()
|
|
528
|
+
budget_guard = BudgetGuard(max_tokens=max_tokens, max_cost_usd=max_cost_usd, ledger=ledger)
|
|
529
|
+
loop_detector = LoopDetector(
|
|
530
|
+
max_identical_outputs=int(contract.worker.get("hybrid_max_identical_outputs", 2)),
|
|
531
|
+
max_identical_failures=int(contract.worker.get("hybrid_max_identical_failures", 2)),
|
|
532
|
+
max_identical_verdicts=int(contract.worker.get("hybrid_max_identical_verdicts", 3)),
|
|
533
|
+
)
|
|
534
|
+
acceptance_summary = summarize_acceptance(contract.acceptance_checks)
|
|
535
|
+
expected_paths = [out["path"] for out in contract.outputs]
|
|
536
|
+
|
|
537
|
+
return _LLMLoopContext(
|
|
538
|
+
contract=contract,
|
|
539
|
+
workspace_root=workspace_root,
|
|
540
|
+
run_dir=run_dir,
|
|
541
|
+
inner_model=inner_model,
|
|
542
|
+
critic_model=critic_model,
|
|
543
|
+
max_turns=max_turns,
|
|
544
|
+
repair_budget=repair_budget,
|
|
545
|
+
timeout_sec=timeout_sec,
|
|
546
|
+
brief_text=brief_text,
|
|
547
|
+
supervisor_attempt=supervisor_attempt,
|
|
548
|
+
ledger=ledger,
|
|
549
|
+
budget_guard=budget_guard,
|
|
550
|
+
loop_detector=loop_detector,
|
|
551
|
+
acceptance_summary=acceptance_summary,
|
|
552
|
+
expected_paths=expected_paths,
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _execute_implementer_stage(ctx: _LLMLoopContext) -> _StageOutcome:
|
|
557
|
+
from .budget import BudgetExhaustedError
|
|
558
|
+
from .prompts import build_implementer_prompt
|
|
559
|
+
|
|
560
|
+
try:
|
|
561
|
+
ctx.budget_guard.check_before_call(estimated_prompt_tokens=5000, estimated_completion_tokens=2000)
|
|
562
|
+
except BudgetExhaustedError as e:
|
|
563
|
+
ctx.record_step("BudgetGuard", "preflight", "fail", str(e))
|
|
564
|
+
return _StageOutcome.fail(ctx.fail(5, f"budget exhausted: {e}"))
|
|
565
|
+
|
|
566
|
+
quality_spec = getattr(ctx.contract, "quality_spec", {})
|
|
567
|
+
implementer_prompt = build_implementer_prompt(
|
|
568
|
+
title=ctx.contract.title,
|
|
569
|
+
objective=ctx.contract.objective,
|
|
570
|
+
output_paths=ctx.expected_paths,
|
|
571
|
+
acceptance_summary=ctx.acceptance_summary,
|
|
572
|
+
prior_failures=ctx.prior_failures if ctx.prior_failures else None,
|
|
573
|
+
critic_feedback=ctx.critic_feedback,
|
|
574
|
+
verifier_feedback=ctx.verifier_feedback,
|
|
575
|
+
max_turns=ctx.max_turns,
|
|
576
|
+
current_turn=ctx.turn,
|
|
577
|
+
quality_spec=quality_spec,
|
|
578
|
+
supervisor_attempt=ctx.supervisor_attempt,
|
|
579
|
+
strategy_fingerprint=str(ctx.contract.worker.get("_strategy_fingerprint", "") or ""),
|
|
580
|
+
prior_fingerprint=str(ctx.contract.worker.get("_prior_fingerprint", "") or ""),
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
llm_result = _call_llm("Implementer", ctx.inner_model, implementer_prompt, ctx.workspace_root, ctx.timeout_sec)
|
|
584
|
+
ctx.ledger.record("Implementer", ctx.inner_model, llm_result["prompt_tokens"], llm_result["completion_tokens"])
|
|
585
|
+
|
|
586
|
+
if not llm_result["ok"]:
|
|
587
|
+
msg = f"LLM call failed (exit={llm_result['exit_code']}): {llm_result['stderr'][:200]}"
|
|
588
|
+
ctx.record_step("Implementer", "llm_call", "fail", msg)
|
|
589
|
+
ctx.stderr_parts.append(msg)
|
|
590
|
+
ctx.prior_failures.append({"message": msg})
|
|
591
|
+
if ctx.loop_detector.record_failure(msg):
|
|
592
|
+
return _StageOutcome.fail(ctx.fail(6, f"stuck loop: {msg}"))
|
|
593
|
+
return _StageOutcome.retry()
|
|
594
|
+
|
|
595
|
+
ctx.record_step("Implementer", "llm_call", "pass", "implementer produced output")
|
|
596
|
+
return _StageOutcome.continue_with(llm_result["raw"])
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _execute_parser_scope_stage(ctx: _LLMLoopContext, raw_text: str) -> _StageOutcome:
|
|
600
|
+
from .parsing import parse_llm_artifacts
|
|
601
|
+
|
|
602
|
+
parse_result = parse_llm_artifacts(raw_text, ctx.expected_paths)
|
|
603
|
+
if not parse_result.ok:
|
|
604
|
+
ctx.parse_failure_count += 1
|
|
605
|
+
msg = f"parse failed: {parse_result.error}"
|
|
606
|
+
ctx.record_step("Implementer", "parse_output", "fail", msg, parser_tier="none")
|
|
607
|
+
ctx.stderr_parts.append(msg)
|
|
608
|
+
ctx.prior_failures.append({"message": msg})
|
|
609
|
+
if ctx.parse_failure_count >= ctx.max_parse_failures:
|
|
610
|
+
return _StageOutcome.fail(ctx.fail(7, f"parse failure budget exhausted: {msg}"))
|
|
611
|
+
if ctx.loop_detector.record_failure(f"parse:{parse_result.error}"):
|
|
612
|
+
return _StageOutcome.fail(ctx.fail(6, "stuck loop: repeated parse failure"))
|
|
613
|
+
return _StageOutcome.retry()
|
|
614
|
+
|
|
615
|
+
parser_tier = parse_result.artifacts[0].parser_tier if parse_result.artifacts else "?"
|
|
616
|
+
ctx.record_step("Parser", "parse_output", "pass", f"parsed via {parser_tier}", parser_tier=parser_tier)
|
|
617
|
+
|
|
618
|
+
current_artifacts = _write_llm_outputs(ctx.contract, ctx.workspace_root, parse_result.artifacts)
|
|
619
|
+
for ap in current_artifacts:
|
|
620
|
+
if ap not in ctx.artifact_paths:
|
|
621
|
+
ctx.artifact_paths.append(ap)
|
|
622
|
+
|
|
623
|
+
scope_ok, scope_reason = _validate_outputs(ctx.contract, ctx.workspace_root)
|
|
624
|
+
if not scope_ok:
|
|
625
|
+
msg = f"scope violation: {scope_reason}"
|
|
626
|
+
ctx.record_step("Critic", "validate_outputs", "fail", msg, parser_tier=parser_tier)
|
|
627
|
+
return _StageOutcome.fail(ctx.fail(4, msg))
|
|
628
|
+
|
|
629
|
+
content_hashes = [a.content for a in parse_result.artifacts]
|
|
630
|
+
stuck = ctx.loop_detector.record_outputs(content_hashes)
|
|
631
|
+
if stuck:
|
|
632
|
+
msg = f"stuck loop: {stuck}"
|
|
633
|
+
ctx.record_step("LoopDetector", "check", "fail", msg, parser_tier=parser_tier)
|
|
634
|
+
return _StageOutcome.fail(ctx.fail(6, msg))
|
|
635
|
+
|
|
636
|
+
return _StageOutcome.continue_with((parse_result.artifacts, parser_tier))
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def _execute_precheck_stage(ctx: _LLMLoopContext, parser_tier: str) -> _StageOutcome:
|
|
640
|
+
from .prompts import summarize_verifier_results
|
|
641
|
+
from .verifier import run_checks
|
|
642
|
+
|
|
643
|
+
precheck_results = run_checks(ctx.contract.acceptance_checks, ctx.workspace_root)
|
|
644
|
+
precheck_passed = all(r.passed for r in precheck_results)
|
|
645
|
+
if not precheck_passed:
|
|
646
|
+
verifier_results_dict = [r.to_dict() for r in precheck_results]
|
|
647
|
+
ctx.verifier_feedback = summarize_verifier_results(verifier_results_dict)
|
|
648
|
+
msg = "deterministic precheck failed"
|
|
649
|
+
ctx.record_step("Verifier", "precheck", "fail", msg, parser_tier=parser_tier)
|
|
650
|
+
ctx.stderr_parts.append(msg)
|
|
651
|
+
ctx.prior_failures.append({"message": msg, "verifier": verifier_results_dict})
|
|
652
|
+
if ctx.loop_detector.record_failure(f"precheck:{msg}"):
|
|
653
|
+
return _StageOutcome.fail(ctx.fail(6, "stuck loop: repeated precheck failure"))
|
|
654
|
+
return _StageOutcome.retry()
|
|
655
|
+
|
|
656
|
+
ctx.record_step("Verifier", "precheck", "pass", "deterministic checks passed", parser_tier=parser_tier)
|
|
657
|
+
return _StageOutcome.continue_with(precheck_results)
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def _parse_critic_payload(critic_result: Dict[str, Any]) -> Tuple[str, str]:
|
|
661
|
+
if not critic_result.get("ok"):
|
|
662
|
+
return "FAIL", critic_result.get("stderr", "")[:300] or "critic LLM call failed"
|
|
663
|
+
try:
|
|
664
|
+
parsed = json.loads(critic_result.get("raw", ""))
|
|
665
|
+
if isinstance(parsed, dict):
|
|
666
|
+
return parsed.get("status", "FAIL"), parsed.get("implementer_guidance", "no guidance provided")
|
|
667
|
+
return "FAIL", "critic output was not a JSON object"
|
|
668
|
+
except (json.JSONDecodeError, ValueError):
|
|
669
|
+
return "FAIL", "critic output was not valid JSON"
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _execute_critic_stage(
|
|
673
|
+
ctx: _LLMLoopContext,
|
|
674
|
+
artifacts: List[Any],
|
|
675
|
+
precheck_results: List[Any],
|
|
676
|
+
parser_tier: str,
|
|
677
|
+
) -> _StageOutcome:
|
|
678
|
+
from .prompts import build_critic_prompt
|
|
679
|
+
|
|
680
|
+
artifact_summaries = [{"path": a.path, "content": a.content} for a in artifacts]
|
|
681
|
+
verifier_results_dict = [r.to_dict() for r in precheck_results]
|
|
682
|
+
quality_spec = getattr(ctx.contract, "quality_spec", {})
|
|
683
|
+
critic_prompt = build_critic_prompt(
|
|
684
|
+
title=ctx.contract.title,
|
|
685
|
+
objective=ctx.contract.objective,
|
|
686
|
+
output_paths=ctx.expected_paths,
|
|
687
|
+
acceptance_summary=ctx.acceptance_summary,
|
|
688
|
+
artifact_summaries=artifact_summaries,
|
|
689
|
+
verifier_results=verifier_results_dict,
|
|
690
|
+
quality_spec=quality_spec,
|
|
691
|
+
)
|
|
692
|
+
|
|
693
|
+
critic_result = _call_llm("Critic", ctx.critic_model, critic_prompt, ctx.workspace_root, ctx.timeout_sec)
|
|
694
|
+
ctx.ledger.record("Critic", ctx.critic_model, critic_result["prompt_tokens"], critic_result["completion_tokens"])
|
|
695
|
+
|
|
696
|
+
critic_verdict, critic_feedback = _parse_critic_payload(critic_result)
|
|
697
|
+
ctx.critic_feedback = critic_feedback
|
|
698
|
+
|
|
699
|
+
stuck_verdict = ctx.loop_detector.record_critic_verdict(critic_verdict)
|
|
700
|
+
if stuck_verdict:
|
|
701
|
+
ctx.record_step("Critic", "evaluate", "fail", stuck_verdict, parser_tier=parser_tier)
|
|
702
|
+
return _StageOutcome.fail(ctx.fail(6, stuck_verdict))
|
|
703
|
+
|
|
704
|
+
if critic_verdict == "PASS":
|
|
705
|
+
ctx.record_step("Critic", "evaluate", "pass", "critic approved", parser_tier=parser_tier)
|
|
706
|
+
return _StageOutcome.pass_loop()
|
|
707
|
+
|
|
708
|
+
msg = critic_feedback[:200]
|
|
709
|
+
ctx.record_step("Critic", "evaluate", "fail", msg, parser_tier=parser_tier)
|
|
710
|
+
ctx.stderr_parts.append(f"critic: {msg}")
|
|
711
|
+
ctx.prior_failures.append({"message": f"critic: {msg}"})
|
|
712
|
+
if ctx.repair_budget <= 0:
|
|
713
|
+
return _StageOutcome.fail(ctx.fail(3, "hybrid repair budget exhausted"))
|
|
714
|
+
ctx.repair_budget -= 1
|
|
715
|
+
return _StageOutcome.retry()
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def _execute_turn(ctx: _LLMLoopContext) -> _StageOutcome:
|
|
719
|
+
imp_res = _execute_implementer_stage(ctx)
|
|
720
|
+
if imp_res.action != "continue":
|
|
721
|
+
return imp_res
|
|
722
|
+
|
|
723
|
+
parse_res = _execute_parser_scope_stage(ctx, imp_res.data)
|
|
724
|
+
if parse_res.action != "continue":
|
|
725
|
+
return parse_res
|
|
726
|
+
|
|
727
|
+
artifacts, parser_tier = parse_res.data
|
|
728
|
+
precheck_res = _execute_precheck_stage(ctx, parser_tier)
|
|
729
|
+
if precheck_res.action != "continue":
|
|
730
|
+
return precheck_res
|
|
731
|
+
|
|
732
|
+
return _execute_critic_stage(ctx, artifacts, precheck_res.data, parser_tier)
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def _execute_final_verification(ctx: _LLMLoopContext) -> Optional[Dict[str, Any]]:
|
|
736
|
+
from .verifier import run_verification
|
|
737
|
+
|
|
738
|
+
final_passed, final_results, _ = run_verification(ctx.contract, ctx.workspace_root, ctx.run_dir)
|
|
739
|
+
if not final_passed:
|
|
740
|
+
msg = "final verification failed"
|
|
741
|
+
ctx.record_step("Verifier", "final_check", "fail", msg)
|
|
742
|
+
return ctx.fail(1, msg)
|
|
743
|
+
return None
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _run_llm_loop(
|
|
747
|
+
contract,
|
|
748
|
+
workspace_root: str,
|
|
749
|
+
run_dir: str,
|
|
750
|
+
inner_model: str,
|
|
751
|
+
max_turns: int,
|
|
752
|
+
repair_budget: int,
|
|
753
|
+
timeout_sec: int,
|
|
754
|
+
brief_text: str,
|
|
755
|
+
supervisor_attempt: int = 1,
|
|
756
|
+
) -> Dict[str, Any]:
|
|
757
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
758
|
+
ctx = _init_llm_loop_context(
|
|
759
|
+
contract=contract,
|
|
760
|
+
workspace_root=workspace_root,
|
|
761
|
+
run_dir=run_dir,
|
|
762
|
+
inner_model=inner_model,
|
|
763
|
+
max_turns=max_turns,
|
|
764
|
+
repair_budget=repair_budget,
|
|
765
|
+
timeout_sec=timeout_sec,
|
|
766
|
+
brief_text=brief_text,
|
|
767
|
+
supervisor_attempt=supervisor_attempt,
|
|
768
|
+
)
|
|
769
|
+
|
|
770
|
+
for turn in range(1, max_turns + 1):
|
|
771
|
+
ctx.turn = turn
|
|
772
|
+
outcome = _execute_turn(ctx)
|
|
773
|
+
if outcome.action == "fail":
|
|
774
|
+
return outcome.exit_dict # type: ignore[return-value]
|
|
775
|
+
if outcome.action == "pass":
|
|
776
|
+
ctx.final_status = "success"
|
|
777
|
+
break
|
|
778
|
+
|
|
779
|
+
if ctx.final_status != "success":
|
|
780
|
+
return ctx.fail(2, "hybrid turn budget exhausted")
|
|
781
|
+
|
|
782
|
+
final_fail = _execute_final_verification(ctx)
|
|
783
|
+
if final_fail:
|
|
784
|
+
return final_fail
|
|
785
|
+
|
|
786
|
+
return ctx.succeed()
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
# ---------------------------------------------------------------
|
|
790
|
+
# Public entry point
|
|
791
|
+
# ---------------------------------------------------------------
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def run_hybrid_worker(
|
|
795
|
+
contract,
|
|
796
|
+
workspace_root: str,
|
|
797
|
+
run_dir: str,
|
|
798
|
+
previous_failures=None,
|
|
799
|
+
changed_approach=None,
|
|
800
|
+
timeout_sec: int = 300,
|
|
801
|
+
brief_text: str = "",
|
|
802
|
+
supervisor_attempt: int = 1,
|
|
803
|
+
) -> Dict[str, Any]:
|
|
804
|
+
"""Run the bounded hybrid worker loop.
|
|
805
|
+
|
|
806
|
+
Two modes:
|
|
807
|
+
- If contract.worker has 'hybrid_profile': deterministic profile path
|
|
808
|
+
- Otherwise: real LLM loop with budget/parser/verifier
|
|
809
|
+
"""
|
|
810
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
811
|
+
max_turns = int(contract.worker.get("hybrid_max_turns", HYBRID_DEFAULT_MAX_TURNS))
|
|
812
|
+
repair_budget = int(contract.worker.get("hybrid_repair_budget", 1))
|
|
813
|
+
|
|
814
|
+
if "hybrid_profile" in contract.worker:
|
|
815
|
+
profile = str(contract.worker["hybrid_profile"])
|
|
816
|
+
return _run_deterministic_loop(
|
|
817
|
+
contract,
|
|
818
|
+
workspace_root,
|
|
819
|
+
run_dir,
|
|
820
|
+
profile=profile,
|
|
821
|
+
max_turns=max_turns,
|
|
822
|
+
repair_budget=repair_budget,
|
|
823
|
+
timeout_sec=timeout_sec,
|
|
824
|
+
brief_text=brief_text,
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
inner_model_raw = contract.worker.get("model", "")
|
|
828
|
+
inner_model = inner_model_raw.replace("hybrid:", "", 1)
|
|
829
|
+
|
|
830
|
+
return _run_llm_loop(
|
|
831
|
+
contract,
|
|
832
|
+
workspace_root,
|
|
833
|
+
run_dir,
|
|
834
|
+
inner_model=inner_model,
|
|
835
|
+
max_turns=max_turns,
|
|
836
|
+
repair_budget=repair_budget,
|
|
837
|
+
timeout_sec=timeout_sec,
|
|
838
|
+
brief_text=brief_text,
|
|
839
|
+
supervisor_attempt=supervisor_attempt,
|
|
840
|
+
)
|