diff --git a/CHANGELOG.md b/CHANGELOG.md index 547ac33ed..bdd832f5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -544,6 +544,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 and the README snippet — so `bd init` and copy-paste do not re-introduce the prohibition. +- **`bd mol bond --ref` no longer deadlocks the molecule it bonds into, and no + longer accepts `--type conditional`.** A `--ref` arm is nested inside its + target and its hierarchical ID records that, so an ordering edge onto the + target was unsatisfiable in both directions: the arm waited for the molecule + to close, and the molecule could not close while it held an open arm. `bd + ready` went empty with nothing to point at. For a sequential bond (the + default) that edge is now dropped, so the arm carries **no ordering** and is + ready as soon as it is spawned - containment is a nested arm's only + satisfiable relationship to its container. A conditional edge has no such + degradation: it means "run only if the target fails", so dropping it would + run the arm unconditionally, turning a deadlock into a silent false dispatch. + `--ref` with `--type conditional` is therefore refused outright (including + under `--dry-run` and on the proxied route); omit `--ref` to bond a + conditional arm as a sibling, which is satisfiable and keeps its edge. + +- **`bd mol ready --gated` prints a dispatch command that exists.** The hint + named `bd sling`, which has never been a command in this binary, so the one + actionable line in the output could not be run. It now prints `bd assign + `, and says which listed molecule the example belongs + to when more than one is waiting. + - **`bd purge` keeps closed beads a live bead depends on.** A closed bead that a not-done bead depends on through `parent-child`, `tracks` or `blocks` is no longer purged (reported as `live_dependent_skipped`), so a diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index c75f22f04..6a77df6ab 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -892,6 +892,7 @@ go_test( "mol_bond_compound_label_test.go", "mol_bond_gwn_test.go", "mol_bond_proxied_integration_test.go", + "mol_bond_ref_attach_test.go", "mol_bond_test.go", "mol_burn_proxied_integration_test.go", "mol_current_proxied_integration_test.go", @@ -903,6 +904,7 @@ go_test( "mol_last_activity_proxied_integration_test.go", "mol_progress_proxied_integration_test.go", "mol_ready_gated_flag_test.go", + "mol_ready_gated_hint_test.go", "mol_ready_gated_proxied_integration_test.go", "mol_ready_gated_test.go", "mol_show_proxied_integration_test.go", diff --git a/cmd/bd/mol_bond.go b/cmd/bd/mol_bond.go index a19b68527..a3316f820 100644 --- a/cmd/bd/mol_bond.go +++ b/cmd/bd/mol_bond.go @@ -39,6 +39,15 @@ Bond types: parallel - B runs alongside A conditional - B runs only if A fails + With --ref, the spawned proto arm is nested inside the molecule operand + rather than ordered against it - whichever side of the bond that is - so a + sequential --ref arm carries no ordering: it is ready as soon as it is + spawned. Ordering a nested arm against its own container is unsatisfiable + in both directions (the arm waits for the molecule to close; the molecule + cannot close while it holds an open arm). --ref is refused with --type + conditional, which has no safe degradation - omit --ref to bond a + conditional arm as a sibling. + Phase control: By default, spawned protos follow the target's phase: - Attaching to mol (Ephemeral=false) → spawns as persistent (Ephemeral=false) @@ -189,6 +198,9 @@ func gatherMolBondInput(cmd *cobra.Command, args []string) (molBondInput, error) if in.bondType != types.BondTypeSequential && in.bondType != types.BondTypeParallel && in.bondType != types.BondTypeConditional { return in, fmt.Errorf("invalid bond type '%s', must be: sequential, parallel, or conditional", in.bondType) } + if err := refuseConditionalRefArm(in.bondType, in.childRef); err != nil { + return in, err + } varFlags, _ := cmd.Flags().GetStringArray("var") vars, err := parseVarFlags(varFlags) @@ -446,7 +458,38 @@ func bondProtoMolAttachInto(ctx context.Context, w molWriter, protoSubgraph *Tem }, nil } +// refuseConditionalRefArm rejects --ref combined with --type conditional. +// +// A --ref arm is nested inside its target, so an ordering edge onto that +// target can never be satisfied (see buildAttachCloneOpts). A sequential bond +// degrades gracefully: the edge is dropped and the arm carries no ordering. A +// conditional edge means "run only if the target fails", so dropping it would +// turn an arm that should almost never run into one that always runs - a +// silent false dispatch, which is worse than the deadlock it replaced. There +// is no reading of the two flags together that is both safe and useful, so +// refuse rather than guess. +// +// Both gatherMolBondInput (which also covers --dry-run and the proxied route) +// and buildAttachCloneOpts consult this, so a caller that skips flag +// validation cannot construct the arm either. +// +// The message has to read correctly for every operand shape, not just the +// nesting ones. gatherMolBondInput runs before operands are resolved, so this +// also refuses mol+mol and proto+proto - shapes that never receive a childRef +// at all, where --ref is inert and nothing nests. It is therefore phrased as +// what --ref does where it applies rather than as a claim about the bond in +// front of the user. Keep it that way if you reword it. +func refuseConditionalRefArm(bondType, childRef string) error { + if childRef == "" || bondType != types.BondTypeConditional { + return nil + } + return fmt.Errorf("--ref cannot be combined with --type conditional: where --ref nests an arm, a conditional edge onto the arm's own container cannot be satisfied, and dropping that edge would run the arm unconditionally instead of only on failure. Omit --ref to bond a conditional arm as a sibling, or use --type sequential or --type parallel with --ref") +} + func buildAttachCloneOpts(subgraph *TemplateSubgraph, mol *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (CloneOptions, error) { + if err := refuseConditionalRefArm(bondType, childRef); err != nil { + return CloneOptions{}, err + } requiredVars := extractAllVariables(subgraph) var missingVars []string for _, v := range requiredVars { @@ -485,6 +528,34 @@ func buildAttachCloneOpts(subgraph *TemplateSubgraph, mol *types.Issue, bondType if childRef != "" { opts.ParentID = mol.ID opts.ChildRef = childRef + + // A --ref arm is nested INSIDE mol, and its ID already records that. + // Blocking it on mol as well is unsatisfiable in both directions: the + // arm waits for mol to close, and mol cannot close while it holds an + // open arm. Nesting carries the attachment, so the blocking edge is + // dropped rather than deadlocking the molecule it was bonded into. + // + // The arm therefore carries NO ordering relative to mol - it is ready + // as soon as it is spawned. That is a real loss of the "B runs after A + // completes" promise, documented in the place that makes it: this + // command's long help. docs/cli-reference/mol.md is generated from the + // release named in docs/cli-docs.pin, so it will carry the same text + // once that pin advances past this change - do not hand-write it there. + // The loss is the deliberate trade: a nested arm's only satisfiable + // relationship to its container is containment. + // + // Only DepBlocks is dropped. DepConditionalBlocks never arrives here - + // refuseConditionalRefArm above rejects it - and keeping the check + // narrow means a future bond type that does reach this point is not + // silently stripped of its edge as well. + if depType == types.DepBlocks { + opts.AttachToID = "" + opts.AttachDepType = "" + } + // A parallel arm keeps its DepParentChild edge on top of the ParentID + // nesting. The two say the same thing, so the edge is redundant rather + // than wrong - but it is what `bd dep list` reports for every parallel + // arm bonded so far, and it is satisfiable, so it stays. } return opts, nil } @@ -683,14 +754,21 @@ func resolveOrCookToSubgraph(ctx context.Context, s molReader, operand string, v return subgraph, true, nil } +// registerMolBondFlags declares bond's flags on cmd. It exists so a test can +// build an isolated command with the real flag set rather than mutating the +// package-level molBondCmd, whose flag values would then leak between tests. +func registerMolBondFlags(cmd *cobra.Command) { + cmd.Flags().String("type", types.BondTypeSequential, "Bond type: sequential, parallel, or conditional") + cmd.Flags().String("as", "", "Custom title for compound proto (proto+proto only)") + cmd.Flags().Bool("dry-run", false, "Preview what would be created") + cmd.Flags().StringArray("var", []string{}, "Variable substitution for spawned protos (key=value)") + cmd.Flags().Bool("ephemeral", false, "Force spawn as vapor (ephemeral, Ephemeral=true)") + cmd.Flags().Bool("pour", false, "Force spawn as liquid (persistent, Ephemeral=false)") + cmd.Flags().String("ref", "", "Custom child reference with {{var}} substitution (e.g., arm-{{polecat_name}})") +} + func init() { - molBondCmd.Flags().String("type", types.BondTypeSequential, "Bond type: sequential, parallel, or conditional") - molBondCmd.Flags().String("as", "", "Custom title for compound proto (proto+proto only)") - molBondCmd.Flags().Bool("dry-run", false, "Preview what would be created") - molBondCmd.Flags().StringArray("var", []string{}, "Variable substitution for spawned protos (key=value)") - molBondCmd.Flags().Bool("ephemeral", false, "Force spawn as vapor (ephemeral, Ephemeral=true)") - molBondCmd.Flags().Bool("pour", false, "Force spawn as liquid (persistent, Ephemeral=false)") - molBondCmd.Flags().String("ref", "", "Custom child reference with {{var}} substitution (e.g., arm-{{polecat_name}})") + registerMolBondFlags(molBondCmd) molCmd.AddCommand(molBondCmd) } diff --git a/cmd/bd/mol_bond_ref_attach_test.go b/cmd/bd/mol_bond_ref_attach_test.go new file mode 100644 index 000000000..36cf87f3a --- /dev/null +++ b/cmd/bd/mol_bond_ref_attach_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/types" +) + +func bondSubgraph() *TemplateSubgraph { + root := &types.Issue{ID: "proto-arm", Title: "arm"} + return &TemplateSubgraph{ + Root: root, + Issues: []*types.Issue{root}, + IssueMap: map[string]*types.Issue{root.ID: root}, + } +} + +// A --ref arm is nested under the molecule, so it must not also be blocked by +// it: the arm would wait for the molecule to close while the molecule waits for +// its own open arm, and bd ready goes empty with nothing to point at. +func TestBuildAttachCloneOptsRefArmIsNotBlockedByItsParent(t *testing.T) { + mol := &types.Issue{ID: "bd-patrol", Title: "patrol"} + + opts, err := buildAttachCloneOpts(bondSubgraph(), mol, types.BondTypeSequential, nil, "arm-ace", "tester", false, false) + if err != nil { + t.Fatalf("buildAttachCloneOpts() error = %v", err) + } + + if opts.AttachToID != "" { + t.Errorf("AttachToID = %q, want no blocking attachment for a nested arm", opts.AttachToID) + } + if opts.ParentID != mol.ID { + t.Errorf("ParentID = %q, want %q", opts.ParentID, mol.ID) + } + if opts.ChildRef != "arm-ace" { + t.Errorf("ChildRef = %q, want %q", opts.ChildRef, "arm-ace") + } +} + +// A conditional --ref arm is refused rather than degraded. Dropping a +// "conditional-blocks" edge does not lose ordering, it inverts the meaning: +// the edge says "run only if the molecule fails", so an arm without it runs +// unconditionally. A silent false dispatch is worse than the deadlock the +// sequential case trades away, and there is no safe reading of the two flags +// together, so bd refuses the combination instead of guessing. +func TestBuildAttachCloneOptsConditionalRefArmIsRefused(t *testing.T) { + mol := &types.Issue{ID: "bd-patrol", Title: "patrol"} + + _, err := buildAttachCloneOpts(bondSubgraph(), mol, types.BondTypeConditional, nil, "arm-ace", "tester", false, false) + if err == nil { + t.Fatal("buildAttachCloneOpts() error = nil, want --ref + --type conditional to be refused") + } + if !strings.Contains(err.Error(), "--ref cannot be combined with --type conditional") { + t.Errorf("error = %q, want it to name the refused flag combination", err.Error()) + } +} + +// A conditional bond WITHOUT --ref keeps its edge: a sibling arm can wait on +// the molecule, so there is nothing unsatisfiable to work around. +func TestBuildAttachCloneOptsConditionalSiblingKeepsItsEdge(t *testing.T) { + mol := &types.Issue{ID: "bd-patrol", Title: "patrol"} + + opts, err := buildAttachCloneOpts(bondSubgraph(), mol, types.BondTypeConditional, nil, "", "tester", false, false) + if err != nil { + t.Fatalf("buildAttachCloneOpts() error = %v", err) + } + + if opts.AttachToID != mol.ID { + t.Errorf("AttachToID = %q, want %q", opts.AttachToID, mol.ID) + } + if opts.AttachDepType != types.DepConditionalBlocks { + t.Errorf("AttachDepType = %q, want %q", opts.AttachDepType, types.DepConditionalBlocks) + } +} + +// The refusal also has to fire before either bond route runs, so --dry-run +// and the proxied path refuse identically rather than previewing a bond the +// real command rejects. +func TestGatherMolBondInputRefusesConditionalRefArm(t *testing.T) { + cmd := &cobra.Command{Use: "bond"} + registerMolBondFlags(cmd) + if err := cmd.Flags().Set("type", types.BondTypeConditional); err != nil { + t.Fatalf("set --type: %v", err) + } + if err := cmd.Flags().Set("ref", "arm-ace"); err != nil { + t.Fatalf("set --ref: %v", err) + } + + _, err := gatherMolBondInput(cmd, []string{"mol-arm", "bd-patrol"}) + if err == nil { + t.Fatal("gatherMolBondInput() error = nil, want --ref + --type conditional to be refused") + } + if !strings.Contains(err.Error(), "--ref cannot be combined with --type conditional") { + t.Errorf("error = %q, want it to name the refused flag combination", err.Error()) + } +} + +// Without --ref the arm is a sibling, which is satisfiable: the molecule closes +// and then the arm unblocks. That attachment must survive. +func TestBuildAttachCloneOptsSiblingKeepsBlockingAttachment(t *testing.T) { + mol := &types.Issue{ID: "bd-patrol", Title: "patrol"} + + opts, err := buildAttachCloneOpts(bondSubgraph(), mol, types.BondTypeSequential, nil, "", "tester", false, false) + if err != nil { + t.Fatalf("buildAttachCloneOpts() error = %v", err) + } + + if opts.AttachToID != mol.ID { + t.Errorf("AttachToID = %q, want %q", opts.AttachToID, mol.ID) + } + if opts.AttachDepType != types.DepBlocks { + t.Errorf("AttachDepType = %q, want %q", opts.AttachDepType, types.DepBlocks) + } + if opts.ParentID != "" { + t.Errorf("ParentID = %q, want empty without --ref", opts.ParentID) + } +} + +// A parallel bond never blocked, so nesting changes nothing about it. +func TestBuildAttachCloneOptsParallelRefArmKeepsAttachment(t *testing.T) { + mol := &types.Issue{ID: "bd-patrol", Title: "patrol"} + + opts, err := buildAttachCloneOpts(bondSubgraph(), mol, types.BondTypeParallel, nil, "arm-ace", "tester", false, false) + if err != nil { + t.Fatalf("buildAttachCloneOpts() error = %v", err) + } + + if opts.AttachToID != mol.ID { + t.Errorf("AttachToID = %q, want %q", opts.AttachToID, mol.ID) + } + if opts.AttachDepType != types.DepParentChild { + t.Errorf("AttachDepType = %q, want %q", opts.AttachDepType, types.DepParentChild) + } +} diff --git a/cmd/bd/mol_ready_gated.go b/cmd/bd/mol_ready_gated.go index f82d4a980..749a7c7ac 100644 --- a/cmd/bd/mol_ready_gated.go +++ b/cmd/bd/mol_ready_gated.go @@ -113,11 +113,36 @@ func renderGatedReadyMolecules(molecules []*GatedMolecule) error { fmt.Println() } - fmt.Println("To dispatch a molecule:") - fmt.Println(" bd sling --mol ") + stepID, listPos := firstReadyStepID(molecules) + if len(molecules) > 1 && listPos > 0 { + // The example can only name one molecule's step, so point at the entry + // it came from rather than letting it read as the single thing to + // dispatch. Naming the position instead of "the first one" keeps the + // header and the printed ID from ever disagreeing: the first listed + // molecule is not necessarily the one the example belongs to. + fmt.Printf("To dispatch a molecule, assign its ready step to an agent - for #%d above:\n", listPos) + } else { + fmt.Println("To dispatch a molecule, assign its ready step to an agent:") + } + fmt.Printf(" bd assign %s \n", stepID) return nil } +// firstReadyStepID names the ready step of the first listed molecule that has +// one, for use as the example in the dispatch hint, along with that molecule's +// 1-based position in the listing above. The position is 0 when no listed +// molecule has a ready step, in which case the returned ID is a placeholder and +// there is no entry for the hint to point at. Every molecule's own ready step is +// printed in the listing above the hint. +func firstReadyStepID(molecules []*GatedMolecule) (string, int) { + for i, mol := range molecules { + if mol.ReadyStep != nil && mol.ReadyStep.ID != "" { + return mol.ReadyStep.ID, i + 1 + } + } + return "", 0 +} + // findGateReadyMolecules finds molecules where a gate has closed and work can resume. // // Logic: diff --git a/cmd/bd/mol_ready_gated_hint_test.go b/cmd/bd/mol_ready_gated_hint_test.go new file mode 100644 index 000000000..a379edfff --- /dev/null +++ b/cmd/bd/mol_ready_gated_hint_test.go @@ -0,0 +1,134 @@ +package main + +import ( + "io" + "os" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func renderGatedHint(t *testing.T, molecules []*GatedMolecule) string { + t.Helper() + + oldStdout := os.Stdout + oldJSON := jsonOutput + jsonOutput = false + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("create stdout pipe: %v", err) + } + os.Stdout = w + + renderErr := renderGatedReadyMolecules(molecules) + + _ = w.Close() + var b strings.Builder + _, _ = io.Copy(&b, r) + _ = r.Close() + os.Stdout = oldStdout + jsonOutput = oldJSON + + if renderErr != nil { + t.Fatalf("renderGatedReadyMolecules: %v", renderErr) + } + return b.String() +} + +func hintCommandLine(t *testing.T, out string) string { + t.Helper() + for _, line := range strings.Split(out, "\n") { + if trimmed := strings.TrimSpace(line); strings.HasPrefix(trimmed, "bd ") { + return trimmed + } + } + t.Fatalf("no dispatch command found in output:\n%s", out) + return "" +} + +// The dispatch hint must name a command bd actually has. It previously printed +// "bd sling", which has never existed in this binary. +func TestGatedReadyHintNamesRealCommand(t *testing.T) { + out := renderGatedHint(t, []*GatedMolecule{{ + MoleculeID: "test-mol1", + MoleculeTitle: "Gated molecule", + ReadyStep: &types.Issue{ID: "test-step1", Title: "Resume work"}, + }}) + + fields := strings.Fields(hintCommandLine(t, out)) + if len(fields) < 2 { + t.Fatalf("dispatch hint is not a runnable command: %q", strings.Join(fields, " ")) + } + if _, _, err := rootCmd.Find(fields[1:2]); err != nil { + t.Errorf("dispatch hint names unknown command %q: %v", fields[1], err) + } +} + +func TestGatedReadyHintUsesReadyStepID(t *testing.T) { + out := renderGatedHint(t, []*GatedMolecule{{ + MoleculeID: "test-mol1", + MoleculeTitle: "Gated molecule", + ReadyStep: &types.Issue{ID: "test-step1", Title: "Resume work"}, + }}) + + if got := hintCommandLine(t, out); !strings.Contains(got, "test-step1") { + t.Errorf("dispatch hint = %q, want it to name ready step test-step1", got) + } +} + +// With more than one molecule listed, the header names which listed entry the +// example came from, so it cannot disagree with the ID printed beneath it. The +// first listed molecule is not necessarily the one that has a ready step. +func TestGatedReadyHintHeaderNamesTheEntryItPrinted(t *testing.T) { + gated := func(id, step string) *GatedMolecule { + mol := &GatedMolecule{MoleculeID: id, MoleculeTitle: "Gated molecule"} + if step != "" { + mol.ReadyStep = &types.Issue{ID: step, Title: "Resume work"} + } + return mol + } + + tests := []struct { + name string + molecules []*GatedMolecule + wantEntry string + wantStep string + }{ + { + name: "first listed molecule has the ready step", + molecules: []*GatedMolecule{gated("test-mol1", "test-step1"), gated("test-mol2", "test-step2")}, + wantEntry: "#1 above", + wantStep: "test-step1", + }, + { + name: "example comes from a later molecule", + molecules: []*GatedMolecule{gated("test-mol1", ""), gated("test-mol2", "test-step2")}, + wantEntry: "#2 above", + wantStep: "test-step2", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + out := renderGatedHint(t, tt.molecules) + if !strings.Contains(out, tt.wantEntry) { + t.Errorf("hint header does not name listing entry %q:\n%s", tt.wantEntry, out) + } + if got := hintCommandLine(t, out); !strings.Contains(got, tt.wantStep) { + t.Errorf("dispatch hint = %q, want it to name ready step %s", got, tt.wantStep) + } + }) + } +} + +func TestGatedReadyHintWithoutReadyStep(t *testing.T) { + out := renderGatedHint(t, []*GatedMolecule{{ + MoleculeID: "test-mol1", + MoleculeTitle: "Gated molecule", + }}) + + if got := hintCommandLine(t, out); !strings.Contains(got, "") { + t.Errorf("dispatch hint = %q, want a placeholder when no ready step is known", got) + } +}