sugarai 3.1.1.dev6__tar.gz → 3.2.0__tar.gz

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 (97) hide show
  1. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/PKG-INFO +107 -1
  2. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/README.md +102 -0
  3. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/pyproject.toml +6 -1
  4. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/executor/agent_sdk_executor.py +130 -0
  5. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/main.py +91 -1
  6. sugarai-3.2.0/sugar/mcp/__init__.py +34 -0
  7. sugarai-3.2.0/sugar/ralph/__init__.py +19 -0
  8. sugarai-3.2.0/sugar/ralph/config.py +75 -0
  9. sugarai-3.2.0/sugar/ralph/profile.py +365 -0
  10. sugarai-3.2.0/sugar/ralph/validator.py +293 -0
  11. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugarai.egg-info/PKG-INFO +107 -1
  12. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugarai.egg-info/SOURCES.txt +7 -0
  13. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugarai.egg-info/requires.txt +5 -0
  14. sugarai-3.2.0/tests/test_github_client.py +561 -0
  15. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_goose_integration.py +3 -2
  16. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_issue_responder_cli.py +36 -7
  17. sugarai-3.2.0/tests/test_mcp_server.py +253 -0
  18. sugarai-3.2.0/tests/test_ralph.py +410 -0
  19. sugarai-3.1.1.dev6/sugar/mcp/__init__.py +0 -11
  20. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/LICENSE +0 -0
  21. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/setup.cfg +0 -0
  22. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/__init__.py +0 -0
  23. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/__version__.py +0 -0
  24. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/agent/__init__.py +0 -0
  25. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/agent/base.py +0 -0
  26. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/agent/hooks.py +0 -0
  27. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/agent/subagent_manager.py +0 -0
  28. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/agent/tools.py +0 -0
  29. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/billing/__init__.py +0 -0
  30. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/billing/api_keys.py +0 -0
  31. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/billing/tiers.py +0 -0
  32. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/billing/usage.py +0 -0
  33. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/config/__init__.py +0 -0
  34. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/config/issue_responder_config.py +0 -0
  35. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/config/prompt_config.py +0 -0
  36. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/core/__init__.py +0 -0
  37. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/core/loop.py +0 -0
  38. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/discovery/__init__.py +0 -0
  39. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/discovery/code_quality.py +0 -0
  40. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/discovery/error_monitor.py +0 -0
  41. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/discovery/github_watcher.py +0 -0
  42. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/discovery/test_coverage.py +0 -0
  43. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/executor/__init__.py +0 -0
  44. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/executor/base.py +0 -0
  45. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/executor/claude_wrapper.py +0 -0
  46. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/executor/structured_request.py +0 -0
  47. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/integrations/__init__.py +0 -0
  48. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/integrations/github.py +0 -0
  49. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/learning/__init__.py +0 -0
  50. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/learning/adaptive_scheduler.py +0 -0
  51. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/learning/feedback_processor.py +0 -0
  52. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/mcp/server.py +0 -0
  53. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/orchestration/__init__.py +0 -0
  54. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/orchestration/agent_router.py +0 -0
  55. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/orchestration/task_orchestrator.py +0 -0
  56. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/profiles/__init__.py +0 -0
  57. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/profiles/base.py +0 -0
  58. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/profiles/default.py +0 -0
  59. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/profiles/issue_responder.py +0 -0
  60. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/__init__.py +0 -0
  61. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/coordinator.py +0 -0
  62. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/diff_validator.py +0 -0
  63. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/evidence.py +0 -0
  64. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/failure_handler.py +0 -0
  65. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/functional_verifier.py +0 -0
  66. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/preflight_checks.py +0 -0
  67. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/success_criteria.py +0 -0
  68. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/test_validator.py +0 -0
  69. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/quality_gates/truth_enforcer.py +0 -0
  70. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/storage/__init__.py +0 -0
  71. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/storage/issue_response_manager.py +0 -0
  72. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/storage/task_type_manager.py +0 -0
  73. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/storage/work_queue.py +0 -0
  74. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/utils/__init__.py +0 -0
  75. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/utils/git_operations.py +0 -0
  76. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/utils/toon_encoder.py +0 -0
  77. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/workflow/__init__.py +0 -0
  78. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugar/workflow/orchestrator.py +0 -0
  79. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugarai.egg-info/dependency_links.txt +0 -0
  80. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugarai.egg-info/entry_points.txt +0 -0
  81. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/sugarai.egg-info/top_level.txt +0 -0
  82. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_agent.py +0 -0
  83. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_billing.py +0 -0
  84. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_cli.py +0 -0
  85. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_core_loop.py +0 -0
  86. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_hold_functionality.py +0 -0
  87. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_hooks.py +0 -0
  88. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_issue_response_integration.py +0 -0
  89. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_orchestration.py +0 -0
  90. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_profiles.py +0 -0
  91. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_prompt_config.py +0 -0
  92. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_quality_gates.py +0 -0
  93. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_storage.py +0 -0
  94. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_subagent_manager.py +0 -0
  95. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_task_types.py +0 -0
  96. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_toon_encoder.py +0 -0
  97. {sugarai-3.1.1.dev6 → sugarai-3.2.0}/tests/test_v3_benchmarks.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sugarai
