letitloop 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,191 @@
1
+ """Reconciliation — compares expected vs actual state for resume integrity."""
2
+
3
+ import json
4
+ import os
5
+ from typing import Any, Dict, List
6
+
7
+ from . import evidence as ev
8
+ from .goal import Plan
9
+
10
+ RECONCILE_ISSUE_OUTPUT_MISSING = "output_missing"
11
+ RECONCILE_ISSUE_FILE_MISSING = "file_missing"
12
+ RECONCILE_ISSUE_HASH_CHANGED = "hash_changed"
13
+ RECONCILE_ISSUE_LEDGER_MISSING = "ledger_missing"
14
+
15
+
16
+ class ReconciliationIssue:
17
+ """A single reconciliation issue — file missing, hash changed, etc."""
18
+
19
+ def __init__(self, task_id: str, path: str, issue_type: str, expected: str = "", actual: str = ""):
20
+ self.task_id = task_id
21
+ self.path = path
22
+ self.issue_type = issue_type
23
+ self.expected = expected
24
+ self.actual = actual
25
+
26
+ def to_dict(self) -> Dict[str, str]:
27
+ return {
28
+ "task_id": self.task_id,
29
+ "path": self.path,
30
+ "issue_type": self.issue_type,
31
+ "expected": self.expected,
32
+ "actual": self.actual,
33
+ }
34
+
35
+ def __repr__(self) -> str:
36
+ return f"[{self.issue_type}] {self.task_id}:{self.path}"
37
+
38
+
39
+ class ReconciliationReport:
40
+ """Full reconciliation result for a goal plan."""
41
+
42
+ def __init__(
43
+ self, goal_id: str, passed: bool, issues: List[ReconciliationIssue], total_tasks: int, checked_tasks: int
44
+ ):
45
+ self.goal_id = goal_id
46
+ self.passed = passed
47
+ self.issues = issues
48
+ self.total_tasks = total_tasks
49
+ self.checked_tasks = checked_tasks
50
+ self.failed_tasks = len(issues)
51
+
52
+ def to_dict(self) -> Dict[str, Any]:
53
+ return {
54
+ "goal_id": self.goal_id,
55
+ "passed": self.passed,
56
+ "total_tasks": self.total_tasks,
57
+ "checked_tasks": self.checked_tasks,
58
+ "failed_tasks": self.failed_tasks,
59
+ "issues": [i.to_dict() for i in self.issues],
60
+ }
61
+
62
+ def __repr__(self) -> str:
63
+ return f"<ReconciliationReport goal={self.goal_id} passed={self.passed} issues={self.failed_tasks}>"
64
+
65
+
66
+ def run_reconciliation(goal_id: str, plan: Plan, workspace_root: str, run_dir: str) -> ReconciliationReport:
67
+ """Compare expected vs actual state for all completed tasks in a plan.
68
+
69
+ Checks:
70
+ 1. Output integrity — every output path from completed contracts exists
71
+ 2. Ledger consistency — every ledger entry's file exists and hash matches
72
+ 3. Ledger completeness — every COMPLETE task has ledger entries
73
+ """
74
+ issues = []
75
+
76
+ completed_count = 0
77
+ for c in plan.contracts:
78
+ task_id = c["task_id"]
79
+ state_file = os.path.join(run_dir, task_id, "state.json")
80
+ if not os.path.isfile(state_file):
81
+ continue
82
+
83
+ from .state import load_state
84
+
85
+ state = load_state(state_file)
86
+ if state.status.upper() not in (
87
+ "COMPLETE",
88
+ "VERIFIED",
89
+ "DEGRADED_PASS",
90
+ "FORCE_COMPLETE",
91
+ ):
92
+ continue
93
+
94
+ contract_file = os.path.join(run_dir, task_id, "contract.json")
95
+ if os.path.isfile(contract_file):
96
+ with open(contract_file, "r", encoding="utf-8") as f:
97
+ contract_dict = json.load(f)
98
+ outputs = contract_dict.get("outputs", [])
99
+ else:
100
+ outputs = []
101
+
102
+ for out in outputs:
103
+ out_path = out.get("path", "") if isinstance(out, dict) else ""
104
+ if not out_path:
105
+ continue
106
+ abs_path = os.path.join(workspace_root, out_path) if not os.path.isabs(out_path) else out_path
107
+ if not os.path.exists(abs_path):
108
+ issues.append(
109
+ ReconciliationIssue(
110
+ task_id=task_id,
111
+ path=out_path,
112
+ issue_type=RECONCILE_ISSUE_OUTPUT_MISSING,
113
+ expected="file_exists",
114
+ actual="not_found",
115
+ )
116
+ )
117
+
118
+ completed_count += 1
119
+
120
+ ledger = ev.load_ledger(run_dir)
121
+ for task_id, entries in ledger.items():
122
+ for e in entries:
123
+ abs_path = e.get("absolute_path", "")
124
+ if not abs_path:
125
+ continue
126
+ if not os.path.exists(abs_path):
127
+ issues.append(
128
+ ReconciliationIssue(
129
+ task_id=task_id,
130
+ path=e.get("relative_path", "?"),
131
+ issue_type=RECONCILE_ISSUE_FILE_MISSING,
132
+ expected="file_exists",
133
+ actual="not_found",
134
+ )
135
+ )
136
+ continue
137
+ stored_hash = e.get("sha256", "")
138
+ if stored_hash:
139
+ current_hash = ev._sha256(abs_path)
140
+ if stored_hash != current_hash:
141
+ issues.append(
142
+ ReconciliationIssue(
143
+ task_id=task_id,
144
+ path=e.get("relative_path", "?"),
145
+ issue_type=RECONCILE_ISSUE_HASH_CHANGED,
146
+ expected=stored_hash,
147
+ actual=current_hash,
148
+ )
149
+ )
150
+
151
+ for c in plan.contracts:
152
+ task_id = c["task_id"]
153
+ state_file = os.path.join(run_dir, task_id, "state.json")
154
+ if os.path.isfile(state_file):
155
+ from .state import load_state
156
+
157
+ state = load_state(state_file)
158
+ if state.status.upper() == "COMPLETE" and task_id not in ledger:
159
+ issues.append(
160
+ ReconciliationIssue(
161
+ task_id=task_id,
162
+ path="",
163
+ issue_type=RECONCILE_ISSUE_LEDGER_MISSING,
164
+ expected="ledger_entries",
165
+ actual="no_entries",
166
+ )
167
+ )
168
+
169
+ passed = len(issues) == 0
170
+ return ReconciliationReport(
171
+ goal_id=goal_id,
172
+ passed=passed,
173
+ issues=issues,
174
+ total_tasks=len(plan.contracts),
175
+ checked_tasks=completed_count,
176
+ )
177
+
178
+
179
+ def format_report(report: ReconciliationReport) -> str:
180
+ """Format a reconciliation report as human-readable string."""
181
+ if report.passed:
182
+ return (
183
+ f"Reconciliation PASSED for {report.goal_id} "
184
+ f"({report.checked_tasks}/{report.total_tasks} tasks checked, no issues)."
185
+ )
186
+ lines = [f"Reconciliation FAILED for {report.goal_id} — {report.failed_tasks} issue(s):"]
187
+ for iss in report.issues:
188
+ lines.append(f" [{iss.issue_type}] {iss.task_id}: {iss.path or '(no path)'}")
189
+ if iss.expected or iss.actual:
190
+ lines.append(f" expected: {iss.expected}, actual: {iss.actual}")
191
+ return "\n".join(lines)
@@ -0,0 +1,433 @@
1
+ """Evidence-aware replanner for dynamic plan adjustment and subtask splitting.
2
+
3
+ Expanded with richer evidence inputs (scope violations, crash info, telemetry),
4
+ better heuristics (scope-narrow, strategy-switch, merge), and explainable
5
+ replan rationale metadata.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ from typing import Any, Dict, List
11
+
12
+ from .contract import load_contract, requires_semantic_qc, validate_contract
13
+ from .failure import (
14
+ FAILURE_CLASS_TASK_CRASHED,
15
+ FAILURE_CLASS_TIMEOUT,
16
+ FAILURE_CLASS_WORKER_EMPTY_OUTPUT,
17
+ FAILURE_CLASS_WORKER_NONZERO_EXIT,
18
+ classify_failure,
19
+ suggest_remediation,
20
+ )
21
+ from .goal import Goal, Plan
22
+ from .models import ModelRegistry
23
+ from .state import load_state
24
+
25
+
26
+ class InspectResults:
27
+ """Inspects run directory artifacts and state for tasks."""
28
+
29
+ def __init__(self, run_dir: str):
30
+ self.run_dir = run_dir
31
+
32
+ def inspect_task(self, task_id: str) -> Dict[str, Any]:
33
+ task_dir = os.path.join(self.run_dir, task_id)
34
+ state_file = os.path.join(task_dir, "state.json")
35
+ contract_file = os.path.join(task_dir, "contract.json")
36
+
37
+ if not os.path.isfile(state_file):
38
+ return {
39
+ "task_id": task_id,
40
+ "status": "missing",
41
+ "attempt": 0,
42
+ "max_attempts": 1,
43
+ "stderr": "",
44
+ "timed_out": False,
45
+ "scope_violations": [],
46
+ "crash_reason": "",
47
+ "failure_class": "",
48
+ }
49
+
50
+ state = load_state(state_file)
51
+ max_attempts = 1
52
+ if os.path.isfile(contract_file):
53
+ contract, _ = load_contract(contract_file)
54
+ if contract:
55
+ max_attempts = contract.worker.get("max_attempts", 1)
56
+
57
+ stderr = ""
58
+ timed_out = False
59
+ if state.worker_results:
60
+ last = state.worker_results[-1]
61
+ stderr = last.get("stderr", "")
62
+ if "timed out" in stderr.lower():
63
+ timed_out = True
64
+
65
+ scope_violations = state.data.get("scope_violations", [])
66
+ crash_reason = state.data.get("crash_reason", "")
67
+ fclass = state.data.get("last_failure_class", "") or classify_failure(state)
68
+
69
+ return {
70
+ "task_id": task_id,
71
+ "status": state.status,
72
+ "attempt": state.attempt,
73
+ "max_attempts": max_attempts,
74
+ "stderr": stderr,
75
+ "timed_out": timed_out,
76
+ "worker_results": state.worker_results,
77
+ "scope_violations": scope_violations,
78
+ "crash_reason": crash_reason,
79
+ "failure_class": fclass,
80
+ }
81
+
82
+
83
+ def _rich_suggest_fix(task_id: str, info: Dict[str, Any]) -> Dict[str, Any]:
84
+ """Analyze rich evidence for task_id and suggest a remediation action with rationale.
85
+
86
+ Returns dict with keys: action, reason, rationale (structured metadata).
87
+ """
88
+ status = info["status"]
89
+ attempt = info["attempt"]
90
+ max_attempts = info["max_attempts"]
91
+ fclass = info["failure_class"]
92
+ rem_attempts = max_attempts - attempt
93
+
94
+ if status in ("COMPLETE", "complete", "VERIFIED", "QC_PASSED"):
95
+ return {
96
+ "action": "none",
97
+ "reason": f"task {task_id} completed successfully",
98
+ "rationale": {"evidence": "status", "trigger": status},
99
+ }
100
+
101
+ if status == "ESCALATED":
102
+ return {
103
+ "action": "split",
104
+ "reason": f"task {task_id} escalated after {attempt} attempts",
105
+ "rationale": {"evidence": "status", "trigger": "ESCALATED", "attempt": attempt},
106
+ }
107
+
108
+ # Scope violation → narrow scope
109
+ if info["scope_violations"]:
110
+ viol_types = [v.get("violation_type", "") for v in info["scope_violations"]]
111
+ return {
112
+ "action": "narrow_scope",
113
+ "reason": f"scope violation(s): {', '.join(viol_types)} — narrowing allowed paths",
114
+ "rationale": {"evidence": "scope_violations", "violations": viol_types},
115
+ }
116
+
117
+ # Crash → retry with more conservative settings
118
+ if fclass == FAILURE_CLASS_TASK_CRASHED:
119
+ if attempt < max_attempts:
120
+ return {
121
+ "action": "retry",
122
+ "reason": f"task crashed ({info['crash_reason']}) — retry ({rem_attempts} left)",
123
+ "rationale": {"evidence": "crash", "crash_reason": info["crash_reason"], "attempt": attempt},
124
+ }
125
+ return {
126
+ "action": "split",
127
+ "reason": f"task crashed {max_attempts} times — splitting into smaller subtasks",
128
+ "rationale": {"evidence": "crash", "crash_reason": info["crash_reason"], "attempts_exhausted": True},
129
+ }
130
+
131
+ # Timeout → retry or split
132
+ if fclass == FAILURE_CLASS_TIMEOUT:
133
+ if attempt < max_attempts:
134
+ return {
135
+ "action": "retry",
136
+ "reason": f"timed out (attempt {attempt}/{max_attempts})",
137
+ "rationale": {"evidence": "timeout", "attempt": attempt},
138
+ }
139
+ return {
140
+ "action": "split",
141
+ "reason": f"timed out after {max_attempts} attempts — splitting",
142
+ "rationale": {"evidence": "timeout", "attempts_exhausted": True},
143
+ }
144
+
145
+ # Worker issues → retry with changed approach
146
+ if fclass in (FAILURE_CLASS_WORKER_NONZERO_EXIT, FAILURE_CLASS_WORKER_EMPTY_OUTPUT):
147
+ if attempt < max_attempts:
148
+ return {
149
+ "action": "retry",
150
+ "reason": f"worker issue ({fclass}) — retry ({rem_attempts} left)",
151
+ "rationale": {"evidence": "worker_result", "failure_class": fclass, "attempt": attempt},
152
+ }
153
+ return {
154
+ "action": "split",
155
+ "reason": f"worker failed after {max_attempts} attempts",
156
+ "rationale": {"evidence": "worker_result", "failure_class": fclass, "attempts_exhausted": True},
157
+ }
158
+
159
+ # Use structured failure classification as fallback
160
+ if status in ("VERIFICATION_FAILED", "BLOCKED", "RETRY_PENDING"):
161
+ rem = suggest_remediation(fclass, attempt, max_attempts)
162
+ rem["rationale"] = {"evidence": "failure_class", "failure_class": fclass}
163
+ return rem
164
+
165
+ return {
166
+ "action": "replan",
167
+ "reason": f"task {task_id} in state {status}",
168
+ "rationale": {"evidence": "status", "trigger": status},
169
+ }
170
+
171
+
172
+ def replan(goal: Goal, results: Dict[str, Any], run_dir: str) -> Plan:
173
+ """Generate a revised Plan based on goal, previous results, and rich evidence inspection.
174
+
175
+ Returns a Plan with a replan_rationale attached for explainability.
176
+ """
177
+ inspector = InspectResults(run_dir)
178
+ all_passed = True
179
+ suggested_actions: Dict[str, Dict[str, Any]] = {}
180
+ replan_evidence: List[Dict[str, Any]] = []
181
+
182
+ for task_id in results:
183
+ info = inspector.inspect_task(task_id)
184
+ if info["status"] not in ("COMPLETE", "complete", "VERIFIED"):
185
+ all_passed = False
186
+ fix = _rich_suggest_fix(task_id, info)
187
+ suggested_actions[task_id] = fix
188
+ replan_evidence.append(
189
+ {
190
+ "task_id": task_id,
191
+ "status": info["status"],
192
+ "action": fix["action"],
193
+ "rationale": fix.get("rationale", {}),
194
+ }
195
+ )
196
+
197
+ if all_passed:
198
+ contracts = [{"task_id": tid, "depends_on": [], "status": "complete"} for tid in results]
199
+ plan = Plan(goal_id=goal.goal_id, contracts=contracts)
200
+ plan.replan_rationale = {
201
+ "trigger": "all_completed",
202
+ "evidence": replan_evidence,
203
+ }
204
+ return plan
205
+
206
+ new_contracts_meta = []
207
+ scope = goal.constraints.get("workspace_scope", {"allow": ["scratch/"], "deny": []})
208
+ workspace_root = os.path.dirname(os.path.dirname(run_dir))
209
+ out_dir = os.path.join(workspace_root, "orchestrator", "fixtures", "generated")
210
+ os.makedirs(out_dir, exist_ok=True)
211
+
212
+ split_rename_map: Dict[str, str] = {}
213
+
214
+ contract_depends_on: Dict[str, List[str]] = {}
215
+ for c in getattr(goal, "contracts", []):
216
+ if isinstance(c, dict):
217
+ tid = c.get("task_id", "")
218
+ deps = c.get("depends_on", [])
219
+ if tid:
220
+ contract_depends_on[tid] = list(deps)
221
+ elif hasattr(c, "task_id"):
222
+ tid = c.task_id
223
+ deps = getattr(c, "depends_on", [])
224
+ if tid:
225
+ contract_depends_on[tid] = list(deps)
226
+
227
+ for task_id, res in results.items():
228
+ fix = suggested_actions.get(task_id, {"action": "none"})
229
+
230
+ if fix["action"] == "split":
231
+ tid_a = f"{task_id}-part-a"
232
+ tid_b = f"{task_id}-part-b"
233
+ out_a = f"scratch/{tid_a}_out.txt"
234
+ out_b = f"scratch/{tid_b}_out.txt"
235
+
236
+ original_depends_on = list(contract_depends_on.get(task_id, []))
237
+ if not original_depends_on:
238
+ orig_contract_path = os.path.join(run_dir, task_id, "contract.json")
239
+ if os.path.isfile(orig_contract_path):
240
+ with open(orig_contract_path, "r", encoding="utf-8") as f:
241
+ orig_contract = json.load(f)
242
+ original_depends_on = list(orig_contract.get("depends_on", []))
243
+
244
+ c_a = {
245
+ "task_id": tid_a,
246
+ "title": f"{task_id} - Part A (Setup)",
247
+ "status": "DRAFTED",
248
+ "risk_tier": "auto",
249
+ "workspace_scope": scope,
250
+ "objective": f"Decomposed subtask part A for {task_id}",
251
+ "worker": {"model": ModelRegistry.WORKER_PREFIXED, "max_attempts": 2},
252
+ "inputs": [],
253
+ "outputs": [{"path": out_a}],
254
+ "acceptance_checks": [
255
+ {"id": f"{tid_a}-cmd", "kind": "command", "command": "python --version", "expected": 0}
256
+ ],
257
+ "qc": {
258
+ "required": requires_semantic_qc("auto", [{"path": out_a}], [{"kind": "command"}]),
259
+ "lens": "code_correctness",
260
+ },
261
+ }
262
+ c_b = {
263
+ "task_id": tid_b,
264
+ "title": f"{task_id} - Part B (Verify)",
265
+ "status": "DRAFTED",
266
+ "risk_tier": "auto",
267
+ "workspace_scope": scope,
268
+ "objective": f"Decomposed subtask part B for {task_id}",
269
+ "worker": {"model": ModelRegistry.WORKER_PREFIXED, "max_attempts": 2},
270
+ "inputs": [{"path": out_a}],
271
+ "outputs": [{"path": out_b}],
272
+ "acceptance_checks": [
273
+ {"id": f"{tid_b}-exists", "kind": "file_exists", "path": out_b, "expected": True}
274
+ ],
275
+ "qc": {
276
+ "required": requires_semantic_qc("auto", [{"path": out_b}], [{"kind": "file_exists"}]),
277
+ "lens": "code_correctness",
278
+ },
279
+ }
280
+
281
+ path_a = os.path.join(out_dir, f"{tid_a}.json")
282
+ path_b = os.path.join(out_dir, f"{tid_b}.json")
283
+
284
+ with open(path_a, "w", encoding="utf-8") as f:
285
+ json.dump(c_a, f, indent=2, ensure_ascii=False)
286
+ with open(path_b, "w", encoding="utf-8") as f:
287
+ json.dump(c_b, f, indent=2, ensure_ascii=False)
288
+
289
+ errs_a = validate_contract(c_a, workspace_root=workspace_root)
290
+ if errs_a:
291
+ raise ValueError(f"Replanned contract {tid_a} failed validation: {errs_a}")
292
+ errs_b = validate_contract(c_b, workspace_root=workspace_root)
293
+ if errs_b:
294
+ raise ValueError(f"Replanned contract {tid_b} failed validation: {errs_b}")
295
+
296
+ # Downstream contracts must depend on BOTH split parts, not only
297
+ # tid_b. Mapping task_id -> [tid_a, tid_b] means a downstream that
298
+ # only needs Part A's outputs is not blocked until Part B finishes.
299
+ split_rename_map[task_id] = [tid_a, tid_b]
300
+
301
+ new_contracts_meta.append(
302
+ {
303
+ "task_id": tid_a,
304
+ "depends_on": list(original_depends_on),
305
+ "status": "DRAFTED",
306
+ "contract": c_a,
307
+ "contract_path": os.path.relpath(path_a, workspace_root),
308
+ }
309
+ )
310
+ new_contracts_meta.append(
311
+ {
312
+ "task_id": tid_b,
313
+ "depends_on": [tid_a],
314
+ "status": "DRAFTED",
315
+ "contract": c_b,
316
+ "contract_path": os.path.relpath(path_b, workspace_root),
317
+ }
318
+ )
319
+
320
+ elif fix["action"] == "narrow_scope":
321
+ viol_paths = [v.get("path", "") for v in info.get("scope_violations", [])]
322
+ narrowed_deny = list(scope.get("deny", []))
323
+ for vp in viol_paths:
324
+ if vp and vp not in narrowed_deny:
325
+ narrowed_deny.append(vp)
326
+ narrowed_contract = {
327
+ "task_id": task_id,
328
+ "title": f"{task_id} (scope-narrowed)",
329
+ "status": "DRAFTED",
330
+ "risk_tier": "auto",
331
+ "workspace_scope": {"allow": scope.get("allow", ["scratch/"]), "deny": narrowed_deny},
332
+ "objective": f"Retry {task_id} with narrowed scope",
333
+ "worker": {"model": ModelRegistry.WORKER_PREFIXED, "max_attempts": 2},
334
+ "inputs": [],
335
+ "outputs": [{"path": f"scratch/{task_id}_narrowed_out.txt"}],
336
+ "acceptance_checks": [
337
+ {
338
+ "id": f"{task_id}-narrow-exists",
339
+ "kind": "file_exists",
340
+ "path": f"scratch/{task_id}_narrowed_out.txt",
341
+ "expected": True,
342
+ }
343
+ ],
344
+ "qc": {
345
+ "required": requires_semantic_qc(
346
+ "auto", [{"path": f"scratch/{task_id}_narrowed_out.txt"}], [{"kind": "file_exists"}]
347
+ ),
348
+ "lens": "code_correctness",
349
+ },
350
+ }
351
+ errs = validate_contract(narrowed_contract, workspace_root=workspace_root)
352
+ if errs:
353
+ raise ValueError(f"Narrowed contract {task_id} failed validation: {errs}")
354
+ new_contracts_meta.append(
355
+ {
356
+ "task_id": task_id,
357
+ "depends_on": [],
358
+ "status": "DRAFTED",
359
+ "contract": narrowed_contract,
360
+ }
361
+ )
362
+
363
+ elif fix["action"] in ("retry", "none"):
364
+ new_contracts_meta.append(
365
+ {
366
+ "task_id": task_id,
367
+ "depends_on": [],
368
+ "status": "DRAFTED",
369
+ }
370
+ )
371
+
372
+ else:
373
+ new_contracts_meta.append(
374
+ {
375
+ "task_id": task_id,
376
+ "depends_on": [],
377
+ "status": "DRAFTED",
378
+ }
379
+ )
380
+
381
+ rewritten_ids = {meta["task_id"] for meta in new_contracts_meta}
382
+
383
+ # Carry forward downstream contracts that were not in results, rewriting
384
+ # any depends_on that referenced a split task to BOTH split parts, so the
385
+ # DAG is not corrupted by dropping them.
386
+ for c in getattr(goal, "contracts", []):
387
+ tid = c.get("task_id", "") if isinstance(c, dict) else getattr(c, "task_id", "")
388
+ deps = c.get("depends_on", []) if isinstance(c, dict) else getattr(c, "depends_on", [])
389
+ if not tid or tid in rewritten_ids:
390
+ continue
391
+ rewritten = []
392
+ for dep in deps:
393
+ replacement = split_rename_map.get(dep)
394
+ if isinstance(replacement, list):
395
+ for part in replacement:
396
+ if part not in rewritten:
397
+ rewritten.append(part)
398
+ else:
399
+ rewritten.append(replacement if replacement is not None else dep)
400
+ new_contracts_meta.append(
401
+ {
402
+ "task_id": tid,
403
+ "depends_on": rewritten,
404
+ "status": "DRAFTED",
405
+ }
406
+ )
407
+
408
+ for meta in new_contracts_meta:
409
+ rewritten = []
410
+ for dep in meta.get("depends_on", []):
411
+ replacement = split_rename_map.get(dep)
412
+ if isinstance(replacement, list):
413
+ # Flatten a split mapping into both parts, keeping order.
414
+ for part in replacement:
415
+ if part not in rewritten:
416
+ rewritten.append(part)
417
+ else:
418
+ rewritten.append(replacement if replacement is not None else dep)
419
+ meta["depends_on"] = rewritten
420
+
421
+ plan = Plan(goal_id=goal.goal_id, contracts=new_contracts_meta)
422
+ plan.replan_rationale = {
423
+ "trigger": "replan_needed",
424
+ "evidence": replan_evidence,
425
+ }
426
+ return plan
427
+
428
+
429
+ def suggest_fix(task_id: str, run_dir: str) -> Dict[str, Any]:
430
+ """Public wrapper — analyzes evidence for a task and returns a remediation suggestion."""
431
+ inspector = InspectResults(run_dir)
432
+ info = inspector.inspect_task(task_id)
433
+ return _rich_suggest_fix(task_id, info)