beads/cmd/bd/quick.go
Julian Knutsen 3ef94a084a
fix(create): commit issue and dependency edges in one transaction (#4731)
* fix(create): commit issue and dependency edges in one transaction

The sqlite concurrency audit (defect #3, MED) found that `bd create
--deps` commits the new issue in one transaction and then adds each
requested edge in its own transaction with warn-only error handling: a
dep-add hitting SQLITE_BUSY still exits 0 with valid JSON, leaving a
dep-less bead behind that is permanently READY, so an orchestrator
polling `bd ready` dispatches it before its prerequisites exist.
Red-team reproduction against a queued BEGIN IMMEDIATE lock holder
confirmed it empirically: the stock binary silently dropped edges in 6
of 13 forty-edge create races (five rounds committed 33/40, one 30/40,
all exit 0 with warnings only on stderr).

createIssueWithDeps now persists the create and every --parent/--deps/
--waits-for edge in one store transaction; any edge failure is fatal,
names the failing edge, and rolls back the create. Under the same race
the fixed binary went 20/20 rounds with all 40/40 edges committed and
zero warnings. Dolt server mode splits one logical transaction across
two SQL sessions (versioned vs dolt-ignored tables), so cross-tier
edges gained a target precheck on the session that owns the target
table, a cycle check over the merged two-session graph, and a scoped
FK suspension for wisp-source edges whose issue target is still
uncommitted on the other session.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(create-deps): repair regression test backend, close mixed-tier cycle gap, cut complexity

Maintainer review fixes for the create-time dependency atomicity PR.

- TestCreateDepsAtomicity initialized the removed `--backend sqlite`, so
  `go test ./cmd/bd` was red and the orphan-bead regression coverage never
  ran. Switch it to the supported Dolt backend (the subprocess binary is
  built with gms_pure_go embedded Dolt) and give the subprocess a hermetic
  env that strips ambient BEADS_/BD_ config and pins an isolated BEADS_DIR,
  so a shared Dolt server or real workspace cannot leak in.

- A create-time batch like `blocks:<wisp>,depends-on:<regular>` could commit
  a scheduling cycle: the merged two-session cycle check only ran when the
  edge being added was itself cross-tier, so a same-tier closing edge missed
  an earlier uncommitted cross-tier edge on the other session. Track which
  dependency tiers a logical transaction has written and force the merged
  CycleThroughEdges check once both tiers are in play. Add a regression for
  the cross-tier-first, same-tier-closing ordering.

- Extract addParentEdge/addDepSpecEdges/addWaitsForEdge from
  createIssueWithDeps, dropping its cognitive complexity from 27 to 10 while
  preserving atomic create-plus-edges behavior and error messages.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Test User <test@test.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-07-18 07:15:40 -07:00

111 lines
3.4 KiB
Go

package main
import (
"errors"
"fmt"
"strings"
"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/validation"
)
var quickCmd = &cobra.Command{
Use: "q [title]",
GroupID: "issues",
Short: "Quick capture: create issue and output only ID",
Long: `Quick capture creates an issue and outputs only the issue ID.
Designed for scripting and AI agent integration.
Example:
bd q "Fix login bug" # Outputs: bd-a1b2
ISSUE=$(bd q "New feature") # Capture ID in variable
bd q "Task" | xargs bd show # Pipe to other commands
bd q "Subtask" --parent=bd-a1b2 # Hierarchical child (outputs: bd-a1b2.1)`,
Args: cobra.MinimumNArgs(1),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
// Create the event before the readonly guard so the operation label
// matches this command ("q", not "create") and the readonly exit path
// still flushes queued metrics via CheckReadonly's CloseAndFlush.
evt := metrics.NewCommandEvent("q")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
CheckReadonly("q")
if usesProxiedServer() {
return runQuickProxiedServer(cmd, rootCtx, args)
}
title := strings.Join(args, " ")
priorityStr, _ := cmd.Flags().GetString("priority")
issueType, _ := cmd.Flags().GetString("type")
labels, _ := cmd.Flags().GetStringSlice("labels")
parentID, _ := cmd.Flags().GetString("parent")
priority, err := validation.ValidatePriority(priorityStr)
if err != nil {
return HandleError("%v", err)
}
ctx := rootCtx
// Mirrors bd create's parent handling: validate the parent exists,
// inherit its labels, and reserve a hierarchical child ID.
var inheritedLabels []string
if parentID != "" {
if _, err := store.GetIssue(ctx, parentID); err != nil {
if errors.Is(err, storage.ErrNotFound) {
return HandleError("parent issue %s not found", parentID)
}
return HandleError("failed to check parent issue: %v", err)
}
inheritedLabels, _ = store.GetLabels(ctx, parentID)
}
issue := &types.Issue{
Title: title,
Status: types.StatusOpen,
Priority: priority,
IssueType: types.IssueType(issueType).Normalize(),
Labels: mergeCreateLabels(labels, inheritedLabels),
}
if parentID != "" {
childID, err := store.GetNextChildID(ctx, parentID)
if err != nil {
return HandleError("%v", err)
}
issue.ID = childID
ctx = storage.WithReservedChildCounter(ctx, parentID, childID)
}
// The issue and its parent-child edge commit in one transaction; a
// failed edge rolls back the create instead of leaving a dep-less
// child behind (same contract as bd create).
if err := createIssueWithDeps(ctx, store, issue, actor, createDepEdges{parentID: parentID}); err != nil {
return HandleError("%v", err)
}
commandDidWrite.Store(true)
fmt.Println(issue.ID)
return nil
},
}
func init() {
quickCmd.Flags().StringP("priority", "p", "2", "Priority (0-4 or P0-P4)")
quickCmd.Flags().StringP("type", "t", "task", "Issue type")
quickCmd.Flags().StringSliceP("labels", "l", []string{}, "Labels")
quickCmd.Flags().String("parent", "", "Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9')")
rootCmd.AddCommand(quickCmd)
}