-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProjectScaffolder.cs
More file actions
776 lines (644 loc) · 30.3 KB
/
ProjectScaffolder.cs
File metadata and controls
776 lines (644 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using RalphController.Models;
namespace RalphController;
/// <summary>
/// Scaffolds new Ralph projects by generating required files using AI
/// </summary>
public class ProjectScaffolder
{
private readonly RalphConfig _config;
/// <summary>Fired when scaffolding starts for a file</summary>
public event Action<string>? OnScaffoldStart;
/// <summary>Fired when scaffolding completes for a file</summary>
public event Action<string, bool>? OnScaffoldComplete;
/// <summary>Fired when output is received from AI</summary>
public event Action<string>? OnOutput;
/// <summary>
/// Project description/context provided by the user.
/// This is included in all scaffolding prompts so the AI understands the project.
/// </summary>
public string? ProjectContext { get; set; }
/// <summary>
/// When true, overwrites existing files during scaffolding.
/// Used for re-initializing a project with a new spec.
/// </summary>
public bool ForceOverwrite { get; set; }
public ProjectScaffolder(RalphConfig config)
{
_config = config;
}
/// <summary>
/// Check what project files are missing
/// </summary>
public ProjectStructure ValidateProject()
{
return ProjectValidator.ValidateProject(_config);
}
/// <summary>
/// Scaffold all missing files using AI
/// </summary>
public async Task<bool> ScaffoldMissingAsync(CancellationToken cancellationToken = default)
{
var structure = ValidateProject();
if (structure.IsComplete && !ForceOverwrite)
{
return true;
}
// Ensure we have project context
var context = ProjectContext ?? "No project description provided. Create generic templates.";
var success = true;
// Create specs directory first (doesn't need AI)
if (!structure.HasSpecsDirectory)
{
Directory.CreateDirectory(_config.SpecsDirectoryPath);
}
// Generate agents.md
if (!structure.HasAgentsMd || ForceOverwrite)
{
success &= await ScaffoldFileAsync("agents.md", ScaffoldPrompts.GetAgentsMdPrompt(context), cancellationToken);
}
// Generate specs files
if (!structure.HasSpecsDirectory || !Directory.EnumerateFiles(_config.SpecsDirectoryPath, "*.md").Any() || ForceOverwrite)
{
success &= await ScaffoldFileAsync("specs/", ScaffoldPrompts.GetSpecsDirectoryPrompt(context), cancellationToken);
}
// Generate prompt.md
if (!structure.HasPromptMd || ForceOverwrite)
{
success &= await ScaffoldFileAsync("prompt.md", ScaffoldPrompts.GetPromptMdPrompt(context), cancellationToken);
}
// Generate implementation_plan.md
if (!structure.HasImplementationPlan || ForceOverwrite)
{
success &= await ScaffoldFileAsync("implementation_plan.md", ScaffoldPrompts.GetImplementationPlanPrompt(context), cancellationToken);
}
return success;
}
/// <summary>
/// Scaffold all project files using AI (overwrites existing files)
/// </summary>
public async Task<bool> ScaffoldAllAsync(CancellationToken cancellationToken = default)
{
ForceOverwrite = true;
return await ScaffoldMissingAsync(cancellationToken);
}
/// <summary>
/// Scaffold a specific file using AI
/// </summary>
public async Task<bool> ScaffoldFileAsync(string fileName, string prompt, CancellationToken cancellationToken = default)
{
OnScaffoldStart?.Invoke(fileName);
// Use HTTP API for Ollama provider instead of process
if (_config.ProviderConfig.Provider == AIProvider.Ollama)
{
return await ScaffoldFileViaOllamaAsync(fileName, prompt, cancellationToken);
}
var process = new AIProcess(_config);
process.OnOutput += line => OnOutput?.Invoke(line);
process.OnError += line => OnOutput?.Invoke($"[ERROR] {line}");
try
{
var result = await process.RunAsync(prompt, cancellationToken);
if (!result.Success)
{
OnOutput?.Invoke($"[FAILED] Exit code: {result.ExitCode}");
if (!string.IsNullOrWhiteSpace(result.Error))
{
OnOutput?.Invoke($"[STDERR] {result.Error}");
}
}
OnScaffoldComplete?.Invoke(fileName, result.Success);
return result.Success;
}
catch (Exception ex)
{
OnOutput?.Invoke($"[EXCEPTION] {ex.Message}");
OnScaffoldComplete?.Invoke(fileName, false);
return false;
}
finally
{
process.Dispose();
}
}
/// <summary>
/// Scaffold a file using Ollama HTTP API
/// </summary>
private async Task<bool> ScaffoldFileViaOllamaAsync(string fileName, string prompt, CancellationToken cancellationToken)
{
var baseUrl = _config.ProviderConfig.ExecutablePath.TrimEnd('/'); // URL stored in ExecutablePath
var model = _config.ProviderConfig.Arguments; // Model stored in Arguments
// Truncate prompt if too long for local models
// 4096 token context = ~3000 chars max to leave room for response (~1000 tokens)
const int maxPromptLength = 3000;
if (prompt.Length > maxPromptLength)
{
// Find PROJECT CONTEXT section and truncate it
var contextMarker = "PROJECT CONTEXT:";
var contextStart = prompt.IndexOf(contextMarker);
if (contextStart >= 0)
{
var contextEnd = prompt.IndexOf("\n\n", contextStart + contextMarker.Length + 100);
if (contextEnd > contextStart)
{
var contextContent = prompt.Substring(contextStart, contextEnd - contextStart);
var maxContextLen = maxPromptLength - (prompt.Length - contextContent.Length);
if (maxContextLen > 500)
{
var truncatedContext = contextContent.Length > maxContextLen
? contextContent.Substring(0, maxContextLen) + "\n... [truncated for length]"
: contextContent;
prompt = prompt.Substring(0, contextStart) + truncatedContext + prompt.Substring(contextEnd);
}
}
}
// If still too long, hard truncate
if (prompt.Length > maxPromptLength)
{
prompt = prompt.Substring(0, maxPromptLength) + "\n\n... [truncated]";
}
}
try
{
using var httpClient = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
// Build system prompt based on file type - be VERY explicit about format
string systemPrompt;
if (fileName == "agents.md")
{
systemPrompt = """
You are creating an agents.md file for an autonomous AI coding project.
CRITICAL: This is an OPERATIONAL GUIDE for how the AI agent should operate.
It defines workflow, rules, and build commands - NOT project documentation.
VERIFICATION WORKFLOW - CRITICAL:
This project uses a verification system where work is marked `[?]` and verified in the next iteration.
Tasks have THREE states:
- `[ ]` - Incomplete (not started or needs rework)
- `[?]` - Waiting verification (work done, needs verification)
- `[x]` - Complete (verified)
YOUR OUTPUT MUST START EXACTLY LIKE THIS:
```
# Agent Configuration
## Core Principle
- **One task at a time** - Pick ONE incomplete task, complete it, verify it works
- **ALL tasks must be completed** - Not just high priority ones
- **Verification workflow** - Mark work `[?]` after completion, next iteration verifies before `[x]`
- **Commit often** - After every successful change
```
REQUIRED SECTIONS:
1. Core Principle - one task at a time, all tasks must be done
2. Build Commands - actual commands for this project
3. Test Commands - actual test commands for this project
4. Task Selection - how to pick the next task
5. Error Handling - what to do when things fail
6. Project-Specific Rules - any special rules for this project
DO NOT output JSON. DO NOT output the project spec.
""";
}
else if (fileName == "prompt.md")
{
systemPrompt = """
You are creating a prompt.md file for an autonomous AI coding agent.
CRITICAL: This is NOT a spec or documentation. It's a SHORT instruction file (under 400 words).
The prompt tells the AI what to do EACH LOOP ITERATION.
VERIFICATION WORKFLOW - CRITICAL:
This project uses a verification system where one agent does work and another verifies it.
Tasks have THREE states:
- `[ ]` - Incomplete (not started or needs rework)
- `[?]` - Waiting verification (work done, needs different agent to verify)
- `[x]` - Complete (verified by a second agent)
YOUR OUTPUT MUST START EXACTLY LIKE THIS:
```
## Task Status & Transitions
- `[ ]` - Incomplete: not started or needs rework
- `[?]` - Waiting verification: work done, needs different agent to verify
- `[x]` - Complete: verified by a second agent
## Context Loading
1. Read agents.md for project context
2. Read specs/* for requirements
3. Read implementation_plan.md for progress
## Task Selection (IN THIS ORDER)
1. FIRST: Look for any `[?]` tasks - verify these before doing new work
2. SECOND: If no `[?]` tasks, pick an incomplete `[ ]` task (ALL tasks must be completed)
```
REQUIRED RULES TO INCLUDE:
- When completing YOUR work: mark `[ ]` → `[?]` (NEVER directly to `[x]`)
- When verifying ANOTHER agent's work: mark `[?]` → `[x]` if good, or `[?]` → `[ ]` if bad
- NEVER mark your own work as `[x]` complete
Include sections for: Task Status, Context Loading, Task Selection, Git Commits, Rules.
DO NOT output JSON. DO NOT output the project spec.
Just output the prompt.md file content.
""";
}
else if (fileName == "implementation_plan.md")
{
systemPrompt = """
You are creating an implementation_plan.md task list for an autonomous AI agent.
VERIFICATION WORKFLOW - CRITICAL:
This project uses a verification system where one agent does work and another verifies it.
Tasks have THREE states:
- `[ ]` - Incomplete (not started or needs rework)
- `[?]` - Waiting verification (work done, needs different agent to verify)
- `[x]` - Complete (verified by a second agent)
YOUR OUTPUT MUST START EXACTLY LIKE THIS:
```
# Implementation Plan
## Status Legend
- `[ ]` - Incomplete (not started or needs rework)
- `[?]` - Waiting to be verified (work done, needs verification by different agent)
- `[x]` - Complete (verified by a second agent)
---
## Verified Complete
- [x] Project initialized
## Waiting Verification
<!-- Tasks marked [?] appear here after an agent completes them -->
## High Priority
- [ ] First critical task
```
REQUIRED SECTIONS (in order):
1. Status Legend - explains the three task states
2. Verified Complete - tasks verified by a second agent
3. Waiting Verification - tasks done but need verification
4. High Priority - critical incomplete tasks
5. Medium Priority - important incomplete tasks
6. Low Priority - nice-to-have tasks
Create tasks based on the project requirements. Use markdown checkboxes.
DO NOT output JSON. Output ONLY the markdown task list.
""";
}
else if (fileName.EndsWith(".md"))
{
systemPrompt = $"""
You are generating content for a markdown file named '{fileName}'.
CRITICAL FORMAT REQUIREMENTS:
- Output valid MARKDOWN content ONLY
- Do NOT output JSON
- Do NOT wrap output in code blocks
- Do NOT add commentary before or after
- Start DIRECTLY with markdown (e.g., '# Heading')
The output will be saved directly as {fileName}. Begin with the markdown content now.
""";
}
else
{
systemPrompt = $"You are an expert software architect. Generate the content for '{fileName}'. Output ONLY the raw file content with no commentary or code blocks.";
}
// Try OpenAI-compatible endpoint first (works with LMStudio and many others)
var requestBody = new
{
model = model,
messages = new[]
{
new { role = "system", content = systemPrompt },
new { role = "user", content = prompt }
},
stream = true,
temperature = 0.7
};
var jsonContent = new StringContent(
JsonSerializer.Serialize(requestBody),
Encoding.UTF8,
"application/json");
// Use ResponseHeadersRead to enable streaming (don't buffer the entire response)
var request = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}/v1/chat/completions")
{
Content = jsonContent
};
var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (!response.IsSuccessStatusCode)
{
// Fall back to Ollama native endpoint
var ollamaRequest = new
{
model = model,
messages = new[]
{
new { role = "system", content = systemPrompt },
new { role = "user", content = prompt }
},
stream = true
};
jsonContent = new StringContent(
JsonSerializer.Serialize(ollamaRequest),
Encoding.UTF8,
"application/json");
request = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}/api/chat")
{
Content = jsonContent
};
response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
}
if (!response.IsSuccessStatusCode)
{
var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
OnOutput?.Invoke($"[ERROR] API returned {response.StatusCode}: {errorContent}");
OnScaffoldComplete?.Invoke(fileName, false);
return false;
}
// Parse streaming response
var content = new StringBuilder();
using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var reader = new StreamReader(stream);
var lineCount = 0;
while (!reader.EndOfStream && !cancellationToken.IsCancellationRequested)
{
var line = await reader.ReadLineAsync(cancellationToken);
lineCount++;
if (string.IsNullOrEmpty(line)) continue;
// Handle SSE format
if (line.StartsWith("data: "))
{
var data = line.Substring(6);
if (data == "[DONE]") break;
try
{
using var doc = JsonDocument.Parse(data);
var root = doc.RootElement;
// OpenAI format: choices[0].delta.content
if (root.TryGetProperty("choices", out var choices) && choices.GetArrayLength() > 0)
{
var choice = choices[0];
if (choice.TryGetProperty("delta", out var delta) &&
delta.TryGetProperty("content", out var textEl))
{
var text = textEl.GetString();
if (!string.IsNullOrEmpty(text))
{
content.Append(text);
OnOutput?.Invoke(text);
}
}
}
}
catch (Exception ex)
{
OnOutput?.Invoke($"[DEBUG] Parse error: {ex.Message}");
}
}
else if (line.StartsWith("{"))
{
// Ollama native format: message.content
try
{
using var doc = JsonDocument.Parse(line);
var root = doc.RootElement;
if (root.TryGetProperty("message", out var message) &&
message.TryGetProperty("content", out var textEl))
{
var text = textEl.GetString();
if (!string.IsNullOrEmpty(text))
{
content.Append(text);
OnOutput?.Invoke(text);
}
}
}
catch { /* Skip unparseable lines */ }
}
}
// Write the generated content to file
var fileContent = content.ToString().Trim();
if (string.IsNullOrEmpty(fileContent))
{
OnOutput?.Invoke("[ERROR] No content generated");
OnScaffoldComplete?.Invoke(fileName, false);
return false;
}
// Remove markdown code blocks if present
fileContent = StripMarkdownCodeBlocks(fileContent);
// Detect if model output JSON instead of markdown for .md files
if (fileName.EndsWith(".md") && (fileContent.TrimStart().StartsWith("{") || fileContent.TrimStart().StartsWith("[")))
{
OnOutput?.Invoke("\n[WARNING] Model output JSON instead of markdown. This is a known issue with code-focused models.");
OnOutput?.Invoke("[TIP] Try using a general-purpose model, or create scaffold files manually.");
OnOutput?.Invoke("[TIP] You can also use --fresh and choose 'Create default template files' option.");
OnScaffoldComplete?.Invoke(fileName, false);
return false;
}
// Detect if model just echoed back the spec instead of creating the requested file
// This happens when code-focused models don't follow meta-instructions
var isScaffoldFile = fileName == "prompt.md" || fileName == "implementation_plan.md" || fileName == "agents.md";
// Check for spec-like content (but be careful - agents.md legitimately has "## Agent Architecture")
var looksLikeProjectSpec = fileContent.Contains("## Overview") && fileContent.Contains("## Features");
var hasMcpSpecContent = fileContent.Contains("MCP (Model Context Protocol)") || fileContent.Contains("server that provides AI agents");
// Validate proper format for each file type
var notProperFormat = false;
if (fileName == "prompt.md")
{
notProperFormat = !fileContent.Contains("agents.md") && !fileContent.Contains("implementation_plan.md");
}
else if (fileName == "agents.md")
{
// agents.md should have agent-related content, not just echo the spec
notProperFormat = !fileContent.Contains("Agent") && !fileContent.Contains("Subagent");
}
if (isScaffoldFile && (looksLikeProjectSpec || hasMcpSpecContent || notProperFormat))
{
OnOutput?.Invoke($"\n[WARNING] Model echoed the spec instead of creating {fileName}.");
OnOutput?.Invoke("[ISSUE] Code-focused models (like qwen-coder) often struggle with meta-instructions.");
OnOutput?.Invoke("[TIP] Use a general-purpose model for scaffolding, or choose 'Create default template files'.");
OnOutput?.Invoke("[TIP] You can then manually edit the generated templates.");
OnScaffoldComplete?.Invoke(fileName, false);
return false;
}
// Determine the full path
var fullPath = fileName.Contains('/')
? Path.Combine(_config.ProjectFilesDirectory, fileName.TrimStart('/'))
: Path.Combine(_config.ProjectFilesDirectory, fileName);
// Create directory if needed
var dir = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
await File.WriteAllTextAsync(fullPath, fileContent, cancellationToken);
OnOutput?.Invoke($"\n[SUCCESS] Created {fileName}");
OnScaffoldComplete?.Invoke(fileName, true);
return true;
}
catch (Exception ex)
{
OnOutput?.Invoke($"[EXCEPTION] {ex.Message}");
OnScaffoldComplete?.Invoke(fileName, false);
return false;
}
}
/// <summary>
/// Strip markdown code blocks from generated content
/// </summary>
private static string StripMarkdownCodeBlocks(string content)
{
var lines = content.Split('\n').ToList();
// Remove leading code block marker
if (lines.Count > 0 && lines[0].StartsWith("```"))
{
lines.RemoveAt(0);
}
// Remove trailing code block marker
if (lines.Count > 0 && lines[^1].Trim() == "```")
{
lines.RemoveAt(lines.Count - 1);
}
return string.Join('\n', lines);
}
/// <summary>
/// Create default files without AI (minimal templates)
/// </summary>
public async Task CreateDefaultFilesAsync()
{
var structure = ValidateProject();
// Create specs directory
if (!structure.HasSpecsDirectory)
{
Directory.CreateDirectory(_config.SpecsDirectoryPath);
}
// Create agents.md with minimal template
if (!structure.HasAgentsMd)
{
await File.WriteAllTextAsync(_config.AgentsFilePath, GetDefaultAgentsMd());
}
// Create specs README
var specsReadme = Path.Combine(_config.SpecsDirectoryPath, "README.md");
if (!File.Exists(specsReadme))
{
await File.WriteAllTextAsync(specsReadme, GetDefaultSpecsReadme());
}
// Create prompt.md with minimal template
if (!structure.HasPromptMd)
{
await File.WriteAllTextAsync(_config.PromptFilePath, GetDefaultPromptMd());
}
// Create implementation_plan.md with minimal template
if (!structure.HasImplementationPlan)
{
await File.WriteAllTextAsync(_config.PlanFilePath, GetDefaultImplementationPlan());
}
}
private static string GetDefaultAgentsMd() => """
# Agent Configuration
## Core Principle
- **One task at a time** - Pick ONE incomplete task, complete it, verify it works
- **ALL tasks must be completed** - Not just high priority ones
- **Verification workflow** - Mark work `[?]` after completion, next iteration verifies before `[x]`
- **Commit often** - After every successful change
## Build Commands
```bash
# Add build commands for this project
```
## Test Commands
```bash
# Add test commands for this project
```
## Task Selection
1. Read IMPLEMENTATION_PLAN.md
2. Find an incomplete `[ ]` task (ALL tasks must be completed)
3. If blocked, complete blocking task first
4. Execute selected task
5. Update plan
6. Loop until ALL tasks are `[x]` complete
## Error Handling
- **Build errors**: Try to fix, if stuck 3 times mark as blocked and move on
- **Test failures**: Fix before proceeding
- **File not found**: Use glob or list_directory to find it
## See Also
- [prompt.md](./prompt.md) - Main loop prompt
- [implementation_plan.md](./implementation_plan.md) - Current task list
- [specs/](./specs/) - Specifications
""";
private static string GetDefaultSpecsReadme() => """
# Specifications
This directory contains specification files that describe what needs to be built.
## Writing Specs
Each spec file should include:
1. **Purpose**: What the feature/component does
2. **Requirements**: Technical requirements and constraints
3. **Acceptance Criteria**: How to verify it's complete
## Example
See `example.md` for a template.
""";
private static string GetDefaultPromptMd() => """
## Task Status & Transitions
```
[ ] Incomplete ──(you implement)──► [?] Waiting Verification
[?] Waiting ──(next agent verifies)──► [x] Complete
[?] Waiting ──(verification fails)──► [ ] Incomplete (with note)
```
- `[ ]` - Incomplete: not started or needs rework
- `[?]` - Waiting verification: work done, needs different agent to verify
- `[x]` - Complete: verified by a second agent
## Context Loading
1. Read agents.md for project context and build commands
2. Read specs/* for requirements
3. Read implementation_plan.md for current progress
## Task Selection (IN THIS ORDER)
1. **FIRST**: Look for any `[?]` tasks - verify these before doing new work
2. **SECOND**: If no `[?]` tasks, pick an incomplete `[ ]` task (ALL tasks must be completed)
## When You Find a `[?]` Task:
1. Review the implementation thoroughly
2. Check code exists, compiles, meets requirements
3. Run relevant tests
4. **If GOOD**: Change `[?]` to `[x]` and move to Verified Complete section
5. **If BAD**: Change `[?]` back to `[ ]` with a note explaining what's missing
## When You Find a `[ ]` Task:
1. Implement the task completely
2. Run tests/build to verify your work
3. Change `[ ]` to `[?]` (NEVER directly to `[x]`)
4. Commit your work
## Allowed Transitions
- `[ ]` → `[?]` : You completed implementation (only valid transition for your own work)
- `[?]` → `[x]` : You verified ANOTHER agent's work passed
- `[?]` → `[ ]` : You verified another agent's work and it failed
## NOT Allowed
- `[ ]` → `[x]` : NEVER skip verification
- Marking your own work `[x]` : NEVER self-verify
## Git Commits - MANDATORY
After EVERY successful change:
```bash
git add -A && git commit -m "Description of change"
```
## Error Handling
- If stuck after 3 attempts: mark task as blocked, move on
## Status Reporting
End response with:
```
---RALPH_STATUS---
STATUS: IN_PROGRESS | COMPLETE | BLOCKED
EXIT_SIGNAL: true | false
NEXT_STEP: <what to do next>
---END_STATUS---
```
""";
private static string GetDefaultImplementationPlan() => """
# Implementation Plan
## Status Legend
- `[ ]` - Incomplete (not started or needs rework)
- `[?]` - Waiting to be verified (work done, needs verification by different agent)
- `[x]` - Complete (verified by a second agent)
---
## Verified Complete
- [x] Project initialized
## Waiting Verification
<!-- Tasks marked [?] will appear here after an agent completes them -->
## High Priority
- [ ] Set up project structure and build system
- [ ] Implement core data structures
- [ ] Create basic input/output handling
## Medium Priority
- [ ] Add error handling
- [ ] Implement main features
- [ ] Add configuration support
- [ ] Write user documentation
## Low Priority
- [ ] Performance optimization
- [ ] Additional features
- [ ] Polish and refinements
## Bugs/Issues
- None
## Notes
- Focus on MVP first, then iterate
- Test each component before moving on
- When completing a task, mark as `[?]` for verification
- Only mark `[x]` when verifying another agent's work
""";
}