3
- Version: 3.1.1.dev6
3
+ Version: 3.2.0
4
4
  Summary: Sugar 🍰 - A dev team that never stops. Delegate full tasks to AI in the background.
5
5
  Author-email: Steven Leggett <contact@roboticforce.io>
6
6
  License: MIT
@@ -50,6 +50,10 @@ Provides-Extra: test
50
50
  Requires-Dist: pytest>=7.0.0; extra == "test"
51
51
  Requires-Dist: pytest-asyncio>=0.21.0; extra == "test"
52
52
  Requires-Dist: pytest-cov>=4.0.0; extra == "test"
53
+ Provides-Extra: mcp
54
+ Requires-Dist: mcp>=1.0.0; extra == "mcp"
55
+ Requires-Dist: starlette>=0.27.0; extra == "mcp"
56
+ Requires-Dist: uvicorn>=0.22.0; extra == "mcp"
53
57
  Dynamic: license-file
54
58
 
55
59
  # Sugar 🍰
@@ -208,6 +212,108 @@ sugar list --status completed
208
212
  - Confidence-based auto-posting
209
213
  - Searchable issue history
210
214
 
215
+ **Ralph Wiggum Integration** *(New)*
216
+ - Iterative execution for complex tasks
217
+ - Self-correcting loops until tests pass
218
+ - Prevents single-shot failures
219
+ - Automatic completion detection
220
+
221
+ ## Ralph Wiggum: Why Sugar Gets It Right
222
+
223
+ Here's the thing about AI coding: **single-shot attempts often fail on complex tasks**.
224
+
225
+ Ask Claude to implement a feature in one go, and you might get something that's 80% right. But that 20% means broken tests, edge cases missed, or subtle bugs. You end up going back and forth, manually iterating until it works.
226
+
227
+ **Ralph Wiggum fixes this by design.**
228
+
229
+ Instead of trying to complete a task perfectly the first time, Sugar can feed the same prompt repeatedly. Each iteration:
230
+
231
+ 1. Claude sees its previous work in the files
232
+ 2. Runs tests and sees what's failing
233
+ 3. Fixes issues and improves the implementation
234
+ 4. Repeats until the task is actually complete
235
+
236
+ ```bash
237
+ # Without Ralph (traditional single-shot):
238
+ sugar add "Implement rate limiting"
239
+ # Claude attempts once, maybe tests fail, task marked "done" anyway
240
+
241
+ # With Ralph (iterative):
242
+ sugar add "Implement rate limiting" --ralph --max-iterations 10
243
+ # Claude iterates: implement → test → fix → test → fix → done
244
+ # Only marked complete when tests actually pass
245
+ ```
246
+
247
+ **Think of it like code review cycles**, but automated. Junior dev writes code, tests fail, they fix it, tests pass, PR merged. Ralph does this loop automatically.
248
+
249
+ ### When to Use Ralph
250
+
251
+ | Task Type | Without Ralph | With Ralph |
252
+ |-----------|---------------|------------|
253
+ | Simple bug fix | Works fine | Overkill |
254
+ | New feature | Hit or miss | Iterates until working |
255
+ | Complex refactor | Often breaks things | Self-corrects |
256
+ | TDD implementation | Tests often fail | Keeps going until green |
257
+ | Flaky test debugging | Might give up | Tries multiple approaches |
258
+
259
+ ### How It Works
260
+
261
+ ```
262
+ Iteration 1: "Implement rate limiting"
263
+ → Creates RateLimiter class
264
+ → Tests: 2 passing, 3 failing
265
+
266
+ Iteration 2: Same prompt, sees previous work
267
+ → Fixes failing tests
268
+ → Tests: 4 passing, 1 failing
269
+
270
+ Iteration 3: Same prompt, sees more progress
271
+ → Handles edge case
272
+ → Tests: 5 passing, 0 failing
273
+ → Outputs: <promise>DONE</promise>
274
+ → Task complete!
275
+ ```
276
+
277
+ The `<promise>` tag is how Claude signals "I'm actually done." Without it, Ralph knows to keep iterating.
278
+
279
+ ### Setup
280
+
281
+ **Ralph is built into Sugar** - no separate installation required. Just enable it in your config:
282
+
283
+ ```yaml
284
+ # .sugar/config.yaml
285
+ sugar:
286
+ ralph:
287
+ enabled: true
288
+ max_iterations: 10
289
+ require_completion_criteria: true
290
+ ```
291
+
292
+ Or use the `--ralph` flag when adding tasks:
293
+
294
+ ```bash
295
+ sugar add "Complex feature" --ralph --max-iterations 15
296
+ ```
297
+
298
+ ### Safety First
299
+
300
+ Ralph won't run forever. You must include:
301
+ - A `<promise>` tag in your prompt (completion signal)
302
+ - OR `--max-iterations` flag (safety limit)
303
+
304
+ Sugar validates this BEFORE starting. No completion criteria = task rejected.
305
+
306
+ ### Interactive Use (Claude Code)
307
+
308
+ For interactive Ralph loops in Claude Code sessions (outside of Sugar), install the Ralph Wiggum plugin:
309
+
310
+ ```bash
311
+ # If you have the toolkit installed:
312
+ /ralph-wiggum:ralph-loop "Fix the flaky tests" --max-iterations 10
313
+ ```
314
+
315
+ **Full docs:** [docs/ralph-wiggum.md](docs/ralph-wiggum.md)
316
+
211
317
  ## Issue Responder
