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,166 @@
1
+ import importlib.util
2
+ import os
3
+ import platform
4
+ import shutil
5
+ import sys
6
+ import urllib.error
7
+ import urllib.request
8
+ from typing import Optional
9
+
10
+ from .config import DEFAULT_RUN_DIR
11
+
12
+
13
+ def print_status(ok: bool, msg: str, is_warning: bool = False) -> None:
14
+ if ok:
15
+ print(f"[\033[92m+\033[0m] {msg}")
16
+ elif is_warning:
17
+ print(f"[\033[93m!\033[0m] {msg}")
18
+ else:
19
+ print(f"[\033[91mx\033[0m] {msg}")
20
+
21
+
22
+ def _probe_endpoint(url: str, timeout: float = 1.5) -> bool:
23
+ """Lightweight reachability probe. Returns True if the endpoint responds or rejects auth (HTTP 200/401/403)."""
24
+ if not (url.startswith("https://") or url.startswith("http://")):
25
+ return False
26
+ try:
27
+ req = urllib.request.Request(
28
+ url,
29
+ headers={"User-Agent": "letitloop-doctor/0.1.0"},
30
+ method="GET",
31
+ )
32
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310
33
+ return resp.status in (200, 204)
34
+ except urllib.error.HTTPError as e:
35
+ # HTTP 400, 401, 403, 404, 405 indicate the host is alive and responding
36
+ return e.code in (200, 400, 401, 403, 404, 405)
37
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError):
38
+ return False
39
+
40
+
41
+ def _has_module(name: str) -> bool:
42
+ """Safely check if a module is available without raising on missing namespace roots."""
43
+ try:
44
+ return importlib.util.find_spec(name) is not None
45
+ except (ModuleNotFoundError, ValueError, AttributeError, ImportError):
46
+ return False
47
+
48
+
49
+ def run_env_doctor(run_dir: Optional[str] = None, check_connectivity: bool = False) -> int:
50
+ fatal = False
51
+
52
+ # 1. Python & Runtime
53
+ py_version = sys.version_info
54
+ py_ok = py_version >= (3, 11)
55
+ py_msg = f"Python {platform.python_version()} "
56
+ if py_ok:
57
+ print_status(True, py_msg + "(OK)")
58
+ else:
59
+ print_status(False, py_msg + "(Requires >= 3.11)")
60
+ fatal = True
61
+
62
+ # Check optional packages aligned with pyproject.toml extras
63
+ has_pytest = _has_module("pytest")
64
+ has_ruff = shutil.which("ruff") is not None or _has_module("ruff")
65
+ has_bandit = _has_module("bandit")
66
+ has_openai = _has_module("openai")
67
+ has_anthropic = _has_module("anthropic")
68
+ has_google = _has_module("google.genai") or _has_module("google.generativeai")
69
+
70
+ installed_extras = []
71
+ if has_pytest and has_ruff:
72
+ installed_extras.append("dev")
73
+ if has_bandit:
74
+ installed_extras.append("security")
75
+ if has_openai:
76
+ installed_extras.append("openai")
77
+ if has_anthropic:
78
+ installed_extras.append("anthropic")
79
+ if has_google:
80
+ installed_extras.append("google")
81
+
82
+ if installed_extras:
83
+ print_status(True, f"Installed Extras: {', '.join(installed_extras)} (OK)")
84
+ else:
85
+ print_status(
86
+ False,
87
+ "Installed Extras: None detected (e.g. pip install -e '.[dev,security,all-providers]')",
88
+ is_warning=True,
89
+ )
90
+
91
+ # 2. Storage
92
+ target_run_dir = run_dir or os.environ.get("LIL_RUN_DIR", DEFAULT_RUN_DIR)
93
+ try:
94
+ os.makedirs(target_run_dir, exist_ok=True)
95
+ is_writable = os.access(target_run_dir, os.W_OK)
96
+ except OSError:
97
+ is_writable = False
98
+
99
+ if is_writable:
100
+ try:
101
+ total, used, free = shutil.disk_usage(target_run_dir)
102
+ free_gb = free // (2**30)
103
+ print_status(True, f"Storage: {target_run_dir} (Writable, {free_gb} GB free)")
104
+ except OSError:
105
+ print_status(True, f"Storage: {target_run_dir} (Writable)")
106
+ else:
107
+ print_status(False, f"Storage: {target_run_dir} (Not writable)")
108
+ fatal = True
109
+
110
+ # 3. Worker Adapter Tooling
111
+ clis = ["claude", "agy", "opencode", "hermes", "cline", "aider", "docker"]
112
+ print("[!] Agent CLIs:")
113
+ for cli in clis:
114
+ path = shutil.which(cli)
115
+ if path:
116
+ print(f" \033[92m+\033[0m {cli} ({path})")
117
+ else:
118
+ desc = "container sandbox disabled" if cli == "docker" else "optional"
119
+ print(f" \033[91mx\033[0m {cli} (not found - {desc})")
120
+
121
+ # 4. LLM API Keys & Connectivity
122
+ probe_targets = {
123
+ "OPENAI_API_KEY": "https://api.openai.com/v1/models",
124
+ "ANTHROPIC_API_KEY": "https://api.anthropic.com/v1/models",
125
+ "GEMINI_API_KEY": "https://generativelanguage.googleapis.com/v1beta/models",
126
+ "DEEPSEEK_API_KEY": "https://api.deepseek.com/v1/models",
127
+ "LLM_BASE_URL": None,
128
+ }
129
+
130
+ configured = []
131
+ for k, url in probe_targets.items():
132
+ if os.environ.get(k):
133
+ if check_connectivity and url:
134
+ reachable = _probe_endpoint(url)
135
+ status_str = "reachable" if reachable else "unreachable / offline"
136
+ configured.append(f"{k} (configured, {status_str})")
137
+ else:
138
+ configured.append(f"{k} (configured)")
139
+
140
+ if configured:
141
+ print_status(True, f"Providers: {', '.join(configured)}")
142
+ else:
143
+ print_status(
144
+ False,
145
+ "Providers: No API keys configured in environment (e.g., OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY)",
146
+ is_warning=True,
147
+ )
148
+
149
+ # 5. Architecture & Living ADR Registry
150
+ adr_dir = os.path.join(os.getcwd(), "docs", "adr")
151
+ if os.path.isdir(adr_dir):
152
+ adrs = [f for f in os.listdir(adr_dir) if f.endswith(".md") and f not in ("README.md", "template.md")]
153
+ print_status(True, f"Architecture Decisions: {len(adrs)} living ADRs found in docs/adr/ (OK)")
154
+ else:
155
+ print_status(
156
+ True,
157
+ "Architecture Decisions: docs/adr/ not present in current workspace (optional)",
158
+ is_warning=True,
159
+ )
160
+
161
+ if fatal:
162
+ print("\nPrerequisites failed. Please fix the errors above.")
163
+ return 1
164
+
165
+ print('\nEverything is ready! Run `lil propose "Your Goal"` to start.')
166
+ return 0
orchestrator/errors.py ADDED
@@ -0,0 +1,211 @@
1
+ """Structured error schema — typed error codes with severity, component, and context."""
2
+
3
+ import os
4
+ from datetime import datetime, timezone
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from .failure import classify_failure
8
+ from .state import State, load_state
9
+
10
+ # Error severity levels
11
+ SEVERITY_ERROR = "error"
12
+ SEVERITY_WARNING = "warning"
13
+ SEVERITY_CRITICAL = "critical"
14
+
15
+ # Error components
16
+ COMPONENT_CONTRACT = "contract"
17
+ COMPONENT_STATE = "state"
18
+ COMPONENT_PREFLIGHT = "preflight"
19
+ COMPONENT_WORKER = "worker"
20
+ COMPONENT_VERIFIER = "verifier"
21
+ COMPONENT_PLANNER = "planner"
22
+ COMPONENT_SUPERVISOR = "supervisor"
23
+ COMPONENT_LOCK = "lock"
24
+ COMPONENT_SCOPE = "scope"
25
+ COMPONENT_RECONCILE = "reconcile"
26
+
27
+ # Error codes
28
+ E_CONTRACT_INVALID = "E001"
29
+ E_CONTRACT_MISSING_FIELD = "E002"
30
+ E_ILLEGAL_TRANSITION = "E003"
31
+ E_PREFLIGHT_FAILED = "E004"
32
+ E_WORKER_NONZERO_EXIT = "E005"
33
+ E_WORKER_TIMEOUT = "E006"
34
+ E_WORKER_EMPTY_OUTPUT = "E007"
35
+ E_VERIFIER_OUTPUT_MISSING = "E008"
36
+ E_VERIFIER_CONTENT_MISMATCH = "E009"
37
+ E_SCOPE_VIOLATION = "E010"
38
+ E_RECONCILE_TAMPER = "E011"
39
+ E_RECONCILE_MISSING = "E012"
40
+ E_LOCK_HELD = "E013"
41
+ E_LOCK_STALE = "E014"
42
+ E_PLANNER_FAILED = "E015"
43
+ E_UNKNOWN = "E999"
44
+
45
+
46
+ ERROR_META: Dict[str, Dict[str, str]] = {
47
+ E_CONTRACT_INVALID: {"title": "Contract Invalid", "severity": SEVERITY_ERROR, "component": COMPONENT_CONTRACT},
48
+ E_CONTRACT_MISSING_FIELD: {
49
+ "title": "Missing Contract Field",
50
+ "severity": SEVERITY_ERROR,
51
+ "component": COMPONENT_CONTRACT,
52
+ },
53
+ E_ILLEGAL_TRANSITION: {
54
+ "title": "Illegal State Transition",
55
+ "severity": SEVERITY_ERROR,
56
+ "component": COMPONENT_STATE,
57
+ },
58
+ E_PREFLIGHT_FAILED: {"title": "Preflight Failed", "severity": SEVERITY_ERROR, "component": COMPONENT_PREFLIGHT},
59
+ E_WORKER_NONZERO_EXIT: {"title": "Worker Non-Zero Exit", "severity": SEVERITY_ERROR, "component": COMPONENT_WORKER},
60
+ E_WORKER_TIMEOUT: {"title": "Worker Timeout", "severity": SEVERITY_CRITICAL, "component": COMPONENT_WORKER},
61
+ E_WORKER_EMPTY_OUTPUT: {"title": "Worker Empty Output", "severity": SEVERITY_ERROR, "component": COMPONENT_WORKER},
62
+ E_VERIFIER_OUTPUT_MISSING: {
63
+ "title": "Verifier Output Missing",
64
+ "severity": SEVERITY_ERROR,
65
+ "component": COMPONENT_VERIFIER,
66
+ },
67
+ E_VERIFIER_CONTENT_MISMATCH: {
68
+ "title": "Verifier Content Mismatch",
69
+ "severity": SEVERITY_ERROR,
70
+ "component": COMPONENT_VERIFIER,
71
+ },
72
+ E_SCOPE_VIOLATION: {"title": "Scope Violation", "severity": SEVERITY_CRITICAL, "component": COMPONENT_SCOPE},
73
+ E_RECONCILE_TAMPER: {
74
+ "title": "Reconcile Hash Changed",
75
+ "severity": SEVERITY_CRITICAL,
76
+ "component": COMPONENT_RECONCILE,
77
+ },
78
+ E_RECONCILE_MISSING: {
79
+ "title": "Reconcile Missing Output",
80
+ "severity": SEVERITY_ERROR,
81
+ "component": COMPONENT_RECONCILE,
82
+ },
83
+ E_LOCK_HELD: {"title": "Lock Held", "severity": SEVERITY_ERROR, "component": COMPONENT_LOCK},
84
+ E_LOCK_STALE: {"title": "Lock Stale", "severity": SEVERITY_WARNING, "component": COMPONENT_LOCK},
85
+ E_PLANNER_FAILED: {"title": "Planner Failed", "severity": SEVERITY_ERROR, "component": COMPONENT_PLANNER},
86
+ E_UNKNOWN: {"title": "Unknown Error", "severity": SEVERITY_ERROR, "component": COMPONENT_SUPERVISOR},
87
+ }
88
+
89
+
90
+ FAILURE_CLASS_TO_CODE: Dict[str, str] = {
91
+ "timeout": E_WORKER_TIMEOUT,
92
+ "preflight_missing_input": E_PREFLIGHT_FAILED,
93
+ "verifier_output_missing": E_VERIFIER_OUTPUT_MISSING,
94
+ "verifier_content_mismatch": E_VERIFIER_CONTENT_MISMATCH,
95
+ "worker_nonzero_exit": E_WORKER_NONZERO_EXIT,
96
+ "worker_empty_output": E_WORKER_EMPTY_OUTPUT,
97
+ "contract_invalid": E_CONTRACT_INVALID,
98
+ "scope_violation": E_SCOPE_VIOLATION,
99
+ "unknown": E_UNKNOWN,
100
+ }
101
+
102
+
103
+ class StructuredError:
104
+ """A structured error with code, severity, component, and context."""
105
+
106
+ def __init__(
107
+ self,
108
+ code: str,
109
+ message: str,
110
+ task_id: str = "",
111
+ context: Optional[Dict[str, Any]] = None,
112
+ ):
113
+ self.code = code
114
+ self.message = message
115
+ self.task_id = task_id
116
+ self.context = context or {}
117
+ self.timestamp = datetime.now(timezone.utc).isoformat()
118
+
119
+ meta = ERROR_META.get(code, ERROR_META[E_UNKNOWN])
120
+ self.title = meta["title"]
121
+ self.severity = meta["severity"]
122
+ self.component = meta["component"]
123
+
124
+ def to_dict(self) -> Dict[str, Any]:
125
+ return {
126
+ "code": self.code,
127
+ "title": self.title,
128
+ "message": self.message,
129
+ "severity": self.severity,
130
+ "component": self.component,
131
+ "task_id": self.task_id,
132
+ "timestamp": self.timestamp,
133
+ "context": dict(self.context),
134
+ }
135
+
136
+ def __repr__(self) -> str:
137
+ return f"[{self.code}] {self.severity.upper()} {self.component}: {self.message}"
138
+
139
+
140
+ def from_failure_class(
141
+ failure_class: str, task_id: str = "", message: str = "", context: Optional[Dict] = None
142
+ ) -> StructuredError:
143
+ """Create a StructuredError from a failure class string."""
144
+ code = FAILURE_CLASS_TO_CODE.get(failure_class, E_UNKNOWN)
145
+ msg = message or ERROR_META.get(code, ERROR_META[E_UNKNOWN])["title"]
146
+ return StructuredError(code=code, message=msg, task_id=task_id, context=context)
147
+
148
+
149
+ def from_state(state: State, task_id: str, workspace_root: str = "") -> Optional[StructuredError]:
150
+ """Create a StructuredError from a task's state and workspace, if errored."""
151
+
152
+ is_error = state.status in (
153
+ "PREFLIGHT_FAILED",
154
+ "BLOCKED",
155
+ "VERIFICATION_FAILED",
156
+ "ESCALATED",
157
+ "RETRY_PENDING",
158
+ )
159
+ if not is_error:
160
+ return None
161
+
162
+ fclass = classify_failure(state)
163
+ if not fclass or fclass == "unknown":
164
+ if state.status == "ESCALATED":
165
+ return StructuredError(
166
+ code=E_UNKNOWN,
167
+ message=f"Task escalated after {state.attempt} attempts",
168
+ task_id=task_id,
169
+ context={"attempt": state.attempt, "worker_runs": len(state.worker_results)},
170
+ )
171
+ return StructuredError(
172
+ code=E_UNKNOWN,
173
+ message=f"Unknown failure (status: {state.status})",
174
+ task_id=task_id,
175
+ context={"status": state.status},
176
+ )
177
+
178
+ err = from_failure_class(fclass, task_id=task_id)
179
+ err.context["status"] = state.status
180
+ err.context["attempt"] = state.attempt
181
+ err.context["worker_runs"] = len(state.worker_results)
182
+ return err
183
+
184
+
185
+ def inspect_goal(goal_id: str, plan, workspace_root: str, run_dir: str) -> List[StructuredError]:
186
+ """Inspect all contracts in a goal for errors, returning StructuredError list."""
187
+ errors = []
188
+ for c in plan.contracts:
189
+ tid = c["task_id"]
190
+ state_file = os.path.join(run_dir, tid, "state.json")
191
+ if not os.path.isfile(state_file):
192
+ continue
193
+ state = load_state(state_file)
194
+ err = from_state(state, tid, workspace_root)
195
+ if err is not None:
196
+ errors.append(err)
197
+ return errors
198
+
199
+
200
+ def format_error_list(errors: List[StructuredError]) -> str:
201
+ """Format a list of StructuredError objects as human-readable string."""
202
+ if not errors:
203
+ return "No errors found."
204
+ lines = [f"{len(errors)} error(s) found:"]
205
+ for e in errors:
206
+ lines.append(f" [{e.code}] {e.severity.upper()} | {e.component} | {e.task_id}")
207
+ lines.append(f" {e.title}: {e.message}")
208
+ if e.context:
209
+ ctx_preview = ", ".join(f"{k}={v}" for k, v in list(e.context.items())[:4])
210
+ lines.append(f" context: {ctx_preview}")
211
+ return "\n".join(lines)
orchestrator/events.py ADDED
@@ -0,0 +1,120 @@
1
+ """Thread-safe event bus for goal lifecycle events — async pub/sub with no blocking.
2
+
3
+ Delivery is bounded: a shared semaphore caps concurrent subscriber invocations so
4
+ a slow consumer cannot turn event bursts into unbounded thread pileups. When the
5
+ cap is saturated, delivery is skipped (counted in ``dropped_count``) rather than
6
+ blocking the control loop - telemetry may drop; execution must not stall.
7
+ """
8
+
9
+ import sys
10
+ import threading
11
+ from datetime import datetime, timezone
12
+ from typing import Any, Callable, Dict, List, Optional, Tuple
13
+
14
+ EVENT_TYPES: Tuple[str, ...] = (
15
+ "goal.started",
16
+ "contract.working",
17
+ "contract.verified",
18
+ "contract.qc_passed",
19
+ "contract.failed",
20
+ "impossibility.generated",
21
+ "goal.completed",
22
+ )
23
+
24
+ Subscriber = Callable[[Dict[str, Any]], None]
25
+
26
+ DEFAULT_MAX_CONCURRENT_DELIVERIES = 32
27
+
28
+
29
+ class EventBus:
30
+ """Publish/subscribe bus delivering each event to matching subscribers.
31
+
32
+ Subscriber invocations run asynchronously in daemon threads, bounded by
33
+ ``max_concurrent_deliveries``. When the bound is saturated the delivery is
34
+ dropped and counted instead of queueing or blocking the publisher.
35
+ """
36
+
37
+ def __init__(self, max_concurrent_deliveries: int = DEFAULT_MAX_CONCURRENT_DELIVERIES) -> None:
38
+ self._lock = threading.Lock()
39
+ self._subscribers: List[Tuple[Optional[str], Subscriber]] = []
40
+ cap = max(1, int(max_concurrent_deliveries))
41
+ self._capacity = cap
42
+ self._slots = threading.BoundedSemaphore(cap)
43
+ self.dropped_count = 0
44
+
45
+ def subscribe(
46
+ self,
47
+ callback: Subscriber,
48
+ event_type: Optional[str] = None,
49
+ ) -> Callable[[], None]:
50
+ """Register callback; event_type=None matches all events. Returns unsubscribe."""
51
+ entry = (event_type, callback)
52
+ with self._lock:
53
+ self._subscribers.append(entry)
54
+
55
+ def unsubscribe() -> None:
56
+ with self._lock:
57
+ try:
58
+ self._subscribers.remove(entry)
59
+ except ValueError:
60
+ pass
61
+
62
+ return unsubscribe
63
+
64
+ def publish(
65
+ self,
66
+ event_type: str,
67
+ goal_id: Optional[str] = None,
68
+ task_id: Optional[str] = None,
69
+ **payload: Any,
70
+ ) -> Dict[str, Any]:
71
+ """Build an envelope and deliver it to all matching subscribers asynchronously."""
72
+ envelope: Dict[str, Any] = {
73
+ "event": event_type,
74
+ "goal_id": goal_id,
75
+ "task_id": task_id,
76
+ "timestamp": datetime.now(timezone.utc).isoformat(),
77
+ "data": dict(payload),
78
+ }
79
+ with self._lock:
80
+ targets = [cb for et, cb in self._subscribers if et is None or et == event_type]
81
+ for cb in targets:
82
+ if not self._slots.acquire(blocking=False):
83
+ with self._lock:
84
+ self.dropped_count += 1
85
+ print(
86
+ f"[events] delivery saturated - dropping event {event_type} (dropped_total={self.dropped_count})",
87
+ file=sys.stderr,
88
+ )
89
+ continue
90
+ thread = threading.Thread(
91
+ target=self._deliver,
92
+ args=(cb, envelope),
93
+ daemon=True,
94
+ )
95
+ thread.start()
96
+ return envelope
97
+
98
+ def clear(self) -> None:
99
+ """Drop all subscriptions (test helper)."""
100
+ with self._lock:
101
+ self._subscribers = []
102
+
103
+ def _deliver(self, callback: Subscriber, envelope: Dict[str, Any]) -> None:
104
+ try:
105
+ callback(envelope)
106
+ except Exception as exc:
107
+ print(f"[events] subscriber error: {exc}", file=sys.stderr)
108
+ finally:
109
+ try:
110
+ self._slots.release()
111
+ except ValueError:
112
+ pass
113
+
114
+
115
+ _bus = EventBus()
116
+
117
+
118
+ def get_bus() -> EventBus:
119
+ """Return the process-wide singleton bus."""
120
+ return _bus