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
orchestrator/scope.py ADDED
@@ -0,0 +1,466 @@
1
+ """Filesystem scope enforcement — snapshot/diff for contract execution boundaries."""
2
+
3
+ import json
4
+ import os
5
+ import shutil
6
+ import sys
7
+ import time
8
+ import uuid
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ from . import evidence as ev
12
+
13
+ _snapshot_cache: Dict[str, Dict[str, str]] = {}
14
+
15
+
16
+ SCOPE_SNAPSHOT_FILE = "scope_snapshot.json"
17
+
18
+
19
+ def _is_under_path(child: str, parent_dir: str) -> bool:
20
+ """Check if child is under parent_dir using path component comparison.
21
+
22
+ Avoids raw prefix-match false positives: /app/src_malicious/f.py vs /app/src.
23
+ """
24
+ parent_parts = os.path.normcase(os.path.normpath(parent_dir)).rstrip(os.sep).split(os.sep)
25
+ child_parts = os.path.normcase(os.path.normpath(child)).split(os.sep)
26
+ return child_parts[: len(parent_parts)] == parent_parts
27
+
28
+
29
+ class ScopeViolation:
30
+ """A single scope violation — file in denied path or outside allowed scope."""
31
+
32
+ def __init__(
33
+ self,
34
+ path: str,
35
+ violation_type: str,
36
+ detail: str = "",
37
+ created_new: bool = False,
38
+ old_hash: str = "",
39
+ current_hash: str = "",
40
+ ):
41
+ self.path = path
42
+ self.violation_type = violation_type
43
+ self.detail = detail
44
+ # AUT-018: machine-readable provenance for safe auto-cleanup — only
45
+ # newly-created files may be deleted automatically; modified
46
+ # pre-existing files must never be auto-removed.
47
+ self.created_new = created_new
48
+ self.old_hash = old_hash
49
+ self.current_hash = current_hash
50
+
51
+ def to_dict(self) -> Dict[str, str]:
52
+ return {
53
+ "path": self.path,
54
+ "violation_type": self.violation_type,
55
+ "detail": self.detail,
56
+ "created_new": self.created_new,
57
+ "old_hash": self.old_hash,
58
+ "current_hash": self.current_hash,
59
+ }
60
+
61
+ def __repr__(self) -> str:
62
+ return f"[{self.violation_type}] {self.path}"
63
+
64
+
65
+ class ScopeCheckResult:
66
+ """Result of scope violation check."""
67
+
68
+ def __init__(self, passed: bool, violations: List[ScopeViolation], snapshot_path: str = ""):
69
+ self.passed = passed
70
+ self.violations = violations
71
+ self.snapshot_path = snapshot_path
72
+
73
+ def to_dict(self) -> Dict:
74
+ return {
75
+ "passed": self.passed,
76
+ "violations": [v.to_dict() for v in self.violations],
77
+ "snapshot_path": self.snapshot_path,
78
+ }
79
+
80
+
81
+ _IGNORED_DIRS = {".opencode", ".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "generated"}
82
+ _IGNORED_EXTS = {".pyc", ".pyo", ".pyd"}
83
+
84
+
85
+ def _walk_matching(root: str, prefixes: List[str]) -> Dict[str, str]:
86
+ """Walk files under root matching any prefix via component-safe comparison."""
87
+ files: Dict[str, str] = {}
88
+ root_abs = os.path.abspath(root)
89
+ for dirpath, _dirnames, filenames in os.walk(root_abs):
90
+ if _IGNORED_DIRS & set(dirpath.split(os.sep)):
91
+ _dirnames[:] = []
92
+ continue
93
+ for fn in filenames:
94
+ if any(fn.endswith(ext) for ext in _IGNORED_EXTS):
95
+ continue
96
+ abs_path = os.path.join(dirpath, fn)
97
+ rel_path = os.path.relpath(abs_path, root_abs)
98
+ for prefix in prefixes:
99
+ prefix_abs = os.path.abspath(os.path.join(root_abs, prefix))
100
+ if _is_under_path(abs_path, prefix_abs):
101
+ files[rel_path] = ev._sha256(abs_path)
102
+ break
103
+ return files
104
+
105
+
106
+ def _walk_all(root: str, exclude_dir: str = None) -> Dict[str, str]:
107
+ """Walk all files under root, optionally excluding a directory."""
108
+ files: Dict[str, str] = {}
109
+ root_abs = os.path.abspath(root)
110
+ exclude_abs = os.path.abspath(exclude_dir) if exclude_dir else None
111
+ for dirpath, _dirnames, filenames in os.walk(root_abs):
112
+ if _IGNORED_DIRS & set(dirpath.split(os.sep)):
113
+ _dirnames[:] = []
114
+ continue
115
+ for fn in filenames:
116
+ if any(fn.endswith(ext) for ext in _IGNORED_EXTS):
117
+ continue
118
+ abs_path = os.path.join(dirpath, fn)
119
+ if exclude_abs and _is_under_path(abs_path, exclude_abs):
120
+ continue
121
+ rel_path = os.path.relpath(abs_path, root_abs)
122
+ files[rel_path] = ev._sha256(abs_path)
123
+ return files
124
+
125
+
126
+ def snapshot_scope(workspace_root: str, allowed_paths: List[str], run_dir: str, denied_paths: List[str] = None) -> str:
127
+ """Take pre-execution snapshot of the entire workspace (excl. run_dir).
128
+
129
+ Captures all files under workspace_root so post-execution check can
130
+ distinguish worker-created files from pre-existing ones.
131
+ Returns path to snapshot file.
132
+ """
133
+ snapshot = _walk_all(workspace_root, exclude_dir=run_dir)
134
+ cache_key = f"{workspace_root}|{run_dir}"
135
+ _snapshot_cache[cache_key] = snapshot
136
+ os.makedirs(run_dir, exist_ok=True)
137
+ snapshot_path = os.path.join(run_dir, SCOPE_SNAPSHOT_FILE)
138
+ with open(snapshot_path, "w", encoding="utf-8") as f:
139
+ json.dump(snapshot, f, indent=2, sort_keys=True)
140
+ return snapshot_path
141
+
142
+
143
+ def load_snapshot(run_dir: str) -> Dict[str, str]:
144
+ """Load scope snapshot from disk."""
145
+ snapshot_path = os.path.join(run_dir, SCOPE_SNAPSHOT_FILE)
146
+ if not os.path.isfile(snapshot_path):
147
+ return {}
148
+ with open(snapshot_path, "r", encoding="utf-8") as f:
149
+ return json.load(f)
150
+
151
+
152
+ def is_path_exempt(
153
+ target_path: str,
154
+ exemption_paths: List[str],
155
+ workspace_root: Optional[str] = None,
156
+ ) -> bool:
157
+ """Return whether target_path is an exemption path or descendant.
158
+
159
+ Uses normalized absolute paths and os.path.commonpath so a declared output
160
+ DIRECTORY exempts nested outputs (prefix semantics, not exact match).
161
+ Different Windows drives are never considered related.
162
+ """
163
+
164
+ def _absolute(path: str) -> str:
165
+ path = path.replace("\\", os.sep).replace("/", os.sep)
166
+ if workspace_root and not os.path.isabs(path):
167
+ path = os.path.join(workspace_root, path)
168
+ return os.path.normcase(os.path.abspath(os.path.normpath(path)))
169
+
170
+ target_abs = _absolute(target_path)
171
+ for exemption_path in exemption_paths:
172
+ if not exemption_path:
173
+ continue
174
+ exemption_abs = _absolute(exemption_path)
175
+ try:
176
+ if os.path.commonpath([target_abs, exemption_abs]) == exemption_abs:
177
+ return True
178
+ except ValueError:
179
+ continue
180
+ return False
181
+
182
+
183
+ class FileBackedScopeRegistry:
184
+ """Multiprocess registry for declared-output scope leases (autonomy fix).
185
+
186
+ Serialized through a short-lived lock file; persisted with temp+os.replace.
187
+ Stale leases are TTL-pruned on read/write. Lets a parallel task's scope
188
+ check ignore sibling tasks' declared outputs that are still being written.
189
+ """
190
+
191
+ LEASE_TTL_SEC = 300
192
+ LOCK_TTL_SEC = 30
193
+
194
+ def __init__(self, workspace_root: str, ttl_sec: int = LEASE_TTL_SEC):
195
+ import threading
196
+
197
+ self.workspace_root = os.path.abspath(workspace_root)
198
+ self.ttl_sec = ttl_sec
199
+ self.lock_dir = os.path.join(self.workspace_root, ".opencode", "locks")
200
+ self.path = os.path.join(self.lock_dir, "scope_leases.json")
201
+ self.lock_path = f"{self.path}.lock"
202
+ self._thread_lock = threading.Lock()
203
+
204
+ def _acquire(self) -> None:
205
+ os.makedirs(self.lock_dir, exist_ok=True)
206
+ deadline = time.time() + self.LOCK_TTL_SEC
207
+ while True:
208
+ try:
209
+ fd = os.open(self.lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
210
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
211
+ json.dump({"pid": os.getpid(), "created_at": time.time()}, f)
212
+ return
213
+ except (FileExistsError, PermissionError):
214
+ try:
215
+ if time.time() - os.path.getmtime(self.lock_path) > self.LOCK_TTL_SEC:
216
+ os.remove(self.lock_path)
217
+ continue
218
+ except OSError:
219
+ pass
220
+ if time.time() >= deadline:
221
+ raise TimeoutError("timed out acquiring scope lease registry lock")
222
+ time.sleep(0.01)
223
+
224
+ def _release(self) -> None:
225
+ try:
226
+ os.remove(self.lock_path)
227
+ except OSError:
228
+ pass
229
+
230
+ def _load_unlocked(self) -> List[Dict[str, Any]]:
231
+ try:
232
+ with open(self.path, "r", encoding="utf-8") as f:
233
+ payload = json.load(f)
234
+ except (OSError, json.JSONDecodeError):
235
+ payload = {}
236
+ leases = payload.get("leases", []) if isinstance(payload, dict) else []
237
+ if not isinstance(leases, list):
238
+ leases = []
239
+ now = time.time()
240
+ return [
241
+ lease
242
+ for lease in leases
243
+ if isinstance(lease, dict)
244
+ and isinstance(lease.get("created_at"), (int, float))
245
+ and now - lease["created_at"] <= self.ttl_sec
246
+ ]
247
+
248
+ def _write_unlocked(self, leases: List[Dict[str, Any]]) -> None:
249
+ os.makedirs(self.lock_dir, exist_ok=True)
250
+ temp_path = f"{self.path}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
251
+ try:
252
+ with open(temp_path, "w", encoding="utf-8") as f:
253
+ json.dump({"leases": leases}, f, indent=2, sort_keys=True)
254
+ f.flush()
255
+ os.fsync(f.fileno())
256
+ os.replace(temp_path, self.path)
257
+ finally:
258
+ try:
259
+ if os.path.exists(temp_path):
260
+ os.remove(temp_path)
261
+ except OSError:
262
+ pass
263
+
264
+ def register(self, task_id: str, declared_outputs: List[str]) -> None:
265
+ with self._thread_lock:
266
+ self._acquire()
267
+ try:
268
+ leases = [lease for lease in self._load_unlocked() if lease.get("task_id") != task_id]
269
+ leases.append(
270
+ {
271
+ "task_id": task_id,
272
+ "pid": os.getpid(),
273
+ "created_at": time.time(),
274
+ "declared_outputs": list(declared_outputs),
275
+ }
276
+ )
277
+ self._write_unlocked(leases)
278
+ finally:
279
+ self._release()
280
+
281
+ def unregister(self, task_id: str) -> None:
282
+ with self._thread_lock:
283
+ try:
284
+ self._acquire()
285
+ except TimeoutError:
286
+ return
287
+ try:
288
+ leases = [lease for lease in self._load_unlocked() if lease.get("task_id") != task_id]
289
+ self._write_unlocked(leases)
290
+ finally:
291
+ self._release()
292
+
293
+ def sibling_declared_outputs(self, task_id: Optional[str] = None) -> List[str]:
294
+ with self._thread_lock:
295
+ try:
296
+ self._acquire()
297
+ except TimeoutError:
298
+ return []
299
+ try:
300
+ leases = self._load_unlocked()
301
+ self._write_unlocked(leases)
302
+ outputs: List[str] = []
303
+ for lease in leases:
304
+ if task_id is not None and lease.get("task_id") == task_id:
305
+ continue
306
+ declared = lease.get("declared_outputs", [])
307
+ if isinstance(declared, list):
308
+ outputs.extend(str(p) for p in declared if p)
309
+ return outputs
310
+ finally:
311
+ self._release()
312
+
313
+
314
+ def check_scope(
315
+ contract, workspace_root: str, run_dir: str, exclude_dir: Optional[str] = None, task_id: Optional[str] = None
316
+ ) -> ScopeCheckResult:
317
+ """Check if contract execution caused scope violations.
318
+
319
+ Compares current filesystem state against pre-execution snapshot.
320
+ Detects:
321
+ - New or modified files outside allowed paths
322
+ - New or modified files in denied paths
323
+ - Files in scratch_dir (temp_dir) are exempt from new-file violations
324
+
325
+ exclude_dir: an additional directory tree to exclude from the walk —
326
+ used by the supervisor to hide its own run-state (state.json, journals,
327
+ sibling task dirs) from the scope check (parallel-mode fix 2026-07-31).
328
+
329
+ task_id: when set, sibling tasks' active declared-output leases are exempt
330
+ (they may be writing their own declared outputs concurrently).
331
+ """
332
+ cache_key = f"{workspace_root}|{run_dir}"
333
+ before = _snapshot_cache.get(cache_key)
334
+ if before is None:
335
+ before = load_snapshot(run_dir)
336
+ snapshot_path = os.path.join(run_dir, SCOPE_SNAPSHOT_FILE)
337
+ if before is None or (not before and not os.path.isfile(snapshot_path)):
338
+ missing_snapshot = not os.path.isfile(snapshot_path)
339
+ if missing_snapshot:
340
+ return ScopeCheckResult(
341
+ passed=False,
342
+ violations=[
343
+ ScopeViolation(
344
+ path=snapshot_path,
345
+ violation_type="missing_snapshot",
346
+ detail="scope snapshot file missing — cannot verify scope integrity",
347
+ )
348
+ ],
349
+ snapshot_path=snapshot_path,
350
+ )
351
+ before = {}
352
+
353
+ allowed = contract.workspace_scope.get("allow", [])
354
+ denied = contract.workspace_scope.get("deny", [])
355
+ scratch_dir = contract.workspace_scope.get("scratch_dir", "")
356
+
357
+ after = _walk_all(workspace_root, exclude_dir=exclude_dir or run_dir)
358
+ violations: List[ScopeViolation] = []
359
+
360
+ sibling_outputs: List[str] = []
361
+ if task_id:
362
+ try:
363
+ sibling_outputs = FileBackedScopeRegistry(workspace_root).sibling_declared_outputs(task_id=task_id)
364
+ except (TimeoutError, OSError, json.JSONDecodeError, KeyError):
365
+ sibling_outputs = []
366
+ violations: List[ScopeViolation] = []
367
+
368
+ allowed_abs = [os.path.abspath(os.path.join(workspace_root, a)) for a in allowed]
369
+ denied_abs = [os.path.abspath(os.path.join(workspace_root, d)) for d in denied]
370
+ scratch_abs = os.path.abspath(os.path.join(workspace_root, scratch_dir)) if scratch_dir else ""
371
+
372
+ for path, current_hash in after.items():
373
+ abs_path = os.path.abspath(os.path.join(workspace_root, path))
374
+
375
+ # Sibling tasks' active declared-output leases are exempt — they may be
376
+ # writing their own declared outputs concurrently.
377
+ if sibling_outputs and is_path_exempt(abs_path, sibling_outputs, workspace_root=workspace_root):
378
+ continue
379
+
380
+ # Skip scratch_dir files — they are temp helper artifacts
381
+ if scratch_abs and _is_under_path(abs_path, scratch_abs):
382
+ old_hash = before.get(path)
383
+ if old_hash is None:
384
+ continue
385
+
386
+ in_denied = any(_is_under_path(abs_path, d_abs) for d_abs in denied_abs)
387
+ in_allowed = any(_is_under_path(abs_path, a_abs) for a_abs in allowed_abs)
388
+
389
+ if in_denied:
390
+ old_hash = before.get(path)
391
+ if old_hash is None:
392
+ violations.append(
393
+ ScopeViolation(
394
+ path=path,
395
+ violation_type="denied_new",
396
+ detail="new file created in denied path",
397
+ created_new=True,
398
+ current_hash=current_hash,
399
+ )
400
+ )
401
+ elif old_hash != current_hash:
402
+ violations.append(
403
+ ScopeViolation(
404
+ path=path,
405
+ violation_type="denied_modified",
406
+ detail="file in denied path was modified",
407
+ created_new=False,
408
+ old_hash=old_hash,
409
+ current_hash=current_hash,
410
+ )
411
+ )
412
+ elif not in_allowed:
413
+ old_hash = before.get(path)
414
+ if old_hash is None:
415
+ violations.append(
416
+ ScopeViolation(
417
+ path=path,
418
+ violation_type="outside_scope",
419
+ detail="new file created outside allowed scope",
420
+ created_new=True,
421
+ current_hash=current_hash,
422
+ )
423
+ )
424
+ elif old_hash != current_hash:
425
+ violations.append(
426
+ ScopeViolation(
427
+ path=path,
428
+ violation_type="outside_scope_modified",
429
+ detail="file outside allowed scope was modified",
430
+ created_new=False,
431
+ old_hash=old_hash,
432
+ current_hash=current_hash,
433
+ )
434
+ )
435
+
436
+ return ScopeCheckResult(
437
+ passed=len(violations) == 0,
438
+ violations=violations,
439
+ snapshot_path=snapshot_path,
440
+ )
441
+
442
+
443
+ def cleanup_scratch_dir(workspace_root: str, contract) -> None:
444
+ """Remove scratch_dir if defined in contract workspace_scope."""
445
+ scratch_dir = contract.workspace_scope.get("scratch_dir", "")
446
+ if not scratch_dir:
447
+ return
448
+ full = os.path.join(workspace_root, scratch_dir) if not os.path.isabs(scratch_dir) else scratch_dir
449
+ if os.path.isdir(full):
450
+ try:
451
+ shutil.rmtree(full, ignore_errors=True)
452
+ print(f"[scope] cleaned scratch_dir: {scratch_dir}", file=sys.stderr)
453
+ except OSError as e:
454
+ print(f"[scope] failed to clean scratch_dir {scratch_dir}: {e}", file=sys.stderr)
455
+
456
+
457
+ def format_scope_result(result: ScopeCheckResult) -> str:
458
+ """Format scope check result as human-readable string."""
459
+ if result.passed:
460
+ return "Scope check PASSED — all files within allowed boundaries."
461
+ lines = [f"Scope check FAILED — {len(result.violations)} violation(s):"]
462
+ for v in result.violations:
463
+ lines.append(f" [{v.violation_type}] {v.path}")
464
+ if v.detail:
465
+ lines.append(f" {v.detail}")
466
+ return "\n".join(lines)
@@ -0,0 +1,79 @@
1
+ """
2
+ orchestrator/sensory_radar.py
3
+ Autonomous sensory radar for scanning codebases and ranking evolutionary vectors.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import List, Optional
12
+
13
+ from orchestrator.elasticity_governor import DynamicElasticityGovernor
14
+
15
+
16
+ @dataclass
17
+ class SensoryTask:
18
+ task_id: str
19
+ target_module: str
20
+ target_function: Optional[str]
21
+ optimization_goal: str
22
+ complexity_score: float
23
+ priority: int
24
+
25
+
26
+ class SensoryRadar:
27
+ """Autonomous sensory radar for scanning codebases and ranking evolutionary vectors."""
28
+
29
+ def __init__(self, workspace_root: Path):
30
+ self.workspace_root = Path(workspace_root)
31
+
32
+ def scan_workspace(self) -> List[SensoryTask]:
33
+ tasks: List[SensoryTask] = []
34
+ for py_file in self.workspace_root.rglob("*.py"):
35
+ try:
36
+ rel = py_file.relative_to(self.workspace_root)
37
+ except ValueError:
38
+ continue
39
+
40
+ rel_parts = rel.parts
41
+ if (
42
+ "test" in py_file.stem
43
+ or "tests" in rel_parts
44
+ or ".venv" in rel_parts
45
+ or ".git" in rel_parts
46
+ or "scratch" in rel_parts
47
+ or "build" in rel_parts
48
+ or "dist" in rel_parts
49
+ ):
50
+ continue
51
+
52
+ try:
53
+ content = py_file.read_text(encoding="utf-8")
54
+ tree = ast.parse(content)
55
+ except Exception:
56
+ continue
57
+
58
+ lines = content.splitlines()
59
+ rel_path = str(rel).replace("\\", "/")
60
+ for node in ast.walk(tree):
61
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
62
+ start = getattr(node, "lineno", 1)
63
+ end = getattr(node, "end_lineno", len(lines))
64
+ func_src = "\n".join(lines[start - 1 : end])
65
+
66
+ score = DynamicElasticityGovernor.calculate_complexity(func_src)
67
+ if score >= 8.0: # Optimization hotspot threshold (>= 8 LOC / cyclomatic)
68
+ tasks.append(
69
+ SensoryTask(
70
+ task_id=f"HOTSPOT-{py_file.stem}-{node.name}",
71
+ target_module=rel_path,
72
+ target_function=node.name,
73
+ optimization_goal=f"Decompose logic and reduce cyclomatic complexity from {score:.1f}.",
74
+ complexity_score=score,
75
+ priority=max(1, int(score // 10)),
76
+ )
77
+ )
78
+ tasks.sort(key=lambda t: t.complexity_score, reverse=True)
79
+ return tasks
@@ -0,0 +1,140 @@
1
+ """Multi-platform Agent Skill Installer for letitloop.
2
+
3
+ Installs the `letitloop` agent skill into supported 2026 AI coding environments:
4
+ - Claude Code (~/.claude/skills/letitloop/)
5
+ - Google Antigravity (~/.gemini/antigravity/builtin/skills/letitloop/ or .agents/skills/letitloop/)
6
+ - OpenAI Codex (~/.codex/skills/letitloop/ or .codex/skills/letitloop/)
7
+ - Hermes Agent (~/.hermes/skills/letitloop/ or .hermes/skills/letitloop/)
8
+ - OpenCode (.opencode/skills/letitloop/)
9
+ - Cursor IDE (.cursor/skills/letitloop/)
10
+ - Cline (.cline/skills/letitloop/ or ~/.cline/skills/letitloop/)
11
+ - Windsurf (.windsurf/skills/letitloop/)
12
+ """
13
+
14
+ import shutil
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import List, Optional, Tuple
18
+
19
+
20
+ def get_skill_src() -> Path:
21
+ """Resolve SKILL.md directory path."""
22
+ current_dir = Path(__file__).resolve().parent.parent / "skill"
23
+ skill_file = current_dir / "SKILL.md"
24
+ if not skill_file.is_file():
25
+ # Fallback: check alongside module if packaged
26
+ pkg_skill = Path(__file__).resolve().parent / "SKILL.md"
27
+ if pkg_skill.is_file():
28
+ return Path(__file__).resolve().parent
29
+ raise FileNotFoundError(f"SKILL.md not found at {skill_file}")
30
+ return current_dir
31
+
32
+
33
+ def install_for_claude_code(src_dir: Path) -> Path:
34
+ home = Path.home()
35
+ dest = home / ".claude" / "skills" / "letitloop"
36
+ dest.mkdir(parents=True, exist_ok=True)
37
+ shutil.copy2(src_dir / "SKILL.md", dest / "SKILL.md")
38
+ return dest
39
+
40
+
41
+ def install_for_antigravity(src_dir: Path, target_workspace: Optional[Path] = None) -> Path:
42
+ if target_workspace and (target_workspace / ".agents").exists():
43
+ dest = target_workspace / ".agents" / "skills" / "letitloop"
44
+ else:
45
+ home = Path.home()
46
+ dest = home / ".gemini" / "antigravity" / "builtin" / "skills" / "letitloop"
47
+ dest.mkdir(parents=True, exist_ok=True)
48
+ shutil.copy2(src_dir / "SKILL.md", dest / "SKILL.md")
49
+ return dest
50
+
51
+
52
+ def install_for_hermes(src_dir: Path, target_workspace: Optional[Path] = None) -> Path:
53
+ if target_workspace and (target_workspace / ".hermes").exists():
54
+ dest = target_workspace / ".hermes" / "skills" / "letitloop"
55
+ else:
56
+ home = Path.home()
57
+ dest = home / ".hermes" / "skills" / "letitloop"
58
+ dest.mkdir(parents=True, exist_ok=True)
59
+ shutil.copy2(src_dir / "SKILL.md", dest / "SKILL.md")
60
+ return dest
61
+
62
+
63
+ def install_for_opencode(src_dir: Path, target_workspace: Path) -> Path:
64
+ dest = target_workspace / ".opencode" / "skills" / "letitloop"
65
+ dest.mkdir(parents=True, exist_ok=True)
66
+ shutil.copy2(src_dir / "SKILL.md", dest / "SKILL.md")
67
+ return dest
68
+
69
+
70
+ def install_for_cursor(src_dir: Path, target_workspace: Path) -> Path:
71
+ dest = target_workspace / ".cursor" / "skills" / "letitloop"
72
+ dest.mkdir(parents=True, exist_ok=True)
73
+ shutil.copy2(src_dir / "SKILL.md", dest / "SKILL.md")
74
+ return dest
75
+
76
+
77
+ def install_for_cline(src_dir: Path, target_workspace: Path) -> Path:
78
+ dest = target_workspace / ".cline" / "skills" / "letitloop"
79
+ dest.mkdir(parents=True, exist_ok=True)
80
+ shutil.copy2(src_dir / "SKILL.md", dest / "SKILL.md")
81
+ return dest
82
+
83
+
84
+ def install_for_windsurf(src_dir: Path, target_workspace: Path) -> Path:
85
+ dest = target_workspace / ".windsurf" / "skills" / "letitloop"
86
+ dest.mkdir(parents=True, exist_ok=True)
87
+ shutil.copy2(src_dir / "SKILL.md", dest / "SKILL.md")
88
+ return dest
89
+
90
+
91
+ def install_for_codex(src_dir: Path, target_workspace: Optional[Path] = None) -> Path:
92
+ """Install letitloop skill for OpenAI Codex (global skills dir or project-local .codex/skills)."""
93
+ if target_workspace and (target_workspace / ".codex").exists():
94
+ dest = target_workspace / ".codex" / "skills" / "letitloop"
95
+ elif target_workspace and (target_workspace / "AGENTS.md").exists():
96
+ dest = target_workspace / ".codex" / "skills" / "letitloop"
97
+ else:
98
+ home = Path.home()
99
+ dest = home / ".codex" / "skills" / "letitloop"
100
+ dest.mkdir(parents=True, exist_ok=True)
101
+ shutil.copy2(src_dir / "SKILL.md", dest / "SKILL.md")
102
+ return dest
103
+
104
+
105
+ TARGET_MAP = {
106
+ "claude": ("Claude Code", install_for_claude_code),
107
+ "antigravity": ("Google Antigravity", install_for_antigravity),
108
+ "codex": ("OpenAI Codex", install_for_codex),
109
+ "hermes": ("Hermes Agent", install_for_hermes),
110
+ "opencode": ("OpenCode", install_for_opencode),
111
+ "cursor": ("Cursor IDE", install_for_cursor),
112
+ "cline": ("Cline", install_for_cline),
113
+ "windsurf": ("Windsurf", install_for_windsurf),
114
+ }
115
+
116
+
117
+ def run_skill_install(target: str = "all", workspace: Optional[Path] = None) -> List[Tuple[str, Path]]:
118
+ """Execute skill installation for the given target and workspace."""
119
+ src = get_skill_src()
120
+ ws = (workspace or Path.cwd()).resolve()
121
+ installed = []
122
+
123
+ targets_to_run = list(TARGET_MAP.keys()) if target == "all" else [target]
124
+
125
+ for key in targets_to_run:
126
+ if key not in TARGET_MAP:
127
+ continue
128
+ name, fn = TARGET_MAP[key]
129
+ try:
130
+ if key in ("claude",):
131
+ dest = fn(src)
132
+ elif key in ("antigravity", "hermes", "codex"):
133
+ dest = fn(src, ws)
134
+ else:
135
+ dest = fn(src, ws)
136
+ installed.append((name, dest))
137
+ except Exception as e:
138
+ print(f"[-] {name} install skipped: {e}", file=sys.stderr)
139
+
140
+ return installed