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/SKILL.md ADDED
@@ -0,0 +1,292 @@
1
+ ---
2
+ name: letitloop
3
+ description: Comprehensive Autonomous Macro-Task Control Loop & Verification Engine. Plans DAG dependency contracts, executes tasks via pluggable worker adapters (Claude Code, Antigravity CLI, Omniroute, Ollama, direct LLMs), enforces zero-trust deterministic acceptance checks, arbitrates multi-lens quality reviews, and reconciles cryptographic evidence ledgers. Fully provider-agnostic (0-subscription local Ollama, routing gateways, or commercial APIs).
4
+ version: 0.1.0
5
+ author: letitloop-maintainers
6
+ tags:
7
+ - orchestration
8
+ - autonomous-macro-loop
9
+ - dag-planner
10
+ - zero-trust-verification
11
+ - quality-plane
12
+ - multi-provider
13
+ - local-ollama
14
+ - mcp-tools
15
+ - claude-code-skill
16
+ - openai-codex
17
+ - codex
18
+ ---
19
+
20
+ # `letitloop` (LIL) — Universal Agent Skill Specification
21
+
22
+ The assistant decomposes complex, ambiguous goals into typed contract dependency graphs (DAGs), delegates task execution through sandboxed worker adapters, runs deterministic acceptance verification, and arbitrates multi-lens quality reviews with zero hallucinations and crash-resilient state recovery.
23
+
24
+ ### ⚡ Autonomous Engine Setup & Launch Protocol
25
+ When this skill is triggered by a user request:
26
+ 1. **Auto-Install Check**: Check if the `lil` CLI engine is installed. If not yet installed in the current environment, run:
27
+ ```bash
28
+ pip install letitloop
29
+ ```
30
+ *(Or from GitHub: `pip install git+https://github.com/sdageltc/letitloop.git`)*
31
+ 2. **Execute Full Orchestrator**:
32
+ ```bash
33
+ lil propose "<natural language goal>" --run
34
+ ```
35
+ 3. **MCP Server Mode**: If connecting through Model Context Protocol, the agent starts and queries `letitloop-mcp` to run deterministic checks, inspect DAG states, and evaluate quality lenses directly.
36
+
37
+ ---
38
+
39
+ ## 🌟 Core System Capabilities
40
+
41
+ ```
42
+ ┌───────────────────────────────┐
43
+ │ Natural Language Goal │
44
+ └───────────────┬───────────────┘
45
+ ▼
46
+ ┌───────────────────────────────┐
47
+ │ LLM DAG Planner │
48
+ │ (Decomposes into Contracts) │
49
+ └───────────────┬───────────────┘
50
+ ▼
51
+ ┌───────────────────────────────┐
52
+ │ Contract Dependency Graph │
53
+ └───────────────┬───────────────┘
54
+ ▼
55
+ ┌─────────────────────────────────────────────────────────┐
56
+ │ Supervisor Loop │
57
+ │ 1. Atomic File-Locking & State Journal (WAL) │
58
+ │ 2. Sandboxed Worker Dispatch (Claude Code, agy, Local) │
59
+ │ 3. Deterministic Acceptance Verifier (AST / Tests) │
60
+ │ 4. Multi-Lens Quality Plane (Security / Correctness) │
61
+ │ 5. Dynamic Replanning & Bounded 3-Strike Escalation │
62
+ └────────────────────────────┬────────────────────────────┘
63
+ ▼
64
+ ┌───────────────────────────────┐
65
+ │ Cryptographic Evidence Ledger │
66
+ │ & Reconciled Workspace Files │
67
+ └───────────────────────────────┘
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 📊 Deterministic Architecture vs. Other Autonomous Agents
73
+
74
+ | Architectural Feature | **`letitloop` (LIL)** | **OpenHands** | **SWE-agent** | **AutoGPT / AgentGPT** | **MetaGPT / ChatDev** |
75
+ |---|:---:|:---:|:---:|:---:|:---:|
76
+ | **Orchestration Model** | **Typed DAG Contracts** | Container Terminal Chat | Single-Task Benchmark Agent | Open-Ended While-Loop | Multi-Role Chat Simulation |
77
+ | **Deterministic Verifier** | **8 Machine-Verified Checks** (AST, Cmd Exit Codes, Regex, Render, Scope) | Eyeball / Agent Judgement | Unit Test Execution Only | None (LLM Self-Assessment) | Role-Play Text Review |
78
+ | **Crash Recovery & Resume** | **Write-Ahead Log (WAL) Journal** | Manual Session Replay | No (Ephemeral Run) | None (Lost State) | None |
79
+ | **Retry & Failure Policy** | **Bounded 3-Strike with Strategy Mutation & Impossibility Proof** | Infinite Loop / Timeout | Fixed Retries / Prompt Dump | Infinite Hallucination Loop | Reprompting Loop |
80
+ | **Sandbox Scope Enforcement** | **Strict `allow`/`deny` & Undeclared Output Detection** | Docker Container Isolation | Bash Environment Isolation | None (Unrestricted Host) | None |
81
+ | **Quality Plane & Lenses** | **5 Specialized Lenses + Senior Arbitration & QC Overrule** | Single Review Step | None | None | Simulated Peer Chat |
82
+ | **AI Ecosystem & Skill Support** | **Universal Skill & MCP across 8 Platforms** (Claude Code, Antigravity, OpenAI Codex, Hermes, Cursor, OpenCode, Cline, Windsurf) | Standalone Web UI / Docker | Standalone CLI | Standalone CLI / Web | Standalone Framework |
83
+ | **Zero-Subscription Local Use** | **Native Ollama, vLLM, LM Studio & Omniroute Support** | Local LLMs supported via LiteLLM | Local LLMs supported | Local LLMs (Ollama) | Local LLMs supported |
84
+
85
+ ---
86
+
87
+ ## 🔑 Universal Provider & Model Support (Zero Subscriptions Required)
88
+
89
+ `letitloop` is completely vendor-agnostic. It does not require any specific commercial subscription. Users can run on free local models, open-source gateways, or frontier commercial APIs:
90
+
91
+ ### 1. Free / Local Zero-Cloud Execution (Ollama, LM Studio, vLLM)
92
+ No API keys or cloud subscriptions needed:
93
+ ```bash
94
+ # Run local models via Ollama
95
+ export OLLAMA_BASE_URL="http://localhost:11434/v1"
96
+ export WORKER_MODEL="ollama:qwen2.5-coder:32b"
97
+ export QC_MODEL="ollama:deepseek-r1:14b"
98
+ export PLANNER_MODEL="ollama:qwen2.5-coder:32b"
99
+ ```
100
+
101
+ ### 2. Multi-Provider Routing Gateways (Omniroute, OpenRouter, Groq)
102
+ Use dynamic gateway routing across dozens of models:
103
+ ```bash
104
+ # Omniroute Gateway (Local or Remote Proxy)
105
+ export OMNIROUTE_API_KEY="your-key"
106
+ export OMNIROUTE_BASE_URL="http://localhost:8000/v1"
107
+ export WORKER_MODEL="omniroute:auto"
108
+
109
+ # OpenRouter
110
+ export OPENROUTER_API_KEY="your-openrouter-key"
111
+ export WORKER_MODEL="openrouter:anthropic/claude-3.5-sonnet"
112
+
113
+ # Groq (Ultra-Fast LPU Inference)
114
+ export GROQ_API_KEY="your-groq-key"
115
+ export WORKER_MODEL="groq:llama-3.3-70b-versatile"
116
+ ```
117
+
118
+ ### 3. Frontier Commercial APIs (Gemini, Anthropic, OpenAI, DeepSeek)
119
+ ```bash
120
+ # Google Gemini 3 Generation
121
+ export GEMINI_API_KEY="your-gemini-key"
122
+ export WORKER_MODEL="gemini:gemini-3.7-flash"
123
+ export QC_MODEL="gemini:gemini-3.1-pro"
124
+
125
+ # OpenAI GPT-5.6 Generation
126
+ export OPENAI_API_KEY="your-openai-key"
127
+ export WORKER_MODEL="openai:gpt-5.6-luna"
128
+ export QC_MODEL="openai:gpt-5.6-sol"
129
+
130
+ # Anthropic Claude 5 Generation
131
+ export ANTHROPIC_API_KEY="your-anthropic-key"
132
+ export WORKER_MODEL="anthropic:claude-sonnet-5"
133
+ export QC_MODEL="anthropic:claude-opus-5"
134
+
135
+ # DeepSeek V4 Generation
136
+ export DEEPSEEK_API_KEY="your-deepseek-key"
137
+ export WORKER_MODEL="deepseek:deepseek-v4-flash"
138
+ export QC_MODEL="deepseek:deepseek-v4-pro"
139
+ ```
140
+
141
+ ---
142
+
143
+ ## 🤖 Pluggable Worker Adapters
144
+
145
+ The Supervisor executes task contracts through specialized worker adapters:
146
+
147
+ | Adapter Name | Mode Identifier | Description |
148
+ |---|---|---|
149
+ | **Claude Code Adapter** | `claude-code` | Invokes the Claude Code CLI (`claude -p "<prompt>"`) autonomously |
150
+ | **Antigravity CLI Adapter** | `antigravity-cli` | Invokes Google Antigravity CLI (`agy exec --prompt "<prompt>"`) |
151
+ | **OpenAI Codex Adapter** | `codex` | Invokes the OpenAI Codex CLI (`codex exec --prompt "<prompt>"`) autonomously |
152
+ | **Omniroute Adapter** | `omniroute` | Invokes local/remote multi-provider proxy gateways |
153
+ | **Script Worker Adapter** | `script` | Executes custom local bash/Python scripts with injected environment variables |
154
+ | **Direct API Worker** | `direct` | In-process zero-dependency stdlib HTTP transport |
155
+ | **Mock Worker** | `mock` | Deterministic simulation worker for CI, offline verification, and dry-runs |
156
+
157
+ ---
158
+
159
+ ## 🛠️ Complete MCP Tool Catalog (8 Native Tools)
160
+
161
+ When connecting via Model Context Protocol (`letitloop-mcp`), the assistant has direct access to the full orchestrator engine:
162
+
163
+ ### 1. `create_goal`
164
+ Initializes a new macro-goal with isolated state directory.
165
+ * **Arguments**: `goal_id` (str), `title` (str), `description` (str)
166
+
167
+ ### 2. `load_contract_file`
168
+ Loads and validates a contract JSON file against strict schema rules.
169
+ * **Arguments**: `contract_path` (str)
170
+
171
+ ### 3. `run_contract_verification`
172
+ Executes deterministic acceptance checks against task outputs.
173
+ * **Arguments**: `contract_path` (str), `task_id` (optional str)
174
+
175
+ ### 4. `run_quality_review`
176
+ Executes multi-lens quality plane review on produced artifacts.
177
+ * **Arguments**: `contract_path` (str), `lens` (optional str, e.g. `code_correctness`, `security`, `documentation`, `adversarial_architecture_audit`)
178
+
179
+ ### 5. `execute_supervisor_plan`
180
+ Executes a multi-task contract DAG with automated retries, WAL state logging, and parallel execution.
181
+ * **Arguments**: `goal_id` (str), `contracts` (array of contract dicts), `parallel` (bool, default `False`)
182
+
183
+ ### 6. `inspect_task_state`
184
+ Inspects state journal, attempt history, and evidence artifacts for a specific task.
185
+ * **Arguments**: `task_id` (str), `run_dir` (optional str)
186
+
187
+ ### 7. `reconcile_workspace_state`
188
+ Audits file hashes against cryptographic evidence ledgers to detect out-of-band edits or missing outputs.
189
+ * **Arguments**: `goal_id` (str), `contracts` (array of contract dicts)
190
+
191
+ ### 8. `get_system_health`
192
+ Returns runtime status, registered worker adapters, configured model transports, and memory health.
193
+ * **Arguments**: None
194
+
195
+ ---
196
+
197
+ ## 📋 Comprehensive Contract JSON Schema
198
+
199
+ Every step in an autonomous plan is defined by a strictly validated contract:
200
+
201
+ ```json
202
+ {
203
+ "task_id": "auth-jwt-01",
204
+ "title": "Implement JWT validation middleware",
205
+ "status": "drafted",
206
+ "risk_tier": "qc_required",
207
+ "workspace_scope": {
208
+ "allow": ["src/auth/", "tests/test_auth.py"],
209
+ "deny": [".env", "config/secrets.json"]
210
+ },
211
+ "objective": "Build token decode, expiration validation, and signature verification with unit tests.",
212
+ "worker": {
213
+ "model": "gemini:gemini-3.7-flash",
214
+ "fallback_model": "openai:gpt-5.6-luna",
215
+ "max_attempts": 3,
216
+ "adapter": "direct"
217
+ },
218
+ "inputs": [],
219
+ "outputs": [
220
+ {"path": "src/auth/jwt.py"},
221
+ {"path": "tests/test_auth.py"}
222
+ ],
223
+ "acceptance_checks": [
224
+ {
225
+ "id": "syntax_check",
226
+ "kind": "syntax",
227
+ "path": "src/auth/jwt.py",
228
+ "expected": "python"
229
+ },
230
+ {
231
+ "id": "unit_tests",
232
+ "kind": "command",
233
+ "command": "pytest tests/test_auth.py -q",
234
+ "expected": 0,
235
+ "timeout_sec": 30
236
+ },
237
+ {
238
+ "id": "doc_check",
239
+ "kind": "render",
240
+ "path": "src/auth/README.md",
241
+ "expected": "markdown"
242
+ },
243
+ {
244
+ "id": "scope_check",
245
+ "kind": "undeclared_outputs"
246
+ }
247
+ ],
248
+ "qc": {
249
+ "required": true,
250
+ "lens": "security"
251
+ }
252
+ }
253
+ ```
254
+
255
+ ### Supported Acceptance Check Kinds:
256
+ - `syntax`: AST syntax validation for Python, TypeScript, JavaScript, Go, Rust.
257
+ - `command`: Subprocess command execution with exit code matching and process-tree killing on timeout.
258
+ - `file_exists`: Verifies output files exist and are non-empty.
259
+ - `min_size`: Asserts minimum byte size of generated artifact.
260
+ - `content_regex`: Matches required regular expressions in output text.
261
+ - `required_sections`: Asserts presence of required Markdown headers or JSON keys.
262
+ - `render`: Heuristic source structure validator for Markdown and HTML.
263
+ - `undeclared_outputs`: Detects any modified or created files outside the declared output manifest.
264
+
265
+ ---
266
+
267
+ ## ⚡ CLI Operational Playbook
268
+
269
+ For command-line and shell execution:
270
+
271
+ ```bash
272
+ # 1. Propose & Preview a Contract DAG from natural language
273
+ lil propose "Build a rate-limiting middleware with Redis backend and unit tests" --run
274
+
275
+ # 2. Monitor execution in real-time via live ASCII Dashboard
276
+ lil dashboard
277
+
278
+ # 3. Reconcile workspace file hashes with evidence ledger
279
+ lil reconcile <goal_id>
280
+
281
+ # 4. Diagnose system configuration and provider health
282
+ lil doctor
283
+ ```
284
+
285
+ ---
286
+
287
+ ## 🛡️ Fail-Closed Governance Invariants
288
+
289
+ 1. **Zero Blind Edits**: All worker file mutations must reside within `workspace_scope.allow`.
290
+ 2. **Deterministic Empirical Proof**: A task is never marked complete without evaluating acceptance check exit codes.
291
+ 3. **Bounded 3-Strike Policy**: If a worker fails 3 consecutive attempts on a contract, the supervisor halts that branch, marks it `ESCALATED`, and emits an `impossibility.md` report.
292
+ 4. **Secret Masking Firewall**: API keys, OAuth tokens, and SSH keys are automatically redacted from evidence ledgers and stdout logs.
@@ -0,0 +1,151 @@
1
+ """orchestrator — durable macro-task control-loop package."""
2
+
3
+ __version__ = "0.1.1"
4
+
5
+ from . import (
6
+ audit,
7
+ config,
8
+ errors,
9
+ feedback,
10
+ limits,
11
+ lock,
12
+ metrics,
13
+ provenance,
14
+ safety,
15
+ telemetry,
16
+ templates,
17
+ worker_pool,
18
+ )
19
+ from .contract import (
20
+ Contract,
21
+ load_contract,
22
+ validate_contract,
23
+ )
24
+ from .exceptions import (
25
+ PlannerError,
26
+ PreflightError,
27
+ ValidationError,
28
+ VerifierError,
29
+ WorkerError,
30
+ )
31
+ from .failure import (
32
+ FAILURE_CLASS_SCOPE_VIOLATION,
33
+ MAX_SAME_CLASS_STRIKES,
34
+ classify_failure,
35
+ count_consecutive_same_class,
36
+ suggest_remediation,
37
+ )
38
+ from .generator import (
39
+ generate_contracts,
40
+ )
41
+ from .goal import (
42
+ ContractGraph,
43
+ Goal,
44
+ Plan,
45
+ )
46
+ from .handoff import (
47
+ build_handoff,
48
+ )
49
+ from .impossibility import (
50
+ build_artifact,
51
+ write_artifact,
52
+ write_impossibility,
53
+ )
54
+ from .plan_quality import (
55
+ PlanQualityWarning,
56
+ check_plan_quality,
57
+ format_warnings,
58
+ plan_is_safe,
59
+ )
60
+ from .planner import (
61
+ decompose_goal,
62
+ )
63
+ from .preflight import (
64
+ run_preflight,
65
+ )
66
+ from .reconcile import (
67
+ ReconciliationIssue,
68
+ ReconciliationReport,
69
+ format_report,
70
+ run_reconciliation,
71
+ )
72
+ from .replanner import (
73
+ InspectResults,
74
+ replan,
75
+ suggest_fix,
76
+ )
77
+ from .state import (
78
+ LEGAL_TRANSITIONS,
79
+ IllegalTransitionError,
80
+ State,
81
+ create_initial_state,
82
+ load_state,
83
+ )
84
+ from .supervisor import (
85
+ Supervisor,
86
+ )
87
+ from .verifier import (
88
+ VerifierResult,
89
+ run_verification,
90
+ )
91
+ from .worker import (
92
+ run_worker,
93
+ )
94
+
95
+ __all__ = [
96
+ "audit",
97
+ "config",
98
+ "errors",
99
+ "feedback",
100
+ "limits",
101
+ "lock",
102
+ "metrics",
103
+ "provenance",
104
+ "safety",
105
+ "telemetry",
106
+ "templates",
107
+ "worker_pool",
108
+ "ValidationError",
109
+ "run_reconciliation",
110
+ "format_report",
111
+ "ReconciliationReport",
112
+ "ReconciliationIssue",
113
+ "Contract",
114
+ "load_contract",
115
+ "validate_contract",
116
+ "LEGAL_TRANSITIONS",
117
+ "State",
118
+ "IllegalTransitionError",
119
+ "load_state",
120
+ "create_initial_state",
121
+ "PreflightError",
122
+ "run_preflight",
123
+ "VerifierError",
124
+ "VerifierResult",
125
+ "run_verification",
126
+ "WorkerError",
127
+ "run_worker",
128
+ "build_handoff",
129
+ "Goal",
130
+ "Plan",
131
+ "ContractGraph",
132
+ "PlannerError",
133
+ "decompose_goal",
134
+ "generate_contracts",
135
+ "Supervisor",
136
+ "InspectResults",
137
+ "suggest_fix",
138
+ "replan",
139
+ "classify_failure",
140
+ "suggest_remediation",
141
+ "count_consecutive_same_class",
142
+ "MAX_SAME_CLASS_STRIKES",
143
+ "FAILURE_CLASS_SCOPE_VIOLATION",
144
+ "build_artifact",
145
+ "write_artifact",
146
+ "write_impossibility",
147
+ "check_plan_quality",
148
+ "plan_is_safe",
149
+ "format_warnings",
150
+ "PlanQualityWarning",
151
+ ]
@@ -0,0 +1,78 @@
1
+ """
2
+ orchestrator/anti_ouroboros.py
3
+ Fail-closed mutation novelty and complexity evaluator.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ from dataclasses import dataclass
10
+
11
+ from orchestrator.elasticity_governor import DynamicElasticityGovernor
12
+
13
+
14
+ @dataclass
15
+ class OuroborosVerdict:
16
+ is_approved: bool
17
+ reason: str
18
+ loc_delta: int
19
+ complexity_delta: float
20
+
21
+
22
+ class AntiOuroborosGate:
23
+ """Guards against regressions, cosmetic no-ops, and fail-open mutations."""
24
+
25
+ @classmethod
26
+ def evaluate_mutation(cls, original_code: str, modified_code: str) -> OuroborosVerdict:
27
+ if original_code.strip() == modified_code.strip():
28
+ return OuroborosVerdict(
29
+ is_approved=False,
30
+ reason="REJECT_IDENTICAL_CODE",
31
+ loc_delta=0,
32
+ complexity_delta=0.0,
33
+ )
34
+
35
+ try:
36
+ orig_ast = ast.parse(original_code)
37
+ except SyntaxError:
38
+ return OuroborosVerdict(
39
+ is_approved=False,
40
+ reason="REJECT_ORIGINAL_SYNTAX_ERROR",
41
+ loc_delta=0,
42
+ complexity_delta=0.0,
43
+ )
44
+
45
+ try:
46
+ mod_ast = ast.parse(modified_code)
47
+ except SyntaxError:
48
+ return OuroborosVerdict(
49
+ is_approved=False,
50
+ reason="REJECT_SYNTAX_ERROR",
51
+ loc_delta=0,
52
+ complexity_delta=0.0,
53
+ )
54
+
55
+ # Calculate complexity delta
56
+ orig_c = DynamicElasticityGovernor.calculate_complexity(original_code)
57
+ mod_c = DynamicElasticityGovernor.calculate_complexity(modified_code)
58
+ c_delta = mod_c - orig_c
59
+
60
+ orig_lines = original_code.splitlines()
61
+ mod_lines = modified_code.splitlines()
62
+ loc_delta = len(mod_lines) - len(orig_lines)
63
+
64
+ # Reject if AST is structurally identical (ignoring comments/whitespace)
65
+ if ast.dump(orig_ast, include_attributes=False) == ast.dump(mod_ast, include_attributes=False):
66
+ return OuroborosVerdict(
67
+ is_approved=False,
68
+ reason="REJECT_COSMETIC_NOOP",
69
+ loc_delta=loc_delta,
70
+ complexity_delta=c_delta,
71
+ )
72
+
73
+ return OuroborosVerdict(
74
+ is_approved=True,
75
+ reason="APPROVED_SEMANTIC_MUTATION",
76
+ loc_delta=loc_delta,
77
+ complexity_delta=c_delta,
78
+ )
@@ -0,0 +1,139 @@
1
+ """Approval classifier — decides whether a plan needs user approval."""
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+ from .goal import Plan
6
+
7
+ DESTRUCTIVE_KEYWORDS = [
8
+ "delete",
9
+ "remove",
10
+ "rm ",
11
+ "drop",
12
+ "truncate",
13
+ "reset",
14
+ "clear",
15
+ "purge",
16
+ "destroy",
17
+ ]
18
+
19
+ MACRO_TRIGGERS = [
20
+ "refactor",
21
+ "migrate",
22
+ "rewrite",
23
+ "convert",
24
+ "architecture",
25
+ "redesign",
26
+ "restructure",
27
+ ]
28
+
29
+
30
+ def _get_plan_stats(plan: Plan) -> Dict[str, Any]:
31
+ """Aggregate statistics about a plan."""
32
+ total = len(plan.contracts)
33
+ touches_src = 0
34
+ touches_tests = 0
35
+ touches_config = 0
36
+ touches_scratch = 0
37
+ has_commands = False
38
+ has_syntax_check = False
39
+ has_destructive = False
40
+ has_macro_keyword = False
41
+ for c in plan.contracts:
42
+ contract_dict = c.get("contract", {}) or {}
43
+ outputs = contract_dict.get("outputs", c.get("outputs", []))
44
+ for out in outputs:
45
+ p = out.get("path", "") if isinstance(out, dict) else str(out)
46
+ if p.startswith("src/"):
47
+ touches_src += 1
48
+ if p.startswith("tests/"):
49
+ touches_tests += 1
50
+ if any(p.startswith(x) for x in (".opencode/", ".claude/", ".agents/", "memory/", "AGENTS.md")):
51
+ touches_config += 1
52
+ if p.startswith("scratch/"):
53
+ touches_scratch += 1
54
+ checks = contract_dict.get("acceptance_checks", c.get("acceptance_checks", []))
55
+ for ch in checks:
56
+ if ch.get("kind") == "command":
57
+ has_commands = True
58
+ if ch.get("kind") == "syntax":
59
+ has_syntax_check = True
60
+ objective = (contract_dict.get("objective", c.get("objective", "")) or "").lower()
61
+ if any(kw in objective for kw in DESTRUCTIVE_KEYWORDS):
62
+ has_destructive = True
63
+ if any(kw in objective for kw in MACRO_TRIGGERS):
64
+ has_macro_keyword = True
65
+ return {
66
+ "total": total,
67
+ "touches_src": touches_src,
68
+ "touches_tests": touches_tests,
69
+ "touches_config": touches_config,
70
+ "touches_scratch": touches_scratch,
71
+ "has_commands": has_commands,
72
+ "has_syntax_check": has_syntax_check,
73
+ "has_destructive": has_destructive,
74
+ "has_macro_keyword": has_macro_keyword,
75
+ }
76
+
77
+
78
+ def requires_approval(
79
+ plan: Plan,
80
+ prefs: Optional[Dict[str, Any]] = None,
81
+ ) -> Dict[str, Any]:
82
+ """Decide if a plan needs user approval.
83
+
84
+ Returns dict with:
85
+ - requires_approval: bool
86
+ - reasons: list[str]
87
+ """
88
+ stats = _get_plan_stats(plan)
89
+ reasons = []
90
+ planning_prefs = (prefs or {}).get("planning", {})
91
+
92
+ # Rule: macro keyword in objective
93
+ if stats["has_macro_keyword"]:
94
+ reasons.append("Plan contains architecture/refactor keywords")
95
+
96
+ # Rule: destructive action
97
+ if stats["has_destructive"]:
98
+ reasons.append("Plan contains destructive operations")
99
+
100
+ # Rule: touches config paths
101
+ if stats["touches_config"] > 0:
102
+ reasons.append("Plan modifies config or protected files")
103
+
104
+ # Rule: touches src/ and approval_required_for_src_changes
105
+ if stats["touches_src"] > 0 and planning_prefs.get("approval_required_for_src_changes", True):
106
+ reasons.append("Plan modifies source code under src/")
107
+
108
+ # Rule: touches tests/
109
+ if stats["touches_tests"] > 0:
110
+ reasons.append("Plan writes test files under tests/")
111
+
112
+ # Rule: multi-file and approval_required_for_multi_file
113
+ total_outputs = stats["touches_src"] + stats["touches_tests"] + stats["touches_scratch"]
114
+ if total_outputs > 1 and planning_prefs.get("approval_required_for_multi_file", True):
115
+ reasons.append("Plan writes multiple files")
116
+
117
+ # Rule: more contracts than threshold
118
+ max_ok = planning_prefs.get("max_contracts_before_approval", 2)
119
+ if stats["total"] > max_ok:
120
+ reasons.append(f"Plan has {stats['total']} steps (limit: {max_ok})")
121
+
122
+ # Rule: has shell commands
123
+ if stats["has_commands"]:
124
+ reasons.append("Plan executes shell commands")
125
+
126
+ return {
127
+ "requires_approval": len(reasons) > 0,
128
+ "reasons": reasons,
129
+ }
130
+
131
+
132
+ def format_approval_reasons(result: Dict[str, Any]) -> str:
133
+ """Format approval reasons as a block string."""
134
+ if not result["requires_approval"]:
135
+ return "Approval not required."
136
+ lines = ["Approval required because:"]
137
+ for r in result["reasons"]:
138
+ lines.append(f"- {r}")
139
+ return "\n".join(lines)