//go:build cgo package main import ( "context" "encoding/json" "fmt" "path/filepath" "slices" "sort" "strings" "testing" "time" "github.com/steveyegge/beads/internal/formula" "github.com/steveyegge/beads/internal/storage/dolt" "github.com/steveyegge/beads/internal/testutil" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/validation" ) // ============================================================================= // Beads Template Tests (for bd template instantiate) // ============================================================================= // TestExtractVariables tests the {{variable}} pattern extraction func TestExtractVariables(t *testing.T) { t.Parallel() 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}, {name: "handlebars else keyword ignored", input: "{{ready}} then {{else}} or {{other}}", expected: []string{"ready", "other"}}, {name: "handlebars this keyword ignored", input: "{{this}} and {{name}}", expected: []string{"name"}}, {name: "multiple handlebars keywords ignored", input: "{{else}} {{this}} {{root}} {{index}} {{key}} {{first}} {{last}} {{actual_var}}", expected: []string{"actual_var"}}, } 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) { t.Parallel() 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) } }) } } // TestSubstituteMetadataVars covers the SF2 follow-up and GH#5110: step // metadata (`[steps.metadata]`) and a gate step's `repo` selector // ("repo": "{{gate_repo}}") are stored literally in the persisted proto's // metadata by cook --persist (compile-time mode never substitutes), so // substitution must happen at the same point other var-bearing issue fields // (Title, Description, Assignee, Labels, AwaitID, ...) are substituted: here, // when a proto is cloned/poured into real issues. func TestSubstituteMetadataVars(t *testing.T) { t.Parallel() tests := []struct { name string metadata string vars map[string]string want string }{ { name: "substitutes repo variable", metadata: `{"repo":"{{gate_repo}}"}`, vars: map[string]string{"gate_repo": "srobroek/agentic-packages"}, want: `{"repo":"srobroek/agentic-packages"}`, }, { // GH#5110: general step metadata, not a gate repo selector. name: "substitutes arbitrary metadata key", metadata: `{"ado_id":"{{ado_id}}","domain":"team/{{domain}}"}`, vars: map[string]string{"ado_id": "731878", "domain": "payroll"}, want: `{"ado_id":"731878","domain":"team/payroll"}`, }, { name: "substitutes nested and array values", metadata: `{"outer":{"inner":"{{v}}"},"list":["{{v}}","static"]}`, vars: map[string]string{"v": "resolved"}, want: `{"outer":{"inner":"resolved"},"list":["resolved","static"]}`, }, { name: "missing var leaves placeholder", metadata: `{"repo":"{{gate_repo}}"}`, vars: map[string]string{}, want: `{"repo":"{{gate_repo}}"}`, }, { name: "no placeholder untouched", metadata: `{"other":"value"}`, vars: map[string]string{"gate_repo": "srobroek/agentic-packages"}, want: `{"other":"value"}`, }, { name: "empty metadata untouched", metadata: "", vars: map[string]string{"gate_repo": "srobroek/agentic-packages"}, want: "", }, { name: "null repo left for check-time validation", metadata: `{"repo":null}`, vars: map[string]string{"gate_repo": "srobroek/agentic-packages"}, want: `{"repo":null}`, }, { // Supersedes the earlier SF4 gh:*-only rule. That restriction // existed because reading a `repo` key AS a GitHub selector is // only correct on a gh:* gate - but resolving a {{var}} in it // interprets the key not at all, and a bead poured with a literal // `{{gate_repo}}` in its metadata is broken whatever the gate type. name: "non-github gate metadata also substitutes", metadata: `{"repo":"{{gate_repo}}"}`, vars: map[string]string{"gate_repo": "srobroek/agentic-packages"}, want: `{"repo":"srobroek/agentic-packages"}`, }, { name: "object keys are never rewritten", metadata: `{"{{key}}":"{{val}}"}`, vars: map[string]string{"key": "k", "val": "v"}, want: `{"{{key}}":"v"}`, }, { name: "malformed metadata returned untouched", metadata: `{not json`, vars: map[string]string{"v": "x"}, want: `{not json`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var metadata json.RawMessage if tt.metadata != "" { metadata = json.RawMessage(tt.metadata) } got := substituteMetadataVars(metadata, tt.vars) if tt.want == "" { if len(got) != 0 { t.Errorf("substituteMetadataVars(%q, %v) = %q, want empty", tt.metadata, tt.vars, got) } return } if !json.Valid([]byte(tt.want)) { // Malformed input: assert the bytes came back verbatim. if string(got) != tt.want { t.Errorf("substituteMetadataVars(%q, %v) = %s, want %s", tt.metadata, tt.vars, got, tt.want) } return } // Compare parsed JSON to avoid brittleness over key ordering. var gotObj, wantObj map[string]interface{} if err := json.Unmarshal(got, &gotObj); err != nil { t.Fatalf("result %s is not valid JSON: %v", got, err) } if err := json.Unmarshal([]byte(tt.want), &wantObj); err != nil { t.Fatalf("want %s is not valid JSON: %v", tt.want, err) } gotJSON, _ := json.Marshal(gotObj) wantJSON, _ := json.Marshal(wantObj) if string(gotJSON) != string(wantJSON) { t.Errorf("substituteMetadataVars(%q, %v) = %s, want %s", tt.metadata, tt.vars, got, tt.want) } }) } } // TestSubstituteMetadataVars_DepthLimit verifies the recursion bound holds and // that a value nested past the limit is returned untouched rather than // panicking the pour. func TestSubstituteMetadataVars_DepthLimit(t *testing.T) { t.Parallel() deep := `"{{v}}"` for i := 0; i < maxMetadataSubstitutionDepth+5; i++ { deep = `{"a":` + deep + `}` } got := substituteMetadataVars(json.RawMessage(deep), map[string]string{"v": "resolved"}) if !json.Valid(got) { t.Fatalf("result is not valid JSON: %s", got) } if !strings.Contains(string(got), "{{v}}") { t.Errorf("expected the past-limit placeholder to survive untouched, got %s", got) } } // TestSubstituteLabels covers GH#5110: a step's labels are carried onto the // proto literally by processStepToIssue, so they must resolve at pour time // like Title and Description do. An unsubstituted label doesn't error - it // just silently stops matching every label query downstream. func TestSubstituteLabels(t *testing.T) { t.Parallel() vars := map[string]string{"widget_id": "my_widget", "domain": "payroll"} got := substituteLabels([]string{"qa-run", "widget:{{widget_id}}", "domain:{{domain}}", "{{unset}}"}, vars) want := []string{"qa-run", "widget:my_widget", "domain:payroll", "{{unset}}"} if !slices.Equal(got, want) { t.Errorf("substituteLabels() = %v, want %v", got, want) } if got := substituteLabels(nil, vars); got != nil { t.Errorf("substituteLabels(nil) = %v, want nil", got) } } // TestSubstituteMetadataVars_PreservesUnrelatedValuesByteIdentical covers the // round-trip-fidelity half of the SF2/SF4 follow-up: the walk must decode into // map[string]json.RawMessage, not map[string]interface{}, so a sibling key's // value survives untouched when another value is substituted - a decode into // interface{} would mangle a JSON number to float64 (losing its original // formatting/precision on re-encode), reorder a nested object's keys, and // HTML-escape '<'/'>'/'&' inside string values that were never touched by the // substitution. func TestSubstituteMetadataVars_PreservesUnrelatedValuesByteIdentical(t *testing.T) { t.Parallel() metadata := json.RawMessage(`{"repo":"{{gate_repo}}","count":123456789012345,"nested":{"z":1,"a":2,"m":3},"note":"a & c"}`) got := substituteMetadataVars(metadata, map[string]string{"gate_repo": "srobroek/agentic-packages"}) var raw map[string]json.RawMessage if err := json.Unmarshal(got, &raw); err != nil { t.Fatalf("result %s is not valid JSON: %v", got, err) } if string(raw["count"]) != "123456789012345" { t.Errorf(`metadata["count"] = %s, want 123456789012345 (byte-identical, not float64-mangled)`, raw["count"]) } if string(raw["nested"]) != `{"z":1,"a":2,"m":3}` { t.Errorf(`metadata["nested"] = %s, want {"z":1,"a":2,"m":3} (byte-identical key order)`, raw["nested"]) } if string(raw["note"]) != `"a & c"` { t.Errorf(`metadata["note"] = %s, want "a & c" (no HTML-escaping)`, raw["note"]) } var repo string if err := json.Unmarshal(raw["repo"], &repo); err != nil { t.Fatalf("metadata[\"repo\"] = %s is not a JSON string: %v", raw["repo"], err) } if repo != "srobroek/agentic-packages" { t.Errorf(`metadata["repo"] = %q, want "srobroek/agentic-packages"`, repo) } } // TestCloneSubgraph_SubstitutesGateRepoMetadata is the end-to-end regression // test for the cook --persist -> pour path: a gate issue persisted with // metadata.repo="{{gate_repo}}" (as createGateIssue/persistCookFormula would // write it for `repo = "{{gate_repo}}"` in the formula) must have that // placeholder substituted when the proto is cloned/poured with // --var gate_repo=..., exactly like it would be if the repo selector were an // AwaitID or Title placeholder instead. func TestCloneSubgraph_SubstitutesGateRepoMetadata(t *testing.T) { t.Parallel() tmpDir := t.TempDir() testDB := filepath.Join(tmpDir, ".beads", "beads.db") s := newTestStore(t, testDB) ctx := context.Background() h := &templateTestHelper{s: s, ctx: ctx, t: t} epic := h.createIssue("Release {{version}}", "", types.TypeEpic, 1) h.addLabel(epic.ID, BeadsTemplateLabel) gate := &types.Issue{ Title: "Gate: gh:run", IssueType: "gate", Status: types.StatusOpen, AwaitType: "gh:run", AwaitID: "release.yml", Metadata: json.RawMessage(`{"repo":"{{gate_repo}}"}`), } if err := s.CreateIssue(ctx, gate, "test-user"); err != nil { t.Fatalf("Failed to create gate issue: %v", err) } h.addParentChild(gate.ID, epic.ID) subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } vars := map[string]string{"version": "2.0.0", "gate_repo": "srobroek/agentic-packages"} opts := CloneOptions{Vars: vars, Actor: "test-user"} result, err := cloneSubgraph(ctx, s, subgraph, opts) if err != nil { t.Fatalf("cloneSubgraph failed: %v", err) } newGateID, ok := result.IDMapping[gate.ID] if !ok { t.Fatalf("IDMapping missing entry for gate %s: %+v", gate.ID, result.IDMapping) } newGate, err := s.GetIssue(ctx, newGateID) if err != nil { t.Fatalf("Failed to get cloned gate issue: %v", err) } var metadata struct { Repo string `json:"repo"` } if err := json.Unmarshal(newGate.Metadata, &metadata); err != nil { t.Fatalf("newGate.Metadata = %s, not valid JSON: %v", newGate.Metadata, err) } if metadata.Repo != "srobroek/agentic-packages" { t.Errorf("cloned gate metadata.repo = %q, want %q (repo = \"{{gate_repo}}\" must be substituted at pour time, same as AwaitID/Title)", metadata.Repo, "srobroek/agentic-packages") } } // TestCloneSubgraph_SubstitutesLabelsAssigneeAndMetadata is the end-to-end // regression test for GH#5110 and GH#5754: a proto step persisted with // templated labels, assignee, and metadata (as cook writes them - compile-time // mode keeps placeholders so the proto stays reusable across pours) must have // all three resolved when the proto is poured, exactly like Title and // Description are. // // The assignee assertion goes through validation.AssigneeMatches rather than // just comparing strings: an unsubstituted assignee is not a cosmetic defect, // it makes the poured bead unclosable by the actor that poured it, so every // step of the molecule is dead on arrival. func TestCloneSubgraph_SubstitutesLabelsAssigneeAndMetadata(t *testing.T) { t.Parallel() tmpDir := t.TempDir() testDB := filepath.Join(tmpDir, ".beads", "beads.db") s := newTestStore(t, testDB) ctx := context.Background() h := &templateTestHelper{s: s, ctx: ctx, t: t} const actor = "design-agent" epic := h.createIssue("QA {{widget_id}}", "", types.TypeEpic, 1) h.addLabel(epic.ID, BeadsTemplateLabel) step := &types.Issue{ Title: "API-contract QA: {{widget_id}}", IssueType: types.TypeTask, Status: types.StatusOpen, Assignee: "{{agent}}", Labels: []string{"qa-run", "widget:{{widget_id}}", "domain:{{domain}}"}, Metadata: json.RawMessage(`{"ado_id":"{{ado_id}}"}`), } if err := s.CreateIssue(ctx, step, "test-user"); err != nil { t.Fatalf("Failed to create step issue: %v", err) } h.addParentChild(step.ID, epic.ID) subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } vars := map[string]string{ "widget_id": "my_widget", "domain": "payroll", "agent": actor, "ado_id": "731878", } result, err := cloneSubgraph(ctx, s, subgraph, CloneOptions{Vars: vars, Actor: actor}) if err != nil { t.Fatalf("cloneSubgraph failed: %v", err) } newStepID, ok := result.IDMapping[step.ID] if !ok { t.Fatalf("IDMapping missing entry for step %s: %+v", step.ID, result.IDMapping) } newStep, err := s.GetIssue(ctx, newStepID) if err != nil { t.Fatalf("Failed to get poured step: %v", err) } // GH#5110: labels. An unsubstituted label doesn't error - it just stops // matching every label-based query and automation downstream. gotLabels := slices.Clone(newStep.Labels) sort.Strings(gotLabels) wantLabels := []string{"domain:payroll", "qa-run", "widget:my_widget"} if !slices.Equal(gotLabels, wantLabels) { t.Errorf("poured step labels = %v, want %v", gotLabels, wantLabels) } // GH#5110: general step metadata, not just a gh:* gate's repo selector. var metadata struct { ADOID string `json:"ado_id"` } if err := json.Unmarshal(newStep.Metadata, &metadata); err != nil { t.Fatalf("poured step metadata = %s, not valid JSON: %v", newStep.Metadata, err) } if metadata.ADOID != "731878" { t.Errorf("poured step metadata.ado_id = %q, want %q", metadata.ADOID, "731878") } // GH#5754: assignee, and the symptom that makes it severe. if newStep.Assignee != actor { t.Errorf("poured step assignee = %q, want %q", newStep.Assignee, actor) } if err := validation.AssigneeMatches(actor, false)(newStepID, newStep); err != nil { t.Errorf("poured step is not closable by the pouring actor %q: %v", actor, err) } } // TestCloneSubgraph_AssigneeOverrideBeatsSubstitution pins the precedence // between an explicit `bd mol pour --assignee` and a templated Step.assignee: // the flag is a literal value supplied on the command line and wins on the // root, while the steps still resolve their own placeholder (GH#5754). func TestCloneSubgraph_AssigneeOverrideBeatsSubstitution(t *testing.T) { t.Parallel() tmpDir := t.TempDir() testDB := filepath.Join(tmpDir, ".beads", "beads.db") s := newTestStore(t, testDB) ctx := context.Background() h := &templateTestHelper{s: s, ctx: ctx, t: t} epic := &types.Issue{ Title: "Root", IssueType: types.TypeEpic, Status: types.StatusOpen, Assignee: "{{agent}}", } if err := s.CreateIssue(ctx, epic, "test-user"); err != nil { t.Fatalf("Failed to create epic: %v", err) } h.addLabel(epic.ID, BeadsTemplateLabel) step := &types.Issue{ Title: "Step", IssueType: types.TypeTask, Status: types.StatusOpen, Assignee: "{{agent}}", } if err := s.CreateIssue(ctx, step, "test-user"); err != nil { t.Fatalf("Failed to create step: %v", err) } h.addParentChild(step.ID, epic.ID) subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } opts := CloneOptions{ Vars: map[string]string{"agent": "from-var"}, Assignee: "from-flag", Actor: "test-user", } result, err := cloneSubgraph(ctx, s, subgraph, opts) if err != nil { t.Fatalf("cloneSubgraph failed: %v", err) } newEpic, err := s.GetIssue(ctx, result.IDMapping[epic.ID]) if err != nil { t.Fatalf("Failed to get poured epic: %v", err) } if newEpic.Assignee != "from-flag" { t.Errorf("poured root assignee = %q, want %q (--assignee overrides the template)", newEpic.Assignee, "from-flag") } newStep, err := s.GetIssue(ctx, result.IDMapping[step.ID]) if err != nil { t.Fatalf("Failed to get poured step: %v", err) } if newStep.Assignee != "from-var" { t.Errorf("poured step assignee = %q, want %q (override applies to the root only)", newStep.Assignee, "from-var") } } // TestExtractAllVariables_CoversSubstitutedFields pins the scan side of // GH#5110/GH#5754: pour must demand every variable it is going to resolve. A // var appearing only in an assignee, label, metadata value, or await ID used // to go undemanded, so a declared-but-unsupplied var silently shipped a // literal placeholder onto the poured bead. func TestExtractAllVariables_CoversSubstitutedFields(t *testing.T) { t.Parallel() subgraph := &TemplateSubgraph{ Issues: []*types.Issue{ { Title: "Step {{in_title}}", Assignee: "{{in_assignee}}", Labels: []string{"static", "widget:{{in_label}}"}, Metadata: json.RawMessage(`{"ado_id":"{{in_metadata}}","nested":{"k":"{{in_nested_metadata}}"}}`), AwaitID: "{{in_await_id}}", }, }, } got := extractAllVariables(subgraph) for _, want := range []string{ "in_title", "in_assignee", "in_label", "in_metadata", "in_nested_metadata", "in_await_id", } { if !slices.Contains(got, want) { t.Errorf("extractAllVariables() = %v, missing %q", got, want) } } } // templateTestHelper provides helpers for Beads template tests type templateTestHelper struct { s *dolt.DoltStore 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) } } // createIssueWithID creates an issue with a specific ID (for testing hierarchical IDs) func (h *templateTestHelper) createIssueWithID(id, title, description string, issueType types.IssueType, priority int) *types.Issue { issue := &types.Issue{ ID: id, 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 with ID %s: %v", id, err) } return issue } func (h *templateTestHelper) createHierarchy(rootID string, descendantIDs ...string) { h.createIssueWithID(rootID, rootID, "", types.TypeEpic, 1) for _, id := range descendantIDs { h.createIssueWithID(id, id, "", types.TypeTask, 2) } } func issueIDs(issues []*types.Issue) []string { ids := make([]string, 0, len(issues)) for _, issue := range issues { ids = append(ids, issue.ID) } sort.Strings(ids) return ids } func requireIssueIDs(t testing.TB, issues []*types.Issue, want ...string) { t.Helper() got := issueIDs(issues) want = slices.Clone(want) sort.Strings(want) if !slices.Equal(got, want) { t.Fatalf("issue IDs = %v, want %v", got, want) } } func newTemplateBenchmarkStore(b *testing.B) (*dolt.DoltStore, context.Context) { b.Helper() if testDoltServerPort == 0 { b.Skip("Dolt test server not available, skipping") } if testutil.DoltContainerCrashed() { b.Skipf("Dolt test server crashed: %v", testutil.DoltContainerCrashError()) } ctx := context.Background() testDB := filepath.Join(b.TempDir(), ".beads", "beads.db") database := fmt.Sprintf("benchdb_%d", time.Now().UnixNano()) s, err := dolt.New(ctx, &dolt.Config{ Path: testDB, ServerHost: "127.0.0.1", ServerPort: testDoltServerPort, Database: database, CreateIfMissing: true, }) if err != nil { b.Fatalf("Failed to create benchmark dolt store: %v", err) } b.Cleanup(func() { s.Close() dropTestDatabase(database, testDoltServerPort) }) if err := s.SetConfig(ctx, "issue_prefix", "bench"); err != nil { b.Fatalf("Failed to set issue_prefix: %v", err) } if err := s.SetConfig(ctx, "types.custom", "molecule,gate,convoy,merge-request,slot,agent,role,rig,event,message"); err != nil { b.Fatalf("Failed to set types.custom: %v", err) } return s, ctx } func createBenchmarkIssue(b *testing.B, ctx context.Context, s *dolt.DoltStore, id string, priority int, issueType types.IssueType) { b.Helper() issue := &types.Issue{ ID: id, Title: id, Priority: priority, IssueType: issueType, Status: types.StatusOpen, } if err := s.CreateIssue(ctx, issue, "benchmark"); err != nil { b.Fatalf("CreateIssue(%s): %v", id, err) } } func seedHierarchicalTemplateGraph(b *testing.B, ctx context.Context, s *dolt.DoltStore, rootID string, directChildren, grandchildrenPerNode, unrelatedIssueCount int) int { b.Helper() createBenchmarkIssue(b, ctx, s, rootID, 1, types.TypeEpic) expectedIssues := 1 for childIndex := 1; childIndex <= directChildren; childIndex++ { childID := fmt.Sprintf("%s.%d", rootID, childIndex) createBenchmarkIssue(b, ctx, s, childID, 2, types.TypeTask) expectedIssues++ for grandchildIndex := 1; grandchildIndex <= grandchildrenPerNode; grandchildIndex++ { createBenchmarkIssue(b, ctx, s, fmt.Sprintf("%s.%d", childID, grandchildIndex), 3, types.TypeTask) expectedIssues++ } } for noiseIndex := 0; noiseIndex < unrelatedIssueCount; noiseIndex++ { createBenchmarkIssue(b, ctx, s, fmt.Sprintf("bench-noise-%04d", noiseIndex), 4, types.TypeTask) } return expectedIssues } // TestTemplateSuite consolidates template loading, cloning, and variable extraction // tests that share one DB to reduce Dolt store initialization overhead. func TestTemplateSuite(t *testing.T) { t.Parallel() tmpDir := t.TempDir() testDB := filepath.Join(tmpDir, ".beads", "beads.db") s := newTestStore(t, testDB) ctx := context.Background() h := &templateTestHelper{s: s, ctx: ctx, t: t} // --- LoadTemplateSubgraph tests --- t.Run("LoadTemplate_EpicWithNoChildren", 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("LoadTemplate_EpicWithChildren", 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)) } vars := extractAllVariables(subgraph) if len(vars) != 1 || vars[0] != "name" { t.Errorf("Variables = %v, want [name]", vars) } }) t.Run("LoadTemplate_NestedChildren", 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)) } }) // --- CloneSubgraph tests --- t.Run("Clone_SimpleTemplate", 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"} opts := CloneOptions{Vars: vars, Actor: "test-user"} result, err := cloneSubgraph(ctx, s, subgraph, opts) 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") } 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_TemplateWithChildren", 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"} opts := CloneOptions{Vars: vars, Actor: "test-user"} result, err := cloneSubgraph(ctx, s, subgraph, opts) if err != nil { t.Fatalf("cloneSubgraph failed: %v", err) } if result.Created != 3 { t.Errorf("Created = %d, want 3", result.Created) } 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") } 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") } 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("Clone_StartsWithOpenStatus", func(t *testing.T) { 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) } opts := CloneOptions{Actor: "test-user"} result, err := cloneSubgraph(ctx, s, subgraph, opts) 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) } }) t.Run("Clone_AssigneeOverrideRootOnly", func(t *testing.T) { epic := h.createIssue("Root Epic", "", types.TypeEpic, 1) child := h.createIssue("Child Task", "", types.TypeTask, 2) h.addParentChild(child.ID, epic.ID) err := s.UpdateIssue(ctx, epic.ID, map[string]interface{}{"assignee": "template-owner"}, "test-user") if err != nil { t.Fatalf("Failed to set epic assignee: %v", err) } err = s.UpdateIssue(ctx, child.ID, map[string]interface{}{"assignee": "child-owner"}, "test-user") if err != nil { t.Fatalf("Failed to set child assignee: %v", err) } subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } opts := CloneOptions{Assignee: "new-assignee", Actor: "test-user"} result, err := cloneSubgraph(ctx, s, subgraph, opts) 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 epic: %v", err) } if newEpic.Assignee != "new-assignee" { t.Errorf("Epic assignee = %q, want %q", newEpic.Assignee, "new-assignee") } newChildID := result.IDMapping[child.ID] newChild, err := s.GetIssue(ctx, newChildID) if err != nil { t.Fatalf("Failed to get cloned child: %v", err) } if newChild.Assignee != "child-owner" { t.Errorf("Child assignee = %q, want %q", newChild.Assignee, "child-owner") } }) t.Run("Clone_RootOnly_CreatedCountMatchesActual", func(t *testing.T) { epic := h.createIssue("Root Epic", "", types.TypeEpic, 1) child1 := h.createIssue("Child 1", "", types.TypeTask, 2) child2 := h.createIssue("Child 2", "", 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) } // With RootOnly=true, only the root should be created opts := CloneOptions{RootOnly: true, Actor: "test-user"} result, err := cloneSubgraph(ctx, s, subgraph, opts) if err != nil { t.Fatalf("cloneSubgraph failed: %v", err) } if result.Created != 1 { t.Errorf("Created = %d, want 1 (only root should be counted when RootOnly=true)", result.Created) } if len(result.IDMapping) != 1 { t.Errorf("IDMapping has %d entries, want 1", len(result.IDMapping)) } }) // --- ExtractAllVariables tests --- t.Run("ExtractAllVariables", func(t *testing.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) 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") } }) // --- LoadTemplateSubgraphWithManyChildren tests (bd-c8d5) --- t.Run("ManyChildren_4Children", func(t *testing.T) { epic := h.createIssue("Proto Workflow", "Workflow with 4 steps", types.TypeEpic, 1) h.addLabel(epic.ID, BeadsTemplateLabel) child1 := h.createIssue("load-context", "", types.TypeTask, 2) child2 := h.createIssue("implement", "", types.TypeTask, 2) child3 := h.createIssue("self-review", "", types.TypeTask, 2) child4 := h.createIssue("request-shutdown", "", types.TypeTask, 2) h.addParentChild(child1.ID, epic.ID) h.addParentChild(child2.ID, epic.ID) h.addParentChild(child3.ID, epic.ID) h.addParentChild(child4.ID, epic.ID) subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } if len(subgraph.Issues) != 5 { t.Errorf("Issues count = %d, want 5 (epic + 4 children)", len(subgraph.Issues)) for _, iss := range subgraph.Issues { t.Logf(" - %s: %s", iss.ID, iss.Title) } } childIDs := []string{child1.ID, child2.ID, child3.ID, child4.ID} for _, childID := range childIDs { if _, ok := subgraph.IssueMap[childID]; !ok { t.Errorf("Child %s not found in subgraph", childID) } } }) t.Run("ManyChildren_CloneCreatesAll4", func(t *testing.T) { epic := h.createIssue("Polecat Work", "", types.TypeEpic, 1) h.addLabel(epic.ID, BeadsTemplateLabel) child1 := h.createIssue("load-context", "", types.TypeTask, 2) child2 := h.createIssue("implement", "", types.TypeTask, 2) child3 := h.createIssue("self-review", "", types.TypeTask, 2) child4 := h.createIssue("request-shutdown", "", types.TypeTask, 2) h.addParentChild(child1.ID, epic.ID) h.addParentChild(child2.ID, epic.ID) h.addParentChild(child3.ID, epic.ID) h.addParentChild(child4.ID, epic.ID) subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } opts := CloneOptions{Actor: "test-user"} result, err := cloneSubgraph(ctx, s, subgraph, opts) if err != nil { t.Fatalf("cloneSubgraph failed: %v", err) } if result.Created != 5 { t.Errorf("Created = %d, want 5", result.Created) } for _, childID := range []string{child1.ID, child2.ID, child3.ID, child4.ID} { if _, ok := result.IDMapping[childID]; !ok { t.Errorf("Child %s not in ID mapping", childID) } } }) t.Run("ManyChildren_HierarchicalIDs", func(t *testing.T) { epic := h.createIssueWithID("test-lwuu", "mol-polecat-work", "", types.TypeEpic, 1) h.addLabel(epic.ID, BeadsTemplateLabel) child1 := h.createIssueWithID("test-lwuu.1", "load-context", "", types.TypeTask, 2) child2 := h.createIssueWithID("test-lwuu.2", "implement", "", types.TypeTask, 2) child3 := h.createIssueWithID("test-lwuu.3", "self-review", "", types.TypeTask, 2) child8 := h.createIssueWithID("test-lwuu.8", "request-shutdown", "", types.TypeTask, 2) h.addParentChild(child1.ID, epic.ID) h.addParentChild(child2.ID, epic.ID) h.addParentChild(child3.ID, epic.ID) h.addParentChild(child8.ID, epic.ID) subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } if len(subgraph.Issues) != 5 { t.Errorf("Issues count = %d, want 5", len(subgraph.Issues)) for _, iss := range subgraph.Issues { t.Logf(" - %s: %s", iss.ID, iss.Title) } } for _, childID := range []string{"test-lwuu.1", "test-lwuu.2", "test-lwuu.3", "test-lwuu.8"} { if _, ok := subgraph.IssueMap[childID]; !ok { t.Errorf("Child %s not found in subgraph", childID) } } }) t.Run("ManyChildren_WrongDepTypeNotLoaded", func(t *testing.T) { epic := h.createIssue("Proto with mixed deps", "", types.TypeEpic, 1) h.addLabel(epic.ID, BeadsTemplateLabel) child1 := h.createIssue("load-context", "", types.TypeTask, 2) child2 := h.createIssue("implement", "", types.TypeTask, 2) child3 := h.createIssue("self-review", "", types.TypeTask, 2) child4 := h.createIssue("request-shutdown", "", types.TypeTask, 2) h.addParentChild(child1.ID, epic.ID) h.addParentChild(child2.ID, epic.ID) // child3 and child4 have "related" dependency (wrong type — not parent-child) for _, childID := range []string{child3.ID, child4.ID} { blocksDep := &types.Dependency{IssueID: childID, DependsOnID: epic.ID, Type: types.DepRelated} if err := s.AddDependency(ctx, blocksDep, "test-user"); err != nil { t.Fatalf("Failed to add blocks dependency: %v", err) } } subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } if len(subgraph.Issues) != 3 { t.Errorf("Expected 3 issues (without hierarchical ID fallback), got %d", len(subgraph.Issues)) } }) t.Run("ManyChildren_HierarchicalWrongDepTypeLoaded", func(t *testing.T) { epic := h.createIssueWithID("test-pcat", "Proto with mixed deps", "", types.TypeEpic, 1) h.addLabel(epic.ID, BeadsTemplateLabel) child1 := h.createIssueWithID("test-pcat.1", "load-context", "", types.TypeTask, 2) child2 := h.createIssueWithID("test-pcat.2", "implement", "", types.TypeTask, 2) h.addParentChild(child1.ID, epic.ID) h.addParentChild(child2.ID, epic.ID) // child3 has NO dependency at all (broken data) _ = h.createIssueWithID("test-pcat.3", "self-review", "", types.TypeTask, 2) // child8 has wrong dependency type (related, not parent-child) child8 := h.createIssueWithID("test-pcat.8", "request-shutdown", "", types.TypeTask, 2) relatedDep := &types.Dependency{IssueID: child8.ID, DependsOnID: epic.ID, Type: types.DepRelated} if err := s.AddDependency(ctx, relatedDep, "test-user"); err != nil { t.Fatalf("Failed to add related dependency: %v", err) } subgraph, err := loadTemplateSubgraph(ctx, s, epic.ID) if err != nil { t.Fatalf("loadTemplateSubgraph failed: %v", err) } if len(subgraph.Issues) != 5 { t.Errorf("Expected 5 issues (root + 4 hierarchical children), got %d", len(subgraph.Issues)) } for _, childID := range []string{"test-pcat.1", "test-pcat.2", "test-pcat.3", "test-pcat.8"} { if _, ok := subgraph.IssueMap[childID]; !ok { t.Errorf("Child %s not found in subgraph", childID) } } }) } // TestResolveProtoIDOrTitle tests proto lookup by ID or title (bd-drcx). // Kept separate from TestTemplateSuite because title-based search is affected by shared data. func TestResolveProtoIDOrTitle(t *testing.T) { t.Parallel() tmpDir := t.TempDir() testDB := filepath.Join(tmpDir, ".beads", "beads.db") s := newTestStore(t, testDB) ctx := context.Background() h := &templateTestHelper{s: s, ctx: ctx, t: t} proto1 := h.createIssue("mol-polecat-work", "Polecat workflow", types.TypeEpic, 1) h.addLabel(proto1.ID, BeadsTemplateLabel) proto2 := h.createIssue("mol-version-bump", "Version bump workflow", types.TypeEpic, 1) h.addLabel(proto2.ID, BeadsTemplateLabel) proto3 := h.createIssue("mol-release", "Release workflow", types.TypeEpic, 1) h.addLabel(proto3.ID, BeadsTemplateLabel) nonProto := h.createIssue("mol-test", "Not a proto", types.TypeTask, 2) t.Run("resolve by exact ID", func(t *testing.T) { resolved, err := resolveProtoIDOrTitle(ctx, s, proto1.ID) if err != nil { t.Fatalf("Failed to resolve by ID: %v", err) } if resolved != proto1.ID { t.Errorf("Expected %s, got %s", proto1.ID, resolved) } }) t.Run("resolve by exact title", func(t *testing.T) { resolved, err := resolveProtoIDOrTitle(ctx, s, "mol-polecat-work") if err != nil { t.Fatalf("Failed to resolve by title: %v", err) } if resolved != proto1.ID { t.Errorf("Expected %s, got %s", proto1.ID, resolved) } }) t.Run("resolve by title case-insensitive", func(t *testing.T) { resolved, err := resolveProtoIDOrTitle(ctx, s, "MOL-POLECAT-WORK") if err != nil { t.Fatalf("Failed to resolve by title (case-insensitive): %v", err) } if resolved != proto1.ID { t.Errorf("Expected %s, got %s", proto1.ID, resolved) } }) t.Run("resolve by unique partial title", func(t *testing.T) { resolved, err := resolveProtoIDOrTitle(ctx, s, "polecat") if err != nil { t.Fatalf("Failed to resolve by partial title: %v", err) } if resolved != proto1.ID { t.Errorf("Expected %s, got %s", proto1.ID, resolved) } }) t.Run("ambiguous partial title returns error", func(t *testing.T) { _, err := resolveProtoIDOrTitle(ctx, s, "mol-") if err == nil { t.Fatal("Expected error for ambiguous title, got nil") } if !strings.Contains(err.Error(), "ambiguous") { t.Errorf("Expected 'ambiguous' in error, got: %v", err) } }) t.Run("non-existent returns error", func(t *testing.T) { _, err := resolveProtoIDOrTitle(ctx, s, "nonexistent-proto") if err == nil { t.Fatal("Expected error for non-existent proto, got nil") } if !strings.Contains(err.Error(), "no proto found") { t.Errorf("Expected 'no proto found' in error, got: %v", err) } }) t.Run("non-proto ID returns error", func(t *testing.T) { _, err := resolveProtoIDOrTitle(ctx, s, nonProto.ID) if err == nil { t.Fatal("Expected error for non-proto ID, got nil") } }) } func TestFindHierarchicalChildren_DirectChildrenOnly(t *testing.T) { t.Parallel() tmpDir := t.TempDir() testDB := filepath.Join(tmpDir, ".beads", "beads.db") s := newTestStore(t, testDB) ctx := context.Background() h := &templateTestHelper{s: s, ctx: ctx, t: t} h.createHierarchy( "test-tree", "test-tree.1", "test-tree.2", "test-tree.1.1", "test-tree.2.1", "test-tree.2.1.1", ) h.createIssueWithID("test-other.1", "test-other.1", "", types.TypeTask, 2) children, err := findHierarchicalChildren(ctx, s, "test-tree") if err != nil { t.Fatalf("findHierarchicalChildren(root) failed: %v", err) } requireIssueIDs(t, children, "test-tree.1", "test-tree.2") nestedChildren, err := findHierarchicalChildren(ctx, s, "test-tree.2") if err != nil { t.Fatalf("findHierarchicalChildren(child) failed: %v", err) } requireIssueIDs(t, nestedChildren, "test-tree.2.1") } func BenchmarkLoadTemplateSubgraph_HierarchicalChildren(b *testing.B) { s, ctx := newTemplateBenchmarkStore(b) expectedIssues := seedHierarchicalTemplateGraph(b, ctx, s, "bench-root", 150, 4, 3000) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { subgraph, loadErr := loadTemplateSubgraph(ctx, s, "bench-root") if loadErr != nil { b.Fatalf("loadTemplateSubgraph failed: %v", loadErr) } if len(subgraph.Issues) != expectedIssues { b.Fatalf("Issues count = %d, want %d", len(subgraph.Issues), expectedIssues) } } } // TestExtractRequiredVariables_IgnoresUndeclaredVars tests that handlebars in // description text that are NOT defined in VarDefs are ignored (gt-ky9loa). func TestExtractRequiredVariables_IgnoresUndeclaredVars(t *testing.T) { t.Parallel() tests := []struct { name string issues []*types.Issue varDefs map[string]formula.VarDef wantRequired []string }{ { name: "declared var without default is required", issues: []*types.Issue{{Title: "Deploy {{component}}", Description: "Deploy the component"}}, varDefs: map[string]formula.VarDef{"component": {Required: true}}, wantRequired: []string{"component"}, }, { name: "declared var with default is not required", issues: []*types.Issue{{Title: "Deploy {{component}}", Description: "Deploy the component"}}, varDefs: map[string]formula.VarDef{"component": {Default: formula.StringPtr("api")}}, wantRequired: []string{}, }, { name: "undeclared var in description is ignored when VarDefs exists", issues: []*types.Issue{{ Title: "Generate report", Description: "Output format:\n**Ready**: {{ready_count}}\n**Done**: {{done_count}}", }}, varDefs: map[string]formula.VarDef{}, wantRequired: []string{}, }, { name: "mix of declared and undeclared vars", issues: []*types.Issue{{ Title: "Deploy {{component}} to {{env}}", Description: "Shows: {{status_count}} items processed", }}, varDefs: map[string]formula.VarDef{ "component": {Required: true}, "env": {Default: formula.StringPtr("prod")}, }, wantRequired: []string{"component"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { subgraph := &TemplateSubgraph{Issues: tt.issues, VarDefs: tt.varDefs} got := extractRequiredVariables(subgraph) gotMap := make(map[string]bool) for _, v := range got { gotMap[v] = true } wantMap := make(map[string]bool) for _, v := range tt.wantRequired { wantMap[v] = true } if len(got) != len(tt.wantRequired) { t.Errorf("extractRequiredVariables() = %v, want %v", got, tt.wantRequired) return } for _, v := range tt.wantRequired { if !gotMap[v] { t.Errorf("extractRequiredVariables() missing expected var %q, got %v", v, got) } } for _, v := range got { if !wantMap[v] { t.Errorf("extractRequiredVariables() has unexpected var %q, want %v", v, tt.wantRequired) } } }) } } // stubConfigReader serves config values from a map for // flattenUnregisteredIssueTypes tests. type stubConfigReader map[string]string func (s stubConfigReader) GetConfig(_ context.Context, key string) (string, error) { return s[key], nil } // TestFlattenUnregisteredIssueTypes verifies that pour/cook honor built-in // and already-registered custom types but never auto-register: an // unregistered type degrades (with a warning) instead of silently growing // types.custom — to epic when the issue has children, task otherwise. func TestFlattenUnregisteredIssueTypes(t *testing.T) { cfg := stubConfigReader{"types.custom": `["duty"]`} issues := []*types.Issue{ {ID: "f.a", IssueType: types.TypeBug}, {ID: "f.b", IssueType: types.IssueType("gate")}, // built-in orchestrator type {ID: "f.c", IssueType: types.IssueType("duty")}, // registered custom type {ID: "f.d", IssueType: types.IssueType("typo")}, // unregistered leaf — flattens to task {ID: "f.e", IssueType: ""}, {ID: "f.p", IssueType: types.IssueType("typo")}, // unregistered parent — flattens to epic } deps := []*types.Dependency{ {IssueID: "f.d", DependsOnID: "f.p", Type: types.DepParentChild}, } if err := flattenUnregisteredIssueTypes(context.Background(), cfg, issues, deps); err != nil { t.Fatalf("flattenUnregisteredIssueTypes: %v", err) } want := []types.IssueType{ types.TypeBug, types.IssueType("gate"), types.IssueType("duty"), types.TypeTask, "", types.TypeEpic, } for i, issue := range issues { if issue.IssueType != want[i] { t.Errorf("issues[%d] (%s) IssueType = %q, want %q", i, issue.ID, issue.IssueType, want[i]) } } } // TestBuildAttachCloneOpts_VarResolutionMatchesPour pins that `bd mol bond` // resolves variables exactly the way pour and wisp do, rather than demanding // every handlebar the subgraph mentions. // // buildAttachCloneOpts used the unfiltered extractAllVariables and applied no // defaults, so widening the scanned field set to assignee/labels/metadata // (GH#5110, GH#5754) would have widened bond's hard refusal along with it: a // proto whose label or metadata carried an undeclared documentation handlebar // would newly fail with "missing required variables". It now runs // applyVariableDefaults + extractRequiredVariables, matching cmd/bd/pour.go // and cmd/bd/wisp.go. func TestBuildAttachCloneOpts_VarResolutionMatchesPour(t *testing.T) { t.Parallel() mol := &types.Issue{ID: "mol-host", Title: "Host molecule"} tests := []struct { name string issues []*types.Issue varDefs map[string]formula.VarDef vars map[string]string wantErr string wantVarVals map[string]string }{ { name: "undeclared handlebars in the widened fields do not block the bond", issues: []*types.Issue{{ Title: "Review {{component}}", Assignee: "{{reviewer_placeholder}}", Labels: []string{"owner:{{team_placeholder}}"}, Metadata: json.RawMessage(`{"runbook":"see {{runbook_placeholder}}"}`), }}, varDefs: map[string]formula.VarDef{"component": {Required: true}}, vars: map[string]string{"component": "api"}, wantVarVals: map[string]string{"component": "api"}, }, { name: "a declared var that only has a default is filled, not demanded", issues: []*types.Issue{{ Title: "Deploy {{component}} to {{env}}", Assignee: "{{agent}}", }}, varDefs: map[string]formula.VarDef{ "component": {Required: true}, "env": {Default: formula.StringPtr("prod")}, "agent": {Default: formula.StringPtr("deploy-agent")}, }, vars: map[string]string{"component": "api"}, wantVarVals: map[string]string{ "component": "api", "env": "prod", "agent": "deploy-agent", }, }, { name: "a declared var with no default is still demanded", issues: []*types.Issue{{Title: "Deploy {{component}}"}}, varDefs: map[string]formula.VarDef{"component": {Required: true}}, vars: map[string]string{}, wantErr: "missing required variables: component", wantVarVals: nil, }, { name: "a legacy template with no VarDefs still requires every var it mentions", issues: []*types.Issue{{Title: "Deploy {{component}}", Assignee: "{{agent}}"}}, varDefs: nil, vars: map[string]string{"component": "api"}, wantErr: "missing required variables: agent", wantVarVals: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() subgraph := &TemplateSubgraph{Issues: tt.issues, VarDefs: tt.varDefs} opts, err := buildAttachCloneOpts(subgraph, mol, types.BondTypeSequential, tt.vars, "", "actor", false, false) if tt.wantErr != "" { if err == nil { t.Fatalf("expected error %q, got nil", tt.wantErr) } if !strings.Contains(err.Error(), tt.wantErr) { t.Fatalf("error = %q, want it to contain %q", err.Error(), tt.wantErr) } return } if err != nil { t.Fatalf("buildAttachCloneOpts: %v", err) } // The defaults have to land in opts.Vars too, not just in the // missing-var check - cloneSubgraphInto substitutes from this map. for name, want := range tt.wantVarVals { if got := opts.Vars[name]; got != want { t.Errorf("opts.Vars[%q] = %q, want %q", name, got, want) } } }) } }