beads/cmd/bd/mol_embedded_test.go
Harry Miller d0743f89d7
fix(formula): substitute vars in step assignee, labels, and metadata (#5758)
* fix(formula): substitute vars in step assignee, labels, and metadata

Cook and pour substituted title/description/notes/gate but copied
assignee, labels, and metadata through raw, so a poured bead carried
literal `{{var}}` text in all three.

- labels: every label-based query, filter, and automation silently stops
  matching, and nothing errors (GH#5110).
- metadata: general keys came through literal; only a top-level "repo"
  key on a gh:* gate was substituted (GH#5110).
- assignee: worse than cosmetic - close refuses when the actor doesn't
  match the assignee, so every step of a poured molecule is unclosable
  and the molecule can never advance (GH#5754).

internal/formula/expand.go already substituted assignee and labels on
the inline-expansion path, so the two paths disagreed on the same
fields; Step.Assignee is documented as "supports substitution" and
ExtractVariables already scanned it, meaning pour hard-failed demanding
a variable it then refused to resolve.

Both call sites are fixed together: runtime-mode cook feeds the proto
that pour clones, so a field left literal in either path ships a
placeholder onto the bead. Fixing cloneSubgraphInto covers pour, wisp,
bond, and the proxied-server paths, which all funnel through it.

substituteMetadataRepo is generalized to substituteMetadataVars, which
resolves every string leaf of the metadata JSON at any depth. This drops
the earlier gh:*-gate-only restriction (SF2/SF4): 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. The walk still decodes into
json.RawMessage, so untouched values stay byte-identical, and object
keys are never rewritten (a rewritten key could collide with a sibling).

The variable scan is widened to match: extractAllVariables (pour) and
ExtractVariables (cook) now cover assignee, labels, metadata strings,
notes, and await ID, so pour demands exactly the variables it resolves.
Undeclared handlebars are still filtered out by VarDefs.

Regression coverage asserts on a poured bead, and checks the assignee
via validation.AssigneeMatches rather than a string compare - a
substitution-only assertion would pass while the unclosable symptom
persisted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(formula): regenerate schema_gen.go after the types.go doc edits

TestSchemaGenIsCurrent holds schema_gen.go to a byte-for-byte rerun of
the generator over types.go, and the field docs are part of the
generated output — so the Labels/Metadata comment updates made it stale.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(mol bond): resolve vars like pour instead of demanding every handlebar

buildAttachCloneOpts demanded every variable extractAllVariables found in
the proto subgraph and applied no declared defaults, unlike pour
(cmd/bd/pour.go) and wisp (cmd/bd/wisp.go). Widening the scanned field set
to assignee, labels and metadata therefore widened bond's hard refusal
along with it: a proto whose label or metadata carried an undeclared
documentation handlebar, or a declared var carrying only a default, made
`bd mol bond` fail with "missing required variables" where it previously
succeeded.

Run applyVariableDefaults + extractRequiredVariables there, matching the
sibling call sites. extractRequiredVariables returns the unfiltered list
when VarDefs is nil, so a legacy template still requires every var it
mentions; the change is strictly a reduction in false failures. Applying
the defaults also puts them in opts.Vars, which is the map
cloneSubgraphInto actually substitutes from.

Also from review:

- docs/workflows/gates.md no longer enumerates a stale three-field list for
  where `{{var}}` substitution applies.
- maxMetadataSubstitutionDepth's doc names walkJSONStrings (not the
  long-gone substituteJSONVars) and says plainly that hitting the bound
  deliberately ships a literal placeholder rather than erroring.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* build(bazel): add the validation dep to the bd_test go_test (make bazel-sync)

mol_embedded_test.go and template_test.go now import internal/validation
directly (validation.AssigneeMatches, to check the substituted step
assignee), so gazelle emits //internal/validation on bd_test. bd_lib
already carries the dep, so bd_test compiles through embed, but gazelle
lists every direct test import on the go_test itself. cmd/bd/BUILD.bazel
landed on main after this PR branched, so the PR could not carry the
line; without it, bazel.yml's "BUILD files in sync" step fails in the
required Bazel / test lane. Generated by `make bazel-sync`.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-09-30 18:08:44 -07:00

175 lines
5.3 KiB
Go

//go:build cgo
package main
import (
"encoding/json"
"os"
"testing"
"github.com/steveyegge/beads/internal/formula"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/validation"
)
// TestSpawnMolecule_PreservesStepLabels verifies that a cooked formula with
// per-step labels results in spawned issues whose labels are persisted to the
// database. Regression for labels being silently dropped by cloneSubgraph in
// the same shape as the metadata bug fixed by gastownhall/beads#3341.
func TestSpawnMolecule_PreservesStepLabels(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
ctx := t.Context()
s, err := embeddeddolt.Open(ctx, t.TempDir(), "beads", "main")
if err != nil {
t.Fatalf("embeddeddolt.Open failed: %v", err)
}
defer s.Close()
if err := s.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("SetConfig failed: %v", err)
}
f := &formula.Formula{
Formula: "label-test",
Version: 1,
Type: formula.TypeWorkflow,
Steps: []*formula.Step{
{
ID: "work",
Title: "Do the work",
Labels: []string{"worker", "phase:build"},
},
},
}
subgraph, err := cookFormulaToSubgraph(f, "label-test")
if err != nil {
t.Fatalf("cookFormulaToSubgraph failed: %v", err)
}
result, err := spawnMolecule(ctx, s, subgraph, nil, "", "test", false, types.IDPrefixMol)
if err != nil {
t.Fatalf("spawnMolecule failed: %v", err)
}
newWorkID, ok := result.IDMapping["label-test.work"]
if !ok {
t.Fatalf("result.IDMapping missing entry for label-test.work; got %v", result.IDMapping)
}
labels, err := s.GetLabels(ctx, newWorkID)
if err != nil {
t.Fatalf("GetLabels(%s) failed: %v", newWorkID, err)
}
got := make(map[string]bool, len(labels))
for _, l := range labels {
got[l] = true
}
for _, want := range []string{"worker", "phase:build"} {
if !got[want] {
t.Errorf("spawned issue %s missing label %q; got %v", newWorkID, want, labels)
}
}
}
// TestSpawnMolecule_SubstitutesTemplatedStepFields is the cook -> pour
// regression test for GH#5110 (labels, metadata) and GH#5754 (assignee).
// TestSpawnMolecule_PreservesStepLabels above fixed labels being dropped
// entirely, but its labels carry no {{vars}}, so the missing substitution went
// unnoticed: the labels ARE carried through - just literal, which silently
// stops matching every label query downstream.
//
// The assignee case is the severe one. An unsubstituted assignee makes the
// spawned bead unclosable by the actor that poured it, so the molecule can
// never advance - which is what the AssigneeMatches assertion pins, not just
// the string value.
func TestSpawnMolecule_SubstitutesTemplatedStepFields(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
ctx := t.Context()
s, err := embeddeddolt.Open(ctx, t.TempDir(), "beads", "main")
if err != nil {
t.Fatalf("embeddeddolt.Open failed: %v", err)
}
defer s.Close()
if err := s.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("SetConfig failed: %v", err)
}
const actor = "design-agent"
f := &formula.Formula{
Formula: "subst-test",
Version: 1,
Type: formula.TypeWorkflow,
Steps: []*formula.Step{
{
ID: "qa",
Title: "API-contract QA: {{widget_id}}",
Assignee: "{{agent}}",
Labels: []string{"qa-run", "widget:{{widget_id}}", "domain:{{domain}}"},
Metadata: map[string]interface{}{"ado_id": "{{ado_id}}"},
},
},
}
subgraph, err := cookFormulaToSubgraph(f, "subst-test")
if err != nil {
t.Fatalf("cookFormulaToSubgraph failed: %v", err)
}
vars := map[string]string{
"widget_id": "my_widget",
"domain": "payroll",
"agent": actor,
"ado_id": "731878",
}
result, err := spawnMolecule(ctx, s, subgraph, vars, "", actor, false, types.IDPrefixMol)
if err != nil {
t.Fatalf("spawnMolecule failed: %v", err)
}
newQAID, ok := result.IDMapping["subst-test.qa"]
if !ok {
t.Fatalf("result.IDMapping missing entry for subst-test.qa; got %v", result.IDMapping)
}
issue, err := s.GetIssue(ctx, newQAID)
if err != nil {
t.Fatalf("GetIssue(%s) failed: %v", newQAID, err)
}
labels, err := s.GetLabels(ctx, newQAID)
if err != nil {
t.Fatalf("GetLabels(%s) failed: %v", newQAID, err)
}
gotLabels := make(map[string]bool, len(labels))
for _, l := range labels {
gotLabels[l] = true
}
for _, want := range []string{"qa-run", "widget:my_widget", "domain:payroll"} {
if !gotLabels[want] {
t.Errorf("spawned issue %s missing substituted label %q; got %v", newQAID, want, labels)
}
}
var metadata struct {
ADOID string `json:"ado_id"`
}
if err := json.Unmarshal(issue.Metadata, &metadata); err != nil {
t.Fatalf("spawned issue metadata = %s, not valid JSON: %v", issue.Metadata, err)
}
if metadata.ADOID != "731878" {
t.Errorf("spawned issue metadata.ado_id = %q, want %q", metadata.ADOID, "731878")
}
if issue.Assignee != actor {
t.Errorf("spawned issue assignee = %q, want %q", issue.Assignee, actor)
}
if err := validation.AssigneeMatches(actor, false)(newQAID, issue); err != nil {
t.Errorf("spawned issue is not closable by the pouring actor %q: %v", actor, err)
}
}