212
318
 
213
319
  Automatically analyze and respond to GitHub issues with AI-powered insights. Sugar understands issue context, codebase structure, and project patterns to generate helpful responses.
@@ -154,6 +154,108 @@ sugar list --status completed
154
154
  - Confidence-based auto-posting
155
155
  - Searchable issue history
156
156
 
157
+ **Ralph Wiggum Integration** *(New)*
158
+ - Iterative execution for complex tasks
159
+ - Self-correcting loops until tests pass
160
+ - Prevents single-shot failures
161
+ - Automatic completion detection
162
+
163
+ ## Ralph Wiggum: Why Sugar Gets It Right
164
+
165
+ Here's the thing about AI coding: **single-shot attempts often fail on complex tasks**.
166
+
167
+ Ask Claude to implement a feature in one go, and you might get something that's 80% right. But that 20% means broken tests, edge cases missed, or subtle bugs. You end up going back and forth, manually iterating until it works.
168
+
169
+ **Ralph Wiggum fixes this by design.**
170
+
171
+ Instead of trying to complete a task perfectly the first time, Sugar can feed the same prompt repeatedly. Each iteration:
172
+
173
+ 1. Claude sees its previous work in the files
174
+ 2. Runs tests and sees what's failing
175
+ 3. Fixes issues and improves the implementation
176
+ 4. Repeats until the task is actually complete
177
+
178
+ ```bash
179
+ # Without Ralph (traditional single-shot):
180
+ sugar add "Implement rate limiting"
181
+ # Claude attempts once, maybe tests fail, task marked "done" anyway
182
+
183
+ # With Ralph (iterative):
184
+ sugar add "Implement rate limiting" --ralph --max-iterations 10
185
+ # Claude iterates: implement → test → fix → test → fix → done
186
+ # Only marked complete when tests actually pass
187
+ ```
188
+
189
+ **Think of it like code review cycles**, but automated. Junior dev writes code, tests fail, they fix it, tests pass, PR merged. Ralph does this loop automatically.
190
+
191
+ ### When to Use Ralph
192
+
193
+ | Task Type | Without Ralph | With Ralph |
194
+ |-----------|---------------|------------|
195
+ | Simple bug fix | Works fine | Overkill |
196
+ | New feature | Hit or miss | Iterates until working |
197
+ | Complex refactor | Often breaks things | Self-corrects |
198
+ | TDD implementation | Tests often fail | Keeps going until green |
199
+ | Flaky test debugging | Might give up | Tries multiple approaches |
200
+
201
+ ### How It Works
202
+
203
+ ```
204
+ Iteration 1: "Implement rate limiting"
205
+ → Creates RateLimiter class
206
+ → Tests: 2 passing, 3 failing
207
+
208
+ Iteration 2: Same prompt, sees previous work
209
+ → Fixes failing tests
210
+ → Tests: 4 passing, 1 failing
211
+
212
+ Iteration 3: Same prompt, sees more progress
213
+ → Handles edge case
214
+ → Tests: 5 passing, 0 failing
215
+ → Outputs: <promise>DONE</promise>
216
+ → Task complete!
217
+ ```
218
+
219
+ The `<promise>` tag is how Claude signals "I'm actually done." Without it, Ralph knows to keep iterating.
220
+
221
+ ### Setup
222
+
223
+ **Ralph is built into Sugar** - no separate installation required. Just enable it in your config:
224
+
225
+ ```yaml
226
+ # .sugar/config.yaml
227
+ sugar:
228
+ ralph:
229
+ enabled: true
230
+ max_iterations: 10
231
+ require_completion_criteria: true
232
+ ```
233
+
234
+ Or use the `--ralph` flag when adding tasks:
235
+
236
+ ```bash
237
+ sugar add "Complex feature" --ralph --max-iterations 15
238
+ ```
239
+
240
+ ### Safety First
241
+
242
+ Ralph won't run forever. You must include:
243
+ - A `<promise>` tag in your prompt (completion signal)
244
+ - OR `--max-iterations` flag (safety limit)
245
+
246
+ Sugar validates this BEFORE starting. No completion criteria = task rejected.
247
+
248
+ ### Interactive Use (Claude Code)
249
+
250
+ For interactive Ralph loops in Claude Code sessions (outside of Sugar), install the Ralph Wiggum plugin:
251
+
252
+ ```bash
253
+ # If you have the toolkit installed:
254
+ /ralph-wiggum:ralph-loop "Fix the flaky tests" --max-iterations 10
255
+ ```
256
+
257
+ **Full docs:** [docs/ralph-wiggum.md](docs/ralph-wiggum.md)
258
+
157
259
  ## Issue Responder
