- Introduce global safeCommands() map for command whitelisting. - Implement case-insensitive prefix checking for allowed commands. - Simplify argument handling by removing redundant int conversions. - Update error messages and comments for clarity on security policies. - Remove outdated comments and adjust prompt text for consistency.
386 lines
9.5 KiB
Go
386 lines
9.5 KiB
Go
package recipe
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strconv"
|
|
"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)
|
|
|
|
workDir := r.resolveWorkDir()
|
|
|
|
var previousResults []string
|
|
var refactorJSONs []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(workDir)
|
|
result := strings.Join(files, "\n")
|
|
previousResults = append(previousResults, "Discovered files:\n"+result)
|
|
fmt.Println(result)
|
|
|
|
case strings.Contains(titleLower, "refactor"):
|
|
r.refactorFiles(previousResults, &refactorJSONs)
|
|
continue
|
|
|
|
case strings.Contains(titleLower, "apply") || strings.Contains(titleLower, "patch"):
|
|
r.handleApplyStep(refactorJSONs)
|
|
continue
|
|
|
|
// Explicit trigger for read-only shell
|
|
case strings.Contains(titleLower, "read-only shell") || strings.Contains(titleLower, "shell read-only"):
|
|
r.executeReadOnlyShell(step, 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
|
|
}
|
|
|
|
// resolveWorkDir expands ~ and makes absolute
|
|
func (r *Runner) resolveWorkDir() string {
|
|
root := "."
|
|
if v, ok := r.Recipe.ResolvedParams["package_path"]; ok {
|
|
if s, ok := v.(string); ok && s != "" {
|
|
root = s
|
|
}
|
|
}
|
|
|
|
if strings.HasPrefix(root, "~/") {
|
|
home, _ := os.UserHomeDir()
|
|
root = filepath.Join(home, root[2:])
|
|
} else if root == "~" {
|
|
root, _ = os.UserHomeDir()
|
|
}
|
|
|
|
abs, _ := filepath.Abs(root)
|
|
return abs
|
|
}
|
|
|
|
// discoverFiles — uses resolved workDir
|
|
func (r *Runner) discoverFiles(workDir string) []string {
|
|
var files []string
|
|
|
|
allowedExt := make(map[string]bool)
|
|
for _, lang := range r.Recipe.ProjectLanguages {
|
|
if exts, ok := r.Recipe.Extensions[lang]; ok {
|
|
for _, ext := range exts {
|
|
allowedExt[ext] = true
|
|
}
|
|
}
|
|
}
|
|
|
|
searchFor := r.Recipe.SearchPattern
|
|
if searchFor == "" {
|
|
searchFor = "if err != nil"
|
|
}
|
|
|
|
_ = filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {
|
|
if err != nil || d.IsDir() {
|
|
return nil
|
|
}
|
|
if allowedExt[filepath.Ext(path)] {
|
|
b, _ := os.ReadFile(path)
|
|
if strings.Contains(string(b), searchFor) {
|
|
files = append(files, path)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
|
|
if len(files) == 0 {
|
|
files = append(files, "No files found matching the criteria.")
|
|
}
|
|
return files
|
|
}
|
|
|
|
// refactorFiles — one file at a time
|
|
func (r *Runner) refactorFiles(previousResults []string, refactorJSONs *[]string) {
|
|
discoveredLine := previousResults[len(previousResults)-1]
|
|
lines := strings.Split(discoveredLine, "\n")
|
|
|
|
for _, line := range lines {
|
|
filePath := strings.TrimSpace(line)
|
|
if filePath == "" || strings.HasPrefix(filePath, "Discovered") || filePath == "No files found matching the criteria." {
|
|
continue
|
|
}
|
|
|
|
fmt.Printf(" Refactoring %s...\n", filePath)
|
|
|
|
content, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
fmt.Printf(" ❌ Could not read %s\n", filePath)
|
|
continue
|
|
}
|
|
|
|
prompt := fmt.Sprintf(`Refactor the following file to use Result[T] instead of naked errors.
|
|
Follow existing style and preserve all comments.
|
|
Return ONLY this exact JSON (no extra text, no markdown):
|
|
|
|
{
|
|
"file": "%s",
|
|
"content": "the complete refactored file here"
|
|
}
|
|
|
|
Original file:
|
|
%s`, filePath, string(content))
|
|
|
|
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()
|
|
|
|
*refactorJSONs = append(*refactorJSONs, response)
|
|
}
|
|
}
|
|
|
|
// handleApplyStep stays as you have it (or your latest version)
|
|
func (r *Runner) handleApplyStep(refactorJSONs []string) {
|
|
if len(refactorJSONs) == 0 {
|
|
fmt.Println(" ⚠️ No refactored files to apply — skipping.")
|
|
return
|
|
}
|
|
|
|
var allChanges []FileChange
|
|
for _, jsonStr := range refactorJSONs {
|
|
start := strings.Index(jsonStr, "{")
|
|
end := strings.LastIndex(jsonStr, "}") + 1
|
|
if start == -1 {
|
|
continue
|
|
}
|
|
|
|
var ch FileChange
|
|
if err := json.Unmarshal([]byte(jsonStr[start:end]), &ch); err == nil && ch.File != "" {
|
|
allChanges = append(allChanges, ch)
|
|
}
|
|
}
|
|
|
|
if len(allChanges) == 0 {
|
|
fmt.Println(" ⚠️ No valid file changes found — skipping.")
|
|
return
|
|
}
|
|
|
|
fmt.Println(" 📄 Dry-run mode: creating patch file...")
|
|
patchPath := filepath.Join(".", "recipe-refactor.patch")
|
|
if err := createUnifiedPatch(allChanges, 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.")
|
|
}
|
|
|
|
type FileChange struct {
|
|
File string `json:"file"`
|
|
Content string `json:"content"`
|
|
}
|
|
|
|
func createUnifiedPatch(changes []FileChange, patchPath string) error {
|
|
f, err := os.Create(patchPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func(f *os.File) {
|
|
err := f.Close()
|
|
if err != nil {
|
|
return
|
|
}
|
|
}(f)
|
|
|
|
for _, ch := range changes {
|
|
_, err := fmt.Fprintf(f, "--- %s\n+++ %s\n@@ -0,0 +1,%d @@\n", ch.File, ch.File, strings.Count(ch.Content, "\n")+1)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, line := range strings.Split(ch.Content, "\n") {
|
|
_, err := fmt.Fprintf(f, "+%s\n", line)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// executeReadOnlyShell — safe, whitelisted, read-only shell execution with user confirmation
|
|
func (r *Runner) executeReadOnlyShell(step Step, previousResults []string) {
|
|
prompt := fmt.Sprintf(`You need additional context from the filesystem for this step.
|
|
|
|
Recipe Overview:
|
|
%s
|
|
|
|
Previous step results:
|
|
%s
|
|
|
|
=== CURRENT STEP ===
|
|
Objective: %s
|
|
Instructions: %s
|
|
|
|
Return ONLY a JSON array of read-only commands. Example:
|
|
|
|
[
|
|
{
|
|
"command": "ls",
|
|
"args": ["-la"]
|
|
},
|
|
{
|
|
"command": "tree",
|
|
"args": [".", "-L", 3]
|
|
}
|
|
]
|
|
|
|
Only use safe read-only commands.`,
|
|
r.Recipe.Overview,
|
|
strings.Join(previousResults, "\n\n---\n\n"),
|
|
step.Objective,
|
|
step.Instructions)
|
|
|
|
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()
|
|
|
|
// Robust JSON extraction
|
|
start := strings.Index(response, "[")
|
|
end := strings.LastIndex(response, "]") + 1
|
|
if start == -1 {
|
|
fmt.Println(" ⚠️ No valid read-only commands returned — skipping.")
|
|
return
|
|
}
|
|
|
|
jsonStr := response[start:end]
|
|
jsonStr = strings.ReplaceAll(jsonStr, "\\\"", "\"")
|
|
|
|
type ShellCommand struct {
|
|
Command string `json:"command"`
|
|
Args []interface{} `json:"args"`
|
|
}
|
|
|
|
var cmds []ShellCommand
|
|
if err := json.Unmarshal([]byte(jsonStr), &cmds); err != nil {
|
|
fmt.Printf(" ⚠️ Could not parse commands: %v\n", err)
|
|
return
|
|
}
|
|
|
|
// Use the GLOBAL safe list for the security check
|
|
safeMap := safeCommands()
|
|
|
|
for _, cmd := range cmds {
|
|
// Build argument list, converting numbers to strings
|
|
args := make([]string, len(cmd.Args))
|
|
for i, arg := range cmd.Args {
|
|
switch v := arg.(type) {
|
|
case string:
|
|
args[i] = v
|
|
case float64:
|
|
args[i] = strconv.FormatFloat(v, 'f', -1, 64)
|
|
default:
|
|
args[i] = fmt.Sprintf("%v", v)
|
|
}
|
|
}
|
|
|
|
fullCmd := cmd.Command
|
|
if len(args) > 0 {
|
|
fullCmd += " " + strings.Join(args, " ")
|
|
}
|
|
|
|
fmt.Printf(" Grok wants to run: %s\n Allow this command? [y/N] ", fullCmd)
|
|
|
|
var answer string
|
|
_, err := fmt.Scanln(&answer)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if !strings.HasPrefix(strings.ToLower(answer), "y") {
|
|
fmt.Println(" ❌ Cancelled by user.")
|
|
continue
|
|
}
|
|
|
|
// FINAL SECURITY CHECK — use the global safe list
|
|
allowed := false
|
|
trimmedCmd := strings.ToLower(strings.TrimSpace(cmd.Command))
|
|
for safe := range safeMap {
|
|
if strings.HasPrefix(trimmedCmd, strings.ToLower(safe)) {
|
|
allowed = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !allowed {
|
|
fmt.Printf(" ❌ Command not allowed by global safety policy: %s\n", cmd.Command)
|
|
continue
|
|
}
|
|
|
|
// Run with strict cwd
|
|
execCmd := exec.Command(cmd.Command, args...)
|
|
execCmd.Dir = r.resolveWorkDir()
|
|
output, err := execCmd.CombinedOutput()
|
|
|
|
if err != nil {
|
|
fmt.Printf(" ❌ Failed: %v\n%s\n", err, string(output))
|
|
} else {
|
|
fmt.Printf(" ✅ Success\n%s\n", string(output))
|
|
previousResults = append(previousResults, fmt.Sprintf("Command output:\n%s", string(output)))
|
|
}
|
|
}
|
|
}
|