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,299 @@
1
+ """Standalone proof runner — runs phase-1 proof contracts programmatically.
2
+
3
+ Usage:
4
+ python orchestrator/fixtures/run_proofs.py [--run-dir PATH]
5
+ python orchestrator/fixtures/run_proofs.py --only HAPPY
6
+ python orchestrator/fixtures/run_proofs.py --all --json
7
+
8
+ Each proof is run through the full control loop via direct function calls.
9
+ Exit 0 if all proofs pass, exit 1 if any fail.
10
+ """
11
+
12
+ import argparse
13
+ import glob
14
+ import json
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import threading
19
+ import time
20
+ from argparse import Namespace
21
+
22
+ # Ensure the package root is on sys.path
23
+ _THIS_DIR = os.path.dirname(os.path.abspath(__file__))
24
+ _PROJECT_ROOT = os.path.abspath(os.path.join(_THIS_DIR, "..", ".."))
25
+ if _PROJECT_ROOT not in sys.path:
26
+ sys.path.insert(0, _PROJECT_ROOT)
27
+
28
+ from orchestrator.cli import ( # noqa: E402
29
+ DEFAULT_RUN_DIR,
30
+ WORKSPACE_ROOT,
31
+ cmd_create,
32
+ cmd_preflight,
33
+ cmd_qc_pass,
34
+ cmd_retry,
35
+ cmd_verify,
36
+ cmd_work,
37
+ )
38
+
39
+
40
+ def _clean_run_dir(run_dir, task_id):
41
+ path = os.path.join(run_dir, task_id)
42
+ if os.path.isdir(path):
43
+ shutil.rmtree(path)
44
+
45
+
46
+ def _state_path(run_dir, task_id):
47
+ return os.path.join(run_dir, task_id, "state.json")
48
+
49
+
50
+ def _check_state(run_dir, task_id, expected_statuses):
51
+ sp = _state_path(run_dir, task_id)
52
+ if not os.path.isfile(sp):
53
+ return False, f"state.json not found at {sp}"
54
+ with open(sp, encoding="utf-8") as f:
55
+ state = json.load(f)
56
+ actual = state["status"]
57
+ if actual in expected_statuses:
58
+ return True, actual
59
+ return False, f"expected one of {expected_statuses}, got {actual}"
60
+
61
+
62
+ def run_proof(contract_rel_path, run_dir, verbose=False, proof_name=None):
63
+ """Run a single proof contract end-to-end. Returns (pass: bool, message: str)."""
64
+ contract_path = os.path.join(WORKSPACE_ROOT, contract_rel_path)
65
+
66
+ if not os.path.isfile(contract_path):
67
+ return False, f"contract not found: {contract_path}"
68
+
69
+ # Load contract to get task_id
70
+ from orchestrator.contract import load_contract
71
+
72
+ contract_obj, errors = load_contract(contract_path, workspace_root=WORKSPACE_ROOT)
73
+ if errors or contract_obj is None:
74
+ return False, f"contract load failed: {errors}"
75
+
76
+ task_id = contract_obj.task_id
77
+ max_att = contract_obj.worker.get("max_attempts", 3)
78
+ qc_required = contract_obj.qc.get("required", False)
79
+
80
+ if not proof_name:
81
+ proof_name = os.path.basename(contract_rel_path).replace("_contract.json", "").replace("phase1_", "")
82
+
83
+ _clean_run_dir(run_dir, task_id)
84
+ total_start = time.time()
85
+
86
+ try:
87
+ # CREATE
88
+ print(f" [{proof_name}] create...", file=sys.stderr)
89
+ cmd_create(Namespace(contract=contract_rel_path))
90
+ print(" create: OK")
91
+
92
+ # PREFLIGHT
93
+ print(f" [{proof_name}] preflight...", file=sys.stderr)
94
+ cmd_preflight(Namespace(task_id=task_id))
95
+ print(" preflight: OK")
96
+
97
+ # WORK
98
+ print(f" [{proof_name}] work...", file=sys.stderr)
99
+ if verbose:
100
+ stop = threading.Event()
101
+ t0 = time.time()
102
+
103
+ def _heartbeat():
104
+ while not stop.is_set():
105
+ stop.wait(15)
106
+ if not stop.is_set():
107
+ print(f" [{proof_name}] work still running ({time.time() - t0:.0f}s)...", file=sys.stderr)
108
+
109
+ ht = threading.Thread(target=_heartbeat, daemon=True)
110
+ ht.start()
111
+ cmd_work(Namespace(task_id=task_id))
112
+ if verbose:
113
+ stop.set()
114
+ ht.join(timeout=2)
115
+ print(" work (attempt 1): OK")
116
+
117
+ # VERIFY
118
+ print(f" [{proof_name}] verify...", file=sys.stderr)
119
+ cmd_verify(Namespace(task_id=task_id))
120
+ print(" verify: OK")
121
+
122
+ # Check post-verify state
123
+ ok, msg = _check_state(run_dir, task_id, ["COMPLETE", "VERIFIED", "VERIFICATION_FAILED", "RETRY_PENDING"])
124
+ if not ok:
125
+ return False, msg
126
+
127
+ state_data = _get_state_dict(run_dir, task_id)
128
+ status = state_data["status"]
129
+
130
+ # Handle repair loop: if VERIFICATION_FAILED, retry + work + verify
131
+ if status == "VERIFICATION_FAILED":
132
+ print(f" [{proof_name}] retry...", file=sys.stderr)
133
+ if max_att <= 1:
134
+ # Will escalate on retry
135
+ cmd_retry(Namespace(task_id=task_id, approach="retry from escalation proof"))
136
+ print(" retry: OK")
137
+ ok, msg = _check_state(run_dir, task_id, ["ESCALATED", "RETRY_PENDING"])
138
+ if not ok:
139
+ return False, msg
140
+ state_data = _get_state_dict(run_dir, task_id)
141
+ if state_data["status"] == "ESCALATED":
142
+ print(" escalated as expected")
143
+ return True, "ESCALATED as expected (max_attempts=1)"
144
+ # Otherwise fall through to work again
145
+ else:
146
+ # Normal retry: record approach and work again
147
+ cmd_retry(Namespace(task_id=task_id, approach="changed approach: produce correct output"))
148
+ print(" retry: OK")
149
+ print(f" [{proof_name}] work...", file=sys.stderr)
150
+ if verbose:
151
+ stop = threading.Event()
152
+ t0 = time.time()
153
+
154
+ def _heartbeat_retry():
155
+ while not stop.is_set():
156
+ stop.wait(15)
157
+ if not stop.is_set():
158
+ print(
159
+ f" [{proof_name}] work still running ({time.time() - t0:.0f}s)...", file=sys.stderr
160
+ )
161
+
162
+ ht = threading.Thread(target=_heartbeat_retry, daemon=True)
163
+ ht.start()
164
+ cmd_work(Namespace(task_id=task_id))
165
+ if verbose:
166
+ stop.set()
167
+ ht.join(timeout=2)
168
+ print(" work (attempt 2): OK")
169
+ print(f" [{proof_name}] verify...", file=sys.stderr)
170
+ cmd_verify(Namespace(task_id=task_id))
171
+ print(" verify: OK")
172
+ ok, msg = _check_state(run_dir, task_id, ["COMPLETE", "VERIFIED", "VERIFICATION_FAILED"])
173
+ if not ok:
174
+ return False, msg
175
+ state_data = _get_state_dict(run_dir, task_id)
176
+ if state_data["status"] == "VERIFICATION_FAILED":
177
+ return False, "still VERIFICATION_FAILED after retry+work+verify"
178
+
179
+ # Check post-repair state
180
+ state_data = _get_state_dict(run_dir, task_id)
181
+ status = state_data["status"]
182
+
183
+ if qc_required and status == "VERIFIED":
184
+ print(f" [{proof_name}] qc...", file=sys.stderr)
185
+ cmd_qc_pass(Namespace(task_id=task_id, passed=True, reason="proof-runner QC pass"))
186
+ print(" qc: OK")
187
+ ok, msg = _check_state(run_dir, task_id, ["COMPLETE"])
188
+ if not ok:
189
+ return False, msg
190
+ elif not qc_required and status == "COMPLETE":
191
+ pass # already complete
192
+ elif status == "COMPLETE":
193
+ pass # already complete
194
+ else:
195
+ return False, f"unexpected final status: {status}"
196
+
197
+ elapsed_total = time.time() - total_start
198
+ print(f" [{proof_name}] total elapsed: {elapsed_total:.0f}s", file=sys.stderr)
199
+ return True, f"PASS (final: {status})"
200
+
201
+ except Exception as e:
202
+ elapsed_total = time.time() - total_start
203
+ print(f" [{proof_name}] total elapsed: {elapsed_total:.0f}s", file=sys.stderr)
204
+ return False, f"exception: {type(e).__name__}: {e}"
205
+
206
+
207
+ def _get_state_dict(run_dir, task_id):
208
+ sp = _state_path(run_dir, task_id)
209
+ with open(sp, encoding="utf-8") as f:
210
+ return json.load(f)
211
+
212
+
213
+ PROOF_NAME_MAP = {
214
+ "HAPPY": "phase1_proof_happy_path_contract.json",
215
+ "REPAIR": "phase1_proof_repair_contract.json",
216
+ "ESCALATION": "phase1_proof_escalation_contract.json",
217
+ "QC": "phase1_proof_qc_contract.json",
218
+ }
219
+
220
+
221
+ def _resolve_proof_files(only=None):
222
+ fixture_dir = os.path.join(_PROJECT_ROOT, "orchestrator", "fixtures")
223
+ if only:
224
+ fname = PROOF_NAME_MAP.get(only.upper())
225
+ if not fname:
226
+ valid = ", ".join(PROOF_NAME_MAP)
227
+ print(f"error: unknown proof '{only}'. Valid: {valid}", file=sys.stderr)
228
+ sys.exit(1)
229
+ path = os.path.join(fixture_dir, fname)
230
+ return [path] if os.path.isfile(path) else []
231
+ pattern = os.path.join(fixture_dir, "phase1_proof_*.json")
232
+ return sorted(glob.glob(pattern))
233
+
234
+
235
+ def main():
236
+ parser = argparse.ArgumentParser(description="Run phase-1 proofs")
237
+ parser.add_argument("--run-dir", default=DEFAULT_RUN_DIR, help=f"run state directory (default: {DEFAULT_RUN_DIR})")
238
+ parser.add_argument("--all", action="store_true", dest="run_all", help="run all proofs (default)")
239
+ parser.add_argument(
240
+ "--only", type=str, default=None, help="run a single proof by name: HAPPY, REPAIR, ESCALATION, QC"
241
+ )
242
+ parser.add_argument("--json", action="store_true", dest="json_output", help="output results as JSON")
243
+ parser.add_argument(
244
+ "--continue-on-fail", action="store_true", help="continue running remaining proofs after a failure"
245
+ )
246
+ parser.add_argument("--verbose", action="store_true", help="print heartbeat every 15s during long worker calls")
247
+ args = parser.parse_args()
248
+
249
+ run_dir = args.run_dir
250
+ os.makedirs(run_dir, exist_ok=True)
251
+
252
+ # Override the CLI's DEFAULT_RUN_DIR so cmd_* functions use our dir
253
+ import orchestrator.cli as cli_mod
254
+
255
+ cli_mod.DEFAULT_RUN_DIR = run_dir
256
+
257
+ proof_files = _resolve_proof_files(only=args.only)
258
+
259
+ if not proof_files:
260
+ print("No proof contracts found matching phase1_proof_*.json")
261
+ sys.exit(1)
262
+
263
+ results = []
264
+ for pf in proof_files:
265
+ rel_path = os.path.relpath(pf, WORKSPACE_ROOT)
266
+ task_name = os.path.basename(pf).replace("_contract.json", "").replace("phase1_", "")
267
+ print(f"\n{'=' * 60}")
268
+ print(f"PROOF: {task_name}")
269
+ print(f"{'=' * 60}")
270
+
271
+ passed, msg = run_proof(rel_path, run_dir, verbose=args.verbose, proof_name=task_name)
272
+ status = "PASS" if passed else "FAIL"
273
+ print(f" >>> {status}: {msg}")
274
+ results.append((task_name, status, msg))
275
+
276
+ if not passed and not args.continue_on_fail:
277
+ print("Stopping on first failure (use --continue-on-fail to override)")
278
+ break
279
+
280
+ if args.json_output:
281
+ json_results = [{"name": name, "status": status, "detail": msg} for name, status, msg in results]
282
+ print(json.dumps(json_results, indent=2, ensure_ascii=False))
283
+ else:
284
+ print(f"\n{'=' * 60}")
285
+ print("SUMMARY")
286
+ print(f"{'=' * 60}")
287
+ print(f"{'Proof':40s} {'Status':6s} Detail")
288
+ print("-" * 60)
289
+ for name, status, msg in results:
290
+ flag = "+" if status == "PASS" else "X"
291
+ print(f" [{flag}] {name:37s} {status:6s} {msg}")
292
+ print(f"\n{sum(1 for _, s, _ in results if s == 'PASS')}/{len(results)} passed")
293
+
294
+ all_pass = all(s == "PASS" for _, s, _ in results)
295
+ sys.exit(0 if all_pass else 1)
296
+
297
+
298
+ if __name__ == "__main__":
299
+ main()
@@ -0,0 +1,16 @@
1
+ import os
2
+ import sys
3
+
4
+ sys.path.insert(
5
+ 0,
6
+ os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "scratch", "phase1", "proof_happy_path"),
7
+ )
8
+
9
+ import result
10
+
11
+ assert result.normalize_company_name(" ACME GmbH ") == "acme gmbh"
12
+ assert result.normalize_company_name("Company-Outreach") == "company outreach"
13
+ assert result.normalize_company_name("Enterprise__System") == "enterprise system"
14
+ assert result.normalize_company_name("A B") == "a b"
15
+
16
+ print("normalize_company_name: OK")
@@ -0,0 +1,239 @@
1
+ """Contract generator: decomposes high-level goals into executable contracts."""
2
+
3
+ import json
4
+ import os
5
+ import sys
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from .contract import requires_semantic_qc, validate_contract
9
+ from .exceptions import PlannerError
10
+ from .goal import Goal, Plan
11
+ from .models import ModelRegistry
12
+ from .plan_quality import check_plan_quality, plan_is_safe
13
+ from .planner import _pick_checks, _pick_worker, decompose_goal
14
+
15
+ GENERATED_DIR_NAME = os.path.join("orchestrator", "fixtures", "generated")
16
+
17
+ HYBRID_MODEL = ModelRegistry.hybrid()
18
+ WORKER_MODEL = ModelRegistry.default_worker()
19
+
20
+
21
+ def _get_scope(goal: Goal) -> Dict[str, List[str]]:
22
+ constraints = goal.constraints
23
+ if "workspace_scope" in constraints and isinstance(constraints["workspace_scope"], dict):
24
+ scope = constraints["workspace_scope"]
25
+ return {
26
+ "allow": list(scope.get("allow", ["scratch/"])),
27
+ "deny": list(scope.get("deny", [])),
28
+ }
29
+ allow = constraints.get("allow", ["scratch/"])
30
+ deny = constraints.get("deny", [])
31
+ return {"allow": list(allow), "deny": list(deny)}
32
+
33
+
34
+ def _make_contract_dict(
35
+ task_id,
36
+ title,
37
+ task_type,
38
+ objective,
39
+ outputs,
40
+ depends_on,
41
+ scope,
42
+ acceptance_checks,
43
+ risk_tier="auto",
44
+ quality_spec=None,
45
+ qc_explicit=None,
46
+ ):
47
+ worker = _pick_worker(task_type)
48
+ worker["hybrid_critic_model"] = WORKER_MODEL
49
+ worker["hybrid_max_repair_turns"] = 3
50
+ worker["hybrid_max_tokens"] = 32000
51
+ worker["hybrid_max_cost_usd"] = 0.30
52
+ worker["hybrid_max_identical_verdicts"] = 2
53
+ qc_semantic = requires_semantic_qc(risk_tier, outputs, acceptance_checks, quality_spec)
54
+ if qc_explicit is True:
55
+ qc_required = True
56
+ elif qc_explicit is False:
57
+ qc_required = qc_semantic
58
+ else:
59
+ qc_required = qc_semantic
60
+ return {
61
+ "task_id": task_id,
62
+ "title": title,
63
+ "status": "DRAFTED",
64
+ "risk_tier": risk_tier,
65
+ "workspace_scope": scope,
66
+ "objective": objective,
67
+ "worker": worker,
68
+ "inputs": [],
69
+ "outputs": outputs,
70
+ "acceptance_checks": acceptance_checks,
71
+ "qc": {"required": qc_required, "lens": "code_correctness"},
72
+ "quality_spec": quality_spec or {},
73
+ }
74
+
75
+
76
+ def generate_contracts(
77
+ goal: Goal,
78
+ workspace_root: str,
79
+ failure_context: str = "",
80
+ prefs: Optional[Dict[str, Any]] = None,
81
+ ) -> Plan:
82
+ """Generate a Plan of 1-3 contracts from a Goal and write JSONs to fixtures/generated/.
83
+
84
+ If failure_context is provided (formatted feedback string), it is attached
85
+ to the goal's constraints for downstream planner visibility.
86
+ Uses hybrid: workers for implementation/code_generation tasks.
87
+ """
88
+ if failure_context:
89
+ existing = goal.constraints.get("failure_context", "")
90
+ goal.constraints["failure_context"] = f"{existing}\n{failure_context}" if existing else failure_context
91
+ scope = _get_scope(goal)
92
+ if not scope["allow"]:
93
+ scope["allow"] = [workspace_root]
94
+ out_dir = os.path.join(workspace_root, GENERATED_DIR_NAME)
95
+ os.makedirs(out_dir, exist_ok=True)
96
+
97
+ has_explicit_subtasks = ("subtasks" in goal.constraints and isinstance(goal.constraints["subtasks"], list)) or (
98
+ "tasks" in goal.constraints and isinstance(goal.constraints["tasks"], list)
99
+ )
100
+
101
+ if not has_explicit_subtasks:
102
+ try:
103
+ return decompose_goal(goal, workspace_root, prefs=prefs)
104
+ except PlannerError as e:
105
+ print(f"[generator] Planner decomposition failed: {e}", file=sys.stderr)
106
+
107
+ subtask_specs = []
108
+
109
+ if "subtasks" in goal.constraints and isinstance(goal.constraints["subtasks"], list):
110
+ subtask_specs = goal.constraints["subtasks"]
111
+ elif "tasks" in goal.constraints and isinstance(goal.constraints["tasks"], list):
112
+ subtask_specs = goal.constraints["tasks"]
113
+ else:
114
+ desc_lower = goal.description.lower()
115
+ title_lower = goal.title.lower()
116
+
117
+ if (
118
+ "step 1" in desc_lower
119
+ or "two-step" in title_lower
120
+ or "two step" in title_lower
121
+ or "validates" in desc_lower
122
+ ):
123
+ out1 = f"scratch/phase2/{goal.goal_id}_step1.txt"
124
+ out2 = f"scratch/phase2/{goal.goal_id}_step2.txt"
125
+ allow_paths = scope["allow"]
126
+ if allow_paths and allow_paths[0] != "scratch/":
127
+ base_dir = allow_paths[0].rstrip("/\\")
128
+ out1 = f"{base_dir}/step1.txt"
129
+ out2 = f"{base_dir}/step2.txt"
130
+
131
+ subtask_specs = [
132
+ {
133
+ "task_id": f"{goal.goal_id}-step-1",
134
+ "title": f"{goal.title} - Step 1 (Implementation)",
135
+ "type": "implementation",
136
+ "objective": "Execute step 1 implementation",
137
+ "output_path": out1,
138
+ "depends_on": [],
139
+ },
140
+ {
141
+ "task_id": f"{goal.goal_id}-step-2",
142
+ "title": f"{goal.title} - Step 2 (Verification)",
143
+ "type": "verification",
144
+ "objective": "Verify step 1 output",
145
+ "output_path": out2,
146
+ "depends_on": [f"{goal.goal_id}-step-1"],
147
+ },
148
+ ]
149
+ elif "research" in desc_lower or "recon" in desc_lower:
150
+ out = f"scratch/phase2/{goal.goal_id}_recon.txt"
151
+ subtask_specs = [
152
+ {
153
+ "task_id": f"{goal.goal_id}-recon",
154
+ "title": f"{goal.title} - Research",
155
+ "type": "research",
156
+ "objective": goal.description,
157
+ "output_path": out,
158
+ "depends_on": [],
159
+ }
160
+ ]
161
+ else:
162
+ out = f"scratch/phase2/{goal.goal_id}_output.txt"
163
+ subtask_specs = [
164
+ {
165
+ "task_id": f"{goal.goal_id}-task-1",
166
+ "title": goal.title,
167
+ "type": "implementation",
168
+ "objective": goal.description,
169
+ "output_path": out,
170
+ "depends_on": [],
171
+ }
172
+ ]
173
+
174
+ if len(subtask_specs) > 3:
175
+ print(f"[generator] Warning: truncating {len(subtask_specs)} subtasks to 3", file=sys.stderr)
176
+ subtask_specs = subtask_specs[:3]
177
+ contracts_plan_meta = []
178
+
179
+ for idx, spec in enumerate(subtask_specs):
180
+ task_id = spec.get("task_id", f"{goal.goal_id}-step-{idx + 1}")
181
+ title = spec.get("title", f"{goal.title} Step {idx + 1}")
182
+ task_type = spec.get("type", "implementation")
183
+ objective = spec.get("objective", goal.description)
184
+ depends_on = spec.get("depends_on", [])
185
+
186
+ out_path = spec.get("output_path", spec.get("path"))
187
+ if not out_path:
188
+ allow_base = scope["allow"][0].rstrip("/\\") if scope["allow"] else "scratch"
189
+ out_path = f"{allow_base}/{task_id}_out.txt"
190
+
191
+ outputs = spec.get("outputs", [{"path": out_path}])
192
+ main_out = outputs[0]["path"] if outputs else out_path
193
+
194
+ if "acceptance_checks" in spec and spec["acceptance_checks"]:
195
+ acceptance_checks = spec["acceptance_checks"]
196
+ else:
197
+ acceptance_checks = _pick_checks(task_type, main_out)
198
+
199
+ contract_dict = _make_contract_dict(
200
+ task_id=task_id,
201
+ title=title,
202
+ task_type=task_type,
203
+ objective=objective,
204
+ outputs=outputs,
205
+ depends_on=depends_on,
206
+ scope=scope,
207
+ acceptance_checks=acceptance_checks,
208
+ risk_tier=goal.constraints.get("risk_tier", "auto"),
209
+ )
210
+
211
+ errors = validate_contract(contract_dict, workspace_root=workspace_root)
212
+ if errors:
213
+ raise ValueError(f"Generated contract {task_id} failed validation: {errors}")
214
+
215
+ contract_file_path = os.path.join(out_dir, f"{task_id}.json")
216
+ with open(contract_file_path, "w", encoding="utf-8") as f:
217
+ json.dump(contract_dict, f, indent=2, ensure_ascii=False)
218
+
219
+ try:
220
+ rel_contract_path = os.path.relpath(contract_file_path, workspace_root)
221
+ except ValueError:
222
+ rel_contract_path = os.path.abspath(contract_file_path)
223
+
224
+ contracts_plan_meta.append(
225
+ {
226
+ "task_id": task_id,
227
+ "depends_on": depends_on,
228
+ "status": "DRAFTED",
229
+ "contract_path": rel_contract_path,
230
+ "contract": contract_dict,
231
+ }
232
+ )
233
+
234
+ plan = Plan(goal_id=goal.goal_id, contracts=contracts_plan_meta)
235
+ quality_warnings = check_plan_quality(plan, workspace_root=workspace_root)
236
+ if not plan_is_safe(quality_warnings):
237
+ error_msgs = [w.message for w in quality_warnings if w.severity == "error"]
238
+ raise ValueError(f"Generated plan has quality errors: {'; '.join(error_msgs)}")
239
+ return plan