158
260
 
159
261
  Automatically analyze and respond to GitHub issues with AI-powered insights. Sugar understands issue context, codebase structure, and project patterns to generate helpful responses.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sugarai"
7
- version = "3.1.1.dev6"
7
+ version = "3.2.0"
8
8
  description = "Sugar 🍰 - A dev team that never stops. Delegate full tasks to AI in the background."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -59,6 +59,11 @@ test = [
59
59
  "pytest-asyncio>=0.21.0",
60
60
  "pytest-cov>=4.0.0"
61
61
  ]
62
+ mcp = [
63
+ "mcp>=1.0.0",
64
+ "starlette>=0.27.0",
65
+ "uvicorn>=0.22.0",
66
+ ]
62
67
 
63
68
  [project.scripts]
64
69
  sugar = "sugar.main:cli"
@@ -20,6 +20,7 @@ from ..storage import IssueResponseManager
20
20
  from ..profiles import IssueResponderProfile
21
21
  from ..config import IssueResponderConfig
22
22
  from ..integrations import GitHubClient
23
+ from ..ralph import RalphWiggumProfile, RalphConfig
23
24
 
24
25
  logger = logging.getLogger(__name__)
25
26
 
@@ -157,6 +158,129 @@ class AgentSDKExecutor(BaseExecutor):
157
158
  finally:
