feat: Add Beads template instantiation system (bd-r6a.2)

Implements native Beads templates as an alternative to YAML templates:

- Templates are epics with the "template" label and {{variable}} placeholders
- `bd template list` shows both YAML and Beads templates
- `bd template show <id>` displays template structure and variables
- `bd template instantiate <id> --var key=value` clones subgraph with substitution

Key implementation:
- loadTemplateSubgraph: Recursively loads epic and all descendants
- cloneSubgraph: Creates new issues with ID remapping in a transaction
- extractVariables/substituteVariables: {{name}} pattern handling

Closes bd-r6a.2, bd-r6a.4

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Steve Yegge
2025-12-17 23:03:16 -08:00
parent 71ff52deda
commit 6920cd5224
2 changed files with 1024 additions and 79 deletions

View File

@@ -1,21 +1,29 @@
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/rpc"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
"gopkg.in/yaml.v3"
)
//go:embed templates/*.yaml
var builtinTemplates embed.FS
// Template represents an issue template
// Template represents a simple YAML issue template (for --from-template)
type Template struct {
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
@@ -26,118 +34,284 @@ type Template struct {
AcceptanceCriteria string `yaml:"acceptance_criteria" json:"acceptance_criteria"`
}
// BeadsTemplateLabel is the label used to identify Beads-based templates
const BeadsTemplateLabel = "template"
// variablePattern matches {{variable}} placeholders
var variablePattern = regexp.MustCompile(`\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}`)
// TemplateSubgraph holds a template epic and all its descendants
type TemplateSubgraph struct {
Root *types.Issue // The template epic
Issues []*types.Issue // All issues in the subgraph (including root)
Dependencies []*types.Dependency // All dependencies within the subgraph
IssueMap map[string]*types.Issue // ID -> Issue for quick lookup
}
// InstantiateResult holds the result of template instantiation
type InstantiateResult struct {
NewEpicID string `json:"new_epic_id"`
IDMapping map[string]string `json:"id_mapping"` // old ID -> new ID
Created int `json:"created"` // number of issues created
}
var templateCmd = &cobra.Command{
Use: "template",
Short: "Manage issue templates",
Long: `Manage issue templates for streamlined issue creation.
Templates can be built-in (epic, bug, feature) or custom templates
stored in .beads/templates/ directory.`,
There are two types of templates:
1. YAML Templates (for single issues):
- Built-in: epic, bug, feature
- Custom: stored in .beads/templates/
- Used with: bd create --from-template=<name>
2. Beads Templates (for issue hierarchies):
- Any epic with the "template" label
- Can have child issues with {{variable}} placeholders
- Used with: bd template instantiate <id> --var key=value`,
}
var templateListCmd = &cobra.Command{
Use: "list",
Short: "List available templates",
Run: func(cmd *cobra.Command, args []string) {
templates, err := loadAllTemplates()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading templates: %v\n", err)
os.Exit(1)
yamlOnly, _ := cmd.Flags().GetBool("yaml-only")
beadsOnly, _ := cmd.Flags().GetBool("beads-only")
type combinedOutput struct {
YAMLTemplates []Template `json:"yaml_templates,omitempty"`
BeadsTemplates []*types.Issue `json:"beads_templates,omitempty"`
}
output := combinedOutput{}
// Load YAML templates
if !beadsOnly {
templates, err := loadAllTemplates()
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: error loading YAML templates: %v\n", err)
} else {
output.YAMLTemplates = templates
}
}
// Load Beads templates
if !yamlOnly {
ctx := rootCtx
var beadsTemplates []*types.Issue
var err error
if daemonClient != nil {
resp, err := daemonClient.List(&rpc.ListArgs{})
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: error loading Beads templates: %v\n", err)
} else {
var allIssues []*types.Issue
if err := json.Unmarshal(resp.Data, &allIssues); err == nil {
for _, issue := range allIssues {
for _, label := range issue.Labels {
if label == BeadsTemplateLabel {
beadsTemplates = append(beadsTemplates, issue)
break
}
}
}
}
}
} else if store != nil {
beadsTemplates, err = store.GetIssuesByLabel(ctx, BeadsTemplateLabel)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: error loading Beads templates: %v\n", err)
}
}
output.BeadsTemplates = beadsTemplates
}
if jsonOutput {
outputJSON(templates)
outputJSON(output)
return
}
// Group by source
builtins := []Template{}
customs := []Template{}
for _, tmpl := range templates {
if isBuiltinTemplate(tmpl.Name) {
builtins = append(builtins, tmpl)
} else {
customs = append(customs, tmpl)
}
}
// Human-readable output
green := color.New(color.FgGreen).SprintFunc()
blue := color.New(color.FgBlue).SprintFunc()
cyan := color.New(color.FgCyan).SprintFunc()
if len(builtins) > 0 {
fmt.Printf("%s\n", green("Built-in Templates:"))
for _, tmpl := range builtins {
fmt.Printf(" %s\n", blue(tmpl.Name))
fmt.Printf(" Type: %s, Priority: P%d\n", tmpl.Type, tmpl.Priority)
if len(tmpl.Labels) > 0 {
fmt.Printf(" Labels: %s\n", strings.Join(tmpl.Labels, ", "))
// Show YAML templates
if !beadsOnly && len(output.YAMLTemplates) > 0 {
// Group by source
builtins := []Template{}
customs := []Template{}
for _, tmpl := range output.YAMLTemplates {
if isBuiltinTemplate(tmpl.Name) {
builtins = append(builtins, tmpl)
} else {
customs = append(customs, tmpl)
}
}
if len(builtins) > 0 {
fmt.Printf("%s\n", green("Built-in Templates (for --from-template):"))
for _, tmpl := range builtins {
fmt.Printf(" %s\n", blue(tmpl.Name))
fmt.Printf(" Type: %s, Priority: P%d\n", tmpl.Type, tmpl.Priority)
}
fmt.Println()
}
if len(customs) > 0 {
fmt.Printf("%s\n", green("Custom Templates (for --from-template):"))
for _, tmpl := range customs {
fmt.Printf(" %s\n", blue(tmpl.Name))
fmt.Printf(" Type: %s, Priority: P%d\n", tmpl.Type, tmpl.Priority)
}
fmt.Println()
}
}
// Show Beads templates
if !yamlOnly && len(output.BeadsTemplates) > 0 {
fmt.Printf("%s\n", green("Beads Templates (for bd template instantiate):"))
for _, tmpl := range output.BeadsTemplates {
vars := extractVariables(tmpl.Title + " " + tmpl.Description)
varStr := ""
if len(vars) > 0 {
varStr = fmt.Sprintf(" (vars: %s)", strings.Join(vars, ", "))
}
fmt.Printf(" %s: %s%s\n", cyan(tmpl.ID), tmpl.Title, varStr)
}
fmt.Println()
}
if len(customs) > 0 {
fmt.Printf("%s\n", green("Custom Templates:"))
for _, tmpl := range customs {
fmt.Printf(" %s\n", blue(tmpl.Name))
fmt.Printf(" Type: %s, Priority: P%d\n", tmpl.Type, tmpl.Priority)
if len(tmpl.Labels) > 0 {
fmt.Printf(" Labels: %s\n", strings.Join(tmpl.Labels, ", "))
}
}
fmt.Println()
}
if len(templates) == 0 {
fmt.Println("No templates available")
if len(output.YAMLTemplates) == 0 && len(output.BeadsTemplates) == 0 {
fmt.Println("No templates available.")
fmt.Println("\nTo create a Beads template:")
fmt.Println(" 1. Create an epic with child issues")
fmt.Println(" 2. Add the 'template' label: bd label add <epic-id> template")
fmt.Println(" 3. Use {{variable}} placeholders in titles/descriptions")
}
},
}
var templateShowCmd = &cobra.Command{
Use: "show <template-name>",
Use: "show <template-name-or-id>",
Short: "Show template details",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
templateName := args[0]
tmpl, err := loadTemplate(templateName)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
arg := args[0]
if jsonOutput {
outputJSON(tmpl)
// Try loading as YAML template first
yamlTmpl, yamlErr := loadTemplate(arg)
if yamlErr == nil {
showYAMLTemplate(yamlTmpl)
return
}
green := color.New(color.FgGreen).SprintFunc()
blue := color.New(color.FgBlue).SprintFunc()
// Try loading as Beads template
ctx := rootCtx
var templateID string
fmt.Printf("%s %s\n", green("Template:"), blue(tmpl.Name))
fmt.Printf("Type: %s\n", tmpl.Type)
fmt.Printf("Priority: P%d\n", tmpl.Priority)
if len(tmpl.Labels) > 0 {
fmt.Printf("Labels: %s\n", strings.Join(tmpl.Labels, ", "))
if daemonClient != nil {
resolveArgs := &rpc.ResolveIDArgs{ID: arg}
resp, err := daemonClient.ResolveID(resolveArgs)
if err != nil {
// Neither YAML nor Beads template found
fmt.Fprintf(os.Stderr, "Error: template '%s' not found\n", arg)
os.Exit(1)
}
if err := json.Unmarshal(resp.Data, &templateID); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
} else if store != nil {
var err error
templateID, err = utils.ResolvePartialID(ctx, store, arg)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: template '%s' not found\n", arg)
os.Exit(1)
}
} else {
fmt.Fprintf(os.Stderr, "Error: no database connection\n")
os.Exit(1)
}
fmt.Printf("\n%s\n%s\n", green("Description:"), tmpl.Description)
if tmpl.Design != "" {
fmt.Printf("\n%s\n%s\n", green("Design:"), tmpl.Design)
}
if tmpl.AcceptanceCriteria != "" {
fmt.Printf("\n%s\n%s\n", green("Acceptance Criteria:"), tmpl.AcceptanceCriteria)
// Load and show Beads template
subgraph, err := loadTemplateSubgraph(ctx, store, templateID)
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading template: %v\n", err)
os.Exit(1)
}
showBeadsTemplate(subgraph)
},
}
func showYAMLTemplate(tmpl *Template) {
if jsonOutput {
outputJSON(tmpl)
return
}
green := color.New(color.FgGreen).SprintFunc()
blue := color.New(color.FgBlue).SprintFunc()
fmt.Printf("%s %s (YAML template)\n", green("Template:"), blue(tmpl.Name))
fmt.Printf("Type: %s\n", tmpl.Type)
fmt.Printf("Priority: P%d\n", tmpl.Priority)
if len(tmpl.Labels) > 0 {
fmt.Printf("Labels: %s\n", strings.Join(tmpl.Labels, ", "))
}
fmt.Printf("\n%s\n%s\n", green("Description:"), tmpl.Description)
if tmpl.Design != "" {
fmt.Printf("\n%s\n%s\n", green("Design:"), tmpl.Design)
}
if tmpl.AcceptanceCriteria != "" {
fmt.Printf("\n%s\n%s\n", green("Acceptance Criteria:"), tmpl.AcceptanceCriteria)
}
}
func showBeadsTemplate(subgraph *TemplateSubgraph) {
if jsonOutput {
outputJSON(map[string]interface{}{
"root": subgraph.Root,
"issues": subgraph.Issues,
"dependencies": subgraph.Dependencies,
"variables": extractAllVariables(subgraph),
})
return
}
cyan := color.New(color.FgCyan).SprintFunc()
yellow := color.New(color.FgYellow).SprintFunc()
green := color.New(color.FgGreen).SprintFunc()
fmt.Printf("\n%s Template: %s (Beads template)\n", cyan("📋"), subgraph.Root.Title)
fmt.Printf(" ID: %s\n", subgraph.Root.ID)
fmt.Printf(" Issues: %d\n", len(subgraph.Issues))
// Show variables
vars := extractAllVariables(subgraph)
if len(vars) > 0 {
fmt.Printf("\n%s Variables:\n", yellow("📝"))
for _, v := range vars {
fmt.Printf(" {{%s}}\n", v)
}
}
// Show structure
fmt.Printf("\n%s Structure:\n", green("🌲"))
printTemplateTree(subgraph, subgraph.Root.ID, 0, true)
fmt.Println()
}
var templateCreateCmd = &cobra.Command{
Use: "create <template-name>",
Short: "Create a custom template",
Long: `Create a custom template in .beads/templates/ directory.
Short: "Create a custom YAML template",
Long: `Create a custom YAML template in .beads/templates/ directory.
This will create a template file that you can edit to customize
the default values for your common issue types.`,
This creates a simple template for pre-filling issue fields.
For workflow templates with hierarchies, create an epic and add the 'template' label.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
templateName := args[0]
@@ -164,12 +338,12 @@ the default values for your common issue types.`,
// Default template structure
tmpl := Template{
Name: templateName,
Description: "[Describe the issue]\n\n## Additional Context\n\n[Add relevant details]",
Type: "task",
Priority: 2,
Labels: []string{},
Design: "[Design notes]",
Name: templateName,
Description: "[Describe the issue]\n\n## Additional Context\n\n[Add relevant details]",
Type: "task",
Priority: 2,
Labels: []string{},
Design: "[Design notes]",
AcceptanceCriteria: "- [ ] Acceptance criterion 1\n- [ ] Acceptance criterion 2",
}
@@ -192,14 +366,137 @@ the default values for your common issue types.`,
},
}
var templateInstantiateCmd = &cobra.Command{
Use: "instantiate <template-id>",
Short: "Create issues from a Beads template",
Long: `Instantiate a Beads template by cloning its subgraph and substituting variables.
Variables are specified with --var key=value flags. The template's {{key}}
placeholders will be replaced with the corresponding values.
Example:
bd template instantiate bd-abc123 --var version=1.2.0 --var date=2024-01-15`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
CheckReadonly("template instantiate")
ctx := rootCtx
dryRun, _ := cmd.Flags().GetBool("dry-run")
varFlags, _ := cmd.Flags().GetStringSlice("var")
// Parse variables
vars := make(map[string]string)
for _, v := range varFlags {
parts := strings.SplitN(v, "=", 2)
if len(parts) != 2 {
fmt.Fprintf(os.Stderr, "Error: invalid variable format '%s', expected 'key=value'\n", v)
os.Exit(1)
}
vars[parts[0]] = parts[1]
}
// Resolve template ID
var templateID string
if daemonClient != nil {
resolveArgs := &rpc.ResolveIDArgs{ID: args[0]}
resp, err := daemonClient.ResolveID(resolveArgs)
if err != nil {
fmt.Fprintf(os.Stderr, "Error resolving template ID %s: %v\n", args[0], err)
os.Exit(1)
}
if err := json.Unmarshal(resp.Data, &templateID); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
} else if store != nil {
var err error
templateID, err = utils.ResolvePartialID(ctx, store, args[0])
if err != nil {
fmt.Fprintf(os.Stderr, "Error resolving template ID %s: %v\n", args[0], err)
os.Exit(1)
}
} else {
fmt.Fprintf(os.Stderr, "Error: no database connection\n")
os.Exit(1)
}
// Load the template subgraph
subgraph, err := loadTemplateSubgraph(ctx, store, templateID)
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading template: %v\n", err)
os.Exit(1)
}
// Check for missing variables
requiredVars := extractAllVariables(subgraph)
var missingVars []string
for _, v := range requiredVars {
if _, ok := vars[v]; !ok {
missingVars = append(missingVars, v)
}
}
if len(missingVars) > 0 {
fmt.Fprintf(os.Stderr, "Error: missing required variables: %s\n", strings.Join(missingVars, ", "))
fmt.Fprintf(os.Stderr, "Provide them with: --var %s=<value>\n", missingVars[0])
os.Exit(1)
}
if dryRun {
// Preview what would be created
fmt.Printf("\nDry run: would create %d issues from template %s\n\n", len(subgraph.Issues), templateID)
for _, issue := range subgraph.Issues {
newTitle := substituteVariables(issue.Title, vars)
fmt.Printf(" - %s (from %s)\n", newTitle, issue.ID)
}
if len(vars) > 0 {
fmt.Printf("\nVariables:\n")
for k, v := range vars {
fmt.Printf(" {{%s}} = %s\n", k, v)
}
}
return
}
// Clone the subgraph
result, err := cloneSubgraph(ctx, store, subgraph, vars, actor)
if err != nil {
fmt.Fprintf(os.Stderr, "Error instantiating template: %v\n", err)
os.Exit(1)
}
// Schedule auto-flush
markDirtyAndScheduleFlush()
if jsonOutput {
outputJSON(result)
return
}
green := color.New(color.FgGreen).SprintFunc()
fmt.Printf("%s Created %d issues from template\n", green("✓"), result.Created)
fmt.Printf(" New epic: %s\n", result.NewEpicID)
},
}
func init() {
templateListCmd.Flags().Bool("yaml-only", false, "Show only YAML templates")
templateListCmd.Flags().Bool("beads-only", false, "Show only Beads templates")
templateInstantiateCmd.Flags().StringSlice("var", []string{}, "Variable substitution (key=value)")
templateInstantiateCmd.Flags().Bool("dry-run", false, "Preview what would be created")
templateCmd.AddCommand(templateListCmd)
templateCmd.AddCommand(templateShowCmd)
templateCmd.AddCommand(templateCreateCmd)
templateCmd.AddCommand(templateInstantiateCmd)
rootCmd.AddCommand(templateCmd)
}
// loadAllTemplates loads both built-in and custom templates
// =============================================================================
// YAML Template Functions (for --from-template)
// =============================================================================
// loadAllTemplates loads both built-in and custom YAML templates
func loadAllTemplates() ([]Template, error) {
templates := []Template{}
@@ -208,7 +505,6 @@ func loadAllTemplates() ([]Template, error) {
for _, name := range builtins {
tmpl, err := loadBuiltinTemplate(name)
if err != nil {
// Skip if not found (shouldn't happen with built-ins)
continue
}
templates = append(templates, *tmpl)
@@ -230,7 +526,6 @@ func loadAllTemplates() ([]Template, error) {
name := strings.TrimSuffix(entry.Name(), ".yaml")
tmpl, err := loadCustomTemplate(name)
if err != nil {
// Skip invalid templates
continue
}
templates = append(templates, *tmpl)
@@ -251,7 +546,7 @@ func sanitizeTemplateName(name string) error {
return nil
}
// loadTemplate loads a template by name (checks custom first, then built-in)
// loadTemplate loads a YAML template by name (checks custom first, then built-in)
func loadTemplate(name string) (*Template, error) {
if err := sanitizeTemplateName(name); err != nil {
return nil, err
@@ -267,7 +562,7 @@ func loadTemplate(name string) (*Template, error) {
return loadBuiltinTemplate(name)
}
// loadBuiltinTemplate loads a built-in template
// loadBuiltinTemplate loads a built-in YAML template
func loadBuiltinTemplate(name string) (*Template, error) {
path := fmt.Sprintf("templates/%s.yaml", name)
data, err := builtinTemplates.ReadFile(path)
@@ -283,7 +578,7 @@ func loadBuiltinTemplate(name string) (*Template, error) {
return &tmpl, nil
}
// loadCustomTemplate loads a custom template from .beads/templates/
// loadCustomTemplate loads a custom YAML template from .beads/templates/
func loadCustomTemplate(name string) (*Template, error) {
path := filepath.Join(".beads", "templates", name+".yaml")
// #nosec G304 - path is sanitized via sanitizeTemplateName before calling this function
@@ -309,3 +604,234 @@ func isBuiltinTemplate(name string) bool {
}
return builtins[name]
}
// =============================================================================
// Beads Template Functions (for bd template instantiate)
// =============================================================================
// loadTemplateSubgraph loads a template epic and all its descendants
func loadTemplateSubgraph(ctx context.Context, s storage.Storage, templateID string) (*TemplateSubgraph, error) {
if s == nil {
return nil, fmt.Errorf("no database connection")
}
// Get the root issue
root, err := s.GetIssue(ctx, templateID)
if err != nil {
return nil, fmt.Errorf("failed to get template: %w", err)
}
if root == nil {
return nil, fmt.Errorf("template %s not found", templateID)
}
subgraph := &TemplateSubgraph{
Root: root,
Issues: []*types.Issue{root},
IssueMap: map[string]*types.Issue{root.ID: root},
}
// Recursively load all children
if err := loadDescendants(ctx, s, subgraph, root.ID); err != nil {
return nil, err
}
// Load all dependencies within the subgraph
for _, issue := range subgraph.Issues {
deps, err := s.GetDependencyRecords(ctx, issue.ID)
if err != nil {
return nil, fmt.Errorf("failed to get dependencies for %s: %w", issue.ID, err)
}
for _, dep := range deps {
// Only include dependencies where both ends are in the subgraph
if _, ok := subgraph.IssueMap[dep.DependsOnID]; ok {
subgraph.Dependencies = append(subgraph.Dependencies, dep)
}
}
}
return subgraph, nil
}
// loadDescendants recursively loads all child issues
func loadDescendants(ctx context.Context, s storage.Storage, subgraph *TemplateSubgraph, parentID string) error {
// GetDependents returns issues that depend on parentID
dependents, err := s.GetDependents(ctx, parentID)
if err != nil {
return fmt.Errorf("failed to get dependents of %s: %w", parentID, err)
}
// Check each dependent to see if it's a child (has parent-child relationship)
for _, dependent := range dependents {
if _, exists := subgraph.IssueMap[dependent.ID]; exists {
continue // Already in subgraph
}
// Check if this dependent has a parent-child relationship with parentID
depRecs, err := s.GetDependencyRecords(ctx, dependent.ID)
if err != nil {
continue
}
isChild := false
for _, depRec := range depRecs {
if depRec.DependsOnID == parentID && depRec.Type == types.DepParentChild {
isChild = true
break
}
}
if !isChild {
continue
}
// Add to subgraph
subgraph.Issues = append(subgraph.Issues, dependent)
subgraph.IssueMap[dependent.ID] = dependent
// Recurse to get children of this child
if err := loadDescendants(ctx, s, subgraph, dependent.ID); err != nil {
return err
}
}
return nil
}
// extractVariables finds all {{variable}} patterns in text
func extractVariables(text string) []string {
matches := variablePattern.FindAllStringSubmatch(text, -1)
seen := make(map[string]bool)
var vars []string
for _, match := range matches {
if len(match) >= 2 && !seen[match[1]] {
vars = append(vars, match[1])
seen[match[1]] = true
}
}
return vars
}
// extractAllVariables finds all variables across the entire subgraph
func extractAllVariables(subgraph *TemplateSubgraph) []string {
allText := ""
for _, issue := range subgraph.Issues {
allText += issue.Title + " " + issue.Description + " "
allText += issue.Design + " " + issue.AcceptanceCriteria + " " + issue.Notes + " "
}
return extractVariables(allText)
}
// substituteVariables replaces {{variable}} with values
func substituteVariables(text string, vars map[string]string) string {
return variablePattern.ReplaceAllStringFunc(text, func(match string) string {
// Extract variable name from {{name}}
name := match[2 : len(match)-2]
if val, ok := vars[name]; ok {
return val
}
return match // Leave unchanged if not found
})
}
// cloneSubgraph creates new issues from the template with variable substitution
func cloneSubgraph(ctx context.Context, s storage.Storage, subgraph *TemplateSubgraph, vars map[string]string, actorName string) (*InstantiateResult, error) {
if s == nil {
return nil, fmt.Errorf("no database connection")
}
// Generate new IDs and create mapping
idMapping := make(map[string]string)
// Use transaction for atomicity
err := s.RunInTransaction(ctx, func(tx storage.Transaction) error {
// First pass: create all issues with new IDs
for _, oldIssue := range subgraph.Issues {
newIssue := &types.Issue{
// Don't set ID - let the system generate it
Title: substituteVariables(oldIssue.Title, vars),
Description: substituteVariables(oldIssue.Description, vars),
Design: substituteVariables(oldIssue.Design, vars),
AcceptanceCriteria: substituteVariables(oldIssue.AcceptanceCriteria, vars),
Notes: substituteVariables(oldIssue.Notes, vars),
Status: types.StatusOpen, // Always start fresh
Priority: oldIssue.Priority,
IssueType: oldIssue.IssueType,
Assignee: oldIssue.Assignee,
EstimatedMinutes: oldIssue.EstimatedMinutes,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if err := tx.CreateIssue(ctx, newIssue, actorName); err != nil {
return fmt.Errorf("failed to create issue from %s: %w", oldIssue.ID, err)
}
idMapping[oldIssue.ID] = newIssue.ID
}
// Second pass: recreate dependencies with new IDs
for _, dep := range subgraph.Dependencies {
newFromID, ok1 := idMapping[dep.IssueID]
newToID, ok2 := idMapping[dep.DependsOnID]
if !ok1 || !ok2 {
continue // Skip if either end is outside the subgraph
}
newDep := &types.Dependency{
IssueID: newFromID,
DependsOnID: newToID,
Type: dep.Type,
}
if err := tx.AddDependency(ctx, newDep, actorName); err != nil {
return fmt.Errorf("failed to create dependency: %w", err)
}
}
return nil
})
if err != nil {
return nil, err
}
return &InstantiateResult{
NewEpicID: idMapping[subgraph.Root.ID],
IDMapping: idMapping,
Created: len(subgraph.Issues),
}, nil
}
// printTemplateTree prints the template structure as a tree
func printTemplateTree(subgraph *TemplateSubgraph, parentID string, depth int, isRoot bool) {
indent := strings.Repeat(" ", depth)
// Print root
if isRoot {
fmt.Printf("%s %s (root)\n", indent, subgraph.Root.Title)
}
// Find children of this parent
var children []*types.Issue
for _, dep := range subgraph.Dependencies {
if dep.DependsOnID == parentID && dep.Type == types.DepParentChild {
if child, ok := subgraph.IssueMap[dep.IssueID]; ok {
children = append(children, child)
}
}
}
// Print children
for i, child := range children {
connector := "├──"
if i == len(children)-1 {
connector = "└──"
}
vars := extractVariables(child.Title)
varStr := ""
if len(vars) > 0 {
varStr = fmt.Sprintf(" [%s]", strings.Join(vars, ", "))
}
fmt.Printf("%s %s %s%s\n", indent, connector, child.Title, varStr)
printTemplateTree(subgraph, child.ID, depth+1, false)
}
}

View File

@@ -1,9 +1,13 @@
package main
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/storage/sqlite"
"github.com/steveyegge/beads/internal/types"
)
func TestLoadBuiltinTemplate(t *testing.T) {
@@ -187,3 +191,418 @@ func TestIsBuiltinTemplate(t *testing.T) {
})
}
}
// =============================================================================
// Beads Template Tests (for bd template instantiate)
// =============================================================================
// TestExtractVariables tests the {{variable}} pattern extraction
func TestExtractVariables(t *testing.T) {
tests := []struct {
name string
input string
expected []string
}{
{
name: "single variable",
input: "Release {{version}}",
expected: []string{"version"},
},
{
name: "multiple variables",
input: "Release {{version}} on {{date}}",
expected: []string{"version", "date"},
},
{
name: "no variables",
input: "Just plain text",
expected: nil,
},
{
name: "duplicate variables",
input: "{{version}} and {{version}} again",
expected: []string{"version"},
},
{
name: "variable with underscore",
input: "{{my_variable}}",
expected: []string{"my_variable"},
},
{
name: "variable with numbers",
input: "{{var123}}",
expected: []string{"var123"},
},
{
name: "invalid variable format",
input: "{{123invalid}}",
expected: nil,
},
{
name: "empty braces",
input: "{{}}",
expected: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := extractVariables(tt.input)
if len(result) != len(tt.expected) {
t.Errorf("extractVariables(%q) = %v, want %v", tt.input, result, tt.expected)
return
}
for i, v := range result {
if v != tt.expected[i] {
t.Errorf("extractVariables(%q)[%d] = %q, want %q", tt.input, i, v, tt.expected[i])
}
}
})
}
}
// TestSubstituteVariables tests the variable substitution
func TestSubstituteVariables(t *testing.T) {
tests := []struct {
name string
input string
vars map[string]string
expected string
}{
{
name: "single variable",
input: "Release {{version}}",
vars: map[string]string{"version": "1.2.0"},
expected: "Release 1.2.0",
},
{
name: "multiple variables",
input: "Release {{version}} on {{date}}",
vars: map[string]string{"version": "1.2.0", "date": "2024-01-15"},
expected: "Release 1.2.0 on 2024-01-15",
},
{
name: "missing variable unchanged",
input: "Release {{version}}",
vars: map[string]string{},
expected: "Release {{version}}",
},
{
name: "partial substitution",
input: "{{found}} and {{missing}}",
vars: map[string]string{"found": "yes"},
expected: "yes and {{missing}}",
},
{
name: "no variables",
input: "Just plain text",
vars: map[string]string{"version": "1.0"},
expected: "Just plain text",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := substituteVariables(tt.input, tt.vars)
if result != tt.expected {
t.Errorf("substituteVariables(%q, %v) = %q, want %q", tt.input, tt.vars, result, tt.expected)
}
})
}
}
// templateTestHelper provides helpers for Beads template tests
type templateTestHelper struct {
s *sqlite.SQLiteStorage
ctx context.Context
t *testing.T
}
func (h *templateTestHelper) createIssue(title, description string, issueType types.IssueType, priority int) *types.Issue {
issue := &types.Issue{
Title: title,
Description: description,
Priority: priority,
IssueType: issueType,
Status: types.StatusOpen,
}
if err := h.s.CreateIssue(h.ctx, issue, "test-user"); err != nil {
h.t.Fatalf("Failed to create issue: %v", err)
}
return issue
}
func (h *templateTestHelper) addParentChild(childID, parentID string) {
dep := &types.Dependency{
IssueID: childID,
DependsOnID: parentID,
Type: types.DepParentChild,
}
if err := h.s.AddDependency(h.ctx, dep, "test-user"); err != nil {
h.t.Fatalf("Failed to add parent-child dependency: %v", err)
}
}
func (h *templateTestHelper) addLabel(issueID, label string) {
if err := h.s.AddLabel(h.ctx, issueID, label, "test-user"); err != nil {
h.t.Fatalf("Failed to add label: %v", err)
}
}
// TestLoadTemplateSubgraph tests loading a template epic with children
func TestLoadTemplateSubgraph(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "bd-test-template-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
testDB := filepath.Join(tmpDir, "test.db")
s := newTestStore(t, testDB)
defer s.Close()
ctx := context.Background()
h := &templateTestHelper{s: s, ctx: ctx, t: t}
t.Run("load epic with no children", func(t *testing.T) {
epic := h.createIssue("Template Epic", "Description", types.TypeEpic, 1)
h.addLabel(epic.ID, BeadsTemplateLabel)
subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID)
if err != nil {
t.Fatalf("loadTemplateSubgraph failed: %v", err)
}
if subgraph.Root.ID != epic.ID {
t.Errorf("Root ID = %s, want %s", subgraph.Root.ID, epic.ID)
}
if len(subgraph.Issues) != 1 {
t.Errorf("Issues count = %d, want 1", len(subgraph.Issues))
}
})
t.Run("load epic with children", func(t *testing.T) {
epic := h.createIssue("Template {{name}}", "Epic for {{name}}", types.TypeEpic, 1)
h.addLabel(epic.ID, BeadsTemplateLabel)
child1 := h.createIssue("Task 1 for {{name}}", "", types.TypeTask, 2)
child2 := h.createIssue("Task 2 for {{name}}", "", types.TypeTask, 2)
h.addParentChild(child1.ID, epic.ID)
h.addParentChild(child2.ID, epic.ID)
subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID)
if err != nil {
t.Fatalf("loadTemplateSubgraph failed: %v", err)
}
if len(subgraph.Issues) != 3 {
t.Errorf("Issues count = %d, want 3", len(subgraph.Issues))
}
// Check variables extracted
vars := extractAllVariables(subgraph)
if len(vars) != 1 || vars[0] != "name" {
t.Errorf("Variables = %v, want [name]", vars)
}
})
t.Run("load epic with nested children", func(t *testing.T) {
epic := h.createIssue("Nested Template", "", types.TypeEpic, 1)
child := h.createIssue("Child Task", "", types.TypeTask, 2)
grandchild := h.createIssue("Grandchild Task", "", types.TypeTask, 3)
h.addParentChild(child.ID, epic.ID)
h.addParentChild(grandchild.ID, child.ID)
subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID)
if err != nil {
t.Fatalf("loadTemplateSubgraph failed: %v", err)
}
if len(subgraph.Issues) != 3 {
t.Errorf("Issues count = %d, want 3 (epic + child + grandchild)", len(subgraph.Issues))
}
})
}
// TestCloneSubgraph tests cloning a template with variable substitution
func TestCloneSubgraph(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "bd-test-clone-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
testDB := filepath.Join(tmpDir, "test.db")
s := newTestStore(t, testDB)
defer s.Close()
ctx := context.Background()
h := &templateTestHelper{s: s, ctx: ctx, t: t}
t.Run("clone simple template", func(t *testing.T) {
epic := h.createIssue("Release {{version}}", "Release notes for {{version}}", types.TypeEpic, 1)
h.addLabel(epic.ID, BeadsTemplateLabel)
subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID)
if err != nil {
t.Fatalf("loadTemplateSubgraph failed: %v", err)
}
vars := map[string]string{"version": "2.0.0"}
result, err := cloneSubgraph(ctx, s, subgraph, vars, "test-user")
if err != nil {
t.Fatalf("cloneSubgraph failed: %v", err)
}
if result.Created != 1 {
t.Errorf("Created = %d, want 1", result.Created)
}
if result.NewEpicID == epic.ID {
t.Error("NewEpicID should be different from template ID")
}
// Verify the cloned issue
newEpic, err := s.GetIssue(ctx, result.NewEpicID)
if err != nil {
t.Fatalf("Failed to get cloned issue: %v", err)
}
if newEpic.Title != "Release 2.0.0" {
t.Errorf("Title = %q, want %q", newEpic.Title, "Release 2.0.0")
}
if newEpic.Description != "Release notes for 2.0.0" {
t.Errorf("Description = %q, want %q", newEpic.Description, "Release notes for 2.0.0")
}
})
t.Run("clone template with children", func(t *testing.T) {
epic := h.createIssue("Deploy {{service}}", "", types.TypeEpic, 1)
child1 := h.createIssue("Build {{service}}", "", types.TypeTask, 2)
child2 := h.createIssue("Test {{service}}", "", types.TypeTask, 2)
h.addParentChild(child1.ID, epic.ID)
h.addParentChild(child2.ID, epic.ID)
h.addLabel(epic.ID, BeadsTemplateLabel)
subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID)
if err != nil {
t.Fatalf("loadTemplateSubgraph failed: %v", err)
}
vars := map[string]string{"service": "api-gateway"}
result, err := cloneSubgraph(ctx, s, subgraph, vars, "test-user")
if err != nil {
t.Fatalf("cloneSubgraph failed: %v", err)
}
if result.Created != 3 {
t.Errorf("Created = %d, want 3", result.Created)
}
// Verify all IDs are different
if _, ok := result.IDMapping[epic.ID]; !ok {
t.Error("ID mapping missing epic")
}
if _, ok := result.IDMapping[child1.ID]; !ok {
t.Error("ID mapping missing child1")
}
if _, ok := result.IDMapping[child2.ID]; !ok {
t.Error("ID mapping missing child2")
}
// Verify cloned epic title
newEpic, err := s.GetIssue(ctx, result.NewEpicID)
if err != nil {
t.Fatalf("Failed to get cloned epic: %v", err)
}
if newEpic.Title != "Deploy api-gateway" {
t.Errorf("Epic title = %q, want %q", newEpic.Title, "Deploy api-gateway")
}
// Verify dependencies were cloned
deps, err := s.GetDependencyRecords(ctx, result.IDMapping[child1.ID])
if err != nil {
t.Fatalf("Failed to get dependencies: %v", err)
}
hasParentChild := false
for _, dep := range deps {
if dep.DependsOnID == result.NewEpicID && dep.Type == types.DepParentChild {
hasParentChild = true
break
}
}
if !hasParentChild {
t.Error("Cloned child should have parent-child dependency on cloned epic")
}
})
t.Run("cloned issues start with open status", func(t *testing.T) {
// Create template with in_progress status
epic := h.createIssue("Template", "", types.TypeEpic, 1)
err := s.UpdateIssue(ctx, epic.ID, map[string]interface{}{"status": "in_progress"}, "test-user")
if err != nil {
t.Fatalf("Failed to update status: %v", err)
}
subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID)
if err != nil {
t.Fatalf("loadTemplateSubgraph failed: %v", err)
}
result, err := cloneSubgraph(ctx, s, subgraph, nil, "test-user")
if err != nil {
t.Fatalf("cloneSubgraph failed: %v", err)
}
newEpic, err := s.GetIssue(ctx, result.NewEpicID)
if err != nil {
t.Fatalf("Failed to get cloned issue: %v", err)
}
if newEpic.Status != types.StatusOpen {
t.Errorf("Status = %s, want %s", newEpic.Status, types.StatusOpen)
}
})
}
// TestExtractAllVariables tests extracting variables from entire subgraph
func TestExtractAllVariables(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "bd-test-extractall-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
testDB := filepath.Join(tmpDir, "test.db")
s := newTestStore(t, testDB)
defer s.Close()
ctx := context.Background()
h := &templateTestHelper{s: s, ctx: ctx, t: t}
epic := h.createIssue("Release {{version}}", "For {{product}}", types.TypeEpic, 1)
child := h.createIssue("Deploy to {{environment}}", "", types.TypeTask, 2)
h.addParentChild(child.ID, epic.ID)
subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID)
if err != nil {
t.Fatalf("loadTemplateSubgraph failed: %v", err)
}
vars := extractAllVariables(subgraph)
// Should find version, product, and environment
varMap := make(map[string]bool)
for _, v := range vars {
varMap[v] = true
}
if !varMap["version"] {
t.Error("Missing variable: version")
}
if !varMap["product"] {
t.Error("Missing variable: product")
}
if !varMap["environment"] {
t.Error("Missing variable: environment")
}
}