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,226 @@
1
+ """Failure classification — categorizes contract execution failures for retry routing."""
2
+
3
+ import os
4
+ from typing import Any, Dict, Optional
5
+
6
+ from .contract import Contract
7
+ from .state import State
8
+
9
+ FAILURE_CLASS_TIMEOUT = "timeout"
10
+ FAILURE_CLASS_PREFLIGHT_MISSING_INPUT = "preflight_missing_input"
11
+ FAILURE_CLASS_VERIFIER_OUTPUT_MISSING = "verifier_output_missing"
12
+ FAILURE_CLASS_VERIFIER_CONTENT_MISMATCH = "verifier_content_mismatch"
13
+ FAILURE_CLASS_WORKER_NONZERO_EXIT = "worker_nonzero_exit"
14
+ FAILURE_CLASS_WORKER_EMPTY_OUTPUT = "worker_empty_output"
15
+ FAILURE_CLASS_CONTRACT_INVALID = "contract_invalid"
16
+ FAILURE_CLASS_SCOPE_VIOLATION = "scope_violation"
17
+ FAILURE_CLASS_TASK_CRASHED = "task_crashed" # unexpected exception in supervisor execution
18
+ FAILURE_CLASS_UNKNOWN = "unknown"
19
+
20
+ # Heuristic: same failure class 3 times -> permanent escalation
21
+ MAX_SAME_CLASS_STRIKES = 3
22
+
23
+
24
+ def classify_failure(state: State, contract: Optional[Contract] = None) -> str:
25
+ """Classify a failed task's state into a structured failure category.
26
+
27
+ Inspects state.status, worker_results, and evidence to determine
28
+ the most likely root cause category.
29
+ """
30
+ if state.data.get("scope_violations"):
31
+ return FAILURE_CLASS_SCOPE_VIOLATION
32
+
33
+ if state.status == "PREFLIGHT_FAILED":
34
+ # Read preflight evidence file for missing input files
35
+ preflight_path = state.evidence.get("preflight", "")
36
+ if preflight_path and isinstance(preflight_path, str) and os.path.isfile(preflight_path):
37
+ try:
38
+ import json as _json
39
+
40
+ with open(preflight_path, "r", encoding="utf-8") as f:
41
+ pdata = _json.load(f)
42
+ for r in pdata.get("preflight_checks", []):
43
+ if r.get("kind") == "required_files" and not r.get("passed"):
44
+ return FAILURE_CLASS_PREFLIGHT_MISSING_INPUT
45
+ except (OSError, _json.JSONDecodeError):
46
+ pass
47
+ return FAILURE_CLASS_UNKNOWN
48
+
49
+ if state.status in ("VERIFICATION_FAILED",):
50
+ # Check verification evidence for missing output vs content mismatch
51
+ for ev_key, ev_path in state.evidence.items():
52
+ if isinstance(ev_path, str) and os.path.isfile(ev_path):
53
+ try:
54
+ import json as _json
55
+
56
+ with open(ev_path, "r", encoding="utf-8") as f:
57
+ vdata = _json.load(f)
58
+ for r in vdata.get("verification_results", []):
59
+ if r.get("kind") == "file_exists" and not r.get("passed"):
60
+ return FAILURE_CLASS_VERIFIER_OUTPUT_MISSING
61
+ if r.get("kind") in ("content_exact", "content_regex") and not r.get("passed"):
62
+ return FAILURE_CLASS_VERIFIER_CONTENT_MISMATCH
63
+ except (OSError, _json.JSONDecodeError):
64
+ pass
65
+
66
+ # Check worker results for timeout or nonzero exit
67
+ if state.worker_results:
68
+ last = state.worker_results[-1]
69
+ stderr = last.get("stderr", "")
70
+ if "timed out" in stderr.lower():
71
+ return FAILURE_CLASS_TIMEOUT
72
+ exit_code = last.get("exit_code", 0)
73
+ if exit_code != 0:
74
+ return FAILURE_CLASS_WORKER_NONZERO_EXIT
75
+ stdout = last.get("stdout", "")
76
+ if not stdout or not stdout.strip():
77
+ return FAILURE_CLASS_WORKER_EMPTY_OUTPUT
78
+
79
+ if state.status in ("BLOCKED",):
80
+ return FAILURE_CLASS_PREFLIGHT_MISSING_INPUT
81
+
82
+ return FAILURE_CLASS_UNKNOWN
83
+
84
+
85
+ def suggest_remediation(failure_class: str, attempt: int, max_attempts: int) -> Dict[str, Any]:
86
+ """Suggest remediation action based on failure class and attempt count.
87
+
88
+ Returns dict with keys: action (str), reason (str), requires_new_approach (bool).
89
+
90
+ Actions: retry, split, escalate, wait, replan.
91
+ """
92
+ rem_attempts = max_attempts - attempt
93
+ if failure_class == FAILURE_CLASS_TIMEOUT:
94
+ if attempt < max_attempts:
95
+ return {
96
+ "action": "retry",
97
+ "reason": f"timed out (attempt {attempt}/{max_attempts}, {rem_attempts} attempts remaining)",
98
+ "requires_new_approach": True,
99
+ }
100
+ return {
101
+ "action": "split",
102
+ "reason": f"timed out after {max_attempts} attempts — split into smaller subtasks",
103
+ "requires_new_approach": False,
104
+ }
105
+
106
+ if failure_class in (FAILURE_CLASS_VERIFIER_OUTPUT_MISSING, FAILURE_CLASS_WORKER_EMPTY_OUTPUT):
107
+ if attempt < max_attempts:
108
+ return {
109
+ "action": "retry",
110
+ "reason": f"output missing (attempt {attempt}/{max_attempts}, {rem_attempts} attempts remaining)",
111
+ "requires_new_approach": True,
112
+ }
113
+ return {
114
+ "action": "split",
115
+ "reason": f"output missing after {max_attempts} attempts — split into smaller subtasks",
116
+ "requires_new_approach": False,
117
+ }
118
+
119
+ if failure_class == FAILURE_CLASS_VERIFIER_CONTENT_MISMATCH:
120
+ if attempt < max_attempts:
121
+ return {
122
+ "action": "retry",
123
+ "reason": f"content mismatch (attempt {attempt}/{max_attempts}, {rem_attempts} attempts remaining)",
124
+ "requires_new_approach": True,
125
+ }
126
+ return {
127
+ "action": "split",
128
+ "reason": f"content mismatch after {max_attempts} attempts — split",
129
+ "requires_new_approach": False,
130
+ }
131
+
132
+ if failure_class == FAILURE_CLASS_WORKER_NONZERO_EXIT:
133
+ if attempt < max_attempts:
134
+ return {
135
+ "action": "retry",
136
+ "reason": f"worker nonzero exit (attempt {attempt}/{max_attempts}, {rem_attempts} attempts remaining)",
137
+ "requires_new_approach": True,
138
+ }
139
+ return {
140
+ "action": "split",
141
+ "reason": f"worker failed after {max_attempts} attempts",
142
+ "requires_new_approach": False,
143
+ }
144
+
145
+ if failure_class in (FAILURE_CLASS_PREFLIGHT_MISSING_INPUT, FAILURE_CLASS_CONTRACT_INVALID):
146
+ return {"action": "replan", "reason": "contract/input issue — needs replanning", "requires_new_approach": False}
147
+
148
+ if attempt < max_attempts:
149
+ return {
150
+ "action": "retry",
151
+ "reason": f"unclassified failure (attempt {attempt}/{max_attempts}, {rem_attempts} attempts remaining)",
152
+ "requires_new_approach": True,
153
+ }
154
+
155
+ return {
156
+ "action": "replan",
157
+ "reason": f"unclassified failure after {max_attempts} attempts",
158
+ "requires_new_approach": False,
159
+ }
160
+
161
+
162
+ def count_consecutive_same_class(state: State, failure_class: str) -> int:
163
+ """Count how many consecutive worker results share the same failure class.
164
+
165
+ Used for 3-strike bounding. AUT-015: an unannotated (missing/empty
166
+ failure_class) result is treated as matching the current class so the
167
+ strike counter does not prematurely reset.
168
+ """
169
+ current_class = failure_class or FAILURE_CLASS_UNKNOWN
170
+ count = 0
171
+ for wr in reversed(state.worker_results):
172
+ wr_class = wr.get("failure_class") or current_class
173
+ if wr_class == current_class:
174
+ count += 1
175
+ else:
176
+ break
177
+ return count
178
+
179
+
180
+ def annotate_worker_result(result: Dict[str, Any], failure_class: str) -> Dict[str, Any]:
181
+ """Add failure_class annotation to a worker result dict."""
182
+ result["failure_class"] = failure_class
183
+ return result
184
+
185
+
186
+ FINGERPRINT_FIELDS = {"decomposition", "strategy", "format_strategy", "validation_strategy", "review_strategy"}
187
+
188
+
189
+ def compute_strategy_fingerprint(state: State) -> str:
190
+ """Compute a hash of the approach fingerprints for divergence checking.
191
+
192
+ Uses the last recorded changed_approach if available.
193
+ """
194
+ import hashlib
195
+
196
+ if state.changed_approaches:
197
+ raw = state.changed_approaches[-1]
198
+ else:
199
+ raw = f"default_attempt_{state.attempt}"
200
+ return hashlib.sha256(raw.encode()).hexdigest()[:12]
201
+
202
+
203
+ def is_divergent(state: State, new_approach: str) -> bool:
204
+ """Check if a new approach fingerprint differs from prior non-divergent ones.
205
+
206
+ Returns True (divergent) if the fingerprint is new or if there is no prior
207
+ fingerprint to compare against. Returns False (not divergent) if this
208
+ exact approach has been tried before in the same task.
209
+ """
210
+ import hashlib
211
+
212
+ new_hash = hashlib.sha256(new_approach.encode()).hexdigest()[:12]
213
+ for old_approach in state.changed_approaches[:-1]:
214
+ old_hash = hashlib.sha256(old_approach.encode()).hexdigest()[:12]
215
+ if old_hash == new_hash and old_approach == new_approach:
216
+ return False
217
+ return True
218
+
219
+
220
+ def require_divergent_retry(state: State, new_approach: str) -> bool:
221
+ """Return True if retry can proceed. If not divergent, escalate."""
222
+ if not state.changed_approaches:
223
+ return True
224
+ if is_divergent(state, new_approach):
225
+ return True
226
+ return False
@@ -0,0 +1,126 @@
1
+ """
2
+ orchestrator/fast_sandbox.py
3
+ Zero-Copy Layered Fast Sandbox with Windows Job Object & In-Memory Module Injection.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import subprocess
10
+ import sys
11
+ import time
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Optional
15
+
16
+
17
+ @dataclass
18
+ class FastSandboxResult:
19
+ passed: bool
20
+ tier_reached: int
21
+ execution_time_ms: float
22
+ error_message: Optional[str] = None
23
+
24
+
25
+ class ZeroCopyFastSandbox:
26
+ """Evaluates patched code using in-memory sys.modules overlays without workspace disk mutation."""
27
+
28
+ def __init__(self, workspace_root: Path):
29
+ self.workspace_root = workspace_root
30
+
31
+ def evaluate_in_memory_overlay(
32
+ self,
33
+ target_relative_path: str,
34
+ candidate_code: str,
35
+ test_file_path: Optional[str] = None,
36
+ timeout_sec: int = 15,
37
+ ) -> FastSandboxResult:
38
+ start = time.perf_counter()
39
+
40
+ # Tier 0: In-Memory Syntax Check (<1ms)
41
+ try:
42
+ compile(candidate_code, target_relative_path, "exec")
43
+ except SyntaxError as e:
44
+ return FastSandboxResult(
45
+ passed=False,
46
+ tier_reached=0,
47
+ execution_time_ms=(time.perf_counter() - start) * 1000,
48
+ error_message=f"Tier 0 SyntaxError: {e}",
49
+ )
50
+
51
+ # Tier 1: Subprocess Execution with in-memory sys.modules injection (<150ms)
52
+ escaped_target = target_relative_path.replace("\\", "/")
53
+ escaped_test = (test_file_path or "").replace("\\", "/")
54
+ escaped_root = str(self.workspace_root).replace("\\", "/")
55
+
56
+ clean_rel = target_relative_path.replace("\\", "/")
57
+ if clean_rel.endswith(".py"):
58
+ clean_rel = clean_rel[:-3]
59
+ target_mod_name = clean_rel.replace("/", ".")
60
+
61
+ runner_code = f"""
62
+ import sys
63
+ import os
64
+ import importlib.util
65
+ import importlib.machinery
66
+
67
+ os.environ["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1"
68
+ sys.path.insert(0, r"{escaped_root}")
69
+
70
+ # Pre-inject in-memory candidate into sys.modules
71
+ candidate_src = {repr(candidate_code)}
72
+ target_mod = "{target_mod_name}"
73
+ target_path = r"{escaped_root}/{escaped_target}"
74
+
75
+ try:
76
+ code_obj = compile(candidate_src, target_path, "exec")
77
+ spec = importlib.machinery.ModuleSpec(target_mod, None, origin=target_path)
78
+ module = importlib.util.module_from_spec(spec)
79
+ module.__file__ = target_path
80
+ sys.modules[target_mod] = module
81
+ exec(code_obj, module.__dict__)
82
+ except Exception as e:
83
+ print(f"Pre-injection error: {{e}}", file=sys.stderr)
84
+ sys.exit(2)
85
+
86
+ if "{escaped_test}":
87
+ import pytest
88
+ code = pytest.main(["-q", "-p", "no:benchmark", r"{escaped_root}/{escaped_test}", "-k", "not slow"])
89
+ sys.exit(code)
90
+ else:
91
+ sys.exit(0)
92
+ """
93
+ creationflags = 0
94
+ if sys.platform == "win32":
95
+ creationflags = 0x08000000 # CREATE_NO_WINDOW
96
+
97
+ env = os.environ.copy()
98
+ env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1"
99
+
100
+ try:
101
+ proc = subprocess.run(
102
+ [sys.executable, "-c", runner_code],
103
+ cwd=str(self.workspace_root),
104
+ capture_output=True,
105
+ text=True,
106
+ timeout=timeout_sec,
107
+ creationflags=creationflags,
108
+ env=env,
109
+ )
110
+ elapsed = (time.perf_counter() - start) * 1000
111
+ if proc.returncode == 0:
112
+ return FastSandboxResult(passed=True, tier_reached=1, execution_time_ms=elapsed)
113
+ else:
114
+ return FastSandboxResult(
115
+ passed=False,
116
+ tier_reached=1,
117
+ execution_time_ms=elapsed,
118
+ error_message=proc.stderr[:600] if proc.stderr else proc.stdout[:600],
119
+ )
120
+ except subprocess.TimeoutExpired:
121
+ return FastSandboxResult(
122
+ passed=False,
123
+ tier_reached=1,
124
+ execution_time_ms=(time.perf_counter() - start) * 1000,
125
+ error_message="Sandbox execution timed out.",
126
+ )
@@ -0,0 +1,115 @@
1
+ """
2
+ orchestrator/feasibility_gate.py
3
+ Cognitive Feasibility & Architectural Deliberation Gate.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import re
10
+ from dataclasses import dataclass
11
+
12
+ from orchestrator.llm import call_llm
13
+
14
+
15
+ @dataclass
16
+ class FeasibilityVerdict:
17
+ verdict: str # "FEASIBLE", "IRREDUCIBLE", "DEFER"
18
+ is_approved: bool
19
+ rationale: str
20
+ suggested_strategy: str
21
+ risk_score: float # 0.0 (low risk) to 1.0 (critical risk)
22
+ requires_research: bool
23
+
24
+
25
+ class CognitiveFeasibilityGate:
26
+ """Pre-implementation deliberation gate that reasons on architectural necessity, risk, and feasibility before code mutation."""
27
+
28
+ @classmethod
29
+ def deliberate(
30
+ cls,
31
+ target_symbol: str,
32
+ source_code: str,
33
+ complexity_score: float,
34
+ model_name: str = "cli:agy",
35
+ thinking_budget: int = 2048,
36
+ ) -> FeasibilityVerdict:
37
+ prompt = f"""You are the Principal Systems Architect for LetItLoop.
38
+ Evaluate whether the following Python symbol should undergo self-evolution refactoring.
39
+
40
+ Target Symbol: `{target_symbol}`
41
+ McCabe Complexity Score: {complexity_score:.1f}
42
+
43
+ Source Code Context:
44
+ ```python
45
+ {source_code}
46
+ ```
47
+
48
+ Evaluate:
49
+ 1. Is this logic genuinely reducible / refactorable, or is it already optimal?
50
+ 2. What are the regression risks to callers? (Auth, cryptographic, or core lockfiles should be DEFERRED).
51
+ 3. Does this require external research/patterns (e.g. arXiv algorithms, GitHub reference implementations)?
52
+
53
+ Return ONLY valid JSON matching this schema:
54
+ ```json
55
+ {{
56
+ "verdict": "FEASIBLE" | "IRREDUCIBLE" | "DEFER",
57
+ "rationale": "...",
58
+ "suggested_strategy": "...",
59
+ "risk_score": 0.0-1.0,
60
+ "requires_research": true | false
61
+ }}
62
+ ```
63
+ """
64
+ try:
65
+ raw_resp = call_llm(
66
+ model=model_name,
67
+ prompt=prompt,
68
+ thinking_budget=thinking_budget,
69
+ )
70
+ raw_text = raw_resp["text"] if isinstance(raw_resp, dict) else str(raw_resp)
71
+ return cls._parse_verdict(raw_text)
72
+ except Exception as e:
73
+ return FeasibilityVerdict(
74
+ verdict="DEFER",
75
+ is_approved=False,
76
+ rationale=f"Feasibility deliberation error: {e}",
77
+ suggested_strategy="Defer due to deliberation failure",
78
+ risk_score=1.0,
79
+ requires_research=False,
80
+ )
81
+
82
+ @classmethod
83
+ def _parse_verdict(cls, text: str) -> FeasibilityVerdict:
84
+ # Strip markdown fences if present
85
+ cleaned = text.strip()
86
+ json_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", cleaned, re.DOTALL)
87
+ if json_match:
88
+ cleaned = json_match.group(1)
89
+ else:
90
+ # Try to match raw JSON object
91
+ raw_match = re.search(r"(\{.*\})", cleaned, re.DOTALL)
92
+ if raw_match:
93
+ cleaned = raw_match.group(1)
94
+
95
+ try:
96
+ data = json.loads(cleaned)
97
+ verdict = str(data.get("verdict", "DEFER")).upper()
98
+ is_approved = verdict == "FEASIBLE"
99
+ return FeasibilityVerdict(
100
+ verdict=verdict,
101
+ is_approved=is_approved,
102
+ rationale=str(data.get("rationale", "No rationale provided.")),
103
+ suggested_strategy=str(data.get("suggested_strategy", "None")),
104
+ risk_score=float(data.get("risk_score", 0.5)),
105
+ requires_research=bool(data.get("requires_research", False)),
106
+ )
107
+ except Exception:
108
+ return FeasibilityVerdict(
109
+ verdict="DEFER",
110
+ is_approved=False,
111
+ rationale="Malformed LLM feasibility output; defaulted to fail-closed DEFER.",
112
+ suggested_strategy="Defer",
113
+ risk_score=1.0,
114
+ requires_research=False,
115
+ )