158
159
  await agent.end_session()
159
160
 
161
+ async def _execute_ralph_iteration(
162
+ self, work_item: Dict[str, Any]
163
+ ) -> Dict[str, Any]:
164
+ """Execute a work item with Ralph Wiggum iterative loop."""
165
+ context = work_item.get("context", {})
166
+ max_iterations = context.get("max_iterations", 10)
167
+
168
+ # Create Ralph config
169
+ ralph_config = RalphConfig(
170
+ max_iterations=max_iterations,
171
+ completion_promise=context.get("completion_promise", "DONE"),
172
+ require_completion_criteria=False, # Already validated at CLI
173
+ quality_gates_enabled=self.quality_gates_enabled,
174
+ stop_on_gate_failure=context.get("stop_on_gate_failure", False),
175
+ )
176
+
177
+ profile = RalphWiggumProfile(ralph_config=ralph_config)
178
+
179
+ # Validate input
180
+ input_data = {
181
+ "prompt": work_item.get("description", work_item.get("title", "")),
182
+ "work_item": work_item,
183
+ }
184
+ processed = await profile.process_input(input_data)
185
+
186
+ if not processed.get("valid", True):
187
+ return {
188
+ "success": False,
189
+ "error": "Invalid Ralph input: "
190
+ + ", ".join(processed.get("errors", [])),
191
+ "timestamp": datetime.now(timezone.utc).isoformat(),
192
+ "work_item_id": work_item.get("id"),
193
+ }
194
+
195
+ start_time = datetime.now(timezone.utc)
196
+ agent = await self._get_agent()
197
+ prompt = processed.get("prompt", work_item.get("description", ""))
198
+
199
+ iteration_results = []
200
+ final_result = None
201
+
202
+ logger.info(f"Starting Ralph execution with max {max_iterations} iterations")
203
+
204
+ while profile.should_continue():
205
+ iteration = profile.current_iteration + 1 # 1-indexed for display
206
+ logger.info(f"Ralph iteration {iteration}/{max_iterations}")
207
+
208
+ try:
209
+ # Execute the prompt
210
+ response = await agent.execute(prompt)
211
+
212
+ # Process output to check for completion
213
+ output_data = {
214
+ "content": response.content,
215
+ "success": response.success,
216
+ "files_changed": getattr(response, "files_changed", []),
217
+ }
218
+
219
+ result = await profile.process_output(output_data)
220
+
221
+ iteration_results.append(
222
+ {
223
+ "iteration": iteration,
224
+ "complete": result.get("complete", False),
225
+ "promise_detected": result.get("promise_detected"),
226
+ "stuck": result.get("stuck", False),
227
+ }
228
+ )
229
+
230
+ if result.get("complete"):
231
+ logger.info(f"Ralph completed after {iteration} iterations")
232
+ final_result = {
233
+ "success": True,
234
+ "content": response.content,
235
+ "iterations": iteration,
236
+ "completion_reason": result.get(
237
+ "completion_reason", "promise_detected"
238
+ ),
239
+ }
240
+ break
241
+
242
+ if result.get("stuck"):
243
+ logger.warning(
244
+ f"Ralph detected stuck state at iteration {iteration}"
245
+ )
246
+ final_result = {
247
+ "success": False,
248
+ "error": "Task appears stuck",
249
+ "iterations": iteration,
250
+ "stuck_reason": result.get("stuck_reason"),
251
+ }
252
+ break
253
+
254
+ except Exception as e:
255
+ logger.error(f"Ralph iteration {iteration} failed: {e}")
256
+ iteration_results.append(
257
+ {
258
+ "iteration": iteration,
259
+ "error": str(e),
260
+ }
261
+ )
262
+
263
+ # If loop ended without completion
264
+ if final_result is None:
265
+ final_result = {
266
+ "success": False,
267
+ "error": f"Max iterations ({max_iterations}) reached without completion",
268
+ "iterations": profile.current_iteration,
269
+ }
270
+
271
+ execution_time = (datetime.now(timezone.utc) - start_time).total_seconds()
272
+ stats = profile.get_iteration_stats()
273
+
274
+ return {
275
+ **final_result,
276
+ "timestamp": datetime.now(timezone.utc).isoformat(),
277
+ "work_item_id": work_item.get("id"),
278
+ "execution_time": execution_time,
279
+ "executor": "agent_sdk_ralph",
280
+ "ralph_stats": stats,
281
+ "iteration_results": iteration_results,
282
+ }
283
+
160
284
  async def execute_work(self, work_item: Dict[str, Any]) -> Dict[str, Any]:
