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/cli.py ADDED
@@ -0,0 +1,1971 @@
1
+ """CLI for Phase-1 durable macro-task control loop.
2
+
3
+ Commands:
4
+ create Validate a contract JSON and create initial state
5
+ preflight Run preflight checks on a drafted/blocked task
6
+ work Invoke worker on a ready/retry_pending task
7
+ verify Run verification checks on a worked task
8
+ resume Show current state and next legal action
9
+ handoff Generate session handoff from current state
10
+ status Show task state summary
11
+ """
12
+
13
+ import argparse
14
+ import contextlib
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import subprocess
19
+ import sys
20
+ from importlib.metadata import PackageNotFoundError
21
+ from importlib.metadata import version as package_version
22
+ from typing import Optional
23
+
24
+ from .approval import format_approval_reasons, requires_approval
25
+ from .contract import load_contract
26
+ from .generator import generate_contracts
27
+ from .goal import Goal, Plan
28
+ from .handoff import build_handoff
29
+ from .plan_preview import render_plan_preview, write_plan_preview
30
+ from .preferences import apply_preferences_to_goal, collect_preferences
31
+ from .preflight import run_preflight
32
+ from .schemas import get_schema
33
+ from .state import (
34
+ IllegalTransitionError,
35
+ create_initial_state,
36
+ load_state,
37
+ save_state,
38
+ )
39
+ from .supervisor import Supervisor
40
+ from .verifier import run_verification
41
+ from .worker import run_worker
42
+
43
+
44
+ def _git_sha():
45
+ """Return the current short Git commit SHA, if available."""
46
+ try:
47
+ result = subprocess.run(
48
+ ["git", "rev-parse", "--short", "HEAD"],
49
+ cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
50
+ capture_output=True,
51
+ text=True,
52
+ check=True,
53
+ )
54
+ sha = result.stdout.strip()
55
+ return sha or None
56
+ except (OSError, subprocess.CalledProcessError):
57
+ return None
58
+
59
+
60
+ def _version_string():
61
+ """Return the package version with the current Git SHA when available."""
62
+ try:
63
+ version = package_version("letitloop")
64
+ except PackageNotFoundError:
65
+ from . import __version__
66
+
67
+ version = __version__
68
+
69
+ sha = _git_sha()
70
+ if sha:
71
+ return f"letitloop {version} ({sha})"
72
+ return f"letitloop {version}"
73
+
74
+
75
+ WORKSPACE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
76
+ DEFAULT_RUN_DIR = os.environ.get("LIL_RUN_DIR", os.path.join(WORKSPACE_ROOT, "scratch", "orchestrator_runs"))
77
+ IMPOSSIBILITY_LOG = os.path.join(WORKSPACE_ROOT, "scratch", "impossibility_theorems.log")
78
+
79
+
80
+ def _run_dir(task_id):
81
+ return os.path.join(DEFAULT_RUN_DIR, task_id)
82
+
83
+
84
+ def _plan_digest(goal_dict: dict, plan_dict: dict) -> str:
85
+ """SHA-256 over canonical goal+plan JSON to bind approvals to content."""
86
+ canonical = json.dumps(
87
+ {"goal": goal_dict, "plan": plan_dict},
88
+ sort_keys=True,
89
+ separators=(",", ":"),
90
+ ensure_ascii=False,
91
+ )
92
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
93
+
94
+
95
+ def _state_path(task_id):
96
+ return os.path.join(_run_dir(task_id), "state.json")
97
+
98
+
99
+ def _get_state(task_id):
100
+ sp = _state_path(task_id)
101
+ if not os.path.isfile(sp):
102
+ print(f"error: no state found for task {task_id} at {sp}", file=sys.stderr)
103
+ sys.exit(1)
104
+ return load_state(sp)
105
+
106
+
107
+ def _save(state):
108
+ save_state(state, _state_path(state.task_id))
109
+
110
+
111
+ def _print_json(obj):
112
+ print(json.dumps(obj, indent=2, ensure_ascii=False))
113
+
114
+
115
+ def cmd_create(args):
116
+ contract_path = os.path.join(WORKSPACE_ROOT, args.contract)
117
+ contract, errors = load_contract(contract_path, workspace_root=WORKSPACE_ROOT)
118
+ if errors:
119
+ print("Contract validation FAILED:", file=sys.stderr)
120
+ for e in errors:
121
+ print(f" - {e}", file=sys.stderr)
122
+ sys.exit(1)
123
+
124
+ state = create_initial_state(contract.task_id, journal_dir=_run_dir(contract.task_id))
125
+ state.patch_data({"contract_path": contract_path})
126
+
127
+ contract_out = os.path.join(_run_dir(contract.task_id), "contract.json")
128
+ os.makedirs(os.path.dirname(contract_out), exist_ok=True)
129
+ with open(contract_out, "w", encoding="utf-8") as f:
130
+ json.dump(contract.to_dict(), f, indent=2, ensure_ascii=False)
131
+
132
+ _save(state)
133
+ print(f"Task {contract.task_id} created (state: {state.status})")
134
+ print(f" State: {_state_path(contract.task_id)}")
135
+ print(f" Contract: {contract_out}")
136
+
137
+
138
+ def cmd_preflight(args):
139
+ state = _get_state(args.task_id)
140
+ contract, _ = load_contract(state.data.get("contract_path", ""), workspace_root=WORKSPACE_ROOT)
141
+ if contract is None:
142
+ print("error: contract not found in state", file=sys.stderr)
143
+ sys.exit(1)
144
+
145
+ run_dir = _run_dir(args.task_id)
146
+ try:
147
+ state.transition("PREFLIGHT_RUNNING", reason="preflight started")
148
+ _save(state)
149
+ except IllegalTransitionError as e:
150
+ print(f"error: {e}", file=sys.stderr)
151
+ sys.exit(1)
152
+
153
+ print(f"[orchestrator] preflight: running checks for {args.task_id}", file=sys.stderr)
154
+ passed, results, evidence_path = run_preflight(contract, WORKSPACE_ROOT, run_dir)
155
+ print(f"[orchestrator] preflight: complete for {args.task_id}", file=sys.stderr)
156
+
157
+ if evidence_path:
158
+ state.add_evidence("preflight", evidence_path)
159
+
160
+ for r in results:
161
+ status = "PASS" if r["passed"] else "FAIL"
162
+ print(f" [{status}] {r['check_id']}: {r['message']}")
163
+
164
+ if passed:
165
+ state.transition("READY", reason="all preflight checks passed", evidence_path=evidence_path)
166
+ else:
167
+ state.transition("PREFLIGHT_FAILED", reason="one or more preflight checks failed", evidence_path=evidence_path)
168
+ state.transition("BLOCKED", reason="preflight failures block execution", evidence_path=evidence_path)
169
+
170
+ _save(state)
171
+ print(f"Task {args.task_id} now: {state.status}")
172
+
173
+
174
+ def cmd_work(args):
175
+ state = _get_state(args.task_id)
176
+ contract, _ = load_contract(state.data.get("contract_path", ""), workspace_root=WORKSPACE_ROOT)
177
+ if contract is None:
178
+ print("error: contract not found", file=sys.stderr)
179
+ sys.exit(1)
180
+
181
+ run_dir = _run_dir(args.task_id)
182
+ try:
183
+ state.transition("WORKING", reason="worker invocation started")
184
+ _save(state)
185
+ except IllegalTransitionError:
186
+ print(f"error: cannot work from state {state.status}", file=sys.stderr)
187
+ legal = sorted(state.legal_transitions())
188
+ print(f" legal next states: {legal}", file=sys.stderr)
189
+ if "RETRY_PENDING" in legal or "READY" in legal:
190
+ print(" suggest: ensure task is in READY or RETRY_PENDING state before running work", file=sys.stderr)
191
+ sys.exit(1)
192
+
193
+ max_attempts = contract.worker.get("max_attempts", 3)
194
+ if state.attempt > max_attempts:
195
+ state.transition("ESCALATED", reason=f"attempt {state.attempt} exceeds max {max_attempts}")
196
+ _save(state)
197
+ _write_impossibility(contract, state)
198
+ print(f"Task {args.task_id} ESCALATED: all {max_attempts} attempts exhausted")
199
+ return
200
+
201
+ previous_failures = None
202
+ changed_approach = None
203
+ if state.worker_results:
204
+ previous_failures = [
205
+ {"message": r.get("stderr", "") or f"exit code {r.get('exit_code', '?')}"}
206
+ for r in state.worker_results[-3:]
207
+ ]
208
+ if state.changed_approaches:
209
+ changed_approach = state.changed_approaches[-1]
210
+
211
+ print(f"[orchestrator] work: starting worker for {args.task_id}", file=sys.stderr)
212
+ result = run_worker(
213
+ contract, WORKSPACE_ROOT, run_dir, previous_failures=previous_failures, changed_approach=changed_approach
214
+ )
215
+ print("[orchestrator] work: worker returned", file=sys.stderr)
216
+
217
+ state.add_worker_result(result)
218
+ state.add_evidence(f"worker_attempt_{state.attempt}", os.path.join(run_dir, "worker_output.log"))
219
+
220
+ kind = "initial" if state.attempt == 1 else "retry"
221
+ state.transition("VERIFYING", reason=f"worker {kind} attempt {state.attempt} complete (exit={result['exit_code']})")
222
+ _save(state)
223
+
224
+ print(f"Worker attempt {state.attempt} finished (exit={result['exit_code']}, {result['elapsed_sec']:.1f}s)")
225
+ print(f"Task {args.task_id} now: {state.status}")
226
+
227
+
228
+ def cmd_verify(args):
229
+ state = _get_state(args.task_id)
230
+ contract, _ = load_contract(state.data.get("contract_path", ""), workspace_root=WORKSPACE_ROOT)
231
+ if contract is None:
232
+ print("error: contract not found", file=sys.stderr)
233
+ sys.exit(1)
234
+
235
+ run_dir = _run_dir(args.task_id)
236
+ try:
237
+ state.transition("VERIFYING", reason="verification started")
238
+ _save(state)
239
+ except IllegalTransitionError:
240
+ if state.status != "VERIFYING":
241
+ print(f"error: cannot verify from state {state.status}", file=sys.stderr)
242
+ legal = sorted(state.legal_transitions())
243
+ print(f" legal next states: {legal}", file=sys.stderr)
244
+ print(" suggest: verify requires VERIFYING state", file=sys.stderr)
245
+ sys.exit(1)
246
+
247
+ print(f"[orchestrator] verify: running checks for {args.task_id}", file=sys.stderr)
248
+ all_passed, results, evidence_path = run_verification(contract, WORKSPACE_ROOT, run_dir)
249
+ print(f"[orchestrator] verify: checks complete for {args.task_id}", file=sys.stderr)
250
+
251
+ if evidence_path:
252
+ state.add_evidence("verification", evidence_path)
253
+
254
+ for r in results:
255
+ status = "PASS" if r.passed else "FAIL"
256
+ print(f" [{status}] {r.check_id}: {r.message}")
257
+
258
+ if all_passed:
259
+ qc_required = contract.qc.get("required", False)
260
+ state.transition("VERIFIED", reason="all checks passed")
261
+ if not qc_required:
262
+ state.transition("COMPLETE", reason="all checks passed, no QC required")
263
+ else:
264
+ state.transition("VERIFICATION_FAILED", reason="one or more checks failed", evidence_path=evidence_path)
265
+
266
+ _save(state)
267
+ print(
268
+ f"Task {args.task_id} now: {state.status} ({state.attempt}/{contract.worker.get('max_attempts', 3)} attempts)"
269
+ )
270
+
271
+
272
+ def cmd_retry(args):
273
+ state = _get_state(args.task_id)
274
+ contract, _ = load_contract(state.data.get("contract_path", ""), workspace_root=WORKSPACE_ROOT)
275
+ if contract is None:
276
+ print("error: contract not found", file=sys.stderr)
277
+ sys.exit(1)
278
+
279
+ max_attempts = contract.worker.get("max_attempts", 3)
280
+ if state.status not in ("RETRY_PENDING", "VERIFICATION_FAILED", "QC_REJECTED", "QC_CONDITIONAL_PASS"):
281
+ print(f"error: cannot retry from state {state.status}", file=sys.stderr)
282
+ print(
283
+ " legal retry source states: VERIFICATION_FAILED, QC_REJECTED, QC_CONDITIONAL_PASS, RETRY_PENDING",
284
+ file=sys.stderr,
285
+ )
286
+ print(f" current state transitions: {sorted(state.legal_transitions())}", file=sys.stderr)
287
+ sys.exit(1)
288
+
289
+ state.increment_attempt()
290
+ if args.approach:
291
+ state.record_approach(args.approach)
292
+
293
+ if state.attempt > max_attempts:
294
+ if state.status == "VERIFICATION_FAILED":
295
+ state.transition("RETRY_PENDING", reason=f"retrying as attempt {state.attempt}")
296
+ state.transition("ESCALATED", reason=f"max attempts ({max_attempts}) reached, no further retries")
297
+ _save(state)
298
+ _write_impossibility(contract, state)
299
+ print(f"Task {args.task_id} ESCALATED: all {max_attempts} attempts exhausted")
300
+ return
301
+
302
+ if state.status == "VERIFICATION_FAILED":
303
+ state.transition("RETRY_PENDING", reason=f"verification failed, retrying as attempt {state.attempt}")
304
+ elif state.status == "QC_REJECTED":
305
+ state.transition("RETRY_PENDING", reason=f"QC rejected, retrying as attempt {state.attempt}")
306
+ elif state.status == "QC_CONDITIONAL_PASS":
307
+ state.transition("RETRY_PENDING", reason=f"QC conditional pass, retrying as attempt {state.attempt}")
308
+
309
+ _save(state)
310
+ print(f"Task {args.task_id} retrying as attempt {state.attempt} (state: {state.status})")
311
+
312
+
313
+ def cmd_qc_pass(args):
314
+ state = _get_state(args.task_id)
315
+ if state.status == "VERIFIED":
316
+ state.transition("QC_RUNNING", reason="QC review started")
317
+ elif state.status in ("QC_RUNNING", "QC_REJECTED", "QC_CONDITIONAL_PASS"):
318
+ pass
319
+ else:
320
+ print(f"error: cannot start QC from state {state.status}", file=sys.stderr)
321
+ print(" expected states: VERIFIED, QC_RUNNING, QC_REJECTED, QC_CONDITIONAL_PASS", file=sys.stderr)
322
+ sys.exit(1)
323
+
324
+ if args.passed:
325
+ state.transition("QC_PASSED", reason=args.reason or "QC review passed")
326
+ state.transition("COMPLETE", reason="all checks passed, QC passed")
327
+ else:
328
+ state.transition("QC_REJECTED", reason=args.reason or "QC review failed")
329
+
330
+ _save(state)
331
+ print(f"Task {args.task_id} now: {state.status}")
332
+
333
+
334
+ def cmd_resume(args):
335
+ state = _get_state(args.task_id)
336
+ if state.is_terminal():
337
+ print(f"Task {args.task_id} is terminal ({state.status}); no resume possible")
338
+ return
339
+
340
+ print(f"Task: {state.task_id}")
341
+ print(f"Status: {state.status}")
342
+ print(f"Attempt: {state.attempt}")
343
+ print(f"Events: {len(state.events)} total")
344
+ print(f"Worker runs: {len(state.worker_results)}")
345
+ print(f"Next legal actions: {sorted(state.legal_transitions())}")
346
+ print(f"Suggest: {_suggest_next_action(state)}")
347
+
348
+
349
+ def cmd_handoff(args):
350
+ state = _get_state(args.task_id)
351
+ run_dir = _run_dir(args.task_id)
352
+ handoff = build_handoff(state, run_dir)
353
+ _print_json(handoff)
354
+
355
+
356
+ def cmd_status(args):
357
+ state = _get_state(args.task_id)
358
+ _print_json(state.to_dict())
359
+
360
+
361
+ def cmd_doctor(args):
362
+ if not args.task_id:
363
+ from .env_doctor import run_env_doctor
364
+
365
+ sys.exit(run_env_doctor(check_connectivity=getattr(args, "probe", False)))
366
+
367
+ sp = _state_path(args.task_id)
368
+ if not os.path.isfile(sp):
369
+ print(f"error: no state found for task {args.task_id} at {sp}", file=sys.stderr)
370
+ sys.exit(1)
371
+ state = load_state(sp)
372
+
373
+ contract, _ = load_contract(state.data.get("contract_path", ""), workspace_root=WORKSPACE_ROOT)
374
+
375
+ print(f"Task: {state.task_id}")
376
+ print(f"Status: {state.status}")
377
+ print(f"Terminal: {state.is_terminal()}")
378
+ print(f"Attempt: {state.attempt}")
379
+ max_att = contract.worker.get("max_attempts", 3) if contract else "?"
380
+ print(f"Max attempts: {max_att}")
381
+ print(f"Events: {len(state.events)}")
382
+ print(f"Worker runs: {len(state.worker_results)}")
383
+ if state.worker_results:
384
+ last = state.worker_results[-1]
385
+ print(f"Last worker exit: {last.get('exit_code', '?')}")
386
+ print(f"Last worker elapsed: {last.get('elapsed_sec', '?')}s")
387
+
388
+ run_dir = _run_dir(args.task_id)
389
+ evidence_files = {
390
+ "preflight_evidence.json": os.path.join(run_dir, "preflight_evidence.json"),
391
+ "worker_output.log": os.path.join(run_dir, "worker_output.log"),
392
+ "verification_evidence.json": os.path.join(run_dir, "verification_evidence.json"),
393
+ "handoff.json": os.path.join(run_dir, "handoff.json"),
394
+ }
395
+ print("Evidence files:")
396
+ for label, fpath in evidence_files.items():
397
+ present = "present" if os.path.isfile(fpath) else "missing"
398
+ print(f" {label}: {present}")
399
+
400
+ contract_present = os.path.isfile(os.path.join(run_dir, "contract.json"))
401
+ print(f"Contract file: {'present' if contract_present else 'missing'}")
402
+
403
+ legal = sorted(state.legal_transitions())
404
+ print(f"Next actions: {legal}")
405
+ print(f"Suggest: {_suggest_next_action(state)}")
406
+
407
+ imp_exists = os.path.isfile(IMPOSSIBILITY_LOG)
408
+ has_imp = False
409
+ if imp_exists:
410
+ with open(IMPOSSIBILITY_LOG, encoding="utf-8") as f:
411
+ has_imp = args.task_id in f.read()
412
+ print(f"Impossibility log entries for this task: {has_imp}")
413
+
414
+ blocked = state.status == "BLOCKED"
415
+ print(f"Blocked: {blocked}")
416
+ print(f"In progress: {state.status in ('WORKING', 'VERIFYING')}")
417
+ print(f"Run dir: {run_dir}")
418
+
419
+ sys.exit(0)
420
+
421
+
422
+ def _suggest_next_action(state):
423
+ transitions = state.legal_transitions()
424
+ if "PREFLIGHT_RUNNING" in transitions:
425
+ return "orchestrator preflight <task_id>"
426
+ if "WORKING" in transitions:
427
+ return "orchestrator work <task_id>"
428
+ if "VERIFYING" in transitions:
429
+ return "orchestrator verify <task_id>"
430
+ if "QC_RUNNING" in transitions:
431
+ return "orchestrator qc_pass <task_id> --passed/--rejected"
432
+ return "orchestrator resume <task_id>"
433
+
434
+
435
+ def _write_impossibility(contract, state):
436
+ entry = {
437
+ "timestamp": __import__("datetime").datetime.now().isoformat(),
438
+ "task_id": contract.task_id,
439
+ "title": contract.title,
440
+ "objective": contract.objective,
441
+ "max_attempts": contract.worker.get("max_attempts", 3),
442
+ "attempts_made": state.attempt,
443
+ "worker_results": [
444
+ {
445
+ "exit_code": r.get("exit_code"),
446
+ "elapsed_sec": r.get("elapsed_sec"),
447
+ "stderr_preview": r.get("stderr", "")[:500],
448
+ }
449
+ for r in state.worker_results
450
+ ],
451
+ "rejected_approaches": list(state.changed_approaches),
452
+ "events": [{"from": e["from"], "to": e["to"], "reason": e["reason"]} for e in state.events],
453
+ }
454
+ os.makedirs(os.path.dirname(IMPOSSIBILITY_LOG), exist_ok=True)
455
+ with open(IMPOSSIBILITY_LOG, "a", encoding="utf-8") as f:
456
+ f.write(json.dumps(entry, indent=2, ensure_ascii=False))
457
+ f.write("\n---\n")
458
+
459
+
460
+ def _latest_goal_id(status_filter: Optional[str] = None) -> Optional[str]:
461
+ """Find the most recently updated goal directory in DEFAULT_RUN_DIR."""
462
+ if not os.path.isdir(DEFAULT_RUN_DIR):
463
+ return None
464
+ candidates = []
465
+ for d in os.listdir(DEFAULT_RUN_DIR):
466
+ full = os.path.join(DEFAULT_RUN_DIR, d)
467
+ if os.path.isdir(full) and os.path.isfile(os.path.join(full, "goal.json")):
468
+ mtime = os.path.getmtime(full)
469
+ candidates.append((mtime, d))
470
+ if not candidates:
471
+ return None
472
+ candidates.sort(key=lambda x: x[0], reverse=True)
473
+ return candidates[0][1]
474
+
475
+
476
+ def cmd_propose(args):
477
+ """Propose a plan for a natural-language task: goal → plan → preview → approval check."""
478
+ prompt = args.prompt
479
+ goal_id = args.goal_id or prompt.lower().replace(" ", "-")[:40]
480
+
481
+ # Create goal
482
+ description = args.description or prompt
483
+ constraints = {}
484
+ if args.constraints:
485
+ try:
486
+ constraints = json.loads(args.constraints)
487
+ except json.JSONDecodeError as e:
488
+ print(f"error: invalid constraints JSON: {e}", file=sys.stderr)
489
+ sys.exit(1)
490
+
491
+ goal = Goal(
492
+ goal_id=goal_id,
493
+ title=args.title or prompt,
494
+ description=description,
495
+ constraints=constraints,
496
+ )
497
+
498
+ # Collect preferences
499
+ prefs = collect_preferences(WORKSPACE_ROOT, user_hints=constraints.get("preferences"))
500
+ goal = Goal.from_dict(apply_preferences_to_goal(goal.to_dict(), prefs))
501
+
502
+ # Generate plan
503
+ try:
504
+ plan = generate_contracts(goal, workspace_root=WORKSPACE_ROOT, prefs=prefs)
505
+ except Exception as e:
506
+ print(f"error: plan generation failed: {e}", file=sys.stderr)
507
+ sys.exit(1)
508
+
509
+ # Save goal and plan after plan generation so on-disk state matches the
510
+ # digest computed below (generate_contracts mutates goal._preferences)
511
+ run_dir = _run_dir(goal_id)
512
+ os.makedirs(run_dir, exist_ok=True)
513
+ goal_dict = goal.to_dict()
514
+ goal_path = os.path.join(run_dir, "goal.json")
515
+ with open(goal_path, "w", encoding="utf-8") as f:
516
+ json.dump(goal_dict, f, indent=2, ensure_ascii=False)
517
+
518
+ plan_dict = plan.to_dict()
519
+ plan_path = os.path.join(run_dir, "plan.json")
520
+ with open(plan_path, "w", encoding="utf-8") as f:
521
+ json.dump(plan_dict, f, indent=2, ensure_ascii=False)
522
+
523
+ # Approval check
524
+ approval = requires_approval(plan, prefs=prefs)
525
+
526
+ # Write approval marker
527
+ approval_path = os.path.join(run_dir, "approval.json")
528
+ approval_data = {
529
+ "status": "pending" if approval["requires_approval"] else "approved",
530
+ "requires_approval": approval["requires_approval"],
531
+ "reasons": approval["reasons"],
532
+ "plan_digest": _plan_digest(goal_dict, plan_dict),
533
+ }
534
+ with open(approval_path, "w", encoding="utf-8") as f:
535
+ json.dump(approval_data, f, indent=2, ensure_ascii=False)
536
+
537
+ # Write plan preview
538
+ preview_path = os.path.join(run_dir, "plan_preview.md")
539
+ write_plan_preview(plan, preview_path, goal_dict=goal.to_dict(), prefs=prefs)
540
+
541
+ # Output summary
542
+ print(f"Goal: {goal_id}")
543
+ print(" Status: created")
544
+ print(f" Goal file: {goal_path}")
545
+ print(f" Plan file: {plan_path}")
546
+ print(f" Preview: {preview_path}")
547
+ print()
548
+
549
+ auto_run = getattr(args, "run", False) or getattr(args, "yes", False)
550
+
551
+ if approval["requires_approval"]:
552
+ if auto_run:
553
+ print("Auto-approving proposed plan (--run / -y specified)...")
554
+ approval_data["status"] = "approved"
555
+ with open(approval_path, "w", encoding="utf-8") as f:
556
+ json.dump(approval_data, f, indent=2, ensure_ascii=False)
557
+ print("Executing approved plan...")
558
+ _execute_approved_plan(goal, plan, run_dir)
559
+ return
560
+
561
+ print("Approval required.")
562
+ print(format_approval_reasons(approval))
563
+ print()
564
+ print(f"To approve: lil approve {goal_id}")
565
+ print(f"To execute: lil run-approved {goal_id}")
566
+ else:
567
+ print("Approval not required — ready to execute.")
568
+ print(f"To execute: lil run-approved {goal_id}")
569
+ if auto_run:
570
+ print()
571
+ print("Auto-executing plan...")
572
+ _execute_approved_plan(goal, plan, run_dir)
573
+
574
+
575
+ def _execute_approved_plan(goal, plan, run_dir, force: bool = False):
576
+ """Execute an approved plan via the supervisor."""
577
+ supervisor = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir)
578
+ result = supervisor.execute_plan(force=force)
579
+ print(f"Execution complete for goal {goal.goal_id}")
580
+ _print_json(result)
581
+
582
+
583
+ def cmd_approve(args):
584
+ """Mark a plan as approved."""
585
+ goal_id = args.goal_id or _latest_goal_id()
586
+ if not goal_id:
587
+ print("error: no goal_id specified and no existing goals found in run directory.", file=sys.stderr)
588
+ sys.exit(1)
589
+
590
+ run_dir = _run_dir(goal_id)
591
+ approval_path = os.path.join(run_dir, "approval.json")
592
+
593
+ if not os.path.isfile(approval_path):
594
+ print(f"error: no approval record found for goal {goal_id}. Run 'lil propose' first.", file=sys.stderr)
595
+ sys.exit(1)
596
+
597
+ with open(approval_path, "r", encoding="utf-8") as f:
598
+ approval_data = json.load(f)
599
+
600
+ if approval_data.get("status") == "approved":
601
+ print(f"Goal {goal_id} is already approved.")
602
+ print(f"To execute: lil run-approved {goal_id}")
603
+ return
604
+
605
+ # Verify the plan being approved matches the one that was proposed
606
+ goal_path = os.path.join(run_dir, "goal.json")
607
+ plan_path = os.path.join(run_dir, "plan.json")
608
+ if os.path.isfile(goal_path) and os.path.isfile(plan_path):
609
+ with open(goal_path, "r", encoding="utf-8") as f:
610
+ goal_dict = json.load(f)
611
+ with open(plan_path, "r", encoding="utf-8") as f:
612
+ plan_dict = json.load(f)
613
+ current_digest = _plan_digest(goal_dict, plan_dict)
614
+ recorded_digest = approval_data.get("plan_digest")
615
+ if recorded_digest and current_digest != recorded_digest:
616
+ print(
617
+ f"error: plan for goal {goal_id} changed since propose "
618
+ f"(digest mismatch). Re-run 'lil propose' before approving.",
619
+ file=sys.stderr,
620
+ )
621
+ sys.exit(1)
622
+
623
+ approval_data["status"] = "approved"
624
+ with open(approval_path, "w", encoding="utf-8") as f:
625
+ json.dump(approval_data, f, indent=2, ensure_ascii=False)
626
+
627
+ print(f"Goal {goal_id} approved.")
628
+ print(f"To execute: lil run-approved {goal_id}")
629
+
630
+
631
+ @contextlib.contextmanager
632
+ def _worktree_env_scope(args):
633
+ """Enable worktree sandboxing for the command duration only (no env leakage)."""
634
+ _prev = os.environ.get("LETITLOOP_WORKTREE_SANDBOX")
635
+ if getattr(args, "worktree", False):
636
+ os.environ["LETITLOOP_WORKTREE_SANDBOX"] = "1"
637
+ try:
638
+ yield
639
+ finally:
640
+ if _prev is None:
641
+ os.environ.pop("LETITLOOP_WORKTREE_SANDBOX", None)
642
+ else:
643
+ os.environ["LETITLOOP_WORKTREE_SANDBOX"] = _prev
644
+
645
+
646
+ def cmd_run_approved(args):
647
+ """Execute an approved plan."""
648
+ with _worktree_env_scope(args):
649
+ return _cmd_run_approved_inner(args)
650
+
651
+
652
+ def _cmd_run_approved_inner(args):
653
+ goal_id = args.goal_id or _latest_goal_id()
654
+ if not goal_id:
655
+ print("error: no goal_id specified and no existing goals found in run directory.", file=sys.stderr)
656
+ sys.exit(1)
657
+
658
+ run_dir = _run_dir(goal_id)
659
+
660
+ # Load goal
661
+ goal_path = os.path.join(run_dir, "goal.json")
662
+ if not os.path.isfile(goal_path):
663
+ print(f"error: no goal found for {goal_id}. Run 'lil propose' first.", file=sys.stderr)
664
+ sys.exit(1)
665
+ with open(goal_path, "r", encoding="utf-8") as f:
666
+ goal = Goal.from_dict(json.load(f))
667
+
668
+ # Load plan
669
+ plan_path = os.path.join(run_dir, "plan.json")
670
+ if not os.path.isfile(plan_path):
671
+ print(f"error: no plan found for {goal_id}. Run 'lil propose' first.", file=sys.stderr)
672
+ sys.exit(1)
673
+ with open(plan_path, "r", encoding="utf-8") as f:
674
+ plan = Plan.from_dict(json.load(f))
675
+
676
+ # Check approval
677
+ approval_path = os.path.join(run_dir, "approval.json")
678
+ if not os.path.isfile(approval_path):
679
+ print(
680
+ f"error: no approval record found for goal {goal_id}; run 'lil propose' and 'lil approve' before execution",
681
+ file=sys.stderr,
682
+ )
683
+ sys.exit(1)
684
+
685
+ try:
686
+ with open(approval_path, "r", encoding="utf-8") as f:
687
+ approval_data = json.load(f)
688
+ except (OSError, json.JSONDecodeError) as exc:
689
+ print(
690
+ f"error: approval record for goal {goal_id} is invalid: {exc}",
691
+ file=sys.stderr,
692
+ )
693
+ sys.exit(1)
694
+
695
+ if approval_data.get("status") != "approved":
696
+ print(
697
+ f"error: goal {goal_id} has not been approved. Run 'lil approve {goal_id}' first.",
698
+ file=sys.stderr,
699
+ )
700
+ sys.exit(1)
701
+
702
+ # Verify the plan has not changed since it was approved
703
+ recorded_digest = approval_data.get("plan_digest")
704
+ if recorded_digest:
705
+ current_digest = _plan_digest(goal.to_dict(), plan.to_dict())
706
+ if current_digest != recorded_digest:
707
+ print(
708
+ f"error: plan for goal {goal_id} changed after approval "
709
+ f"(digest mismatch). Plan must be re-proposed and re-approved.",
710
+ file=sys.stderr,
711
+ )
712
+ sys.exit(1)
713
+
714
+ _execute_approved_plan(goal, plan, run_dir, force=getattr(args, "force", False))
715
+
716
+
717
+ def cmd_plan_preview(args):
718
+ """Render and display a plan preview."""
719
+ goal_id = args.goal_id
720
+ run_dir = _run_dir(goal_id)
721
+ plan_path = os.path.join(run_dir, "plan.json")
722
+
723
+ if not os.path.isfile(plan_path):
724
+ print(f"error: no plan found for {goal_id}. Run 'propose' first.", file=sys.stderr)
725
+ sys.exit(1)
726
+
727
+ with open(plan_path, "r", encoding="utf-8") as f:
728
+ plan = Plan.from_dict(json.load(f))
729
+
730
+ goal_path = os.path.join(run_dir, "goal.json")
731
+ goal_dict = None
732
+ if os.path.isfile(goal_path):
733
+ with open(goal_path, "r", encoding="utf-8") as f:
734
+ goal_dict = json.load(f)
735
+
736
+ preview = render_plan_preview(plan, goal_dict=goal_dict)
737
+ print(preview)
738
+
739
+
740
+ def cmd_goal_create(args):
741
+ goal_id = args.goal_id
742
+ title = args.title or goal_id
743
+ description = args.description or ""
744
+ constraints = {}
745
+ if args.constraints:
746
+ try:
747
+ constraints = json.loads(args.constraints)
748
+ except json.JSONDecodeError as e:
749
+ print(f"error: invalid constraints JSON: {e}", file=sys.stderr)
750
+ sys.exit(1)
751
+
752
+ goal = Goal(
753
+ goal_id=goal_id,
754
+ title=title,
755
+ description=description,
756
+ constraints=constraints,
757
+ )
758
+ run_dir = _run_dir(goal_id)
759
+ os.makedirs(run_dir, exist_ok=True)
760
+ out_path = args.out if args.out else os.path.join(run_dir, "goal.json")
761
+ os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
762
+
763
+ with open(out_path, "w", encoding="utf-8") as f:
764
+ json.dump(goal.to_dict(), f, indent=2, ensure_ascii=False)
765
+
766
+ print(f"Goal {goal_id} created (status: {goal.status})")
767
+ print(f" Saved to: {out_path}")
768
+
769
+
770
+ def _load_goal(goal_id_or_path):
771
+ candidates = [
772
+ goal_id_or_path,
773
+ os.path.join(WORKSPACE_ROOT, goal_id_or_path),
774
+ os.path.join(_run_dir(goal_id_or_path), "goal.json"),
775
+ os.path.join(WORKSPACE_ROOT, "orchestrator", "fixtures", f"{goal_id_or_path}.json"),
776
+ os.path.join(WORKSPACE_ROOT, "orchestrator", "fixtures", goal_id_or_path),
777
+ ]
778
+ for cand in candidates:
779
+ if os.path.isfile(cand):
780
+ try:
781
+ with open(cand, "r", encoding="utf-8") as f:
782
+ data = json.load(f)
783
+ return Goal.from_dict(data)
784
+ except (OSError, json.JSONDecodeError, KeyError):
785
+ pass
786
+
787
+ print(f"error: goal file not found for {goal_id_or_path}", file=sys.stderr)
788
+ sys.exit(1)
789
+
790
+
791
+ def cmd_plan(args):
792
+ goal = _load_goal(args.goal_id)
793
+ plan = generate_contracts(goal, workspace_root=WORKSPACE_ROOT)
794
+ run_dir = _run_dir(goal.goal_id)
795
+ os.makedirs(run_dir, exist_ok=True)
796
+ plan_path = os.path.join(run_dir, "plan.json")
797
+ with open(plan_path, "w", encoding="utf-8") as f:
798
+ json.dump(plan.to_dict(), f, indent=2, ensure_ascii=False)
799
+
800
+ print(f"Plan generated for goal {goal.goal_id} ({len(plan.contracts)} contracts)")
801
+ print(f" Plan: {plan_path}")
802
+
803
+
804
+ def _load_plan(goal_id):
805
+ candidates = [
806
+ os.path.join(_run_dir(goal_id), "plan.json"),
807
+ os.path.join(WORKSPACE_ROOT, goal_id),
808
+ ]
809
+ for cand in candidates:
810
+ if os.path.isfile(cand):
811
+ with open(cand, "r", encoding="utf-8") as f:
812
+ data = json.load(f)
813
+ return Plan.from_dict(data)
814
+
815
+ print(f"error: plan not found for goal {goal_id}", file=sys.stderr)
816
+ sys.exit(1)
817
+
818
+
819
+ def cmd_plan_check(args):
820
+ """Run quality checks on a plan without executing."""
821
+ from .plan_quality import check_plan_quality, format_warnings, plan_is_safe
822
+
823
+ _load_goal(args.goal_id)
824
+ plan = _load_plan(args.goal_id)
825
+ warnings = check_plan_quality(plan, workspace_root=WORKSPACE_ROOT)
826
+ print(format_warnings(warnings))
827
+ if not plan_is_safe(warnings):
828
+ sys.exit(1)
829
+
830
+
831
+ def cmd_supervise(args):
832
+ with _worktree_env_scope(args):
833
+ goal = _load_goal(args.goal_id)
834
+ plan = _load_plan(goal.goal_id)
835
+ run_dir = _run_dir(goal.goal_id)
836
+ supervisor = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir)
837
+ res = supervisor.execute_plan()
838
+ print(f"Supervision complete for goal {goal.goal_id} (status: {goal.status})")
839
+ _print_json(res)
840
+
841
+
842
+ def cmd_supervise_resume(args):
843
+ with _worktree_env_scope(args):
844
+ goal = _load_goal(args.goal_id)
845
+ plan = _load_plan(goal.goal_id)
846
+ run_dir = _run_dir(goal.goal_id)
847
+ supervisor = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir)
848
+ res = supervisor.resume_plan()
849
+ print(f"Resume complete for goal {goal.goal_id} (status: {goal.status})")
850
+ _print_json(res)
851
+
852
+
853
+ def cmd_supervise_status(args):
854
+ goal = _load_goal(args.goal_id)
855
+ plan = _load_plan(args.goal_id)
856
+ run_dir = _run_dir(goal.goal_id)
857
+ supervisor = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir)
858
+ agg = supervisor.aggregate_results()
859
+ _print_json(agg)
860
+
861
+
862
+ def cmd_goal_result(args):
863
+ cmd_supervise_status(args)
864
+
865
+
866
+ def cmd_failure_report(args):
867
+ """Show failure classification and remediation for each contract in a goal."""
868
+ from .failure import classify_failure, count_consecutive_same_class, suggest_remediation
869
+ from .state import load_state
870
+
871
+ goal = _load_goal(args.goal_id)
872
+ plan = _load_plan(args.goal_id)
873
+ run_dir = _run_dir(goal.goal_id)
874
+
875
+ reports = []
876
+ for c in plan.contracts:
877
+ tid = c["task_id"]
878
+ state_file = os.path.join(run_dir, tid, "state.json")
879
+ if not os.path.isfile(state_file):
880
+ reports.append(
881
+ {
882
+ "task_id": tid,
883
+ "status": "no_state",
884
+ "failure_class": "none",
885
+ "attempt": 0,
886
+ "max_attempts": 1,
887
+ "consecutive_same_class": 0,
888
+ "remediation": "none",
889
+ "reason": "not yet executed",
890
+ }
891
+ )
892
+ continue
893
+
894
+ state = load_state(state_file)
895
+ contract_path = os.path.join(run_dir, tid, "contract.json")
896
+ contract, _ = load_contract(contract_path, workspace_root=WORKSPACE_ROOT)
897
+ max_attempts = contract.worker.get("max_attempts", 1) if contract else 1
898
+
899
+ if state.status in ("COMPLETE", "complete", "VERIFIED", "QC_PASSED"):
900
+ reports.append(
901
+ {
902
+ "task_id": tid,
903
+ "status": state.status,
904
+ "failure_class": "none",
905
+ "attempt": state.attempt,
906
+ "max_attempts": max_attempts,
907
+ "consecutive_same_class": 0,
908
+ "remediation": "none",
909
+ "reason": "completed successfully",
910
+ }
911
+ )
912
+ continue
913
+
914
+ fclass = classify_failure(state, contract)
915
+ strikes = count_consecutive_same_class(state, fclass) if state.worker_results else 0
916
+ rem = suggest_remediation(fclass, state.attempt, max_attempts)
917
+
918
+ reports.append(
919
+ {
920
+ "task_id": tid,
921
+ "status": state.status,
922
+ "failure_class": fclass,
923
+ "attempt": state.attempt,
924
+ "max_attempts": max_attempts,
925
+ "consecutive_same_class": strikes,
926
+ "remediation": rem["action"],
927
+ "reason": rem["reason"],
928
+ }
929
+ )
930
+
931
+ if args.json:
932
+ _print_json(reports)
933
+ return
934
+
935
+ print(f"=== Failure Report: {args.goal_id} ===")
936
+ print()
937
+ for r in reports:
938
+ print(f" {r['task_id']}:")
939
+ print(f" Status: {r['status']}")
940
+ print(f" Failure: {r['failure_class']}")
941
+ print(f" Attempt: {r.get('attempt', 0)}/{r.get('max_attempts', 1)}")
942
+ print(f" Consecutive: {r.get('consecutive_same_class', 0)} same class")
943
+ print(f" Remediation: {r['remediation']}")
944
+ print(f" Reason: {r['reason']}")
945
+ print()
946
+
947
+
948
+ def cmd_evidence_flow(args):
949
+ goal = _load_goal(args.goal_id)
950
+ plan = _load_plan(args.goal_id)
951
+ run_dir = _run_dir(goal.goal_id)
952
+ supervisor = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir)
953
+ agg = supervisor.aggregate_results()
954
+
955
+ if getattr(args, "json", False):
956
+ # Build a structured flow graph
957
+ flow_graph = {
958
+ "goal_id": agg["goal_id"],
959
+ "contracts": agg.get("contracts", {}),
960
+ "evidence_store": agg.get("evidence_store", {}),
961
+ "nodes": {},
962
+ "edges": [],
963
+ }
964
+ for c in plan.contracts:
965
+ tid = c["task_id"]
966
+ node_info = agg["contracts"].get(tid, {})
967
+ flow_graph["nodes"][tid] = {
968
+ "status": node_info.get("status", "UNKNOWN"),
969
+ "outputs": node_info.get("outputs", []),
970
+ }
971
+ # Edges from dependency
972
+ for dep in c.get("depends_on", []):
973
+ edge = {
974
+ "from": dep,
975
+ "to": tid,
976
+ "type": "dependency",
977
+ }
978
+ evidence = agg.get("evidence_store", {}).get(dep, [])
979
+ if evidence:
980
+ edge["evidence_paths"] = evidence
981
+ flow_graph["edges"].append(edge)
982
+ # Also add evidence-ledger edges (where evidence was actually injected)
983
+ for tid, info in agg.get("contracts", {}).items():
984
+ for ei_key, ei_path in info.get("evidence", {}).items():
985
+ edge = {
986
+ "from": tid,
987
+ "to": tid,
988
+ "type": "evidence",
989
+ "evidence_key": ei_key,
990
+ "evidence_path": ei_path,
991
+ }
992
+ flow_graph["edges"].append(edge)
993
+ _print_json(flow_graph)
994
+ return
995
+
996
+ print(f"=== Evidence Flow: {agg['goal_id']} ===")
997
+
998
+ # Build evidence flow map
999
+ # For each contract, find what evidence it injected into downstream contracts
1000
+ evidence_map = {} # source -> list of (downstream_task_id, path)
1001
+ for c in plan.contracts:
1002
+ tid = c["task_id"]
1003
+ deps = c.get("depends_on", [])
1004
+ for dep in deps:
1005
+ # For each dependency, the upstream outputs feed into this contract
1006
+ if tid not in evidence_map:
1007
+ evidence_map[tid] = {"receives_from": [], "injects_into": []}
1008
+ evidence_map[tid]["receives_from"].append(dep)
1009
+
1010
+ # Also build reverse map (who injects into whom)
1011
+ for c in plan.contracts:
1012
+ tid = c["task_id"]
1013
+ # Look at the contract's inputs for evidence entries
1014
+ contract_dict = c.get("contract", {})
1015
+ inputs = contract_dict.get("inputs", [])
1016
+ evidence_inputs = [i for i in inputs if i.get("evidence")]
1017
+ for ei in evidence_inputs:
1018
+ source = ei.get("source", "?")
1019
+ if source not in evidence_map:
1020
+ evidence_map[source] = {"receives_from": [], "injects_into": []}
1021
+ evidence_map[source].setdefault("injects_into", []).append(tid)
1022
+
1023
+ # Print the evidence flow
1024
+ print()
1025
+ for c in plan.contracts:
1026
+ tid = c["task_id"]
1027
+ info = agg["contracts"].get(tid, {})
1028
+ status = info.get("status", "UNKNOWN")
1029
+ outputs = info.get("outputs", [])
1030
+ print(f"Contract: {tid}")
1031
+ print(f"Status: {status}")
1032
+ print(f"Outputs: {', '.join(outputs) if outputs else '(none)'}")
1033
+
1034
+ # Show evidence injected INTO this contract
1035
+ e_info = evidence_map.get(tid, {})
1036
+ receives = e_info.get("receives_from", [])
1037
+ if receives:
1038
+ print(f"Receives evidence from: {receives}")
1039
+ for src in receives:
1040
+ src_outputs = agg["contracts"].get(src, {}).get("outputs", [])
1041
+ for out_path in src_outputs:
1042
+ print(f" \u2192 {out_path}")
1043
+ print()
1044
+
1045
+ # Print the evidence store summary
1046
+ evidence_store = agg.get("evidence_store", {})
1047
+ if evidence_store:
1048
+ print()
1049
+ print("Evidence Store (completed outputs):")
1050
+ for tid, paths in evidence_store.items():
1051
+ for p in paths:
1052
+ print(f" {tid}: {p}")
1053
+ print()
1054
+
1055
+
1056
+ def cmd_reconcile(args):
1057
+ """Run reconciliation check on a goal's plan."""
1058
+ from . import reconcile as rec
1059
+
1060
+ goal = _load_goal(args.goal_id)
1061
+ plan = _load_plan(args.goal_id)
1062
+ run_dir = _run_dir(goal.goal_id)
1063
+ report = rec.run_reconciliation(goal.goal_id, plan, WORKSPACE_ROOT, run_dir)
1064
+ if args.json:
1065
+ _print_json(report.to_dict())
1066
+ return
1067
+ print(rec.format_report(report))
1068
+ if not report.passed:
1069
+ sys.exit(1)
1070
+
1071
+
1072
+ def cmd_scope_check(args):
1073
+ """Run scope check on a completed goal to detect scope violations."""
1074
+ from . import scope as sc
1075
+ from .state import load_state
1076
+
1077
+ goal = _load_goal(args.goal_id)
1078
+ plan = _load_plan(args.goal_id)
1079
+ run_dir = _run_dir(goal.goal_id)
1080
+
1081
+ all_clean = True
1082
+ for c in plan.contracts:
1083
+ tid = c["task_id"]
1084
+ task_dir = os.path.join(run_dir, tid)
1085
+ state_file = os.path.join(task_dir, "state.json")
1086
+ if not os.path.isfile(state_file):
1087
+ continue
1088
+ state = load_state(state_file)
1089
+ contract_file = os.path.join(task_dir, "contract.json")
1090
+ contract, _ = load_contract(contract_file, workspace_root=WORKSPACE_ROOT)
1091
+ if contract is None:
1092
+ continue
1093
+ scope_result = sc.check_scope(contract, WORKSPACE_ROOT, task_dir)
1094
+ if not args.json:
1095
+ print(f"{tid}: {sc.format_scope_result(scope_result)}")
1096
+ print()
1097
+ if not scope_result.passed:
1098
+ all_clean = False
1099
+ # Store violations in state data for failure_class
1100
+ state.patch_data({"scope_violations": [v.to_dict() for v in scope_result.violations]})
1101
+
1102
+ if args.json:
1103
+ result = {"goal_id": goal.goal_id, "passed": all_clean}
1104
+ _print_json(result)
1105
+
1106
+ if not all_clean:
1107
+ sys.exit(1)
1108
+
1109
+
1110
+ def cmd_provenance(args):
1111
+ """Show provenance graph for a goal — contract lineage, I/O chains."""
1112
+ from . import provenance as prov
1113
+
1114
+ goal = _load_goal(args.goal_id)
1115
+ plan = _load_plan(args.goal_id)
1116
+ run_dir = _run_dir(goal.goal_id)
1117
+ graph = prov.build_provenance(goal.goal_id, goal.title, plan, WORKSPACE_ROOT, run_dir)
1118
+ if args.json:
1119
+ _print_json(graph.to_dict())
1120
+ return
1121
+ print(prov.format_provenance(graph))
1122
+
1123
+
1124
+ def cmd_pause(args):
1125
+ """Pause all active tasks in a goal."""
1126
+ goal = _load_goal(args.goal_id)
1127
+ plan = _load_plan(args.goal_id)
1128
+ run_dir = _run_dir(goal.goal_id)
1129
+ sup = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir)
1130
+ res = sup.pause_plan(reason=args.reason or "operator pause")
1131
+ print(f"Pause result for goal {goal.goal_id}:")
1132
+ for tid, status in res.items():
1133
+ print(f" {tid}: {status}")
1134
+ print(f"Goal status: {goal.status}")
1135
+
1136
+
1137
+ def cmd_cancel(args):
1138
+ """Cancel all non-terminal tasks in a goal."""
1139
+ goal = _load_goal(args.goal_id)
1140
+ plan = _load_plan(args.goal_id)
1141
+ run_dir = _run_dir(goal.goal_id)
1142
+ sup = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir)
1143
+ res = sup.cancel_plan(reason=args.reason or "operator cancel")
1144
+ print(f"Cancel result for goal {goal.goal_id}:")
1145
+ for tid, status in res.items():
1146
+ print(f" {tid}: {status}")
1147
+ print(f"Goal status: {goal.status}")
1148
+
1149
+
1150
+ def cmd_inspect(args):
1151
+ """Deep inspect a single task's state and evidence."""
1152
+ goal = _load_goal(args.goal_id)
1153
+ plan = _load_plan(args.goal_id)
1154
+ run_dir = _run_dir(goal.goal_id)
1155
+ sup = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir)
1156
+ info = sup.inspect_task(args.task_id)
1157
+ if "error" in info:
1158
+ print(f"Error: {info['error']}", file=sys.stderr)
1159
+ sys.exit(1)
1160
+ if args.json:
1161
+ _print_json(info)
1162
+ return
1163
+ print(f"=== Inspect: {info['task_id']} ===")
1164
+ print(f"Status: {info['status']}")
1165
+ print(f"Attempt: {info['attempt']}")
1166
+ print(f"Terminal: {info['is_terminal']}")
1167
+ print(f"Can resume: {info['can_resume']}")
1168
+ print(f"Next actions: {info['legal_transitions']}")
1169
+ print(f"Events: {info['events_count']}")
1170
+ print(f"Worker runs: {info['worker_runs']}")
1171
+ if info["last_worker_result"]:
1172
+ wr = info["last_worker_result"]
1173
+ print(f"Last exit code: {wr.get('exit_code', '?')}")
1174
+ print(f"Last elapsed: {wr.get('elapsed_sec', '?')}s")
1175
+ if info.get("failure_class"):
1176
+ print(f"Failure class: {info['failure_class']}")
1177
+ if info.get("crash_reason"):
1178
+ print(f"Crash reason: {info['crash_reason']}")
1179
+ if info.get("scope_violations"):
1180
+ print(f"Scope violations: {len(info['scope_violations'])}")
1181
+ print(f"Contract: {info.get('contract_title', '?')}")
1182
+ print(f"Objective: {info.get('contract_objective', '?')}")
1183
+ print(f"Task dir: {info['task_dir']}")
1184
+ print("Evidence files:")
1185
+ for key, ef in info.get("evidence_files", {}).items():
1186
+ print(f" [{ef['exists'] and 'OK' or 'MISSING'}] {key}: {ef['path']}")
1187
+
1188
+
1189
+ def cmd_dryrun(args):
1190
+ """Simulate plan execution without real worker calls."""
1191
+ goal = _load_goal(args.goal_id)
1192
+ plan = _load_plan(args.goal_id)
1193
+ run_dir = _run_dir(goal.goal_id)
1194
+ sup = Supervisor(goal, plan, workspace_root=WORKSPACE_ROOT, run_dir=run_dir, dry_run=True)
1195
+ res = sup.execute_plan()
1196
+ print(f"Dry-run complete for goal {goal.goal_id} — {len(res)} tasks simulated")
1197
+
1198
+
1199
+ def cmd_config(args):
1200
+ """Show current orchestrator configuration."""
1201
+ from .config import OrchestratorConfig
1202
+
1203
+ cfg = OrchestratorConfig.load(args.path) if args.path else OrchestratorConfig.load()
1204
+ print(cfg.display())
1205
+
1206
+
1207
+ def cmd_audit(args):
1208
+ """Show audit log for a goal."""
1209
+ from . import audit as audit_mod
1210
+
1211
+ goal = _load_goal(args.goal_id)
1212
+ run_dir = _run_dir(goal.goal_id)
1213
+ entries = audit_mod.query_audit(run_dir, goal_id=args.goal_id, action_type=args.action, task_id=args.task_id)
1214
+ if args.json:
1215
+ _print_json(entries)
1216
+ return
1217
+ print(audit_mod.format_audit_entries(entries))
1218
+
1219
+
1220
+ def cmd_metrics(args):
1221
+ """Show runtime metrics for a goal."""
1222
+ from . import metrics as metrics_mod
1223
+
1224
+ goal = _load_goal(args.goal_id)
1225
+ run_dir = _run_dir(goal.goal_id)
1226
+ metrics_path = os.path.join(run_dir, "metrics.json")
1227
+ if not os.path.isfile(metrics_path):
1228
+ print(f"No metrics found for goal {args.goal_id}")
1229
+ return
1230
+ mc = metrics_mod.MetricsCollector.load(metrics_path)
1231
+ if args.json:
1232
+ _print_json(mc.to_dict())
1233
+ return
1234
+ print(mc.summary())
1235
+
1236
+
1237
+ def cmd_safety_check(args):
1238
+ """Run pre-execution safety checks on a plan."""
1239
+ from .limits import DEFAULT_LIMITS
1240
+ from .safety import format_safety_report, run_safety_checks
1241
+
1242
+ _load_goal(args.goal_id)
1243
+ plan = _load_plan(args.goal_id)
1244
+ report = run_safety_checks(plan, WORKSPACE_ROOT, limits=DEFAULT_LIMITS)
1245
+ if args.json:
1246
+ _print_json(report.to_dict())
1247
+ return
1248
+ print(format_safety_report(report))
1249
+ if not report.passed:
1250
+ sys.exit(1)
1251
+
1252
+
1253
+ def cmd_checkpoint_list(args):
1254
+ """List checkpoints for a goal."""
1255
+ from . import checkpoint as cp_mod
1256
+
1257
+ goal = _load_goal(args.goal_id)
1258
+ run_dir = _run_dir(goal.goal_id)
1259
+ entries = cp_mod.list_checkpoints(run_dir)
1260
+ if args.json:
1261
+ _print_json(entries)
1262
+ return
1263
+ if not entries:
1264
+ print(f"No checkpoints found for goal {args.goal_id}")
1265
+ return
1266
+ print(f"Checkpoints for goal {args.goal_id}:")
1267
+ for e in entries:
1268
+ print(
1269
+ f" iter={e['iteration']} status={e['goal_status']} contracts={e['total_contracts']} time={e['timestamp']}"
1270
+ )
1271
+
1272
+
1273
+ def cmd_checkpoint_recover(args):
1274
+ """Recover plan state from latest checkpoint."""
1275
+ from . import checkpoint as cp_mod
1276
+
1277
+ goal = _load_goal(args.goal_id)
1278
+ run_dir = _run_dir(goal.goal_id)
1279
+ recovery = cp_mod.recover_from_checkpoint(run_dir)
1280
+ if not recovery.get("recovered"):
1281
+ print(f"No checkpoint to recover for goal {args.goal_id}")
1282
+ sys.exit(1)
1283
+ if args.json:
1284
+ _print_json(recovery)
1285
+ return
1286
+ print(f"Recovery available for goal {args.goal_id}")
1287
+ print(f" Iteration: {recovery['iteration']}")
1288
+ print(f" Goal status: {recovery['goal_status']}")
1289
+ print(f" Contracts: {len(recovery['plan_contracts'])}")
1290
+ print(f" Results: {len(recovery['results'])} tasks")
1291
+ if args.apply:
1292
+ applied = cp_mod.apply_checkpoint(run_dir, WORKSPACE_ROOT)
1293
+ print(f"Successfully applied checkpoint (iteration {applied['iteration']}) to goal {args.goal_id}.")
1294
+ print(f"Restored {len(applied['plan_contracts'])} contracts and {len(applied['graph_statuses'])} task states.")
1295
+ print(f"You can now resume execution via: lil resume {args.goal_id}")
1296
+
1297
+
1298
+ def cmd_checkpoint_clear(args):
1299
+ """Remove all checkpoints for a goal."""
1300
+ from . import checkpoint as cp_mod
1301
+
1302
+ goal = _load_goal(args.goal_id)
1303
+ run_dir = _run_dir(goal.goal_id)
1304
+ count = cp_mod.clear_checkpoints(run_dir)
1305
+ print(f"Cleared {count} checkpoints for goal {args.goal_id}")
1306
+
1307
+
1308
+ def cmd_feedback(args):
1309
+ """Show failure feedback history for a goal."""
1310
+ from . import feedback as fb_mod
1311
+
1312
+ goal = _load_goal(args.goal_id)
1313
+ _load_plan(args.goal_id)
1314
+ run_dir = _run_dir(goal.goal_id)
1315
+ records = fb_mod.load_feedback(goal.goal_id, run_dir)
1316
+ if args.json:
1317
+ _print_json([r.to_dict() for r in records])
1318
+ return
1319
+ print(fb_mod.format_feedback(records))
1320
+
1321
+
1322
+ def cmd_error_inspect(args):
1323
+ """Inspect structured errors for a goal's contracts."""
1324
+ from . import errors as err_mod
1325
+
1326
+ goal = _load_goal(args.goal_id)
1327
+ plan = _load_plan(args.goal_id)
1328
+ run_dir = _run_dir(goal.goal_id)
1329
+ errors = err_mod.inspect_goal(goal.goal_id, plan, WORKSPACE_ROOT, run_dir)
1330
+ if args.json:
1331
+ _print_json([e.to_dict() for e in errors])
1332
+ return
1333
+ print(err_mod.format_error_list(errors))
1334
+ if errors:
1335
+ sys.exit(1)
1336
+
1337
+
1338
+ def cmd_evidence_ledger(args):
1339
+ goal = _load_goal(args.goal_id)
1340
+ _load_plan(args.goal_id)
1341
+ run_dir = _run_dir(goal.goal_id)
1342
+ from . import evidence as ev
1343
+
1344
+ ledger = ev.load_ledger(run_dir)
1345
+ if not ledger:
1346
+ print(f"No evidence ledger found for goal {args.goal_id}")
1347
+ return
1348
+
1349
+ issues = ev.check_evidence_freshness(run_dir)
1350
+
1351
+ print(f"=== Evidence Ledger: {args.goal_id} ===")
1352
+ print(f"Total entries: {sum(len(v) for v in ledger.values())}")
1353
+ print()
1354
+
1355
+ for task_id in sorted(ledger.keys()):
1356
+ entries = ledger[task_id]
1357
+ print(f" {task_id} ({len(entries)} outputs):")
1358
+ for e in entries:
1359
+ status = "OK"
1360
+ if not os.path.isfile(e.get("absolute_path", "")):
1361
+ status = "MISSING"
1362
+ elif e.get("sha256", "") and e["sha256"] != ev._sha256(e["absolute_path"]):
1363
+ status = "MODIFIED"
1364
+ print(f" [{status}] {e.get('relative_path', '?')} ({e.get('size_bytes', 0)} bytes)")
1365
+ print()
1366
+
1367
+ if issues:
1368
+ print(" Issues:")
1369
+ for iss in issues:
1370
+ print(f" [{iss['issue']}] {iss['path']} (task: {iss['task_id']})")
1371
+ print()
1372
+
1373
+
1374
+ def cmd_impossibility(args):
1375
+ """Show impossibility artifact for an escalated task."""
1376
+ from . import impossibility as imp
1377
+
1378
+ goal = _load_goal(args.goal_id)
1379
+ plan = _load_plan(args.goal_id)
1380
+ _run_dir(goal.goal_id)
1381
+
1382
+ artifacts_found = []
1383
+ for c in plan.contracts:
1384
+ tid = c["task_id"]
1385
+ art_dir = os.path.join(WORKSPACE_ROOT, imp.artifact_dir(args.goal_id, tid))
1386
+ json_path = os.path.join(art_dir, "impossibility.json")
1387
+ os.path.join(art_dir, "impossibility.md")
1388
+ if os.path.isfile(json_path):
1389
+ with open(json_path, "r", encoding="utf-8") as f:
1390
+ artifact = json.load(f)
1391
+ artifacts_found.append(artifact)
1392
+
1393
+ if not artifacts_found:
1394
+ print(f"No impossibility artifacts found for goal {args.goal_id}")
1395
+ return
1396
+
1397
+ if args.json:
1398
+ _print_json(artifacts_found)
1399
+ return
1400
+
1401
+ for art in artifacts_found:
1402
+ print(f"=== Impossibility: {art['task_id']} ===")
1403
+ print(f" Title: {art['title']}")
1404
+ print(f" Failure Class: {art['failure_class']}")
1405
+ print(f" Attempts: {art['attempts_made']}/{art['max_attempts']}")
1406
+ print(f" Objective: {art['objective'][:80]}...")
1407
+ print(f" Artifacts: scratch/impossibility/{args.goal_id}/{art['task_id']}/")
1408
+ print()
1409
+
1410
+
1411
+ def cmd_trace(args):
1412
+ """Render comprehensive step-by-step reasoning, verification and QC trace for a goal."""
1413
+ goal_id = getattr(args, "goal_id", None) or _latest_goal_id()
1414
+ if not goal_id:
1415
+ print("error: no goal_id specified and no existing goals found in run directory.", file=sys.stderr)
1416
+ sys.exit(1)
1417
+
1418
+ run_dir = _run_dir(goal_id)
1419
+ goal_path = os.path.join(run_dir, "goal.json")
1420
+ if not os.path.isfile(goal_path):
1421
+ print(f"error: goal {goal_id} not found at {run_dir}", file=sys.stderr)
1422
+ sys.exit(1)
1423
+
1424
+ try:
1425
+ with open(goal_path, "r", encoding="utf-8") as f:
1426
+ goal_data = json.load(f)
1427
+ except Exception:
1428
+ goal_data = {}
1429
+
1430
+ print("\n" + "=" * 78)
1431
+ print(f" LETITLOOP TRACE TIMELINE: {goal_id}")
1432
+ print(f" Title: {goal_data.get('title', 'Untitled')}")
1433
+ print(f" Status: {goal_data.get('status', 'UNKNOWN')}")
1434
+ print("=" * 78)
1435
+
1436
+ subdirs = sorted(
1437
+ [
1438
+ d
1439
+ for d in os.listdir(run_dir)
1440
+ if os.path.isdir(os.path.join(run_dir, d)) and d not in ("state_backups", "checkpoints")
1441
+ ]
1442
+ )
1443
+ if not subdirs:
1444
+ print(" (No step executions recorded for this goal)\n")
1445
+ return
1446
+
1447
+ for idx, sdir in enumerate(subdirs, 1):
1448
+ step_dir = os.path.join(run_dir, sdir)
1449
+ state_file = os.path.join(step_dir, "state.json")
1450
+ qc_file = os.path.join(step_dir, "qc_verdict.json")
1451
+ v_file = os.path.join(step_dir, "verification_evidence.json")
1452
+ c_file = os.path.join(step_dir, "contract.json")
1453
+
1454
+ st_name = "UNKNOWN"
1455
+ att = 1
1456
+ if os.path.isfile(state_file):
1457
+ try:
1458
+ with open(state_file, "r", encoding="utf-8") as sf:
1459
+ s_data = json.load(sf)
1460
+ st_name = s_data.get("status", "UNKNOWN")
1461
+ att = s_data.get("attempt", 1)
1462
+ except Exception:
1463
+ pass
1464
+
1465
+ print(f"\n [{idx:02d}] Step: {sdir}")
1466
+ print(f" * Final Status: {st_name} (Attempts: {att})")
1467
+
1468
+ # Contract info
1469
+ if os.path.isfile(c_file):
1470
+ try:
1471
+ with open(c_file, "r", encoding="utf-8") as cf:
1472
+ c_data = json.load(cf)
1473
+ worker_m = c_data.get("worker", {}).get("model", "default")
1474
+ outs = [o.get("path", "") for o in c_data.get("outputs", []) if isinstance(o, dict)]
1475
+ print(f" * Worker Model: {worker_m}")
1476
+ if outs:
1477
+ print(f" * Target Outputs: {', '.join(outs)}")
1478
+ except Exception:
1479
+ pass
1480
+
1481
+ # Verification Evidence
1482
+ if os.path.isfile(v_file):
1483
+ try:
1484
+ with open(v_file, "r", encoding="utf-8") as vf:
1485
+ v_data = json.load(vf)
1486
+ v_res = v_data.get("verification_results", [])
1487
+ all_p = v_data.get("all_passed", False)
1488
+ print(f" * Verification Checks: {'[ALL PASS]' if all_p else '[FAIL]'} ({len(v_res)} checks)")
1489
+ for chk in v_res[:3]:
1490
+ c_kind = chk.get("kind", chk.get("check_id", "check"))
1491
+ c_pass = "[PASS]" if chk.get("passed") else "[FAIL]"
1492
+ print(f" - {c_pass} {c_kind}")
1493
+ except Exception:
1494
+ pass
1495
+
1496
+ # QC Verdict
1497
+ if os.path.isfile(qc_file):
1498
+ try:
1499
+ with open(qc_file, "r", encoding="utf-8") as qf:
1500
+ q_data = json.load(qf)
1501
+ q_stat = q_data.get("status", "UNKNOWN")
1502
+ q_score = q_data.get("score", 0.0)
1503
+ q_reason = q_data.get("reason", "")
1504
+ print(f" * Multi-Lens QC: [{q_stat}] (Score: {q_score:.2f})")
1505
+ if q_reason:
1506
+ print(f" - {q_reason[:75]}...")
1507
+ except Exception:
1508
+ pass
1509
+
1510
+ print("\n" + "=" * 78 + "\n")
1511
+
1512
+
1513
+ def cmd_dashboard(args):
1514
+ """Render rich terminal UI dashboard for active run directory."""
1515
+ from .tui import LiveDashboard, print_dashboard
1516
+
1517
+ run_dir = getattr(args, "run_dir", DEFAULT_RUN_DIR)
1518
+ live = bool(getattr(args, "live", False))
1519
+ once = bool(getattr(args, "once", False))
1520
+ if live or once:
1521
+ interval = float(getattr(args, "interval", 2.0) or 2.0)
1522
+ LiveDashboard(run_dir, interval=interval).run(once=once)
1523
+ return
1524
+ print_dashboard(run_dir)
1525
+
1526
+
1527
+ def cmd_serve(args):
1528
+ """Serve orchestrator lifecycle events over SSE (GET /events, GET /health)."""
1529
+ import time as _time
1530
+
1531
+ from .events import get_bus
1532
+ from .sse_server import SSEServer
1533
+ from .webhooks import (
1534
+ WebhookDispatcher,
1535
+ attach_webhooks,
1536
+ load_webhook_configs,
1537
+ load_webhook_configs_from_env,
1538
+ )
1539
+
1540
+ host = getattr(args, "host", "127.0.0.1")
1541
+ port = int(getattr(args, "port", 8080))
1542
+ explicit = getattr(args, "webhooks_json", "") or ""
1543
+ configs = load_webhook_configs(explicit) if explicit else load_webhook_configs_from_env()
1544
+ detach = None
1545
+ if configs:
1546
+ detach = attach_webhooks(get_bus(), WebhookDispatcher(configs))
1547
+ print(f"[serve] attached {len(configs)} webhook endpoint(s)")
1548
+ server = SSEServer(host=host, port=port, bus=get_bus())
1549
+ server.start()
1550
+ print(f"[serve] SSE stream ready at http://{host}:{server.bound_port}/events (Ctrl+C to stop)")
1551
+ try:
1552
+ while True:
1553
+ _time.sleep(1)
1554
+ except KeyboardInterrupt:
1555
+ pass
1556
+ finally:
1557
+ server.shutdown()
1558
+ if detach is not None:
1559
+ detach()
1560
+ print("[serve] shutdown complete")
1561
+
1562
+
1563
+ def cmd_install_skill(args):
1564
+ """Install letitloop skill across supported AI agent environments."""
1565
+ from pathlib import Path
1566
+
1567
+ from .skill_installer import run_skill_install
1568
+
1569
+ ws = Path(args.workspace).resolve() if args.workspace else None
1570
+ installed = run_skill_install(target=args.target, workspace=ws)
1571
+ print("\n========================================================")
1572
+ print("letitloop Multi-Platform Skill Installation Summary")
1573
+ print("========================================================")
1574
+ for name, path in installed:
1575
+ print(f"[OK] {name:<22} -> {path}")
1576
+
1577
+
1578
+ def cmd_bench(args):
1579
+ """Execute or inspect agent durability benchmarks (DCP-1.0)."""
1580
+ import subprocess
1581
+
1582
+ framework = getattr(args, "framework", "letitloop")
1583
+ signal = getattr(args, "signal", "SIGKILL")
1584
+ print(f"Executing Durability Conformance Benchmark for '{framework}' (Signal: {signal})...")
1585
+
1586
+ try:
1587
+ res = subprocess.run(
1588
+ [sys.executable, "-m", "harness.runner", "--framework", framework, "--signal", signal], capture_output=False
1589
+ )
1590
+ sys.exit(res.returncode)
1591
+ except Exception as e:
1592
+ print(f"Durability benchmark execution error: {e}")
1593
+ print("Tip: Install agent-durability-bench via: pip install agent-durability-bench")
1594
+ print("Or run standalone: durability-bench --framework letitloop")
1595
+
1596
+
1597
+ def cmd_action(args):
1598
+ """Generate or verify GitHub Actions configuration for LetItLoop Proof-Carrying CI."""
1599
+ if getattr(args, "init", False):
1600
+ workflow_dir = os.path.join(WORKSPACE_ROOT, ".github", "workflows")
1601
+ os.makedirs(workflow_dir, exist_ok=True)
1602
+ workflow_file = os.path.join(workflow_dir, "letitloop-verify.yml")
1603
+ workflow_yaml = """name: LetItLoop Verification Gate
1604
+
1605
+ on:
1606
+ pull_request:
1607
+ branches: [ main, master ]
1608
+
1609
+ permissions:
1610
+ contents: read
1611
+ pull-requests: write
1612
+
1613
+ jobs:
1614
+ verify:
1615
+ runs-on: ubuntu-latest
1616
+ steps:
1617
+ - name: Checkout code
1618
+ uses: actions/checkout@v4
1619
+
1620
+ - name: Set up Python
1621
+ uses: actions/setup-python@v5
1622
+ with:
1623
+ python-version: '3.11'
1624
+
1625
+ - name: LetItLoop Proof-Carrying Gate
1626
+ uses: sdageltc/letitloop-action@v1
1627
+ with:
1628
+ github-token: ${{ secrets.GITHUB_TOKEN }}
1629
+ strict-ast: 'true'
1630
+ test-command: 'pytest -q'
1631
+ """
1632
+ with open(workflow_file, "w", encoding="utf-8") as f:
1633
+ f.write(workflow_yaml)
1634
+ print(f"Created GitHub Action workflow at: {workflow_file}")
1635
+ print("The LetItLoop verification gate will now run automatically on pull requests.")
1636
+ else:
1637
+ print("LetItLoop GitHub Action (Marketplace: sdageltc/letitloop-action@v1)")
1638
+ print("To install into your repository, run: lil action --init")
1639
+ print("Or add to .github/workflows/letitloop-verify.yml:")
1640
+ print(" uses: sdageltc/letitloop-action@v1")
1641
+
1642
+
1643
+ def cmd_schema(args):
1644
+ """Print bundled canonical JSON Schemas."""
1645
+ _print_json(get_schema(args.kind))
1646
+
1647
+
1648
+ def main():
1649
+ global DEFAULT_RUN_DIR
1650
+ parser = argparse.ArgumentParser(
1651
+ description="Phase-1 Durable Macro-Task Orchestrator",
1652
+ )
1653
+ parser.add_argument(
1654
+ "--version",
1655
+ action="version",
1656
+ version=_version_string(),
1657
+ )
1658
+ parser.add_argument(
1659
+ "--run-dir",
1660
+ default=DEFAULT_RUN_DIR,
1661
+ help=f"run state directory (default: {DEFAULT_RUN_DIR})",
1662
+ )
1663
+
1664
+ sub = parser.add_subparsers(dest="command", required=True)
1665
+
1666
+ p_create = sub.add_parser("create", help="Validate contract and create task state")
1667
+ p_create.add_argument("contract", help="path to contract JSON (relative to workspace root)")
1668
+
1669
+ p_preflight = sub.add_parser("preflight", help="Run preflight checks")
1670
+ p_preflight.add_argument("task_id", help="task ID")
1671
+
1672
+ p_work = sub.add_parser("work", help="Invoke worker")
1673
+ p_work.add_argument("task_id", help="task ID")
1674
+
1675
+ p_verify = sub.add_parser("verify", help="Run verification checks")
1676
+ p_verify.add_argument("task_id", help="task ID")
1677
+
1678
+ p_retry = sub.add_parser("retry", help="Retry a failed task (increment attempt, record changed approach)")
1679
+ p_retry.add_argument("task_id", help="task ID")
1680
+ p_retry.add_argument("--approach", required=True, help="description of changed approach")
1681
+
1682
+ p_qc = sub.add_parser("qc", help="Record QC decision")
1683
+ p_qc.add_argument("task_id", help="task ID")
1684
+ p_qc.add_argument("--passed", action="store_true", help="QC passed")
1685
+ p_qc.add_argument("--reason", default="", help="reason for QC decision")
1686
+
1687
+ p_resume = sub.add_parser("resume", help="Show resume info for a task")
1688
+ p_resume.add_argument("task_id", help="task ID")
1689
+
1690
+ p_handoff = sub.add_parser("handoff", help="Generate session handoff")
1691
+ p_handoff.add_argument("task_id", help="task ID")
1692
+
1693
+ p_status = sub.add_parser("status", help="Show full task state")
1694
+ p_status.add_argument("task_id", help="task ID")
1695
+
1696
+ p_doctor = sub.add_parser(
1697
+ "doctor", help="Diagnose task health and next actions, or system environment if no task_id given"
1698
+ )
1699
+ p_doctor.add_argument("task_id", nargs="?", default=None, help="task ID")
1700
+ p_doctor.add_argument(
1701
+ "--probe", action="store_true", help="Perform lightweight network reachability probe on configured endpoints"
1702
+ )
1703
+
1704
+ p_propose = sub.add_parser("propose", help="Propose a plan: intake -> plan -> preview -> approval check")
1705
+ p_propose.add_argument("--goal-id", help="Goal ID (auto-generated from prompt if not given)")
1706
+ p_propose.add_argument("--title", default="", help="Goal title (defaults to prompt)")
1707
+ p_propose.add_argument("--description", default="", help="Goal description (defaults to prompt)")
1708
+ p_propose.add_argument("--constraints", default="{}", help="Goal constraints JSON string")
1709
+ p_propose.add_argument("--run", "-y", "--yes", action="store_true", help="Auto-approve and execute immediately")
1710
+ p_propose.add_argument("prompt", nargs="?", default="", help="Natural language task prompt")
1711
+
1712
+ p_approve = sub.add_parser("approve", help="Approve a proposed plan (defaults to latest goal if omitted)")
1713
+ p_approve.add_argument("goal_id", nargs="?", default=None, help="Goal ID")
1714
+
1715
+ p_run_approved = sub.add_parser(
1716
+ "run-approved", help="Execute an approved plan (defaults to latest goal if omitted)"
1717
+ )
1718
+ p_run_approved.add_argument("goal_id", nargs="?", default=None, help="Goal ID")
1719
+ p_run_approved.add_argument("--force", action="store_true", help="Force acquire lock if stale")
1720
+ p_run_approved.add_argument(
1721
+ "--worktree",
1722
+ action="store_true",
1723
+ help="Run contract attempts inside ephemeral git worktree sandboxes (merge back only on PASS)",
1724
+ )
1725
+
1726
+ p_plan_preview = sub.add_parser("plan-preview", help="Show plan preview for a goal")
1727
+ p_plan_preview.add_argument("goal_id", help="Goal ID")
1728
+
1729
+ p_goal_create = sub.add_parser("goal-create", help="Create a Goal JSON")
1730
+ p_goal_create.add_argument("--goal-id", required=True, help="Goal ID")
1731
+ p_goal_create.add_argument("--title", default="", help="Goal title")
1732
+ p_goal_create.add_argument("--description", default="", help="Goal description")
1733
+ p_goal_create.add_argument("--constraints", default="{}", help="Goal constraints JSON string")
1734
+ p_goal_create.add_argument("--out", help="Output file path for goal JSON")
1735
+
1736
+ p_plan = sub.add_parser("plan", help="Generate plan for a Goal")
1737
+ p_plan.add_argument("goal_id", help="Goal ID or path")
1738
+
1739
+ p_plan_check = sub.add_parser("plan-check", help="Run quality checks on a plan")
1740
+ p_plan_check.add_argument("goal_id", help="Goal ID or path")
1741
+
1742
+ p_supervise = sub.add_parser("supervise", help="Supervise and execute contracts for a Goal")
1743
+ p_supervise.add_argument("goal_id", help="Goal ID")
1744
+ p_supervise.add_argument(
1745
+ "--worktree",
1746
+ action="store_true",
1747
+ help="Run contract attempts inside ephemeral git worktree sandboxes (merge back only on PASS)",
1748
+ )
1749
+
1750
+ p_sup_resume = sub.add_parser("supervise-resume", help="Resume supervision for a partially-executed Goal")
1751
+ p_sup_resume.add_argument("goal_id", help="Goal ID")
1752
+ p_sup_resume.add_argument(
1753
+ "--worktree",
1754
+ action="store_true",
1755
+ help="Run contract attempts inside ephemeral git worktree sandboxes (merge back only on PASS)",
1756
+ )
1757
+
1758
+ p_sup_status = sub.add_parser("supervise-status", help="Show goal supervise status")
1759
+ p_sup_status.add_argument("goal_id", help="Goal ID")
1760
+
1761
+ p_goal_result = sub.add_parser("goal-result", help="Aggregate results for a Goal")
1762
+ p_goal_result.add_argument("goal_id", help="Goal ID")
1763
+
1764
+ p_evidence = sub.add_parser("evidence-flow", help="Show evidence propagation for a supervised goal")
1765
+ p_evidence.add_argument("goal_id", help="Goal ID")
1766
+ p_evidence.add_argument("--json", action="store_true", help="Output as JSON")
1767
+
1768
+ p_evidence_ledger = sub.add_parser("evidence-ledger", help="Show evidence ledger for a supervised goal")
1769
+ p_evidence_ledger.add_argument("goal_id", help="Goal ID")
1770
+
1771
+ p_scope = sub.add_parser("scope-check", help="Check for filesystem scope violations")
1772
+ p_scope.add_argument("goal_id", help="Goal ID")
1773
+ p_scope.add_argument("--json", action="store_true", help="Output as JSON")
1774
+
1775
+ p_reconcile = sub.add_parser("reconcile", help="Run reconciliation checks on a goal")
1776
+ p_reconcile.add_argument("goal_id", help="Goal ID")
1777
+ p_reconcile.add_argument("--json", action="store_true", help="Output as JSON")
1778
+
1779
+ p_prov = sub.add_parser("provenance", help="Show provenance graph for a goal")
1780
+ p_prov.add_argument("goal_id", help="Goal ID")
1781
+ p_prov.add_argument("--json", action="store_true", help="Output as JSON")
1782
+
1783
+ p_err = sub.add_parser("error-inspect", help="Show structured errors for a goal")
1784
+ p_err.add_argument("goal_id", help="Goal ID")
1785
+ p_err.add_argument("--json", action="store_true", help="Output as JSON")
1786
+
1787
+ p_imp = sub.add_parser("impossibility", help="Show impossibility artifacts for an escalated goal")
1788
+ p_imp.add_argument("goal_id", help="Goal ID")
1789
+ p_imp.add_argument("--json", action="store_true", help="Output as JSON")
1790
+
1791
+ p_fail = sub.add_parser("failure-report", help="Show failure classification and remediation for a goal")
1792
+ p_fail.add_argument("goal_id", help="Goal ID")
1793
+ p_fail.add_argument("--json", action="store_true", help="Output as JSON")
1794
+
1795
+ p_fb = sub.add_parser("feedback", help="Show failure feedback history for a goal")
1796
+ p_fb.add_argument("goal_id", help="Goal ID")
1797
+ p_fb.add_argument("--json", action="store_true", help="Output as JSON")
1798
+
1799
+ p_config = sub.add_parser("config", help="Show orchestrator configuration")
1800
+ p_config.add_argument("--path", default="", help="Path to config JSON file")
1801
+
1802
+ p_audit = sub.add_parser("audit", help="Show audit log for a goal")
1803
+ p_audit.add_argument("goal_id", help="Goal ID")
1804
+ p_audit.add_argument("--action", default="", help="Filter by action type")
1805
+ p_audit.add_argument("--task-id", default="", help="Filter by task ID")
1806
+ p_audit.add_argument("--json", action="store_true", help="Output as JSON")
1807
+
1808
+ p_metrics = sub.add_parser("metrics", help="Show runtime metrics for a goal")
1809
+ p_metrics.add_argument("goal_id", help="Goal ID")
1810
+ p_metrics.add_argument("--json", action="store_true", help="Output as JSON")
1811
+
1812
+ p_safety = sub.add_parser("safety-check", help="Run pre-execution safety checks on a plan")
1813
+ p_safety.add_argument("goal_id", help="Goal ID")
1814
+ p_safety.add_argument("--json", action="store_true", help="Output as JSON")
1815
+
1816
+ p_cp_list = sub.add_parser("checkpoint-list", help="List checkpoints for a goal")
1817
+ p_cp_list.add_argument("goal_id", help="Goal ID")
1818
+ p_cp_list.add_argument("--json", action="store_true", help="Output as JSON")
1819
+
1820
+ p_cp_recover = sub.add_parser("checkpoint-recover", help="Recover plan state from latest checkpoint")
1821
+ p_cp_recover.add_argument("goal_id", help="Goal ID")
1822
+ p_cp_recover.add_argument("--json", action="store_true", help="Output as JSON")
1823
+ p_cp_recover.add_argument("--apply", action="store_true", help="Apply recovery (not yet implemented)")
1824
+
1825
+ p_cp_clear = sub.add_parser("checkpoint-clear", help="Remove all checkpoints for a goal")
1826
+ p_cp_clear.add_argument("goal_id", help="Goal ID")
1827
+
1828
+ p_pause = sub.add_parser("pause", help="Pause all active tasks in a goal")
1829
+ p_pause.add_argument("goal_id", help="Goal ID")
1830
+ p_pause.add_argument("--reason", default="", help="Reason for pausing")
1831
+
1832
+ p_cancel = sub.add_parser("cancel", help="Cancel all non-terminal tasks in a goal")
1833
+ p_cancel.add_argument("goal_id", help="Goal ID")
1834
+ p_cancel.add_argument("--reason", default="", help="Reason for cancelling")
1835
+
1836
+ p_inspect = sub.add_parser("inspect", help="Deep inspect a single task")
1837
+ p_inspect.add_argument("goal_id", help="Goal ID")
1838
+ p_inspect.add_argument("task_id", help="Task ID")
1839
+ p_inspect.add_argument("--json", action="store_true", help="Output as JSON")
1840
+
1841
+ p_dryrun = sub.add_parser("dry-run", help="Simulate plan execution without real worker calls")
1842
+ p_dryrun.add_argument("goal_id", help="Goal ID")
1843
+
1844
+ p_dash = sub.add_parser("dashboard", help="Render rich terminal UI dashboard")
1845
+ p_dash.add_argument("--live", action="store_true", help="Continuously refresh the dashboard until quit")
1846
+ p_dash.add_argument(
1847
+ "--interval",
1848
+ type=float,
1849
+ default=2.0,
1850
+ help="Refresh interval in seconds for --live mode (default: 2.0)",
1851
+ )
1852
+ p_dash.add_argument("--once", action="store_true", help="Render a single dashboard frame and exit")
1853
+
1854
+ p_serve = sub.add_parser("serve", help="Stream lifecycle events over SSE (GET /events)")
1855
+ p_serve.add_argument("--host", default="127.0.0.1", help="Bind host (default: 127.0.0.1)")
1856
+ p_serve.add_argument("--port", type=int, default=8080, help="Bind port (default: 8080)")
1857
+ p_serve.add_argument(
1858
+ "--webhooks-json",
1859
+ default="",
1860
+ help="Path to webhook configs JSON (overrides LETITLOOP_WEBHOOKS_JSON)",
1861
+ )
1862
+
1863
+ p_trace = sub.add_parser("trace", help="Render step-by-step reasoning and verification trace for a goal")
1864
+ p_trace.add_argument("goal_id", nargs="?", default=None, help="Goal ID (defaults to latest)")
1865
+
1866
+ p_skill = sub.add_parser("install-skill", help="Install letitloop skill across AI coding assistant environments")
1867
+ p_skill.add_argument(
1868
+ "--target",
1869
+ choices=["all", "claude", "antigravity", "hermes", "opencode", "cursor", "cline", "windsurf", "codex"],
1870
+ default="all",
1871
+ help="Target AI assistant environment (default: all)",
1872
+ )
1873
+ p_skill.add_argument(
1874
+ "--workspace",
1875
+ type=str,
1876
+ default=".",
1877
+ help="Target workspace path for project-local skill installation (default: current directory)",
1878
+ )
1879
+
1880
+ p_bench = sub.add_parser("bench", help="Run agent durability conformance benchmark (DCP-1.0)")
1881
+ p_bench.add_argument("--framework", default="letitloop", help="Target framework adapter (default: letitloop)")
1882
+ p_bench.add_argument("--signal", default="SIGKILL", help="Fault signal to inject (default: SIGKILL)")
1883
+
1884
+ p_action = sub.add_parser("action", help="Generate or inspect LetItLoop GitHub Action for Proof-Carrying CI")
1885
+ p_action.add_argument(
1886
+ "--init", action="store_true", help="Generate .github/workflows/letitloop-verify.yml workflow file"
1887
+ )
1888
+
1889
+ p_schema = sub.add_parser("schema", help="Print a bundled JSON Schema")
1890
+ p_schema.add_argument(
1891
+ "--kind",
1892
+ choices=["contract", "goal", "mcp"],
1893
+ default="contract",
1894
+ help="Schema kind to output (default: contract)",
1895
+ )
1896
+
1897
+ cmds = {
1898
+ "schema": cmd_schema,
1899
+ "bench": cmd_bench,
1900
+ "action": cmd_action,
1901
+ "create": cmd_create,
1902
+ "preflight": cmd_preflight,
1903
+ "work": cmd_work,
1904
+ "verify": cmd_verify,
1905
+ "retry": cmd_retry,
1906
+ "qc": cmd_qc_pass,
1907
+ "resume": cmd_resume,
1908
+ "handoff": cmd_handoff,
1909
+ "status": cmd_status,
1910
+ "doctor": cmd_doctor,
1911
+ "dashboard": cmd_dashboard,
1912
+ "serve": cmd_serve,
1913
+ "trace": cmd_trace,
1914
+ "install-skill": cmd_install_skill,
1915
+ "install_skill": cmd_install_skill,
1916
+ "goal-create": cmd_goal_create,
1917
+ "propose": cmd_propose,
1918
+ "approve": cmd_approve,
1919
+ "run-approved": cmd_run_approved,
1920
+ "run_approved": cmd_run_approved,
1921
+ "plan": cmd_plan,
1922
+ "plan-preview": cmd_plan_preview,
1923
+ "plan_preview": cmd_plan_preview,
1924
+ "plan-check": cmd_plan_check,
1925
+ "plan_check": cmd_plan_check,
1926
+ "supervise": cmd_supervise,
1927
+ "supervise-resume": cmd_supervise_resume,
1928
+ "supervise_resume": cmd_supervise_resume,
1929
+ "supervise-status": cmd_supervise_status,
1930
+ "supervise_status": cmd_supervise_status,
1931
+ "goal-result": cmd_goal_result,
1932
+ "goal_result": cmd_goal_result,
1933
+ "evidence-flow": cmd_evidence_flow,
1934
+ "evidence_flow": cmd_evidence_flow,
1935
+ "evidence-ledger": cmd_evidence_ledger,
1936
+ "evidence_ledger": cmd_evidence_ledger,
1937
+ "scope-check": cmd_scope_check,
1938
+ "scope_check": cmd_scope_check,
1939
+ "reconcile": cmd_reconcile,
1940
+ "provenance": cmd_provenance,
1941
+ "error-inspect": cmd_error_inspect,
1942
+ "error_inspect": cmd_error_inspect,
1943
+ "impossibility": cmd_impossibility,
1944
+ "failure-report": cmd_failure_report,
1945
+ "failure_report": cmd_failure_report,
1946
+ "feedback": cmd_feedback,
1947
+ "config": cmd_config,
1948
+ "audit": cmd_audit,
1949
+ "metrics": cmd_metrics,
1950
+ "safety-check": cmd_safety_check,
1951
+ "safety_check": cmd_safety_check,
1952
+ "checkpoint-list": cmd_checkpoint_list,
1953
+ "checkpoint_list": cmd_checkpoint_list,
1954
+ "checkpoint-recover": cmd_checkpoint_recover,
1955
+ "checkpoint_recover": cmd_checkpoint_recover,
1956
+ "checkpoint-clear": cmd_checkpoint_clear,
1957
+ "checkpoint_clear": cmd_checkpoint_clear,
1958
+ "dry-run": cmd_dryrun,
1959
+ "dry_run": cmd_dryrun,
1960
+ "pause": cmd_pause,
1961
+ "cancel": cmd_cancel,
1962
+ "inspect": cmd_inspect,
1963
+ }
1964
+
1965
+ a = parser.parse_args()
1966
+ DEFAULT_RUN_DIR = a.run_dir # noqa: PLW0603
1967
+ cmds[a.command](a)
1968
+
1969
+
1970
+ if __name__ == "__main__":
1971
+ main()