grokkit/internal/recipe/loader.go

102 lines
2.3 KiB
Go
Raw Normal View History

package recipe
import (
"bytes"
"fmt"
"os"
"regexp"
"strings"
"text/template"
"gopkg.in/yaml.v3"
)
var (
stepRe = regexp.MustCompile(`(?m)^### Step (\d+): (.+)$`)
subRe = regexp.MustCompile(`(?m)^(\*\*(?:Objective|Instructions|Expected output):\*\*)\s*(.+?)(?:\n\n|\n###|\z)`)
)
func Load(path string, userParams map[string]any) (*Recipe, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
parts := bytes.SplitN(b, []byte("---"), 3)
if len(parts) < 3 {
return nil, fmt.Errorf("missing YAML frontmatter")
}
var r Recipe
if err := yaml.Unmarshal(parts[1], &r); err != nil {
return nil, fmt.Errorf("yaml parse: %w", err)
}
// Apply defaults
if r.Parameters == nil {
r.Parameters = make(map[string]Parameter)
}
params := make(map[string]any)
for name, p := range r.Parameters {
if v, ok := userParams[name]; ok {
params[name] = v
} else if p.Default != nil {
params[name] = p.Default
}
}
// Render templates
tpl, err := template.New("recipe").Parse(string(parts[2]))
if err != nil {
return nil, err
}
var rendered bytes.Buffer
if err := tpl.Execute(&rendered, params); err != nil {
return nil, err
}
body := rendered.String()
// Extract Overview
if idx := strings.Index(body, "## Execution Steps"); idx != -1 {
r.Overview = strings.TrimSpace(body[:idx])
}
// Extract steps — split-based to guarantee no duplicates
matches := stepRe.FindAllStringSubmatch(body, -1)
for i, m := range matches {
stepNum := i + 1
title := m[2]
start := strings.Index(body, m[0])
end := len(body)
if i+1 < len(matches) {
nextStart := strings.Index(body[start:], matches[i+1][0])
end = start + nextStart
}
section := body[start:end]
step := Step{Number: stepNum, Title: title}
for _, sub := range subRe.FindAllStringSubmatch(section, -1) {
switch sub[1] {
case "**Objective:**":
step.Objective = strings.TrimSpace(sub[2])
case "**Instructions:**":
step.Instructions = strings.TrimSpace(sub[2])
case "**Expected output:**":
step.Expected = strings.TrimSpace(sub[2])
}
}
r.Steps = append(r.Steps, step)
}
// Final summary = everything after the last step
if len(matches) > 0 {
lastMatch := matches[len(matches)-1][0]
lastIdx := strings.LastIndex(body, lastMatch)
r.FinalSummaryPrompt = strings.TrimSpace(body[lastIdx+len(lastMatch):])
}
return &r, nil
}