letitloop 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,344 @@
1
+ """Model Context Protocol (MCP) server for letitloop (LIL).
2
+
3
+ Exposes the full macro-task control loop, contract graph, verification engine,
4
+ and quality plane as machine-readable tools for AI assistants and IDEs.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import sys
10
+ from dataclasses import asdict
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from .contract import load_contract
14
+ from .goal import Goal, Plan
15
+ from .metrics import MetricsCollector
16
+ from .quality_plan import quality_plan_for_contract
17
+ from .quality_plane import run_quality_plane
18
+ from .reconcile import run_reconciliation
19
+ from .state import load_state
20
+ from .supervisor import Supervisor
21
+ from .verifier import run_verification
22
+
23
+ _DEFAULT_WORKSPACE = os.path.abspath(os.getcwd())
24
+ _DEFAULT_RUN_DIR = os.path.join(_DEFAULT_WORKSPACE, "scratch", "orchestrator_runs")
25
+
26
+
27
+ class LetItLoopMCPServer:
28
+ """Core MCP Server implementation exposing orchestrator capabilities."""
29
+
30
+ def __init__(self, workspace_root: Optional[str] = None, run_dir: Optional[str] = None):
31
+ self.workspace_root = os.path.abspath(workspace_root or _DEFAULT_WORKSPACE)
32
+ self.run_dir = os.path.abspath(run_dir or _DEFAULT_RUN_DIR)
33
+ os.makedirs(self.run_dir, exist_ok=True)
34
+ self.metrics = MetricsCollector()
35
+
36
+ @classmethod
37
+ def get_tool_definitions(cls) -> List[Dict[str, Any]]:
38
+ """Return MCP tool definitions schema."""
39
+ return [
40
+ {
41
+ "name": "create_goal",
42
+ "description": "Initialize a new autonomous macro-goal with goal ID and title.",
43
+ "inputSchema": {
44
+ "type": "object",
45
+ "properties": {
46
+ "goal_id": {"type": "string", "description": "Unique alphanumeric goal ID"},
47
+ "title": {"type": "string", "description": "High-level goal title"},
48
+ "description": {"type": "string", "description": "Detailed goal specification"},
49
+ },
50
+ "required": ["goal_id", "title"],
51
+ },
52
+ },
53
+ {
54
+ "name": "load_contract_file",
55
+ "description": "Load, parse, and validate a contract JSON file from disk.",
56
+ "inputSchema": {
57
+ "type": "object",
58
+ "properties": {
59
+ "contract_path": {
60
+ "type": "string",
61
+ "description": "Relative or absolute path to contract JSON",
62
+ },
63
+ },
64
+ "required": ["contract_path"],
65
+ },
66
+ },
67
+ {
68
+ "name": "run_contract_verification",
69
+ "description": "Execute deterministic acceptance checks (files, regex, pytest commands) for a contract.",
70
+ "inputSchema": {
71
+ "type": "object",
72
+ "properties": {
73
+ "contract_path": {"type": "string", "description": "Path to contract JSON file"},
74
+ "task_id": {"type": "string", "description": "Optional task identifier"},
75
+ },
76
+ "required": ["contract_path"],
77
+ },
78
+ },
79
+ {
80
+ "name": "run_quality_review",
81
+ "description": "Run the multi-lens quality plane audit on contract outputs.",
82
+ "inputSchema": {
83
+ "type": "object",
84
+ "properties": {
85
+ "contract_path": {"type": "string", "description": "Path to contract JSON"},
86
+ "lens": {
87
+ "type": "string",
88
+ "description": "Quality lens to evaluate",
89
+ "enum": [
90
+ "code_correctness",
91
+ "security_hardening",
92
+ "documentation_clarity",
93
+ "test_completeness",
94
+ ],
95
+ "default": "code_correctness",
96
+ },
97
+ },
98
+ "required": ["contract_path"],
99
+ },
100
+ },
101
+ {
102
+ "name": "execute_supervisor_plan",
103
+ "description": "Execute a full DAG plan using the fault-tolerant Supervisor loop with automated retries.",
104
+ "inputSchema": {
105
+ "type": "object",
106
+ "properties": {
107
+ "goal_id": {"type": "string", "description": "Goal ID to execute"},
108
+ "contracts": {
109
+ "type": "array",
110
+ "items": {"type": "object"},
111
+ "description": "List of contract dictionaries defining the DAG",
112
+ },
113
+ "parallel": {
114
+ "type": "boolean",
115
+ "description": "Enable parallel worker pool execution",
116
+ "default": False,
117
+ },
118
+ "max_workers": {"type": "integer", "description": "Maximum concurrent workers", "default": 2},
119
+ },
120
+ "required": ["goal_id", "contracts"],
121
+ },
122
+ },
123
+ {
124
+ "name": "inspect_task_state",
125
+ "description": "Inspect the internal event journal, evidence chain, and state for a specific task.",
126
+ "inputSchema": {
127
+ "type": "object",
128
+ "properties": {
129
+ "task_id": {"type": "string", "description": "Task identifier to inspect"},
130
+ "run_dir": {"type": "string", "description": "Optional custom run directory"},
131
+ },
132
+ "required": ["task_id"],
133
+ },
134
+ },
135
+ {
136
+ "name": "reconcile_workspace_state",
137
+ "description": "Audit and verify disk state, file hashes, and evidence integrity for a goal plan.",
138
+ "inputSchema": {
139
+ "type": "object",
140
+ "properties": {
141
+ "goal_id": {"type": "string", "description": "Goal ID to reconcile"},
142
+ "contracts": {
143
+ "type": "array",
144
+ "items": {"type": "object"},
145
+ "description": "List of plan contract dicts",
146
+ },
147
+ },
148
+ "required": ["goal_id", "contracts"],
149
+ },
150
+ },
151
+ {
152
+ "name": "get_system_health",
153
+ "description": "Query letitloop engine health, active locks, and runtime configuration.",
154
+ "inputSchema": {"type": "object", "properties": {}},
155
+ },
156
+ ]
157
+
158
+ def handle_tool_call(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
159
+ """Dispatch tool calls to internal orchestrator logic."""
160
+ if name == "create_goal":
161
+ goal = Goal(
162
+ goal_id=arguments["goal_id"],
163
+ title=arguments["title"],
164
+ description=arguments.get("description", ""),
165
+ )
166
+ return {"status": "SUCCESS", "goal": goal.to_dict()}
167
+
168
+ elif name == "load_contract_file":
169
+ path = arguments["contract_path"]
170
+ if not os.path.isabs(path):
171
+ path = os.path.join(self.workspace_root, path)
172
+ contract, errors = load_contract(path, workspace_root=self.workspace_root)
173
+ if errors:
174
+ return {"status": "ERROR", "errors": errors}
175
+ return {"status": "SUCCESS", "contract": contract.to_dict()}
176
+
177
+ elif name == "run_contract_verification":
178
+ path = arguments["contract_path"]
179
+ if not os.path.isabs(path):
180
+ path = os.path.join(self.workspace_root, path)
181
+ contract, errors = load_contract(path, workspace_root=self.workspace_root)
182
+ if errors or not contract:
183
+ return {"status": "ERROR", "errors": errors or ["Failed to load contract"]}
184
+ task_dir = os.path.join(self.run_dir, arguments.get("task_id", contract.task_id))
185
+ passed, results, ev_path = run_verification(contract, self.workspace_root, task_dir)
186
+ return {
187
+ "status": "PASS" if passed else "FAIL",
188
+ "all_passed": passed,
189
+ "results": [r.to_dict() for r in results],
190
+ "evidence_path": ev_path,
191
+ }
192
+
193
+ elif name == "run_quality_review":
194
+ path = arguments["contract_path"]
195
+ if not os.path.isabs(path):
196
+ path = os.path.join(self.workspace_root, path)
197
+ contract, errors = load_contract(path, workspace_root=self.workspace_root)
198
+ if errors or not contract:
199
+ return {"status": "ERROR", "errors": errors or ["Failed to load contract"]}
200
+
201
+ lens = arguments.get("lens", "code_correctness")
202
+ output_paths = [
203
+ os.path.join(self.workspace_root, out["path"]) if not os.path.isabs(out["path"]) else out["path"]
204
+ for out in contract.outputs
205
+ ]
206
+ qp = quality_plan_for_contract(contract.risk_tier, lens, contract.quality_spec)
207
+ verdict = run_quality_plane(contract, output_paths, [], self.workspace_root, quality_plan=qp)
208
+ return {
209
+ "status": verdict.status,
210
+ "passed": verdict.passed,
211
+ "score": verdict.score,
212
+ "issues": verdict.issues,
213
+ "reason": verdict.reason,
214
+ }
215
+
216
+ elif name == "execute_supervisor_plan":
217
+ goal = Goal(
218
+ goal_id=arguments["goal_id"],
219
+ title=f"Goal {arguments['goal_id']}",
220
+ description="Executed via MCP server",
221
+ )
222
+ plan = Plan(goal_id=goal.goal_id, contracts=arguments["contracts"])
223
+ sup = Supervisor(
224
+ goal=goal,
225
+ plan=plan,
226
+ workspace_root=self.workspace_root,
227
+ run_dir=self.run_dir,
228
+ parallel=arguments.get("parallel", False),
229
+ max_workers=arguments.get("max_workers", 2),
230
+ )
231
+ results = sup.execute_plan()
232
+ return {
233
+ "status": "SUCCESS" if goal.status == "COMPLETE" else "INCOMPLETE",
234
+ "goal_status": goal.status,
235
+ "results": results,
236
+ }
237
+
238
+ elif name == "inspect_task_state":
239
+ task_id = arguments["task_id"]
240
+ custom_run_dir = arguments.get("run_dir") or self.run_dir
241
+ state_file = os.path.join(custom_run_dir, task_id, "state.json")
242
+ if not os.path.isfile(state_file):
243
+ return {"status": "NOT_FOUND", "message": f"No state file found at {state_file}"}
244
+ st = load_state(state_file)
245
+ return {
246
+ "status": "SUCCESS",
247
+ "task_id": st.task_id,
248
+ "state_status": st.status,
249
+ "attempt": st.attempt,
250
+ "events_count": len(st.events),
251
+ "evidence": st.evidence,
252
+ "worker_results_count": len(st.worker_results),
253
+ }
254
+
255
+ elif name == "reconcile_workspace_state":
256
+ goal_id = arguments["goal_id"]
257
+ plan = Plan(goal_id=goal_id, contracts=arguments["contracts"])
258
+ rep = run_reconciliation(goal_id, plan, self.workspace_root, self.run_dir)
259
+ return {
260
+ "status": "SUCCESS" if rep.passed else "ISSUES_FOUND",
261
+ "passed": rep.passed,
262
+ "checked_tasks": rep.checked_tasks,
263
+ "total_tasks": rep.total_tasks,
264
+ "issues": [asdict(i) for i in rep.issues],
265
+ }
266
+
267
+ elif name == "get_system_health":
268
+ return {
269
+ "status": "HEALTHY",
270
+ "engine": "letitloop (LIL) 0.1.0",
271
+ "workspace_root": self.workspace_root,
272
+ "run_dir": self.run_dir,
273
+ "python_version": sys.version,
274
+ "pid": os.getpid(),
275
+ }
276
+
277
+ else:
278
+ return {"status": "ERROR", "message": f"Unknown tool: {name}"}
279
+
280
+ def run_stdio_server(self):
281
+ """Run standard JSON-RPC stdio loop for MCP integration."""
282
+ sys.stderr.write("[letitloop-mcp] Server starting on stdio...\n")
283
+ sys.stderr.flush()
284
+
285
+ for line in sys.stdin:
286
+ if not line.strip():
287
+ continue
288
+ try:
289
+ req = json.loads(line)
290
+ method = req.get("method", "")
291
+ req_id = req.get("id")
292
+
293
+ if method == "tools/list":
294
+ resp = {
295
+ "jsonrpc": "2.0",
296
+ "id": req_id,
297
+ "result": {"tools": self.get_tool_definitions()},
298
+ }
299
+ elif method == "tools/call":
300
+ params = req.get("params", {})
301
+ tool_name = params.get("name", "")
302
+ tool_args = params.get("arguments", {})
303
+ out = self.handle_tool_call(tool_name, tool_args)
304
+ resp = {
305
+ "jsonrpc": "2.0",
306
+ "id": req_id,
307
+ "result": {"content": [{"type": "text", "text": json.dumps(out, indent=2)}]},
308
+ }
309
+ elif method == "initialize":
310
+ resp = {
311
+ "jsonrpc": "2.0",
312
+ "id": req_id,
313
+ "result": {
314
+ "protocolVersion": "2024-11-05",
315
+ "capabilities": {"tools": {}},
316
+ "serverInfo": {"name": "letitloop-mcp", "version": "0.1.0"},
317
+ },
318
+ }
319
+ else:
320
+ resp = {
321
+ "jsonrpc": "2.0",
322
+ "id": req_id,
323
+ "result": {},
324
+ }
325
+
326
+ sys.stdout.write(json.dumps(resp) + "\n")
327
+ sys.stdout.flush()
328
+ except Exception as e:
329
+ err_resp = {
330
+ "jsonrpc": "2.0",
331
+ "id": req.get("id") if isinstance(req, dict) else None,
332
+ "error": {"code": -32603, "message": str(e)},
333
+ }
334
+ sys.stdout.write(json.dumps(err_resp) + "\n")
335
+ sys.stdout.flush()
336
+
337
+
338
+ def main():
339
+ server = LetItLoopMCPServer()
340
+ server.run_stdio_server()
341
+
342
+
343
+ if __name__ == "__main__":
344
+ main()
@@ -0,0 +1,182 @@
1
+ """Durable cross-subagent memory staging facility."""
2
+
3
+ import json
4
+ import os
5
+ import threading
6
+ import time
7
+ from typing import List, Optional
8
+
9
+ LOCK_TTL_SEC = 35.0
10
+ STALE_TTL_SEC = 30.0
11
+
12
+
13
+ def _pid_alive(pid):
14
+ """Return True if a process with the given pid is alive.
15
+
16
+ Windows: os.kill(pid, 0) is unreliable (returns success for dead pids),
17
+ so use OpenProcess. POSIX: signal 0 probe.
18
+ """
19
+ try:
20
+ if os.name == "nt":
21
+ import ctypes
22
+
23
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
24
+ kernel32 = ctypes.windll.kernel32
25
+ open_process = kernel32.OpenProcess
26
+ open_process.restype = ctypes.c_void_p
27
+ open_process.argtypes = [ctypes.c_uint, ctypes.c_bool, ctypes.c_uint]
28
+ handle = open_process(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
29
+ if handle:
30
+ kernel32.CloseHandle(ctypes.c_void_p(handle))
31
+ return True
32
+ return False
33
+ os.kill(pid, 0)
34
+ return True
35
+ except (OSError, AttributeError):
36
+ return False
37
+
38
+
39
+ class MemoryBridge:
40
+ """Durable JSONL memory staging facility with cross-process locking."""
41
+
42
+ def __init__(self, path: str):
43
+ self.path = os.path.abspath(path)
44
+ self.lock_path = f"{self.path}.lock"
45
+ self._thread_lock = threading.Lock()
46
+
47
+ def _read_lock(self):
48
+ try:
49
+ with open(self.lock_path, "r", encoding="utf-8") as f:
50
+ return json.load(f)
51
+ except (OSError, ValueError, TypeError):
52
+ return None
53
+
54
+ def _steal_stale_lock(self) -> bool:
55
+ """Remove the lock iff its owner is dead, or it is corrupt/absent and
56
+ older than STALE_TTL_SEC. Returns True if removed (caller retries)."""
57
+ data = self._read_lock()
58
+ try:
59
+ if data is None:
60
+ if time.time() - os.path.getmtime(self.lock_path) > STALE_TTL_SEC:
61
+ os.remove(self.lock_path)
62
+ return True
63
+ return False
64
+ if not isinstance(data, dict):
65
+ os.remove(self.lock_path)
66
+ return True
67
+ owner = data.get("pid")
68
+ if isinstance(owner, int) and _pid_alive(owner):
69
+ return False
70
+ os.remove(self.lock_path)
71
+ return True
72
+ except OSError:
73
+ return False
74
+
75
+ def _acquire_lock(self) -> None:
76
+ lock_dir = os.path.dirname(self.lock_path)
77
+ if lock_dir:
78
+ os.makedirs(lock_dir, exist_ok=True)
79
+ deadline = time.time() + LOCK_TTL_SEC
80
+ while True:
81
+ try:
82
+ fd = os.open(self.lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
83
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
84
+ json.dump({"pid": os.getpid(), "created_at": time.time()}, f)
85
+ f.flush()
86
+ os.fsync(f.fileno())
87
+ return
88
+ except FileExistsError:
89
+ if self._steal_stale_lock():
90
+ continue
91
+ if time.time() >= deadline:
92
+ raise TimeoutError(f"timed out acquiring memory bridge lock for {self.path}")
93
+ time.sleep(0.01)
94
+
95
+ def _release_lock(self) -> None:
96
+ """Remove the lock only if we still own it.
97
+
98
+ Atomic claim via rename: if the lock was stolen/replaced meanwhile, the
99
+ renamed file's pid will differ and we restore it untouched.
100
+ """
101
+ tmp = f"{self.lock_path}.{os.getpid()}.{int(time.time() * 1000)}.tmp"
102
+ try:
103
+ os.rename(self.lock_path, tmp)
104
+ except OSError:
105
+ return
106
+ data = self._read_lock_with(tmp)
107
+ if data and data.get("pid") != os.getpid():
108
+ try:
109
+ os.rename(tmp, self.lock_path)
110
+ except OSError:
111
+ pass
112
+ return
113
+ try:
114
+ os.remove(tmp)
115
+ except OSError:
116
+ pass
117
+
118
+ @staticmethod
119
+ def _read_lock_with(path):
120
+ try:
121
+ with open(path, "r", encoding="utf-8") as f:
122
+ return json.load(f)
123
+ except (OSError, ValueError, TypeError):
124
+ return None
125
+
126
+ def append(self, entry: dict) -> int:
127
+ """Append one JSON line atomically with cross-process locking and fsync."""
128
+ with self._thread_lock:
129
+ self._acquire_lock()
130
+ try:
131
+ line_count = 0
132
+ if os.path.exists(self.path):
133
+ with open(self.path, "r", encoding="utf-8", errors="replace") as f:
134
+ line_count = sum(1 for _ in f)
135
+
136
+ parent_dir = os.path.dirname(self.path)
137
+ if parent_dir:
138
+ os.makedirs(parent_dir, exist_ok=True)
139
+
140
+ with open(self.path, "a", encoding="utf-8") as f:
141
+ f.write(json.dumps(entry) + "\n")
142
+ f.flush()
143
+ os.fsync(f.fileno())
144
+
145
+ return line_count + 1
146
+ finally:
147
+ self._release_lock()
148
+
149
+ def read(self, scope: Optional[str] = None, limit: Optional[int] = None) -> List[dict]:
150
+ """Read entries from JSONL file in chronological order (newest last)."""
151
+ with self._thread_lock:
152
+ if not os.path.exists(self.path):
153
+ return []
154
+
155
+ entries: List[dict] = []
156
+ with open(self.path, "r", encoding="utf-8", errors="replace") as f:
157
+ for line in f:
158
+ line_str = line.strip()
159
+ if not line_str:
160
+ continue
161
+ try:
162
+ data = json.loads(line_str)
163
+ except (json.JSONDecodeError, ValueError, TypeError):
164
+ continue
165
+
166
+ if not isinstance(data, dict):
167
+ continue
168
+
169
+ if scope is not None:
170
+ if data.get("scope") != scope:
171
+ continue
172
+
173
+ entries.append(data)
174
+
175
+ if limit is not None and limit > 0:
176
+ return entries[-limit:]
177
+ return entries
178
+
179
+ def read_last(self, scope: Optional[str] = None) -> Optional[dict]:
180
+ """Return the most recent matching entry or None."""
181
+ entries = self.read(scope=scope)
182
+ return entries[-1] if entries else None
@@ -0,0 +1,159 @@
1
+ """Runtime metrics collector — wall-clock per phase, attempt counters,
2
+ named event counters, and cumulative LLM token usage."""
3
+
4
+ import json
5
+ import os
6
+ import time
7
+ from collections import defaultdict
8
+ from dataclasses import asdict, dataclass, field
9
+ from typing import Dict, List
10
+
11
+
12
+ @dataclass
13
+ class PhaseRecord:
14
+ phase: str
15
+ task_id: str
16
+ elapsed_sec: float
17
+ timestamp: str = ""
18
+
19
+
20
+ @dataclass
21
+ class MetricsSnapshot:
22
+ goal_id: str = ""
23
+ total_elapsed_sec: float = 0.0
24
+ phase_counts: Dict[str, int] = field(default_factory=dict)
25
+ phase_elapsed: Dict[str, float] = field(default_factory=dict)
26
+ attempt_counts: Dict[str, int] = field(default_factory=dict)
27
+ total_attempts: int = 0
28
+ completed_tasks: int = 0
29
+ failed_tasks: int = 0
30
+ counters: Dict[str, int] = field(default_factory=dict)
31
+ token_usage: Dict[str, int] = field(default_factory=dict)
32
+ contracts_by_status: Dict[str, int] = field(default_factory=dict)
33
+
34
+
35
+ class MetricsCollector:
36
+ """Collects runtime metrics during plan execution."""
37
+
38
+ def __init__(self, goal_id: str = ""):
39
+ self.goal_id = goal_id
40
+ self.phases: List[PhaseRecord] = []
41
+ self._timers: Dict[str, float] = {}
42
+ self.attempts: Dict[str, int] = {}
43
+ self.counters: Dict[str, int] = defaultdict(int)
44
+ self.token_usage: Dict[str, int] = {"prompt": 0, "completion": 0}
45
+ self.contracts_by_status: Dict[str, int] = {}
46
+
47
+ def start_phase(self, phase: str, task_id: str = "") -> None:
48
+ key = f"{task_id}:{phase}" if task_id else phase
49
+ self._timers[key] = time.time()
50
+
51
+ def end_phase(self, phase: str, task_id: str = "") -> PhaseRecord:
52
+ key = f"{task_id}:{phase}" if task_id else phase
53
+ start = self._timers.pop(key, None)
54
+ elapsed = time.time() - start if start else 0.0
55
+ rec = PhaseRecord(
56
+ phase=phase,
57
+ task_id=task_id,
58
+ elapsed_sec=round(elapsed, 4),
59
+ timestamp=__import__("datetime").datetime.now().isoformat(),
60
+ )
61
+ self.phases.append(rec)
62
+ return rec
63
+
64
+ def get_phases(self, task_id: str = "") -> List[dict]:
65
+ """Return phase records for the given task_id as dicts."""
66
+ return [
67
+ {"phase": r.phase, "task_id": r.task_id, "elapsed_sec": r.elapsed_sec, "timestamp": r.timestamp}
68
+ for r in self.phases
69
+ if not task_id or r.task_id == task_id
70
+ ]
71
+
72
+ def record_attempt(self, task_id: str) -> None:
73
+ self.attempts[task_id] = self.attempts.get(task_id, 0) + 1
74
+
75
+ def incr(self, counter: str, amount: int = 1, **labels) -> None:
76
+ """Increment a named counter. Keyword labels are accepted at call
77
+ sites for compatibility but counters stay plain name -> int."""
78
+ self.counters[counter] += amount
79
+
80
+ def record_token_usage(self, prompt_tokens: int, completion_tokens: int) -> None:
81
+ """Accumulate LLM token usage totals."""
82
+ self.token_usage["prompt"] += int(prompt_tokens)
83
+ self.token_usage["completion"] += int(completion_tokens)
84
+
85
+ def record_three_strike_escalation(self) -> None:
86
+ """Record one three-strike escalation event."""
87
+ self.incr("three_strike_escalations")
88
+
89
+ def record_contract_status(self, status: str) -> None:
90
+ """Increment the terminal-status histogram for contracts."""
91
+ key = str(status)
92
+ self.contracts_by_status[key] = self.contracts_by_status.get(key, 0) + 1
93
+
94
+ def snapshot(self) -> MetricsSnapshot:
95
+ s = MetricsSnapshot(goal_id=self.goal_id)
96
+ phase_elapsed: Dict[str, float] = {}
97
+ phase_counts: Dict[str, int] = {}
98
+ for rec in self.phases:
99
+ phase_elapsed[rec.phase] = phase_elapsed.get(rec.phase, 0.0) + rec.elapsed_sec
100
+ phase_counts[rec.phase] = phase_counts.get(rec.phase, 0) + 1
101
+ s.total_elapsed_sec += rec.elapsed_sec
102
+ s.phase_elapsed = phase_elapsed
103
+ s.phase_counts = phase_counts
104
+ s.attempt_counts = dict(self.attempts)
105
+ s.total_attempts = sum(self.attempts.values())
106
+ s.counters = dict(self.counters)
107
+ s.token_usage = dict(self.token_usage)
108
+ s.contracts_by_status = dict(self.contracts_by_status)
109
+ return s
110
+
111
+ def summary(self) -> str:
112
+ s = self.snapshot()
113
+ lines = [f"Metrics: goal={s.goal_id}"]
114
+ lines.append(f" Total elapsed: {s.total_elapsed_sec:.2f}s")
115
+ lines.append(f" Total attempts: {s.total_attempts}")
116
+ for phase, elapsed in sorted(s.phase_elapsed.items()):
117
+ count = s.phase_counts.get(phase, 0)
118
+ lines.append(f" {phase}: {elapsed:.2f}s ({count} runs)")
119
+ for tid, count in sorted(s.attempt_counts.items()):
120
+ lines.append(f" attempts[{tid}]: {count}")
121
+ return "\n".join(lines)
122
+
123
+ def to_dict(self) -> Dict:
124
+ s = self.snapshot()
125
+ return {
126
+ "goal_id": s.goal_id,
127
+ "total_elapsed_sec": s.total_elapsed_sec,
128
+ "phase_elapsed": s.phase_elapsed,
129
+ "phase_counts": s.phase_counts,
130
+ "attempt_counts": s.attempt_counts,
131
+ "total_attempts": s.total_attempts,
132
+ "counters": dict(self.counters),
133
+ "token_usage": dict(self.token_usage),
134
+ "contracts_by_status": dict(self.contracts_by_status),
135
+ "phases": [asdict(r) for r in self.phases],
136
+ }
137
+
138
+ def save(self, path: str) -> None:
139
+ parent = os.path.dirname(path) or "."
140
+ os.makedirs(parent, exist_ok=True)
141
+ with open(path, "w", encoding="utf-8") as f:
142
+ json.dump(self.to_dict(), f, indent=2, ensure_ascii=False)
143
+
144
+ @classmethod
145
+ def load(cls, path: str) -> "MetricsCollector":
146
+ with open(path, "r", encoding="utf-8") as f:
147
+ data = json.load(f)
148
+ mc = cls(goal_id=data.get("goal_id", ""))
149
+ for rec_data in data.get("phases", []):
150
+ mc.phases.append(PhaseRecord(**rec_data))
151
+ mc.attempts = data.get("attempt_counts", {})
152
+ mc.counters = defaultdict(int, data.get("counters", {}) or {})
153
+ token_usage = dict(data.get("token_usage", {}) or {})
154
+ mc.token_usage = {
155
+ "prompt": int(token_usage.get("prompt", 0)),
156
+ "completion": int(token_usage.get("completion", 0)),
157
+ }
158
+ mc.contracts_by_status = dict(data.get("contracts_by_status", {}) or {})
159
+ return mc