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,162 @@
1
+ """Impossibility theorem — durable artifacts for escalated/failed tasks."""
2
+
3
+ import json
4
+ import os
5
+ from datetime import datetime, timezone
6
+ from typing import Any, Dict
7
+
8
+ from .contract import Contract
9
+ from .state import State
10
+
11
+ IMPOSSIBILITY_DIR = os.path.join("scratch", "impossibility")
12
+
13
+
14
+ def _maybe_stderr_preview(state: State, max_chars: int = 500) -> str:
15
+ if state.worker_results:
16
+ last = state.worker_results[-1]
17
+ return (last.get("stderr", "") or "")[:max_chars]
18
+ return ""
19
+
20
+
21
+ def _maybe_last_stdout(state: State, max_chars: int = 200) -> str:
22
+ if state.worker_results:
23
+ last = state.worker_results[-1]
24
+ return (last.get("stdout", "") or "")[:max_chars]
25
+ return ""
26
+
27
+
28
+ def build_artifact(
29
+ goal_id: str,
30
+ task_id: str,
31
+ contract: Contract,
32
+ state: State,
33
+ failure_class: str = "",
34
+ workspace_root: str = "",
35
+ ) -> Dict[str, Any]:
36
+ """Build a structured impossibility artifact dict for an escalated task."""
37
+
38
+ def _as_dict(c):
39
+ return c if isinstance(c, dict) else c._raw if hasattr(c, "_raw") else {}
40
+
41
+ c = _as_dict(contract)
42
+
43
+ return {
44
+ "artifact_type": "impossibility_theorem",
45
+ "created_at": datetime.now(timezone.utc).isoformat(),
46
+ "goal_id": goal_id,
47
+ "task_id": task_id,
48
+ "title": c.get("title", ""),
49
+ "objective": c.get("objective", ""),
50
+ "failure_class": failure_class or state.data.get("last_failure_class", "unknown"),
51
+ "max_attempts": c.get("worker", {}).get("max_attempts", 1),
52
+ "attempts_made": state.attempt,
53
+ "worker_runs": len(state.worker_results),
54
+ "worker_results": [
55
+ {
56
+ "exit_code": r.get("exit_code"),
57
+ "elapsed_sec": r.get("elapsed_sec"),
58
+ "failure_class": r.get("failure_class", ""),
59
+ "stderr_preview": (r.get("stderr", "") or "")[:300],
60
+ }
61
+ for r in state.worker_results
62
+ ],
63
+ "rejected_approaches": list(state.changed_approaches),
64
+ "events": [{"from": e["from"], "to": e["to"], "reason": e.get("reason", "")} for e in state.events],
65
+ "evidence_paths": dict(state.evidence),
66
+ "last_stderr_preview": _maybe_stderr_preview(state),
67
+ "last_stdout_preview": _maybe_last_stdout(state),
68
+ "recommended_human_action": (
69
+ f"Task {task_id} failed after {state.attempt} attempt(s) "
70
+ f"with failure class '{failure_class or state.data.get('last_failure_class', 'unknown')}'. "
71
+ f"Review artifacts in scratch/impossibility/{goal_id}/{task_id}/ for full context."
72
+ ),
73
+ }
74
+
75
+
76
+ def artifact_dir(goal_id: str, task_id: str) -> str:
77
+ return os.path.join(IMPOSSIBILITY_DIR, goal_id, task_id)
78
+
79
+
80
+ def write_artifact(
81
+ artifact: Dict[str, Any],
82
+ workspace_root: str,
83
+ goal_id: str,
84
+ task_id: str,
85
+ ) -> tuple[str, str]:
86
+ """Write JSON and Markdown impossibility artifacts to disk.
87
+
88
+ Returns (json_path, md_path).
89
+ """
90
+ base_dir = os.path.join(workspace_root, artifact_dir(goal_id, task_id))
91
+ os.makedirs(base_dir, exist_ok=True)
92
+
93
+ json_path = os.path.join(base_dir, "impossibility.json")
94
+ with open(json_path, "w", encoding="utf-8") as f:
95
+ json.dump(artifact, f, indent=2, ensure_ascii=False)
96
+
97
+ md_lines = [
98
+ f"# Impossibility Theorem: {artifact['task_id']}",
99
+ "",
100
+ f"**Goal:** {artifact['goal_id']}",
101
+ f"**Task:** {artifact['task_id']}",
102
+ f"**Title:** {artifact['title']}",
103
+ f"**Objective:** {artifact['objective']}",
104
+ f"**Failure Class:** {artifact['failure_class']}",
105
+ f"**Max Attempts:** {artifact['max_attempts']}",
106
+ f"**Attempts Made:** {artifact['attempts_made']}",
107
+ f"**Created:** {artifact['created_at']}",
108
+ "",
109
+ "## Failure History",
110
+ ]
111
+ for wr in artifact["worker_results"]:
112
+ md_lines.append("")
113
+ md_lines.append(f"- Exit code: {wr.get('exit_code')}")
114
+ md_lines.append(f"- Elapsed: {wr.get('elapsed_sec', '?')}s")
115
+ md_lines.append(f"- Failure class: {wr.get('failure_class', '?')}")
116
+ stderr = (wr.get("stderr_preview", "") or "")[:200]
117
+ if stderr:
118
+ md_lines.append(f"- Stderr: `{stderr}`")
119
+
120
+ if artifact.get("rejected_approaches"):
121
+ md_lines.append("")
122
+ md_lines.append("## Rejected Approaches")
123
+ for a in artifact["rejected_approaches"]:
124
+ md_lines.append(f"- {a}")
125
+
126
+ md_lines.append("")
127
+ md_lines.append("## Evidence Files")
128
+ for key, path in artifact.get("evidence_paths", {}).items():
129
+ md_lines.append(f"- {key}: `{path}`")
130
+
131
+ md_lines.append("")
132
+ md_lines.append("## Recommended Human Action")
133
+ md_lines.append("")
134
+ md_lines.append(artifact.get("recommended_human_action", "Review and decide next steps."))
135
+
136
+ md_path = os.path.join(base_dir, "impossibility.md")
137
+ with open(md_path, "w", encoding="utf-8") as f:
138
+ f.write("\n".join(md_lines))
139
+
140
+ return json_path, md_path
141
+
142
+
143
+ def write_impossibility(
144
+ contract: Contract,
145
+ state: State,
146
+ goal_id: str,
147
+ workspace_root: str,
148
+ failure_class: str = "",
149
+ ) -> tuple[str, str]:
150
+ """Convenience: build + write artifact in one call.
151
+
152
+ Returns (json_path, md_path).
153
+ """
154
+ artifact = build_artifact(
155
+ goal_id=goal_id,
156
+ task_id=contract.task_id,
157
+ contract=contract,
158
+ state=state,
159
+ failure_class=failure_class,
160
+ workspace_root=workspace_root,
161
+ )
162
+ return write_artifact(artifact, workspace_root, goal_id, contract.task_id)
orchestrator/limits.py ADDED
@@ -0,0 +1,60 @@
1
+ """Resource limit enforcement — wall-clock, output size, attempt caps."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict
5
+
6
+
7
+ @dataclass
8
+ class ResourceLimits:
9
+ max_wall_clock_sec: int = 600
10
+ max_output_size_bytes: int = 524288
11
+ max_attempts_global: int = 10
12
+ max_iterations: int = 20
13
+
14
+
15
+ DEFAULT_LIMITS = ResourceLimits()
16
+
17
+
18
+ def check_limits(
19
+ limits: ResourceLimits,
20
+ elapsed_sec: float,
21
+ output_size: int = 0,
22
+ attempts: int = 0,
23
+ iterations: int = 0,
24
+ ) -> Dict[str, Any]:
25
+ """Check if any resource limit is exceeded.
26
+
27
+ Returns {"exceeded": False} or {"exceeded": True, "reason": str, "limit_type": str}.
28
+ """
29
+ if elapsed_sec > limits.max_wall_clock_sec:
30
+ return {
31
+ "exceeded": True,
32
+ "reason": f"wall clock {elapsed_sec:.0f}s exceeds limit of {limits.max_wall_clock_sec}s",
33
+ "limit_type": "wall_clock",
34
+ }
35
+ if output_size > limits.max_output_size_bytes:
36
+ return {
37
+ "exceeded": True,
38
+ "reason": f"output size {output_size} bytes exceeds limit of {limits.max_output_size_bytes}",
39
+ "limit_type": "output_size",
40
+ }
41
+ if attempts > limits.max_attempts_global:
42
+ return {
43
+ "exceeded": True,
44
+ "reason": f"attempts {attempts} exceeds global limit of {limits.max_attempts_global}",
45
+ "limit_type": "attempts",
46
+ }
47
+ if iterations > limits.max_iterations:
48
+ return {
49
+ "exceeded": True,
50
+ "reason": f"iterations {iterations} exceeds limit of {limits.max_iterations}",
51
+ "limit_type": "iterations",
52
+ }
53
+ return {"exceeded": False}
54
+
55
+
56
+ def format_violation(result: Dict[str, Any]) -> str:
57
+ """Format a check_limits result for human consumption."""
58
+ if not result.get("exceeded"):
59
+ return ""
60
+ return f"[LIMIT] {result['reason']} ({result['limit_type']})"
@@ -0,0 +1,247 @@
1
+ """
2
+ orchestrator/live_evolution_engine.py
3
+ Unified Sensory, Cognitive Feasibility & Surgical Self-Evolution Engine.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ from orchestrator.anti_ouroboros import AntiOuroborosGate
12
+ from orchestrator.ast_splicer import ASTInvariantValidator
13
+ from orchestrator.codebase_introspector import (
14
+ NormalizedExplorationEngine,
15
+ )
16
+ from orchestrator.elasticity_governor import DynamicElasticityGovernor
17
+ from orchestrator.fast_sandbox import ZeroCopyFastSandbox
18
+ from orchestrator.feasibility_gate import CognitiveFeasibilityGate, FeasibilityVerdict
19
+ from orchestrator.llm import call_llm
20
+ from orchestrator.micro_epoch import MicroEpochManager
21
+ from orchestrator.patch_applier import PatchApplier
22
+ from orchestrator.proposal_ledger import ProposalLedger
23
+ from orchestrator.research import AdaptiveResearchCoordinator
24
+ from orchestrator.surgical_extractor import SurgicalContextExtractor
25
+
26
+
27
+ class LiveEvolutionEngine:
28
+ """Executes closed-loop self-evolution with cognitive feasibility deliberation, adaptive research, and 5-pillar verification."""
29
+
30
+ def __init__(
31
+ self,
32
+ workspace_root: Path,
33
+ model_name: str = "cli:agy",
34
+ enable_research: bool = True,
35
+ ):
36
+ self.workspace_root = Path(workspace_root)
37
+ self.model_name = model_name
38
+ self.enable_research = enable_research
39
+ self.sandbox = ZeroCopyFastSandbox(self.workspace_root)
40
+ self.epoch_mgr = MicroEpochManager(self.workspace_root / "scratch/evolution_state")
41
+ self.introspector = NormalizedExplorationEngine()
42
+ self.researcher = AdaptiveResearchCoordinator()
43
+ self.proposal_ledger = ProposalLedger(self.workspace_root)
44
+
45
+ def execute_live_optimization_cycle(
46
+ self,
47
+ module_path: str,
48
+ optimization_goal: str,
49
+ target_function: Optional[str] = None,
50
+ test_file_path: Optional[str] = None,
51
+ force_approved: bool = False,
52
+ ) -> Dict[str, Any]:
53
+ full_path = self.workspace_root / module_path
54
+ if not full_path.exists():
55
+ return {
56
+ "is_success": False,
57
+ "status": "MODULE_NOT_FOUND",
58
+ "violations": [f"File {module_path} not found."],
59
+ }
60
+
61
+ existing_code = full_path.read_text(encoding="utf-8")
62
+
63
+ # 1. Surgical Neighborhood Context Extraction
64
+ extractor = SurgicalContextExtractor(self.workspace_root)
65
+ if target_function:
66
+ try:
67
+ ctx = extractor.extract(module_path, target_function)
68
+ context_snippet = ctx.target_node_source
69
+ enclosing_class_context = (
70
+ f"\nEnclosing Class: {ctx.enclosing_class}\nAttributes: {ctx.class_attributes}"
71
+ if ctx.enclosing_class
72
+ else ""
73
+ )
74
+ except Exception:
75
+ context_snippet = existing_code
76
+ enclosing_class_context = ""
77
+ else:
78
+ context_snippet = existing_code
79
+ enclosing_class_context = ""
80
+
81
+ # 2. Dynamic Elasticity Allocation
82
+ complexity_score = DynamicElasticityGovernor.calculate_complexity(context_snippet)
83
+ budget = DynamicElasticityGovernor.allocate(complexity_score)
84
+
85
+ # 3. Phase 1: Cognitive Feasibility Deliberation Gate (Reason First!)
86
+ if not force_approved:
87
+ feasibility = CognitiveFeasibilityGate.deliberate(
88
+ target_symbol=target_function or module_path,
89
+ source_code=context_snippet,
90
+ complexity_score=complexity_score,
91
+ model_name=self.model_name,
92
+ thinking_budget=budget.thinking_tokens,
93
+ )
94
+ else:
95
+ feasibility = FeasibilityVerdict(
96
+ verdict="APPROVED_BY_HUMAN",
97
+ is_approved=True,
98
+ rationale="User explicitly approved execution of staged architectural proposal.",
99
+ suggested_strategy=f"Execute approved refactor for {target_function or module_path}",
100
+ risk_score=0.10,
101
+ requires_research=self.enable_research,
102
+ )
103
+
104
+ if not feasibility.is_approved:
105
+ # Gather research before staging so the proposal artifact contains external intelligence
106
+ findings = []
107
+ if self.enable_research:
108
+ try:
109
+ findings = self.researcher.research(
110
+ f"python {target_function or module_path} {feasibility.suggested_strategy}"
111
+ )
112
+ except Exception:
113
+ findings = []
114
+
115
+ # Stage architectural proposal in persistent ledger
116
+ proposal = self.proposal_ledger.record_proposal(
117
+ target_module=module_path,
118
+ target_function=target_function or "module_level",
119
+ complexity_score=complexity_score,
120
+ deliberation_verdict=feasibility.verdict,
121
+ risk_score=feasibility.risk_score,
122
+ rationale=feasibility.rationale,
123
+ suggested_strategy=feasibility.suggested_strategy,
124
+ research_findings=findings,
125
+ proposed_approach=f"Refactor {target_function or module_path}: {feasibility.suggested_strategy}",
126
+ )
127
+
128
+ diff_summary = f"Staged Proposal {proposal.proposal_id} for {target_function or module_path}: verdict={feasibility.verdict}, risk={feasibility.risk_score:.2f}."
129
+ self.epoch_mgr.record_task_completion(
130
+ task_id=f"{module_path}:{target_function}",
131
+ diff_summary=diff_summary,
132
+ )
133
+ return {
134
+ "is_success": False,
135
+ "status": "PROPOSAL_STAGED_FOR_REVIEW",
136
+ "verdict": feasibility.verdict,
137
+ "rationale": feasibility.rationale,
138
+ "risk_score": feasibility.risk_score,
139
+ "proposal_id": proposal.proposal_id,
140
+ "proposal_markdown": str(
141
+ self.workspace_root / "scratch/evolution_state/proposals" / f"{proposal.proposal_id}.md"
142
+ ),
143
+ }
144
+
145
+ # 4. Optional Adaptive Research Hook
146
+ research_context = ""
147
+ findings_count = 0
148
+ if self.enable_research and feasibility.requires_research:
149
+ findings = self.researcher.research(
150
+ f"python {target_function or module_path} {feasibility.suggested_strategy}"
151
+ )
152
+ findings_count = len(findings)
153
+ if findings:
154
+ research_context = "\nExternal Architectural Intelligence / Prior Art:\n"
155
+ for f in findings:
156
+ research_context += f"• [{f.provider_name}] {f.title}: {f.summary}\n"
157
+
158
+ # 5. Prompt Synthesis (Requesting Aider Search/Replace Delta)
159
+ prompt = f"""You are the Lead Systems Engineer for LetItLoop.
160
+ Synthesize an optimized Python implementation for `{target_function or module_path}`.
161
+ Goal: {optimization_goal}
162
+ Strategy: {feasibility.suggested_strategy}
163
+ McCabe Complexity Target: <= 10
164
+
165
+ Surgical Context:
166
+ ```python
167
+ {context_snippet}
168
+ ```
169
+ {enclosing_class_context}
170
+ {research_context}
171
+
172
+ Return ONLY an exact Search/Replace block matching this schema:
173
+ <<<<<<< SEARCH
174
+ [exact lines to replace]
175
+ =======
176
+ [optimized replacement lines]
177
+ >>>>>>> REPLACE
178
+ """
179
+
180
+ # 6. LLM Generation & 3-Turn Repair Loop
181
+ violations: List[str] = []
182
+
183
+ for attempt in range(1, 4):
184
+ try:
185
+ raw_response = call_llm(
186
+ model=self.model_name,
187
+ prompt=prompt,
188
+ thinking_budget=budget.thinking_tokens,
189
+ )
190
+ raw_text = raw_response["text"] if isinstance(raw_response, dict) else str(raw_response)
191
+ patch_res = PatchApplier.apply_patch(existing_code, raw_text, fuzzy_whitespace=True)
192
+ if not patch_res.success:
193
+ violations = [patch_res.error_message or "Search block not found."]
194
+ continue
195
+
196
+ candidate_code = patch_res.modified_content
197
+
198
+ # 5-Pillar Verification Firewall
199
+ # 6a. AST Invariant Validation
200
+ if target_function:
201
+ inv_res = ASTInvariantValidator.validate(existing_code, candidate_code, target_function)
202
+ if not inv_res.valid:
203
+ violations = inv_res.violations
204
+ continue
205
+
206
+ # 6b. Anti-Ouroboros Gate
207
+ ouro_res = AntiOuroborosGate.evaluate_mutation(existing_code, candidate_code)
208
+ if not ouro_res.is_approved:
209
+ violations = [f"Anti-Ouroboros rejection: {ouro_res.reason}"]
210
+ continue
211
+
212
+ # 6c. Zero-Copy Fast Sandbox (In-Memory Overlay)
213
+ sandbox_res = self.sandbox.evaluate_in_memory_overlay(
214
+ target_relative_path=module_path,
215
+ candidate_code=candidate_code,
216
+ test_file_path=test_file_path,
217
+ timeout_sec=budget.timeout_sec,
218
+ )
219
+ if not sandbox_res.passed:
220
+ violations = [sandbox_res.error_message or "Sandbox evaluation failed."]
221
+ continue
222
+
223
+ # Verified Fix -> Physical Disk Write-Back
224
+ full_path.write_text(candidate_code, encoding="utf-8")
225
+ diff_summary = f"Mutated {target_function or module_path} (Attempt {attempt}): {patch_res.chunks_applied} chunks applied."
226
+ self.epoch_mgr.record_task_completion(
227
+ task_id=f"{module_path}:{target_function}",
228
+ diff_summary=diff_summary,
229
+ )
230
+
231
+ return {
232
+ "is_success": True,
233
+ "status": "VERIFIED_FIX",
234
+ "attempts_used": attempt,
235
+ "diff_summary": diff_summary,
236
+ "complexity_score": complexity_score,
237
+ "thinking_tokens_used": budget.thinking_tokens,
238
+ "research_findings_count": findings_count,
239
+ }
240
+ except Exception as e:
241
+ violations = [str(e)]
242
+
243
+ return {
244
+ "is_success": False,
245
+ "status": "ATTEMPTS_EXHAUSTED",
246
+ "violations": violations,
247
+ }