161
285
  """
162
286
  Execute a work item using the Claude Agent SDK.
@@ -169,10 +293,16 @@ class AgentSDKExecutor(BaseExecutor):
169
293
  """
170
294
  # Check for specialized task types
171
295
  task_type = work_item.get("type", "")
296
+ context = work_item.get("context", {})
172
297
 
173
298
  if task_type == "issue_response":
174
299
  return await self._execute_issue_response(work_item)
175
300
 
301
+ # Check for Ralph-enabled tasks
302
+ if context.get("ralph_enabled"):
303
+ logger.info(f"Executing with Ralph Wiggum: {work_item.get('title')}")
304
+ return await self._execute_ralph_iteration(work_item)
305
+
176
306
  if self.dry_run:
177
307
  logger.info(f"DRY RUN: Simulating execution of {work_item.get('title')}")
178
308
  return await self._simulate_execution(work_item)
@@ -311,6 +311,13 @@ def init(project_dir):
311
311
  @click.option(
312
312
  "--skip-stages", help="Comma-separated stages to skip (research,planning)"
313
313
  )
314
+ @click.option("--ralph", is_flag=True, help="Enable Ralph Wiggum iterative execution")
315
+ @click.option(
316
+ "--max-iterations",
317
+ type=int,
318
+ default=None,
319
+ help="Max iterations for Ralph mode (default: 10)",
320
+ )
314
321
  @click.pass_context
