grokkit/internal/recipe/runner.go
Greg Gauthier 7cb9eb3eb7 refactor(recipe): switch refactor step to strict JSON output
- Update result-refactor.md to output JSON array of file changes instead of code blocks
- Modify runner.go to parse JSON directly, removing regex-based extraction
- Add project_languages and extensions to recipe metadata
- Improve error handling and output consistency in steps
2026-03-06 22:40:29 +00:00

162 lines
4.1 KiB
Go

package recipe
import (
_ "bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"gmgauthier.com/grokkit/internal/grok"
)
type Runner struct {
Recipe *Recipe
Client *grok.Client
Model string
}
func NewRunner(r *Recipe, client *grok.Client, model string) *Runner {
return &Runner{Recipe: r, Client: client, Model: model}
}
func (r *Runner) Run() error {
fmt.Printf("🍳 Starting recipe: %s v%s\n\n", r.Recipe.Name, r.Recipe.Version)
var previousResults []string
for _, step := range r.Recipe.Steps {
fmt.Printf("Step %d/%d: %s\n", step.Number, len(r.Recipe.Steps), step.Title)
titleLower := strings.ToLower(step.Title)
switch {
case strings.Contains(titleLower, "discover") || strings.Contains(titleLower, "find"):
files := r.discoverFiles()
result := strings.Join(files, "\n")
previousResults = append(previousResults, "Discovered files:\n"+result)
fmt.Println(result)
case strings.Contains(titleLower, "apply") || strings.Contains(titleLower, "patch"):
r.handleApplyStep(previousResults)
continue
default:
prompt := fmt.Sprintf(`Recipe Overview:
%s
Previous step results (for context):
%s
=== CURRENT STEP ===
Objective: %s
Instructions: %s
Expected output format: %s
Execute this step now. Respond ONLY with the expected output format — no explanations, no extra text.`,
r.Recipe.Overview,
strings.Join(previousResults, "\n\n---\n\n"),
step.Objective,
step.Instructions,
step.Expected)
messages := []map[string]string{
{"role": "system", "content": "You are Grok, built by xAI. Precise expert programmer and refactoring assistant."},
{"role": "user", "content": prompt},
}
response := r.Client.Stream(messages, r.Model)
fmt.Println()
previousResults = append(previousResults, fmt.Sprintf("Step %d result:\n%s", step.Number, response))
}
}
fmt.Println("\n✅ Recipe complete.")
return nil
}
// discoverFiles does a real filesystem scan
func (r *Runner) discoverFiles() []string {
var files []string
root := "internal"
_ = filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
return nil
}
b, _ := os.ReadFile(path)
if strings.Contains(string(b), "if err != nil") {
files = append(files, path)
}
return nil
})
if len(files) == 0 {
files = append(files, "No files found matching the criteria.")
}
return files
}
// handleApplyStep parses strict JSON from the refactor step — no regex at all
func (r *Runner) handleApplyStep(previousResults []string) {
if len(previousResults) == 0 {
fmt.Println(" ⚠️ No previous results to apply — skipping.")
return
}
lastResult := previousResults[len(previousResults)-1]
// Find the JSON array in the response
start := strings.Index(lastResult, "[")
end := strings.LastIndex(lastResult, "]") + 1
if start == -1 || end == 0 {
fmt.Println(" ⚠️ No JSON found in previous step — skipping.")
return
}
jsonStr := lastResult[start:end]
type FileChange struct {
File string `json:"file"`
Content string `json:"content"`
}
var changes []FileChange
if err := json.Unmarshal([]byte(jsonStr), &changes); err != nil {
fmt.Printf(" ⚠️ Could not parse JSON: %v\n", err)
return
}
if len(changes) == 0 {
fmt.Println(" ⚠️ No files to apply — skipping.")
return
}
fmt.Println(" 📄 Dry-run mode: creating patch file...")
patchPath := filepath.Join(".", "recipe-refactor.patch")
if err := createUnifiedPatch(changes, patchPath); err != nil {
fmt.Printf(" ❌ Failed to create patch: %v\n", err)
return
}
fmt.Printf(" ✅ Patch created: %s\n", patchPath)
fmt.Println(" Review it, then run with dry_run=false to apply.")
}
func createUnifiedPatch(changes []struct{ File, Content string }, patchPath string) error {
f, err := os.Create(patchPath)
if err != nil {
return err
}
defer f.Close()
for _, ch := range changes {
fmt.Fprintf(f, "--- %s\n+++ %s\n@@ -0,0 +1,%d @@\n", ch.File, ch.File, strings.Count(ch.Content, "\n")+1)
for _, line := range strings.Split(ch.Content, "\n") {
fmt.Fprintf(f, "+%s\n", line)
}
}
return nil
}