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/tui.py ADDED
@@ -0,0 +1,649 @@
1
+ """Terminal UI and ASCII Dashboard for letitloop.
2
+
3
+ Renders rich progress trees, DAG execution graphs, state matrices,
4
+ and telemetry directly to the console without heavy external GUI dependencies.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime
10
+ import json
11
+ import os
12
+ import sys
13
+ import time
14
+ from typing import Any, Callable, Dict, List, Optional
15
+
16
+
17
+ class TerminalDashboard:
18
+ """Zero-dependency rich terminal dashboard for letitloop runs."""
19
+
20
+ # Unicode icons with clean ASCII fallback
21
+ STATUS_ICONS = {
22
+ "DRAFTED": "[DRAFT]",
23
+ "PLANNED": "[PLAN]",
24
+ "PLANNING": "[PLAN]",
25
+ "RUNNING": "[RUN]",
26
+ "WORKING": "[WORK]",
27
+ "EXECUTING": "[EXEC]",
28
+ "VERIFYING": "[VERIFY]",
29
+ "VERIFIED": "[VERIFIED]",
30
+ "QC_PENDING": "[QC]",
31
+ "QC_PASS": "[QC_PASS]",
32
+ "QC_PASSED": "[QC_PASS]",
33
+ "COMPLETE": "[COMPLETE]",
34
+ "FAILED": "[FAIL]",
35
+ "CRASHED": "[CRASH]",
36
+ "ESCALATED": "[ESCALATE]",
37
+ "RETRY_PENDING": "[RETRY]",
38
+ "DEGRADED_PASS": "[DEGRADED]",
39
+ "PAUSED": "[PAUSED]",
40
+ "CANCELLED": "[CANCELLED]",
41
+ }
42
+
43
+ @classmethod
44
+ def render_header(cls, title: str = "letitloop (LIL) — Autonomous Macro-Task Orchestrator") -> str:
45
+ bar = "=" * 78
46
+ return f"\n{bar}\n {title}\n{bar}\n"
47
+
48
+ @classmethod
49
+ def render_goal_summary(cls, goal_dict: Dict[str, Any], plan_dict: Optional[Dict[str, Any]] = None) -> str:
50
+ lines = []
51
+ gid = goal_dict.get("goal_id", "unknown")
52
+ gtitle = goal_dict.get("title", "Untitled Goal")
53
+ gstatus = goal_dict.get("status", "DRAFTED")
54
+ icon = cls.STATUS_ICONS.get(gstatus, "[STATUS]")
55
+
56
+ lines.append(f" * Goal: [{gid}] {gtitle}")
57
+ lines.append(f" * Status: {icon} {gstatus}")
58
+
59
+ if plan_dict and "contracts" in plan_dict:
60
+ contracts = plan_dict["contracts"]
61
+ lines.append(f" * Plan DAG: {len(contracts)} tasks scheduled")
62
+ lines.append(" " + "-" * 74)
63
+ for idx, c in enumerate(contracts, 1):
64
+ tid = c.get("task_id", f"task_{idx}")
65
+ obj = c.get("objective", "No objective specified")
66
+ tier = c.get("risk_tier", "standard")
67
+ lines.append(f" [{idx:02d}] - {tid:<20} | Tier: {tier:<8} | {obj[:35]}")
68
+
69
+ lines.append("=" * 78 + "\n")
70
+ return "\n".join(lines)
71
+
72
+ @classmethod
73
+ def render_run_status(cls, run_dir: str) -> str:
74
+ """Inspect and format the live status of all goals/tasks in a run directory."""
75
+ if not os.path.isdir(run_dir):
76
+ return f"No active run directory found at: {run_dir}\n"
77
+
78
+ # Case 1: Single Goal directory (contains goal.json or plan.json)
79
+ goal_file = os.path.join(run_dir, "goal.json")
80
+ plan_file = os.path.join(run_dir, "plan.json")
81
+ if os.path.isfile(goal_file):
82
+ try:
83
+ with open(goal_file, "r", encoding="utf-8") as f:
84
+ goal_data = json.load(f)
85
+ plan_data = None
86
+ if os.path.isfile(plan_file):
87
+ with open(plan_file, "r", encoding="utf-8") as pf:
88
+ plan_data = json.load(pf)
89
+ return cls.render_goal_summary(goal_data, plan_data)
90
+ except Exception as e:
91
+ return f"Error reading goal state: {e}\n"
92
+
93
+ # Case 2: Root runs directory containing multiple goal folders
94
+ lines = [cls.render_header("Active Orchestrator Runs Matrix")]
95
+ entries = sorted([f for f in os.listdir(run_dir) if os.path.isdir(os.path.join(run_dir, f))])
96
+
97
+ if not entries:
98
+ lines.append(" (No runs found in directory)")
99
+ else:
100
+ lines.append(f" {'Goal / Task ID':<32} {'Status':<16} {'Tasks':<12} {'Details':<14}")
101
+ lines.append(" " + "-" * 74)
102
+
103
+ for folder in entries:
104
+ fpath = os.path.join(run_dir, folder)
105
+ g_json = os.path.join(fpath, "goal.json")
106
+ s_json = os.path.join(fpath, "state.json")
107
+
108
+ if os.path.isfile(g_json):
109
+ try:
110
+ with open(g_json, "r", encoding="utf-8") as f:
111
+ g_data = json.load(f)
112
+ st = g_data.get("status", "DRAFTED")
113
+ title = g_data.get("title", "")
114
+ # Count child task folders
115
+ subfolders = [
116
+ sf
117
+ for sf in os.listdir(fpath)
118
+ if os.path.isdir(os.path.join(fpath, sf)) and sf not in ("state_backups", "checkpoints")
119
+ ]
120
+ icon = cls.STATUS_ICONS.get(st, "[STATUS]")
121
+ lines.append(f" {folder:<32} {icon:<14} {len(subfolders):<12} {title[:14]}")
122
+ except Exception:
123
+ lines.append(f" {folder:<32} [ERROR] Corrupt goal.json")
124
+ elif os.path.isfile(s_json):
125
+ try:
126
+ with open(s_json, "r", encoding="utf-8") as f:
127
+ s_data = json.load(f)
128
+ st = s_data.get("status", "UNKNOWN")
129
+ att = s_data.get("attempt", 1)
130
+ icon = cls.STATUS_ICONS.get(st, "[STATUS]")
131
+ lines.append(f" {folder:<32} {icon:<14} {'attempt ' + str(att):<12} {'single task'}")
132
+ except Exception:
133
+ lines.append(f" {folder:<32} [ERROR] Corrupt state.json")
134
+ else:
135
+ lines.append(f" {folder:<32} [INIT] Empty run folder")
136
+
137
+ lines.append("=" * 78 + "\n")
138
+ return "\n".join(lines)
139
+
140
+
141
+ def print_dashboard(run_dir: str) -> None:
142
+ """Print terminal dashboard output safely to stdout."""
143
+ out = TerminalDashboard.render_run_status(run_dir)
144
+ try:
145
+ sys.stdout.write(out)
146
+ sys.stdout.flush()
147
+ except UnicodeEncodeError:
148
+ # Fallback for strict Windows charmap encodings
149
+ safe_out = out.encode("ascii", errors="replace").decode("ascii")
150
+ sys.stdout.write(safe_out)
151
+ sys.stdout.flush()
152
+
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # ANSI color support (zero-dependency; NO_COLOR respected)
156
+ # ---------------------------------------------------------------------------
157
+
158
+ RESET = "\x1b[0m"
159
+
160
+ STATE_COLORS: Dict[str, str] = {
161
+ # planning
162
+ "DRAFTED": "\x1b[90m",
163
+ "PLANNED": "\x1b[36m",
164
+ "PLANNING": "\x1b[36m",
165
+ # queued / ready
166
+ "READY": "\x1b[36m",
167
+ "PREFLIGHT_RUNNING": "\x1b[33m",
168
+ # active work
169
+ "RUNNING": "\x1b[33m",
170
+ "WORKING": "\x1b[33m",
171
+ "WORK": "\x1b[33m",
172
+ "EXECUTING": "\x1b[33m",
173
+ # verification
174
+ "VERIFYING": "\x1b[96m",
175
+ "VERIFIED": "\x1b[92m",
176
+ "VERIFICATION_FAILED": "\x1b[91m",
177
+ # QC family + aliases
178
+ "QC_RUNNING": "\x1b[96m",
179
+ "QC_REVIEW": "\x1b[95m",
180
+ "QC_PENDING": "\x1b[95m",
181
+ "QC_PASS": "\x1b[92m",
182
+ "QC_PASSED": "\x1b[92m",
183
+ "QC_FAILED": "\x1b[91m",
184
+ "QC_REJECTED": "\x1b[91m",
185
+ "QC_INSUFFICIENT_EVIDENCE": "\x1b[95m",
186
+ "QC_CONDITIONAL_PASS": "\x1b[93m",
187
+ # terminal outcomes
188
+ "COMPLETE": "\x1b[92m",
189
+ "FORCE_COMPLETE": "\x1b[92m",
190
+ "DEGRADED_PASS": "\x1b[92m",
191
+ "FAILED": "\x1b[91m",
192
+ "CRASHED": "\x1b[91m",
193
+ "BLOCKED": "\x1b[31m",
194
+ "ESCALATED": "\x1b[35m",
195
+ # retry lifecycle
196
+ "RETRY": "\x1b[93m",
197
+ "RETRY_PENDING": "\x1b[93m",
198
+ "PAUSED": "\x1b[94m",
199
+ "CANCELLED": "\x1b[90m",
200
+ }
201
+
202
+
203
+ def color_enabled(out: Any = None) -> bool:
204
+ """True when ANSI escape sequences should be emitted.
205
+
206
+ Respects the NO_COLOR convention (https://no-color.org): any value set in
207
+ the environment disables all escape output.
208
+ """
209
+ if os.environ.get("NO_COLOR"):
210
+ return False
211
+ return True
212
+
213
+
214
+ def colorize_status(status: str, text: Optional[str] = None, enabled: bool = True) -> str:
215
+ """Wrap a status label with its ANSI color code (plain text when disabled)."""
216
+ body = text if text is not None else status
217
+ if not enabled:
218
+ return body
219
+ code = STATE_COLORS.get((status or "").upper())
220
+ if not code:
221
+ return body
222
+ return f"{code}{body}{RESET}"
223
+
224
+
225
+ def _stream_is_ascii(stream: Any) -> bool:
226
+ """Best-effort detection of streams that cannot encode box-drawing chars."""
227
+ enc = getattr(stream, "encoding", None)
228
+ if not enc:
229
+ return False # StringIO and similar in-memory streams handle unicode
230
+ try:
231
+ "\u251c\u2500".encode(enc) # box-drawing chars used by render_dag_tree
232
+ except (UnicodeEncodeError, LookupError):
233
+ return True
234
+ return False
235
+
236
+
237
+ # Box-drawing glyphs with ASCII fallbacks
238
+ GLYPHS_UNICODE = {"branch": "\u251c\u2500\u2500 ", "last": "\u2514\u2500\u2500 ", "pipe": "\u2502 ", "space": " "}
239
+ GLYPHS_ASCII = {"branch": "|-- ", "last": "`-- ", "pipe": "| ", "space": " "}
240
+
241
+
242
+ def render_dag_tree(
243
+ plan: Optional[Dict[str, Any]] = None,
244
+ goal: Optional[Dict[str, Any]] = None,
245
+ status_map: Optional[Dict[str, str]] = None,
246
+ ascii_mode: bool = False,
247
+ ) -> List[str]:
248
+ """Render plan contracts as an indented dependency tree.
249
+
250
+ Lines look like::
251
+
252
+ root_task
253
+ |-- child_a
254
+ | `-- grandchild
255
+ `-- child_b
256
+
257
+ Dependencies (``depends_on`` edges) drive indentation. Cycles are safe.
258
+ """
259
+ contracts: List[Dict[str, Any]] = []
260
+ if plan and isinstance(plan.get("contracts"), list):
261
+ contracts = [c for c in plan["contracts"] if isinstance(c, dict)]
262
+ elif goal and isinstance(goal.get("plan"), dict):
263
+ nested = goal["plan"]
264
+ if isinstance(nested.get("contracts"), list):
265
+ contracts = [c for c in nested["contracts"] if isinstance(c, dict)]
266
+
267
+ ids_in_order = [str(c.get("task_id", f"task_{i}")) for i, c in enumerate(contracts, 1)]
268
+ id_set = set(ids_in_order)
269
+
270
+ children: Dict[str, List[str]] = {tid: [] for tid in ids_in_order}
271
+ roots: List[str] = []
272
+ seen_root = set()
273
+ for c in contracts:
274
+ tid = str(c.get("task_id", ""))
275
+ deps = c.get("depends_on") or []
276
+ if not isinstance(deps, list):
277
+ deps = []
278
+ internal_deps = [d for d in deps if d in id_set]
279
+ if not internal_deps:
280
+ if tid not in seen_root:
281
+ roots.append(tid)
282
+ seen_root.add(tid)
283
+ continue
284
+ for d in internal_deps:
285
+ children[d].append(tid)
286
+
287
+ glyphs = GLYPHS_ASCII if ascii_mode else GLYPHS_UNICODE
288
+ lines: List[str] = []
289
+ visited = set()
290
+
291
+ def walk(tid: str, node_prefix: str, child_base: str) -> None:
292
+ if tid in visited:
293
+ return
294
+ visited.add(tid)
295
+ label = tid
296
+ if status_map:
297
+ st = status_map.get(tid)
298
+ if st:
299
+ icon = TerminalDashboard.STATUS_ICONS.get(str(st).upper(), "[STATUS]")
300
+ label = f"{tid} {icon}"
301
+ lines.append(node_prefix + label)
302
+ kids = [k for k in children.get(tid, []) if k not in visited]
303
+ for i, kid in enumerate(kids):
304
+ is_last = i == len(kids) - 1
305
+ connector = glyphs["last"] if is_last else glyphs["branch"]
306
+ cont = glyphs["space"] if is_last else glyphs["pipe"]
307
+ walk(kid, child_base + connector, child_base + cont)
308
+
309
+ roots_final = roots if roots else ids_in_order[:1]
310
+ for r in roots_final:
311
+ walk(r, "", "")
312
+ # Any tasks unreachable due to cycles get appended flat so nothing is lost
313
+ for tid in ids_in_order:
314
+ if tid not in visited:
315
+ lines.append(glyphs["branch"] + tid)
316
+ visited.add(tid)
317
+ if not lines:
318
+ lines.append("(empty plan)")
319
+ return lines
320
+
321
+
322
+ def render_budget_gauge(used_tokens: float, max_tokens: float, width: int = 30) -> str:
323
+ """Render a ``[#####-----]`` token usage bar with ``used/max (pct%)`` suffix."""
324
+ try:
325
+ max_tokens_f = float(max_tokens) if max_tokens else 0.0
326
+ used_tokens_f = max(0.0, float(used_tokens))
327
+ except (TypeError, ValueError):
328
+ return "-"
329
+ width = max(int(width), 1)
330
+ if max_tokens_f <= 0:
331
+ return "-"
332
+ ratio = used_tokens_f / max_tokens_f
333
+ ratio = min(max(ratio, 0.0), 1.0)
334
+ filled = int(round(ratio * width))
335
+ filled = min(max(filled, 0), width)
336
+ bar = "[" + "#" * filled + "-" * (width - filled) + "]"
337
+ pct = int(round(ratio * 100))
338
+ used_disp = int(used_tokens_f) if float(used_tokens_f).is_integer() else used_tokens_f
339
+ max_disp = int(max_tokens_f) if max_tokens_f.is_integer() else max_tokens_f
340
+ return f"{bar} {used_disp}/{max_disp} ({pct}%)"
341
+
342
+
343
+ _BUDGET_FILE_CANDIDATES = ("usage.json", "budget.json", "token_usage.json", "usage_ledger.json")
344
+ _LOCK_FILENAME = ".goal.lock"
345
+
346
+
347
+ class LiveDashboard:
348
+ """Single-frame / live-loop terminal dashboard fed from run_dir artifacts.
349
+
350
+ All rendering goes through ``self.out.write`` so tests can inject any
351
+ file-like object. Keyboard handling uses an injectable ``key_reader``
352
+ callable; the real stdin reader is built lazily only when stdin is a tty.
353
+ """
354
+
355
+ PANE_DAG = "dag"
356
+ PANE_METRICS = "metrics"
357
+
358
+ def __init__(self, run_dir: str, interval: float = 2.0, out: Any = None):
359
+ self.run_dir = run_dir
360
+ self.interval = max(float(interval), 0.0)
361
+ self.out = out if out is not None else sys.stdout
362
+ self.active_pane = self.PANE_DAG
363
+ self._ascii_mode = _stream_is_ascii(self.out)
364
+ self._use_color = color_enabled(self.out)
365
+ self._frames_written = 0
366
+ self._stdin_reader: Optional[Callable[[], Optional[str]]] = None
367
+
368
+ # -- data collection ----------------------------------------------------
369
+
370
+ @staticmethod
371
+ def _load_json(path: str) -> Optional[Dict[str, Any]]:
372
+ if not os.path.isfile(path):
373
+ return None
374
+ try:
375
+ with open(path, "r", encoding="utf-8") as f:
376
+ data = json.load(f)
377
+ return data if isinstance(data, dict) else None
378
+ except (OSError, ValueError):
379
+ return None
380
+
381
+ @staticmethod
382
+ def _extract_usage(data: Dict[str, Any]) -> Optional[Dict[str, float]]:
383
+ """Pull token usage numbers out of a persisted artifact dict."""
384
+ total = data.get("total_tokens")
385
+ if isinstance(total, (int, float)) and not isinstance(total, bool):
386
+ usage: Dict[str, float] = {"used": float(total)}
387
+ cap = data.get("max_tokens", data.get("token_max", data.get("budget_max_tokens")))
388
+ if isinstance(cap, (int, float)) and not isinstance(cap, bool) and cap > 0:
389
+ usage["max"] = float(cap)
390
+ return usage
391
+ return None
392
+
393
+ def collect(self) -> Dict[str, Any]:
394
+ goal_data = self._load_json(os.path.join(self.run_dir, "goal.json")) or {}
395
+ plan_data = self._load_json(os.path.join(self.run_dir, "plan.json")) or {}
396
+ metrics_data = self._load_json(os.path.join(self.run_dir, "metrics.json")) or {}
397
+
398
+ states: Dict[str, Dict[str, Any]] = {}
399
+ leases = 0
400
+ attempts_total = 0
401
+ if os.path.isdir(self.run_dir):
402
+ if os.path.isfile(os.path.join(self.run_dir, _LOCK_FILENAME)):
403
+ leases += 1
404
+ for entry in sorted(os.listdir(self.run_dir)):
405
+ spath = os.path.join(self.run_dir, entry, "state.json")
406
+ sdata = self._load_json(spath)
407
+ if sdata is not None:
408
+ states[entry] = sdata
409
+ att = sdata.get("attempt", 1)
410
+ if isinstance(att, (int, float)):
411
+ attempts_total += int(att)
412
+
413
+ # metrics attempt_counts are additive with on-disk states
414
+ mc_attempts = metrics_data.get("attempt_counts") or {}
415
+ metrics_attempts_total = 0
416
+ if isinstance(mc_attempts, dict):
417
+ metrics_attempts_total = sum(v for v in mc_attempts.values() if isinstance(v, (int, float)))
418
+
419
+ usage: Optional[Dict[str, float]] = None
420
+ if os.path.isdir(self.run_dir):
421
+ candidates = list(_BUDGET_FILE_CANDIDATES)
422
+ try:
423
+ candidates += [f for f in os.listdir(self.run_dir) if f.endswith(".json")]
424
+ except OSError:
425
+ pass
426
+ seen_files = set()
427
+ for fname in candidates:
428
+ if fname in seen_files:
429
+ continue
430
+ seen_files.add(fname)
431
+ blob = self._load_json(os.path.join(self.run_dir, fname))
432
+ if blob is not None:
433
+ usage = self._extract_usage(blob)
434
+ if usage:
435
+ break
436
+
437
+ return {
438
+ "goal": goal_data,
439
+ "plan": plan_data,
440
+ "metrics": metrics_data,
441
+ "states": states,
442
+ "leases": leases,
443
+ "attempts_total": attempts_total,
444
+ "metrics_attempts_total": metrics_attempts_total,
445
+ "usage": usage,
446
+ }
447
+
448
+ # -- frame rendering ----------------------------------------------------
449
+
450
+ def _status_map(self, data: Dict[str, Any]) -> Dict[str, str]:
451
+ return {tid: str(s.get("status", "UNKNOWN")) for tid, s in data["states"].items()}
452
+
453
+ def _render_header(self, data: Dict[str, Any]) -> List[str]:
454
+ bar = "=" * 78
455
+ goal = data["goal"]
456
+ gid = goal.get("goal_id", "-")
457
+ gtitle = goal.get("title", "Untitled Goal")
458
+ gstatus = str(goal.get("status", "DRAFTED"))
459
+ now = datetime.datetime.now().strftime("%H:%M:%S")
460
+ head = f"letitloop LIVE — [{gid}] {gtitle}"
461
+ line1 = f" {head} refresh {now} pane: {self.active_pane} ([tab] panes, [q] quit)"
462
+ colored = colorize_status(gstatus, line1, enabled=self._use_color) if self._use_color else line1
463
+ return [bar, colored, bar]
464
+
465
+ def _render_dag_pane(self, data: Dict[str, Any]) -> List[str]:
466
+ lines: List[str] = ["", " Task DAG:"]
467
+ tree = render_dag_tree(plan=data["plan"], goal=data["goal"], ascii_mode=self._ascii_mode)
468
+ lines.extend(" " + line for line in tree)
469
+ lines.append("")
470
+ lines.append(" Contracts:")
471
+ states = data["states"]
472
+ if states:
473
+ for tid, sdata in states.items():
474
+ st = str(sdata.get("status", "UNKNOWN"))
475
+ att = sdata.get("attempt", 1)
476
+ icon = TerminalDashboard.STATUS_ICONS.get(st.upper(), "[STATUS]")
477
+ icon_txt = colorize_status(st, icon, enabled=self._use_color)
478
+ lines.append(f" {tid:<28} {icon_txt:<14} attempt {att}")
479
+ else:
480
+ contracts = (data["plan"] or {}).get("contracts") or []
481
+ if contracts:
482
+ for idx, c in enumerate(contracts, 1):
483
+ tid = c.get("task_id", f"task_{idx}")
484
+ lines.append(f" {tid:<28} {'[INIT]':<14} no state yet")
485
+ else:
486
+ lines.append(" (no task state found)")
487
+ return lines
488
+
489
+ def _render_metrics_pane(self, data: Dict[str, Any]) -> List[str]:
490
+ lines: List[str] = ["", " Phase Timings:"]
491
+ m = data["metrics"]
492
+ phase_elapsed = m.get("phase_elapsed") or {}
493
+ phase_counts = m.get("phase_counts") or {}
494
+ if phase_elapsed:
495
+ lines.append(f" {'phase':<24} {'elapsed':>10} {'runs':>6}")
496
+ for phase in sorted(phase_elapsed):
497
+ el = phase_elapsed.get(phase, 0.0)
498
+ cnt = phase_counts.get(phase, 0)
499
+ lines.append(f" {phase:<24} {el:>9.2f}s {cnt:>6}")
500
+ else:
501
+ lines.append(" (no phase timings recorded)")
502
+ lines.append("")
503
+ lines.append(" Attempt Counts:")
504
+ ac = m.get("attempt_counts") or {}
505
+ if ac:
506
+ for tid in sorted(ac):
507
+ lines.append(f" {tid}: {ac[tid]}")
508
+ else:
509
+ lines.append(" (no retries recorded)")
510
+ total_att = m.get("total_attempts", data["metrics_attempts_total"])
511
+ lines.append(f" total_attempts: {total_att}")
512
+ return lines
513
+
514
+ def render_frame(self, data: Dict[str, Any]) -> str:
515
+ lines: List[str] = self._render_header(data)
516
+ if self.active_pane == self.PANE_METRICS:
517
+ lines.extend(self._render_metrics_pane(data))
518
+ else:
519
+ lines.extend(self._render_dag_pane(data))
520
+
521
+ lines.append("")
522
+ usage = data["usage"]
523
+ if usage:
524
+ used = usage.get("used", 0.0)
525
+ cap = usage.get("max")
526
+ if cap:
527
+ gauge = render_budget_gauge(used, cap, width=30)
528
+ gauge = colorize_status("FAILED" if cap and used >= cap else "WORKING", gauge, enabled=self._use_color)
529
+ lines.append(f" Budget: {gauge}")
530
+ else:
531
+ lines.append(f" Tokens used: {int(used)} (no cap recorded)")
532
+ lines.append(f" Attempts: {data['attempts_total']} | Active leases: {data['leases']}")
533
+ lines.append("=" * 78)
534
+ lines.append("")
535
+ text = "\n".join(lines)
536
+ if self._ascii_mode:
537
+ text = text.encode("ascii", errors="replace").decode("ascii")
538
+ return text
539
+
540
+ def _write_frame(self, frame: str) -> None:
541
+ if self._use_color:
542
+ clear = "\x1b[H\x1b[J"
543
+ if self._frames_written > 0:
544
+ self.out.write(clear)
545
+ else:
546
+ # NO_COLOR / ascii fallback: reprint separated by a blank band
547
+ if self._frames_written > 0:
548
+ self.out.write("\n" * 3)
549
+ self.out.write(frame)
550
+ try:
551
+ self.out.flush()
552
+ except AttributeError:
553
+ pass
554
+ self._frames_written += 1
555
+
556
+ # -- keyboard -----------------------------------------------------------
557
+
558
+ def _default_key_reader(self) -> Optional[str]:
559
+ """Non-blocking single-key read from a real tty (built lazily)."""
560
+ if self._stdin_reader is None:
561
+ try:
562
+ if not sys.stdin.isatty():
563
+ return None
564
+ except (ValueError, OSError, AttributeError):
565
+ return None
566
+ self._stdin_reader = self._build_tty_reader()
567
+ if self._stdin_reader is None:
568
+ return None
569
+ return self._stdin_reader()
570
+
571
+ @staticmethod
572
+ def _build_tty_reader() -> Optional[Callable[[], Optional[str]]]:
573
+ if os.name == "nt":
574
+ try:
575
+ import msvcrt # noqa: F401 - availability probe; used inside read_key_win
576
+ except ImportError:
577
+ return None
578
+
579
+ def read_key_win() -> Optional[str]:
580
+ import msvcrt
581
+
582
+ if msvcrt.kbhit():
583
+ ch = msvcrt.getwch()
584
+ return ch if ch else None
585
+ return None
586
+
587
+ return read_key_win
588
+ try:
589
+ import select
590
+ import termios
591
+ import tty
592
+ except ImportError:
593
+ return None
594
+
595
+ state = {"saved": None}
596
+
597
+ def read_key_posix() -> Optional[str]:
598
+ fd = sys.stdin.fileno()
599
+ if state["saved"] is None:
600
+ state["saved"] = termios.tcgetattr(fd)
601
+ try:
602
+ tty.setcbreak(fd)
603
+ except (termios.error, OSError):
604
+ return None
605
+ dr, _, _ = select.select([sys.stdin], [], [], 0)
606
+ if not dr:
607
+ return None
608
+ return sys.stdin.read(1)
609
+
610
+ def restore() -> None:
611
+ if state["saved"] is not None:
612
+ try:
613
+ termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, state["saved"])
614
+ except (termios.error, OSError, ValueError):
615
+ pass
616
+ state["saved"] = None
617
+
618
+ read_key_posix.restore = restore # type: ignore[attr-defined]
619
+ return read_key_posix
620
+
621
+ def run(self, once: bool = False, key_reader: Optional[Callable[[], Optional[str]]] = None) -> None:
622
+ reader = key_reader if key_reader is not None else self._default_key_reader
623
+ try:
624
+ while True:
625
+ data = self.collect()
626
+ frame = self.render_frame(data)
627
+ self._write_frame(frame)
628
+ if once:
629
+ break
630
+ key = None
631
+ try:
632
+ key = reader() if reader is not None else None
633
+ except StopIteration:
634
+ break
635
+ if key:
636
+ k = str(key).lower()
637
+ if k == "q":
638
+ break
639
+ if key == "\t" or k == "tab":
640
+ self.active_pane = self.PANE_METRICS if self.active_pane == self.PANE_DAG else self.PANE_DAG
641
+ if self.interval > 0:
642
+ time.sleep(self.interval)
643
+ except KeyboardInterrupt:
644
+ pass
645
+ finally:
646
+ reader_obj = self._stdin_reader
647
+ restore = getattr(reader_obj, "restore", None) if reader_obj is not None else None
648
+ if callable(restore):
649
+ restore()