315
322
  def add(
316
323
  ctx,
@@ -325,6 +332,8 @@ def add(
325
332
  parse_json,
326
333
  orchestrate,
327
334
  skip_stages,
335
+ ralph,
336
+ max_iterations,
328
337
  ):
329
338
  """Add a new task to Sugar work queue
330
339
 
@@ -415,6 +424,23 @@ def add(
415
424
  s.strip() for s in skip_stages.split(",")
416
425
  ]
417
426
 
427
+ # Add Ralph Wiggum settings if enabled
428
+ if ralph:
429
+ task_data["context"]["ralph_enabled"] = True
430
+ task_data["context"]["max_iterations"] = max_iterations or 10
431
+ # Validate completion criteria if strict mode
432
+ from .ralph import CompletionCriteriaValidator
433
+
434
+ validator = CompletionCriteriaValidator(strict=False)
435
+ result = validator.validate(
436
+ description, {"max_iterations": max_iterations or 10}
437
+ )
438
+ if not result.is_valid:
439
+ click.echo(
440
+ f"⚠️ Ralph enabled but completion criteria may be weak: {', '.join(result.suggestions[:2])}",
441
+ err=True,
442
+ )
443
+
418
444
  # Override/merge with complex input data
419
445
  if task_data_override:
420
446
  # Handle context merging specially to preserve base context
@@ -445,8 +471,13 @@ def add(
445
471
  elif parse_json:
446
472
  input_method = " (JSON parsed)"
447
473
 
474
+ ralph_mode = ""
475
+ if ralph:
476
+ max_iter = task_data["context"].get("max_iterations", 10)
477
+ ralph_mode = f" [Ralph: max {max_iter} iterations]"
478
+
448
479
  click.echo(
449
- f"✅ Added {task_data.get('type', task_type)} task: '{task_data.get('title', title)}' ({urgency}){input_method}"
480
+ f"✅ Added {task_data.get('type', task_type)} task: '{task_data.get('title', title)}' ({urgency}){input_method}{ralph_mode}"
450
481
  )
451
482
 
452
483
  except Exception as e:
@@ -2149,6 +2180,16 @@ sugar:
2149
2180
 
2150
2181
  # Model selection
2151
2182
  model: "claude-sonnet-4-20250514"
2183
+
2184
+ # Ralph Wiggum (iterative AI execution)
2185
+ ralph:
2186
+ enabled: true # Allow Ralph mode for tasks
2187
+ max_iterations: 10 # Default max iterations per task
2188
+ iteration_timeout: 300 # Max seconds per iteration (5 min)
2189
+ completion_promise: "DONE" # Default completion signal
2190
+ require_completion_criteria: true # Require <promise> tags or --max-iterations
2191
+ quality_gates_enabled: true # Run quality gates between iterations
2192
+ stop_on_gate_failure: false # Keep trying even if gates fail
2152
2193
  """
2153
2194
 
2154
2195
 
@@ -3386,5 +3427,54 @@ def issue_search(ctx, query, repo, limit):
3386
3427
  sys.exit(1)
3387
3428
 
3388
3429
 
3430
+ # =============================================================================
3431
+ # MCP Server Commands
3432
+ # =============================================================================
3433
+
3434
+
3435
+ @cli.group()
3436
+ @click.pass_context
3437
+ def mcp(ctx):
3438
+ """MCP (Model Context Protocol) server for Goose and other MCP clients"""
3439
+ pass
3440
+
3441
+
3442
+ @mcp.command("serve")
3443
+ @click.option("--host", default="0.0.0.0", help="Host to bind to")
3444
+ @click.option("--port", default=8080, type=int, help="Port to listen on")
3445
+ @click.option("--repo", help="Default repository (owner/repo)")
3446
+ @click.pass_context
3447
+ def mcp_serve(ctx, host, port, repo):
3448
+ """Start the Sugar MCP server for Goose integration"""
3449
+ import asyncio
3450
+
3451
+ try:
3452
+ from .mcp.server import create_server
3453
+ except ImportError as e:
3454
+ click.echo(
3455
+ "❌ MCP dependencies not installed. Install with:\n"
3456
+ " pip install sugarai[mcp]",
3457
+ err=True,
3458
+ )
3459
+ click.echo(f"\nMissing: {e}", err=True)
3460
+ sys.exit(1)
3461
+
3462
+ click.echo(f"🍰 Starting Sugar MCP server on {host}:{port}")
3463
+ if repo:
3464
+ click.echo(f" Default repository: {repo}")
3465
+ click.echo("\nPress Ctrl+C to stop\n")
3466
+
3467
+ server = create_server(
3468
+ host=host,
3469
+ port=port,
3470
+ default_repo=repo,
3471
+ )
3472
+
3473
+ try:
3474
+ asyncio.run(server.run())
3475
+ except KeyboardInterrupt:
3476
+ click.echo("\n👋 Server stopped")
3477
+
3478
+
3389
3479
  if __name__ == "__main__":
3390
3480
  cli()
@@ -0,0 +1,34 @@
1
+ """
2
+ Sugar MCP Server
3
+
4
+ Model Context Protocol server for Sugar, enabling integration with:
5
+ - GitHub Copilot Custom Agents
6
+ - Other MCP-compatible clients
7
+
8
+ Note: This module uses lazy imports to avoid requiring MCP dependencies
9
+ unless the MCP server is actually used. This allows the base Sugar CLI
10
+ to work without installing the optional [mcp] extras.
11
+ """
12
+
13
+ __all__ = ["SugarMCPServer", "create_server"]
14
+
15
+ # Lazy import cache
16
+ _lazy_imports = {}
17
+
18
+
19
+ def __getattr__(name: str):
20
+ """Lazy import to avoid requiring MCP dependencies unless actually used."""
21
+ if name in __all__:
22
+ if name not in _lazy_imports:
23
+ try:
24
+ from .server import SugarMCPServer, create_server
25
+
26
+ _lazy_imports["SugarMCPServer"] = SugarMCPServer
27
+ _lazy_imports["create_server"] = create_server
28
+ except ImportError as e:
29
+ raise ImportError(
30
+ f"MCP dependencies not installed. Install with: pip install sugarai[mcp]\n"
31
+ f"Original error: {e}"
32
+ ) from e
33
+ return _lazy_imports[name]
34
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,19 @@
1
+ """
2
+ Ralph Wiggum Integration - Iterative AI loop support for Sugar
3
+
4
+ This module provides:
5
+ - CompletionCriteriaValidator: Validates tasks have clear exit conditions
6
+ - RalphWiggumProfile: Profile for iterative task execution
7
+ - RalphConfig: Configuration for Ralph Wiggum loops
8
+ """
9
+
10
+ from .validator import CompletionCriteriaValidator, ValidationResult
11
+ from .profile import RalphWiggumProfile
12
+ from .config import RalphConfig
13
+
14
+ __all__ = [
15
+ "CompletionCriteriaValidator",
16
+ "ValidationResult",
17
+ "RalphWiggumProfile",
18
+ "RalphConfig",
19
+ ]
@@ -0,0 +1,75 @@
1
+ """
2
+ Ralph Wiggum Configuration
3
+
4
+ Configuration for Ralph Wiggum iterative loops.
5
+ """
6
+
7
+ from dataclasses import dataclass, field
8
+ from typing import List, Optional
9
+
10
+
11
+ @dataclass
12
+ class RalphConfig:
13
+ """Configuration for Ralph Wiggum iterative execution"""
14
+
15
+ # Maximum iterations before auto-stop (safety limit)
16
+ max_iterations: int = 10
17
+
18
+ # Promise text to look for to signal completion
19
+ completion_promise: str = "DONE"
20
+
21
+ # Whether to require explicit completion criteria
22
+ require_completion_criteria: bool = True
23
+
24
+ # Minimum confidence score to consider task complete
25
+ min_confidence: float = 0.8
26
+
27
+ # Timeout per iteration in seconds
28
+ iteration_timeout: int = 300
29
+
30
+ # Delay between iterations in seconds
31
+ iteration_delay: float = 1.0
32
+
33
+ # Quality gates to run between iterations
34
+ quality_gates_enabled: bool = True
35
+
36
+ # Stop on first quality gate failure or continue iterating
37
+ stop_on_gate_failure: bool = False
38
+
39
+ # Patterns that indicate completion (besides promise tag)
40
+ completion_patterns: List[str] = field(
41
+ default_factory=lambda: [
42
+ r"<promise>.*?</promise>",
43
+ r"all tests pass",
44
+ r"task complete",
45
+ r"implementation complete",
46
+ ]
47
+ )
48
+
49
+ # Patterns that indicate the task is stuck and should stop
50
+ stuck_patterns: List[str] = field(
51
+ default_factory=lambda: [
52
+ r"cannot proceed",
53
+ r"blocked by",
54
+ r"need human intervention",
55
+ r"unable to resolve",
56
+ ]
57
+ )
58
+
59
+ def validate(self) -> List[str]:
60
+ """Validate configuration, return list of errors"""
61
+ errors = []
62
+
63
+ if self.max_iterations < 1:
64
+ errors.append("max_iterations must be at least 1")
65
+
66
+ if self.max_iterations > 100:
67
+ errors.append("max_iterations should not exceed 100 (safety limit)")
68
+
69
+ if self.iteration_timeout < 30:
70
+ errors.append("iteration_timeout must be at least 30 seconds")
71
+
72
+ if not 0.0 <= self.min_confidence <= 1.0:
73
+ errors.append("min_confidence must be between 0.0 and 1.0")
74
+
75
+ return errors