/{cmd,docs}: remove FatalError* use HandleError*

This commit is contained in:
coffeegoddd☕️✨ 2026-07-07 14:51:51 -07:00
commit 5d87c30015
35 changed files with 649 additions and 558 deletions

View file

@ -1068,8 +1068,6 @@ func TestCLI_CreateDryRun(t *testing.T) {
})
t.Run("DryRunWithFileReturnsError", func(t *testing.T) {
// This test must use exec.Command because FatalError calls os.Exit(1)
// which would kill the test process if run in-process
tmpDir := createTempDirWithCleanup(t)
// Initialize the database first

View file

@ -46,8 +46,7 @@ the flags appear in the command line.`,
}()
if usesProxiedServer() {
runCloseProxiedServer(cmd, rootCtx, args)
return nil
return runCloseProxiedServer(cmd, rootCtx, args)
}
// If no IDs provided, use last touched issue

View file

@ -35,35 +35,35 @@ type closeProxiedOutcome struct {
closed bool
}
func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
if len(args) == 0 {
FatalErrorRespectJSON("no issue ID provided")
return HandleErrorRespectJSON("no issue ID provided")
}
reasons, updatedArgs, err := resolveCloseReasons(cmd, args)
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
args = updatedArgs
if err := validateCloseReasons(reasons); err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
in := gatherCloseProxiedInput(cmd)
if in.continueOn && len(args) > 1 {
FatalErrorRespectJSON("--continue only works when closing a single issue")
return HandleErrorRespectJSON("--continue only works when closing a single issue")
}
if in.suggestNext && len(args) > 1 {
FatalErrorRespectJSON("--suggest-next only works when closing a single issue")
return HandleErrorRespectJSON("--suggest-next only works when closing a single issue")
}
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return HandleErrorRespectJSON("open unit of work: %v", err)
}
defer uw.Close(ctx)
@ -101,7 +101,7 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
if len(outcomes) > 0 {
msg := closeProxiedCommitMessage(outcomes, claimedNextIssue, continueResult)
if err := uw.Commit(ctx, msg); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("commit close: %v", err)
return HandleErrorRespectJSON("commit close: %v", err)
}
for _, o := range outcomes {
if !o.closed {
@ -144,6 +144,7 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
if len(args) > 0 && len(outcomes) == 0 {
os.Exit(1)
}
return nil
}
func gatherCloseProxiedInput(cmd *cobra.Command) closeProxiedInput {

View file

@ -36,8 +36,10 @@ var (
)
var compactCmd = &cobra.Command{
Use: "compact",
Short: "Compact old closed issues to save space",
Use: "compact",
Short: "Compact old closed issues to save space",
SilenceUsage: true,
SilenceErrors: true,
Long: `Compact old closed issues using semantic summarization.
Compaction reduces database size by summarizing closed issues that are no longer
@ -78,11 +80,11 @@ Examples:
# Statistics
bd compact --stats # Show statistics
`,
Run: func(_ *cobra.Command, _ []string) {
RunE: func(_ *cobra.Command, _ []string) error {
// Block mutating operations in embedded mode; allow --stats, --analyze, --dry-run read-only paths.
if !compactStats && !compactAnalyze && !compactDryRun {
if err := requireServerMode("compact"); err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
}
// Compact modifies data unless --stats or --analyze or --dry-run or --dolt with --dry-run
@ -94,13 +96,12 @@ Examples:
// Handle compact stats first
if compactStats {
runCompactStats(ctx, store)
return
return nil
}
// Handle dolt GC mode
if compactDolt {
runCompactDolt()
return
return runCompactDolt()
}
// Count active modes
@ -140,7 +141,7 @@ Examples:
os.Exit(1)
}
runCompactAnalyze(ctx, store)
return
return nil
}
// Handle apply mode (requires direct database access)
@ -159,7 +160,7 @@ Examples:
os.Exit(1)
}
runCompactApply(ctx, store)
return
return nil
}
// Handle auto mode (legacy)
@ -202,11 +203,12 @@ Examples:
if compactID != "" {
runCompactSingle(ctx, compactor, store, compactID)
return
return nil
}
runCompactAll(ctx, compactor, store)
}
return nil
},
}
@ -771,13 +773,13 @@ func runCompactApply(ctx context.Context, store storage.DoltStorage) {
}
// runCompactDolt runs Dolt garbage collection on the .beads/dolt directory
func runCompactDolt() {
func runCompactDolt() error {
start := time.Now()
// Find beads directory
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
// Check for dolt directory
@ -793,12 +795,12 @@ func runCompactDolt() {
if err := outputJSON(output); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
fmt.Printf("DRY RUN - Dolt garbage collection\n\n")
fmt.Printf("Dolt directory: %s\n", doltPath)
fmt.Printf("No local Dolt directory found; nothing to collect.\n")
return
return nil
}
fmt.Fprintf(os.Stderr, "Error: Dolt directory not found at %s\n", doltPath)
fmt.Fprintf(os.Stderr, "Hint: --dolt flag is only for repositories using the Dolt backend\n")
@ -823,13 +825,13 @@ func runCompactDolt() {
if err := outputJSON(output); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
fmt.Printf("DRY RUN - Dolt garbage collection\n\n")
fmt.Printf("Dolt directory: %s\n", doltPath)
fmt.Printf("Current size: %s\n", formatBytes(sizeBefore))
fmt.Printf("\nRun without --dry-run to perform garbage collection.\n")
return
return nil
}
// Check if dolt command is available
@ -881,12 +883,13 @@ func runCompactDolt() {
if err := outputJSON(result); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
fmt.Printf("✓ Dolt garbage collection complete\n")
fmt.Printf(" %s → %s (freed %s)\n", formatBytes(sizeBefore), formatBytes(sizeAfter), formatBytes(freed))
fmt.Printf(" Time: %v\n", elapsed)
return nil
}
// getDirSize calculates the total size of a directory recursively

View file

@ -190,8 +190,7 @@ var configSetCmd = &cobra.Command{
}
if usesProxiedServer() {
runConfigSetProxiedServer(rootCtx, key, value)
return nil
return runConfigSetProxiedServer(rootCtx, key, value)
}
// Database-stored config requires direct mode
@ -307,8 +306,7 @@ var configGetCmd = &cobra.Command{
}
if usesProxiedServer() {
runConfigGetProxiedServer(rootCtx, key)
return nil
return runConfigGetProxiedServer(rootCtx, key)
}
// Database-stored config requires direct mode
@ -355,8 +353,7 @@ var configListCmd = &cobra.Command{
}()
if usesProxiedServer() {
runConfigListProxiedServer(rootCtx)
return nil
return runConfigListProxiedServer(rootCtx)
}
// Config operations work in direct mode only
@ -529,8 +526,7 @@ var configUnsetCmd = &cobra.Command{
}
if usesProxiedServer() {
runConfigUnsetProxiedServer(rootCtx, key)
return nil
return runConfigUnsetProxiedServer(rootCtx, key)
}
// Database-stored config requires direct mode
@ -809,7 +805,9 @@ Examples:
keys[i] = p.key
values[i] = p.value
}
runConfigSetManyProxiedServer(rootCtx, keys, values)
if err := runConfigSetManyProxiedServer(rootCtx, keys, values); err != nil {
return err
}
} else {
if err := ensureDirectMode("config set-many requires direct database access"); err != nil {
return HandleError("%v", err)

View file

@ -9,33 +9,36 @@ import (
"github.com/steveyegge/beads/internal/types"
)
func openConfigProxiedUOW(ctx context.Context) uow.UnitOfWork {
func openConfigProxiedUOW(ctx context.Context) (uow.UnitOfWork, error) {
if uowProvider == nil {
FatalErrorRespectJSON("proxied-server UOW provider not initialized")
return nil, HandleErrorRespectJSON("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return nil, HandleErrorRespectJSON("open unit of work: %v", err)
}
return uw
return uw, nil
}
func runConfigSetProxiedServer(ctx context.Context, key, value string) {
func runConfigSetProxiedServer(ctx context.Context, key, value string) error {
if key == "status.custom" && value != "" {
if _, err := types.ParseCustomStatusConfig(value); err != nil {
FatalErrorRespectJSON("invalid status.custom value: %v", err)
return HandleErrorRespectJSON("invalid status.custom value: %v", err)
}
}
uw := openConfigProxiedUOW(ctx)
uw, err := openConfigProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
if err := uw.ConfigUseCase().SetConfig(ctx, key, value); err != nil {
FatalErrorRespectJSON("Error setting config: %v", err)
return HandleErrorRespectJSON("Error setting config: %v", err)
}
if err := uw.Commit(ctx, fmt.Sprintf("bd: config set %s", key)); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("failed to commit: %v", err)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
if jsonOutput {
@ -47,15 +50,19 @@ func runConfigSetProxiedServer(ctx context.Context, key, value string) {
fmt.Printf("Set %s = %s\n", key, value)
}
printConfigSideEffects(checkConfigSetSideEffects(key, value))
return nil
}
func runConfigGetProxiedServer(ctx context.Context, key string) {
uw := openConfigProxiedUOW(ctx)
func runConfigGetProxiedServer(ctx context.Context, key string) error {
uw, err := openConfigProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
value, err := uw.ConfigUseCase().GetConfig(ctx, key)
if err != nil {
FatalErrorRespectJSON("Error getting config: %v", err)
return HandleErrorRespectJSON("Error getting config: %v", err)
}
if jsonOutput {
@ -63,32 +70,36 @@ func runConfigGetProxiedServer(ctx context.Context, key string) {
"key": key,
"value": value,
})
return
return nil
}
if value == "" {
fmt.Printf("%s (not set)\n", key)
} else {
fmt.Printf("%s\n", value)
}
return nil
}
func runConfigListProxiedServer(ctx context.Context) {
uw := openConfigProxiedUOW(ctx)
func runConfigListProxiedServer(ctx context.Context) error {
uw, err := openConfigProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
cfg, err := uw.ConfigUseCase().GetAllConfig(ctx)
if err != nil {
FatalErrorRespectJSON("Error listing config: %v", err)
return HandleErrorRespectJSON("Error listing config: %v", err)
}
if jsonOutput {
_ = outputJSON(cfg)
return
return nil
}
if len(cfg) == 0 {
fmt.Println("No configuration set")
return
return nil
}
keys := make([]string, 0, len(cfg))
@ -103,18 +114,22 @@ func runConfigListProxiedServer(ctx context.Context) {
}
showConfigYAMLOverrides(cfg)
return nil
}
func runConfigUnsetProxiedServer(ctx context.Context, key string) {
uw := openConfigProxiedUOW(ctx)
func runConfigUnsetProxiedServer(ctx context.Context, key string) error {
uw, err := openConfigProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
if err := uw.ConfigUseCase().DeleteConfig(ctx, key); err != nil {
FatalErrorRespectJSON("Error deleting config: %v", err)
return HandleErrorRespectJSON("Error deleting config: %v", err)
}
if err := uw.Commit(ctx, fmt.Sprintf("bd: config unset %s", key)); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("failed to commit: %v", err)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
if jsonOutput {
@ -125,23 +140,28 @@ func runConfigUnsetProxiedServer(ctx context.Context, key string) {
fmt.Printf("Unset %s\n", key)
}
printConfigSideEffects(checkConfigUnsetSideEffects(key))
return nil
}
func runConfigSetManyProxiedServer(ctx context.Context, keys, values []string) {
func runConfigSetManyProxiedServer(ctx context.Context, keys, values []string) error {
if len(keys) == 0 {
return
return nil
}
uw, err := openConfigProxiedUOW(ctx)
if err != nil {
return err
}
uw := openConfigProxiedUOW(ctx)
defer uw.Close(ctx)
cfgUC := uw.ConfigUseCase()
for i, k := range keys {
if err := cfgUC.SetConfig(ctx, k, values[i]); err != nil {
FatalErrorRespectJSON("Error setting config %s: %v", k, err)
return HandleErrorRespectJSON("Error setting config %s: %v", k, err)
}
}
if err := uw.Commit(ctx, fmt.Sprintf("bd: config set-many (%d keys)", len(keys))); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("failed to commit: %v", err)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
return nil
}

View file

@ -49,8 +49,7 @@ var createCmd = &cobra.Command{
if err != nil {
return err
}
runCreateProxiedServer(cmd, rootCtx, in)
return nil
return runCreateProxiedServer(cmd, rootCtx, in)
}
file, _ := cmd.Flags().GetString("file")
graphFile, _ := cmd.Flags().GetString("graph")

View file

@ -25,71 +25,73 @@ func resolveProxiedCustomTypes(dbTypes []string) []string {
return config.GetCustomTypesFromYAML()
}
func runCreateProxiedServer(cmd *cobra.Command, ctx context.Context, in createInput) {
func runCreateProxiedServer(cmd *cobra.Command, ctx context.Context, in createInput) error {
if in.repoOverrideSet {
FatalError("--repo is not supported with --proxied-server")
return HandleError("--repo is not supported with --proxied-server")
}
switch {
case in.graphFile != "":
runCreateProxiedGraph(cmd, ctx, in)
return runCreateProxiedGraph(cmd, ctx, in)
case in.markdownFile != "":
runCreateProxiedMarkdown(cmd, ctx, in)
return runCreateProxiedMarkdown(cmd, ctx, in)
default:
runCreateProxiedSingle(cmd, ctx, in)
return runCreateProxiedSingle(cmd, ctx, in)
}
}
func proxiedOpenUOW(ctx context.Context) (uow.UnitOfWork, domain.CreateContext) {
func proxiedOpenUOW(ctx context.Context) (uow.UnitOfWork, domain.CreateContext, error) {
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return nil, domain.CreateContext{}, HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalError("open unit of work: %v", err)
return nil, domain.CreateContext{}, HandleError("open unit of work: %v", err)
}
cctx, err := uw.ConfigUseCase().LoadCreateContext(ctx)
if err != nil {
uw.Close(ctx)
FatalError("load create context: %v", err)
return nil, domain.CreateContext{}, HandleError("load create context: %v", err)
}
return uw, cctx
return uw, cctx, nil
}
func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInput) {
runCreateLintIssue(in)
func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInput) error {
if err := runCreateLintIssue(in); err != nil {
return err
}
if in.explicitID != "" {
if _, err := validation.ValidateIDFormat(in.explicitID); err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
}
deps, err := parseDepSpecs(in.deps)
if err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
waitsFor, err := buildWaitsFor(in.waitsFor, in.waitsForGate)
if err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
if in.dryRun {
previewLabels := in.labels
if in.parentID != "" {
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
dryUW, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalError("open unit of work: %v", err)
return HandleError("open unit of work: %v", err)
}
if _, err := dryUW.IssueUseCase().GetIssue(ctx, in.parentID); err != nil {
dryUW.Close(ctx)
FatalError("parent issue %s not found: %v", in.parentID, err)
return HandleError("parent issue %s not found: %v", in.parentID, err)
}
if !in.noInheritLabels {
inherited, lerr := dryUW.LabelUseCase().GetLabels(ctx, in.parentID)
if lerr != nil {
dryUW.Close(ctx)
FatalError("dry-run inherit labels: %v", lerr)
return HandleError("dry-run inherit labels: %v", lerr)
}
previewLabels = mergeCreateLabels(in.labels, inherited)
}
@ -103,32 +105,35 @@ func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInpu
} else {
renderCreateDryRunPreview(previewIssue, previewLabels, in.deps)
}
return
return nil
}
uw, cctx := proxiedOpenUOW(ctx)
uw, cctx, err := proxiedOpenUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
customTypes := resolveProxiedCustomTypes(cctx.CustomTypes)
if in.issueType != "" {
it := types.IssueType(in.issueType).Normalize()
if !it.IsValidWithCustom(customTypes) {
FatalError("invalid type %q (allowed: built-ins plus configured custom types)", in.issueType)
return HandleError("invalid type %q (allowed: built-ins plus configured custom types)", in.issueType)
}
}
if in.status != "" {
customStatuses, err := uw.ConfigUseCase().GetCustomStatuses(ctx)
if err != nil {
FatalError("failed to get custom statuses: %v", err)
return HandleError("failed to get custom statuses: %v", err)
}
if !types.Status(in.status).IsValidWithCustom(types.CustomStatusNames(customStatuses)) {
FatalErrorRespectJSON("invalid status %q (built-in: open, in_progress, blocked, deferred, closed, pinned, hooked; or configure custom statuses via 'bd config set status.custom')", in.status)
return HandleErrorRespectJSON("invalid status %q (built-in: open, in_progress, blocked, deferred, closed, pinned, hooked; or configure custom statuses via 'bd config set status.custom')", in.status)
}
}
if in.explicitID != "" {
effectivePrefix := overlayYAMLPrefix(cctx.IssuePrefix)
if err := validation.ValidateIDPrefixAllowed(in.explicitID, effectivePrefix, cctx.AllowedPrefixes, in.force); err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
}
@ -152,11 +157,11 @@ func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInpu
result, err = uw.IssueUseCase().CreateIssue(ctx, params, in.createdBy)
}
if err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
if err := uw.Commit(ctx, fmt.Sprintf("bd: create %s", result.Issue.ID)); err != nil && !isDoltNothingToCommit(err) {
FatalError("commit: %v", err)
return HandleError("commit: %v", err)
}
switch {
@ -171,11 +176,12 @@ func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInpu
fmt.Printf(" Priority: P%d\n", result.Issue.Priority)
fmt.Printf(" Status: %s\n", result.Issue.Status)
}
return nil
}
func runCreateLintIssue(in createInput) {
func runCreateLintIssue(in createInput) error {
if in.validationMode != "error" && in.validationMode != "warn" {
return
return nil
}
lintIssue := &types.Issue{
IssueType: types.IssueType(in.issueType).Normalize(),
@ -184,10 +190,11 @@ func runCreateLintIssue(in createInput) {
}
if err := validation.LintIssue(lintIssue); err != nil {
if in.validationMode == "error" {
FatalError("%v", err)
return HandleError("%v", err)
}
fmt.Fprintf(os.Stderr, "%s %v\n", ui.RenderWarn("⚠"), err)
}
return nil
}
func buildCreateIssueFromInput(in createInput) *types.Issue {
@ -221,13 +228,13 @@ func buildCreateIssueFromInput(in createInput) *types.Issue {
})
}
func runCreateProxiedMarkdown(_ *cobra.Command, ctx context.Context, in createInput) {
func runCreateProxiedMarkdown(_ *cobra.Command, ctx context.Context, in createInput) error {
templates, err := parseMarkdownFile(in.markdownFile)
if err != nil {
FatalError("parsing markdown file: %v", err)
return HandleError("parsing markdown file: %v", err)
}
if len(templates) == 0 {
FatalError("no issues found in markdown file")
return HandleError("no issues found in markdown file")
}
if in.validationMode == "error" || in.validationMode == "warn" {
@ -239,7 +246,7 @@ func runCreateProxiedMarkdown(_ *cobra.Command, ctx context.Context, in createIn
}
if err := validation.LintIssue(lintIssue); err != nil {
if in.validationMode == "error" {
FatalError("template %q: %v", t.Title, err)
return HandleError("template %q: %v", t.Title, err)
}
fmt.Fprintf(os.Stderr, "%s template %q: %v\n", ui.RenderWarn("⚠"), t.Title, err)
}
@ -255,12 +262,15 @@ func runCreateProxiedMarkdown(_ *cobra.Command, ctx context.Context, in createIn
for _, t := range templates {
deps, err := parseMarkdownDepSpecs(t.Dependencies, t.Title)
if err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
builds = append(builds, templateBuild{template: t, deps: deps})
}
uw, cctx := proxiedOpenUOW(ctx)
uw, cctx, err := proxiedOpenUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
customTypes := resolveProxiedCustomTypes(cctx.CustomTypes)
@ -269,7 +279,7 @@ func runCreateProxiedMarkdown(_ *cobra.Command, ctx context.Context, in createIn
continue
}
if !b.template.IssueType.IsValidWithCustom(customTypes) {
FatalError("template %q: invalid type %q", b.template.Title, b.template.IssueType)
return HandleError("template %q: invalid type %q", b.template.Title, b.template.IssueType)
}
}
@ -304,25 +314,26 @@ func runCreateProxiedMarkdown(_ *cobra.Command, ctx context.Context, in createIn
result, err = uw.IssueUseCase().CreateIssues(ctx, paramsList, in.createdBy)
}
if err != nil {
FatalError("creating issues from markdown: %v", err)
return HandleError("creating issues from markdown: %v", err)
}
commitMsg := fmt.Sprintf("bd: create %d issue(s) from %s", len(result.Issues), in.markdownFile)
if err := uw.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
FatalError("commit: %v", err)
return HandleError("commit: %v", err)
}
if in.jsonOutput {
if err := outputJSON(result.Issues); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
fmt.Printf("%s Created %d issues from %s:\n", ui.RenderPass("✓"), len(result.Issues), in.markdownFile)
for _, issue := range result.Issues {
fmt.Printf(" %s: %s [P%d, %s]\n", issue.ID, issue.Title, issue.Priority, issue.IssueType)
}
return nil
}
func parseMarkdownDepSpecs(deps []string, templateTitle string) ([]domain.DependencySpec, error) {
@ -358,10 +369,10 @@ func parseMarkdownDepSpecs(deps []string, templateTitle string) ([]domain.Depend
return out, nil
}
func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput) {
func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput) error {
data, err := os.ReadFile(in.graphFile) // #nosec G304 -- user-provided path is intentional
if err != nil {
FatalError("reading graph plan: %v", err)
return HandleError("reading graph plan: %v", err)
}
if unknown := detectUnknownGraphFields(data); len(unknown) > 0 {
warnUnknownGraphFields(os.Stderr, unknown)
@ -369,39 +380,45 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput
var plan GraphApplyPlan
if err := json.Unmarshal(data, &plan); err != nil {
FatalError("parsing graph plan: %v", err)
return HandleError("parsing graph plan: %v", err)
}
if in.dryRun {
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
dryUW, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalError("open unit of work: %v", err)
return HandleError("open unit of work: %v", err)
}
cctx, err := dryUW.ConfigUseCase().LoadCreateContext(ctx)
dryUW.Close(ctx)
if err != nil {
FatalError("load create context: %v", err)
return HandleError("load create context: %v", err)
}
if err := validateGraphApplyPlan(&plan, resolveProxiedCustomTypes(cctx.CustomTypes)); err != nil {
FatalError("invalid graph plan: %v", err)
return HandleError("invalid graph plan: %v", err)
}
if err := emitGraphApplyDryRun(&plan); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
uw, cctx := proxiedOpenUOW(ctx)
uw, cctx, err := proxiedOpenUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
if err := validateGraphApplyPlan(&plan, resolveProxiedCustomTypes(cctx.CustomTypes)); err != nil {
FatalError("invalid graph plan: %v", err)
return HandleError("invalid graph plan: %v", err)
}
domainPlan := buildDomainGraphPlan(plan, in)
domainPlan, err := buildDomainGraphPlan(plan, in)
if err != nil {
return err
}
var result domain.GraphApplyResult
if in.ephemeral {
@ -410,7 +427,7 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput
result, err = uw.IssueUseCase().ApplyIssueGraph(ctx, domainPlan, in.createdBy)
}
if err != nil {
FatalError("graph create: %v", err)
return HandleError("graph create: %v", err)
}
commitMsg := plan.CommitMessage
@ -419,14 +436,14 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput
}
if err := uw.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
FatalError("commit: %v", err)
return HandleError("commit: %v", err)
}
if in.jsonOutput {
if err := outputJSON(GraphApplyResult{IDs: result.IDs}); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
fmt.Printf("Created %d issues\n", len(result.IDs))
@ -439,14 +456,19 @@ func runCreateProxiedGraph(_ *cobra.Command, ctx context.Context, in createInput
for _, k := range keys {
fmt.Printf(" %s -> %s\n", k, result.IDs[k])
}
return nil
}
func buildDomainGraphPlan(plan GraphApplyPlan, in createInput) domain.GraphPlan {
func buildDomainGraphPlan(plan GraphApplyPlan, in createInput) (domain.GraphPlan, error) {
nodes := make([]domain.GraphNode, 0, len(plan.Nodes))
for _, n := range plan.Nodes {
issue, err := materializeGraphNodeIssue(n, in)
if err != nil {
return domain.GraphPlan{}, err
}
nodes = append(nodes, domain.GraphNode{
Key: n.Key,
Issue: materializeGraphNodeIssue(n, in),
Issue: issue,
ParentKey: n.ParentKey,
ParentID: n.ParentID,
Assignee: n.Assignee,
@ -465,10 +487,10 @@ func buildDomainGraphPlan(plan GraphApplyPlan, in createInput) domain.GraphPlan
Type: graphApplyDependencyType(e.Type),
})
}
return domain.GraphPlan{Nodes: nodes, Edges: edges}
return domain.GraphPlan{Nodes: nodes, Edges: edges}, nil
}
func materializeGraphNodeIssue(n GraphApplyNode, in createInput) *types.Issue {
func materializeGraphNodeIssue(n GraphApplyNode, in createInput) (*types.Issue, error) {
issueType := types.IssueType(n.Type)
if issueType == "" {
issueType = types.TypeTask
@ -481,7 +503,7 @@ func materializeGraphNodeIssue(n GraphApplyNode, in createInput) *types.Issue {
if len(n.Metadata) > 0 {
raw, err := json.Marshal(n.Metadata)
if err != nil {
FatalError("node %q: marshaling metadata: %v", n.Key, err)
return nil, HandleError("node %q: marshaling metadata: %v", n.Key, err)
}
metadataJSON = raw
}
@ -497,5 +519,5 @@ func materializeGraphNodeIssue(n GraphApplyNode, in createInput) *types.Issue {
NoHistory: in.noHistory,
CreatedBy: in.createdBy,
Owner: in.owner,
}
}, nil
}

View file

@ -119,7 +119,10 @@ func TestBuildCreateIssueFromInput_ExplicitStatusWinsOverDefer(t *testing.T) {
func TestMaterializeGraphNodeIssue_DefaultsAndOpts(t *testing.T) {
t.Run("type and priority defaults", func(t *testing.T) {
issue := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{createdBy: "t"})
issue, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{createdBy: "t"})
if err != nil {
t.Fatalf("materializeGraphNodeIssue: %v", err)
}
if issue.IssueType != types.TypeTask {
t.Errorf("type default = %q, want task", issue.IssueType)
}
@ -133,9 +136,12 @@ func TestMaterializeGraphNodeIssue_DefaultsAndOpts(t *testing.T) {
t.Run("explicit priority and type", func(t *testing.T) {
p := 0
issue := materializeGraphNodeIssue(GraphApplyNode{
issue, err := materializeGraphNodeIssue(GraphApplyNode{
Key: "n", Title: "N", Type: "bug", Priority: &p,
}, createInput{})
if err != nil {
t.Fatalf("materializeGraphNodeIssue: %v", err)
}
if issue.IssueType != types.TypeBug {
t.Errorf("type = %q, want bug", issue.IssueType)
}
@ -145,26 +151,35 @@ func TestMaterializeGraphNodeIssue_DefaultsAndOpts(t *testing.T) {
})
t.Run("ephemeral and no-history propagate", func(t *testing.T) {
issue := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
issue, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
ephemeral: true,
noHistory: false,
})
if err != nil {
t.Fatalf("materializeGraphNodeIssue: %v", err)
}
if !issue.Ephemeral {
t.Errorf("ephemeral not propagated")
}
issue2 := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
issue2, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
noHistory: true,
})
if err != nil {
t.Fatalf("materializeGraphNodeIssue: %v", err)
}
if !issue2.NoHistory {
t.Errorf("no_history not propagated")
}
})
t.Run("metadata marshalled to JSON", func(t *testing.T) {
issue := materializeGraphNodeIssue(GraphApplyNode{
issue, err := materializeGraphNodeIssue(GraphApplyNode{
Key: "n", Title: "N",
Metadata: map[string]string{"a": "1", "b": "2"},
}, createInput{})
if err != nil {
t.Fatalf("materializeGraphNodeIssue: %v", err)
}
var roundTrip map[string]string
if err := json.Unmarshal(issue.Metadata, &roundTrip); err != nil {
t.Fatalf("metadata not valid JSON: %v", err)
@ -175,17 +190,23 @@ func TestMaterializeGraphNodeIssue_DefaultsAndOpts(t *testing.T) {
})
t.Run("empty metadata leaves Metadata nil", func(t *testing.T) {
issue := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{})
issue, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{})
if err != nil {
t.Fatalf("materializeGraphNodeIssue: %v", err)
}
if issue.Metadata != nil {
t.Errorf("Metadata = %s, want nil for empty input", string(issue.Metadata))
}
})
t.Run("identity fields copied", func(t *testing.T) {
issue := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
issue, err := materializeGraphNodeIssue(GraphApplyNode{Key: "n", Title: "N"}, createInput{
createdBy: "alice",
owner: "alice@example.com",
})
if err != nil {
t.Fatalf("materializeGraphNodeIssue: %v", err)
}
if issue.CreatedBy != "alice" || issue.Owner != "alice@example.com" {
t.Errorf("identity copy wrong: %q / %q", issue.CreatedBy, issue.Owner)
}
@ -206,7 +227,10 @@ func TestBuildDomainGraphPlan(t *testing.T) {
},
}
got := buildDomainGraphPlan(plan, createInput{createdBy: "t"})
got, err := buildDomainGraphPlan(plan, createInput{createdBy: "t"})
if err != nil {
t.Fatalf("buildDomainGraphPlan: %v", err)
}
if len(got.Nodes) != 2 {
t.Fatalf("nodes len = %d", len(got.Nodes))

View file

@ -60,8 +60,7 @@ Force: Delete and orphan dependents
}()
if usesProxiedServer() {
runDeleteProxiedServer(cmd, rootCtx, args)
return nil
return runDeleteProxiedServer(cmd, rootCtx, args)
}
fromFile, _ := cmd.Flags().GetString("from-file")

View file

@ -42,38 +42,37 @@ func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error)
return in, nil
}
func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
in, err := gatherDeleteInput(cmd, args)
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
if len(in.ids) == 0 {
_ = cmd.Usage()
FatalError("no issue IDs provided")
return HandleError("no issue IDs provided")
}
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return HandleErrorRespectJSON("open unit of work: %v", err)
}
defer uw.Close(ctx)
issueUC := uw.IssueUseCase()
if in.dryRun || !in.force {
runDeleteProxiedPreview(ctx, issueUC, in)
return
return runDeleteProxiedPreview(ctx, issueUC, in)
}
preview, err := issueUC.PreviewDelete(ctx, in.ids)
if err != nil {
FatalErrorRespectJSON("preview: %v", err)
return HandleErrorRespectJSON("preview: %v", err)
}
if len(preview.NotFound) > 0 {
FatalErrorRespectJSON("issues not found: %s", strings.Join(preview.NotFound, ", "))
return HandleErrorRespectJSON("issues not found: %s", strings.Join(preview.NotFound, ", "))
}
res, err := issueUC.DeleteIssues(ctx, domain.DeleteIssuesParams{
@ -82,27 +81,28 @@ func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
UpdateTextReferences: true,
}, actor)
if err != nil {
FatalErrorRespectJSON("delete: %v", err)
return HandleErrorRespectJSON("delete: %v", err)
}
if res.DeletedCount == 0 {
FatalErrorRespectJSON("issues not found: %s", strings.Join(in.ids, ", "))
return HandleErrorRespectJSON("issues not found: %s", strings.Join(in.ids, ", "))
}
commitMsg := fmt.Sprintf("bd: delete %d issue(s)", res.DeletedCount)
if err := uw.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("commit: %v", err)
return HandleErrorRespectJSON("commit: %v", err)
}
renderDeleteProxiedResult(in, res)
return nil
}
func runDeleteProxiedPreview(ctx context.Context, issueUC domain.IssueUseCase, in *deleteInput) {
func runDeleteProxiedPreview(ctx context.Context, issueUC domain.IssueUseCase, in *deleteInput) error {
preview, err := issueUC.PreviewDelete(ctx, in.ids)
if err != nil {
FatalErrorRespectJSON("preview: %v", err)
return HandleErrorRespectJSON("preview: %v", err)
}
if len(preview.NotFound) > 0 {
FatalErrorRespectJSON("issues not found: %s", strings.Join(preview.NotFound, ", "))
return HandleErrorRespectJSON("issues not found: %s", strings.Join(preview.NotFound, ", "))
}
res, err := issueUC.DeleteIssues(ctx, domain.DeleteIssuesParams{
@ -111,7 +111,7 @@ func runDeleteProxiedPreview(ctx context.Context, issueUC domain.IssueUseCase, i
DryRun: true,
}, actor)
if err != nil {
FatalErrorRespectJSON("preview counts: %v", err)
return HandleErrorRespectJSON("preview counts: %v", err)
}
if in.jsonOutput {
@ -125,9 +125,10 @@ func runDeleteProxiedPreview(ctx context.Context, issueUC domain.IssueUseCase, i
"connected": sortedKeys(preview.ConnectedIssues),
"dry_run": in.dryRun,
})
return
return nil
}
renderDeletePreview(in, preview, res)
return nil
}
func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res domain.DeleteIssuesResult) {

View file

@ -153,8 +153,7 @@ Examples:
ctx := rootCtx
if usesProxiedServer() {
runDepBlocksProxiedServer(cmd, ctx, blockerID, blocksID)
return nil
return runDepBlocksProxiedServer(cmd, ctx, blockerID, blocksID)
}
depType := "blocks"
@ -297,8 +296,7 @@ Examples:
}()
if usesProxiedServer() {
runDepAddProxiedServer(cmd, rootCtx, args)
return nil
return runDepAddProxiedServer(cmd, rootCtx, args)
}
depType, _ := cmd.Flags().GetString("type")
@ -719,8 +717,7 @@ Examples:
}()
if usesProxiedServer() {
runDepListProxiedServer(cmd, rootCtx, args)
return nil
return runDepListProxiedServer(cmd, rootCtx, args)
}
ctx := rootCtx
@ -912,8 +909,7 @@ var depRemoveCmd = &cobra.Command{
}()
if usesProxiedServer() {
runDepRemoveProxiedServer(cmd, rootCtx, args)
return nil
return runDepRemoveProxiedServer(cmd, rootCtx, args)
}
ctx := rootCtx
@ -1007,8 +1003,7 @@ Examples:
}()
if usesProxiedServer() {
runDepTreeProxiedServer(cmd, rootCtx, args)
return nil
return runDepTreeProxiedServer(cmd, rootCtx, args)
}
ctx := rootCtx
@ -1122,8 +1117,7 @@ var depCyclesCmd = &cobra.Command{
}()
if usesProxiedServer() {
runDepCyclesProxiedServer(cmd, rootCtx)
return nil
return runDepCyclesProxiedServer(cmd, rootCtx)
}
ctx := rootCtx

View file

@ -14,15 +14,15 @@ import (
"github.com/steveyegge/beads/internal/ui"
)
func openDepProxiedUOW(ctx context.Context) uow.UnitOfWork {
func openDepProxiedUOW(ctx context.Context) (uow.UnitOfWork, error) {
if uowProvider == nil {
FatalErrorRespectJSON("proxied-server UOW provider not initialized")
return nil, HandleErrorRespectJSON("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return nil, HandleErrorRespectJSON("open unit of work: %v", err)
}
return uw
return uw, nil
}
func proxiedLookupTitle(ctx context.Context, uw uow.UnitOfWork, id string) string {
@ -68,12 +68,15 @@ func proxiedWarnCycles(ctx context.Context, uw uow.UnitOfWork) {
fmt.Fprintf(os.Stderr, "\nRun 'bd dep cycles' for detailed analysis.\n\n")
}
func runDepBlocksProxiedServer(cmd *cobra.Command, ctx context.Context, blockerID, blockedID string) {
func runDepBlocksProxiedServer(cmd *cobra.Command, ctx context.Context, blockerID, blockedID string) error {
if isChildOf(blockedID, blockerID) {
FatalErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", blockedID, blockerID)
return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", blockedID, blockerID)
}
uw := openDepProxiedUOW(ctx)
uw, err := openDepProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
dep := &types.Dependency{
@ -82,7 +85,7 @@ func runDepBlocksProxiedServer(cmd *cobra.Command, ctx context.Context, blockerI
Type: types.DepBlocks,
}
if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actor, domain.BulkAddDepsOpts{}); err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check")
@ -94,7 +97,7 @@ func runDepBlocksProxiedServer(cmd *cobra.Command, ctx context.Context, blockerI
blockedTitle := proxiedLookupTitle(ctx, uw, blockedID)
if err := uw.Commit(ctx, fmt.Sprintf("bd: dep add %s %s", blockedID, blockerID)); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("failed to commit: %v", err)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
if jsonOutput {
@ -104,22 +107,22 @@ func runDepBlocksProxiedServer(cmd *cobra.Command, ctx context.Context, blockerI
"blocked_id": blockedID,
"type": string(types.DepBlocks),
})
return
return nil
}
fmt.Printf("%s Added dependency: %s blocks %s\n",
ui.RenderPass("✓"),
formatFeedbackIDParen(blockerID, blockerTitle),
formatFeedbackIDParen(blockedID, blockedTitle))
return nil
}
func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
depType, _ := cmd.Flags().GetString("type")
file, _ := cmd.Flags().GetString("file")
if file != "" {
runDepAddBulkProxied(cmd, ctx, file, depType)
return
return runDepAddBulkProxied(cmd, ctx, file, depType)
}
blockedBy, _ := cmd.Flags().GetString("blocked-by")
@ -139,7 +142,7 @@ func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
var toID string
if strings.HasPrefix(dependsOnArg, "external:") {
if err := validateExternalRef(dependsOnArg); err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
toID = dependsOnArg
} else {
@ -147,20 +150,23 @@ func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
}
if isChildOf(fromID, toID) {
FatalErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", fromID, toID)
return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", fromID, toID)
}
dt := types.DependencyType(depType)
if !dt.IsValid() {
FatalErrorRespectJSON("invalid dependency type %q: must be non-empty and at most 50 characters", depType)
return HandleErrorRespectJSON("invalid dependency type %q: must be non-empty and at most 50 characters", depType)
}
uw := openDepProxiedUOW(ctx)
uw, err := openDepProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
dep := &types.Dependency{IssueID: fromID, DependsOnID: toID, Type: dt}
if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actor, domain.BulkAddDepsOpts{}); err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check")
@ -172,7 +178,7 @@ func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
toTitle := proxiedLookupTitle(ctx, uw, toID)
if err := uw.Commit(ctx, fmt.Sprintf("bd: dep add %s %s", fromID, toID)); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("failed to commit: %v", err)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
if jsonOutput {
@ -182,7 +188,7 @@ func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
"depends_on_id": toID,
"type": depType,
})
return
return nil
}
fmt.Printf("%s Added dependency: %s depends on %s (%s)\n",
@ -190,25 +196,26 @@ func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
formatFeedbackIDParen(fromID, fromTitle),
formatFeedbackIDParen(toID, toTitle),
depType)
return nil
}
func runDepAddBulkProxied(cmd *cobra.Command, ctx context.Context, file, defaultType string) {
func runDepAddBulkProxied(cmd *cobra.Command, ctx context.Context, file, defaultType string) error {
edges, err := readBulkDepEdges(file, defaultType)
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
if len(edges) == 0 {
FatalErrorRespectJSON("no dependency edges found")
return HandleErrorRespectJSON("no dependency edges found")
}
deps := make([]*types.Dependency, 0, len(edges))
for _, edge := range edges {
if isChildOf(edge.IssueID, edge.DependsOnID) {
FatalErrorRespectJSON("line %d: cannot add dependency: %s is already a child of %s", edge.Line, edge.IssueID, edge.DependsOnID)
return HandleErrorRespectJSON("line %d: cannot add dependency: %s is already a child of %s", edge.Line, edge.IssueID, edge.DependsOnID)
}
if strings.HasPrefix(edge.DependsOnID, "external:") {
if err := validateExternalRef(edge.DependsOnID); err != nil {
FatalErrorRespectJSON("line %d: %v", edge.Line, err)
return HandleErrorRespectJSON("line %d: %v", edge.Line, err)
}
}
deps = append(deps, &types.Dependency{
@ -218,14 +225,17 @@ func runDepAddBulkProxied(cmd *cobra.Command, ctx context.Context, file, default
})
}
uw := openDepProxiedUOW(ctx)
uw, err := openDepProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check")
if _, err := uw.DependencyUseCase().AddDependencies(ctx, deps, actor, domain.BulkAddDepsOpts{
SkipPerEdgeCycleCheck: noCycleCheck,
}); err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
if !noCycleCheck {
@ -233,7 +243,7 @@ func runDepAddBulkProxied(cmd *cobra.Command, ctx context.Context, file, default
}
if err := uw.Commit(ctx, fmt.Sprintf("dependency: add %d edges", len(deps))); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("failed to commit: %v", err)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
if jsonOutput {
@ -250,33 +260,37 @@ func runDepAddBulkProxied(cmd *cobra.Command, ctx context.Context, file, default
"count": len(deps),
"dependencies": out,
})
return
return nil
}
fmt.Printf("%s Added %d dependencies\n", ui.RenderPass("✓"), len(deps))
return nil
}
func runDepRemoveProxiedServer(_ *cobra.Command, ctx context.Context, args []string) {
func runDepRemoveProxiedServer(_ *cobra.Command, ctx context.Context, args []string) error {
fromID := args[0]
toID := args[1]
if strings.HasPrefix(toID, "external:") {
if err := validateExternalRef(toID); err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
}
uw := openDepProxiedUOW(ctx)
uw, err := openDepProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
if err := uw.DependencyUseCase().RemoveDependency(ctx, fromID, toID, actor); err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
fromTitle := proxiedLookupTitle(ctx, uw, fromID)
toTitle := proxiedLookupTitle(ctx, uw, toID)
if err := uw.Commit(ctx, fmt.Sprintf("bd: dep remove %s %s", fromID, toID)); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("failed to commit: %v", err)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
if jsonOutput {
@ -285,23 +299,27 @@ func runDepRemoveProxiedServer(_ *cobra.Command, ctx context.Context, args []str
"issue_id": fromID,
"depends_on_id": toID,
})
return
return nil
}
fmt.Printf("%s Removed dependency: %s no longer depends on %s\n",
ui.RenderPass("✓"),
formatFeedbackIDParen(fromID, fromTitle),
formatFeedbackIDParen(toID, toTitle))
return nil
}
func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
direction, _ := cmd.Flags().GetString("direction")
typeFilter, _ := cmd.Flags().GetString("type")
if direction == "" {
direction = "down"
}
uw := openDepProxiedUOW(ctx)
uw, err := openDepProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
depUC := uw.DependencyUseCase()
@ -309,7 +327,7 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
if len(args) > 1 && direction == "down" {
depMap, err := depUC.GetIssueDependencyRecords(ctx, args)
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
var allDeps []*types.Dependency
for _, id := range args {
@ -324,7 +342,7 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
allDeps = []*types.Dependency{}
}
_ = outputJSON(allDeps)
return
return nil
}
for _, id := range args {
deps := depMap[id]
@ -341,7 +359,7 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
}
}
fmt.Println()
return
return nil
}
var allIssues []*types.IssueWithDependencyMetadata
@ -352,7 +370,7 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
for _, id := range args {
issues, err := depUC.ListWithIssueMetadata(ctx, id, domain.DepListFilter{Direction: listDirection})
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
if typeFilter != "" {
filtered := issues[:0]
@ -371,7 +389,7 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
allIssues = []*types.IssueWithDependencyMetadata{}
}
_ = outputJSON(allIssues)
return
return nil
}
if len(allIssues) == 0 {
@ -384,7 +402,7 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
} else {
fmt.Println("\nNo dependencies found")
}
return
return nil
}
for _, iss := range allIssues {
@ -405,9 +423,10 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
idStr, iss.Title, iss.Priority, iss.Status, iss.DependencyType)
}
fmt.Println()
return nil
}
func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
fullID := args[0]
showAllPaths, _ := cmd.Flags().GetBool("show-all-paths")
maxDepth, _ := cmd.Flags().GetInt("max-depth")
@ -425,13 +444,16 @@ func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
direction = "down"
}
if direction != "down" && direction != "up" && direction != "both" {
FatalErrorRespectJSON("--direction must be 'down', 'up', or 'both'")
return HandleErrorRespectJSON("--direction must be 'down', 'up', or 'both'")
}
if maxDepth < 1 {
FatalErrorRespectJSON("--max-depth must be >= 1")
return HandleErrorRespectJSON("--max-depth must be >= 1")
}
uw := openDepProxiedUOW(ctx)
uw, err := openDepProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
depUC := uw.DependencyUseCase()
@ -444,7 +466,7 @@ func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
Direction: domain.DepDirectionOut,
})
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
upTree, err := depUC.GetDependencyTree(ctx, fullID, domain.DepTreeOpts{
MaxDepth: maxDepth,
@ -452,7 +474,7 @@ func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
Direction: domain.DepDirectionIn,
})
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
tree = mergeBidirectionalTrees(downTree, upTree, fullID)
} else {
@ -467,7 +489,7 @@ func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
Direction: treeDir,
})
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
}
@ -477,7 +499,7 @@ func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
if formatStr == "mermaid" {
outputMermaidTree(tree, args[0])
return
return nil
}
if jsonOutput {
@ -485,7 +507,7 @@ func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
tree = []*types.TreeNode{}
}
_ = outputJSON(tree)
return
return nil
}
if len(tree) == 0 {
@ -497,7 +519,7 @@ func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
default:
fmt.Printf("\n%s has no dependencies\n", fullID)
}
return
return nil
}
switch direction {
@ -511,15 +533,19 @@ func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
renderTree(tree, maxDepth, direction)
fmt.Println()
return nil
}
func runDepCyclesProxiedServer(_ *cobra.Command, ctx context.Context) {
uw := openDepProxiedUOW(ctx)
func runDepCyclesProxiedServer(_ *cobra.Command, ctx context.Context) error {
uw, err := openDepProxiedUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
cycles, err := uw.DependencyUseCase().DetectCycles(ctx)
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
if jsonOutput {
@ -527,12 +553,12 @@ func runDepCyclesProxiedServer(_ *cobra.Command, ctx context.Context) {
cycles = [][]*types.Issue{}
}
_ = outputJSON(cycles)
return
return nil
}
if len(cycles) == 0 {
fmt.Printf("\n%s No dependency cycles detected\n\n", ui.RenderPass("✓"))
return
return nil
}
fmt.Printf("\n%s Found %d dependency cycles:\n\n", ui.RenderFail("⚠"), len(cycles))
@ -543,4 +569,5 @@ func runDepCyclesProxiedServer(_ *cobra.Command, ctx context.Context) {
}
fmt.Println()
}
return nil
}

View file

@ -73,16 +73,20 @@ Examples:
}
var doltShowCmd = &cobra.Command{
Use: "show",
Short: "Show current Dolt configuration with connection status",
Run: func(cmd *cobra.Command, args []string) {
showDoltConfig(true)
Use: "show",
SilenceUsage: true,
SilenceErrors: true,
Short: "Show current Dolt configuration with connection status",
RunE: func(cmd *cobra.Command, args []string) error {
return showDoltConfig(true)
},
}
var doltSetCmd = &cobra.Command{
Use: "set <key> <value>",
Short: "Set a Dolt configuration value",
Use: "set <key> <value>",
SilenceUsage: true,
SilenceErrors: true,
Short: "Set a Dolt configuration value",
Long: `Set a Dolt configuration value in metadata.json.
Keys:
@ -100,7 +104,7 @@ Examples:
bd dolt set port 3307 --update-config
bd dolt set data-dir /home/user/.beads-dolt/myproject`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
if !usesSQLServer() {
fmt.Fprintln(os.Stderr, "Error: 'bd dolt set' is not supported in embedded mode (no Dolt server)")
os.Exit(1)
@ -108,13 +112,15 @@ Examples:
key := args[0]
value := args[1]
updateConfig, _ := cmd.Flags().GetBool("update-config")
setDoltConfig(key, value, updateConfig)
return setDoltConfig(key, value, updateConfig)
},
}
var doltTestCmd = &cobra.Command{
Use: "test",
Short: "Test connection to Dolt server",
Use: "test",
SilenceUsage: true,
SilenceErrors: true,
Short: "Test connection to Dolt server",
Long: `Test the connection to the configured Dolt server.
This verifies that:
@ -122,12 +128,12 @@ This verifies that:
2. The connection can be established
Use this before switching to server mode to ensure the server is running.`,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
if !usesSQLServer() {
fmt.Fprintln(os.Stderr, "Error: 'bd dolt test' is not supported in embedded mode (no Dolt server)")
os.Exit(1)
}
testDoltConnection()
return testDoltConnection()
},
}
@ -518,8 +524,10 @@ For more options (--stdin, custom messages), see: bd vc commit`,
}
var doltStartCmd = &cobra.Command{
Use: "start",
Short: "Start the Dolt SQL server for this project",
Use: "start",
SilenceUsage: true,
SilenceErrors: true,
Short: "Start the Dolt SQL server for this project",
Long: `Start a dolt sql-server for the current beads project.
The server runs in the background on a per-project port derived from the
@ -527,14 +535,14 @@ project path. PID and logs are stored in .beads/.
The server auto-starts transparently when needed, so manual start is rarely
required. Use this command for explicit control or diagnostics.`,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
if !usesSQLServer() {
fmt.Fprintln(os.Stderr, "Error: 'bd dolt start' is not supported in embedded mode (no Dolt server)")
os.Exit(1)
}
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
serverDir := doltserver.ResolveServerDir(beadsDir)
@ -542,7 +550,7 @@ required. Use this command for explicit control or diagnostics.`,
if err != nil {
if strings.Contains(err.Error(), "already running") {
fmt.Println(err)
return
return nil
}
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
@ -559,24 +567,27 @@ required. Use this command for explicit control or diagnostics.`,
fmt.Printf(" Profile dir: %s\n", doltserver.DebugProfileDir(beadsDir))
fmt.Println(" Note: cpu.pprof is written when the server exits cleanly (bd dolt stop).")
}
return nil
},
}
var doltStopCmd = &cobra.Command{
Use: "stop",
Short: "Stop the Dolt SQL server for this project",
Use: "stop",
SilenceUsage: true,
SilenceErrors: true,
Short: "Stop the Dolt SQL server for this project",
Long: `Stop the dolt sql-server managed by beads for the current project.
This sends a graceful shutdown signal. The server will restart automatically
on the next bd command unless auto-start is disabled.`,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
if !usesSQLServer() {
fmt.Fprintln(os.Stderr, "Error: 'bd dolt stop' is not supported in embedded mode (no Dolt server)")
os.Exit(1)
}
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
serverDir := doltserver.ResolveServerDir(beadsDir)
force, _ := cmd.Flags().GetBool("force")
@ -586,12 +597,15 @@ on the next bd command unless auto-start is disabled.`,
os.Exit(1)
}
fmt.Println("Dolt server stopped.")
return nil
},
}
var doltStatusCmd = &cobra.Command{
Use: "status",
Short: "Show Dolt engine status",
Use: "status",
SilenceUsage: true,
SilenceErrors: true,
Short: "Show Dolt engine status",
Long: `Show the status of the Dolt engine for the current project.
In embedded mode, reports that the Dolt engine runs in-process and shows
@ -601,14 +615,14 @@ managed servers — a shared server (dolt.shared-server: true), a remote
dolt_server_host, or a local server managed outside bd (dolt.auto-start:
false, e.g. an orchestrator-shared sql-server) — pings the configured
endpoint via SQL and reports reachability, server version, and database.`,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
if !usesSQLServer() {
showEmbeddedDoltStatus(beadsDir)
return
return nil
}
// For externally-managed Dolt servers, the local PID file is
@ -634,7 +648,7 @@ endpoint via SQL and reports reachability, server version, and database.`,
}
if cfg != nil && shouldUseExternalDoltStatus(cfg, doltserver.IsAutoStartDisabled(), doltserver.IsSharedServerMode()) {
runExternalDoltStatus(beadsDir, cfg)
return
return nil
}
serverDir := doltserver.ResolveServerDir(beadsDir)
@ -645,6 +659,7 @@ endpoint via SQL and reports reachability, server version, and database.`,
os.Exit(1)
}
renderLocalDoltStatus(state, serverDir)
return nil
},
}
@ -934,8 +949,10 @@ var staleDatabasePrefixes = []string{
}
var doltCleanDatabasesCmd = &cobra.Command{
Use: "clean-databases",
Short: "Drop stale test databases from the Dolt server",
Use: "clean-databases",
SilenceUsage: true,
SilenceErrors: true,
Short: "Drop stale test databases from the Dolt server",
Long: `Identify and drop leftover test and agent databases that accumulate
on the shared Dolt server from interrupted test runs and terminated agents.
@ -943,7 +960,7 @@ Stale database prefixes: testdb_*, beads_test*, beads_pt*, beads_vr*, doctest_*,
These waste server memory and can degrade performance under concurrent load.
Use --dry-run to see what would be dropped without actually dropping.`,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
if !usesSQLServer() {
fmt.Fprintln(os.Stderr, "Error: 'bd dolt clean-databases' is not supported in embedded mode (no Dolt server)")
os.Exit(1)
@ -952,7 +969,10 @@ Use --dry-run to see what would be dropped without actually dropping.`,
// Connect directly to the Dolt server via config instead of getStore(),
// which isn't initialized for dolt subcommands (beads-9vt).
db, cleanup := openDoltServerConnection()
db, cleanup, err := openDoltServerConnection()
if err != nil {
return err
}
defer cleanup()
listCtx, listCancel := context.WithTimeout(context.Background(), 30*time.Second)
@ -981,7 +1001,7 @@ Use --dry-run to see what would be dropped without actually dropping.`,
if len(stale) == 0 {
fmt.Println("No stale databases found.")
return
return nil
}
fmt.Printf("Found %d stale databases:\n", len(stale))
@ -991,7 +1011,7 @@ Use --dry-run to see what would be dropped without actually dropping.`,
if dryRun {
fmt.Println("\n(dry run — no databases dropped)")
return
return nil
}
fmt.Println()
@ -1049,6 +1069,7 @@ Use --dry-run to see what would be dropped without actually dropping.`,
}
}
fmt.Printf("\nDropped %d/%d stale databases.\n", dropped, len(stale))
return nil
},
}
@ -1133,10 +1154,12 @@ Subcommands:
}
var doltRemoteAddCmd = &cobra.Command{
Use: "add <name> <url>",
Short: "Add a Dolt remote",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
Use: "add <name> <url>",
SilenceUsage: true,
SilenceErrors: true,
Short: "Add a Dolt remote",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
if isDoltLocalOnly() {
fmt.Fprintln(os.Stderr, "Error: cannot add Dolt remote: remote sync is disabled (dolt.local-only=true).")
fmt.Fprintln(os.Stderr, "To re-enable remote sync: bd config unset dolt.local-only")
@ -1171,12 +1194,12 @@ var doltRemoteAddCmd = &cobra.Command{
}
if result.Canceled {
fmt.Println("Canceled.")
return
return nil
}
if name == "origin" {
if err := config.SetYamlConfig("sync.remote", url); err != nil {
FatalError("failed to persist sync.remote to config.yaml: %v", err)
return HandleError("failed to persist sync.remote to config.yaml: %v", err)
}
if isGitRepo() {
commitBeadsConfig("bd: update sync.remote")
@ -1193,6 +1216,7 @@ var doltRemoteAddCmd = &cobra.Command{
} else {
fmt.Printf("Added remote %q → %s\n", name, url)
}
return nil
},
}
@ -1257,16 +1281,17 @@ func formatDoltRemoteListJSON(remotes []storage.RemoteInfo) []doltRemoteListJSON
}
var doltRemoteRemoveCmd = &cobra.Command{
Use: "remove <name>",
Short: "Remove a Dolt remote",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
Use: "remove <name>",
Short: "Remove a Dolt remote",
SilenceUsage: true,
SilenceErrors: true,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
name := args[0]
if usesProxiedServer() {
runDoltRemoteRemoveProxied(ctx, name)
return
return runDoltRemoteRemoveProxied(ctx, name)
}
st := getStore()
@ -1305,6 +1330,7 @@ var doltRemoteRemoveCmd = &cobra.Command{
} else {
fmt.Printf("Removed remote %q\n", name)
}
return nil
},
}
@ -1367,10 +1393,10 @@ func selectedDoltBeadsDir() string {
return beadsDir
}
func showDoltConfig(testConnection bool) {
func showDoltConfig(testConnection bool) error {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
@ -1413,12 +1439,12 @@ func showDoltConfig(testConnection bool) {
if err := outputJSON(result); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
if backend != configfile.BackendDolt {
fmt.Printf("Backend: %s\n", backend)
return
return nil
}
fmt.Println("Dolt Configuration")
@ -1470,12 +1496,13 @@ func showDoltConfig(testConnection bool) {
fmt.Println(" 1. Environment variables (BEADS_DOLT_*)")
fmt.Println(" 2. metadata.json (local, gitignored)")
fmt.Println(" 3. config.yaml (team defaults)")
return nil
}
func setDoltConfig(key, value string, updateConfig bool) {
func setDoltConfig(key, value string, updateConfig bool) error {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
@ -1590,7 +1617,7 @@ func setDoltConfig(key, value string, updateConfig bool) {
}); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
if lower == "true" {
fmt.Println("Shared server mode enabled.")
@ -1599,7 +1626,7 @@ func setDoltConfig(key, value string, updateConfig bool) {
} else {
fmt.Println("Shared server mode disabled. Each project will use its own Dolt server.")
}
return
return nil
default:
fmt.Fprintf(os.Stderr, "Error: unknown key '%s'\n", key)
@ -1628,7 +1655,7 @@ func setDoltConfig(key, value string, updateConfig bool) {
if err := outputJSON(result); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return
return nil
}
fmt.Printf("Set %s = %s (in metadata.json)\n", key, value)
@ -1641,12 +1668,13 @@ func setDoltConfig(key, value string, updateConfig bool) {
fmt.Printf("Set %s = %s (in config.yaml)\n", yamlKey, value)
}
}
return nil
}
func testDoltConnection() {
func testDoltConnection() error {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
@ -1679,7 +1707,7 @@ func testDoltConnection() {
if !ok {
os.Exit(1)
}
return
return nil
}
fmt.Printf("Testing connection to %s...\n", addr)
@ -1695,12 +1723,12 @@ func testDoltConnection() {
// Test remote connectivity
st := getStore()
if st == nil {
return
return nil
}
ctx := context.Background()
remotes, err := st.ListRemotes(ctx)
if err != nil || len(remotes) == 0 {
return
return nil
}
fmt.Println("\nRemote connectivity:")
for _, r := range remotes {
@ -1726,6 +1754,7 @@ func testDoltConnection() {
fmt.Printf(" %s (%s)... skipped (no connectivity test for this scheme)\n", r.Name, r.URL)
}
}
return nil
}
// serverDialTimeout controls the TCP dial timeout for server connection tests.
@ -1813,10 +1842,10 @@ func testHTTPConnectivity(url string) bool {
// using config from the beads directory. This bypasses getStore() which isn't
// initialized for dolt subcommands (beads-9vt). Connects without selecting a
// database so callers can operate on all databases (SHOW DATABASES, DROP DATABASE).
func openDoltServerConnection() (*sql.DB, func()) {
func openDoltServerConnection() (*sql.DB, func(), error) {
beadsDir := selectedDoltBeadsDir()
if beadsDir == "" {
FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
return nil, nil, HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := configfile.Load(beadsDir)
@ -1861,7 +1890,7 @@ func openDoltServerConnection() (*sql.DB, func()) {
os.Exit(1)
}
return db, func() { _ = db.Close() }
return db, func() { _ = db.Close() }, nil
}
// doltServerPidFile returns the path to the PID file for the managed dolt server.

View file

@ -8,13 +8,13 @@ import (
"github.com/steveyegge/beads/internal/config"
)
func runDoltRemoteRemoveProxied(ctx context.Context, name string) {
func runDoltRemoteRemoveProxied(ctx context.Context, name string) error {
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return HandleErrorRespectJSON("open unit of work: %v", err)
}
defer uw.Close(ctx)
@ -28,7 +28,7 @@ func runDoltRemoteRemoveProxied(ctx context.Context, name string) {
}
if err := uw.Commit(ctx, fmt.Sprintf("bd: remove remote %s", name)); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("commit: %v", err)
return HandleErrorRespectJSON("commit: %v", err)
}
if name == "origin" {
@ -52,4 +52,5 @@ func runDoltRemoteRemoveProxied(ctx context.Context, name string) {
} else {
fmt.Printf("Removed remote %q\n", name)
}
return nil
}

View file

@ -120,78 +120,16 @@ func SilentExit() error {
return &exitError{Code: 1}
}
// FatalError writes an error message to stderr (structured JSON when --json is
// set) and exits with code 1.
//
// It is retained ONLY for the proxied-server code paths, which run outside
// cobra's RunE error-return convention; every RunE-converted command uses
// HandleError and friends instead. Because FatalError calls os.Exit it bypasses
// the per-command deferred metrics CloseEventAndAdd and main()'s
// metrics.Global().Close()/MaybeSpawnFlusher, so a command that exits through a
// proxied-server FatalError* path records no usage event. That telemetry gap is
// latent today: proxied-server mode cannot be entered ("bd init --proxied-server"
// is rejected as "not yet implemented", see init.go), so usesProxiedServer() is
// never true and these paths never run (verified by
// TestInitProxiedServerRejectedKeepsMetricsGapLatent). When proxied-server mode
// is completed, convert these helpers to return errors up through RunE — like
// HandleError — so the deferred metrics close/flush is preserved.
func FatalError(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
if jsonOutput {
jsonStderrError(msg, "")
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
}
os.Exit(1)
}
// FatalErrorRespectJSON writes an error message and exits with code 1. If
// --json is set, outputs structured JSON to stdout; otherwise plain text to
// stderr.
func FatalErrorRespectJSON(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
if jsonOutput {
jsonStdoutError(msg, "")
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
}
os.Exit(1)
}
// FatalErrorWithHintRespectJSON writes an error message with a hint and exits.
// If --json is set, emits structured JSON to stdout so callers can parse it.
func FatalErrorWithHintRespectJSON(message, hint string) {
if jsonOutput {
jsonStdoutError(message, hint)
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", message)
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint)
}
os.Exit(1)
}
// FatalErrorWithHint writes an error message with a hint to stderr and exits.
func FatalErrorWithHint(message, hint string) {
if jsonOutput {
jsonStderrError(message, hint)
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", message)
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint)
}
os.Exit(1)
}
func WarnError(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "Warning: "+format+"\n", args...)
}
// CheckReadonly aborts the command when bd is running in read-only mode (the
// worker-sandbox posture, see readonlyMode). Like the proxied-server FatalError*
// family above, it exits via os.Exit and so cannot run the per-command deferred
// CloseEventAndAdd — a command blocked here records no cli_command event of its
// own (it never actually ran). It does flush metrics first, so events already
// queued earlier in this run are still written and scheduled for upload rather
// than stranded until the next clean exit.
// worker-sandbox posture, see readonlyMode). It exits via os.Exit and so cannot
// run the per-command deferred CloseEventAndAdd — a command blocked here records
// no cli_command event of its own (it never actually ran). It does flush metrics
// first, so events already queued earlier in this run are still written and
// scheduled for upload rather than stranded until the next clean exit.
func CheckReadonly(operation string) {
if readonlyMode {
fmt.Fprintf(os.Stderr, "Error: operation '%s' is not allowed in read-only mode\n", operation)

View file

@ -216,7 +216,7 @@ Examples:
// Direct mode
if err := ensureStoreActive(); err != nil {
FatalErrorRespectJSON("responding to human bead: %v", err)
return HandleErrorRespectJSON("responding to human bead: %v", err)
}
// Resolve partial ID and get issue
@ -299,7 +299,7 @@ Examples:
// Direct mode
if err := ensureStoreActive(); err != nil {
FatalErrorRespectJSON("dismissing human bead: %v", err)
return HandleErrorRespectJSON("dismissing human bead: %v", err)
}
// Resolve partial ID and get issue

View file

@ -583,14 +583,10 @@ func TestMetricsRootVersionFlagSuppressesFirstRunNotice(t *testing.T) {
}
}
// TestInitProxiedServerRejectedKeepsMetricsGapLatent documents and tests the
// containment of the proxied-server metrics-flush gap flagged on PR #4419:
// proxied-server handlers exit via FatalError*/os.Exit, which would bypass the
// deferred per-command metrics close. That gap is harmless only while
// proxied-server mode cannot be entered. This asserts `bd init --proxied-server`
// is rejected as "not yet implemented", so usesProxiedServer() is never true and
// those FatalError* paths never run. See the FatalError doc comment in errors.go.
func TestInitProxiedServerRejectedKeepsMetricsGapLatent(t *testing.T) {
// TestInitProxiedServerRejectedNotYetImplemented asserts `bd init
// --proxied-server` is rejected as "not yet implemented", keeping
// proxied-server mode gated off so usesProxiedServer() is never true.
func TestInitProxiedServerRejectedNotYetImplemented(t *testing.T) {
bd := buildEmbeddedBD(t)
home, err := testTempDir("bd-proxied-gate-home-*")
if err != nil {

View file

@ -152,7 +152,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalError("failed to open unit of work: %v", err)
return HandleError("failed to open unit of work: %v", err)
}
defer uw.Close(ctx)
@ -179,11 +179,11 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
}
if _, err := uw.BootstrapUseCase().BootstrapProject(ctx, bootstrapParams); err != nil {
FatalError("bootstrap project: %v", err)
return HandleError("bootstrap project: %v", err)
}
if err := uw.Commit(ctx, "bd init"); err != nil {
FatalError("commit init: %v", err)
return HandleError("commit init: %v", err)
}
return runInitProxiedServerTail(cmd, ctx, in, runInitTailContext{

View file

@ -2037,7 +2037,7 @@ func setupBareParentInitWorktree(t *testing.T) (string, string) {
// TestInitDatabaseFlag tests the --database flag for bd init.
// Uses subprocess execution because:
// - init manipulates extensive Cobra global state that's difficult to reset
// - FatalError calls os.Exit(1) for validation errors, which kills in-process tests
// - init validation paths call os.Exit(1), which kills in-process tests
//
// Each subtest runs bd init in a temp directory and verifies metadata.json.
func TestInitDatabaseFlag(t *testing.T) {

View file

@ -1062,7 +1062,7 @@ var rootCmd = &cobra.Command{
// the fresh-repo embedded default below.
cfg, cfgErr := configfile.Load(beadsDir)
if cfgErr != nil {
FatalError("failed to load beads config from %s: %v (refusing to fall back to the embedded store; fix or restore metadata.json and retry)", beadsDir, cfgErr)
return HandleError("failed to load beads config from %s: %v (refusing to fall back to the embedded store; fix or restore metadata.json and retry)", beadsDir, cfgErr)
}
if cfg != nil {
warnSharedServerEmbeddedMismatch(cfg)

View file

@ -46,8 +46,8 @@ func TestReadonlyModeBlocksWrites(t *testing.T) {
for _, tc := range tests {
t.Run(tc.operation, func(t *testing.T) {
// CheckReadonly calls FatalError which calls os.Exit
// We can't test that directly, but we can verify the logic
// CheckReadonly calls os.Exit when readonly, which we can't test
// directly, but we can verify the logic
if !readonlyMode {
t.Error("readonly mode should be enabled")
}
@ -83,9 +83,9 @@ func TestCheckReadonlyReturnsEarlyWhenDisabled(t *testing.T) {
// Disable readonly mode
readonlyMode = false
// Capture that CheckReadonly doesn't call FatalError
// Since FatalError calls os.Exit, we verify by ensuring we don't panic/exit
// The function should just return early
// Capture that CheckReadonly doesn't exit when readonly mode is disabled.
// Since CheckReadonly calls os.Exit when enabled, we verify by ensuring we
// don't panic/exit; the function should just return early
// This test passes if it completes without calling os.Exit
// Since we can't easily mock os.Exit, we just verify the logic
@ -130,7 +130,7 @@ func TestCheckReadonlyErrorMessage(t *testing.T) {
// The error message should mention the operation and readonly mode
expectedSubstrings := []string{"operation", "is not allowed", "read-only mode"}
// We can't easily test FatalError output, but we can verify the format
// We can't easily test the os.Exit output, but we can verify the format
// by checking what error message CheckReadonly would produce
operation := "test-operation"
expectedMsg := "operation 'test-operation' is not allowed in read-only mode"

View file

@ -47,8 +47,7 @@ This is useful for agents executing molecules to see which steps can run next.`,
}()
if usesProxiedServer() {
runReadyProxiedServer(cmd, rootCtx)
return nil
return runReadyProxiedServer(cmd, rootCtx)
}
if offset, _ := cmd.Flags().GetInt("offset"); offset > 0 {
@ -333,8 +332,7 @@ var blockedCmd = &cobra.Command{
}()
if usesProxiedServer() {
runBlockedProxiedServer(cmd, rootCtx)
return nil
return runBlockedProxiedServer(cmd, rootCtx)
}
// Use global jsonOutput set by PersistentPreRun (respects config.yaml + env vars)
// Use factory to respect backend configuration (bd-m2jr: SQLite fallback fix)

View file

@ -27,7 +27,7 @@ type readyInput struct {
jsonOut bool
}
func gatherReadyInput(cmd *cobra.Command) readyInput {
func gatherReadyInput(cmd *cobra.Command) (readyInput, error) {
in := readyInput{}
in.claim, _ = cmd.Flags().GetBool("claim")
@ -42,7 +42,7 @@ func gatherReadyInput(cmd *cobra.Command) readyInput {
if cmd.Flags().Changed("offset") {
offset, _ := cmd.Flags().GetInt("offset")
if offset < 0 {
FatalError("--offset must be >= 0")
return in, HandleError("--offset must be >= 0")
}
in.offset = offset
}
@ -64,34 +64,34 @@ func gatherReadyInput(cmd *cobra.Command) readyInput {
if molTypeStr != "" {
mt := types.MolType(molTypeStr)
if !mt.IsValid() {
FatalError("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr)
return in, HandleError("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr)
}
molType = &mt
}
if in.claim && assignee != "" {
FatalErrorRespectJSON("--claim cannot be combined with --assignee")
return in, HandleErrorRespectJSON("--claim cannot be combined with --assignee")
}
if in.claim && in.gated {
FatalErrorRespectJSON("--claim cannot be combined with --gated")
return in, HandleErrorRespectJSON("--claim cannot be combined with --gated")
}
if in.claim && in.molID != "" {
FatalErrorRespectJSON("--claim cannot be combined with --mol")
return in, HandleErrorRespectJSON("--claim cannot be combined with --mol")
}
if in.claim && in.explain {
FatalErrorRespectJSON("--claim cannot be combined with --explain")
return in, HandleErrorRespectJSON("--claim cannot be combined with --explain")
}
if in.offset > 0 && in.claim {
FatalErrorRespectJSON("--offset cannot be combined with --claim")
return in, HandleErrorRespectJSON("--offset cannot be combined with --claim")
}
if in.offset > 0 && in.gated {
FatalErrorRespectJSON("--offset cannot be combined with --gated")
return in, HandleErrorRespectJSON("--offset cannot be combined with --gated")
}
if in.offset > 0 && in.molID != "" {
FatalErrorRespectJSON("--offset cannot be combined with --mol")
return in, HandleErrorRespectJSON("--offset cannot be combined with --mol")
}
if in.offset > 0 && in.explain {
FatalErrorRespectJSON("--offset cannot be combined with --explain")
return in, HandleErrorRespectJSON("--offset cannot be combined with --explain")
}
labels = utils.NormalizeLabels(labels)
@ -168,8 +168,8 @@ func gatherReadyInput(cmd *cobra.Command) readyInput {
}
if !in.filter.SortPolicy.IsValid() {
FatalError("invalid sort policy '%s'. Valid values: hybrid, priority, oldest", sortPolicy)
return in, HandleError("invalid sort policy '%s'. Valid values: hybrid, priority, oldest", sortPolicy)
}
return in
return in, nil
}

View file

@ -15,39 +15,42 @@ import (
"github.com/steveyegge/beads/internal/ui"
)
func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) {
in := gatherReadyInput(cmd)
func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) error {
in, err := gatherReadyInput(cmd)
if err != nil {
return err
}
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return HandleErrorRespectJSON("open unit of work: %v", err)
}
defer uw.Close(ctx)
switch {
case in.gated:
runReadyProxiedGated(ctx, uw, in)
return runReadyProxiedGated(ctx, uw, in)
case in.molID != "":
runReadyProxiedMolecule(ctx, uw, in)
return runReadyProxiedMolecule(ctx, uw, in)
case in.explain:
runReadyProxiedExplain(ctx, uw, in)
return runReadyProxiedExplain(ctx, uw, in)
case in.claim:
runReadyProxiedClaim(ctx, uw, in)
return runReadyProxiedClaim(ctx, uw, in)
default:
runReadyProxiedList(ctx, uw, in)
return runReadyProxiedList(ctx, uw, in)
}
}
func runBlockedProxiedServer(cmd *cobra.Command, ctx context.Context) {
func runBlockedProxiedServer(cmd *cobra.Command, ctx context.Context) error {
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return HandleErrorRespectJSON("open unit of work: %v", err)
}
defer uw.Close(ctx)
@ -58,7 +61,7 @@ func runBlockedProxiedServer(cmd *cobra.Command, ctx context.Context) {
blocked, err := uw.IssueUseCase().GetBlockedIssues(ctx, filter)
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
if jsonOutput {
@ -66,11 +69,11 @@ func runBlockedProxiedServer(cmd *cobra.Command, ctx context.Context) {
blocked = []*types.BlockedIssue{}
}
_ = outputJSON(blocked)
return
return nil
}
if len(blocked) == 0 {
fmt.Printf("\n%s No blocked issues\n\n", ui.RenderPass("✨"))
return
return nil
}
fmt.Printf("\n%s Blocked issues (%d):\n\n", ui.RenderFail("🚫"), len(blocked))
for _, issue := range blocked {
@ -85,13 +88,14 @@ func runBlockedProxiedServer(cmd *cobra.Command, ctx context.Context) {
issue.BlockedByCount, blockedBy)
fmt.Println()
}
return nil
}
func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput) {
func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput) error {
if in.jsonOut {
page, err := uw.IssueUseCase().GetReadyWorkWithCounts(ctx, in.filter)
if err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
results := page.Items
if results == nil {
@ -101,12 +105,12 @@ func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput)
if page.HasMore && in.filter.Limit > 0 {
fmt.Fprintf(os.Stderr, "Showing %d ready issues; more matched but were hidden by --limit. Use --limit 0 for all, or --limit N to raise the cap.\n", len(results))
}
return
return nil
}
page, err := uw.IssueUseCase().GetReadyWork(ctx, in.filter)
if err != nil {
FatalError("%v", err)
return HandleError("%v", err)
}
issues := page.Items
truncated := page.HasMore && in.filter.Limit > 0
@ -124,7 +128,7 @@ func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput)
} else {
fmt.Printf("\n%s No open issues\n\n", ui.RenderPass("✨"))
}
return
return nil
}
parentEpicMap := buildParentEpicMapProxied(ctx, uw, issues)
@ -151,14 +155,15 @@ func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput)
if truncated {
fmt.Printf("%s\n\n", ui.RenderMuted(fmt.Sprintf("Showing %d ready issues; more matched but were hidden by --limit. Use --limit 0 for all, or --limit N to raise the cap.", len(issues))))
}
return nil
}
func runReadyProxiedClaim(ctx context.Context, uw uow.UnitOfWork, in readyInput) {
func runReadyProxiedClaim(ctx context.Context, uw uow.UnitOfWork, in readyInput) error {
CheckReadonly("ready --claim")
res, err := uw.IssueUseCase().ClaimReadyIssue(ctx, in.filter, actor)
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
if !res.Claimed {
if in.jsonOut {
@ -166,7 +171,7 @@ func runReadyProxiedClaim(ctx context.Context, uw uow.UnitOfWork, in readyInput)
} else {
fmt.Printf("\n%s No ready work to claim\n\n", ui.RenderWarn("○"))
}
return
return nil
}
var jsonPayload []*types.IssueWithCounts
@ -175,7 +180,7 @@ func runReadyProxiedClaim(ctx context.Context, uw uow.UnitOfWork, in readyInput)
}
if err := uw.Commit(ctx, fmt.Sprintf("bd: ready --claim %s", res.Issue.ID)); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("failed to commit: %v", err)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
SetLastTouchedID(res.Issue.ID)
@ -184,22 +189,23 @@ func runReadyProxiedClaim(ctx context.Context, uw uow.UnitOfWork, in readyInput)
} else {
fmt.Printf("%s Claimed issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(res.Issue.ID, res.Issue.Title))
}
return nil
}
func runReadyProxiedExplain(ctx context.Context, uw uow.UnitOfWork, _ readyInput) {
func runReadyProxiedExplain(ctx context.Context, uw uow.UnitOfWork, _ readyInput) error {
filter := types.WorkFilter{
Status: types.StatusOpen,
SortPolicy: types.SortPolicyPriority,
}
readyPage, err := uw.IssueUseCase().GetReadyWork(ctx, filter)
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
readyIssues := readyPage.Items
blockedIssues, err := uw.IssueUseCase().GetBlockedIssues(ctx, types.WorkFilter{})
if err != nil {
FatalErrorRespectJSON("%v", err)
return HandleErrorRespectJSON("%v", err)
}
readyIDs := make([]string, len(readyIssues))
@ -254,7 +260,7 @@ func runReadyProxiedExplain(ctx context.Context, uw uow.UnitOfWork, _ readyInput
if jsonOutput {
_ = outputJSON(explanation)
return
return nil
}
fmt.Printf("\n%s Ready Work Explanation\n\n", ui.RenderAccent("📊"))
@ -306,13 +312,14 @@ func runReadyProxiedExplain(ctx context.Context, uw uow.UnitOfWork, _ readyInput
fmt.Printf(", %d cycle(s)", explanation.Summary.CycleCount)
}
fmt.Printf("\n\n")
return nil
}
func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInput) {
func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInput) error {
moleculeID := in.molID
subgraph, err := proxiedLoadTemplateSubgraph(ctx, uw, moleculeID)
if err != nil {
FatalError("loading molecule: %v", err)
return HandleError("loading molecule: %v", err)
}
analysis := analyzeMoleculeParallel(subgraph)
@ -339,7 +346,7 @@ func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInp
ParallelGroups: analysis.ParallelGroups,
}
_ = outputJSON(output)
return
return nil
}
fmt.Printf("\n%s Ready steps in molecule: %s\n", ui.RenderAccent("🧪"), subgraph.Root.Title)
@ -347,7 +354,7 @@ func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInp
fmt.Printf(" Total: %d steps, %d ready\n", analysis.TotalSteps, len(readySteps))
if len(readySteps) == 0 {
fmt.Printf("\n%s No ready steps (all blocked or completed)\n\n", ui.RenderWarn("✨"))
return
return nil
}
if len(analysis.ParallelGroups) > 0 {
fmt.Printf("\n%s Parallel Groups:\n", ui.RenderPass("⚡"))
@ -388,9 +395,10 @@ func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInp
}
}
fmt.Println()
return nil
}
func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput) {
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{
@ -398,16 +406,16 @@ func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput)
Status: &closedStatus,
})
if err != nil {
FatalErrorRespectJSON("error searching for closed gates: %v", err)
return HandleErrorRespectJSON("error searching for closed gates: %v", err)
}
if len(gatePage.Items) == 0 {
emitGatedEmpty()
return
return nil
}
readyPage, err := uw.IssueUseCase().GetReadyWork(ctx, types.WorkFilter{})
if err != nil {
FatalErrorRespectJSON("error getting ready work: %v", err)
return HandleErrorRespectJSON("error getting ready work: %v", err)
}
readySet := make(map[string]*types.Issue, len(readyPage.Items))
for _, issue := range readyPage.Items {
@ -417,7 +425,7 @@ func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput)
hookedStatus := types.StatusHooked
hookedPage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Status: &hookedStatus})
if err != nil {
FatalErrorRespectJSON("error searching for hooked issues: %v", err)
return HandleErrorRespectJSON("error searching for hooked issues: %v", err)
}
hookedSet := make(map[string]*types.Issue, len(hookedPage.Items))
for _, issue := range hookedPage.Items {
@ -476,11 +484,11 @@ func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput)
output.Molecules = []*GatedMolecule{}
}
_ = outputJSON(output)
return
return nil
}
if len(molecules) == 0 {
fmt.Printf("\n%s No molecules ready for gate-resume dispatch\n\n", ui.RenderPass("✨"))
return
return nil
}
fmt.Printf("\n%s Molecules ready for gate-resume dispatch (%d):\n\n", ui.RenderAccent("🚪"), len(molecules))
for _, m := range molecules {
@ -489,6 +497,7 @@ func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput)
fmt.Printf(" Ready step: %s (%s)\n", ui.RenderID(m.ReadyStep.ID), m.ReadyStep.Title)
fmt.Println()
}
return nil
}
func emitGatedEmpty() {

View file

@ -31,8 +31,7 @@ This is more explicit than 'bd update --status open' and emits a Reopened event.
}()
if usesProxiedServer() {
runReopenProxiedServer(cmd, rootCtx, args)
return nil
return runReopenProxiedServer(cmd, rootCtx, args)
}
reason, _ := cmd.Flags().GetString("reason")

View file

@ -23,19 +23,19 @@ type reopenProxiedOutcome struct {
reopened bool
}
func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
if len(args) == 0 {
FatalErrorRespectJSON("no issue ID provided")
return HandleErrorRespectJSON("no issue ID provided")
}
reason, _ := cmd.Flags().GetString("reason")
jsonOut, _ := cmd.Flags().GetBool("json")
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return HandleErrorRespectJSON("open unit of work: %v", err)
}
defer uw.Close(ctx)
@ -67,7 +67,7 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
if len(outcomes) > 0 {
msg := reopenProxiedCommitMessage(outcomes)
if err := uw.Commit(ctx, msg); err != nil && !isDoltNothingToCommit(err) {
FatalErrorRespectJSON("commit reopen: %v", err)
return HandleErrorRespectJSON("commit reopen: %v", err)
}
for _, o := range outcomes {
if err := fireProxiedReopenHooks(ctx, o.after); err != nil {
@ -82,6 +82,7 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
if hasError {
os.Exit(1)
}
return nil
}
func reopenProxiedOne(ctx context.Context, uw uow.UnitOfWork, id, reason string) (reopenProxiedOutcome, bool) {

View file

@ -31,8 +31,7 @@ var showCmd = &cobra.Command{
}()
if usesProxiedServer() {
runShowProxiedServer(cmd, rootCtx, args)
return nil
return runShowProxiedServer(cmd, rootCtx, args)
}
showThread, _ := cmd.Flags().GetBool("thread")

View file

@ -54,54 +54,58 @@ func gatherShowProxiedInput(cmd *cobra.Command, args []string) *showProxiedInput
return in
}
func proxiedOpenReadUOW(ctx context.Context) uow.UnitOfWork {
func proxiedOpenReadUOW(ctx context.Context) (uow.UnitOfWork, error) {
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return nil, HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalErrorRespectJSON("open unit of work: %v", err)
return nil, HandleErrorRespectJSON("open unit of work: %v", err)
}
return uw
return uw, nil
}
func runShowProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
func runShowProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
in := gatherShowProxiedInput(cmd, args)
if in.watchMode {
FatalErrorRespectJSON("watch mode not supported in proxied-server mode")
return HandleErrorRespectJSON("watch mode not supported in proxied-server mode")
}
uw := proxiedOpenReadUOW(ctx)
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
defer uw.Close(ctx)
if in.currentMode {
if len(in.ids) > 0 {
FatalErrorRespectJSON("--current cannot be combined with explicit issue IDs")
return HandleErrorRespectJSON("--current cannot be combined with explicit issue IDs")
}
currentID := resolveCurrentIssueIDProxied(ctx, uw)
if currentID == "" {
FatalErrorRespectJSON("no current issue found (no in-progress, hooked, or recently touched issues)")
return HandleErrorRespectJSON("no current issue found (no in-progress, hooked, or recently touched issues)")
}
in.ids = []string{currentID}
}
if len(in.ids) == 0 {
FatalErrorRespectJSON("at least one issue ID is required (use positional args, --id flag, or --current)")
return HandleErrorRespectJSON("at least one issue ID is required (use positional args, --id flag, or --current)")
}
switch {
case in.asOfRef != "":
runShowProxiedAsOf(ctx, uw, in)
case in.thread:
runShowProxiedThread(ctx, uw, in)
return runShowProxiedThread(ctx, uw, in)
case in.refs:
runShowProxiedRefs(ctx, uw, in)
case in.children:
runShowProxiedChildren(ctx, uw, in)
default:
runShowProxiedDefault(ctx, uw, in)
return runShowProxiedDefault(ctx, uw, in)
}
return nil
}
func resolveCurrentIssueIDProxied(ctx context.Context, uw uow.UnitOfWork) string {
@ -304,16 +308,16 @@ func runShowProxiedChildren(ctx context.Context, uw uow.UnitOfWork, in *showProx
}
}
func runShowProxiedThread(ctx context.Context, uw uow.UnitOfWork, in *showProxiedInput) {
func runShowProxiedThread(ctx context.Context, uw uow.UnitOfWork, in *showProxiedInput) error {
if len(in.ids) == 0 {
return
return nil
}
startMsg, _, err := proxiedGetIssueOrWisp(ctx, uw, in.ids[0])
if err != nil {
FatalErrorRespectJSON("fetching message %s: %v", in.ids[0], err)
return HandleErrorRespectJSON("fetching message %s: %v", in.ids[0], err)
}
if startMsg == nil {
FatalErrorRespectJSON("message %s not found", in.ids[0])
return HandleErrorRespectJSON("message %s not found", in.ids[0])
}
rootMsg := startMsg
@ -362,7 +366,7 @@ func runShowProxiedThread(ctx context.Context, uw uow.UnitOfWork, in *showProxie
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
_ = encoder.Encode(threadMessages)
return
return nil
}
fmt.Printf("\n%s Thread: %s\n", ui.RenderAccent("📬"), rootMsg.Title)
@ -394,6 +398,7 @@ func runShowProxiedThread(ctx context.Context, uw uow.UnitOfWork, in *showProxie
fmt.Println()
}
fmt.Printf("Total: %d messages in thread\n\n", len(threadMessages))
return nil
}
func proxiedFindRepliesTo(ctx context.Context, uw uow.UnitOfWork, id string) string {
@ -422,7 +427,7 @@ func proxiedFindReplies(ctx context.Context, uw uow.UnitOfWork, id string) []typ
return out
}
func runShowProxiedDefault(ctx context.Context, uw uow.UnitOfWork, in *showProxiedInput) {
func runShowProxiedDefault(ctx context.Context, uw uow.UnitOfWork, in *showProxiedInput) error {
formatTime := func(t time.Time) string {
if in.localTime {
t = t.Local()
@ -462,11 +467,12 @@ func runShowProxiedDefault(ctx context.Context, uw uow.UnitOfWork, in *showProxi
if len(allDetails) > 0 {
_ = outputJSON(allDetails)
} else {
FatalErrorRespectJSON("no issues found matching the provided IDs")
return HandleErrorRespectJSON("no issues found matching the provided IDs")
}
} else if foundCount == 0 {
os.Exit(1)
}
return nil
}
func proxiedBuildDetails(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool, in *showProxiedInput) *types.IssueDetails {

View file

@ -28,7 +28,7 @@ func runSQLProxiedServer(ctx context.Context, query string, csvOutput bool) erro
CheckReadonly("sql")
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)

View file

@ -10,9 +10,11 @@ import (
)
var unclaimCmd = &cobra.Command{
Use: "unclaim [id...]",
GroupID: "issues",
Short: "Release a claimed issue",
Use: "unclaim [id...]",
GroupID: "issues",
Short: "Release a claimed issue",
SilenceUsage: true,
SilenceErrors: true,
Long: `Release a claimed issue by clearing the assignee and resetting status to 'open'.
Use this when an agent crashes mid-work or you need to abandon a claimed task.
@ -23,7 +25,7 @@ Examples:
bd unclaim bd-123 --reason "Agent crashed"
bd unclaim bd-123 bd-456`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("unclaim")
reason, _ := cmd.Flags().GetString("reason")
ctx := rootCtx
@ -31,7 +33,7 @@ Examples:
unclaimedIssues := []*types.Issue{}
hasError := false
if store == nil {
FatalErrorWithHint("database not initialized",
return HandleErrorWithHint("database not initialized",
diagHint())
}
for _, id := range args {
@ -85,6 +87,7 @@ Examples:
if hasError {
os.Exit(1)
}
return nil
},
}

View file

@ -41,8 +41,7 @@ create, update, show, or close operation).`,
}()
if usesProxiedServer() {
runUpdateProxiedServer(cmd, rootCtx, args)
return nil
return runUpdateProxiedServer(cmd, rootCtx, args)
}
// If no IDs provided, use last touched issue

View file

@ -32,12 +32,14 @@ type updateInput struct {
clearDeferStatus bool
}
func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) (*updateInput, error) {
in := &updateInput{fields: map[string]any{}}
if cmd.Flags().Changed("status") {
status, _ := cmd.Flags().GetString("status")
validateUpdateStatus(ctx, status)
if err := validateUpdateStatus(ctx, status); err != nil {
return nil, err
}
in.fields["status"] = status
if status == "closed" {
session, _ := cmd.Flags().GetString("session")
@ -53,7 +55,7 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
priorityStr, _ := cmd.Flags().GetString("priority")
priority, err := validation.ValidatePriority(priorityStr)
if err != nil {
FatalErrorRespectJSON("%v", err)
return nil, HandleErrorRespectJSON("%v", err)
}
in.fields["priority"] = priority
}
@ -61,7 +63,7 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
title, _ := cmd.Flags().GetString("title")
title = strings.TrimSpace(title)
if title == "" {
FatalErrorRespectJSON("title cannot be empty")
return nil, HandleErrorRespectJSON("title cannot be empty")
}
in.fields["title"] = title
}
@ -71,23 +73,23 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
}
description, descChanged, err := getDescriptionFlag(cmd)
if err != nil {
FatalErrorRespectJSON("%v", err)
return nil, HandleErrorRespectJSON("%v", err)
}
if descChanged {
if err := validateDescriptionUpdate(cmd, description, descChanged); err != nil {
FatalErrorRespectJSON("%v", err)
return nil, HandleErrorRespectJSON("%v", err)
}
in.fields["description"] = description
}
design, designChanged, err := getDesignFlag(cmd)
if err != nil {
FatalErrorRespectJSON("%v", err)
return nil, HandleErrorRespectJSON("%v", err)
}
if designChanged {
in.fields["design"] = design
}
if cmd.Flags().Changed("notes") && cmd.Flags().Changed("append-notes") {
FatalErrorRespectJSON("cannot specify both --notes and --append-notes")
return nil, HandleErrorRespectJSON("cannot specify both --notes and --append-notes")
}
if cmd.Flags().Changed("notes") {
notes, _ := cmd.Flags().GetString("notes")
@ -121,7 +123,7 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
if cmd.Flags().Changed("estimate") {
estimate, _ := cmd.Flags().GetInt("estimate")
if estimate < 0 {
FatalErrorRespectJSON("estimate must be a non-negative number of minutes")
return nil, HandleErrorRespectJSON("estimate must be a non-negative number of minutes")
}
in.fields["estimated_minutes"] = estimate
}
@ -154,7 +156,7 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
} else {
t, err := timeparsing.ParseRelativeTime(dueStr, time.Now())
if err != nil {
FatalErrorRespectJSON("invalid --due format %q. Examples: +6h, tomorrow, next monday, 2025-01-15", dueStr)
return nil, HandleErrorRespectJSON("invalid --due format %q. Examples: +6h, tomorrow, next monday, 2025-01-15", dueStr)
}
in.fields["due_at"] = t
}
@ -170,7 +172,7 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
} else {
t, err := timeparsing.ParseRelativeTime(deferStr, time.Now())
if err != nil {
FatalErrorRespectJSON("invalid --defer format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", deferStr)
return nil, HandleErrorRespectJSON("invalid --defer format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", deferStr)
}
inPast := t.Before(time.Now())
if inPast && !jsonOut {
@ -189,13 +191,13 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
noHistoryChanged := cmd.Flags().Changed("no-history")
historyChanged := cmd.Flags().Changed("history")
if ephemeralChanged && persistentChanged {
FatalErrorRespectJSON("cannot specify both --ephemeral and --persistent flags")
return nil, HandleErrorRespectJSON("cannot specify both --ephemeral and --persistent flags")
}
if noHistoryChanged && ephemeralChanged {
FatalErrorRespectJSON("cannot specify both --no-history and --ephemeral flags")
return nil, HandleErrorRespectJSON("cannot specify both --no-history and --ephemeral flags")
}
if noHistoryChanged && historyChanged {
FatalErrorRespectJSON("cannot specify both --no-history and --history flags")
return nil, HandleErrorRespectJSON("cannot specify both --no-history and --history flags")
}
if ephemeralChanged {
in.fields["wisp"] = true
@ -216,48 +218,48 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) *updateInput {
filePath := metadataValue[1:]
data, err := os.ReadFile(filePath) //#nosec G304 -- user-supplied path via @file syntax
if err != nil {
FatalErrorRespectJSON("failed to read metadata file %s: %v", filePath, err)
return nil, HandleErrorRespectJSON("failed to read metadata file %s: %v", filePath, err)
}
metadataJSON = string(data)
} else {
metadataJSON = metadataValue
}
if !json.Valid([]byte(metadataJSON)) {
FatalErrorRespectJSON("invalid JSON in --metadata: must be valid JSON")
return nil, HandleErrorRespectJSON("invalid JSON in --metadata: must be valid JSON")
}
in.mergeMetadataIn = json.RawMessage(metadataJSON)
}
setMetadataFlags, _ := cmd.Flags().GetStringArray("set-metadata")
unsetMetadataFlags, _ := cmd.Flags().GetStringArray("unset-metadata")
if (len(setMetadataFlags) > 0 || len(unsetMetadataFlags) > 0) && cmd.Flags().Changed("metadata") {
FatalErrorRespectJSON("cannot combine --metadata with --set-metadata or --unset-metadata")
return nil, HandleErrorRespectJSON("cannot combine --metadata with --set-metadata or --unset-metadata")
}
in.setMetadata = setMetadataFlags
in.unsetMetadata = unsetMetadataFlags
in.claim, _ = cmd.Flags().GetBool("claim")
return in
return in, nil
}
func validateUpdateStatus(ctx context.Context, status string) {
func validateUpdateStatus(ctx context.Context, status string) error {
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
FatalError("open unit of work: %v", err)
return HandleError("open unit of work: %v", err)
}
names, err := uw.ConfigUseCase().ListAllStatusNames(ctx)
uw.Close(ctx)
if err != nil {
FatalErrorRespectJSON("read status set: %v", err)
return HandleErrorRespectJSON("read status set: %v", err)
}
for _, name := range names {
if name == status {
return
return nil
}
}
FatalErrorRespectJSON("invalid status %q (allowed: %s)", status, strings.Join(names, ", "))
return HandleErrorRespectJSON("invalid status %q (allowed: %s)", status, strings.Join(names, ", "))
}
func isUpdateInputNoop(in *updateInput) bool {

View file

@ -17,15 +17,18 @@ import (
"github.com/steveyegge/beads/internal/ui"
)
func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) {
func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
if len(args) == 0 {
FatalErrorRespectJSON("no issue ID provided")
return HandleErrorRespectJSON("no issue ID provided")
}
in := gatherUpdateInput(ctx, cmd)
in, err := gatherUpdateInput(ctx, cmd)
if err != nil {
return err
}
if isUpdateInputNoop(in) {
fmt.Println("No updates specified")
return
return nil
}
jsonOut, _ := cmd.Flags().GetBool("json")
@ -33,7 +36,10 @@ func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
var anyUpdated bool
for _, id := range args {
issue, ok := applyUpdateProxiedOne(ctx, id, in)
issue, ok, err := applyUpdateProxiedOne(ctx, id, in)
if err != nil {
return err
}
if !ok {
continue
}
@ -51,16 +57,17 @@ func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
if !anyUpdated {
os.Exit(1)
}
return nil
}
func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, bool) {
func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, bool, error) {
if uowProvider == nil {
FatalError("proxied-server UOW provider not initialized")
return nil, false, HandleError("proxied-server UOW provider not initialized")
}
uw, err := uowProvider.NewUOW(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening unit of work for %s: %v\n", id, err)
return nil, false
return nil, false, nil
}
defer uw.Close(ctx)
@ -72,20 +79,20 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
current = wispCurrent
} else if err != nil {
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
return nil, false
return nil, false, nil
} else {
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)
return nil, false
return nil, false, nil
}
}
if err := validateIssueUpdatable(id, current); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
return nil, false
return nil, false, nil
}
spec, err := buildUpdateSpecForIssue(current, in)
if err != nil {
FatalErrorRespectJSON("%v", err)
return nil, false, HandleErrorRespectJSON("%v", err)
}
updated, err := issueUC.ApplyUpdate(ctx, id, spec, actor)
@ -95,18 +102,18 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
} else {
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err)
}
return nil, false
return nil, false, nil
}
if err := uw.Commit(ctx, fmt.Sprintf("bd: update %s", id)); err != nil && !isDoltNothingToCommit(err) {
fmt.Fprintf(os.Stderr, "Error committing %s: %v\n", id, err)
return nil, false
return nil, false, nil
}
if err := fireProxiedUpdateHooks(ctx, current, updated); err != nil {
fmt.Fprintf(os.Stderr, "warning: %s: %v\n", id, err)
}
return updated, true
return updated, true, nil
}
func fireProxiedUpdateHooks(ctx context.Context, before, after *types.Issue) error {

View file

@ -1,6 +1,6 @@
# Error Handling Guidelines
Last reviewed: 2026-05-08
Last reviewed: 2026-07-07
Freshness source: `cmd/bd/*.go`, especially command error exits and JSON error
helpers in `cmd/bd/errors.go`.
@ -13,7 +13,7 @@ The beads codebase currently uses **three distinct error handling patterns** acr
## The Three Patterns
### Pattern A: Exit Immediately (`os.Exit(1)`)
### Pattern A: Return a Fatal Error Through `RunE` (`return HandleError(...)`)
**When to use:**
- **Fatal errors** that prevent the command from completing its core function
@ -24,21 +24,36 @@ The beads codebase currently uses **three distinct error handling patterns** acr
**Example:**
```go
if err := store.CreateIssue(ctx, issue, actor); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
return HandleError("%v", err)
}
```
**Characteristics:**
- Writes `Error:` prefix to stderr
- Returns exit code 1 immediately
- Command makes no further progress
- Database/JSONL may be left in partial state (should be transactional)
**Why not `os.Exit(1)`?** Calling `os.Exit` inside a command handler abandons the
stack without running deferred functions — the per-command metrics event
(`CloseEventAndAdd`) and `main()`'s `metrics.CloseAndFlush()` never run, so the
invocation records no usage event and any `defer`red cleanup (unit-of-work close,
temp-file removal) is skipped. Instead return a `HandleError*` value: it prints
the message and returns a sentinel `*exitError`; cobra unwinds the stack (running
every `defer`), and `main()` maps the sentinel to exit code 1.
**Files using this pattern:**
- `cmd/bd/create.go` (lines 31-32, 46-49, 57-58, 74-75, 107-108, etc.)
- `cmd/bd/init.go` (lines 77-78, 96-97, 104-105, 112-115, 209-210, 225-227)
- `cmd/bd/sync.go` (lines 52-54, 59-60, 82-83, etc.)
**Characteristics:**
- Prints `Error:` (plus `Hint:` for the `WithHint` variants) to stderr; the
`RespectJSON` variants emit a structured JSON error to stdout under `--json`
- Returns `&exitError{Code: 1}` up through `RunE`; `main()` exits 1 after
deferred cleanup and the metrics flush have run
- The command's `cobra.Command` **must** set `SilenceUsage: true` and
`SilenceErrors: true`, or cobra will additionally print `Error: exit code 1`
and the usage text on top of the real message
**Narrow exceptions still using `os.Exit`:** process-level gates that run before
or outside the `RunE` error path — e.g. `CheckReadonly`, which aborts a blocked
command after flushing metrics first. A handful of pre-existing direct
`os.Exit(1)` calls also remain inside handler bodies; new command code should
return a `HandleError*` value instead of adding more.
**Files using this pattern:** nearly every command in `cmd/bd/` — search for
`return HandleError` (e.g. `create.go`, `defer.go`, `dolt.go`, `unclaim.go`,
`compact.go`).
---
@ -115,10 +130,10 @@ Use this flowchart to choose the appropriate error handling pattern:
├─ Is this a fatal error that prevents
│ the command's core purpose?
│
│ YES → Pattern A: Exit with os.Exit(1)
│ • Write "Error: ..." to stderr
│ • Provide actionable hint if possible
│ • Exit code 1
│ YES → Pattern A: return HandleError(...) from RunE
│ • Prints "Error: ..." to stderr
│ • Provide actionable hint (HandleErrorWithHint)
│ • Returns *exitError; main() exits 1 after defers
│
├─ Is this an optional/auxiliary operation
│ where the command can still succeed?
@ -139,13 +154,12 @@ Use this flowchart to choose the appropriate error handling pattern:
## Examples by Scenario
### User Input Validation → Pattern A (Exit)
### User Input Validation → Pattern A (Return Fatal Error)
```go
priority, err := validation.ValidatePriority(priorityStr)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
return HandleError("%v", err)
}
```
@ -177,12 +191,11 @@ if err := store.SetMetadata(ctx, "last_import_hash", currentHash); err != nil {
}
```
### Database Transaction Failures → Pattern A (Exit)
### Database Transaction Failures → Pattern A (Return Fatal Error)
```go
if err := store.CreateIssue(ctx, issue, actor); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
return HandleError("%v", err)
}
```
@ -219,10 +232,9 @@ _ = store.CreateIssue(ctx, issue, actor)
```
```go
// GOOD: Exit on critical errors
// GOOD: Return a fatal error through RunE
if err := store.CreateIssue(ctx, issue, actor); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
return HandleError("%v", err)
}
```
@ -249,7 +261,7 @@ if err := installGitHooks(); err != nil {
When writing tests for error handling:
1. **Pattern A (Exit)** - Test with subprocess or mock `os.Exit`
1. **Pattern A (Fatal)** - Assert `RunE` returns a non-nil error (a `*exitError`); no subprocess or `os.Exit` mock needed, since `HandleError` returns rather than exiting
2. **Pattern B (Warn)** - Capture stderr and verify warning message
3. **Pattern C (Ignore)** - Verify operation was attempted, no error propagates
@ -264,17 +276,18 @@ When writing tests for error handling:
Configuration metadata defines **fundamental system behavior** and must succeed:
```go
// Pattern A: Exit on failure
// Pattern A: return a fatal error through RunE.
// Returning lets a single `defer store.Close()` cover every exit path, instead
// of repeating a manual `_ = store.Close()` before each os.Exit (which os.Exit
// would otherwise skip).
defer store.Close()
if err := store.SetConfig(ctx, "issue_prefix", prefix); err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to set issue prefix: %v\n", err)
_ = store.Close()
os.Exit(1)
return HandleError("failed to set issue prefix: %v", err)
}
if err := syncbranch.Set(ctx, store, branch); err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to set sync branch: %v\n", err)
_ = store.Close()
os.Exit(1)
return HandleError("failed to set sync branch: %v", err)
}
```
@ -346,21 +359,27 @@ defer func() {
- [ ] Similar operations use consistent patterns
- [ ] Error messages provide actionable hints when possible
### Suggested Helper Functions
### Error Helpers
Consider creating helper functions to enforce consistency:
`cmd/bd/errors.go` provides the shared helpers that enforce consistency. Pattern A
handlers return one of the `HandleError*` values; Pattern B uses `WarnError`:
```go
// FatalError writes error to stderr and exits
func FatalError(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "Error: "+format+"\n", args...)
os.Exit(1)
}
// Return through RunE — prints "Error: ..." to stderr, returns *exitError{Code: 1}
func HandleError(format string, args ...interface{}) error
// WarnError writes warning to stderr and continues
func WarnError(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "Warning: "+format+"\n", args...)
}
// Like HandleError, but emits a structured JSON error to stdout under --json
func HandleErrorRespectJSON(format string, args ...interface{}) error
// Adds a "Hint: ..." line (the …RespectJSON variant routes JSON to stdout)
func HandleErrorWithHint(message, hint string) error
func HandleErrorWithHintRespectJSON(message, hint string) error
// Exit 1 with no message, when the error was already reported
func SilentExit() error
// Pattern B — prints "Warning: ..." to stderr and returns nothing
func WarnError(format string, args ...interface{})
```
## Related Issues
@ -371,7 +390,7 @@ func WarnError(format string, args ...interface{}) {
## References
- `cmd/bd/create.go` - Examples of Pattern A for user input validation
- `cmd/bd/errors.go` - The `HandleError*` / `WarnError` / `SilentExit` helpers and the `exitError` sentinel that `main()` maps to an exit code
- `cmd/bd/defer.go` - Clean example of Pattern A: `return HandleError(...)` from a `RunE` with `SilenceUsage`/`SilenceErrors` set
- `cmd/bd/init.go` - Examples of all three patterns
- `cmd/bd/sync.go` - Examples of Pattern B for metadata operations
- `cmd/bd/sync.go` - Examples of Pattern C for cleanup operations
- `cmd/bd/sync.go` - Examples of Pattern B for metadata operations and Pattern C for cleanup operations