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,1680 @@
|
|
|
1
|
+
"""Core - extracted verbatim from the former monolithic supervisor.py."""
|
|
2
|
+
|
|
3
|
+
from orchestrator import dag_validator as dv
|
|
4
|
+
from orchestrator.dag_validator import DagValidationError
|
|
5
|
+
from orchestrator.events import get_bus
|
|
6
|
+
from orchestrator.supervisor._shared import (
|
|
7
|
+
DEFAULT_RUN_DIR as DEFAULT_RUN_DIR,
|
|
8
|
+
)
|
|
9
|
+
from orchestrator.supervisor._shared import (
|
|
10
|
+
FAILURE_CLASS_TASK_CRASHED as FAILURE_CLASS_TASK_CRASHED,
|
|
11
|
+
)
|
|
12
|
+
from orchestrator.supervisor._shared import (
|
|
13
|
+
MAX_SAME_CLASS_STRIKES as MAX_SAME_CLASS_STRIKES,
|
|
14
|
+
)
|
|
15
|
+
from orchestrator.supervisor._shared import (
|
|
16
|
+
WORKSPACE_ROOT as WORKSPACE_ROOT,
|
|
17
|
+
)
|
|
18
|
+
from orchestrator.supervisor._shared import (
|
|
19
|
+
Any as Any,
|
|
20
|
+
)
|
|
21
|
+
from orchestrator.supervisor._shared import (
|
|
22
|
+
ContractGraph as ContractGraph,
|
|
23
|
+
)
|
|
24
|
+
from orchestrator.supervisor._shared import (
|
|
25
|
+
Dict as Dict,
|
|
26
|
+
)
|
|
27
|
+
from orchestrator.supervisor._shared import (
|
|
28
|
+
Goal as Goal,
|
|
29
|
+
)
|
|
30
|
+
from orchestrator.supervisor._shared import (
|
|
31
|
+
IllegalTransitionError as IllegalTransitionError,
|
|
32
|
+
)
|
|
33
|
+
from orchestrator.supervisor._shared import (
|
|
34
|
+
List as List,
|
|
35
|
+
)
|
|
36
|
+
from orchestrator.supervisor._shared import (
|
|
37
|
+
Optional as Optional,
|
|
38
|
+
)
|
|
39
|
+
from orchestrator.supervisor._shared import (
|
|
40
|
+
Plan as Plan,
|
|
41
|
+
)
|
|
42
|
+
from orchestrator.supervisor._shared import (
|
|
43
|
+
StateError as StateError,
|
|
44
|
+
)
|
|
45
|
+
from orchestrator.supervisor._shared import (
|
|
46
|
+
_pid_alive as _pid_alive,
|
|
47
|
+
)
|
|
48
|
+
from orchestrator.supervisor._shared import (
|
|
49
|
+
_retry_fingerprints as _retry_fingerprints,
|
|
50
|
+
)
|
|
51
|
+
from orchestrator.supervisor._shared import (
|
|
52
|
+
annotate_worker_result as annotate_worker_result,
|
|
53
|
+
)
|
|
54
|
+
from orchestrator.supervisor._shared import (
|
|
55
|
+
audit_mod as audit_mod,
|
|
56
|
+
)
|
|
57
|
+
from orchestrator.supervisor._shared import (
|
|
58
|
+
budget_mod as budget_mod,
|
|
59
|
+
)
|
|
60
|
+
from orchestrator.supervisor._shared import (
|
|
61
|
+
classify_failure as classify_failure,
|
|
62
|
+
)
|
|
63
|
+
from orchestrator.supervisor._shared import (
|
|
64
|
+
count_consecutive_same_class as count_consecutive_same_class,
|
|
65
|
+
)
|
|
66
|
+
from orchestrator.supervisor._shared import (
|
|
67
|
+
cp as cp,
|
|
68
|
+
)
|
|
69
|
+
from orchestrator.supervisor._shared import (
|
|
70
|
+
create_initial_state as create_initial_state,
|
|
71
|
+
)
|
|
72
|
+
from orchestrator.supervisor._shared import (
|
|
73
|
+
ev as ev,
|
|
74
|
+
)
|
|
75
|
+
from orchestrator.supervisor._shared import (
|
|
76
|
+
fb as fb,
|
|
77
|
+
)
|
|
78
|
+
from orchestrator.supervisor._shared import (
|
|
79
|
+
hashlib as hashlib,
|
|
80
|
+
)
|
|
81
|
+
from orchestrator.supervisor._shared import (
|
|
82
|
+
hmac as hmac,
|
|
83
|
+
)
|
|
84
|
+
from orchestrator.supervisor._shared import (
|
|
85
|
+
imp as imp,
|
|
86
|
+
)
|
|
87
|
+
from orchestrator.supervisor._shared import (
|
|
88
|
+
json as json,
|
|
89
|
+
)
|
|
90
|
+
from orchestrator.supervisor._shared import (
|
|
91
|
+
lk as lk,
|
|
92
|
+
)
|
|
93
|
+
from orchestrator.supervisor._shared import (
|
|
94
|
+
lm as lm,
|
|
95
|
+
)
|
|
96
|
+
from orchestrator.supervisor._shared import (
|
|
97
|
+
load_contract as load_contract,
|
|
98
|
+
)
|
|
99
|
+
from orchestrator.supervisor._shared import (
|
|
100
|
+
load_state as load_state,
|
|
101
|
+
)
|
|
102
|
+
from orchestrator.supervisor._shared import (
|
|
103
|
+
mb_mod as mb_mod,
|
|
104
|
+
)
|
|
105
|
+
from orchestrator.supervisor._shared import (
|
|
106
|
+
metrics_mod as metrics_mod,
|
|
107
|
+
)
|
|
108
|
+
from orchestrator.supervisor._shared import (
|
|
109
|
+
os as os,
|
|
110
|
+
)
|
|
111
|
+
from orchestrator.supervisor._shared import (
|
|
112
|
+
re as re,
|
|
113
|
+
)
|
|
114
|
+
from orchestrator.supervisor._shared import (
|
|
115
|
+
rec as rec,
|
|
116
|
+
)
|
|
117
|
+
from orchestrator.supervisor._shared import (
|
|
118
|
+
require_divergent_retry as require_divergent_retry,
|
|
119
|
+
)
|
|
120
|
+
from orchestrator.supervisor._shared import (
|
|
121
|
+
run_preflight as run_preflight,
|
|
122
|
+
)
|
|
123
|
+
from orchestrator.supervisor._shared import (
|
|
124
|
+
run_verification as run_verification,
|
|
125
|
+
)
|
|
126
|
+
from orchestrator.supervisor._shared import (
|
|
127
|
+
run_worker as run_worker,
|
|
128
|
+
)
|
|
129
|
+
from orchestrator.supervisor._shared import (
|
|
130
|
+
save_state as save_state,
|
|
131
|
+
)
|
|
132
|
+
from orchestrator.supervisor._shared import (
|
|
133
|
+
sc as sc,
|
|
134
|
+
)
|
|
135
|
+
from orchestrator.supervisor._shared import (
|
|
136
|
+
sys as sys,
|
|
137
|
+
)
|
|
138
|
+
from orchestrator.supervisor._shared import (
|
|
139
|
+
threading as threading,
|
|
140
|
+
)
|
|
141
|
+
from orchestrator.supervisor._shared import (
|
|
142
|
+
time as time,
|
|
143
|
+
)
|
|
144
|
+
from orchestrator.supervisor._shared import (
|
|
145
|
+
validate_contract_against_plan as validate_contract_against_plan,
|
|
146
|
+
)
|
|
147
|
+
from orchestrator.supervisor._shared import (
|
|
148
|
+
wp as wp,
|
|
149
|
+
)
|
|
150
|
+
from orchestrator.supervisor.cleanup import CleanupMixin
|
|
151
|
+
from orchestrator.supervisor.recovery import RecoveryMixin
|
|
152
|
+
from orchestrator.supervisor.reporting import ReportingMixin
|
|
153
|
+
from orchestrator.worktree import WorktreeManager
|
|
154
|
+
|
|
155
|
+
_SANDBOX_PASS_STATUSES = ("COMPLETE", "complete", "DEGRADED_PASS", "FORCE_COMPLETE")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _worktree_sandbox_requested(contract) -> bool:
|
|
159
|
+
"""Sandbox when LETITLOOP_WORKTREE_SANDBOX=1 or contract.worker.worktree is 'sandbox'/True."""
|
|
160
|
+
if os.environ.get("LETITLOOP_WORKTREE_SANDBOX") == "1":
|
|
161
|
+
return True
|
|
162
|
+
worker = getattr(contract, "worker", None)
|
|
163
|
+
flag = worker.get("worktree") if isinstance(worker, dict) else None
|
|
164
|
+
return flag in ("sandbox", True)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class Supervisor(RecoveryMixin, ReportingMixin, CleanupMixin):
|
|
168
|
+
"""Deterministic plan executor (public surface unchanged)."""
|
|
169
|
+
|
|
170
|
+
"""Supervisor to manage execution of a Goal and its multi-contract Plan."""
|
|
171
|
+
|
|
172
|
+
def __init__(
|
|
173
|
+
self,
|
|
174
|
+
goal: Goal,
|
|
175
|
+
plan: Plan,
|
|
176
|
+
graph: Optional[ContractGraph] = None,
|
|
177
|
+
workspace_root: str = WORKSPACE_ROOT,
|
|
178
|
+
run_dir: Optional[str] = None,
|
|
179
|
+
parallel: bool = False,
|
|
180
|
+
max_workers: int = 3,
|
|
181
|
+
dry_run: bool = False,
|
|
182
|
+
adaptive_replan: bool = False,
|
|
183
|
+
):
|
|
184
|
+
self.goal = goal
|
|
185
|
+
self.plan = plan
|
|
186
|
+
self.graph = graph if graph is not None else ContractGraph(plan)
|
|
187
|
+
self.workspace_root = workspace_root
|
|
188
|
+
self.run_dir = run_dir if run_dir is not None else DEFAULT_RUN_DIR
|
|
189
|
+
self.parallel = parallel
|
|
190
|
+
self.max_workers = max_workers
|
|
191
|
+
self.dry_run = dry_run
|
|
192
|
+
self.adaptive_replan = adaptive_replan
|
|
193
|
+
self.results: Dict[str, Dict[str, Any]] = {}
|
|
194
|
+
self.evidence_store: Dict[str, List[str]] = {}
|
|
195
|
+
self.metrics_coll = metrics_mod.MetricsCollector(goal_id=goal.goal_id)
|
|
196
|
+
self._checkpoint_iteration = 0
|
|
197
|
+
self._checkpoint_interval = 2 # save every N loop iterations
|
|
198
|
+
# AUT-011: guards shared-state writes from worker threads in parallel
|
|
199
|
+
# mode (_execute_single_contract_impl + on_result callbacks).
|
|
200
|
+
self._shared_lock = threading.Lock()
|
|
201
|
+
self._overrule_secret_hash = self._load_or_create_overrule_secret_hash()
|
|
202
|
+
# Scope-lease registry: lets parallel tasks exempt each other's declared
|
|
203
|
+
# outputs from scope checks (perpetual-loop round 1).
|
|
204
|
+
self._scope_leases = sc.FileBackedScopeRegistry(self.workspace_root)
|
|
205
|
+
# Budget guard & usage ledger
|
|
206
|
+
max_tokens = 500_000
|
|
207
|
+
max_cost_usd = 2.0
|
|
208
|
+
if isinstance(self.goal.constraints, dict):
|
|
209
|
+
max_tokens = int(self.goal.constraints.get("max_tokens", 500_000))
|
|
210
|
+
max_cost_usd = float(self.goal.constraints.get("max_cost_usd", 2.0))
|
|
211
|
+
self.budget_guard = budget_mod.BudgetGuard(max_tokens=max_tokens, max_cost_usd=max_cost_usd)
|
|
212
|
+
# Durable memory bridge
|
|
213
|
+
self.memory_bridge = mb_mod.MemoryBridge(os.path.join(self.run_dir, "memory_bridge.jsonl"))
|
|
214
|
+
|
|
215
|
+
def _emit(self, event_type: str, **kw) -> None:
|
|
216
|
+
"""Publish a lifecycle event on the process-wide bus; never raises."""
|
|
217
|
+
try:
|
|
218
|
+
get_bus().publish(event_type, **kw)
|
|
219
|
+
except Exception:
|
|
220
|
+
pass
|
|
221
|
+
|
|
222
|
+
def _short_fail_reason(self, task_id: str) -> str:
|
|
223
|
+
try:
|
|
224
|
+
state_file = self._state_path(task_id)
|
|
225
|
+
if os.path.isfile(state_file):
|
|
226
|
+
st = load_state(state_file, journal_dir=self._task_run_dir(task_id))
|
|
227
|
+
reason = st.data.get("crash_reason") or st.data.get("last_failure_class") or ""
|
|
228
|
+
return str(reason)[:120] if reason else str(st.status)
|
|
229
|
+
except Exception:
|
|
230
|
+
pass
|
|
231
|
+
return ""
|
|
232
|
+
|
|
233
|
+
def _record_terminal(self, task_id: str, status: str) -> None:
|
|
234
|
+
"""Record final contract status in metrics; emit contract.failed on terminal-fail paths."""
|
|
235
|
+
try:
|
|
236
|
+
self.metrics_coll.record_contract_status(status)
|
|
237
|
+
except Exception:
|
|
238
|
+
pass
|
|
239
|
+
if str(status).upper() in ("FAILED", "CRASHED", "ESCALATED"):
|
|
240
|
+
self._emit(
|
|
241
|
+
"contract.failed",
|
|
242
|
+
goal_id=self.goal.goal_id,
|
|
243
|
+
task_id=task_id,
|
|
244
|
+
reason=self._short_fail_reason(task_id),
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
def _task_run_dir(self, task_id: str) -> str:
|
|
248
|
+
return os.path.join(self.run_dir, task_id)
|
|
249
|
+
|
|
250
|
+
def _state_path(self, task_id: str) -> str:
|
|
251
|
+
return os.path.join(self._task_run_dir(task_id), "state.json")
|
|
252
|
+
|
|
253
|
+
def _load_or_create_state(self, task_id, contract_path=""):
|
|
254
|
+
"""Load existing state or create fresh, with journal_dir set."""
|
|
255
|
+
task_dir = self._task_run_dir(task_id)
|
|
256
|
+
state_file = self._state_path(task_id)
|
|
257
|
+
if os.path.isfile(state_file):
|
|
258
|
+
state = load_state(state_file, journal_dir=task_dir)
|
|
259
|
+
else:
|
|
260
|
+
state = create_initial_state(task_id, journal_dir=task_dir)
|
|
261
|
+
state.patch_data({"contract_path": contract_path})
|
|
262
|
+
return state
|
|
263
|
+
|
|
264
|
+
def _safe_save(self, state, state_file):
|
|
265
|
+
for _ in range(5):
|
|
266
|
+
try:
|
|
267
|
+
save_state(state, state_file)
|
|
268
|
+
return
|
|
269
|
+
except OSError:
|
|
270
|
+
time.sleep(0.02)
|
|
271
|
+
save_state(state, state_file)
|
|
272
|
+
|
|
273
|
+
def _get_contract_path_and_dict(self, c_info: Dict[str, Any]) -> tuple[str, Dict[str, Any]]:
|
|
274
|
+
task_id = c_info["task_id"]
|
|
275
|
+
task_dir = self._task_run_dir(task_id)
|
|
276
|
+
os.makedirs(task_dir, exist_ok=True)
|
|
277
|
+
contract_path = os.path.join(task_dir, "contract.json")
|
|
278
|
+
|
|
279
|
+
contract_dict = c_info.get("contract")
|
|
280
|
+
if not contract_dict and "contract_path" in c_info:
|
|
281
|
+
src_path = os.path.join(self.workspace_root, c_info["contract_path"])
|
|
282
|
+
if os.path.isfile(src_path):
|
|
283
|
+
with open(src_path, "r", encoding="utf-8") as f:
|
|
284
|
+
contract_dict = json.load(f)
|
|
285
|
+
|
|
286
|
+
if contract_dict:
|
|
287
|
+
with open(contract_path, "w", encoding="utf-8") as f:
|
|
288
|
+
json.dump(contract_dict, f, indent=2, ensure_ascii=False)
|
|
289
|
+
|
|
290
|
+
return contract_path, contract_dict
|
|
291
|
+
|
|
292
|
+
def _inject_upstream_evidence(self, c_info: Dict[str, Any], contract_dict: Optional[Dict[str, Any]] = None) -> bool:
|
|
293
|
+
with self._shared_lock:
|
|
294
|
+
evidence_snapshot = {k: list(v) for k, v in self.evidence_store.items()}
|
|
295
|
+
|
|
296
|
+
c_info.get("task_id")
|
|
297
|
+
depends_on = c_info.get("depends_on", [])
|
|
298
|
+
if not depends_on:
|
|
299
|
+
return False
|
|
300
|
+
|
|
301
|
+
if contract_dict is None:
|
|
302
|
+
contract_dict = c_info.get("contract")
|
|
303
|
+
|
|
304
|
+
if contract_dict is None:
|
|
305
|
+
return False
|
|
306
|
+
|
|
307
|
+
if "inputs" not in contract_dict or not isinstance(contract_dict["inputs"], list):
|
|
308
|
+
contract_dict["inputs"] = []
|
|
309
|
+
|
|
310
|
+
existing_paths = set()
|
|
311
|
+
for inp in contract_dict["inputs"]:
|
|
312
|
+
if isinstance(inp, dict) and "path" in inp:
|
|
313
|
+
existing_paths.add(inp["path"])
|
|
314
|
+
elif isinstance(inp, str):
|
|
315
|
+
existing_paths.add(inp)
|
|
316
|
+
|
|
317
|
+
injected = False
|
|
318
|
+
workspace_real = os.path.realpath(os.path.abspath(self.workspace_root))
|
|
319
|
+
for dep_id in depends_on:
|
|
320
|
+
if dep_id in evidence_snapshot:
|
|
321
|
+
for out_path in evidence_snapshot[dep_id]:
|
|
322
|
+
# Canonicalize + confine injected
|
|
323
|
+
# evidence paths to workspace_root before treating them as
|
|
324
|
+
# contract inputs (security bound).
|
|
325
|
+
candidate = out_path if os.path.isabs(out_path) else os.path.join(self.workspace_root, out_path)
|
|
326
|
+
canonical_path = os.path.realpath(candidate)
|
|
327
|
+
try:
|
|
328
|
+
if os.path.commonpath([canonical_path, workspace_real]) != workspace_real:
|
|
329
|
+
continue
|
|
330
|
+
except ValueError:
|
|
331
|
+
continue
|
|
332
|
+
rel_path = os.path.relpath(canonical_path, workspace_real)
|
|
333
|
+
if rel_path not in existing_paths:
|
|
334
|
+
contract_dict["inputs"].append(
|
|
335
|
+
{
|
|
336
|
+
"path": rel_path,
|
|
337
|
+
"source": dep_id,
|
|
338
|
+
"evidence": True,
|
|
339
|
+
}
|
|
340
|
+
)
|
|
341
|
+
existing_paths.add(rel_path)
|
|
342
|
+
injected = True
|
|
343
|
+
|
|
344
|
+
if injected and "contract" in c_info:
|
|
345
|
+
c_info["contract"] = contract_dict
|
|
346
|
+
|
|
347
|
+
return injected
|
|
348
|
+
|
|
349
|
+
def _record_task_exception(self, task_id: str, exception: Exception) -> None:
|
|
350
|
+
"""Persist an unexpected exception as structured failure evidence and update graph."""
|
|
351
|
+
task_dir = self._task_run_dir(task_id)
|
|
352
|
+
import traceback
|
|
353
|
+
|
|
354
|
+
tb_path = os.path.join(task_dir, "crash_traceback.log")
|
|
355
|
+
os.makedirs(task_dir, exist_ok=True)
|
|
356
|
+
with open(tb_path, "w", encoding="utf-8") as f:
|
|
357
|
+
traceback.print_exception(type(exception), exception, exception.__traceback__, file=f)
|
|
358
|
+
|
|
359
|
+
state_file = self._state_path(task_id)
|
|
360
|
+
final_status = "BLOCKED"
|
|
361
|
+
try:
|
|
362
|
+
state = self._load_or_create_state(task_id, contract_path="")
|
|
363
|
+
if hasattr(state, "patch_data") and callable(state.patch_data):
|
|
364
|
+
state.patch_data(
|
|
365
|
+
{
|
|
366
|
+
"last_failure_class": FAILURE_CLASS_TASK_CRASHED,
|
|
367
|
+
"crash_reason": f"{type(exception).__name__}: {exception}",
|
|
368
|
+
}
|
|
369
|
+
)
|
|
370
|
+
elif hasattr(state, "data") and isinstance(state.data, dict):
|
|
371
|
+
state.data.update(
|
|
372
|
+
{
|
|
373
|
+
"last_failure_class": FAILURE_CLASS_TASK_CRASHED,
|
|
374
|
+
"crash_reason": f"{type(exception).__name__}: {exception}",
|
|
375
|
+
}
|
|
376
|
+
)
|
|
377
|
+
if hasattr(state, "add_evidence") and callable(state.add_evidence):
|
|
378
|
+
state.add_evidence("crash", tb_path)
|
|
379
|
+
|
|
380
|
+
preserve_statuses = (
|
|
381
|
+
"COMPLETE",
|
|
382
|
+
"FORCE_COMPLETE",
|
|
383
|
+
"DEGRADED_PASS",
|
|
384
|
+
"ESCALATED",
|
|
385
|
+
"BLOCKED",
|
|
386
|
+
"CRASHED",
|
|
387
|
+
"QC_CONDITIONAL_PASS",
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
try:
|
|
391
|
+
if state.status not in preserve_statuses:
|
|
392
|
+
state.force_block(reason=f"crashed: {type(exception).__name__}")
|
|
393
|
+
else:
|
|
394
|
+
if hasattr(state, "events") and isinstance(state.events, list):
|
|
395
|
+
state.events.append(
|
|
396
|
+
{
|
|
397
|
+
"from": state.status,
|
|
398
|
+
"to": state.status,
|
|
399
|
+
"reason": f"crashed: {type(exception).__name__}",
|
|
400
|
+
"synthetic": True,
|
|
401
|
+
}
|
|
402
|
+
)
|
|
403
|
+
except (KeyError, AttributeError, ValueError, TypeError):
|
|
404
|
+
pass
|
|
405
|
+
|
|
406
|
+
self._safe_save(state, state_file)
|
|
407
|
+
final_status = state.status
|
|
408
|
+
except (OSError, ValueError, AttributeError, KeyError):
|
|
409
|
+
pass
|
|
410
|
+
|
|
411
|
+
self.graph.update_status(task_id, final_status)
|
|
412
|
+
print(f"[supervisor] TASK CRASHED: {task_id} — {type(exception).__name__}: {exception}", file=sys.stderr)
|
|
413
|
+
|
|
414
|
+
def _force_complete_task(
|
|
415
|
+
self,
|
|
416
|
+
task_id: str,
|
|
417
|
+
reason: str = "",
|
|
418
|
+
failed_checks: list = None,
|
|
419
|
+
output_hash: str = "",
|
|
420
|
+
waived_files: list = None,
|
|
421
|
+
) -> str:
|
|
422
|
+
"""Force a task to FORCE_COMPLETE with auditable waiver metadata.
|
|
423
|
+
|
|
424
|
+
Only legal from VERIFICATION_FAILED, QC_REJECTED,
|
|
425
|
+
QC_INSUFFICIENT_EVIDENCE, or QC_CONDITIONAL_PASS. This is a privileged
|
|
426
|
+
break-glass bypass, not a verified QC overrule.
|
|
427
|
+
"""
|
|
428
|
+
task_dir = self._task_run_dir(task_id)
|
|
429
|
+
state_file = self._state_path(task_id)
|
|
430
|
+
if not os.path.isfile(state_file):
|
|
431
|
+
print(f"[supervisor] no state file for {task_id}, cannot force-complete", file=sys.stderr)
|
|
432
|
+
return "FAILED"
|
|
433
|
+
state = load_state(state_file, journal_dir=task_dir)
|
|
434
|
+
try:
|
|
435
|
+
state.force_complete(
|
|
436
|
+
reason=reason or "manual override",
|
|
437
|
+
failed_checks=failed_checks or [],
|
|
438
|
+
output_hash=output_hash,
|
|
439
|
+
waived_files=waived_files or [],
|
|
440
|
+
cleanup_decision="retained",
|
|
441
|
+
)
|
|
442
|
+
self._safe_save(state, state_file)
|
|
443
|
+
self.graph.mark_complete(task_id)
|
|
444
|
+
print(f"[supervisor] FORCE_COMPLETE: {task_id} — {reason}", file=sys.stderr)
|
|
445
|
+
return "FORCE_COMPLETE"
|
|
446
|
+
except Exception as e:
|
|
447
|
+
print(f"[supervisor] force_complete failed for {task_id}: {e}", file=sys.stderr)
|
|
448
|
+
return "FAILED"
|
|
449
|
+
|
|
450
|
+
def _load_or_create_overrule_secret_hash(self) -> str:
|
|
451
|
+
"""Create/load the run-scoped overrule token and retain only its SHA-256 hash."""
|
|
452
|
+
import secrets
|
|
453
|
+
|
|
454
|
+
os.makedirs(self.run_dir, exist_ok=True)
|
|
455
|
+
secret_path = os.path.join(self.run_dir, "overrule.secret")
|
|
456
|
+
lock_path = os.path.join(self.run_dir, "overrule.secret.lock")
|
|
457
|
+
|
|
458
|
+
with lk.FileLock(lock_path):
|
|
459
|
+
if os.path.isfile(secret_path):
|
|
460
|
+
with open(secret_path, "r", encoding="utf-8") as f:
|
|
461
|
+
secret = f.read().strip()
|
|
462
|
+
if not secret:
|
|
463
|
+
raise RuntimeError("overrule secret file is empty")
|
|
464
|
+
else:
|
|
465
|
+
secret = secrets.token_urlsafe(32)
|
|
466
|
+
fd = os.open(
|
|
467
|
+
secret_path,
|
|
468
|
+
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
|
|
469
|
+
0o600,
|
|
470
|
+
)
|
|
471
|
+
try:
|
|
472
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
473
|
+
f.write(secret)
|
|
474
|
+
f.write("\n")
|
|
475
|
+
f.flush()
|
|
476
|
+
os.fsync(f.fileno())
|
|
477
|
+
except Exception:
|
|
478
|
+
try:
|
|
479
|
+
os.unlink(secret_path)
|
|
480
|
+
except OSError:
|
|
481
|
+
pass
|
|
482
|
+
raise
|
|
483
|
+
|
|
484
|
+
if os.name != "nt":
|
|
485
|
+
os.chmod(secret_path, 0o600)
|
|
486
|
+
|
|
487
|
+
return hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
|
488
|
+
|
|
489
|
+
def _qc_overrule(self, task_id: str, evidence: dict, secret: str) -> str:
|
|
490
|
+
"""Apply one verified QC overrule exactly once using a durable task marker.
|
|
491
|
+
|
|
492
|
+
The ONLY route that accepts evidence-based overrule for QC states.
|
|
493
|
+
Requires status in (QC_REJECTED, QC_INSUFFICIENT_EVIDENCE,
|
|
494
|
+
QC_CONDITIONAL_PASS, VERIFICATION_FAILED), verifies the secret against
|
|
495
|
+
the run-scoped hash, validates evidence against the already-recorded
|
|
496
|
+
verification_evidence.json, then reserves consumption with a durable
|
|
497
|
+
write-ahead marker BEFORE transitioning to FORCE_COMPLETE. Fail-closed:
|
|
498
|
+
a crash after reservation still consumes the overrule (no replay).
|
|
499
|
+
"""
|
|
500
|
+
task_dir = self._task_run_dir(task_id)
|
|
501
|
+
state_file = self._state_path(task_id)
|
|
502
|
+
evidence_path = os.path.join(task_dir, "verification_evidence.json")
|
|
503
|
+
lock_path = os.path.join(task_dir, "overrule.consume.lock")
|
|
504
|
+
marker_path = os.path.join(task_dir, "overrule_consumed.json")
|
|
505
|
+
|
|
506
|
+
if not isinstance(evidence, dict) or not isinstance(secret, str):
|
|
507
|
+
return "FAILED"
|
|
508
|
+
|
|
509
|
+
supplied_secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
|
510
|
+
if not hmac.compare_digest(supplied_secret_hash, self._overrule_secret_hash):
|
|
511
|
+
return "FAILED"
|
|
512
|
+
|
|
513
|
+
os.makedirs(task_dir, exist_ok=True)
|
|
514
|
+
|
|
515
|
+
with lk.FileLock(lock_path):
|
|
516
|
+
if not os.path.isfile(state_file):
|
|
517
|
+
return "FAILED"
|
|
518
|
+
|
|
519
|
+
state = load_state(state_file, journal_dir=task_dir)
|
|
520
|
+
if state.status not in (
|
|
521
|
+
"QC_REJECTED",
|
|
522
|
+
"QC_INSUFFICIENT_EVIDENCE",
|
|
523
|
+
"QC_CONDITIONAL_PASS",
|
|
524
|
+
"VERIFICATION_FAILED",
|
|
525
|
+
):
|
|
526
|
+
return "FAILED"
|
|
527
|
+
|
|
528
|
+
if state.data.get("overrule_consumed") or os.path.exists(marker_path):
|
|
529
|
+
return "FAILED"
|
|
530
|
+
|
|
531
|
+
try:
|
|
532
|
+
with open(evidence_path, "r", encoding="utf-8") as f:
|
|
533
|
+
verification_evidence = json.load(f)
|
|
534
|
+
except (OSError, json.JSONDecodeError):
|
|
535
|
+
return "FAILED"
|
|
536
|
+
|
|
537
|
+
from orchestrator.qc_overrule import verify_overrule
|
|
538
|
+
|
|
539
|
+
valid, errors = verify_overrule(evidence, secret, verification_evidence)
|
|
540
|
+
if not valid:
|
|
541
|
+
return "FAILED"
|
|
542
|
+
|
|
543
|
+
public_evidence = {key: value for key, value in evidence.items() if key != "secret"}
|
|
544
|
+
marker = {
|
|
545
|
+
"task_id": task_id,
|
|
546
|
+
"check_id": public_evidence["check_id"],
|
|
547
|
+
"stdout_hash": public_evidence["stdout_hash"],
|
|
548
|
+
"evidence_sha256": hashlib.sha256(
|
|
549
|
+
json.dumps(
|
|
550
|
+
public_evidence,
|
|
551
|
+
sort_keys=True,
|
|
552
|
+
separators=(",", ":"),
|
|
553
|
+
).encode("utf-8")
|
|
554
|
+
).hexdigest(),
|
|
555
|
+
"consumed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
try:
|
|
559
|
+
fd = os.open(
|
|
560
|
+
marker_path,
|
|
561
|
+
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
|
|
562
|
+
0o600,
|
|
563
|
+
)
|
|
564
|
+
except FileExistsError:
|
|
565
|
+
return "FAILED"
|
|
566
|
+
|
|
567
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
568
|
+
json.dump(marker, f, sort_keys=True)
|
|
569
|
+
f.write("\n")
|
|
570
|
+
f.flush()
|
|
571
|
+
os.fsync(f.fileno())
|
|
572
|
+
|
|
573
|
+
patch_payload = {
|
|
574
|
+
"overrule_consumed": marker,
|
|
575
|
+
"overrule_evidence": public_evidence,
|
|
576
|
+
"overrule_verified": True,
|
|
577
|
+
}
|
|
578
|
+
if hasattr(state, "patch_data"):
|
|
579
|
+
state.patch_data(patch_payload)
|
|
580
|
+
elif hasattr(state, "data") and isinstance(state.data, dict):
|
|
581
|
+
state.data.update(patch_payload)
|
|
582
|
+
state.transition(
|
|
583
|
+
"FORCE_COMPLETE",
|
|
584
|
+
reason=f"QC overruled: {public_evidence['assertions'][0]}",
|
|
585
|
+
)
|
|
586
|
+
self._safe_save(state, state_file)
|
|
587
|
+
self.graph.mark_complete(task_id)
|
|
588
|
+
return "FORCE_COMPLETE"
|
|
589
|
+
|
|
590
|
+
def _store_qc_timing_artifact(self, task_id: str):
|
|
591
|
+
"""Write a qc_timing.json artifact with phase-level timing data."""
|
|
592
|
+
task_dir = self._task_run_dir(task_id)
|
|
593
|
+
phases = self.metrics_coll.get_phases(task_id)
|
|
594
|
+
if phases:
|
|
595
|
+
import json
|
|
596
|
+
|
|
597
|
+
timing_path = os.path.join(task_dir, "qc_timing.json")
|
|
598
|
+
with open(timing_path, "w", encoding="utf-8") as f:
|
|
599
|
+
json.dump(phases, f, indent=2, ensure_ascii=False)
|
|
600
|
+
|
|
601
|
+
def _execute_single_contract(self, task_id: str) -> str:
|
|
602
|
+
"""Execute preflight -> work -> verify for a single task contract.
|
|
603
|
+
|
|
604
|
+
Wrapped in a fault barrier — any unexpected exception is caught,
|
|
605
|
+
recorded as a structured failure, and the task is marked BLOCKED.
|
|
606
|
+
"""
|
|
607
|
+
try:
|
|
608
|
+
status = self._execute_single_contract_impl(task_id)
|
|
609
|
+
except Exception as e:
|
|
610
|
+
self._prune_leftover_sandbox(task_id)
|
|
611
|
+
self._record_task_exception(task_id, e)
|
|
612
|
+
status = "CRASHED"
|
|
613
|
+
self._record_terminal(task_id, status)
|
|
614
|
+
return status
|
|
615
|
+
|
|
616
|
+
def _sandbox_registry_add(self, task_id: str, manager: "WorktreeManager", handle) -> None:
|
|
617
|
+
reg = getattr(self, "_active_sandboxes", None)
|
|
618
|
+
if reg is None:
|
|
619
|
+
reg = {}
|
|
620
|
+
self._active_sandboxes = reg
|
|
621
|
+
with self._shared_lock:
|
|
622
|
+
reg[task_id] = (manager, handle)
|
|
623
|
+
|
|
624
|
+
def _sandbox_registry_pop(self, task_id: str):
|
|
625
|
+
reg = getattr(self, "_active_sandboxes", None)
|
|
626
|
+
if not reg:
|
|
627
|
+
return None
|
|
628
|
+
with self._shared_lock:
|
|
629
|
+
return reg.pop(task_id, None)
|
|
630
|
+
|
|
631
|
+
def _prune_leftover_sandbox(self, task_id: str) -> None:
|
|
632
|
+
"""Exception-path cleanup: discard any sandbox still open for task_id."""
|
|
633
|
+
entry = self._sandbox_registry_pop(task_id)
|
|
634
|
+
if entry is None:
|
|
635
|
+
return
|
|
636
|
+
manager, handle = entry
|
|
637
|
+
try:
|
|
638
|
+
manager.prune_on_fail(handle)
|
|
639
|
+
print(f"[worktree] pruned leftover sandbox for {task_id}", file=sys.stderr)
|
|
640
|
+
except Exception as prune_exc:
|
|
641
|
+
print(f"[worktree] leftover prune failed for {task_id}: {prune_exc}", file=sys.stderr)
|
|
642
|
+
|
|
643
|
+
def _execute_single_contract_impl(self, task_id: str) -> str:
|
|
644
|
+
"""Core implementation of single-contract execution with retry and QC loops."""
|
|
645
|
+
c_info = next((c for c in self.plan.contracts if c["task_id"] == task_id), None)
|
|
646
|
+
if not c_info:
|
|
647
|
+
return "FAILED"
|
|
648
|
+
|
|
649
|
+
task_dir = self._task_run_dir(task_id)
|
|
650
|
+
contract_path, contract_dict = self._get_contract_path_and_dict(c_info)
|
|
651
|
+
|
|
652
|
+
if contract_dict:
|
|
653
|
+
injected = self._inject_upstream_evidence(c_info, contract_dict)
|
|
654
|
+
if injected:
|
|
655
|
+
with open(contract_path, "w", encoding="utf-8") as f:
|
|
656
|
+
json.dump(contract_dict, f, indent=2, ensure_ascii=False)
|
|
657
|
+
|
|
658
|
+
contract, errors = load_contract(contract_path, workspace_root=self.workspace_root)
|
|
659
|
+
if errors or contract is None:
|
|
660
|
+
self.graph.update_status(task_id, "FAILED")
|
|
661
|
+
return "FAILED"
|
|
662
|
+
|
|
663
|
+
plan_contract = c_info.get("contract", {})
|
|
664
|
+
if plan_contract and contract_dict:
|
|
665
|
+
diff_errors = validate_contract_against_plan(plan_contract, contract_dict)
|
|
666
|
+
if diff_errors:
|
|
667
|
+
self.graph.update_status(task_id, "BLOCKED")
|
|
668
|
+
state = create_initial_state(task_id, journal_dir=task_dir)
|
|
669
|
+
state.patch_data({"contract_path": contract_path})
|
|
670
|
+
state.force_block(reason="Contract safety downgrade: " + "; ".join(diff_errors))
|
|
671
|
+
self._safe_save(state, self._state_path(task_id))
|
|
672
|
+
return "BLOCKED"
|
|
673
|
+
|
|
674
|
+
state_file = self._state_path(task_id)
|
|
675
|
+
state = self._load_or_create_state(task_id, contract_path=contract_path)
|
|
676
|
+
if not os.path.isfile(state_file):
|
|
677
|
+
self._safe_save(state, state_file)
|
|
678
|
+
|
|
679
|
+
if state.status in ("COMPLETE", "FORCE_COMPLETE", "ESCALATED", "BLOCKED", "CANCELLED"):
|
|
680
|
+
return state.status
|
|
681
|
+
|
|
682
|
+
# Enforce budget guard before dispatching task
|
|
683
|
+
try:
|
|
684
|
+
self.budget_guard.check_before_call()
|
|
685
|
+
except budget_mod.BudgetExhaustedError as be:
|
|
686
|
+
print(f"[supervisor] BUDGET EXHAUSTED for task {task_id}: {be}", file=sys.stderr)
|
|
687
|
+
state.force_block(reason=f"budget exhausted: {be}")
|
|
688
|
+
state.patch_data({"budget_error": str(be)})
|
|
689
|
+
self._safe_save(state, state_file)
|
|
690
|
+
self.graph.update_status(task_id, "BLOCKED")
|
|
691
|
+
return "BLOCKED"
|
|
692
|
+
|
|
693
|
+
max_attempts = contract.worker.get("max_attempts", 3)
|
|
694
|
+
|
|
695
|
+
# 1. Preflight (once)
|
|
696
|
+
if state.status in ("DRAFTED", "drafted"):
|
|
697
|
+
self.metrics_coll.start_phase("preflight", task_id)
|
|
698
|
+
state.transition("PREFLIGHT_RUNNING", reason="supervisor starting preflight")
|
|
699
|
+
self._safe_save(state, state_file)
|
|
700
|
+
passed, results, evidence_path = run_preflight(contract, self.workspace_root, task_dir)
|
|
701
|
+
self.metrics_coll.end_phase("preflight", task_id)
|
|
702
|
+
if evidence_path:
|
|
703
|
+
state.add_evidence("preflight", evidence_path)
|
|
704
|
+
if passed:
|
|
705
|
+
state.transition("READY", reason="supervisor preflight passed")
|
|
706
|
+
else:
|
|
707
|
+
state.transition("PREFLIGHT_FAILED", reason="preflight failed")
|
|
708
|
+
state.transition("BLOCKED", reason="preflight failed")
|
|
709
|
+
fclass = classify_failure(state, contract)
|
|
710
|
+
state.patch_data({"last_failure_class": fclass})
|
|
711
|
+
self._safe_save(state, state_file)
|
|
712
|
+
self.graph.update_status(task_id, "BLOCKED")
|
|
713
|
+
fb_rec = fb.collect_feedback(task_id, self.goal.goal_id, state)
|
|
714
|
+
if fb_rec:
|
|
715
|
+
fb.store_feedback(self.goal.goal_id, self.run_dir, [fb_rec])
|
|
716
|
+
return "BLOCKED"
|
|
717
|
+
self._safe_save(state, state_file)
|
|
718
|
+
|
|
719
|
+
# Recover stale WORKING state (supervisor or worker died mid-work).
|
|
720
|
+
# Lease-based recovery (2026-07-31): when we entered WORKING we recorded
|
|
721
|
+
# the owning supervisor PID. On resume, a WORKING task whose lease owner
|
|
722
|
+
# is a DIFFERENT, now-dead pid means the previous supervisor crashed —
|
|
723
|
+
# crash the task and let the retry budget requeue it. A live owner (or
|
|
724
|
+
# our own pid on resume) keeps the existing worker_results check.
|
|
725
|
+
if state.status == "WORKING":
|
|
726
|
+
lease = state.data.get("worker_lease")
|
|
727
|
+
lease_dead = (
|
|
728
|
+
isinstance(lease, dict)
|
|
729
|
+
and isinstance(lease.get("pid"), int)
|
|
730
|
+
and lease["pid"] != os.getpid()
|
|
731
|
+
and not _pid_alive(lease["pid"])
|
|
732
|
+
)
|
|
733
|
+
worker_done = bool(state.worker_results) and state.worker_results[-1].get("exit_code") is not None
|
|
734
|
+
if lease_dead or not worker_done:
|
|
735
|
+
state.transition("CRASHED", reason="worker terminated abnormally (stale WORKING)")
|
|
736
|
+
state.patch_data({"crash_reason": "recovered: WORKING with no live lease owner"})
|
|
737
|
+
self._safe_save(state, state_file)
|
|
738
|
+
self.graph.update_status(task_id, "CRASHED")
|
|
739
|
+
|
|
740
|
+
# Ephemeral worktree sandboxing (issue #15): opt-in via env or
|
|
741
|
+
# contract flag. When active, worker + verifiers for THIS contract
|
|
742
|
+
# run against an isolated git worktree; changes merge into the base
|
|
743
|
+
# branch only on overall PASS. Never crashes the contract.
|
|
744
|
+
sandbox_manager = None
|
|
745
|
+
sandbox_handle = None
|
|
746
|
+
exec_root = self.workspace_root
|
|
747
|
+
if _worktree_sandbox_requested(contract):
|
|
748
|
+
try:
|
|
749
|
+
_mgr = WorktreeManager(workspace_root=self.workspace_root)
|
|
750
|
+
_attempt = int(getattr(state, "attempt", 1) or 1)
|
|
751
|
+
_handle = _mgr.sandbox_create(task_id, attempt=_attempt)
|
|
752
|
+
if _handle is None:
|
|
753
|
+
print(f"[worktree] not a git repo; running {task_id} unsandboxed", file=sys.stderr)
|
|
754
|
+
else:
|
|
755
|
+
sandbox_manager = _mgr
|
|
756
|
+
sandbox_handle = _handle
|
|
757
|
+
exec_root = _handle.path
|
|
758
|
+
self._sandbox_registry_add(task_id, _mgr, _handle)
|
|
759
|
+
print(
|
|
760
|
+
f"[worktree] sandboxed {task_id} at {_handle.path} (branch {_handle.branch})",
|
|
761
|
+
file=sys.stderr,
|
|
762
|
+
)
|
|
763
|
+
except Exception as wt_exc:
|
|
764
|
+
sandbox_manager = None
|
|
765
|
+
sandbox_handle = None
|
|
766
|
+
exec_root = self.workspace_root
|
|
767
|
+
print(
|
|
768
|
+
f"[worktree] sandbox unavailable for {task_id}: {wt_exc}; falling back to unsandboxed",
|
|
769
|
+
file=sys.stderr,
|
|
770
|
+
)
|
|
771
|
+
|
|
772
|
+
# 2. Work + Verify + QC retry loop
|
|
773
|
+
while state.attempt <= max_attempts:
|
|
774
|
+
if state.status in ("COMPLETE", "FORCE_COMPLETE", "DEGRADED_PASS", "ESCALATED", "BLOCKED", "CANCELLED"):
|
|
775
|
+
break
|
|
776
|
+
|
|
777
|
+
# Auto-retry from VERIFICATION_FAILED, QC_REJECTED, CRASHED,
|
|
778
|
+
# QC_INSUFFICIENT_EVIDENCE, or QC_CONDITIONAL_PASS
|
|
779
|
+
if state.status in (
|
|
780
|
+
"VERIFICATION_FAILED",
|
|
781
|
+
"QC_REJECTED",
|
|
782
|
+
"CRASHED",
|
|
783
|
+
"QC_INSUFFICIENT_EVIDENCE",
|
|
784
|
+
"QC_CONDITIONAL_PASS",
|
|
785
|
+
):
|
|
786
|
+
if state.attempt >= max_attempts:
|
|
787
|
+
# AUT-003: EVERY exhausted failure state escalates with an
|
|
788
|
+
# impossibility artifact — no silent terminal
|
|
789
|
+
# VERIFICATION_FAILED that leaves the goal unexplained.
|
|
790
|
+
state.transition("ESCALATED", reason=f"max attempts ({max_attempts}) reached")
|
|
791
|
+
imp.write_impossibility(contract, state, self.goal.goal_id, self.workspace_root)
|
|
792
|
+
self._emit("impossibility.generated", goal_id=self.goal.goal_id, task_id=task_id)
|
|
793
|
+
self.graph.update_status(task_id, "ESCALATED")
|
|
794
|
+
break
|
|
795
|
+
state.increment_attempt()
|
|
796
|
+
retry_trigger = state.status
|
|
797
|
+
fclass = classify_failure(state, contract)
|
|
798
|
+
state.patch_data({"last_failure_class": fclass})
|
|
799
|
+
strategy_fingerprint, prior_fingerprint = _retry_fingerprints(state, fclass, state.attempt)
|
|
800
|
+
approach_desc = f"auto-retry from {retry_trigger}"
|
|
801
|
+
# AUT-002: repair nondeterministic worker slips (leaving an
|
|
802
|
+
# undeclared helper file) by deleting newly-created
|
|
803
|
+
# undeclared files before the retry — never modified
|
|
804
|
+
# pre-existing files.
|
|
805
|
+
if state.status == "VERIFICATION_FAILED":
|
|
806
|
+
self._auto_clean_undeclared_outputs(contract, state)
|
|
807
|
+
state.record_approach(approach_desc)
|
|
808
|
+
state.add_retry_metadata(
|
|
809
|
+
{
|
|
810
|
+
"attempt": state.attempt,
|
|
811
|
+
"trigger": retry_trigger,
|
|
812
|
+
"approach": approach_desc,
|
|
813
|
+
"changed_dimensions": ["implementation_approach"],
|
|
814
|
+
"strategy_fingerprint": strategy_fingerprint,
|
|
815
|
+
"prior_fingerprint": prior_fingerprint,
|
|
816
|
+
"failure_ids": [fclass],
|
|
817
|
+
}
|
|
818
|
+
)
|
|
819
|
+
state.transition("RETRY_PENDING", reason=f"auto-retry as attempt {state.attempt}")
|
|
820
|
+
self._safe_save(state, state_file)
|
|
821
|
+
|
|
822
|
+
# Work phase
|
|
823
|
+
if state.status in ("READY", "ready", "RETRY_PENDING", "retry_pending"):
|
|
824
|
+
self.metrics_coll.start_phase("work", task_id)
|
|
825
|
+
state.transition("WORKING", reason="supervisor starting work")
|
|
826
|
+
# Lease owner = this supervisor process. Lets a resumed run
|
|
827
|
+
# detect that the previous supervisor died mid-work.
|
|
828
|
+
state.patch_data({"worker_lease": {"pid": os.getpid(), "ts": time.time()}})
|
|
829
|
+
self._safe_save(state, state_file)
|
|
830
|
+
self._emit("contract.working", goal_id=self.goal.goal_id, task_id=task_id)
|
|
831
|
+
|
|
832
|
+
allowed = contract.workspace_scope.get("allow", [])
|
|
833
|
+
denied = contract.workspace_scope.get("deny", [])
|
|
834
|
+
sc.snapshot_scope(self.workspace_root, allowed, task_dir, denied_paths=denied)
|
|
835
|
+
|
|
836
|
+
if self.dry_run:
|
|
837
|
+
for out in contract.outputs:
|
|
838
|
+
out_path = out["path"]
|
|
839
|
+
full = os.path.join(self.workspace_root, out_path) if not os.path.isabs(out_path) else out_path
|
|
840
|
+
os.makedirs(os.path.dirname(full), exist_ok=True)
|
|
841
|
+
with open(full, "w", encoding="utf-8") as f:
|
|
842
|
+
f.write("SIMULATED: dry-run output")
|
|
843
|
+
worker_result = {
|
|
844
|
+
"success": True,
|
|
845
|
+
"stdout": "dry-run simulated",
|
|
846
|
+
"stderr": "",
|
|
847
|
+
"exit_code": 0,
|
|
848
|
+
"elapsed_sec": 0.01,
|
|
849
|
+
"artifact_paths": [out["path"] for out in contract.outputs],
|
|
850
|
+
}
|
|
851
|
+
else:
|
|
852
|
+
previous_failures = None
|
|
853
|
+
if state.worker_results:
|
|
854
|
+
previous_failures = [
|
|
855
|
+
{"message": r.get("stderr", "") or f"exit code {r.get('exit_code', '?')}"}
|
|
856
|
+
for r in state.worker_results[-3:]
|
|
857
|
+
]
|
|
858
|
+
# Perpetual-loop r2: expose retry fingerprints to the worker
|
|
859
|
+
# so build_implementer_prompt can demand a real approach
|
|
860
|
+
# change when the failure signature repeats.
|
|
861
|
+
_rm = state.data.get("retry_metadata", [])
|
|
862
|
+
_latest = _rm[-1] if isinstance(_rm, list) and _rm and isinstance(_rm[-1], dict) else {}
|
|
863
|
+
contract.worker["_strategy_fingerprint"] = str(_latest.get("strategy_fingerprint", "") or "")
|
|
864
|
+
contract.worker["_prior_fingerprint"] = str(_latest.get("prior_fingerprint", "") or "")
|
|
865
|
+
worker_result = run_worker(
|
|
866
|
+
contract,
|
|
867
|
+
exec_root,
|
|
868
|
+
task_dir,
|
|
869
|
+
previous_failures=previous_failures,
|
|
870
|
+
supervisor_attempt=state.attempt,
|
|
871
|
+
)
|
|
872
|
+
state.add_worker_result(worker_result)
|
|
873
|
+
if worker_result.get("exit_code", 0) != 0:
|
|
874
|
+
state.patch_data({"worker_exit_nonzero": True})
|
|
875
|
+
elif state.data.get("worker_exit_nonzero") and worker_result.get("exit_code") == 0:
|
|
876
|
+
state.delete_data_key("worker_exit_nonzero")
|
|
877
|
+
self.metrics_coll.end_phase("work", task_id)
|
|
878
|
+
self.metrics_coll.record_attempt(task_id)
|
|
879
|
+
state.add_evidence(
|
|
880
|
+
f"worker_attempt_{state.attempt}",
|
|
881
|
+
os.path.join(task_dir, "worker_output.log"),
|
|
882
|
+
)
|
|
883
|
+
state.transition("VERIFYING", reason="supervisor worker finished")
|
|
884
|
+
self._safe_save(state, state_file)
|
|
885
|
+
|
|
886
|
+
# Post-worker scope check. Exclude the supervisor's OWN run-state
|
|
887
|
+
# tree (state.json, journals, sibling task dirs) — those are
|
|
888
|
+
# orchestrator artifacts, not worker output. Parallel-mode fix.
|
|
889
|
+
# Worktree-sandboxed attempts skip the host scan entirely: worker
|
|
890
|
+
# writes land inside the sandbox (whose undeclared_outputs
|
|
891
|
+
# verifier check enforces scope there), and scanning the host
|
|
892
|
+
# would otherwise flag files physically nested under
|
|
893
|
+
# .letitloop/worktrees/.
|
|
894
|
+
scope_violations = []
|
|
895
|
+
if state.worker_results and sandbox_handle is None:
|
|
896
|
+
scope_result = sc.check_scope(
|
|
897
|
+
contract, self.workspace_root, task_dir, exclude_dir=self.run_dir, task_id=task_id
|
|
898
|
+
)
|
|
899
|
+
if not scope_result.passed:
|
|
900
|
+
print(
|
|
901
|
+
f"[supervisor] SCOPE VIOLATION in {task_id} — {len(scope_result.violations)} issue(s)",
|
|
902
|
+
file=sys.stderr,
|
|
903
|
+
)
|
|
904
|
+
for v in scope_result.violations:
|
|
905
|
+
print(f" [{v.violation_type}] {v.path}", file=sys.stderr)
|
|
906
|
+
state.patch_data({"scope_violations": [v.to_dict() for v in scope_result.violations]})
|
|
907
|
+
# Parallel-mode fix (2026-07-31): a sibling task's declared
|
|
908
|
+
# output is NOT an undeclared file — filter it out before
|
|
909
|
+
# treating violations as scope enforcement failures.
|
|
910
|
+
plan_outputs = set()
|
|
911
|
+
for _plan_c in self.plan.contracts:
|
|
912
|
+
c = _plan_c.get("contract", {})
|
|
913
|
+
if isinstance(c, dict):
|
|
914
|
+
plan_outputs.update(o.get("path", "") for o in c.get("outputs", []))
|
|
915
|
+
undeclared = [
|
|
916
|
+
v
|
|
917
|
+
for v in scope_result.violations
|
|
918
|
+
if v.violation_type in ("outside_scope", "denied_new", "denied_modified")
|
|
919
|
+
and not sc.is_path_exempt(
|
|
920
|
+
v.path,
|
|
921
|
+
list(plan_outputs),
|
|
922
|
+
workspace_root=self.workspace_root,
|
|
923
|
+
)
|
|
924
|
+
]
|
|
925
|
+
if undeclared:
|
|
926
|
+
scope_violations = undeclared
|
|
927
|
+
state.patch_data({"undeclared_outputs": [v.to_dict() for v in undeclared]})
|
|
928
|
+
print(
|
|
929
|
+
f"[supervisor] SCOPE ENFORCEMENT: {len(undeclared)} undeclared file(s) detected",
|
|
930
|
+
file=sys.stderr,
|
|
931
|
+
)
|
|
932
|
+
|
|
933
|
+
# Verify phase
|
|
934
|
+
if state.status in ("VERIFYING", "verifying"):
|
|
935
|
+
self.metrics_coll.start_phase("verify", task_id)
|
|
936
|
+
|
|
937
|
+
# Inject auto-generated checks from quality_spec
|
|
938
|
+
injected_checks = []
|
|
939
|
+
quality_spec = getattr(contract, "quality_spec", {})
|
|
940
|
+
if quality_spec:
|
|
941
|
+
req_secs = quality_spec.get("required_sections", [])
|
|
942
|
+
if req_secs and contract.outputs:
|
|
943
|
+
for out in contract.outputs[:1]:
|
|
944
|
+
out_path = str(out.get("path", "")).lower()
|
|
945
|
+
if out_path.endswith((".md", ".markdown", ".txt", ".rst")):
|
|
946
|
+
injected_checks.append(
|
|
947
|
+
{
|
|
948
|
+
"id": "required_sections",
|
|
949
|
+
"kind": "required_sections",
|
|
950
|
+
"path": out["path"],
|
|
951
|
+
"expected": req_secs,
|
|
952
|
+
}
|
|
953
|
+
)
|
|
954
|
+
# Inject undeclared outputs check using scope snapshot
|
|
955
|
+
snapshot_path = os.path.join(task_dir, sc.SCOPE_SNAPSHOT_FILE)
|
|
956
|
+
if contract.outputs and os.path.isfile(snapshot_path):
|
|
957
|
+
allowed = contract.workspace_scope.get("allow", [])
|
|
958
|
+
# Parallel-mode fix (2026-07-31): concurrent tasks write
|
|
959
|
+
# their OWN declared outputs, which a sibling's check would
|
|
960
|
+
# otherwise flag as undeclared. Treat every contract's
|
|
961
|
+
# declared outputs as declared for the whole plan.
|
|
962
|
+
plan_outputs = []
|
|
963
|
+
for _plan_c in self.plan.contracts:
|
|
964
|
+
c = _plan_c.get("contract", {})
|
|
965
|
+
if isinstance(c, dict):
|
|
966
|
+
plan_outputs.extend(o.get("path", "") for o in c.get("outputs", []))
|
|
967
|
+
injected_checks.append(
|
|
968
|
+
{
|
|
969
|
+
"id": "undeclared_outputs",
|
|
970
|
+
"kind": "undeclared_outputs",
|
|
971
|
+
"declared_outputs": [o["path"] for o in contract.outputs] + plan_outputs,
|
|
972
|
+
"scope_snapshot_path": snapshot_path,
|
|
973
|
+
"allowed_paths": allowed,
|
|
974
|
+
}
|
|
975
|
+
)
|
|
976
|
+
base_checks = [
|
|
977
|
+
c
|
|
978
|
+
for c in contract.acceptance_checks
|
|
979
|
+
if isinstance(c, dict) and c.get("id") not in ("undeclared_outputs", "required_sections")
|
|
980
|
+
]
|
|
981
|
+
contract.acceptance_checks = base_checks + injected_checks
|
|
982
|
+
|
|
983
|
+
all_passed, v_results, evidence_path = run_verification(contract, exec_root, task_dir)
|
|
984
|
+
|
|
985
|
+
# If scope violations found, force verification failure and update evidence
|
|
986
|
+
if scope_violations:
|
|
987
|
+
all_passed = False
|
|
988
|
+
# AUT-019: append a REAL VerifierResult, never a lambda —
|
|
989
|
+
# downstream code calls .to_dict() on these results.
|
|
990
|
+
from orchestrator.verifier import VerifierResult
|
|
991
|
+
|
|
992
|
+
v_results.append(
|
|
993
|
+
VerifierResult(
|
|
994
|
+
check_id="scope_enforcement",
|
|
995
|
+
kind="scope_enforcement",
|
|
996
|
+
passed=False,
|
|
997
|
+
message=f"{len(scope_violations)} undeclared file(s)",
|
|
998
|
+
)
|
|
999
|
+
)
|
|
1000
|
+
scope_entry = {
|
|
1001
|
+
"check_id": "scope_enforcement",
|
|
1002
|
+
"kind": "scope_enforcement",
|
|
1003
|
+
"passed": False,
|
|
1004
|
+
"message": f"{len(scope_violations)} undeclared file(s)",
|
|
1005
|
+
"stdout": "",
|
|
1006
|
+
"stderr": "",
|
|
1007
|
+
"exit_code": None,
|
|
1008
|
+
}
|
|
1009
|
+
# Re-save evidence to include scope check
|
|
1010
|
+
if evidence_path and os.path.isfile(evidence_path):
|
|
1011
|
+
try:
|
|
1012
|
+
with open(evidence_path, "r", encoding="utf-8") as f:
|
|
1013
|
+
ev_data = json.load(f)
|
|
1014
|
+
ev_data["verification_results"].append(scope_entry)
|
|
1015
|
+
ev_data["all_passed"] = False
|
|
1016
|
+
with open(evidence_path, "w", encoding="utf-8") as f:
|
|
1017
|
+
json.dump(ev_data, f, indent=2, ensure_ascii=False)
|
|
1018
|
+
except (OSError, json.JSONDecodeError):
|
|
1019
|
+
pass
|
|
1020
|
+
self.metrics_coll.end_phase("verify", task_id)
|
|
1021
|
+
if evidence_path:
|
|
1022
|
+
state.add_evidence("verification", evidence_path)
|
|
1023
|
+
|
|
1024
|
+
if all_passed:
|
|
1025
|
+
state.transition("VERIFIED", reason="supervisor verify passed")
|
|
1026
|
+
self._emit("contract.verified", goal_id=self.goal.goal_id, task_id=task_id)
|
|
1027
|
+
qc_required = contract.qc.get("required", False)
|
|
1028
|
+
if state.data.get("worker_exit_nonzero"):
|
|
1029
|
+
qc_required = True
|
|
1030
|
+
if not qc_required:
|
|
1031
|
+
state.transition("COMPLETE", reason="verify passed, no QC required")
|
|
1032
|
+
self.graph.mark_complete(task_id)
|
|
1033
|
+
self._safe_save(state, state_file)
|
|
1034
|
+
break
|
|
1035
|
+
state.transition("QC_RUNNING", reason="verify passed, starting QC review")
|
|
1036
|
+
self._safe_save(state, state_file)
|
|
1037
|
+
|
|
1038
|
+
output_paths = [
|
|
1039
|
+
os.path.join(exec_root, out["path"]) if not os.path.isabs(out["path"]) else out["path"]
|
|
1040
|
+
for out in contract.outputs
|
|
1041
|
+
]
|
|
1042
|
+
v_results_dicts = [r.to_dict() for r in v_results]
|
|
1043
|
+
from orchestrator.quality_plan import QualityPlan, quality_plan_for_contract, validate_quality_plan
|
|
1044
|
+
from orchestrator.quality_plane import run_quality_plane
|
|
1045
|
+
|
|
1046
|
+
qp = None
|
|
1047
|
+
if getattr(contract, "quality_plan", None):
|
|
1048
|
+
try:
|
|
1049
|
+
qp = QualityPlan.from_dict(contract.quality_plan)
|
|
1050
|
+
plan_errors = validate_quality_plan(qp)
|
|
1051
|
+
if plan_errors:
|
|
1052
|
+
print(
|
|
1053
|
+
f"[supervisor] invalid explicit quality_plan for {task_id}: {plan_errors}; falling back to default",
|
|
1054
|
+
file=sys.stderr,
|
|
1055
|
+
)
|
|
1056
|
+
qp = None
|
|
1057
|
+
except (TypeError, ValueError, KeyError, AttributeError) as e:
|
|
1058
|
+
print(
|
|
1059
|
+
f"[supervisor] unparseable quality_plan for {task_id}: {e}; falling back to default",
|
|
1060
|
+
file=sys.stderr,
|
|
1061
|
+
)
|
|
1062
|
+
qp = None
|
|
1063
|
+
if qp is None:
|
|
1064
|
+
qp = quality_plan_for_contract(
|
|
1065
|
+
contract.risk_tier,
|
|
1066
|
+
contract.qc.get("lens", "code_correctness"),
|
|
1067
|
+
contract.quality_spec,
|
|
1068
|
+
)
|
|
1069
|
+
if qp.budget.max_llm_calls is not None and qp.estimate_calls() > qp.budget.max_llm_calls:
|
|
1070
|
+
qp = qp.degraded_copy()
|
|
1071
|
+
self.metrics_coll.start_phase("qc", task_id)
|
|
1072
|
+
verdict = run_quality_plane(
|
|
1073
|
+
contract,
|
|
1074
|
+
output_paths,
|
|
1075
|
+
v_results_dicts,
|
|
1076
|
+
self.workspace_root,
|
|
1077
|
+
quality_plan=qp,
|
|
1078
|
+
)
|
|
1079
|
+
self.metrics_coll.end_phase("qc", task_id)
|
|
1080
|
+
print(
|
|
1081
|
+
f"[supervisor] QC for {task_id}: {verdict.status} score={verdict.score:.2f}"
|
|
1082
|
+
f" issues={len(verdict.issues)} — {verdict.reason}",
|
|
1083
|
+
file=sys.stderr,
|
|
1084
|
+
)
|
|
1085
|
+
|
|
1086
|
+
evidence_path_qc = os.path.join(task_dir, "qc_verdict.json")
|
|
1087
|
+
vd = verdict.to_dict()
|
|
1088
|
+
with open(evidence_path_qc, "w", encoding="utf-8") as f:
|
|
1089
|
+
json.dump(vd, f, indent=2, ensure_ascii=False)
|
|
1090
|
+
state.add_evidence("qc_verdict", evidence_path_qc)
|
|
1091
|
+
self._store_qc_timing_artifact(task_id)
|
|
1092
|
+
|
|
1093
|
+
if verdict.passed:
|
|
1094
|
+
if not os.path.isfile(evidence_path_qc):
|
|
1095
|
+
state.transition("QC_INSUFFICIENT_EVIDENCE", reason="QC verdict file missing after write")
|
|
1096
|
+
self.graph.update_status(task_id, "QC_INSUFFICIENT_EVIDENCE")
|
|
1097
|
+
self._safe_save(state, state_file)
|
|
1098
|
+
break
|
|
1099
|
+
state.transition("QC_PASSED", reason=verdict.reason)
|
|
1100
|
+
self._emit("contract.qc_passed", goal_id=self.goal.goal_id, task_id=task_id)
|
|
1101
|
+
if state.data.get("worker_exit_nonzero"):
|
|
1102
|
+
state.transition("DEGRADED_PASS", reason="QC passed with degraded worker exit")
|
|
1103
|
+
else:
|
|
1104
|
+
state.transition("COMPLETE", reason="QC passed")
|
|
1105
|
+
self.graph.mark_complete(task_id)
|
|
1106
|
+
self._safe_save(state, state_file)
|
|
1107
|
+
break
|
|
1108
|
+
else:
|
|
1109
|
+
state.patch_data(
|
|
1110
|
+
{
|
|
1111
|
+
"last_qc_rejection": verdict.reason,
|
|
1112
|
+
"qc_score": verdict.score,
|
|
1113
|
+
"qc_issues": verdict.issues,
|
|
1114
|
+
}
|
|
1115
|
+
)
|
|
1116
|
+
if verdict.status == "INSUFFICIENT_EVIDENCE":
|
|
1117
|
+
state.transition(
|
|
1118
|
+
"QC_INSUFFICIENT_EVIDENCE", reason=f"QC {verdict.status}: {verdict.reason}"
|
|
1119
|
+
)
|
|
1120
|
+
self.graph.update_status(task_id, "QC_INSUFFICIENT_EVIDENCE")
|
|
1121
|
+
elif verdict.status == "CONDITIONAL_PASS":
|
|
1122
|
+
state.transition("QC_CONDITIONAL_PASS", reason=f"QC {verdict.status}: {verdict.reason}")
|
|
1123
|
+
self.graph.update_status(task_id, "QC_CONDITIONAL_PASS")
|
|
1124
|
+
elif verdict.status == "ERROR":
|
|
1125
|
+
state.patch_data({"last_qc_error": True})
|
|
1126
|
+
state.transition("QC_REJECTED", reason=f"QC ERROR: {verdict.reason}")
|
|
1127
|
+
self.graph.update_status(task_id, "QC_REJECTED")
|
|
1128
|
+
else:
|
|
1129
|
+
state.transition("QC_REJECTED", reason=f"QC {verdict.status}: {verdict.reason}")
|
|
1130
|
+
self.graph.update_status(task_id, "QC_REJECTED")
|
|
1131
|
+
state.add_retry_metadata(
|
|
1132
|
+
{
|
|
1133
|
+
"attempt": state.attempt,
|
|
1134
|
+
"trigger": f"QC_{verdict.status}",
|
|
1135
|
+
"approach": f"QC rejection: {verdict.reason}",
|
|
1136
|
+
"changed_dimensions": ["implementation_approach"],
|
|
1137
|
+
"strategy_fingerprint": "",
|
|
1138
|
+
"prior_fingerprint": "",
|
|
1139
|
+
"failure_ids": [verdict.status],
|
|
1140
|
+
}
|
|
1141
|
+
)
|
|
1142
|
+
self._safe_save(state, state_file)
|
|
1143
|
+
continue
|
|
1144
|
+
else:
|
|
1145
|
+
state.transition("VERIFICATION_FAILED", reason="verification failed")
|
|
1146
|
+
if state.data.get("worker_exit_nonzero"):
|
|
1147
|
+
state.patch_data({"degraded_exit": True})
|
|
1148
|
+
self.graph.update_status(task_id, "VERIFICATION_FAILED")
|
|
1149
|
+
self._safe_save(state, state_file)
|
|
1150
|
+
continue
|
|
1151
|
+
|
|
1152
|
+
# Sandbox resolution: fold isolated changes into the base branch only
|
|
1153
|
+
# on overall PASS; discard them otherwise. Worktree errors never fail
|
|
1154
|
+
# the task itself.
|
|
1155
|
+
if sandbox_handle is not None:
|
|
1156
|
+
if state.status in _SANDBOX_PASS_STATUSES:
|
|
1157
|
+
try:
|
|
1158
|
+
merged = sandbox_manager.merge_on_pass(sandbox_handle)
|
|
1159
|
+
except Exception as merge_exc:
|
|
1160
|
+
merged = False
|
|
1161
|
+
print(f"[worktree] merge error for {task_id}: {merge_exc}", file=sys.stderr)
|
|
1162
|
+
if merged:
|
|
1163
|
+
print(f"[worktree] merged {task_id} into base branch", file=sys.stderr)
|
|
1164
|
+
else:
|
|
1165
|
+
print(f"[worktree] merge declined for {task_id}; pruning sandbox", file=sys.stderr)
|
|
1166
|
+
try:
|
|
1167
|
+
sandbox_manager.prune_on_fail(sandbox_handle)
|
|
1168
|
+
except Exception as prune_exc:
|
|
1169
|
+
print(f"[worktree] prune error for {task_id}: {prune_exc}", file=sys.stderr)
|
|
1170
|
+
else:
|
|
1171
|
+
try:
|
|
1172
|
+
sandbox_manager.prune_on_fail(sandbox_handle)
|
|
1173
|
+
except Exception as prune_exc:
|
|
1174
|
+
print(f"[worktree] prune error for {task_id}: {prune_exc}", file=sys.stderr)
|
|
1175
|
+
self._sandbox_registry_pop(task_id)
|
|
1176
|
+
sandbox_handle = None
|
|
1177
|
+
sandbox_manager = None
|
|
1178
|
+
exec_root = self.workspace_root
|
|
1179
|
+
|
|
1180
|
+
# Clean up scratch_dir (helper artifacts) on terminal success
|
|
1181
|
+
if state.status in ("COMPLETE", "complete", "FORCE_COMPLETE", "DEGRADED_PASS"):
|
|
1182
|
+
try:
|
|
1183
|
+
sc.cleanup_scratch_dir(self.workspace_root, contract)
|
|
1184
|
+
except (OSError, ValueError):
|
|
1185
|
+
pass
|
|
1186
|
+
|
|
1187
|
+
# Post-loop: handle COMPLETE evidence store
|
|
1188
|
+
if state.status in ("COMPLETE", "complete", "DEGRADED_PASS", "FORCE_COMPLETE"):
|
|
1189
|
+
import shutil
|
|
1190
|
+
|
|
1191
|
+
art_dir = os.path.join(self.workspace_root, imp.artifact_dir(self.goal.goal_id, task_id))
|
|
1192
|
+
if os.path.isdir(art_dir):
|
|
1193
|
+
shutil.rmtree(art_dir, ignore_errors=True)
|
|
1194
|
+
contract_path, contract_dict_completed = self._get_contract_path_and_dict(c_info)
|
|
1195
|
+
completed_contract, _ = load_contract(contract_path, workspace_root=self.workspace_root)
|
|
1196
|
+
if completed_contract:
|
|
1197
|
+
with self._shared_lock:
|
|
1198
|
+
self.evidence_store[task_id] = [
|
|
1199
|
+
os.path.join(self.workspace_root, out["path"])
|
|
1200
|
+
if not os.path.isabs(out["path"])
|
|
1201
|
+
else out["path"]
|
|
1202
|
+
for out in completed_contract.outputs
|
|
1203
|
+
]
|
|
1204
|
+
completed_outs = completed_contract.outputs if completed_contract else []
|
|
1205
|
+
for out in completed_outs:
|
|
1206
|
+
ev.append_output(self.run_dir, task_id, out["path"], self.workspace_root)
|
|
1207
|
+
try:
|
|
1208
|
+
self.memory_bridge.append(
|
|
1209
|
+
{
|
|
1210
|
+
"task_id": task_id,
|
|
1211
|
+
"event": "CONTRACT_COMPLETED",
|
|
1212
|
+
"outputs": [o.get("path") if isinstance(o, dict) else str(o) for o in completed_outs],
|
|
1213
|
+
"status": state.status,
|
|
1214
|
+
}
|
|
1215
|
+
)
|
|
1216
|
+
except (TimeoutError, OSError, json.JSONDecodeError, ValueError):
|
|
1217
|
+
pass
|
|
1218
|
+
|
|
1219
|
+
if state.status in ("PREFLIGHT_FAILED", "BLOCKED", "VERIFICATION_FAILED", "ESCALATED"):
|
|
1220
|
+
fclass = classify_failure(state, contract)
|
|
1221
|
+
state.patch_data({"last_failure_class": fclass})
|
|
1222
|
+
self._safe_save(state, state_file)
|
|
1223
|
+
|
|
1224
|
+
fb_rec = fb.collect_feedback(task_id, self.goal.goal_id, state)
|
|
1225
|
+
if fb_rec:
|
|
1226
|
+
fb.store_feedback(self.goal.goal_id, self.run_dir, [fb_rec])
|
|
1227
|
+
|
|
1228
|
+
return state.status
|
|
1229
|
+
|
|
1230
|
+
def _declared_output_paths(self, task_id: str) -> List[str]:
|
|
1231
|
+
"""Return a task's declared output paths (for scope-lease registration)."""
|
|
1232
|
+
c_info = next((c for c in self.plan.contracts if c["task_id"] == task_id), None)
|
|
1233
|
+
if not c_info:
|
|
1234
|
+
return []
|
|
1235
|
+
contract_dict = c_info.get("contract", {})
|
|
1236
|
+
outputs = contract_dict.get("outputs", []) if isinstance(contract_dict, dict) else []
|
|
1237
|
+
return [o.get("path", "") for o in outputs if isinstance(o, dict) and o.get("path")]
|
|
1238
|
+
|
|
1239
|
+
def _execute_batch_serial(self, ready_tasks: List[str]) -> bool:
|
|
1240
|
+
"""Execute ready tasks serially. Returns True if any task made progress."""
|
|
1241
|
+
progress_made = False
|
|
1242
|
+
for idx, task_id in enumerate(ready_tasks):
|
|
1243
|
+
print(f"[supervisor] executing {task_id} ({idx + 1}/{len(ready_tasks)})", file=sys.stderr)
|
|
1244
|
+
prev_status = self.graph.nodes.get(task_id, {}).get("status")
|
|
1245
|
+
status = self._execute_single_contract(task_id)
|
|
1246
|
+
self.results[task_id] = {"status": status}
|
|
1247
|
+
print(f"[supervisor] {task_id} -> {status}", file=sys.stderr)
|
|
1248
|
+
if status != prev_status or status in ("COMPLETE", "complete", "DEGRADED_PASS", "FORCE_COMPLETE"):
|
|
1249
|
+
progress_made = True
|
|
1250
|
+
return progress_made
|
|
1251
|
+
|
|
1252
|
+
def _execute_batch_parallel(self, ready_tasks: List[str]) -> bool:
|
|
1253
|
+
"""Execute ready tasks in parallel using WorkerPool. Returns True if any made progress."""
|
|
1254
|
+
pool = wp.WorkerPool(max_workers=self.max_workers)
|
|
1255
|
+
task_infos = [{"task_id": tid} for tid in ready_tasks]
|
|
1256
|
+
|
|
1257
|
+
# Register every ready task's declared outputs BEFORE any worker can
|
|
1258
|
+
# launch, so sibling scope checks exempt them (perpetual-loop r1).
|
|
1259
|
+
for task_id in ready_tasks:
|
|
1260
|
+
try:
|
|
1261
|
+
self._scope_leases.register(task_id, self._declared_output_paths(task_id))
|
|
1262
|
+
except (KeyError, ValueError, OSError, AttributeError):
|
|
1263
|
+
pass
|
|
1264
|
+
|
|
1265
|
+
def run_leased(task_id: str) -> str:
|
|
1266
|
+
try:
|
|
1267
|
+
return self._execute_single_contract(task_id)
|
|
1268
|
+
finally:
|
|
1269
|
+
try:
|
|
1270
|
+
self._scope_leases.unregister(task_id)
|
|
1271
|
+
except (KeyError, ValueError, OSError, AttributeError):
|
|
1272
|
+
pass
|
|
1273
|
+
|
|
1274
|
+
def on_result(tid: str, status: str):
|
|
1275
|
+
with self._shared_lock:
|
|
1276
|
+
self.results[tid] = {"status": status}
|
|
1277
|
+
prev = self.graph.nodes.get(tid, {}).get("status")
|
|
1278
|
+
if status != prev or status in ("COMPLETE", "complete", "FORCE_COMPLETE"):
|
|
1279
|
+
print(f"[supervisor] {tid} -> {status} (parallel)", file=sys.stderr)
|
|
1280
|
+
|
|
1281
|
+
try:
|
|
1282
|
+
pool.execute_batch(task_infos, run_leased, on_result=on_result)
|
|
1283
|
+
finally:
|
|
1284
|
+
# Best-effort cleanup on pool setup failures too.
|
|
1285
|
+
for task_id in ready_tasks:
|
|
1286
|
+
try:
|
|
1287
|
+
self._scope_leases.unregister(task_id)
|
|
1288
|
+
except (KeyError, ValueError, OSError, AttributeError):
|
|
1289
|
+
pass
|
|
1290
|
+
return True
|
|
1291
|
+
|
|
1292
|
+
def execute_plan(self, force: Optional[bool] = None) -> Dict[str, str]:
|
|
1293
|
+
"""Execute plan under the goal lock (safe for direct CLI entry)."""
|
|
1294
|
+
try:
|
|
1295
|
+
dv.raise_if_invalid(self.plan.contracts)
|
|
1296
|
+
except DagValidationError as e:
|
|
1297
|
+
print(f"[supervisor] INVALID DAG: {e}", file=sys.stderr)
|
|
1298
|
+
raise
|
|
1299
|
+
force_lock = force if force is not None else getattr(self, "force", False)
|
|
1300
|
+
try:
|
|
1301
|
+
lk.acquire_lock(self.goal.goal_id, self.run_dir, force=force_lock)
|
|
1302
|
+
except lk.LockHeldError as e:
|
|
1303
|
+
print(f"[supervisor] LOCK HELD: {e}", file=sys.stderr)
|
|
1304
|
+
self.goal.status = "FAILED"
|
|
1305
|
+
return {}
|
|
1306
|
+
self._emit("goal.started", goal_id=self.goal.goal_id)
|
|
1307
|
+
results: Dict[str, str] = {}
|
|
1308
|
+
try:
|
|
1309
|
+
results = self._execute_plan()
|
|
1310
|
+
return results
|
|
1311
|
+
finally:
|
|
1312
|
+
lk.release_lock(self.run_dir)
|
|
1313
|
+
print(f"[supervisor] lock released for {self.goal.goal_id}", file=sys.stderr)
|
|
1314
|
+
try:
|
|
1315
|
+
completed = sum(
|
|
1316
|
+
1 for s in results.values() if str(s).upper() in ("COMPLETE", "DEGRADED_PASS", "FORCE_COMPLETE")
|
|
1317
|
+
)
|
|
1318
|
+
self._emit(
|
|
1319
|
+
"goal.completed",
|
|
1320
|
+
goal_id=self.goal.goal_id,
|
|
1321
|
+
completed=completed,
|
|
1322
|
+
failed=len(results) - completed,
|
|
1323
|
+
)
|
|
1324
|
+
except Exception:
|
|
1325
|
+
pass
|
|
1326
|
+
|
|
1327
|
+
def _execute_plan(self) -> Dict[str, str]:
|
|
1328
|
+
"""Execute all contracts in plan according to dependency order.
|
|
1329
|
+
|
|
1330
|
+
If self.parallel is True, independent ready-tasks are executed
|
|
1331
|
+
concurrently via WorkerPool. Sequential fallback otherwise.
|
|
1332
|
+
|
|
1333
|
+
Callers are responsible for holding the goal lock (see execute_plan).
|
|
1334
|
+
"""
|
|
1335
|
+
self.goal.status = "EXECUTING"
|
|
1336
|
+
_plan_start = time.time()
|
|
1337
|
+
|
|
1338
|
+
# Recover graph from state files (for resumption after interruption)
|
|
1339
|
+
self._recover_graph_from_state_files()
|
|
1340
|
+
self._save_plan()
|
|
1341
|
+
|
|
1342
|
+
max_attempts_sum = sum(
|
|
1343
|
+
c.get("contract", {}).get("worker", {}).get("max_attempts", 1) if isinstance(c.get("contract"), dict) else 1
|
|
1344
|
+
for c in self.plan.contracts
|
|
1345
|
+
)
|
|
1346
|
+
max_iterations = max_attempts_sum + 10
|
|
1347
|
+
iterations = 0
|
|
1348
|
+
_limit_breached = False
|
|
1349
|
+
|
|
1350
|
+
# Self-audit discovery 2026-07-31: the 600s default wall-clock limit
|
|
1351
|
+
# aborts multi-step research goals even after every contract passed
|
|
1352
|
+
# QC (5-step audit needs ~750s+). Scale the goal budget with plan
|
|
1353
|
+
# size: 300s per step, never below the 600s default.
|
|
1354
|
+
n_contracts = max(len(self.plan.contracts), 1)
|
|
1355
|
+
goal_limits = lm.ResourceLimits(
|
|
1356
|
+
max_wall_clock_sec=max(lm.DEFAULT_LIMITS.max_wall_clock_sec, n_contracts * 300),
|
|
1357
|
+
max_output_size_bytes=lm.DEFAULT_LIMITS.max_output_size_bytes,
|
|
1358
|
+
max_attempts_global=lm.DEFAULT_LIMITS.max_attempts_global,
|
|
1359
|
+
max_iterations=lm.DEFAULT_LIMITS.max_iterations,
|
|
1360
|
+
)
|
|
1361
|
+
|
|
1362
|
+
while iterations < max_iterations:
|
|
1363
|
+
try:
|
|
1364
|
+
lc = lm.check_limits(goal_limits, elapsed_sec=time.time() - _plan_start, iterations=iterations)
|
|
1365
|
+
if lc["exceeded"]:
|
|
1366
|
+
print(f"[supervisor] {lm.format_violation(lc)}", file=sys.stderr)
|
|
1367
|
+
_limit_breached = True
|
|
1368
|
+
break
|
|
1369
|
+
|
|
1370
|
+
ready_tasks = self.graph.get_ready_tasks()
|
|
1371
|
+
if not ready_tasks:
|
|
1372
|
+
break
|
|
1373
|
+
|
|
1374
|
+
# Auto-concurrent DAG execution: use ThreadPool parallel batch if >1 independent tasks ready
|
|
1375
|
+
active_batch_fn = (
|
|
1376
|
+
self._execute_batch_parallel
|
|
1377
|
+
if (self.parallel or len(ready_tasks) > 1)
|
|
1378
|
+
else self._execute_batch_serial
|
|
1379
|
+
)
|
|
1380
|
+
progress_made = active_batch_fn(ready_tasks)
|
|
1381
|
+
self._save_plan()
|
|
1382
|
+
|
|
1383
|
+
if not progress_made:
|
|
1384
|
+
# Stall-escalation (2026-07-31): no task advanced this
|
|
1385
|
+
# iteration. Do not exit leaving non-terminal nodes without
|
|
1386
|
+
# a decisive outcome — escalate them with impossibility
|
|
1387
|
+
# artifacts so an unattended run always ends in a terminal,
|
|
1388
|
+
# auditable state.
|
|
1389
|
+
self._escalate_stalled_nodes()
|
|
1390
|
+
break
|
|
1391
|
+
|
|
1392
|
+
iterations += 1
|
|
1393
|
+
|
|
1394
|
+
self._checkpoint_iteration += 1
|
|
1395
|
+
if self._checkpoint_iteration % self._checkpoint_interval == 0:
|
|
1396
|
+
cp.save_checkpoint(
|
|
1397
|
+
run_dir=self.run_dir,
|
|
1398
|
+
iteration=iterations,
|
|
1399
|
+
plan_contracts=self.plan.contracts,
|
|
1400
|
+
results=self.results,
|
|
1401
|
+
graph_statuses={tid: info.get("status", "UNKNOWN") for tid, info in self.graph.nodes.items()},
|
|
1402
|
+
evidence_store=self.evidence_store,
|
|
1403
|
+
goal_status=self.goal.status,
|
|
1404
|
+
total_contracts=len(self.plan.contracts),
|
|
1405
|
+
)
|
|
1406
|
+
print(f"[supervisor] checkpoint saved at iteration {iterations}", file=sys.stderr)
|
|
1407
|
+
|
|
1408
|
+
if iterations >= max_iterations:
|
|
1409
|
+
print(f"[supervisor] WARNING: max iterations ({max_iterations}) reached", file=sys.stderr)
|
|
1410
|
+
break
|
|
1411
|
+
except Exception as e:
|
|
1412
|
+
print(f"[supervisor] LOOP CRASHED at iteration {iterations}: {type(e).__name__}: {e}", file=sys.stderr)
|
|
1413
|
+
_limit_breached = True
|
|
1414
|
+
break
|
|
1415
|
+
|
|
1416
|
+
blocked_tasks = self.graph.get_blocked_tasks()
|
|
1417
|
+
all_completed = len(self.results) == len(self.plan.contracts) and all(
|
|
1418
|
+
r["status"] in ("COMPLETE", "complete", "DEGRADED_PASS", "FORCE_COMPLETE") for r in self.results.values()
|
|
1419
|
+
)
|
|
1420
|
+
|
|
1421
|
+
# AUT-004: a goal whose contracts all completed must be COMPLETE even
|
|
1422
|
+
# if the wall-clock limit was breached AFTER the final batch — the
|
|
1423
|
+
# completion result wins over the limit signal.
|
|
1424
|
+
if all_completed:
|
|
1425
|
+
self.goal.status = "COMPLETE"
|
|
1426
|
+
elif _limit_breached:
|
|
1427
|
+
self.goal.status = "FAILED"
|
|
1428
|
+
else:
|
|
1429
|
+
self.goal.status = (
|
|
1430
|
+
"FAILED"
|
|
1431
|
+
if blocked_tasks
|
|
1432
|
+
or any(
|
|
1433
|
+
r["status"]
|
|
1434
|
+
in (
|
|
1435
|
+
"VERIFICATION_FAILED",
|
|
1436
|
+
"FAILED",
|
|
1437
|
+
"failed",
|
|
1438
|
+
"BLOCKED",
|
|
1439
|
+
"blocked",
|
|
1440
|
+
"CRASHED",
|
|
1441
|
+
"DRAFTED",
|
|
1442
|
+
"drafted",
|
|
1443
|
+
)
|
|
1444
|
+
for r in self.results.values()
|
|
1445
|
+
)
|
|
1446
|
+
else "EXECUTING"
|
|
1447
|
+
)
|
|
1448
|
+
|
|
1449
|
+
metrics_path = os.path.join(self.run_dir, "metrics.json")
|
|
1450
|
+
self.metrics_coll.save(metrics_path)
|
|
1451
|
+
|
|
1452
|
+
self._print_run_summary()
|
|
1453
|
+
|
|
1454
|
+
return {tid: res["status"] for tid, res in self.results.items()}
|
|
1455
|
+
|
|
1456
|
+
def execute_plan_with_retry(self, changed_approach: Optional[str] = None) -> Dict[str, str]:
|
|
1457
|
+
"""Execute plan, and retry failed contracts if attempts remain."""
|
|
1458
|
+
try:
|
|
1459
|
+
lk.acquire_lock(self.goal.goal_id, self.run_dir)
|
|
1460
|
+
except lk.LockHeldError as e:
|
|
1461
|
+
print(f"[supervisor] LOCK HELD: {e}", file=sys.stderr)
|
|
1462
|
+
self.goal.status = "FAILED"
|
|
1463
|
+
return {}
|
|
1464
|
+
print(f"[supervisor] lock acquired for {self.goal.goal_id}", file=sys.stderr)
|
|
1465
|
+
try:
|
|
1466
|
+
res = self._execute_plan()
|
|
1467
|
+
|
|
1468
|
+
for c_info in self.plan.contracts:
|
|
1469
|
+
task_id = c_info["task_id"]
|
|
1470
|
+
state_file = self._state_path(task_id)
|
|
1471
|
+
if not os.path.isfile(state_file):
|
|
1472
|
+
continue
|
|
1473
|
+
state = load_state(state_file)
|
|
1474
|
+
contract_path, _ = self._get_contract_path_and_dict(c_info)
|
|
1475
|
+
contract, _ = load_contract(contract_path, workspace_root=self.workspace_root)
|
|
1476
|
+
if contract is None:
|
|
1477
|
+
continue
|
|
1478
|
+
|
|
1479
|
+
max_attempts = contract.worker.get("max_attempts", 1)
|
|
1480
|
+
if state.status in (
|
|
1481
|
+
"VERIFICATION_FAILED",
|
|
1482
|
+
"BLOCKED",
|
|
1483
|
+
"CRASHED",
|
|
1484
|
+
"QC_REJECTED",
|
|
1485
|
+
"QC_INSUFFICIENT_EVIDENCE",
|
|
1486
|
+
"QC_CONDITIONAL_PASS",
|
|
1487
|
+
):
|
|
1488
|
+
fclass = classify_failure(state, contract)
|
|
1489
|
+
state.patch_data({"last_failure_class": fclass})
|
|
1490
|
+
if state.status in ("BLOCKED", "CRASHED"):
|
|
1491
|
+
state.transition("DRAFTED", reason="resetting for retry")
|
|
1492
|
+
if state.attempt >= max_attempts:
|
|
1493
|
+
state.force_escalate(reason="max attempts reached in retry")
|
|
1494
|
+
self._safe_save(state, state_file)
|
|
1495
|
+
self.graph.update_status(task_id, "ESCALATED")
|
|
1496
|
+
res[task_id] = "ESCALATED"
|
|
1497
|
+
self._record_terminal(task_id, "ESCALATED")
|
|
1498
|
+
audit_mod.record_action(
|
|
1499
|
+
self.run_dir,
|
|
1500
|
+
"failsafe_escalation",
|
|
1501
|
+
goal_id=self.goal.goal_id,
|
|
1502
|
+
task_id=task_id,
|
|
1503
|
+
details={
|
|
1504
|
+
"reason": "max attempts reached",
|
|
1505
|
+
"attempt": state.attempt,
|
|
1506
|
+
"max_attempts": max_attempts,
|
|
1507
|
+
"failure_class": fclass,
|
|
1508
|
+
},
|
|
1509
|
+
)
|
|
1510
|
+
imp.write_impossibility(
|
|
1511
|
+
contract,
|
|
1512
|
+
state,
|
|
1513
|
+
goal_id=self.goal.goal_id,
|
|
1514
|
+
workspace_root=self.workspace_root,
|
|
1515
|
+
failure_class=fclass,
|
|
1516
|
+
)
|
|
1517
|
+
self._emit("impossibility.generated", goal_id=self.goal.goal_id, task_id=task_id)
|
|
1518
|
+
fb_rec = fb.collect_feedback(task_id, self.goal.goal_id, state)
|
|
1519
|
+
if fb_rec:
|
|
1520
|
+
fb.store_feedback(self.goal.goal_id, self.run_dir, [fb_rec])
|
|
1521
|
+
continue
|
|
1522
|
+
if state.worker_results:
|
|
1523
|
+
state.patch_worker_result(
|
|
1524
|
+
len(state.worker_results) - 1, annotate_worker_result(state.worker_results[-1], fclass)
|
|
1525
|
+
)
|
|
1526
|
+
strikes = count_consecutive_same_class(state, fclass)
|
|
1527
|
+
if strikes >= MAX_SAME_CLASS_STRIKES:
|
|
1528
|
+
state.force_escalate(reason="consecutive identical failure class")
|
|
1529
|
+
self._safe_save(state, state_file)
|
|
1530
|
+
self.graph.update_status(task_id, "ESCALATED")
|
|
1531
|
+
res[task_id] = "ESCALATED"
|
|
1532
|
+
self._record_terminal(task_id, "ESCALATED")
|
|
1533
|
+
self.metrics_coll.record_three_strike_escalation()
|
|
1534
|
+
imp.write_impossibility(
|
|
1535
|
+
contract,
|
|
1536
|
+
state,
|
|
1537
|
+
goal_id=self.goal.goal_id,
|
|
1538
|
+
workspace_root=self.workspace_root,
|
|
1539
|
+
failure_class=fclass,
|
|
1540
|
+
)
|
|
1541
|
+
self._emit("impossibility.generated", goal_id=self.goal.goal_id, task_id=task_id)
|
|
1542
|
+
fb_rec = fb.collect_feedback(task_id, self.goal.goal_id, state)
|
|
1543
|
+
if fb_rec:
|
|
1544
|
+
fb.store_feedback(self.goal.goal_id, self.run_dir, [fb_rec])
|
|
1545
|
+
continue
|
|
1546
|
+
state.increment_attempt()
|
|
1547
|
+
if changed_approach:
|
|
1548
|
+
if not require_divergent_retry(state, changed_approach):
|
|
1549
|
+
state.force_escalate(reason="non-divergent retry approach")
|
|
1550
|
+
res[task_id] = "ESCALATED"
|
|
1551
|
+
self._record_terminal(task_id, "ESCALATED")
|
|
1552
|
+
print(f"[supervisor] {task_id} ESCALATED — non-divergent retry approach", file=sys.stderr)
|
|
1553
|
+
imp.write_impossibility(
|
|
1554
|
+
contract,
|
|
1555
|
+
state,
|
|
1556
|
+
goal_id=self.goal.goal_id,
|
|
1557
|
+
workspace_root=self.workspace_root,
|
|
1558
|
+
failure_class=fclass,
|
|
1559
|
+
)
|
|
1560
|
+
self._emit("impossibility.generated", goal_id=self.goal.goal_id, task_id=task_id)
|
|
1561
|
+
continue
|
|
1562
|
+
state.record_approach(changed_approach)
|
|
1563
|
+
state.transition("RETRY_PENDING", reason="supervisor retrying contract")
|
|
1564
|
+
self._safe_save(state, state_file)
|
|
1565
|
+
self.graph.update_status(task_id, "RETRY_PENDING")
|
|
1566
|
+
|
|
1567
|
+
print(f"[supervisor] retrying {task_id}", file=sys.stderr)
|
|
1568
|
+
status = self._execute_single_contract(task_id)
|
|
1569
|
+
res[task_id] = status
|
|
1570
|
+
|
|
1571
|
+
if self.adaptive_replan:
|
|
1572
|
+
new_plan = self.adaptively_replan()
|
|
1573
|
+
if new_plan:
|
|
1574
|
+
print(
|
|
1575
|
+
f"[supervisor] Adaptively replanned into {len(new_plan.contracts)} contracts",
|
|
1576
|
+
file=sys.stderr,
|
|
1577
|
+
)
|
|
1578
|
+
res = self._execute_plan()
|
|
1579
|
+
|
|
1580
|
+
all_completed = all(
|
|
1581
|
+
status in ("COMPLETE", "complete", "DEGRADED_PASS", "FORCE_COMPLETE") for status in res.values()
|
|
1582
|
+
)
|
|
1583
|
+
self.goal.status = "COMPLETE" if all_completed else "FAILED"
|
|
1584
|
+
self._print_run_summary()
|
|
1585
|
+
return res
|
|
1586
|
+
finally:
|
|
1587
|
+
lk.release_lock(self.run_dir)
|
|
1588
|
+
print(f"[supervisor] lock released for {self.goal.goal_id}", file=sys.stderr)
|
|
1589
|
+
|
|
1590
|
+
def adaptively_replan(self) -> Optional[Plan]:
|
|
1591
|
+
"""Invoke evidence-aware replanner to split or adjust failed tasks."""
|
|
1592
|
+
from orchestrator import replanner as rep_mod
|
|
1593
|
+
|
|
1594
|
+
try:
|
|
1595
|
+
results = dict(self.results)
|
|
1596
|
+
for c in self.plan.contracts:
|
|
1597
|
+
tid = c.get("task_id")
|
|
1598
|
+
if tid and tid not in results:
|
|
1599
|
+
results[tid] = {"status": self.graph.nodes.get(tid, {}).get("status", "DRAFTED")}
|
|
1600
|
+
|
|
1601
|
+
new_plan = rep_mod.replan(self.goal, results, self.run_dir)
|
|
1602
|
+
if new_plan and len(new_plan.contracts) != len(self.plan.contracts):
|
|
1603
|
+
self.plan = new_plan
|
|
1604
|
+
self.graph = ContractGraph(new_plan)
|
|
1605
|
+
self._save_plan()
|
|
1606
|
+
return new_plan
|
|
1607
|
+
except (ValueError, KeyError, OSError, json.JSONDecodeError, TypeError) as e:
|
|
1608
|
+
print(f"[supervisor] Replanning error: {e}", file=sys.stderr)
|
|
1609
|
+
return None
|
|
1610
|
+
|
|
1611
|
+
def pause_plan(self, reason: str = "operator pause") -> Dict[str, str]:
|
|
1612
|
+
"""Pause all currently active (non-terminal, non-idle) tasks."""
|
|
1613
|
+
results = {}
|
|
1614
|
+
audit_mod.record_action(self.run_dir, "pause", goal_id=self.goal.goal_id, details={"reason": reason})
|
|
1615
|
+
for c_info in self.plan.contracts:
|
|
1616
|
+
tid = c_info["task_id"]
|
|
1617
|
+
state_file = self._state_path(tid)
|
|
1618
|
+
if not os.path.isfile(state_file):
|
|
1619
|
+
continue
|
|
1620
|
+
state = load_state(state_file)
|
|
1621
|
+
if state.pause(reason):
|
|
1622
|
+
self._safe_save(state, state_file)
|
|
1623
|
+
results[tid] = "PAUSED"
|
|
1624
|
+
else:
|
|
1625
|
+
results[tid] = state.status
|
|
1626
|
+
self.goal.status = "PAUSED"
|
|
1627
|
+
return results
|
|
1628
|
+
|
|
1629
|
+
def cancel_plan(self, reason: str = "operator cancel") -> Dict[str, str]:
|
|
1630
|
+
"""Cancel all non-terminal tasks."""
|
|
1631
|
+
results = {}
|
|
1632
|
+
audit_mod.record_action(self.run_dir, "cancel", goal_id=self.goal.goal_id, details={"reason": reason})
|
|
1633
|
+
for c_info in self.plan.contracts:
|
|
1634
|
+
tid = c_info["task_id"]
|
|
1635
|
+
state_file = self._state_path(tid)
|
|
1636
|
+
if not os.path.isfile(state_file):
|
|
1637
|
+
continue
|
|
1638
|
+
state = load_state(state_file)
|
|
1639
|
+
if state.cancel(reason):
|
|
1640
|
+
self._safe_save(state, state_file)
|
|
1641
|
+
results[tid] = "CANCELLED"
|
|
1642
|
+
else:
|
|
1643
|
+
results[tid] = state.status
|
|
1644
|
+
self.graph.update_status(tid, state.status)
|
|
1645
|
+
self.goal.status = "CANCELLED"
|
|
1646
|
+
return results
|
|
1647
|
+
|
|
1648
|
+
def inspect_task(self, task_id: str) -> Dict[str, Any]:
|
|
1649
|
+
"""Deep inspect a single task's state, evidence, and next actions."""
|
|
1650
|
+
state_file = self._state_path(task_id)
|
|
1651
|
+
if not os.path.isfile(state_file):
|
|
1652
|
+
return {"task_id": task_id, "error": "no state found"}
|
|
1653
|
+
state = load_state(state_file)
|
|
1654
|
+
c_info = next((c for c in self.plan.contracts if c["task_id"] == task_id), None)
|
|
1655
|
+
contract_dict = c_info.get("contract", {}) if c_info else {}
|
|
1656
|
+
task_dir = self._task_run_dir(task_id)
|
|
1657
|
+
evidence_files = {}
|
|
1658
|
+
for key, path in state.evidence.items():
|
|
1659
|
+
evidence_files[key] = {
|
|
1660
|
+
"path": path,
|
|
1661
|
+
"exists": os.path.isfile(path),
|
|
1662
|
+
}
|
|
1663
|
+
return {
|
|
1664
|
+
"task_id": task_id,
|
|
1665
|
+
"status": state.status,
|
|
1666
|
+
"attempt": state.attempt,
|
|
1667
|
+
"is_terminal": state.is_terminal(),
|
|
1668
|
+
"can_resume": state.can_resume(),
|
|
1669
|
+
"legal_transitions": sorted(state.legal_transitions()),
|
|
1670
|
+
"events_count": len(state.events),
|
|
1671
|
+
"worker_runs": len(state.worker_results),
|
|
1672
|
+
"last_worker_result": state.worker_results[-1] if state.worker_results else None,
|
|
1673
|
+
"failure_class": state.data.get("last_failure_class"),
|
|
1674
|
+
"crash_reason": state.data.get("crash_reason"),
|
|
1675
|
+
"scope_violations": state.data.get("scope_violations"),
|
|
1676
|
+
"evidence_files": evidence_files,
|
|
1677
|
+
"contract_title": contract_dict.get("title", ""),
|
|
1678
|
+
"contract_objective": contract_dict.get("objective", ""),
|
|
1679
|
+
"task_dir": task_dir,
|
|
1680
|
+
}
|