feat(mol): support bd mol commands in proxied-server mode

Introduces a narrow molReader/molWriter port (cmd/bd/mol_port.go) whose
method names match storage.DoltStorage's own, so the embedded/server
backend satisfies it structurally with no wrapping, while a uow-backed
adapter bridges proxied-server mode's UnitOfWork. All 16 `bd mol`
subcommands (show, current, progress, last-activity, stale,
ready --gated, distill, seed, pour, wisp/wisp create/list/gc, bond,
squash, burn) now work under --proxied-server.

Also dedupes close_proxied_server.go's drifted reimplementations of
loadTemplateSubgraph/getMoleculeProgress/AdvanceToNextStep (which had
fallen out of sync with the embedded versions) and ready_proxied_server.go's
duplicate gate-ready query, routing both through the shared functions.

Wires FindWispDependentsRecursive into domain.IssueUseCase, delegating to
the existing issueops.FindWispDependentsRecursiveInTx query (widened from
*sql.Tx to the existing DBTX interface) so `bd mol wisp gc`'s cascade
works under proxied mode too.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
coffeegoddd☕️✨ 2026-07-24 15:39:21 -07:00
commit 71516ec479
23 changed files with 2397 additions and 1124 deletions

View file

@ -279,7 +279,7 @@ the flags appear in the command line.`,
if continueFlag && len(resolvedIDs) == 1 && closedForCommand {
autoClaim := !noAuto
result, err := AdvanceToNextStep(ctx, postCloseStore, resolvedIDs[0], autoClaim, actor)
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(postCloseStore), resolvedIDs[0], autoClaim, actor)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not advance to next step: %v\n", err)
} else if result != nil {

View file

@ -350,7 +350,7 @@ func closeProxiedClaimNext(ctx context.Context, uw uow.UnitOfWork) (*types.Issue
}
func closeProxiedContinue(ctx context.Context, uw uow.UnitOfWork, closedID string, autoClaim bool) (*ContinueResult, string) {
result, err := proxiedAdvanceToNextStep(ctx, uw, closedID, autoClaim, actor)
result, err := AdvanceToNextStep(ctx, newUOWMolWriter(uw), closedID, autoClaim, actor)
if err != nil {
return nil, fmt.Sprintf("could not advance to next step: %v", err)
}
@ -374,7 +374,7 @@ func autoCloseProxiedCompletedMolecule(ctx context.Context, uw uow.UnitOfWork, c
return nil
}
progress, err := proxiedGetMoleculeProgress(ctx, uw, moleculeID)
progress, err := getMoleculeProgress(ctx, uowMolReader{uw: uw}, moleculeID)
if err != nil {
return nil
}
@ -391,213 +391,5 @@ func autoCloseProxiedCompletedMolecule(ctx context.Context, uw uow.UnitOfWork, c
}
func proxiedFindParentMolecule(ctx context.Context, uw uow.UnitOfWork, issueID string) string {
current := issueID
for depth := 0; depth < 50; depth++ {
deps, err := uw.DependencyUseCase().GetForIssueIDs(ctx, []string{current})
if err != nil {
return ""
}
var parent string
for _, dep := range deps[current] {
if dep.Type == types.DepParentChild {
parent = dep.DependsOnID
break
}
}
if parent == "" {
if current == issueID {
return ""
}
return current
}
current = parent
}
return current
}
func proxiedLoadTemplateSubgraph(ctx context.Context, uw uow.UnitOfWork, templateID string) (*TemplateSubgraph, error) {
root, err := uw.IssueUseCase().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},
}
visited := map[string]bool{root.ID: true}
if err := proxiedLoadDescendants(ctx, uw, subgraph, root.ID, visited); err != nil {
return nil, err
}
for _, issue := range subgraph.Issues {
deps, err := uw.DependencyUseCase().GetForIssueIDs(ctx, []string{issue.ID})
if err != nil {
return nil, fmt.Errorf("failed to get dependencies for %s: %w", issue.ID, err)
}
for _, dep := range deps[issue.ID] {
if _, ok := subgraph.IssueMap[dep.DependsOnID]; ok {
subgraph.Dependencies = append(subgraph.Dependencies, dep)
}
}
}
return subgraph, nil
}
func proxiedLoadDescendants(ctx context.Context, uw uow.UnitOfWork, subgraph *TemplateSubgraph, parentID string, visited map[string]bool) error {
dependents, err := uw.DependencyUseCase().ListWithIssueMetadata(ctx, parentID, domain.DepListFilter{
Direction: domain.DepDirectionIn,
})
if err != nil {
return fmt.Errorf("failed to get dependents of %s: %w", parentID, err)
}
for _, dependent := range dependents {
if dependent.DependencyType != types.DepParentChild {
continue
}
if _, exists := subgraph.IssueMap[dependent.ID]; exists {
continue
}
if visited[dependent.ID] {
continue
}
child := dependent.Issue
subgraph.Issues = append(subgraph.Issues, &child)
subgraph.IssueMap[child.ID] = &child
visited[child.ID] = true
if err := proxiedLoadDescendants(ctx, uw, subgraph, child.ID, visited); err != nil {
return err
}
}
return nil
}
func proxiedGetMoleculeProgress(ctx context.Context, uw uow.UnitOfWork, moleculeID string) (*MoleculeProgress, error) {
subgraph, err := proxiedLoadTemplateSubgraph(ctx, uw, moleculeID)
if err != nil {
return nil, err
}
progress := &MoleculeProgress{
MoleculeID: subgraph.Root.ID,
MoleculeTitle: subgraph.Root.Title,
Assignee: subgraph.Root.Assignee,
Total: len(subgraph.Issues) - 1,
}
analysis := analyzeMoleculeParallel(subgraph)
readyIDs := make(map[string]bool)
for id, info := range analysis.Steps {
if info.IsReady {
readyIDs[id] = true
}
}
var steps []*StepStatus
for _, issue := range subgraph.Issues {
if issue.ID == subgraph.Root.ID {
continue
}
step := &StepStatus{Issue: issue}
switch issue.Status {
case types.StatusClosed:
step.Status = "done"
progress.Completed++
case types.StatusInProgress:
step.Status = "current"
step.IsCurrent = true
progress.CurrentStep = issue
case types.StatusBlocked:
step.Status = "blocked"
default:
if readyIDs[issue.ID] {
step.Status = "ready"
if progress.NextStep == nil {
progress.NextStep = issue
}
} else {
step.Status = "pending"
}
}
steps = append(steps, step)
}
sortStepsByDependencyOrder(steps, subgraph)
progress.Steps = steps
if progress.CurrentStep == nil && progress.NextStep == nil {
for _, step := range steps {
if step.Status == "ready" {
progress.NextStep = step.Issue
break
}
}
}
return progress, nil
}
func proxiedAdvanceToNextStep(ctx context.Context, uw uow.UnitOfWork, closedStepID string, autoClaim bool, actorName string) (*ContinueResult, error) {
closedStep, err := uw.IssueUseCase().GetIssue(ctx, closedStepID)
if err != nil || closedStep == nil {
wisp, wErr := uw.IssueUseCase().GetWisp(ctx, closedStepID)
if wErr != nil || wisp == nil {
return nil, fmt.Errorf("could not get closed step: %w", err)
}
closedStep = wisp
}
result := &ContinueResult{ClosedStep: closedStep}
moleculeID := proxiedFindParentMolecule(ctx, uw, closedStepID)
if moleculeID == "" {
return nil, nil
}
result.MoleculeID = moleculeID
progress, err := proxiedGetMoleculeProgress(ctx, uw, moleculeID)
if err != nil {
return nil, fmt.Errorf("could not load molecule: %w", err)
}
if progress.Completed >= progress.Total {
result.MolComplete = true
return result, nil
}
var readySteps []*types.Issue
for _, step := range progress.Steps {
if step.Status == "ready" {
readySteps = append(readySteps, step.Issue)
}
}
if len(readySteps) == 0 {
return result, nil
}
result.NextStep = readySteps[0]
if !autoClaim {
return result, nil
}
for _, candidate := range readySteps {
_, claimErr := uw.IssueUseCase().ClaimIssueIfOpen(ctx, candidate.ID, actorName)
if claimErr == nil {
result.NextStep = candidate
result.AutoAdvanced = true
return result, nil
}
if errors.Is(claimErr, storage.ErrAlreadyClaimed) || errors.Is(claimErr, storage.ErrNotClaimable) {
continue
}
return result, nil
}
return result, nil
return findParentMolecule(ctx, uowMolReader{uw: uw}, issueID)
}

View file

@ -11,7 +11,6 @@ import (
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
)
var molBondCmd = &cobra.Command{
@ -84,9 +83,6 @@ type BondResult struct {
}
func runMolBond(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol bond is not supported in proxied-server mode")
}
CheckReadonly("mol bond")
evt := metrics.NewCommandEvent("mol-bond")
@ -96,157 +92,173 @@ func runMolBond(cmd *cobra.Command, args []string) error {
}
}()
in, err := gatherMolBondInput(cmd, args)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if usesProxiedServer() {
return runMolBondProxiedServer(rootCtx, in)
}
ctx := rootCtx
if store == nil {
return HandleErrorRespectJSON("no database connection")
}
bondType, _ := cmd.Flags().GetString("type")
customTitle, _ := cmd.Flags().GetString("as")
dryRun, _ := cmd.Flags().GetBool("dry-run")
varFlags, _ := cmd.Flags().GetStringArray("var")
ephemeral, _ := cmd.Flags().GetBool("ephemeral")
pour, _ := cmd.Flags().GetBool("pour")
childRef, _ := cmd.Flags().GetString("ref")
if ephemeral && pour {
return HandleErrorRespectJSON("cannot use both --ephemeral and --pour")
}
if bondType != types.BondTypeSequential && bondType != types.BondTypeParallel && bondType != types.BondTypeConditional {
return HandleErrorRespectJSON("invalid bond type '%s', must be: sequential, parallel, or conditional", bondType)
}
vars := make(map[string]string)
for _, v := range varFlags {
parts := strings.SplitN(v, "=", 2)
if len(parts) != 2 {
return HandleErrorRespectJSON("invalid variable format '%s', expected 'key=value'", v)
}
vars[parts[0]] = parts[1]
}
if dryRun {
issueA, formulaA, err := resolveOrDescribe(ctx, store, args[0])
if in.dryRun {
issueA, formulaA, err := resolveOrDescribe(ctx, store, in.argA)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
issueB, formulaB, err := resolveOrDescribe(ctx, store, args[1])
issueB, formulaB, err := resolveOrDescribe(ctx, store, in.argB)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
idA := args[0]
idB := args[1]
aIsProto := false
bIsProto := false
if issueA != nil {
idA = issueA.ID
aIsProto = isProto(issueA)
}
if issueB != nil {
idB = issueB.ID
bIsProto = isProto(issueB)
}
// Formulas are treated as protos for dry-run display
if formulaA != "" {
aIsProto = true
}
if formulaB != "" {
bIsProto = true
}
fmt.Printf("\nDry run: bond %s + %s\n", idA, idB)
if formulaA != "" {
fmt.Printf(" A: %s (formula → will cook as proto)\n", formulaA)
} else if issueA != nil {
fmt.Printf(" A: %s (%s)\n", issueA.Title, operandType(aIsProto))
}
if formulaB != "" {
fmt.Printf(" B: %s (formula → will cook as proto)\n", formulaB)
} else if issueB != nil {
fmt.Printf(" B: %s (%s)\n", issueB.Title, operandType(bIsProto))
}
fmt.Printf(" Bond type: %s\n", bondType)
if ephemeral {
fmt.Printf(" Phase override: vapor (--ephemeral)\n")
} else if pour {
fmt.Printf(" Phase override: liquid (--pour)\n")
}
if childRef != "" {
resolvedRef := substituteVariables(childRef, vars)
fmt.Printf(" Child ref: %s (resolved: %s)\n", childRef, resolvedRef)
}
if aIsProto && bIsProto {
fmt.Printf(" Result: compound proto\n")
if customTitle != "" {
fmt.Printf(" Custom title: %s\n", customTitle)
}
} else if aIsProto || bIsProto {
fmt.Printf(" Result: spawn proto, attach to molecule\n")
} else {
fmt.Printf(" Result: compound molecule\n")
}
if formulaA != "" || formulaB != "" {
fmt.Printf("\n Note: Cooked formulas are ephemeral and deleted after bonding.\n")
}
renderMolBondDryRun(in, issueA, formulaA, issueB, formulaB)
return nil
}
subgraphA, cookedA, err := resolveOrCookToSubgraph(ctx, store, args[0], vars)
subgraphA, cookedA, err := resolveOrCookToSubgraph(ctx, store, in.argA, in.vars)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
subgraphB, cookedB, err := resolveOrCookToSubgraph(ctx, store, args[1], vars)
subgraphB, cookedB, err := resolveOrCookToSubgraph(ctx, store, in.argB, in.vars)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
// No cleanup needed - in-memory subgraphs don't pollute the DB
issueA := subgraphA.Root
issueB := subgraphB.Root
idA := issueA.ID
idB := issueB.ID
// Determine operand types
aIsProto := issueA.IsTemplate || cookedA
bIsProto := issueB.IsTemplate || cookedB
// Dispatch based on operand types
// All operations use the main store; wisp flag determines ephemeral vs persistent
var result *BondResult
switch {
case aIsProto && bIsProto:
// Compound protos are templates - always persistent
// Note: Proto+proto bonding from formulas is a DB operation, not in-memory
result, err = bondProtoProto(ctx, store, issueA, issueB, bondType, customTitle, actor)
result, err = bondProtoProto(ctx, store, issueA, issueB, in.bondType, in.customTitle, actor)
case aIsProto && !bIsProto:
// Pass subgraph directly if cooked from formula
if cookedA {
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphA, issueA, issueB, bondType, vars, childRef, actor, ephemeral, pour)
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphA, issueA, issueB, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
} else {
result, err = bondProtoMol(ctx, store, issueA, issueB, bondType, vars, childRef, actor, ephemeral, pour)
result, err = bondProtoMol(ctx, store, issueA, issueB, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
}
case !aIsProto && bIsProto:
// Pass subgraph directly if cooked from formula
if cookedB {
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphB, issueB, issueA, bondType, vars, childRef, actor, ephemeral, pour)
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphB, issueB, issueA, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
} else {
result, err = bondMolProto(ctx, store, issueA, issueB, bondType, vars, childRef, actor, ephemeral, pour)
result, err = bondMolProto(ctx, store, issueA, issueB, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
}
default:
result, err = bondMolMol(ctx, store, issueA, issueB, bondType, actor)
result, err = bondMolMol(ctx, store, issueA, issueB, in.bondType, actor)
}
if err != nil {
return HandleErrorRespectJSON("bonding: %v", err)
}
renderMolBondResult(result, issueA.ID, issueB.ID, in.ephemeral, in.pour)
return nil
}
type molBondInput struct {
argA string
argB string
bondType string
customTitle string
dryRun bool
vars map[string]string
ephemeral bool
pour bool
childRef string
}
func gatherMolBondInput(cmd *cobra.Command, args []string) (molBondInput, error) {
in := molBondInput{argA: args[0], argB: args[1]}
in.bondType, _ = cmd.Flags().GetString("type")
in.customTitle, _ = cmd.Flags().GetString("as")
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
in.ephemeral, _ = cmd.Flags().GetBool("ephemeral")
in.pour, _ = cmd.Flags().GetBool("pour")
in.childRef, _ = cmd.Flags().GetString("ref")
if in.ephemeral && in.pour {
return in, fmt.Errorf("cannot use both --ephemeral and --pour")
}
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)
}
varFlags, _ := cmd.Flags().GetStringArray("var")
vars, err := parseVarFlags(varFlags)
if err != nil {
return in, err
}
in.vars = vars
return in, nil
}
func renderMolBondDryRun(in molBondInput, issueA *types.Issue, formulaA string, issueB *types.Issue, formulaB string) {
idA := in.argA
idB := in.argB
aIsProto := false
bIsProto := false
if issueA != nil {
idA = issueA.ID
aIsProto = isProto(issueA)
}
if issueB != nil {
idB = issueB.ID
bIsProto = isProto(issueB)
}
if formulaA != "" {
aIsProto = true
}
if formulaB != "" {
bIsProto = true
}
fmt.Printf("\nDry run: bond %s + %s\n", idA, idB)
if formulaA != "" {
fmt.Printf(" A: %s (formula → will cook as proto)\n", formulaA)
} else if issueA != nil {
fmt.Printf(" A: %s (%s)\n", issueA.Title, operandType(aIsProto))
}
if formulaB != "" {
fmt.Printf(" B: %s (formula → will cook as proto)\n", formulaB)
} else if issueB != nil {
fmt.Printf(" B: %s (%s)\n", issueB.Title, operandType(bIsProto))
}
fmt.Printf(" Bond type: %s\n", in.bondType)
if in.ephemeral {
fmt.Printf(" Phase override: vapor (--ephemeral)\n")
} else if in.pour {
fmt.Printf(" Phase override: liquid (--pour)\n")
}
if in.childRef != "" {
resolvedRef := substituteVariables(in.childRef, in.vars)
fmt.Printf(" Child ref: %s (resolved: %s)\n", in.childRef, resolvedRef)
}
if aIsProto && bIsProto {
fmt.Printf(" Result: compound proto\n")
if in.customTitle != "" {
fmt.Printf(" Custom title: %s\n", in.customTitle)
}
} else if aIsProto || bIsProto {
fmt.Printf(" Result: spawn proto, attach to molecule\n")
} else {
fmt.Printf(" Result: compound molecule\n")
}
if formulaA != "" || formulaB != "" {
fmt.Printf("\n Note: Cooked formulas are ephemeral and deleted after bonding.\n")
}
}
func renderMolBondResult(result *BondResult, idA, idB string, ephemeral, pour bool) {
if jsonOutput {
return outputJSON(result)
_ = outputJSON(result)
return
}
fmt.Printf("%s Bonded: %s + %s\n", ui.RenderPass("✓"), idA, idB)
@ -259,7 +271,6 @@ func runMolBond(cmd *cobra.Command, args []string) error {
} else if pour {
fmt.Printf(" Phase: liquid (persistent, Ephemeral=false)\n")
}
return nil
}
// isProto checks if an issue is a proto (has the template label)
@ -282,6 +293,22 @@ func operandType(isProtoIssue bool) string {
// bondProtoProto bonds two protos to create a compound proto
func bondProtoProto(ctx context.Context, s storage.DoltStorage, protoA, protoB *types.Issue, bondType, customTitle, actorName string) (*BondResult, error) {
var result *BondResult
err := transact(ctx, s, fmt.Sprintf("bd: bond protos %s + %s", protoA.ID, protoB.ID), func(tx storage.Transaction) error {
r, err := bondProtoProtoInto(ctx, storeMolWriter{DoltStorage: s, tx: tx}, protoA, protoB, bondType, customTitle, actorName)
if err != nil {
return err
}
result = r
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
func bondProtoProtoInto(ctx context.Context, w molWriter, protoA, protoB *types.Issue, bondType, customTitle, actorName string) (*BondResult, error) {
// Create compound proto: a new root that references both protos as children
// The compound root will be a new issue that ties them together
compoundTitle := fmt.Sprintf("Compound: %s + %s", protoA.Title, protoB.Title)
@ -289,72 +316,63 @@ func bondProtoProto(ctx context.Context, s storage.DoltStorage, protoA, protoB *
compoundTitle = customTitle
}
var compoundID string
err := transact(ctx, s, fmt.Sprintf("bd: bond protos %s + %s", protoA.ID, protoB.ID), func(tx storage.Transaction) error {
// Create compound root issue
compound := &types.Issue{
Title: compoundTitle,
Description: fmt.Sprintf("Compound proto bonding %s and %s", protoA.ID, protoB.ID),
Status: types.StatusOpen,
Priority: minPriority(protoA.Priority, protoB.Priority),
IssueType: types.TypeEpic,
BondedFrom: []types.BondRef{
{SourceID: protoA.ID, BondType: bondType, BondPoint: ""},
{SourceID: protoB.ID, BondType: bondType, BondPoint: ""},
},
}
if err := tx.CreateIssue(ctx, compound, actorName); err != nil {
return fmt.Errorf("creating compound: %w", err)
}
compoundID = compound.ID
// Create compound root issue
compound := &types.Issue{
Title: compoundTitle,
Description: fmt.Sprintf("Compound proto bonding %s and %s", protoA.ID, protoB.ID),
Status: types.StatusOpen,
Priority: minPriority(protoA.Priority, protoB.Priority),
IssueType: types.TypeEpic,
BondedFrom: []types.BondRef{
{SourceID: protoA.ID, BondType: bondType, BondPoint: ""},
{SourceID: protoB.ID, BondType: bondType, BondPoint: ""},
},
}
if err := w.CreateIssue(ctx, compound, actorName); err != nil {
return nil, fmt.Errorf("creating compound: %w", err)
}
compoundID := compound.ID
// Add template label (labels are stored separately, not in issue table)
if err := tx.AddLabel(ctx, compoundID, MoleculeLabel, actorName); err != nil {
return fmt.Errorf("adding template label: %w", err)
}
// Add template label (labels are stored separately, not in issue table)
if err := w.AddLabel(ctx, compoundID, MoleculeLabel, actorName); err != nil {
return nil, fmt.Errorf("adding template label: %w", err)
}
// Add parent-child dependencies from compound to both proto roots
depA := &types.Dependency{
IssueID: protoA.ID,
DependsOnID: compoundID,
Type: types.DepParentChild,
}
if err := tx.AddDependency(ctx, depA, actorName); err != nil {
return fmt.Errorf("linking proto A: %w", err)
}
// Add parent-child dependencies from compound to both proto roots
depA := &types.Dependency{
IssueID: protoA.ID,
DependsOnID: compoundID,
Type: types.DepParentChild,
}
if err := w.AddDependency(ctx, depA, actorName); err != nil {
return nil, fmt.Errorf("linking proto A: %w", err)
}
depB := &types.Dependency{
depB := &types.Dependency{
IssueID: protoB.ID,
DependsOnID: compoundID,
Type: types.DepParentChild,
}
if err := w.AddDependency(ctx, depB, actorName); err != nil {
return nil, fmt.Errorf("linking proto B: %w", err)
}
// For sequential/conditional bonding, add blocking dependency: B blocks on A
// Sequential: B runs after A completes (any outcome)
// Conditional: B runs only if A fails
if bondType == types.BondTypeSequential || bondType == types.BondTypeConditional {
depType := types.DepBlocks
if bondType == types.BondTypeConditional {
depType = types.DepConditionalBlocks
}
seqDep := &types.Dependency{
IssueID: protoB.ID,
DependsOnID: compoundID,
Type: types.DepParentChild,
DependsOnID: protoA.ID,
Type: depType,
}
if err := tx.AddDependency(ctx, depB, actorName); err != nil {
return fmt.Errorf("linking proto B: %w", err)
if err := w.AddDependency(ctx, seqDep, actorName); err != nil {
return nil, fmt.Errorf("adding sequence dep: %w", err)
}
// For sequential/conditional bonding, add blocking dependency: B blocks on A
// Sequential: B runs after A completes (any outcome)
// Conditional: B runs only if A fails
if bondType == types.BondTypeSequential || bondType == types.BondTypeConditional {
depType := types.DepBlocks
if bondType == types.BondTypeConditional {
depType = types.DepConditionalBlocks
}
seqDep := &types.Dependency{
IssueID: protoB.ID,
DependsOnID: protoA.ID,
Type: depType,
}
if err := tx.AddDependency(ctx, seqDep, actorName); err != nil {
return fmt.Errorf("adding sequence dep: %w", err)
}
}
return nil
})
if err != nil {
return nil, err
}
return &BondResult{
@ -374,17 +392,59 @@ func bondProtoMol(ctx context.Context, s storage.DoltStorage, proto, mol *types.
// bondProtoMolWithSubgraph is the internal implementation that accepts a pre-loaded subgraph.
func bondProtoMolWithSubgraph(ctx context.Context, s storage.DoltStorage, protoSubgraph *TemplateSubgraph, proto, mol *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (*BondResult, error) {
// Use provided subgraph or load from DB
subgraph := protoSubgraph
if subgraph == nil {
if protoSubgraph == nil {
var err error
subgraph, err = loadTemplateSubgraph(ctx, s, proto.ID)
protoSubgraph, err = loadTemplateSubgraph(ctx, s, proto.ID)
if err != nil {
return nil, fmt.Errorf("loading proto: %w", err)
}
}
opts, err := buildAttachCloneOpts(protoSubgraph, mol, bondType, vars, childRef, actorName, ephemeralFlag, pourFlag)
if err != nil {
return nil, err
}
spawnResult, err := cloneSubgraph(ctx, s, protoSubgraph, opts)
if err != nil {
return nil, fmt.Errorf("spawning and attaching proto: %w", err)
}
return &BondResult{
ResultID: mol.ID,
ResultType: "compound_molecule",
BondType: bondType,
Spawned: spawnResult.Created,
IDMapping: spawnResult.IDMapping,
}, nil
}
// Check for missing variables
// bondProtoMolAttachInto is bondProtoMolWithSubgraph's counterpart for
// callers that already have an open molWriter (the proxied-server duals),
// so spawn + attach happen inside the caller's own transaction.
func bondProtoMolAttachInto(ctx context.Context, w molWriter, protoSubgraph *TemplateSubgraph, proto, mol *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (*BondResult, error) {
if protoSubgraph == nil {
var err error
protoSubgraph, err = loadTemplateSubgraph(ctx, w, proto.ID)
if err != nil {
return nil, fmt.Errorf("loading proto: %w", err)
}
}
opts, err := buildAttachCloneOpts(protoSubgraph, mol, bondType, vars, childRef, actorName, ephemeralFlag, pourFlag)
if err != nil {
return nil, err
}
spawnResult, err := cloneSubgraphInto(ctx, w, protoSubgraph, opts)
if err != nil {
return nil, fmt.Errorf("spawning and attaching proto: %w", err)
}
return &BondResult{
ResultID: mol.ID,
ResultType: "compound_molecule",
BondType: bondType,
Spawned: spawnResult.Created,
IDMapping: spawnResult.IDMapping,
}, nil
}
func buildAttachCloneOpts(subgraph *TemplateSubgraph, mol *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (CloneOptions, error) {
requiredVars := extractAllVariables(subgraph)
var missingVars []string
for _, v := range requiredVars {
@ -393,22 +453,16 @@ func bondProtoMolWithSubgraph(ctx context.Context, s storage.DoltStorage, protoS
}
}
if len(missingVars) > 0 {
return nil, fmt.Errorf("missing required variables: %s (use --var)", strings.Join(missingVars, ", "))
return CloneOptions{}, fmt.Errorf("missing required variables: %s (use --var)", strings.Join(missingVars, ", "))
}
// Determine ephemeral flag based on explicit flags or target's phase
// --ephemeral: force ephemeral=true, --pour: force ephemeral=false, neither: follow target
makeEphemeral := mol.Ephemeral // Default: follow target's phase
makeEphemeral := mol.Ephemeral
if ephemeralFlag {
makeEphemeral = true
} else if pourFlag {
makeEphemeral = false
}
// Determine dependency type for attachment
// Sequential: use blocks (B runs after A completes)
// Conditional: use conditional-blocks (B runs only if A fails)
// Parallel: use parent-child (organizational, no blocking)
var depType types.DependencyType
switch bondType {
case types.BondTypeSequential:
@ -419,8 +473,6 @@ func bondProtoMolWithSubgraph(ctx context.Context, s storage.DoltStorage, protoS
depType = types.DepParentChild
}
// Build CloneOptions for spawning
// AttachToID ensures spawn + attach happen in a single transaction (bd-wvplu)
opts := CloneOptions{
Vars: vars,
Actor: actorName,
@ -428,26 +480,11 @@ func bondProtoMolWithSubgraph(ctx context.Context, s storage.DoltStorage, protoS
AttachToID: mol.ID,
AttachDepType: depType,
}
// Dynamic bonding: use custom IDs if childRef is provided
if childRef != "" {
opts.ParentID = mol.ID
opts.ChildRef = childRef
}
// Spawn the proto and atomically attach to molecule
spawnResult, err := spawnMoleculeWithOptions(ctx, s, subgraph, opts)
if err != nil {
return nil, fmt.Errorf("spawning and attaching proto: %w", err)
}
return &BondResult{
ResultID: mol.ID,
ResultType: "compound_molecule",
BondType: bondType,
Spawned: spawnResult.Created,
IDMapping: spawnResult.IDMapping,
}, nil
return opts, nil
}
// bondMolProto bonds a molecule to a proto (symmetric with bondProtoMol)
@ -460,7 +497,7 @@ func bondMolProto(ctx context.Context, s storage.DoltStorage, mol, proto *types.
// would create a cycle in the dependency graph. It does a BFS from newDependsOnID
// following "depends on" edges; if newDepID is reachable, a cycle would be formed.
// Returns (hasCycle, cyclePath) where cyclePath shows the chain if found.
func wouldCreateCycle(ctx context.Context, s storage.DoltStorage, newDepID, newDependsOnID string) (bool, []string) {
func wouldCreateCycle(ctx context.Context, s molReader, newDepID, newDependsOnID string) (bool, []string) {
visited := map[string]bool{newDependsOnID: true}
// parent tracks how we reached each node, for path reconstruction.
parent := map[string]string{newDependsOnID: ""}
@ -504,48 +541,52 @@ func wouldCreateCycle(ctx context.Context, s storage.DoltStorage, newDepID, newD
// bondMolMol bonds two molecules together.
// It checks for transitive cycles in the dependency graph (GH#2719).
func bondMolMol(ctx context.Context, s storage.DoltStorage, molA, molB *types.Issue, bondType, actorName string) (*BondResult, error) {
// The bond creates: molB depends on molA (IssueID=molB.ID, DependsOnID=molA.ID).
// A cycle exists if molA already transitively depends on molB, because then
// adding molB→molA would close the loop: molA→...→molB→molA.
hasCycle, cyclePath := wouldCreateCycle(ctx, s, molB.ID, molA.ID)
if hasCycle {
if hasCycle, cyclePath := wouldCreateCycle(ctx, s, molB.ID, molA.ID); hasCycle {
return nil, fmt.Errorf("cannot bond %s → %s: would create a transitive dependency cycle: %s",
molA.ID, molB.ID, strings.Join(cyclePath, " → "))
}
var result *BondResult
err := transact(ctx, s, fmt.Sprintf("bd: bond molecules %s + %s", molA.ID, molB.ID), func(tx storage.Transaction) error {
// Add dependency: B links to A
// Sequential: use blocks (B runs after A completes)
// Conditional: use conditional-blocks (B runs only if A fails)
// Parallel: use parent-child (organizational, no blocking)
// Note: Schema only allows one dependency per (issue_id, target) pair (target = typed column)
var depType types.DependencyType
switch bondType {
case types.BondTypeSequential:
depType = types.DepBlocks
case types.BondTypeConditional:
depType = types.DepConditionalBlocks
default:
depType = types.DepParentChild
r, err := bondMolMolInto(ctx, storeMolWriter{DoltStorage: s, tx: tx}, molA, molB, bondType, actorName)
if err != nil {
return err
}
dep := &types.Dependency{
IssueID: molB.ID,
DependsOnID: molA.ID,
Type: depType,
}
if err := tx.AddDependency(ctx, dep, actorName); err != nil {
return fmt.Errorf("linking molecules: %w", err)
}
// Note: bonded_from field tracking is not yet supported by storage layer.
// The dependency relationship captures the bonding semantics.
result = r
return nil
})
if err != nil {
return nil, fmt.Errorf("linking molecules: %w", err)
}
return result, nil
}
func bondMolMolInto(ctx context.Context, w molWriter, molA, molB *types.Issue, bondType, actorName string) (*BondResult, error) {
// Add dependency: B links to A
// Sequential: use blocks (B runs after A completes)
// Conditional: use conditional-blocks (B runs only if A fails)
// Parallel: use parent-child (organizational, no blocking)
// Note: Schema only allows one dependency per (issue_id, target) pair (target = typed column)
var depType types.DependencyType
switch bondType {
case types.BondTypeSequential:
depType = types.DepBlocks
case types.BondTypeConditional:
depType = types.DepConditionalBlocks
default:
depType = types.DepParentChild
}
dep := &types.Dependency{
IssueID: molB.ID,
DependsOnID: molA.ID,
Type: depType,
}
if err := w.AddDependency(ctx, dep, actorName); err != nil {
return nil, fmt.Errorf("linking molecules: %w", err)
}
// Note: bonded_from field tracking is not yet supported by storage layer.
// The dependency relationship captures the bonding semantics.
return &BondResult{
ResultID: molA.ID,
ResultType: "compound_molecule",
@ -564,9 +605,9 @@ func minPriority(a, b int) int {
// resolveOrDescribe checks if an operand is an issue or formula without cooking.
// Used for dry-run mode. Returns (issue, formulaName, error).
// If it's an issue, issue is set. If it's a formula, formulaName is set.
func resolveOrDescribe(ctx context.Context, s storage.DoltStorage, operand string) (*types.Issue, string, error) {
func resolveOrDescribe(ctx context.Context, s molReader, operand string) (*types.Issue, string, error) {
// First, try to resolve as an existing issue
id, err := utils.ResolvePartialID(ctx, s, operand)
id, err := resolveMolID(ctx, s, operand)
if err == nil {
issue, err := s.GetIssue(ctx, id)
if err == nil {
@ -593,9 +634,9 @@ func resolveOrDescribe(ctx context.Context, s storage.DoltStorage, operand strin
//
// The vars parameter is used for step condition filtering (bd-7zka.1).
// This implements gt-4v1eo: formulas are cooked to in-memory subgraphs (no DB storage).
func resolveOrCookToSubgraph(ctx context.Context, s storage.DoltStorage, operand string, vars map[string]string) (*TemplateSubgraph, bool, error) {
func resolveOrCookToSubgraph(ctx context.Context, s molReader, operand string, vars map[string]string) (*TemplateSubgraph, bool, error) {
// First, try to resolve as an existing issue
id, err := utils.ResolvePartialID(ctx, s, operand)
id, err := resolveMolID(ctx, s, operand)
if err == nil {
issue, err := s.GetIssue(ctx, id)
if err == nil {

View file

@ -56,9 +56,6 @@ type BatchBurnResult struct {
}
func runMolBurn(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol burn is not supported in proxied-server mode")
}
CheckReadonly("mol burn")
evt := metrics.NewCommandEvent("mol-burn")
@ -68,18 +65,22 @@ func runMolBurn(cmd *cobra.Command, args []string) error {
}
}()
ctx := rootCtx
if store == nil {
return HandleErrorWithHint("no database connection", diagHint())
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
force, _ := cmd.Flags().GetBool("force")
if yes, _ := cmd.Flags().GetBool("yes"); yes {
force = true
}
if usesProxiedServer() {
return runMolBurnProxiedServer(rootCtx, args, dryRun, force)
}
ctx := rootCtx
if store == nil {
return HandleErrorWithHint("no database connection", diagHint())
}
if len(args) == 1 {
return burnSingleMolecule(ctx, args[0], dryRun, force)
}
@ -374,24 +375,32 @@ func burnPersistentMolecule(ctx context.Context, resolvedID string, dryRun, forc
// burnWisps deletes all wisp issues atomically within a single transaction.
// If any delete fails, the entire operation is rolled back to prevent partial deletion.
func burnWisps(ctx context.Context, s storage.DoltStorage, ids []string) (*BurnResult, error) {
result := &BurnResult{
DeletedIDs: make([]string, 0, len(ids)),
}
var result *BurnResult
err := transact(ctx, s, "bd: burn wisps", func(tx storage.Transaction) error {
for _, id := range ids {
if err := tx.DeleteIssue(ctx, id); err != nil {
return fmt.Errorf("failed to delete wisp %s: %w", id, err)
}
result.DeletedIDs = append(result.DeletedIDs, id)
result.DeletedCount++
r, err := burnWispsInto(ctx, storeMolWriter{DoltStorage: s, tx: tx}, ids)
if err != nil {
return err
}
result = r
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
func burnWispsInto(ctx context.Context, w molWriter, ids []string) (*BurnResult, error) {
result := &BurnResult{
DeletedIDs: make([]string, 0, len(ids)),
}
for _, id := range ids {
if err := w.DeleteIssue(ctx, id, ""); err != nil {
return nil, fmt.Errorf("failed to delete wisp %s: %w", id, err)
}
result.DeletedIDs = append(result.DeletedIDs, id)
result.DeletedCount++
}
return result, nil
}

View file

@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
@ -61,9 +60,6 @@ Use --limit or --range to view specific steps:
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol current is not supported in proxied-server mode")
}
evt := metrics.NewCommandEvent("mol-current")
defer func() {
if c := metrics.Global(); c != nil {
@ -71,7 +67,6 @@ Use --limit or --range to view specific steps:
}
}()
ctx := rootCtx
forAgent, _ := cmd.Flags().GetString("for")
limit, _ := cmd.Flags().GetInt("limit")
rangeStr, _ := cmd.Flags().GetString("range")
@ -81,6 +76,12 @@ Use --limit or --range to view specific steps:
agent = actor
}
if usesProxiedServer() {
return runMolCurrentProxiedServer(rootCtx, args, agent, limit, rangeStr)
}
ctx := rootCtx
if store == nil {
return HandleErrorRespectJSON("no database connection")
}
@ -164,7 +165,7 @@ Use --limit or --range to view specific steps:
}
// getMoleculeProgress loads a molecule and computes progress
func getMoleculeProgress(ctx context.Context, s storage.DoltStorage, moleculeID string) (*MoleculeProgress, error) {
func getMoleculeProgress(ctx context.Context, s molReader, moleculeID string) (*MoleculeProgress, error) {
subgraph, err := loadTemplateSubgraph(ctx, s, moleculeID)
if err != nil {
return nil, err
@ -243,7 +244,7 @@ func getMoleculeProgress(ctx context.Context, s storage.DoltStorage, moleculeID
}
// findInProgressMolecules finds molecules with in_progress steps for an agent
func findInProgressMolecules(ctx context.Context, s storage.DoltStorage, agent string) []*MoleculeProgress {
func findInProgressMolecules(ctx context.Context, s molReader, agent string) []*MoleculeProgress {
var inProgressIssues []*types.Issue
status := types.StatusInProgress
@ -299,7 +300,7 @@ func findInProgressMolecules(ctx context.Context, s storage.DoltStorage, agent s
// findHookedMolecules finds molecules bonded to hooked issues for an agent.
// This is a fallback when no in_progress steps exist but a molecule is attached
// to the agent's hooked work via a "blocks" dependency.
func findHookedMolecules(ctx context.Context, s storage.DoltStorage, agent string) []*MoleculeProgress {
func findHookedMolecules(ctx context.Context, s molReader, agent string) []*MoleculeProgress {
// Query for hooked issues assigned to the agent
status := types.StatusHooked
filter := types.IssueFilter{Status: &status}
@ -386,7 +387,7 @@ func findHookedMolecules(ctx context.Context, s storage.DoltStorage, agent strin
// in a loop, issuing GetDependencyRecords + GetIssue per level per issue.
// Instead, this walks parent-child chains level-by-level using batch queries,
// reducing O(N * depth) round-trips to O(depth). (bd-hn4q)
func findParentMolecules(ctx context.Context, s storage.DoltStorage, issueIDs []string) map[string]string {
func findParentMolecules(ctx context.Context, s molReader, issueIDs []string) map[string]string {
if len(issueIDs) == 0 {
return nil
}
@ -492,7 +493,7 @@ func findParentMolecules(ctx context.Context, s storage.DoltStorage, issueIDs []
// findParentMolecule walks up the parent-child chain to find the root molecule
// for a single issue. Returns "" if the issue is not part of a molecule.
func findParentMolecule(ctx context.Context, s storage.DoltStorage, issueID string) string {
func findParentMolecule(ctx context.Context, s molReader, issueID string) string {
roots := findParentMolecules(ctx, s, []string{issueID})
return roots[issueID]
}
@ -588,11 +589,11 @@ type ContinueResult struct {
// AdvanceToNextStep finds the next ready step in a molecule after closing a step.
// If autoClaim is true, it marks the next step as in_progress using optimistic
// concurrency control: the step's status is re-verified inside a transaction to
// concurrency control: the step's status is re-verified before claiming to
// guard against TOCTOU races where multiple agents identify and try to claim the
// same step concurrently.
// Returns nil if the issue is not part of a molecule.
func AdvanceToNextStep(ctx context.Context, s storage.DoltStorage, closedStepID string, autoClaim bool, actorName string) (*ContinueResult, error) {
func AdvanceToNextStep(ctx context.Context, s molWriter, closedStepID string, autoClaim bool, actorName string) (*ContinueResult, error) {
if s == nil {
return nil, fmt.Errorf("no database connection")
}
@ -643,30 +644,9 @@ func AdvanceToNextStep(ctx context.Context, s storage.DoltStorage, closedStepID
result.NextStep = readySteps[0]
// Auto-claim if requested, using optimistic concurrency control.
// Re-read the step inside a transaction to verify it hasn't been claimed
// by another agent between our read and write (TOCTOU guard).
if autoClaim {
for _, candidate := range readySteps {
err := s.RunInTransaction(ctx, fmt.Sprintf("bd: advance to step %s", candidate.ID), func(tx storage.Transaction) error {
// Re-read inside transaction to check current status
current, txErr := tx.GetIssue(ctx, candidate.ID)
if txErr != nil {
return txErr
}
if current == nil {
return fmt.Errorf("step %s not found", candidate.ID)
}
// Only claim if still in open status (not already claimed)
if current.Status != types.StatusOpen {
return fmt.Errorf("step %s already claimed (status: %s)", candidate.ID, current.Status)
}
updates := map[string]interface{}{
"status": types.StatusInProgress,
}
return tx.UpdateIssue(ctx, candidate.ID, updates, actorName)
})
if err == nil {
if err := s.ClaimStepIfOpen(ctx, candidate.ID, actorName); err == nil {
result.NextStep = candidate
result.AutoAdvanced = true
break

View file

@ -102,10 +102,26 @@ func parseDistillVar(varFlag, searchableText string) (string, string, error) {
}
}
func runMolDistill(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol distill is not supported in proxied-server mode")
type molDistillInput struct {
epicID string
formulaNameArg string
varFlags []string
dryRun bool
outputDir string
}
func gatherMolDistillInput(cmd *cobra.Command, args []string) molDistillInput {
in := molDistillInput{epicID: args[0]}
in.varFlags, _ = cmd.Flags().GetStringArray("var")
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
in.outputDir, _ = cmd.Flags().GetString("output")
if len(args) > 1 {
in.formulaNameArg = args[1]
}
return in
}
func runMolDistill(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("mol-distill")
defer func() {
if c := metrics.Global(); c != nil {
@ -113,19 +129,21 @@ func runMolDistill(cmd *cobra.Command, args []string) error {
}
}()
in := gatherMolDistillInput(cmd, args)
if usesProxiedServer() {
return runMolDistillProxiedServer(rootCtx, in)
}
ctx := rootCtx
if store == nil {
return HandleErrorRespectJSON("no database connection")
}
varFlags, _ := cmd.Flags().GetStringArray("var")
dryRun, _ := cmd.Flags().GetBool("dry-run")
outputDir, _ := cmd.Flags().GetString("output")
epicID, err := utils.ResolvePartialID(ctx, store, args[0])
epicID, err := utils.ResolvePartialID(ctx, store, in.epicID)
if err != nil {
return HandleErrorRespectJSON("'%s' not found", args[0])
return HandleErrorRespectJSON("'%s' not found", in.epicID)
}
subgraph, err := loadTemplateSubgraph(ctx, store, epicID)
@ -133,17 +151,22 @@ func runMolDistill(cmd *cobra.Command, args []string) error {
return HandleErrorRespectJSON("loading epic: %v", err)
}
formulaName := ""
if len(args) > 1 {
formulaName = args[1]
} else {
return distillSubgraph(epicID, subgraph, in)
}
// distillSubgraph converts an already-loaded subgraph into a formula file
// (dry-run preview or write-to-disk), shared by the embedded and
// proxied-server dual.
func distillSubgraph(epicID string, subgraph *TemplateSubgraph, in molDistillInput) error {
formulaName := in.formulaNameArg
if formulaName == "" {
formulaName = sanitizeFormulaName(subgraph.Root.Title)
}
replacements := make(map[string]string)
if len(varFlags) > 0 {
if len(in.varFlags) > 0 {
searchableText := collectSubgraphText(subgraph)
for _, v := range varFlags {
for _, v := range in.varFlags {
findText, varName, err := parseDistillVar(v, searchableText)
if err != nil {
return HandleErrorRespectJSON("%v", err)
@ -155,8 +178,8 @@ func runMolDistill(cmd *cobra.Command, args []string) error {
f := subgraphToFormula(subgraph, formulaName, replacements)
outputPath := ""
if outputDir != "" {
outputPath = filepath.Join(outputDir, formulaName+formula.FormulaExt)
if in.outputDir != "" {
outputPath = filepath.Join(in.outputDir, formulaName+formula.FormulaExt)
} else {
outputPath = findWritableFormulaDir(formulaName)
if outputPath == "" {
@ -168,7 +191,7 @@ func runMolDistill(cmd *cobra.Command, args []string) error {
}
}
if dryRun {
if in.dryRun {
fmt.Printf("\nDry run: would distill %d steps from %s into formula\n\n", countSteps(f.Steps), epicID)
fmt.Printf("Formula: %s\n", formulaName)
fmt.Printf("Output: %s\n", outputPath)

View file

@ -29,9 +29,6 @@ Examples:
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol last-activity is not supported in proxied-server mode")
}
evt := metrics.NewCommandEvent("mol-last-activity")
defer func() {
if c := metrics.Global(); c != nil {
@ -39,6 +36,10 @@ Examples:
}
}()
if usesProxiedServer() {
return runMolLastActivityProxiedServer(rootCtx, args[0])
}
ctx := rootCtx
if store == nil {

424
cmd/bd/mol_port.go Normal file
View file

@ -0,0 +1,424 @@
package main
import (
"context"
"fmt"
"strings"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
type molReader interface {
GetIssue(ctx context.Context, id string) (*types.Issue, error)
GetIssuesByIDs(ctx context.Context, ids []string) ([]*types.Issue, error)
GetIssuesByLabel(ctx context.Context, label string) ([]*types.Issue, error)
GetDependents(ctx context.Context, issueID string) ([]*types.Issue, error)
GetDependentsWithMetadata(ctx context.Context, issueID string) ([]*types.IssueWithDependencyMetadata, error)
GetDependencyRecords(ctx context.Context, issueID string) ([]*types.Dependency, error)
GetDependencyRecordsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error)
SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error)
GetReadyWork(ctx context.Context, filter types.WorkFilter) ([]*types.Issue, error)
GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error)
GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error)
GetLabels(ctx context.Context, issueID string) ([]string, error)
GetConfig(ctx context.Context, key string) (string, error)
IsInfraTypeCtx(ctx context.Context, t types.IssueType) bool
GetCustomStatusesDetailed(ctx context.Context) ([]types.CustomStatus, error)
GetMoleculeProgress(ctx context.Context, moleculeID string) (*types.MoleculeProgressStats, error)
GetMoleculeLastActivity(ctx context.Context, moleculeID string) (*types.MoleculeLastActivity, error)
FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error)
}
var _ molReader = storage.DoltStorage(nil)
type molConfigWriter interface {
molReader
SetConfig(ctx context.Context, key, value string) error
}
var _ molConfigWriter = storage.DoltStorage(nil)
type molWriter interface {
molReader
CreateIssue(ctx context.Context, issue *types.Issue, actor string) error
AddDependency(ctx context.Context, dep *types.Dependency, actor string) error
AddLabel(ctx context.Context, issueID, label, actor string) error
UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error
CloseIssue(ctx context.Context, id, reason, actor string) error
DeleteIssue(ctx context.Context, id, actor string) error
SetConfig(ctx context.Context, key, value string) error
ClaimStepIfOpen(ctx context.Context, id, actor string) error
}
type storeMolWriter struct {
storage.DoltStorage
tx storage.Transaction
}
func (w storeMolWriter) CreateIssue(ctx context.Context, issue *types.Issue, actor string) error {
return w.tx.CreateIssue(ctx, issue, actor)
}
func (w storeMolWriter) AddDependency(ctx context.Context, dep *types.Dependency, actor string) error {
return w.tx.AddDependency(ctx, dep, actor)
}
func (w storeMolWriter) AddLabel(ctx context.Context, issueID, label, actor string) error {
return w.tx.AddLabel(ctx, issueID, label, actor)
}
func (w storeMolWriter) UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error {
return w.tx.UpdateIssue(ctx, id, updates, actor)
}
func (w storeMolWriter) CloseIssue(ctx context.Context, id, reason, actor string) error {
return w.tx.CloseIssue(ctx, id, reason, actor, "")
}
func (w storeMolWriter) DeleteIssue(ctx context.Context, id, _ string) error {
return w.tx.DeleteIssue(ctx, id)
}
func (w storeMolWriter) SetConfig(ctx context.Context, key, value string) error {
return w.tx.SetConfig(ctx, key, value)
}
func (w storeMolWriter) ClaimStepIfOpen(ctx context.Context, id, actor string) error {
return w.DoltStorage.RunInTransaction(ctx, fmt.Sprintf("bd: advance to step %s", id), func(tx storage.Transaction) error {
current, err := tx.GetIssue(ctx, id)
if err != nil {
return err
}
if current == nil {
return fmt.Errorf("step %s not found", id)
}
if current.Status != types.StatusOpen {
return fmt.Errorf("step %s already claimed (status: %s)", id, current.Status)
}
return tx.UpdateIssue(ctx, id, map[string]interface{}{"status": types.StatusInProgress}, actor)
})
}
func newStandaloneStoreMolWriter(store storage.DoltStorage) storeMolWriter {
return storeMolWriter{DoltStorage: store}
}
type uowMolReader struct {
uw uow.UnitOfWork
}
func (r uowMolReader) GetIssue(ctx context.Context, id string) (*types.Issue, error) {
issue, _ := proxiedResolveIssueOrWisp(ctx, r.uw, id)
if issue == nil {
return nil, fmt.Errorf("issue %s not found", id)
}
return issue, nil
}
func (r uowMolReader) GetIssuesByIDs(ctx context.Context, ids []string) ([]*types.Issue, error) {
issues, err := r.uw.IssueUseCase().GetIssuesByIDs(ctx, ids)
if err != nil {
return nil, err
}
wisps, err := r.uw.IssueUseCase().GetWispsByIDs(ctx, ids)
if err != nil {
return issues, nil //nolint:nilerr // wisps table may not exist; issues result still valid
}
return append(issues, wisps...), nil
}
func (r uowMolReader) GetIssuesByLabel(ctx context.Context, label string) ([]*types.Issue, error) {
page, err := r.uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Labels: []string{label}})
if err != nil {
return nil, err
}
return page.Items, nil
}
func (r uowMolReader) GetDependents(ctx context.Context, issueID string) ([]*types.Issue, error) {
withMeta, err := r.GetDependentsWithMetadata(ctx, issueID)
if err != nil {
return nil, err
}
out := make([]*types.Issue, len(withMeta))
for i, m := range withMeta {
issue := m.Issue
out[i] = &issue
}
return out, nil
}
func (r uowMolReader) GetDependentsWithMetadata(ctx context.Context, issueID string) ([]*types.IssueWithDependencyMetadata, error) {
filter := domain.DepListFilter{Direction: domain.DepDirectionIn}
issueDeps, err := r.uw.DependencyUseCase().ListWithIssueMetadata(ctx, issueID, filter)
if err != nil {
return nil, err
}
wispDeps, err := r.uw.DependencyUseCase().ListWispWithIssueMetadata(ctx, issueID, filter)
if err != nil {
return issueDeps, nil //nolint:nilerr // wisp_dependencies table may not exist
}
return append(issueDeps, wispDeps...), nil
}
func (r uowMolReader) GetDependencyRecords(ctx context.Context, issueID string) ([]*types.Dependency, error) {
out, err := r.uw.DependencyUseCase().GetForIssueIDs(ctx, []string{issueID})
if err != nil {
return nil, err
}
return out[issueID], nil
}
func (r uowMolReader) GetDependencyRecordsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error) {
return r.uw.DependencyUseCase().GetForIssueIDs(ctx, issueIDs)
}
func (r uowMolReader) SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) {
page, err := r.uw.IssueUseCase().SearchIssues(ctx, query, filter)
if err != nil {
return nil, err
}
return page.Items, nil
}
func (r uowMolReader) GetReadyWork(ctx context.Context, filter types.WorkFilter) ([]*types.Issue, error) {
page, err := r.uw.IssueUseCase().GetReadyWork(ctx, filter)
if err != nil {
return nil, err
}
return page.Items, nil
}
func (r uowMolReader) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error) {
return r.uw.IssueUseCase().GetBlockedIssues(ctx, filter)
}
func (r uowMolReader) GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error) {
return r.uw.IssueUseCase().GetEpicsEligibleForClosure(ctx)
}
func (r uowMolReader) GetLabels(ctx context.Context, issueID string) ([]string, error) {
return r.uw.LabelUseCase().GetLabels(ctx, issueID)
}
func (r uowMolReader) GetConfig(ctx context.Context, key string) (string, error) {
return r.uw.ConfigUseCase().GetConfig(ctx, key)
}
func (r uowMolReader) IsInfraTypeCtx(ctx context.Context, t types.IssueType) bool {
ok, err := r.uw.ConfigUseCase().IsInfraTypeCtx(ctx, t)
return err == nil && ok
}
func (r uowMolReader) GetCustomStatusesDetailed(ctx context.Context) ([]types.CustomStatus, error) {
return r.uw.ConfigUseCase().GetCustomStatuses(ctx)
}
func (r uowMolReader) GetMoleculeProgress(ctx context.Context, moleculeID string) (*types.MoleculeProgressStats, error) {
progress, err := getMoleculeProgress(ctx, r, moleculeID)
if err != nil {
return nil, err
}
stats := &types.MoleculeProgressStats{
MoleculeID: progress.MoleculeID,
MoleculeTitle: progress.MoleculeTitle,
Total: progress.Total,
Completed: progress.Completed,
}
if progress.CurrentStep != nil {
stats.CurrentStepID = progress.CurrentStep.ID
stats.InProgress = 1
}
return stats, nil
}
func (r uowMolReader) GetMoleculeLastActivity(ctx context.Context, moleculeID string) (*types.MoleculeLastActivity, error) {
root, err := r.GetIssue(ctx, moleculeID)
if err != nil {
return nil, err
}
subgraph, err := loadTemplateSubgraph(ctx, r, moleculeID)
if err != nil {
return nil, err
}
last := &types.MoleculeLastActivity{
MoleculeID: moleculeID,
LastActivity: root.UpdatedAt,
Source: "molecule_updated",
}
for _, issue := range subgraph.Issues {
if issue.ID == moleculeID {
continue
}
if issue.UpdatedAt.After(last.LastActivity) {
last.LastActivity = issue.UpdatedAt
last.Source = "step_updated"
last.SourceStepID = issue.ID
}
if issue.ClosedAt != nil && issue.ClosedAt.After(last.LastActivity) {
last.LastActivity = *issue.ClosedAt
last.Source = "step_closed"
last.SourceStepID = issue.ID
}
}
return last, nil
}
func (r uowMolReader) FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error) {
return r.uw.IssueUseCase().FindWispDependentsRecursive(ctx, ids)
}
type uowMolWriter struct {
uowMolReader
wispIDs map[string]bool
}
func newUOWMolWriter(uw uow.UnitOfWork) *uowMolWriter {
return &uowMolWriter{uowMolReader: uowMolReader{uw: uw}, wispIDs: make(map[string]bool)}
}
func (w *uowMolWriter) isWisp(ctx context.Context, id string) bool {
if w.wispIDs[id] {
return true
}
if _, err := w.uw.IssueUseCase().GetWisp(ctx, id); err == nil {
return true
}
return false
}
func (w *uowMolWriter) CreateIssue(ctx context.Context, issue *types.Issue, actor string) error {
params := domain.CreateIssueParams{Issue: issue, ExplicitID: issue.ID}
var err error
if issue.Ephemeral || issue.NoHistory {
_, err = w.uw.IssueUseCase().CreateWisp(ctx, params, actor)
if err == nil {
w.wispIDs[issue.ID] = true
}
} else {
_, err = w.uw.IssueUseCase().CreateIssue(ctx, params, actor)
}
return err
}
func (w *uowMolWriter) AddDependency(ctx context.Context, dep *types.Dependency, actor string) error {
if w.isWisp(ctx, dep.IssueID) || w.isWisp(ctx, dep.DependsOnID) {
return w.uw.DependencyUseCase().AddWispDependency(ctx, dep, actor)
}
return w.uw.DependencyUseCase().AddDependency(ctx, dep, actor)
}
func (w *uowMolWriter) AddLabel(ctx context.Context, issueID, label, actor string) error {
if w.isWisp(ctx, issueID) {
return w.uw.LabelUseCase().AddWispLabel(ctx, issueID, label, actor)
}
return w.uw.LabelUseCase().AddLabel(ctx, issueID, label, actor)
}
func (w *uowMolWriter) UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error {
if w.isWisp(ctx, id) {
return w.uw.IssueUseCase().UpdateWisp(ctx, id, updates, actor)
}
return w.uw.IssueUseCase().UpdateIssue(ctx, id, updates, actor)
}
func (w *uowMolWriter) CloseIssue(ctx context.Context, id, reason, actor string) error {
params := domain.CloseIssueParams{Reason: reason}
var err error
if w.isWisp(ctx, id) {
_, err = w.uw.IssueUseCase().CloseWisp(ctx, id, params, actor)
} else {
_, err = w.uw.IssueUseCase().CloseIssue(ctx, id, params, actor)
}
return err
}
func (w *uowMolWriter) DeleteIssue(ctx context.Context, id, actor string) error {
var err error
if w.isWisp(ctx, id) {
_, err = w.uw.IssueUseCase().DeleteWisp(ctx, id, actor)
} else {
_, err = w.uw.IssueUseCase().DeleteIssue(ctx, id, actor)
}
return err
}
func (w *uowMolWriter) SetConfig(ctx context.Context, key, value string) error {
return w.uw.ConfigUseCase().SetConfig(ctx, key, value)
}
func (w *uowMolWriter) ClaimStepIfOpen(ctx context.Context, id, actor string) error {
if w.isWisp(ctx, id) {
_, err := w.uw.IssueUseCase().ClaimWispIfOpen(ctx, id, actor)
return err
}
_, err := w.uw.IssueUseCase().ClaimIssueIfOpen(ctx, id, actor)
return err
}
func resolveMolID(ctx context.Context, r molReader, input string) (string, error) {
if issues, err := r.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{input}}); err == nil && len(issues) > 0 {
return issues[0].ID, nil
}
prefix, err := r.GetConfig(ctx, "issue_prefix")
if err != nil || prefix == "" {
prefix = "bd"
}
prefixWithHyphen := prefix
if !strings.HasSuffix(prefix, "-") {
prefixWithHyphen += "-"
}
normalized := input
if !strings.HasPrefix(input, prefixWithHyphen) && utils.ExtractIssuePrefix(input) == "" {
normalized = prefixWithHyphen + input
}
if issues, err := r.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{normalized}}); err == nil && len(issues) > 0 {
return issues[0].ID, nil
}
hashPart := strings.TrimPrefix(normalized, prefixWithHyphen)
if hashPart == "" {
return "", fmt.Errorf("no issue found matching %q", input)
}
issues, err := r.SearchIssues(ctx, hashPart, types.IssueFilter{})
if err != nil {
return "", fmt.Errorf("searching for %q: %w", input, err)
}
var matches []string
var exactMatch string
for _, issue := range issues {
if issue.ID == input || issue.ID == normalized {
exactMatch = issue.ID
break
}
hash := issue.ID
if p := utils.ExtractIssuePrefix(issue.ID); p != "" {
hash = strings.TrimPrefix(issue.ID, p+"-")
}
if hash == hashPart {
exactMatch = issue.ID
}
if strings.Contains(hash, hashPart) {
matches = append(matches, issue.ID)
}
}
if exactMatch != "" {
return exactMatch, nil
}
if len(matches) == 0 {
return "", fmt.Errorf("no issue found matching %q", input)
}
if len(matches) > 1 {
return "", fmt.Errorf("ambiguous ID %q matches %d issues: %v", input, len(matches), matches)
}
return matches[0], nil
}

View file

@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
@ -34,9 +33,6 @@ Example:
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol progress is not supported in proxied-server mode")
}
evt := metrics.NewCommandEvent("mol-progress")
defer func() {
if c := metrics.Global(); c != nil {
@ -44,6 +40,10 @@ Example:
}
}()
if usesProxiedServer() {
return runMolProgressProxiedServer(rootCtx, args)
}
ctx := rootCtx
if store == nil {
@ -109,7 +109,7 @@ Example:
// findInProgressMoleculeIDs finds molecule IDs with in_progress steps for an agent.
// This is a lightweight version that only returns IDs without loading subgraphs.
func findInProgressMoleculeIDs(ctx context.Context, s storage.DoltStorage, agent string) []string {
func findInProgressMoleculeIDs(ctx context.Context, s molReader, agent string) []string {
// Query for in_progress issues
status := types.StatusInProgress
filter := types.IssueFilter{Status: &status}

View file

@ -0,0 +1,678 @@
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
type pourProxiedResult struct {
spawn *InstantiateResult
totalAttached int
attachCount int
}
func runPourProxiedServer(ctx context.Context, in pourInput) error {
CheckReadonly("pour")
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
vars, err := parseVarFlags(in.varFlags)
if err != nil {
return HandleError("%v", err)
}
var formulaSubgraph *TemplateSubgraph
var formulaProtoID string
if sg, err := resolveAndCookFormulaWithVars(in.protoArg, nil, vars); err == nil {
formulaSubgraph = sg
formulaProtoID = sg.Root.ID
if sg.Phase == "vapor" {
warnPourVaporFormula(in.protoArg, in.varFlags)
}
}
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (pourProxiedResult, string, error) {
w := newUOWMolWriter(uw)
subgraph := formulaSubgraph
protoID := formulaProtoID
if subgraph == nil {
resolvedID, err := resolveMolID(ctx, w, in.protoArg)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("%s not found as formula or proto ID", in.protoArg)
}
protoID = resolvedID
protoIssue, err := w.GetIssue(ctx, protoID)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("loading proto %s: %w", protoID, err)
}
if !isProto(protoIssue) {
return pourProxiedResult{}, "", fmt.Errorf("%s is not a proto (missing '%s' label)", protoID, MoleculeLabel)
}
subgraph, err = loadTemplateSubgraph(ctx, w, protoID)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("loading proto: %w", err)
}
}
type attachmentInfo struct {
id string
issue *types.Issue
subgraph *TemplateSubgraph
}
var attachments []attachmentInfo
for _, attachArg := range in.attachArgs {
attachID, err := resolveMolID(ctx, w, attachArg)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("resolving attachment ID %s: %w", attachArg, err)
}
attachIssue, err := w.GetIssue(ctx, attachID)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("loading attachment %s: %w", attachID, err)
}
if !isProto(attachIssue) {
return pourProxiedResult{}, "", fmt.Errorf("%s is not a proto (missing '%s' label)", attachID, MoleculeLabel)
}
attachSubgraph, err := loadTemplateSubgraph(ctx, w, attachID)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("loading attachment subgraph %s: %w", attachID, err)
}
attachments = append(attachments, attachmentInfo{attachID, attachIssue, attachSubgraph})
}
vars := applyVariableDefaults(vars, subgraph)
var attachSubgraphs []*TemplateSubgraph
for _, a := range attachments {
attachSubgraphs = append(attachSubgraphs, a.subgraph)
}
if err := checkPourVars(subgraph, attachSubgraphs, vars); err != nil {
return pourProxiedResult{}, "", err
}
if in.dryRun {
var previews []pourAttachPreview
for _, a := range attachments {
previews = append(previews, pourAttachPreview{title: a.issue.Title, steps: len(a.subgraph.Issues)})
}
renderPourDryRun(protoID, subgraph, vars, in.assignee, in.attachType, previews)
return pourProxiedResult{}, "", nil
}
spawnResult, err := cloneSubgraphInto(ctx, w, subgraph, CloneOptions{
Vars: vars,
Assignee: in.assignee,
Actor: actor,
Prefix: types.IDPrefixMol,
})
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("pouring proto: %w", err)
}
totalAttached := 0
if len(attachments) > 0 {
spawnedMol, err := w.GetIssue(ctx, spawnResult.NewEpicID)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("loading spawned mol: %w", err)
}
for _, attach := range attachments {
bondResult, err := bondProtoMolAttachInto(ctx, w, attach.subgraph, attach.issue, spawnedMol, in.attachType, vars, "", actor, false, true)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("attaching %s: %w", attach.id, err)
}
totalAttached += bondResult.Spawned
}
}
return pourProxiedResult{spawn: spawnResult, totalAttached: totalAttached, attachCount: len(attachments)},
fmt.Sprintf("bd: mol pour %s", protoID), nil
})
if err != nil {
return HandleError("%v", err)
}
if res.spawn == nil {
return nil
}
renderPourResult(res.spawn, res.totalAttached, res.attachCount)
return nil
}
func runMolShowProxiedServer(ctx context.Context, arg string) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
moleculeID, err := resolveMolID(ctx, r, arg)
if err != nil {
return HandleErrorRespectJSON("molecule '%s' not found", arg)
}
subgraph, err := loadTemplateSubgraph(ctx, r, moleculeID)
if err != nil {
return HandleErrorRespectJSON("loading molecule: %v", err)
}
if molShowParallel {
return showMoleculeWithParallel(subgraph)
}
return showMolecule(subgraph)
}
func runMolCurrentProxiedServer(ctx context.Context, args []string, agent string, limit int, rangeStr string) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
var rangeStart, rangeEnd int
if rangeStr != "" {
rangeStart, rangeEnd, err = parseRange(rangeStr)
if err != nil {
return HandleErrorRespectJSON("invalid range '%s': %v", rangeStr, err)
}
}
explicitSteps := limit > 0 || rangeStr != ""
var molecules []*MoleculeProgress
if len(args) == 1 {
moleculeID, err := resolveMolID(ctx, r, args[0])
if err != nil {
return HandleErrorRespectJSON("molecule '%s' not found", args[0])
}
stats, err := r.GetMoleculeProgress(ctx, moleculeID)
if err != nil {
return HandleErrorRespectJSON("loading molecule: %v", err)
}
if stats.Total > LargeMoleculeThreshold && !explicitSteps && !jsonOutput {
printLargeMoleculeSummary(stats)
return nil
}
progress, err := getMoleculeProgress(ctx, r, moleculeID)
if err != nil {
return HandleErrorRespectJSON("loading molecule: %v", err)
}
if rangeStr != "" {
progress.Steps = filterStepsByRange(progress.Steps, rangeStart, rangeEnd)
} else if limit > 0 && len(progress.Steps) > limit {
progress.Steps = progress.Steps[:limit]
}
molecules = append(molecules, progress)
} else {
molecules = findInProgressMolecules(ctx, r, agent)
if len(molecules) == 0 {
molecules = findHookedMolecules(ctx, r, agent)
}
if len(molecules) == 0 {
if jsonOutput {
return outputJSON([]interface{}{})
}
fmt.Printf("No molecules in progress")
if agent != "" {
fmt.Printf(" for %s", agent)
}
fmt.Println(".")
fmt.Println("\nTo start work on a molecule:")
fmt.Println(" bd mol wisp create <proto-id> # Instantiate as ephemeral wisp")
fmt.Println(" bd update <step-id> --claim # Claim a step")
return nil
}
}
if jsonOutput {
return outputJSON(molecules)
}
for i, mol := range molecules {
if i > 0 {
fmt.Println()
}
printMoleculeProgress(mol)
}
return nil
}
func runMolProgressProxiedServer(ctx context.Context, args []string) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
var moleculeID string
if len(args) == 1 {
resolved, err := resolveMolID(ctx, r, args[0])
if err != nil {
return HandleErrorRespectJSON("molecule '%s' not found", args[0])
}
moleculeID = resolved
} else {
moleculeIDs := findInProgressMoleculeIDs(ctx, r, actor)
if len(moleculeIDs) == 0 {
if jsonOutput {
return outputJSON([]interface{}{})
}
fmt.Println("No molecules in progress.")
fmt.Println("\nUse: bd mol progress <molecule-id>")
return nil
}
moleculeID = moleculeIDs[0]
}
stats, err := r.GetMoleculeProgress(ctx, moleculeID)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if jsonOutput {
output := map[string]interface{}{
"molecule_id": stats.MoleculeID,
"molecule_title": stats.MoleculeTitle,
"total": stats.Total,
"completed": stats.Completed,
"in_progress": stats.InProgress,
"current_step_id": stats.CurrentStepID,
}
if stats.Total > 0 {
output["percent"] = float64(stats.Completed) * 100 / float64(stats.Total)
}
return outputJSON(output)
}
printMoleculeProgressStats(stats)
return nil
}
func runMolLastActivityProxiedServer(ctx context.Context, arg string) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
moleculeID, err := resolveMolID(ctx, r, arg)
if err != nil {
return HandleErrorRespectJSON("molecule '%s' not found", arg)
}
activity, err := r.GetMoleculeLastActivity(ctx, moleculeID)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if jsonOutput {
return outputJSON(activity)
}
fmt.Println(activity.LastActivity.UTC().Format(time.RFC3339))
return nil
}
func runMolStaleProxiedServer(ctx context.Context, blockingOnly, unassignedOnly, showAll bool) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
result, err := findStaleMolecules(ctx, uowMolReader{uw: uw}, blockingOnly, unassignedOnly, showAll)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if jsonOutput {
return outputJSON(result)
}
renderStaleResult(result, blockingOnly)
return nil
}
func runMolReadyGatedProxiedServer(ctx context.Context) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
molecules, err := findGateReadyMolecules(ctx, uowMolReader{uw: uw})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
return renderGatedReadyMolecules(molecules)
}
func runMolBondProxiedServer(ctx context.Context, in molBondInput) error {
if uowProvider == nil {
return HandleErrorRespectJSON("proxied-server UOW provider not initialized")
}
if in.dryRun {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
issueA, formulaA, err := resolveOrDescribe(ctx, r, in.argA)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
issueB, formulaB, err := resolveOrDescribe(ctx, r, in.argB)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
renderMolBondDryRun(in, issueA, formulaA, issueB, formulaB)
return nil
}
type bondTxResult struct {
result *BondResult
idA string
idB string
}
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (bondTxResult, string, error) {
w := newUOWMolWriter(uw)
subgraphA, cookedA, err := resolveOrCookToSubgraph(ctx, w, in.argA, in.vars)
if err != nil {
return bondTxResult{}, "", err
}
subgraphB, cookedB, err := resolveOrCookToSubgraph(ctx, w, in.argB, in.vars)
if err != nil {
return bondTxResult{}, "", err
}
issueA := subgraphA.Root
issueB := subgraphB.Root
aIsProto := issueA.IsTemplate || cookedA
bIsProto := issueB.IsTemplate || cookedB
var result *BondResult
switch {
case aIsProto && bIsProto:
result, err = bondProtoProtoInto(ctx, w, issueA, issueB, in.bondType, in.customTitle, actor)
case aIsProto && !bIsProto:
result, err = bondProtoMolAttachInto(ctx, w, subgraphA, issueA, issueB, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
case !aIsProto && bIsProto:
result, err = bondProtoMolAttachInto(ctx, w, subgraphB, issueB, issueA, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
default:
result, err = bondMolMolInto(ctx, w, issueA, issueB, in.bondType, actor)
}
if err != nil {
return bondTxResult{}, "", fmt.Errorf("bonding: %w", err)
}
return bondTxResult{result: result, idA: issueA.ID, idB: issueB.ID},
fmt.Sprintf("bd: mol bond %s %s", issueA.ID, issueB.ID), nil
})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
renderMolBondResult(res.result, res.idA, res.idB, in.ephemeral, in.pour)
return nil
}
func runMolSquashProxiedServer(ctx context.Context, in molSquashInput) error {
CheckReadonly("mol squash")
if uowProvider == nil {
return HandleErrorRespectJSON("proxied-server UOW provider not initialized")
}
if in.dryRun {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
moleculeID, err := resolveMolID(ctx, r, in.moleculeArg)
if err != nil {
return HandleErrorRespectJSON("resolving molecule ID %s: %v", in.moleculeArg, err)
}
subgraph, err := loadTemplateSubgraph(ctx, r, moleculeID)
if err != nil {
return HandleErrorRespectJSON("loading molecule: %v", err)
}
wispChildren := wispChildrenOf(subgraph)
if len(wispChildren) == 0 {
if jsonOutput {
return outputJSON(SquashResult{MoleculeID: moleculeID, SquashedCount: 0})
}
fmt.Printf("No ephemeral children found for molecule %s\n", moleculeID)
return nil
}
renderSquashDryRun(moleculeID, subgraph, wispChildren, in.keepChildren)
return nil
}
result, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (*SquashResult, string, error) {
w := newUOWMolWriter(uw)
moleculeID, err := resolveMolID(ctx, w, in.moleculeArg)
if err != nil {
return nil, "", fmt.Errorf("resolving molecule ID %s: %w", in.moleculeArg, err)
}
subgraph, err := loadTemplateSubgraph(ctx, w, moleculeID)
if err != nil {
return nil, "", fmt.Errorf("loading molecule: %w", err)
}
wispChildren := wispChildrenOf(subgraph)
if len(wispChildren) == 0 {
return &SquashResult{MoleculeID: moleculeID, SquashedCount: 0}, "", nil
}
result, err := squashMoleculeInto(ctx, w, subgraph.Root, wispChildren, in.keepChildren, in.summary, actor)
if err != nil {
return nil, "", fmt.Errorf("squashing molecule: %w", err)
}
return result, fmt.Sprintf("bd: mol squash %s", moleculeID), nil
})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if result.SquashedCount == 0 && result.DigestID == "" {
if jsonOutput {
return outputJSON(result)
}
fmt.Printf("No ephemeral children found for molecule %s\n", result.MoleculeID)
return nil
}
renderSquashResult(result)
return nil
}
func runMolBurnProxiedServer(ctx context.Context, args []string, dryRun, force bool) error {
if uowProvider == nil {
return HandleErrorRespectJSON("proxied-server UOW provider not initialized")
}
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
r := uowMolReader{uw: uw}
var wispIDs []string
var persistentIDs []string
var failedResolve []string
for _, moleculeID := range args {
resolvedID, err := resolveMolID(ctx, r, moleculeID)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to resolve %s: %v\n", moleculeID, err)
}
failedResolve = append(failedResolve, moleculeID)
continue
}
issue, err := r.GetIssue(ctx, resolvedID)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to load %s: %v\n", resolvedID, err)
}
failedResolve = append(failedResolve, moleculeID)
continue
}
if issue.Ephemeral {
wispIDs = append(wispIDs, resolvedID)
} else {
persistentIDs = append(persistentIDs, resolvedID)
}
}
uw.Close(ctx)
if len(wispIDs) == 0 && len(persistentIDs) == 0 {
if jsonOutput {
return outputJSON(BatchBurnResult{FailedCount: len(failedResolve)})
}
fmt.Println("No valid molecules to burn")
return nil
}
if dryRun {
if !jsonOutput {
fmt.Printf("\nDry run: would burn %d wisp(s) and %d persistent molecule(s)\n", len(wispIDs), len(persistentIDs))
if len(wispIDs) > 0 {
fmt.Printf("\nWisps to delete:\n")
for _, id := range wispIDs {
fmt.Printf(" - %s\n", id)
}
}
if len(persistentIDs) > 0 {
fmt.Printf("\nPersistent molecules to delete:\n")
for _, id := range persistentIDs {
fmt.Printf(" - %s\n", id)
}
}
if len(failedResolve) > 0 {
fmt.Printf("\nFailed to resolve (%d):\n", len(failedResolve))
for _, id := range failedResolve {
fmt.Printf(" - %s\n", id)
}
}
}
return nil
}
if !force && !jsonOutput {
fmt.Printf("About to burn %d wisp(s) and %d persistent molecule(s)\n", len(wispIDs), len(persistentIDs))
fmt.Printf("This will permanently delete all molecule data with no digest.\n")
fmt.Printf("\nContinue? [y/N] ")
var response string
_, _ = fmt.Scanln(&response)
if response != "y" && response != "Y" {
fmt.Println("Canceled.")
return nil
}
}
batchResult := BatchBurnResult{
Results: make([]BurnResult, 0),
FailedCount: len(failedResolve),
}
err = uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
w := newUOWMolWriter(uw)
if len(wispIDs) > 0 {
result, err := burnWispsInto(ctx, w, wispIDs)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Error burning wisps: %v\n", err)
}
} else {
batchResult.TotalDeleted += result.DeletedCount
batchResult.Results = append(batchResult.Results, *result)
}
}
for _, id := range persistentIDs {
subgraph, err := loadTemplateSubgraph(ctx, w, id)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to load subgraph for %s: %v\n", id, err)
}
batchResult.FailedCount++
continue
}
issueIDs := make([]string, len(subgraph.Issues))
for i, issue := range subgraph.Issues {
issueIDs[i] = issue.ID
}
res, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: issueIDs,
Cascade: true,
UpdateTextReferences: true,
}, actor)
if err != nil {
return "", fmt.Errorf("burning %s: %w", id, err)
}
batchResult.TotalDeleted += res.DeletedCount
batchResult.Results = append(batchResult.Results, BurnResult{
MoleculeID: id,
DeletedIDs: issueIDs,
DeletedCount: res.DeletedCount,
})
}
return fmt.Sprintf("bd: mol burn %d molecule(s)", len(wispIDs)+len(persistentIDs)), nil
})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if jsonOutput {
return outputJSON(batchResult)
}
fmt.Printf("%s Burned %d molecule(s): %d issues deleted\n", ui.RenderPass("✓"), len(wispIDs)+len(persistentIDs), batchResult.TotalDeleted)
if batchResult.FailedCount > 0 {
fmt.Printf(" %d failed\n", batchResult.FailedCount)
}
return nil
}
func runMolDistillProxiedServer(ctx context.Context, in molDistillInput) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
epicID, err := resolveMolID(ctx, r, in.epicID)
if err != nil {
return HandleErrorRespectJSON("'%s' not found", in.epicID)
}
subgraph, err := loadTemplateSubgraph(ctx, r, epicID)
if err != nil {
return HandleErrorRespectJSON("loading epic: %v", err)
}
return distillSubgraph(epicID, subgraph, in)
}

View file

@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
@ -49,9 +48,6 @@ Examples:
}
func runMolReadyGated(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol ready is not supported in proxied-server mode")
}
evt := metrics.NewCommandEvent("mol-ready-gated")
defer func() {
if c := metrics.Global(); c != nil {
@ -68,6 +64,10 @@ func runMolReadyGated(cmd *cobra.Command, args []string) error {
// standalone runMolReadyGated entrypoint records "mol-ready-gated"; this keeps a
// single `bd ready --gated` invocation to exactly one cli_command event.
func runMolReadyGatedCore(_ *cobra.Command, _ []string) error {
if usesProxiedServer() {
return runMolReadyGatedProxiedServer(rootCtx)
}
ctx := rootCtx
if store == nil {
@ -79,6 +79,10 @@ func runMolReadyGatedCore(_ *cobra.Command, _ []string) error {
return HandleErrorRespectJSON("%v", err)
}
return renderGatedReadyMolecules(molecules)
}
func renderGatedReadyMolecules(molecules []*GatedMolecule) error {
if jsonOutput {
output := GatedReadyOutput{
Molecules: molecules,
@ -122,7 +126,7 @@ func runMolReadyGatedCore(_ *cobra.Command, _ []string) error {
// 3. Check if that step is now ready (unblocked)
// 4. Find the parent molecule
// 5. Filter out molecules that are already hooked by someone
func findGateReadyMolecules(ctx context.Context, s storage.DoltStorage) ([]*GatedMolecule, error) {
func findGateReadyMolecules(ctx context.Context, s molReader) ([]*GatedMolecule, error) {
// Step 1: Find all closed gate beads
gateType := types.IssueType("gate")
closedStatus := types.StatusClosed

View file

@ -32,9 +32,6 @@ Example:
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol show is not supported in proxied-server mode")
}
evt := metrics.NewCommandEvent("mol-show")
defer func() {
if c := metrics.Global(); c != nil {
@ -42,6 +39,10 @@ Example:
}
}()
if usesProxiedServer() {
return runMolShowProxiedServer(rootCtx, args[0])
}
ctx := rootCtx
if store == nil {

View file

@ -62,39 +62,22 @@ type SquashResult struct {
WispSquash bool `json:"wisp_squash,omitempty"` // True if this was a wisp→digest squash
}
func runMolSquash(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol squash is not supported in proxied-server mode")
}
CheckReadonly("mol squash")
type molSquashInput struct {
moleculeArg string
dryRun bool
keepChildren bool
summary string
}
evt := metrics.NewCommandEvent("mol-squash")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
ctx := rootCtx
if store == nil {
return HandleErrorWithHint("no database connection", diagHint())
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
keepChildren, _ := cmd.Flags().GetBool("keep-children")
summary, _ := cmd.Flags().GetString("summary")
moleculeID, err := utils.ResolvePartialID(ctx, store, args[0])
if err != nil {
return HandleErrorRespectJSON("resolving molecule ID %s: %v", args[0], err)
}
subgraph, err := loadTemplateSubgraph(ctx, store, moleculeID)
if err != nil {
return HandleErrorRespectJSON("loading molecule: %v", err)
}
func gatherMolSquashInput(cmd *cobra.Command, args []string) molSquashInput {
in := molSquashInput{moleculeArg: args[0]}
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
in.keepChildren, _ = cmd.Flags().GetBool("keep-children")
in.summary, _ = cmd.Flags().GetString("summary")
return in
}
func wispChildrenOf(subgraph *TemplateSubgraph) []*types.Issue {
var wispChildren []*types.Issue
for _, issue := range subgraph.Issues {
if issue.ID == subgraph.Root.ID {
@ -104,7 +87,81 @@ func runMolSquash(cmd *cobra.Command, args []string) error {
wispChildren = append(wispChildren, issue)
}
}
return wispChildren
}
func renderSquashDryRun(moleculeID string, subgraph *TemplateSubgraph, wispChildren []*types.Issue, keepChildren bool) {
fmt.Printf("\nDry run: would squash %d ephemeral children of %s\n\n", len(wispChildren), moleculeID)
fmt.Printf("Root: %s\n", subgraph.Root.Title)
fmt.Printf("\nWisp children to squash:\n")
for _, issue := range wispChildren {
status := string(issue.Status)
fmt.Printf(" - [%s] %s (%s)\n", status, issue.Title, issue.ID)
}
fmt.Printf("\nDigest preview:\n")
digest := generateDigest(subgraph.Root, wispChildren)
if len(digest) > 500 {
fmt.Printf("%s...\n", digest[:500])
} else {
fmt.Printf("%s\n", digest)
}
if keepChildren {
fmt.Printf("\n--keep-children: children would NOT be deleted\n")
} else {
fmt.Printf("\nChildren would be deleted after digest creation.\n")
}
}
func renderSquashResult(result *SquashResult) {
if jsonOutput {
_ = outputJSON(result)
return
}
fmt.Printf("%s Squashed molecule: %d children → 1 digest\n", ui.RenderPass("✓"), result.SquashedCount)
fmt.Printf(" Digest ID: %s\n", result.DigestID)
if result.DeletedCount > 0 {
fmt.Printf(" Deleted: %d wisps\n", result.DeletedCount)
} else if result.KeptChildren {
fmt.Printf(" Children preserved (--keep-children)\n")
}
if result.WispSquash {
fmt.Printf(" Root auto-closed: %s\n", result.MoleculeID)
}
}
func runMolSquash(cmd *cobra.Command, args []string) error {
CheckReadonly("mol squash")
evt := metrics.NewCommandEvent("mol-squash")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
in := gatherMolSquashInput(cmd, args)
if usesProxiedServer() {
return runMolSquashProxiedServer(rootCtx, in)
}
ctx := rootCtx
if store == nil {
return HandleErrorWithHint("no database connection", diagHint())
}
moleculeID, err := utils.ResolvePartialID(ctx, store, in.moleculeArg)
if err != nil {
return HandleErrorRespectJSON("resolving molecule ID %s: %v", in.moleculeArg, err)
}
subgraph, err := loadTemplateSubgraph(ctx, store, moleculeID)
if err != nil {
return HandleErrorRespectJSON("loading molecule: %v", err)
}
wispChildren := wispChildrenOf(subgraph)
if len(wispChildren) == 0 {
if jsonOutput {
return outputJSON(SquashResult{
@ -116,48 +173,16 @@ func runMolSquash(cmd *cobra.Command, args []string) error {
return nil
}
if dryRun {
fmt.Printf("\nDry run: would squash %d ephemeral children of %s\n\n", len(wispChildren), moleculeID)
fmt.Printf("Root: %s\n", subgraph.Root.Title)
fmt.Printf("\nWisp children to squash:\n")
for _, issue := range wispChildren {
status := string(issue.Status)
fmt.Printf(" - [%s] %s (%s)\n", status, issue.Title, issue.ID)
}
fmt.Printf("\nDigest preview:\n")
digest := generateDigest(subgraph.Root, wispChildren)
if len(digest) > 500 {
fmt.Printf("%s...\n", digest[:500])
} else {
fmt.Printf("%s\n", digest)
}
if keepChildren {
fmt.Printf("\n--keep-children: children would NOT be deleted\n")
} else {
fmt.Printf("\nChildren would be deleted after digest creation.\n")
}
if in.dryRun {
renderSquashDryRun(moleculeID, subgraph, wispChildren, in.keepChildren)
return nil
}
result, err := squashMolecule(ctx, store, subgraph.Root, wispChildren, keepChildren, summary, actor)
result, err := squashMolecule(ctx, store, subgraph.Root, wispChildren, in.keepChildren, in.summary, actor)
if err != nil {
return HandleErrorRespectJSON("squashing molecule: %v", err)
}
if jsonOutput {
return outputJSON(result)
}
fmt.Printf("%s Squashed molecule: %d children → 1 digest\n", ui.RenderPass("✓"), result.SquashedCount)
fmt.Printf(" Digest ID: %s\n", result.DigestID)
if result.DeletedCount > 0 {
fmt.Printf(" Deleted: %d wisps\n", result.DeletedCount)
} else if result.KeptChildren {
fmt.Printf(" Children preserved (--keep-children)\n")
}
if result.WispSquash {
fmt.Printf(" Root auto-closed: %s\n", result.MoleculeID)
}
renderSquashResult(result)
return nil
}
@ -219,6 +244,22 @@ func squashMolecule(ctx context.Context, s storage.DoltStorage, root *types.Issu
return nil, fmt.Errorf("no database connection")
}
var result *SquashResult
err := transact(ctx, s, fmt.Sprintf("bd: squash molecule %s", root.ID), func(tx storage.Transaction) error {
r, err := squashMoleculeInto(ctx, storeMolWriter{DoltStorage: s, tx: tx}, root, children, keepChildren, summary, actorName)
if err != nil {
return err
}
result = r
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
func squashMoleculeInto(ctx context.Context, w molWriter, root *types.Issue, children []*types.Issue, keepChildren bool, summary string, actorName string) (*SquashResult, error) {
// Collect child IDs
childIDs := make([]string, len(children))
for i, c := range children {
@ -253,53 +294,43 @@ func squashMolecule(ctx context.Context, s storage.DoltStorage, root *types.Issu
KeptChildren: keepChildren,
}
// All squash operations in a single transaction for atomicity (bd-4kgbq):
// digest creation, child deletion, and root close
err := transact(ctx, s, fmt.Sprintf("bd: squash molecule %s", root.ID), func(tx storage.Transaction) error {
// Create digest issue
if err := tx.CreateIssue(ctx, digestIssue, actorName); err != nil {
return fmt.Errorf("failed to create digest issue: %w", err)
}
result.DigestID = digestIssue.ID
// Create digest issue
if err := w.CreateIssue(ctx, digestIssue, actorName); err != nil {
return nil, fmt.Errorf("failed to create digest issue: %w", err)
}
result.DigestID = digestIssue.ID
// Link digest to root as parent-child
dep := &types.Dependency{
IssueID: digestIssue.ID,
DependsOnID: root.ID,
Type: types.DepParentChild,
}
if err := tx.AddDependency(ctx, dep, actorName); err != nil {
return fmt.Errorf("failed to link digest to root: %w", err)
}
// Link digest to root as parent-child
dep := &types.Dependency{
IssueID: digestIssue.ID,
DependsOnID: root.ID,
Type: types.DepParentChild,
}
if err := w.AddDependency(ctx, dep, actorName); err != nil {
return nil, fmt.Errorf("failed to link digest to root: %w", err)
}
// Delete ephemeral children within the same transaction
if !keepChildren {
for _, id := range childIDs {
if err := tx.DeleteIssue(ctx, id); err != nil {
return fmt.Errorf("failed to delete child %s: %w", id, err)
}
result.DeletedCount++
// Delete ephemeral children within the same transaction
if !keepChildren {
for _, id := range childIDs {
if err := w.DeleteIssue(ctx, id, actorName); err != nil {
return nil, fmt.Errorf("failed to delete child %s: %w", id, err)
}
result.DeletedCount++
}
}
// Auto-close the root if it's a wisp — squash completes the molecule lifecycle
if root.Ephemeral {
reason := fmt.Sprintf("Squashed: %d steps → digest %s", len(children), result.DigestID)
if err := tx.CloseIssue(ctx, root.ID, reason, actorName, ""); err != nil {
return fmt.Errorf("failed to close wisp root %s: %w", root.ID, err)
}
// Clear ephemeral so the closed root stops being re-emitted by every wisp-table export cycle.
if err := tx.UpdateIssue(ctx, root.ID, map[string]interface{}{"wisp": false}, actorName); err != nil {
return fmt.Errorf("failed to clear ephemeral flag on root %s: %w", root.ID, err)
}
result.WispSquash = true
// Auto-close the root if it's a wisp — squash completes the molecule lifecycle
if root.Ephemeral {
reason := fmt.Sprintf("Squashed: %d steps → digest %s", len(children), result.DigestID)
if err := w.CloseIssue(ctx, root.ID, reason, actorName); err != nil {
return nil, fmt.Errorf("failed to close wisp root %s: %w", root.ID, err)
}
return nil
})
if err != nil {
return nil, err
// Clear ephemeral so the closed root stops being re-emitted by every wisp-table export cycle.
if err := w.UpdateIssue(ctx, root.ID, map[string]interface{}{"wisp": false}, actorName); err != nil {
return nil, fmt.Errorf("failed to clear ephemeral flag on root %s: %w", root.ID, err)
}
result.WispSquash = true
}
return result, nil

View file

@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
@ -54,9 +53,6 @@ type StaleResult struct {
}
func runMolStale(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("mol stale is not supported in proxied-server mode")
}
evt := metrics.NewCommandEvent("mol-stale")
defer func() {
if c := metrics.Global(); c != nil {
@ -64,12 +60,16 @@ func runMolStale(cmd *cobra.Command, args []string) error {
}
}()
ctx := rootCtx
blockingOnly, _ := cmd.Flags().GetBool("blocking")
unassignedOnly, _ := cmd.Flags().GetBool("unassigned")
showAll, _ := cmd.Flags().GetBool("all")
if usesProxiedServer() {
return runMolStaleProxiedServer(rootCtx, blockingOnly, unassignedOnly, showAll)
}
ctx := rootCtx
var result *StaleResult
var err error
@ -85,10 +85,14 @@ func runMolStale(cmd *cobra.Command, args []string) error {
if jsonOutput {
return outputJSON(result)
}
renderStaleResult(result, blockingOnly)
return nil
}
func renderStaleResult(result *StaleResult, blockingOnly bool) {
if len(result.StaleMolecules) == 0 {
fmt.Println("No stale molecules found.")
return nil
return
}
if blockingOnly {
@ -122,11 +126,10 @@ func runMolStale(cmd *cobra.Command, args []string) error {
fmt.Printf(", %d blocking other work", result.BlockingCount)
}
fmt.Println()
return nil
}
// findStaleMolecules queries the database for stale molecules
func findStaleMolecules(ctx context.Context, s storage.DoltStorage, blockingOnly, unassignedOnly, showAll bool) (*StaleResult, error) {
func findStaleMolecules(ctx context.Context, s molReader, blockingOnly, unassignedOnly, showAll bool) (*StaleResult, error) {
// Get all epics eligible for closure (complete but unclosed)
epicStatuses, err := s.GetEpicsEligibleForClosure(ctx)
if err != nil {

View file

@ -1853,7 +1853,7 @@ func TestAdvanceToNextStep_PouredMolecule(t *testing.T) {
t.Fatalf("Failed to add blocking dep: %v", err)
}
result, err := AdvanceToNextStep(ctx, s, step1.ID, true, "test")
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, true, "test")
if err != nil {
t.Fatalf("AdvanceToNextStep failed: %v", err)
}
@ -2024,7 +2024,7 @@ func TestAdvanceToNextStep(t *testing.T) {
}
// Advance from step1 (just closed) without auto-claim
result, err := AdvanceToNextStep(ctx, s, step1.ID, false, "test")
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, false, "test")
if err != nil {
t.Fatalf("AdvanceToNextStep failed: %v", err)
}
@ -2050,7 +2050,7 @@ func TestAdvanceToNextStep(t *testing.T) {
}
// Now test with auto-claim
result, err = AdvanceToNextStep(ctx, s, step1.ID, true, "test")
result, err = AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, true, "test")
if err != nil {
t.Fatalf("AdvanceToNextStep with auto-claim failed: %v", err)
}
@ -2108,7 +2108,7 @@ func TestAdvanceToNextStepMoleculeComplete(t *testing.T) {
}
// Advance from the only step (molecule should be complete)
result, err := AdvanceToNextStep(ctx, s, step1.ID, false, "test")
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, false, "test")
if err != nil {
t.Fatalf("AdvanceToNextStep failed: %v", err)
}
@ -2148,7 +2148,7 @@ func TestAdvanceToNextStepOrphanIssue(t *testing.T) {
}
// Advance should return nil (not part of molecule)
result, err := AdvanceToNextStep(ctx, s, orphan.ID, false, "test")
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), orphan.ID, false, "test")
if err != nil {
t.Fatalf("AdvanceToNextStep failed: %v", err)
}
@ -2238,7 +2238,7 @@ func TestAdvanceToNextStepConcurrentClaim(t *testing.T) {
// Now our agent tries to advance with autoClaim — step2 was identified as
// ready during the read phase, but it's already in_progress. The function
// should fall back to step3.
result, err := AdvanceToNextStep(ctx, s, step1.ID, true, "our-agent")
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, true, "our-agent")
if err != nil {
t.Fatalf("AdvanceToNextStep failed: %v", err)
}
@ -2331,7 +2331,7 @@ func TestAdvanceToNextStepAllClaimed(t *testing.T) {
}
// Advance with autoClaim — should fail gracefully (no steps to claim)
result, err := AdvanceToNextStep(ctx, s, step1.ID, true, "our-agent")
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, true, "our-agent")
if err != nil {
t.Fatalf("AdvanceToNextStep failed: %v", err)
}

View file

@ -52,6 +52,37 @@ Examples:
RunE: runPour,
}
type pourInput struct {
protoArg string
dryRun bool
varFlags []string
assignee string
attachArgs []string
attachType string
}
func gatherPourInput(cmd *cobra.Command, args []string) pourInput {
in := pourInput{protoArg: args[0]}
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
in.varFlags, _ = cmd.Flags().GetStringArray("var")
in.assignee, _ = cmd.Flags().GetString("assignee")
in.attachArgs, _ = cmd.Flags().GetStringSlice("attach")
in.attachType, _ = cmd.Flags().GetString("attach-type")
return in
}
func parseVarFlags(varFlags []string) (map[string]string, error) {
vars := make(map[string]string)
for _, v := range varFlags {
parts := strings.SplitN(v, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid variable format '%s', expected 'key=value'", v)
}
vars[parts[0]] = parts[1]
}
return vars, nil
}
func runPour(cmd *cobra.Command, args []string) error {
CheckReadonly("pour")
@ -62,61 +93,40 @@ func runPour(cmd *cobra.Command, args []string) error {
}
}()
in := gatherPourInput(cmd, args)
if usesProxiedServer() {
return runPourProxiedServer(rootCtx, in)
}
ctx := rootCtx
if store == nil {
return HandleError("no database connection")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
varFlags, _ := cmd.Flags().GetStringArray("var")
assignee, _ := cmd.Flags().GetString("assignee")
attachFlags, _ := cmd.Flags().GetStringSlice("attach")
attachType, _ := cmd.Flags().GetString("attach-type")
// Parse variables
vars := make(map[string]string)
for _, v := range varFlags {
parts := strings.SplitN(v, "=", 2)
if len(parts) != 2 {
return HandleError("invalid variable format '%s', expected 'key=value'", v)
}
vars[parts[0]] = parts[1]
vars, err := parseVarFlags(in.varFlags)
if err != nil {
return HandleError("%v", err)
}
// Try to load as formula first (ephemeral proto - gt-4v1eo)
// If that fails, fall back to loading from DB (legacy proto beads)
var subgraph *TemplateSubgraph
var protoID string
isFormula := false
// Try to cook formula inline (gt-4v1eo: ephemeral protos)
// This works for any valid formula name, not just "mol-" prefixed ones
// Pass vars for step condition filtering (bd-7zka.1)
sg, err := resolveAndCookFormulaWithVars(args[0], nil, vars)
sg, err := resolveAndCookFormulaWithVars(in.protoArg, nil, vars)
if err == nil {
subgraph = sg
protoID = sg.Root.ID
isFormula = true
// Warn if formula recommends vapor phase (bd-mol cleanup)
if sg.Phase == "vapor" {
fmt.Fprintf(os.Stderr, "%s Formula %q recommends vapor phase (ephemeral)\n", ui.RenderWarn("⚠"), args[0])
fmt.Fprintf(os.Stderr, " Consider using: bd mol wisp %s", args[0])
for _, v := range varFlags {
fmt.Fprintf(os.Stderr, " --var %s", v)
}
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, " Pour creates persistent issues that sync like any other bead.\n")
fmt.Fprintf(os.Stderr, " Wisp creates ephemeral issues that auto-cleanup.\n\n")
warnPourVaporFormula(in.protoArg, in.varFlags)
}
}
if subgraph == nil {
// Try to load as existing proto bead (legacy path)
resolvedID, err := utils.ResolvePartialID(ctx, store, args[0])
resolvedID, err := utils.ResolvePartialID(ctx, store, in.protoArg)
if err != nil {
return HandleError("%s not found as formula or proto ID", args[0])
return HandleError("%s not found as formula or proto ID", in.protoArg)
}
protoID = resolvedID
@ -134,16 +144,13 @@ func runPour(cmd *cobra.Command, args []string) error {
}
}
_ = isFormula // For future use (e.g., logging)
// Resolve and load attached protos
type attachmentInfo struct {
id string
issue *types.Issue
subgraph *TemplateSubgraph
}
var attachments []attachmentInfo
for _, attachArg := range attachFlags {
for _, attachArg := range in.attachArgs {
attachID, err := utils.ResolvePartialID(ctx, store, attachArg)
if err != nil {
return HandleError("resolving attachment ID %s: %v", attachArg, err)
@ -159,21 +166,68 @@ func runPour(cmd *cobra.Command, args []string) error {
if err != nil {
return HandleError("loading attachment subgraph %s: %v", attachID, err)
}
attachments = append(attachments, attachmentInfo{
id: attachID,
issue: attachIssue,
subgraph: attachSubgraph,
})
attachments = append(attachments, attachmentInfo{attachID, attachIssue, attachSubgraph})
}
// Apply variable defaults from formula
vars = applyVariableDefaults(vars, subgraph)
// Check for missing required variables (those without defaults)
var attachSubgraphs []*TemplateSubgraph
for _, a := range attachments {
attachSubgraphs = append(attachSubgraphs, a.subgraph)
}
if err := checkPourVars(subgraph, attachSubgraphs, vars); err != nil {
return HandleErrorWithHint(err.Error(), fmt.Sprintf("Provide them with: --var %s=<value>", missingVarHint(subgraph, attachSubgraphs, vars)))
}
if in.dryRun {
var previews []pourAttachPreview
for _, a := range attachments {
previews = append(previews, pourAttachPreview{title: a.issue.Title, steps: len(a.subgraph.Issues)})
}
renderPourDryRun(protoID, subgraph, vars, in.assignee, in.attachType, previews)
return nil
}
result, err := spawnMolecule(ctx, store, subgraph, vars, in.assignee, actor, false, types.IDPrefixMol)
if err != nil {
return HandleError("pouring proto: %v", err)
}
totalAttached := 0
if len(attachments) > 0 {
spawnedMol, err := store.GetIssue(ctx, result.NewEpicID)
if err != nil {
return HandleError("loading spawned mol: %v", err)
}
for _, attach := range attachments {
bondResult, err := bondProtoMol(ctx, store, attach.issue, spawnedMol, in.attachType, vars, "", actor, false, true)
if err != nil {
return HandleError("attaching %s: %v", attach.id, err)
}
totalAttached += bondResult.Spawned
}
}
renderPourResult(result, totalAttached, len(attachments))
return nil
}
func warnPourVaporFormula(protoArg string, varFlags []string) {
fmt.Fprintf(os.Stderr, "%s Formula %q recommends vapor phase (ephemeral)\n", ui.RenderWarn("⚠"), protoArg)
fmt.Fprintf(os.Stderr, " Consider using: bd mol wisp %s", protoArg)
for _, v := range varFlags {
fmt.Fprintf(os.Stderr, " --var %s", v)
}
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, " Pour creates persistent issues that sync like any other bead.\n")
fmt.Fprintf(os.Stderr, " Wisp creates ephemeral issues that auto-cleanup.\n\n")
}
func requiredVarsAcross(subgraph *TemplateSubgraph, attachSubgraphs []*TemplateSubgraph) []string {
requiredVars := extractRequiredVariables(subgraph)
for _, attach := range attachments {
attachVars := extractRequiredVariables(attach.subgraph)
for _, v := range attachVars {
for _, attachSubgraph := range attachSubgraphs {
for _, v := range extractRequiredVariables(attachSubgraph) {
found := false
for _, rv := range requiredVars {
if rv == v {
@ -186,77 +240,72 @@ func runPour(cmd *cobra.Command, args []string) error {
}
}
}
return requiredVars
}
func checkPourVars(subgraph *TemplateSubgraph, attachSubgraphs []*TemplateSubgraph, vars map[string]string) error {
var missingVars []string
for _, v := range requiredVars {
for _, v := range requiredVarsAcross(subgraph, attachSubgraphs) {
if _, ok := vars[v]; !ok {
missingVars = append(missingVars, v)
}
}
if len(missingVars) > 0 {
return HandleErrorWithHint(
fmt.Sprintf("missing required variables: %s", strings.Join(missingVars, ", ")),
fmt.Sprintf("Provide them with: --var %s=<value>", missingVars[0]),
)
return fmt.Errorf("missing required variables: %s", strings.Join(missingVars, ", "))
}
return nil
}
if dryRun {
fmt.Printf("\nDry run: would pour %d issues from proto %s\n\n", len(subgraph.Issues), protoID)
fmt.Printf("Storage: permanent (.beads/)\n\n")
for _, issue := range subgraph.Issues {
newTitle := substituteVariables(issue.Title, vars)
suffix := ""
if issue.ID == subgraph.Root.ID && assignee != "" {
suffix = fmt.Sprintf(" (assignee: %s)", assignee)
}
fmt.Printf(" - %s (from %s)%s\n", newTitle, issue.ID, suffix)
func missingVarHint(subgraph *TemplateSubgraph, attachSubgraphs []*TemplateSubgraph, vars map[string]string) string {
for _, v := range requiredVarsAcross(subgraph, attachSubgraphs) {
if _, ok := vars[v]; !ok {
return v
}
if len(attachments) > 0 {
fmt.Printf("\nAttachments (%s bonding):\n", attachType)
for _, attach := range attachments {
fmt.Printf(" + %s (%d issues)\n", attach.issue.Title, len(attach.subgraph.Issues))
}
}
return ""
}
type pourAttachPreview struct {
title string
steps int
}
func renderPourDryRun(protoID string, subgraph *TemplateSubgraph, vars map[string]string, assignee, attachType string, attachments []pourAttachPreview) {
fmt.Printf("\nDry run: would pour %d issues from proto %s\n\n", len(subgraph.Issues), protoID)
fmt.Printf("Storage: permanent (.beads/)\n\n")
for _, issue := range subgraph.Issues {
newTitle := substituteVariables(issue.Title, vars)
suffix := ""
if issue.ID == subgraph.Root.ID && assignee != "" {
suffix = fmt.Sprintf(" (assignee: %s)", assignee)
}
return nil
fmt.Printf(" - %s (from %s)%s\n", newTitle, issue.ID, suffix)
}
result, err := spawnMolecule(ctx, store, subgraph, vars, assignee, actor, false, types.IDPrefixMol)
if err != nil {
return HandleError("pouring proto: %v", err)
}
// Attach bonded protos
totalAttached := 0
if len(attachments) > 0 {
spawnedMol, err := store.GetIssue(ctx, result.NewEpicID)
if err != nil {
return HandleError("loading spawned mol: %v", err)
}
fmt.Printf("\nAttachments (%s bonding):\n", attachType)
for _, attach := range attachments {
bondResult, err := bondProtoMol(ctx, store, attach.issue, spawnedMol, attachType, vars, "", actor, false, true)
if err != nil {
return HandleError("attaching %s: %v", attach.id, err)
}
totalAttached += bondResult.Spawned
fmt.Printf(" + %s (%d issues)\n", attach.title, attach.steps)
}
}
}
func renderPourResult(result *InstantiateResult, totalAttached, attachCount int) {
if jsonOutput {
type pourResult struct {
*InstantiateResult
Attached int `json:"attached"`
Phase string `json:"phase"`
}
return outputJSON(pourResult{result, totalAttached, "liquid"})
_ = outputJSON(pourResult{result, totalAttached, "liquid"})
return
}
fmt.Printf("%s Poured mol: created %d issues\n", ui.RenderPass("✓"), result.Created)
fmt.Printf(" Root issue: %s\n", result.NewEpicID)
fmt.Printf(" Phase: liquid (persistent in the issue database)\n")
if totalAttached > 0 {
fmt.Printf(" Attached: %d issues from %d protos\n", totalAttached, len(attachments))
fmt.Printf(" Attached: %d issues from %d protos\n", totalAttached, attachCount)
}
return nil
}
func init() {

View file

@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
@ -350,7 +349,7 @@ func runReadyProxiedExplain(ctx context.Context, uw uow.UnitOfWork, _ readyInput
func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInput) error {
moleculeID := in.molID
subgraph, err := proxiedLoadTemplateSubgraph(ctx, uw, moleculeID)
subgraph, err := loadTemplateSubgraph(ctx, uowMolReader{uw: uw}, moleculeID)
if err != nil {
return HandleError("loading molecule: %v", err)
}
@ -432,83 +431,9 @@ func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInp
}
func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput) error {
gateType := types.IssueType("gate")
closedStatus := types.StatusClosed
gatePage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{
IssueType: &gateType,
Status: &closedStatus,
})
molecules, err := findGateReadyMolecules(ctx, uowMolReader{uw: uw})
if err != nil {
return HandleErrorRespectJSON("error searching for closed gates: %v", err)
}
if len(gatePage.Items) == 0 {
emitGatedEmpty()
return nil
}
readyPage, err := uw.IssueUseCase().GetReadyWork(ctx, types.WorkFilter{})
if err != nil {
return HandleErrorRespectJSON("error getting ready work: %v", err)
}
readySet := make(map[string]*types.Issue, len(readyPage.Items))
for _, issue := range readyPage.Items {
readySet[issue.ID] = issue
}
hookedStatus := types.StatusHooked
hookedPage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Status: &hookedStatus})
if err != nil {
return HandleErrorRespectJSON("error searching for hooked issues: %v", err)
}
hookedSet := make(map[string]*types.Issue, len(hookedPage.Items))
for _, issue := range hookedPage.Items {
hookedSet[issue.ID] = issue
}
moleculeMap := make(map[string]*GatedMolecule)
for _, gate := range gatePage.Items {
dependents, err := uw.DependencyUseCase().ListWithIssueMetadata(ctx, gate.ID, domain.DepListFilter{
Direction: domain.DepDirectionIn,
})
if err != nil {
continue
}
for _, dep := range dependents {
depIssue := dep.Issue
ready, isReady := readySet[depIssue.ID]
hooked, isHooked := hookedSet[depIssue.ID]
if !isReady && !isHooked {
continue
}
var step *types.Issue
if isReady {
step = ready
} else {
step = hooked
}
moleculeID := proxiedFindParentMolecule(ctx, uw, depIssue.ID)
if moleculeID == "" {
continue
}
if _, seen := moleculeMap[moleculeID]; seen {
continue
}
moleculeIssue, err := uw.IssueUseCase().GetIssue(ctx, moleculeID)
if err != nil || moleculeIssue == nil {
continue
}
moleculeMap[moleculeID] = &GatedMolecule{
MoleculeID: moleculeID,
MoleculeTitle: moleculeIssue.Title,
ClosedGate: gate,
ReadyStep: step,
}
}
}
molecules := make([]*GatedMolecule, 0, len(moleculeMap))
for _, m := range moleculeMap {
molecules = append(molecules, m)
return HandleErrorRespectJSON("%v", err)
}
if jsonOutput {
@ -533,14 +458,6 @@ func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput)
return nil
}
func emitGatedEmpty() {
if jsonOutput {
_ = outputJSON(GatedReadyOutput{Molecules: []*GatedMolecule{}})
return
}
fmt.Printf("\n%s No closed gates found — nothing to dispatch\n\n", ui.RenderPass("✨"))
}
func buildReadyIssueOutputProxied(ctx context.Context, uw uow.UnitOfWork, issues []*types.Issue) []*types.IssueWithCounts {
if issues == nil {
issues = []*types.Issue{}

View file

@ -10,7 +10,6 @@ import (
"github.com/steveyegge/beads/internal/formula"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
// BeadsTemplateLabel is the label used to identify Beads-based templates
@ -67,7 +66,7 @@ var bondedIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
// =============================================================================
// loadTemplateSubgraph loads a template epic and all its descendants
func loadTemplateSubgraph(ctx context.Context, s storage.DoltStorage, templateID string) (*TemplateSubgraph, error) {
func loadTemplateSubgraph(ctx context.Context, s molReader, templateID string) (*TemplateSubgraph, error) {
if s == nil {
return nil, fmt.Errorf("no database connection")
}
@ -117,7 +116,7 @@ func loadTemplateSubgraph(ctx context.Context, s storage.DoltStorage, templateID
//
// The visited set tracks IDs already expanded to detect cycles (GH#2719).
// Without this, cyclic parent-child dependencies cause unbounded recursion leading to OOM.
func loadDescendants(ctx context.Context, s storage.DoltStorage, subgraph *TemplateSubgraph, parentID string, visited map[string]bool) error {
func loadDescendants(ctx context.Context, s molReader, subgraph *TemplateSubgraph, parentID string, visited map[string]bool) error {
// Track children we've already added to avoid duplicates
addedChildren := make(map[string]bool)
@ -212,7 +211,7 @@ func loadDescendants(ctx context.Context, s storage.DoltStorage, subgraph *Templ
// findHierarchicalChildren finds issues with IDs that match the pattern parentID.N
// This catches hierarchical children that may be missing parent-child dependencies.
func findHierarchicalChildren(ctx context.Context, s storage.DoltStorage, parentID string) ([]*types.Issue, error) {
func findHierarchicalChildren(ctx context.Context, s molReader, parentID string) ([]*types.Issue, error) {
pattern := parentID + "."
candidates, err := s.SearchIssues(ctx, "", types.IssueFilter{IDPrefix: pattern})
if err != nil {
@ -238,9 +237,9 @@ func findHierarchicalChildren(ctx context.Context, s storage.DoltStorage, parent
// It first tries to resolve as an ID (via ResolvePartialID).
// If that fails, it searches for protos with matching titles.
// Returns the proto ID if found, or an error if not found or ambiguous.
func resolveProtoIDOrTitle(ctx context.Context, s storage.DoltStorage, input string) (string, error) {
func resolveProtoIDOrTitle(ctx context.Context, s molReader, input string) (string, error) {
// Strategy 1: Try to resolve as an ID
protoID, err := utils.ResolvePartialID(ctx, s, input)
protoID, err := resolveMolID(ctx, s, input)
if err == nil {
// Verify it's a proto (has template label)
issue, getErr := s.GetIssue(ctx, protoID)
@ -484,7 +483,7 @@ func getRelativeID(oldID, rootID string) string {
// issues with types like "gate" (for async coordination beads) that are
// not in the default type whitelist. Without this, cloneSubgraph fails
// with "invalid issue type" on the first non-built-in bead. (GH#3213)
func ensureSubgraphCustomTypes(ctx context.Context, s storage.DoltStorage, subgraph *TemplateSubgraph) error {
func ensureSubgraphCustomTypes(ctx context.Context, s molConfigWriter, subgraph *TemplateSubgraph) error {
// Collect non-built-in types used by the subgraph.
needed := make(map[string]bool)
for _, issue := range subgraph.Issues {
@ -564,106 +563,107 @@ func cloneSubgraph(ctx context.Context, s storage.DoltStorage, subgraph *Templat
return nil, fmt.Errorf("registering custom types for subgraph: %w", err)
}
// Generate new IDs and create mapping
idMapping := make(map[string]string)
// Use transaction for atomicity
var result *InstantiateResult
err := transact(ctx, s, "bd: clone template subgraph", func(tx storage.Transaction) error {
// First pass: create all issues with new IDs
for _, oldIssue := range subgraph.Issues {
// RootOnly: skip child issues, only create the root
if opts.RootOnly && oldIssue.ID != subgraph.Root.ID {
continue
}
// Determine assignee: use override for root epic, otherwise keep template's
issueAssignee := oldIssue.Assignee
if oldIssue.ID == subgraph.Root.ID && opts.Assignee != "" {
issueAssignee = opts.Assignee
}
newIssue := &types.Issue{
// ID will be set below based on bonding options
Title: substituteVariables(oldIssue.Title, opts.Vars),
Description: substituteVariables(oldIssue.Description, opts.Vars),
Design: substituteVariables(oldIssue.Design, opts.Vars),
AcceptanceCriteria: substituteVariables(oldIssue.AcceptanceCriteria, opts.Vars),
Notes: substituteVariables(oldIssue.Notes, opts.Vars),
Status: types.StatusOpen, // Always start fresh
Priority: oldIssue.Priority,
IssueType: oldIssue.IssueType,
Assignee: issueAssignee,
EstimatedMinutes: oldIssue.EstimatedMinutes,
Ephemeral: opts.Ephemeral, // mark for cleanup when closed
IDPrefix: opts.Prefix, // distinct prefixes for mols/wisps
// Gate fields (for async coordination)
AwaitType: oldIssue.AwaitType,
AwaitID: substituteVariables(oldIssue.AwaitID, opts.Vars),
Timeout: oldIssue.Timeout,
Labels: oldIssue.Labels,
Metadata: oldIssue.Metadata,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
// Generate custom ID for dynamic bonding if ParentID is set
if opts.ParentID != "" {
bondedID, err := generateBondedID(oldIssue.ID, subgraph.Root.ID, opts)
if err != nil {
return fmt.Errorf("failed to generate bonded ID for %s: %w", oldIssue.ID, err)
}
newIssue.ID = bondedID
}
if err := tx.CreateIssue(ctx, newIssue, opts.Actor); err != nil {
return fmt.Errorf("failed to create issue from %s: %w", oldIssue.ID, err)
}
idMapping[oldIssue.ID] = newIssue.ID
r, err := cloneSubgraphInto(ctx, storeMolWriter{DoltStorage: s, tx: tx}, subgraph, opts)
if err != nil {
return err
}
// 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,
// Carry template metadata through to the clone (GH#3875):
// waits-for edges store their gate (and, for a collapsed
// needs/depends_on edge, also_blocks) here. Dropping it
// silently reset every poured waits-for edge to the
// default all-children gate with also_blocks unset.
Metadata: dep.Metadata,
}
if err := tx.AddDependency(ctx, newDep, opts.Actor); err != nil {
return fmt.Errorf("failed to create dependency: %w", err)
}
}
// Atomic attachment: link spawned root to target molecule within
// the same transaction (bd-wvplu: prevents orphaned spawns)
if opts.AttachToID != "" {
attachDep := &types.Dependency{
IssueID: idMapping[subgraph.Root.ID],
DependsOnID: opts.AttachToID,
Type: opts.AttachDepType,
}
if err := tx.AddDependency(ctx, attachDep, opts.Actor); err != nil {
return fmt.Errorf("attaching to molecule: %w", err)
}
}
result = r
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
func cloneSubgraphInto(ctx context.Context, w molWriter, subgraph *TemplateSubgraph, opts CloneOptions) (*InstantiateResult, error) {
idMapping := make(map[string]string)
// First pass: create all issues with new IDs
for _, oldIssue := range subgraph.Issues {
// RootOnly: skip child issues, only create the root
if opts.RootOnly && oldIssue.ID != subgraph.Root.ID {
continue
}
// Determine assignee: use override for root epic, otherwise keep template's
issueAssignee := oldIssue.Assignee
if oldIssue.ID == subgraph.Root.ID && opts.Assignee != "" {
issueAssignee = opts.Assignee
}
newIssue := &types.Issue{
// ID will be set below based on bonding options
Title: substituteVariables(oldIssue.Title, opts.Vars),
Description: substituteVariables(oldIssue.Description, opts.Vars),
Design: substituteVariables(oldIssue.Design, opts.Vars),
AcceptanceCriteria: substituteVariables(oldIssue.AcceptanceCriteria, opts.Vars),
Notes: substituteVariables(oldIssue.Notes, opts.Vars),
Status: types.StatusOpen, // Always start fresh
Priority: oldIssue.Priority,
IssueType: oldIssue.IssueType,
Assignee: issueAssignee,
EstimatedMinutes: oldIssue.EstimatedMinutes,
Ephemeral: opts.Ephemeral, // mark for cleanup when closed
IDPrefix: opts.Prefix, // distinct prefixes for mols/wisps
// Gate fields (for async coordination)
AwaitType: oldIssue.AwaitType,
AwaitID: substituteVariables(oldIssue.AwaitID, opts.Vars),
Timeout: oldIssue.Timeout,
Labels: oldIssue.Labels,
Metadata: oldIssue.Metadata,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
// Generate custom ID for dynamic bonding if ParentID is set
if opts.ParentID != "" {
bondedID, err := generateBondedID(oldIssue.ID, subgraph.Root.ID, opts)
if err != nil {
return nil, fmt.Errorf("failed to generate bonded ID for %s: %w", oldIssue.ID, err)
}
newIssue.ID = bondedID
}
if err := w.CreateIssue(ctx, newIssue, opts.Actor); err != nil {
return nil, 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,
Metadata: dep.Metadata,
}
if err := w.AddDependency(ctx, newDep, opts.Actor); err != nil {
return nil, fmt.Errorf("failed to create dependency: %w", err)
}
}
// Atomic attachment: link spawned root to target molecule within
// the same transaction (bd-wvplu: prevents orphaned spawns)
if opts.AttachToID != "" {
attachDep := &types.Dependency{
IssueID: idMapping[subgraph.Root.ID],
DependsOnID: opts.AttachToID,
Type: opts.AttachDepType,
}
if err := w.AddDependency(ctx, attachDep, opts.Actor); err != nil {
return nil, fmt.Errorf("attaching to molecule: %w", err)
}
}
return &InstantiateResult{
NewEpicID: idMapping[subgraph.Root.ID],

View file

@ -159,27 +159,43 @@ func runWispCreate(cmd *cobra.Command, args []string) error {
// event, so the caller owns emission: the standalone `bd mol wisp create`
// entrypoint records "wisp-create", while the bare `bd wisp <name>` alias records
// "wisp". This keeps each invocation to exactly one cli_command event.
type wispCreateInput struct {
protoArg string
dryRun bool
rootOnly bool
varFlags []string
}
func gatherWispCreateInput(cmd *cobra.Command, args []string) wispCreateInput {
in := wispCreateInput{protoArg: args[0]}
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
in.rootOnly, _ = cmd.Flags().GetBool("root-only")
in.varFlags, _ = cmd.Flags().GetStringArray("var")
return in
}
func runWispCreateCore(cmd *cobra.Command, args []string) error {
CheckReadonly("wisp create")
in := gatherWispCreateInput(cmd, args)
if usesProxiedServer() {
return runWispCreateProxiedServer(rootCtx, in)
}
ctx := rootCtx
if store == nil {
return HandleErrorWithHint("no database connection", diagHint())
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
rootOnly, _ := cmd.Flags().GetBool("root-only")
varFlags, _ := cmd.Flags().GetStringArray("var")
vars := make(map[string]string)
for _, v := range varFlags {
parts := strings.SplitN(v, "=", 2)
if len(parts) != 2 {
return HandleError("invalid variable format '%s', expected 'key=value'", v)
}
vars[parts[0]] = parts[1]
vars, err := parseVarFlags(in.varFlags)
if err != nil {
return HandleError("%v", err)
}
args = []string{in.protoArg}
dryRun := in.dryRun
rootOnly := in.rootOnly
// Try to load as formula first (ephemeral proto)
// If that fails, fall back to loading from DB (legacy proto beads)
@ -243,47 +259,14 @@ func runWispCreateCore(cmd *cobra.Command, args []string) error {
}
}
// Apply variable defaults from formula
vars = applyVariableDefaults(vars, subgraph)
// Check for missing required variables (those without defaults)
requiredVars := extractRequiredVariables(subgraph)
var missingVars []string
for _, v := range requiredVars {
if _, ok := vars[v]; !ok {
missingVars = append(missingVars, v)
}
}
if len(missingVars) > 0 {
return HandleErrorWithHint(
fmt.Sprintf("missing required variables: %s", strings.Join(missingVars, ", ")),
fmt.Sprintf("Provide them with: --var %s=<value>", missingVars[0]),
)
if err := checkRequiredVars(subgraph, vars); err != nil {
return HandleErrorWithHint(err.Error(), fmt.Sprintf("Provide them with: --var %s=<value>", firstMissingVar(subgraph, vars)))
}
// By default, wisps materialize the same child DAG as pour, just marked
// Ephemeral=true so they don't sync via git. Use --root-only to opt out
// of fanout (e.g. for patrol wisps whose steps are inlined at prime time
// rather than tracked as beads). GH#3872.
if dryRun {
if rootOnly {
skipped := len(subgraph.Issues) - 1
fmt.Printf("\nDry run: would create wisp with 1 issue (root only) from proto %s\n", protoID)
if skipped > 0 {
fmt.Printf(" Note: %d child step(s) skipped (--root-only)\n", skipped)
}
} else {
fmt.Printf("\nDry run: would create wisp with %d issues from proto %s\n\n", len(subgraph.Issues), protoID)
}
fmt.Printf("Storage: main database (ephemeral=true, not synced via git)\n\n")
issuesToShow := subgraph.Issues
if rootOnly && len(issuesToShow) > 0 {
issuesToShow = issuesToShow[:1]
}
for _, issue := range issuesToShow {
newTitle := substituteVariables(issue.Title, vars)
fmt.Printf(" - %s (from %s)\n", newTitle, issue.ID)
}
renderWispCreateDryRun(protoID, subgraph, vars, rootOnly)
return nil
}
@ -298,12 +281,61 @@ func runWispCreateCore(cmd *cobra.Command, args []string) error {
return HandleError("creating wisp: %v", err)
}
renderWispCreateResult(result)
return nil
}
func checkRequiredVars(subgraph *TemplateSubgraph, vars map[string]string) error {
var missingVars []string
for _, v := range extractRequiredVariables(subgraph) {
if _, ok := vars[v]; !ok {
missingVars = append(missingVars, v)
}
}
if len(missingVars) > 0 {
return fmt.Errorf("missing required variables: %s", strings.Join(missingVars, ", "))
}
return nil
}
func firstMissingVar(subgraph *TemplateSubgraph, vars map[string]string) string {
for _, v := range extractRequiredVariables(subgraph) {
if _, ok := vars[v]; !ok {
return v
}
}
return ""
}
func renderWispCreateDryRun(protoID string, subgraph *TemplateSubgraph, vars map[string]string, rootOnly bool) {
if rootOnly {
skipped := len(subgraph.Issues) - 1
fmt.Printf("\nDry run: would create wisp with 1 issue (root only) from proto %s\n", protoID)
if skipped > 0 {
fmt.Printf(" Note: %d child step(s) skipped (--root-only)\n", skipped)
}
} else {
fmt.Printf("\nDry run: would create wisp with %d issues from proto %s\n\n", len(subgraph.Issues), protoID)
}
fmt.Printf("Storage: main database (ephemeral=true, not synced via git)\n\n")
issuesToShow := subgraph.Issues
if rootOnly && len(issuesToShow) > 0 {
issuesToShow = issuesToShow[:1]
}
for _, issue := range issuesToShow {
newTitle := substituteVariables(issue.Title, vars)
fmt.Printf(" - %s (from %s)\n", newTitle, issue.ID)
}
}
func renderWispCreateResult(result *InstantiateResult) {
if jsonOutput {
type wispCreateResult struct {
*InstantiateResult
Phase string `json:"phase"`
}
return outputJSON(wispCreateResult{result, "vapor"})
_ = outputJSON(wispCreateResult{result, "vapor"})
return
}
fmt.Printf("%s Created wisp: %d issues\n", ui.RenderPass("✓"), result.Created)
@ -313,7 +345,6 @@ func runWispCreateCore(cmd *cobra.Command, args []string) error {
fmt.Printf(" bd close %s.<step> # Complete steps\n", result.NewEpicID)
fmt.Printf(" bd mol squash %s # Condense to digest (promotes to persistent)\n", result.NewEpicID)
fmt.Printf(" bd mol burn %s # Discard without creating digest\n", result.NewEpicID)
return nil
}
// isProtoIssue checks if an issue is a proto (has the template label)
@ -376,30 +407,7 @@ Examples:
RunE: runWispList,
}
func runWispList(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("wisp-list")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
ctx := rootCtx
showAll, _ := cmd.Flags().GetBool("all")
typeFilter, _ := cmd.Flags().GetString("type")
if store == nil {
if jsonOutput {
return outputJSON(WispListResult{
Wisps: []WispListItem{},
Count: 0,
})
}
fmt.Println("No database connection")
return nil
}
func wispListFilter(typeFilter string) types.IssueFilter {
ephemeralFlag := true
filter := types.IssueFilter{
Ephemeral: &ephemeralFlag,
@ -409,12 +417,10 @@ func runWispList(cmd *cobra.Command, args []string) error {
it := types.IssueType(typeFilter)
filter.IssueType = &it
}
issues, err := store.SearchIssues(ctx, "", filter)
if err != nil {
return HandleError("listing wisps: %v", err)
}
return filter
}
// Filter closed issues unless --all is specified
func buildWispListResult(issues []*types.Issue, showAll bool) WispListResult {
if !showAll {
var filtered []*types.Issue
for _, issue := range issues {
@ -425,7 +431,6 @@ func runWispList(cmd *cobra.Command, args []string) error {
issues = filtered
}
// Convert to list items and detect old wisps
now := time.Now()
items := make([]WispListItem, 0, len(issues))
oldCount := 0
@ -441,68 +446,95 @@ func runWispList(cmd *cobra.Command, args []string) error {
CreatedAt: issue.CreatedAt,
UpdatedAt: issue.UpdatedAt,
}
// Check if old (not updated in 24+ hours)
if now.Sub(issue.UpdatedAt) > OldThreshold {
item.Old = true
oldCount++
}
items = append(items, item)
}
// Sort by updated_at descending (most recent first)
slices.SortFunc(items, func(a, b WispListItem) int {
return b.UpdatedAt.Compare(a.UpdatedAt) // descending order
return b.UpdatedAt.Compare(a.UpdatedAt)
})
result := WispListResult{
return WispListResult{
Wisps: items,
Count: len(items),
OldCount: oldCount,
}
}
func renderWispListResult(result WispListResult) {
if jsonOutput {
return outputJSON(result)
_ = outputJSON(result)
return
}
if len(items) == 0 {
if len(result.Wisps) == 0 {
fmt.Println("No wisps found")
return nil
return
}
fmt.Printf("Wisps (%d):\n\n", len(items))
// Print header
fmt.Printf("Wisps (%d):\n\n", len(result.Wisps))
fmt.Printf("%-12s %-10s %-4s %-10s %-46s %s\n",
"ID", "STATUS", "PRI", "TYPE", "TITLE", "UPDATED")
fmt.Println(strings.Repeat("-", 100))
for _, item := range items {
// Truncate title if too long
for _, item := range result.Wisps {
title := item.Title
if len(title) > 44 {
title = title[:41] + "..."
}
// Format status with color
status := ui.RenderStatus(item.Status)
// Format updated time
updated := formatTimeAgo(item.UpdatedAt)
if item.Old {
updated = ui.RenderWarn(updated + " ⚠")
}
fmt.Printf("%-12s %-10s P%-3d %-10s %-46s %s\n",
item.ID, status, item.Priority, item.Type, title, updated)
}
if oldCount > 0 {
if result.OldCount > 0 {
fmt.Printf("\n%s %d old wisp(s) (not updated in 24+ hours)\n",
ui.RenderWarn("⚠"), oldCount)
ui.RenderWarn("⚠"), result.OldCount)
fmt.Println(" Hint: Use 'bd mol wisp gc' to clean up old wisps")
}
}
func runWispList(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("wisp-list")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
showAll, _ := cmd.Flags().GetBool("all")
typeFilter, _ := cmd.Flags().GetString("type")
if usesProxiedServer() {
return runWispListProxiedServer(rootCtx, showAll, typeFilter)
}
ctx := rootCtx
if store == nil {
if jsonOutput {
return outputJSON(WispListResult{
Wisps: []WispListItem{},
Count: 0,
})
}
fmt.Println("No database connection")
return nil
}
issues, err := store.SearchIssues(ctx, "", wispListFilter(typeFilter))
if err != nil {
return HandleError("listing wisps: %v", err)
}
renderWispListResult(buildWispListResult(issues, showAll))
return nil
}
@ -629,7 +661,7 @@ type WispGCResult struct {
// sibling destructive command in purge.go. Reading them is required, not
// best-effort: if we cannot enumerate them we must not under-protect and risk
// deleting live molecule steps, so the error propagates and aborts the GC.
func protectedWispStatuses(ctx context.Context) (map[types.Status]bool, error) {
func protectedWispStatuses(ctx context.Context, r molReader) (map[types.Status]bool, error) {
protected := make(map[types.Status]bool)
for _, s := range []types.Status{
types.StatusOpen,
@ -646,7 +678,7 @@ func protectedWispStatuses(ctx context.Context) (map[types.Status]bool, error) {
}
}
customStatuses, err := store.GetCustomStatusesDetailed(ctx)
customStatuses, err := r.GetCustomStatusesDetailed(ctx)
if err != nil {
return nil, fmt.Errorf("reading custom statuses for wisp age GC: %w", err)
}
@ -708,124 +740,29 @@ func runWispGC(cmd *cobra.Command, args []string) error {
}
}
if store == nil {
return HandleErrorWithHint("no database connection", diagHint())
}
var excludeTypes []types.IssueType
for _, t := range excludeTypeStrs {
excludeTypes = append(excludeTypes, types.IssueType(t))
}
if usesProxiedServer() {
return runWispGCProxiedServer(rootCtx, dryRun, ageThreshold, cleanAll, closedMode, force, excludeTypes)
}
if store == nil {
return HandleErrorWithHint("no database connection", diagHint())
}
if closedMode {
return runWispPurgeClosed(ctx, dryRun, force, excludeTypes)
}
ephemeralFlag := true
filter := types.IssueFilter{
Ephemeral: &ephemeralFlag,
ExcludeTypes: excludeTypes,
Limit: 5000,
abandoned, err := findAbandonedWisps(ctx, store, cleanAll, ageThreshold, excludeTypes)
if err != nil && abandoned == nil {
return HandleError("%v", err)
}
issues, err := store.SearchIssues(ctx, "", filter)
if err != nil {
return HandleError("listing wisps: %v", err)
}
// Wisps that are still actively blocked on an open dependency are live
// molecule steps waiting their turn, not abandoned. is_blocked is derived
// state and a recompute deliberately does NOT bump updated_at, so a step
// that has been waiting longer than --age otherwise looks stale and gets
// reclaimed mid-execution, killing the molecule (GH#4394).
//
// Determining blocked state is required, not best-effort. Falling back to
// an empty set on error would silently re-expose every live blocked step to
// deletion, and status is not a usable substitute because is_blocked is
// derived state independent of it (a blocked-but-status=open step would
// lose all protection). Abort instead.
blocked, bErr := store.GetBlockedIssues(ctx, types.WorkFilter{})
if bErr != nil {
return HandleError("determining blocked wisps for age GC: %v", bErr)
}
blockedSet := make(map[string]bool, len(blocked))
for _, b := range blocked {
blockedSet[b.ID] = true
}
protectedStatuses, psErr := protectedWispStatuses(ctx)
if psErr != nil {
return HandleError("%v", psErr)
}
// Find old/abandoned wisps
now := time.Now()
var abandoned []*types.Issue
for _, issue := range issues {
// Never GC infrastructure beads (configured via types.infra)
if store.IsInfraTypeCtx(ctx, issue.IssueType) {
continue
}
// Skip closed issues unless --all is specified
if issue.Status == types.StatusClosed && !cleanAll {
continue
}
// Never reclaim active wisps by age — blocked/in-progress steps are
// live molecule work, not abandoned (GH#4394).
if isProtectedWisp(issue, blockedSet, protectedStatuses) {
continue
}
// Check if old (not updated within age threshold)
if now.Sub(issue.UpdatedAt) > ageThreshold {
abandoned = append(abandoned, issue)
}
}
// Cascade: expand to include blocked step children of abandoned wisps.
// Without this, deleting a parent formula wisp leaves its dependent step
// wisps as permanent orphans (they have no other references keeping them alive).
if len(abandoned) > 0 {
parentIDs := make([]string, len(abandoned))
for i, issue := range abandoned {
parentIDs[i] = issue.ID
}
childIDs, err := store.FindWispDependentsRecursive(ctx, parentIDs)
if err != nil {
// Log but don't fail the GC — partial cascade is better than none
fmt.Fprintf(cmd.ErrOrStderr(), "Warning: cascade expansion incomplete: %v\n", err)
}
if len(childIDs) > 0 {
// Fetch the child wisps and add them to the abandoned set
childIDSlice := make([]string, 0, len(childIDs))
for id := range childIDs {
childIDSlice = append(childIDSlice, id)
}
childIssues, fetchErr := store.GetIssuesByIDs(ctx, childIDSlice)
if fetchErr == nil {
abandonedSet := make(map[string]bool, len(abandoned))
for _, issue := range abandoned {
abandonedSet[issue.ID] = true
}
for _, child := range childIssues {
if abandonedSet[child.ID] {
continue
}
// Never cascade to infra types
if store.IsInfraTypeCtx(ctx, child.IssueType) {
continue
}
// Never cascade into active wisps — a blocked/in-progress
// step is live work even if its parent looks abandoned
// (GH#4394).
if isProtectedWisp(child, blockedSet, protectedStatuses) {
continue
}
abandoned = append(abandoned, child)
}
}
}
fmt.Fprintf(cmd.ErrOrStderr(), "Warning: cascade expansion incomplete: %v\n", err)
}
if len(abandoned) == 0 {
@ -872,6 +809,86 @@ func runWispGC(cmd *cobra.Command, args []string) error {
return nil
}
func findAbandonedWisps(ctx context.Context, r molReader, cleanAll bool, ageThreshold time.Duration, excludeTypes []types.IssueType) ([]*types.Issue, error) {
ephemeralFlag := true
filter := types.IssueFilter{
Ephemeral: &ephemeralFlag,
ExcludeTypes: excludeTypes,
Limit: 5000,
}
issues, err := r.SearchIssues(ctx, "", filter)
if err != nil {
return nil, err
}
blocked, err := r.GetBlockedIssues(ctx, types.WorkFilter{})
if err != nil {
return nil, fmt.Errorf("determining blocked wisps for age GC: %w", err)
}
blockedSet := make(map[string]bool, len(blocked))
for _, b := range blocked {
blockedSet[b.ID] = true
}
protectedStatuses, err := protectedWispStatuses(ctx, r)
if err != nil {
return nil, err
}
now := time.Now()
var abandoned []*types.Issue
for _, issue := range issues {
if r.IsInfraTypeCtx(ctx, issue.IssueType) {
continue
}
if issue.Status == types.StatusClosed && !cleanAll {
continue
}
if isProtectedWisp(issue, blockedSet, protectedStatuses) {
continue
}
if now.Sub(issue.UpdatedAt) > ageThreshold {
abandoned = append(abandoned, issue)
}
}
if len(abandoned) == 0 {
return abandoned, nil
}
parentIDs := make([]string, len(abandoned))
for i, issue := range abandoned {
parentIDs[i] = issue.ID
}
childIDs, cascadeErr := r.FindWispDependentsRecursive(ctx, parentIDs)
if len(childIDs) > 0 {
childIDSlice := make([]string, 0, len(childIDs))
for id := range childIDs {
childIDSlice = append(childIDSlice, id)
}
childIssues, fetchErr := r.GetIssuesByIDs(ctx, childIDSlice)
if fetchErr == nil {
abandonedSet := make(map[string]bool, len(abandoned))
for _, issue := range abandoned {
abandonedSet[issue.ID] = true
}
for _, child := range childIssues {
if abandonedSet[child.ID] {
continue
}
if r.IsInfraTypeCtx(ctx, child.IssueType) {
continue
}
if isProtectedWisp(child, blockedSet, protectedStatuses) {
continue
}
abandoned = append(abandoned, child)
}
}
}
return abandoned, cascadeErr
}
func runWispPurgeClosed(ctx context.Context, dryRun bool, force bool, excludeTypes []types.IssueType) error {
statusClosed := types.StatusClosed
ephemeralTrue := true

View file

@ -0,0 +1,293 @@
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
)
func runWispCreateProxiedServer(ctx context.Context, in wispCreateInput) error {
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
vars, err := parseVarFlags(in.varFlags)
if err != nil {
return HandleError("%v", err)
}
var formulaSubgraph *TemplateSubgraph
var formulaProtoID string
if sg, err := resolveAndCookFormulaWithVars(in.protoArg, nil, vars); err == nil {
formulaSubgraph = sg
formulaProtoID = sg.Root.ID
}
if formulaSubgraph == nil {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
r := uowMolReader{uw: uw}
protoID, err := resolveMolID(ctx, r, in.protoArg)
if err != nil {
uw.Close(ctx)
return HandleErrorWithHint(fmt.Sprintf("'%s' not found as formula or proto", in.protoArg), "run 'bd formula list' to see available formulas")
}
protoIssue, err := r.GetIssue(ctx, protoID)
if err != nil {
uw.Close(ctx)
return HandleError("loading proto %s: %v", protoID, err)
}
if !isProtoIssue(protoIssue) {
uw.Close(ctx)
return HandleError("%s is not a proto (missing '%s' label)", protoID, MoleculeLabel)
}
sg, err := loadTemplateSubgraph(ctx, r, protoID)
uw.Close(ctx)
if err != nil {
return HandleError("loading proto: %v", err)
}
formulaSubgraph = sg
formulaProtoID = protoID
}
subgraph := formulaSubgraph
protoID := formulaProtoID
vars = applyVariableDefaults(vars, subgraph)
if err := checkRequiredVars(subgraph, vars); err != nil {
return HandleErrorWithHint(err.Error(), fmt.Sprintf("Provide them with: --var %s=<value>", firstMissingVar(subgraph, vars)))
}
if in.dryRun {
renderWispCreateDryRun(protoID, subgraph, vars, in.rootOnly)
return nil
}
result, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (*InstantiateResult, string, error) {
w := newUOWMolWriter(uw)
spawnResult, err := cloneSubgraphInto(ctx, w, subgraph, CloneOptions{
Vars: vars,
Actor: actor,
Ephemeral: true,
Prefix: types.IDPrefixWisp,
RootOnly: in.rootOnly,
})
if err != nil {
return nil, "", fmt.Errorf("creating wisp: %w", err)
}
return spawnResult, fmt.Sprintf("bd: wisp create %s", protoID), nil
})
if err != nil {
return HandleError("%v", err)
}
renderWispCreateResult(result)
return nil
}
func runWispListProxiedServer(ctx context.Context, showAll bool, typeFilter string) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
r := uowMolReader{uw: uw}
issues, err := r.SearchIssues(ctx, "", wispListFilter(typeFilter))
if err != nil {
return HandleError("listing wisps: %v", err)
}
renderWispListResult(buildWispListResult(issues, showAll))
return nil
}
func runWispGCProxiedServer(ctx context.Context, dryRun bool, ageThreshold time.Duration, cleanAll, closedMode, force bool, excludeTypes []types.IssueType) error {
CheckReadonly("wisp gc")
if uowProvider == nil {
return HandleError("proxied-server UOW provider not initialized")
}
if closedMode {
return runWispPurgeClosedProxiedServer(ctx, dryRun, force, excludeTypes)
}
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
r := uowMolReader{uw: uw}
abandoned, err := findAbandonedWisps(ctx, r, cleanAll, ageThreshold, excludeTypes)
uw.Close(ctx)
if err != nil && abandoned == nil {
return HandleError("%v", err)
}
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: cascade expansion incomplete: %v\n", err)
}
if len(abandoned) == 0 {
if jsonOutput {
return outputJSON(WispGCResult{CleanedIDs: []string{}, CleanedCount: 0, DryRun: dryRun})
}
fmt.Println("No abandoned wisps found")
return nil
}
if dryRun {
if jsonOutput {
ids := make([]string, len(abandoned))
for i, o := range abandoned {
ids[i] = o.ID
}
return outputJSON(WispGCResult{CleanedIDs: ids, Candidates: len(abandoned), CleanedCount: 0, DryRun: true})
}
fmt.Printf("Dry run: would clean %d abandoned wisp(s):\n\n", len(abandoned))
for _, issue := range abandoned {
age := formatTimeAgo(issue.UpdatedAt)
fmt.Printf(" %s: %s (last updated: %s)\n", issue.ID, issue.Title, age)
}
fmt.Printf("\nRun without --dry-run to delete these wisps.\n")
return nil
}
ids := make([]string, len(abandoned))
for i, issue := range abandoned {
ids[i] = issue.ID
}
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeleteIssuesResult, string, error) {
res, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: ids,
Cascade: true,
UpdateTextReferences: true,
}, actor)
if err != nil {
return domain.DeleteIssuesResult{}, "", err
}
return res, fmt.Sprintf("bd: wisp gc %d", res.DeletedCount), nil
})
if err != nil {
return HandleError("%v", err)
}
if jsonOutput {
return outputJSON(WispGCResult{CleanedIDs: ids, CleanedCount: res.DeletedCount})
}
fmt.Printf("Cleaned %d abandoned wisp(s)\n", res.DeletedCount)
return nil
}
func runWispPurgeClosedProxiedServer(ctx context.Context, dryRun, force bool, excludeTypes []types.IssueType) error {
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
r := uowMolReader{uw: uw}
statusClosed := types.StatusClosed
ephemeralTrue := true
filter := types.IssueFilter{
Status: &statusClosed,
Ephemeral: &ephemeralTrue,
ExcludeTypes: excludeTypes,
Limit: 5000,
}
closedIssues, err := r.SearchIssues(ctx, "", filter)
uw.Close(ctx)
if err != nil {
return HandleError("listing closed wisps: %v", err)
}
pinnedCount := 0
infraCount := 0
filtered := make([]*types.Issue, 0, len(closedIssues))
for _, issue := range closedIssues {
if issue.Pinned {
pinnedCount++
continue
}
if r.IsInfraTypeCtx(ctx, issue.IssueType) {
infraCount++
continue
}
filtered = append(filtered, issue)
}
closedIssues = filtered
if pinnedCount > 0 && !jsonOutput {
fmt.Printf("Skipping %d pinned issue(s) (protected from cleanup)\n", pinnedCount)
}
if infraCount > 0 && !jsonOutput {
fmt.Printf("Skipping %d configured infra issue(s) protected from GC\n", infraCount)
}
if len(closedIssues) == 0 {
if jsonOutput {
return outputJSON(map[string]interface{}{
"deleted_count": 0,
"message": "No closed wisps to delete",
})
}
fmt.Println("No closed wisps to delete")
return nil
}
ids := make([]string, len(closedIssues))
for i, issue := range closedIssues {
ids[i] = issue.ID
}
if !force && !dryRun {
if jsonOutput {
return outputJSON(map[string]interface{}{
"candidates": len(ids),
"dry_run": true,
})
}
fmt.Printf("Found %d closed wisp(s) to delete\n", len(ids))
fmt.Printf("\nUse --force to proceed, or --dry-run for detailed preview.\n")
return nil
}
if dryRun {
if jsonOutput {
return outputJSON(map[string]interface{}{
"candidates": len(ids),
"dry_run": true,
})
}
fmt.Printf("Found %d closed wisp(s)\n", len(ids))
fmt.Println("DRY RUN - no changes will be made")
return nil
}
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeleteIssuesResult, string, error) {
res, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: ids,
Cascade: true,
UpdateTextReferences: true,
}, actor)
if err != nil {
return domain.DeleteIssuesResult{}, "", err
}
return res, fmt.Sprintf("bd: wisp gc --closed %d", res.DeletedCount), nil
})
if err != nil {
return HandleError("%v", err)
}
if jsonOutput {
return outputJSON(map[string]interface{}{"deleted_count": res.DeletedCount})
}
fmt.Printf("Deleted %d closed wisp(s)\n", res.DeletedCount)
return nil
}

View file

@ -864,6 +864,10 @@ func (r *issueSQLRepositoryImpl) FindAllDependents(ctx context.Context, ids []st
return out, nil
}
func (r *issueSQLRepositoryImpl) FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error) {
return issueops.FindWispDependentsRecursiveInTx(ctx, r.runner, ids)
}
func (r *issueSQLRepositoryImpl) AffectedByDeletion(ctx context.Context, issueIDs, wispIDs []string) ([]string, []string, error) {
return issueops.AffectedByDeletionInTx(ctx, r.runner, issueIDs, wispIDs)
}

View file

@ -53,6 +53,7 @@ type IssueSQLRepository interface {
DeleteByIDs(ctx context.Context, ids []string, opts IssueTableOpts) (int, error)
PartitionWispIDs(ctx context.Context, ids []string) (wispIDs, regularIDs []string, err error)
FindAllDependents(ctx context.Context, ids []string) ([]string, error)
FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error)
AffectedByDeletion(ctx context.Context, issueIDs, wispIDs []string) (affectedIssues, affectedWisps []string, err error)
RecomputeIsBlocked(ctx context.Context, issueIDs, wispIDs []string) error
Close(ctx context.Context, id string, params CloseRowParams, actor string, opts IssueTableOpts) (CloseRowResult, error)
@ -251,6 +252,7 @@ type UpdateSpec struct {
type IssueUseCase interface {
GetIssue(ctx context.Context, id string) (*types.Issue, error)
GetIssuesByIDs(ctx context.Context, ids []string) ([]*types.Issue, error)
FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error)
SearchIssues(ctx context.Context, query string, filter types.IssueFilter) (SearchPage, error)
SearchIssuesWithCounts(ctx context.Context, query string, filter types.IssueFilter) (SearchCountsPage, error)
GetReadyWork(ctx context.Context, filter types.WorkFilter) (SearchPage, error)
@ -395,6 +397,10 @@ func (u *issueUseCaseImpl) GetIssuesByIDs(ctx context.Context, ids []string) ([]
return u.getByIDs(ctx, ids, false)
}
func (u *issueUseCaseImpl) FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error) {
return u.issueRepo.FindWispDependentsRecursive(ctx, ids)
}
func (u *issueUseCaseImpl) GetWispsByIDs(ctx context.Context, ids []string) ([]*types.Issue, error) {
return u.getByIDs(ctx, ids, true)
}

View file

@ -286,7 +286,7 @@ func updateWispIDInTx(ctx context.Context, tx *sql.Tx, oldID, newID string, issu
// FindWispDependentsRecursiveInTx walks wisp_dependencies to find all transitive
// dependents of the given IDs.
func FindWispDependentsRecursiveInTx(ctx context.Context, tx *sql.Tx, ids []string) (map[string]bool, error) {
func FindWispDependentsRecursiveInTx(ctx context.Context, tx DBTX, ids []string) (map[string]bool, error) {
if len(ids) == 0 {
return nil, nil
}