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,404 @@
1
+ """Strict JSON task contract validation."""
2
+
3
+ import json
4
+ import os
5
+
6
+ from .quality_plan import VALID_LENSES
7
+
8
+ REQUIRED_TOP_LEVEL = {
9
+ "task_id": str,
10
+ "title": str,
11
+ "status": str,
12
+ "risk_tier": str,
13
+ "workspace_scope": dict,
14
+ "objective": str,
15
+ "worker": dict,
16
+ "outputs": list,
17
+ "acceptance_checks": list,
18
+ "qc": dict,
19
+ }
20
+
21
+ VALID_RISK_TIERS = {"auto", "qc_required", "human_required"}
22
+ VALID_STATUSES = {"drafted", "DRAFTED"}
23
+ VALID_CHECK_KINDS = {
24
+ "command",
25
+ "file_exists",
26
+ "json_schema",
27
+ "content_exact",
28
+ "content_regex",
29
+ "syntax",
30
+ "hygiene",
31
+ "min_size",
32
+ "required_sections",
33
+ "render",
34
+ "contradiction_count",
35
+ "edge_case_count",
36
+ "test_spec_count",
37
+ "schema_count",
38
+ "novel_artifact",
39
+ }
40
+ VALID_QC_LENSES = set(VALID_LENSES) # single canonical registry (see quality_plan.VALID_LENSES)
41
+
42
+
43
+ def requires_semantic_qc(risk_tier: str, outputs: list, acceptance_checks: list, quality_spec: dict = None) -> bool:
44
+ """Central policy: determine if a task requires semantic QC review.
45
+
46
+ Returns True when:
47
+ - risk_tier is qc_required or human_required
48
+ - multiple outputs exist
49
+ - outputs touch src/ or tests/
50
+ - any acceptance check implies semantic significance
51
+ - quality_spec has hard_failures, minimum_score, or minimum_counts
52
+ """
53
+ if risk_tier in ("qc_required", "human_required"):
54
+ return True
55
+ if len(outputs) > 1:
56
+ return True
57
+ for out in outputs:
58
+ path = out.get("path", "").replace("\\", "/")
59
+ if path.startswith("src/") or path.startswith("tests/") or "/tests/" in path:
60
+ return True
61
+ for check in acceptance_checks:
62
+ kind = check.get("kind", "")
63
+ if kind == "file_exists":
64
+ continue
65
+ if kind in ("syntax", "hygiene", "min_size", "command"):
66
+ continue
67
+ if kind == "content_regex":
68
+ if check.get("expected", "") in (".+", ".*", ""):
69
+ continue
70
+ return True
71
+ if quality_spec:
72
+ if quality_spec.get("hard_failures") or quality_spec.get("minimum_score", 0) > 0:
73
+ return True
74
+ if quality_spec.get("minimum_counts"):
75
+ return True
76
+ if not outputs and quality_spec:
77
+ return True
78
+ return False
79
+
80
+
81
+ def validate_contract_against_plan(plan_contract: dict, generated_contract: dict) -> list[str]:
82
+ """Compare safety fields between plan and generated contract.
83
+
84
+ Generated contract may only ADD protections, never remove them.
85
+ Returns list of error/warning strings if any safety field was DOWNGRADED.
86
+ """
87
+ messages = []
88
+
89
+ plan_qc = plan_contract.get("qc", {})
90
+ gen_qc = generated_contract.get("qc", {})
91
+ if plan_qc.get("required") is True and gen_qc.get("required") is not True:
92
+ messages.append("qc.required: plan requires QC (true) but generated contract does not")
93
+
94
+ plan_allow = set(plan_contract.get("workspace_scope", {}).get("allow", []))
95
+ gen_allow = set(generated_contract.get("workspace_scope", {}).get("allow", []))
96
+ if not gen_allow.issuperset(plan_allow):
97
+ missing = plan_allow - gen_allow
98
+ messages.append(
99
+ f"workspace_scope.allow: generated contract missing {len(missing)} path(s) from plan: {sorted(missing)}"
100
+ )
101
+
102
+ plan_deny = set(plan_contract.get("workspace_scope", {}).get("deny", []))
103
+ gen_deny = set(generated_contract.get("workspace_scope", {}).get("deny", []))
104
+ if not gen_deny.issuperset(plan_deny):
105
+ missing = plan_deny - gen_deny
106
+ messages.append(
107
+ f"workspace_scope.deny: generated contract missing {len(missing)} path(s) from plan: {sorted(missing)}"
108
+ )
109
+
110
+ plan_checks = len(plan_contract.get("acceptance_checks", []))
111
+ gen_checks = len(generated_contract.get("acceptance_checks", []))
112
+ if gen_checks < plan_checks:
113
+ messages.append(f"WARNING: acceptance_checks: plan has {plan_checks}, generated has {gen_checks}")
114
+
115
+ plan_hf = set(plan_contract.get("quality_spec", {}).get("hard_failures", []))
116
+ gen_hf = set(generated_contract.get("quality_spec", {}).get("hard_failures", []))
117
+ if not gen_hf.issuperset(plan_hf):
118
+ missing = plan_hf - gen_hf
119
+ messages.append(
120
+ f"quality_spec.hard_failures: generated contract missing {len(missing)} failure(s) from plan: {sorted(missing)}"
121
+ )
122
+
123
+ plan_ms = plan_contract.get("quality_spec", {}).get("minimum_score", 0)
124
+ gen_ms = generated_contract.get("quality_spec", {}).get("minimum_score", 0)
125
+ if gen_ms < plan_ms:
126
+ messages.append(f"quality_spec.minimum_score: plan requires {plan_ms}, generated has {gen_ms}")
127
+
128
+ return messages
129
+
130
+
131
+ class Contract:
132
+ """Immutable validated task contract."""
133
+
134
+ def __init__(self, raw, source_path=None):
135
+ self._raw = raw
136
+ self.source_path = source_path
137
+ self.task_id = raw["task_id"]
138
+ self.title = raw["title"]
139
+ self.status = raw["status"]
140
+ self.risk_tier = raw["risk_tier"]
141
+ self.workspace_scope = raw["workspace_scope"]
142
+ self.objective = raw["objective"]
143
+ self.worker = raw["worker"]
144
+ self.inputs = raw.get("inputs", [])
145
+ self.outputs = raw["outputs"]
146
+ self.acceptance_checks = raw["acceptance_checks"]
147
+ self.qc = raw["qc"]
148
+ self.quality_spec = raw.get("quality_spec", {})
149
+ self.quality_plan = raw.get("quality_plan")
150
+ self.components = raw.get("components", [])
151
+ self.required_mcp_servers = raw.get("required_mcp_servers", [])
152
+ self.next_action = raw.get("next_action", "preflight")
153
+
154
+ def allowed_paths(self):
155
+ """Return set of paths this contract is allowed to write to."""
156
+ return set(self.workspace_scope.get("allow", []))
157
+
158
+ def denied_paths(self):
159
+ """Return set of paths this contract is denied from writing to."""
160
+ return set(self.workspace_scope.get("deny", []))
161
+
162
+ def to_dict(self):
163
+ return dict(self._raw)
164
+
165
+ def __repr__(self):
166
+ return f"<Contract {self.task_id} status={self.status}>"
167
+
168
+
169
+ def _canonical_under(path: str, root: str) -> bool:
170
+ try:
171
+ candidate = os.path.realpath(path)
172
+ base = os.path.realpath(root)
173
+ return os.path.commonpath([candidate, base]) == base
174
+ except (OSError, ValueError):
175
+ return False
176
+
177
+
178
+ def check_path_allowed(path, allowed_paths, denied_paths, workspace_root):
179
+ """Check if path is within allow-list and outside deny-list.
180
+
181
+ Uses os.path.realpath + commonpath so symlinks, .. traversal, and
182
+ absolute escapes are resolved before the scope check.
183
+ """
184
+ if not isinstance(path, str) or not path or "\x00" in path:
185
+ return False, "invalid path"
186
+ ws = os.path.realpath(os.path.abspath(workspace_root))
187
+ raw = path if os.path.isabs(path) else os.path.join(ws, path)
188
+ abs_path = os.path.realpath(os.path.abspath(raw))
189
+
190
+ if not _canonical_under(abs_path, ws):
191
+ return False, f"path {path} escapes workspace"
192
+
193
+ for denied in denied_paths:
194
+ denied_abs = os.path.realpath(os.path.abspath(os.path.join(ws, denied)))
195
+ try:
196
+ in_deny = os.path.commonpath([abs_path, denied_abs]) == denied_abs
197
+ except ValueError:
198
+ in_deny = False
199
+ if in_deny:
200
+ return False, f"path {path} is in deny-list"
201
+
202
+ for allowed in allowed_paths:
203
+ allowed_abs = os.path.realpath(os.path.abspath(os.path.join(ws, allowed)))
204
+ try:
205
+ in_allow = os.path.commonpath([abs_path, allowed_abs]) == allowed_abs
206
+ except ValueError:
207
+ in_allow = False
208
+ if in_allow:
209
+ return True, None
210
+
211
+ return False, f"path {path} is not in allow-list"
212
+
213
+
214
+ def validate_contract(raw, workspace_root=None, strict_unknown=True):
215
+ """Validate a parsed contract dict, returning list of error messages.
216
+
217
+ Returns a list of error strings. Empty list means valid.
218
+ """
219
+ errors = []
220
+
221
+ for field, expected_type in REQUIRED_TOP_LEVEL.items():
222
+ if field not in raw:
223
+ errors.append(f"missing required field: {field}")
224
+ elif not isinstance(raw[field], expected_type):
225
+ errors.append(f"{field}: expected {expected_type.__name__}, got {type(raw[field]).__name__}")
226
+
227
+ if errors:
228
+ return errors
229
+
230
+ if raw["status"] not in VALID_STATUSES:
231
+ errors.append(f"status must be one of {sorted(VALID_STATUSES)}, got {raw['status']!r}")
232
+
233
+ if raw["risk_tier"] not in VALID_RISK_TIERS:
234
+ errors.append(f"risk_tier must be one of {sorted(VALID_RISK_TIERS)}, got {raw['risk_tier']!r}")
235
+
236
+ scope = raw["workspace_scope"]
237
+ if not isinstance(scope.get("allow"), list):
238
+ errors.append("workspace_scope.allow must be a list")
239
+ if not isinstance(scope.get("deny"), list):
240
+ errors.append("workspace_scope.deny must be a list")
241
+ if "scratch_dir" in scope and not isinstance(scope["scratch_dir"], str):
242
+ errors.append("workspace_scope.scratch_dir must be a string")
243
+
244
+ worker = raw["worker"]
245
+ if not isinstance(worker.get("model"), str):
246
+ errors.append("worker.model must be a string")
247
+ if not isinstance(worker.get("max_attempts"), int) or worker["max_attempts"] < 1:
248
+ errors.append("worker.max_attempts must be an int >= 1")
249
+
250
+ if not isinstance(raw.get("inputs", []), list):
251
+ errors.append("inputs must be a list")
252
+
253
+ for idx, out in enumerate(raw["outputs"]):
254
+ if not isinstance(out, dict) or "path" not in out:
255
+ errors.append(f"outputs[{idx}]: each output must have a 'path' field")
256
+ continue
257
+ # Zero-trust: outputs must be inside workspace_scope allow
258
+ out_path = out.get("path", "")
259
+ if isinstance(out_path, str) and out_path:
260
+ ws_for_check = workspace_root or os.path.join(os.getcwd(), "__letitloop_validate__")
261
+ allowed = raw["workspace_scope"].get("allow", [])
262
+ denied = raw["workspace_scope"].get("deny", [])
263
+ ok, _ = check_path_allowed(out_path, allowed, denied, ws_for_check)
264
+ if not ok:
265
+ errors.append(f"outputs[{idx}].path {out_path!r} is not inside workspace_scope.allow")
266
+
267
+ for idx, check in enumerate(raw["acceptance_checks"]):
268
+ if not isinstance(check, dict):
269
+ errors.append(f"acceptance_checks[{idx}]: must be an object")
270
+ continue
271
+ if "id" not in check:
272
+ errors.append(f"acceptance_checks[{idx}]: missing 'id'")
273
+ if check.get("kind") not in VALID_CHECK_KINDS:
274
+ errors.append(
275
+ f"acceptance_checks[{idx}]: kind must be one of {sorted(VALID_CHECK_KINDS)}, got {check.get('kind')!r}"
276
+ )
277
+ if check["kind"] in ("command", "content_exact", "content_regex") and "expected" not in check:
278
+ errors.append(f"acceptance_checks[{idx}]: kind={check['kind']!r} requires 'expected' field")
279
+ if check["kind"] == "min_size" and "expected" not in check:
280
+ errors.append(f"acceptance_checks[{idx}]: kind='min_size' requires 'expected' field (minimum byte count)")
281
+
282
+ qc = raw["qc"]
283
+ if not isinstance(qc.get("required"), bool):
284
+ errors.append("qc.required must be a bool")
285
+ if qc.get("lens") not in VALID_QC_LENSES:
286
+ errors.append(f"qc.lens must be one of {sorted(VALID_QC_LENSES)}, got {qc.get('lens')!r}")
287
+
288
+ qs = raw.get("quality_spec", {})
289
+ if qs:
290
+ if not isinstance(qs, dict):
291
+ errors.append("quality_spec must be a dict")
292
+ else:
293
+ if "required_sections" in qs and not isinstance(qs["required_sections"], list):
294
+ errors.append("quality_spec.required_sections must be a list")
295
+ if "quality_dimensions" in qs and not isinstance(qs["quality_dimensions"], dict):
296
+ errors.append("quality_spec.quality_dimensions must be a dict")
297
+ if "hard_failures" in qs and not isinstance(qs["hard_failures"], list):
298
+ errors.append("quality_spec.hard_failures must be a list")
299
+ if "minimum_counts" in qs and not isinstance(qs["minimum_counts"], dict):
300
+ errors.append("quality_spec.minimum_counts must be a dict")
301
+ if "minimum_score" in qs:
302
+ ms = qs["minimum_score"]
303
+ if not isinstance(ms, (int, float)) or ms < 0 or ms > 1:
304
+ errors.append("quality_spec.minimum_score must be a float between 0 and 1")
305
+ elif raw.get("qc", {}).get("required", False):
306
+ is_scratch = all(o.get("path", "").replace("\\", "/").startswith("scratch/") for o in raw.get("outputs", []))
307
+ if not is_scratch:
308
+ errors.append("qc.required is True but quality_spec is missing or empty (required for non-scratch tasks)")
309
+
310
+ if "required_mcp_servers" in raw:
311
+ rms = raw["required_mcp_servers"]
312
+ if not isinstance(rms, list):
313
+ errors.append("required_mcp_servers must be a list of strings")
314
+ else:
315
+ seen_servers = set()
316
+ for idx, srv in enumerate(rms):
317
+ if not isinstance(srv, str) or not srv.strip():
318
+ errors.append(f"required_mcp_servers[{idx}]: must be a non-empty string")
319
+ elif srv in seen_servers:
320
+ errors.append(f"required_mcp_servers[{idx}]: duplicate server {srv!r}")
321
+ else:
322
+ seen_servers.add(srv)
323
+
324
+ if strict_unknown:
325
+ known_keys = set(REQUIRED_TOP_LEVEL.keys()) | {
326
+ "next_action",
327
+ "inputs",
328
+ "quality_spec",
329
+ "quality_plan",
330
+ "components",
331
+ "required_mcp_servers",
332
+ }
333
+ extra = set(raw.keys()) - known_keys
334
+ if extra:
335
+ errors.append(f"unknown top-level keys: {sorted(extra)}")
336
+
337
+ if "quality_plan" in raw and not isinstance(raw["quality_plan"], dict):
338
+ errors.append("quality_plan must be a dict")
339
+
340
+ if "components" in raw and not isinstance(raw["components"], list):
341
+ errors.append("components must be a list")
342
+ elif "components" in raw:
343
+ seen_ids = set()
344
+ for idx, comp in enumerate(raw["components"]):
345
+ if not isinstance(comp, dict):
346
+ errors.append(f"components[{idx}]: each component must be a dict")
347
+ continue
348
+ comp_id = comp.get("id")
349
+ if not isinstance(comp_id, str) or not comp_id.strip():
350
+ errors.append(f"components[{idx}]: missing non-empty 'id'")
351
+ elif comp_id in seen_ids:
352
+ errors.append(f"components[{idx}]: duplicate component id {comp_id!r}")
353
+ else:
354
+ seen_ids.add(comp_id)
355
+ files = comp.get("files")
356
+ if not isinstance(files, list) or not files:
357
+ errors.append(f"components[{idx}]: 'files' must be a non-empty list of strings")
358
+ elif not all(isinstance(f, str) and f.strip() for f in files):
359
+ errors.append(f"components[{idx}]: every 'files' entry must be a non-empty string")
360
+ if "description" in comp and not isinstance(comp["description"], str):
361
+ errors.append(f"components[{idx}]: 'description' must be a string")
362
+
363
+ if workspace_root:
364
+ for path_entry in raw.get("inputs", []):
365
+ if isinstance(path_entry, dict) and "path" in path_entry:
366
+ ok, err = check_path_allowed(
367
+ path_entry["path"],
368
+ scope.get("allow", []),
369
+ scope.get("deny", []),
370
+ workspace_root,
371
+ )
372
+ if not ok:
373
+ errors.append(f"input path {path_entry['path']}: {err}")
374
+
375
+ for path_entry in raw["outputs"]:
376
+ if isinstance(path_entry, dict) and "path" in path_entry:
377
+ ok, err = check_path_allowed(
378
+ path_entry["path"],
379
+ scope.get("allow", []),
380
+ scope.get("deny", []),
381
+ workspace_root,
382
+ )
383
+ if not ok:
384
+ errors.append(f"output path {path_entry['path']}: {err}")
385
+
386
+ return errors
387
+
388
+
389
+ def load_contract(path, workspace_root=None):
390
+ """Load and validate a contract JSON file.
391
+
392
+ Returns (Contract, errors). If errors is non-empty, Contract may be None.
393
+ """
394
+ try:
395
+ with open(path, "r", encoding="utf-8") as f:
396
+ raw = json.load(f)
397
+ except (json.JSONDecodeError, OSError) as e:
398
+ return None, [str(e)]
399
+
400
+ errors = validate_contract(raw, workspace_root=workspace_root)
401
+ if errors:
402
+ return None, errors
403
+
404
+ return Contract(raw, source_path=path), []
@@ -0,0 +1,172 @@
1
+ """Cycle & dangling-dependency validation for contract DAGs (issue #17).
2
+
3
+ Enforced at plan creation (planner), dispatch (supervisor.execute_plan) and
4
+ resume (supervisor.resume_plan) so cyclic or broken plans never reach the
5
+ execution loop, where ``get_ready_tasks`` would silently return nothing.
6
+ """
7
+
8
+ from collections import deque
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Dict, Iterable, List, Optional
11
+
12
+ CYCLE = "cycle"
13
+ DANGLING_DEPENDENCY = "dangling_dependency"
14
+ SELF_REFERENCE = "self_reference"
15
+ DUPLICATE_TASK_ID = "duplicate_task_id"
16
+
17
+
18
+ class DagValidationError(Exception):
19
+ """Raised when a contract DAG contains cycles or broken dependencies."""
20
+
21
+ def __init__(self, message: str, issues: Optional[List["DagIssue"]] = None):
22
+ super().__init__(message)
23
+ self.issues = issues if issues is not None else []
24
+
25
+
26
+ @dataclass
27
+ class DagIssue:
28
+ kind: str # "cycle" | "dangling_dependency" | "self_reference"
29
+ task_id: str
30
+ message: str
31
+ cycle_path: List[str] = field(default_factory=list)
32
+
33
+
34
+ def _get_field(item: Any, name: str) -> Any:
35
+ if isinstance(item, dict):
36
+ return item.get(name)
37
+ return getattr(item, name, None)
38
+
39
+
40
+ def _find_cycle_in(remaining: set, deps_of: Dict[str, List[str]]) -> Optional[List[str]]:
41
+ """Iterative DFS restricted to ``remaining`` nodes; returns one concrete
42
+ cycle as [n0, n1, ..., n0], or None."""
43
+ color: Dict[str, int] = {}
44
+ parent: Dict[str, str] = {}
45
+ for root in sorted(remaining):
46
+ if color.get(root):
47
+ continue
48
+ color[root] = 1
49
+ stack = [(root, iter(deps_of.get(root, ())))]
50
+ while stack:
51
+ node, dep_iter = stack[-1]
52
+ advanced = False
53
+ for nxt in dep_iter:
54
+ if nxt not in remaining:
55
+ continue
56
+ state = color.get(nxt)
57
+ if state is None:
58
+ color[nxt] = 1
59
+ parent[nxt] = node
60
+ stack.append((nxt, iter(deps_of.get(nxt, ()))))
61
+ advanced = True
62
+ break
63
+ if state == 1:
64
+ chain = []
65
+ cur = node
66
+ while True:
67
+ chain.append(cur)
68
+ if cur == nxt:
69
+ break
70
+ cur = parent[cur]
71
+ chain.reverse()
72
+ chain.append(nxt)
73
+ return chain
74
+ if not advanced:
75
+ color[node] = 2
76
+ stack.pop()
77
+ return None
78
+
79
+
80
+ def validate_contract_dag(contracts: Iterable[Any]) -> List[DagIssue]:
81
+ """Validate task_id/depends_on structure of contracts.
82
+
83
+ Accepts dicts or objects exposing ``task_id`` / ``depends_on`` attributes.
84
+ Returns a list of DagIssue; empty list means the DAG is valid.
85
+ Cycle detection uses iterative Kahn's algorithm: nodes left after peeling
86
+ zero-in-degree nodes belong to (or depend on) a cycle.
87
+ """
88
+ items = list(contracts)
89
+ order: List[str] = []
90
+ deps_of: Dict[str, List[str]] = {}
91
+ id_set = set()
92
+ duplicate_ids: set = set()
93
+ for item in items:
94
+ tid = _get_field(item, "task_id")
95
+ if tid in id_set:
96
+ # Duplicate task_id: later entries would silently overwrite the
97
+ # first node's edges in the maps below, hiding cycles/self-deps.
98
+ duplicate_ids.add(tid)
99
+ continue
100
+ raw_deps = _get_field(item, "depends_on") or []
101
+ deps_of[tid] = list(raw_deps)
102
+ order.append(tid)
103
+ id_set.add(tid)
104
+
105
+ issues: List[DagIssue] = []
106
+ for tid in duplicate_ids:
107
+ issues.append(DagIssue(DUPLICATE_TASK_ID, tid, f"Duplicate contract task_id: {tid} (later entries ignored)"))
108
+ valid_edges: Dict[str, List[str]] = {tid: [] for tid in order}
109
+ for tid in order:
110
+ for dep in deps_of[tid]:
111
+ if dep == tid:
112
+ issues.append(DagIssue(SELF_REFERENCE, tid, f"Contract {tid} depends on itself"))
113
+ elif dep not in id_set:
114
+ issues.append(DagIssue(DANGLING_DEPENDENCY, tid, f"Contract {tid} depends on unknown task: {dep}"))
115
+ else:
116
+ valid_edges[tid].append(dep)
117
+
118
+ indegree = {tid: 0 for tid in order}
119
+ dependents: Dict[str, List[str]] = {tid: [] for tid in order}
120
+ for tid in order:
121
+ for dep in valid_edges[tid]:
122
+ indegree[tid] += 1
123
+ dependents[dep].append(tid)
124
+
125
+ queue = deque(tid for tid in order if indegree[tid] == 0)
126
+ peeled = 0
127
+ while queue:
128
+ node = queue.popleft()
129
+ peeled += 1
130
+ for m in dependents[node]:
131
+ indegree[m] -= 1
132
+ if indegree[m] == 0:
133
+ queue.append(m)
134
+
135
+ if peeled < len(order):
136
+ remaining = {tid for tid in order if indegree[tid] > 0}
137
+ path = _find_cycle_in(remaining, valid_edges)
138
+ if path:
139
+ issues.append(
140
+ DagIssue(CYCLE, path[0], f"Cycle detected among contracts: {' -> '.join(path)}", cycle_path=path)
141
+ )
142
+ else: # pragma: no cover - defensive, should not happen
143
+ issues.append(
144
+ DagIssue(
145
+ CYCLE,
146
+ sorted(remaining)[0],
147
+ f"Cycle detected involving contracts: {sorted(remaining)}",
148
+ cycle_path=[],
149
+ )
150
+ )
151
+ return issues
152
+
153
+
154
+ def format_cycle_trace(issue: DagIssue) -> str:
155
+ """Format a cycle issue as an actionable ASCII trace: 'Cycle detected: A -> B -> A'."""
156
+ path = issue.cycle_path or [issue.task_id]
157
+ return f"Cycle detected: {' -> '.join(path)}"
158
+
159
+
160
+ def format_issue(issue: DagIssue) -> str:
161
+ if issue.kind == CYCLE:
162
+ return format_cycle_trace(issue)
163
+ return issue.message
164
+
165
+
166
+ def raise_if_invalid(contracts: Iterable[Any]) -> List[DagIssue]:
167
+ """Raise DagValidationError listing every formatted issue if the DAG is invalid."""
168
+ issues = validate_contract_dag(contracts)
169
+ if issues:
170
+ message = "\n".join(format_issue(i) for i in issues)
171
+ raise DagValidationError(message, issues=issues)
172
+ return issues
@@ -0,0 +1,80 @@
1
+ """
2
+ orchestrator/elasticity_governor.py
3
+ Dynamic Elasticity & Compute Governor.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ from dataclasses import dataclass
10
+ from enum import Enum
11
+
12
+
13
+ class ComputeTier(Enum):
14
+ TIER_1_MICRO = "tier_1_micro"
15
+ TIER_2_MODERATE = "tier_2_moderate"
16
+ TIER_3_MACRO = "tier_3_macro"
17
+
18
+
19
+ @dataclass
20
+ class AllocationBudget:
21
+ tier: ComputeTier
22
+ thinking_tokens: int
23
+ speculative_workers: int
24
+ timeout_sec: int
25
+ hard_token_cap: int
26
+ justification: str
27
+
28
+
29
+ class DynamicElasticityGovernor:
30
+ """Calculates compute allocations adaptively based on AST metrics."""
31
+
32
+ @classmethod
33
+ def calculate_complexity(cls, function_source: str) -> float:
34
+ try:
35
+ tree = ast.parse(function_source)
36
+ except Exception:
37
+ return 30.0
38
+
39
+ loc = len(function_source.splitlines())
40
+ cyclomatic = 1
41
+
42
+ for node in ast.walk(tree):
43
+ if isinstance(node, (ast.If, ast.While, ast.For, ast.ExceptHandler, ast.With, ast.Assert)):
44
+ cyclomatic += 1
45
+ elif isinstance(node, ast.BoolOp):
46
+ cyclomatic += len(node.values) - 1
47
+
48
+ # Complexity formula
49
+ score = (loc * 0.35) + (cyclomatic * 1.8)
50
+ return score
51
+
52
+ @classmethod
53
+ def allocate(cls, complexity_score: float) -> AllocationBudget:
54
+ if complexity_score < 25.0:
55
+ return AllocationBudget(
56
+ tier=ComputeTier.TIER_1_MICRO,
57
+ thinking_tokens=2048,
58
+ speculative_workers=1,
59
+ timeout_sec=20,
60
+ hard_token_cap=15000,
61
+ justification=f"Micro task (score={complexity_score:.1f}): single worker @ 2k thinking tokens.",
62
+ )
63
+ elif complexity_score <= 75.0:
64
+ return AllocationBudget(
65
+ tier=ComputeTier.TIER_2_MODERATE,
66
+ thinking_tokens=8192,
67
+ speculative_workers=2,
68
+ timeout_sec=45,
69
+ hard_token_cap=30000,
70
+ justification=f"Moderate refactor (score={complexity_score:.1f}): 2 speculative swarms @ 8k thinking tokens.",
71
+ )
72
+ else:
73
+ return AllocationBudget(
74
+ tier=ComputeTier.TIER_3_MACRO,
75
+ thinking_tokens=16384,
76
+ speculative_workers=3,
77
+ timeout_sec=90,
78
+ hard_token_cap=45000,
79
+ justification=f"Macro architecture (score={complexity_score:.1f}): 3 speculative swarms @ 16k thinking tokens with early-exit.",
80
+ )