diff --git a/.github/workflows/ci-measurements.yml b/.github/workflows/ci-measurements.yml index fad70ce47..80a906579 100644 --- a/.github/workflows/ci-measurements.yml +++ b/.github/workflows/ci-measurements.yml @@ -46,6 +46,10 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }}-${{ inputs.suite }} cancel-in-progress: false +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: pr-linux: name: Measure PR Linux commands diff --git a/.github/workflows/cross-version-smoke.yml b/.github/workflows/cross-version-smoke.yml index 26bb04e95..ac635222e 100644 --- a/.github/workflows/cross-version-smoke.yml +++ b/.github/workflows/cross-version-smoke.yml @@ -22,6 +22,10 @@ concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: smoke: name: Upgrade smoke (${{ matrix.prev_version }} → candidate) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 9afd51d4e..ab26dbcff 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -8,6 +8,10 @@ concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: detect-ci-tier: name: Detect CI tier diff --git a/.github/workflows/migration-test.yml b/.github/workflows/migration-test.yml index bc5b6e500..b16a20a30 100644 --- a/.github/workflows/migration-test.yml +++ b/.github/workflows/migration-test.yml @@ -19,6 +19,10 @@ on: - direct-only - stepping-only +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: migration-test: name: Migration fidelity diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index b8ae05af8..4d9daa933 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -32,6 +32,10 @@ on: required: false default: "" +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: measure: name: Measure selected CI suite diff --git a/.github/workflows/nix-build.yml b/.github/workflows/nix-build.yml index 89562dc08..6d4253a59 100644 --- a/.github/workflows/nix-build.yml +++ b/.github/workflows/nix-build.yml @@ -18,6 +18,10 @@ on: - 'flake.lock' workflow_dispatch: +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: nix-build: name: nix build .#default diff --git a/.github/workflows/pr-risk.yml b/.github/workflows/pr-risk.yml index 873aa43d7..f7d6e8d0a 100644 --- a/.github/workflows/pr-risk.yml +++ b/.github/workflows/pr-risk.yml @@ -9,6 +9,10 @@ concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: detect-ci-tier: name: Detect CI tier diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 4ef0025cb..0e9ada55d 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -9,6 +9,10 @@ concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: build-artifacts: diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml index f71919248..b7e840471 100644 --- a/.github/workflows/regression.yml +++ b/.github/workflows/regression.yml @@ -9,6 +9,10 @@ on: # Allow manual trigger workflow_dispatch: +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: detect-regression-need: name: Detect regression need diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 28e32a557..07f2fdf54 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,6 +17,10 @@ permissions: id-token: write attestations: write +env: + BD_DISABLE_METRICS: "1" + BD_DISABLE_EVENT_FLUSH: "1" + jobs: # Pre-publish gate: refuse to publish a release whose version constants and # Docusaurus docs snapshot disagree. This blocks the failure mode where a tag diff --git a/AGENT_INSTRUCTIONS.md b/AGENT_INSTRUCTIONS.md index a1f29b713..be6038f12 100644 --- a/AGENT_INSTRUCTIONS.md +++ b/AGENT_INSTRUCTIONS.md @@ -586,6 +586,12 @@ gh issue view 201 **Do NOT use:** `browser_navigate`, `browser_snapshot`, or other playwright tools for GitHub PR/issue reviews unless specifically requested by the user. +## Telemetry + +`bd` collects anonymous command-usage metrics. No email, repo path, remote URL, or user-supplied strings are collected. + +To disable persistently: `bd config set --global metrics.disabled true`. For a one-off override: `BD_DISABLE_METRICS=1`. + ## Questions? - Check existing issues: `bd list` diff --git a/cmd/bd/ado.go b/cmd/bd/ado.go index 61a8f6e3d..867522688 100644 --- a/cmd/bd/ado.go +++ b/cmd/bd/ado.go @@ -11,6 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/ado" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" "github.com/steveyegge/beads/internal/tracker" @@ -355,6 +356,13 @@ type adoStatusResult struct { // runADOStatus implements the ado status command. func runADOStatus(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("ado-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + cfg := getADOConfig() if jsonOutput { @@ -371,8 +379,7 @@ func runADOStatus(cmd *cobra.Command, _ []string) error { } else { result.Configured = true } - outputJSON(result) - return nil + return outputJSON(result) } out := cmd.OutOrStdout() @@ -402,6 +409,13 @@ func runADOStatus(cmd *cobra.Command, _ []string) error { // runADOProjects implements the ado projects command. func runADOProjects(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("ado-projects") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + cfg := getADOConfig() if cfg.PAT == "" { return fmt.Errorf("ado.pat not configured: set via 'bd config set ado.pat ' or AZURE_DEVOPS_PAT env var") @@ -423,8 +437,7 @@ func runADOProjects(cmd *cobra.Command, _ []string) error { } if jsonOutput { - outputJSON(projects) - return nil + return outputJSON(projects) } _, _ = fmt.Fprintln(out, "Azure DevOps Projects") @@ -465,6 +478,13 @@ type adoSyncResult struct { // runADOSync implements the ado sync command. // Uses the tracker.Engine for all sync operations. func runADOSync(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("ado-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + cfg := getADOConfig() if err := validateADOConfig(cfg); err != nil { return err @@ -667,8 +687,7 @@ func runADOSync(cmd *cobra.Command, _ []string) error { syncResult.ReconcileDeleted = len(reconcileResult.Deleted) syncResult.ReconcileDenied = len(reconcileResult.Denied) } - outputJSON(syncResult) - return nil + return outputJSON(syncResult) } // Human-readable output diff --git a/cmd/bd/assign.go b/cmd/bd/assign.go index ce7c8a169..19e876423 100644 --- a/cmd/bd/assign.go +++ b/cmd/bd/assign.go @@ -4,6 +4,8 @@ import ( "fmt" "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -18,13 +20,22 @@ Shorthand for 'bd update --assignee '. Examples: bd assign bd-123 alice bd assign bd-123 "" # unassign`, - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("assign") id := args[0] assignee := args[1] + evt := metrics.NewCommandEvent("assign") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx result, err := resolveAndGetIssueForMutation(ctx, store, id) @@ -32,39 +43,38 @@ Examples: if result != nil { result.Close() } - FatalErrorRespectJSON("resolving %s: %v", id, err) + return HandleErrorRespectJSON("resolving %s: %v", id, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } - FatalErrorRespectJSON("issue %s not found", id) + return HandleErrorRespectJSON("issue %s not found", id) } defer result.Close() issueStore := result.Store if err := validateIssueUpdatable(id, result.Issue); err != nil { - FatalErrorRespectJSON("%s", err) + return HandleErrorRespectJSON("%s", err) } updates := map[string]interface{}{ "assignee": assignee, } if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, actor); err != nil { - FatalErrorRespectJSON("updating %s: %v", id, err) + return HandleErrorRespectJSON("updating %s: %v", id, err) } if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{ Command: "assign", IssueIDs: []string{result.ResolvedID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } SetLastTouchedID(result.ResolvedID) - // Re-fetch for display updatedIssue, _ := issueStore.GetIssue(ctx, result.ResolvedID) title := "" if updatedIssue != nil { @@ -72,7 +82,9 @@ Examples: } if jsonOutput { if updatedIssue != nil { - outputJSON(updatedIssue) + if err := outputJSON(updatedIssue); err != nil { + return err + } } } else { if assignee == "" { @@ -81,6 +93,7 @@ Examples: fmt.Printf("%s Assigned %s to %s\n", ui.RenderPass("āœ“"), formatFeedbackID(result.ResolvedID, title), assignee) } } + return nil }, } diff --git a/cmd/bd/audit.go b/cmd/bd/audit.go index cd9cb6c2c..900da6c82 100644 --- a/cmd/bd/audit.go +++ b/cmd/bd/audit.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/audit" + "github.com/steveyegge/beads/internal/metrics" ) var ( @@ -38,14 +39,21 @@ Entries are append-only. Labeling creates a new "label" entry that references a } var auditRecordCmd = &cobra.Command{ - Use: "record", - Short: "Append an audit interaction entry", - Run: func(cmd *cobra.Command, _ []string) { + Use: "record", + Short: "Append an audit interaction entry", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("audit-record") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + var e audit.Entry - // If stdin is piped and no explicit record fields were provided, assume stdin JSON. - // This matches "or pipe JSON via stdin" without requiring a flag. - fi, _ := os.Stdin.Stat() // Best effort: nil FileInfo means not a pipe, use default behavior + fi, _ := os.Stdin.Stat() stdinPiped := fi != nil && (fi.Mode()&os.ModeCharDevice) == 0 noFieldsProvided := auditRecordKind == "" && auditRecordModel == "" && @@ -59,21 +67,17 @@ var auditRecordCmd = &cobra.Command{ if auditRecordStdin || (stdinPiped && noFieldsProvided) { b, err := io.ReadAll(os.Stdin) if err != nil { - fmt.Fprintf(os.Stderr, "Error: failed to read stdin: %v\n", err) - os.Exit(1) + return HandleError("failed to read stdin: %v", err) } if err := json.Unmarshal(b, &e); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid JSON on stdin: %v\n", err) - os.Exit(1) + return HandleError("invalid JSON on stdin: %v", err) } - // Allow --actor to override/augment stdin. if actor != "" { e.Actor = actor } } else { if auditRecordKind == "" { - fmt.Fprintf(os.Stderr, "Error: --kind is required\n") - os.Exit(1) + return HandleError("--kind is required") } e = audit.Entry{ Kind: auditRecordKind, @@ -93,31 +97,38 @@ var auditRecordCmd = &cobra.Command{ id, err := audit.Append(&e) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } if jsonOutput { - outputJSON(map[string]any{ + return outputJSON(map[string]any{ "id": id, "kind": e.Kind, }) - return } fmt.Println(id) + return nil }, } var auditLabelCmd = &cobra.Command{ - Use: "label ", - Short: "Append a label entry referencing an existing interaction", - Args: cobra.ExactArgs(1), - Run: func(_ *cobra.Command, args []string) { + Use: "label ", + Short: "Append a label entry referencing an existing interaction", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(_ *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("audit-label") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + parentID := args[0] if auditLabelValue == "" { - fmt.Fprintf(os.Stderr, "Error: --label is required\n") - os.Exit(1) + return HandleError("--label is required") } e := audit.Entry{ Kind: "label", @@ -129,20 +140,19 @@ var auditLabelCmd = &cobra.Command{ id, err := audit.Append(&e) if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } if jsonOutput { - outputJSON(map[string]any{ + return outputJSON(map[string]any{ "id": id, "parent_id": parentID, "label": auditLabelValue, }) - return } fmt.Println(id) + return nil }, } @@ -160,7 +170,6 @@ func init() { auditLabelCmd.Flags().StringVar(&auditLabelValue, "label", "", `Label value (e.g. "good" or "bad")`) auditLabelCmd.Flags().StringVar(&auditLabelReason, "reason", "", "Reason for label") - // Issue ID completions auditCmd.ValidArgsFunction = issueIDCompletion auditCmd.AddCommand(auditRecordCmd) diff --git a/cmd/bd/backup.go b/cmd/bd/backup.go index f0bfd8bd9..01184ce65 100644 --- a/cmd/bd/backup.go +++ b/cmd/bd/backup.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" ) var backupCmd = &cobra.Command{ @@ -36,6 +37,13 @@ var backupStatusCmd = &cobra.Command{ Use: "status", Short: "Show last backup status", RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("backup-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + dir, err := backupDir() if err != nil { return err diff --git a/cmd/bd/backup_dolt.go b/cmd/bd/backup_dolt.go index f777026cc..a78155d10 100644 --- a/cmd/bd/backup_dolt.go +++ b/cmd/bd/backup_dolt.go @@ -11,6 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/doltserver" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/versioncontrolops" ) @@ -45,6 +46,13 @@ DoltHub (recommended for cloud backup): After adding, run 'bd backup sync' to push your data.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("backup-init") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx rawPath := args[0] @@ -88,12 +96,11 @@ After adding, run 'bd backup sync' to push your data.`, commandDidWrite.Store(true) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "backup_url": backupURL, "backup_name": defaultDoltBackupName, "initialized": true, }) - return nil } fmt.Printf("Backup destination configured: %s\n", backupURL) @@ -114,6 +121,13 @@ The backup is atomic — if the sync fails, the previous backup state is preserv Run 'bd backup init ' first to configure a destination.`, RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("backup-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx if store == nil { return fmt.Errorf("no store available") @@ -149,11 +163,10 @@ Run 'bd backup init ' first to configure a destination.`, } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "synced": true, "duration": elapsed.String(), }) - return nil } fmt.Printf("Backup synced in %s\n", elapsed.Round(time.Millisecond)) @@ -390,6 +403,13 @@ This unregisters the backup remote from Dolt and removes the local backup configuration. The backup data at the destination is not deleted.`, Aliases: []string{"rm"}, RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("backup-remove") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx if store == nil { return fmt.Errorf("no store available") @@ -419,8 +439,7 @@ backup configuration. The backup data at the destination is not deleted.`, } if jsonOutput { - outputJSON(map[string]interface{}{"removed": true}) - return nil + return outputJSON(map[string]interface{}{"removed": true}) } fmt.Println("Backup destination removed.") diff --git a/cmd/bd/backup_restore.go b/cmd/bd/backup_restore.go index f4780dd3d..0cce3f49f 100644 --- a/cmd/bd/backup_restore.go +++ b/cmd/bd/backup_restore.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/ui" ) @@ -31,6 +32,13 @@ The database must already be initialized (run 'bd init' first if needed). To initialize and restore in one step, use: bd init && bd backup restore`, Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("backup-restore") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx var dir string diff --git a/cmd/bd/batch.go b/cmd/bd/batch.go index b002ff203..a9255b24e 100644 --- a/cmd/bd/batch.go +++ b/cmd/bd/batch.go @@ -3,6 +3,7 @@ package main import ( "bufio" "context" + "errors" "fmt" "io" "os" @@ -10,6 +11,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" ) @@ -78,6 +80,13 @@ normal 'bd' subcommands for interactive/read operations.`, RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("batch") + evt := metrics.NewCommandEvent("batch") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if store == nil { return fmt.Errorf("no database connection available (%s)", diagHint()) } @@ -110,10 +119,12 @@ normal 'bd' subcommands for interactive/read operations.`, fmt.Fprintf(cmd.OutOrStdout(), "line %d: %s\n", op.line, op.raw) } if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "dry_run": true, "operations": len(ops), - }) + }); err != nil { + return err + } } else { fmt.Fprintf(cmd.OutOrStdout(), "%d operations parsed (dry-run, nothing executed)\n", len(ops)) } @@ -124,10 +135,12 @@ normal 'bd' subcommands for interactive/read operations.`, // Empty input is a no-op success, matching 'bd list | bd batch' on // an empty list. if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "operations": 0, "status": "ok", - }) + }); err != nil { + return err + } } else { fmt.Fprintln(cmd.OutOrStdout(), "batch: 0 operations (no-op)") } @@ -156,7 +169,9 @@ normal 'bd' subcommands for interactive/read operations.`, }) if err != nil { if jsonOutput { - outputJSONError(err, "batch_error") + if jerr := outputJSONError(err, "batch_error"); jerr != nil { + return errors.Join(err, jerr) + } } return err } @@ -164,11 +179,13 @@ normal 'bd' subcommands for interactive/read operations.`, commandDidWrite.Store(true) if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "operations": len(results), "status": "ok", "results": results, - }) + }); err != nil { + return err + } } else { fmt.Fprintf(cmd.OutOrStdout(), "batch: %d operations committed\n", len(results)) for _, r := range results { diff --git a/cmd/bd/bootstrap.go b/cmd/bd/bootstrap.go index eb0c6c81d..949ab6260 100644 --- a/cmd/bd/bootstrap.go +++ b/cmd/bd/bootstrap.go @@ -21,6 +21,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/doltserver" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage/dolt" "github.com/steveyegge/beads/internal/storage/doltutil" "github.com/steveyegge/beads/internal/storage/embeddeddolt" @@ -123,7 +124,16 @@ Examples: bd bootstrap --json # Output plan as JSON bd bootstrap --yes # Skip confirmation prompt `, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("bootstrap") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + dryRun, _ := cmd.Flags().GetBool("dry-run") yesFlag, _ := cmd.Flags().GetBool("yes") nonInteractiveFlag, _ := cmd.Flags().GetBool("non-interactive") @@ -153,7 +163,7 @@ Examples: } else { cwd, err := os.Getwd() if err != nil { - FatalError("failed to get working directory: %v", err) + return HandleError("failed to get working directory: %v", err) } beadsDir = filepath.Join(cwd, ".beads") } @@ -163,15 +173,15 @@ Examples: } if beadsDir == "" { - // No .beads and no remote data — nothing to bootstrap from. if jsonOutput { - outputJSON(noWorkspaceBootstrapPayload()) - } else { - fmt.Fprintf(os.Stderr, "%s\n", activeWorkspaceNotFoundMessage()) - fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint()) - fmt.Fprintf(os.Stderr, "Bootstrap is for existing projects that need database setup.\n") + if err := outputJSON(noWorkspaceBootstrapPayload()); err != nil { + return err + } + return SilentExit() } - os.Exit(1) + fmt.Fprintf(os.Stderr, "Hint: %s\n", diagHint()) + fmt.Fprintf(os.Stderr, "Bootstrap is for existing projects that need database setup.\n") + return HandleError("%s", activeWorkspaceNotFoundMessage()) } // Load config from .beads/metadata.json. When the beadsDir was @@ -190,7 +200,7 @@ Examples: resolvedCfg, repairMsg, err := applyBootstrapMetadataRepair(beadsDir, cfg, !dryRun) if err != nil { - FatalError("failed to reconcile shared-server metadata: %v", err) + return HandleError("failed to reconcile shared-server metadata: %v", err) } if resolvedCfg != nil { cfg = resolvedCfg @@ -200,9 +210,11 @@ Examples: plan := detectBootstrapAction(beadsDir, cfg) if jsonOutput { - outputJSON(plan) + if err := outputJSON(plan); err != nil { + return err + } if plan.Action == "none" || dryRun { - return + return nil } } else { if repairMsg != "" { @@ -210,14 +222,14 @@ Examples: } printBootstrapPlan(plan) if plan.Action == "none" || dryRun { - return + return nil } } - // Execute the plan if err := executeBootstrapPlan(plan, cfg, nonInteractive); err != nil { - FatalError("Bootstrap failed: %v", err) + return HandleError("Bootstrap failed: %v", err) } + return nil }, } diff --git a/cmd/bd/branch.go b/cmd/bd/branch.go index df52cce57..4dcbc8302 100644 --- a/cmd/bd/branch.go +++ b/cmd/bd/branch.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -19,29 +20,35 @@ it lists all branches. With an argument, it creates a new branch. Examples: bd branch # List all branches bd branch feature-xyz # Create a new branch named feature-xyz`, - Args: cobra.MaximumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("branch") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // If no args, list branches if len(args) == 0 { branches, err := store.ListBranches(ctx) if err != nil { - FatalErrorRespectJSON("failed to list branches: %v", err) + return HandleErrorRespectJSON("failed to list branches: %v", err) } currentBranch, err := store.CurrentBranch(ctx) if err != nil { - // Non-fatal, just don't show current marker currentBranch = "" } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "current": currentBranch, "branches": branches, }) - return } fmt.Printf("\n%s Branches:\n\n", ui.RenderAccent("🌿")) @@ -53,23 +60,22 @@ Examples: } } fmt.Println() - return + return nil } - // Create new branch branchName := args[0] if err := store.Branch(ctx, branchName); err != nil { - FatalErrorRespectJSON("failed to create branch: %v", err) + return HandleErrorRespectJSON("failed to create branch: %v", err) } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "created": branchName, }) - return } fmt.Printf("Created branch: %s\n", ui.RenderAccent(branchName)) + return nil }, } diff --git a/cmd/bd/children.go b/cmd/bd/children.go index a3fada1d5..84b2bbb31 100644 --- a/cmd/bd/children.go +++ b/cmd/bd/children.go @@ -2,11 +2,10 @@ package main import ( "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/metrics" ) -// childrenCmd lists child beads of a parent. -// This is a convenience alias for 'bd list --parent --status all'. -// Unlike plain 'bd list', children includes closed issues by default (GH#2477). var childrenCmd = &cobra.Command{ Use: "children ", GroupID: "issues", @@ -21,16 +20,23 @@ Examples: bd children hq-abc123 # List all children of hq-abc123 bd children hq-abc123 --json # List children in JSON format bd children hq-abc123 --pretty # Show children in tree format`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("children") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + parentID := args[0] pretty, _ := cmd.Flags().GetBool("pretty") - // Set the parent flag on listCmd, run it, then reset _ = listCmd.Flags().Set("parent", parentID) defer func() { _ = listCmd.Flags().Set("parent", "") }() - // Include all statuses by default so closed children are visible (GH#2477). _ = listCmd.Flags().Set("status", "all") defer func() { _ = listCmd.Flags().Set("status", "") }() @@ -39,7 +45,7 @@ Examples: defer func() { _ = listCmd.Flags().Set("pretty", "false") }() } - listCmd.Run(listCmd, []string{}) + return listCmd.RunE(listCmd, []string{}) }, } diff --git a/cmd/bd/cleanup.go b/cmd/bd/cleanup.go index 6c1c9ef9a..fefcca536 100644 --- a/cmd/bd/cleanup.go +++ b/cmd/bd/cleanup.go @@ -5,6 +5,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -45,9 +46,18 @@ SAFETY: SEE ALSO: bd doctor --fix Automatic health checks and repairs (recommended for routine maintenance) bd admin compact Compact old closed issues to save space`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("admin-cleanup") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := requireServerMode("cleanup"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } force, _ := cmd.Flags().GetBool("force") dryRun, _ := cmd.Flags().GetBool("dry-run") @@ -55,40 +65,34 @@ SEE ALSO: olderThanDays, _ := cmd.Flags().GetInt("older-than") wispOnly, _ := cmd.Flags().GetBool("ephemeral") - // Ensure we have storage if store == nil { if err := ensureStoreActive(); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } ctx := rootCtx - // Build filter for closed issues statusClosed := types.StatusClosed filter := types.IssueFilter{ Status: &statusClosed, } - // Add age filter if specified if olderThanDays > 0 { cutoffTime := time.Now().AddDate(0, 0, -olderThanDays) filter.ClosedBefore = &cutoffTime } - // Add wisp filter if specified (bd-kwro.9) if wispOnly { wispTrue := true filter.Ephemeral = &wispTrue } - // Get all closed issues matching filter closedIssues, err := store.SearchIssues(ctx, "", filter) if err != nil { - FatalError("listing issues: %v", err) + return HandleError("listing issues: %v", err) } - // Filter out pinned issues - they are protected from cleanup (bd-b2k) pinnedCount := 0 filteredIssues := make([]*types.Issue, 0, len(closedIssues)) for _, issue := range closedIssues { @@ -116,7 +120,9 @@ SEE ALSO: if wispOnly { result.Ephemeral = true } - outputJSON(result) + if err := outputJSON(result); err != nil { + return err + } } else { msg := "No closed issues to delete" if wispOnly && olderThanDays > 0 { @@ -128,22 +134,20 @@ SEE ALSO: } fmt.Println(msg) } - return + return nil } - // Extract IDs issueIDs := make([]string, len(closedIssues)) for i, issue := range closedIssues { issueIDs[i] = issue.ID } - // Show preview if !force && !dryRun { issueType := "closed" if wispOnly { issueType = "closed wisp" } - FatalErrorWithHint( + return HandleErrorWithHint( fmt.Sprintf("would delete %d %s issue(s)", len(issueIDs), issueType), "Use --force to confirm or --dry-run to preview.") } @@ -164,8 +168,10 @@ SEE ALSO: fmt.Println() } - // Use the existing batch deletion logic - deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false, "cleanup") + if err := deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false, "cleanup"); err != nil { + return HandleError("%v", err) + } + return nil }, } diff --git a/cmd/bd/close.go b/cmd/bd/close.go index e8370e054..7c5d50eaa 100644 --- a/cmd/bd/close.go +++ b/cmd/bd/close.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/audit" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -30,31 +31,40 @@ When closing multiple issues, provide one --reason for all IDs or repeat --reason once per ID. Reasons map positionally: the first --reason applies to the first ID, the second --reason to the second ID, regardless of where the flags appear in the command line.`, - Args: cobra.MinimumNArgs(0), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(0), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("close") + evt := metrics.NewCommandEvent("close") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runCloseProxiedServer(cmd, rootCtx, args) - return + return nil } // If no IDs provided, use last touched issue if len(args) == 0 { lastTouched := GetLastTouchedID() if lastTouched == "" { - FatalErrorRespectJSON("no issue ID provided and no last touched issue") + return HandleErrorRespectJSON("no issue ID provided and no last touched issue") } args = []string{lastTouched} } 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) } force, _ := cmd.Flags().GetBool("force") @@ -64,7 +74,6 @@ the flags appear in the command line.`, claimNext, _ := cmd.Flags().GetBool("claim-next") - // Get session ID from flag or environment variable session, _ := cmd.Flags().GetString("session") if session == "" { session = os.Getenv("CLAUDE_SESSION_ID") @@ -72,21 +81,18 @@ the flags appear in the command line.`, ctx := rootCtx - // --continue only works with a single issue if continueFlag && len(args) > 1 { - FatalErrorRespectJSON("--continue only works when closing a single issue") + return HandleErrorRespectJSON("--continue only works when closing a single issue") } - // --suggest-next only works with a single issue if 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") } - // Resolve partial IDs with routing fallback (beads-0km). results, cleanup, resolveErr := resolveCloseTargets(ctx, store, args) defer cleanup() if resolveErr != nil { - FatalErrorRespectJSON("%v", resolveErr) + return HandleErrorRespectJSON("%v", resolveErr) } resolvedIDs := make([]string, 0, len(results)) for _, r := range results { @@ -183,16 +189,14 @@ the flags appear in the command line.`, postCloseStore = results[0].Store } - // Handle --suggest-next flag in direct mode if suggestNext && len(resolvedIDs) == 1 && closedCount > 0 { unblocked, err := postCloseStore.GetNewlyUnblockedByClose(ctx, resolvedIDs[0]) if err == nil && len(unblocked) > 0 { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "closed": closedIssues, "unblocked": unblocked, }) - return } fmt.Printf("\nNewly unblocked:\n") for _, issue := range unblocked { @@ -201,7 +205,6 @@ the flags appear in the command line.`, } } - // Handle --continue flag if continueFlag && len(resolvedIDs) == 1 && closedCount > 0 { autoClaim := !noAuto result, err := AdvanceToNextStep(ctx, postCloseStore, resolvedIDs[0], autoClaim, actor) @@ -209,12 +212,10 @@ the flags appear in the command line.`, fmt.Fprintf(os.Stderr, "Warning: could not advance to next step: %v\n", err) } else if result != nil { if jsonOutput { - // Include continue result in JSON output - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "closed": closedIssues, "continue": result, }) - return } PrintContinueResult(result) } @@ -252,12 +253,16 @@ the flags appear in the command line.`, if jsonOutput && len(closedIssues) > 0 { if claimedNextIssue != nil { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "closed": closedIssues, "claimed": claimedNextIssue, - }) + }); err != nil { + return err + } } else { - outputJSON(closedIssues) + if err := outputJSON(closedIssues); err != nil { + return err + } } } @@ -270,17 +275,16 @@ the flags appear in the command line.`, Command: "close", IssueIDs: ids, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } } } - // Exit non-zero if no issues were actually closed (close guard - // and other soft failures should surface as non-zero exit codes for scripting) totalAttempted := len(resolvedIDs) if totalAttempted > 0 && closedCount == 0 { - os.Exit(1) + return SilentExit() } + return nil }, } diff --git a/cmd/bd/comment.go b/cmd/bd/comment.go index 813463f91..421d8010e 100644 --- a/cmd/bd/comment.go +++ b/cmd/bd/comment.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -23,14 +24,22 @@ Examples: bd comment bd-123 Working on this now echo "comment from pipe" | bd comment bd-123 --stdin bd comment bd-123 --file notes.txt`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("comment") + evt := metrics.NewCommandEvent("comment") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + id := args[0] textArgs := args[1:] - // Determine comment text from args, stdin, or file stdinFlag, _ := cmd.Flags().GetBool("stdin") fileFlag, _ := cmd.Flags().GetString("file") @@ -39,23 +48,23 @@ Examples: case stdinFlag: content, err := io.ReadAll(os.Stdin) if err != nil { - FatalErrorRespectJSON("reading from stdin: %v", err) + return HandleErrorRespectJSON("reading from stdin: %v", err) } commentText = strings.TrimRight(string(content), "\n") case fileFlag != "": content, err := readBodyFile(fileFlag) if err != nil { - FatalErrorRespectJSON("reading file: %v", err) + return HandleErrorRespectJSON("reading file: %v", err) } commentText = content case len(textArgs) > 0: commentText = strings.Join(textArgs, " ") default: - FatalErrorRespectJSON("no comment text provided (use positional args, --stdin, or --file)") + return HandleErrorRespectJSON("no comment text provided (use positional args, --stdin, or --file)") } if strings.TrimSpace(commentText) == "" { - FatalErrorRespectJSON("comment text cannot be empty") + return HandleErrorRespectJSON("comment text cannot be empty") } author := getActorWithGit() @@ -67,40 +76,40 @@ Examples: if result != nil { result.Close() } - FatalErrorRespectJSON("resolving %s: %v", id, err) + return HandleErrorRespectJSON("resolving %s: %v", id, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } - FatalErrorRespectJSON("issue %s not found", id) + return HandleErrorRespectJSON("issue %s not found", id) } defer result.Close() issueStore := result.Store if err := validateIssueUpdatable(id, result.Issue); err != nil { - FatalErrorRespectJSON("%s", err) + return HandleErrorRespectJSON("%s", err) } comment, err := issueStore.AddIssueComment(ctx, result.ResolvedID, author, commentText) if err != nil { - FatalErrorRespectJSON("adding comment: %v", err) + return HandleErrorRespectJSON("adding comment: %v", err) } if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{ Command: "comment", IssueIDs: []string{result.ResolvedID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } SetLastTouchedID(result.ResolvedID) if jsonOutput { - outputJSON(comment) - } else { - fmt.Printf("%s Comment added to %s\n", ui.RenderPass("āœ“"), formatFeedbackID(result.ResolvedID, result.Issue.Title)) + return outputJSON(comment) } + fmt.Printf("%s Comment added to %s\n", ui.RenderPass("āœ“"), formatFeedbackID(result.ResolvedID, result.Issue.Title)) + return nil }, } diff --git a/cmd/bd/comments.go b/cmd/bd/comments.go index d932cd0e3..a1a04e9d2 100644 --- a/cmd/bd/comments.go +++ b/cmd/bd/comments.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/uimd" ) @@ -28,13 +29,22 @@ Examples: # Add a comment from a file bd comments add bd-123 -f notes.txt`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("comments") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + localTime, _ := cmd.Flags().GetBool("local-time") issueID := args[0] if err := ensureStoreActive(); err != nil { - FatalErrorRespectJSON("getting comments: %v", err) + return HandleErrorRespectJSON("getting comments: %v", err) } ctx := rootCtx @@ -43,36 +53,33 @@ Examples: if result != nil { result.Close() } - FatalErrorRespectJSON("resolving %s: %v", issueID, err) + return HandleErrorRespectJSON("resolving %s: %v", issueID, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } - FatalErrorRespectJSON("issue %s not found", issueID) + return HandleErrorRespectJSON("issue %s not found", issueID) } defer result.Close() issueID = result.ResolvedID comments, err := result.Store.GetIssueComments(ctx, issueID) if err != nil { - FatalErrorRespectJSON("getting comments: %v", err) + return HandleErrorRespectJSON("getting comments: %v", err) } - // Normalize nil to empty slice for consistent JSON output if comments == nil { comments = make([]*types.Comment, 0) } if jsonOutput { - outputJSON(comments) - return + return outputJSON(comments) } - // Human-readable output if len(comments) == 0 { fmt.Printf("No comments on %s\n", issueID) - return + return nil } fmt.Printf("\nComments on %s:\n\n", issueID) @@ -83,22 +90,22 @@ Examples: } fmt.Printf("[%s] at %s\n", comment.Author, ts.Format("2006-01-02 15:04")) rendered := uimd.RenderMarkdown(comment.Text) - // TrimRight removes trailing newlines that Glamour adds, preventing extra blank lines for _, line := range strings.Split(strings.TrimRight(rendered, "\n"), "\n") { fmt.Printf(" %s\n", line) } fmt.Println() } + return nil }, } -// commentsMisplacedListCmd catches the reflexive "bd comments list" invocation (GH#3542). -// Listing comments always requires an issue id: bd comments . var commentsMisplacedListCmd = &cobra.Command{ - Use: "list", - Short: "Invalid — use bd comments to list comments", - Run: func(cmd *cobra.Command, args []string) { - FatalErrorRespectJSON(`"bd comments list" is not valid. + Use: "list", + Short: "Invalid — use bd comments to list comments", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + return HandleErrorRespectJSON(`"bd comments list" is not valid. To list comments on an issue, run: bd comments @@ -121,38 +128,45 @@ Examples: # Add a comment from a file bd comments add bd-123 -f notes.txt`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("comment add") + + evt := metrics.NewCommandEvent("comments-add") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + issueID := args[0] - // Get comment text from flag or argument commentText, _ := cmd.Flags().GetString("file") if commentText != "" { - // Read from file data, err := os.ReadFile(commentText) // #nosec G304 - user-provided file path is intentional if err != nil { - FatalErrorRespectJSON("reading file: %v", err) + return HandleErrorRespectJSON("reading file: %v", err) } commentText = string(data) } else if len(args) < 2 { - FatalErrorRespectJSON("comment text required (use -f to read from file)") + return HandleErrorRespectJSON("comment text required (use -f to read from file)") } else { commentText = args[1] } if strings.TrimSpace(commentText) == "" { - FatalErrorRespectJSON("comment text cannot be empty") + return HandleErrorRespectJSON("comment text cannot be empty") } - // Get author from author flag, or use git-aware default author, _ := cmd.Flags().GetString("author") if author == "" { author = getActorWithGit() } if err := ensureStoreActive(); err != nil { - FatalErrorRespectJSON("adding comment: %v", err) + return HandleErrorRespectJSON("adding comment: %v", err) } ctx := rootCtx @@ -161,34 +175,34 @@ Examples: if result != nil { result.Close() } - FatalErrorRespectJSON("resolving %s: %v", issueID, err) + return HandleErrorRespectJSON("resolving %s: %v", issueID, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } - FatalErrorRespectJSON("issue %s not found", issueID) + return HandleErrorRespectJSON("issue %s not found", issueID) } defer result.Close() issueID = result.ResolvedID comment, err := result.Store.AddIssueComment(ctx, issueID, author, commentText) if err != nil { - FatalErrorRespectJSON("adding comment: %v", err) + return HandleErrorRespectJSON("adding comment: %v", err) } if err := commitPendingIfEmbedded(ctx, result.Store, actor, doltAutoCommitParams{ Command: "comments add", IssueIDs: []string{issueID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } if jsonOutput { - outputJSON(comment) - return + return outputJSON(comment) } fmt.Printf("Comment added to %s\n", issueID) + return nil }, } diff --git a/cmd/bd/compact_dolt.go b/cmd/bd/compact_dolt.go index 30b80fe0f..2e91b2ff6 100644 --- a/cmd/bd/compact_dolt.go +++ b/cmd/bd/compact_dolt.go @@ -5,6 +5,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" ) @@ -39,7 +40,16 @@ Examples: bd compact --force # Squash commits older than 30 days bd compact --days 7 --force # Keep only last 7 days of history bd compact --days 90 --force # Conservative: squash 90+ day old commits`, - Run: func(_ *cobra.Command, _ []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(_ *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("compact") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if !compactDoltDryRun { CheckReadonly("compact") } @@ -47,58 +57,50 @@ Examples: start := time.Now() if compactDoltDays < 0 { - FatalError("--days must be non-negative") + return HandleError("--days must be non-negative") } - // Get commit log via store interface logEntries, logErr := store.Log(ctx, 0) if logErr != nil { - FatalError("failed to read commit log: %v", logErr) + return HandleError("failed to read commit log: %v", logErr) } totalCommits := len(logEntries) if totalCommits <= 1 { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "success": true, "message": "nothing to compact", "total_commits": totalCommits, }) - return } fmt.Printf("Only %d commit(s). Nothing to compact.\n", totalCommits) - return + return nil } - // Find cutoff and partition commits cutoff := time.Now().AddDate(0, 0, -compactDoltDays) var oldCommits int var recentHashes []string var initialHash, boundaryHash string - // Log is ordered newest-first (ORDER BY date DESC) for _, entry := range logEntries { if entry.Date.Before(cutoff) { oldCommits++ - boundaryHash = entry.Hash // keeps getting overwritten; last = most recent old + boundaryHash = entry.Hash } else { recentHashes = append(recentHashes, entry.Hash) } } - // Initial hash is the oldest commit (last in DESC-ordered log) initialHash = logEntries[totalCommits-1].Hash - // boundaryHash is the most recent old commit — but we iterated DESC, - // so the first old commit we saw is the most recent. Re-scan: boundaryHash = "" for _, entry := range logEntries { if entry.Date.Before(cutoff) { boundaryHash = entry.Hash - break // first match in DESC order = most recent old commit + break } } - // Recent hashes need to be in chronological order (oldest first) for cherry-pick for i, j := 0, len(recentHashes)-1; i < j; i, j = i+1, j-1 { recentHashes[i], recentHashes[j] = recentHashes[j], recentHashes[i] } @@ -107,7 +109,7 @@ Examples: if compactDoltDryRun { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "dry_run": true, "total_commits": totalCommits, "old_commits": oldCommits, @@ -117,7 +119,6 @@ Examples: "initial_hash": initialHash, "boundary_hash": boundaryHash, }) - return } fmt.Printf("DRY RUN — Compact preview\n\n") fmt.Printf(" Total commits: %d\n", totalCommits) @@ -130,29 +131,28 @@ Examples: fmt.Printf("\n Result: %d commits → %d commits\n", totalCommits, recentCommits+1) fmt.Printf(" Run with --force to proceed.\n") } - return + return nil } if oldCommits <= 1 { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "success": true, "message": "nothing to compact", "total_commits": totalCommits, "old_commits": oldCommits, }) - return } fmt.Printf("Only %d old commit(s). Nothing to compact.\n", oldCommits) - return + return nil } if boundaryHash == "" { - FatalError("could not find boundary commit for compaction") + return HandleError("could not find boundary commit for compaction") } if !compactDoltForce { - FatalErrorWithHint( + return HandleErrorWithHint( fmt.Sprintf("would squash %d old commits into 1, preserving %d recent commits", oldCommits, recentCommits), "Use --force to confirm or --dry-run to preview.") @@ -165,11 +165,11 @@ Examples: compactor, ok := storage.UnwrapStore(store).(storage.Compactor) if !ok { - FatalError("storage backend does not support compact") + return HandleError("storage backend does not support compact") } if err := compactor.Compact(ctx, initialHash, boundaryHash, oldCommits, recentHashes); err != nil { - FatalError("compact failed: %v", err) + return HandleError("compact failed: %v", err) } // Reclaim disk space from orphaned old history @@ -183,7 +183,7 @@ Examples: resultCommits := len(recentHashes) + 1 if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "success": true, "commits_before": totalCommits, "commits_after": resultCommits, @@ -191,12 +191,12 @@ Examples: "recent_kept": len(recentHashes), "elapsed_ms": elapsed.Milliseconds(), }) - return } fmt.Printf("āœ“ Compacted %d commits → %d\n", totalCommits, resultCommits) fmt.Printf(" Squashed: %d old commits → 1 base\n", oldCommits) fmt.Printf(" Preserved: %d recent commits\n", len(recentHashes)) fmt.Printf(" Time: %v\n", elapsed.Round(time.Millisecond)) + return nil }, } diff --git a/cmd/bd/config.go b/cmd/bd/config.go index 44e4fba65..4648ae6b5 100644 --- a/cmd/bd/config.go +++ b/cmd/bd/config.go @@ -14,6 +14,7 @@ import ( "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/remotecache" "github.com/steveyegge/beads/internal/types" ) @@ -94,32 +95,33 @@ Examples: var forceGitTracked bool var configSetCmd = &cobra.Command{ - Use: "set ", - Short: "Set a configuration value", - Args: cobra.ExactArgs(2), - Run: func(_ *cobra.Command, args []string) { + Use: "set ", + Short: "Set a configuration value", + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(_ *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("config-set") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + key := args[0] value := args[1] - // Reject keys that look like init-only state so the user does not - // silently land a write in a store that 'bd create' never reads. - // 'bd config set issue-prefix' used to write DB key "issue-prefix" - // (dash) while 'bd create' only reads YAML "issue-prefix" or DB - // "issue_prefix" (underscore) — three divergent stores, write never - // visible. if msg, rejected := rejectProtectedConfigKey(key); rejected { fmt.Fprintln(os.Stderr, msg) - os.Exit(1) + return SilentExit() } if key == "dolt.debug" && !usesSQLServer() { fmt.Fprintln(os.Stderr, "Error: dolt.debug requires a sql-server-backed project (embedded mode has no managed server).") fmt.Fprintln(os.Stderr, " To migrate: re-init with 'bd init --server' or 'bd init --shared-server'.") - os.Exit(1) + return SilentExit() } - // Warn on unrecognized config keys so typos don't silently become - // no-ops. The custom.* namespace is exempt (user-extensible). GH#3293. if !isRecognizedConfigKey(key) { suggestion := suggestConfigKey(key) if suggestion != "" { @@ -130,131 +132,135 @@ var configSetCmd = &cobra.Command{ fmt.Fprintf(os.Stderr, "Run 'bd config --help' for valid namespaces.\n") } - // Refuse to write secret keys to git-tracked config files unless - // --force-git-tracked is set. This prevents accidental exposure of - // API keys and tokens in git history. if !forceGitTracked { if err := config.CheckSecretKeyGitSafety(key); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } } - // Check if this is a yaml-only key (startup settings like no-db, etc.) - // These must be written to config.yaml, not SQLite, because they're read - // before the database is opened. (GH#536) if config.IsYamlOnlyKey(key) { - if err := config.SetYamlConfig(key, value); err != nil { - fmt.Fprintf(os.Stderr, "Error setting config: %v\n", err) - os.Exit(1) + var setErr error + location := "config.yaml" + if config.IsUserGlobalKey(key) { + setErr = config.SetUserYamlConfig(key, value) + location = config.UserConfigYamlPath() + } else { + setErr = config.SetYamlConfig(key, value) + } + if setErr != nil { + return HandleError("setting config: %v", setErr) } if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "key": key, "value": value, - "location": "config.yaml", - }) + "location": location, + }); err != nil { + return err + } } else { - fmt.Printf("Set %s = %s (in config.yaml)\n", key, value) + fmt.Printf("Set %s = %s (in %s)\n", key, value, location) } printConfigSideEffects(checkConfigSetSideEffects(key, value)) - return + return nil } - // beads.role is stored in git config, not SQLite (GH#1531). - // bd doctor reads it from git config, so we write there for consistency. if key == "beads.role" { validRoles := map[string]bool{"maintainer": true, "contributor": true} if !validRoles[value] { - fmt.Fprintf(os.Stderr, "Error: invalid role %q (valid values: maintainer, contributor)\n", value) - os.Exit(1) + return HandleError("invalid role %q (valid values: maintainer, contributor)", value) } cmd := exec.Command("git", "config", "beads.role", value) //nolint:gosec // value is validated against allowlist above if err := cmd.Run(); err != nil { - fmt.Fprintf(os.Stderr, "Error setting beads.role in git config: %v\n", err) - os.Exit(1) + return HandleError("setting beads.role in git config: %v", err) } if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "key": key, "value": value, "location": "git config", - }) + }); err != nil { + return err + } } else { fmt.Printf("Set %s = %s (in git config)\n", key, value) } - return + return nil } if usesProxiedServer() { runConfigSetProxiedServer(rootCtx, key, value) - return + return nil } // Database-stored config requires direct mode if err := ensureDirectMode("config set requires direct database access"); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } ctx := rootCtx - // Validate status.custom config before writing if key == "status.custom" && value != "" { if _, err := types.ParseCustomStatusConfig(value); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid status.custom value: %v\n", err) - os.Exit(1) + return HandleError("invalid status.custom value: %v", err) } } if err := store.SetConfig(ctx, key, value); err != nil { - fmt.Fprintf(os.Stderr, "Error setting config: %v\n", err) - os.Exit(1) + return HandleError("setting config: %v", err) } commandDidWrite.Store(true) if jsonOutput { - outputJSON(map[string]string{ + if err := outputJSON(map[string]string{ "key": key, "value": value, - }) + }); err != nil { + return err + } } else { fmt.Printf("Set %s = %s\n", key, value) } printConfigSideEffects(checkConfigSetSideEffects(key, value)) + return nil }, } var configGetCmd = &cobra.Command{ - Use: "get ", - Short: "Get a configuration value", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Use: "get ", + Short: "Get a configuration value", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("config-get") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + key := args[0] - // Check if this is a yaml-only key (startup settings) - // These are read from config.yaml via viper, not SQLite. (GH#536) if config.IsYamlOnlyKey(key) { value := config.GetYamlConfig(key) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "key": key, "value": value, "location": "config.yaml", }) - } else { - if value == "" { - fmt.Printf("%s (not set in config.yaml)\n", key) - } else { - fmt.Printf("%s\n", value) - } } - return + if value == "" { + fmt.Printf("%s (not set in config.yaml)\n", key) + } else { + fmt.Printf("%s\n", value) + } + return nil } - // beads.role is stored in git config, not SQLite (GH#1531). if key == "beads.role" { cmd := exec.Command("git", "config", "--get", "beads.role") output, err := cmd.Output() @@ -263,30 +269,28 @@ var configGetCmd = &cobra.Command{ value = "" } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "key": key, "value": value, "location": "git config", }) - } else { - if value == "" { - fmt.Printf("%s (not set in git config)\n", key) - } else { - fmt.Printf("%s\n", value) - } } - return + if value == "" { + fmt.Printf("%s (not set in git config)\n", key) + } else { + fmt.Printf("%s\n", value) + } + return nil } if usesProxiedServer() { runConfigGetProxiedServer(rootCtx, key) - return + return nil } // Database-stored config requires direct mode if err := ensureDirectMode("config get requires direct database access"); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } ctx := rootCtx @@ -296,58 +300,62 @@ var configGetCmd = &cobra.Command{ value, err = store.GetConfig(ctx, key) if err != nil { - fmt.Fprintf(os.Stderr, "Error getting config: %v\n", err) - os.Exit(1) + return HandleError("getting config: %v", err) } if jsonOutput { - outputJSON(map[string]string{ + return outputJSON(map[string]string{ "key": key, "value": value, }) - } else { - if value == "" { - fmt.Printf("%s (not set)\n", key) - } else { - fmt.Printf("%s\n", value) - } } + if value == "" { + fmt.Printf("%s (not set)\n", key) + } else { + fmt.Printf("%s\n", value) + } + return nil }, } var configListCmd = &cobra.Command{ - Use: "list", - Short: "List all configuration", - Run: func(cmd *cobra.Command, args []string) { + Use: "list", + Short: "List all configuration", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("config-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runConfigListProxiedServer(rootCtx) - return + return nil } // Config operations work in direct mode only if err := ensureDirectMode("config list requires direct database access"); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } ctx := rootCtx config, err := store.GetAllConfig(ctx) if err != nil { - fmt.Fprintf(os.Stderr, "Error listing config: %v\n", err) - os.Exit(1) + return HandleError("listing config: %v", err) } if jsonOutput { - outputJSON(config) - return + return outputJSON(config) } if len(config) == 0 { fmt.Println("No configuration set") - return + return nil } - // Sort keys for consistent output keys := make([]string, 0, len(config)) for k := range config { keys = append(keys, k) @@ -359,9 +367,8 @@ var configListCmd = &cobra.Command{ fmt.Printf(" %s = %s\n", k, config[k]) } - // Check for config.yaml overrides that take precedence (bd-20j) - // This helps diagnose when effective config differs from database config showConfigYAMLOverrides(config) + return nil }, } @@ -438,76 +445,93 @@ func showConfigYAMLOverrides(dbConfig map[string]string) { } var configUnsetCmd = &cobra.Command{ - Use: "unset ", - Short: "Delete a configuration value", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Use: "unset ", + Short: "Delete a configuration value", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("config-unset") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + key := args[0] - // Check if this is a yaml-only key (startup settings like backup.*, routing.*, etc.) - // These must be removed from config.yaml, not the database. (GH#2727) if config.IsYamlOnlyKey(key) { - if err := config.UnsetYamlConfig(key); err != nil { - fmt.Fprintf(os.Stderr, "Error unsetting config: %v\n", err) - os.Exit(1) + location := "config.yaml" + var unsetErr error + if config.IsUserGlobalKey(key) { + unsetErr = config.UnsetUserYamlConfig(key) + location = config.UserConfigYamlPath() + } else { + unsetErr = config.UnsetYamlConfig(key) + } + if unsetErr != nil { + return HandleError("unsetting config: %v", unsetErr) } if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "key": key, - "location": "config.yaml", - }) + "location": location, + }); err != nil { + return err + } } else { - fmt.Printf("Unset %s (in config.yaml)\n", key) + fmt.Printf("Unset %s (in %s)\n", key, location) } printConfigSideEffects(checkConfigUnsetSideEffects(key)) - return + return nil } - // beads.role is stored in git config, not the database (GH#1531). if key == "beads.role" { gitCmd := exec.Command("git", "config", "--unset", "beads.role") if err := gitCmd.Run(); err != nil { - fmt.Fprintf(os.Stderr, "Error unsetting beads.role in git config: %v\n", err) - os.Exit(1) + return HandleError("unsetting beads.role in git config: %v", err) } if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "key": key, "location": "git config", - }) + }); err != nil { + return err + } } else { fmt.Printf("Unset %s (in git config)\n", key) } - return + return nil } if usesProxiedServer() { runConfigUnsetProxiedServer(rootCtx, key) - return + return nil } // Database-stored config requires direct mode if err := ensureDirectMode("config unset requires direct database access"); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } ctx := rootCtx if err := store.DeleteConfig(ctx, key); err != nil { - fmt.Fprintf(os.Stderr, "Error deleting config: %v\n", err) - os.Exit(1) + return HandleError("deleting config: %v", err) } commandDidWrite.Store(true) if jsonOutput { - outputJSON(map[string]string{ + if err := outputJSON(map[string]string{ "key": key, - }) + }); err != nil { + return err + } } else { fmt.Printf("Unset %s\n", key) } printConfigSideEffects(checkConfigUnsetSideEffects(key)) + return nil }, } @@ -525,38 +549,41 @@ Checks: Examples: bd config validate bd config validate --json`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("config-validate") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + repoPath, err := resolvedConfigRepoRoot() if err != nil { - FatalErrorWithHintRespectJSON(activeWorkspaceNotFoundError(), diagHint()) + return HandleErrorWithHintRespectJSON(activeWorkspaceNotFoundError(), diagHint()) } - // Run the existing doctor config values check doctorCheck := doctor.CheckConfigValues(repoPath) - // Run additional sync-related validations syncIssues := validateSyncConfig(repoPath) - // Combine results allIssues := []string{} if doctorCheck.Detail != "" { allIssues = append(allIssues, strings.Split(doctorCheck.Detail, "\n")...) } allIssues = append(allIssues, syncIssues...) - // Output results if jsonOutput { - result := map[string]interface{}{ + return outputJSON(map[string]interface{}{ "valid": len(allIssues) == 0, "issues": allIssues, - } - outputJSON(result) - return + }) } if len(allIssues) == 0 { fmt.Println("āœ“ All sync-related configuration is valid") - return + return nil } fmt.Println("Configuration validation found issues:") @@ -566,7 +593,7 @@ Checks: } } fmt.Println("\nRun 'bd config set ' to fix configuration issues.") - os.Exit(1) + return SilentExit() }, } @@ -676,9 +703,17 @@ calls, especially in CI. Examples: bd config set-many ado.state_map.open=New ado.state_map.closed=Closed bd config set-many jira.url=https://example.atlassian.net jira.project=PROJ`, - Args: cobra.MinimumNArgs(1), - Run: func(_ *cobra.Command, args []string) { - // Phase 1: Parse all key=value pairs + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(_ *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("config-set-many") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + type kvPair struct { key, value string } @@ -686,30 +721,25 @@ Examples: for _, arg := range args { idx := strings.Index(arg, "=") if idx <= 0 { - fmt.Fprintf(os.Stderr, "Error: invalid argument %q (expected key=value format)\n", arg) - os.Exit(1) + return HandleError("invalid argument %q (expected key=value format)", arg) } pairs = append(pairs, kvPair{key: arg[:idx], value: arg[idx+1:]}) } - // Phase 2: Validate all pairs before writing any for _, p := range pairs { if p.key == "beads.role" { validRoles := map[string]bool{"maintainer": true, "contributor": true} if !validRoles[p.value] { - fmt.Fprintf(os.Stderr, "Error: invalid role %q (valid values: maintainer, contributor)\n", p.value) - os.Exit(1) + return HandleError("invalid role %q (valid values: maintainer, contributor)", p.value) } } if p.key == "status.custom" && p.value != "" { if _, err := types.ParseCustomStatusConfig(p.value); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid status.custom value: %v\n", err) - os.Exit(1) + return HandleError("invalid status.custom value: %v", err) } } } - // Phase 3: Separate into categories var yamlPairs, gitPairs, dbPairs []kvPair for _, p := range pairs { if config.IsYamlOnlyKey(p.key) { @@ -721,34 +751,33 @@ Examples: } } - // Phase 3b: Check git-tracked secret safety for yaml keys if !forceGitTracked { for _, p := range yamlPairs { if err := config.CheckSecretKeyGitSafety(p.key); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } } } - // Phase 4: Write yaml-only keys for _, p := range yamlPairs { - if err := config.SetYamlConfig(p.key, p.value); err != nil { - fmt.Fprintf(os.Stderr, "Error setting config %s: %v\n", p.key, err) - os.Exit(1) + var setErr error + if config.IsUserGlobalKey(p.key) { + setErr = config.SetUserYamlConfig(p.key, p.value) + } else { + setErr = config.SetYamlConfig(p.key, p.value) + } + if setErr != nil { + return HandleError("setting config %s: %v", p.key, setErr) } } - // Phase 5: Write git config keys for _, p := range gitPairs { cmd := exec.Command("git", "config", "beads.role", p.value) //nolint:gosec // value is validated against allowlist above if err := cmd.Run(); err != nil { - fmt.Fprintf(os.Stderr, "Error setting %s in git config: %v\n", p.key, err) - os.Exit(1) + return HandleError("setting %s in git config: %v", p.key, err) } } - // Phase 6: Write DB keys in batch if len(dbPairs) > 0 { if usesProxiedServer() { keys := make([]string, len(dbPairs)) @@ -760,27 +789,26 @@ Examples: runConfigSetManyProxiedServer(rootCtx, keys, values) } else { if err := ensureDirectMode("config set-many requires direct database access"); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } ctx := rootCtx for _, p := range dbPairs { if err := store.SetConfig(ctx, p.key, p.value); err != nil { - fmt.Fprintf(os.Stderr, "Error setting config %s: %v\n", p.key, err) - os.Exit(1) + return HandleError("setting config %s: %v", p.key, err) } } commandDidWrite.Store(true) } } - // Phase 7: Output results if jsonOutput { results := make([]map[string]string, 0, len(pairs)) for _, p := range pairs { location := "database" - if config.IsYamlOnlyKey(p.key) { + if config.IsUserGlobalKey(p.key) { + location = config.UserConfigYamlPath() + } else if config.IsYamlOnlyKey(p.key) { location = "config.yaml" } else if p.key == "beads.role" { location = "git config" @@ -791,11 +819,15 @@ Examples: "location": location, }) } - outputJSON(results) + if err := outputJSON(results); err != nil { + return err + } } else { for _, p := range pairs { location := "" - if config.IsYamlOnlyKey(p.key) { + if config.IsUserGlobalKey(p.key) { + location = fmt.Sprintf(" (in %s)", config.UserConfigYamlPath()) + } else if config.IsYamlOnlyKey(p.key) { location = " (in config.yaml)" } else if p.key == "beads.role" { location = " (in git config)" @@ -803,6 +835,7 @@ Examples: fmt.Printf("Set %s = %s%s\n", p.key, p.value, location) } } + return nil }, } @@ -812,7 +845,7 @@ var recognizedConfigPrefixes = []string{ "export.", "import.", "dolt.", "jira.", "linear.", "github.", "custom.", "status.", "doctor.suppress.", "routing.", "sync.", "git.", "directory.", "repos.", "external_projects.", "validation.", - "hierarchy.", "ai.", "backup.", "federation.", + "hierarchy.", "ai.", "backup.", "federation.", "metrics.", } // recognizedConfigKeys lists valid non-namespaced config keys. diff --git a/cmd/bd/config_apply.go b/cmd/bd/config_apply.go index 3a2bdabd9..a76087232 100644 --- a/cmd/bd/config_apply.go +++ b/cmd/bd/config_apply.go @@ -11,6 +11,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/doltserver" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage/dolt" "github.com/steveyegge/beads/internal/storage/doltutil" ) @@ -50,21 +51,33 @@ Examples: bd config apply bd config apply --dry-run bd config apply --json`, - Run: func(cmd *cobra.Command, _ []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("config-apply") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + dryRun, _ := cmd.Flags().GetBool("dry-run") results := runApply(dryRun) if jsonOutput { - outputJSON(results) + if err := outputJSON(results); err != nil { + return err + } } else { printApplyResults(results) } for _, r := range results { if r.Status == applyStatusError { - os.Exit(1) + return SilentExit() } } + return nil }, } diff --git a/cmd/bd/config_drift.go b/cmd/bd/config_drift.go index 0e68d66ba..e7c858997 100644 --- a/cmd/bd/config_drift.go +++ b/cmd/bd/config_drift.go @@ -14,6 +14,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/doltserver" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage/dolt" ) @@ -53,21 +54,32 @@ Exit codes: Examples: bd config drift bd config drift --json`, - Run: func(_ *cobra.Command, _ []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(_ *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("config-drift") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + items := runDriftChecks() if jsonOutput { - outputJSON(items) + if err := outputJSON(items); err != nil { + return err + } } else { printDriftItems(items) } - // Exit 1 if any drift detected for _, item := range items { if item.Status == driftStatusDrift { - os.Exit(1) + return SilentExit() } } + return nil }, } diff --git a/cmd/bd/config_show.go b/cmd/bd/config_show.go index 9019454f1..c22974069 100644 --- a/cmd/bd/config_show.go +++ b/cmd/bd/config_show.go @@ -11,6 +11,7 @@ import ( "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/metrics" ) // configEntry represents a single configuration key with its effective value and source. @@ -40,7 +41,14 @@ Examples: bd config show bd config show --json bd config show --source config.yaml`, - Run: func(cmd *cobra.Command, _ []string) { + RunE: func(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("config-show") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + sourceFilter, _ := cmd.Flags().GetString("source") entries := collectConfigEntries() @@ -50,16 +58,16 @@ Examples: } if jsonOutput { - outputJSON(entries) - return + return outputJSON(entries) } if len(entries) == 0 { fmt.Println("No configuration found") - return + return nil } printConfigEntries(entries) + return nil }, } diff --git a/cmd/bd/context_binding_integration_test.go b/cmd/bd/context_binding_integration_test.go index 3ae4afe9b..37a37d409 100644 --- a/cmd/bd/context_binding_integration_test.go +++ b/cmd/bd/context_binding_integration_test.go @@ -39,7 +39,7 @@ func filteredEnvForContextBinding(keys ...string) []string { filtered = append(filtered, entry) } } - return filtered + return append(filtered, "BD_DISABLE_METRICS=1", "BD_DISABLE_EVENT_FLUSH=1") } func TestListExplicitDBPathRebindsTargetContext(t *testing.T) { diff --git a/cmd/bd/context_cmd.go b/cmd/bd/context_cmd.go index 9e59f0782..8a7f855a8 100644 --- a/cmd/bd/context_cmd.go +++ b/cmd/bd/context_cmd.go @@ -2,12 +2,12 @@ package main import ( "fmt" - "os" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/doltserver" + "github.com/steveyegge/beads/internal/metrics" ) // ContextInfo contains the effective backend identity and repository context. @@ -45,13 +45,21 @@ Examples: bd context # Show context information bd context --json # Output in JSON format `, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("context") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + info := ContextInfo{ Backend: configfile.BackendDolt, BdVersion: Version, } - // Resolve repo context (works without DB open) if selected := selectedNoDBBeadsDir(cmd); selected != "" { prepareSelectedNoDBContext(selected) } @@ -59,11 +67,12 @@ Examples: rc, err := beads.GetRepoContext() if err != nil { if jsonOutput { - outputJSON(map[string]string{"error": fmt.Sprintf("cannot resolve repo context: %v", err)}) - } else { - fmt.Fprintf(os.Stderr, "Error: cannot resolve repo context: %v\n", err) + if jerr := outputJSON(map[string]string{"error": fmt.Sprintf("cannot resolve repo context: %v", err)}); jerr != nil { + return jerr + } + return SilentExit() } - os.Exit(1) + return HandleError("cannot resolve repo context: %v", err) } info.BeadsDir = rc.BeadsDir @@ -72,12 +81,10 @@ Examples: info.IsRedirected = rc.IsRedirected info.IsWorktree = rc.IsWorktree - // Read role from repo context if role, ok := rc.Role(); ok { info.Role = string(role) } - // Load metadata.json config (does not require DB) cfg, err := configfile.Load(rc.BeadsDir) if err != nil { cfg = configfile.DefaultConfig() @@ -92,16 +99,13 @@ Examples: if cfg.IsDoltServerMode() { info.ServerHost = cfg.GetDoltServerHost() - // Use doltserver.DefaultConfig to resolve the actual runtime port - // (from port file, env var, etc.) instead of the static config default. - // This matches what "bd dolt show" does (GH#2555). dsCfg := doltserver.DefaultConfig(rc.BeadsDir) info.ServerPort = dsCfg.Port } if cfg.IsDoltProxiedServerMode() { p, err := resolveProxiedServerRootPath(rc.BeadsDir) if err != nil { - FatalError("resolve proxied server root: %v", err) + return HandleError("resolve proxied server root: %v", err) } info.ProxiedDir = p } @@ -110,17 +114,16 @@ Examples: info.DataDir = dataDir } - // Read sync remote from the selected repo's config.yaml. if remote := resolveSyncRemoteFromDir(rc.BeadsDir); remote != "" { info.SyncRemote = remote - info.SyncGitRemote = remote // Deprecated: kept for backwards compat + info.SyncGitRemote = remote } if jsonOutput { - outputJSON(info) - } else { - printContextText(info) + return outputJSON(info) } + printContextText(info) + return nil }, } diff --git a/cmd/bd/cook.go b/cmd/bd/cook.go index 797d8e2c3..ac7c9d0f9 100644 --- a/cmd/bd/cook.go +++ b/cmd/bd/cook.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/formula" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -84,8 +85,10 @@ Output (--persist): - The "template" label for proto identification - Child issues for each step - Dependencies matching depends_on relationships`, - Args: cobra.ExactArgs(1), - Run: runCook, + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runCook, } // cookResult holds the result of cooking a formula @@ -306,8 +309,7 @@ func outputCookEphemeral(resolved *formula.Formula, runtimeMode bool, inputVars // Substitute variables in the formula substituteFormulaVars(resolved, inputVars) } - outputJSON(resolved) - return nil + return outputJSON(resolved) } // persistCookFormula creates a proto bead in the database (persist mode) @@ -331,14 +333,13 @@ func persistCookFormula(ctx context.Context, resolved *formula.Formula, protoID } if jsonOutput { - outputJSON(cookResult{ + return outputJSON(cookResult{ ProtoID: result.ProtoID, Formula: resolved.Formula, Created: result.Created, Variables: vars, BondPoints: bondPoints, }) - return nil } fmt.Printf("%s Cooked proto: %s\n", ui.RenderPass("āœ“"), result.ProtoID) @@ -353,34 +354,36 @@ func persistCookFormula(ctx context.Context, resolved *formula.Formula, protoID return nil } -func runCook(cmd *cobra.Command, args []string) { - // Parse and validate flags +func runCook(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("cook") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + flags, err := parseCookFlags(cmd, args) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - // Validate store access for persist mode if flags.persist { CheckReadonly("cook --persist") if store == nil { - FatalError("no database connection") + return HandleError("no database connection") } } - // Load and resolve the formula resolved, err := loadAndResolveFormula(flags.formulaPath, flags.searchPaths) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - // Apply prefix to proto ID if specified protoID := resolved.Formula if flags.prefix != "" { protoID = flags.prefix + resolved.Formula } - // Extract variables and bond points vars := formula.ExtractVariables(resolved) var bondPoints []string if resolved.Compose != nil { @@ -389,24 +392,22 @@ func runCook(cmd *cobra.Command, args []string) { } } - // Handle dry-run mode if flags.dryRun { outputCookDryRun(resolved, protoID, flags.runtimeMode, flags.inputVars, vars, bondPoints) - return + return nil } - // Handle ephemeral mode (default) if !flags.persist { if err := outputCookEphemeral(resolved, flags.runtimeMode, flags.inputVars, vars); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - return + return nil } - // Handle persist mode if err := persistCookFormula(rootCtx, resolved, protoID, flags.force, vars, bondPoints); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } + return nil } // cookFormulaResult holds the result of cooking diff --git a/cmd/bd/count.go b/cmd/bd/count.go index 21aea4007..b3ac5ab6b 100644 --- a/cmd/bd/count.go +++ b/cmd/bd/count.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/utils" ) @@ -31,7 +32,16 @@ Examples: bd count --assignee alice --by-status # Count alice's issues by status bd count --include-infra # Count issues + wisps tier (matches 'bd list --include-infra --all' cardinality) `, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("count") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + status, _ := cmd.Flags().GetString("status") assignee, _ := cmd.Flags().GetString("assignee") issueType, _ := cmd.Flags().GetString("type") @@ -94,7 +104,7 @@ Examples: } if groupCount > 1 { - FatalError("only one --by-* flag can be specified") + return HandleErrorRespectJSON("only one --by-* flag can be specified") } // Normalize labels @@ -145,42 +155,42 @@ Examples: if createdAfter != "" { t, err := parseTimeFlag(createdAfter) if err != nil { - FatalError("parsing --created-after: %v", err) + return HandleErrorRespectJSON("parsing --created-after: %v", err) } filter.CreatedAfter = &t } if createdBefore != "" { t, err := parseTimeFlag(createdBefore) if err != nil { - FatalError("parsing --created-before: %v", err) + return HandleErrorRespectJSON("parsing --created-before: %v", err) } filter.CreatedBefore = &t } if updatedAfter != "" { t, err := parseTimeFlag(updatedAfter) if err != nil { - FatalError("parsing --updated-after: %v", err) + return HandleErrorRespectJSON("parsing --updated-after: %v", err) } filter.UpdatedAfter = &t } if updatedBefore != "" { t, err := parseTimeFlag(updatedBefore) if err != nil { - FatalError("parsing --updated-before: %v", err) + return HandleErrorRespectJSON("parsing --updated-before: %v", err) } filter.UpdatedBefore = &t } if closedAfter != "" { t, err := parseTimeFlag(closedAfter) if err != nil { - FatalError("parsing --closed-after: %v", err) + return HandleErrorRespectJSON("parsing --closed-after: %v", err) } filter.ClosedAfter = &t } if closedBefore != "" { t, err := parseTimeFlag(closedBefore) if err != nil { - FatalError("parsing --closed-before: %v", err) + return HandleErrorRespectJSON("parsing --closed-before: %v", err) } filter.ClosedBefore = &t } @@ -201,33 +211,30 @@ Examples: if includeInfra, _ := cmd.Flags().GetBool("include-infra"); includeInfra { cfg, err := loadDirectListFilterConfig(ctx, store) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } applyCountIncludeInfra(&filter, issueType, cfg) } else { filter.SkipWisps = true // durable tier only; bd count's historical default } - // Q1: SQL COUNT(*) aggregate — avoids materializing all rows. if groupBy == "" { count, err := store.CountIssues(ctx, "", filter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { - result := struct { + return outputJSON(struct { Count int64 `json:"count"` - }{Count: count} - outputJSON(result) - } else { - fmt.Println(count) + }{Count: count}) } - return + fmt.Println(count) + return nil } counts, err := store.CountIssuesByGroup(ctx, filter, groupBy) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } type GroupCount struct { @@ -240,33 +247,31 @@ Examples: groups = append(groups, GroupCount{Group: group, Count: count}) } - // Use CountIssues for the total so multi-label issues aren't double-counted - // (--by-label buckets are not mutually exclusive, unlike status/priority/type). + // --by-label buckets are not mutually exclusive, so use CountIssues for the total + // to avoid double-counting multi-label issues. total, err := store.CountIssues(ctx, "", filter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Sort for consistent output slices.SortFunc(groups, func(a, b GroupCount) int { return cmp.Compare(a.Group, b.Group) }) if jsonOutput { - result := struct { + return outputJSON(struct { Total int64 `json:"total"` Groups []GroupCount `json:"groups"` }{ Total: total, Groups: groups, - } - outputJSON(result) - } else { - fmt.Printf("Total: %d\n\n", total) - for _, g := range groups { - fmt.Printf("%s: %d\n", g.Group, g.Count) - } + }) } + fmt.Printf("Total: %d\n\n", total) + for _, g := range groups { + fmt.Printf("%s: %d\n", g.Group, g.Count) + } + return nil }, } diff --git a/cmd/bd/create.go b/cmd/bd/create.go index 2ecf3556b..bd09576ab 100644 --- a/cmd/bd/create.go +++ b/cmd/bd/create.go @@ -15,6 +15,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/debug" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/remotecache" "github.com/steveyegge/beads/internal/routing" "github.com/steveyegge/beads/internal/storage" @@ -26,42 +27,53 @@ import ( ) var createCmd = &cobra.Command{ - Use: "create [title]", - GroupID: "issues", - Aliases: []string{"new"}, - Short: "Create a new issue (or batch from markdown/graph JSON)", - Args: cobra.MinimumNArgs(0), // Changed to allow no args when using -f - Run: func(cmd *cobra.Command, args []string) { + Use: "create [title]", + GroupID: "issues", + Aliases: []string{"new"}, + Short: "Create a new issue (or batch from markdown/graph JSON)", + Args: cobra.MinimumNArgs(0), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("create") + + evt := metrics.NewCommandEvent("create") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { - in := gatherCreateInput(cmd, args) - runCreateProxiedServer(cmd, rootCtx, in) - return + in, err := gatherCreateInput(cmd, args) + if err != nil { + return err + } + if err := runCreateProxiedServer(cmd, rootCtx, in); err != nil { + return HandleError("%v", err) + } + return nil } file, _ := cmd.Flags().GetString("file") graphFile, _ := cmd.Flags().GetString("graph") - // If file flag is provided, parse markdown and create multiple issues if file != "" { if graphFile != "" { - FatalError("cannot specify both --file and --graph") + return HandleError("cannot specify both --file and --graph") } if len(args) > 0 { - FatalError("cannot specify both title and --file flag") + return HandleError("cannot specify both title and --file flag") } - // --dry-run not supported with --file (would need to parse and preview multiple issues) dryRun, _ := cmd.Flags().GetBool("dry-run") if dryRun { - FatalError("--dry-run is not supported with --file flag") + return HandleError("--dry-run is not supported with --file flag") } - createIssuesFromMarkdown(cmd, file) - return + return createIssuesFromMarkdown(cmd, file) } - // If graph flag is provided, batch-create a graph of issues atomically if graphFile != "" { if len(args) > 0 { - FatalError("cannot specify both title and --graph flag") + return HandleError("cannot specify both title and --graph flag") } graphDryRun, _ := cmd.Flags().GetBool("dry-run") wisp, _ := cmd.Flags().GetBool("ephemeral") @@ -71,35 +83,28 @@ var createCmd = &cobra.Command{ NoHistory: noHistory, } if err := graphOpts.Validate(); err != nil { - FatalError("invalid graph options: %v", err) + return HandleError("invalid graph options: %v", err) } - createIssuesFromGraph(graphFile, graphDryRun, graphOpts) - return + return createIssuesFromGraph(graphFile, graphDryRun, graphOpts) } - // Original single-issue creation logic - // Get title from flag or positional argument titleFlag, _ := cmd.Flags().GetString("title") var title string if len(args) > 0 && titleFlag != "" { - // Both provided - check if they match if args[0] != titleFlag { - FatalError("cannot specify different titles as both positional argument and --title flag\n Positional: %q\n --title: %q", args[0], titleFlag) + return HandleError("cannot specify different titles as both positional argument and --title flag\n Positional: %q\n --title: %q", args[0], titleFlag) } - title = args[0] // They're the same, use either + title = args[0] } else if len(args) > 0 { - // Guard: reject positional args that look like flags (bd-2c0). - // When --help or other flags bypass Cobra's flag parsing (e.g., - // programmatic invocation), they end up here as positional args. if strings.HasPrefix(args[0], "-") { - FatalError("title %q looks like a flag (starts with '-').\n Run 'bd create --help' for available options.\n To use this title anyway, pass it explicitly: bd create --title=%q", args[0], args[0]) + return HandleError("title %q looks like a flag (starts with '-').\n Run 'bd create --help' for available options.\n To use this title anyway, pass it explicitly: bd create --title=%q", args[0], args[0]) } title = args[0] } else if titleFlag != "" { title = titleFlag } else { - FatalError("title required (or use --file to create from markdown)") + return HandleError("title required (or use --file to create from markdown)") } // Get silent flag @@ -116,8 +121,10 @@ var createCmd = &cobra.Command{ } } - // Get field values - description, _ := getDescriptionFlag(cmd) + description, _, err := getDescriptionFlag(cmd) + if err != nil { + return err + } skills, _ := cmd.Flags().GetString("skills") if skills != "" { @@ -135,23 +142,24 @@ var createCmd = &cobra.Command{ description += "## Context\n" + ctxStr } - // Check if description is required by config if description == "" && !isTestIssue(title) { if config.GetBool("create.require-description") { - FatalError("description is required (set create.require-description: false in config.yaml to disable)") + return HandleError("description is required (set create.require-description: false in config.yaml to disable)") } } - design, _ := getDesignFlag(cmd) + design, _, err := getDesignFlag(cmd) + if err != nil { + return err + } acceptance, _ := cmd.Flags().GetString("acceptance") notes, _ := cmd.Flags().GetString("notes") specID, _ := cmd.Flags().GetString("spec-id") - // Parse priority (supports both "1" and "P1" formats) priorityStr, _ := cmd.Flags().GetString("priority") priority, err := validation.ValidatePriority(priorityStr) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } issueType, _ := cmd.Flags().GetString("type") @@ -174,57 +182,51 @@ var createCmd = &cobra.Command{ wisp, _ := cmd.Flags().GetBool("ephemeral") noHistory, _ := cmd.Flags().GetBool("no-history") if wisp && noHistory { - FatalError("--ephemeral and --no-history are mutually exclusive") + return HandleError("--ephemeral and --no-history are mutually exclusive") } molTypeStr, _ := cmd.Flags().GetString("mol-type") var molType types.MolType if molTypeStr != "" { molType = types.MolType(molTypeStr) if !molType.IsValid() { - FatalError("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr) + return HandleError("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr) } } - // Parse wisp type (TTL classification for ephemeral wisps) wispTypeStr, _ := cmd.Flags().GetString("wisp-type") var wispType types.WispType if wispTypeStr != "" { wispType = types.WispType(wispTypeStr) if !wispType.IsValid() { - FatalError("invalid wisp-type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", wispTypeStr) + return HandleError("invalid wisp-type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", wispTypeStr) } } - // Event-specific flags eventCategory, _ := cmd.Flags().GetString("event-category") eventActor, _ := cmd.Flags().GetString("event-actor") eventTarget, _ := cmd.Flags().GetString("event-target") eventPayload, _ := cmd.Flags().GetString("event-payload") - // Validate event-specific flags require --type=event if (eventCategory != "" || eventActor != "" || eventTarget != "" || eventPayload != "") && issueType != "event" { - FatalError("--event-category, --event-actor, --event-target, and --event-payload flags require --type=event") + return HandleError("--event-category, --event-actor, --event-target, and --event-payload flags require --type=event") } - // Parse --due flag (GH#820) - // Uses layered parsing: compact duration → NLP → date-only → RFC3339 var dueAt *time.Time dueStr, _ := cmd.Flags().GetString("due") if dueStr != "" { t, err := timeparsing.ParseRelativeTime(dueStr, time.Now()) if err != nil { - FatalError("invalid --due format %q. Examples: +6h, tomorrow, next monday, 2025-01-15", dueStr) + return HandleError("invalid --due format %q. Examples: +6h, tomorrow, next monday, 2025-01-15", dueStr) } dueAt = &t } - // Parse --defer flag (GH#820) var deferUntil *time.Time deferStr, _ := cmd.Flags().GetString("defer") if deferStr != "" { t, err := timeparsing.ParseRelativeTime(deferStr, time.Now()) if err != nil { - FatalError("invalid --defer format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", deferStr) + return HandleError("invalid --defer format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", deferStr) } // Warn if defer date is in the past (user probably meant future) if t.Before(time.Now()) && !silent && !debug.IsQuiet() { @@ -235,7 +237,6 @@ var createCmd = &cobra.Command{ deferUntil = &t } - // Parse --metadata flag (GH#1406) var metadata json.RawMessage if cmd.Flags().Changed("metadata") { metadataValue, _ := cmd.Flags().GetString("metadata") @@ -245,20 +246,18 @@ var createCmd = &cobra.Command{ // #nosec G304 -- user explicitly provides file path via @file.json syntax data, err := os.ReadFile(filePath) if err != nil { - FatalError("failed to read metadata file %s: %v", filePath, err) + return HandleError("failed to read metadata file %s: %v", filePath, err) } metadataJSON = string(data) } else { metadataJSON = metadataValue } if !json.Valid([]byte(metadataJSON)) { - FatalError("invalid JSON in --metadata: must be valid JSON") + return HandleError("invalid JSON in --metadata: must be valid JSON") } metadata = json.RawMessage(metadataJSON) } - // Validate template based on --validate flag or config - // Uses LintIssue for field-aware validation: checks --acceptance field too (GH#2468 parity) validateTemplate, _ := cmd.Flags().GetBool("validate") validationMode := config.GetString("validation.on-create") if validateTemplate || validationMode == "error" || validationMode == "warn" { @@ -269,21 +268,19 @@ var createCmd = &cobra.Command{ } if err := validation.LintIssue(lintIssue); err != nil { if validateTemplate || validationMode == "error" { - FatalError("%v", err) + return HandleError("%v", err) } - // warn mode: print warning but proceed fmt.Fprintf(os.Stderr, "%s %v\n", ui.RenderWarn("⚠"), err) } } dryRun, _ := cmd.Flags().GetBool("dry-run") - // Get estimate if provided var estimatedMinutes *int if cmd.Flags().Changed("estimate") { est, _ := cmd.Flags().GetInt("estimate") if est < 0 { - FatalError("estimate must be a non-negative number of minutes") + return HandleError("estimate must be a non-negative number of minutes") } estimatedMinutes = &est } @@ -328,7 +325,7 @@ var createCmd = &cobra.Command{ repoPath = routing.DetermineTargetRepo(routingConfig, userRole, ".") } - renderDryRun := func() { + renderDryRun := func() error { previewIssue := buildCreateIssue(createIssueParams{ ID: explicitID, Title: title, @@ -359,51 +356,45 @@ var createCmd = &cobra.Command{ }) if jsonOutput { - outputJSON(previewIssue) - } else { - renderCreateDryRunPreview(previewIssue, labels, deps) + return outputJSON(previewIssue) } + renderCreateDryRunPreview(previewIssue, labels, deps) + return nil } if dryRun && parentID == "" { - renderDryRun() - return + return renderDryRun() } - // Switch to target repo for multi-repo support (bd-6x6g) - // When routing to a different repo, we use direct storage access var targetStore storage.DoltStorage - var remoteCache *remotecache.Cache // non-nil when routing to a remote URL + var remoteCache *remotecache.Cache if !dryRun && repoPath != "." { if remotecache.IsRemoteURL(repoPath) { - // Remote URL: pull into cache, open store, push explicitly after create var err error remoteCache, err = remotecache.DefaultCache() if err != nil { - FatalError("failed to initialize remote cache: %v", err) + return HandleError("failed to initialize remote cache: %v", err) } if _, err := remoteCache.Ensure(rootCtx, repoPath); err != nil { - FatalError("failed to sync remote %s: %v", repoPath, err) + return HandleError("failed to sync remote %s: %v", repoPath, err) } targetStore, err = remoteCache.OpenStore(rootCtx, repoPath, newDoltStoreFromConfig) if err != nil { - FatalError("failed to open remote store: %v", err) + return HandleError("failed to open remote store: %v", err) } } else { targetBeadsDir := routing.ExpandPath(repoPath) debug.Logf("DEBUG: Routing to target repo: %s\n", targetBeadsDir) - // Ensure target beads directory exists with prefix inheritance if err := ensureBeadsDirForPath(rootCtx, targetBeadsDir, store); err != nil { - FatalError("failed to initialize target repo: %v", err) + return HandleError("failed to initialize target repo: %v", err) } - // Open new store for target repo using factory to respect backend config targetBeadsDirPath := filepath.Join(targetBeadsDir, ".beads") var err error targetStore, err = newDoltStoreFromConfig(rootCtx, targetBeadsDirPath) if err != nil { - FatalError("failed to open target store: %v", err) + return HandleError("failed to open target store: %v", err) } } @@ -422,9 +413,8 @@ var createCmd = &cobra.Command{ setStore(targetStore) } - // Check for conflicting flags if explicitID != "" && parentID != "" { - FatalError("cannot specify both --id and --parent flags") + return HandleError("cannot specify both --id and --parent flags") } parentLookupStore := store @@ -432,26 +422,22 @@ var createCmd = &cobra.Command{ var err error parentLookupStore, err = openDryRunTargetStore(rootCtx, repoPath) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } defer func() { _ = parentLookupStore.Close() }() } - // If parent is specified, validate it and optionally inherit labels. - // Child ID allocation is delayed until after the dry-run gate so - // previews do not consume the next child counter. var inheritedLabels []string if parentID != "" { ctx := rootCtx _, err := parentLookupStore.GetIssue(ctx, parentID) if err != nil { if errors.Is(err, storage.ErrNotFound) { - FatalError("parent issue %s not found", parentID) + return HandleError("parent issue %s not found", parentID) } - FatalError("failed to check parent issue: %v", err) + return HandleError("failed to check parent issue: %v", err) } - // Inherit parent labels unless --no-inherit-labels is set (GH#2100) noInheritLabels, _ := cmd.Flags().GetBool("no-inherit-labels") if !noInheritLabels { inheritedLabels, _ = parentLookupStore.GetLabels(ctx, parentID) @@ -461,49 +447,37 @@ var createCmd = &cobra.Command{ labels = mergeCreateLabels(labels, inheritedLabels) if dryRun { - renderDryRun() - return + return renderDryRun() } createCtx := rootCtx if parentID != "" { childID, err := store.GetNextChildID(rootCtx, parentID) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - explicitID = childID // Set as explicit ID for the rest of the flow. + explicitID = childID createCtx = storage.WithReservedChildCounter(createCtx, parentID, childID) } - // Validate explicit ID format if provided if explicitID != "" { - // Basic format validation for all issue types. - // Note: Orchestrator-specific agent ID validation (mayor, polecat, witness, etc.) - // is handled by the orchestrator, not beads core. _, err := validation.ValidateIDFormat(explicitID) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - // Validate prefix matches database prefix ctx := createCtx - // Get database prefix and allowed prefixes from config. - // YAML config takes precedence over DB — in shared-server mode the DB - // may belong to a different project (GH#2469). var dbPrefix, allowedPrefixes string if yamlPrefix := config.GetString("issue-prefix"); yamlPrefix != "" { dbPrefix = yamlPrefix } else { - dbPrefix, _ = store.GetConfig(ctx, "issue_prefix") // Best effort: empty prefix is a valid fallback + dbPrefix, _ = store.GetConfig(ctx, "issue_prefix") } - allowedPrefixes, _ = store.GetConfig(ctx, "allowed_prefixes") // Best effort: empty means no prefix restriction + allowedPrefixes, _ = store.GetConfig(ctx, "allowed_prefixes") - // Use ValidateIDPrefixAllowed which handles multi-hyphen prefixes correctly (GH#1135) - // This checks if the ID starts with an allowed prefix, rather than extracting - // the prefix first (which can fail for IDs like "hq-cv-test" where "test" looks like a word) if err := validation.ValidateIDPrefixAllowed(explicitID, dbPrefix, allowedPrefixes, forceCreate); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } @@ -574,7 +548,7 @@ var createCmd = &cobra.Command{ } if err := store.CreateIssue(ctx, issue, actor); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } // Track whether any post-create writes occurred. CreateIssue commits @@ -634,10 +608,10 @@ var createCmd = &cobra.Command{ } if !depType.IsValid() { - FatalErrorRespectJSON("invalid dependency type %q (must be non-empty, max 50 chars); valid types: %s", depType, createDepsAcceptedTypeList()) + return HandleErrorRespectJSON("invalid dependency type %q (must be non-empty, max 50 chars); valid types: %s", depType, createDepsAcceptedTypeList()) } if !depType.IsWellKnown() { - FatalErrorRespectJSON("unknown dependency type %q; valid types: %s", depType, createDepsAcceptedTypeList()) + return HandleErrorRespectJSON("unknown dependency type %q; valid types: %s", depType, createDepsAcceptedTypeList()) } dep := &types.Dependency{ @@ -656,24 +630,21 @@ var createCmd = &cobra.Command{ } } - // Add waits-for dependency if specified if waitsFor != "" { - // Validate gate type gate := waitsForGate if gate == "" { gate = types.WaitsForAllChildren } if gate != types.WaitsForAllChildren && gate != types.WaitsForAnyChildren { - FatalError("invalid --waits-for-gate value '%s' (valid: all-children, any-children)", gate) + return HandleError("invalid --waits-for-gate value '%s' (valid: all-children, any-children)", gate) } - // Create metadata JSON meta := types.WaitsForMeta{ Gate: gate, } metaJSON, err := json.Marshal(meta) if err != nil { - FatalError("failed to serialize waits-for metadata: %v", err) + return HandleError("failed to serialize waits-for metadata: %v", err) } dep := &types.Dependency{ @@ -689,12 +660,9 @@ var createCmd = &cobra.Command{ } } - // Commit to Dolt. Server-mode DoltStore writes version themselves. - // EmbeddedDoltStore writes to the working set and commits here only - // when --dolt-auto-commit=on. shouldCommit, err := shouldCommitCreatePostWrites(issue, postCreateWrites) if err != nil { - FatalError("dolt auto-commit failed: %v", err) + return HandleError("dolt auto-commit failed: %v", err) } if shouldCommit { commitMsg := fmt.Sprintf("bd: create %s", issue.ID) @@ -703,10 +671,6 @@ var createCmd = &cobra.Command{ } } - // If issue was routed to a different repo, commit pending changes. - // Push is NOT done here — periodic sync handles pushes to - // DoltHub remotes. Per-create pushes caused 22GB of git-remote-cache - // bloat with dozens of agents creating wisps constantly (hq-glw). if repoPath != "." && targetStore != nil { if err := commitPendingIfEmbedded(ctx, targetStore, actor, doltAutoCommitParams{ Command: "create", @@ -716,17 +680,16 @@ var createCmd = &cobra.Command{ } } - // Push to remote if this was a remote-routed create. - // Done explicitly (not via defer) because FatalError calls os.Exit, - // which skips deferred functions. if remoteCache != nil { if pushErr := remoteCache.Push(rootCtx, repoPath); pushErr != nil { - FatalError("failed to push to %s: %v\nThe issue was created locally but not synced to the remote.", repoPath, pushErr) + return HandleError("failed to push to %s: %v\nThe issue was created locally but not synced to the remote.", repoPath, pushErr) } } if jsonOutput { - outputJSON(issue) + if err := outputJSON(issue); err != nil { + return err + } } else if silent { fmt.Println(issue.ID) } else { @@ -734,12 +697,11 @@ var createCmd = &cobra.Command{ fmt.Printf(" Priority: P%d\n", issue.Priority) fmt.Printf(" Status: %s\n", issue.Status) - // Show tip after successful create (direct mode only) maybeShowTip(store) } - // Track as last touched issue SetLastTouchedID(issue.ID) + return nil }, } diff --git a/cmd/bd/create_form.go b/cmd/bd/create_form.go index f98236cdf..935d9d127 100644 --- a/cmd/bd/create_form.go +++ b/cmd/bd/create_form.go @@ -10,6 +10,7 @@ import ( "charm.land/huh/v2" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -274,13 +275,23 @@ The form uses keyboard navigation: - Enter: Submit the form (on the last field or submit button) - Ctrl+C: Cancel and exit - Arrow keys: Navigate within select fields`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("create-form") - runCreateForm(cmd) + + evt := metrics.NewCommandEvent("create-form") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + + return runCreateForm(cmd) }, } -func runCreateForm(cmd *cobra.Command) { +func runCreateForm(cmd *cobra.Command) error { parentID, _ := cmd.Flags().GetString("parent") // Raw form input - will be populated by the form @@ -396,26 +407,24 @@ func runCreateForm(cmd *cobra.Command) { if err != nil { if err == huh.ErrUserAborted { fmt.Fprintln(os.Stderr, "Issue creation canceled.") - os.Exit(0) + return nil } - FatalError("form error: %v", err) + return HandleError("form error: %v", err) } - // Parse the form input fv := parseCreateFormInput(raw) fv.ParentID = parentID - // Direct mode - use the extracted creation function issue, err := CreateIssueFromFormValues(rootCtx, store, fv, actor) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } if jsonOutput { - outputJSON(issue) - } else { - printCreatedIssue(issue) + return outputJSON(issue) } + printCreatedIssue(issue) + return nil } func printCreatedIssue(issue *types.Issue) { diff --git a/cmd/bd/create_input.go b/cmd/bd/create_input.go index 8a9837c1b..09dbe91b7 100644 --- a/cmd/bd/create_input.go +++ b/cmd/bd/create_input.go @@ -62,7 +62,7 @@ type createInput struct { validationMode string } -func gatherCreateInput(cmd *cobra.Command, args []string) createInput { +func gatherCreateInput(cmd *cobra.Command, args []string) (createInput, error) { in := createInput{} in.markdownFile, _ = cmd.Flags().GetString("file") @@ -70,22 +70,26 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { in.dryRun, _ = cmd.Flags().GetBool("dry-run") if in.markdownFile != "" && in.graphFile != "" { - FatalError("cannot specify both --file and --graph") + return in, HandleError("cannot specify both --file and --graph") } if in.markdownFile != "" { if len(args) > 0 { - FatalError("cannot specify both title and --file flag") + return in, HandleError("cannot specify both title and --file flag") } if in.dryRun { - FatalError("--dry-run is not supported with --file flag") + return in, HandleError("--dry-run is not supported with --file flag") + } + if err := rejectSingleIssueFlagsForMarkdown(cmd); err != nil { + return in, err } - rejectSingleIssueFlagsForMarkdown(cmd) } if in.graphFile != "" { if len(args) > 0 { - FatalError("cannot specify both title and --graph flag") + return in, HandleError("cannot specify both title and --graph flag") + } + if err := rejectSingleIssueFlagsForGraph(cmd); err != nil { + return in, err } - rejectSingleIssueFlagsForGraph(cmd) } in.silent, _ = cmd.Flags().GetBool("silent") @@ -96,13 +100,21 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { in.noHistory, _ = cmd.Flags().GetBool("no-history") if in.ephemeral && in.noHistory { - FatalError("--ephemeral and --no-history are mutually exclusive") + return in, HandleError("--ephemeral and --no-history are mutually exclusive") } titleFlag, _ := cmd.Flags().GetString("title") - in.title = resolveTitle(args, titleFlag, in.markdownFile, in.graphFile) + title, err := resolveTitle(args, titleFlag, in.markdownFile, in.graphFile) + if err != nil { + return in, err + } + in.title = title - in.description, _ = getDescriptionFlag(cmd) + desc, _, err := getDescriptionFlag(cmd) + if err != nil { + return in, err + } + in.description = desc skills, _ := cmd.Flags().GetString("skills") if skills != "" { if in.description != "" { @@ -118,7 +130,11 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { in.description += "## Context\n" + ctxStr } - in.design, _ = getDesignFlag(cmd) + design, _, err := getDesignFlag(cmd) + if err != nil { + return in, err + } + in.design = design in.acceptanceCriteria, _ = cmd.Flags().GetString("acceptance") in.notes, _ = cmd.Flags().GetString("notes") in.appendNotes, _ = cmd.Flags().GetString("append-notes") @@ -127,7 +143,7 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { if in.markdownFile == "" && in.graphFile == "" { if in.description == "" && !isTestIssue(in.title) { if config.GetBool("create.require-description") { - FatalError("description is required (set create.require-description: false in config.yaml to disable)") + return in, HandleError("description is required (set create.require-description: false in config.yaml to disable)") } } } @@ -135,7 +151,7 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { priorityStr, _ := cmd.Flags().GetString("priority") priority, err := validation.ValidatePriority(priorityStr) if err != nil { - FatalError("%v", err) + return in, HandleError("%v", err) } in.priority = priority @@ -148,7 +164,7 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { in.waitsForGate, _ = cmd.Flags().GetString("waits-for-gate") if in.explicitID != "" && in.parentID != "" { - FatalError("cannot specify both --id and --parent flags") + return in, HandleError("cannot specify both --id and --parent flags") } in.labels, _ = cmd.Flags().GetStringSlice("labels") @@ -164,14 +180,14 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { if molTypeStr, _ := cmd.Flags().GetString("mol-type"); 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) } in.molType = mt } if wispTypeStr, _ := cmd.Flags().GetString("wisp-type"); wispTypeStr != "" { wt := types.WispType(wispTypeStr) if !wt.IsValid() { - FatalError("invalid wisp-type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", wispTypeStr) + return in, HandleError("invalid wisp-type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", wispTypeStr) } in.wispType = wt } @@ -181,13 +197,13 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { in.eventTarget, _ = cmd.Flags().GetString("event-target") in.eventPayload, _ = cmd.Flags().GetString("event-payload") if (in.eventCategory != "" || in.eventActor != "" || in.eventTarget != "" || in.eventPayload != "") && in.issueType != "event" { - FatalError("--event-category, --event-actor, --event-target, and --event-payload flags require --type=event") + return in, HandleError("--event-category, --event-actor, --event-target, and --event-payload flags require --type=event") } if dueStr, _ := cmd.Flags().GetString("due"); dueStr != "" { t, err := timeparsing.ParseRelativeTime(dueStr, time.Now()) if err != nil { - FatalError("invalid --due format %q. Examples: +6h, tomorrow, next monday, 2025-01-15", dueStr) + return in, HandleError("invalid --due format %q. Examples: +6h, tomorrow, next monday, 2025-01-15", dueStr) } in.dueAt = &t } @@ -195,7 +211,7 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { if deferStr, _ := cmd.Flags().GetString("defer"); deferStr != "" { t, err := timeparsing.ParseRelativeTime(deferStr, time.Now()) if err != nil { - FatalError("invalid --defer format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", deferStr) + return in, HandleError("invalid --defer format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", deferStr) } if t.Before(time.Now()) && !in.silent && !debug.IsQuiet() { fmt.Fprintf(os.Stderr, "%s Defer date %q is in the past. Issue will appear in bd ready immediately.\n", @@ -213,14 +229,14 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { // #nosec G304 -- user explicitly provides file path via @file.json syntax data, err := os.ReadFile(filePath) if err != nil { - FatalError("failed to read metadata file %s: %v", filePath, err) + return in, HandleError("failed to read metadata file %s: %v", filePath, err) } metadataJSON = string(data) } else { metadataJSON = metadataValue } if !json.Valid([]byte(metadataJSON)) { - FatalError("invalid JSON in --metadata: must be valid JSON") + return in, HandleError("invalid JSON in --metadata: must be valid JSON") } in.metadata = json.RawMessage(metadataJSON) in.metadataSet = true @@ -229,7 +245,7 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { if cmd.Flags().Changed("estimate") { est, _ := cmd.Flags().GetInt("estimate") if est < 0 { - FatalError("estimate must be a non-negative number of minutes") + return in, HandleError("estimate must be a non-negative number of minutes") } in.estimatedMinutes = &est } @@ -244,7 +260,7 @@ func gatherCreateInput(cmd *cobra.Command, args []string) createInput { in.validationMode = "error" } - return in + return in, nil } var singleIssueOnlyFlags = []string{ @@ -260,45 +276,46 @@ var singleIssueOnlyFlags = []string{ "metadata", "estimate", "force", "wisp-type", } -func rejectSingleIssueFlagsForMarkdown(cmd *cobra.Command) { +func rejectSingleIssueFlagsForMarkdown(cmd *cobra.Command) error { for _, name := range singleIssueOnlyFlags { if cmd.Flags().Changed(name) { - FatalError("--%s is not valid with --file (markdown templates supply per-issue fields)", name) + return HandleError("--%s is not valid with --file (markdown templates supply per-issue fields)", name) } } + return nil } -func rejectSingleIssueFlagsForGraph(cmd *cobra.Command) { +func rejectSingleIssueFlagsForGraph(cmd *cobra.Command) error { for _, name := range singleIssueOnlyFlags { if cmd.Flags().Changed(name) { - FatalError("--%s is not valid with --graph (graph plans supply per-node fields)", name) + return HandleError("--%s is not valid with --graph (graph plans supply per-node fields)", name) } } if cmd.Flags().Changed("mol-type") { - FatalError("--mol-type is not valid with --graph (graph plans don't carry molecule semantics)") + return HandleError("--mol-type is not valid with --graph (graph plans don't carry molecule semantics)") } + return nil } -func resolveTitle(args []string, titleFlag, markdownFile, graphFile string) string { +func resolveTitle(args []string, titleFlag, markdownFile, graphFile string) (string, error) { if markdownFile != "" || graphFile != "" { - return "" + return "", nil } switch { case len(args) > 0 && titleFlag != "": if args[0] != titleFlag { - FatalError("cannot specify different titles as both positional argument and --title flag\n Positional: %q\n --title: %q", args[0], titleFlag) + return "", HandleError("cannot specify different titles as both positional argument and --title flag\n Positional: %q\n --title: %q", args[0], titleFlag) } - return args[0] + return args[0], nil case len(args) > 0: if strings.HasPrefix(args[0], "-") { - FatalError("title %q looks like a flag (starts with '-').\n Run 'bd create --help' for available options.\n To use this title anyway, pass it explicitly: bd create --title=%q", args[0], args[0]) + return "", HandleError("title %q looks like a flag (starts with '-').\n Run 'bd create --help' for available options.\n To use this title anyway, pass it explicitly: bd create --title=%q", args[0], args[0]) } - return args[0] + return args[0], nil case titleFlag != "": - return titleFlag + return titleFlag, nil default: - FatalError("title required (or use --file to create from markdown)") - return "" + return "", HandleError("title required (or use --file to create from markdown)") } } diff --git a/cmd/bd/create_proxied_server_test.go b/cmd/bd/create_proxied_server_test.go index ff2a98b73..c8568d064 100644 --- a/cmd/bd/create_proxied_server_test.go +++ b/cmd/bd/create_proxied_server_test.go @@ -102,7 +102,10 @@ func TestBuildCreateIssueFromInput_EmptyExternalRefIsNilPointer(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("unexpected error: %v", err) + } if issue.IssueType != types.TypeTask { t.Errorf("type default = %q, want task", issue.IssueType) } @@ -116,9 +119,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("unexpected error: %v", err) + } if issue.IssueType != types.TypeBug { t.Errorf("type = %q, want bug", issue.IssueType) } @@ -128,26 +134,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("unexpected error: %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("unexpected error: %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("unexpected error: %v", err) + } var roundTrip map[string]string if err := json.Unmarshal(issue.Metadata, &roundTrip); err != nil { t.Fatalf("metadata not valid JSON: %v", err) @@ -158,17 +173,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("unexpected error: %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("unexpected error: %v", err) + } if issue.CreatedBy != "alice" || issue.Owner != "alice@example.com" { t.Errorf("identity copy wrong: %q / %q", issue.CreatedBy, issue.Owner) } @@ -189,7 +210,10 @@ func TestBuildDomainGraphPlan(t *testing.T) { }, } - got := buildDomainGraphPlan(plan, createInput{createdBy: "t"}) + got, err := buildDomainGraphPlan(plan, createInput{createdBy: "t"}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if len(got.Nodes) != 2 { t.Fatalf("nodes len = %d", len(got.Nodes)) diff --git a/cmd/bd/defer.go b/cmd/bd/defer.go index 114acac72..56c0c65c3 100644 --- a/cmd/bd/defer.go +++ b/cmd/bd/defer.go @@ -7,6 +7,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/timeparsing" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -30,19 +31,26 @@ Examples: bd defer bd-abc --until=tomorrow # Defer until specific time bd defer bd-abc --reason="waiting on API access" bd defer bd-abc bd-def # Defer multiple issues`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("defer") - // Parse --until flag (GH#820) + evt := metrics.NewCommandEvent("defer") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + var deferUntil *time.Time untilStr, _ := cmd.Flags().GetString("until") if untilStr != "" { t, err := timeparsing.ParseRelativeTime(untilStr, time.Now()) if err != nil { - FatalError("invalid --until format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", untilStr) + return HandleError("invalid --until format %q. Examples: +1h, tomorrow, next monday, 2025-01-15", untilStr) } - // Warn if defer date is in the past (user probably meant future) if t.Before(time.Now()) && !jsonOutput { fmt.Fprintf(os.Stderr, "%s Defer date %q is in the past. Issue will appear in bd ready immediately.\n", ui.RenderWarn("!"), t.Format("2006-01-02 15:04")) @@ -53,23 +61,20 @@ Examples: reason, _ := cmd.Flags().GetString("reason") reason = strings.TrimSpace(reason) if cmd.Flags().Changed("reason") && reason == "" { - FatalError("reason cannot be empty") + return HandleError("reason cannot be empty") } ctx := rootCtx - // Resolve partial IDs _, err := utils.ResolvePartialIDs(ctx, store, args) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } deferredIssues := []*types.Issue{} - // Direct storage access if store == nil { - FatalErrorWithHint("database not initialized", - diagHint()) + return HandleErrorWithHint("database not initialized", diagHint()) } for _, id := range args { @@ -82,7 +87,6 @@ Examples: updates := map[string]interface{}{ "status": string(types.StatusDeferred), } - // Add defer_until if --until specified (GH#820) if deferUntil != nil { updates["defer_until"] = *deferUntil } @@ -119,12 +123,15 @@ Examples: } if jsonOutput && len(deferredIssues) > 0 { - outputJSON(deferredIssues) + if err := outputJSON(deferredIssues); err != nil { + return err + } } if len(args) > 0 { commandDidWrite.Store(true) } + return nil }, } diff --git a/cmd/bd/delete.go b/cmd/bd/delete.go index b24d74b32..249b328cc 100644 --- a/cmd/bd/delete.go +++ b/cmd/bd/delete.go @@ -3,13 +3,13 @@ package main import ( "bufio" "context" - "errors" "fmt" "os" "regexp" "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -46,95 +46,94 @@ Cascade: Recursively delete all dependents Force: Delete and orphan dependents bd delete bd-1 --force`, - Args: cobra.MinimumNArgs(0), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(0), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("delete") + evt := metrics.NewCommandEvent("delete") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runDeleteProxiedServer(cmd, rootCtx, args) - return + return nil } fromFile, _ := cmd.Flags().GetString("from-file") force, _ := cmd.Flags().GetBool("force") dryRun, _ := cmd.Flags().GetBool("dry-run") cascade, _ := cmd.Flags().GetBool("cascade") - // Use global jsonOutput set by PersistentPreRun - // Collect issue IDs from args and/or file issueIDs := make([]string, 0, len(args)) issueIDs = append(issueIDs, args...) if fromFile != "" { fileIDs, err := readIssueIDsFromFile(fromFile) if err != nil { - FatalError("reading file: %v", err) + return HandleError("reading file: %v", err) } issueIDs = append(issueIDs, fileIDs...) } if len(issueIDs) == 0 { _ = cmd.Usage() - FatalError("no issue IDs provided") + return HandleError("no issue IDs provided") } - // Remove duplicates issueIDs = uniqueStrings(issueIDs) - // Direct mode - ensure store is available if store == nil { if err := ensureStoreActive(); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } - // Handle batch deletion in direct mode - // Also use batch path for cascade (which needs to expand dependents) if len(issueIDs) > 1 || cascade { - deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false) - return + if err := deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false); err != nil { + return HandleError("%v", err) + } + return nil } - // Single issue deletion (legacy behavior) issueID := issueIDs[0] ctx := rootCtx // Get the issue to be deleted, using prefix-based routing routedResult, err := resolveAndGetIssueForMutation(ctx, store, issueID) if err != nil { if isNotFoundErr(err) { - FatalError("issue %s not found", issueID) + return HandleError("issue %s not found", issueID) } - FatalError("%v", err) + return HandleError("%v", err) } defer routedResult.Close() issue := routedResult.Issue issueID = routedResult.ResolvedID activeStore := routedResult.Store - // Find all connected issues (dependencies in both directions) connectedIssues := make(map[string]*types.Issue) - // Get dependencies (issues this one depends on) deps, err := activeStore.GetDependencies(ctx, issueID) if err != nil { - FatalError("getting dependencies: %v", err) + return HandleError("getting dependencies: %v", err) } for _, dep := range deps { connectedIssues[dep.ID] = dep } - // Get dependents (issues that depend on this one) dependents, err := activeStore.GetDependents(ctx, issueID) if err != nil { - FatalError("getting dependents: %v", err) + return HandleError("getting dependents: %v", err) } for _, dependent := range dependents { connectedIssues[dependent.ID] = dependent } - // Get dependency records (outgoing) to count how many we'll remove depRecords, err := activeStore.GetDependencyRecords(ctx, issueID) if err != nil { - FatalError("getting dependency records: %v", err) + return HandleError("getting dependency records: %v", err) } // Build the regex pattern for matching issue IDs (handles hyphenated IDs properly) // Pattern: (^|non-word-char)(issueID)($|non-word-char) where word-char includes hyphen idPattern := `(^|[^A-Za-z0-9_-])(` + regexp.QuoteMeta(issueID) + `)($|[^A-Za-z0-9_-])` re := regexp.MustCompile(idPattern) replacementText := `$1[deleted:` + issueID + `]$3` - // Preview mode if !force { fmt.Printf("\n%s\n", ui.RenderFail("āš ļø DELETE PREVIEW")) fmt.Printf("\nIssue to delete:\n") @@ -153,7 +152,6 @@ Force: Delete and orphan dependents fmt.Printf("\nConnected issues where text references will be updated:\n") issuesWithRefs := 0 for id, connIssue := range connectedIssues { - // Check if there are actually text references using the fixed regex hasRefs := re.MatchString(connIssue.Description) || (connIssue.Notes != "" && re.MatchString(connIssue.Notes)) || (connIssue.Design != "" && re.MatchString(connIssue.Design)) || @@ -169,13 +167,11 @@ Force: Delete and orphan dependents } fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!")) fmt.Printf("To proceed, run: %s\n\n", ui.RenderWarn("bd delete "+issueID+" --force")) - return + return nil } - // Actually delete — all writes in a single transaction updatedIssueCount := 0 totalDepsRemoved := 0 deleteErr := transactHonoringAutoCommit(ctx, activeStore, fmt.Sprintf("bd: delete %s", issueID), func(tx storage.Transaction) error { - // 1. Update text references in connected issues for id, connIssue := range connectedIssues { updates := make(map[string]interface{}) if re.MatchString(connIssue.Description) { @@ -197,43 +193,43 @@ Force: Delete and orphan dependents updatedIssueCount++ } } - // 2. Remove outgoing dependency links for _, dep := range depRecords { if err := tx.RemoveDependency(ctx, dep.IssueID, dep.DependsOnID, actor); err != nil { return fmt.Errorf("remove dependency %s → %s: %w", dep.IssueID, dep.DependsOnID, err) } totalDepsRemoved++ } - // 3. Remove inbound dependency links for _, dep := range dependents { if err := tx.RemoveDependency(ctx, dep.ID, issueID, actor); err != nil { return fmt.Errorf("remove dependency %s → %s: %w", dep.ID, issueID, err) } totalDepsRemoved++ } - // 4. Delete the issue if err := tx.DeleteIssue(ctx, issueID); err != nil { return fmt.Errorf("delete %s: %w", issueID, err) } return nil }) if deleteErr != nil { - FatalError("deleting issue: %v", deleteErr) + return HandleError("deleting issue: %v", deleteErr) } commandDidWrite.Store(true) if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "deleted": issueID, "dependencies_removed": totalDepsRemoved, "references_updated": updatedIssueCount, - }) + }); err != nil { + return err + } } else { fmt.Printf("%s Deleted %s\n", ui.RenderPass("āœ“"), issueID) fmt.Printf(" Removed %d dependency link(s)\n", totalDepsRemoved) fmt.Printf(" Updated text references in %d issue(s)\n", updatedIssueCount) } + return nil }, } @@ -242,18 +238,14 @@ func deleteIssue(ctx context.Context, issueID string) error { return store.DeleteIssue(ctx, issueID) } -// deleteBatch handles deletion of multiple issues -// //nolint:unparam // cmd parameter required for potential future use -func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, cascade bool, jsonOutput bool, _ bool, _ ...string) { - // Ensure we have a direct store +func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, cascade bool, jsonOutput bool, _ bool, _ ...string) error { if store == nil { if err := ensureStoreActive(); err != nil { - FatalError("%v", err) + return err } } ctx := rootCtx - // Verify all issues exist (using routing for prefix resolution) issues := make(map[string]*types.Issue) notFound := []string{} var routedStore storage.DoltStorage @@ -263,7 +255,7 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c if isNotFoundErr(err) { notFound = append(notFound, id) } else { - FatalError("getting issue %s: %v", id, err) + return fmt.Errorf("getting issue %s: %v", id, err) } } else { issues[result.ResolvedID] = result.Issue @@ -278,20 +270,17 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c defer func() { _ = routedStore.Close() }() } if len(notFound) > 0 { - FatalError("issues not found: %s", strings.Join(notFound, ", ")) + return fmt.Errorf("issues not found: %s", strings.Join(notFound, ", ")) } - // Use the routed store if available, otherwise the local store batchStore := store if routedStore != nil { batchStore = routedStore } - // Dry-run or preview mode if dryRun || !force { result, err := batchStore.DeleteIssues(ctx, issueIDs, cascade, false, true) if err != nil { - // Try to show preview even if there are dependency issues showDeletionPreview(issueIDs, issues, cascade, err) - os.Exit(1) + return err } showDeletionPreview(issueIDs, issues, cascade, nil) fmt.Printf("\nWould delete: %d issues\n", result.DeletedCount) @@ -312,16 +301,14 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c ui.RenderWarn("bd delete "+strings.Join(issueIDs, " ")+" --force")) } } - return + return nil } - // Pre-collect connected issues before deletion (so we can update their text references) connectedIssues := make(map[string]*types.Issue) idSet := make(map[string]bool) for _, id := range issueIDs { idSet[id] = true } for _, id := range issueIDs { - // Get dependencies (issues this one depends on) deps, err := batchStore.GetDependencies(ctx, id) if err == nil { for _, dep := range deps { @@ -330,7 +317,6 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c } } } - // Get dependents (issues that depend on this one) dependents, err := batchStore.GetDependents(ctx, id) if err == nil { for _, dep := range dependents { @@ -340,20 +326,17 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c } } } - // Actually delete result, err := batchStore.DeleteIssues(ctx, issueIDs, cascade, force, false) if err != nil { - FatalError("%v", err) + return err } - // Update text references in connected issues (using pre-collected issues) updatedCount := updateTextReferencesInIssues(ctx, issueIDs, connectedIssues) commandDidWrite.Store(true) - // Output results if jsonOutput { - outputJSON(map[string]interface{}{ + if err := outputJSON(map[string]interface{}{ "deleted": issueIDs, "deleted_count": result.DeletedCount, "dependencies_removed": result.DependenciesCount, @@ -361,7 +344,9 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c "events_removed": result.EventsCount, "references_updated": updatedCount, "orphaned_issues": result.OrphanedIssues, - }) + }); err != nil { + return err + } } else { fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("āœ“"), result.DeletedCount) fmt.Printf(" Removed %d dependency link(s)\n", result.DependenciesCount) @@ -373,133 +358,7 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c ui.RenderWarn("⚠"), len(result.OrphanedIssues), strings.Join(result.OrphanedIssues, ", ")) } } -} - -// deleteBatchFallback handles batch deletion for non-SQLite storage (e.g., MemoryStorage in --no-db mode) -// It iterates through issues one by one, deleting each. -func deleteBatchFallback(issueIDs []string, force bool, dryRun bool, cascade bool, jsonOutput bool) { - ctx := rootCtx - - // Cascade not supported in fallback mode - if cascade { - FatalError("--cascade not supported in --no-db mode") - } - - // Verify all issues exist first - issues := make(map[string]*types.Issue) - notFound := []string{} - for _, id := range issueIDs { - issue, err := store.GetIssue(ctx, id) - if err != nil { - if errors.Is(err, storage.ErrNotFound) { - notFound = append(notFound, id) - } else { - FatalError("getting issue %s: %v", id, err) - } - } else { - issues[id] = issue - } - } - if len(notFound) > 0 { - FatalError("issues not found: %s", strings.Join(notFound, ", ")) - } - - // Preview mode - if dryRun || !force { - fmt.Printf("\n%s\n", ui.RenderFail("āš ļø DELETE PREVIEW")) - fmt.Printf("\nIssues to delete (%d):\n", len(issueIDs)) - for _, id := range issueIDs { - if issue := issues[id]; issue != nil { - fmt.Printf(" %s: %s\n", id, issue.Title) - } - } - if dryRun { - fmt.Printf("\n(Dry-run mode - no changes made)\n") - } else { - fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!")) - fmt.Printf("To proceed, run: %s\n", - ui.RenderWarn("bd delete "+strings.Join(issueIDs, " ")+" --force")) - } - return - } - - // Pre-collect connected issues before deletion (for text reference updates) - connectedIssues := make(map[string]*types.Issue) - idSet := make(map[string]bool) - for _, id := range issueIDs { - idSet[id] = true - } - for _, id := range issueIDs { - deps, err := store.GetDependencies(ctx, id) - if err == nil { - for _, dep := range deps { - if !idSet[dep.ID] { - connectedIssues[dep.ID] = dep - } - } - } - dependents, err := store.GetDependents(ctx, id) - if err == nil { - for _, dep := range dependents { - if !idSet[dep.ID] { - connectedIssues[dep.ID] = dep - } - } - } - } - - // Delete each issue - deleteActor := getActorWithGit() - deletedCount := 0 - depsRemoved := 0 - - for _, issueID := range issueIDs { - // Remove dependencies (outgoing) - depRecords, err := store.GetDependencyRecords(ctx, issueID) - if err == nil { - for _, dep := range depRecords { - if err := store.RemoveDependency(ctx, dep.IssueID, dep.DependsOnID, deleteActor); err == nil { - depsRemoved++ - } - } - } - - // Remove dependencies (inbound) - dependents, err := store.GetDependents(ctx, issueID) - if err == nil { - for _, dep := range dependents { - if err := store.RemoveDependency(ctx, dep.ID, issueID, deleteActor); err == nil { - depsRemoved++ - } - } - } - - // Delete the issue - if err := deleteIssue(ctx, issueID); err != nil { - fmt.Fprintf(os.Stderr, "Error deleting issue %s: %v\n", issueID, err) - continue - } - deletedCount++ - } - - // Update text references in connected issues - updatedCount := updateTextReferencesInIssues(ctx, issueIDs, connectedIssues) - - commandDidWrite.Store(true) - - // Output results - if jsonOutput { - outputJSON(map[string]interface{}{ - "deleted": issueIDs, - "deleted_count": deletedCount, - "dependencies_removed": depsRemoved, - "references_updated": updatedCount, - }) - } else { - fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("āœ“"), deletedCount) - fmt.Printf(" Removed %d dependency link(s)\n", depsRemoved) - fmt.Printf(" Updated text references in %d issue(s)\n", updatedCount) - } + return nil } // showDeletionPreview shows what would be deleted diff --git a/cmd/bd/dep.go b/cmd/bd/dep.go index 650164487..ab76ea705 100644 --- a/cmd/bd/dep.go +++ b/cmd/bd/dep.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -124,20 +125,27 @@ This is equivalent to: Examples: bd dep bd-xyz --blocks bd-abc # bd-xyz blocks bd-abc bd dep add bd-abc bd-xyz # Same as above (bd-abc depends on bd-xyz)`, - Args: cobra.MaximumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("dep") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + blocksID, _ := cmd.Flags().GetString("blocks") - // If no args and no flags, show help if len(args) == 0 && blocksID == "" { - _ = cmd.Help() // Help() always returns nil for cobra commands - return + _ = cmd.Help() + return nil } - // If --blocks flag is provided, create a blocking dependency if blocksID != "" { if len(args) != 1 { - FatalErrorRespectJSON("--blocks requires exactly one issue ID argument") + return HandleErrorRespectJSON("--blocks requires exactly one issue ID argument") } blockerID := args[0] @@ -146,7 +154,7 @@ Examples: ctx := rootCtx if usesProxiedServer() { runDepBlocksProxiedServer(cmd, ctx, blockerID, blocksID) - return + return nil } depType := "blocks" @@ -157,22 +165,20 @@ Examples: // against its history (bd-6dnrw.32, GH#3231). fromID, fromStore, fromCleanup, err := resolveIDForMutation(ctx, store, blocksID) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } defer fromCleanup() toID, _, toCleanup, err := resolveIDWithRouting(ctx, store, blockerID) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } defer toCleanup() - // Check for child→parent dependency anti-pattern 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) } - // Direct mode - use the store that owns the dependent issue dep := &types.Dependency{ IssueID: fromID, DependsOnID: toID, @@ -180,10 +186,9 @@ Examples: } if err := fromStore.AddDependency(ctx, dep, actor); err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Check for cycles after adding dependency (skipped with --no-cycle-check) noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check") if !noCycleCheck { warnIfCyclesExist(fromStore) @@ -193,26 +198,25 @@ Examples: Command: "dep add", IssueIDs: []string{fromID, toID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "added", "blocker_id": toID, "blocked_id": fromID, "type": depType, }) - return } fmt.Printf("%s Added dependency: %s blocks %s\n", ui.RenderPass("āœ“"), formatFeedbackIDParen(toID, lookupTitle(toID)), formatFeedbackIDParen(fromID, lookupTitle(fromID))) - return + return nil } - // If we have an arg but no --blocks flag, show help - _ = cmd.Help() // Help() always returns nil for cobra commands + _ = cmd.Help() + return nil }, } @@ -280,21 +284,33 @@ Examples: } return nil }, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("dep add") + + evt := metrics.NewCommandEvent("dep-add") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runDepAddProxiedServer(cmd, rootCtx, args) - return + return nil } + depType, _ := cmd.Flags().GetString("type") file, _ := cmd.Flags().GetString("file") if file != "" { - addBulkDependencies(cmd, file, depType) - return + if err := addBulkDependencies(cmd, file, depType); err != nil { + return HandleErrorRespectJSON("%v", err) + } + return nil } - // Get the dependency target from flag or positional arg blockedBy, _ := cmd.Flags().GetString("blocked-by") dependsOn, _ := cmd.Flags().GetString("depends-on") @@ -309,10 +325,8 @@ Examples: ctx := rootCtx - // Resolve partial IDs with routing support var fromID, toID string - // Check if toID is an external reference (don't resolve it) isExternalRef := strings.HasPrefix(dependsOnArg, "external:") // Write-intent: the source issue's store is mutated by AddDependency @@ -321,49 +335,40 @@ Examples: // never open a foreign project writable (bd-6dnrw.32, GH#3231). fromID, fromStore, fromCleanup, err := resolveIDForMutation(ctx, store, args[0]) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } defer fromCleanup() if isExternalRef { - // External references are stored as-is toID = dependsOnArg - // Validate format: external:: if err := validateExternalRef(toID); err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } } else { var toCleanup func() toID, _, toCleanup, err = resolveIDWithRouting(ctx, store, dependsOnArg) if err != nil { - // Cross-prefix deps: if the target has a different prefix than - // the source, skip resolution and pass the raw ID through. - // The storage layer's isCrossPrefixDep() handles this correctly. srcPrefix := types.ExtractPrefix(fromID) tgtPrefix := types.ExtractPrefix(dependsOnArg) if srcPrefix != "" && tgtPrefix != "" && srcPrefix != tgtPrefix { toID = dependsOnArg } else { - FatalErrorRespectJSON("resolving dependency ID %s: %v", dependsOnArg, err) + return HandleErrorRespectJSON("resolving dependency ID %s: %v", dependsOnArg, err) } } else { defer toCleanup() } } - // Check for child→parent dependency anti-pattern - // This creates a deadlock: child can't start (parent open), parent can't close (children not done) 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) } - // Validate dependency type 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) } - // Direct mode - use the store that owns the dependent issue dep := &types.Dependency{ IssueID: fromID, DependsOnID: toID, @@ -371,10 +376,9 @@ Examples: } if err := fromStore.AddDependency(ctx, dep, actor); err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Check for cycles after adding dependency (skipped with --no-cycle-check) noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check") if !noCycleCheck { warnIfCyclesExist(fromStore) @@ -384,21 +388,21 @@ Examples: Command: "dep add", IssueIDs: []string{fromID, toID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "added", "issue_id": fromID, "depends_on_id": toID, "type": depType, }) - return } fmt.Printf("%s Added dependency: %s depends on %s (%s)\n", ui.RenderPass("āœ“"), formatFeedbackIDParen(fromID, lookupTitle(fromID)), formatFeedbackIDParen(toID, lookupTitle(toID)), depType) + return nil }, } @@ -442,15 +446,15 @@ type bulkDepEdge struct { Cleanups []func() } -func addBulkDependencies(cmd *cobra.Command, file string, defaultType string) { +func addBulkDependencies(cmd *cobra.Command, file string, defaultType string) error { edges, err := readBulkDepEdges(file, defaultType) if err != nil { - FatalErrorRespectJSON("%v", err) + return err } resolved, err := validateBulkDepEdges(rootCtx, edges) if err != nil { - FatalErrorRespectJSON("%v", err) + return err } defer func() { for _, edge := range resolved { @@ -461,13 +465,13 @@ func addBulkDependencies(cmd *cobra.Command, file string, defaultType string) { }() if len(resolved) == 0 { - FatalErrorRespectJSON("no dependency edges found") + return fmt.Errorf("no dependency edges found") } targetStore := resolved[0].Store targetStoreKey := resolved[0].StoreKey for _, edge := range resolved[1:] { if edge.StoreKey != targetStoreKey { - FatalErrorRespectJSON("bulk dep add requires all source issues to resolve to the same store") + return fmt.Errorf("bulk dep add requires all source issues to resolve to the same store") } } @@ -501,7 +505,7 @@ func addBulkDependencies(cmd *cobra.Command, file string, defaultType string) { } return nil }); err != nil { - FatalErrorRespectJSON("%v", err) + return err } if !noCycleCheck { @@ -517,15 +521,15 @@ func addBulkDependencies(cmd *cobra.Command, file string, defaultType string) { "type": string(edge.Type), }) } - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "added", "count": len(resolved), "dependencies": out, }) - return } fmt.Printf("%s Added %d dependencies\n", ui.RenderPass("āœ“"), len(resolved)) + return nil } func readBulkDepEdges(file string, defaultType string) ([]bulkDepEdge, error) { @@ -703,12 +707,22 @@ Examples: bd dep list gt-abc gt-def # Batch: deps for both issues bd dep list gt-abc --direction=up # Show what depends on gt-abc bd dep list gt-abc --direction=up -t tracks # Show what tracks gt-abc (convoy tracking)`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("dep-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runDepListProxiedServer(cmd, rootCtx, args) - return + return nil } + ctx := rootCtx direction, _ := cmd.Flags().GetString("direction") typeFilter, _ := cmd.Flags().GetString("type") @@ -716,12 +730,6 @@ Examples: direction = "down" } - // Resolve all IDs and group by store. - // In batch mode (>1 arg), unresolved IDs are skipped with a stderr - // warning so a single bad ID does not abort the whole batch — this - // is the ZFC-compliant transport behavior callers like the gascity - // supervisor's dep-cache refresh expect. Single-arg mode keeps the - // fatal behavior for backward compatibility. type resolvedID struct { fullID string store storage.DoltStorage @@ -736,14 +744,14 @@ Examples: fmt.Fprintf(os.Stderr, "warning: resolving %s: %v (skipped)\n", arg, err) continue } - FatalErrorRespectJSON("resolving %s: %v", arg, err) + return HandleErrorRespectJSON("resolving %s: %v", arg, err) } if routedResult == nil || routedResult.Issue == nil { if batchMode { fmt.Fprintf(os.Stderr, "warning: no issue found: %s (skipped)\n", arg) continue } - FatalErrorRespectJSON("no issue found: %s", arg) + return HandleErrorRespectJSON("no issue found: %s", arg) } depStore := store if routedResult.Routed && routedResult.Store != nil { @@ -756,14 +764,11 @@ Examples: }) } if batchMode && len(resolved) == 0 { - // No IDs resolved at all; emit empty result so callers can parse - // JSON cleanly without a special error path. if jsonOutput { - outputJSON([]*types.Dependency{}) - return + return outputJSON([]*types.Dependency{}) } fmt.Fprintln(os.Stderr, "no resolvable issues in batch") - return + return nil } defer func() { for _, r := range resolved { @@ -773,8 +778,6 @@ Examples: } }() - // Batch path: if all IDs route to the same store and direction - // is "down", use GetDependencyRecordsForIssues for one query. if len(resolved) > 1 && direction == "down" { allSameStore := true firstStore := resolved[0].store @@ -791,7 +794,6 @@ Examples: } depMap, err := firstStore.GetDependencyRecordsForIssues(ctx, ids) if err == nil { - // Flatten and filter. var allDeps []*types.Dependency for _, id := range ids { for _, dep := range depMap[id] { @@ -804,10 +806,8 @@ Examples: if allDeps == nil { allDeps = []*types.Dependency{} } - outputJSON(allDeps) - return + return outputJSON(allDeps) } - // Human-readable output grouped by issue. for _, id := range ids { deps := depMap[id] if len(deps) == 0 { @@ -823,13 +823,11 @@ Examples: } } fmt.Println() - return + return nil } - // Fall through to per-ID path on error. } } - // Per-ID path (single ID or mixed stores or "up" direction). var allIssues []*types.IssueWithDependencyMetadata for _, r := range resolved { var issues []*types.IssueWithDependencyMetadata @@ -840,7 +838,7 @@ Examples: issues, err = r.store.GetDependenciesWithMetadata(ctx, r.fullID) } if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } if typeFilter != "" { var filtered []*types.IssueWithDependencyMetadata @@ -858,8 +856,7 @@ Examples: if allIssues == nil { allIssues = []*types.IssueWithDependencyMetadata{} } - outputJSON(allIssues) - return + return outputJSON(allIssues) } if len(allIssues) == 0 { @@ -872,7 +869,7 @@ Examples: } else { fmt.Println("\nNo dependencies found") } - return + return nil } for _, iss := range allIssues { @@ -893,20 +890,32 @@ Examples: idStr, iss.Title, iss.Priority, iss.Status, iss.DependencyType) } fmt.Println() + return nil }, } var depRemoveCmd = &cobra.Command{ - Use: "remove [issue-id] [depends-on-id]", - Aliases: []string{"rm"}, - Short: "Remove a dependency", - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Use: "remove [issue-id] [depends-on-id]", + Aliases: []string{"rm"}, + Short: "Remove a dependency", + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("dep remove") + + evt := metrics.NewCommandEvent("dep-remove") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runDepRemoveProxiedServer(cmd, rootCtx, args) - return + return nil } + ctx := rootCtx // Resolve partial IDs with routing support. The source issue's store is @@ -916,62 +925,58 @@ var depRemoveCmd = &cobra.Command{ var fromID, toID string fromID, fromStore, fromCleanup, err := resolveIDForMutation(ctx, store, args[0]) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } defer fromCleanup() - // Check if toID is an external reference (don't resolve it) isExternalRef := strings.HasPrefix(args[1], "external:") if isExternalRef { toID = args[1] if err := validateExternalRef(toID); err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } } else { var toCleanup func() toID, _, toCleanup, err = resolveIDWithRouting(ctx, store, args[1]) if err != nil { - // Cross-prefix deps: if the target has a different prefix than - // the source, skip resolution and pass the raw ID through. srcPrefix := types.ExtractPrefix(fromID) tgtPrefix := types.ExtractPrefix(args[1]) if srcPrefix != "" && tgtPrefix != "" && srcPrefix != tgtPrefix { toID = args[1] } else { - FatalErrorRespectJSON("resolving dependency ID %s: %v", args[1], err) + return HandleErrorRespectJSON("resolving dependency ID %s: %v", args[1], err) } } else { defer toCleanup() } } - // Direct mode - use the store that owns the dependent issue fullFromID := fromID fullToID := toID if err := fromStore.RemoveDependency(ctx, fullFromID, fullToID, actor); err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } if err := commitPendingIfEmbedded(ctx, fromStore, actor, doltAutoCommitParams{ Command: "dep remove", IssueIDs: []string{fullFromID, fullToID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "removed", "issue_id": fullFromID, "depends_on_id": fullToID, }) - return } fmt.Printf("%s Removed dependency: %s no longer depends on %s\n", ui.RenderPass("āœ“"), formatFeedbackIDParen(fullFromID, lookupTitle(fullFromID)), formatFeedbackIDParen(fullToID, lookupTitle(fullToID))) + return nil }, } @@ -990,18 +995,27 @@ Examples: bd dep tree gt-0iqq --direction=up # Show what gt-0iqq blocks bd dep tree gt-0iqq --status=open # Only show open issues bd dep tree gt-0iqq --depth=3 # Limit to 3 levels deep`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("dep-tree") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runDepTreeProxiedServer(cmd, rootCtx, args) - return + return nil } + ctx := rootCtx - // Resolve partial ID with routing support fullID, treeStore, treeCleanup, err := resolveIDWithRouting(ctx, store, args[0]) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } defer treeCleanup() @@ -1011,75 +1025,60 @@ Examples: direction, _ := cmd.Flags().GetString("direction") statusFilter, _ := cmd.Flags().GetString("status") formatStr, _ := cmd.Flags().GetString("format") - // Handle --format json: the local --format flag shadows the hidden - // persistent --format on rootCmd, so "json" arrives here instead of - // setting jsonOutput via PersistentPreRun. Route it explicitly. if strings.EqualFold(formatStr, "json") { jsonOutput = true formatStr = "" } - // Handle --direction flag (takes precedence over deprecated --reverse) if direction == "" && reverse { direction = "up" } else if direction == "" { direction = "down" } - // Validate direction 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") } - // For "both" direction, we need to fetch both trees and merge them var tree []*types.TreeNode if direction == "both" { - // Get dependencies (down) - what blocks this issue downTree, err := treeStore.GetDependencyTree(ctx, fullID, maxDepth, showAllPaths, false) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Get dependents (up) - what this issue blocks upTree, err := treeStore.GetDependencyTree(ctx, fullID, maxDepth, showAllPaths, true) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Merge: root appears once, dependencies below, dependents above - // We'll show dependents first (with negative-like positioning conceptually), - // then root, then dependencies tree = mergeBidirectionalTrees(downTree, upTree, fullID) } else { tree, err = treeStore.GetDependencyTree(ctx, fullID, maxDepth, showAllPaths, direction == "up") if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } } - // Apply status filter if specified if statusFilter != "" { tree = filterTreeByStatus(tree, types.Status(statusFilter)) } - // Handle format presets (json handled earlier, near flag read) if formatStr == "mermaid" { outputMermaidTree(tree, args[0]) - return + return nil } if jsonOutput { - // Always output array, even if empty if tree == nil { tree = []*types.TreeNode{} } - outputJSON(tree) - return + return outputJSON(tree) } if len(tree) == 0 { @@ -1091,7 +1090,7 @@ Examples: default: fmt.Printf("\n%s has no dependencies\n", fullID) } - return + return nil } switch direction { @@ -1103,39 +1102,46 @@ Examples: fmt.Printf("\n%s Dependency tree for %s:\n\n", ui.RenderAccent("🌲"), fullID) } - // Render tree with proper connectors renderTree(tree, maxDepth, direction) fmt.Println() + return nil }, } var depCyclesCmd = &cobra.Command{ - Use: "cycles", - Short: "Detect dependency cycles", - Run: func(cmd *cobra.Command, args []string) { + Use: "cycles", + Short: "Detect dependency cycles", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("dep-cycles") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runDepCyclesProxiedServer(cmd, rootCtx) - return + return nil } ctx := rootCtx cycles, err := store.DetectCycles(ctx) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { - // Always output array, even if empty if cycles == nil { cycles = [][]*types.Issue{} } - outputJSON(cycles) - return + return outputJSON(cycles) } 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)) @@ -1146,6 +1152,7 @@ var depCyclesCmd = &cobra.Command{ } fmt.Println() } + return nil }, } diff --git a/cmd/bd/diff.go b/cmd/bd/diff.go index f951f5980..3211c5be2 100644 --- a/cmd/bd/diff.go +++ b/cmd/bd/diff.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/ui" ) @@ -23,26 +24,33 @@ Examples: bd diff main feature-branch # Compare main to feature branch bd diff HEAD~5 HEAD # Show changes in last 5 commits bd diff abc123 def456 # Compare two specific commits`, - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("diff") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx fromRef := args[0] toRef := args[1] - // Get diff between refs entries, err := store.Diff(ctx, fromRef, toRef) if err != nil { - FatalErrorRespectJSON("failed to get diff: %v", err) + return HandleErrorRespectJSON("failed to get diff: %v", err) } if len(entries) == 0 { fmt.Printf("No changes between %s and %s\n", fromRef, toRef) - return + return nil } if jsonOutput { - outputJSON(entries) - return + return outputJSON(entries) } // Display diff in human-readable format @@ -111,7 +119,6 @@ Examples: fmt.Println() } - // Display removed issues if len(removed) > 0 { fmt.Printf("%s Removed (%d):\n", ui.RenderAccent("-"), len(removed)) for _, entry := range removed { @@ -125,6 +132,7 @@ Examples: } fmt.Println() } + return nil }, } diff --git a/cmd/bd/doctor.go b/cmd/bd/doctor.go index d2c3cde8d..39b70af89 100644 --- a/cmd/bd/doctor.go +++ b/cmd/bd/doctor.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/cmd/bd/doctor" "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -183,7 +184,16 @@ Examples: bd doctor --migration=pre # Validate readiness for Dolt migration bd doctor --migration=post # Validate Dolt migration completed bd doctor --migration=pre --json # Machine-parseable migration validation`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("doctor") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if !usesSQLServer() { fmt.Fprintln(os.Stderr, "Note: 'bd doctor' is not yet supported in embedded mode.") fmt.Fprintln(os.Stderr, "") @@ -192,98 +202,74 @@ Examples: fmt.Fprintln(os.Stderr, " • Check bd version: bd version") fmt.Fprintln(os.Stderr, " • Reinitialize if needed: bd init --force") fmt.Fprintln(os.Stderr, " • Switch to server mode: bd init --server") - os.Exit(0) + return nil } if usesProxiedServer() { fmt.Fprintln(os.Stderr, "Note: 'bd doctor' is not yet supported in proxied-server mode.") - os.Exit(0) + return nil } - // Use global jsonOutput set by PersistentPreRun - // Determine path to check - // Precedence: explicit arg > BEADS_DIR (parent) > CWD var checkPath string if len(args) > 0 { checkPath = args[0] } else if beadsDir := os.Getenv("BEADS_DIR"); beadsDir != "" { - // BEADS_DIR points to .beads directory, doctor needs parent checkPath = filepath.Dir(beadsDir) } else { checkPath = "." } - // Convert to absolute path absPath, err := filepath.Abs(checkPath) if err != nil { - FatalError("failed to resolve path: %v", err) + return HandleError("failed to resolve path: %v", err) } - // Guardrail: never run mutating bd doctor fix from orchestrator workspace root. - // Workspace roots have additional invariants beyond single-project repos; - // repairs should go through the orchestrator's own doctor command. if doctorFix && isOrchestratorRoot(absPath) { - FatalErrorWithHint( + return HandleErrorWithHint( "refusing to run 'bd doctor --fix' at orchestrator workspace root", "Run the orchestrator's doctor command from workspace root, or run 'bd doctor --fix' inside a specific project clone", ) } - // Run performance diagnostics if --perf flag is set if perfMode { if err := doctor.RunPerformanceDiagnostics(absPath); err != nil { - FatalError("performance diagnostics: %v", err) + return HandleError("performance diagnostics: %v", err) } - return + return nil } - // Run quick health check if --check-health flag is set if checkHealthMode { - runCheckHealth(absPath) - return + return runCheckHealth(absPath) } - // Run specific check if --check flag is set if doctorCheckFlag != "" { switch doctorCheckFlag { case "pollution": - runPollutionCheck(absPath, doctorClean, doctorYes) - return + return runPollutionCheck(absPath, doctorClean, doctorYes) case "validate": - runValidateCheck(absPath) - return + return runValidateCheck(absPath) case "artifacts": - runArtifactsCheck(absPath, doctorClean, doctorYes) - return + return runArtifactsCheck(absPath, doctorClean, doctorYes) case "conventions": - runConventionsCheck(absPath) - return + return runConventionsCheck(absPath) default: - FatalErrorWithHint(fmt.Sprintf("unknown check %q", doctorCheckFlag), "Available checks: artifacts, conventions, pollution, validate") + return HandleErrorWithHint(fmt.Sprintf("unknown check %q", doctorCheckFlag), "Available checks: artifacts, conventions, pollution, validate") } } - // Run deep validation if --deep flag is set if doctorDeep { - runDeepValidation(absPath) - return + return runDeepValidation(absPath) } - // Run server mode health checks if --server flag is set if doctorServer { - runServerHealth(absPath) - return + return runServerHealth(absPath) } - // Run migration validation if --migration flag is set if doctorMigration != "" { - runMigrationValidation(absPath, doctorMigration) - return + return runMigrationValidation(absPath, doctorMigration) } - // Run diagnostics result := runDiagnostics(absPath) - // Preview fixes (dry-run) or apply fixes if requested if doctorDryRun { previewFixes(result) } else if doctorFix { @@ -292,39 +278,39 @@ Examples: result = runDiagnostics(absPath) } - // Add timestamp and platform info for export if doctorOutput != "" || jsonOutput { result.Timestamp = time.Now().UTC().Format(time.RFC3339) result.Platform = doctor.CollectPlatformInfo(absPath) } - // Export to file if --output specified if doctorOutput != "" { if err := exportDiagnostics(result, doctorOutput); err != nil { - FatalError("failed to export diagnostics: %v", err) + return HandleError("failed to export diagnostics: %v", err) } fmt.Printf("āœ“ Diagnostics exported to %s\n", doctorOutput) } - // Output results if doctorAgent { agentResult := buildAgentResult(result) if jsonOutput { - outputJSON(agentResult) + if err := outputJSON(agentResult); err != nil { + return err + } } else { printAgentDiagnostics(agentResult) } } else if jsonOutput { - outputJSON(result) + if err := outputJSON(result); err != nil { + return err + } } else if doctorOutput == "" { - // Only print to console if not exporting (to avoid duplicate output) printDiagnostics(result) } - // Exit with error if any checks failed if !result.OverallOK { - os.Exit(1) + return SilentExit() } + return nil }, } @@ -1196,7 +1182,7 @@ func printAllChecks(checksByCategory map[string][]doctorCheck) { // runMigrationValidation runs Dolt migration validation checks. // Phase can be "pre" (before migration) or "post" (after migration). // Outputs machine-parseable JSON when --json flag is set. -func runMigrationValidation(path string, phase string) { +func runMigrationValidation(path string, phase string) error { var check doctorCheck var result doctor.MigrationValidationResult @@ -1210,10 +1196,9 @@ func runMigrationValidation(path string, phase string) { check = convertDoctorCheck(dc) result = mr default: - FatalError("invalid migration phase %q (use 'pre' or 'post')", phase) + return HandleError("invalid migration phase %q (use 'pre' or 'post')", phase) } - // JSON output for machine consumption if jsonOutput { output := struct { Check doctorCheck `json:"check"` @@ -1226,11 +1211,13 @@ func runMigrationValidation(path string, phase string) { CLIVersion: Version, Timestamp: time.Now().UTC().Format(time.RFC3339), } - outputJSON(output) - if !result.Ready { - os.Exit(1) + if err := outputJSON(output); err != nil { + return err } - return + if !result.Ready { + return SilentExit() + } + return nil } // Human-readable output @@ -1297,8 +1284,8 @@ func runMigrationValidation(path string, phase string) { fmt.Println() if result.Ready { fmt.Printf("%s\n", ui.RenderPass("āœ“ Migration validation passed")) - } else { - fmt.Printf("%s\n", ui.RenderFail("āœ— Migration validation failed")) - os.Exit(1) + return nil } + fmt.Printf("%s\n", ui.RenderFail("āœ— Migration validation failed")) + return SilentExit() } diff --git a/cmd/bd/doctor_artifacts.go b/cmd/bd/doctor_artifacts.go index d42a9331b..0252fbd14 100644 --- a/cmd/bd/doctor_artifacts.go +++ b/cmd/bd/doctor_artifacts.go @@ -11,36 +11,31 @@ import ( // runArtifactsCheck runs detailed classic artifact detection. // With --clean, removes safe-to-delete artifacts after confirmation. -func runArtifactsCheck(path string, clean bool, yes bool) { +func runArtifactsCheck(path string, clean bool, yes bool) error { report, err := doctor.ScanForArtifacts(path) if err != nil { - FatalError("scanning artifacts: %v", err) + return HandleError("scanning artifacts: %v", err) } if report.TotalCount == 0 { - if !jsonOutput { - fmt.Println("No classic artifacts detected.") - } else { - outputJSON(map[string]interface{}{ + if jsonOutput { + return outputJSON(map[string]interface{}{ "total_count": 0, }) } - return + fmt.Println("No classic artifacts detected.") + return nil } if jsonOutput { - // GH#2438: When --clean is also set, perform cleanup before outputting - // JSON. Previously, --json returned early and skipped the clean logic, - // so `bd doctor --check=artifacts --clean --json` would report findings - // but never delete them. + // GH#2438: When --clean is also set, perform cleanup before outputting JSON. if clean && report.SafeDeleteCount > 0 { if err := fix.ClassicArtifacts(path); err != nil { - FatalError("during cleanup: %v", err) + return HandleError("during cleanup: %v", err) } - // Re-scan to show post-cleanup state report, err = doctor.ScanForArtifacts(path) if err != nil { - FatalError("re-scanning artifacts: %v", err) + return HandleError("re-scanning artifacts: %v", err) } } @@ -67,8 +62,7 @@ func runArtifactsCheck(path string, clean bool, yes bool) { } } result["findings"] = findings - outputJSON(result) - return + return outputJSON(result) } // Human-readable output @@ -111,27 +105,26 @@ func runArtifactsCheck(path string, clean bool, yes bool) { if !clean { fmt.Println("Run 'bd doctor --check=artifacts --clean' to remove safe-to-delete artifacts.") - return + return nil } if report.SafeDeleteCount == 0 { fmt.Println("No artifacts are safe to auto-delete. Manual review required.") - return + return nil } - // Confirmation prompt if !yes { fmt.Printf("Delete %d safe-to-delete artifact(s)? [y/N] ", report.SafeDeleteCount) var response string _, _ = fmt.Scanln(&response) if strings.ToLower(response) != "y" { fmt.Println("Canceled.") - return + return nil } } - // Perform cleanup if err := fix.ClassicArtifacts(path); err != nil { - FatalError("during cleanup: %v", err) + return HandleError("during cleanup: %v", err) } + return nil } diff --git a/cmd/bd/doctor_context_test.go b/cmd/bd/doctor_context_test.go index ca4bc389e..4d42b8e68 100644 --- a/cmd/bd/doctor_context_test.go +++ b/cmd/bd/doctor_context_test.go @@ -70,10 +70,12 @@ func TestDoctorPersistentPreRunLoadsServerModeForNoDBCommand(t *testing.T) { t.Cleanup(config.ResetForTesting) savePersistentPreRunState(t) - if rootCmd.PersistentPreRun == nil { - t.Fatal("rootCmd.PersistentPreRun must be set") + if rootCmd.PersistentPreRunE == nil { + t.Fatal("rootCmd.PersistentPreRunE must be set") + } + if err := rootCmd.PersistentPreRunE(doctorCmd, nil); err != nil { + t.Fatalf("PersistentPreRunE: %v", err) } - rootCmd.PersistentPreRun(doctorCmd, nil) if !serverMode { t.Fatal("doctor should load server mode before the no-store early return") @@ -107,7 +109,9 @@ func TestDoctorPersistentPreRunUsesExplicitDBTarget(t *testing.T) { flag.Changed = true } - rootCmd.PersistentPreRun(doctorCmd, nil) + if err := rootCmd.PersistentPreRunE(doctorCmd, nil); err != nil { + t.Fatalf("PersistentPreRunE: %v", err) + } if got := os.Getenv("BEADS_DIR"); got != targetBeadsDir { t.Fatalf("BEADS_DIR = %q, want %q", got, targetBeadsDir) @@ -144,7 +148,9 @@ func TestBootstrapPersistentPreRunUsesExplicitDBTarget(t *testing.T) { flag.Changed = true } - rootCmd.PersistentPreRun(bootstrapCmd, nil) + if err := rootCmd.PersistentPreRunE(bootstrapCmd, nil); err != nil { + t.Fatalf("PersistentPreRunE: %v", err) + } if got := os.Getenv("BEADS_DIR"); got != targetBeadsDir { t.Fatalf("BEADS_DIR = %q, want %q", got, targetBeadsDir) diff --git a/cmd/bd/doctor_conventions.go b/cmd/bd/doctor_conventions.go index 48e50b0ff..e7b29c05e 100644 --- a/cmd/bd/doctor_conventions.go +++ b/cmd/bd/doctor_conventions.go @@ -10,7 +10,7 @@ import ( // runConventionsCheck runs a composite conventions check: lint, stale, and orphans. // All findings are advisory (warning, never error) - conventions are a choice. -func runConventionsCheck(path string) { +func runConventionsCheck(path string) error { var checks []doctorCheck checks = append(checks, runConventionsLint()...) @@ -25,7 +25,7 @@ func runConventionsCheck(path string) { break } } - outputJSON(struct { + return outputJSON(struct { Path string `json:"path"` Checks []doctorCheck `json:"checks"` OverallOK bool `json:"overall_ok"` @@ -34,7 +34,6 @@ func runConventionsCheck(path string) { Checks: checks, OverallOK: overallOK, }) - return } // Human-readable output @@ -77,6 +76,7 @@ func runConventionsCheck(path string) { fmt.Println() fmt.Printf("%s\n", ui.RenderPass("āœ“ All convention checks passed")) } + return nil } // runConventionsLint checks open issues for missing template sections. diff --git a/cmd/bd/doctor_health.go b/cmd/bd/doctor_health.go index c84ea544c..9fad573c1 100644 --- a/cmd/bd/doctor_health.go +++ b/cmd/bd/doctor_health.go @@ -18,36 +18,28 @@ import ( // runCheckHealth runs lightweight health checks for git hooks. // Silent on success, prints a hint if issues detected. // Respects hints.doctor config setting. -func runCheckHealth(path string) { +func runCheckHealth(path string) error { beadsDir := doctor.ResolveBeadsDirForRepo(path) - // Check if .beads/ exists if _, err := os.Stat(beadsDir); os.IsNotExist(err) { - // No .beads directory - nothing to check - return + return nil } - // Load config for Dolt server connection info cfg, err := configfile.Load(beadsDir) if err != nil || cfg == nil { - // Can't load config - only check hooks if issue := doctor.CheckHooksQuick(Version); issue != "" { - printCheckHealthHint([]string{issue}) + return printCheckHealthHint([]string{issue}) } - return + return nil } - // Try connecting to Dolt server for config/version checks. - // Use doltserver.DefaultConfig for port resolution — GetDoltServerPort - // falls back to 3307 which is wrong for ephemeral ports. host := cfg.GetDoltServerHost() port := doltserver.DefaultConfig(beadsDir).Port if port == 0 { - // No server running yet — skip DB checks, only check hooks. if issue := doctor.CheckHooksQuick(Version); issue != "" { - printCheckHealthHint([]string{issue}) + return printCheckHealthHint([]string{issue}) } - return + return nil } database := cfg.GetDoltDatabase() @@ -65,35 +57,28 @@ func runCheckHealth(path string) { db, err := sql.Open("mysql", dsn) if err == nil { defer db.Close() - // Quick ping to verify server is reachable if pingErr := db.Ping(); pingErr == nil { - // Check if hints.doctor is disabled in config if hintsDisabledDB(db) { - return + return nil } - // Check version mismatch if issue := checkVersionMismatchDB(db); issue != "" { issues = append(issues, issue) } } - // If ping fails, server not running — skip DB checks silently } - // Check outdated git hooks if issue := doctor.CheckHooksQuick(Version); issue != "" { issues = append(issues, issue) } - // If any issues found, print hint if len(issues) > 0 { - printCheckHealthHint(issues) + return printCheckHealthHint(issues) } - // Silent exit on success + return nil } // runDeepValidation runs full graph integrity validation -func runDeepValidation(path string) { - // Show warning about potential slowness +func runDeepValidation(path string) error { fmt.Println("Running deep validation (may be slow on large databases)...") fmt.Println() @@ -102,7 +87,7 @@ func runDeepValidation(path string) { if jsonOutput { jsonBytes, err := doctor.DeepValidationResultJSON(result) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } fmt.Println(string(jsonBytes)) } else { @@ -110,18 +95,19 @@ func runDeepValidation(path string) { } if !result.OverallOK { - os.Exit(1) + return SilentExit() } + return nil } // runServerHealth runs Dolt server mode health checks -func runServerHealth(path string) { +func runServerHealth(path string) error { result := doctor.RunServerHealthChecks(path) if jsonOutput { jsonBytes, err := json.Marshal(result) if err != nil { - FatalError("failed to marshal health check result: %v", err) + return HandleError("failed to marshal health check result: %v", err) } fmt.Println(string(jsonBytes)) } else { @@ -131,8 +117,9 @@ func runServerHealth(path string) { } if !result.OverallOK { - os.Exit(1) + return SilentExit() } + return nil } // printServerHealthResult prints the server health check results @@ -203,15 +190,14 @@ func printServerHealthResult(result doctor.ServerHealthResult) { } } -// printCheckHealthHint prints the health check hint and exits with error. -func printCheckHealthHint(issues []string) { +func printCheckHealthHint(issues []string) error { fmt.Fprintf(os.Stderr, "šŸ’” bd doctor recommends a health check:\n") for _, issue := range issues { fmt.Fprintf(os.Stderr, " • %s\n", issue) } fmt.Fprintf(os.Stderr, " Run 'bd doctor' for details, or 'bd doctor --fix' to auto-repair\n") fmt.Fprintf(os.Stderr, " (Suppress with: bd config set %s false)\n", ConfigKeyHintsDoctor) - os.Exit(1) + return SilentExit() } // hintsDisabledDB checks if hints.doctor is set to "false" using an existing DB connection. diff --git a/cmd/bd/doctor_pollution.go b/cmd/bd/doctor_pollution.go index a237b972c..e6b2f9776 100644 --- a/cmd/bd/doctor_pollution.go +++ b/cmd/bd/doctor_pollution.go @@ -13,33 +13,29 @@ import ( // This integrates the detect-pollution command functionality into doctor. // //nolint:unparam // path reserved for future use -func runPollutionCheck(_ string, clean bool, yes bool) { - // Ensure we have a store initialized +func runPollutionCheck(_ string, clean bool, yes bool) error { if err := ensureDirectMode("pollution check requires direct mode"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } ctx := rootCtx - // Get all issues allIssues, err := store.SearchIssues(ctx, "", types.IssueFilter{}) if err != nil { - FatalError("fetching issues: %v", err) + return HandleError("fetching issues: %v", err) } - // Detect pollution (reuse detectTestPollution from detect_pollution.go) polluted := detectTestPollution(allIssues) if len(polluted) == 0 { - if !jsonOutput { - fmt.Println("No test pollution detected!") - } else { - outputJSON(map[string]interface{}{ + if jsonOutput { + return outputJSON(map[string]interface{}{ "polluted_count": 0, "issues": []interface{}{}, }) } - return + fmt.Println("No test pollution detected!") + return nil } // Categorize by confidence @@ -72,8 +68,7 @@ func runPollutionCheck(_ string, clean bool, yes bool) { }) } - outputJSON(result) - return + return outputJSON(result) } // Human-readable output @@ -103,28 +98,25 @@ func runPollutionCheck(_ string, clean bool, yes bool) { if !clean { fmt.Printf("Run 'bd doctor --check=pollution --clean' to delete these issues (with confirmation).\n") - return + return nil } - // Confirmation prompt if !yes { fmt.Printf("\nDelete %d test issues? [y/N] ", len(polluted)) var response string _, _ = fmt.Scanln(&response) if strings.ToLower(response) != "y" { fmt.Println("Canceled.") - return + return nil } } - // Backup to JSONL before deleting backupPath := ".beads/pollution-backup.jsonl" if err := backupPollutedIssues(polluted, backupPath); err != nil { - FatalError("backing up issues: %v", err) + return HandleError("backing up issues: %v", err) } fmt.Printf("Backed up %d issues to %s\n", len(polluted), backupPath) - // Delete issues fmt.Printf("\nDeleting %d issues...\n", len(polluted)) deleted := 0 for _, p := range polluted { @@ -137,6 +129,7 @@ func runPollutionCheck(_ string, clean bool, yes bool) { fmt.Printf("%s Deleted %d test issues\n", ui.RenderPass("āœ“"), deleted) fmt.Printf("\nCleanup complete. To restore, run: bd init --from-jsonl %s\n", backupPath) + return nil } func init() { diff --git a/cmd/bd/doctor_validate.go b/cmd/bd/doctor_validate.go index c0b5060ed..2a5e8c694 100644 --- a/cmd/bd/doctor_validate.go +++ b/cmd/bd/doctor_validate.go @@ -11,22 +11,23 @@ import ( "golang.org/x/term" ) -// validateCheckResult pairs a doctor check with whether it can be auto-fixed. type validateCheckResult struct { check doctorCheck fixable bool } -// runValidateCheck runs focused data-integrity checks and exits non-zero on failure. -func runValidateCheck(path string) { - if !runValidateCheckInner(path) { - os.Exit(1) +func runValidateCheck(path string) error { + ok, err := runValidateCheckInner(path) + if err != nil { + return err } + if !ok { + return SilentExit() + } + return nil } -// runValidateCheckInner runs the checks and returns true if all passed. -// Separated from runValidateCheck so tests can call it without os.Exit. -func runValidateCheckInner(path string) bool { +func runValidateCheckInner(path string) (bool, error) { checks := collectValidateChecks(path) // Apply fixes if --fix is set, then re-check to reflect post-fix state @@ -50,8 +51,10 @@ func runValidateCheckInner(path string) bool { for _, cr := range checks { result.Checks = append(result.Checks, cr.check) } - outputJSON(result) - return overallOK + if err := outputJSON(result); err != nil { + return overallOK, err + } + return overallOK, nil } // Human-readable output @@ -72,7 +75,7 @@ func runValidateCheckInner(path string) bool { fmt.Printf("%s\n", ui.RenderPass("āœ“ All data-integrity checks passed")) } - return overallOK + return overallOK, nil } // collectValidateChecks runs the data-integrity checks. diff --git a/cmd/bd/duplicate.go b/cmd/bd/duplicate.go index 5b12a2978..c96b1ff46 100644 --- a/cmd/bd/duplicate.go +++ b/cmd/bd/duplicate.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -59,6 +60,13 @@ func init() { func runDuplicate(cmd *cobra.Command, args []string) error { CheckReadonly("duplicate") + evt := metrics.NewCommandEvent("duplicate") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := getRootContext() store := getStore() actor := getActor() @@ -108,12 +116,11 @@ func runDuplicate(cmd *cobra.Command, args []string) error { commandDidWrite.Store(true) if isJSONOutput() { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "duplicate": duplicateID, "canonical": canonicalID, "status": "closed", }) - return nil } fmt.Printf("%s Marked %s as duplicate of %s (closed)\n", ui.RenderPass("āœ“"), duplicateID, canonicalID) @@ -123,6 +130,13 @@ func runDuplicate(cmd *cobra.Command, args []string) error { func runSupersede(cmd *cobra.Command, args []string) error { CheckReadonly("supersede") + evt := metrics.NewCommandEvent("supersede") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := getRootContext() store := getStore() actor := getActor() @@ -172,12 +186,11 @@ func runSupersede(cmd *cobra.Command, args []string) error { commandDidWrite.Store(true) if isJSONOutput() { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "superseded": oldID, "replacement": newID, "status": "closed", }) - return nil } fmt.Printf("%s Marked %s as superseded by %s (closed)\n", ui.RenderPass("āœ“"), oldID, newID) diff --git a/cmd/bd/duplicates.go b/cmd/bd/duplicates.go index faf3f4d7e..a0d28e472 100644 --- a/cmd/bd/duplicates.go +++ b/cmd/bd/duplicates.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -24,46 +25,46 @@ Example: bd duplicates # Show all duplicate groups bd duplicates --auto-merge # Automatically merge all duplicates bd duplicates --dry-run # Show what would be merged`, - Run: func(cmd *cobra.Command, _ []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("duplicates") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + autoMerge, _ := cmd.Flags().GetBool("auto-merge") dryRun, _ := cmd.Flags().GetBool("dry-run") - // Block writes in readonly mode (merging modifies data) if autoMerge && !dryRun { CheckReadonly("duplicates --auto-merge") } - // Use global jsonOutput set by PersistentPreRun ctx := rootCtx - // Get all issues allIssues, err := store.SearchIssues(ctx, "", types.IssueFilter{}) if err != nil { - FatalError("fetching issues: %v", err) + return HandleError("fetching issues: %v", err) } - // Filter out closed issues - they're done, no point detecting duplicates openIssues := make([]*types.Issue, 0, len(allIssues)) for _, issue := range allIssues { if issue.Status != types.StatusClosed { openIssues = append(openIssues, issue) } } - // Find duplicates (only among open issues) duplicateGroups := findDuplicateGroups(openIssues) if len(duplicateGroups) == 0 { if !jsonOutput { fmt.Println("No duplicates found!") - } else { - outputJSON(map[string]interface{}{ - "duplicate_groups": 0, - "groups": []interface{}{}, - }) + return nil } - return + return outputJSON(map[string]interface{}{ + "duplicate_groups": 0, + "groups": []interface{}{}, + }) } - // Count references for each issue refCounts := countReferences(allIssues) - // Count structural relationships (children, dependencies) for duplicate groups structuralScores := countStructuralRelationships(duplicateGroups) - // Prepare output var mergeCommands []string var mergeResults []map[string]interface{} for _, group := range duplicateGroups { @@ -74,7 +75,6 @@ Example: sources = append(sources, issue.ID) } } - // Generate actionable command suggestion cmd := fmt.Sprintf("# Duplicate: %s (same content as %s)\n# Suggested action: bd close %s && bd dep add %s %s --type related", strings.Join(sources, " "), target.ID, @@ -93,7 +93,6 @@ Example: if autoMerge && !dryRun { commandDidWrite.Store(true) } - // Output results if jsonOutput { output := map[string]interface{}{ "duplicate_groups": len(duplicateGroups), @@ -105,45 +104,45 @@ Example: output["merge_results"] = mergeResults } } - outputJSON(output) - } else { - fmt.Printf("%s Found %d duplicate group(s):\n\n", ui.RenderWarn("šŸ”"), len(duplicateGroups)) - for i, group := range duplicateGroups { - target := chooseMergeTarget(group, refCounts, structuralScores) - fmt.Printf("%s Group %d: %s\n", ui.RenderAccent("━━"), i+1, group[0].Title) - for _, issue := range group { - refs := refCounts[issue.ID] - weight := 0 - if score, ok := structuralScores[issue.ID]; ok { - weight = score.dependentCount*3 + score.dependsOnCount - } - marker := " " - if issue.ID == target.ID { - marker = ui.RenderPass("→ ") - } - fmt.Printf("%s%s (%s, P%d, weight=%d, %d refs)\n", - marker, issue.ID, issue.Status, issue.Priority, weight, refs) - } - sources := make([]string, 0, len(group)-1) - for _, issue := range group { - if issue.ID != target.ID { - sources = append(sources, issue.ID) - } - } - fmt.Printf(" %s Duplicate: %s (same content as %s)\n", ui.RenderAccent("Note:"), strings.Join(sources, " "), target.ID) - fmt.Printf(" %s bd close %s && bd dep add %s %s --type related\n\n", - ui.RenderAccent("Suggested:"), strings.Join(sources, " "), strings.Join(sources, " "), target.ID) - } - if autoMerge { - if dryRun { - fmt.Printf("%s Dry run - would execute %d merge(s)\n", ui.RenderWarn("⚠"), len(mergeCommands)) - } else { - fmt.Printf("%s Merged %d group(s)\n", ui.RenderPass("āœ“"), len(mergeCommands)) - } - } else { - fmt.Printf("%s Run with --auto-merge to execute all suggested merges\n", ui.RenderAccent("šŸ’”")) - } + return outputJSON(output) } + fmt.Printf("%s Found %d duplicate group(s):\n\n", ui.RenderWarn("šŸ”"), len(duplicateGroups)) + for i, group := range duplicateGroups { + target := chooseMergeTarget(group, refCounts, structuralScores) + fmt.Printf("%s Group %d: %s\n", ui.RenderAccent("━━"), i+1, group[0].Title) + for _, issue := range group { + refs := refCounts[issue.ID] + weight := 0 + if score, ok := structuralScores[issue.ID]; ok { + weight = score.dependentCount*3 + score.dependsOnCount + } + marker := " " + if issue.ID == target.ID { + marker = ui.RenderPass("→ ") + } + fmt.Printf("%s%s (%s, P%d, weight=%d, %d refs)\n", + marker, issue.ID, issue.Status, issue.Priority, weight, refs) + } + sources := make([]string, 0, len(group)-1) + for _, issue := range group { + if issue.ID != target.ID { + sources = append(sources, issue.ID) + } + } + fmt.Printf(" %s Duplicate: %s (same content as %s)\n", ui.RenderAccent("Note:"), strings.Join(sources, " "), target.ID) + fmt.Printf(" %s bd close %s && bd dep add %s %s --type related\n\n", + ui.RenderAccent("Suggested:"), strings.Join(sources, " "), strings.Join(sources, " "), target.ID) + } + if autoMerge { + if dryRun { + fmt.Printf("%s Dry run - would execute %d merge(s)\n", ui.RenderWarn("⚠"), len(mergeCommands)) + } else { + fmt.Printf("%s Merged %d group(s)\n", ui.RenderPass("āœ“"), len(mergeCommands)) + } + } else { + fmt.Printf("%s Run with --auto-merge to execute all suggested merges\n", ui.RenderAccent("šŸ’”")) + } + return nil }, } diff --git a/cmd/bd/edit.go b/cmd/bd/edit.go index 36bea7535..214719a2d 100644 --- a/cmd/bd/edit.go +++ b/cmd/bd/edit.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/ui" ) @@ -25,22 +26,31 @@ Examples: bd edit bd-42 --design # Edit design notes bd edit bd-42 --notes # Edit notes bd edit bd-42 --acceptance # Edit acceptance criteria`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("edit") + + evt := metrics.NewCommandEvent("edit") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + id := args[0] ctx := rootCtx // Resolve ID with prefix routing (supports cross-rig edits like `bd edit xe-5ls`) result, err := resolveAndGetIssueForMutation(ctx, store, id) if err != nil { - FatalErrorRespectJSON("resolving %s: %v", id, err) + return HandleErrorRespectJSON("resolving %s: %v", id, err) } defer result.Close() id = result.ResolvedID issueStore := result.Store - // Determine which field to edit fieldToEdit := "description" if cmd.Flags().Changed("title") { fieldToEdit = "title" @@ -52,13 +62,11 @@ Examples: fieldToEdit = "acceptance_criteria" } - // Get the editor from environment editor := os.Getenv("EDITOR") if editor == "" { editor = os.Getenv("VISUAL") } if editor == "" { - // Try common defaults for _, defaultEditor := range []string{"vim", "vi", "nano", "emacs"} { if _, err := exec.LookPath(defaultEditor); err == nil { editor = defaultEditor @@ -67,12 +75,11 @@ Examples: } } if editor == "" { - FatalErrorRespectJSON("no editor found. Set $EDITOR or $VISUAL environment variable") + return HandleErrorRespectJSON("no editor found. Set $EDITOR or $VISUAL environment variable") } issue := result.Issue - // Get the current field value var currentValue string switch fieldToEdit { case "title": @@ -87,10 +94,9 @@ Examples: currentValue = issue.AcceptanceCriteria } - // Create a temporary file with the current value tmpFile, err := os.CreateTemp("", fmt.Sprintf("bd-edit-%s-*.txt", fieldToEdit)) if err != nil { - FatalErrorRespectJSON("creating temp file: %v", err) + return HandleErrorRespectJSON("creating temp file: %v", err) } tmpPath := tmpFile.Name() editSaved := false @@ -100,14 +106,12 @@ Examples: } }() - // Write current value to temp file if _, err := tmpFile.WriteString(currentValue); err != nil { _ = tmpFile.Close() - FatalErrorRespectJSON("writing to temp file: %v", err) + return HandleErrorRespectJSON("writing to temp file: %v", err) } _ = tmpFile.Close() - // Open the editor - parse command and args (handles "vim -w" or "zeditor --wait") editorParts := strings.Fields(editor) editorArgs := append(editorParts[1:], tmpPath) editorCmd := exec.Command(editorParts[0], editorArgs...) //nolint:gosec // G204: editor from trusted $EDITOR/$VISUAL env or known defaults @@ -116,44 +120,35 @@ Examples: editorCmd.Stderr = os.Stderr if err := editorCmd.Run(); err != nil { - FatalErrorRespectJSON("running editor: %v", err) + return HandleErrorRespectJSON("running editor: %v", err) } - // Read the edited content // #nosec G304 -- tmpPath was created earlier in this function editedContent, err := os.ReadFile(tmpPath) if err != nil { - FatalErrorRespectJSON("reading edited file: %v", err) + return HandleErrorRespectJSON("reading edited file: %v", err) } newValue := strings.TrimSpace(string(editedContent)) - // Check if the value changed if newValue == currentValue { - editSaved = true // no changes — safe to remove temp file + editSaved = true fmt.Println("No changes made") - return + return nil } - // Validate title if editing title if fieldToEdit == "title" && newValue == "" { - FatalErrorRespectJSON("title cannot be empty") + return HandleErrorRespectJSON("title cannot be empty") } - // Update the issue — retry once if the DB connection went stale - // during a long editor session (GH-2267). - // Use the routed store for cross-rig mutations. updates := map[string]interface{}{ fieldToEdit: newValue, } err = issueStore.UpdateIssue(ctx, id, updates, actor) if err != nil { - // Connection may have gone stale while the editor was open. - // Ping to force the pool to discard dead connections, then retry. if accessor, ok := storage.UnwrapStore(issueStore).(storage.RawDBAccessor); ok { if pingErr := accessor.DB().PingContext(ctx); pingErr != nil { - // Ping failed — try to force a fresh connection via sql.DB pool reset. accessor.DB().SetConnMaxIdleTime(0) _ = accessor.DB().PingContext(ctx) } @@ -162,7 +157,7 @@ Examples: } if err != nil { fmt.Fprintf(os.Stderr, "Your edits are preserved in: %s\n", tmpPath) - FatalErrorRespectJSON("updating issue: %v", err) + return HandleErrorRespectJSON("updating issue: %v", err) } editSaved = true if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{ @@ -170,7 +165,7 @@ Examples: IssueIDs: []string{id}, }); err != nil { fmt.Fprintf(os.Stderr, "Your edits are preserved in: %s\n", tmpPath) - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } displayTitle := issue.Title @@ -180,6 +175,7 @@ Examples: fieldName := strings.ReplaceAll(fieldToEdit, "_", " ") fmt.Printf("%s Updated %s for issue: %s\n", ui.RenderPass("āœ“"), fieldName, formatFeedbackID(id, displayTitle)) + return nil }, } diff --git a/cmd/bd/epic.go b/cmd/bd/epic.go index 0771f1f51..96a1847de 100644 --- a/cmd/bd/epic.go +++ b/cmd/bd/epic.go @@ -3,6 +3,7 @@ package main import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "os" @@ -14,17 +15,25 @@ var epicCmd = &cobra.Command{ Short: "Epic management commands", } var epicStatusCmd = &cobra.Command{ - Use: "status", - Short: "Show epic completion status", - Run: func(cmd *cobra.Command, args []string) { + Use: "status", + Short: "Show epic completion status", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("epic-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + eligibleOnly, _ := cmd.Flags().GetBool("eligible-only") - // Use global jsonOutput set by PersistentPreRun var epics []*types.EpicStatus var err error ctx := rootCtx epics, err = store.GetEpicsEligibleForClosure(ctx) if err != nil { - FatalErrorRespectJSON("getting epic status: %v", err) + return HandleErrorRespectJSON("getting epic status: %v", err) } if eligibleOnly { filtered := []*types.EpicStatus{} @@ -39,13 +48,11 @@ var epicStatusCmd = &cobra.Command{ if epics == nil { epics = []*types.EpicStatus{} } - outputJSON(epics) - return + return outputJSON(epics) } - // Human-readable output if len(epics) == 0 { fmt.Println("No open epics found") - return + return nil } for _, epicStatus := range epics { epic := epicStatus.Epic @@ -69,23 +76,31 @@ var epicStatusCmd = &cobra.Command{ } fmt.Println() } + return nil }, } var closeEligibleEpicsCmd = &cobra.Command{ - Use: "close-eligible", - Short: "Close epics where all children are complete", - Run: func(cmd *cobra.Command, args []string) { + Use: "close-eligible", + Short: "Close epics where all children are complete", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("epic-close-eligible") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + dryRun, _ := cmd.Flags().GetBool("dry-run") - // Block writes in readonly mode (closing modifies data) if !dryRun { CheckReadonly("epic close-eligible") } - // Use global jsonOutput set by PersistentPreRun var eligibleEpics []*types.EpicStatus ctx := rootCtx epics, err := store.GetEpicsEligibleForClosure(ctx) if err != nil { - FatalErrorRespectJSON("getting eligible epics: %v", err) + return HandleErrorRespectJSON("getting eligible epics: %v", err) } for _, epic := range epics { if epic.EligibleForClose { @@ -94,24 +109,21 @@ var closeEligibleEpicsCmd = &cobra.Command{ } if len(eligibleEpics) == 0 { if jsonOutput { - outputJSON([]*types.EpicStatus{}) - } else { - fmt.Println("No epics eligible for closure") + return outputJSON([]*types.EpicStatus{}) } - return + fmt.Println("No epics eligible for closure") + return nil } if dryRun { if jsonOutput { - outputJSON(eligibleEpics) - } else { - fmt.Printf("Would close %d epic(s):\n", len(eligibleEpics)) - for _, epicStatus := range eligibleEpics { - fmt.Printf(" - %s: %s\n", epicStatus.Epic.ID, epicStatus.Epic.Title) - } + return outputJSON(eligibleEpics) } - return + fmt.Printf("Would close %d epic(s):\n", len(eligibleEpics)) + for _, epicStatus := range eligibleEpics { + fmt.Printf(" - %s: %s\n", epicStatus.Epic.ID, epicStatus.Epic.Title) + } + return nil } - // Actually close the epics closedIDs := []string{} for _, epicStatus := range eligibleEpics { err := store.CloseIssue(ctx, epicStatus.Epic.ID, "All children completed", "system", "") @@ -125,16 +137,16 @@ var closeEligibleEpicsCmd = &cobra.Command{ commandDidWrite.Store(true) } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "closed": closedIDs, "count": len(closedIDs), }) - } else { - fmt.Printf("āœ“ Closed %d epic(s)\n", len(closedIDs)) - for _, id := range closedIDs { - fmt.Printf(" - %s\n", id) - } } + fmt.Printf("āœ“ Closed %d epic(s)\n", len(closedIDs)) + for _, id := range closedIDs { + fmt.Printf(" - %s\n", id) + } + return nil }, } diff --git a/cmd/bd/errors.go b/cmd/bd/errors.go index 85de69255..671736c04 100644 --- a/cmd/bd/errors.go +++ b/cmd/bd/errors.go @@ -2,10 +2,27 @@ package main import ( "encoding/json" + "errors" "fmt" "os" ) +type exitError struct { + Code int +} + +func (e *exitError) Error() string { + return fmt.Sprintf("exit code %d", e.Code) +} + +func exitCodeFromError(err error) (int, bool) { + var ee *exitError + if errors.As(err, &ee) { + return ee.Code, true + } + return 0, false +} + func activeWorkspaceNotFoundError() string { return "no active beads workspace found" } @@ -14,9 +31,6 @@ func activeWorkspaceNotFoundMessage() string { return "No active beads workspace found." } -// diagHint returns the appropriate diagnostic hint when the active beads -// workspace cannot be resolved. In embedded mode, 'bd doctor' is not -// available so the hint omits it. func diagHint() string { return workspaceDiagHint(true) } @@ -38,7 +52,6 @@ func workspaceDiagHint(includeWhere bool) string { return "check BEADS_DIR/worktree setup, run 'bd doctor' to diagnose, or run 'bd init' to create a new database" } -// buildJSONError constructs a JSON error object respecting envelope mode. func buildJSONError(message, hint string) interface{} { inner := map[string]interface{}{ "error": message, @@ -56,35 +69,59 @@ func buildJSONError(message, hint string) interface{} { return inner } -// jsonStderrError writes a structured JSON error to stderr when --json is active. func jsonStderrError(message, hint string) { encoder := json.NewEncoder(os.Stderr) encoder.SetIndent("", " ") _ = encoder.Encode(buildJSONError(message, hint)) } -// jsonStdoutError writes a structured JSON error to stdout when --json is active. -// Used by FatalErrorRespectJSON and FatalErrorWithHintRespectJSON where -// callers expect errors on stdout (e.g., bd show nonexistent-id --json). func jsonStdoutError(message, hint string) { encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("", " ") _ = encoder.Encode(buildJSONError(message, hint)) } -// FatalError writes an error message to stderr and exits with code 1. -// Use this for fatal errors that prevent the command from completing. -// -// Pattern A from ERROR_HANDLING.md: -// - User input validation failures -// - Critical preconditions not met -// - Unrecoverable system errors -// -// Example: -// -// if err := store.CreateIssue(ctx, issue, actor); err != nil { -// FatalError("%v", err) -// } +func HandleError(format string, args ...interface{}) error { + fmt.Fprintf(os.Stderr, "Error: "+format+"\n", args...) + return &exitError{Code: 1} +} + +func HandleErrorRespectJSON(format string, args ...interface{}) error { + if jsonOutput { + jsonStdoutError(fmt.Sprintf(format, args...), "") + return &exitError{Code: 1} + } + return HandleError(format, args...) +} + +func HandleErrorWithHint(message, hint string) error { + if jsonOutput { + jsonStderrError(message, hint) + } else { + fmt.Fprintf(os.Stderr, "Error: %s\n", message) + fmt.Fprintf(os.Stderr, "Hint: %s\n", hint) + } + return &exitError{Code: 1} +} + +func HandleErrorWithHintRespectJSON(message, hint string) error { + if jsonOutput { + jsonStdoutError(message, hint) + } else { + fmt.Fprintf(os.Stderr, "Error: %s\n", message) + fmt.Fprintf(os.Stderr, "Hint: %s\n", hint) + } + return &exitError{Code: 1} +} + +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. Retained for the proxied-server code paths that +// run outside cobra's RunE error-return convention; the RunE-converted commands +// use HandleError and friends instead. func FatalError(format string, args ...interface{}) { msg := fmt.Sprintf(format, args...) if jsonOutput { @@ -95,17 +132,9 @@ func FatalError(format string, args ...interface{}) { os.Exit(1) } -// FatalErrorRespectJSON writes an error message and exits with code 1. -// If --json flag is set, outputs structured JSON to stdout. -// Otherwise, outputs plain text to stderr. -// -// Use this for errors in commands that support --json output. -// -// Example: -// -// if err := store.GetIssue(ctx, id); err != nil { -// FatalErrorRespectJSON("%v", err) -// } +// 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 { @@ -129,11 +158,6 @@ func FatalErrorWithHintRespectJSON(message, hint string) { } // FatalErrorWithHint writes an error message with a hint to stderr and exits. -// Use this when you can provide an actionable suggestion to fix the error. -// -// Example: -// -// FatalErrorWithHint("database not found", "Run 'bd init' to create a database") func FatalErrorWithHint(message, hint string) { if jsonOutput { jsonStderrError(message, hint) @@ -144,37 +168,13 @@ func FatalErrorWithHint(message, hint string) { os.Exit(1) } -// WarnError writes a warning message to stderr and returns. -// Use this for optional operations that enhance functionality but aren't required. -// -// Pattern B from ERROR_HANDLING.md: -// - Metadata operations -// - Cleanup operations -// - Auxiliary features (git hooks, merge drivers) -// -// Example: -// -// if err := createConfigYaml(beadsDir, false); err != nil { -// WarnError("failed to create config.yaml: %v", err) -// } func WarnError(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, "Warning: "+format+"\n", args...) } -// CheckReadonly exits with an error if readonly mode is enabled. -// Call this at the start of write commands (create, update, close, delete, sync, etc.). -// Used by worker sandboxes that should only read beads, not modify them. -// -// Example: -// -// var createCmd = &cobra.Command{ -// Run: func(cmd *cobra.Command, args []string) { -// CheckReadonly("create") -// // ... rest of command -// }, -// } func CheckReadonly(operation string) { if readonlyMode { - FatalError("operation '%s' is not allowed in read-only mode", operation) + fmt.Fprintf(os.Stderr, "Error: operation '%s' is not allowed in read-only mode\n", operation) + os.Exit(1) } } diff --git a/cmd/bd/export.go b/cmd/bd/export.go index 71e1e3b56..db8a60702 100644 --- a/cmd/bd/export.go +++ b/cmd/bd/export.go @@ -11,6 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/atomicfile" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/types" ) @@ -42,8 +43,10 @@ EXAMPLES: bd export --include-memories # Export issues + memories bd export --all -o full.jsonl # Include infra + templates + gates + memories bd export --scrub -o clean.jsonl # Exclude test/pollution records`, - GroupID: "sync", - RunE: runExport, + GroupID: "sync", + SilenceUsage: true, + SilenceErrors: true, + RunE: runExport, } var ( @@ -67,6 +70,13 @@ func init() { } func runExport(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("export") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx // Determine output destination. File output uses atomic writes @@ -78,7 +88,7 @@ func runExport(cmd *cobra.Command, args []string) error { var err error aw, err = atomicfile.Create(exportOutput, 0o644) if err != nil { - return fmt.Errorf("failed to create output file: %w", err) + return HandleErrorRespectJSON("failed to create output file: %v", err) } defer func() { // Abort is a no-op if Close was already called. @@ -127,7 +137,7 @@ func runExport(cmd *cobra.Command, args []string) error { issues, err := store.SearchIssues(ctx, "", filter) if err != nil { - return fmt.Errorf("failed to search issues: %w", err) + return HandleErrorRespectJSON("failed to search issues: %v", err) } // Scrub test/pollution records if requested @@ -186,13 +196,13 @@ func runExport(cmd *cobra.Command, args []string) error { data, err := json.Marshal(record) if err != nil { - return fmt.Errorf("failed to marshal issue %s: %w", issue.ID, err) + return HandleErrorRespectJSON("failed to marshal issue %s: %v", issue.ID, err) } if _, err := w.Write(data); err != nil { - return fmt.Errorf("failed to write: %w", err) + return HandleErrorRespectJSON("failed to write: %v", err) } if _, err := w.Write([]byte{'\n'}); err != nil { - return fmt.Errorf("failed to write newline: %w", err) + return HandleErrorRespectJSON("failed to write newline: %v", err) } count++ } @@ -203,7 +213,7 @@ func runExport(cmd *cobra.Command, args []string) error { if (exportIncludeMemories || exportAll) && !exportNoMemories { allConfig, err := store.GetAllConfig(ctx) if err != nil { - return fmt.Errorf("failed to read config for memories: %w", err) + return HandleErrorRespectJSON("failed to read config for memories: %v", err) } fullPrefix := kvPrefix + memoryPrefix // Sort keys for deterministic output order (GH#3474). @@ -224,13 +234,13 @@ func runExport(cmd *cobra.Command, args []string) error { } data, err := json.Marshal(record) if err != nil { - return fmt.Errorf("failed to marshal memory %s: %w", userKey, err) + return HandleErrorRespectJSON("failed to marshal memory %s: %v", userKey, err) } if _, err := w.Write(data); err != nil { - return fmt.Errorf("failed to write: %w", err) + return HandleErrorRespectJSON("failed to write: %v", err) } if _, err := w.Write([]byte{'\n'}); err != nil { - return fmt.Errorf("failed to write newline: %w", err) + return HandleErrorRespectJSON("failed to write newline: %v", err) } memoryCount++ } @@ -239,7 +249,7 @@ func runExport(cmd *cobra.Command, args []string) error { // Finalize atomic write if writing to file (fsync + rename). if aw != nil { if err := aw.Close(); err != nil { - return fmt.Errorf("failed to finalize export file: %w", err) + return HandleErrorRespectJSON("failed to finalize export file: %v", err) } } diff --git a/cmd/bd/export_auto_test.go b/cmd/bd/export_auto_test.go index 6eeda793e..d3d5201f0 100644 --- a/cmd/bd/export_auto_test.go +++ b/cmd/bd/export_auto_test.go @@ -1030,5 +1030,5 @@ func autoExportDataLossTestEnv(home string) []string { } env = append(env, e) } - return append(env, "HOME="+home, "BEADS_DOLT_AUTO_START=0", "BEADS_NO_DAEMON=1") + return append(env, "HOME="+home, "BEADS_DOLT_AUTO_START=0", "BEADS_NO_DAEMON=1", "BD_DISABLE_METRICS=1", "BD_DISABLE_EVENT_FLUSH=1") } diff --git a/cmd/bd/federation.go b/cmd/bd/federation.go index 6075c6831..5f3188446 100644 --- a/cmd/bd/federation.go +++ b/cmd/bd/federation.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/ui" "golang.org/x/term" @@ -52,7 +53,9 @@ Examples: bd federation sync # Sync with all peers bd federation sync --peer town-beta # Sync with specific peer bd federation sync --strategy theirs # Auto-resolve using remote values`, - Run: runFederationSync, + SilenceUsage: true, + SilenceErrors: true, + RunE: runFederationSync, } var federationStatusCmd = &cobra.Command{ @@ -68,7 +71,9 @@ Displays: Examples: bd federation status # Status for all peers bd federation status --peer town-beta # Status for specific peer`, - Run: runFederationStatus, + SilenceUsage: true, + SilenceErrors: true, + RunE: runFederationStatus, } var federationAddPeerCmd = &cobra.Command{ @@ -89,21 +94,27 @@ Examples: bd federation add-peer town-beta dolthub://acme/town-beta-beads bd federation add-peer town-gamma 192.168.1.100:3306/beads --user sync-bot bd federation add-peer partner https://partner.example.com/beads --user admin --password secret`, - Args: cobra.ExactArgs(2), - Run: runFederationAddPeer, + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: runFederationAddPeer, } var federationRemovePeerCmd = &cobra.Command{ - Use: "remove-peer ", - Short: "Remove a federation peer", - Args: cobra.ExactArgs(1), - Run: runFederationRemovePeer, + Use: "remove-peer ", + Short: "Remove a federation peer", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runFederationRemovePeer, } var federationListPeersCmd = &cobra.Command{ - Use: "list-peers", - Short: "List configured federation peers", - Run: runFederationListPeers, + Use: "list-peers", + Short: "List configured federation peers", + SilenceUsage: true, + SilenceErrors: true, + RunE: runFederationListPeers, } func init() { @@ -136,31 +147,34 @@ func getFederatedStore() (storage.DoltStorage, error) { return store, nil } -func runFederationSync(cmd *cobra.Command, args []string) { +func runFederationSync(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("federation-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx ds, err := getFederatedStore() if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Validate strategy if provided if federationStrategy != "" && federationStrategy != "ours" && federationStrategy != "theirs" { - FatalErrorRespectJSON("invalid strategy %q: must be 'ours' or 'theirs'", federationStrategy) + return HandleErrorRespectJSON("invalid strategy %q: must be 'ours' or 'theirs'", federationStrategy) } - // Get peers to sync with var peers []string if federationPeer != "" { peers = []string{federationPeer} } else { - // Get all configured remotes remotes, err := ds.ListRemotes(ctx) if err != nil { - FatalErrorRespectJSON("failed to list peers: %v", err) + return HandleErrorRespectJSON("failed to list peers: %v", err) } for _, r := range remotes { - // Skip 'origin' which is typically the backup remote, not a peer if r.Name != "origin" { peers = append(peers, r.Name) } @@ -168,7 +182,7 @@ func runFederationSync(cmd *cobra.Command, args []string) { } if len(peers) == 0 { - FatalErrorRespectJSON("no federation peers configured (use 'bd federation add-peer' to add peers)") + return HandleErrorRespectJSON("no federation peers configured (use 'bd federation add-peer' to add peers)") } // Sync with each peer @@ -220,32 +234,38 @@ func runFederationSync(cmd *cobra.Command, args []string) { } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "peers": peers, "results": results, }) } + return nil } -func runFederationStatus(cmd *cobra.Command, args []string) { +func runFederationStatus(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("federation-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx ds, err := getFederatedStore() if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Get all remotes for URL lookup allRemotes, err := ds.ListRemotes(ctx) if err != nil { - FatalErrorRespectJSON("failed to list remotes: %v", err) + return HandleErrorRespectJSON("failed to list remotes: %v", err) } remoteURLs := make(map[string]string) for _, r := range allRemotes { remoteURLs[r.Name] = r.URL } - // Get peers to check var peers []string if federationPeer != "" { peers = []string{federationPeer} @@ -257,24 +277,21 @@ func runFederationStatus(cmd *cobra.Command, args []string) { if len(peers) == 0 { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "peers": []string{}, "pendingChanges": 0, }) - } else { - fmt.Println("No federation peers configured.") } - return + fmt.Println("No federation peers configured.") + return nil } - // Get pending local changes - doltStatus, _ := ds.Status(ctx) // Best effort: nil status means federation not available + doltStatus, _ := ds.Status(ctx) pendingChanges := 0 if doltStatus != nil { pendingChanges = len(doltStatus.Staged) + len(doltStatus.Unstaged) } - // Collect status for each peer type peerStatus struct { Status *storage.SyncStatus URL string @@ -288,16 +305,13 @@ func runFederationStatus(cmd *cobra.Command, args []string) { URL: remoteURLs[peer], } - // Get sync status - status, _ := ds.SyncStatus(ctx, peer) // Best effort: nil status means sync info unavailable + status, _ := ds.SyncStatus(ctx, peer) ps.Status = status - // Test connectivity by attempting a fetch fetchErr := ds.Fetch(ctx, peer) if fetchErr == nil { ps.Reachable = true - // Re-get status after successful fetch for accurate ahead/behind - status, _ = ds.SyncStatus(ctx, peer) // Best effort: nil status means sync info unavailable + status, _ = ds.SyncStatus(ctx, peer) ps.Status = status } else { ps.ReachError = fetchErr.Error() @@ -307,16 +321,14 @@ func runFederationStatus(cmd *cobra.Command, args []string) { } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "peers": peerStatuses, "pendingChanges": pendingChanges, }) - return } fmt.Printf("\n%s Federation Status:\n\n", ui.RenderAccent("🌐")) - // Show local pending changes if pendingChanges > 0 { fmt.Printf(" %s %d pending local changes\n\n", ui.RenderWarn("⚠"), pendingChanges) } @@ -325,14 +337,12 @@ func runFederationStatus(cmd *cobra.Command, args []string) { status := ps.Status fmt.Printf(" %s %s\n", ui.RenderAccent(status.Peer), ui.RenderMuted(ps.URL)) - // Connectivity status if ps.Reachable { fmt.Printf(" %s Reachable\n", ui.RenderPass("āœ“")) } else { fmt.Printf(" %s Unreachable: %s\n", ui.RenderFail("āœ—"), ps.ReachError) } - // Sync status if status.LocalAhead >= 0 { fmt.Printf(" Ahead: %d commits\n", status.LocalAhead) fmt.Printf(" Behind: %d commits\n", status.LocalBehind) @@ -340,47 +350,50 @@ func runFederationStatus(cmd *cobra.Command, args []string) { fmt.Printf(" Sync: %s\n", ui.RenderMuted("not fetched yet")) } - // Last sync time if !status.LastSync.IsZero() { fmt.Printf(" Last sync: %s\n", status.LastSync.Format("2006-01-02 15:04:05")) } - // Conflicts if status.HasConflicts { fmt.Printf(" %s Unresolved conflicts\n", ui.RenderWarn("⚠")) } fmt.Println() } + return nil } -func runFederationAddPeer(cmd *cobra.Command, args []string) { +func runFederationAddPeer(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("federation-add-peer") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx name := args[0] url := args[1] - // If user is provided but password is not, prompt for it password := federationPassword if federationUser != "" && password == "" { fmt.Fprint(os.Stderr, "Password: ") pwBytes, err := term.ReadPassword(int(os.Stdin.Fd())) - fmt.Fprintln(os.Stderr) // newline after password + fmt.Fprintln(os.Stderr) if err != nil { - FatalErrorRespectJSON("failed to read password: %v", err) + return HandleErrorRespectJSON("failed to read password: %v", err) } password = string(pwBytes) } - // Validate sovereignty tier if provided sov := federationSov if sov != "" { sov = strings.ToUpper(sov) if sov != "T1" && sov != "T2" && sov != "T3" && sov != "T4" { - FatalErrorRespectJSON("invalid sovereignty tier: %s (must be T1, T2, T3, or T4)", federationSov) + return HandleErrorRespectJSON("invalid sovereignty tier: %s (must be T1, T2, T3, or T4)", federationSov) } } - // If credentials provided, use AddFederationPeer to store them if federationUser != "" { peer := &storage.FederationPeer{ Name: name, @@ -390,23 +403,21 @@ func runFederationAddPeer(cmd *cobra.Command, args []string) { Sovereignty: sov, } if err := store.AddFederationPeer(ctx, peer); err != nil { - FatalErrorRespectJSON("failed to add peer: %v", err) + return HandleErrorRespectJSON("failed to add peer: %v", err) } } else { - // No credentials, just add the remote if err := store.AddRemote(ctx, name, url); err != nil { - FatalErrorRespectJSON("failed to add peer: %v", err) + return HandleErrorRespectJSON("failed to add peer: %v", err) } } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "added": name, "url": url, "has_auth": federationUser != "", "sovereignty": sov, }) - return } fmt.Printf("Added peer %s: %s\n", ui.RenderAccent(name), url) @@ -416,43 +427,57 @@ func runFederationAddPeer(cmd *cobra.Command, args []string) { if sov != "" { fmt.Printf(" Sovereignty: %s\n", sov) } + return nil } -func runFederationRemovePeer(cmd *cobra.Command, args []string) { +func runFederationRemovePeer(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("federation-remove-peer") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx name := args[0] if err := store.RemoveRemote(ctx, name); err != nil { - FatalErrorRespectJSON("failed to remove peer: %v", err) + return HandleErrorRespectJSON("failed to remove peer: %v", err) } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "removed": name, }) - return } fmt.Printf("Removed peer: %s\n", name) + return nil } -func runFederationListPeers(cmd *cobra.Command, args []string) { +func runFederationListPeers(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("federation-list-peers") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx remotes, err := store.ListRemotes(ctx) if err != nil { - FatalErrorRespectJSON("failed to list peers: %v", err) + return HandleErrorRespectJSON("failed to list peers: %v", err) } if jsonOutput { - outputJSON(formatFederationPeerListJSON(remotes)) - return + return outputJSON(formatFederationPeerListJSON(remotes)) } if len(remotes) == 0 { fmt.Println("No federation peers configured.") - return + return nil } fmt.Printf("\n%s Federation Peers:\n\n", ui.RenderAccent("🌐")) @@ -460,6 +485,7 @@ func runFederationListPeers(cmd *cobra.Command, args []string) { fmt.Printf(" %s %s\n", ui.RenderAccent(r.Name), ui.RenderMuted(r.URL)) } fmt.Println() + return nil } type federationPeerListJSON struct { diff --git a/cmd/bd/find_duplicates.go b/cmd/bd/find_duplicates.go index a6aeaa1ce..6de3fa623 100644 --- a/cmd/bd/find_duplicates.go +++ b/cmd/bd/find_duplicates.go @@ -16,6 +16,7 @@ import ( "github.com/anthropics/anthropic-sdk-go/option" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/telemetry" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -53,7 +54,9 @@ Examples: bd find-duplicates --status open # Only check open issues bd find-duplicates --limit 20 # Show top 20 pairs bd find-duplicates --json # JSON output`, - Run: runFindDuplicates, + SilenceUsage: true, + SilenceErrors: true, + RunE: runFindDuplicates, } func init() { @@ -74,7 +77,14 @@ type duplicatePair struct { Reason string `json:"reason,omitempty"` } -func runFindDuplicates(cmd *cobra.Command, _ []string) { +func runFindDuplicates(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("find-duplicates") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + method, _ := cmd.Flags().GetString("method") threshold, _ := cmd.Flags().GetFloat64("threshold") status, _ := cmd.Flags().GetString("status") @@ -86,19 +96,16 @@ func runFindDuplicates(cmd *cobra.Command, _ []string) { ctx := rootCtx - // Validate method if method != "mechanical" && method != "ai" { - FatalError("invalid method %q (use: mechanical, ai)", method) + return HandleErrorRespectJSON("invalid method %q (use: mechanical, ai)", method) } - // AI method requires API key if method == "ai" { if os.Getenv("ANTHROPIC_API_KEY") == "" && config.GetString("ai.api_key") == "" { - FatalError("--method ai requires ANTHROPIC_API_KEY environment variable or ai.api_key in config") + return HandleErrorRespectJSON("--method ai requires ANTHROPIC_API_KEY environment variable or ai.api_key in config") } } - // Fetch issues filter := types.IssueFilter{} if status != "" && status != "all" { s := types.Status(status) @@ -110,10 +117,9 @@ func runFindDuplicates(cmd *cobra.Command, _ []string) { issues, err = store.SearchIssues(ctx, "", filter) if err != nil { - FatalError("fetching issues: %v", err) + return HandleErrorRespectJSON("fetching issues: %v", err) } - // Default: filter out closed issues unless status flag is set if status == "" { var filtered []*types.Issue for _, issue := range issues { @@ -126,14 +132,13 @@ func runFindDuplicates(cmd *cobra.Command, _ []string) { if len(issues) < 2 { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "pairs": []interface{}{}, "count": 0, }) - } else { - fmt.Println("Not enough issues to compare (need at least 2)") } - return + fmt.Println("Not enough issues to compare (need at least 2)") + return nil } // Find duplicate pairs @@ -178,18 +183,17 @@ func runFindDuplicates(cmd *cobra.Command, _ []string) { Reason: p.Reason, } } - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "pairs": jsonPairs, "count": len(jsonPairs), "method": method, "threshold": threshold, }) - return } if len(pairs) == 0 { fmt.Printf("No similar issues found (threshold: %.0f%%)\n", threshold*100) - return + return nil } fmt.Printf("%s Found %d potential duplicate pair(s) (threshold: %.0f%%):\n\n", @@ -205,6 +209,7 @@ func runFindDuplicates(cmd *cobra.Command, _ []string) { } fmt.Printf(" %s bd show %s %s\n\n", ui.RenderAccent("Compare:"), p.IssueA.ID, p.IssueB.ID) } + return nil } // tokenize splits text into lowercase word tokens, removing punctuation. diff --git a/cmd/bd/flags.go b/cmd/bd/flags.go index 1f821ce8c..c5c70a9f9 100644 --- a/cmd/bd/flags.go +++ b/cmd/bd/flags.go @@ -38,15 +38,14 @@ func registerCommonIssueFlags(cmd *cobra.Command) { // --description, and --body (in that order of precedence). // Supports reading from stdin via --description=- or --body=- (useful when description // contains apostrophes or other characters that are hard to escape in shell). -// Returns the value and whether any flag was explicitly changed. -func getDescriptionFlag(cmd *cobra.Command) (string, bool) { - // --stdin is an alias for --body-file - +// Returns the value, whether any flag was explicitly changed, and any error. +func getDescriptionFlag(cmd *cobra.Command) (string, bool, error) { if stdinFlag, _ := cmd.Flags().GetBool("stdin"); stdinFlag { content, err := readBodyFile("-") if err != nil { - FatalError("reading from stdin: %v", err) + return "", false, HandleError("reading from stdin: %v", err) } - return content, true + return content, true, nil } bodyFileChanged := cmd.Flags().Changed("body-file") @@ -55,16 +54,14 @@ func getDescriptionFlag(cmd *cobra.Command) (string, bool) { bodyChanged := cmd.Flags().Changed("body") messageChanged := cmd.Flags().Changed("message") - // Check for conflicting file flags if bodyFileChanged && descFileChanged { bodyFile, _ := cmd.Flags().GetString("body-file") descFile, _ := cmd.Flags().GetString("description-file") if bodyFile != descFile { - FatalError("cannot specify both --body-file and --description-file with different values") + return "", false, HandleError("cannot specify both --body-file and --description-file with different values") } } - // File flags take precedence over string flags if bodyFileChanged || descFileChanged { var filePath string if bodyFileChanged { @@ -73,26 +70,22 @@ func getDescriptionFlag(cmd *cobra.Command) (string, bool) { filePath, _ = cmd.Flags().GetString("description-file") } - // Error if both file and string flags are specified if descChanged || bodyChanged || messageChanged { - FatalError("cannot specify both --body-file and --description/--body/--message") + return "", false, HandleError("cannot specify both --body-file and --description/--body/--message") } content, err := readBodyFile(filePath) if err != nil { - FatalError("reading body file: %v", err) + return "", false, HandleError("reading body file: %v", err) } - return content, true + return content, true, nil } - // Check if description, body, or message is "-" (read from stdin) - // This provides a convenient shorthand: --description=- instead of --body-file=- desc, _ := cmd.Flags().GetString("description") body, _ := cmd.Flags().GetString("body") message, _ := cmd.Flags().GetString("message") if desc == "-" || body == "-" || message == "-" { - // Error if multiple are set to different values values := make(map[string]string) if descChanged { values["--description"] = desc @@ -113,18 +106,17 @@ func getDescriptionFlag(cmd *cobra.Command) (string, bool) { for flag, val := range values { fmt.Fprintf(os.Stderr, " %s: %q\n", flag, val) } - os.Exit(1) + return "", false, SilentExit() } } } content, err := readBodyFile("-") if err != nil { - FatalError("reading from stdin: %v", err) + return "", false, HandleError("reading from stdin: %v", err) } - return content, true + return content, true, nil } - // Error if multiple description flags are specified with different values changedCount := 0 var firstVal string var firstFlag string @@ -142,7 +134,7 @@ func getDescriptionFlag(cmd *cobra.Command) (string, bool) { fmt.Fprintf(os.Stderr, "Error: cannot specify both %s and --body with different values\n", firstFlag) fmt.Fprintf(os.Stderr, " %s: %q\n", firstFlag, firstVal) fmt.Fprintf(os.Stderr, " --body: %q\n", body) - os.Exit(1) + return "", false, SilentExit() } } if messageChanged { @@ -154,43 +146,41 @@ func getDescriptionFlag(cmd *cobra.Command) (string, bool) { fmt.Fprintf(os.Stderr, "Error: cannot specify both %s and --message with different values\n", firstFlag) fmt.Fprintf(os.Stderr, " %s: %q\n", firstFlag, firstVal) fmt.Fprintf(os.Stderr, " --message: %q\n", message) - os.Exit(1) + return "", false, SilentExit() } } - // Return whichever was set (priority: description > body > message) if descChanged { - return desc, true + return desc, true, nil } if bodyChanged { - return body, true + return body, true, nil } if messageChanged { - return message, true + return message, true, nil } - return desc, descChanged + return desc, descChanged, nil } // getDesignFlag retrieves the design value from --design-file or --design. // Returns the value, whether any flag was explicitly changed, and any error. -func getDesignFlag(cmd *cobra.Command) (string, bool) { +func getDesignFlag(cmd *cobra.Command) (string, bool, error) { if cmd.Flags().Changed("design-file") { path, _ := cmd.Flags().GetString("design-file") content, err := readBodyFile(path) if err != nil { - FatalError("reading from stdin: %v", err) + return "", false, HandleError("reading from stdin: %v", err) } - - return content, true + return content, true, nil } if cmd.Flags().Changed("design") { v, _ := cmd.Flags().GetString("design") - return v, true + return v, true, nil } - return "", false + return "", false, nil } // readBodyFile reads the description content from a file. diff --git a/cmd/bd/flags_test.go b/cmd/bd/flags_test.go index 93f6882e1..14a21e1b1 100644 --- a/cmd/bd/flags_test.go +++ b/cmd/bd/flags_test.go @@ -147,7 +147,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -169,7 +172,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -204,7 +210,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -219,7 +228,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -234,7 +246,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -249,7 +264,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if changed { t.Error("expected changed=false when no flags set") } @@ -272,7 +290,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -303,7 +324,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -331,7 +355,10 @@ func TestGetDescriptionFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDescriptionFlag(cmd) + got, changed, err := getDescriptionFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -358,7 +385,10 @@ func TestGetDesignFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDesignFlag(cmd) + got, changed, err := getDesignFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -380,7 +410,10 @@ func TestGetDesignFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDesignFlag(cmd) + got, changed, err := getDesignFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -409,7 +442,10 @@ func TestGetDesignFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDesignFlag(cmd) + got, changed, err := getDesignFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if !changed { t.Error("expected changed=true") } @@ -424,7 +460,10 @@ func TestGetDesignFlag(t *testing.T) { t.Fatalf("failed to parse flags: %v", err) } - got, changed := getDesignFlag(cmd) + got, changed, err := getDesignFlag(cmd) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } if changed { t.Error("expected changed=false when no flags set") } diff --git a/cmd/bd/flatten.go b/cmd/bd/flatten.go index 78d4231d2..578b3a9b4 100644 --- a/cmd/bd/flatten.go +++ b/cmd/bd/flatten.go @@ -5,6 +5,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" ) @@ -38,7 +39,16 @@ Examples: bd flatten --dry-run # Preview: show commit count and disk usage bd flatten --force # Actually squash all history bd flatten --force --json # JSON output`, - Run: func(_ *cobra.Command, _ []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(_ *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("flatten") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if !flattenDryRun { CheckReadonly("flatten") } @@ -47,32 +57,28 @@ Examples: flattener, ok := storage.UnwrapStore(store).(storage.Flattener) if !ok { - FatalError("storage backend does not support flatten") + return HandleErrorRespectJSON("storage backend does not support flatten") } - // Get commit count and initial hash for reporting. - // Use store.Log() which works across both backends. logEntries, logErr := store.Log(ctx, 0) if logErr != nil { - FatalError("failed to read commit log: %v", logErr) + return HandleErrorRespectJSON("failed to read commit log: %v", logErr) } commitCount := len(logEntries) var initialHash string if commitCount > 0 { - initialHash = logEntries[commitCount-1].Hash // oldest is last + initialHash = logEntries[commitCount-1].Hash } if flattenDryRun { if jsonOutput { - result := map[string]interface{}{ + return outputJSON(map[string]interface{}{ "dry_run": true, "commit_count": commitCount, "initial_hash": initialHash, "would_flatten": commitCount > 1, - } - outputJSON(result) - return + }) } fmt.Printf("DRY RUN — Flatten preview\n\n") fmt.Printf(" Commits: %d\n", commitCount) @@ -83,24 +89,23 @@ Examples: fmt.Printf("\n Would squash %d commits into 1.\n", commitCount) fmt.Printf(" Run with --force to proceed.\n") } - return + return nil } if commitCount <= 1 { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "success": true, "message": "already flat", "commit_count": commitCount, }) - return } fmt.Println("Already flat (1 commit). Nothing to do.") - return + return nil } if !flattenForce { - FatalErrorWithHint( + return HandleErrorWithHintRespectJSON( fmt.Sprintf("would squash %d commits into 1 (irreversible)", commitCount), "Use --force to confirm or --dry-run to preview.") } @@ -110,10 +115,9 @@ Examples: } if err := flattener.Flatten(ctx); err != nil { - FatalError("flatten failed: %v", err) + return HandleErrorRespectJSON("flatten failed: %v", err) } - // Reclaim disk space from the now-orphaned old history. if gc, ok := storage.UnwrapStore(store).(storage.GarbageCollector); ok { if err := gc.DoltGC(ctx); err != nil { WarnError("dolt gc after flatten failed: %v", err) @@ -123,16 +127,16 @@ Examples: elapsed := time.Since(start) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "success": true, "commits_before": commitCount, "commits_after": 1, "elapsed_ms": elapsed.Milliseconds(), }) - return } fmt.Printf("āœ“ Flattened %d commits → 1\n", commitCount) fmt.Printf(" Time: %v\n", elapsed.Round(time.Millisecond)) + return nil }, } diff --git a/cmd/bd/formula.go b/cmd/bd/formula.go index af6f5ab71..f0751e800 100644 --- a/cmd/bd/formula.go +++ b/cmd/bd/formula.go @@ -12,6 +12,7 @@ import ( "github.com/BurntSushi/toml" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/formula" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -54,7 +55,9 @@ Examples: bd formula list --json bd formula list --type workflow bd formula list --type convoy`, - Run: runFormulaList, + SilenceUsage: true, + SilenceErrors: true, + RunE: runFormulaList, } // formulaShowCmd shows details of a specific formula. @@ -74,8 +77,10 @@ Examples: bd formula show shiny bd formula show rule-of-five bd formula show security-audit --json`, - Args: cobra.ExactArgs(1), - Run: runFormulaShow, + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runFormulaShow, } // FormulaListEntry represents a formula in the list output. @@ -88,30 +93,33 @@ type FormulaListEntry struct { Vars int `json:"vars"` } -func runFormulaList(cmd *cobra.Command, args []string) { +func runFormulaList(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("formula-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + typeFilter, _ := cmd.Flags().GetString("type") - // Get all search paths searchPaths := getFormulaSearchPaths() - // Track seen formulas (first occurrence wins) seen := make(map[string]bool) var entries []FormulaListEntry - // Scan each search path for _, dir := range searchPaths { formulas, err := scanFormulaDir(dir) if err != nil { - continue // Skip inaccessible directories + continue } for _, f := range formulas { if seen[f.Formula] { - continue // Skip shadowed formulas + continue } seen[f.Formula] = true - // Apply type filter if typeFilter != "" && string(f.Type) != typeFilter { continue } @@ -127,14 +135,12 @@ func runFormulaList(cmd *cobra.Command, args []string) { } } - // Sort by name sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name }) if jsonOutput { - outputJSON(entries) - return + return outputJSON(entries) } if len(entries) == 0 { @@ -143,18 +149,16 @@ func runFormulaList(cmd *cobra.Command, args []string) { for _, p := range searchPaths { fmt.Printf(" %s\n", p) } - return + return nil } fmt.Printf("šŸ“œ Formulas (%d found)\n\n", len(entries)) - // Group by type byType := make(map[string][]FormulaListEntry) for _, e := range entries { byType[e.Type] = append(byType[e.Type], e) } - // Print in type order: workflow, expansion, aspect, convoy typeOrder := []string{"workflow", "expansion", "aspect", "convoy"} for _, t := range typeOrder { typeEntries := byType[t] @@ -174,15 +178,21 @@ func runFormulaList(cmd *cobra.Command, args []string) { } fmt.Println() } + return nil } -func runFormulaShow(cmd *cobra.Command, args []string) { +func runFormulaShow(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("formula-show") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + name := args[0] - // Create parser with default search paths parser := formula.NewParser() - // Try to load the formula f, err := parser.LoadByName(name) if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) @@ -190,15 +200,13 @@ func runFormulaShow(cmd *cobra.Command, args []string) { for _, p := range getFormulaSearchPaths() { fmt.Fprintf(os.Stderr, " %s\n", p) } - os.Exit(1) + return SilentExit() } if jsonOutput { - outputJSON(f) - return + return outputJSON(f) } - // Print header typeIcon := getTypeIcon(string(f.Type)) fmt.Printf("\n%s %s\n", typeIcon, f.Formula) fmt.Printf(" Type: %s\n", f.Type) @@ -342,6 +350,7 @@ func runFormulaShow(cmd *cobra.Command, args []string) { } fmt.Println() + return nil } // getFormulaSearchPaths returns the formula search paths in priority order. @@ -481,7 +490,9 @@ Examples: bd formula convert --all # Convert all JSON formulas bd formula convert shiny --delete # Convert and remove JSON file bd formula convert shiny --stdout # Print TOML to stdout`, - Run: runFormulaConvert, + SilenceUsage: true, + SilenceErrors: true, + RunE: runFormulaConvert, } var ( @@ -490,27 +501,31 @@ var ( convertStdout bool ) -func runFormulaConvert(cmd *cobra.Command, args []string) { +func runFormulaConvert(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("formula-convert") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if convertAll { convertAllFormulas() - return + return nil } if len(args) == 0 { - FatalErrorWithHint("formula name or path required", "Usage: bd formula convert [--all]") + return HandleErrorWithHint("formula name or path required", "Usage: bd formula convert [--all]") } name := args[0] - // Determine the JSON file path var jsonPath string if strings.HasSuffix(name, formula.FormulaExtJSON) { - // Direct path provided jsonPath = name } else if strings.HasSuffix(name, formula.FormulaExtTOML) { - FatalError("%s is already a TOML file", name) + return HandleError("%s is already a TOML file", name) } else { - // Search for the formula in search paths jsonPath = findFormulaJSON(name) if jsonPath == "" { fmt.Fprintf(os.Stderr, "Error: JSON formula %q not found\n", name) @@ -518,34 +533,30 @@ func runFormulaConvert(cmd *cobra.Command, args []string) { for _, p := range getFormulaSearchPaths() { fmt.Fprintf(os.Stderr, " %s\n", p) } - os.Exit(1) + return SilentExit() } } - // Parse the JSON file parser := formula.NewParser() f, err := parser.ParseFile(jsonPath) if err != nil { - FatalError("parsing %s: %v", jsonPath, err) + return HandleError("parsing %s: %v", jsonPath, err) } - // Convert to TOML tomlData, err := formulaToTOML(f) if err != nil { - FatalError("converting to TOML: %v", err) + return HandleError("converting to TOML: %v", err) } if convertStdout { fmt.Print(string(tomlData)) - return + return nil } - // Determine output path tomlPath := strings.TrimSuffix(jsonPath, formula.FormulaExtJSON) + formula.FormulaExtTOML - // Write the TOML file if err := os.WriteFile(tomlPath, tomlData, 0600); err != nil { - FatalError("writing %s: %v", tomlPath, err) + return HandleError("writing %s: %v", tomlPath, err) } fmt.Printf("āœ“ Converted: %s\n", tomlPath) @@ -557,6 +568,7 @@ func runFormulaConvert(cmd *cobra.Command, args []string) { fmt.Printf("āœ“ Deleted: %s\n", jsonPath) } } + return nil } func convertAllFormulas() { diff --git a/cmd/bd/gate.go b/cmd/bd/gate.go index 9e74ffbdb..1318e668a 100644 --- a/cmd/bd/gate.go +++ b/cmd/bd/gate.go @@ -11,6 +11,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -49,36 +50,42 @@ var gateListCmd = &cobra.Command{ Long: `List all gate issues in the current beads database. By default, shows only open gates. Use --all to include closed gates.`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("gate-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + allFlag, _ := cmd.Flags().GetBool("all") limit, _ := cmd.Flags().GetInt("limit") - // Build filter for gate type issues gateType := types.IssueType("gate") filter := types.IssueFilter{ IssueType: &gateType, Limit: limit, } - // By default, exclude closed gates if !allFlag { filter.ExcludeStatus = []types.Status{types.StatusClosed} } ctx := rootCtx - // Direct mode issues, err := store.SearchIssues(ctx, "", filter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { - outputJSON(issues) - return + return outputJSON(issues) } displayGates(issues, allFlag) + return nil }, } @@ -168,49 +175,55 @@ When the gate closes, the waiter will receive a wake notification via 'bd gate w The waiter is typically the worker's address (e.g., "my-project/workers/agent-1"). This is used by 'bd done --phase-complete' to register for gate wake notifications.`, - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("gate add-waiter") + evt := metrics.NewCommandEvent("gate-add-waiter") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + gateID := args[0] waiter := args[1] ctx := rootCtx - // Get the gate issue var issue *types.Issue var err error issue, err = store.GetIssue(ctx, gateID) if err != nil { - FatalError("gate not found: %s", gateID) + return HandleError("gate not found: %s", gateID) } if issue.IssueType != "gate" { - FatalError("%s is not a gate issue (type=%s)", gateID, issue.IssueType) + return HandleError("%s is not a gate issue (type=%s)", gateID, issue.IssueType) } - // Check if waiter is already registered for _, w := range issue.Waiters { if w == waiter { fmt.Printf("Waiter already registered on gate %s\n", gateID) - return + return nil } } - // Add waiter to the waiters list newWaiters := append(issue.Waiters, waiter) - // Update the gate updates := map[string]interface{}{ "waiters": newWaiters, } if err := store.UpdateIssue(ctx, gateID, updates, actor); err != nil { - FatalError("updating gate: %v", err) + return HandleError("updating gate: %v", err) } commandDidWrite.Store(true) fmt.Printf("%s Added waiter to gate %s: %s\n", ui.RenderPass("āœ“"), gateID, waiter) + return nil }, } @@ -234,9 +247,18 @@ Examples: bd gate create --type=human --blocks bd-abc --reason="Need design review" bd gate create --type=timer --blocks bd-abc --timeout=2h bd gate create --type=gh:pr --blocks bd-abc --await-id=42`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("gate create") + evt := metrics.NewCommandEvent("gate-create") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + blocksID, _ := cmd.Flags().GetString("blocks") gateType, _ := cmd.Flags().GetString("type") reason, _ := cmd.Flags().GetString("reason") @@ -245,35 +267,30 @@ Examples: ctx := rootCtx - // Verify the target issue exists targetIssue, err := store.GetIssue(ctx, blocksID) if err != nil { - FatalError("issue not found: %s", blocksID) + return HandleErrorRespectJSON("issue not found: %s", blocksID) } - // Parse timeout if specified var timeout time.Duration if timeoutStr != "" { parsed, err := time.ParseDuration(timeoutStr) if err != nil { - FatalError("invalid timeout: %v", err) + return HandleErrorRespectJSON("invalid timeout: %v", err) } timeout = parsed } - // Build gate title title := fmt.Sprintf("Gate: %s", gateType) if awaitID != "" { title = fmt.Sprintf("Gate: %s %s", gateType, awaitID) } - // Build description desc := fmt.Sprintf("Ad-hoc gate blocking %s", targetIssue.ID) if reason != "" { desc = fmt.Sprintf("%s\n\nReason: %s", desc, reason) } - // Create the gate issue gate := &types.Issue{ Title: title, Description: desc, @@ -288,29 +305,25 @@ Examples: } if err := store.CreateIssue(ctx, gate, actor); err != nil { - FatalError("creating gate: %v", err) + return HandleErrorRespectJSON("creating gate: %v", err) } - // Add blocking dependency: target issue depends on gate dep := &types.Dependency{ IssueID: targetIssue.ID, DependsOnID: gate.ID, Type: types.DepBlocks, } if err := store.AddDependency(ctx, dep, actor); err != nil { - FatalError("adding blocking dependency: %v", err) + return HandleErrorRespectJSON("adding blocking dependency: %v", err) } - // CreateIssue commits the issue row. AddDependency writes to the - // working set and needs a follow-up commit. commitMsg := fmt.Sprintf("bd: create gate %s blocking %s", gate.ID, targetIssue.ID) if err := store.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) { - FatalError("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } if jsonOutput { - outputJSON(gate) - return + return outputJSON(gate) } fmt.Printf("%s Created gate %s (type: %s)\n", ui.RenderPass("āœ“"), ui.RenderID(gate.ID), gateType) @@ -322,6 +335,7 @@ Examples: fmt.Printf(" Timeout: %s\n", timeout) } fmt.Printf("\nResolve with: bd gate resolve %s\n", gate.ID) + return nil }, } @@ -332,30 +346,36 @@ var gateShowCmd = &cobra.Command{ Long: `Display details of a gate issue including its waiters. This is similar to 'bd show' but validates that the issue is a gate.`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("gate-show") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + gateID := args[0] ctx := rootCtx - // Get the gate issue var issue *types.Issue var err error issue, err = store.GetIssue(ctx, gateID) if err != nil { - FatalError("gate not found: %s", gateID) + return HandleErrorRespectJSON("gate not found: %s", gateID) } if issue.IssueType != "gate" { - FatalError("%s is not a gate issue (type=%s)", gateID, issue.IssueType) + return HandleErrorRespectJSON("%s is not a gate issue (type=%s)", gateID, issue.IssueType) } if jsonOutput { - outputJSON(issue) - return + return outputJSON(issue) } - // Display gate details statusSym := "ā—‹" if issue.Status == types.StatusClosed { statusSym = "ā—" @@ -379,6 +399,7 @@ This is similar to 'bd show' but validates that the issue is a gate.`, if issue.Description != "" { fmt.Printf(" Description: %s\n", issue.Description) } + return nil }, } @@ -390,30 +411,37 @@ var gateResolveCmd = &cobra.Command{ This is equivalent to 'bd close ' but with a more explicit name. Use --reason to provide context for why the gate was resolved.`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("gate resolve") + evt := metrics.NewCommandEvent("gate-resolve") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + gateID := args[0] reason, _ := cmd.Flags().GetString("reason") - // Verify it's a gate issue ctx := rootCtx var issue *types.Issue var err error issue, err = store.GetIssue(ctx, gateID) if err != nil { - FatalError("gate not found: %s", gateID) + return HandleError("gate not found: %s", gateID) } if issue.IssueType != "gate" { - FatalError("%s is not a gate issue (type=%s)", gateID, issue.IssueType) + return HandleError("%s is not a gate issue (type=%s)", gateID, issue.IssueType) } - // Close the gate if err := store.CloseIssue(ctx, gateID, reason, actor, ""); err != nil { - FatalError("closing gate: %v", err) + return HandleError("closing gate: %v", err) } commandDidWrite.Store(true) @@ -422,6 +450,7 @@ Use --reason to provide context for why the gate was resolved.`, if reason != "" { fmt.Printf(" Reason: %s\n", reason) } + return nil }, } @@ -463,15 +492,23 @@ Examples: bd gate check --type=bead # Check only cross-rig bead gates bd gate check --dry-run # Show what would happen without changes bd gate check --escalate # Escalate expired/failed gates`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("gate check") + evt := metrics.NewCommandEvent("gate-check") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + gateTypeFilter, _ := cmd.Flags().GetString("type") dryRun, _ := cmd.Flags().GetBool("dry-run") escalateFlag, _ := cmd.Flags().GetBool("escalate") limit, _ := cmd.Flags().GetInt("limit") - // Get open gates gateType := types.IssueType("gate") filter := types.IssueFilter{ IssueType: &gateType, @@ -485,10 +522,9 @@ Examples: gates, err = store.SearchIssues(ctx, "", filter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Filter by type if specified var filteredGates []*types.Issue for _, gate := range gates { if shouldCheckGate(gate, gateTypeFilter) { @@ -502,7 +538,7 @@ Examples: } else { fmt.Println("No open gates found.") } - return + return nil } // Results tracking @@ -593,15 +629,15 @@ Examples: len(results), resolvedCount, escalatedCount, errorCount) if jsonOutput { - summary := map[string]interface{}{ + return outputJSON(map[string]interface{}{ "checked": len(results), "resolved": resolvedCount, "escalated": escalatedCount, "errors": errorCount, "dry_run": dryRun, - } - outputJSON(summary) + }) } + return nil }, } diff --git a/cmd/bd/gate_discover.go b/cmd/bd/gate_discover.go index 606fab43d..e9d7b75df 100644 --- a/cmd/bd/gate_discover.go +++ b/cmd/bd/gate_discover.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -50,7 +51,9 @@ Examples: bd gate discover # Auto-discover run IDs for all matching gates bd gate discover --dry-run # Preview what would be matched (no updates) bd gate discover --branch main --limit 10 # Only match runs on 'main' branch`, - Run: runGateDiscover, + SilenceUsage: true, + SilenceErrors: true, + RunE: runGateDiscover, } func init() { @@ -62,9 +65,16 @@ func init() { gateCmd.AddCommand(gateDiscoverCmd) } -func runGateDiscover(cmd *cobra.Command, args []string) { +func runGateDiscover(cmd *cobra.Command, args []string) error { CheckReadonly("gate discover") + evt := metrics.NewCommandEvent("gate-discover") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + dryRun, _ := cmd.Flags().GetBool("dry-run") branchFilter, _ := cmd.Flags().GetString("branch") limit, _ := cmd.Flags().GetInt("limit") @@ -72,33 +82,30 @@ func runGateDiscover(cmd *cobra.Command, args []string) { ctx := rootCtx - // Step 1: Find open gh:run gates without await_id gates, err := findPendingGates() if err != nil { - FatalError("finding gates: %v", err) + return HandleError("finding gates: %v", err) } if len(gates) == 0 { fmt.Println("No pending gh:run gates found (all gates have numeric run IDs)") - return + return nil } fmt.Printf("%s Found %d gate(s) awaiting run ID discovery\n\n", ui.RenderAccent("šŸ”"), len(gates)) - // Get current branch if not specified if branchFilter == "" { branchFilter = getGitBranchForGateDiscovery() } - // Step 2: Query recent GitHub workflow runs runs, err := queryGitHubRuns(branchFilter, limit) if err != nil { - FatalError("querying GitHub runs: %v", err) + return HandleError("querying GitHub runs: %v", err) } if len(runs) == 0 { fmt.Println("No recent workflow runs found on GitHub") - return + return nil } fmt.Printf("Found %d recent workflow run(s) on branch '%s'\n\n", len(runs), branchFilter) @@ -142,6 +149,7 @@ func runGateDiscover(cmd *cobra.Command, args []string) { } else { fmt.Printf("Updated %d gate(s) with discovered run IDs.\n", matchCount) } + return nil } // isNumericRunID returns true if the string looks like a GitHub numeric run ID. diff --git a/cmd/bd/gate_test.go b/cmd/bd/gate_test.go index ba5782969..cee19b027 100644 --- a/cmd/bd/gate_test.go +++ b/cmd/bd/gate_test.go @@ -609,7 +609,9 @@ func TestGateCheck_GHRunWorkflowDiscoveryPersistence(t *testing.T) { } output := captureGateStdout(t, func() { - gateCheckCmd.Run(gateCheckCmd, nil) + if err := gateCheckCmd.RunE(gateCheckCmd, nil); err != nil { + t.Fatalf("gateCheckCmd.RunE: %v", err) + } }) if updateCalls != tt.wantUpdateCalls { diff --git a/cmd/bd/gc.go b/cmd/bd/gc.go index ab73c1c49..2540a55c7 100644 --- a/cmd/bd/gc.go +++ b/cmd/bd/gc.go @@ -5,6 +5,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" ) @@ -38,7 +39,16 @@ Examples: bd gc --skip-decay # Skip issue deletion, just compact+GC bd gc --skip-dolt # Skip Dolt GC, just decay+compact bd gc --force # Skip confirmation prompt`, - Run: func(cmd *cobra.Command, _ []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("gc") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if !gcDryRun { CheckReadonly("gc") } @@ -46,10 +56,9 @@ Examples: start := time.Now() if gcOlderThan < 0 { - FatalError("--older-than must be non-negative") + return HandleErrorRespectJSON("--older-than must be non-negative") } - // Phase tracking for summary type phaseResult struct { name string skipped bool @@ -57,7 +66,6 @@ Examples: } var results []phaseResult - // ── Phase 1: DECAY ── if gcSkipDecay { results = append(results, phaseResult{name: "Decay", skipped: true}) } else { @@ -75,7 +83,7 @@ Examples: closedIssues, err := store.SearchIssues(ctx, "", filter) if err != nil { - FatalError("searching closed issues: %v", err) + return HandleErrorRespectJSON("searching closed issues: %v", err) } var stats closedDeletionCandidateStats @@ -97,7 +105,7 @@ Examples: results = append(results, phaseResult{name: "Decay", detail: fmt.Sprintf("%d issues (dry-run)", len(closedIssues))}) } else { if !gcForce { - FatalErrorWithHint( + return HandleErrorWithHintRespectJSON( fmt.Sprintf("would delete %d closed issue(s) older than %d days", len(closedIssues), cutoffDays), "Use --force to confirm or --dry-run to preview.") } @@ -127,7 +135,6 @@ Examples: } } - // ── Phase 2: COMPACT (report only — actual squashing is bd flatten) ── if !jsonOutput { fmt.Println("Phase 2/3: Compact (Dolt commit history info)") } @@ -160,7 +167,6 @@ Examples: } } - // ── Phase 3: Dolt GC ── if gcSkipDolt { results = append(results, phaseResult{name: "Dolt GC", skipped: true}) } else { @@ -197,7 +203,6 @@ Examples: elapsed := time.Since(start) - // ── Summary ── if jsonOutput { summaryMap := make(map[string]interface{}) summaryMap["dry_run"] = gcDryRun @@ -214,8 +219,7 @@ Examples: phases = append(phases, p) } summaryMap["phases"] = phases - outputJSON(summaryMap) - return + return outputJSON(summaryMap) } mode := "āœ“ GC complete" @@ -230,6 +234,7 @@ Examples: fmt.Printf(" %s: %s\n", r.name, r.detail) } } + return nil }, } diff --git a/cmd/bd/github.go b/cmd/bd/github.go index 2e355b98e..39609f576 100644 --- a/cmd/bd/github.go +++ b/cmd/bd/github.go @@ -11,6 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/github" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/tracker" "github.com/steveyegge/beads/internal/types" ) @@ -49,23 +50,29 @@ By default, performs bidirectional sync: - Pushes local beads issues to GitHub Use --pull-only or --push-only to limit direction.`, - RunE: runGitHubSync, + SilenceUsage: true, + SilenceErrors: true, + RunE: runGitHubSync, } // githubStatusCmd displays GitHub configuration and sync status. var githubStatusCmd = &cobra.Command{ - Use: "status", - Short: "Show GitHub sync status", - Long: `Display current GitHub configuration and sync status.`, - RunE: runGitHubStatus, + Use: "status", + Short: "Show GitHub sync status", + Long: `Display current GitHub configuration and sync status.`, + SilenceUsage: true, + SilenceErrors: true, + RunE: runGitHubStatus, } // githubReposCmd lists accessible GitHub repositories. var githubReposCmd = &cobra.Command{ - Use: "repos", - Short: "List accessible GitHub repositories", - Long: `List GitHub repositories that the configured token has access to.`, - RunE: runGitHubRepos, + Use: "repos", + Short: "List accessible GitHub repositories", + Long: `List GitHub repositories that the configured token has access to.`, + SilenceUsage: true, + SilenceErrors: true, + RunE: runGitHubRepos, } var ( @@ -287,6 +294,13 @@ func getGitHubClient(config GitHubConfig) *github.Client { // runGitHubStatus implements the github status command. func runGitHubStatus(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("github-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + config := getGitHubConfig() out := cmd.OutOrStdout() @@ -312,9 +326,16 @@ func runGitHubStatus(cmd *cobra.Command, args []string) error { // runGitHubRepos implements the github repos command. func runGitHubRepos(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("github-repos") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + config := getGitHubConfig() if config.Token == "" { - return fmt.Errorf("github.token is not configured. Set via 'bd config set github.token ' or GITHUB_TOKEN environment variable") + return HandleError("github.token is not configured. Set via 'bd config set github.token ' or GITHUB_TOKEN environment variable") } out := cmd.OutOrStdout() @@ -323,7 +344,7 @@ func runGitHubRepos(cmd *cobra.Command, args []string) error { repos, err := client.ListRepositories(ctx) if err != nil { - return fmt.Errorf("failed to fetch repositories: %w", err) + return HandleError("failed to fetch repositories: %v", err) } _, _ = fmt.Fprintln(out, "Accessible GitHub Repositories") @@ -347,9 +368,16 @@ func runGitHubRepos(cmd *cobra.Command, args []string) error { // runGitHubSync implements the github sync command. // Uses the tracker.Engine for all sync operations. func runGitHubSync(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("github-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + config := getGitHubConfig() if err := validateGitHubConfig(config); err != nil { - return err + return HandleError("%v", err) } if !githubSyncDryRun { @@ -357,26 +385,24 @@ func runGitHubSync(cmd *cobra.Command, args []string) error { } if githubSyncPullOnly && githubSyncPushOnly { - return fmt.Errorf("cannot use both --pull-only and --push-only") + return HandleError("cannot use both --pull-only and --push-only") } - // Validate conflict flags conflictStrategy, err := getGitHubConflictStrategy(githubPreferLocal, githubPreferGitHub, githubPreferNewer) if err != nil { - return fmt.Errorf("%w (--prefer-local, --prefer-github, --prefer-newer)", err) + return HandleError("%v (--prefer-local, --prefer-github, --prefer-newer)", err) } if err := ensureStoreActive(); err != nil { - return fmt.Errorf("database not available: %w", err) + return HandleError("database not available: %v", err) } out := cmd.OutOrStdout() ctx := context.Background() - // Create and initialize the GitHub tracker gt := &github.Tracker{} if err := gt.Init(ctx, store); err != nil { - return fmt.Errorf("initializing GitHub tracker: %w", err) + return HandleError("initializing GitHub tracker: %v", err) } // Create the sync engine @@ -398,10 +424,9 @@ func runGitHubSync(cmd *cobra.Command, args []string) error { } if err := applySelectiveSyncFlags(cmd, &opts, push); err != nil { - return err + return HandleError("%v", err) } - // Map conflict resolution switch conflictStrategy { case GitHubConflictPreferLocal: opts.ConflictResolution = tracker.ConflictLocal @@ -416,11 +441,9 @@ func runGitHubSync(cmd *cobra.Command, args []string) error { _, _ = fmt.Fprintln(out) } - // Run sync result, err := engine.Sync(ctx, opts) if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err) - return err + return HandleError("%v", err) } // Output results diff --git a/cmd/bd/gitlab.go b/cmd/bd/gitlab.go index dbd34c8ef..e32f8f450 100644 --- a/cmd/bd/gitlab.go +++ b/cmd/bd/gitlab.go @@ -14,6 +14,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/gitlab" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/tracker" "github.com/steveyegge/beads/internal/types" ) @@ -52,23 +53,29 @@ By default, performs bidirectional sync: - Pushes local beads issues to GitLab Use --pull-only or --push-only to limit direction.`, - RunE: runGitLabSync, + SilenceUsage: true, + SilenceErrors: true, + RunE: runGitLabSync, } // gitlabStatusCmd displays GitLab configuration and sync status. var gitlabStatusCmd = &cobra.Command{ - Use: "status", - Short: "Show GitLab sync status", - Long: `Display current GitLab configuration and sync status.`, - RunE: runGitLabStatus, + Use: "status", + Short: "Show GitLab sync status", + Long: `Display current GitLab configuration and sync status.`, + SilenceUsage: true, + SilenceErrors: true, + RunE: runGitLabStatus, } // gitlabProjectsCmd lists accessible GitLab projects. var gitlabProjectsCmd = &cobra.Command{ - Use: "projects", - Short: "List accessible GitLab projects", - Long: `List GitLab projects that the configured token has access to.`, - RunE: runGitLabProjects, + Use: "projects", + Short: "List accessible GitLab projects", + Long: `List GitLab projects that the configured token has access to.`, + SilenceUsage: true, + SilenceErrors: true, + RunE: runGitLabProjects, } var ( @@ -317,6 +324,13 @@ func getGitLabClient(config GitLabConfig) *gitlab.Client { // runGitLabStatus implements the gitlab status command. func runGitLabStatus(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("gitlab-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + config := getGitLabConfig() out := cmd.OutOrStdout() @@ -370,9 +384,16 @@ func runGitLabStatus(cmd *cobra.Command, args []string) error { // runGitLabProjects implements the gitlab projects command. func runGitLabProjects(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("gitlab-projects") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + config := getGitLabConfig() if err := validateGitLabConfig(config); err != nil { - return err + return HandleError("%v", err) } out := cmd.OutOrStdout() @@ -381,7 +402,7 @@ func runGitLabProjects(cmd *cobra.Command, args []string) error { projects, err := client.ListProjects(ctx) if err != nil { - return fmt.Errorf("failed to fetch projects: %w", err) + return HandleError("failed to fetch projects: %v", err) } _, _ = fmt.Fprintln(out, "Accessible GitLab Projects") @@ -404,9 +425,16 @@ func runGitLabProjects(cmd *cobra.Command, args []string) error { // runGitLabSync implements the gitlab sync command. // Uses the tracker.Engine for all sync operations. func runGitLabSync(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("gitlab-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + config := getGitLabConfig() if err := validateGitLabConfig(config); err != nil { - return err + return HandleError("%v", err) } if !gitlabSyncDryRun { @@ -414,26 +442,24 @@ func runGitLabSync(cmd *cobra.Command, args []string) error { } if gitlabSyncPullOnly && gitlabSyncPushOnly { - return fmt.Errorf("cannot use both --pull-only and --push-only") + return HandleError("cannot use both --pull-only and --push-only") } - // Validate conflict flags conflictStrategy, err := getConflictStrategy(gitlabPreferLocal, gitlabPreferGitLab, gitlabPreferNewer) if err != nil { - return fmt.Errorf("%w (--prefer-local, --prefer-gitlab, --prefer-newer)", err) + return HandleError("%v (--prefer-local, --prefer-gitlab, --prefer-newer)", err) } if err := ensureStoreActive(); err != nil { - return fmt.Errorf("database not available: %w", err) + return HandleError("database not available: %v", err) } out := cmd.OutOrStdout() ctx := context.Background() - // Create and initialize the GitLab tracker gt := &gitlab.Tracker{} if err := gt.Init(ctx, store); err != nil { - return fmt.Errorf("initializing GitLab tracker: %w", err) + return HandleError("initializing GitLab tracker: %v", err) } // Apply CLI filter overrides (take precedence over config defaults) @@ -474,10 +500,9 @@ func runGitLabSync(cmd *cobra.Command, args []string) error { } if err := applySelectiveSyncFlags(cmd, &opts, push); err != nil { - return err + return HandleError("%v", err) } - // Map conflict resolution switch conflictStrategy { case ConflictStrategyPreferLocal: opts.ConflictResolution = tracker.ConflictLocal @@ -492,11 +517,9 @@ func runGitLabSync(cmd *cobra.Command, args []string) error { _, _ = fmt.Fprintln(out) } - // Run sync result, err := engine.Sync(ctx, opts) if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err) - return err + return HandleError("%v", err) } // Output results diff --git a/cmd/bd/global_identity_integration_test.go b/cmd/bd/global_identity_integration_test.go index 9689a3a33..31e2c5b0b 100644 --- a/cmd/bd/global_identity_integration_test.go +++ b/cmd/bd/global_identity_integration_test.go @@ -58,6 +58,8 @@ func TestGlobalDBIdentityCheck(t *testing.T) { "BEADS_DOLT_SERVER_PORT=" + strconv.Itoa(containerPort), "BEADS_DOLT_AUTO_START=0", "BEADS_TEST_MODE=1", + "BD_DISABLE_METRICS=1", + "BD_DISABLE_EVENT_FLUSH=1", "GIT_TERMINAL_PROMPT=0", "GIT_ASKPASS=", "SSH_ASKPASS=", diff --git a/cmd/bd/graph.go b/cmd/bd/graph.go index c9a7e289d..d707b0cf3 100644 --- a/cmd/bd/graph.go +++ b/cmd/bd/graph.go @@ -3,11 +3,11 @@ package main import ( "context" "fmt" - "os" "sort" "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -70,48 +70,52 @@ Examples: bd graph --dot issue-id | dot -Tpng > graph.png # PNG via Graphviz bd graph --html issue-id > graph.html # Interactive browser view bd graph --all --html > all.html # All issues, interactive`, - Args: cobra.RangeArgs(0, 1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.RangeArgs(0, 1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("graph") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // Validate args if graphAll && len(args) > 0 { - FatalError("cannot specify issue ID with --all flag") + return HandleErrorRespectJSON("cannot specify issue ID with --all flag") } if !graphAll && len(args) == 0 { - FatalErrorWithHint("issue ID required", "Use --all for all open issues") + return HandleErrorWithHintRespectJSON("issue ID required", "Use --all for all open issues") } if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } - // Handle --all flag: show graph for all open issues if graphAll { subgraphs, err := loadAllGraphSubgraphs(ctx, store) if err != nil { - FatalError("loading all issues: %v", err) + return HandleErrorRespectJSON("loading all issues: %v", err) } if len(subgraphs) == 0 { fmt.Println("No open issues found") - return + return nil } if jsonOutput { - outputJSON(subgraphs) - return + return outputJSON(subgraphs) } - // HTML: merge all components into one graph for a single document if graphHTML { merged := mergeSubgraphsForHTML(subgraphs) layout := computeLayout(merged) renderGraphHTML(layout, merged) - return + return nil } - // Render all subgraphs for i, subgraph := range subgraphs { layout := computeLayout(subgraph) if graphDOT { @@ -127,34 +131,29 @@ Examples: fmt.Println(strings.Repeat("─", 60)) } } - return + return nil } - // Single issue mode issueID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalError("issue '%s' not found", args[0]) + return HandleErrorRespectJSON("issue '%s' not found", args[0]) } - // Load the subgraph subgraph, err := loadGraphSubgraph(ctx, store, issueID) if err != nil { - FatalError("loading graph: %v", err) + return HandleErrorRespectJSON("loading graph: %v", err) } - // Compute layout layout := computeLayout(subgraph) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "root": subgraph.Root, "issues": subgraph.Issues, "layout": layout, }) - return } - // Render graph in selected format if graphDOT { renderGraphDOT(layout, subgraph) } else if graphHTML { @@ -166,6 +165,7 @@ Examples: } else { renderGraphVisual(layout, subgraph) } + return nil }, } @@ -175,7 +175,16 @@ var graphCheckCmd = &cobra.Command{ Long: `Check the dependency graph for cycles, orphans, and other integrity issues. Returns exit code 0 if the graph is clean, 1 if issues are found.`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("graph-check") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx type GraphCheckResult struct { @@ -188,10 +197,9 @@ Returns exit code 0 if the graph is clean, 1 if issues are found.`, result := GraphCheckResult{Clean: true} - // Detect cycles cycles, err := store.DetectCycles(ctx) if err != nil { - FatalErrorRespectJSON("cycle detection failed: %v", err) + return HandleErrorRespectJSON("cycle detection failed: %v", err) } for _, cycle := range cycles { @@ -208,14 +216,15 @@ Returns exit code 0 if the graph is clean, 1 if issues are found.`, } if jsonOutput { - outputJSON(result) - if !result.Clean { - os.Exit(1) + if err := outputJSON(result); err != nil { + return err } - return + if !result.Clean { + return SilentExit() + } + return nil } - // Human-readable output if result.Clean { fmt.Printf("\n%s Graph integrity check passed\n\n", ui.RenderPass("āœ“")) } else { @@ -235,8 +244,9 @@ Returns exit code 0 if the graph is clean, 1 if issues are found.`, fmt.Println() if !result.Clean { - os.Exit(1) + return SilentExit() } + return nil }, } diff --git a/cmd/bd/graph_apply.go b/cmd/bd/graph_apply.go index 588ae9dde..563b51fa9 100644 --- a/cmd/bd/graph_apply.go +++ b/cmd/bd/graph_apply.go @@ -253,15 +253,10 @@ func loadEmbeddedCustomTypes() []string { return config.GetCustomTypesFromYAML() } -// createIssuesFromGraph handles `bd create --graph `. -// When dryRun is true, the plan is parsed and validated but no writes occur; -// a preview is emitted to stdout (JSON when jsonOutput is set, otherwise -// human-readable). Unknown plan/node/edge fields are reported to stderr in -// both modes so schema gaps are visible before any writes happen. (GH#3367) -func createIssuesFromGraph(planFile string, dryRun bool, opts GraphApplyOptions) { +func createIssuesFromGraph(planFile string, dryRun bool, opts GraphApplyOptions) error { data, err := os.ReadFile(planFile) // #nosec G304 -- user-provided path is intentional if err != nil { - FatalError("reading graph plan: %v", err) + return HandleErrorRespectJSON("reading graph plan: %v", err) } if unknown := detectUnknownGraphFields(data); len(unknown) > 0 { @@ -270,42 +265,38 @@ func createIssuesFromGraph(planFile string, dryRun bool, opts GraphApplyOptions) var plan GraphApplyPlan if err := json.Unmarshal(data, &plan); err != nil { - FatalError("parsing graph plan: %v", err) + return HandleErrorRespectJSON("parsing graph plan: %v", err) } if err := validateGraphApplyPlan(&plan, loadEmbeddedCustomTypes()); err != nil { - FatalError("invalid graph plan: %v", err) + return HandleErrorRespectJSON("invalid graph plan: %v", err) } if dryRun { - emitGraphApplyDryRun(&plan) - return + return emitGraphApplyDryRun(&plan) } result, err := executeGraphApply(rootCtx, &plan, opts) if err != nil { - FatalError("graph create: %v", err) + return HandleErrorRespectJSON("graph create: %v", err) } if jsonOutput { - outputJSON(result) - } else { - fmt.Printf("Created %d issues\n", len(result.IDs)) - keys := make([]string, 0, len(result.IDs)) - for key := range result.IDs { - keys = append(keys, key) - } - sort.Strings(keys) - for _, key := range keys { - fmt.Printf(" %s -> %s\n", key, result.IDs[key]) - } + return outputJSON(result) } + fmt.Printf("Created %d issues\n", len(result.IDs)) + keys := make([]string, 0, len(result.IDs)) + for key := range result.IDs { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + fmt.Printf(" %s -> %s\n", key, result.IDs[key]) + } + return nil } -// emitGraphApplyDryRun prints what `bd create --graph` would do without -// performing any writes. Mirrors the JSON-vs-human split of the live path. -// (GH#3367) -func emitGraphApplyDryRun(plan *GraphApplyPlan) { +func emitGraphApplyDryRun(plan *GraphApplyPlan) error { parentDeps := 0 rows := make([]GraphApplyDryRunRow, 0, len(plan.Nodes)) for _, node := range plan.Nodes { @@ -340,8 +331,7 @@ func emitGraphApplyDryRun(plan *GraphApplyPlan) { } if jsonOutput { - outputJSON(preview) - return + return outputJSON(preview) } fmt.Printf("Dry run: would create %d issue(s) and %d edge(s) (%d parent-child link(s))\n", @@ -357,6 +347,7 @@ func emitGraphApplyDryRun(plan *GraphApplyPlan) { } fmt.Printf(" %s [%s] P%d %q%s\n", row.Key, row.Type, row.Priority, row.Title, parent) } + return nil } func validateGraphApplyPlan(plan *GraphApplyPlan, customTypes []string) error { diff --git a/cmd/bd/history.go b/cmd/bd/history.go index 64a91daa3..ea050fcb8 100644 --- a/cmd/bd/history.go +++ b/cmd/bd/history.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -21,51 +22,51 @@ where the issue was modified. Examples: bd history bd-123 # Show all history for issue bd-123 bd history bd-123 --limit 5 # Show last 5 changes`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("history") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx issueID := args[0] - // Get issue history history, err := store.History(ctx, issueID) if err != nil { - FatalErrorRespectJSON("failed to get history: %v", err) + return HandleErrorRespectJSON("failed to get history: %v", err) } - // Empty-history short-circuit handles both formats: --json gets [] - // (so consumers piping to jq don't break), human format gets prose. if len(history) == 0 { if jsonOutput { - outputJSON(history) - return + return outputJSON(history) } fmt.Printf("No history found for issue %s\n", issueID) - return + return nil } - // Apply limit only to non-empty history; slicing an empty slice is a no-op. if historyLimit > 0 && historyLimit < len(history) { history = history[:historyLimit] } if jsonOutput { - outputJSON(history) - return + return outputJSON(history) } - // Display history in human-readable format fmt.Printf("\n%s History for %s (%d entries)\n\n", ui.RenderAccent("šŸ“œ"), issueID, len(history)) for i, entry := range history { - // Commit info line fmt.Printf("%s %s\n", ui.RenderMuted(entry.CommitHash[:8]), ui.RenderMuted(entry.CommitDate.Format("2006-01-02 15:04:05"))) fmt.Printf(" Author: %s\n", entry.Committer) if entry.Issue != nil { - // Show issue state at this commit statusIcon := ui.GetStatusIcon(string(entry.Issue.Status)) fmt.Printf(" %s %s: %s [P%d - %s]\n", statusIcon, @@ -75,12 +76,12 @@ Examples: entry.Issue.Status) } - // Separator between entries if i < len(history)-1 { fmt.Println() } } fmt.Println() + return nil }, } diff --git a/cmd/bd/hooks.go b/cmd/bd/hooks.go index 94bd60b7c..ab407e081 100644 --- a/cmd/bd/hooks.go +++ b/cmd/bd/hooks.go @@ -14,6 +14,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/debug" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -641,14 +642,23 @@ Installed hooks: - pre-push: Run chained hooks before push - post-checkout: Run chained hooks after branch checkout - prepare-commit-msg: Add agent identity trailers (for orchestrator agents)`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("hooks-install") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + force, _ := cmd.Flags().GetBool("force") shared, _ := cmd.Flags().GetBool("shared") chain, _ := cmd.Flags().GetBool("chain") beadsHooks, _ := cmd.Flags().GetBool("beads") if err := installHooksWithOptions(managedHookNames, force, shared, chain, beadsHooks); err != nil { - FatalErrorRespectJSON("installing hooks: %v", err) + return HandleErrorRespectJSON("installing hooks: %v", err) } if jsonOutput { @@ -680,16 +690,26 @@ Installed hooks: fmt.Printf(" - %s\n", hookName) } } + return nil }, } var hooksUninstallCmd = &cobra.Command{ - Use: "uninstall", - Short: "Uninstall bd git hooks", - Long: `Remove bd git hooks from .git/hooks/ directory.`, - Run: func(cmd *cobra.Command, args []string) { + Use: "uninstall", + Short: "Uninstall bd git hooks", + Long: `Remove bd git hooks from .git/hooks/ directory.`, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("hooks-uninstall") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := uninstallHooks(); err != nil { - FatalErrorRespectJSON("uninstalling hooks: %v", err) + return HandleErrorRespectJSON("uninstalling hooks: %v", err) } if jsonOutput { @@ -702,14 +722,24 @@ var hooksUninstallCmd = &cobra.Command{ } else { fmt.Println("āœ“ Git hooks uninstalled successfully") } + return nil }, } var hooksListCmd = &cobra.Command{ - Use: "list", - Short: "List installed git hooks status", - Long: `Show the status of bd git hooks (installed, outdated, missing).`, - Run: func(cmd *cobra.Command, args []string) { + Use: "list", + Short: "List installed git hooks status", + Long: `Show the status of bd git hooks (installed, outdated, missing).`, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("hooks-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + statuses := CheckGitHooks() if jsonOutput { @@ -733,6 +763,7 @@ var hooksListCmd = &cobra.Command{ } } } + return nil }, } @@ -1645,13 +1676,17 @@ Supported hooks: The thin shim pattern ensures hook logic is always in sync with the installed bd version - upgrading bd automatically updates hook behavior.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - // Disable terminal color probing to prevent OSC 11 escape sequence leaks (GH#1303). - // Our shell shims set BD_GIT_HOOK=1 before invoking bd, but third-party hook - // runners (lefthook, husky, etc.) call 'bd hooks run' directly without it. - // By this point ui.init() has already run, so we must also reset styles - // to suppress ANSI output — the env var alone only helps if set before process start. + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("hooks-run") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + _ = os.Setenv("BD_GIT_HOOK", "1") ui.DisableColors() @@ -1671,10 +1706,13 @@ installed bd version - upgrading bd automatically updates hook behavior.`, case "prepare-commit-msg": exitCode = runPrepareCommitMsgHook(hookArgs) default: - FatalError("unknown hook: %s", hookName) + return HandleError("unknown hook: %s", hookName) } - os.Exit(exitCode) + if exitCode != 0 { + return &exitError{Code: exitCode} + } + return nil }, } diff --git a/cmd/bd/human.go b/cmd/bd/human.go index 7f8278598..3be8e773d 100644 --- a/cmd/bd/human.go +++ b/cmd/bd/human.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -28,6 +29,13 @@ SUBCOMMANDS: human dismiss Dismiss a human-needed bead permanently human stats Show summary statistics for human-needed beads`, Run: func(cmd *cobra.Command, args []string) { + evt := metrics.NewCommandEvent("human") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + fmt.Printf("\n%s\n", ui.RenderBold("bd - Essential Commands for Humans")) fmt.Printf("For all 70+ commands: bd --help\n\n") @@ -99,12 +107,20 @@ Examples: bd human list bd human list --status=open bd human list --json`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("human-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + status, _ := cmd.Flags().GetString("status") ctx := rootCtx - // Build filter for human-labeled issues filter := types.IssueFilter{ Labels: []string{"human"}, } @@ -114,37 +130,36 @@ Examples: filter.Status = &s } - // Direct mode if err := ensureStoreActive(); err != nil { - FatalErrorRespectJSON("listing human beads: %v", err) + return HandleErrorRespectJSON("listing human beads: %v", err) } var err error issues, err := store.SearchIssues(ctx, "", filter) if err != nil { - FatalErrorRespectJSON("listing human beads: %v", err) + return HandleErrorRespectJSON("listing human beads: %v", err) } if jsonOutput { - // Get labels for JSON output issueIDs := make([]string, len(issues)) for i, issue := range issues { issueIDs[i] = issue.ID } - labelsMap, _ := store.GetLabelsForIssues(ctx, issueIDs) // Best effort: labels are supplementary display info + labelsMap, _ := store.GetLabelsForIssues(ctx, issueIDs) for _, issue := range issues { issue.Labels = labelsMap[issue.ID] } data, err := json.MarshalIndent(issues, "", " ") if err != nil { - FatalErrorRespectJSON("encoding JSON: %v", err) + return HandleErrorRespectJSON("encoding JSON: %v", err) } fmt.Println(string(data)) - return + return nil } printHumanList(issues) + return nil }, } @@ -178,12 +193,21 @@ The response is added as a comment and the issue is closed with reason "Responde Examples: bd human respond bd-123 --response "Use OAuth2 for authentication" bd human respond bd-123 -r "Approved, proceed with implementation"`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("human-respond") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + response, _ := cmd.Flags().GetString("response") if response == "" { - FatalErrorRespectJSON("--response is required") + return HandleErrorRespectJSON("--response is required") } CheckReadonly("human respond") @@ -194,13 +218,13 @@ Examples: // Resolve partial ID and get issue result, err := resolveAndGetIssueForMutation(ctx, store, issueID) if err != nil { - FatalErrorRespectJSON("resolving issue ID %s: %v", issueID, err) + return HandleErrorRespectJSON("resolving issue ID %s: %v", issueID, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } - FatalErrorRespectJSON("issue not found: %s", issueID) + return HandleErrorRespectJSON("issue not found: %s", issueID) } defer result.Close() @@ -208,13 +232,11 @@ Examples: issue := result.Issue targetStore := result.Store - // Check if issue is already closed if issue.Status == "closed" { - FatalErrorRespectJSON("issue %s is already closed", resolvedID) + return HandleErrorRespectJSON("issue %s is already closed", resolvedID) } - // Fetch labels (not populated by GetIssue) and check for 'human' label - labelsMap, _ := targetStore.GetLabelsForIssues(ctx, []string{resolvedID}) // Best effort: labels are supplementary display info + labelsMap, _ := targetStore.GetLabelsForIssues(ctx, []string{resolvedID}) hasHumanLabel := false for _, label := range labelsMap[resolvedID] { if label == "human" { @@ -227,19 +249,18 @@ Examples: fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", resolvedID) } - // Add comment using AddIssueComment (issueID, author, text) commentText := fmt.Sprintf("Response: %s", response) _, err = targetStore.AddIssueComment(ctx, resolvedID, actor, commentText) if err != nil { - FatalErrorRespectJSON("adding comment: %v", err) + return HandleErrorRespectJSON("adding comment: %v", err) } - // Close the issue using CloseIssue (id, reason, actor, session) if err := targetStore.CloseIssue(ctx, resolvedID, "Responded", actor, ""); err != nil { - FatalErrorRespectJSON("closing bead: %v", err) + return HandleErrorRespectJSON("closing bead: %v", err) } fmt.Printf("%s Bead %s closed with response.\n", ui.RenderPass("āœ”"), resolvedID) + return nil }, } @@ -254,8 +275,17 @@ The issue is closed with a "Dismissed" reason and optional note. Examples: bd human dismiss bd-123 bd human dismiss bd-123 --reason "No longer applicable"`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("human-dismiss") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + reason, _ := cmd.Flags().GetString("reason") CheckReadonly("human dismiss") @@ -266,13 +296,13 @@ Examples: // Resolve partial ID and get issue result, err := resolveAndGetIssueForMutation(ctx, store, issueID) if err != nil { - FatalErrorRespectJSON("resolving issue ID %s: %v", issueID, err) + return HandleErrorRespectJSON("resolving issue ID %s: %v", issueID, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } - FatalErrorRespectJSON("issue not found: %s", issueID) + return HandleErrorRespectJSON("issue not found: %s", issueID) } defer result.Close() @@ -280,13 +310,11 @@ Examples: issue := result.Issue targetStore := result.Store - // Check if issue is already closed if issue.Status == "closed" { - FatalErrorRespectJSON("issue %s is already closed", resolvedID) + return HandleErrorRespectJSON("issue %s is already closed", resolvedID) } - // Fetch labels (not populated by GetIssue) and check for 'human' label - labelsMap, _ := targetStore.GetLabelsForIssues(ctx, []string{resolvedID}) // Best effort: labels are supplementary display info + labelsMap, _ := targetStore.GetLabelsForIssues(ctx, []string{resolvedID}) hasHumanLabel := false for _, label := range labelsMap[resolvedID] { if label == "human" { @@ -299,18 +327,17 @@ Examples: fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", resolvedID) } - // Build close reason closeReason := "Dismissed" if reason != "" { closeReason = fmt.Sprintf("Dismissed: %s", reason) } - // Close the issue if err := targetStore.CloseIssue(ctx, resolvedID, closeReason, actor, ""); err != nil { - FatalErrorRespectJSON("closing bead: %v", err) + return HandleErrorRespectJSON("closing bead: %v", err) } fmt.Printf("%s Bead %s dismissed.\n", ui.RenderPass("āœ”"), resolvedID) + return nil }, } @@ -325,25 +352,34 @@ and dismissed beads. Example: bd human stats`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("human-stats") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx filter := types.IssueFilter{ Labels: []string{"human"}, } - // Direct mode if err := ensureStoreActive(); err != nil { - FatalErrorRespectJSON("getting human bead stats: %v", err) + return HandleErrorRespectJSON("getting human bead stats: %v", err) } var err error issues, err := store.SearchIssues(ctx, "", filter) if err != nil { - FatalErrorRespectJSON("getting human bead stats: %v", err) + return HandleErrorRespectJSON("getting human bead stats: %v", err) } printHumanStats(issues) + return nil }, } diff --git a/cmd/bd/import.go b/cmd/bd/import.go index 941a9147e..516bb8583 100644 --- a/cmd/bd/import.go +++ b/cmd/bd/import.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" ) @@ -81,8 +82,10 @@ EXAMPLES: bd import --dedup # Skip issues with duplicate titles bd import --allow-stale old.jsonl # Restore an older snapshot (overwrites newer local rows) bd import --json # Structured output with created and skipped IDs`, - GroupID: "sync", - RunE: runImport, + GroupID: "sync", + SilenceUsage: true, + SilenceErrors: true, + RunE: runImport, } var ( @@ -101,6 +104,23 @@ func init() { } func runImport(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("import") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + + if err := runImportInner(args); err != nil { + if _, isExit := err.(*exitError); isExit { + return err + } + return HandleErrorRespectJSON("%v", err) + } + return nil +} + +func runImportInner(args []string) error { ctx := rootCtx if importInput != "" && len(args) > 0 { return fmt.Errorf("use either --input or a positional file, not both") @@ -136,8 +156,7 @@ func runImport(cmd *cobra.Command, args []string) error { } if info.Size() == 0 { if jsonOutput { - outputJSON(importResultJSON{Source: jsonlPath}) - return nil + return outputJSON(importResultJSON{Source: jsonlPath}) } fmt.Fprintf(os.Stderr, "Empty file: %s\n", jsonlPath) return nil @@ -240,8 +259,7 @@ func runImportFromReader(ctx context.Context, r io.Reader, source string) error result.Memories = len(memories) result.Skipped = dedupHits if jsonOutput { - outputJSON(result) - return nil + return outputJSON(result) } fmt.Fprintf(os.Stderr, "Would import %d issues and %d memories from %s", len(issues), len(memories), source) if dedupHits > 0 { @@ -294,8 +312,7 @@ func runImportFromReader(ctx context.Context, r io.Reader, source string) error } if jsonOutput { - outputJSON(result) - return nil + return outputJSON(result) } fmt.Fprintf(os.Stderr, "Imported %d issues", result.Created) diff --git a/cmd/bd/info.go b/cmd/bd/info.go index a0254432b..bc8f6f028 100644 --- a/cmd/bd/info.go +++ b/cmd/bd/info.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" ) @@ -28,21 +29,27 @@ Examples: bd info --whats-new bd info --whats-new --json bd info --thanks`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("info") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + schemaFlag, _ := cmd.Flags().GetBool("schema") whatsNewFlag, _ := cmd.Flags().GetBool("whats-new") thanksFlag, _ := cmd.Flags().GetBool("thanks") - // Handle --thanks flag if thanksFlag { printThanksPage() - return + return nil } - // Handle --whats-new flag if whatsNewFlag { - showWhatsNew() - return + return showWhatsNew() } // Get database path (absolute) @@ -126,13 +133,10 @@ Examples: } } - // JSON output if jsonOutput { - outputJSON(info) - return + return outputJSON(info) } - // Human-readable output fmt.Println("\nBeads Database Information") fmt.Println("===========================") fmt.Printf("Database: %s\n", absDBPath) @@ -160,13 +164,13 @@ Examples: } } - // Check git hooks status hookStatuses := CheckGitHooks() if warning := FormatHookWarnings(hookStatuses); warning != "" { fmt.Printf("\n%s\n", warning) } fmt.Println() + return nil }, } @@ -1377,16 +1381,14 @@ var versionChanges = []VersionChange{ }, } -// showWhatsNew displays agent-relevant changes from recent versions -func showWhatsNew() { - currentVersion := Version // from version.go +func showWhatsNew() error { + currentVersion := Version if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "current_version": currentVersion, "recent_changes": versionChanges, }) - return } // Human-readable output @@ -1411,6 +1413,7 @@ func showWhatsNew() { fmt.Println("šŸ’” Tip: Use `bd info --whats-new --json` for machine-readable output") fmt.Println() + return nil } func init() { diff --git a/cmd/bd/init.go b/cmd/bd/init.go index cc541c4e8..189f60aef 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -21,6 +21,7 @@ import ( "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/doltserver" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" "github.com/steveyegge/beads/internal/storage/schema" @@ -31,9 +32,11 @@ import ( ) var initCmd = &cobra.Command{ - Use: "init", - GroupID: "setup", - Short: "Initialize bd in the current directory", + Use: "init", + GroupID: "setup", + SilenceUsage: true, + SilenceErrors: true, + Short: "Initialize bd in the current directory", Long: `Initialize bd in the current directory by creating a .beads/ directory and Dolt database. Optionally specify a custom issue prefix. @@ -67,7 +70,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): • Auto-export left at default (disabled) • --contributor and --team flags are rejected (wizards require interaction) Also auto-detected when stdin is not a terminal or CI=true is set.`, - Run: func(cmd *cobra.Command, _ []string) { + RunE: func(cmd *cobra.Command, _ []string) (retErr error) { prefix, _ := cmd.Flags().GetString("prefix") quiet, _ := cmd.Flags().GetBool("quiet") contributor, _ := cmd.Flags().GetBool("contributor") @@ -121,52 +124,60 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if os.Getenv("BEADS_DOLT_PROXIED_SERVER") == "1" { initProxiedServer = true } + + initEvt := metrics.NewCommandEvent("init-" + resolveInitDoltMode(initProxiedServer, sharedServer, initServerMode)) + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(initEvt) + } + }() + if initProxiedServer { // Proxied-server mode has no local Dolt init lifecycle yet. When it // is implemented, that path must mark any local .dolt/ it creates or // acknowledges with doltserver.MarkDoltDirCompatible. - FatalError("--proxied-server is not yet implemented") + return fmt.Errorf("--proxied-server is not yet implemented") } if initProxiedServer && initServerMode { - FatalError("--server and --proxied-server are mutually exclusive") + return fmt.Errorf("--server and --proxied-server are mutually exclusive") } if initProxiedServer { if sharedServer || externalServer || serverHost != "" || serverPort != 0 || serverSocket != "" || serverUser != "" { - FatalError("--proxied-server cannot be combined with --shared-server, --external, or any --server-* flag") + return fmt.Errorf("--proxied-server cannot be combined with --shared-server, --external, or any --server-* flag") } } if serverConfigPath != "" { if !initProxiedServer { - FatalError("--proxied-server-config-path requires --proxied-server") + return fmt.Errorf("--proxied-server-config-path requires --proxied-server") } if !filepath.IsAbs(serverConfigPath) { - FatalError("--proxied-server-config-path must be an absolute path, got %q", serverConfigPath) + return fmt.Errorf("--proxied-server-config-path must be an absolute path, got %q", serverConfigPath) } if err := validateProxiedServerConfig(serverConfigPath); err != nil { - FatalError("--proxied-server-config-path %v", err) + return fmt.Errorf("--proxied-server-config-path %v", err) } } if serverLogPath != "" { if !initProxiedServer { - FatalError("--proxied-server-log-path requires --proxied-server") + return fmt.Errorf("--proxied-server-log-path requires --proxied-server") } if !filepath.IsAbs(serverLogPath) { - FatalError("--proxied-server-log-path must be an absolute path, got %q", serverLogPath) + return fmt.Errorf("--proxied-server-log-path must be an absolute path, got %q", serverLogPath) } if err := validateProxiedServerLogPath(serverLogPath); err != nil { - FatalError("--proxied-server-log-path %v", err) + return fmt.Errorf("--proxied-server-log-path %v", err) } } if serverRootPath != "" { if !initProxiedServer { - FatalError("--proxied-server-root-path requires --proxied-server") + return fmt.Errorf("--proxied-server-root-path requires --proxied-server") } if !filepath.IsAbs(serverRootPath) { - FatalError("--proxied-server-root-path must be an absolute path, got %q", serverRootPath) + return fmt.Errorf("--proxied-server-root-path must be an absolute path, got %q", serverRootPath) } if err := validateProxiedServerRootPath(serverRootPath); err != nil { - FatalError("--proxied-server-root-path %v", err) + return fmt.Errorf("--proxied-server-root-path %v", err) } } @@ -174,13 +185,13 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): externalUser != "" || externalTLS || externalTLSCertPath != "" || externalTLSKeyPath != "" || externalKeepAlive != 0 if externalProvided && !initProxiedServer { - FatalError("--proxied-server-external-* flags require --proxied-server") + return fmt.Errorf("--proxied-server-external-* flags require --proxied-server") } if externalProvided && serverConfigPath != "" { - FatalError("--proxied-server-external-* flags cannot be combined with --proxied-server-config-path (external mode has no managed dolt sql-server to configure)") + return fmt.Errorf("--proxied-server-external-* flags cannot be combined with --proxied-server-config-path (external mode has no managed dolt sql-server to configure)") } if externalProvided && debugMode { - FatalError("--debug cannot be combined with --proxied-server-external-* (debug applies to the managed dolt sql-server only)") + return fmt.Errorf("--debug cannot be combined with --proxied-server-external-* (debug applies to the managed dolt sql-server only)") } var externalConfig *configfile.ExternalDoltConfig if externalProvided { @@ -195,7 +206,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): KeepAlivePeriod: externalKeepAlive, } if err := cfg.Validate(); err != nil { - FatalError("--proxied-server-external-*: %v", err) + return fmt.Errorf("--proxied-server-external-*: %v", err) } externalConfig = &cfg } @@ -211,15 +222,15 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fmt.Fprintf(os.Stderr, "To import issues from an existing JSONL export:\n") fmt.Fprintf(os.Stderr, " bd init --from-jsonl\n\n") fmt.Fprintf(os.Stderr, "See: https://github.com/gastownhall/beads/blob/main/docs/DOLT.md\n") - os.Exit(1) + return fmt.Errorf("--backend=sqlite is no longer supported") } else if backendFlag != "" && backendFlag != "dolt" { - FatalError("unknown backend %q: only \"dolt\" is supported", backendFlag) + return fmt.Errorf("unknown backend %q: only \"dolt\" is supported", backendFlag) } // Validate --database format early, before any side effects. if database != "" { if err := dolt.ValidateDatabaseName(database); err != nil { - FatalError("invalid database name %q: %v", database, err) + return fmt.Errorf("invalid database name %q: %v", database, err) } } @@ -233,16 +244,16 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): case "maintainer", "contributor": // valid default: - FatalError("invalid --role %q: must be \"maintainer\" or \"contributor\"", roleFlag) + return fmt.Errorf("invalid --role %q: must be \"maintainer\" or \"contributor\"", roleFlag) } } // Fail-fast: contributor/team wizards require interaction if nonInteractive && contributor { - FatalError("--contributor requires interactive prompts and cannot be used with --non-interactive") + return fmt.Errorf("--contributor requires interactive prompts and cannot be used with --non-interactive") } if nonInteractive && team { - FatalError("--team requires interactive prompts and cannot be used with --non-interactive") + return fmt.Errorf("--team requires interactive prompts and cannot be used with --non-interactive") } // Dolt is the only supported backend @@ -272,7 +283,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } if initProxiedServer { - runInitProxiedServer(cmd, rootCtx, initProxiedServerInput{ + return runInitProxiedServer(cmd, rootCtx, initProxiedServerInput{ prefix: prefix, database: database, roleFlag: roleFlag, @@ -293,7 +304,6 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fromJSONL: fromJSONL, nonInteractive: nonInteractive, }) - return } // Propagate --shared-server flag to env so that IsSharedServerMode(), @@ -331,7 +341,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // serverMode is set above — otherwise !usesSQLServer() always returns // true and incorrectly rejects server-mode names (GH#3231). if database != "" && strings.ContainsRune(database, '-') && !usesSQLServer() { - FatalError("database name %q contains hyphens which are invalid in embedded mode; use underscores instead (e.g. %q)", + return fmt.Errorf("database name %q contains hyphens which are invalid in embedded mode; use underscores instead (e.g. %q)", database, sanitizeDBName(database)) } @@ -356,7 +366,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if configPort != "" || envPort != "" { detail = fmt.Sprintf("dolt.host (%s) and dolt.port are", effectiveHost) } - FatalError("%s set via %s but server mode is not enabled.\n"+ + return fmt.Errorf("%s set via %s but server mode is not enabled.\n"+ " Embedded mode has no host/port — these settings require server mode.\n"+ " Set dolt.mode: server in %s or pass --server to bd init.", detail, hostSource, config.UserConfigYamlPath()) @@ -386,19 +396,19 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): existing := existingWorkspaceDBName() if cmd.Flags().Changed("database") { if initIfMissingDatabaseMismatch(existing, database) { - FatalError("workspace already initialized as database %q, but --database %q was requested.\nRemove --database (or pass a matching value) to reuse the existing workspace.", existing, database) + return fmt.Errorf("workspace already initialized as database %q, but --database %q was requested.\nRemove --database (or pass a matching value) to reuse the existing workspace", existing, database) } } else if cmd.Flags().Changed("prefix") { if initIfMissingPrefixMismatch(existing, prefix) { - FatalError("workspace already initialized as database %q, but --prefix %q was requested.\nRemove --prefix (or pass a matching value) to reuse the existing workspace.", existing, prefix) + return fmt.Errorf("workspace already initialized as database %q, but --prefix %q was requested.\nRemove --prefix (or pass a matching value) to reuse the existing workspace", existing, prefix) } } if !quiet { fmt.Fprintln(os.Stderr, "Skipping init: workspace already initialized.") } - return + return nil } - FatalError("%v", err) + return fmt.Errorf("%v", err) } } @@ -421,7 +431,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): expected := fmt.Sprintf("destroy %d issues", count) if strings.TrimSpace(scanner.Text()) != expected { fmt.Fprintf(os.Stderr, "\nAborted. Database was NOT modified.\n") - os.Exit(ExitLocalExistsRefused) + return &exitError{Code: ExitLocalExistsRefused} } } else { // Non-interactive (piped input, AI agent, etc.) @@ -438,7 +448,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fmt.Fprintf(os.Stderr, "Refusing to destroy %d issues in non-interactive mode.\n", count) fmt.Fprintf(os.Stderr, " See 'bd help init-safety' for the required --destroy-token format.\n") fmt.Fprintf(os.Stderr, " Or export issue records first: bd export > issue-export.jsonl\n") - os.Exit(ExitDestroyTokenMissing) + return &exitError{Code: ExitDestroyTokenMissing} } } } @@ -447,7 +457,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // Handle stealth mode setup if stealth { if err := setupStealthMode(!quiet); err != nil { - FatalError("setting up stealth mode: %v", err) + return fmt.Errorf("setting up stealth mode: %v", err) } // In stealth mode, skip git hooks installation @@ -474,7 +484,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // Auto-detect from directory name cwd, err := os.Getwd() if err != nil { - FatalError("failed to get current directory: %v", err) + return fmt.Errorf("failed to get current directory: %v", err) } prefix = filepath.Base(cwd) } @@ -523,7 +533,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): }) if earlyDecision.Action == ActionRefuseDivergence || earlyDecision.Action == ActionRequireDestroyToken { fmt.Fprintf(os.Stderr, "\n%s\n\n", earlyDecision.UserMessage) - os.Exit(earlyDecision.ExitCode) + return &exitError{Code: earlyDecision.ExitCode} } } } @@ -558,7 +568,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // For worktrees, .beads should always be in the main repository root cwd, err := os.Getwd() if err != nil { - FatalError("failed to get current directory: %v", err) + return fmt.Errorf("failed to get current directory: %v", err) } hasExplicitBeadsDir := os.Getenv("BEADS_DIR") != "" @@ -574,7 +584,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fmt.Fprintf(os.Stderr, "Error: cannot initialize bd inside a .beads directory\n") fmt.Fprintf(os.Stderr, "Current directory: %s\n", cwd) fmt.Fprintf(os.Stderr, "Please run 'bd init' from outside the .beads directory.\n") - os.Exit(1) + return &exitError{Code: 1} } initDBDir := filepath.Dir(initDBPath) @@ -604,19 +614,19 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if err := os.MkdirAll(beadsDir, config.BeadsDirPerm); err != nil { if os.IsPermission(err) { if runtime.GOOS == "windows" { - FatalError("failed to create .beads directory: %v\n\n"+ + return fmt.Errorf("failed to create .beads directory: %v\n\n"+ "Windows Controlled Folder Access may be blocking bd.exe.\n"+ "To fix: Open Windows Security > Virus & threat protection >\n"+ "Ransomware protection > Allow an app through Controlled folder access\n"+ "and add bd.exe (typically %%USERPROFILE%%\\go\\bin\\bd.exe).", err) } else { - FatalError("failed to create .beads directory: %v\n\n"+ + return fmt.Errorf("failed to create .beads directory: %v\n\n"+ "Permission denied. Check directory ownership and permissions:\n"+ " ls -la %s\n"+ " chmod 755 %s", err, filepath.Dir(beadsDir), filepath.Dir(beadsDir)) } } - FatalError("failed to create .beads directory: %v", err) + return fmt.Errorf("failed to create .beads directory: %v", err) } // Fix permissions on pre-existing .beads/ directories that may @@ -699,7 +709,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if !isGitRepo() && !hasExplicitBeadsDir { gitInitCmd := exec.Command("git", "init") if output, err := gitInitCmd.CombinedOutput(); err != nil { - FatalError("failed to initialize git repository: %v\n%s", err, output) + return fmt.Errorf("failed to initialize git repository: %v\n%s", err, output) } // Clear cached git context so subsequent operations (e.g. hook // installation) see the newly-created repository (GH#2899). @@ -716,7 +726,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // so skip this to avoid leaving an empty .beads/dolt/ artifact (GH#2903). if initServerMode { if err := os.MkdirAll(initDBPath, config.BeadsDirPerm); err != nil { - FatalError("failed to create storage directory %s: %v", initDBPath, err) + return fmt.Errorf("failed to create storage directory %s: %v", initDBPath, err) } // Linux btrfs: disable compression on the dolt data dir to avoid // kworker thrashing on the append-only write path. Best-effort; a @@ -766,7 +776,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fmt.Fprintf(os.Stderr, "Error: directory name %q produces an invalid database name %q.\n", dirName, dbName) fmt.Fprintf(os.Stderr, "Re-run with a valid prefix: bd init --prefix \n") fmt.Fprintf(os.Stderr, "(Database names must start with a letter or underscore and contain only letters, digits, underscores, or hyphens.)\n") - os.Exit(1) + return &exitError{Code: 1} } } } @@ -818,7 +828,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): switch decision.Action { case ActionRefuseDivergence, ActionRequireDestroyToken: fmt.Fprintf(os.Stderr, "\n%s\n\n", decision.UserMessage) - os.Exit(decision.ExitCode) + return &exitError{Code: decision.ExitCode} case ActionBootstrap: syncFromRemote = true case ActionProceedWithDivergence: @@ -833,7 +843,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): scanner.Scan() if strings.TrimSpace(scanner.Text()) != expected { fmt.Fprintf(os.Stderr, "\nAborted. See 'bd help init-safety' for details.\n") - os.Exit(ExitDestroyTokenMissing) + return &exitError{Code: ExitDestroyTokenMissing} } } // Race-safety: re-verify the remote state hasn't @@ -843,7 +853,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // overwriting their fresh work. if gitOriginHasDoltDataRef() != remoteHasDoltData { fmt.Fprintf(os.Stderr, "\nAborted: remote state changed during confirmation. Re-run to re-verify intent.\n") - os.Exit(ExitRemoteDivergenceRefused) + return &exitError{Code: ExitRemoteDivergenceRefused} } // Proceed without bootstrap; remote will be overwritten on next push. // syncFromRemote stays false. @@ -865,7 +875,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } else { fmt.Fprintf(os.Stderr, "Error: failed to clone remote %q: %v\n", syncURL, err) fmt.Fprintf(os.Stderr, "Hint: verify the URL is reachable and any credentials are valid, or omit --remote to initialize a fresh local database.\n") - os.Exit(1) + return &exitError{Code: 1} } } else { bootstrappedFromRemote = true @@ -922,7 +932,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): initLock, err := acquireEmbeddedLock(beadsDir, initServerMode || initProxiedServer) if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return &exitError{Code: 1} } defer initLock.Unlock() @@ -945,7 +955,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if state == nil || !state.Running { if _, startErr := doltserver.Start(sharedDir); startErr != nil { fmt.Fprintf(os.Stderr, "Error: failed to start shared Dolt server: %v\n", startErr) - os.Exit(1) + return &exitError{Code: 1} } if !quiet { fmt.Printf(" %s Shared Dolt server started\n", ui.RenderPass("āœ“")) @@ -1010,7 +1020,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): os.Exit(1) } fmt.Fprintf(os.Stderr, "Error: failed to open Dolt store: %v\n", err) - os.Exit(1) + return &exitError{Code: 1} } // Initialize global database schema and config in shared-server mode. @@ -1043,7 +1053,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): issuePrefix := strings.ReplaceAll(prefix, ".", "_") if err := store.SetConfig(ctx, "issue_prefix", issuePrefix); err != nil { _ = store.Close() - FatalError("failed to set issue prefix: %v", err) + return fmt.Errorf("failed to set issue prefix: %v", err) } } @@ -1205,7 +1215,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // Dolt, not JSONL, is the cross-machine sync path. Plain git // origins are valid here: the first push creates refs/dolt/data. if err := persistInitSyncRemote(beadsDir, initRemote, syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin); err != nil { - FatalError("failed to persist sync.remote to config.yaml: %v", err) + return fmt.Errorf("failed to persist sync.remote to config.yaml: %v", err) } // Enable shared server mode if requested via flag OR env var (GH#2377). @@ -1260,12 +1270,12 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): localJSONLPath := configuredImportJSONLPath(beadsDir) if _, statErr := os.Stat(localJSONLPath); os.IsNotExist(statErr) { _ = store.Close() - FatalError("--from-jsonl specified but %s does not exist", localJSONLPath) + return fmt.Errorf("--from-jsonl specified but %s does not exist", localJSONLPath) } issueCount, importErr := importFromLocalJSONL(ctx, store, localJSONLPath) if importErr != nil { _ = store.Close() - FatalError("failed to import from JSONL: %v", importErr) + return fmt.Errorf("failed to import from JSONL: %v", importErr) } if !quiet { fmt.Printf(" Imported %d issues from %s\n", issueCount, localJSONLPath) @@ -1283,7 +1293,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if isCanceled(err) { fmt.Fprintln(os.Stderr, "Setup canceled.") _ = store.Close() - exitCanceled() + return errCanceled() } // Non-fatal: warn but continue with default behavior if !quiet { @@ -1321,9 +1331,9 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } _ = store.Close() if canceled { - exitCanceled() + return errCanceled() } - FatalError("running contributor wizard: %v", err) + return fmt.Errorf("running contributor wizard: %v", err) } // Contributor setup must also pin role detection to contributor. @@ -1344,9 +1354,9 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } _ = store.Close() if canceled { - exitCanceled() + return errCanceled() } - FatalError("running team wizard: %v", err) + return fmt.Errorf("running team wizard: %v", err) } } @@ -1419,7 +1429,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): if err != nil { if isCanceled(err) { fmt.Fprintln(os.Stderr, "Setup canceled.") - exitCanceled() + return errCanceled() } } if shouldExclude { @@ -1438,7 +1448,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): wantExport, err := promptAutoExport() if err != nil && isCanceled(err) { fmt.Fprintln(os.Stderr, "Setup canceled.") - exitCanceled() + return errCanceled() } if wantExport { if err := config.SetYamlConfig("export.auto", "true"); err != nil { @@ -1691,6 +1701,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): fmt.Printf("\nRun %s to see details and fix these issues.\n\n", ui.RenderAccent("bd doctor --fix")) } } + return nil }, } @@ -2457,3 +2468,17 @@ func initGlobalDatabaseConfig(ctx context.Context, projectCfg *dolt.Config, quie fmt.Printf(" %s Global database schema initialized\n", ui.RenderPass("āœ“")) } } + +func resolveInitDoltMode(proxiedFlag, sharedFlag, serverFlag bool) string { + if proxiedFlag || os.Getenv("BEADS_DOLT_PROXIED_SERVER") == "1" { + return "proxied-server" + } + shared := os.Getenv("BEADS_DOLT_SHARED_SERVER") + if sharedFlag || shared == "1" || strings.EqualFold(shared, "true") { + return "shared-server" + } + if serverFlag || os.Getenv("BEADS_DOLT_SERVER_MODE") == "1" { + return "server" + } + return "embedded" +} diff --git a/cmd/bd/init_embedded_test.go b/cmd/bd/init_embedded_test.go index 631d81b3c..22f34a9da 100644 --- a/cmd/bd/init_embedded_test.go +++ b/cmd/bd/init_embedded_test.go @@ -89,7 +89,13 @@ func bdEnv(dir string) []string { } env = append(env, e) } - return append(env, "HOME="+dir, "BEADS_DOLT_AUTO_START=0", "BEADS_NO_DAEMON=1") + return append(env, + "HOME="+dir, + "BEADS_DOLT_AUTO_START=0", + "BEADS_NO_DAEMON=1", + "BD_DISABLE_METRICS=1", + "BD_DISABLE_EVENT_FLUSH=1", + ) } func isEmbeddedLockOutput(out string) bool { diff --git a/cmd/bd/init_metrics_test.go b/cmd/bd/init_metrics_test.go new file mode 100644 index 000000000..d60498936 --- /dev/null +++ b/cmd/bd/init_metrics_test.go @@ -0,0 +1,371 @@ +//go:build cgo + +package main + +import ( + "bytes" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/metrics" +) + +type metricsEvent struct { + AppName string `json:"app_name"` + Events []struct { + Name string `json:"name"` + Attributes []struct { + Key string `json:"key"` + Value string `json:"value"` + } `json:"attributes"` + } `json:"events"` +} + +func readInitEvent(t *testing.T, home, expectedCommand string) metricsEvent { + t.Helper() + dir := filepath.Join(home, ".beads", "eventsData") + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("read eventsData dir: %v", err) + } + var evtqs []string + for _, e := range entries { + if strings.HasSuffix(e.Name(), ".evtq") { + evtqs = append(evtqs, e.Name()) + } + } + if len(evtqs) == 0 { + t.Fatalf("expected at least 1 .evtq file, got 0") + } + for _, name := range evtqs { + body, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Fatalf("read evtq %s: %v", name, err) + } + var got metricsEvent + if err := json.Unmarshal(body, &got); err != nil { + t.Fatalf("unmarshal evtq %s: %v\n%s", name, err, body) + } + if got.commandAttr() == expectedCommand { + return got + } + } + t.Fatalf("no .evtq with command=%s among %v", expectedCommand, evtqs) + return metricsEvent{} +} + +func (e metricsEvent) commandAttr() string { + if len(e.Events) == 0 { + return "" + } + for _, a := range e.Events[0].Attributes { + if a.Key == "command" { + return a.Value + } + } + return "" +} + +func (e metricsEvent) attr(key string) (string, bool) { + if len(e.Events) == 0 { + return "", false + } + for _, a := range e.Events[0].Attributes { + if a.Key == key { + return a.Value, true + } + } + return "", false +} + +func metricsTestEnv(home string, extra ...string) []string { + base := bdEnv(home) + out := make([]string, 0, len(base)+len(extra)+1) + for _, e := range base { + if strings.HasPrefix(e, "BD_DISABLE_METRICS=") { + continue + } + out = append(out, e) + } + out = append(out, "BD_DISABLE_EVENT_FLUSH=1") + return append(out, extra...) +} + +func runBdInitForMetrics(t *testing.T, home string, args ...string) { + t.Helper() + bd := buildEmbeddedBD(t) + repo, err := testTempDir("bd-metrics-repo-*") + if err != nil { + t.Fatalf("temp repo: %v", err) + } + initGitRepoAt(t, repo) + + full := append([]string{"init", "--non-interactive", "--quiet"}, args...) + cmd := exec.Command(bd, full...) + cmd.Dir = repo + cmd.Env = metricsTestEnv(home) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + _ = cmd.Run() +} + +func TestInitMetricsEmittedPerDoltMode(t *testing.T) { + cases := []struct { + name string + extraArgs []string + extraEnv []string + expectedCommand string + }{ + { + name: "embedded_default", + expectedCommand: "init-embedded", + }, + { + name: "server_via_flag", + extraArgs: []string{"--server"}, + expectedCommand: "init-server", + }, + { + name: "shared_server_via_flag", + extraArgs: []string{"--shared-server"}, + expectedCommand: "init-shared-server", + }, + { + name: "proxied_server_via_flag", + extraArgs: []string{"--proxied-server"}, + expectedCommand: "init-proxied-server", + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + home, err := testTempDir("bd-metrics-home-*") + if err != nil { + t.Fatalf("temp home: %v", err) + } + runBdInitForMetrics(t, home, tc.extraArgs...) + evt := readInitEvent(t, home, tc.expectedCommand) + + if evt.AppName != "beads" { + t.Errorf("app_name = %q, want %q", evt.AppName, "beads") + } + if len(evt.Events) != 1 { + t.Fatalf("events len = %d, want 1", len(evt.Events)) + } + if evt.Events[0].Name != "cli_command" { + t.Errorf("event name = %q, want %q", evt.Events[0].Name, "cli_command") + } + if got, _ := evt.attr("command"); got != tc.expectedCommand { + t.Errorf("command attr = %q, want %q", got, tc.expectedCommand) + } + if got, ok := evt.attr("dolt_mode"); ok { + t.Errorf("dolt_mode attr should no longer be set, got %q", got) + } + }) + } +} + +func writeUserMetricsDisabled(t *testing.T, home string, disabled bool) { + t.Helper() + dir := filepath.Join(home, ".config", "bd") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("mkdir user config: %v", err) + } + body := []byte("metrics.disabled: false\n") + if disabled { + body = []byte("metrics.disabled: true\n") + } + if err := os.WriteFile(filepath.Join(dir, "config.yaml"), body, 0o644); err != nil { + t.Fatalf("write user config: %v", err) + } +} + +func evtqFilesIn(t *testing.T, home string) []string { + t.Helper() + dir := filepath.Join(home, ".beads", "eventsData") + entries, err := os.ReadDir(dir) + if err != nil { + return nil + } + var out []string + for _, e := range entries { + if strings.HasSuffix(e.Name(), ".evtq") { + out = append(out, e.Name()) + } + } + return out +} + +func runBdInitWithEnv(t *testing.T, home string, extraEnv []string) { + t.Helper() + bd := buildEmbeddedBD(t) + repo, err := testTempDir("bd-metrics-repo-*") + if err != nil { + t.Fatalf("temp repo: %v", err) + } + initGitRepoAt(t, repo) + + cmd := exec.Command(bd, "init", "--non-interactive", "--quiet") + cmd.Dir = repo + cmd.Env = metricsTestEnv(home, extraEnv...) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + _ = cmd.Run() +} + +func TestInitMetricsEnvConfigPrecedence(t *testing.T) { + cases := []struct { + name string + setUserConfig bool + configDisabled bool + envVar []string + wantEvtq bool + }{ + { + name: "default_no_config_no_env", + wantEvtq: true, + }, + { + name: "config_disabled_env_unset", + setUserConfig: true, + configDisabled: true, + wantEvtq: false, + }, + { + name: "config_enabled_env_disables", + setUserConfig: true, + configDisabled: false, + envVar: []string{"BD_DISABLE_METRICS=1"}, + wantEvtq: false, + }, + { + name: "config_disabled_env_overrides_to_enabled", + setUserConfig: true, + configDisabled: true, + envVar: []string{"BD_DISABLE_METRICS=0"}, + wantEvtq: true, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + home, err := testTempDir("bd-metrics-prec-*") + if err != nil { + t.Fatalf("temp home: %v", err) + } + if tc.setUserConfig { + writeUserMetricsDisabled(t, home, tc.configDisabled) + } + + runBdInitWithEnv(t, home, tc.envVar) + + files := evtqFilesIn(t, home) + if tc.wantEvtq && len(files) == 0 { + t.Errorf("expected an .evtq file, got none") + } + if !tc.wantEvtq && len(files) > 0 { + t.Errorf("expected no .evtq files, got %v", files) + } + }) + } +} + +func TestInitBootstrapsUserConfigWhenMissing(t *testing.T) { + home, err := testTempDir("bd-bootstrap-fresh-*") + if err != nil { + t.Fatalf("temp home: %v", err) + } + + runBdInitWithEnv(t, home, nil) + + path := filepath.Join(home, ".config", "bd", "config.yaml") + body, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + got := string(body) + if !strings.Contains(got, metrics.DefaultEndpoint) { + t.Errorf("user config missing metrics endpoint.\nfile: %q", got) + } + if !strings.Contains(got, "endpoint:") { + t.Errorf("user config missing endpoint key.\nfile: %q", got) + } +} + +func TestInitPreservesExistingMetricsValuesAndFillsMissingLeaves(t *testing.T) { + home, err := testTempDir("bd-bootstrap-existing-*") + if err != nil { + t.Fatalf("temp home: %v", err) + } + + dir := filepath.Join(home, ".config", "bd") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + path := filepath.Join(dir, "config.yaml") + original := []byte("metrics:\n endpoint: https://example.invalid/custom\n") + if err := os.WriteFile(path, original, 0o644); err != nil { + t.Fatalf("seed: %v", err) + } + + runBdInitWithEnv(t, home, nil) + + got, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read: %v", err) + } + body := string(got) + if !strings.Contains(body, "https://example.invalid/custom") { + t.Errorf("user-set endpoint was clobbered.\nfile: %q", body) + } + if !strings.Contains(body, "disabled:") { + t.Errorf("missing metrics.disabled was not filled in.\nfile: %q", body) + } +} + +func TestInitMetricsDisabledSuppresses(t *testing.T) { + bd := buildEmbeddedBD(t) + home, err := testTempDir("bd-metrics-disabled-home-*") + if err != nil { + t.Fatalf("temp home: %v", err) + } + repo, err := testTempDir("bd-metrics-disabled-repo-*") + if err != nil { + t.Fatalf("temp repo: %v", err) + } + initGitRepoAt(t, repo) + + cmd := exec.Command(bd, "init", "--non-interactive", "--quiet") + cmd.Dir = repo + env := append([]string{}, bdEnv(home)...) + env = append(env, "BD_DISABLE_METRICS=1") + cmd.Env = env + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + t.Fatalf("bd init failed: %v\n%s\n%s", err, stdout.String(), stderr.String()) + } + + dir := filepath.Join(home, ".beads", "eventsData") + if _, err := os.Stat(dir); err == nil { + entries, _ := os.ReadDir(dir) + var evtqs []string + for _, e := range entries { + if strings.HasSuffix(e.Name(), ".evtq") { + evtqs = append(evtqs, e.Name()) + } + } + if len(evtqs) > 0 { + t.Errorf("BD_DISABLE_METRICS=1 still produced .evtq files: %v", evtqs) + } + } +} diff --git a/cmd/bd/init_safety_help.go b/cmd/bd/init_safety_help.go index d90eef798..b0ca80079 100644 --- a/cmd/bd/init_safety_help.go +++ b/cmd/bd/init_safety_help.go @@ -4,6 +4,8 @@ import ( "fmt" "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/metrics" ) // initSafetyHelpCmd documents the init flag surface and the destroy-token @@ -77,6 +79,13 @@ RECOVERY playbooks for each exit code. `, Run: func(cmd *cobra.Command, _ []string) { + evt := metrics.NewCommandEvent("init-safety") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + fmt.Print(cmd.Long) }, } diff --git a/cmd/bd/init_safety_test.go b/cmd/bd/init_safety_test.go index 5efa887d1..855995638 100644 --- a/cmd/bd/init_safety_test.go +++ b/cmd/bd/init_safety_test.go @@ -288,13 +288,11 @@ func TestLocalOnlyInitSkipsConfigureButPersistsExplicitRemote(t *testing.T) { if err := persistInitSyncRemote(beadsDir, remote, remote, false, true, false); err != nil { t.Fatalf("persistInitSyncRemote failed: %v", err) } - data, err := os.ReadFile(configPath) - if err != nil { - t.Fatalf("read config: %v", err) - } - if !strings.Contains(string(data), `sync.remote: "git+ssh://git@example.com/org/project.git"`) && - !strings.Contains(string(data), "sync.remote: git+ssh://git@example.com/org/project.git") { - t.Fatalf("sync.remote was not persisted under local-only config:\n%s", data) + got := config.GetStringFromDir(beadsDir, "sync.remote") + if got != remote { + data, _ := os.ReadFile(configPath) + t.Fatalf("sync.remote was not persisted under local-only config: got %q, want %q\nfile:\n%s", + got, remote, data) } } diff --git a/cmd/bd/jira.go b/cmd/bd/jira.go index c4fbc2d7c..53080faf6 100644 --- a/cmd/bd/jira.go +++ b/cmd/bd/jira.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/jira" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/tracker" "github.com/steveyegge/beads/internal/types" ) @@ -60,7 +61,9 @@ Examples: bd jira sync --push --create-only # Push new issues only bd jira sync --dry-run # Preview without changes bd jira sync --prefer-local # Bidirectional, local wins`, - Run: runJiraSync, + SilenceUsage: true, + SilenceErrors: true, + RunE: runJiraSync, } var jiraStatusCmd = &cobra.Command{ @@ -71,7 +74,9 @@ var jiraStatusCmd = &cobra.Command{ - Configuration status - Number of issues with Jira links - Issues pending push (no external_ref)`, - Run: runJiraStatus, + SilenceUsage: true, + SilenceErrors: true, + RunE: runJiraStatus, } func init() { @@ -90,7 +95,14 @@ func init() { rootCmd.AddCommand(jiraCmd) } -func runJiraSync(cmd *cobra.Command, args []string) { +func runJiraSync(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("jira-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + pull, _ := cmd.Flags().GetBool("pull") push, _ := cmd.Flags().GetBool("push") dryRun, _ := cmd.Flags().GetBool("dry-run") @@ -104,38 +116,34 @@ func runJiraSync(cmd *cobra.Command, args []string) { } if preferLocal && preferJira { - FatalError("cannot use both --prefer-local and --prefer-jira") + return HandleErrorRespectJSON("cannot use both --prefer-local and --prefer-jira") } if err := ensureStoreActive(); err != nil { - FatalError("database not available: %v", err) + return HandleErrorRespectJSON("database not available: %v", err) } if err := validateJiraConfig(); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } ctx := rootCtx - // Create and initialize the Jira tracker jt := &jira.Tracker{} cliProjects, _ := cmd.Flags().GetStringSlice("project") if len(cliProjects) > 0 { jt.SetProjectKeys(tracker.DeduplicateStrings(cliProjects)) } if err := jt.Init(ctx, store); err != nil { - FatalError("initializing Jira tracker: %v", err) + return HandleErrorRespectJSON("initializing Jira tracker: %v", err) } - // Create the sync engine engine := tracker.NewEngine(jt, store, actor) engine.OnMessage = func(msg string) { fmt.Println(" " + msg) } engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) } - // Set up Jira-specific push hooks (prefix filtering) engine.PushHooks = buildJiraPushHooks(ctx) - // Build sync options from CLI flags opts := tracker.SyncOptions{ Pull: pull, Push: push, @@ -145,10 +153,9 @@ func runJiraSync(cmd *cobra.Command, args []string) { } if err := applySelectiveSyncFlags(cmd, &opts, push); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Map conflict resolution if preferLocal { opts.ConflictResolution = tracker.ConflictLocal } else if preferJira { @@ -157,41 +164,42 @@ func runJiraSync(cmd *cobra.Command, args []string) { opts.ConflictResolution = tracker.ConflictTimestamp } - // Run sync result, err := engine.Sync(ctx, opts) if err != nil { if jsonOutput { - outputJSON(result) - } else { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) + if jerr := outputJSON(result); jerr != nil { + return jerr + } + return SilentExit() } - os.Exit(1) + return HandleError("%v", err) } - // Output results if jsonOutput { - outputJSON(result) - } else if dryRun { + return outputJSON(result) + } + if dryRun { fmt.Println("\nāœ“ Dry run complete (no changes made)") - } else { - if result.Stats.Pulled > 0 { - fmt.Printf("āœ“ Pulled %d issues (%d created, %d updated)\n", - result.Stats.Pulled, result.Stats.Created, result.Stats.Updated) - } - if result.Stats.Pushed > 0 { - fmt.Printf("āœ“ Pushed %d issues\n", result.Stats.Pushed) - } - if result.Stats.Conflicts > 0 { - fmt.Printf("→ Resolved %d conflicts\n", result.Stats.Conflicts) - } - fmt.Println("\nāœ“ Jira sync complete") - if len(result.Warnings) > 0 { - fmt.Println("\nWarnings:") - for _, w := range result.Warnings { - fmt.Printf(" - %s\n", w) - } + return nil + } + if result.Stats.Pulled > 0 { + fmt.Printf("āœ“ Pulled %d issues (%d created, %d updated)\n", + result.Stats.Pulled, result.Stats.Created, result.Stats.Updated) + } + if result.Stats.Pushed > 0 { + fmt.Printf("āœ“ Pushed %d issues\n", result.Stats.Pushed) + } + if result.Stats.Conflicts > 0 { + fmt.Printf("→ Resolved %d conflicts\n", result.Stats.Conflicts) + } + fmt.Println("\nāœ“ Jira sync complete") + if len(result.Warnings) > 0 { + fmt.Println("\nWarnings:") + for _, w := range result.Warnings { + fmt.Printf(" - %s\n", w) } } + return nil } // buildJiraPushHooks creates PushHooks for Jira-specific push behavior. @@ -214,17 +222,23 @@ func buildJiraPushHooks(ctx context.Context) *tracker.PushHooks { } } -func runJiraStatus(cmd *cobra.Command, args []string) { +func runJiraStatus(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("jira-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx if err := ensureStoreActive(); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } jiraURL, _ := store.GetConfig(ctx, "jira.url") lastSync, _ := store.GetConfig(ctx, "jira.last_sync") - // Resolve project keys from all config sources. pluralProjects, _ := store.GetConfig(ctx, "jira.projects") singularProject, _ := store.GetConfig(ctx, "jira.project") projectKeys := tracker.ResolveProjectIDs(nil, pluralProjects, singularProject) @@ -233,7 +247,7 @@ func runJiraStatus(cmd *cobra.Command, args []string) { allIssues, err := store.SearchIssues(ctx, "", types.IssueFilter{}) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } withJiraRef := 0 @@ -247,12 +261,11 @@ func runJiraStatus(cmd *cobra.Command, args []string) { } if jsonOutput { - // Backward compat: include jira_project as first project, plus full list. primaryProject := "" if len(projectKeys) > 0 { primaryProject = projectKeys[0] } - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "configured": configured, "jira_url": jiraURL, "jira_project": primaryProject, @@ -262,7 +275,6 @@ func runJiraStatus(cmd *cobra.Command, args []string) { "with_jira_ref": withJiraRef, "pending_push": pendingPush, }) - return } fmt.Println("Jira Sync Status") @@ -278,7 +290,7 @@ func runJiraStatus(cmd *cobra.Command, args []string) { fmt.Println(" bd config set jira.projects \"PROJ1,PROJ2\" # multiple projects") fmt.Println(" bd config set jira.api_token \"YOUR_TOKEN\"") fmt.Println(" bd config set jira.username \"your@email.com\"") - return + return nil } fmt.Printf("Jira URL: %s\n", jiraURL) @@ -301,6 +313,7 @@ func runJiraStatus(cmd *cobra.Command, args []string) { fmt.Println() fmt.Printf("Run 'bd jira sync --push' to push %d local issue(s) to Jira\n", pendingPush) } + return nil } // validateJiraConfig checks that required Jira configuration is present. diff --git a/cmd/bd/kv.go b/cmd/bd/kv.go index f90081c61..195a7e650 100644 --- a/cmd/bd/kv.go +++ b/cmd/bd/kv.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage/kvkeys" ) @@ -76,34 +77,43 @@ Examples: bd kv set feature_flag true bd kv set api_endpoint https://api.example.com bd kv set max_retries 3`, - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("kv set") + evt := metrics.NewCommandEvent("kv-set") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("kv set requires direct database access"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } key := args[0] if err := validateKVKey(key); err != nil { - FatalErrorRespectJSON("invalid key: %v", err) + return HandleErrorRespectJSON("invalid key: %v", err) } value := args[1] storageKey := kvPrefix + key ctx := rootCtx if err := store.SetConfig(ctx, storageKey, value); err != nil { - FatalErrorRespectJSON("setting key: %v", err) + return HandleErrorRespectJSON("setting key: %v", err) } if jsonOutput { - outputJSON(map[string]string{ + return outputJSON(map[string]string{ "key": key, "value": value, }) - } else { - fmt.Printf("Set %s = %s\n", key, value) } + fmt.Printf("Set %s = %s\n", key, value) + return nil }, } @@ -116,10 +126,19 @@ var kvGetCmd = &cobra.Command{ Examples: bd kv get feature_flag bd kv get api_endpoint`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("kv-get") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("kv get requires direct database access"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } key := args[0] @@ -128,27 +147,28 @@ Examples: ctx := rootCtx value, err := store.GetConfig(ctx, storageKey) if err != nil { - FatalErrorRespectJSON("getting key: %v", err) + return HandleErrorRespectJSON("getting key: %v", err) } if jsonOutput { - result := map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "key": key, "value": value, "found": value != "", + }); jerr != nil { + return jerr } - outputJSON(result) if value == "" { - os.Exit(1) - } - } else { - if value == "" { - fmt.Fprintf(os.Stderr, "%s (not set)\n", key) - os.Exit(1) - } else { - fmt.Printf("%s\n", value) + return SilentExit() } + return nil } + if value == "" { + fmt.Fprintf(os.Stderr, "%s (not set)\n", key) + return SilentExit() + } + fmt.Printf("%s\n", value) + return nil }, } @@ -161,33 +181,42 @@ var kvClearCmd = &cobra.Command{ Examples: bd kv clear feature_flag bd kv clear api_endpoint`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("kv clear") + evt := metrics.NewCommandEvent("kv-clear") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("kv clear requires direct database access"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } key := args[0] if err := validateKVKey(key); err != nil { - FatalErrorRespectJSON("invalid key: %v", err) + return HandleErrorRespectJSON("invalid key: %v", err) } storageKey := kvPrefix + key ctx := rootCtx if err := store.DeleteConfig(ctx, storageKey); err != nil { - FatalErrorRespectJSON("deleting key: %v", err) + return HandleErrorRespectJSON("deleting key: %v", err) } if jsonOutput { - outputJSON(map[string]string{ + return outputJSON(map[string]string{ "key": key, "deleted": "true", }) - } else { - fmt.Printf("Cleared %s\n", key) } + fmt.Printf("Cleared %s\n", key) + return nil }, } @@ -200,18 +229,26 @@ var kvListCmd = &cobra.Command{ Examples: bd kv list bd kv list --json`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("kv-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("kv list requires direct database access"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } ctx := rootCtx allConfig, err := store.GetAllConfig(ctx) if err != nil { - FatalErrorRespectJSON("listing keys: %v", err) + return HandleErrorRespectJSON("listing keys: %v", err) } - // Filter for kv.* keys and strip prefix kvPairs := make(map[string]string) for k, v := range allConfig { if strings.HasPrefix(k, kvPrefix) { @@ -221,16 +258,14 @@ Examples: } if jsonOutput { - outputJSON(kvPairs) - return + return outputJSON(kvPairs) } if len(kvPairs) == 0 { fmt.Println("No key-value pairs set") - return + return nil } - // Sort keys for consistent output keys := make([]string, 0, len(kvPairs)) for k := range kvPairs { keys = append(keys, k) @@ -241,6 +276,7 @@ Examples: for _, k := range keys { fmt.Printf(" %s = %s\n", k, kvPairs[k]) } + return nil }, } diff --git a/cmd/bd/label.go b/cmd/bd/label.go index 2ee25c823..434106f70 100644 --- a/cmd/bd/label.go +++ b/cmd/bd/label.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -21,10 +22,8 @@ var labelCmd = &cobra.Command{ Short: "Manage issue labels", } -// processBatchLabelOperation wraps label add/remove for multiple issues in a -// single transaction for atomicity. func processBatchLabelOperation(issueIDs []string, label string, operation string, jsonOut bool, - txFunc func(context.Context, storage.Transaction, string, string, string) error) { + txFunc func(context.Context, storage.Transaction, string, string, string) error) error { ctx := rootCtx commitMsg := fmt.Sprintf("bd: label %s '%s' on %d issue(s)", operation, label, len(issueIDs)) err := transactHonoringAutoCommit(ctx, store, commitMsg, func(tx storage.Transaction) error { @@ -36,7 +35,7 @@ func processBatchLabelOperation(issueIDs []string, label string, operation strin return nil }) if err != nil { - FatalErrorRespectJSON("label %s: %v", operation, err) + return HandleErrorRespectJSON("label %s: %v", operation, err) } commandDidWrite.Store(true) if jsonOut { @@ -48,18 +47,18 @@ func processBatchLabelOperation(issueIDs []string, label string, operation strin "label": label, }) } - outputJSON(results) - } else { - verb := "Added" - prep := "to" - if operation == "removed" { - verb = "Removed" - prep = "from" - } - for _, issueID := range issueIDs { - fmt.Printf("%s %s label '%s' %s %s\n", ui.RenderPass("āœ“"), verb, label, prep, issueID) - } + return outputJSON(results) } + verb := "Added" + prep := "to" + if operation == "removed" { + verb = "Removed" + prep = "from" + } + for _, issueID := range issueIDs { + fmt.Printf("%s %s label '%s' %s %s\n", ui.RenderPass("āœ“"), verb, label, prep, issueID) + } + return nil } func parseLabelArgs(args []string) (issueIDs []string, label string) { label = args[len(args)-1] @@ -69,18 +68,26 @@ func parseLabelArgs(args []string) (issueIDs []string, label string) { //nolint:dupl // labelAddCmd and labelRemoveCmd are similar but serve different operations var labelAddCmd = &cobra.Command{ - Use: "add [issue-id...] [label]", - Short: "Add a label to one or more issues", - Args: cobra.MinimumNArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Use: "add [issue-id...] [label]", + Short: "Add a label to one or more issues", + Args: cobra.MinimumNArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("label add") - // Use global jsonOutput set by PersistentPreRun + + evt := metrics.NewCommandEvent("label-add") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + issueIDs, label := parseLabelArgs(args) label = strings.TrimSpace(label) if label == "" { - FatalErrorRespectJSON("label cannot be empty") + return HandleErrorRespectJSON("label cannot be empty") } - // Resolve partial IDs ctx := rootCtx resolvedIDs := make([]string, 0, len(issueIDs)) for _, id := range issueIDs { @@ -95,13 +102,11 @@ var labelAddCmd = &cobra.Command{ } issueIDs = resolvedIDs - // Protect reserved label namespaces - // provides:* labels can only be added via 'bd ship' command if strings.HasPrefix(label, "provides:") { - FatalErrorRespectJSON("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship %s' instead", strings.TrimPrefix(label, "provides:")) + return HandleErrorRespectJSON("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship %s' instead", strings.TrimPrefix(label, "provides:")) } - processBatchLabelOperation(issueIDs, label, "added", jsonOutput, + return processBatchLabelOperation(issueIDs, label, "added", jsonOutput, func(ctx context.Context, tx storage.Transaction, issueID, lbl, act string) error { return tx.AddLabel(ctx, issueID, lbl, act) }) @@ -110,14 +115,22 @@ var labelAddCmd = &cobra.Command{ //nolint:dupl // labelRemoveCmd and labelAddCmd are similar but serve different operations var labelRemoveCmd = &cobra.Command{ - Use: "remove [issue-id...] [label]", - Short: "Remove a label from one or more issues", - Args: cobra.MinimumNArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Use: "remove [issue-id...] [label]", + Short: "Remove a label from one or more issues", + Args: cobra.MinimumNArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("label remove") - // Use global jsonOutput set by PersistentPreRun + + evt := metrics.NewCommandEvent("label-remove") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + issueIDs, label := parseLabelArgs(args) - // Resolve partial IDs ctx := rootCtx resolvedIDs := make([]string, 0, len(issueIDs)) for _, id := range issueIDs { @@ -131,71 +144,81 @@ var labelRemoveCmd = &cobra.Command{ resolvedIDs = append(resolvedIDs, fullID) } issueIDs = resolvedIDs - processBatchLabelOperation(issueIDs, label, "removed", jsonOutput, + return processBatchLabelOperation(issueIDs, label, "removed", jsonOutput, func(ctx context.Context, tx storage.Transaction, issueID, lbl, act string) error { return tx.RemoveLabel(ctx, issueID, lbl, act) }) }, } var labelListCmd = &cobra.Command{ - Use: "list [issue-id]", - Short: "List labels for an issue", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { - // Use global jsonOutput set by PersistentPreRun + Use: "list [issue-id]", + Short: "List labels for an issue", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("label-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // Resolve partial ID first var issueID string var err error issueID, err = utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalErrorRespectJSON("resolving %s: %v", args[0], err) + return HandleErrorRespectJSON("resolving %s: %v", args[0], err) } var labels []string - // Direct mode labels, err = store.GetLabels(ctx, issueID) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { - // Always output array, even if empty if labels == nil { labels = []string{} } - outputJSON(labels) - return + return outputJSON(labels) } if len(labels) == 0 { fmt.Printf("\n%s has no labels\n", issueID) - return + return nil } fmt.Printf("\n%s Labels for %s:\n", ui.RenderAccent("šŸ·"), issueID) for _, label := range labels { fmt.Printf(" - %s\n", label) } fmt.Println() + return nil }, } var labelListAllCmd = &cobra.Command{ - Use: "list-all", - Short: "List all unique labels in the database", - Run: func(cmd *cobra.Command, args []string) { - // Use global jsonOutput set by PersistentPreRun + Use: "list-all", + Short: "List all unique labels in the database", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("label-list-all") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx var issues []*types.Issue var err error - // Direct mode issues, err = store.SearchIssues(ctx, "", types.IssueFilter{}) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Collect unique labels with counts labelCounts := make(map[string]int) for _, issue := range issues { - // Direct mode - need to fetch labels labels, err := store.GetLabels(ctx, issue.ID) if err != nil { - FatalErrorRespectJSON("getting labels for %s: %v", issue.ID, err) + return HandleErrorRespectJSON("getting labels for %s: %v", issue.ID, err) } for _, label := range labels { labelCounts[label]++ @@ -207,20 +230,17 @@ var labelListAllCmd = &cobra.Command{ } if len(labelCounts) == 0 { if jsonOutput { - outputJSON([]labelInfo{}) - } else { - fmt.Println("\nNo labels found in database") + return outputJSON([]labelInfo{}) } - return + fmt.Println("\nNo labels found in database") + return nil } - // Sort labels alphabetically labels := make([]string, 0, len(labelCounts)) for label := range labelCounts { labels = append(labels, label) } sort.Strings(labels) if jsonOutput { - // Output as array of {label, count} objects result := make([]labelInfo, 0, len(labels)) for _, label := range labels { result = append(result, labelInfo{ @@ -228,11 +248,9 @@ var labelListAllCmd = &cobra.Command{ Count: labelCounts[label], }) } - outputJSON(result) - return + return outputJSON(result) } fmt.Printf("\n%s All labels (%d unique):\n", ui.RenderAccent("šŸ·"), len(labels)) - // Find longest label for alignment maxLen := 0 for _, label := range labels { if len(label) > maxLen { @@ -244,48 +262,55 @@ var labelListAllCmd = &cobra.Command{ fmt.Printf(" %s%s (%d issues)\n", label, padding, labelCounts[label]) } fmt.Println() + return nil }, } var labelPropagateCmd = &cobra.Command{ - Use: "propagate [parent-id] [label]", - Short: "Propagate a label from a parent issue to all its children", - Long: "Push a label from a parent down to all direct children that don't already have it. Useful for applying branch: labels across an epic's subtasks.", - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Use: "propagate [parent-id] [label]", + Short: "Propagate a label from a parent issue to all its children", + Long: "Push a label from a parent down to all direct children that don't already have it. Useful for applying branch: labels across an epic's subtasks.", + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("label propagate") + + evt := metrics.NewCommandEvent("label-propagate") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx parentID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalErrorRespectJSON("resolving parent %s: %v", args[0], err) + return HandleErrorRespectJSON("resolving parent %s: %v", args[0], err) } label := strings.TrimSpace(args[1]) if label == "" { - FatalErrorRespectJSON("label cannot be empty") + return HandleErrorRespectJSON("label cannot be empty") } - // Protect reserved label namespaces if strings.HasPrefix(label, "provides:") { - FatalErrorRespectJSON("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship %s' instead", strings.TrimPrefix(label, "provides:")) + return HandleErrorRespectJSON("'provides:' labels are reserved for cross-project capabilities. Hint: use 'bd ship %s' instead", strings.TrimPrefix(label, "provides:")) } - // Find all direct children via parent-child dependency children, err := store.SearchIssues(ctx, "", types.IssueFilter{ParentID: &parentID}) if err != nil { - FatalErrorRespectJSON("searching children of %s: %v", parentID, err) + return HandleErrorRespectJSON("searching children of %s: %v", parentID, err) } if len(children) == 0 { if jsonOutput { - outputJSON([]map[string]interface{}{}) - } else { - fmt.Printf("No children found for %s\n", parentID) + return outputJSON([]map[string]interface{}{}) } - return + fmt.Printf("No children found for %s\n", parentID) + return nil } - // Add label to each child in a single transaction (AddLabel is idempotent) commitMsg := fmt.Sprintf("bd: propagate label '%s' from %s to %d children", label, parentID, len(children)) err = transactHonoringAutoCommit(ctx, store, commitMsg, func(tx storage.Transaction) error { for _, child := range children { @@ -296,7 +321,7 @@ var labelPropagateCmd = &cobra.Command{ return nil }) if err != nil { - FatalErrorRespectJSON("label propagate: %v", err) + return HandleErrorRespectJSON("label propagate: %v", err) } if jsonOutput { @@ -308,12 +333,12 @@ var labelPropagateCmd = &cobra.Command{ "label": label, }) } - outputJSON(results) - } else { - for _, child := range children { - fmt.Printf("%s Propagated label '%s' to %s\n", ui.RenderPass("āœ“"), label, child.ID) - } + return outputJSON(results) } + for _, child := range children { + fmt.Printf("%s Propagated label '%s' to %s\n", ui.RenderPass("āœ“"), label, child.ID) + } + return nil }, } diff --git a/cmd/bd/linear.go b/cmd/bd/linear.go index b06846b72..3bebd195e 100644 --- a/cmd/bd/linear.go +++ b/cmd/bd/linear.go @@ -16,6 +16,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/debug" "github.com/steveyegge/beads/internal/linear" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/tracker" "github.com/steveyegge/beads/internal/types" @@ -138,7 +139,9 @@ Examples: bd linear sync --push --parent=bd-abc123 # Push one ticket tree bd linear sync --dry-run # Preview without changes bd linear sync --prefer-local # Bidirectional, local wins`, - Run: runLinearSync, + SilenceUsage: true, + SilenceErrors: true, + RunE: runLinearSync, } // linearStatusCmd shows the current sync status. @@ -150,7 +153,9 @@ var linearStatusCmd = &cobra.Command{ - Configuration status - Number of issues with Linear links - Issues pending push (no external_ref)`, - Run: runLinearStatus, + SilenceUsage: true, + SilenceErrors: true, + RunE: runLinearStatus, } // linearTeamsCmd lists available teams. @@ -164,7 +169,9 @@ Use this to find the team ID (UUID) needed for configuration. Example: bd linear teams bd config set linear.team_id "12345678-1234-1234-1234-123456789abc"`, - Run: runLinearTeams, + SilenceUsage: true, + SilenceErrors: true, + RunE: runLinearTeams, } func init() { @@ -194,7 +201,14 @@ func init() { rootCmd.AddCommand(linearCmd) } -func runLinearSync(cmd *cobra.Command, args []string) { +func runLinearSync(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("linear-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + pull, _ := cmd.Flags().GetBool("pull") push, _ := cmd.Flags().GetBool("push") dryRun, _ := cmd.Flags().GetBool("dry-run") @@ -212,46 +226,40 @@ func runLinearSync(cmd *cobra.Command, args []string) { threshold, _ := cmd.Flags().GetDuration("threshold") noWait, _ := cmd.Flags().GetBool("no-wait") - // Handle --pull-if-stale: skip pull if data is fresh if pullIfStale { beadsDir := resolveBeadsDirForStaleness() if beadsDir != "" { - // Debounce: if a pull completed within 5 minutes, always fresh if linear.IsWithinDebounce(beadsDir) { info := linear.GetStalenessInfo(beadsDir, threshold) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "is_fresh": true, "last_pull": info.LastPull.Format(time.RFC3339), "age": linear.FormatAge(info.Age), "skipped": true, }) - } else { - fmt.Printf("Linear data is fresh (last pull %s ago, within debounce)\n", linear.FormatAge(info.Age)) } - return + fmt.Printf("Linear data is fresh (last pull %s ago, within debounce)\n", linear.FormatAge(info.Age)) + return nil } if !linear.IsPullStale(beadsDir, threshold) { info := linear.GetStalenessInfo(beadsDir, threshold) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "is_fresh": true, "last_pull": info.LastPull.Format(time.RFC3339), "age": linear.FormatAge(info.Age), "skipped": true, }) - } else { - fmt.Printf("Linear data is fresh (last pull %s ago)\n", linear.FormatAge(info.Age)) } - return + fmt.Printf("Linear data is fresh (last pull %s ago)\n", linear.FormatAge(info.Age)) + return nil } } - // Data is stale — proceed with pull pull = true } - // Acquire per-workspace concurrency lock to serialize sync invocations. if lockDir := beads.FindBeadsDir(); lockDir != "" { wait := !noWait if !wait { @@ -263,12 +271,12 @@ func runLinearSync(cmd *cobra.Command, args []string) { if err != nil { if held, ok := err.(*linear.SyncLockHeldError); ok { if held.Info != nil { - FatalError("another bd linear sync is already running (PID %d, started %s)", + return HandleError("another bd linear sync is already running (PID %d, started %s)", held.Info.PID, held.Info.Started.Format("15:04:05")) } - FatalError("another bd linear sync is already running") + return HandleError("another bd linear sync is already running") } - FatalError("acquiring sync lock: %v", err) + return HandleError("acquiring sync lock: %v", err) } defer func() { if err := syncLock.Release(); err != nil { @@ -282,55 +290,50 @@ func runLinearSync(cmd *cobra.Command, args []string) { } if preferLocal && preferLinear { - FatalError("cannot use both --prefer-local and --prefer-linear") + return HandleErrorRespectJSON("cannot use both --prefer-local and --prefer-linear") } if milestones && push && !pull { - FatalError("--milestones only applies when pulling from Linear") + return HandleErrorRespectJSON("--milestones only applies when pulling from Linear") } if err := ensureStoreActive(); err != nil { - FatalError("database not available: %v", err) + return HandleErrorRespectJSON("database not available: %v", err) } if err := validateLinearConfig(cliTeams); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } ctx := rootCtx teamIDs := getLinearTeamIDs(ctx, cliTeams) willPush := push || !pull - // Require explicit --team for push when multiple teams are configured. if willPush && len(teamIDs) > 1 && len(cliTeams) == 0 { - FatalError("push requires explicit --team flag when multiple teams are configured\n" + + return HandleErrorRespectJSON("push requires explicit --team flag when multiple teams are configured\n" + "Use: bd linear sync --push --team ") } - // Create and initialize the Linear tracker lt := &linear.Tracker{} lt.SetTeamIDs(teamIDs) if err := lt.Init(ctx, store); err != nil { - FatalError("initializing Linear tracker: %v", err) + return HandleErrorRespectJSON("initializing Linear tracker: %v", err) } if willPush { if err := lt.ValidatePushStateMappings(ctx); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } } - // Create the sync engine engine := tracker.NewEngine(lt, store, actor) engine.OnMessage = func(msg string) { fmt.Println(" " + msg) } engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) } - // Set up Linear-specific pull hooks engine.PullHooks = buildLinearPullHooks(ctx, linearPullHookOptions{ Milestones: milestones, DryRun: dryRun, Actor: actor, }) - // Build sync options from CLI flags opts := tracker.SyncOptions{ Pull: pull, Push: push, @@ -340,7 +343,6 @@ func runLinearSync(cmd *cobra.Command, args []string) { } opts.DependencySources = linearPullDependencySources(relations) - // Convert type filters for _, t := range typeFilters { opts.TypeFilter = append(opts.TypeFilter, types.IssueType(strings.ToLower(t))) } @@ -352,14 +354,12 @@ func runLinearSync(cmd *cobra.Command, args []string) { } if err := applySelectiveSyncFlags(cmd, &opts, push); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } allowProjectCreates := opts.ParentID != "" || len(opts.IssueIDs) > 0 - // Set up Linear-specific push hooks engine.PushHooks = buildLinearPushHooks(ctx, lt, allowProjectCreates) - // Map conflict resolution if preferLocal { opts.ConflictResolution = tracker.ConflictLocal } else if preferLinear { @@ -368,59 +368,56 @@ func runLinearSync(cmd *cobra.Command, args []string) { opts.ConflictResolution = tracker.ConflictTimestamp } - // Run sync result, err := engine.Sync(ctx, opts) if err != nil { if jsonOutput { - outputJSON(result) - } else { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) + if jerr := outputJSON(result); jerr != nil { + return jerr + } + return SilentExit() } - os.Exit(1) + return HandleError("%v", err) } - // Record successful pull timestamp if (pull || !push) && !dryRun { if beadsDir := resolveBeadsDirForStaleness(); beadsDir != "" { _ = linear.WriteLastPullTimestamp(beadsDir) } } - // Output results if jsonOutput { if pullIfStale { - // Augment JSON output with staleness info - resultMap := map[string]interface{}{ + return outputJSON(map[string]interface{}{ "stats": result.Stats, "warnings": result.Warnings, "is_fresh": true, "skipped": false, - } - outputJSON(resultMap) - } else { - outputJSON(result) + }) } - } else if dryRun { + return outputJSON(result) + } + if dryRun { fmt.Println("\nāœ“ Dry run complete (no changes made)") - } else { - if result.Stats.Pulled > 0 { - fmt.Printf("āœ“ Pulled %d issues (%d created, %d updated)\n", - result.Stats.Pulled, result.Stats.Created, result.Stats.Updated) - } - if result.Stats.Pushed > 0 { - fmt.Printf("āœ“ Pushed %d issues\n", result.Stats.Pushed) - } - if result.Stats.Conflicts > 0 { - fmt.Printf("→ Resolved %d conflicts\n", result.Stats.Conflicts) - } - fmt.Println("\nāœ“ Linear sync complete") - if len(result.Warnings) > 0 { - fmt.Println("\nWarnings:") - for _, w := range result.Warnings { - fmt.Printf(" - %s\n", w) - } + return nil + } + if result.Stats.Pulled > 0 { + fmt.Printf("āœ“ Pulled %d issues (%d created, %d updated)\n", + result.Stats.Pulled, result.Stats.Created, result.Stats.Updated) + } + if result.Stats.Pushed > 0 { + fmt.Printf("āœ“ Pushed %d issues\n", result.Stats.Pushed) + } + if result.Stats.Conflicts > 0 { + fmt.Printf("→ Resolved %d conflicts\n", result.Stats.Conflicts) + } + fmt.Println("\nāœ“ Linear sync complete") + if len(result.Warnings) > 0 { + fmt.Println("\nWarnings:") + for _, w := range result.Warnings { + fmt.Printf(" - %s\n", w) } } + return nil } func linearPullDependencySources(includeRelations bool) []tracker.DependencySource { @@ -761,11 +758,18 @@ func buildLinearPushHooks(ctx context.Context, lt *linear.Tracker, allowProjectC } } -func runLinearStatus(cmd *cobra.Command, args []string) { +func runLinearStatus(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("linear-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx if err := ensureStoreActive(); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } apiKey, _ := getLinearConfig(ctx, "linear.api_key") @@ -779,7 +783,7 @@ func runLinearStatus(cmd *cobra.Command, args []string) { allIssues, err := store.SearchIssues(ctx, "", types.IssueFilter{}) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } withLinearRef := 0 @@ -794,7 +798,6 @@ func runLinearStatus(cmd *cobra.Command, args []string) { if jsonOutput { hasAPIKey := apiKey != "" - // Backward compat: include team_id as first team, plus full list. teamID := "" if len(teamIDs) > 0 { teamID = teamIDs[0] @@ -805,7 +808,7 @@ func runLinearStatus(cmd *cobra.Command, args []string) { } else if hasAPIKey { authMode = "api_key" } - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "configured": configured, "has_api_key": hasAPIKey, "has_oauth": hasOAuth, @@ -817,7 +820,6 @@ func runLinearStatus(cmd *cobra.Command, args []string) { "with_linear_ref": withLinearRef, "pending_push": pendingPush, }) - return } fmt.Println("Linear Sync Status") @@ -839,7 +841,7 @@ func runLinearStatus(cmd *cobra.Command, args []string) { fmt.Println("For CI/OAuth authentication:") fmt.Println(" export LINEAR_OAUTH_CLIENT_ID=\"...\"") fmt.Println(" export LINEAR_OAUTH_CLIENT_SECRET=\"...\"") - return + return nil } if len(teamIDs) == 1 { @@ -866,30 +868,36 @@ func runLinearStatus(cmd *cobra.Command, args []string) { fmt.Println() fmt.Printf("Run 'bd linear sync --push' to push %d local issue(s) to Linear\n", pendingPush) } + return nil } -func runLinearTeams(cmd *cobra.Command, args []string) { +func runLinearTeams(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("linear-teams") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx client, err := buildLinearClient(ctx, "") if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - os.Exit(1) + return HandleError("%v", err) } teams, err := client.FetchTeams(ctx) if err != nil { - FatalError("fetching teams: %v", err) + return HandleError("fetching teams: %v", err) } if len(teams) == 0 { fmt.Println("No teams found (check your API key permissions)") - return + return nil } if jsonOutput { - outputJSON(teams) - return + return outputJSON(teams) } fmt.Println("Available Linear Teams") @@ -904,6 +912,7 @@ func runLinearTeams(cmd *cobra.Command, args []string) { fmt.Println("To configure:") fmt.Println(" bd config set linear.team_id \"\"") fmt.Println(" bd config set linear.team_ids \",\" # multiple teams") + return nil } // resolveBeadsDirForStaleness returns the active beads directory for diff --git a/cmd/bd/link.go b/cmd/bd/link.go index fac5c1ff7..39fe91d43 100644 --- a/cmd/bd/link.go +++ b/cmd/bd/link.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -21,10 +22,19 @@ Examples: bd link bd-123 bd-456 # bd-456 blocks bd-123 bd link bd-123 bd-456 --type related # bd-123 related to bd-456 bd link bd-123 bd-456 --type parent-child`, - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("link") + evt := metrics.NewCommandEvent("link") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + id1 := args[0] id2 := args[1] depType, _ := cmd.Flags().GetString("type") @@ -37,25 +47,23 @@ Examples: // read-only (bd-6dnrw.32, GH#3231). fromID, fromStore, fromCleanup, err := resolveIDForMutation(ctx, store, id1) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } defer fromCleanup() toID, _, toCleanup, err := resolveIDWithRouting(ctx, store, id2) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } defer toCleanup() - // Check for child→parent dependency anti-pattern 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) } - // Validate dependency type 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) } dep := &types.Dependency{ @@ -65,32 +73,31 @@ Examples: } if err := fromStore.AddDependency(ctx, dep, actor); err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Check for cycles after adding dependency warnIfCyclesExist(fromStore) if err := commitPendingIfEmbedded(ctx, fromStore, actor, doltAutoCommitParams{ Command: "link", IssueIDs: []string{fromID, toID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } SetLastTouchedID(fromID) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "added", "issue_id": fromID, "depends_on_id": toID, "type": depType, }) - } else { - fmt.Printf("%s Linked: %s depends on %s (%s)\n", - ui.RenderPass("āœ“"), formatFeedbackIDParen(fromID, lookupTitle(fromID)), formatFeedbackIDParen(toID, lookupTitle(toID)), depType) } + fmt.Printf("%s Linked: %s depends on %s (%s)\n", + ui.RenderPass("āœ“"), formatFeedbackIDParen(fromID, lookupTitle(fromID)), formatFeedbackIDParen(toID, lookupTitle(toID)), depType) + return nil }, } diff --git a/cmd/bd/lint.go b/cmd/bd/lint.go index e82d2e584..b9f8659a2 100644 --- a/cmd/bd/lint.go +++ b/cmd/bd/lint.go @@ -6,6 +6,7 @@ import ( "os" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/validation" ) @@ -41,7 +42,16 @@ Examples: bd lint --type bug # Lint only bugs bd lint --status all # Lint all issues (including closed) `, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("lint") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx typeFilter, _ := cmd.Flags().GetString("type") @@ -49,15 +59,11 @@ Examples: var issues []*types.Issue - // Direct mode - if store == nil { - FatalErrorWithHint("database not initialized", - diagHint()) + return HandleErrorWithHint("database not initialized", diagHint()) } if len(args) > 0 { - // Lint specific issues for _, id := range args { issue, err := store.GetIssue(ctx, id) if err != nil { @@ -71,10 +77,8 @@ Examples: issues = append(issues, issue) } } else { - // Lint all matching issues filter := types.IssueFilter{} - // Default to open issues unless --status specified if statusFilter == "" || statusFilter == "open" { s := types.StatusOpen filter.Status = &s @@ -91,7 +95,7 @@ Examples: var err error issues, err = store.SearchIssues(ctx, "", filter) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } @@ -101,7 +105,7 @@ Examples: for _, issue := range issues { err := validation.LintIssue(issue) if err == nil { - continue // No warnings for this issue + continue } templateErr, ok := err.(*validation.TemplateError) @@ -137,13 +141,12 @@ Examples: } data, _ := json.MarshalIndent(output, "", " ") fmt.Println(string(data)) - return + return nil } - // Human-readable output if len(results) == 0 { fmt.Printf("āœ“ No template warnings found (%d issues checked)\n", len(issues)) - return + return nil } fmt.Printf("Template warnings (%d issues, %d warnings):\n\n", len(results), totalWarnings) @@ -155,8 +158,7 @@ Examples: fmt.Println() } - // Exit with error code if warnings found (useful for CI) - os.Exit(1) + return SilentExit() }, } diff --git a/cmd/bd/list.go b/cmd/bd/list.go index 1bc6fcc73..1377fd2ff 100644 --- a/cmd/bd/list.go +++ b/cmd/bd/list.go @@ -12,6 +12,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -456,36 +457,47 @@ var listCmd = &cobra.Command{ } return fmt.Errorf("bd list does not accept positional arguments; use flags instead (see bd list --help)") }, - Run: func(cmd *cobra.Command, args []string) { - in := gatherListInput(cmd) + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + + in, err := gatherListInput(cmd) + if err != nil { + return err + } if usesProxiedServer() { if err := runListProxiedServer(cmd, rootCtx, in); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - return + return nil } if in.offset > 0 { - FatalError("--offset is only supported under --proxied-server") + return HandleError("--offset is only supported under --proxied-server") } cfg, err := loadDirectListFilterConfig(rootCtx, store) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } filter, err := buildListFilter(in, cfg) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } ctx := rootCtx activeStore := store - // Contributor auto-routing: read from the same target repo as bd create. routedStore, routed, err := openRoutedReadStore(ctx, activeStore) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } if routed { defer func() { _ = routedStore.Close() }() @@ -494,7 +506,7 @@ var listCmd = &cobra.Command{ if in.watchMode { watchIssues(ctx, activeStore, filter, in.readyFlag, in.parentID, in.sortBy, in.reverse, in.effectiveLimit) - return + return nil } if jsonOutput { @@ -506,7 +518,7 @@ var listCmd = &cobra.Command{ iwc, err = activeStore.SearchIssuesWithCounts(ctx, "", withFetchOneExtra(filter)) } if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } sortIssuesWithCounts(iwc, in.sortBy, in.reverse) truncated := in.effectiveLimit > 0 && len(iwc) > in.effectiveLimit @@ -517,89 +529,76 @@ var listCmd = &cobra.Command{ iwc = []*types.IssueWithCounts{} } if in.skipLabels { - outputJSON(newSkipLabelsListJSONResponse(iwc)) + if err := outputJSON(newSkipLabelsListJSONResponse(iwc)); err != nil { + return err + } printTruncationHint(truncated, in.effectiveLimit) - return + return nil + } + if err := outputJSON(iwc); err != nil { + return err } - outputJSON(iwc) printTruncationHint(truncated, in.effectiveLimit) - return + return nil } var issues []*types.Issue if in.readyFlag { - // Use blocker-aware GetReadyWork semantics (GH#3478). - // This ensures bd list --ready matches bd ready behavior, - // excluding issues with open blocks dependencies. wf := readyWorkFilterFromIssueFilter(withFetchOneExtra(filter)) var err error issues, err = activeStore.GetReadyWork(ctx, wf) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } else { var err error issues, err = activeStore.SearchIssues(ctx, "", withFetchOneExtra(filter)) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } - // Apply sorting sortIssues(issues, in.sortBy, in.reverse) - // Detect truncation (GH#3212). We fetched effectiveLimit+1 above, so any - // overflow means more matches exist than we're displaying. truncated := in.effectiveLimit > 0 && len(issues) > in.effectiveLimit if truncated { issues = issues[:in.effectiveLimit] } - // Handle pretty format (GH#654) - // JSON output takes priority over pretty/tree format (bd-list-json-fix, bd-03r) if in.prettyFormat && !jsonOutput { - // Special handling for --tree --parent combination (hierarchical descendants) if in.parentID != "" && !in.readyFlag { treeIssues, err := getHierarchicalChildren(ctx, activeStore, "", in.parentID, filter) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } if len(treeIssues) == 0 { fmt.Printf("Issue '%s' has no children\n", in.parentID) - return + return nil } - // Load dependencies for tree structure - // Best effort: display gracefully degrades with empty data allDeps, _ := activeStore.GetAllDependencyRecords(ctx) displayPrettyListWithDeps(treeIssues, false, allDeps) printSkipLabelsFooter(in.skipLabels) - return + return nil } - // Regular tree display (no parent filter) - // Load dependencies for tree structure - // Best effort: display gracefully degrades with empty data allDeps, _ := activeStore.GetAllDependencyRecords(ctx) displayPrettyListWithDeps(issues, false, allDeps) printTruncationHint(truncated, in.effectiveLimit) printSkipLabelsFooter(in.skipLabels) - return + return nil } - // Handle format flag (non-json presets handled here; json handled earlier) if in.formatStr != "" { - // Best effort: rendering degrades gracefully on dep-load failure. depsByIssueID, _ := activeStore.GetAllDependencyRecords(ctx) if err := outputFormattedList(issues, depsByIssueID, in.formatStr); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } printTruncationHint(truncated, in.effectiveLimit) - return + return nil } - // Show upgrade notification if needed maybeShowUpgradeNotification() issueIDs := make([]string, len(issues)) @@ -611,43 +610,33 @@ var listCmd = &cobra.Command{ } } - // Load blocking info for displayed issues only (bd-7di). - // Previously loaded ALL dependency records which was O(total_issues) and took 2-4s. - // Now scoped to only the displayed issues, making it O(displayed_issues). - // Best effort: display gracefully degrades with empty data blockedByMap, blocksMap, parentMap, _ := activeStore.GetBlockingInfoForIssues(ctx, issueIDs) - // Build output in buffer for pager support (bd-jdz3) var buf strings.Builder if ui.IsAgentMode() { - // Agent mode: ultra-compact, no colors, no pager for _, issue := range issues { formatAgentIssue(&buf, issue, blockedByMap[issue.ID], blocksMap[issue.ID], parentMap[issue.ID]) } fmt.Print(buf.String()) printTruncationHint(truncated, in.effectiveLimit) - return + return nil } else if in.longFormat { - // Long format: multi-line with details buf.WriteString(fmt.Sprintf("\nFound %d issues:\n\n", len(issues))) for _, issue := range issues { labels := labelsMap[issue.ID] formatIssueLong(&buf, issue, labels, in.skipLabels) } } else { - // Compact format: one line per issue for _, issue := range issues { labels := labelsMap[issue.ID] formatIssueCompact(&buf, issue, labels, blockedByMap[issue.ID], blocksMap[issue.ID], parentMap[issue.ID]) } } - // AD-02: footer note when --skip-labels is in effect (suppressed under --quiet). if in.skipLabels && !isQuiet() { buf.WriteString(skipLabelsFooterText()) } - // Output with pager support if err := ui.ToPager(buf.String(), ui.PagerOptions{NoPager: in.noPager}); err != nil { if _, writeErr := fmt.Fprint(os.Stdout, buf.String()); writeErr != nil { fmt.Fprintf(os.Stderr, "Error writing output: %v\n", writeErr) @@ -656,8 +645,8 @@ var listCmd = &cobra.Command{ printTruncationHint(truncated, in.effectiveLimit) - // Show tip after successful list (direct mode only) maybeShowTip(store) + return nil }, } diff --git a/cmd/bd/list_input.go b/cmd/bd/list_input.go index 7e29d4211..fc3112cb6 100644 --- a/cmd/bd/list_input.go +++ b/cmd/bd/list_input.go @@ -96,7 +96,7 @@ type listInput struct { repoOverrideSet bool } -func gatherListInput(cmd *cobra.Command) listInput { +func gatherListInput(cmd *cobra.Command) (listInput, error) { in := listInput{} in.status, _ = cmd.Flags().GetString("status") @@ -144,7 +144,7 @@ func gatherListInput(cmd *cobra.Command) listInput { conflicts := skipLabelsConflicts(in.labels, in.labelsAny, in.labelPattern, in.labelRegex, in.excludeLabels, in.noLabels) if len(conflicts) > 0 { fmt.Fprint(os.Stderr, formatSkipLabelsConflictError(conflicts)) - os.Exit(2) + return in, &exitError{Code: 2} } } @@ -152,7 +152,7 @@ func gatherListInput(cmd *cobra.Command) listInput { priorityStr, _ := cmd.Flags().GetString("priority") p, err := validation.ValidatePriority(priorityStr) if err != nil { - FatalError("%v", err) + return in, HandleError("%v", err) } in.priority = p in.prioritySet = true @@ -161,7 +161,7 @@ func gatherListInput(cmd *cobra.Command) listInput { s, _ := cmd.Flags().GetString("priority-min") p, err := validation.ValidatePriority(s) if err != nil { - FatalError("parsing --priority-min: %v", err) + return in, HandleError("parsing --priority-min: %v", err) } in.priorityMin = p in.priorityMinSet = true @@ -170,7 +170,7 @@ func gatherListInput(cmd *cobra.Command) listInput { s, _ := cmd.Flags().GetString("priority-max") p, err := validation.ValidatePriority(s) if err != nil { - FatalError("parsing --priority-max: %v", err) + return in, HandleError("parsing --priority-max: %v", err) } in.priorityMax = p in.priorityMaxSet = true @@ -179,7 +179,7 @@ func gatherListInput(cmd *cobra.Command) listInput { in.pinnedFlag, _ = cmd.Flags().GetBool("pinned") in.noPinnedFlag, _ = cmd.Flags().GetBool("no-pinned") if in.pinnedFlag && in.noPinnedFlag { - FatalError("--pinned and --no-pinned are mutually exclusive") + return in, HandleError("--pinned and --no-pinned are mutually exclusive") } in.includeTemplates, _ = cmd.Flags().GetBool("include-templates") @@ -193,20 +193,20 @@ func gatherListInput(cmd *cobra.Command) listInput { } in.noParent, _ = cmd.Flags().GetBool("no-parent") if in.parentID != "" && in.noParent { - FatalError("--parent and --no-parent are mutually exclusive") + return in, HandleError("--parent and --no-parent are mutually exclusive") } if s, _ := cmd.Flags().GetString("mol-type"); s != "" { mt := types.MolType(s) if !mt.IsValid() { - FatalError("invalid mol-type %q (must be swarm, patrol, or work)", s) + return in, HandleError("invalid mol-type %q (must be swarm, patrol, or work)", s) } in.molType = &mt } if s, _ := cmd.Flags().GetString("wisp-type"); s != "" { wt := types.WispType(s) if !wt.IsValid() { - FatalError("invalid wisp-type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", s) + return in, HandleError("invalid wisp-type %q (must be heartbeat, ping, patrol, gc_report, recovery, error, or escalation)", s) } in.wispType = &wt } @@ -214,16 +214,37 @@ func gatherListInput(cmd *cobra.Command) listInput { in.deferredFlag, _ = cmd.Flags().GetBool("deferred") in.overdueFlag, _ = cmd.Flags().GetBool("overdue") - in.createdAfter = parseListTimeFlag(cmd, "created-after") - in.createdBefore = parseListTimeFlag(cmd, "created-before") - in.updatedAfter = parseListTimeFlag(cmd, "updated-after") - in.updatedBefore = parseListTimeFlag(cmd, "updated-before") - in.closedAfter = parseListTimeFlag(cmd, "closed-after") - in.closedBefore = parseListTimeFlag(cmd, "closed-before") - in.deferAfter = parseListTimeFlag(cmd, "defer-after") - in.deferBefore = parseListTimeFlag(cmd, "defer-before") - in.dueAfter = parseListTimeFlag(cmd, "due-after") - in.dueBefore = parseListTimeFlag(cmd, "due-before") + var err error + if in.createdAfter, err = parseListTimeFlag(cmd, "created-after"); err != nil { + return in, err + } + if in.createdBefore, err = parseListTimeFlag(cmd, "created-before"); err != nil { + return in, err + } + if in.updatedAfter, err = parseListTimeFlag(cmd, "updated-after"); err != nil { + return in, err + } + if in.updatedBefore, err = parseListTimeFlag(cmd, "updated-before"); err != nil { + return in, err + } + if in.closedAfter, err = parseListTimeFlag(cmd, "closed-after"); err != nil { + return in, err + } + if in.closedBefore, err = parseListTimeFlag(cmd, "closed-before"); err != nil { + return in, err + } + if in.deferAfter, err = parseListTimeFlag(cmd, "defer-after"); err != nil { + return in, err + } + if in.deferBefore, err = parseListTimeFlag(cmd, "defer-before"); err != nil { + return in, err + } + if in.dueAfter, err = parseListTimeFlag(cmd, "due-after"); err != nil { + return in, err + } + if in.dueBefore, err = parseListTimeFlag(cmd, "due-before"); err != nil { + return in, err + } metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field") if len(metadataFieldFlags) > 0 { @@ -231,17 +252,17 @@ func gatherListInput(cmd *cobra.Command) listInput { for _, mf := range metadataFieldFlags { k, v, ok := strings.Cut(mf, "=") if !ok || k == "" { - FatalErrorRespectJSON("invalid --metadata-field: expected key=value, got %q", mf) + return in, HandleErrorRespectJSON("invalid --metadata-field: expected key=value, got %q", mf) } if err := storage.ValidateMetadataKey(k); err != nil { - FatalErrorRespectJSON("invalid --metadata-field key: %v", err) + return in, HandleErrorRespectJSON("invalid --metadata-field key: %v", err) } in.metadataFields[k] = v } } if k, _ := cmd.Flags().GetString("has-metadata-key"); k != "" { if err := storage.ValidateMetadataKey(k); err != nil { - FatalErrorRespectJSON("invalid --has-metadata-key: %v", err) + return in, HandleErrorRespectJSON("invalid --has-metadata-key: %v", err) } in.hasMetadataKey = k } @@ -266,7 +287,7 @@ func gatherListInput(cmd *cobra.Command) listInput { "status": true, "id": true, "title": true, "type": true, "assignee": true, } if !validSortFields[in.sortBy] { - FatalError("invalid sort field %q (valid: priority, created, updated, closed, status, id, title, type, assignee)", in.sortBy) + return in, HandleError("invalid sort field %q (valid: priority, created, updated, closed, status, id, title, type, assignee)", in.sortBy) } } @@ -303,7 +324,7 @@ func gatherListInput(cmd *cobra.Command) listInput { 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") } // --offset only makes sense when pagination happens in SQL. Sorts // that fall back to Go-side (currently --sort id) fetch everything @@ -311,7 +332,7 @@ func gatherListInput(cmd *cobra.Command) listInput { // caller would think they're paging when they're really pulling // the whole result set. if offset > 0 && in.sqlLimit == 0 && in.sortBy == "id" { - FatalError("--offset is not supported with --sort %s (sort requires fetching the full result set)", in.sortBy) + return in, HandleError("--offset is not supported with --sort %s (sort requires fetching the full result set)", in.sortBy) } in.offset = offset } @@ -319,17 +340,17 @@ func gatherListInput(cmd *cobra.Command) listInput { in.repoOverride, _ = cmd.Flags().GetString("repo") in.repoOverrideSet = cmd.Flags().Changed("repo") - return in + return in, nil } -func parseListTimeFlag(cmd *cobra.Command, name string) *time.Time { +func parseListTimeFlag(cmd *cobra.Command, name string) (*time.Time, error) { s, _ := cmd.Flags().GetString(name) if s == "" { - return nil + return nil, nil } t, err := parseTimeFlag(s) if err != nil { - FatalError("parsing --%s: %v", name, err) + return nil, HandleError("parsing --%s: %v", name, err) } - return &t + return &t, nil } diff --git a/cmd/bd/list_proxied_server.go b/cmd/bd/list_proxied_server.go index 571ea120b..3b7a79f1a 100644 --- a/cmd/bd/list_proxied_server.go +++ b/cmd/bd/list_proxied_server.go @@ -79,8 +79,7 @@ func runListProxiedSearch(_ *cobra.Command, ctx context.Context, in listInput) e if err != nil { return err } - emitProxiedListJSONResult(page.Items, in, page.HasMore) - return nil + return emitProxiedListJSONResult(page.Items, in, page.HasMore) } page, err := uw.IssueUseCase().SearchIssues(ctx, "", filter) @@ -150,8 +149,7 @@ func runListProxiedReady(_ *cobra.Command, ctx context.Context, in listInput) er if err != nil { return err } - emitProxiedListJSONResult(page.Items, in, page.HasMore) - return nil + return emitProxiedListJSONResult(page.Items, in, page.HasMore) } page, err := uw.IssueUseCase().GetReadyWork(ctx, wf) @@ -254,17 +252,22 @@ func runListProxiedWatch(_ *cobra.Command, ctx context.Context, in listInput) er } } -func emitProxiedListJSONResult(iwc []*types.IssueWithCounts, in listInput, hasMore bool) { +func emitProxiedListJSONResult(iwc []*types.IssueWithCounts, in listInput, hasMore bool) error { sortIssuesWithCounts(iwc, in.sortBy, in.reverse) if iwc == nil { iwc = []*types.IssueWithCounts{} } + var err error if in.skipLabels { - outputJSON(newSkipLabelsListJSONResponse(iwc)) + err = outputJSON(newSkipLabelsListJSONResponse(iwc)) } else { - outputJSON(iwc) + err = outputJSON(iwc) + } + if err != nil { + return err } printTruncationHint(hasMore, in.effectiveLimit) + return nil } func loadDepsForIssues(ctx context.Context, uw uow.UnitOfWork, issues []*types.Issue) (map[string][]*types.Dependency, error) { diff --git a/cmd/bd/mail.go b/cmd/bd/mail.go index 784dda0a1..7bec2e72e 100644 --- a/cmd/bd/mail.go +++ b/cmd/bd/mail.go @@ -1,12 +1,13 @@ package main import ( - "fmt" "os" "os/exec" "strings" "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/metrics" ) // mailCmd delegates to an external mail provider. @@ -35,38 +36,39 @@ Examples: bd mail inbox # Lists inbox bd mail send mayor/ -s "Hi" # Sends mail bd mail read msg-123 # Reads a message`, - DisableFlagParsing: true, // Pass all args through to delegate - Run: func(cmd *cobra.Command, args []string) { - // Handle --help and -h ourselves since flag parsing is disabled + DisableFlagParsing: true, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mail") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + for _, arg := range args { if arg == "--help" || arg == "-h" { - _ = cmd.Help() // Help() always returns nil for cobra commands - return + _ = cmd.Help() + return nil } } - // Find the mail delegate command delegate := findMailDelegate() if delegate == "" { - fmt.Fprintf(os.Stderr, "Error: no mail delegate configured\n\n") - fmt.Fprintf(os.Stderr, "bd mail delegates to an external mail provider.\n") - fmt.Fprintf(os.Stderr, "Configure one of:\n") - fmt.Fprintf(os.Stderr, " export BEADS_MAIL_DELEGATE=\"gt mail\" # Environment variable\n") - fmt.Fprintf(os.Stderr, " bd config set mail.delegate \"gt mail\" # Per-project config\n") - os.Exit(1) + return HandleErrorWithHint( + "no mail delegate configured", + "Set BEADS_MAIL_DELEGATE=\"gt mail\" or run: bd config set mail.delegate \"gt mail\"") } - // Parse the delegate command (e.g., "gt mail" -> ["gt", "mail"]) parts := strings.Fields(delegate) if len(parts) == 0 { - FatalError("invalid mail delegate: %q", delegate) + return HandleError("invalid mail delegate: %q", delegate) } - // Build the full command with our args appended cmdName := parts[0] cmdArgs := append(parts[1:], args...) - // Execute the delegate command // #nosec G204 - cmdName comes from user configuration (mail_delegate setting) execCmd := exec.Command(cmdName, cmdArgs...) execCmd.Stdin = os.Stdin @@ -74,12 +76,12 @@ Examples: execCmd.Stderr = os.Stderr if err := execCmd.Run(); err != nil { - // Try to preserve the exit code if exitErr, ok := err.(*exec.ExitError); ok { - os.Exit(exitErr.ExitCode()) + return &exitError{Code: exitErr.ExitCode()} } - FatalError("running %s: %v", delegate, err) + return HandleError("running %s: %v", delegate, err) } + return nil }, } diff --git a/cmd/bd/main.go b/cmd/bd/main.go index b728dd5d6..fa2283329 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -26,6 +26,7 @@ import ( "github.com/steveyegge/beads/internal/debug" "github.com/steveyegge/beads/internal/doltserver" "github.com/steveyegge/beads/internal/hooks" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/molecules" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" @@ -576,13 +577,13 @@ func resolveChangeDirBeadsDir(path string) (string, error) { return beadsDir, nil } -func applyChangeDirSelection() { +func applyChangeDirSelection() error { if strings.TrimSpace(changeDir) == "" { - return + return nil } beadsDir, err := resolveChangeDirBeadsDir(changeDir) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } changeDirEnvSnapshot = make(map[string]envSnapshotValue, 3) for _, key := range []string{"BEADS_DIR", "BEADS_DB", "BD_DB"} { @@ -590,6 +591,7 @@ func applyChangeDirSelection() { changeDirEnvSnapshot[key] = envSnapshotValue{value: value, ok: ok} } _ = os.Setenv("BEADS_DIR", beadsDir) + return nil } func restoreChangeDirSelection() { @@ -619,7 +621,7 @@ var rootCmd = &cobra.Command{ // No subcommand - show help _ = cmd.Help() // Help() always returns nil for cobra commands }, - PersistentPreRun: func(cmd *cobra.Command, args []string) { + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { // Initialize CommandContext to hold runtime state (replaces scattered globals) initCommandContext() @@ -641,6 +643,20 @@ var rootCmd = &cobra.Command{ debug.Logf("warning: telemetry init failed: %v", err) } + if cmd.Name() != metrics.SendMetricsSubcommand { + if err := metrics.EnsureUserConfigDefaults(); err != nil { + debug.Logf("warning: ensure user config defaults failed: %v", err) + } + } + + if _, err := metrics.Init(Version, resolveMetricsEnabled(), resolveMetricsEndpoint()); err != nil { + debug.Logf("warning: metrics init failed: %v", err) + } + + if cmd.Name() == metrics.SendMetricsSubcommand { + return nil + } + // Start root span for this command. rootCtx now carries the span, so // all downstream DB and AI calls become child spans automatically. rootCtx, commandSpan = telemetry.Tracer("bd").Start(rootCtx, "bd.command."+cmd.Name(), @@ -655,11 +671,13 @@ var rootCmd = &cobra.Command{ debug.SetVerbose(verboseFlag) debug.SetQuiet(quietFlag) - applyChangeDirSelection() + if err := applyChangeDirSelection(); err != nil { + return err + } // Block dangerous env var overrides that could cause data fragmentation (bd-hevyw). if err := checkBlockedEnvVars(); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } loadSelectionEnvironment() @@ -763,6 +781,7 @@ var rootCmd = &cobra.Command{ "powershell", "prime", "quickstart", + metrics.SendMetricsSubcommand, "setup", "version", "where", @@ -821,12 +840,12 @@ var rootCmd = &cobra.Command{ loadServerModeFromConfig() } if _, err := getDoltAutoCommitMode(); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } if skipsStoreInit { - return + return nil } // Performance profiling setup @@ -885,7 +904,7 @@ var rootCmd = &cobra.Command{ prepareSelectedCommandContext(beadsDir, false) } } - return + return nil } if cmd.Name() != "import" && cmd.Name() != "setup" { @@ -915,7 +934,7 @@ var rootCmd = &cobra.Command{ prepareSelectedCommandContext(beadsDir, true) refreshBoundCommandConfig(cmd) if _, err := getDoltAutoCommitMode(); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } // Set actor for audit trail @@ -1034,7 +1053,7 @@ var rootCmd = &cobra.Command{ // Must be in shared-server mode; errors otherwise. if globalFlag { if !doltserver.IsSharedServerMode() { - FatalError("--global requires shared-server mode (set BEADS_DOLT_SHARED_SERVER=1 or dolt.shared-server: true in config.yaml)") + return HandleError("--global requires shared-server mode (set BEADS_DOLT_SHARED_SERVER=1 or dolt.shared-server: true in config.yaml)") } doltCfg.Database = doltserver.GlobalDatabaseName } @@ -1046,12 +1065,12 @@ var rootCmd = &cobra.Command{ if proxiedServerMode { p, err := newProxiedServerUOWProvider(rootCtx, beadsDir) if err != nil { - FatalError("failed to open uow provider: %v", err) + return HandleError("failed to open uow provider: %v", err) } uowProvider = p syncCommandContext() - return + return nil } // Default auto-commit based on mode when the user hasn't set a value: @@ -1106,7 +1125,7 @@ var rootCmd = &cobra.Command{ } os.Exit(1) } - FatalError("failed to open database: %v", err) + return HandleError("failed to open database: %v", err) } // Mark store as active for flush goroutine safety @@ -1170,8 +1189,9 @@ var rootCmd = &cobra.Command{ // Tips (including sync conflict proactive checks) are shown via maybeShowTip() // after successful command execution, not in PreRun + return nil }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { + PersistentPostRunE: func(cmd *cobra.Command, args []string) error { defer restoreChangeDirSelection() if proxiedServerMode { @@ -1184,7 +1204,7 @@ var rootCmd = &cobra.Command{ // create a Dolt commit so changes don't remain only in the working set. if commandDidWrite.Load() && !commandDidExplicitDoltCommit { if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil { - FatalError("dolt auto-commit failed: %v", err) + return HandleError("dolt auto-commit failed: %v", err) } } @@ -1193,14 +1213,14 @@ var rootCmd = &cobra.Command{ if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 { // Only applies when dolt auto-commit is enabled and backend is versioned (Dolt). if mode, err := getDoltAutoCommitMode(); err != nil { - FatalError("dolt tip auto-commit failed: %v", err) + return HandleError("dolt tip auto-commit failed: %v", err) } else if mode == doltAutoCommitOn { // Apply tip metadata writes now (deferred in recordTipShown for Dolt). for tipID := range commandTipIDsShown { key := fmt.Sprintf("tip_%s_last_shown", tipID) value := time.Now().Format(time.RFC3339) if err := store.SetLocalMetadata(rootCtx, key, value); err != nil { - FatalError("dolt tip auto-commit failed: %v", err) + return HandleError("dolt tip auto-commit failed: %v", err) } } @@ -1210,7 +1230,7 @@ var rootCmd = &cobra.Command{ } msg := formatDoltAutoCommitMessage("tip", getActor(), ids) if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil { - FatalError("dolt tip auto-commit failed: %v", err) + return HandleError("dolt tip auto-commit failed: %v", err) } } } @@ -1223,7 +1243,7 @@ var rootCmd = &cobra.Command{ // sync guidance after machine-readable output. if shouldRunPostCommandAutoExport(cmd) { if err := maybeAutoExport(rootCtx, serverMode, commandAllowsEmptyAutoExport(cmd)); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } @@ -1266,6 +1286,7 @@ var rootCmd = &cobra.Command{ if rootCancel != nil { rootCancel() } + return nil }, } @@ -1427,7 +1448,47 @@ func main() { rootCmd.InitDefaultHelpCmd() registerHelpAllFlag() - if err := rootCmd.Execute(); err != nil { + executedCmd, err := rootCmd.ExecuteC() + + metricsCloseCtx, metricsCloseCancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + if c := metrics.Global(); c != nil { + _ = c.Close(metricsCloseCtx) + } + metricsCloseCancel() + metrics.MaybeSpawnFlusher() + + if err != nil { + if code, ok := exitCodeFromError(err); ok { + os.Exit(code) + } + if executedCmd != nil && executedCmd.SilenceErrors { + fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error()) + } os.Exit(1) } } + +func resolveMetricsEnabled() bool { + if v, ok := os.LookupEnv(metrics.EnvDisableMetrics); ok { + return !envTruthyValue(v) + } + return !config.GetBool("metrics.disabled") +} + +func resolveMetricsEndpoint() string { + if v := os.Getenv(metrics.EnvEndpoint); v != "" { + return v + } + return config.GetString("metrics.endpoint") +} + +func envTruthyValue(v string) bool { + if v == "" { + return false + } + switch strings.ToLower(v) { + case "0", "false": + return false + } + return true +} diff --git a/cmd/bd/markdown.go b/cmd/bd/markdown.go index 4faf482cb..d0e83ee68 100644 --- a/cmd/bd/markdown.go +++ b/cmd/bd/markdown.go @@ -303,20 +303,18 @@ func parseMarkdownFile(path string) ([]*IssueTemplate, error) { } // createIssuesFromMarkdown parses a markdown file and creates multiple issues from it -func createIssuesFromMarkdown(_ *cobra.Command, filepath string) { - // Parse markdown file first (doesn't require store access) +func createIssuesFromMarkdown(_ *cobra.Command, filepath string) error { templates, err := parseMarkdownFile(filepath) 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") } - // Ensure globals are initialized if store == nil { - FatalErrorWithHint("database not initialized", + return HandleErrorWithHint("database not initialized", diagHint()) } if actor == "" { @@ -354,7 +352,7 @@ func createIssuesFromMarkdown(_ *cobra.Command, filepath string) { if strings.Contains(depSpec, ":") { parts := strings.SplitN(depSpec, ":", 2) if len(parts) != 2 { - FatalError("invalid dependency format '%s' for issue '%s'", depSpec, template.Title) + return HandleError("invalid dependency format '%s' for issue '%s'", depSpec, template.Title) } depType = types.DependencyType(strings.TrimSpace(parts[0])) dependsOnID = strings.TrimSpace(parts[1]) @@ -364,7 +362,7 @@ func createIssuesFromMarkdown(_ *cobra.Command, filepath string) { } if !depType.IsValid() { - FatalError("invalid dependency type '%s' for issue '%s'", depType, template.Title) + return HandleError("invalid dependency type '%s' for issue '%s'", depType, template.Title) } // IssueID left empty — PersistDependencies defaults it to issue.ID @@ -379,7 +377,7 @@ func createIssuesFromMarkdown(_ *cobra.Command, filepath string) { } if err := store.CreateIssues(ctx, issues, actor); 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(templates), filepath) issueIDs := make([]string, 0, len(issues)) @@ -396,11 +394,11 @@ func createIssuesFromMarkdown(_ *cobra.Command, filepath string) { createdIssues = append(createdIssues, issues...) if jsonOutput { - outputJSON(createdIssues) - } else { - fmt.Printf("%s Created %d issues from %s:\n", ui.RenderPass("āœ“"), len(createdIssues), filepath) - for _, issue := range createdIssues { - fmt.Printf(" %s: %s [P%d, %s]\n", issue.ID, issue.Title, issue.Priority, issue.IssueType) - } + return outputJSON(createdIssues) } + fmt.Printf("%s Created %d issues from %s:\n", ui.RenderPass("āœ“"), len(createdIssues), filepath) + for _, issue := range createdIssues { + fmt.Printf(" %s: %s [P%d, %s]\n", issue.ID, issue.Title, issue.Priority, issue.IssueType) + } + return nil } diff --git a/cmd/bd/memory.go b/cmd/bd/memory.go index fe2cc4f95..4b9480126 100644 --- a/cmd/bd/memory.go +++ b/cmd/bd/memory.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage/kvkeys" ) @@ -56,34 +57,41 @@ Examples: bd remember "always run tests with -race flag" bd remember "Dolt phantom DBs hide in three places" --key dolt-phantoms bd remember "auth module uses JWT not sessions" --key auth-jwt`, - GroupID: "setup", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + GroupID: "setup", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("remember") + evt := metrics.NewCommandEvent("remember") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("remember requires direct database access"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } insight := args[0] if strings.TrimSpace(insight) == "" { - FatalErrorRespectJSON("memory content cannot be empty") + return HandleErrorRespectJSON("memory content cannot be empty") } - // Generate or use provided key key := memoryKeyFlag if key == "" { key = slugify(insight) } if key == "" { - FatalErrorRespectJSON("could not generate key from content; use --key to specify one") + return HandleErrorRespectJSON("could not generate key from content; use --key to specify one") } storageKey := kvPrefix + memoryPrefix + key ctx := rootCtx - // Check if updating an existing memory existing, _ := store.GetConfig(ctx, storageKey) verb := "Remembered" if existing != "" { @@ -91,19 +99,19 @@ Examples: } if err := store.SetConfig(ctx, storageKey, insight); err != nil { - FatalErrorRespectJSON("storing memory: %v", err) + return HandleErrorRespectJSON("storing memory: %v", err) } commandDidWrite.Store(true) if jsonOutput { - outputJSON(map[string]string{ + return outputJSON(map[string]string{ "key": key, "value": insight, "action": strings.ToLower(verb), }) - } else { - fmt.Printf("%s [%s]: %s\n", verb, key, truncateMemory(insight, 80)) } + fmt.Printf("%s [%s]: %s\n", verb, key, truncateMemory(insight, 80)) + return nil }, } @@ -117,17 +125,26 @@ Examples: bd memories # list all memories bd memories dolt # search for memories about dolt bd memories "race flag" # search for a phrase`, - GroupID: "setup", - Args: cobra.MaximumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + GroupID: "setup", + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("memories") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("memories requires direct database access"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } ctx := rootCtx allConfig, err := store.GetAllConfig(ctx) if err != nil { - FatalErrorRespectJSON("listing memories: %v", err) + return HandleErrorRespectJSON("listing memories: %v", err) } // Filter for kv.memory.* keys @@ -140,7 +157,6 @@ Examples: } } - // Apply search filter if provided var search string if len(args) > 0 { search = strings.ToLower(args[0]) @@ -157,8 +173,7 @@ Examples: } if jsonOutput { - outputJSON(memories) - return + return outputJSON(memories) } if len(memories) == 0 { @@ -167,10 +182,9 @@ Examples: } else { fmt.Println("No memories stored. Use 'bd remember \"insight\"' to add one.") } - return + return nil } - // Sort keys for consistent output keys := make([]string, 0, len(memories)) for k := range memories { keys = append(keys, k) @@ -185,9 +199,9 @@ Examples: for _, k := range keys { v := memories[k] fmt.Printf(" %s\n", k) - // Indent the value, wrapping long lines fmt.Printf(" %s\n\n", truncateMemory(v, 120)) } + return nil }, } @@ -202,13 +216,22 @@ Use 'bd memories' to see available keys. Examples: bd forget dolt-phantoms bd forget auth-jwt`, - GroupID: "setup", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + GroupID: "setup", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("forget") + evt := metrics.NewCommandEvent("forget") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("forget requires direct database access"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } key := args[0] @@ -216,33 +239,34 @@ Examples: ctx := rootCtx - // Check if it exists first existing, _ := store.GetConfig(ctx, storageKey) if existing == "" { if jsonOutput { - outputJSON(map[string]string{ + if jerr := outputJSON(map[string]string{ "key": key, "found": "false", - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } fmt.Fprintf(os.Stderr, "No memory with key %q\n", key) - os.Exit(1) + return SilentExit() } if err := store.DeleteConfig(ctx, storageKey); err != nil { - FatalErrorRespectJSON("forgetting memory: %v", err) + return HandleErrorRespectJSON("forgetting memory: %v", err) } commandDidWrite.Store(true) if jsonOutput { - outputJSON(map[string]string{ + return outputJSON(map[string]string{ "key": key, "deleted": "true", }) - } else { - fmt.Printf("Forgot [%s]: %s\n", key, truncateMemory(existing, 80)) } + fmt.Printf("Forgot [%s]: %s\n", key, truncateMemory(existing, 80)) + return nil }, } @@ -255,11 +279,20 @@ var recallCmd = &cobra.Command{ Examples: bd recall dolt-phantoms bd recall auth-jwt`, - GroupID: "setup", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + GroupID: "setup", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("recall") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("recall requires direct database access"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } key := args[0] @@ -268,26 +301,28 @@ Examples: ctx := rootCtx value, err := store.GetConfig(ctx, storageKey) if err != nil { - FatalErrorRespectJSON("recalling memory: %v", err) + return HandleErrorRespectJSON("recalling memory: %v", err) } if jsonOutput { - result := map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "key": key, "value": value, "found": value != "", + }); jerr != nil { + return jerr } - outputJSON(result) if value == "" { - os.Exit(1) + return SilentExit() } - } else { - if value == "" { - fmt.Fprintf(os.Stderr, "No memory with key %q\n", key) - os.Exit(1) - } - fmt.Printf("%s\n", value) + return nil } + if value == "" { + fmt.Fprintf(os.Stderr, "No memory with key %q\n", key) + return SilentExit() + } + fmt.Printf("%s\n", value) + return nil }, } diff --git a/cmd/bd/merge_slot.go b/cmd/bd/merge_slot.go index b94d9e5e6..c257db290 100644 --- a/cmd/bd/merge_slot.go +++ b/cmd/bd/merge_slot.go @@ -6,6 +6,7 @@ import ( "os" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/ui" ) @@ -42,8 +43,10 @@ var mergeSlotCreateCmd = &cobra.Command{ The slot ID is automatically generated based on the beads prefix (e.g., gt-merge-slot). The slot is created with status=open (available).`, - Args: cobra.NoArgs, - RunE: runMergeSlotCreate, + Args: cobra.NoArgs, + SilenceUsage: true, + SilenceErrors: true, + RunE: runMergeSlotCreate, } var mergeSlotCheckCmd = &cobra.Command{ @@ -55,8 +58,10 @@ Returns: - available: slot can be acquired - held by : slot is currently held - not found: no merge slot exists for this rig`, - Args: cobra.NoArgs, - RunE: runMergeSlotCheck, + Args: cobra.NoArgs, + SilenceUsage: true, + SilenceErrors: true, + RunE: runMergeSlotCheck, } var mergeSlotAcquireCmd = &cobra.Command{ @@ -72,8 +77,10 @@ If the slot is held (status=in_progress), the command fails unless --wait is passed, which adds the requester to the waiters queue. Use --holder to specify who is acquiring (default: BEADS_ACTOR env var).`, - Args: cobra.NoArgs, - RunE: runMergeSlotAcquire, + Args: cobra.NoArgs, + SilenceUsage: true, + SilenceErrors: true, + RunE: runMergeSlotAcquire, } var mergeSlotReleaseCmd = &cobra.Command{ @@ -83,8 +90,10 @@ var mergeSlotReleaseCmd = &cobra.Command{ Sets status back to open and clears the holder field. If there are waiters, the highest-priority waiter should then acquire.`, - Args: cobra.NoArgs, - RunE: runMergeSlotRelease, + Args: cobra.NoArgs, + SilenceUsage: true, + SilenceErrors: true, + RunE: runMergeSlotRelease, } var ( @@ -107,9 +116,16 @@ func init() { func runMergeSlotCreate(cmd *cobra.Command, args []string) error { CheckReadonly("merge-slot create") + evt := metrics.NewCommandEvent("merge-slot-create") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + issue, err := store.MergeSlotCreate(rootCtx, actor) if err != nil { - return err + return HandleErrorRespectJSON("%v", err) } commandDidWrite.Store(true) @@ -129,6 +145,13 @@ func runMergeSlotCreate(cmd *cobra.Command, args []string) error { } func runMergeSlotCheck(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("merge-slot-check") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + status, err := store.MergeSlotCheck(rootCtx) if err != nil { if isNotFoundErr(err) { @@ -147,7 +170,7 @@ func runMergeSlotCheck(cmd *cobra.Command, args []string) error { fmt.Printf("Run 'bd merge-slot create' to create one.\n") return nil } - return err + return HandleErrorRespectJSON("%v", err) } if jsonOutput { @@ -181,21 +204,27 @@ func runMergeSlotCheck(cmd *cobra.Command, args []string) error { func runMergeSlotAcquire(cmd *cobra.Command, args []string) error { CheckReadonly("merge-slot acquire") + evt := metrics.NewCommandEvent("merge-slot-acquire") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + holder := mergeSlotHolder if holder == "" { holder = actor } if holder == "" { - return fmt.Errorf("no holder specified; use --holder or set BEADS_ACTOR env var") + return HandleError("no holder specified; use --holder or set BEADS_ACTOR env var") } result, err := store.MergeSlotAcquire(rootCtx, holder, actor, mergeSlotAddWaiter) if err != nil { - return err + return HandleErrorRespectJSON("%v", err) } if !result.Acquired && !result.Waiting { - // Slot was held, no --wait flag. if jsonOutput { out := map[string]interface{}{ "id": result.SlotID, @@ -204,12 +233,14 @@ func runMergeSlotAcquire(cmd *cobra.Command, args []string) error { } encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("", " ") - _ = encoder.Encode(out) - } else { - fmt.Printf("%s Slot held by: %s\n", ui.RenderFail("āœ—"), result.Holder) - fmt.Printf("Use --wait to add yourself to the waiters queue.\n") + if eerr := encoder.Encode(out); eerr != nil { + return eerr + } + return SilentExit() } - os.Exit(1) + return HandleErrorWithHint( + fmt.Sprintf("slot held by: %s", result.Holder), + "Use --wait to add yourself to the waiters queue.") } if result.Waiting { @@ -223,12 +254,14 @@ func runMergeSlotAcquire(cmd *cobra.Command, args []string) error { } encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("", " ") - _ = encoder.Encode(out) - } else { - fmt.Printf("%s Slot held by %s, added to waiters queue (position %d)\n", - ui.RenderAccent("ā—‹"), result.Holder, result.Position) + if eerr := encoder.Encode(out); eerr != nil { + return eerr + } + return SilentExit() } - os.Exit(1) + fmt.Printf("%s Slot held by %s, added to waiters queue (position %d)\n", + ui.RenderAccent("ā—‹"), result.Holder, result.Position) + return SilentExit() } // Successfully acquired. @@ -253,8 +286,15 @@ func runMergeSlotAcquire(cmd *cobra.Command, args []string) error { func runMergeSlotRelease(cmd *cobra.Command, args []string) error { CheckReadonly("merge-slot release") + evt := metrics.NewCommandEvent("merge-slot-release") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := store.MergeSlotRelease(rootCtx, mergeSlotHolder, actor); err != nil { - return err + return HandleErrorRespectJSON("%v", err) } commandDidWrite.Store(true) diff --git a/cmd/bd/migrate.go b/cmd/bd/migrate.go index 51a1a62a0..1ea2e2db5 100644 --- a/cmd/bd/migrate.go +++ b/cmd/bd/migrate.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/schema" "github.com/steveyegge/beads/internal/types" @@ -29,78 +30,79 @@ Subcommands: schema Apply pending schema migrations (idempotent) sync Set up sync.branch workflow for multi-clone setups `, - Run: func(cmd *cobra.Command, _ []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("migrate") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + autoYes, _ := cmd.Flags().GetBool("yes") dryRun, _ := cmd.Flags().GetBool("dry-run") updateRepoID, _ := cmd.Flags().GetBool("update-repo-id") inspect, _ := cmd.Flags().GetBool("inspect") - // Block writes in readonly mode (migration modifies data, --inspect is read-only) if !dryRun && !inspect { CheckReadonly("migrate") } - // Handle --update-repo-id first if updateRepoID { - handleUpdateRepoID(dryRun, autoYes) - return + return handleUpdateRepoID(dryRun, autoYes) } - // Handle --inspect flag (show migration plan for AI agents) if inspect { - handleInspect() - return + return handleInspect() } - // Find .beads directory beadsDir := beads.FindBeadsDir() if beadsDir == "" { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "no_beads_directory", "message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".", - }) - os.Exit(1) - } else { - FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) + }); jerr != nil { + return jerr + } + return SilentExit() } + return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } - // Load config cfg, err := loadOrCreateConfig(beadsDir) if err != nil { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "config_load_failed", "message": err.Error(), - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalError("failed to load config: %v", err) + return HandleError("failed to load config: %v", err) } - // Handle Dolt metadata update - handleDoltMetadataUpdate(cfg, dryRun) + return handleDoltMetadataUpdate(cfg, dryRun) }, } -// handleDoltMetadataUpdate handles version metadata updates for Dolt backends. -func handleDoltMetadataUpdate(cfg *configfile.Config, dryRun bool) { +func handleDoltMetadataUpdate(cfg *configfile.Config, dryRun bool) error { ctx := rootCtx store := getStore() if store == nil { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "no_databases", "message": "No Dolt database found in .beads/", }) - } else { - fmt.Fprintf(os.Stderr, "No Dolt database found. Run 'bd init' to create a new database.\n") } - return + fmt.Fprintf(os.Stderr, "No Dolt database found. Run 'bd init' to create a new database.\n") + return nil } - // Check current state of all metadata fields currentVersion, _ := store.GetLocalMetadata(ctx, "bd_version") currentRepoID, _ := store.GetMetadata(ctx, "repo_id") currentCloneID, _ := store.GetMetadata(ctx, "clone_id") @@ -109,19 +111,17 @@ func handleDoltMetadataUpdate(cfg *configfile.Config, dryRun bool) { needsRepoID := currentRepoID == "" needsCloneID := currentCloneID == "" - // If everything is already current, return early if !needsVersionUpdate && !needsRepoID && !needsCloneID { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "current", "message": fmt.Sprintf("Dolt database already at version %s", Version), }) - } else { - fmt.Printf("Dolt database version: %s\n", currentVersion) - fmt.Printf("%s\n", ui.RenderPass("āœ“ Version matches")) - fmt.Printf("%s\n", ui.RenderPass("āœ“ All metadata fields present")) } - return + fmt.Printf("Dolt database version: %s\n", currentVersion) + fmt.Printf("%s\n", ui.RenderPass("āœ“ Version matches")) + fmt.Printf("%s\n", ui.RenderPass("āœ“ All metadata fields present")) + return nil } if dryRun { @@ -136,20 +136,19 @@ func handleDoltMetadataUpdate(cfg *configfile.Config, dryRun bool) { dryRunResult["target_version"] = Version } if jsonOutput { - outputJSON(dryRunResult) - } else { - fmt.Println("Dry run mode - no changes will be made") - if needsVersionUpdate { - fmt.Printf("Would update Dolt version: %s → %s\n", currentVersion, Version) - } - if needsRepoID { - fmt.Println("Would set repo_id") - } - if needsCloneID { - fmt.Println("Would set clone_id") - } + return outputJSON(dryRunResult) } - return + fmt.Println("Dry run mode - no changes will be made") + if needsVersionUpdate { + fmt.Printf("Would update Dolt version: %s → %s\n", currentVersion, Version) + } + if needsRepoID { + fmt.Println("Would set repo_id") + } + if needsCloneID { + fmt.Println("Would set clone_id") + } + return nil } versionUpdated := false @@ -180,16 +179,17 @@ func handleDoltMetadataUpdate(cfg *configfile.Config, dryRun bool) { } } - // Update version metadata (fatal on failure — version is critical) if err := store.SetLocalMetadata(ctx, "bd_version", Version); err != nil { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "version_update_failed", "message": err.Error(), - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalError("failed to update version: %v", err) + return HandleError("failed to update version: %v", err) } versionUpdated = true @@ -240,8 +240,12 @@ func handleDoltMetadataUpdate(cfg *configfile.Config, dryRun bool) { } } + if versionUpdated || repoIDSet || cloneIDSet { + commandDidWrite.Store(true) + } + if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "success", "current_database": cfg.Database, "backend": "dolt", @@ -250,13 +254,9 @@ func handleDoltMetadataUpdate(cfg *configfile.Config, dryRun bool) { "repo_id_set": repoIDSet, "clone_id_set": cloneIDSet, }) - } else { - fmt.Printf("\nDolt database: %s (version %s)\n", cfg.Database, Version) - } - - if versionUpdated || repoIDSet || cloneIDSet { - commandDidWrite.Store(true) } + fmt.Printf("\nDolt database: %s (version %s)\n", cfg.Database, Version) + return nil } // truncateID safely truncates an ID string to maxLen characters. @@ -282,50 +282,53 @@ func loadOrCreateConfig(beadsDir string) (*configfile.Config, error) { return cfg, nil } -func handleUpdateRepoID(dryRun bool, autoYes bool) { - // Find .beads directory +func handleUpdateRepoID(dryRun bool, autoYes bool) error { beadsDir := beads.FindBeadsDir() if beadsDir == "" { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "no_database", "message": "No beads database found. " + diagHint() + ".", - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalErrorWithHint("no beads database found", diagHint()) + return HandleErrorWithHint("no beads database found", diagHint()) } - // Compute new repo ID newRepoID, err := beads.ComputeRepoID() if err != nil { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "compute_failed", "message": err.Error(), - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalError("failed to compute repository ID: %v", err) + return HandleError("failed to compute repository ID: %v", err) } store := getStore() if store == nil { - FatalError("no database — run 'bd init' first") + return HandleError("no database — run 'bd init' first") } - // Get old repo ID ctx := rootCtx oldRepoID, err := store.GetMetadata(ctx, "repo_id") if err != nil && err.Error() != "metadata key not found: repo_id" { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "read_failed", "message": err.Error(), - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalError("failed to read repo_id: %v", err) + return HandleError("failed to read repo_id: %v", err) } oldDisplay := "none" @@ -335,21 +338,19 @@ func handleUpdateRepoID(dryRun bool, autoYes bool) { if dryRun { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "dry_run": true, "old_repo_id": oldDisplay, "new_repo_id": truncateID(newRepoID, 8), }) - } else { - fmt.Println("Dry run mode - no changes will be made") - fmt.Printf("Would update repository ID:\n") - fmt.Printf(" Old: %s\n", oldDisplay) - fmt.Printf(" New: %s\n", truncateID(newRepoID, 8)) } - return + fmt.Println("Dry run mode - no changes will be made") + fmt.Printf("Would update repository ID:\n") + fmt.Printf(" Old: %s\n", oldDisplay) + fmt.Printf(" New: %s\n", truncateID(newRepoID, 8)) + return nil } - // Prompt for confirmation if repo_id exists and differs if oldRepoID != "" && oldRepoID != newRepoID && !autoYes && !jsonOutput { fmt.Printf("WARNING: Changing repository ID can break sync if other clones exist.\n\n") fmt.Printf("Current repo ID: %s\n", oldDisplay) @@ -359,56 +360,55 @@ func handleUpdateRepoID(dryRun bool, autoYes bool) { _, _ = fmt.Scanln(&response) if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" { fmt.Println("Canceled") - return + return nil } } - // Update repo ID if err := store.SetMetadata(ctx, "repo_id", newRepoID); err != nil { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "update_failed", "message": err.Error(), - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalError("failed to update repo_id: %v", err) + return HandleError("failed to update repo_id: %v", err) } + commandDidWrite.Store(true) + if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "success", "old_repo_id": oldDisplay, "new_repo_id": truncateID(newRepoID, 8), }) - } else { - fmt.Printf("%s\n\n", ui.RenderPass("āœ“ Repository ID updated")) - fmt.Printf(" Old: %s\n", oldDisplay) - fmt.Printf(" New: %s\n", truncateID(newRepoID, 8)) } - - commandDidWrite.Store(true) + fmt.Printf("%s\n\n", ui.RenderPass("āœ“ Repository ID updated")) + fmt.Printf(" Old: %s\n", oldDisplay) + fmt.Printf(" New: %s\n", truncateID(newRepoID, 8)) + return nil } -// handleInspect shows migration plan and database state for AI agent analysis -func handleInspect() { - // Find .beads directory +func handleInspect() error { beadsDir := beads.FindBeadsDir() if beadsDir == "" { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "no_beads_directory", "message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".", - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) + return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } - // Check if database is available via the global store dbExists := getStore() != nil - // If database doesn't exist, return inspection with defaults if !dbExists { result := map[string]interface{}{ "registered_migrations": listMigrations(), @@ -424,19 +424,18 @@ func handleInspect() { } if jsonOutput { - outputJSON(result) - } else { - fmt.Println("\nMigration Inspection") - fmt.Println("====================") - fmt.Println("Database: missing") - fmt.Println("\n⚠ Database does not exist - " + diagHint()) + return outputJSON(result) } - return + fmt.Println("\nMigration Inspection") + fmt.Println("====================") + fmt.Println("Database: missing") + fmt.Println("\n⚠ Database does not exist - " + diagHint()) + return nil } store := getStore() if store == nil { - FatalError("no database — run 'bd init' first") + return HandleError("no database — run 'bd init' first") } ctx := rootCtx @@ -497,78 +496,86 @@ func handleInspect() { } if jsonOutput { - outputJSON(result) - } else { - fmt.Println("\nMigration Inspection") - fmt.Println("====================") - fmt.Printf("Schema Version: %s\n", schemaVersion) - fmt.Printf("Issue Count: %d\n", issueCount) - fmt.Printf("Registered Migrations: %d\n", len(registeredMigrations)) - - if len(warnings) > 0 { - fmt.Println("\nWarnings:") - for _, w := range warnings { - fmt.Printf(" ⚠ %s\n", w) - } - } - - if len(missingConfig) > 0 { - fmt.Println("\nMissing Config:") - for _, k := range missingConfig { - fmt.Printf(" - %s\n", k) - } - } - fmt.Println() + return outputJSON(result) } + fmt.Println("\nMigration Inspection") + fmt.Println("====================") + fmt.Printf("Schema Version: %s\n", schemaVersion) + fmt.Printf("Issue Count: %d\n", issueCount) + fmt.Printf("Registered Migrations: %d\n", len(registeredMigrations)) + + if len(warnings) > 0 { + fmt.Println("\nWarnings:") + for _, w := range warnings { + fmt.Printf(" ⚠ %s\n", w) + } + } + + if len(missingConfig) > 0 { + fmt.Println("\nMissing Config:") + for _, k := range missingConfig { + fmt.Printf(" - %s\n", k) + } + } + fmt.Println() + return nil } -func handleSchemaMigrate() { +func handleSchemaMigrate() error { beadsDir := beads.FindBeadsDir() if beadsDir == "" { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "no_beads_directory", "message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".", - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) + return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } store := getStore() if store == nil { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "no_database", "message": "No database found. Run 'bd init' to create a new database.", - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalErrorWithHint("no database", "Run 'bd init' to create a new database") + return HandleErrorWithHint("no database", "Run 'bd init' to create a new database") } migrator, ok := storage.UnwrapStore(store).(storage.SchemaMigrator) if !ok { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "unsupported_backend", "message": "current storage backend does not support schema migration", - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalError("current storage backend does not support schema migration") + return HandleError("current storage backend does not support schema migration") } applied, err := migrator.ApplySchemaMigrations(rootCtx) if err != nil { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "schema_migration_failed", "message": err.Error(), - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalError("schema migration failed: %v", err) + return HandleError("schema migration failed: %v", err) } latest := schema.LatestVersion() @@ -579,126 +586,120 @@ func handleSchemaMigrate() { } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": status, "applied": applied, "latest_version": latest, }) - return } if applied == 0 { fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("āœ“ Schema already at v%d", latest))) - return + return nil } fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("āœ“ Applied %d schema migration(s); schema now at v%d", applied, latest))) + return nil } -// handleToSeparateBranch configures separate branch workflow for existing repos -func handleToSeparateBranch(branch string, dryRun bool) { - // Validate branch name +func handleToSeparateBranch(branch string, dryRun bool) error { b := strings.TrimSpace(branch) if b == "" || strings.ContainsAny(b, " \t\n") { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "invalid_branch", "message": "Branch name cannot be empty or contain whitespace", - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalErrorWithHint(fmt.Sprintf("invalid branch name '%s'", branch), "branch name cannot be empty or contain whitespace") + return HandleErrorWithHint(fmt.Sprintf("invalid branch name '%s'", branch), "branch name cannot be empty or contain whitespace") } - // Find .beads directory beadsDir := beads.FindBeadsDir() if beadsDir == "" { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "no_beads_directory", "message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".", - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) + return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } store := getStore() if store == nil { - FatalError("no database — run 'bd init' first") + return HandleError("no database — run 'bd init' first") } - // Get current sync.branch config ctx := rootCtx current, _ := store.GetConfig(ctx, "sync.branch") - // Dry-run mode if dryRun { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "dry_run": true, "previous": current, "branch": b, "changed": current != b, }) - } else { - fmt.Println("Dry run mode - no changes will be made") - if current == b { - fmt.Printf("sync.branch already set to '%s'\n", b) - } else { - fmt.Printf("Would set sync.branch: '%s' → '%s'\n", current, b) - } } - return + fmt.Println("Dry run mode - no changes will be made") + if current == b { + fmt.Printf("sync.branch already set to '%s'\n", b) + } else { + fmt.Printf("Would set sync.branch: '%s' → '%s'\n", current, b) + } + return nil } - // Check if already set if current == b { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "noop", "branch": b, "message": "sync.branch already set to this value", }) - } else { - fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("āœ“ sync.branch already set to '%s'", b))) - fmt.Println("No changes needed") } - return + fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("āœ“ sync.branch already set to '%s'", b))) + fmt.Println("No changes needed") + return nil } - // Update sync.branch config if err := store.SetConfig(ctx, "sync.branch", b); err != nil { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "config_update_failed", "message": err.Error(), - }) - os.Exit(1) + }); jerr != nil { + return jerr + } + return SilentExit() } - FatalError("failed to set sync.branch: %v", err) + return HandleError("failed to set sync.branch: %v", err) } - // Success output + commandDidWrite.Store(true) + if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "success", "previous": current, "branch": b, "message": "Enabled separate branch workflow", }) - } else { - fmt.Printf("%s\n\n", ui.RenderPass("āœ“ Enabled separate branch workflow")) - fmt.Printf("Set sync.branch to '%s'\n\n", b) - fmt.Println("Next steps:") - fmt.Println(" 1. No restart required. sync.branch is active immediately.") - fmt.Printf(" bd dolt push\n\n") - fmt.Println(" 2. Your existing data is preserved - no changes to git history") - fmt.Println(" 3. Future issue updates are stored in Dolt directly") - } - - if !dryRun { - commandDidWrite.Store(true) } + fmt.Printf("%s\n\n", ui.RenderPass("āœ“ Enabled separate branch workflow")) + fmt.Printf("Set sync.branch to '%s'\n\n", b) + fmt.Println("Next steps:") + fmt.Println(" 1. No restart required. sync.branch is active immediately.") + fmt.Printf(" bd dolt push\n\n") + fmt.Println(" 2. Your existing data is preserved - no changes to git history") + fmt.Println(" 3. Future issue updates are stored in Dolt directly") + return nil } // listMigrations returns registered Dolt schema migrations. The compat runner @@ -722,13 +723,22 @@ to a dedicated branch, keeping your main branch clean. Example: bd migrate sync beads-sync`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("migrate-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + dryRun, _ := cmd.Flags().GetBool("dry-run") if !dryRun { CheckReadonly("migrate sync") } - handleToSeparateBranch(args[0], dryRun) + return handleToSeparateBranch(args[0], dryRun) }, } @@ -744,10 +754,20 @@ in CI, release gates, and recovery scenarios. Example: bd migrate schema bd migrate schema --json`, - Args: cobra.NoArgs, - Run: func(cmd *cobra.Command, _ []string) { + Args: cobra.NoArgs, + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { CheckReadonly("migrate schema") - handleSchemaMigrate() + + evt := metrics.NewCommandEvent("migrate-schema") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + + return handleSchemaMigrate() }, } diff --git a/cmd/bd/migrate_hooks.go b/cmd/bd/migrate_hooks.go index cb13a8583..385e55cbd 100644 --- a/cmd/bd/migrate_hooks.go +++ b/cmd/bd/migrate_hooks.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/cmd/bd/doctor" + "github.com/steveyegge/beads/internal/metrics" "golang.org/x/term" ) @@ -25,15 +26,24 @@ Examples: bd migrate hooks --apply bd migrate hooks --apply --yes bd migrate hooks --dry-run --json`, - Args: cobra.MaximumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("migrate-hooks") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + requestedDryRun, _ := cmd.Flags().GetBool("dry-run") requestedApply, _ := cmd.Flags().GetBool("apply") requestedYes, _ := cmd.Flags().GetBool("yes") mode, err := validateHookMigrationMode(requestedDryRun, requestedApply, requestedYes) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } if mode.RequestedApply { @@ -47,23 +57,23 @@ Examples: absPath, err := filepath.Abs(targetPath) if err != nil { - FatalErrorRespectJSON("resolving path: %v", err) + return HandleErrorRespectJSON("resolving path: %v", err) } plan, err := doctor.PlanHookMigration(absPath) if err != nil { - FatalErrorRespectJSON("building hook migration plan: %v", err) + return HandleErrorRespectJSON("building hook migration plan: %v", err) } execPlan := buildHookMigrationExecutionPlan(plan) if mode.RequestedApply { if len(execPlan.BlockingErrors) > 0 { - FatalErrorRespectJSON("hook migration is blocked:\n- %s", strings.Join(execPlan.BlockingErrors, "\n- ")) + return HandleErrorRespectJSON("hook migration is blocked:\n- %s", strings.Join(execPlan.BlockingErrors, "\n- ")) } if execPlan.operationCount() > 0 { if err := validateHookMigrationApplyConsent(mode.RequestedYes, term.IsTerminal(int(os.Stdin.Fd())), jsonOutput); err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } } } @@ -72,17 +82,15 @@ Examples: if mode.RequestedApply { summary, applied, applyErr := maybeApplyHookMigration(execPlan, mode.RequestedYes) if applyErr != nil { - FatalErrorRespectJSON("applying hook migration: %v", applyErr) + return HandleErrorRespectJSON("applying hook migration: %v", applyErr) } if !applied { summary.SkippedArtifacts = append(summary.SkippedArtifacts, "canceled") summary.SkippedCount = len(summary.SkippedArtifacts) } - outputJSON(buildHookMigrationJSON(plan, mode, execPlan, &summary)) - return + return outputJSON(buildHookMigrationJSON(plan, mode, execPlan, &summary)) } - outputJSON(buildHookMigrationJSON(plan, mode, execPlan, nil)) - return + return outputJSON(buildHookMigrationJSON(plan, mode, execPlan, nil)) } fmt.Println(strings.Join(formatHookMigrationPlan(plan, mode), "\n")) @@ -90,22 +98,23 @@ Examples: fmt.Println(strings.Join(formatHookMigrationOperations(execPlan), "\n")) if mode.RequestedDryRun { - return + return nil } summary, applied, applyErr := maybeApplyHookMigration(execPlan, mode.RequestedYes) if applyErr != nil { - FatalErrorRespectJSON("applying hook migration: %v", applyErr) + return HandleErrorRespectJSON("applying hook migration: %v", applyErr) } if !applied { fmt.Println() fmt.Println("Migration canceled.") - return + return nil } for _, line := range formatHookMigrationApplySummary(summary) { fmt.Println(line) } + return nil }, } diff --git a/cmd/bd/migrate_issues.go b/cmd/bd/migrate_issues.go index d1b3825b8..03110626b 100644 --- a/cmd/bd/migrate_issues.go +++ b/cmd/bd/migrate_issues.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" ) @@ -33,17 +34,24 @@ Examples: # Move issues with label filter bd migrate-issues --from . --to ~/feature-work --label frontend --label urgent`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("migrate-issues") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + dryRun, _ := cmd.Flags().GetBool("dry-run") - // Block writes in readonly mode if !dryRun { CheckReadonly("migrate-issues") } ctx := rootCtx - // Parse flags from, _ := cmd.Flags().GetString("from") to, _ := cmd.Flags().GetString("to") statusStr, _ := cmd.Flags().GetString("status") @@ -57,49 +65,22 @@ Examples: strict, _ := cmd.Flags().GetBool("strict") yes, _ := cmd.Flags().GetBool("yes") - // Validate required flags if from == "" || to == "" { - if jsonOutput { - outputJSON(map[string]interface{}{ - "error": "missing_required_flags", - "message": "Both --from and --to are required", - }) - } else { - fmt.Fprintln(os.Stderr, "Error: both --from and --to flags are required") - } - os.Exit(1) + return HandleErrorRespectJSON("both --from and --to flags are required") } if from == to { - if jsonOutput { - outputJSON(map[string]interface{}{ - "error": "same_source_and_dest", - "message": "Source and destination repositories must be different", - }) - } else { - fmt.Fprintln(os.Stderr, "Error: --from and --to must be different repositories") - } - os.Exit(1) + return HandleErrorRespectJSON("--from and --to must be different repositories") } - // Load IDs from file if specified if idsFile != "" { fileIDs, err := loadIDsFromFile(idsFile) if err != nil { - if jsonOutput { - outputJSON(map[string]interface{}{ - "error": "ids_file_read_failed", - "message": err.Error(), - }) - } else { - fmt.Fprintf(os.Stderr, "Error reading IDs file: %v\n", err) - } - os.Exit(1) + return HandleErrorRespectJSON("reading IDs file: %v", err) } ids = append(ids, fileIDs...) } - // Execute migration if err := executeMigrateIssues(ctx, migrateIssuesParams{ from: from, to: to, @@ -114,16 +95,9 @@ Examples: strict: strict, yes: yes, }); err != nil { - if jsonOutput { - outputJSON(map[string]interface{}{ - "error": "migration_failed", - "message": err.Error(), - }) - } else { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - } - os.Exit(1) + return HandleErrorRespectJSON("%v", err) } + return nil }, } @@ -170,12 +144,11 @@ func executeMigrateIssues(ctx context.Context, p migrateIssuesParams) error { if len(candidates) == 0 { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "message": "No issues match the specified filters", }) - } else { - fmt.Println("Nothing to do: no issues match the specified filters") } + fmt.Println("Nothing to do: no issues match the specified filters") return nil } @@ -217,14 +190,13 @@ func executeMigrateIssues(ctx context.Context, p migrateIssuesParams) error { } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "success": true, "message": fmt.Sprintf("Migrated %d issues from %s to %s", len(migrationSet), p.from, p.to), "plan": plan, }) - } else { - fmt.Printf("\nāœ“ Successfully migrated %d issues from %s to %s\n", len(migrationSet), p.from, p.to) } + fmt.Printf("\nāœ“ Successfully migrated %d issues from %s to %s\n", len(migrationSet), p.from, p.to) } return nil @@ -556,15 +528,12 @@ func buildMigrationPlan(candidates, migrationSet []string, stats dependencyStats func displayMigrationPlan(plan migrationPlan, dryRun bool) error { if jsonOutput { - output := map[string]interface{}{ + return outputJSON(map[string]interface{}{ "plan": plan, "dry_run": dryRun, - } - outputJSON(output) - return nil + }) } - // Human-readable output fmt.Println("\n=== Migration Plan ===") fmt.Printf("From: %s\n", plan.From) fmt.Printf("To: %s\n", plan.To) diff --git a/cmd/bd/mol_bond.go b/cmd/bd/mol_bond.go index f25b14d19..53c320e06 100644 --- a/cmd/bd/mol_bond.go +++ b/cmd/bd/mol_bond.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/formula" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -67,8 +68,10 @@ Examples: bd mol bond mol-critical-bug wisp-patrol --pour # Persist found bug bd mol bond mol-temp-check bd-feature --ephemeral # Ephemeral diagnostic bd mol bond mol-arm bd-patrol --ref arm-{{name}} --var name=ace # Dynamic child ID`, - Args: cobra.ExactArgs(2), - Run: runMolBond, + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: runMolBond, } // BondResult holds the result of a bond operation @@ -80,15 +83,20 @@ type BondResult struct { IDMapping map[string]string `json:"id_mapping,omitempty"` // Old ID -> new ID for spawned issues } -// runMolBond implements the polymorphic bond command -func runMolBond(cmd *cobra.Command, args []string) { +func runMolBond(cmd *cobra.Command, args []string) error { CheckReadonly("mol bond") + evt := metrics.NewCommandEvent("mol-bond") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // mol bond requires direct store access if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } bondType, _ := cmd.Flags().GetString("type") @@ -99,40 +107,31 @@ func runMolBond(cmd *cobra.Command, args []string) { pour, _ := cmd.Flags().GetBool("pour") childRef, _ := cmd.Flags().GetString("ref") - // Validate phase flags are not both set if ephemeral && pour { - FatalError("cannot use both --ephemeral and --pour") + return HandleErrorRespectJSON("cannot use both --ephemeral and --pour") } - // All issues go in the main store; ephemeral vs pour determines the Wisp flag - // --ephemeral: create with Ephemeral=true (ephemeral, stored in dolt_ignore table, excluded from sync) - // --pour: create with Ephemeral=false (persistent, synced via Dolt) - // Default: follow target's phase (ephemeral if target is ephemeral, otherwise persistent) - - // Validate bond type if bondType != types.BondTypeSequential && bondType != types.BondTypeParallel && bondType != types.BondTypeConditional { - FatalError("invalid bond type '%s', must be: sequential, parallel, or conditional", bondType) + return HandleErrorRespectJSON("invalid bond type '%s', must be: sequential, parallel, or conditional", bondType) } - // Parse variables vars := make(map[string]string) for _, v := range varFlags { parts := strings.SplitN(v, "=", 2) if len(parts) != 2 { - FatalError("invalid variable format '%s', expected 'key=value'", v) + return HandleErrorRespectJSON("invalid variable format '%s', expected 'key=value'", v) } vars[parts[0]] = parts[1] } - // For dry-run, just check if operands can be resolved (don't cook) if dryRun { issueA, formulaA, err := resolveOrDescribe(ctx, store, args[0]) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } issueB, formulaB, err := resolveOrDescribe(ctx, store, args[1]) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } idA := args[0] @@ -191,19 +190,16 @@ func runMolBond(cmd *cobra.Command, args []string) { if formulaA != "" || formulaB != "" { fmt.Printf("\n Note: Cooked formulas are ephemeral and deleted after bonding.\n") } - return + return nil } - // Resolve both operands - can be issue IDs or formula names - // Formula names are cooked inline to in-memory subgraphs - // Pass vars for step condition filtering (bd-7zka.1) subgraphA, cookedA, err := resolveOrCookToSubgraph(ctx, store, args[0], vars) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } subgraphB, cookedB, err := resolveOrCookToSubgraph(ctx, store, args[1], vars) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } // No cleanup needed - in-memory subgraphs don't pollute the DB @@ -243,12 +239,11 @@ func runMolBond(cmd *cobra.Command, args []string) { } if err != nil { - FatalError("bonding: %v", err) + return HandleErrorRespectJSON("bonding: %v", err) } if jsonOutput { - outputJSON(result) - return + return outputJSON(result) } fmt.Printf("%s Bonded: %s + %s\n", ui.RenderPass("āœ“"), idA, idB) @@ -261,6 +256,7 @@ func runMolBond(cmd *cobra.Command, args []string) { } else if pour { fmt.Printf(" Phase: liquid (persistent, Ephemeral=false)\n") } + return nil } // isProto checks if an issue is a proto (has the template label) diff --git a/cmd/bd/mol_burn.go b/cmd/bd/mol_burn.go index 09ad92ca5..8a8651d4e 100644 --- a/cmd/bd/mol_burn.go +++ b/cmd/bd/mol_burn.go @@ -6,6 +6,7 @@ import ( "os" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -34,8 +35,10 @@ Example: bd mol burn bd-abc123 --dry-run # Preview what would be deleted bd mol burn bd-abc123 --force # Skip confirmation bd mol burn bd-a1 bd-b2 bd-c3 # Batch delete multiple wisps`, - Args: cobra.MinimumNArgs(1), - Run: runMolBurn, + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runMolBurn, } // BurnResult holds the result of a burn operation @@ -52,14 +55,20 @@ type BatchBurnResult struct { FailedCount int `json:"failed_count"` } -func runMolBurn(cmd *cobra.Command, args []string) { +func runMolBurn(cmd *cobra.Command, args []string) error { CheckReadonly("mol burn") + evt := metrics.NewCommandEvent("mol-burn") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // mol burn requires direct store access if store == nil { - FatalErrorWithHint("no database connection", diagHint()) + return HandleErrorWithHint("no database connection", diagHint()) } dryRun, _ := cmd.Flags().GetBool("dry-run") @@ -68,42 +77,31 @@ func runMolBurn(cmd *cobra.Command, args []string) { force = true } - // Single ID: use original logic for backward compatibility if len(args) == 1 { - burnSingleMolecule(ctx, args[0], dryRun, force) - return + return burnSingleMolecule(ctx, args[0], dryRun, force) } - // Multiple IDs: batch mode for efficiency - burnMultipleMolecules(ctx, args, dryRun, force) + return burnMultipleMolecules(ctx, args, dryRun, force) } -// burnSingleMolecule handles the single molecule case (original behavior) -func burnSingleMolecule(ctx context.Context, moleculeID string, dryRun, force bool) { - // Resolve molecule ID in main store +func burnSingleMolecule(ctx context.Context, moleculeID string, dryRun, force bool) error { resolvedID, err := utils.ResolvePartialID(ctx, store, moleculeID) if err != nil { - FatalError("resolving molecule ID %s: %v", moleculeID, err) + return HandleErrorRespectJSON("resolving molecule ID %s: %v", moleculeID, err) } - // Load the molecule rootIssue, err := store.GetIssue(ctx, resolvedID) if err != nil { - FatalError("loading molecule: %v", err) + return HandleErrorRespectJSON("loading molecule: %v", err) } - // Branch based on molecule phase if rootIssue.Ephemeral { - // Wisp: direct delete - burnWispMolecule(ctx, resolvedID, dryRun, force) - } else { - // Mol: cascade delete - burnPersistentMolecule(ctx, resolvedID, dryRun, force) + return burnWispMolecule(ctx, resolvedID, dryRun, force) } + return burnPersistentMolecule(ctx, resolvedID, dryRun, force) } -// burnMultipleMolecules handles batch deletion of multiple molecules efficiently -func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, force bool) { +func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, force bool) error { var wispIDs []string var persistentIDs []string var failedResolve []string @@ -137,11 +135,10 @@ func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, fo if len(wispIDs) == 0 && len(persistentIDs) == 0 { if jsonOutput { - outputJSON(BatchBurnResult{FailedCount: len(failedResolve)}) - } else { - fmt.Println("No valid molecules to burn") + return outputJSON(BatchBurnResult{FailedCount: len(failedResolve)}) } - return + fmt.Println("No valid molecules to burn") + return nil } if dryRun { @@ -166,10 +163,9 @@ func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, fo } } } - return + return nil } - // Confirm unless --force if !force && !jsonOutput { fmt.Printf("About to burn %d wisp(s) and %d persistent molecule(s)\n", len(wispIDs), len(persistentIDs)) fmt.Printf("This will permanently delete all molecule data with no digest.\n") @@ -179,7 +175,7 @@ func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, fo _, _ = fmt.Scanln(&response) if response != "y" && response != "Y" { fmt.Println("Canceled.") - return + return nil } } @@ -217,8 +213,9 @@ func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, fo issueIDs = append(issueIDs, issue.ID) } - // Use deleteBatch for persistent molecules - deleteBatch(nil, issueIDs, true, false, false, false, false, "mol burn") + if err := deleteBatch(nil, issueIDs, true, false, false, false, false, "mol burn"); err != nil { + return HandleErrorRespectJSON("%v", err) + } batchResult.TotalDeleted += len(issueIDs) batchResult.Results = append(batchResult.Results, BurnResult{ MoleculeID: id, @@ -228,25 +225,22 @@ func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, fo } if jsonOutput { - outputJSON(batchResult) - return + return outputJSON(batchResult) } fmt.Printf("%s Burned %d molecule(s): %d issues deleted\n", ui.RenderPass("āœ“"), len(wispIDs)+len(persistentIDs), batchResult.TotalDeleted) if batchResult.FailedCount > 0 { fmt.Printf(" %d failed\n", batchResult.FailedCount) } + return nil } -// burnWispMolecule handles wisp deletion (ephemeral-only) -func burnWispMolecule(ctx context.Context, resolvedID string, dryRun, force bool) { - // Load the molecule subgraph +func burnWispMolecule(ctx context.Context, resolvedID string, dryRun, force bool) error { subgraph, err := loadTemplateSubgraph(ctx, store, resolvedID) if err != nil { - FatalError("loading wisp molecule: %v", err) + return HandleErrorRespectJSON("loading wisp molecule: %v", err) } - // Collect wisp issue IDs to delete (only delete wisps, not regular children) var wispIDs []string for _, issue := range subgraph.Issues { if issue.Ephemeral { @@ -256,14 +250,13 @@ func burnWispMolecule(ctx context.Context, resolvedID string, dryRun, force bool if len(wispIDs) == 0 { if jsonOutput { - outputJSON(BurnResult{ + return outputJSON(BurnResult{ MoleculeID: resolvedID, DeletedCount: 0, }) - } else { - fmt.Printf("No wisp issues found for molecule %s\n", resolvedID) } - return + fmt.Printf("No wisp issues found for molecule %s\n", resolvedID) + return nil } if dryRun { @@ -282,10 +275,9 @@ func burnWispMolecule(ctx context.Context, resolvedID string, dryRun, force bool } } fmt.Printf("\nNo digest will be created (use 'bd mol squash' to create one).\n") - return + return nil } - // Confirm unless --force if !force && !jsonOutput { fmt.Printf("About to burn wisp %s (%d issues)\n", resolvedID, len(wispIDs)) fmt.Printf("This will permanently delete all wisp data with no digest.\n") @@ -296,36 +288,32 @@ func burnWispMolecule(ctx context.Context, resolvedID string, dryRun, force bool _, _ = fmt.Scanln(&response) if response != "y" && response != "Y" { fmt.Println("Canceled.") - return + return nil } } - // Perform the burn result, err := burnWisps(ctx, store, wispIDs) if err != nil { - FatalError("burning wisp: %v", err) + return HandleErrorRespectJSON("burning wisp: %v", err) } result.MoleculeID = resolvedID if jsonOutput { - outputJSON(result) - return + return outputJSON(result) } fmt.Printf("%s Burned wisp: %d issues deleted\n", ui.RenderPass("āœ“"), result.DeletedCount) fmt.Printf(" Ephemeral: %s\n", resolvedID) fmt.Printf(" No digest created.\n") + return nil } -// burnPersistentMolecule handles mol deletion (cascade delete) -func burnPersistentMolecule(ctx context.Context, resolvedID string, dryRun, force bool) { - // Load the molecule subgraph to show what will be deleted +func burnPersistentMolecule(ctx context.Context, resolvedID string, dryRun, force bool) error { subgraph, err := loadTemplateSubgraph(ctx, store, resolvedID) if err != nil { - FatalError("loading molecule: %v", err) + return HandleErrorRespectJSON("loading molecule: %v", err) } - // Collect all issue IDs in the molecule var issueIDs []string for _, issue := range subgraph.Issues { issueIDs = append(issueIDs, issue.ID) @@ -333,14 +321,13 @@ func burnPersistentMolecule(ctx context.Context, resolvedID string, dryRun, forc if len(issueIDs) == 0 { if jsonOutput { - outputJSON(BurnResult{ + return outputJSON(BurnResult{ MoleculeID: resolvedID, DeletedCount: 0, }) - } else { - fmt.Printf("No issues found for molecule %s\n", resolvedID) } - return + fmt.Printf("No issues found for molecule %s\n", resolvedID) + return nil } if dryRun { @@ -357,10 +344,9 @@ func burnPersistentMolecule(ctx context.Context, resolvedID string, dryRun, forc } fmt.Printf("\nNote: Persistent mol - deletions sync to remotes.\n") fmt.Printf("No digest will be created (use 'bd mol squash' to create one).\n") - return + return nil } - // Confirm unless --force if !force && !jsonOutput { fmt.Printf("About to burn mol %s (%d issues)\n", resolvedID, len(issueIDs)) fmt.Printf("This will permanently delete all molecule data with no digest.\n") @@ -372,13 +358,14 @@ func burnPersistentMolecule(ctx context.Context, resolvedID string, dryRun, forc _, _ = fmt.Scanln(&response) if response != "y" && response != "Y" { fmt.Println("Canceled.") - return + return nil } } - // Use deleteBatch with cascade=false (we already have all IDs from subgraph) - // force=true, hardDelete=false (Dolt handles sync) - deleteBatch(nil, issueIDs, true, false, false, jsonOutput, false, "mol burn") + if err := deleteBatch(nil, issueIDs, true, false, false, jsonOutput, false, "mol burn"); err != nil { + return HandleErrorRespectJSON("%v", err) + } + return nil } // burnWisps deletes all wisp issues atomically within a single transaction. diff --git a/cmd/bd/mol_current.go b/cmd/bd/mol_current.go index 783899d45..8f4a73a77 100644 --- a/cmd/bd/mol_current.go +++ b/cmd/bd/mol_current.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -56,63 +57,65 @@ For large molecules (>100 steps), a summary is shown instead. Use --limit or --range to view specific steps: bd mol current --limit 50 # Show first 50 steps bd mol current --range 100-150 # Show steps 100-150`, - Args: cobra.MaximumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mol-current") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx forAgent, _ := cmd.Flags().GetString("for") limit, _ := cmd.Flags().GetInt("limit") rangeStr, _ := cmd.Flags().GetString("range") - // Determine who we're looking for agent := forAgent if agent == "" { - agent = actor // Default to current user/agent + agent = actor } if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } - // Parse range flag if provided var rangeStart, rangeEnd int if rangeStr != "" { var err error rangeStart, rangeEnd, err = parseRange(rangeStr) if err != nil { - FatalError("invalid range '%s': %v", rangeStr, err) + return HandleErrorRespectJSON("invalid range '%s': %v", rangeStr, err) } } - // Determine if user explicitly requested steps explicitSteps := limit > 0 || rangeStr != "" var molecules []*MoleculeProgress if len(args) == 1 { - // Explicit molecule ID given moleculeID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalError("molecule '%s' not found", args[0]) + return HandleErrorRespectJSON("molecule '%s' not found", args[0]) } - // Check child count first for large molecule detection stats, err := store.GetMoleculeProgress(ctx, moleculeID) if err != nil { - FatalError("loading molecule: %v", err) + return HandleErrorRespectJSON("loading molecule: %v", err) } - // If large molecule and no explicit flags, show summary if stats.Total > LargeMoleculeThreshold && !explicitSteps && !jsonOutput { printLargeMoleculeSummary(stats) - return + return nil } progress, err := getMoleculeProgress(ctx, store, moleculeID) if err != nil { - FatalError("loading molecule: %v", err) + return HandleErrorRespectJSON("loading molecule: %v", err) } - // Apply limit or range filtering if rangeStr != "" { progress.Steps = filterStepsByRange(progress.Steps, rangeStart, rangeEnd) } else if limit > 0 && len(progress.Steps) > limit { @@ -121,18 +124,15 @@ Use --limit or --range to view specific steps: molecules = append(molecules, progress) } else { - // Infer from in_progress issues molecules = findInProgressMolecules(ctx, store, agent) - // Fallback: check for hooked issues with bonded molecules if len(molecules) == 0 { molecules = findHookedMolecules(ctx, store, agent) } if len(molecules) == 0 { if jsonOutput { - outputJSON([]interface{}{}) - return + return outputJSON([]interface{}{}) } fmt.Printf("No molecules in progress") if agent != "" { @@ -142,22 +142,21 @@ Use --limit or --range to view specific steps: fmt.Println("\nTo start work on a molecule:") fmt.Println(" bd mol wisp create # Instantiate as ephemeral wisp") fmt.Println(" bd update --claim # Claim a step") - return + return nil } } if jsonOutput { - outputJSON(molecules) - return + return outputJSON(molecules) } - // Human-readable output for i, mol := range molecules { if i > 0 { fmt.Println() } printMoleculeProgress(mol) } + return nil }, } diff --git a/cmd/bd/mol_distill.go b/cmd/bd/mol_distill.go index 46ded57ce..8d1948f28 100644 --- a/cmd/bd/mol_distill.go +++ b/cmd/bd/mol_distill.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/formula" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" ) @@ -43,8 +44,10 @@ Output locations (first writable wins): Examples: bd mol distill bd-o5xe my-workflow bd mol distill bd-abc release-workflow --var feature_name=auth-refactor`, - Args: cobra.RangeArgs(1, 2), - Run: runMolDistill, + Args: cobra.RangeArgs(1, 2), + SilenceUsage: true, + SilenceErrors: true, + RunE: runMolDistill, } // DistillResult holds the result of a distill operation @@ -99,69 +102,66 @@ func parseDistillVar(varFlag, searchableText string) (string, string, error) { } } -// runMolDistill implements the distill command -func runMolDistill(cmd *cobra.Command, args []string) { +func runMolDistill(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mol-distill") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // mol distill requires direct store access for reading the epic if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } varFlags, _ := cmd.Flags().GetStringArray("var") dryRun, _ := cmd.Flags().GetBool("dry-run") outputDir, _ := cmd.Flags().GetString("output") - // Resolve epic ID epicID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalError("'%s' not found", args[0]) + return HandleErrorRespectJSON("'%s' not found", args[0]) } - // Load the epic subgraph subgraph, err := loadTemplateSubgraph(ctx, store, epicID) if err != nil { - FatalError("loading epic: %v", err) + return HandleErrorRespectJSON("loading epic: %v", err) } - // Determine formula name formulaName := "" if len(args) > 1 { formulaName = args[1] } else { - // Derive from epic title formulaName = sanitizeFormulaName(subgraph.Root.Title) } - // Parse variable substitutions with smart detection replacements := make(map[string]string) if len(varFlags) > 0 { searchableText := collectSubgraphText(subgraph) for _, v := range varFlags { findText, varName, err := parseDistillVar(v, searchableText) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } replacements[findText] = varName } } - // Convert to formula f := subgraphToFormula(subgraph, formulaName, replacements) - // Determine output path outputPath := "" if outputDir != "" { outputPath = filepath.Join(outputDir, formulaName+formula.FormulaExt) } else { - // Find first writable formula directory outputPath = findWritableFormulaDir(formulaName) if outputPath == "" { hint := "Try creating one of the formula search paths" if searchPaths := getFormulaSearchPaths(); len(searchPaths) > 0 { hint = fmt.Sprintf("Try: mkdir -p %s", searchPaths[0]) } - FatalErrorWithHint("no writable formula directory found", hint) + return HandleErrorWithHint("no writable formula directory found", hint) } } @@ -177,24 +177,22 @@ func runMolDistill(cmd *cobra.Command, args []string) { } fmt.Printf("\nStructure:\n") printFormulaStepsTree(f.Steps, "") - return + return nil } - // Ensure output directory exists dir := filepath.Dir(outputPath) if err := os.MkdirAll(dir, 0755); err != nil { - FatalError("creating directory %s: %v", dir, err) + return HandleErrorRespectJSON("creating directory %s: %v", dir, err) } - // Write formula data, err := json.MarshalIndent(f, "", " ") if err != nil { - FatalError("encoding formula: %v", err) + return HandleErrorRespectJSON("encoding formula: %v", err) } // #nosec G306 -- Formula files are not sensitive if err := os.WriteFile(outputPath, data, 0644); err != nil { - FatalError("writing formula: %v", err) + return HandleErrorRespectJSON("writing formula: %v", err) } result := &DistillResult{ @@ -205,8 +203,7 @@ func runMolDistill(cmd *cobra.Command, args []string) { } if jsonOutput { - outputJSON(result) - return + return outputJSON(result) } fmt.Printf("%s Distilled formula: %d steps\n", ui.RenderPass("āœ“"), result.Steps) @@ -221,6 +218,7 @@ func runMolDistill(cmd *cobra.Command, args []string) { fmt.Printf(" --var %s=", v) } fmt.Println() + return nil } // sanitizeFormulaName converts a title to a valid formula name diff --git a/cmd/bd/mol_last_activity.go b/cmd/bd/mol_last_activity.go index 467ccbdc4..71b3d1524 100644 --- a/cmd/bd/mol_last_activity.go +++ b/cmd/bd/mol_last_activity.go @@ -5,6 +5,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/utils" ) @@ -24,30 +25,39 @@ Activity sources: Examples: bd mol last-activity hq-wisp-0laki bd mol last-activity hq-wisp-0laki --json`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mol-last-activity") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } moleculeID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalError("molecule '%s' not found", args[0]) + return HandleErrorRespectJSON("molecule '%s' not found", args[0]) } activity, err := store.GetMoleculeLastActivity(ctx, moleculeID) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { - outputJSON(activity) - return + return outputJSON(activity) } fmt.Println(activity.LastActivity.UTC().Format(time.RFC3339)) + return nil }, } diff --git a/cmd/bd/mol_progress.go b/cmd/bd/mol_progress.go index 168bb41e4..f05ae09a4 100644 --- a/cmd/bd/mol_progress.go +++ b/cmd/bd/mol_progress.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -29,46 +30,49 @@ Output includes: Example: bd mol progress bd-hanoi-xyz`, - Args: cobra.MaximumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mol-progress") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // mol progress requires direct store access if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } var moleculeID string if len(args) == 1 { - // Explicit molecule ID given resolved, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalError("molecule '%s' not found", args[0]) + return HandleErrorRespectJSON("molecule '%s' not found", args[0]) } moleculeID = resolved } else { - // Infer from in_progress work - use lightweight discovery moleculeIDs := findInProgressMoleculeIDs(ctx, store, actor) if len(moleculeIDs) == 0 { if jsonOutput { - outputJSON([]interface{}{}) - return + return outputJSON([]interface{}{}) } fmt.Println("No molecules in progress.") fmt.Println("\nUse: bd mol progress ") - return + return nil } - // Show progress for first molecule moleculeID = moleculeIDs[0] } stats, err := store.GetMoleculeProgress(ctx, moleculeID) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { - // Add computed fields for JSON output output := map[string]interface{}{ "molecule_id": stats.MoleculeID, "molecule_title": stats.MoleculeTitle, @@ -92,12 +96,11 @@ Example: } } } - outputJSON(output) - return + return outputJSON(output) } - // Human-readable output printMoleculeProgressStats(stats) + return nil }, } diff --git a/cmd/bd/mol_ready_gated.go b/cmd/bd/mol_ready_gated.go index 637e499c3..1a6e94774 100644 --- a/cmd/bd/mol_ready_gated.go +++ b/cmd/bd/mol_ready_gated.go @@ -6,6 +6,7 @@ import ( "sort" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -42,21 +43,28 @@ The patrol system uses this to find and dispatch gate-ready molecules. Examples: bd mol ready --gated # Find all gate-ready molecules bd mol ready --gated --json # JSON output for automation`, - Run: runMolReadyGated, + SilenceUsage: true, + SilenceErrors: true, + RunE: runMolReadyGated, } -func runMolReadyGated(cmd *cobra.Command, args []string) { +func runMolReadyGated(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mol-ready-gated") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // --gated mode requires direct store access if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } - // Find gate-ready molecules molecules, err := findGateReadyMolecules(ctx, store) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { @@ -67,14 +75,12 @@ func runMolReadyGated(cmd *cobra.Command, args []string) { if output.Molecules == nil { output.Molecules = []*GatedMolecule{} } - outputJSON(output) - return + return outputJSON(output) } - // Human-readable output if len(molecules) == 0 { fmt.Printf("\n%s No molecules ready for gate-resume dispatch\n\n", ui.RenderWarn("")) - return + return nil } fmt.Printf("\n%s Molecules ready for gate-resume dispatch (%d):\n\n", @@ -93,6 +99,7 @@ func runMolReadyGated(cmd *cobra.Command, args []string) { fmt.Println("To dispatch a molecule:") fmt.Println(" bd sling --mol ") + return nil } // findGateReadyMolecules finds molecules where a gate has closed and work can resume. diff --git a/cmd/bd/mol_seed.go b/cmd/bd/mol_seed.go index e4f838d16..effe8eb5c 100644 --- a/cmd/bd/mol_seed.go +++ b/cmd/bd/mol_seed.go @@ -5,6 +5,8 @@ import ( "strings" "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/metrics" ) var molSeedCmd = &cobra.Command{ @@ -25,37 +27,44 @@ Formula search paths (checked in order): Examples: bd mol seed mol-feature # Verify specific formula bd mol seed mol-review --var name=test # Verify with variable substitution`, - Args: cobra.ExactArgs(1), - Run: runMolSeed, + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runMolSeed, } -func runMolSeed(cmd *cobra.Command, args []string) { +func runMolSeed(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mol-seed") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + varFlags, _ := cmd.Flags().GetStringArray("var") - // Parse variables (for formula condition filtering if needed) vars := make(map[string]string) for _, v := range varFlags { parts := strings.SplitN(v, "=", 2) if len(parts) != 2 { - FatalError("invalid variable format '%s', expected 'key=value'", v) + return HandleErrorRespectJSON("invalid variable format '%s', expected 'key=value'", v) } vars[parts[0]] = parts[1] } - // Verify single formula formulaName := args[0] if err := verifyFormula(formulaName, vars); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } - if !jsonOutput { - fmt.Printf("āœ“ Formula %q accessible\n", formulaName) - } else { - outputJSON(map[string]interface{}{ + if jsonOutput { + return outputJSON(map[string]interface{}{ "status": "ok", "formula": formulaName, }) } + fmt.Printf("āœ“ Formula %q accessible\n", formulaName) + return nil } // verifyFormula checks if a formula can be loaded and cooked diff --git a/cmd/bd/mol_show.go b/cmd/bd/mol_show.go index a4b7d95c0..5ef57ca72 100644 --- a/cmd/bd/mol_show.go +++ b/cmd/bd/mol_show.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -27,36 +28,43 @@ The --parallel flag highlights parallelizable steps: Example: bd mol show bd-patrol --parallel`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mol-show") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // mol show requires direct store access for subgraph loading if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } moleculeID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalError("molecule '%s' not found", args[0]) + return HandleErrorRespectJSON("molecule '%s' not found", args[0]) } subgraph, err := loadTemplateSubgraph(ctx, store, moleculeID) if err != nil { - FatalError("loading molecule: %v", err) + return HandleErrorRespectJSON("loading molecule: %v", err) } if molShowParallel { - showMoleculeWithParallel(subgraph) - } else { - showMolecule(subgraph) + return showMoleculeWithParallel(subgraph) } + return showMolecule(subgraph) }, } -func showMolecule(subgraph *MoleculeSubgraph) { +func showMolecule(subgraph *MoleculeSubgraph) error { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "root": subgraph.Root, "issues": subgraph.Issues, "dependencies": subgraph.Dependencies, @@ -64,7 +72,6 @@ func showMolecule(subgraph *MoleculeSubgraph) { "is_compound": subgraph.Root.IsCompound(), "bonded_from": subgraph.Root.BondedFrom, }) - return } // Determine molecule type label @@ -93,6 +100,7 @@ func showMolecule(subgraph *MoleculeSubgraph) { fmt.Printf("\n%s Structure:\n", ui.RenderPass("🌲")) printMoleculeTree(subgraph, subgraph.Root.ID, 0, true) fmt.Println() + return nil } // showCompoundBondingInfo displays the bonding lineage for compound molecules. @@ -406,12 +414,11 @@ func calculateBlockingDepths(subgraph *MoleculeSubgraph, blockedBy map[string]ma return depths } -// showMoleculeWithParallel displays molecule structure with parallel annotations -func showMoleculeWithParallel(subgraph *MoleculeSubgraph) { +func showMoleculeWithParallel(subgraph *MoleculeSubgraph) error { analysis := analyzeMoleculeParallel(subgraph) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "root": subgraph.Root, "issues": subgraph.Issues, "dependencies": subgraph.Dependencies, @@ -420,7 +427,6 @@ func showMoleculeWithParallel(subgraph *MoleculeSubgraph) { "is_compound": subgraph.Root.IsCompound(), "bonded_from": subgraph.Root.BondedFrom, }) - return } // Determine molecule type label @@ -457,6 +463,7 @@ func showMoleculeWithParallel(subgraph *MoleculeSubgraph) { fmt.Printf("\n%s Structure:\n", ui.RenderPass("🌲")) printMoleculeTreeWithParallel(subgraph, analysis, subgraph.Root.ID, 0, true) fmt.Println() + return nil } // printMoleculeTreeWithParallel prints the molecule structure with parallel annotations. diff --git a/cmd/bd/mol_squash.go b/cmd/bd/mol_squash.go index 8a00b0724..a5119ee30 100644 --- a/cmd/bd/mol_squash.go +++ b/cmd/bd/mol_squash.go @@ -7,6 +7,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -44,8 +45,10 @@ Example: bd mol squash bd-abc123 --dry-run # Preview what would be squashed bd mol squash bd-abc123 --keep-children # Keep wisps after digest bd mol squash bd-abc123 --summary "Agent-generated summary of work done"`, - Args: cobra.ExactArgs(1), - Run: runMolSquash, + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runMolSquash, } // SquashResult holds the result of a squash operation @@ -59,37 +62,40 @@ type SquashResult struct { WispSquash bool `json:"wisp_squash,omitempty"` // True if this was a wisp→digest squash } -func runMolSquash(cmd *cobra.Command, args []string) { +func runMolSquash(cmd *cobra.Command, args []string) error { CheckReadonly("mol squash") + evt := metrics.NewCommandEvent("mol-squash") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // mol squash requires direct store access if store == nil { - FatalErrorWithHint("no database connection", diagHint()) + return HandleErrorWithHint("no database connection", diagHint()) } dryRun, _ := cmd.Flags().GetBool("dry-run") keepChildren, _ := cmd.Flags().GetBool("keep-children") summary, _ := cmd.Flags().GetString("summary") - // Resolve molecule ID in main store moleculeID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalError("resolving molecule ID %s: %v", args[0], err) + return HandleErrorRespectJSON("resolving molecule ID %s: %v", args[0], err) } - // Load the molecule subgraph from main store subgraph, err := loadTemplateSubgraph(ctx, store, moleculeID) if err != nil { - FatalError("loading molecule: %v", err) + return HandleErrorRespectJSON("loading molecule: %v", err) } - // Filter to only ephemeral children (exclude root) var wispChildren []*types.Issue for _, issue := range subgraph.Issues { if issue.ID == subgraph.Root.ID { - continue // Skip root + continue } if issue.Ephemeral { wispChildren = append(wispChildren, issue) @@ -98,14 +104,13 @@ func runMolSquash(cmd *cobra.Command, args []string) { if len(wispChildren) == 0 { if jsonOutput { - outputJSON(SquashResult{ + return outputJSON(SquashResult{ MoleculeID: moleculeID, SquashedCount: 0, }) - } else { - fmt.Printf("No ephemeral children found for molecule %s\n", moleculeID) } - return + fmt.Printf("No ephemeral children found for molecule %s\n", moleculeID) + return nil } if dryRun { @@ -118,7 +123,6 @@ func runMolSquash(cmd *cobra.Command, args []string) { } fmt.Printf("\nDigest preview:\n") digest := generateDigest(subgraph.Root, wispChildren) - // Show first 500 chars of digest if len(digest) > 500 { fmt.Printf("%s...\n", digest[:500]) } else { @@ -129,18 +133,16 @@ func runMolSquash(cmd *cobra.Command, args []string) { } else { fmt.Printf("\nChildren would be deleted after digest creation.\n") } - return + return nil } - // Perform the squash result, err := squashMolecule(ctx, store, subgraph.Root, wispChildren, keepChildren, summary, actor) if err != nil { - FatalError("squashing molecule: %v", err) + return HandleErrorRespectJSON("squashing molecule: %v", err) } if jsonOutput { - outputJSON(result) - return + return outputJSON(result) } fmt.Printf("%s Squashed molecule: %d children → 1 digest\n", ui.RenderPass("āœ“"), result.SquashedCount) @@ -153,6 +155,7 @@ func runMolSquash(cmd *cobra.Command, args []string) { if result.WispSquash { fmt.Printf(" Root auto-closed: %s\n", result.MoleculeID) } + return nil } // generateDigest creates a summary from the molecule execution diff --git a/cmd/bd/mol_stale.go b/cmd/bd/mol_stale.go index 36d9da0dd..c47cd74c3 100644 --- a/cmd/bd/mol_stale.go +++ b/cmd/bd/mol_stale.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -29,7 +30,9 @@ Examples: bd mol stale --blocking # Only show those blocking other work bd mol stale --unassigned # Only show unassigned molecules bd mol stale --all # Include molecules with 0 children`, - Run: runMolStale, + SilenceUsage: true, + SilenceErrors: true, + RunE: runMolStale, } // StaleMolecule holds info about a stale molecule @@ -50,7 +53,14 @@ type StaleResult struct { BlockingCount int `json:"blocking_count"` } -func runMolStale(cmd *cobra.Command, args []string) { +func runMolStale(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("mol-stale") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx blockingOnly, _ := cmd.Flags().GetBool("blocking") @@ -61,25 +71,23 @@ func runMolStale(cmd *cobra.Command, args []string) { var err error if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } result, err = findStaleMolecules(ctx, store, blockingOnly, unassignedOnly, showAll) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { - outputJSON(result) - return + return outputJSON(result) } if len(result.StaleMolecules) == 0 { fmt.Println("No stale molecules found.") - return + return nil } - // Print header if blockingOnly { fmt.Printf("%s Stale molecules (complete but unclosed, blocking work):\n\n", ui.RenderWarnIcon()) @@ -88,7 +96,6 @@ func runMolStale(cmd *cobra.Command, args []string) { ui.RenderInfoIcon()) } - // Print each stale molecule for _, mol := range result.StaleMolecules { progress := fmt.Sprintf("%d/%d", mol.ClosedChildren, mol.TotalChildren) @@ -107,12 +114,12 @@ func runMolStale(cmd *cobra.Command, args []string) { fmt.Println() } - // Summary fmt.Printf("Total: %d stale", result.TotalCount) if result.BlockingCount > 0 { fmt.Printf(", %d blocking other work", result.BlockingCount) } fmt.Println() + return nil } // findStaleMolecules queries the database for stale molecules diff --git a/cmd/bd/note.go b/cmd/bd/note.go index 72d942a9e..650139302 100644 --- a/cmd/bd/note.go +++ b/cmd/bd/note.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -23,14 +24,22 @@ Examples: bd note gt-abc Fixed the flaky test echo "note from pipe" | bd note gt-abc --stdin bd note gt-abc --file notes.txt`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("note") + evt := metrics.NewCommandEvent("note") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + id := args[0] textArgs := args[1:] - // Determine note text from args, stdin, or file stdinFlag, _ := cmd.Flags().GetBool("stdin") fileFlag, _ := cmd.Flags().GetString("file") @@ -39,23 +48,23 @@ Examples: case stdinFlag: content, err := io.ReadAll(os.Stdin) if err != nil { - FatalErrorRespectJSON("reading from stdin: %v", err) + return HandleErrorRespectJSON("reading from stdin: %v", err) } noteText = strings.TrimRight(string(content), "\n") case fileFlag != "": content, err := readBodyFile(fileFlag) if err != nil { - FatalErrorRespectJSON("reading file: %v", err) + return HandleErrorRespectJSON("reading file: %v", err) } noteText = content case len(textArgs) > 0: noteText = strings.Join(textArgs, " ") default: - FatalErrorRespectJSON("no note text provided (use positional args, --stdin, or --file)") + return HandleErrorRespectJSON("no note text provided (use positional args, --stdin, or --file)") } if noteText == "" { - FatalErrorRespectJSON("note text is empty") + return HandleErrorRespectJSON("note text is empty") } ctx := rootCtx @@ -65,13 +74,13 @@ Examples: if result != nil { result.Close() } - FatalErrorRespectJSON("resolving %s: %v", id, err) + return HandleErrorRespectJSON("resolving %s: %v", id, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } - FatalErrorRespectJSON("issue %s not found", id) + return HandleErrorRespectJSON("issue %s not found", id) } defer result.Close() @@ -79,10 +88,9 @@ Examples: issueStore := result.Store if err := validateIssueUpdatable(id, issue); err != nil { - FatalErrorRespectJSON("%s", err) + return HandleErrorRespectJSON("%s", err) } - // Append to existing notes combined := issue.Notes if combined != "" { combined += "\n" @@ -93,18 +101,17 @@ Examples: "notes": combined, } if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, actor); err != nil { - FatalErrorRespectJSON("updating %s: %v", id, err) + return HandleErrorRespectJSON("updating %s: %v", id, err) } if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{ Command: "note", IssueIDs: []string{result.ResolvedID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } SetLastTouchedID(result.ResolvedID) - // Re-fetch for display updatedIssue, _ := issueStore.GetIssue(ctx, result.ResolvedID) title := "" if updatedIssue != nil { @@ -112,11 +119,12 @@ Examples: } if jsonOutput { if updatedIssue != nil { - outputJSON(updatedIssue) + return outputJSON(updatedIssue) } - } else { - fmt.Printf("%s Note added to %s\n", ui.RenderPass("āœ“"), formatFeedbackID(result.ResolvedID, title)) + return nil } + fmt.Printf("%s Note added to %s\n", ui.RenderPass("āœ“"), formatFeedbackID(result.ResolvedID, title)) + return nil }, } diff --git a/cmd/bd/notion.go b/cmd/bd/notion.go index 1b9ccdcb3..bbdc069af 100644 --- a/cmd/bd/notion.go +++ b/cmd/bd/notion.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/notion" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/tracker" @@ -83,21 +84,27 @@ var notionCmd = &cobra.Command{ } var notionStatusCmd = &cobra.Command{ - Use: "status", - Short: "Show Notion sync status", - RunE: runNotionStatus, + Use: "status", + Short: "Show Notion sync status", + SilenceUsage: true, + SilenceErrors: true, + RunE: runNotionStatus, } var notionInitCmd = &cobra.Command{ - Use: "init", - Short: "Create a dedicated Beads database in Notion", - RunE: runNotionInit, + Use: "init", + Short: "Create a dedicated Beads database in Notion", + SilenceUsage: true, + SilenceErrors: true, + RunE: runNotionInit, } var notionConnectCmd = &cobra.Command{ - Use: "connect", - Short: "Connect bd to an existing Notion database or data source", - RunE: runNotionConnect, + Use: "connect", + Short: "Connect bd to an existing Notion database or data source", + SilenceUsage: true, + SilenceErrors: true, + RunE: runNotionConnect, } var notionSyncCmd = &cobra.Command{ @@ -105,7 +112,9 @@ var notionSyncCmd = &cobra.Command{ Short: "Sync issues with Notion", Long: "Synchronize issues between beads and Notion.\n\n" + "By default this performs bidirectional sync. Use --pull or --push to limit direction.", - RunE: runNotionSync, + SilenceUsage: true, + SilenceErrors: true, + RunE: runNotionSync, } func init() { @@ -210,10 +219,17 @@ func maskNotionAuth(auth *notion.ResolvedAuth) string { } func runNotionStatus(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("notion-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + cfg := getNotionConfig() auth, err := resolveNotionAuth(cmd.Context()) if err != nil { - return err + return HandleError("%v", err) } result := notion.StatusResponse{ Configured: auth != nil && strings.TrimSpace(auth.Token) != "" && cfg.DataSourceID != "", @@ -232,7 +248,8 @@ func runNotionStatus(cmd *cobra.Command, _ []string) error { if jsonOutput { return writeNotionJSON(cmd, result) } - return renderNotionStatus(cmd, auth, cfg, &result) + renderNotionStatus(cmd, auth, cfg, &result) + return nil } client := newNotionStatusClient(auth.Token) @@ -267,29 +284,38 @@ func runNotionStatus(cmd *cobra.Command, _ []string) error { if jsonOutput { return writeNotionJSON(cmd, result) } - return renderNotionStatus(cmd, auth, cfg, &result) + renderNotionStatus(cmd, auth, cfg, &result) + return nil } func runNotionInit(cmd *cobra.Command, _ []string) error { CheckReadonly("notion init") + + evt := metrics.NewCommandEvent("notion-init") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureStoreActive(); err != nil { - return fmt.Errorf("database not available: %w", err) + return HandleError("database not available: %v", err) } auth, err := resolveNotionAuth(cmd.Context()) if err != nil { - return err + return HandleError("%v", err) } if err := validateNotionToken(auth); err != nil { - return err + return HandleError("%v", err) } client := newNotionSetupClient(auth.Token) db, err := client.CreateDatabase(cmd.Context(), notionInitParent, notionInitTitle) if err != nil { - return err + return HandleError("%v", err) } if len(db.DataSources) == 0 || strings.TrimSpace(db.DataSources[0].ID) == "" { - return fmt.Errorf("Notion create database response did not include a child data source") + return HandleError("Notion create database response did not include a child data source") } result := notionSetupResult{ Action: "init", @@ -299,7 +325,7 @@ func runNotionInit(cmd *cobra.Command, _ []string) error { Message: "Notion target initialized", } if err := saveNotionTargetConfig(cmd.Context(), result.DataSourceID, result.ViewURL); err != nil { - return err + return HandleError("%v", err) } if jsonOutput { return writeNotionJSON(cmd, result) @@ -314,25 +340,33 @@ func runNotionInit(cmd *cobra.Command, _ []string) error { func runNotionConnect(cmd *cobra.Command, _ []string) error { CheckReadonly("notion connect") + + evt := metrics.NewCommandEvent("notion-connect") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureStoreActive(); err != nil { - return fmt.Errorf("database not available: %w", err) + return HandleError("database not available: %v", err) } auth, err := resolveNotionAuth(cmd.Context()) if err != nil { - return err + return HandleError("%v", err) } if err := validateNotionToken(auth); err != nil { - return err + return HandleError("%v", err) } client := newNotionSetupClient(auth.Token) resolved, err := notion.ResolveDataSourceReference(cmd.Context(), client, notionConnectURL) if err != nil { - return err + return HandleError("%v", err) } schema := notion.ValidateDataSourceSchema(resolved.DataSource) if len(schema.Missing) > 0 { - return fmt.Errorf("target is missing required Notion properties: %s", strings.Join(schema.Missing, ", ")) + return HandleError("target is missing required Notion properties: %s", strings.Join(schema.Missing, ", ")) } result := notionSetupResult{ Action: "connect", @@ -345,7 +379,7 @@ func runNotionConnect(cmd *cobra.Command, _ []string) error { result.DatabaseID = strings.TrimSpace(resolved.Database.ID) } if err := saveNotionTargetConfig(cmd.Context(), result.DataSourceID, result.ViewURL); err != nil { - return err + return HandleError("%v", err) } if jsonOutput { return writeNotionJSON(cmd, result) @@ -357,7 +391,7 @@ func runNotionConnect(cmd *cobra.Command, _ []string) error { return nil } -func renderNotionStatus(cmd *cobra.Command, auth *notion.ResolvedAuth, cfg notionConfig, result *notion.StatusResponse) error { +func renderNotionStatus(cmd *cobra.Command, auth *notion.ResolvedAuth, cfg notionConfig, result *notion.StatusResponse) { out := cmd.OutOrStdout() _, _ = fmt.Fprintln(out, "Notion Configuration") _, _ = fmt.Fprintln(out, "====================") @@ -391,35 +425,41 @@ func renderNotionStatus(cmd *cobra.Command, auth *notion.ResolvedAuth, cfg notio _, _ = fmt.Fprintf(out, "Schema: missing %s\n", strings.Join(result.Schema.Missing, ", ")) } } - return nil } func runNotionSync(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("notion-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + cfg := getNotionConfig() auth, err := resolveNotionAuth(cmd.Context()) if err != nil { - return err + return HandleError("%v", err) } if err := validateNotionConfig(cfg, auth); err != nil { - return err + return HandleError("%v", err) } if !notionSyncDryRun { CheckReadonly("notion sync") } if notionPreferLocal && notionPreferNotion { - return fmt.Errorf("cannot use both --prefer-local and --prefer-notion") + return HandleError("cannot use both --prefer-local and --prefer-notion") } if notionSyncPull && notionSyncPush { - return fmt.Errorf("cannot use both --pull and --push") + return HandleError("cannot use both --pull and --push") } if err := ensureStoreActive(); err != nil { - return fmt.Errorf("database not available: %w", err) + return HandleError("database not available: %v", err) } ctx := cmd.Context() nt := ¬ion.Tracker{} if err := nt.Init(ctx, store); err != nil { - return fmt.Errorf("initializing Notion tracker: %w", err) + return HandleError("initializing Notion tracker: %v", err) } engine := tracker.NewEngine(nt, store, actor) @@ -461,12 +501,12 @@ func runNotionSync(cmd *cobra.Command, _ []string) error { } if err := applySelectiveSyncFlags(cmd, &syncOpts, push); err != nil { - return err + return HandleError("%v", err) } result, err := engine.Sync(ctx, syncOpts) if err != nil { - return err + return HandleError("%v", err) } if warning := unsupportedStats.warningText(); warning != "" { result.Warnings = append(result.Warnings, warning) @@ -475,10 +515,11 @@ func runNotionSync(cmd *cobra.Command, _ []string) error { if jsonOutput { return writeNotionJSON(cmd, result) } - return renderNotionSyncResult(cmd, result) + renderNotionSyncResult(cmd, result) + return nil } -func renderNotionSyncResult(cmd *cobra.Command, result *tracker.SyncResult) error { +func renderNotionSyncResult(cmd *cobra.Command, result *tracker.SyncResult) { out := cmd.OutOrStdout() if notionSyncDryRun { _, _ = fmt.Fprintln(out, "Dry run mode") @@ -504,7 +545,6 @@ func renderNotionSyncResult(cmd *cobra.Command, result *tracker.SyncResult) erro if notionSyncDryRun { _, _ = fmt.Fprintln(out, "Run without --dry-run to apply changes") } - return nil } func summarizeNotionSyncWarnings(warnings []string) []string { diff --git a/cmd/bd/notion_test.go b/cmd/bd/notion_test.go index 6a87a687d..894917eae 100644 --- a/cmd/bd/notion_test.go +++ b/cmd/bd/notion_test.go @@ -304,7 +304,7 @@ func TestRenderNotionSyncResultUsesPhaseStats(t *testing.T) { var stdout bytes.Buffer cmd.SetOut(&stdout) - err := renderNotionSyncResult(cmd, &tracker.SyncResult{ + renderNotionSyncResult(cmd, &tracker.SyncResult{ Stats: tracker.SyncStats{Pulled: 2, Pushed: 3, Conflicts: 1}, Warnings: []string{ "Skipped unsupported Notion issue types: event=2", @@ -322,9 +322,6 @@ func TestRenderNotionSyncResultUsesPhaseStats(t *testing.T) { Updated: 1, }, }) - if err != nil { - t.Fatalf("renderNotionSyncResult returned error: %v", err) - } out := stdout.String() for _, want := range []string{ "Dry run mode", @@ -358,15 +355,12 @@ func TestRenderNotionSyncResultOmitsMutationSummaryForSameMinuteNoopDryRun(t *te var stdout bytes.Buffer cmd.SetOut(&stdout) - err := renderNotionSyncResult(cmd, &tracker.SyncResult{ + renderNotionSyncResult(cmd, &tracker.SyncResult{ PullStats: tracker.PullStats{ Queried: 49, Candidates: 3, }, }) - if err != nil { - t.Fatalf("renderNotionSyncResult returned error: %v", err) - } out := stdout.String() for _, want := range []string{ "Dry run mode", diff --git a/cmd/bd/onboard.go b/cmd/bd/onboard.go index 7f9df3987..b1a050922 100644 --- a/cmd/bd/onboard.go +++ b/cmd/bd/onboard.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -124,10 +125,20 @@ by default. This approach: For agents or environments that do not auto-inject hook output, use 'bd init --agents-profile=full' to embed the complete command reference.`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("onboard") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := renderOnboardInstructions(cmd.OutOrStdout()); err != nil { - _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Error: %v\n", err) + return HandleError("%v", err) } + return nil }, } diff --git a/cmd/bd/orphans.go b/cmd/bd/orphans.go index 98a91a202..c249db688 100644 --- a/cmd/bd/orphans.go +++ b/cmd/bd/orphans.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/cmd/bd/doctor" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -40,7 +41,16 @@ Examples: bd orphans --fix # Close orphaned issues with confirmation bd orphans --label theme:personal # Only orphans with this label bd orphans --label-any theme:personal,theme:ventures # Orphans with either label`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("orphans") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + path := "." labels, _ := cmd.Flags().GetStringSlice("label") labelsAny, _ := cmd.Flags().GetStringSlice("label-any") @@ -48,25 +58,23 @@ Examples: labelsAny = utils.NormalizeLabels(labelsAny) orphans, err := findOrphanedIssues(path, labels, labelsAny) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } fix, _ := cmd.Flags().GetBool("fix") details, _ := cmd.Flags().GetBool("details") if jsonOutput { - outputJSON(orphans) - return + return outputJSON(orphans) } if len(orphans) == 0 { fmt.Printf("%s No orphaned issues found\n", ui.RenderPass("āœ“")) - return + return nil } fmt.Printf("\n%s Found %d orphaned issue(s):\n\n", ui.RenderWarn("⚠"), len(orphans)) - // Sort by issue ID for consistent output sort.Slice(orphans, func(i, j int) bool { return orphans[i].IssueID < orphans[j].IssueID }) @@ -87,10 +95,9 @@ Examples: response = strings.ToLower(strings.TrimSpace(response)) if response != "" && response != "y" && response != "yes" { fmt.Println("Canceled.") - return + return nil } - // Close orphaned issues closedCount := 0 for _, orphan := range orphans { err := closeIssue(orphan.IssueID) @@ -103,6 +110,7 @@ Examples: } fmt.Printf("\nClosed %d issue(s)\n", closedCount) } + return nil }, } diff --git a/cmd/bd/output.go b/cmd/bd/output.go index 6ef42f05b..104a841e0 100644 --- a/cmd/bd/output.go +++ b/cmd/bd/output.go @@ -9,57 +9,35 @@ import ( "github.com/steveyegge/beads/internal/ui" ) -// JSONSchemaVersion is the current version of the bd JSON output schema. -// Consumers can check this field to detect format changes. Bump when -// fields are added, renamed, or removed from any --json output. const JSONSchemaVersion = 1 -// jsonEnvelopeEnabled returns true when BD_JSON_ENVELOPE=1 is set, -// opting into the uniform {"schema_version": N, "data": } -// envelope for all --json output. This will become the default in v2.0. func jsonEnvelopeEnabled() bool { return os.Getenv("BD_JSON_ENVELOPE") == "1" } -// outputJSON outputs data as pretty-printed JSON to stdout. -// -// When BD_JSON_ENVELOPE=1: all output is wrapped uniformly as -// {"schema_version": N, "data": }. The original payload -// is untouched inside .data — no type corruption, no injection. -// -// Legacy mode (default): objects get schema_version injected as a -// top-level field; arrays pass through unchanged. -func outputJSON(v interface{}) { +func outputJSON(v interface{}) error { wrapped := wrapWithSchemaVersion(v) encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("", " ") if err := encoder.Encode(wrapped); err != nil { - FatalError("encoding JSON: %v", err) + return fmt.Errorf("encoding JSON: %v", err) } if !jsonEnvelopeEnabled() { emitEnvelopeDeprecation() } + return nil } -// outputJSONRaw outputs data without schema_version wrapping. -// Use for internal/machine-only output that should not be versioned. -func outputJSONRaw(v interface{}) { +func outputJSONRaw(v interface{}) error { encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("", " ") if err := encoder.Encode(v); err != nil { - FatalError("encoding JSON: %v", err) + return fmt.Errorf("encoding JSON: %v", err) } + return nil } -// wrapWithSchemaVersion wraps output with schema_version metadata. -// -// Envelope mode (BD_JSON_ENVELOPE=1): all output wrapped uniformly as -// {"schema_version": N, "data": }. Type-safe for all payload -// types including map[string]string and slices. -// -// Legacy mode: objects get schema_version injected inline; arrays and -// slices pass through unchanged for backwards compatibility. func wrapWithSchemaVersion(v interface{}) interface{} { if jsonEnvelopeEnabled() { return map[string]interface{}{ @@ -68,7 +46,6 @@ func wrapWithSchemaVersion(v interface{}) interface{} { } } - // Legacy mode: inline injection for objects, passthrough for arrays. if v == nil { return map[string]interface{}{"schema_version": JSONSchemaVersion} } @@ -96,8 +73,6 @@ func wrapWithSchemaVersion(v interface{}) interface{} { var envelopeDeprecationEmitted bool -// emitEnvelopeDeprecation prints a one-time deprecation notice to stderr -// when --json output is used without BD_JSON_ENVELOPE=1. func emitEnvelopeDeprecation() { if envelopeDeprecationEmitted || !ui.IsStderrTerminal() { return @@ -109,8 +84,7 @@ func emitEnvelopeDeprecation() { "See docs/JSON_SCHEMA.md for migration details.\n") } -// outputJSONError outputs an error as JSON to stderr and exits with code 1. -func outputJSONError(err error, code string) { +func outputJSONError(err error, code string) error { var errObj interface{} base := map[string]interface{}{ "error": err.Error(), @@ -130,5 +104,5 @@ func outputJSONError(err error, code string) { encoder := json.NewEncoder(os.Stderr) encoder.SetIndent("", " ") _ = encoder.Encode(errObj) - os.Exit(1) + return &exitError{Code: 1} } diff --git a/cmd/bd/ping.go b/cmd/bd/ping.go index 0ee62c413..0b61ed95e 100644 --- a/cmd/bd/ping.go +++ b/cmd/bd/ping.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -29,64 +30,69 @@ Exit 0 on success, exit 1 on failure. Examples: bd ping # Quick connectivity check bd ping --json # Structured output for automation`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("ping") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + start := time.Now() beadsDir := beads.FindBeadsDir() if beadsDir == "" { - pingFail(start, "no .beads directory found") - return + return pingFail(start, "no .beads directory found") } resolveMs := time.Since(start).Milliseconds() st := getStore() if st == nil { - pingFail(start, "store not initialized") - return + return pingFail(start, "store not initialized") } if lm, ok := storage.UnwrapStore(st).(storage.LifecycleManager); ok && lm.IsClosed() { - pingFail(start, "store is closed") - return + return pingFail(start, "store is closed") } storeMs := time.Since(start).Milliseconds() filter := types.IssueFilter{Limit: 1} _, err := st.SearchIssues(rootCtx, "", filter) if err != nil { - pingFail(start, fmt.Sprintf("query failed: %v", err)) - return + return pingFail(start, fmt.Sprintf("query failed: %v", err)) } totalMs := time.Since(start).Milliseconds() queryMs := totalMs - storeMs if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "ok", "resolve_ms": resolveMs, "store_ms": storeMs - resolveMs, "query_ms": queryMs, "total_ms": totalMs, }) - return } fmt.Fprintf(os.Stdout, "%s bd ping: ok (%dms)\n", ui.RenderPass("āœ“"), totalMs) + return nil }, } -func pingFail(start time.Time, reason string) { +func pingFail(start time.Time, reason string) error { totalMs := time.Since(start).Milliseconds() if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "status": "error", "error": reason, "total_ms": totalMs, - }) - os.Exit(1) - return + }); jerr != nil { + return jerr + } + return SilentExit() } - fmt.Fprintf(os.Stderr, "%s bd ping: %s (%dms)\n", ui.RenderFail("āœ—"), reason, totalMs) - os.Exit(1) + return HandleError("bd ping: %s (%dms)", reason, totalMs) } func init() { diff --git a/cmd/bd/pour.go b/cmd/bd/pour.go index 813ce5be1..b4cf989e5 100644 --- a/cmd/bd/pour.go +++ b/cmd/bd/pour.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -44,18 +45,26 @@ TIP: Formulas can specify phase:"vapor" to recommend wisp usage. Examples: bd mol pour mol-feature --var name=auth # Persistent feature work bd mol pour mol-review --var pr=123 # Persistent code review`, - Args: cobra.ExactArgs(1), - Run: runPour, + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runPour, } -func runPour(cmd *cobra.Command, args []string) { +func runPour(cmd *cobra.Command, args []string) error { CheckReadonly("pour") + evt := metrics.NewCommandEvent("pour") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // Pour requires direct store access for cloning if store == nil { - FatalError("no database connection") + return HandleError("no database connection") } dryRun, _ := cmd.Flags().GetBool("dry-run") @@ -69,7 +78,7 @@ func runPour(cmd *cobra.Command, args []string) { for _, v := range varFlags { parts := strings.SplitN(v, "=", 2) if len(parts) != 2 { - FatalError("invalid variable format '%s', expected 'key=value'", v) + return HandleError("invalid variable format '%s', expected 'key=value'", v) } vars[parts[0]] = parts[1] } @@ -106,23 +115,21 @@ func runPour(cmd *cobra.Command, args []string) { // Try to load as existing proto bead (legacy path) resolvedID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalError("%s not found as formula or proto ID", args[0]) + return HandleError("%s not found as formula or proto ID", args[0]) } protoID = resolvedID - // Verify it's a proto protoIssue, err := store.GetIssue(ctx, protoID) if err != nil { - FatalError("loading proto %s: %v", protoID, err) + return HandleError("loading proto %s: %v", protoID, err) } if !isProto(protoIssue) { - FatalError("%s is not a proto (missing '%s' label)", protoID, MoleculeLabel) + return HandleError("%s is not a proto (missing '%s' label)", protoID, MoleculeLabel) } - // Load the proto subgraph from DB subgraph, err = loadTemplateSubgraph(ctx, store, protoID) if err != nil { - FatalError("loading proto: %v", err) + return HandleError("loading proto: %v", err) } } @@ -138,18 +145,18 @@ func runPour(cmd *cobra.Command, args []string) { for _, attachArg := range attachFlags { attachID, err := utils.ResolvePartialID(ctx, store, attachArg) if err != nil { - FatalError("resolving attachment ID %s: %v", attachArg, err) + return HandleError("resolving attachment ID %s: %v", attachArg, err) } attachIssue, err := store.GetIssue(ctx, attachID) if err != nil { - FatalError("loading attachment %s: %v", attachID, err) + return HandleError("loading attachment %s: %v", attachID, err) } if !isProto(attachIssue) { - FatalError("%s is not a proto (missing '%s' label)", attachID, MoleculeLabel) + return HandleError("%s is not a proto (missing '%s' label)", attachID, MoleculeLabel) } attachSubgraph, err := loadTemplateSubgraph(ctx, store, attachID) if err != nil { - FatalError("loading attachment subgraph %s: %v", attachID, err) + return HandleError("loading attachment subgraph %s: %v", attachID, err) } attachments = append(attachments, attachmentInfo{ id: attachID, @@ -185,7 +192,7 @@ func runPour(cmd *cobra.Command, args []string) { } } if len(missingVars) > 0 { - FatalErrorWithHint( + return HandleErrorWithHint( fmt.Sprintf("missing required variables: %s", strings.Join(missingVars, ", ")), fmt.Sprintf("Provide them with: --var %s=", missingVars[0]), ) @@ -208,14 +215,12 @@ func runPour(cmd *cobra.Command, args []string) { fmt.Printf(" + %s (%d issues)\n", attach.issue.Title, len(attach.subgraph.Issues)) } } - return + return nil } - // Spawn as persistent mol (ephemeral=false) - // Use mol prefix for distinct visual recognition (see types.IDPrefixMol) result, err := spawnMolecule(ctx, store, subgraph, vars, assignee, actor, false, types.IDPrefixMol) if err != nil { - FatalError("pouring proto: %v", err) + return HandleError("pouring proto: %v", err) } // Attach bonded protos @@ -223,14 +228,13 @@ func runPour(cmd *cobra.Command, args []string) { if len(attachments) > 0 { spawnedMol, err := store.GetIssue(ctx, result.NewEpicID) if err != nil { - FatalError("loading spawned mol: %v", err) + return HandleError("loading spawned mol: %v", err) } for _, attach := range attachments { - // pour command always creates persistent (Wisp=false) issues bondResult, err := bondProtoMol(ctx, store, attach.issue, spawnedMol, attachType, vars, "", actor, false, true) if err != nil { - FatalError("attaching %s: %v", attach.id, err) + return HandleError("attaching %s: %v", attach.id, err) } totalAttached += bondResult.Spawned } @@ -242,8 +246,7 @@ func runPour(cmd *cobra.Command, args []string) { Attached int `json:"attached"` Phase string `json:"phase"` } - outputJSON(pourResult{result, totalAttached, "liquid"}) - return + return outputJSON(pourResult{result, totalAttached, "liquid"}) } fmt.Printf("%s Poured mol: created %d issues\n", ui.RenderPass("āœ“"), result.Created) @@ -252,6 +255,7 @@ func runPour(cmd *cobra.Command, args []string) { if totalAttached > 0 { fmt.Printf(" Attached: %d issues from %d protos\n", totalAttached, len(attachments)) } + return nil } func init() { diff --git a/cmd/bd/preflight.go b/cmd/bd/preflight.go index 41879433e..918b23b1a 100644 --- a/cmd/bd/preflight.go +++ b/cmd/bd/preflight.go @@ -13,6 +13,7 @@ import ( "github.com/steveyegge/beads/cmd/bd/doctor" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/metrics" ) // CheckResult represents the result of a single preflight check. @@ -52,7 +53,9 @@ Examples: bd preflight --check --json # JSON output for programmatic use bd preflight --check --skip-lint # Explicitly skip lint check `, - Run: runPreflight, + SilenceUsage: true, + SilenceErrors: true, + RunE: runPreflight, } func init() { @@ -64,7 +67,14 @@ func init() { rootCmd.AddCommand(preflightCmd) } -func runPreflight(cmd *cobra.Command, args []string) { +func runPreflight(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("preflight") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + check, _ := cmd.Flags().GetBool("check") fix, _ := cmd.Flags().GetBool("fix") jsonOutput, _ := cmd.Flags().GetBool("json") @@ -77,11 +87,9 @@ func runPreflight(cmd *cobra.Command, args []string) { } if check { - runChecks(jsonOutput, skipLint) - return + return runChecks(jsonOutput, skipLint) } - // Static checklist mode fmt.Println("PR Readiness Checklist:") fmt.Println() fmt.Println("[ ] Tests pass: go test -tags gms_pure_go -short ./...") @@ -92,10 +100,10 @@ func runPreflight(cmd *cobra.Command, args []string) { fmt.Println("[ ] Version sync: version.go matches default.nix") fmt.Println() fmt.Println("Run 'bd preflight --check' to validate automatically.") + return nil } -// runChecks executes all preflight checks and reports results. -func runChecks(jsonOutput, skipLint bool) { +func runChecks(jsonOutput, skipLint bool) error { var results []CheckResult // Run test check @@ -162,43 +170,43 @@ func runChecks(jsonOutput, skipLint bool) { enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") if err := enc.Encode(result); err != nil { - fmt.Fprintf(os.Stderr, "Error encoding preflight result: %v\n", err) + return HandleError("encoding preflight result: %v", err) } - } else { - // Human-readable output - for _, r := range results { - if r.Skipped { - fmt.Printf("⚠ %s (skipped)\n", r.Name) - } else if r.Warning { - fmt.Printf("⚠ %s\n", r.Name) - } else if r.Passed { - fmt.Printf("āœ“ %s\n", r.Name) - } else { - fmt.Printf("āœ— %s\n", r.Name) - } - fmt.Printf(" Command: %s\n", r.Command) - if r.Skipped && r.Output != "" { - // Show skip reason - fmt.Printf(" Reason: %s\n", r.Output) - } else if r.Warning && r.Output != "" { - // Show warning message - fmt.Printf(" Warning: %s\n", r.Output) - } else if !r.Passed && r.Output != "" { - // Truncate output for terminal display - output := truncateOutput(r.Output, 500) - fmt.Printf(" Output:\n") - for _, line := range strings.Split(output, "\n") { - fmt.Printf(" %s\n", line) - } - } - fmt.Println() + if !allPassed { + return SilentExit() } - fmt.Println(summary) + return nil } + for _, r := range results { + if r.Skipped { + fmt.Printf("⚠ %s (skipped)\n", r.Name) + } else if r.Warning { + fmt.Printf("⚠ %s\n", r.Name) + } else if r.Passed { + fmt.Printf("āœ“ %s\n", r.Name) + } else { + fmt.Printf("āœ— %s\n", r.Name) + } + fmt.Printf(" Command: %s\n", r.Command) + if r.Skipped && r.Output != "" { + fmt.Printf(" Reason: %s\n", r.Output) + } else if r.Warning && r.Output != "" { + fmt.Printf(" Warning: %s\n", r.Output) + } else if !r.Passed && r.Output != "" { + output := truncateOutput(r.Output, 500) + fmt.Printf(" Output:\n") + for _, line := range strings.Split(output, "\n") { + fmt.Printf(" %s\n", line) + } + } + fmt.Println() + } + fmt.Println(summary) if !allPassed { - os.Exit(1) + return SilentExit() } + return nil } // runTestCheck runs go test -short ./... and returns the result. diff --git a/cmd/bd/prime.go b/cmd/bd/prime.go index 8c6562e2f..1cef456a9 100644 --- a/cmd/bd/prime.go +++ b/cmd/bd/prime.go @@ -17,6 +17,7 @@ import ( "github.com/steveyegge/beads" internalbeads "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" ) var ( @@ -97,9 +98,16 @@ Config options: - Place a .beads/PRIME.md file in the local clone or resolved workspace to override the default output entirely. - Use --export to dump the default content for customization. - Use --memories-only for hook contexts that should inject only persistent memories.`, - Run: func(cmd *cobra.Command, args []string) { - // emit writes content either as raw text (default behavior) or wrapped - // in the SessionStart hook JSON envelope when --hook-json is set. + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("prime") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + emit := func(content string) { if primeHookJSONMode { _ = outputHookJSON(os.Stdout, content) @@ -108,19 +116,14 @@ Config options: } } - // Resolve the active beads workspace. beadsDir := beads.FindBeadsDir() if beadsDir == "" { - // Not in a beads project - silent exit with success - // CRITICAL: No stderr output, exit 0 - // This enables cross-platform hook integration. - // - // Under --hook-json we still must emit a valid JSON envelope - // (with empty additionalContext) so the hook host receives valid JSON. + // Silent exit with success enables cross-platform hook integration. + // Under --hook-json still emit a valid empty envelope. if primeHookJSONMode { _ = outputHookJSON(os.Stdout, "") } - os.Exit(0) + return nil } // Detect MCP mode (unless overridden by flags) @@ -132,54 +135,41 @@ Config options: mcpMode = true } - // Check for stealth mode: flag OR config (GH#593) - // This allows users to disable git ops in session close protocol via config stealthMode := primeStealthMode || config.GetBool("no-git-ops") - // Check for custom PRIME.md override (unless --export flag) - // This allows users to fully customize workflow instructions - // Check local .beads/ first (clone-specific override), then the - // resolved workspace location. if !primeExportMode { localPrimePath := filepath.Join(".beads", "PRIME.md") redirectedPrimePath := filepath.Join(beadsDir, "PRIME.md") - // Try local first (user's clone-specific customization) // #nosec G304 -- path is relative to cwd if content, err := os.ReadFile(localPrimePath); err == nil { emit(string(content)) - return + return nil } - // Fall back to redirected location (shared customization) // #nosec G304 -- path is constructed from beadsDir which we control if content, err := os.ReadFile(redirectedPrimePath); err == nil { emit(string(content)) - return + return nil } - // Fall back to global config (~/.config/beads/PRIME.md) // #nosec G304 -- path constructed from UserConfigDir which we control if globalPath := resolveGlobalPrimePath(""); globalPath != "" { if content, err := os.ReadFile(globalPath); err == nil { emit(string(content)) - return + return nil } } } - // Output workflow context (adaptive based on MCP and stealth mode). - // Buffer first so we can wrap in the hook JSON envelope as a single field. var buf bytes.Buffer if err := outputPrimeContextWithOptions(&buf, mcpMode, stealthMode, primeMemoriesOnly); err != nil { - // Suppress all errors - silent exit with success. - // Never write to stderr (breaks Windows compatibility). - // Under --hook-json still emit the empty envelope so stdout - // is valid JSON for the hook host. + // Errors are suppressed by design for hook integration. if primeHookJSONMode { _ = outputHookJSON(os.Stdout, "") } - os.Exit(0) + return nil } emit(buf.String()) + return nil }, } diff --git a/cmd/bd/priority.go b/cmd/bd/priority.go index df62e74fd..97b18ca66 100644 --- a/cmd/bd/priority.go +++ b/cmd/bd/priority.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/validation" ) @@ -26,16 +27,25 @@ Priority levels: Examples: bd priority bd-123 0 # Critical bd priority bd-123 2 # Medium`, - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("priority") + evt := metrics.NewCommandEvent("priority") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + id := args[0] priorityStr := args[1] priority, err := validation.ValidatePriority(priorityStr) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } ctx := rootCtx @@ -45,38 +55,37 @@ Examples: if result != nil { result.Close() } - FatalErrorRespectJSON("resolving %s: %v", id, err) + return HandleErrorRespectJSON("resolving %s: %v", id, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } - FatalErrorRespectJSON("issue %s not found", id) + return HandleErrorRespectJSON("issue %s not found", id) } defer result.Close() issueStore := result.Store if err := validateIssueUpdatable(id, result.Issue); err != nil { - FatalErrorRespectJSON("%s", err) + return HandleErrorRespectJSON("%s", err) } updates := map[string]interface{}{ "priority": priority, } if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, actor); err != nil { - FatalErrorRespectJSON("updating %s: %v", id, err) + return HandleErrorRespectJSON("updating %s: %v", id, err) } if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{ Command: "priority", IssueIDs: []string{result.ResolvedID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } SetLastTouchedID(result.ResolvedID) - // Re-fetch for display updatedIssue, _ := issueStore.GetIssue(ctx, result.ResolvedID) title := "" if updatedIssue != nil { @@ -84,11 +93,12 @@ Examples: } if jsonOutput { if updatedIssue != nil { - outputJSON(updatedIssue) + return outputJSON(updatedIssue) } - } else { - fmt.Printf("%s Set priority of %s to P%d\n", ui.RenderPass("āœ“"), formatFeedbackID(result.ResolvedID, title), priority) + return nil } + fmt.Printf("%s Set priority of %s to P%d\n", ui.RenderPass("āœ“"), formatFeedbackID(result.ResolvedID, title), priority) + return nil }, } diff --git a/cmd/bd/promote.go b/cmd/bd/promote.go index 561772ba3..c11d076ad 100644 --- a/cmd/bd/promote.go +++ b/cmd/bd/promote.go @@ -6,6 +6,7 @@ import ( "os" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -26,44 +27,48 @@ A comment is added recording the promotion and optional reason. Examples: bd promote bd-wisp-abc123 bd promote bd-wisp-abc123 --reason "Worth tracking long-term"`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("promote") + evt := metrics.NewCommandEvent("promote") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + id := args[0] reason, _ := cmd.Flags().GetString("reason") ctx := rootCtx if store == nil { - FatalErrorWithHint("database not initialized", - diagHint()) + return HandleErrorWithHint("database not initialized", diagHint()) } fullID, err := utils.ResolvePartialID(ctx, store, id) if err != nil { - FatalErrorRespectJSON("resolving %s: %v", id, err) + return HandleErrorRespectJSON("resolving %s: %v", id, err) } - // Verify the issue is actually a wisp issue, err := store.GetIssue(ctx, fullID) if err != nil { if errors.Is(err, storage.ErrNotFound) { - FatalErrorRespectJSON("issue %s not found", fullID) + return HandleErrorRespectJSON("issue %s not found", fullID) } - FatalErrorRespectJSON("getting issue %s: %v", fullID, err) + return HandleErrorRespectJSON("getting issue %s: %v", fullID, err) } if !issue.Ephemeral { - FatalErrorRespectJSON("%s is not a wisp (already persistent)", fullID) + return HandleErrorRespectJSON("%s is not a wisp (already persistent)", fullID) } - // Promote: copy from wisps to issues table, preserving labels/deps/events/comments if err := store.PromoteFromEphemeral(ctx, fullID, actor); err != nil { - FatalErrorRespectJSON("promoting %s: %v", fullID, err) + return HandleErrorRespectJSON("promoting %s: %v", fullID, err) } - // Add promotion comment (issue is now in permanent table, AddComment routes correctly - // via GetIssue fallback) comment := "Promoted from wisp to permanent bead" if reason != "" { comment += ": " + reason @@ -77,11 +82,12 @@ Examples: if jsonOutput { updated, _ := store.GetIssue(ctx, fullID) if updated != nil { - outputJSON(updated) + return outputJSON(updated) } - } else { - fmt.Printf("%s Promoted %s to permanent bead\n", ui.RenderPass("āœ“"), fullID) + return nil } + fmt.Printf("%s Promoted %s to permanent bead\n", ui.RenderPass("āœ“"), fullID) + return nil }, } diff --git a/cmd/bd/prompt.go b/cmd/bd/prompt.go index 6145aaf29..239f6c113 100644 --- a/cmd/bd/prompt.go +++ b/cmd/bd/prompt.go @@ -63,6 +63,6 @@ func isCanceled(err error) bool { return errors.Is(err, context.Canceled) } -func exitCanceled() { - os.Exit(exitCodeCanceled) +func errCanceled() error { + return &exitError{Code: exitCodeCanceled} } diff --git a/cmd/bd/proxied_integration_helpers_test.go b/cmd/bd/proxied_integration_helpers_test.go index 9c4abbe65..ae9a88334 100644 --- a/cmd/bd/proxied_integration_helpers_test.go +++ b/cmd/bd/proxied_integration_helpers_test.go @@ -45,6 +45,8 @@ func bdProxiedEnv(dir string) []string { "HOME="+dir, "BEADS_DOLT_PROXIED_SERVER=1", "BEADS_NO_DAEMON=1", + "BD_DISABLE_METRICS=1", + "BD_DISABLE_EVENT_FLUSH=1", ) } diff --git a/cmd/bd/prune.go b/cmd/bd/prune.go index b5d35904b..60282e9d1 100644 --- a/cmd/bd/prune.go +++ b/cmd/bd/prune.go @@ -2,6 +2,8 @@ package main import ( "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/metrics" ) var pruneCmd = &cobra.Command{ @@ -33,8 +35,17 @@ EXAMPLES: bd prune --older-than 90d --dry-run # Detailed preview with stats bd prune --pattern "*" --force # Delete all closed regular beads bd prune --pattern "gm-temp-*" --force # Scope to a pattern`, - Run: func(cmd *cobra.Command, _ []string) { - runPurgeOrPrune(cmd, purgeScope{ + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("prune") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + + return runPurgeOrPrune(cmd, purgeScope{ cmdName: "prune", pastTense: "pruned", countKey: "pruned_count", diff --git a/cmd/bd/purge.go b/cmd/bd/purge.go index f4401ea6f..5515b1eb2 100644 --- a/cmd/bd/purge.go +++ b/cmd/bd/purge.go @@ -8,6 +8,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -64,8 +65,17 @@ EXAMPLES: bd purge --older-than 7d --force # Only purge items closed 7+ days ago bd purge --pattern "*-wisp-*" # Only purge matching ID pattern bd purge --dry-run # Detailed preview with stats`, - Run: func(cmd *cobra.Command, _ []string) { - runPurgeOrPrune(cmd, purgeScope{ + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, _ []string) error { + evt := metrics.NewCommandEvent("purge") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + + return runPurgeOrPrune(cmd, purgeScope{ cmdName: "purge", pastTense: "purged", countKey: "purged_count", @@ -77,10 +87,7 @@ EXAMPLES: }, } -// runPurgeOrPrune implements the shared delete-closed-beads flow used by -// both `bd purge` (ephemeral scope) and `bd prune` (non-ephemeral scope). -// The caller's scope controls the filter, messaging, and safety gate. -func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) { +func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error { CheckReadonly(scope.cmdName) force, _ := cmd.Flags().GetBool("force") @@ -88,10 +95,8 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) { olderThan, _ := cmd.Flags().GetString("older-than") pattern, _ := cmd.Flags().GetString("pattern") - // Safety gate: prune refuses to run without scope narrowing so a typo - // or muscle-memory `--force` can't wipe every closed bead in the repo. if scope.requireFilter && olderThan == "" && pattern == "" { - FatalErrorWithHint( + return HandleErrorWithHint( fmt.Sprintf("bd %s requires --older-than or --pattern", scope.cmdName), "Protects against accidental bulk deletion. Use `--pattern '*'` to\n"+ " include all closed beads in this scope, or `--older-than 1d`\n"+ @@ -100,13 +105,12 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) { if store == nil { if err := ensureStoreActive(); err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } } ctx := rootCtx - // Build filter: closed + ephemeral-or-not per scope statusClosed := types.StatusClosed ephemeralFlag := scope.ephemeralOnly filter := types.IssueFilter{ @@ -114,25 +118,22 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) { Ephemeral: &ephemeralFlag, } - // Parse --older-than duration (e.g., "7d", "30d", "24h", or just "30" for days) var cutoff *time.Time if olderThan != "" { days, err := parseHumanDuration(olderThan) if err != nil { - FatalError("invalid --older-than value %q: %v", olderThan, err) + return HandleErrorRespectJSON("invalid --older-than value %q: %v", olderThan, err) } cutoffTime := time.Now().UTC().AddDate(0, 0, -days) cutoff = &cutoffTime filter.ClosedBefore = cutoff } - // Get matching issues closedIssues, err := store.SearchIssues(ctx, "", filter) if err != nil { - FatalError("listing issues: %v", err) + return HandleErrorRespectJSON("listing issues: %v", err) } - // Filter by ID pattern if specified if pattern != "" { var matched []*types.Issue for _, issue := range closedIssues { @@ -148,33 +149,29 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) { pinnedCount := safetyStats.PinnedSkipped warnClosedDeletionSafetySkips(safetyStats) - // Report nothing-to-do if len(closedIssues) == 0 { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ scope.countKey: 0, "message": fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName), }) - } else { - msg := fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName) - if olderThan != "" { - msg += fmt.Sprintf(" (older than %s)", olderThan) - } - if pattern != "" { - msg += fmt.Sprintf(" (matching %q)", pattern) - } - fmt.Println(msg) } - return + msg := fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName) + if olderThan != "" { + msg += fmt.Sprintf(" (older than %s)", olderThan) + } + if pattern != "" { + msg += fmt.Sprintf(" (matching %q)", pattern) + } + fmt.Println(msg) + return nil } - // Extract IDs issueIDs := make([]string, len(closedIssues)) for i, issue := range closedIssues { issueIDs[i] = issue.ID } - // Dry-run: show stats preview if dryRun { result, err := store.DeleteIssues(ctx, issueIDs, false, false, true) if jsonOutput { @@ -193,23 +190,21 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) { if pinnedCount > 0 { stats["pinned_skipped"] = pinnedCount } - outputJSON(stats) - } else { - fmt.Printf("Would %s %d %s(s)\n", scope.cmdName, len(issueIDs), scope.subjectNoun) - if err == nil { - fmt.Printf(" Dependencies: %d\n", result.DependenciesCount) - fmt.Printf(" Labels: %d\n", result.LabelsCount) - fmt.Printf(" Events: %d\n", result.EventsCount) - } - if pinnedCount > 0 { - fmt.Printf(" Pinned (skipped): %d\n", pinnedCount) - } - fmt.Printf("\n(Dry-run mode — no changes made)\n") + return outputJSON(stats) } - return + fmt.Printf("Would %s %d %s(s)\n", scope.cmdName, len(issueIDs), scope.subjectNoun) + if err == nil { + fmt.Printf(" Dependencies: %d\n", result.DependenciesCount) + fmt.Printf(" Labels: %d\n", result.LabelsCount) + fmt.Printf(" Events: %d\n", result.EventsCount) + } + if pinnedCount > 0 { + fmt.Printf(" Pinned (skipped): %d\n", pinnedCount) + } + fmt.Printf("\n(Dry-run mode — no changes made)\n") + return nil } - // Preview mode (no --force) if !force { fmt.Printf("Found %d %s(s) to %s\n", len(issueIDs), scope.subjectNoun, scope.cmdName) if pinnedCount > 0 { @@ -222,18 +217,20 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) { if pattern != "" { hint += " --pattern " + pattern } - FatalErrorWithHint( + return HandleErrorWithHint( fmt.Sprintf("would %s %d bead(s)", scope.cmdName, len(issueIDs)), fmt.Sprintf("Use --force to confirm or --dry-run to preview.\n %s", hint)) } - // Actually purge result, err := store.DeleteIssues(ctx, issueIDs, false, true, false) if err != nil { - FatalError("%s failed: %v", scope.cmdName, err) + return HandleErrorRespectJSON("%s failed: %v", scope.cmdName, err) } commandDidWrite.Store(true) + if result.DeletedCount > 0 { + commandMayEmptyJSONLExport.Store(true) + } if jsonOutput { stats := map[string]interface{}{ @@ -245,21 +242,16 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) { if pinnedCount > 0 { stats["pinned_skipped"] = pinnedCount } - outputJSON(stats) - } else { - fmt.Printf("%s %s %d %s(s)\n", ui.RenderPass("āœ“"), capitalize(scope.pastTense), result.DeletedCount, scope.subjectNoun) - fmt.Printf(" Dependencies removed: %d\n", result.DependenciesCount) - fmt.Printf(" Labels removed: %d\n", result.LabelsCount) - fmt.Printf(" Events removed: %d\n", result.EventsCount) - if pinnedCount > 0 { - fmt.Printf(" Pinned (skipped): %d\n", pinnedCount) - } + return outputJSON(stats) } - - if result.DeletedCount > 0 { - commandDidWrite.Store(true) - commandMayEmptyJSONLExport.Store(true) + fmt.Printf("%s %s %d %s(s)\n", ui.RenderPass("āœ“"), capitalize(scope.pastTense), result.DeletedCount, scope.subjectNoun) + fmt.Printf(" Dependencies removed: %d\n", result.DependenciesCount) + fmt.Printf(" Labels removed: %d\n", result.LabelsCount) + fmt.Printf(" Events removed: %d\n", result.EventsCount) + if pinnedCount > 0 { + fmt.Printf(" Pinned (skipped): %d\n", pinnedCount) } + return nil } func capitalize(s string) string { diff --git a/cmd/bd/query.go b/cmd/bd/query.go index 63acc2c60..4fe511408 100644 --- a/cmd/bd/query.go +++ b/cmd/bd/query.go @@ -7,6 +7,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/query" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -73,19 +74,26 @@ Examples: bd query "created>30d AND status!=closed" bd query "label=frontend OR label=backend" bd query "title=authentication AND priority=0"`, - Run: func(cmd *cobra.Command, args []string) { - // Get query from args + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("query") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { fmt.Fprintf(os.Stderr, "Error: query expression is required\n\n") if err := cmd.Help(); err != nil { fmt.Fprintf(os.Stderr, "Error displaying help: %v\n", err) } - os.Exit(1) + return SilentExit() } queryStr := strings.Join(args, " ") - // Get option flags limit, _ := cmd.Flags().GetInt("limit") allFlag, _ := cmd.Flags().GetBool("all") longFormat, _ := cmd.Flags().GetBool("long") @@ -93,40 +101,34 @@ Examples: reverse, _ := cmd.Flags().GetBool("reverse") parseOnly, _ := cmd.Flags().GetBool("parse-only") - // Parse the query node, err := query.Parse(queryStr) if err != nil { - FatalError("parsing query: %v", err) + return HandleErrorRespectJSON("parsing query: %v", err) } - // If --parse-only, just show the parsed AST if parseOnly { fmt.Printf("Parsed query: %s\n", node.String()) - return + return nil } - // Evaluate the query to get filter and/or predicate eval := query.NewEvaluator(time.Now()) result, err := eval.Evaluate(node) if err != nil { - FatalError("evaluating query: %v", err) + return HandleErrorRespectJSON("evaluating query: %v", err) } - // Apply limit if specified if limit > 0 && !result.RequiresPredicate { result.Filter.Limit = limit } - // By default exclude closed issues unless --all is specified or query explicitly filters by status if !allFlag && result.Filter.Status == nil && !hasExplicitStatusFilter(node) { result.Filter.ExcludeStatus = append(result.Filter.ExcludeStatus, types.StatusClosed) } ctx := rootCtx - // Direct mode if store == nil { - FatalError("no storage available") + return HandleErrorRespectJSON("no storage available") } searchFilter := result.Filter @@ -140,7 +142,7 @@ Examples: if jsonOutput { iwc, err := store.SearchIssuesWithCounts(ctx, "", searchFilter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if result.RequiresPredicate && result.Predicate != nil { filtered := make([]*types.IssueWithCounts, 0, len(iwc)) @@ -161,13 +163,12 @@ Examples: if iwc == nil { iwc = []*types.IssueWithCounts{} } - outputJSON(iwc) - return + return outputJSON(iwc) } issues, err := store.SearchIssues(ctx, "", searchFilter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if result.RequiresPredicate && result.Predicate != nil { @@ -186,6 +187,7 @@ Examples: sortIssues(issues, sortBy, reverse) outputQueryResults(issues, queryStr, longFormat) + return nil }, } diff --git a/cmd/bd/quick.go b/cmd/bd/quick.go index c51cbc15d..db42b979d 100644 --- a/cmd/bd/quick.go +++ b/cmd/bd/quick.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/validation" ) @@ -20,24 +21,30 @@ Example: bd q "Fix login bug" # Outputs: bd-a1b2 ISSUE=$(bd q "New feature") # Capture ID in variable bd q "Task" | xargs bd show # Pipe to other commands`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("create") + evt := metrics.NewCommandEvent("q") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + title := strings.Join(args, " ") - // Get optional flags priorityStr, _ := cmd.Flags().GetString("priority") issueType, _ := cmd.Flags().GetString("type") labels, _ := cmd.Flags().GetStringSlice("labels") - // Parse priority priority, err := validation.ValidatePriority(priorityStr) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - // Direct mode issue := &types.Issue{ Title: title, Status: types.StatusOpen, @@ -48,13 +55,13 @@ Example: ctx := rootCtx if err := store.CreateIssue(ctx, issue, actor); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } commandDidWrite.Store(true) - // Output only the ID fmt.Println(issue.ID) + return nil }, } diff --git a/cmd/bd/quickstart.go b/cmd/bd/quickstart.go index 3c244a732..bf7bde9b0 100644 --- a/cmd/bd/quickstart.go +++ b/cmd/bd/quickstart.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -13,6 +14,13 @@ var quickstartCmd = &cobra.Command{ Short: "Quick start guide for bd", Long: `Display a quick start guide showing common bd workflows and patterns.`, Run: func(cmd *cobra.Command, args []string) { + evt := metrics.NewCommandEvent("quickstart") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + fmt.Printf("\n%s\n\n", ui.RenderBold("bd - Dependency-Aware Issue Tracker")) fmt.Printf("Issues chained together like beads.\n\n") diff --git a/cmd/bd/ready.go b/cmd/bd/ready.go index 1a8ae7d46..ea09e9c07 100644 --- a/cmd/bd/ready.go +++ b/cmd/bd/ready.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/debug" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -35,46 +36,49 @@ Use --claim to atomically claim the first ready issue matching the filters: bd ready --claim --json This is useful for agents executing molecules to see which steps can run next.`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("ready") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runReadyProxiedServer(cmd, rootCtx) - return + return nil } if offset, _ := cmd.Flags().GetInt("offset"); offset > 0 { - FatalError("--offset is only supported under --proxied-server") + return HandleErrorRespectJSON("--offset is only supported under --proxied-server") } claimReady, _ := cmd.Flags().GetBool("claim") - // Handle --gated flag (gate-resume discovery) gated, _ := cmd.Flags().GetBool("gated") if gated { if claimReady { - FatalErrorRespectJSON("--claim cannot be combined with --gated") + return HandleErrorRespectJSON("--claim cannot be combined with --gated") } - runMolReadyGated(cmd, args) - return + return runMolReadyGated(cmd, args) } - // Handle molecule-specific ready query molID, _ := cmd.Flags().GetString("mol") if molID != "" { if claimReady { - FatalErrorRespectJSON("--claim cannot be combined with --mol") + return HandleErrorRespectJSON("--claim cannot be combined with --mol") } - runMoleculeReady(cmd, molID) - return + return runMoleculeReady(cmd, molID) } - // Handle --explain flag (dependency-aware reasoning) explain, _ := cmd.Flags().GetBool("explain") if explain { if claimReady { - FatalErrorRespectJSON("--claim cannot be combined with --explain") + return HandleErrorRespectJSON("--claim cannot be combined with --explain") } - runReadyExplain(cmd) - return + return runReadyExplain(cmd) } limit, _ := cmd.Flags().GetInt("limit") @@ -97,13 +101,12 @@ This is useful for agents executing molecules to see which steps can run next.`, if molTypeStr != "" { mt := types.MolType(molTypeStr) if !mt.IsValid() { - FatalError("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr) + return HandleErrorRespectJSON("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr) } molType = &mt } - // Use global jsonOutput set by PersistentPreRun (respects config.yaml + env vars) if claimReady && assignee != "" { - FatalErrorRespectJSON("--claim cannot be combined with --assignee") + return HandleErrorRespectJSON("--claim cannot be combined with --assignee") } // Normalize labels: trim, dedupe, remove empty @@ -163,12 +166,10 @@ This is useful for agents executing molecules to see which steps can run next.`, for _, mf := range metadataFieldFlags { k, v, ok := strings.Cut(mf, "=") if !ok || k == "" { - fmt.Fprintf(os.Stderr, "Error: invalid --metadata-field: expected key=value, got %q\n", mf) - os.Exit(1) + return HandleErrorRespectJSON("invalid --metadata-field: expected key=value, got %q", mf) } if err := storage.ValidateMetadataKey(k); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid --metadata-field key: %v\n", err) - os.Exit(1) + return HandleErrorRespectJSON("invalid --metadata-field key: %v", err) } filter.MetadataFields[k] = v } @@ -176,27 +177,23 @@ This is useful for agents executing molecules to see which steps can run next.`, hasMetadataKey, _ := cmd.Flags().GetString("has-metadata-key") if hasMetadataKey != "" { if err := storage.ValidateMetadataKey(hasMetadataKey); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid --has-metadata-key: %v\n", err) - os.Exit(1) + return HandleErrorRespectJSON("invalid --has-metadata-key: %v", err) } filter.HasMetadataKey = hasMetadataKey } - // Validate sort policy if !filter.SortPolicy.IsValid() { - FatalError("invalid sort policy '%s'. Valid values: hybrid, priority, oldest", sortPolicy) + return HandleErrorRespectJSON("invalid sort policy '%s'. Valid values: hybrid, priority, oldest", sortPolicy) } - // Direct mode ctx := rootCtx activeStore := store if claimReady { CheckReadonly("ready --claim") } else { - // Contributor auto-routing: read from the same target repo as bd create. routedStore, routed, err := openRoutedReadStore(ctx, activeStore) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if routed { defer func() { _ = routedStore.Close() }() @@ -207,35 +204,33 @@ This is useful for agents executing molecules to see which steps can run next.`, if claimReady { claimed, err := activeStore.ClaimReadyIssue(ctx, filter, actor) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } if claimed == nil { if jsonOutput { - outputJSON([]*types.IssueWithCounts{}) - } else { - fmt.Printf("\n%s No ready work to claim\n\n", ui.RenderWarn("ā—‹")) + return outputJSON([]*types.IssueWithCounts{}) } - return + fmt.Printf("\n%s No ready work to claim\n\n", ui.RenderWarn("ā—‹")) + return nil } if err := commitPendingIfEmbedded(ctx, activeStore, actor, doltAutoCommitParams{ Command: "ready", IssueIDs: []string{claimed.ID}, }); err != nil { - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } SetLastTouchedID(claimed.ID) if jsonOutput { - outputJSON(buildReadyIssueOutput(ctx, activeStore, []*types.Issue{claimed})) - } else { - fmt.Printf("%s Claimed issue: %s\n", ui.RenderPass("āœ“"), formatFeedbackID(claimed.ID, claimed.Title)) + return outputJSON(buildReadyIssueOutput(ctx, activeStore, []*types.Issue{claimed})) } - return + fmt.Printf("%s Claimed issue: %s\n", ui.RenderPass("āœ“"), formatFeedbackID(claimed.ID, claimed.Title)) + return nil } if jsonOutput { results, err := activeStore.GetReadyWorkWithCounts(ctx, filter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } totalReady := len(results) truncated := false @@ -251,16 +246,18 @@ This is useful for agents executing molecules to see which steps can run next.`, if results == nil { results = []*types.IssueWithCounts{} } - outputJSON(results) + if jerr := outputJSON(results); jerr != nil { + return jerr + } if truncated { fmt.Fprintf(os.Stderr, "Showing %d of %d ready issues. Use --limit 0 for all, or --limit N to raise the cap.\n", len(results), totalReady) } - return + return nil } issues, err := activeStore.GetReadyWork(ctx, filter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } totalReady := len(issues) @@ -274,11 +271,9 @@ This is useful for agents executing molecules to see which steps can run next.`, truncated = true } } - // Show upgrade notification if needed maybeShowUpgradeNotification() if len(issues) == 0 { - // Check if there are any open issues at all hasOpenIssues := false if stats, statsErr := activeStore.GetStatistics(ctx); statsErr == nil { hasOpenIssues = stats.OpenIssues > 0 || stats.InProgressIssues > 0 @@ -289,14 +284,11 @@ This is useful for agents executing molecules to see which steps can run next.`, } else { fmt.Printf("\n%s No open issues\n\n", ui.RenderPass("✨")) } - // Show tip even when no ready work found maybeShowTip(store) - return + return nil } - // Build parent epic map for pretty display parentEpicMap := buildParentEpicMap(ctx, activeStore, issues) - // Determine display mode: --plain or --pretty=false triggers plain format usePlain := plainFormat || !prettyFormat if usePlain { fmt.Printf("\n%s Ready work (%d issues with no active blockers):\n\n", ui.RenderAccent("šŸ“‹"), len(issues)) @@ -317,22 +309,30 @@ This is useful for agents executing molecules to see which steps can run next.`, displayReadyList(issues, parentEpicMap) } - // Show truncation footer if results were limited if truncated { fmt.Printf("%s\n\n", ui.RenderMuted(fmt.Sprintf("Showing %d of %d ready issues. Use -n to show more.", len(issues), totalReady))) } - // Show tip after successful ready (direct mode only) maybeShowTip(store) + return nil }, } var blockedCmd = &cobra.Command{ - Use: "blocked", - Short: "Show blocked issues", - Run: func(cmd *cobra.Command, args []string) { + Use: "blocked", + Short: "Show blocked issues", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("blocked") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runBlockedProxiedServer(cmd, rootCtx) - return + return nil } // Use global jsonOutput set by PersistentPreRun (respects config.yaml + env vars) // Use factory to respect backend configuration (bd-m2jr: SQLite fallback fix) @@ -344,19 +344,17 @@ var blockedCmd = &cobra.Command{ } blocked, err := store.GetBlockedIssues(ctx, blockedFilter) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { - // Always output array, even if empty if blocked == nil { blocked = []*types.BlockedIssue{} } - outputJSON(blocked) - return + return outputJSON(blocked) } 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 { @@ -371,6 +369,7 @@ var blockedCmd = &cobra.Command{ issue.BlockedByCount, blockedBy) fmt.Println() } + return nil }, } @@ -486,26 +485,23 @@ func buildReadyIssueOutput(ctx context.Context, s storage.DoltStorage, issues [] return issuesWithCounts } -// runReadyExplain shows dependency-aware reasoning for why issues are ready or blocked. -func runReadyExplain(_ *cobra.Command) { +func runReadyExplain(_ *cobra.Command) error { ctx := rootCtx activeStore := store - // Get ready issues (no limit for explain mode — show everything) filter := types.WorkFilter{ Status: types.StatusOpen, SortPolicy: types.SortPolicyPriority, } readyIssues, err := activeStore.GetReadyWork(ctx, filter) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Get blocked issues blockedIssues, err := activeStore.GetBlockedIssues(ctx, types.WorkFilter{}) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } // Get dependency records for ready issues to find resolved blockers @@ -553,11 +549,9 @@ func runReadyExplain(_ *cobra.Command) { explanation := types.BuildReadyExplanation(readyIssues, blockedIssues, depCounts, allDeps, blockerMap, cycles) if jsonOutput { - outputJSON(explanation) - return + return outputJSON(explanation) } - // Human-readable output fmt.Printf("\n%s Ready Work Explanation\n\n", ui.RenderAccent("šŸ“Š")) // Ready section @@ -615,27 +609,24 @@ func runReadyExplain(_ *cobra.Command) { fmt.Printf(", %d cycle(s)", explanation.Summary.CycleCount) } fmt.Printf("\n\n") + return nil } -// runMoleculeReady shows ready steps within a specific molecule -func runMoleculeReady(_ *cobra.Command, molIDArg string) { +func runMoleculeReady(_ *cobra.Command, molIDArg string) error { ctx := rootCtx - // Molecule-ready requires direct store access for subgraph loading if store == nil { - FatalError("no database connection") + return HandleErrorRespectJSON("no database connection") } - // Resolve molecule ID moleculeID, err := utils.ResolvePartialID(ctx, store, molIDArg) if err != nil { - FatalError("molecule '%s' not found", molIDArg) + return HandleErrorRespectJSON("molecule '%s' not found", molIDArg) } - // Load molecule subgraph subgraph, err := loadTemplateSubgraph(ctx, store, moleculeID) if err != nil { - FatalError("loading molecule: %v", err) + return HandleErrorRespectJSON("loading molecule: %v", err) } // Get parallel analysis to find ready steps @@ -655,26 +646,23 @@ func runMoleculeReady(_ *cobra.Command, molIDArg string) { } if jsonOutput { - output := MoleculeReadyOutput{ + return outputJSON(MoleculeReadyOutput{ MoleculeID: moleculeID, MoleculeTitle: subgraph.Root.Title, TotalSteps: analysis.TotalSteps, ReadySteps: len(readySteps), Steps: readySteps, ParallelGroups: analysis.ParallelGroups, - } - outputJSON(output) - return + }) } - // Human-readable output fmt.Printf("\n%s Ready steps in molecule: %s\n", ui.RenderAccent("🧪"), subgraph.Root.Title) fmt.Printf(" ID: %s\n", moleculeID) 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 } // Show parallel groups if any @@ -709,7 +697,6 @@ func runMoleculeReady(_ *cobra.Command, molIDArg string) { step.Issue.Title, groupAnnotation) - // Show what this step can parallelize with if len(step.ParallelInfo.CanParallel) > 0 { readyParallel := []string{} for _, pID := range step.ParallelInfo.CanParallel { @@ -723,6 +710,7 @@ func runMoleculeReady(_ *cobra.Command, molIDArg string) { } } fmt.Println() + return nil } // MoleculeReadyStep holds a ready step with its parallel info diff --git a/cmd/bd/relate.go b/cmd/bd/relate.go index e2b768c54..55bb116da 100644 --- a/cmd/bd/relate.go +++ b/cmd/bd/relate.go @@ -6,6 +6,7 @@ import ( "os" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -52,6 +53,13 @@ func init() { func runRelate(cmd *cobra.Command, args []string) error { CheckReadonly("relate") + evt := metrics.NewCommandEvent("relate") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx // Resolve partial IDs @@ -127,6 +135,13 @@ func runRelate(cmd *cobra.Command, args []string) error { func runUnrelate(cmd *cobra.Command, args []string) error { CheckReadonly("unrelate") + evt := metrics.NewCommandEvent("unrelate") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx // Resolve partial IDs diff --git a/cmd/bd/rename.go b/cmd/bd/rename.go index 24f12775b..5dd2898a0 100644 --- a/cmd/bd/rename.go +++ b/cmd/bd/rename.go @@ -7,6 +7,7 @@ import ( "regexp" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -28,8 +29,10 @@ Examples: bd rename gt-abc123 gt-auth # Use descriptive ID Note: The new ID must use a valid prefix for this database.`, - Args: cobra.ExactArgs(2), - RunE: runRename, + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: runRename, } func init() { @@ -37,53 +40,53 @@ func init() { } func runRename(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("rename") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + oldID := args[0] newID := args[1] - // Validate IDs if oldID == newID { - return fmt.Errorf("old and new IDs are the same") + return HandleError("old and new IDs are the same") } - // Basic ID format validation idPattern := regexp.MustCompile(`^[a-z]+-[a-zA-Z0-9._-]+$`) if !idPattern.MatchString(newID) { - return fmt.Errorf("invalid new ID format %q: must be prefix-suffix (e.g., bd-dolt)", newID) + return HandleError("invalid new ID format %q: must be prefix-suffix (e.g., bd-dolt)", newID) } ctx := context.Background() if err := ensureStoreActive(); err != nil { - return fmt.Errorf("failed to get storage: %w", err) + return HandleError("failed to get storage: %v", err) } - // Check if old issue exists oldIssue, err := store.GetIssue(ctx, oldID) if err != nil { if errors.Is(err, storage.ErrNotFound) { - return fmt.Errorf("issue %s not found", oldID) + return HandleError("issue %s not found", oldID) } - return fmt.Errorf("failed to get issue %s: %w", oldID, err) + return HandleError("failed to get issue %s: %v", oldID, err) } - // Check if new ID already exists _, err = store.GetIssue(ctx, newID) if err == nil { - return fmt.Errorf("issue %s already exists", newID) + return HandleError("issue %s already exists", newID) } if !errors.Is(err, storage.ErrNotFound) { - return fmt.Errorf("failed to check for existing issue: %w", err) + return HandleError("failed to check for existing issue: %v", err) } - // Update the issue ID oldIssue.ID = newID actor := getActorWithGit() if err := store.UpdateIssueID(ctx, oldID, newID, oldIssue, actor); err != nil { - return fmt.Errorf("failed to rename issue: %w", err) + return HandleError("failed to rename issue: %v", err) } - // Update references in other issues if err := updateReferencesInAllIssues(ctx, store, oldID, newID, actor); err != nil { - // Non-fatal - the primary rename succeeded fmt.Printf("Warning: failed to update some references: %v\n", err) } diff --git a/cmd/bd/rename_prefix.go b/cmd/bd/rename_prefix.go index 71be16b48..195b0f683 100644 --- a/cmd/bd/rename_prefix.go +++ b/cmd/bd/rename_prefix.go @@ -13,6 +13,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -50,48 +51,52 @@ EXAMPLES: bd rename-prefix team- --dry-run # Preview changes without applying NOTE: This is a rare operation. Most users never need this command.`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("rename-prefix") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + newPrefix := args[0] dryRun, _ := cmd.Flags().GetBool("dry-run") repair, _ := cmd.Flags().GetBool("repair") - // Block writes in readonly mode if !dryRun { CheckReadonly("rename-prefix") } ctx := rootCtx - // rename-prefix requires direct database access if store == nil { if err := ensureStoreActive(); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } } if err := validatePrefix(newPrefix); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } oldPrefix, err := store.GetConfig(ctx, "issue_prefix") if err != nil || oldPrefix == "" { - FatalError("failed to get current prefix: %v", err) + return HandleError("failed to get current prefix: %v", err) } newPrefix = strings.TrimRight(newPrefix, "-") - // Check for multiple prefixes first issues, err := store.SearchIssues(ctx, "", types.IssueFilter{}) if err != nil { - FatalError("failed to list issues: %v", err) + return HandleError("failed to list issues: %v", err) } prefixes := detectPrefixes(issues) if len(prefixes) > 1 { - // Multiple prefixes detected - requires repair mode - fmt.Fprintf(os.Stderr, "%s Multiple prefixes detected in database:\n", ui.RenderFail("āœ—")) for prefix, count := range prefixes { fmt.Fprintf(os.Stderr, " - %s: %d issues\n", ui.RenderWarn(prefix), count) @@ -99,37 +104,34 @@ NOTE: This is a rare operation. Most users never need this command.`, fmt.Fprintf(os.Stderr, "\n") if !repair { - FatalErrorWithHint( + return HandleErrorWithHint( "cannot rename with multiple prefixes. Use --repair to consolidate.", fmt.Sprintf("Example: bd rename-prefix %s --repair", newPrefix), ) } - // Repair mode: consolidate all prefixes to newPrefix if err := repairPrefixes(ctx, store, actor, newPrefix, issues, prefixes, dryRun); err != nil { - FatalError("failed to repair prefixes: %v", err) + return HandleError("failed to repair prefixes: %v", err) } if !dryRun { commandDidWrite.Store(true) } - return + return nil } - // Single prefix case - check if trying to rename to same prefix if len(prefixes) == 1 && oldPrefix == newPrefix { - FatalError("new prefix is the same as current prefix: %s", oldPrefix) + return HandleError("new prefix is the same as current prefix: %s", oldPrefix) } - // issues already fetched above if len(issues) == 0 { fmt.Printf("No issues to rename. Updating prefix to %s\n", newPrefix) if !dryRun { if err := store.SetConfig(ctx, "issue_prefix", newPrefix); err != nil { - FatalError("failed to update prefix: %v", err) + return HandleError("failed to update prefix: %v", err) } commandDidWrite.Store(true) } - return + return nil } if dryRun { @@ -144,15 +146,17 @@ NOTE: This is a rare operation. Most users never need this command.`, newID := fmt.Sprintf("%s-%s", newPrefix, strings.TrimPrefix(issue.ID, oldPrefix+"-")) fmt.Printf(" %s -> %s\n", ui.RenderAccent(oldID), ui.RenderAccent(newID)) } - return + return nil } fmt.Printf("Renaming %d issues from prefix '%s' to '%s'...\n", len(issues), oldPrefix, newPrefix) if err := renamePrefixInDB(ctx, oldPrefix, newPrefix, issues); err != nil { - FatalError("failed to rename prefix: %v", err) + return HandleError("failed to rename prefix: %v", err) } + commandDidWrite.Store(true) + fmt.Printf("%s Successfully renamed prefix from %s to %s\n", ui.RenderPass("āœ“"), ui.RenderAccent(oldPrefix), ui.RenderAccent(newPrefix)) if jsonOutput { @@ -163,10 +167,12 @@ NOTE: This is a rare operation. Most users never need this command.`, } enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") - _ = enc.Encode(result) // Best effort: JSON encoding of simple struct does not fail in practice + if eerr := enc.Encode(result); eerr != nil { + return eerr + } } - commandDidWrite.Store(true) + return nil }, } diff --git a/cmd/bd/reopen.go b/cmd/bd/reopen.go index 819fcd28a..f7baec7c4 100644 --- a/cmd/bd/reopen.go +++ b/cmd/bd/reopen.go @@ -5,6 +5,7 @@ import ( "os" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -16,13 +17,22 @@ var reopenCmd = &cobra.Command{ Short: "Reopen one or more closed issues", Long: `Reopen closed issues by setting status to 'open' and clearing the closed_at timestamp. This is more explicit than 'bd update --status open' and emits a Reopened event.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.MinimumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("reopen") + evt := metrics.NewCommandEvent("reopen") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runReopenProxiedServer(cmd, rootCtx, args) - return + return nil } reason, _ := cmd.Flags().GetString("reason") @@ -33,8 +43,7 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. mutatedStores := map[storage.DoltStorage][]string{} pendingCloseResults := []*RoutedResult{} if store == nil { - FatalErrorWithHint("database not initialized", - diagHint()) + return HandleErrorWithHint("database not initialized", diagHint()) } for _, id := range args { // Resolve with prefix routing (supports cross-rig reopens like `bd reopen xe-5ls`) @@ -48,7 +57,6 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. issueStore := result.Store issue := result.Issue - // Skip if already open — avoid false "Reopened" message if issue.Status == types.StatusOpen { fmt.Fprintf(os.Stderr, "%s is already open\n", fullID) result.Close() @@ -84,7 +92,7 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. for _, result := range pendingCloseResults { result.Close() } - FatalErrorRespectJSON("failed to commit: %v", err) + return HandleErrorRespectJSON("failed to commit: %v", err) } } for _, result := range pendingCloseResults { @@ -92,12 +100,15 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. } if jsonOutput && len(reopenedIssues) > 0 { - outputJSON(reopenedIssues) + if jerr := outputJSON(reopenedIssues); jerr != nil { + return jerr + } } if hasError { - os.Exit(1) + return SilentExit() } + return nil }, } diff --git a/cmd/bd/repo.go b/cmd/bd/repo.go index 6b2d41568..a25aafd0e 100644 --- a/cmd/bd/repo.go +++ b/cmd/bd/repo.go @@ -9,6 +9,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/remotecache" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" @@ -49,15 +50,22 @@ Paths can be absolute or relative (they are stored as-is). This modifies .beads/config.yaml, which is version-controlled and shared across all clones of this repository.`, - Args: cobra.ExactArgs(1), + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("repo-add") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + repoPath := args[0] if remotecache.IsRemoteURL(repoPath) { - // Remote URL: skip local .beads directory validation fmt.Fprintf(os.Stderr, "Adding remote repository: %s\n", repoPath) } else { - // Local path: validate .beads directory exists expandedPath := repoPath if len(repoPath) > 0 && repoPath[0] == '~' { home, err := os.UserHomeDir() @@ -68,19 +76,17 @@ shared across all clones of this repository.`, beadsDir := filepath.Join(expandedPath, ".beads") if _, err := os.Stat(beadsDir); os.IsNotExist(err) { - return fmt.Errorf("no beads workspace found at %s", expandedPath) + return HandleError("no beads workspace found at %s", expandedPath) } } - // Find config.yaml configPath, err := config.FindConfigYAMLPath() if err != nil { - return fmt.Errorf("failed to find config.yaml: %w", err) + return HandleError("failed to find config.yaml: %v", err) } - // Add the repo (use original path to preserve ~ etc.) if err := config.AddRepo(configPath, repoPath); err != nil { - return fmt.Errorf("failed to add repository: %w", err) + return HandleError("failed to add repository: %v", err) } if jsonOutput { @@ -107,39 +113,41 @@ you must remove "~/foo", not "/home/user/foo"). This command also removes any previously-hydrated issues from the database that came from the removed repository.`, - Args: cobra.ExactArgs(1), + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("repo-remove") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + repoPath := args[0] - // Ensure we have direct database access for cleanup if err := ensureDirectMode("repo remove requires direct database access"); err != nil { - return err + return HandleError("%v", err) } ctx := rootCtx - // Delete issues from the removed repo before removing from config - // The source_repo field uses the original path (e.g., "~/foo") deletedCount, err := store.DeleteIssuesBySourceRepo(ctx, repoPath) if err != nil { - return fmt.Errorf("failed to delete issues from repo: %w", err) + return HandleError("failed to delete issues from repo: %v", err) } - // Also clear the mtime cache entry if err := store.ClearRepoMtime(ctx, repoPath); err != nil { - // Non-fatal: just log a warning fmt.Fprintf(os.Stderr, "Warning: failed to clear mtime cache: %v\n", err) } - // Find config.yaml configPath, err := config.FindConfigYAMLPath() if err != nil { - return fmt.Errorf("failed to find config.yaml: %w", err) + return HandleError("failed to find config.yaml: %v", err) } - // Remove the repo from config if err := config.RemoveRepo(configPath, repoPath); err != nil { - return fmt.Errorf("failed to remove repository: %w", err) + return HandleError("failed to remove repository: %v", err) } // Evict remote cache if applicable @@ -175,17 +183,24 @@ var repoListCmd = &cobra.Command{ Shows the primary repository (always ".") and any additional repositories configured for hydration.`, + SilenceUsage: true, + SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - // Find config.yaml + evt := metrics.NewCommandEvent("repo-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + configPath, err := config.FindConfigYAMLPath() if err != nil { - return fmt.Errorf("failed to find config.yaml: %w", err) + return HandleError("failed to find config.yaml: %v", err) } - // Get repos from YAML repos, err := config.ListRepos(configPath) if err != nil { - return fmt.Errorf("failed to load config: %w", err) + return HandleError("failed to load config: %v", err) } if jsonOutput { @@ -227,23 +242,31 @@ the primary database with their original prefixes and source_repo set. Uses mtime caching to skip repos whose JSONL hasn't changed. Also triggers Dolt push/pull if a remote is configured.`, + SilenceUsage: true, + SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("repo-sync") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("repo sync requires direct database access"); err != nil { - return err + return HandleError("%v", err) } ctx := rootCtx verbose, _ := cmd.Flags().GetBool("verbose") - // Find config.yaml and get additional repos configPath, err := config.FindConfigYAMLPath() if err != nil { - return fmt.Errorf("failed to find config.yaml: %w", err) + return HandleError("failed to find config.yaml: %v", err) } repos, err := config.ListRepos(configPath) if err != nil { - return fmt.Errorf("failed to load repo config: %w", err) + return HandleError("failed to load repo config: %v", err) } totalImported := 0 diff --git a/cmd/bd/reset.go b/cmd/bd/reset.go index 021349b7c..adf92da39 100644 --- a/cmd/bd/reset.go +++ b/cmd/bd/reset.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -29,7 +30,9 @@ Use --force to actually perform the reset. Examples: bd reset # Show what would be deleted bd reset --force # Actually delete everything`, - Run: runReset, + SilenceUsage: true, + SilenceErrors: true, + RunE: runReset, } func init() { @@ -37,53 +40,54 @@ func init() { // Note: resetCmd is added to adminCmd in admin.go } -func runReset(cmd *cobra.Command, args []string) { +func runReset(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("admin-reset") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := requireServerMode("reset"); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } CheckReadonly("reset") force, _ := cmd.Flags().GetBool("force") - // Get common git directory (for hooks and beads-worktrees, which are shared across worktrees) gitCommonDir, err := git.GetGitCommonDir() if err != nil { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "not a git repository", - }) - } else { - fmt.Fprintf(os.Stderr, "Error: not a git repository\n") + }); jerr != nil { + return jerr + } + return SilentExit() } - os.Exit(1) + return HandleError("not a git repository") } - // Resolve .beads directory (worktree-aware) beadsDir := beads.FindBeadsDir() if beadsDir == "" { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "message": "beads not initialized", "reset": false, }) - } else { - fmt.Println("Beads is not initialized in this repository.") - fmt.Println("Nothing to reset.") } - return + fmt.Println("Beads is not initialized in this repository.") + fmt.Println("Nothing to reset.") + return nil } - // Collect what would be deleted items := collectResetItems(gitCommonDir, beadsDir) if !force { - // Dry-run mode: show what would be deleted - showResetPreview(items) - return + return showResetPreview(items) } - // Actually perform the reset - performReset(items, gitCommonDir, beadsDir) + return performReset(items, gitCommonDir, beadsDir) } type resetItem struct { @@ -152,13 +156,12 @@ func isBdHook(hookPath string) bool { return false } -func showResetPreview(items []resetItem) { +func showResetPreview(items []resetItem) error { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "dry_run": true, "items": items, }) - return } fmt.Println(ui.RenderWarn("Reset preview (dry-run mode)")) @@ -177,9 +180,10 @@ func showResetPreview(items []resetItem) { fmt.Println(ui.RenderFail("⚠ This operation cannot be undone!")) fmt.Println() fmt.Printf("To proceed, run: %s\n", ui.RenderWarn("bd reset --force")) + return nil } -func performReset(items []resetItem, _, _ string) { +func performReset(items []resetItem, _, _ string) error { var errors []string @@ -223,8 +227,7 @@ func performReset(items []resetItem, _, _ string) { if len(errors) > 0 { result["errors"] = errors } - outputJSON(result) - return + return outputJSON(result) } fmt.Println() @@ -238,4 +241,5 @@ func performReset(items []resetItem, _, _ string) { fmt.Println() fmt.Println("To reinitialize beads, run: bd init") } + return nil } diff --git a/cmd/bd/rules.go b/cmd/bd/rules.go index ef7ff7762..1f303f13b 100644 --- a/cmd/bd/rules.go +++ b/cmd/bd/rules.go @@ -11,6 +11,8 @@ import ( "unicode" "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/metrics" ) // --- Types --- @@ -633,15 +635,19 @@ var rulesCmd = &cobra.Command{ } var rulesAuditCmd = &cobra.Command{ - Use: "audit", - Short: "Scan rules for contradictions and merge opportunities", - Run: runRulesAudit, + Use: "audit", + Short: "Scan rules for contradictions and merge opportunities", + SilenceUsage: true, + SilenceErrors: true, + RunE: runRulesAudit, } var rulesCompactCmd = &cobra.Command{ - Use: "compact", - Short: "Merge related rules into composites", - Run: runRulesCompact, + Use: "compact", + Short: "Merge related rules into composites", + SilenceUsage: true, + SilenceErrors: true, + RunE: runRulesCompact, } func init() { @@ -661,21 +667,26 @@ func init() { rootCmd.AddCommand(rulesCmd) } -func runRulesAudit(cmd *cobra.Command, args []string) { +func runRulesAudit(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("rules-audit") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + rulesPath, _ := cmd.Flags().GetString("path") threshold, _ := cmd.Flags().GetFloat64("threshold") result, err := RunAudit(rulesPath, threshold) if err != nil { - FatalErrorRespectJSON("rules audit failed: %v", err) + return HandleErrorRespectJSON("rules audit failed: %v", err) } if jsonOutput { - outputJSON(result) - return + return outputJSON(result) } - // Human-readable output fmt.Printf("Rules Audit — %s\n", rulesPath) fmt.Println(strings.Repeat("=", 60)) fmt.Println() @@ -723,34 +734,40 @@ func runRulesAudit(cmd *cobra.Command, args []string) { } fmt.Printf("Run `bd rules compact --auto` to apply suggested merges.\n") } + return nil } -func runRulesCompact(cmd *cobra.Command, args []string) { +func runRulesCompact(cmd *cobra.Command, args []string) error { CheckReadonly("rules compact") + evt := metrics.NewCommandEvent("rules-compact") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + rulesPath, _ := cmd.Flags().GetString("path") groupNames, _ := cmd.Flags().GetStringSlice("group") autoMode, _ := cmd.Flags().GetBool("auto") dryRun, _ := cmd.Flags().GetBool("dry-run") if !autoMode && len(groupNames) == 0 { - FatalErrorRespectJSON("specify --group or --auto") + return HandleErrorRespectJSON("specify --group or --auto") } if autoMode { - // Run audit to get merge candidates result, err := RunAudit(rulesPath, 0.6) if err != nil { - FatalErrorRespectJSON("audit for auto-compact failed: %v", err) + return HandleErrorRespectJSON("audit for auto-compact failed: %v", err) } if len(result.MergeCandidates) == 0 { if jsonOutput { - outputJSON(map[string]string{"status": "no merge candidates found"}) - } else { - fmt.Println("No merge candidates found.") + return outputJSON(map[string]string{"status": "no merge candidates found"}) } - return + fmt.Println("No merge candidates found.") + return nil } type compactResult struct { @@ -817,12 +834,11 @@ func runRulesCompact(cmd *cobra.Command, args []string) { } if jsonOutput { - outputJSON(results) + return outputJSON(results) } - return + return nil } - // Manual --group mode var groupRules []RuleFile for _, name := range groupNames { if !strings.HasSuffix(name, ".md") { @@ -831,29 +847,28 @@ func runRulesCompact(cmd *cobra.Command, args []string) { path := filepath.Join(rulesPath, name) rf, err := ParseRuleFile(path) if err != nil { - FatalErrorRespectJSON("cannot read rule %s: %v", name, err) + return HandleErrorRespectJSON("cannot read rule %s: %v", name, err) } groupRules = append(groupRules, rf) } if len(groupRules) < 2 { - FatalErrorRespectJSON("need at least 2 rules to merge") + return HandleErrorRespectJSON("need at least 2 rules to merge") } label := findGroupLabel(groupRules, makeRange(len(groupRules))) merged, err := CompactRules(groupRules, label) if err != nil { - FatalErrorRespectJSON("compact failed: %v", err) + return HandleErrorRespectJSON("compact failed: %v", err) } if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "group": label, "output": merged, "rules": len(groupRules), "dry_run": dryRun, }) - return } outName := strings.ReplaceAll(label, " ", "-") + ".md" @@ -869,13 +884,14 @@ func runRulesCompact(cmd *cobra.Command, args []string) { if !dryRun { outPath := filepath.Join(rulesPath, outName) if err := os.WriteFile(outPath, []byte(merged), 0o600); err != nil { - FatalErrorRespectJSON("write merged file: %v", err) + return HandleErrorRespectJSON("write merged file: %v", err) } for _, rf := range groupRules { _ = os.Remove(rf.Path) } fmt.Printf("\nCreated %s, deleted %d source files.\n", outName, len(groupRules)) } + return nil } // titleCase capitalizes the first letter of each word. diff --git a/cmd/bd/schema_skew_test.go b/cmd/bd/schema_skew_test.go index b9495574e..2a3826838 100644 --- a/cmd/bd/schema_skew_test.go +++ b/cmd/bd/schema_skew_test.go @@ -101,10 +101,12 @@ func TestIgnoreSchemaSkewFlagPropagatesEnvVar(t *testing.T) { ignoreSchemaSkew = true t.Cleanup(func() { ignoreSchemaSkew = old }) - if rootCmd.PersistentPreRun == nil { - t.Fatal("rootCmd.PersistentPreRun must be set") + if rootCmd.PersistentPreRunE == nil { + t.Fatal("rootCmd.PersistentPreRunE must be set") + } + if err := rootCmd.PersistentPreRunE(versionCmd, nil); err != nil { + t.Fatalf("PersistentPreRunE: %v", err) } - rootCmd.PersistentPreRun(versionCmd, nil) if got := os.Getenv("BD_IGNORE_SCHEMA_SKEW"); got != "1" { t.Errorf("BD_IGNORE_SCHEMA_SKEW = %q after PersistentPreRun with --ignore-schema-skew; want 1", got) diff --git a/cmd/bd/search.go b/cmd/bd/search.go index 477976b30..170ce5955 100644 --- a/cmd/bd/search.go +++ b/cmd/bd/search.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/utils" @@ -35,8 +36,16 @@ Examples: bd search "task" --sort created --reverse bd search "api" --desc-contains "endpoint" bd search "cleanup" --no-assignee --no-labels`, - Run: func(cmd *cobra.Command, args []string) { - // Get query from args or --query flag + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("search") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + queryFlag, _ := cmd.Flags().GetString("query") var query string if len(args) > 0 { @@ -45,12 +54,11 @@ Examples: query = queryFlag } - // If no query provided, show help if query == "" { if err := cmd.Help(); err != nil { fmt.Fprintf(os.Stderr, "Error displaying help: %v\n", err) } - FatalError("search query is required") + return HandleError("search query is required") } // Get filter flags @@ -149,75 +157,71 @@ Examples: if createdAfter != "" { t, err := parseTimeFlag(createdAfter) if err != nil { - FatalError("parsing --created-after: %v", err) + return HandleError("parsing --created-after: %v", err) } filter.CreatedAfter = &t } if createdBefore != "" { t, err := parseTimeFlag(createdBefore) if err != nil { - FatalError("parsing --created-before: %v", err) + return HandleError("parsing --created-before: %v", err) } filter.CreatedBefore = &t } if updatedAfter != "" { t, err := parseTimeFlag(updatedAfter) if err != nil { - FatalError("parsing --updated-after: %v", err) + return HandleError("parsing --updated-after: %v", err) } filter.UpdatedAfter = &t } if updatedBefore != "" { t, err := parseTimeFlag(updatedBefore) if err != nil { - FatalError("parsing --updated-before: %v", err) + return HandleError("parsing --updated-before: %v", err) } filter.UpdatedBefore = &t } if closedAfter != "" { t, err := parseTimeFlag(closedAfter) if err != nil { - FatalError("parsing --closed-after: %v", err) + return HandleError("parsing --closed-after: %v", err) } filter.ClosedAfter = &t } if closedBefore != "" { t, err := parseTimeFlag(closedBefore) if err != nil { - FatalError("parsing --closed-before: %v", err) + return HandleError("parsing --closed-before: %v", err) } filter.ClosedBefore = &t } - // Priority ranges if cmd.Flags().Changed("priority-min") { priorityMin, err := validation.ValidatePriority(priorityMinStr) if err != nil { - FatalError("parsing --priority-min: %v", err) + return HandleError("parsing --priority-min: %v", err) } filter.PriorityMin = &priorityMin } if cmd.Flags().Changed("priority-max") { priorityMax, err := validation.ValidatePriority(priorityMaxStr) if err != nil { - FatalError("parsing --priority-max: %v", err) + return HandleError("parsing --priority-max: %v", err) } filter.PriorityMax = &priorityMax } - // Metadata filters (GH#1406) metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field") if len(metadataFieldFlags) > 0 { filter.MetadataFields = make(map[string]string, len(metadataFieldFlags)) for _, mf := range metadataFieldFlags { k, v, ok := strings.Cut(mf, "=") if !ok || k == "" { - fmt.Fprintf(os.Stderr, "Error: invalid --metadata-field: expected key=value, got %q\n", mf) - os.Exit(1) + return HandleError("invalid --metadata-field: expected key=value, got %q", mf) } if err := storage.ValidateMetadataKey(k); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid --metadata-field key: %v\n", err) - os.Exit(1) + return HandleError("invalid --metadata-field key: %v", err) } filter.MetadataFields[k] = v } @@ -225,19 +229,16 @@ Examples: hasMetadataKey, _ := cmd.Flags().GetString("has-metadata-key") if hasMetadataKey != "" { if err := storage.ValidateMetadataKey(hasMetadataKey); err != nil { - fmt.Fprintf(os.Stderr, "Error: invalid --has-metadata-key: %v\n", err) - os.Exit(1) + return HandleError("invalid --has-metadata-key: %v", err) } filter.HasMetadataKey = hasMetadataKey } ctx := rootCtx - // Direct mode - search using store - // The query parameter in SearchIssues already searches across title, description, and id issues, err := store.SearchIssues(ctx, query, filter) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } // Apply sorting @@ -284,8 +285,7 @@ Examples: CommentCount: commentCounts[issue.ID], } } - outputJSON(issuesWithCounts) - return + return outputJSON(issuesWithCounts) } // Load labels for display @@ -299,6 +299,7 @@ Examples: } outputSearchResults(issues, query, longFormat) + return nil }, } diff --git a/cmd/bd/send_metrics.go b/cmd/bd/send_metrics.go new file mode 100644 index 000000000..68de66276 --- /dev/null +++ b/cmd/bd/send_metrics.go @@ -0,0 +1,22 @@ +package main + +import ( + "os" + + "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" +) + +var sendMetricsCmd = &cobra.Command{ + Use: metrics.SendMetricsSubcommand, + Short: "Internal: flush queued telemetry events (spawned by bd)", + Hidden: true, + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, args []string) { + os.Exit(metrics.RunSendMetrics()) + }, +} + +func init() { + rootCmd.AddCommand(sendMetricsCmd) +} diff --git a/cmd/bd/setup.go b/cmd/bd/setup.go index c35939424..cb65cfe76 100644 --- a/cmd/bd/setup.go +++ b/cmd/bd/setup.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/cmd/bd/setup" "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/recipes" ) @@ -49,51 +50,54 @@ Examples: Use 'bd setup --check' to verify installation status. Use 'bd setup --remove' to uninstall.`, - Args: cobra.MaximumNArgs(1), - Run: runSetup, + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runSetup, } -func runSetup(cmd *cobra.Command, args []string) { - // Handle --list flag +func runSetup(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("setup") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if setupList { - listRecipes() - return + return listRecipes() } - // Handle --print flag (no recipe needed) if setupPrint { fmt.Print(recipes.Template) - return + return nil } - // Handle -o flag (write to arbitrary path) if setupOutput != "" { if err := writeToPath(setupOutput); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } fmt.Printf("āœ“ Wrote template to %s\n", setupOutput) - return + return nil } - // Handle --add flag (save custom recipe) if setupAdd != "" { if len(args) != 1 { - FatalErrorWithHint("--add requires a path argument", "Usage: bd setup --add ") + return HandleErrorWithHint("--add requires a path argument", "Usage: bd setup --add ") } if err := addRecipe(setupAdd, args[0]); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - return + return nil } - // Require a recipe name for install/check/remove if len(args) == 0 { _ = cmd.Help() - return + return nil } recipeName := strings.ToLower(args[0]) - runRecipe(recipeName) + return runRecipe(recipeName) } func setupWorkspaceError() error { @@ -136,13 +140,12 @@ func lookupSetupRecipe(name string) (*recipes.Recipe, error) { return recipes.GetRecipe(name, beadsDir) } -func listRecipes() { +func listRecipes() error { allRecipes, usingWorkspaceRecipes, err := loadSetupRecipes() if err != nil { - FatalError("loading recipes: %v", err) + return HandleError("loading recipes: %v", err) } - // Sort recipe names names := make([]string, 0, len(allRecipes)) for name := range allRecipes { names = append(names, name) @@ -167,6 +170,7 @@ func listRecipes() { } fmt.Println("Use 'bd setup ' to install.") fmt.Println("Use 'bd setup --add ' to add a custom recipe.") + return nil } func writeToPath(path string) error { @@ -201,46 +205,35 @@ func addRecipe(name, path string) error { return nil } -func runRecipe(name string) { - // Check for legacy recipes that need special handling +func runRecipe(name string) error { switch name { case "claude": - runClaudeRecipe() - return + return runClaudeRecipe() case "gemini": - runGeminiRecipe() - return + return runGeminiRecipe() case "factory": - runFactoryRecipe() - return + return runFactoryRecipe() case "codex": - runCodexRecipe() - return + return runCodexRecipe() case "mux": - runMuxRecipe() - return + return runMuxRecipe() case "opencode": - runOpenCodeRecipe() - return + return runOpenCodeRecipe() case "aider": - runAiderRecipe() - return + return runAiderRecipe() case "cursor": - runCursorRecipe() - return + return runCursorRecipe() case "junie": - runJunieRecipe() - return + return runJunieRecipe() } - // For all other recipes (built-in or user), use generic file-based install recipe, err := lookupSetupRecipe(name) if err != nil { - FatalErrorWithHint(fmt.Sprintf("%v", err), "Use 'bd setup --list' to see available recipes.") + return HandleErrorWithHint(fmt.Sprintf("%v", err), "Use 'bd setup --list' to see available recipes.") } if recipe.Type != recipes.TypeFile && recipe.Type != recipes.TypeMultiFile { - FatalError("recipe '%s' has type '%s' which requires special handling", name, recipe.Type) + return HandleError("recipe '%s' has type '%s' which requires special handling", name, recipe.Type) } paths := recipe.Paths @@ -248,7 +241,6 @@ func runRecipe(name string) { paths = []string{recipe.Path} } - // Handle --check if setupCheck { var missing []string for _, path := range paths { @@ -262,16 +254,15 @@ func runRecipe(name string) { for _, path := range missing { fmt.Printf(" Missing: %s\n", path) } - os.Exit(1) + return SilentExit() } fmt.Printf("āœ“ %s integration installed\n", recipe.Name) for _, path := range paths { fmt.Printf(" File: %s\n", path) } - return + return nil } - // Handle --remove if setupRemove { removed := false for _, path := range paths { @@ -279,39 +270,35 @@ func runRecipe(name string) { if os.IsNotExist(err) { continue } - FatalError("%v", err) + return HandleError("%v", err) } removed = true - // Best-effort cleanup for recipe-created parent directories. This only - // succeeds when the directory became empty after removing this file. _ = os.Remove(filepath.Dir(path)) } if !removed { fmt.Println("No integration files found") - return + return nil } fmt.Printf("āœ“ Removed %s integration\n", recipe.Name) - return + return nil } - // Install fmt.Printf("Installing %s integration...\n", recipe.Name) for _, path := range paths { - // Ensure parent directory exists dir := filepath.Dir(path) if dir != "." && dir != "" { if err := os.MkdirAll(dir, 0o755); err != nil { - FatalError("create directory: %v", err) + return HandleError("create directory: %v", err) } } content, err := recipes.ContentForPath(*recipe, path) if err != nil { - FatalError("%v", err) + return HandleError("%v", err) } if err := os.WriteFile(path, []byte(content), 0o644); err != nil { // #nosec G306 -- config files need to be readable - FatalError("write file: %v", err) + return HandleError("write file: %v", err) } } @@ -319,116 +306,113 @@ func runRecipe(name string) { for _, path := range paths { fmt.Printf(" File: %s\n", path) } + return nil } -// Legacy recipe handlers that delegate to existing implementations - -func runCursorRecipe() { - if setupCheck { - setup.CheckCursor() - return +func translateSetupError(err error) error { + if err == nil { + return nil } - if setupRemove { - setup.RemoveCursor() - return - } - setup.InstallCursor() + return SilentExit() } -func runClaudeRecipe() { - if setupCheck { - setup.CheckClaude() - return +func runCursorRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckCursor()) + case setupRemove: + return translateSetupError(setup.RemoveCursor()) + default: + return translateSetupError(setup.InstallCursor()) } - if setupRemove { - setup.RemoveClaude(setupGlobal) - return - } - setup.InstallClaude(setupGlobal, setupStealth) } -func runGeminiRecipe() { - if setupCheck { - setup.CheckGemini() - return +func runClaudeRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckClaude()) + case setupRemove: + return translateSetupError(setup.RemoveClaude(setupGlobal)) + default: + return translateSetupError(setup.InstallClaude(setupGlobal, setupStealth)) } - if setupRemove { - setup.RemoveGemini(setupProject) - return - } - setup.InstallGemini(setupProject, setupStealth) } -func runFactoryRecipe() { - if setupCheck { - setup.CheckFactory() - return +func runGeminiRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckGemini()) + case setupRemove: + return translateSetupError(setup.RemoveGemini(setupProject)) + default: + return translateSetupError(setup.InstallGemini(setupProject, setupStealth)) } - if setupRemove { - setup.RemoveFactory() - return - } - setup.InstallFactory() } -func runCodexRecipe() { - if setupCheck { - setup.CheckCodex(setupGlobal) - return +func runFactoryRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckFactory()) + case setupRemove: + return translateSetupError(setup.RemoveFactory()) + default: + return translateSetupError(setup.InstallFactory()) } - if setupRemove { - setup.RemoveCodex(setupGlobal) - return - } - setup.InstallCodex(setupGlobal) } -func runOpenCodeRecipe() { - if setupCheck { - setup.CheckOpenCode() - return +func runCodexRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckCodex(setupGlobal)) + case setupRemove: + return translateSetupError(setup.RemoveCodex(setupGlobal)) + default: + return translateSetupError(setup.InstallCodex(setupGlobal)) } - if setupRemove { - setup.RemoveOpenCode() - return - } - setup.InstallOpenCode() } -func runMuxRecipe() { - if setupCheck { - setup.CheckMux(setupProject, setupGlobal) - return +func runOpenCodeRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckOpenCode()) + case setupRemove: + return translateSetupError(setup.RemoveOpenCode()) + default: + return translateSetupError(setup.InstallOpenCode()) } - if setupRemove { - setup.RemoveMux(setupProject, setupGlobal) - return - } - setup.InstallMux(setupProject, setupGlobal) } -func runAiderRecipe() { - if setupCheck { - setup.CheckAider() - return +func runMuxRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckMux(setupProject, setupGlobal)) + case setupRemove: + return translateSetupError(setup.RemoveMux(setupProject, setupGlobal)) + default: + return translateSetupError(setup.InstallMux(setupProject, setupGlobal)) } - if setupRemove { - setup.RemoveAider() - return - } - setup.InstallAider() } -func runJunieRecipe() { - if setupCheck { - setup.CheckJunie() - return +func runAiderRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckAider()) + case setupRemove: + return translateSetupError(setup.RemoveAider()) + default: + return translateSetupError(setup.InstallAider()) } - if setupRemove { - setup.RemoveJunie() - return +} + +func runJunieRecipe() error { + switch { + case setupCheck: + return translateSetupError(setup.CheckJunie()) + case setupRemove: + return translateSetupError(setup.RemoveJunie()) + default: + return translateSetupError(setup.InstallJunie()) } - setup.InstallJunie() } func init() { diff --git a/cmd/bd/setup/aider.go b/cmd/bd/setup/aider.go index fba353472..ecbd6c8d2 100644 --- a/cmd/bd/setup/aider.go +++ b/cmd/bd/setup/aider.go @@ -148,32 +148,27 @@ The AI will suggest the appropriate ` + "`bd`" + ` command, which you run via ` - See ` + "`QUICKSTART.md`" + ` for human-oriented guide ` -// InstallAider installs Aider integration -func InstallAider() { +func InstallAider() error { configPath := ".aider.conf.yml" instructionsPath := ".aider/BEADS.md" readmePath := ".aider/README.md" fmt.Println("Installing Aider integration...") - // Ensure .aider directory exists if err := EnsureDir(".aider", 0755); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - // Write config file if err := atomicWriteFile(configPath, []byte(aiderConfigTemplate)); err != nil { - FatalError("write config: %v", err) + return HandleError("write config: %v", err) } - // Write instructions file (loaded by AI) if err := atomicWriteFile(instructionsPath, []byte(aiderBeadsInstructions)); err != nil { - FatalError("write instructions: %v", err) + return HandleError("write instructions: %v", err) } - // Write README (for humans) if err := atomicWriteFile(readmePath, []byte(aiderReadmeTemplate)); err != nil { - FatalError("write README: %v", err) + return HandleError("write README: %v", err) } fmt.Printf("\nāœ“ Aider integration installed\n") @@ -185,21 +180,21 @@ func InstallAider() { fmt.Println(" 2. Ask AI for available work (it will suggest: /run bd ready)") fmt.Println(" 3. Run suggested commands using /run") fmt.Println("\nNote: Aider requires you to explicitly run commands via /run") + return nil } -// CheckAider checks if Aider integration is installed -func CheckAider() { +func CheckAider() error { configPath := ".aider.conf.yml" if !FileExists(configPath) { - FatalErrorWithHint("Aider integration not installed", "Run: bd setup aider") + return HandleErrorWithHint("Aider integration not installed", "Run: bd setup aider") } fmt.Println("āœ“ Aider integration installed:", configPath) + return nil } -// RemoveAider removes Aider integration -func RemoveAider() { +func RemoveAider() error { configPath := ".aider.conf.yml" instructionsPath := ".aider/BEADS.md" readmePath := ".aider/README.md" @@ -209,40 +204,37 @@ func RemoveAider() { removed := false - // Remove config if err := os.Remove(configPath); err != nil { if !os.IsNotExist(err) { - FatalError("failed to remove config: %v", err) + return HandleError("failed to remove config: %v", err) } } else { removed = true } - // Remove instructions if err := os.Remove(instructionsPath); err != nil { if !os.IsNotExist(err) { - FatalError("failed to remove instructions: %v", err) + return HandleError("failed to remove instructions: %v", err) } } else { removed = true } - // Remove README if err := os.Remove(readmePath); err != nil { if !os.IsNotExist(err) { - FatalError("failed to remove README: %v", err) + return HandleError("failed to remove README: %v", err) } } else { removed = true } - // Try to remove .aider directory if empty _ = os.Remove(aiderDir) if !removed { fmt.Println("No Aider integration files found") - return + return nil } fmt.Println("āœ“ Removed Aider integration") + return nil } diff --git a/cmd/bd/setup/aider_test.go b/cmd/bd/setup/aider_test.go index 775c24198..b13c53cbc 100644 --- a/cmd/bd/setup/aider_test.go +++ b/cmd/bd/setup/aider_test.go @@ -330,8 +330,9 @@ func TestCheckAider_NotInstalled(t *testing.T) { } }() - // CheckAider calls os.Exit(1) when not installed - // We can't easily test that, but we document expected behavior + if err := CheckAider(); err == nil { + t.Fatal("CheckAider should return error when not installed") + } } func TestCheckAider_Installed(t *testing.T) { diff --git a/cmd/bd/setup/claude.go b/cmd/bd/setup/claude.go index 118f2e2b6..e25bafd8f 100644 --- a/cmd/bd/setup/claude.go +++ b/cmd/bd/setup/claude.go @@ -77,17 +77,12 @@ func claudeAgentsEnv(env claudeEnv) agentsEnv { } } -// InstallClaude installs Claude Code hooks -func InstallClaude(global bool, stealth bool) { +func InstallClaude(global bool, stealth bool) error { env, err := claudeEnvProvider() if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := installClaude(env, global, stealth); err != nil { - setupExit(1) + return HandleError("%v", err) } + return installClaude(env, global, stealth) } // InstallClaudeProject installs project-local Claude hooks, returning an error @@ -281,17 +276,12 @@ func warnIfClaudeHooksUseRemovedSync(env claudeEnv) { } } -// CheckClaude checks if Claude integration is installed -func CheckClaude() { +func CheckClaude() error { env, err := claudeEnvProvider() if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := checkClaude(env); err != nil { - setupExit(1) + return HandleError("%v", err) } + return checkClaude(env) } func checkClaude(env claudeEnv) error { @@ -321,17 +311,12 @@ func checkClaude(env claudeEnv) error { return checkAgents(claudeAgentsEnv(env), claudeAgentsIntegration) } -// RemoveClaude removes Claude Code hooks -func RemoveClaude(global bool) { +func RemoveClaude(global bool) error { env, err := claudeEnvProvider() if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := removeClaude(env, global); err != nil { - setupExit(1) + return HandleError("%v", err) } + return removeClaude(env, global) } func removeClaude(env claudeEnv, global bool) error { diff --git a/cmd/bd/setup/claude_test.go b/cmd/bd/setup/claude_test.go index d810268c2..0ddeac106 100644 --- a/cmd/bd/setup/claude_test.go +++ b/cmd/bd/setup/claude_test.go @@ -917,42 +917,33 @@ func TestRemoveClaudeScenarios(t *testing.T) { }) } -func TestClaudeWrappersExit(t *testing.T) { +func TestClaudeWrappersReturnError(t *testing.T) { t.Run("install provider error", func(t *testing.T) { - cap := stubSetupExit(t) stubClaudeEnvProvider(t, claudeEnv{}, errors.New("boom")) - InstallClaude(false, false) - if !cap.called || cap.code != 1 { - t.Fatal("InstallClaude should exit on provider error") + if err := InstallClaude(false, false); err == nil { + t.Fatal("InstallClaude should return error on provider error") } }) t.Run("install internal error", func(t *testing.T) { - cap := stubSetupExit(t) env, _, _ := newClaudeTestEnv(t) env.ensureDir = func(string, os.FileMode) error { return errors.New("boom") } stubClaudeEnvProvider(t, env, nil) - // global=false → project-local (default) - InstallClaude(false, false) - if !cap.called || cap.code != 1 { - t.Fatal("InstallClaude should exit when installClaude fails") + if err := InstallClaude(false, false); err == nil { + t.Fatal("InstallClaude should return error when installClaude fails") } }) t.Run("check missing hooks", func(t *testing.T) { - cap := stubSetupExit(t) env, _, _ := newClaudeTestEnv(t) stubClaudeEnvProvider(t, env, nil) - CheckClaude() - if !cap.called || cap.code != 1 { - t.Fatal("CheckClaude should exit when hooks missing") + if err := CheckClaude(); err == nil { + t.Fatal("CheckClaude should return error when hooks missing") } }) t.Run("remove parse error", func(t *testing.T) { - cap := stubSetupExit(t) env, _, _ := newClaudeTestEnv(t) - // Write invalid JSON to project settings path (default target) path := projectSettingsPath(env.projectDir) if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { t.Fatalf("mkdir: %v", err) @@ -961,10 +952,8 @@ func TestClaudeWrappersExit(t *testing.T) { t.Fatalf("write file: %v", err) } stubClaudeEnvProvider(t, env, nil) - // global=false → project-local (default) - RemoveClaude(false) - if !cap.called || cap.code != 1 { - t.Fatal("RemoveClaude should exit on parse error") + if err := RemoveClaude(false); err == nil { + t.Fatal("RemoveClaude should return error on parse error") } }) } diff --git a/cmd/bd/setup/codex.go b/cmd/bd/setup/codex.go index 5cd793d7a..ef576c505 100644 --- a/cmd/bd/setup/codex.go +++ b/cmd/bd/setup/codex.go @@ -69,17 +69,12 @@ func defaultCodexEnv() (codexEnv, error) { }, nil } -// InstallCodex installs Codex integration. -func InstallCodex(global bool) { +func InstallCodex(global bool) error { env, err := codexEnvProvider() if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := installCodex(env, global); err != nil { - setupExit(1) + return HandleError("%v", err) } + return installCodex(env, global) } // InstallCodexProject installs project-local Codex integration, returning an @@ -103,17 +98,12 @@ func installCodex(env codexEnv, global bool) error { return installCodexInstructions(env, global) } -// CheckCodex checks if Codex integration is installed. -func CheckCodex(global bool) { +func CheckCodex(global bool) error { env, err := codexEnvProvider() if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := checkCodex(env, global); err != nil { - setupExit(1) + return HandleError("%v", err) } + return checkCodex(env, global) } func checkCodex(env codexEnv, global bool) error { @@ -126,17 +116,12 @@ func checkCodex(env codexEnv, global bool) error { return checkCodexInstructions(env, global) } -// RemoveCodex removes Codex integration. -func RemoveCodex(global bool) { +func RemoveCodex(global bool) error { env, err := codexEnvProvider() if err != nil { - _, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := removeCodex(env, global); err != nil { - setupExit(1) + return HandleError("%v", err) } + return removeCodex(env, global) } func removeCodex(env codexEnv, global bool) error { diff --git a/cmd/bd/setup/cursor.go b/cmd/bd/setup/cursor.go index e582a48dc..394971ddd 100644 --- a/cmd/bd/setup/cursor.go +++ b/cmd/bd/setup/cursor.go @@ -50,40 +50,37 @@ For detailed docs: see AGENTS.md, QUICKSTART.md, or run ` + "`bd --help`" + ` # END BEADS INTEGRATION ` -// InstallCursor installs Cursor IDE integration -func InstallCursor() { +func InstallCursor() error { rulesPath := ".cursor/rules/beads.mdc" fmt.Println("Installing Cursor integration...") - // Ensure parent directory exists if err := EnsureDir(filepath.Dir(rulesPath), 0755); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - // Write beads rules file (overwrite if exists) if err := atomicWriteFile(rulesPath, []byte(cursorRulesTemplate)); err != nil { - FatalError("write rules: %v", err) + return HandleError("write rules: %v", err) } fmt.Printf("\nāœ“ Cursor integration installed\n") fmt.Printf(" Rules: %s\n", rulesPath) fmt.Println("\nRestart Cursor for changes to take effect.") + return nil } -// CheckCursor checks if Cursor integration is installed -func CheckCursor() { +func CheckCursor() error { rulesPath := ".cursor/rules/beads.mdc" if !FileExists(rulesPath) { - FatalErrorWithHint("Cursor integration not installed", "Run: bd setup cursor") + return HandleErrorWithHint("Cursor integration not installed", "Run: bd setup cursor") } fmt.Println("āœ“ Cursor integration installed:", rulesPath) + return nil } -// RemoveCursor removes Cursor integration -func RemoveCursor() { +func RemoveCursor() error { rulesPath := ".cursor/rules/beads.mdc" fmt.Println("Removing Cursor integration...") @@ -91,10 +88,11 @@ func RemoveCursor() { if err := os.Remove(rulesPath); err != nil { if os.IsNotExist(err) { fmt.Println("No rules file found") - return + return nil } - FatalError("failed to remove file: %v", err) + return HandleError("failed to remove file: %v", err) } fmt.Println("āœ“ Removed Cursor integration") + return nil } diff --git a/cmd/bd/setup/cursor_test.go b/cmd/bd/setup/cursor_test.go index 70c294f88..98c652246 100644 --- a/cmd/bd/setup/cursor_test.go +++ b/cmd/bd/setup/cursor_test.go @@ -239,8 +239,9 @@ func TestCheckCursor_NotInstalled(t *testing.T) { } }() - // CheckCursor calls os.Exit(1) when not installed - // We can't easily test that, but we document expected behavior + if err := CheckCursor(); err == nil { + t.Fatal("CheckCursor should return error when not installed") + } } func TestCheckCursor_Installed(t *testing.T) { diff --git a/cmd/bd/setup/exit.go b/cmd/bd/setup/exit.go index 9ae5a0e56..d6e0f0d28 100644 --- a/cmd/bd/setup/exit.go +++ b/cmd/bd/setup/exit.go @@ -1,24 +1,24 @@ package setup import ( + "errors" "fmt" "os" ) -// setupExit is used by setup commands to exit the process. Tests can stub this. -var setupExit = os.Exit +var ErrSilent = errors.New("setup: failure already reported") -// FatalError writes an error message to stderr and exits with code 1. -// This mirrors the main package's FatalError but uses the testable setupExit. -func FatalError(format string, args ...interface{}) { +func HandleError(format string, args ...interface{}) error { fmt.Fprintf(os.Stderr, "Error: "+format+"\n", args...) - setupExit(1) + return ErrSilent } -// FatalErrorWithHint writes an error message with a hint to stderr and exits. -// This mirrors the main package's FatalErrorWithHint but uses the testable setupExit. -func FatalErrorWithHint(message, hint string) { +func HandleErrorWithHint(message, hint string) error { fmt.Fprintf(os.Stderr, "Error: %s\n", message) fmt.Fprintf(os.Stderr, "Hint: %s\n", hint) - setupExit(1) + return ErrSilent +} + +func SilentExit() error { + return ErrSilent } diff --git a/cmd/bd/setup/factory.go b/cmd/bd/setup/factory.go index c84e2c75e..304133bbd 100644 --- a/cmd/bd/setup/factory.go +++ b/cmd/bd/setup/factory.go @@ -13,36 +13,24 @@ type factoryEnv = agentsEnv var factoryEnvProvider = defaultAgentsEnv -// InstallFactory installs Factory.ai/Droid integration. -func InstallFactory() { - env := factoryEnvProvider() - if err := installAgents(env, factoryIntegration); err != nil { - setupExit(1) - } +func InstallFactory() error { + return installAgents(factoryEnvProvider(), factoryIntegration) } func installFactory(env factoryEnv) error { return installAgents(env, factoryIntegration) } -// CheckFactory checks if Factory.ai integration is installed. -func CheckFactory() { - env := factoryEnvProvider() - if err := checkAgents(env, factoryIntegration); err != nil { - setupExit(1) - } +func CheckFactory() error { + return checkAgents(factoryEnvProvider(), factoryIntegration) } func checkFactory(env factoryEnv) error { return checkAgents(env, factoryIntegration) } -// RemoveFactory removes Factory.ai integration. -func RemoveFactory() { - env := factoryEnvProvider() - if err := removeAgents(env, factoryIntegration); err != nil { - setupExit(1) - } +func RemoveFactory() error { + return removeAgents(factoryEnvProvider(), factoryIntegration) } func removeFactory(env factoryEnv) error { diff --git a/cmd/bd/setup/factory_test.go b/cmd/bd/setup/factory_test.go index bbd8b383b..2af6c84b0 100644 --- a/cmd/bd/setup/factory_test.go +++ b/cmd/bd/setup/factory_test.go @@ -350,32 +350,27 @@ func TestRemoveFactoryScenarios(t *testing.T) { }) } -func TestWrapperExitsOnError(t *testing.T) { +func TestWrapperReturnsErrorOnFailure(t *testing.T) { t.Run("InstallFactory", func(t *testing.T) { - cap := stubSetupExit(t) env := factoryEnv{agentsPath: filepath.Join(t.TempDir(), "dir"), stdout: &bytes.Buffer{}, stderr: &bytes.Buffer{}} if err := os.Mkdir(env.agentsPath, 0o755); err != nil { t.Fatalf("failed to create directory: %v", err) } stubFactoryEnvProvider(t, env) - InstallFactory() - if !cap.called || cap.code != 1 { - t.Fatal("InstallFactory should exit on error") + if err := InstallFactory(); err == nil { + t.Fatal("InstallFactory should return error") } }) t.Run("CheckFactory", func(t *testing.T) { - cap := stubSetupExit(t) env := factoryEnv{agentsPath: filepath.Join(t.TempDir(), "missing"), stdout: &bytes.Buffer{}, stderr: &bytes.Buffer{}} stubFactoryEnvProvider(t, env) - CheckFactory() - if !cap.called || cap.code != 1 { - t.Fatal("CheckFactory should exit on error") + if err := CheckFactory(); err == nil { + t.Fatal("CheckFactory should return error") } }) t.Run("RemoveFactory", func(t *testing.T) { - cap := stubSetupExit(t) env := factoryEnv{agentsPath: filepath.Join(t.TempDir(), "AGENTS.md"), stdout: &bytes.Buffer{}, stderr: &bytes.Buffer{}} beadsSection := agents.EmbeddedBeadsSection() if err := os.WriteFile(env.agentsPath, []byte(beadsSection), 0644); err != nil { @@ -385,9 +380,8 @@ func TestWrapperExitsOnError(t *testing.T) { t.Fatalf("failed to chmod file: %v", err) } stubFactoryEnvProvider(t, env) - RemoveFactory() - if !cap.called || cap.code != 1 { - t.Fatal("RemoveFactory should exit on error") + if err := RemoveFactory(); err == nil { + t.Fatal("RemoveFactory should return error") } }) } diff --git a/cmd/bd/setup/gemini.go b/cmd/bd/setup/gemini.go index 7203f2fb5..d4442cfb7 100644 --- a/cmd/bd/setup/gemini.go +++ b/cmd/bd/setup/gemini.go @@ -73,17 +73,12 @@ func geminiAgentsEnv(env geminiEnv) agentsEnv { } } -// InstallGemini installs Gemini CLI hooks -func InstallGemini(project bool, stealth bool) { +func InstallGemini(project bool, stealth bool) error { env, err := geminiEnvProvider() if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := installGemini(env, project, stealth); err != nil { - setupExit(1) + return HandleError("%v", err) } + return installGemini(env, project, stealth) } func installGemini(env geminiEnv, project bool, stealth bool) error { @@ -172,17 +167,12 @@ func installGemini(env geminiEnv, project bool, stealth bool) error { return nil } -// CheckGemini checks if Gemini integration is installed -func CheckGemini() { +func CheckGemini() error { env, err := geminiEnvProvider() if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := checkGemini(env); err != nil { - setupExit(1) + return HandleError("%v", err) } + return checkGemini(env) } func checkGemini(env geminiEnv) error { @@ -213,17 +203,12 @@ func checkGemini(env geminiEnv) error { return checkAgents(geminiAgentsEnv(env), geminiAgentsIntegration) } -// RemoveGemini removes Gemini CLI hooks -func RemoveGemini(project bool) { +func RemoveGemini(project bool) error { env, err := geminiEnvProvider() if err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - setupExit(1) - return - } - if err := removeGemini(env, project); err != nil { - setupExit(1) + return HandleError("%v", err) } + return removeGemini(env, project) } func removeGemini(env geminiEnv, project bool) error { diff --git a/cmd/bd/setup/junie.go b/cmd/bd/setup/junie.go index e6eb1a4f9..aeb972a1e 100644 --- a/cmd/bd/setup/junie.go +++ b/cmd/bd/setup/junie.go @@ -107,37 +107,32 @@ func junieMCPConfig() map[string]interface{} { } } -// InstallJunie installs Junie integration -func InstallJunie() { +func InstallJunie() error { guidelinesPath := ".junie/guidelines.md" mcpPath := ".junie/mcp/mcp.json" fmt.Println("Installing Junie integration...") - // Ensure .junie directory exists if err := EnsureDir(".junie", 0755); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - // Ensure .junie/mcp directory exists if err := EnsureDir(".junie/mcp", 0755); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } - // Write guidelines file if err := atomicWriteFile(guidelinesPath, []byte(junieGuidelinesTemplate)); err != nil { - FatalError("write guidelines: %v", err) + return HandleError("write guidelines: %v", err) } - // Write MCP config file mcpConfig := junieMCPConfig() mcpData, err := json.MarshalIndent(mcpConfig, "", " ") if err != nil { - FatalError("marshal MCP config: %v", err) + return HandleError("marshal MCP config: %v", err) } if err := atomicWriteFile(mcpPath, mcpData); err != nil { - FatalError("write MCP config: %v", err) + return HandleError("write MCP config: %v", err) } fmt.Printf("\nāœ“ Junie integration installed\n") @@ -145,10 +140,10 @@ func InstallJunie() { fmt.Printf(" MCP Config: %s (MCP server configuration)\n", mcpPath) fmt.Println("\nJunie will automatically read these files on session start.") fmt.Println("The MCP server provides direct access to beads tools.") + return nil } -// CheckJunie checks if Junie integration is installed -func CheckJunie() { +func CheckJunie() error { guidelinesPath := ".junie/guidelines.md" mcpPath := ".junie/mcp/mcp.json" @@ -166,28 +161,27 @@ func CheckJunie() { fmt.Println("āœ“ Junie integration installed") fmt.Printf(" Guidelines: %s\n", guidelinesPath) fmt.Printf(" MCP Config: %s\n", mcpPath) - return + return nil } if guidelinesExists { fmt.Println("⚠ Partial Junie integration (guidelines only)") fmt.Printf(" Guidelines: %s\n", guidelinesPath) fmt.Println(" Missing: MCP config") - FatalErrorWithHint("partial Junie integration", "Run: bd setup junie (to complete installation)") + return HandleErrorWithHint("partial Junie integration", "Run: bd setup junie (to complete installation)") } if mcpExists { fmt.Println("⚠ Partial Junie integration (MCP only)") fmt.Printf(" MCP Config: %s\n", mcpPath) fmt.Println(" Missing: Guidelines") - FatalErrorWithHint("partial Junie integration", "Run: bd setup junie (to complete installation)") + return HandleErrorWithHint("partial Junie integration", "Run: bd setup junie (to complete installation)") } - FatalErrorWithHint("Junie integration not installed", "Run: bd setup junie") + return HandleErrorWithHint("Junie integration not installed", "Run: bd setup junie") } -// RemoveJunie removes Junie integration -func RemoveJunie() { +func RemoveJunie() error { guidelinesPath := ".junie/guidelines.md" mcpPath := ".junie/mcp/mcp.json" mcpDir := ".junie/mcp" @@ -197,34 +191,30 @@ func RemoveJunie() { removed := false - // Remove guidelines if err := os.Remove(guidelinesPath); err != nil { if !os.IsNotExist(err) { - FatalError("failed to remove guidelines: %v", err) + return HandleError("failed to remove guidelines: %v", err) } } else { removed = true } - // Remove MCP config if err := os.Remove(mcpPath); err != nil { if !os.IsNotExist(err) { - FatalError("failed to remove MCP config: %v", err) + return HandleError("failed to remove MCP config: %v", err) } } else { removed = true } - // Try to remove .junie/mcp directory if empty _ = os.Remove(mcpDir) - - // Try to remove .junie directory if empty _ = os.Remove(junieDir) if !removed { fmt.Println("No Junie integration files found") - return + return nil } fmt.Println("āœ“ Removed Junie integration") + return nil } diff --git a/cmd/bd/setup/junie_test.go b/cmd/bd/setup/junie_test.go index 601114635..15782a2dd 100644 --- a/cmd/bd/setup/junie_test.go +++ b/cmd/bd/setup/junie_test.go @@ -366,8 +366,9 @@ func TestCheckJunie_NotInstalled(t *testing.T) { } }() - // CheckJunie calls os.Exit(1) when not installed - // We can't easily test that, but we document expected behavior + if err := CheckJunie(); err == nil { + t.Fatal("CheckJunie should return error when not installed") + } } func TestCheckJunie_Installed(t *testing.T) { @@ -417,8 +418,9 @@ func TestCheckJunie_PartialInstall_GuidelinesOnly(t *testing.T) { t.Fatalf("failed to create guidelines file: %v", err) } - // CheckJunie calls os.Exit(1) for partial installation - // We can't easily test that, but we document expected behavior + if err := CheckJunie(); err == nil { + t.Fatal("CheckJunie should return error for partial installation") + } } func TestCheckJunie_PartialInstall_MCPOnly(t *testing.T) { @@ -447,8 +449,9 @@ func TestCheckJunie_PartialInstall_MCPOnly(t *testing.T) { t.Fatalf("failed to create MCP config file: %v", err) } - // CheckJunie calls os.Exit(1) for partial installation - // We can't easily test that, but we document expected behavior + if err := CheckJunie(); err == nil { + t.Fatal("CheckJunie should return error for partial installation") + } } func TestJunieFilePaths(t *testing.T) { diff --git a/cmd/bd/setup/mux.go b/cmd/bd/setup/mux.go index dfd068e90..6eb359ff0 100644 --- a/cmd/bd/setup/mux.go +++ b/cmd/bd/setup/mux.go @@ -204,11 +204,8 @@ func removeMuxProjectHooks(env agentsEnv) error { // InstallMux installs Mux integration. // When project=true, it also installs .mux/AGENTS.md. // When global=true, it also installs ~/.mux/AGENTS.md. -func InstallMux(project bool, global bool) { - env := muxEnvProvider() - if err := installMux(env, project, global); err != nil { - setupExit(1) - } +func InstallMux(project bool, global bool) error { + return installMux(muxEnvProvider(), project, global) } func installMux(env agentsEnv, project bool, global bool) error { @@ -270,11 +267,8 @@ func installMux(env agentsEnv, project bool, global bool) error { // CheckMux checks if Mux integration is installed. // When project=true, it also verifies .mux/AGENTS.md. // When global=true, it also verifies ~/.mux/AGENTS.md. -func CheckMux(project bool, global bool) { - env := muxEnvProvider() - if err := checkMux(env, project, global); err != nil { - setupExit(1) - } +func CheckMux(project bool, global bool) error { + return checkMux(muxEnvProvider(), project, global) } func checkMux(env agentsEnv, project bool, global bool) error { @@ -309,11 +303,8 @@ func checkMux(env agentsEnv, project bool, global bool) error { // RemoveMux removes Mux integration. // When project=true, it also removes section from .mux/AGENTS.md. // When global=true, it also removes section from ~/.mux/AGENTS.md. -func RemoveMux(project bool, global bool) { - env := muxEnvProvider() - if err := removeMux(env, project, global); err != nil { - setupExit(1) - } +func RemoveMux(project bool, global bool) error { + return removeMux(muxEnvProvider(), project, global) } func removeMux(env agentsEnv, project bool, global bool) error { diff --git a/cmd/bd/setup/opencode.go b/cmd/bd/setup/opencode.go index 324861e28..a728e07d6 100644 --- a/cmd/bd/setup/opencode.go +++ b/cmd/bd/setup/opencode.go @@ -11,36 +11,24 @@ var opencodeIntegration = agentsIntegration{ var opencodeEnvProvider = defaultAgentsEnv -// InstallOpenCode installs OpenCode integration. -func InstallOpenCode() { - env := opencodeEnvProvider() - if err := installOpenCode(env); err != nil { - setupExit(1) - } +func InstallOpenCode() error { + return installOpenCode(opencodeEnvProvider()) } func installOpenCode(env agentsEnv) error { return installAgents(env, opencodeIntegration) } -// CheckOpenCode checks if OpenCode integration is installed. -func CheckOpenCode() { - env := opencodeEnvProvider() - if err := checkOpenCode(env); err != nil { - setupExit(1) - } +func CheckOpenCode() error { + return checkOpenCode(opencodeEnvProvider()) } func checkOpenCode(env agentsEnv) error { return checkAgents(env, opencodeIntegration) } -// RemoveOpenCode removes OpenCode integration. -func RemoveOpenCode() { - env := opencodeEnvProvider() - if err := removeOpenCode(env); err != nil { - setupExit(1) - } +func RemoveOpenCode() error { + return removeOpenCode(opencodeEnvProvider()) } func removeOpenCode(env agentsEnv) error { diff --git a/cmd/bd/setup/setup_test_helpers.go b/cmd/bd/setup/setup_test_helpers.go index 57bf014e2..a5aa5bc45 100644 --- a/cmd/bd/setup/setup_test_helpers.go +++ b/cmd/bd/setup/setup_test_helpers.go @@ -6,25 +6,6 @@ import ( "github.com/steveyegge/beads/internal/templates/agents" ) -type exitCapture struct { - called bool - code int -} - -func stubSetupExit(t *testing.T) *exitCapture { - t.Helper() - cap := &exitCapture{} - orig := setupExit - setupExit = func(code int) { - cap.called = true - cap.code = code - } - t.Cleanup(func() { - setupExit = orig - }) - return cap -} - // stubDetectRenderOpts overrides detectRenderOptsImpl to return // DefaultRenderOpts (HasRemote=true), matching what agents.RenderSection() // produces. This prevents hash mismatches in tests where no beads config exists. diff --git a/cmd/bd/shared_server_integration_test.go b/cmd/bd/shared_server_integration_test.go index 02505798c..46d194c96 100644 --- a/cmd/bd/shared_server_integration_test.go +++ b/cmd/bd/shared_server_integration_test.go @@ -100,6 +100,8 @@ func TestSharedServerConcurrent(t *testing.T) { "BEADS_DOLT_SERVER_PORT=" + strconv.Itoa(containerPort), "BEADS_DOLT_AUTO_START=0", "BEADS_TEST_MODE=1", + "BD_DISABLE_METRICS=1", + "BD_DISABLE_EVENT_FLUSH=1", "GIT_TERMINAL_PROMPT=0", "GIT_ASKPASS=", "SSH_ASKPASS=", diff --git a/cmd/bd/ship.go b/cmd/bd/ship.go index 156fae96e..9f94bbdbd 100644 --- a/cmd/bd/ship.go +++ b/cmd/bd/ship.go @@ -5,6 +5,7 @@ import ( "os" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -29,20 +30,28 @@ Examples: bd ship mol-run-assignee # Ship the mol-run-assignee capability bd ship mol-run-assignee --force # Ship even if issue is not closed bd ship mol-run-assignee --dry-run # Preview without making changes`, - Args: cobra.ExactArgs(1), - Run: runShip, + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: runShip, } -func runShip(cmd *cobra.Command, args []string) { +func runShip(cmd *cobra.Command, args []string) error { CheckReadonly("ship") + evt := metrics.NewCommandEvent("ship") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + capability := args[0] force, _ := cmd.Flags().GetBool("force") dryRun, _ := cmd.Flags().GetBool("dry-run") ctx := rootCtx - // Find issue with export: label exportLabel := "export:" + capability providesLabel := "provides:" + capability @@ -51,11 +60,11 @@ func runShip(cmd *cobra.Command, args []string) { issues, err = store.GetIssuesByLabel(ctx, exportLabel) if err != nil { - FatalError("listing issues: %v", err) + return HandleErrorRespectJSON("listing issues: %v", err) } if len(issues) == 0 { - FatalErrorWithHint( + return HandleErrorWithHintRespectJSON( fmt.Sprintf("no issue found with label '%s'", exportLabel), fmt.Sprintf("add the label first: bd label add %s", exportLabel)) } @@ -65,23 +74,21 @@ func runShip(cmd *cobra.Command, args []string) { for _, issue := range issues { fmt.Fprintf(os.Stderr, " %s: %s (%s)\n", issue.ID, issue.Title, issue.Status) } - FatalError("only one issue should have this label") + return HandleErrorRespectJSON("only one issue should have this label") } issue := issues[0] - // Validate issue is closed (unless --force) if issue.Status != types.StatusClosed && !force { - FatalErrorWithHint( + return HandleErrorWithHintRespectJSON( fmt.Sprintf("issue %s is not closed (status: %s)", issue.ID, issue.Status), "close the issue first, or use --force to override") } - // Check if already shipped (use direct store access) hasProvides := false labels, err := store.GetLabels(ctx, issue.ID) if err != nil { - FatalError("getting labels: %v", err) + return HandleErrorRespectJSON("getting labels: %v", err) } for _, l := range labels { if l == providesLabel { @@ -92,54 +99,51 @@ func runShip(cmd *cobra.Command, args []string) { if hasProvides { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "already_shipped", "capability": capability, "issue_id": issue.ID, }) - } else { - fmt.Printf("%s Capability '%s' already shipped (%s)\n", - ui.RenderPass("āœ“"), capability, issue.ID) } - return + fmt.Printf("%s Capability '%s' already shipped (%s)\n", + ui.RenderPass("āœ“"), capability, issue.ID) + return nil } if dryRun { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "dry_run", "capability": capability, "issue_id": issue.ID, "would_add": providesLabel, }) - } else { - fmt.Printf("%s Would ship '%s' on %s (dry run)\n", - ui.RenderAccent("→"), capability, issue.ID) } - return + fmt.Printf("%s Would ship '%s' on %s (dry run)\n", + ui.RenderAccent("→"), capability, issue.ID) + return nil } - // Add provides: label (use direct store access) if err := store.AddLabel(ctx, issue.ID, providesLabel, actor); err != nil { - FatalError("adding label: %v", err) + return HandleErrorRespectJSON("adding label: %v", err) } + commandDidWrite.Store(true) + if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "status": "shipped", "capability": capability, "issue_id": issue.ID, "label": providesLabel, }) - } else { - fmt.Printf("%s Shipped %s (%s)\n", - ui.RenderPass("āœ“"), capability, issue.ID) - fmt.Printf(" Added label: %s\n", providesLabel) - fmt.Printf("\nExternal projects can now depend on: external:%s:%s\n", - "", capability) } - - commandDidWrite.Store(true) + fmt.Printf("%s Shipped %s (%s)\n", + ui.RenderPass("āœ“"), capability, issue.ID) + fmt.Printf(" Added label: %s\n", providesLabel) + fmt.Printf("\nExternal projects can now depend on: external:%s:%s\n", + "", capability) + return nil } func init() { diff --git a/cmd/bd/show.go b/cmd/bd/show.go index 9cee788d9..28a5becad 100644 --- a/cmd/bd/show.go +++ b/cmd/bd/show.go @@ -8,22 +8,33 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/uimd" ) var showCmd = &cobra.Command{ - Use: "show [id...] [--id=...] [--current]", - Aliases: []string{"view"}, - GroupID: "issues", - Short: "Show issue details", - Args: cobra.ArbitraryArgs, // Allow zero positional args when --id is used - Run: func(cmd *cobra.Command, args []string) { + Use: "show [id...] [--id=...] [--current]", + Aliases: []string{"view"}, + GroupID: "issues", + Short: "Show issue details", + Args: cobra.ArbitraryArgs, // Allow zero positional args when --id is used + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("show") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if usesProxiedServer() { runShowProxiedServer(cmd, rootCtx, args) - return + return nil } + showThread, _ := cmd.Flags().GetBool("thread") shortMode, _ := cmd.Flags().GetBool("short") longMode, _ := cmd.Flags().GetBool("long") @@ -50,69 +61,54 @@ var showCmd = &cobra.Command{ // This allows IDs that look like flags (e.g., --xyz or gt--abc) to be passed safely args = append(args, idFlags...) - // Handle --current: resolve the active issue (GH#2184) if currentMode { if len(args) > 0 { - FatalErrorRespectJSON("--current cannot be combined with explicit issue IDs") + return HandleErrorRespectJSON("--current cannot be combined with explicit issue IDs") } currentID := resolveCurrentIssueID(ctx) 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)") } args = []string{currentID} } - // Validate that at least one ID is provided if len(args) == 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)") } - // Handle --as-of flag: show issue at a specific point in history if asOfRef != "" { - showIssueAsOf(ctx, args, asOfRef, shortMode) - return + return showIssueAsOf(ctx, args, asOfRef, shortMode) } - // Handle --watch mode (GH#654) - // Watch mode requires direct store access for file watching if watchMode { if err := ensureDirectMode("watch mode requires direct database access"); err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } if len(args) != 1 { - FatalErrorRespectJSON("watch mode requires exactly one issue ID") + return HandleErrorRespectJSON("watch mode requires exactly one issue ID") } watchIssue(ctx, args[0]) - return + return nil } - // Note: Direct mode uses resolveAndGetIssueWithRouting for prefix-based routing - - // Handle --thread flag: show full conversation thread if showThread { if len(args) > 0 { - // Direct mode - resolve first arg with routing result, err := resolveAndGetIssueWithRouting(ctx, store, args[0]) if result != nil { defer result.Close() } if err == nil && result != nil && result.ResolvedID != "" { - showMessageThread(ctx, result.ResolvedID, jsonOutput) - return + return showMessageThread(ctx, result.ResolvedID, jsonOutput) } } } - // Handle --refs flag: show issues that reference this issue if showRefs { - showIssueRefs(ctx, args, jsonOutput) - return + return showIssueRefs(ctx, args, jsonOutput) } - // Handle --children flag: show only children of this issue if showChildren { - showIssueChildren(ctx, args, jsonOutput, shortMode) - return + return showIssueChildren(ctx, args, jsonOutput, shortMode) } // Direct mode - use routed resolution for cross-repo lookups @@ -415,24 +411,25 @@ var showCmd = &cobra.Command{ if jsonOutput { if len(allDetails) > 0 { - outputJSON(allDetails) + if jerr := outputJSON(allDetails); jerr != nil { + return jerr + } } else { - // No issues found - exit non-zero with structured JSON error - // so downstream consumers (e.g., gt bd move) get a proper error - // instead of empty stdout causing "unexpected end of JSON input" - FatalErrorRespectJSON("no issues found matching the provided IDs") + return HandleErrorRespectJSON("no issues found matching the provided IDs") } } else if foundCount > 0 { - // Show tip after successful show (non-JSON mode) maybeShowTip(store) } else { - os.Exit(1) + if len(args) > 0 { + SetLastTouchedID(args[0]) + } + return SilentExit() } - // Track first shown issue as last touched if len(args) > 0 { SetLastTouchedID(args[0]) } + return nil }, } diff --git a/cmd/bd/show_children.go b/cmd/bd/show_children.go index 29ba28d4b..010c11b01 100644 --- a/cmd/bd/show_children.go +++ b/cmd/bd/show_children.go @@ -13,7 +13,7 @@ import ( ) // showIssueChildren displays only the children of the specified issue(s) -func showIssueChildren(ctx context.Context, args []string, jsonOut bool, shortMode bool) { +func showIssueChildren(ctx context.Context, args []string, jsonOut bool, shortMode bool) error { // Collect all children for all issues allChildren := make(map[string][]*types.IssueWithDependencyMetadata) @@ -60,8 +60,7 @@ func showIssueChildren(ctx context.Context, args []string, jsonOut bool, shortMo // Output results if jsonOut { - outputJSON(allChildren) - return + return outputJSON(allChildren) } // Display children @@ -81,11 +80,12 @@ func showIssueChildren(ctx context.Context, args []string, jsonOut bool, shortMo } fmt.Println() } + return nil } // showIssueAsOf displays issues as they existed at a specific commit or branch ref. // This requires a versioned storage backend (e.g., Dolt). -func showIssueAsOf(ctx context.Context, args []string, ref string, shortMode bool) { +func showIssueAsOf(ctx context.Context, args []string, ref string, shortMode bool) error { var allIssues []*types.Issue for idx, id := range args { issue, err := store.AsOf(ctx, id, ref) @@ -123,6 +123,7 @@ func showIssueAsOf(ctx context.Context, args []string, ref string, shortMode boo } if jsonOutput && len(allIssues) > 0 { - outputJSON(allIssues) + return outputJSON(allIssues) } + return nil } diff --git a/cmd/bd/show_refs.go b/cmd/bd/show_refs.go index 5adb82c25..8d120b444 100644 --- a/cmd/bd/show_refs.go +++ b/cmd/bd/show_refs.go @@ -11,7 +11,7 @@ import ( ) // showIssueRefs displays issues that reference the given issue(s), grouped by relationship type -func showIssueRefs(ctx context.Context, args []string, jsonOut bool) { +func showIssueRefs(ctx context.Context, args []string, jsonOut bool) error { // Collect all refs for all issues allRefs := make(map[string][]*types.IssueWithDependencyMetadata) @@ -47,8 +47,7 @@ func showIssueRefs(ctx context.Context, args []string, jsonOut bool) { // Output results if jsonOut { - outputJSON(allRefs) - return + return outputJSON(allRefs) } // Display refs grouped by issue and relationship type @@ -91,6 +90,7 @@ func showIssueRefs(ctx context.Context, args []string, jsonOut bool) { } fmt.Println() } + return nil } // displayRefGroup displays a group of references with a given type diff --git a/cmd/bd/show_thread.go b/cmd/bd/show_thread.go index 8ca85d27b..3571222b4 100644 --- a/cmd/bd/show_thread.go +++ b/cmd/bd/show_thread.go @@ -14,18 +14,17 @@ import ( ) // showMessageThread displays a full conversation thread for a message -func showMessageThread(ctx context.Context, messageID string, jsonOutput bool) { - // Get the starting message +func showMessageThread(ctx context.Context, messageID string, jsonOutput bool) error { var startMsg *types.Issue var err error startMsg, err = store.GetIssue(ctx, messageID) if err != nil { - FatalError("fetching message %s: %v", messageID, err) + return HandleError("fetching message %s: %v", messageID, err) } if startMsg == nil { - FatalError("message %s not found", messageID) + return HandleError("message %s not found", messageID) } // Find the root of the thread by following replies-to dependencies upward @@ -88,8 +87,7 @@ func showMessageThread(ctx context.Context, messageID string, jsonOutput bool) { if jsonOutput { encoder := json.NewEncoder(os.Stdout) encoder.SetIndent("", " ") - _ = encoder.Encode(threadMessages) - return + return encoder.Encode(threadMessages) } // Display the thread @@ -132,6 +130,7 @@ func showMessageThread(ctx context.Context, messageID string, jsonOutput bool) { } fmt.Printf("Total: %d messages in thread\n\n", len(threadMessages)) + return nil } // findRepliesTo finds the parent ID that this issue replies to via replies-to dependency. diff --git a/cmd/bd/sql.go b/cmd/bd/sql.go index 517bec1eb..71495b30e 100644 --- a/cmd/bd/sql.go +++ b/cmd/bd/sql.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" ) @@ -29,31 +30,38 @@ table (or JSON/CSV with --json/--csv). Non-SELECT queries (INSERT, UPDATE, DELET report the number of rows affected. WARNING: Direct database access bypasses the storage layer. Use with caution.`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("sql") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if !usesSQLServer() { - fmt.Fprintln(os.Stderr, "Error: 'bd sql' is not yet supported in embedded mode") - os.Exit(1) + return HandleError("'bd sql' is not yet supported in embedded mode") } query := args[0] csvOutput, _ := cmd.Flags().GetBool("csv") if store == nil { - FatalErrorRespectJSON("no database connection available (%s)", diagHint()) + return HandleErrorRespectJSON("no database connection available (%s)", diagHint()) } accessor, ok := storage.UnwrapStore(store).(storage.RawDBAccessor) if !ok { - FatalErrorRespectJSON("storage backend does not support raw DB access") + return HandleErrorRespectJSON("storage backend does not support raw DB access") } db := accessor.UnderlyingDB() if db == nil { - FatalErrorRespectJSON("underlying database not available") + return HandleErrorRespectJSON("underlying database not available") } ctx := rootCtx - // Detect if it's a read query (SELECT, EXPLAIN, PRAGMA, SHOW, DESCRIBE, WITH) trimmed := strings.TrimSpace(strings.ToUpper(query)) isRead := strings.HasPrefix(trimmed, "SELECT") || strings.HasPrefix(trimmed, "EXPLAIN") || @@ -65,16 +73,15 @@ WARNING: Direct database access bypasses the storage layer. Use with caution.`, if isRead { rows, err := db.QueryContext(ctx, query) if err != nil { - FatalErrorRespectJSON("query error: %v", err) + return HandleErrorRespectJSON("query error: %v", err) } defer rows.Close() columns, err := rows.Columns() if err != nil { - FatalErrorRespectJSON("getting columns: %v", err) + return HandleErrorRespectJSON("getting columns: %v", err) } - // Collect all rows allRows := make([]map[string]interface{}, 0) for rows.Next() { values := make([]interface{}, len(columns)) @@ -84,7 +91,7 @@ WARNING: Direct database access bypasses the storage layer. Use with caution.`, } if err := rows.Scan(valuePtrs...); err != nil { - FatalErrorRespectJSON("scanning row: %v", err) + return HandleErrorRespectJSON("scanning row: %v", err) } row := make(map[string]interface{}) @@ -99,19 +106,17 @@ WARNING: Direct database access bypasses the storage layer. Use with caution.`, allRows = append(allRows, row) } if err := rows.Err(); err != nil { - FatalErrorRespectJSON("reading rows: %v", err) + return HandleErrorRespectJSON("reading rows: %v", err) } if jsonOutput { - outputJSON(allRows) - return + return outputJSON(allRows) } if csvOutput { w := csv.NewWriter(os.Stdout) - // Header if err := w.Write(columns); err != nil { - FatalErrorRespectJSON("writing CSV header: %v", err) + return HandleErrorRespectJSON("writing CSV header: %v", err) } for _, row := range allRows { record := make([]string, len(columns)) @@ -119,20 +124,19 @@ WARNING: Direct database access bypasses the storage layer. Use with caution.`, record[i] = fmt.Sprintf("%v", row[col]) } if err := w.Write(record); err != nil { - FatalErrorRespectJSON("writing CSV row: %v", err) + return HandleErrorRespectJSON("writing CSV row: %v", err) } } w.Flush() if err := w.Error(); err != nil { - FatalErrorRespectJSON("flushing CSV: %v", err) + return HandleErrorRespectJSON("flushing CSV: %v", err) } - return + return nil } - // Table output if len(allRows) == 0 { fmt.Println("(0 rows)") - return + return nil } // Calculate column widths @@ -190,26 +194,26 @@ WARNING: Direct database access bypasses the storage layer. Use with caution.`, } fmt.Printf("(%d rows)\n", len(allRows)) - } else { - // Write query - CheckReadonly("sql") - - result, err := db.ExecContext(ctx, query) - if err != nil { - FatalErrorRespectJSON("exec error: %v", err) - } - - affected, _ := result.RowsAffected() - - if jsonOutput { - outputJSON(map[string]interface{}{ - "rows_affected": affected, - }) - return - } - - fmt.Printf("OK, %d rows affected\n", affected) + return nil } + + CheckReadonly("sql") + + result, err := db.ExecContext(ctx, query) + if err != nil { + return HandleErrorRespectJSON("exec error: %v", err) + } + + affected, _ := result.RowsAffected() + + if jsonOutput { + return outputJSON(map[string]interface{}{ + "rows_affected": affected, + }) + } + + fmt.Printf("OK, %d rows affected\n", affected) + return nil }, } diff --git a/cmd/bd/sql_test.go b/cmd/bd/sql_test.go index 772ef157e..81cf55d19 100644 --- a/cmd/bd/sql_test.go +++ b/cmd/bd/sql_test.go @@ -72,7 +72,7 @@ func TestSqlCommand(t *testing.T) { t.Run("select count", func(t *testing.T) { jsonOutput = true output := captureStdout(t, func() error { - sqlCmd.Run(sqlCmd, []string{"SELECT COUNT(*) as count FROM issues"}) + _ = sqlCmd.RunE(sqlCmd, []string{"SELECT COUNT(*) as count FROM issues"}) return nil }) @@ -96,7 +96,7 @@ func TestSqlCommand(t *testing.T) { t.Run("select with filter", func(t *testing.T) { jsonOutput = true output := captureStdout(t, func() error { - sqlCmd.Run(sqlCmd, []string{`SELECT id, title FROM issues WHERE status = 'open'`}) + _ = sqlCmd.RunE(sqlCmd, []string{`SELECT id, title FROM issues WHERE status = 'open'`}) return nil }) @@ -117,7 +117,7 @@ func TestSqlCommand(t *testing.T) { t.Run("empty result json", func(t *testing.T) { jsonOutput = true output := captureStdout(t, func() error { - sqlCmd.Run(sqlCmd, []string{`SELECT * FROM issues WHERE title = 'nonexistent'`}) + _ = sqlCmd.RunE(sqlCmd, []string{`SELECT * FROM issues WHERE title = 'nonexistent'`}) return nil }) @@ -134,7 +134,7 @@ func TestSqlCommand(t *testing.T) { t.Run("table output", func(t *testing.T) { jsonOutput = false output := captureStdout(t, func() error { - sqlCmd.Run(sqlCmd, []string{"SELECT COUNT(*) as count FROM issues"}) + _ = sqlCmd.RunE(sqlCmd, []string{"SELECT COUNT(*) as count FROM issues"}) return nil }) @@ -149,7 +149,7 @@ func TestSqlCommand(t *testing.T) { t.Run("empty table output", func(t *testing.T) { jsonOutput = false output := captureStdout(t, func() error { - sqlCmd.Run(sqlCmd, []string{`SELECT * FROM issues WHERE title = 'nonexistent'`}) + _ = sqlCmd.RunE(sqlCmd, []string{`SELECT * FROM issues WHERE title = 'nonexistent'`}) return nil }) diff --git a/cmd/bd/stale.go b/cmd/bd/stale.go index eecd1b119..1251005ec 100644 --- a/cmd/bd/stale.go +++ b/cmd/bd/stale.go @@ -5,6 +5,7 @@ import ( "time" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -18,38 +19,44 @@ This helps identify: - In-progress issues with no recent activity (may be abandoned) - Open issues that have been forgotten - Issues that might be outdated or no longer relevant`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("stale") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + days, _ := cmd.Flags().GetInt("days") status, _ := cmd.Flags().GetString("status") limit, _ := cmd.Flags().GetInt("limit") - // Use global jsonOutput set by PersistentPreRun if days < 1 { - FatalError("--days must be at least 1") + return HandleErrorRespectJSON("--days must be at least 1") } - // Validate status if provided if status != "" && status != "open" && status != "in_progress" && status != "blocked" && status != "deferred" { - FatalError("invalid status '%s'. Valid values: open, in_progress, blocked, deferred", status) + return HandleErrorRespectJSON("invalid status '%s'. Valid values: open, in_progress, blocked, deferred", status) } filter := types.StaleFilter{ Days: days, Status: status, Limit: limit, } - // Direct mode ctx := rootCtx issues, err := store.GetStaleIssues(ctx, filter) if err != nil { - FatalError("%v", err) + return HandleErrorRespectJSON("%v", err) } if jsonOutput { if issues == nil { issues = []*types.Issue{} } - outputJSON(issues) - return + return outputJSON(issues) } displayStaleIssues(issues, days) + return nil }, } diff --git a/cmd/bd/state.go b/cmd/bd/state.go index e99a17bc9..edbef56a9 100644 --- a/cmd/bd/state.go +++ b/cmd/bd/state.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -31,28 +32,34 @@ Examples: bd state witness-abc patrol # Output: active bd state witness-abc mode # Output: normal bd state witness-abc health # Output: healthy`, - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("state") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx issueID := args[0] dimension := args[1] - // Resolve partial ID var fullID string var err error fullID, err = utils.ResolvePartialID(ctx, store, issueID) if err != nil { - FatalErrorRespectJSON("resolving %s: %v", issueID, err) + return HandleErrorRespectJSON("resolving %s: %v", issueID, err) } - // Get labels for the issue var labels []string labels, err = store.GetLabels(ctx, fullID) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Find label matching dimension:* prefix := dimension + ":" var value string for _, label := range labels { @@ -71,8 +78,7 @@ Examples: if value == "" { result["value"] = nil } - outputJSON(result) - return + return outputJSON(result) } if value == "" { @@ -80,6 +86,7 @@ Examples: } else { fmt.Println(value) } + return nil }, } @@ -105,39 +112,45 @@ Examples: bd set-state agent-abc health=healthy The --reason flag provides context for the event bead (recommended).`, - Args: cobra.ExactArgs(2), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(2), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("set-state") + + evt := metrics.NewCommandEvent("set-state") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx issueID := args[0] stateSpec := args[1] - // Parse dimension=value parts := strings.SplitN(stateSpec, "=", 2) if len(parts) != 2 || parts[0] == "" || parts[1] == "" { - FatalErrorRespectJSON("invalid state format %q, expected =", stateSpec) + return HandleErrorRespectJSON("invalid state format %q, expected =", stateSpec) } dimension := parts[0] newValue := parts[1] reason, _ := cmd.Flags().GetString("reason") - // Resolve partial ID var fullID string var err error fullID, err = utils.ResolvePartialID(ctx, store, issueID) if err != nil { - FatalErrorRespectJSON("resolving %s: %v", issueID, err) + return HandleErrorRespectJSON("resolving %s: %v", issueID, err) } - // Get current labels to find existing dimension value var labels []string labels, err = store.GetLabels(ctx, fullID) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Find existing label for this dimension prefix := dimension + ":" var oldLabel string var oldValue string @@ -151,22 +164,19 @@ The --reason flag provides context for the event bead (recommended).`, newLabel := dimension + ":" + newValue - // Skip if no change if oldLabel == newLabel { if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "issue_id": fullID, "dimension": dimension, "value": newValue, "changed": false, }) - } else { - fmt.Printf("(no change: %s already set to %s)\n", dimension, newValue) } - return + fmt.Printf("(no change: %s already set to %s)\n", dimension, newValue) + return nil } - // 1. Create event bead recording the state change eventTitle := fmt.Sprintf("State change: %s → %s", dimension, newValue) eventDesc := "" if oldValue != "" { @@ -179,26 +189,24 @@ The --reason flag provides context for the event bead (recommended).`, } var eventID string - // Get next child ID for the event childID, err := store.GetNextChildID(ctx, fullID) if err != nil { - FatalErrorRespectJSON("generating child ID: %v", err) + return HandleErrorRespectJSON("generating child ID: %v", err) } event := &types.Issue{ ID: childID, Title: eventTitle, Description: eventDesc, - Status: types.StatusClosed, // Events are immediately closed + Status: types.StatusClosed, Priority: 4, IssueType: types.TypeEvent, CreatedBy: getActorWithGit(), } if err := store.CreateIssue(ctx, event, actor); err != nil { - FatalErrorRespectJSON("creating event: %v", err) + return HandleErrorRespectJSON("creating event: %v", err) } - // Add parent-child dependency dep := &types.Dependency{ IssueID: childID, DependsOnID: fullID, @@ -210,16 +218,14 @@ The --reason flag provides context for the event bead (recommended).`, eventID = childID - // 2. Remove old label if exists if oldLabel != "" { if err := store.RemoveLabel(ctx, fullID, oldLabel, actor); err != nil { WarnError("failed to remove old label %s: %v", oldLabel, err) } } - // 3. Add new label if err := store.AddLabel(ctx, fullID, newLabel, actor); err != nil { - FatalErrorRespectJSON("adding label: %v", err) + return HandleErrorRespectJSON("adding label: %v", err) } commandDidWrite.Store(true) @@ -236,8 +242,7 @@ The --reason flag provides context for the event bead (recommended).`, if oldValue == "" { result["old_value"] = nil } - outputJSON(result) - return + return outputJSON(result) } fmt.Printf("%s Set %s = %s on %s\n", ui.RenderPass("āœ“"), dimension, newValue, fullID) @@ -245,6 +250,7 @@ The --reason flag provides context for the event bead (recommended).`, fmt.Printf(" Previous: %s\n", oldValue) } fmt.Printf(" Event: %s\n", eventID) + return nil }, } @@ -262,27 +268,33 @@ Example: # patrol: active # mode: normal # health: healthy`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("state-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx issueID := args[0] - // Resolve partial ID var fullID string var err error fullID, err = utils.ResolvePartialID(ctx, store, issueID) if err != nil { - FatalErrorRespectJSON("resolving %s: %v", issueID, err) + return HandleErrorRespectJSON("resolving %s: %v", issueID, err) } - // Get labels for the issue var labels []string labels, err = store.GetLabels(ctx, fullID) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Extract state labels (those with colon) states := make(map[string]string) for _, label := range labels { if idx := strings.Index(label, ":"); idx > 0 { @@ -293,17 +305,15 @@ Example: } if jsonOutput { - result := map[string]interface{}{ + return outputJSON(map[string]interface{}{ "issue_id": fullID, "states": states, - } - outputJSON(result) - return + }) } if len(states) == 0 { fmt.Printf("\n%s has no state labels\n", fullID) - return + return nil } fmt.Printf("\n%s State for %s:\n", ui.RenderAccent("šŸ“Š"), fullID) @@ -311,6 +321,7 @@ Example: fmt.Printf(" %s: %s\n", dimension, value) } fmt.Println() + return nil }, } diff --git a/cmd/bd/status.go b/cmd/bd/status.go index 9e13d08e3..c84ab224e 100644 --- a/cmd/bd/status.go +++ b/cmd/bd/status.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -51,38 +52,42 @@ Examples: bd status --json # JSON format output bd status --assigned # Show issues assigned to current user bd stats # Alias for bd status`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + showAll, _ := cmd.Flags().GetBool("all") showAssigned, _ := cmd.Flags().GetBool("assigned") noActivity, _ := cmd.Flags().GetBool("no-activity") jsonFormat, _ := cmd.Flags().GetBool("json") - // Override global jsonOutput if --json flag is set if jsonFormat { jsonOutput = true } - // Get statistics var stats *types.Statistics var err error ctx := rootCtx - // Direct mode stats, err = store.GetStatistics(ctx) if err != nil { - FatalErrorRespectJSON("%v", err) + return HandleErrorRespectJSON("%v", err) } - // Filter by assignee if requested (overrides stats with filtered counts) if showAssigned { stats = getAssignedStatistics(actor) if stats == nil { - FatalErrorRespectJSON("failed to get assigned statistics") + return HandleErrorRespectJSON("failed to get assigned statistics") } } - // Get recent activity from git history (last 24 hours) unless --no-activity var recentActivity *RecentActivitySummary if !noActivity { recentActivity = getGitActivity(24) @@ -93,10 +98,8 @@ Examples: RecentActivity: recentActivity, } - // JSON output if jsonOutput { - outputJSON(output) - return + return outputJSON(output) } // Human-readable colorized output using semantic ui package @@ -135,12 +138,11 @@ Examples: fmt.Printf(" Issues Updated: %d\n", recentActivity.IssuesUpdated) } - // Show hint for more details fmt.Printf("\nFor more details, use 'bd list' to see individual issues.\n") fmt.Println() - // Suppress showAll flag (it's the default behavior, included for CLI familiarity) _ = showAll + return nil }, } diff --git a/cmd/bd/statuses.go b/cmd/bd/statuses.go index 55f8b8c9d..efac42b38 100644 --- a/cmd/bd/statuses.go +++ b/cmd/bd/statuses.go @@ -3,9 +3,9 @@ package main import ( "context" "fmt" - "os" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -48,10 +48,18 @@ Examples: bd statuses # List all statuses with icons and categories bd statuses --json # Output as JSON `, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("statuses") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if err := ensureDirectMode("statuses command requires direct database access"); err != nil { - fmt.Fprintf(os.Stderr, "Error: %v\n", err) - return + return HandleError("%v", err) } var customStatuses []types.CustomStatus @@ -77,11 +85,9 @@ Examples: }) } result.CustomStatuses = customStatuses - outputJSON(result) - return + return outputJSON(result) } - // Text output fmt.Println("Built-in statuses:") for _, s := range builtInStatuses { icon := ui.RenderStatusIcon(string(s.Status)) @@ -99,6 +105,7 @@ Examples: fmt.Println("Configure with: bd config set status.custom \"name:category,...\"") fmt.Println("Categories: active, wip, done, frozen") } + return nil }, } diff --git a/cmd/bd/swarm.go b/cmd/bd/swarm.go index 78ade9acc..0ebfd799b 100644 --- a/cmd/bd/swarm.go +++ b/cmd/bd/swarm.go @@ -5,11 +5,11 @@ import ( "context" "errors" "fmt" - "os" "sort" "strings" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -153,61 +153,66 @@ Reports: Examples: bd swarm validate gt-epic-123 # Validate epic structure bd swarm validate gt-epic-123 --verbose # Include detailed issue graph`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("swarm-validate") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx verbose, _ := cmd.Flags().GetBool("verbose") - // Swarm commands require direct store access if store == nil { - FatalErrorRespectJSON("no database connection") + return HandleErrorRespectJSON("no database connection") } - // Resolve epic ID epicID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalErrorRespectJSON("epic '%s' not found: %v", args[0], err) + return HandleErrorRespectJSON("epic '%s' not found: %v", args[0], err) } - // Get the epic epic, err := store.GetIssue(ctx, epicID) if err != nil { - FatalErrorRespectJSON("failed to get epic: %v", err) + return HandleErrorRespectJSON("failed to get epic: %v", err) } if epic == nil { - FatalErrorRespectJSON("epic '%s' not found", epicID) + return HandleErrorRespectJSON("epic '%s' not found", epicID) } - // Verify it's an epic if epic.IssueType != types.TypeEpic && epic.IssueType != "molecule" { - FatalErrorRespectJSON("'%s' is not an epic or molecule (type: %s)", epicID, epic.IssueType) + return HandleErrorRespectJSON("'%s' is not an epic or molecule (type: %s)", epicID, epic.IssueType) } - // Analyze the epic structure analysis, err := analyzeEpicForSwarm(ctx, store, epic) if err != nil { - FatalErrorRespectJSON("failed to analyze epic: %v", err) + return HandleErrorRespectJSON("failed to analyze epic: %v", err) } - // Include detailed graph only in verbose mode if !verbose { analysis.Issues = nil } if jsonOutput { - outputJSON(analysis) - if !analysis.Swarmable { - os.Exit(1) + if jerr := outputJSON(analysis); jerr != nil { + return jerr } - return + if !analysis.Swarmable { + return SilentExit() + } + return nil } - // Human-readable output renderSwarmAnalysis(analysis) if !analysis.Swarmable { - os.Exit(1) + return SilentExit() } + return nil }, } @@ -611,70 +616,72 @@ Examples: bd swarm status gt-epic-123 # Show swarm status by epic bd swarm status gt-swarm-456 # Show status via swarm molecule bd swarm status gt-epic-123 --json # Machine-readable output`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("swarm-status") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // Swarm commands require direct store access if store == nil { - FatalErrorRespectJSON("no database connection") + return HandleErrorRespectJSON("no database connection") } - // Resolve ID issueID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalErrorRespectJSON("issue '%s' not found: %v", args[0], err) + return HandleErrorRespectJSON("issue '%s' not found: %v", args[0], err) } - // Get the issue issue, err := store.GetIssue(ctx, issueID) if err != nil { if errors.Is(err, storage.ErrNotFound) { - FatalErrorRespectJSON("issue '%s' not found", issueID) + return HandleErrorRespectJSON("issue '%s' not found", issueID) } - FatalErrorRespectJSON("failed to get issue: %v", err) + return HandleErrorRespectJSON("failed to get issue: %v", err) } var epic *types.Issue - // Check if it's a swarm molecule - if so, follow the link to the epic if issue.IssueType == "molecule" && issue.MolType == types.MolTypeSwarm { - // Find linked epic via relates-to dependency deps, err := store.GetDependencyRecords(ctx, issue.ID) if err != nil { - FatalErrorRespectJSON("failed to get swarm dependencies: %v", err) + return HandleErrorRespectJSON("failed to get swarm dependencies: %v", err) } for _, dep := range deps { if dep.Type == types.DepRelatesTo { epic, err = store.GetIssue(ctx, dep.DependsOnID) if err != nil { - FatalErrorRespectJSON("failed to get linked epic: %v", err) + return HandleErrorRespectJSON("failed to get linked epic: %v", err) } break } } if epic == nil { - FatalErrorRespectJSON("swarm molecule '%s' has no linked epic", issueID) + return HandleErrorRespectJSON("swarm molecule '%s' has no linked epic", issueID) } } else if issue.IssueType == types.TypeEpic || issue.IssueType == "molecule" { epic = issue } else { - FatalErrorRespectJSON("'%s' is not an epic or swarm molecule (type: %s)", issueID, issue.IssueType) + return HandleErrorRespectJSON("'%s' is not an epic or swarm molecule (type: %s)", issueID, issue.IssueType) } - // Get swarm status status, err := getSwarmStatus(ctx, store, epic) if err != nil { - FatalErrorRespectJSON("failed to get swarm status: %v", err) + return HandleErrorRespectJSON("failed to get swarm status: %v", err) } if jsonOutput { - outputJSON(status) - return + return outputJSON(status) } - // Human-readable output renderSwarmStatus(status) + return nil }, } @@ -893,42 +900,47 @@ Examples: bd swarm create bd-epic-123 # Create swarm for epic bd swarm create bd-epic-123 --coordinator=observer/ # With specific coordinator bd swarm create bd-task-456 # Auto-wrap single issue`, - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) { + Args: cobra.ExactArgs(1), + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { CheckReadonly("swarm create") + + evt := metrics.NewCommandEvent("swarm-create") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx coordinator, _ := cmd.Flags().GetString("coordinator") force, _ := cmd.Flags().GetBool("force") - // Swarm commands require direct store access if store == nil { - FatalErrorRespectJSON("no database connection") + return HandleErrorRespectJSON("no database connection") } - // Resolve the input ID inputID, err := utils.ResolvePartialID(ctx, store, args[0]) if err != nil { - FatalErrorRespectJSON("issue '%s' not found: %v", args[0], err) + return HandleErrorRespectJSON("issue '%s' not found: %v", args[0], err) } - // Get the issue issue, err := store.GetIssue(ctx, inputID) if err != nil { if errors.Is(err, storage.ErrNotFound) { - FatalErrorRespectJSON("issue '%s' not found", inputID) + return HandleErrorRespectJSON("issue '%s' not found", inputID) } - FatalErrorRespectJSON("failed to get issue: %v", err) + return HandleErrorRespectJSON("failed to get issue: %v", err) } var epicID string var epicTitle string - // Check if it's an epic or single issue that needs wrapping if issue.IssueType == types.TypeEpic || issue.IssueType == "molecule" { epicID = issue.ID epicTitle = issue.Title } else { - // Auto-wrap: create an epic with this issue as child if !jsonOutput { fmt.Printf("Auto-wrapping single issue as epic...\n") } @@ -943,10 +955,9 @@ Examples: } if err := store.CreateIssue(ctx, wrapperEpic, actor); err != nil { - FatalErrorRespectJSON("failed to create wrapper epic: %v", err) + return HandleErrorRespectJSON("failed to create wrapper epic: %v", err) } - // Add parent-child dependency: issue depends on epic (epic is parent) dep := &types.Dependency{ IssueID: issue.ID, DependsOnID: wrapperEpic.ID, @@ -954,7 +965,7 @@ Examples: CreatedBy: actor, } if err := store.AddDependency(ctx, dep, actor); err != nil { - FatalErrorRespectJSON("failed to link issue to epic: %v", err) + return HandleErrorRespectJSON("failed to link issue to epic: %v", err) } epicID = wrapperEpic.ID @@ -965,52 +976,53 @@ Examples: } } - // Check for existing swarm molecule existingSwarm, err := findExistingSwarm(ctx, store, epicID) if err != nil { - FatalErrorRespectJSON("failed to check for existing swarm: %v", err) + return HandleErrorRespectJSON("failed to check for existing swarm: %v", err) } if existingSwarm != nil && !force { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "swarm already exists", "existing_id": existingSwarm.ID, "existing_title": existingSwarm.Title, - }) - } else { - fmt.Printf("%s Swarm already exists: %s\n", ui.RenderWarn("⚠"), ui.RenderID(existingSwarm.ID)) - fmt.Printf(" Use --force to create another.\n") + }); jerr != nil { + return jerr + } + return SilentExit() } - os.Exit(1) + fmt.Printf("%s Swarm already exists: %s\n", ui.RenderWarn("⚠"), ui.RenderID(existingSwarm.ID)) + fmt.Printf(" Use --force to create another.\n") + return SilentExit() } - // Validate the epic structure epic, err := store.GetIssue(ctx, epicID) if err != nil { - FatalErrorRespectJSON("failed to get epic: %v", err) + return HandleErrorRespectJSON("failed to get epic: %v", err) } analysis, err := analyzeEpicForSwarm(ctx, store, epic) if err != nil { - FatalErrorRespectJSON("failed to analyze epic: %v", err) + return HandleErrorRespectJSON("failed to analyze epic: %v", err) } if !analysis.Swarmable { if jsonOutput { - outputJSON(map[string]interface{}{ + if jerr := outputJSON(map[string]interface{}{ "error": "epic is not swarmable", "analysis": analysis, - }) - } else { - fmt.Printf("\n%s Epic is not swarmable. Fix errors first:\n", ui.RenderFail("āœ—")) - for _, e := range analysis.Errors { - fmt.Printf(" • %s\n", e) + }); jerr != nil { + return jerr } + return SilentExit() } - os.Exit(1) + fmt.Printf("\n%s Epic is not swarmable. Fix errors first:\n", ui.RenderFail("āœ—")) + for _, e := range analysis.Errors { + fmt.Printf(" • %s\n", e) + } + return SilentExit() } - // Create the swarm molecule swarmMol := &types.Issue{ Title: fmt.Sprintf("Swarm: %s", epicTitle), Description: fmt.Sprintf("Swarm molecule orchestrating epic %s.\n\nEpic: %s\nCoordinator: %s", epicID, epicID, coordinator), @@ -1023,10 +1035,9 @@ Examples: } if err := store.CreateIssue(ctx, swarmMol, actor); err != nil { - FatalErrorRespectJSON("failed to create swarm molecule: %v", err) + return HandleErrorRespectJSON("failed to create swarm molecule: %v", err) } - // Link swarm molecule to epic with relates-to dependency dep := &types.Dependency{ IssueID: swarmMol.ID, DependsOnID: epicID, @@ -1034,28 +1045,28 @@ Examples: CreatedBy: actor, } if err := store.AddDependency(ctx, dep, actor); err != nil { - FatalErrorRespectJSON("failed to link swarm to epic: %v", err) + return HandleErrorRespectJSON("failed to link swarm to epic: %v", err) } commandDidWrite.Store(true) if jsonOutput { - outputJSON(map[string]interface{}{ + return outputJSON(map[string]interface{}{ "swarm_id": swarmMol.ID, "epic_id": epicID, "coordinator": coordinator, "analysis": analysis, }) - } else { - fmt.Printf("\n%s Created swarm molecule: %s\n", ui.RenderPass("āœ“"), ui.RenderID(swarmMol.ID)) - fmt.Printf(" Epic: %s (%s)\n", epicID, epicTitle) - if coordinator != "" { - fmt.Printf(" Coordinator: %s\n", coordinator) - } - fmt.Printf(" Total issues: %d\n", analysis.TotalIssues) - fmt.Printf(" Max parallelism: %d\n", analysis.MaxParallelism) - fmt.Printf(" Waves: %d\n", len(analysis.ReadyFronts)) } + fmt.Printf("\n%s Created swarm molecule: %s\n", ui.RenderPass("āœ“"), ui.RenderID(swarmMol.ID)) + fmt.Printf(" Epic: %s (%s)\n", epicID, epicTitle) + if coordinator != "" { + fmt.Printf(" Coordinator: %s\n", coordinator) + } + fmt.Printf(" Total issues: %d\n", analysis.TotalIssues) + fmt.Printf(" Max parallelism: %d\n", analysis.MaxParallelism) + fmt.Printf(" Waves: %d\n", len(analysis.ReadyFronts)) + return nil }, } @@ -1072,31 +1083,37 @@ Shows each swarm molecule with: Examples: bd swarm list # List all swarms bd swarm list --json # Machine-readable output`, - Run: func(cmd *cobra.Command, args []string) { + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("swarm-list") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + ctx := rootCtx - // Swarm commands require direct store access if store == nil { - FatalErrorRespectJSON("no database connection") + return HandleErrorRespectJSON("no database connection") } - // Query for all swarm molecules swarmType := types.MolTypeSwarm filter := types.IssueFilter{ MolType: &swarmType, } swarms, err := store.SearchIssues(ctx, "", filter) if err != nil { - FatalErrorRespectJSON("failed to list swarms: %v", err) + return HandleErrorRespectJSON("failed to list swarms: %v", err) } if len(swarms) == 0 { if jsonOutput { - outputJSON(map[string]interface{}{"swarms": []interface{}{}}) - } else { - fmt.Printf("No swarm molecules found.\n") + return outputJSON(map[string]interface{}{"swarms": []interface{}{}}) } - return + fmt.Printf("No swarm molecules found.\n") + return nil } // Build output with status for each swarm @@ -1149,14 +1166,11 @@ Examples: } if jsonOutput { - outputJSON(map[string]interface{}{"swarms": items}) - return + return outputJSON(map[string]interface{}{"swarms": items}) } - // Human-readable output fmt.Printf("\n%s Active Swarms (%d)\n\n", ui.RenderAccent("šŸ"), len(items)) for _, item := range items { - // Progress indicator progressStr := fmt.Sprintf("%d/%d", item.Completed, item.Total) if item.Active > 0 { progressStr += fmt.Sprintf(", %d active", item.Active) @@ -1172,6 +1186,7 @@ Examples: } fmt.Println() } + return nil }, } diff --git a/cmd/bd/sync_push_pull.go b/cmd/bd/sync_push_pull.go index b674940bf..c17e01879 100644 --- a/cmd/bd/sync_push_pull.go +++ b/cmd/bd/sync_push_pull.go @@ -12,6 +12,7 @@ import ( "github.com/steveyegge/beads/internal/gitlab" "github.com/steveyegge/beads/internal/jira" "github.com/steveyegge/beads/internal/linear" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/notion" "github.com/steveyegge/beads/internal/tracker" ) @@ -52,7 +53,9 @@ var jiraPushCmd = &cobra.Command{ Accepts bead IDs as positional arguments. Equivalent to: bd jira sync --push --issues `, - Run: runJiraPush, + SilenceUsage: true, + SilenceErrors: true, + RunE: runJiraPush, } var jiraPullCmd = &cobra.Command{ @@ -62,7 +65,9 @@ var jiraPullCmd = &cobra.Command{ Accepts bead IDs or external references as positional arguments. Equivalent to: bd jira sync --pull --issues `, - Run: runJiraPull, + SilenceUsage: true, + SilenceErrors: true, + RunE: runJiraPull, } // --- Linear push/pull --- @@ -74,7 +79,9 @@ var linearPushCmd = &cobra.Command{ Accepts bead IDs as positional arguments. Equivalent to: bd linear sync --push --issues `, - Run: runLinearPush, + SilenceUsage: true, + SilenceErrors: true, + RunE: runLinearPush, } var linearPullCmd = &cobra.Command{ @@ -84,7 +91,9 @@ var linearPullCmd = &cobra.Command{ Accepts bead IDs or external references as positional arguments. Equivalent to: bd linear sync --pull --issues `, - Run: runLinearPull, + SilenceUsage: true, + SilenceErrors: true, + RunE: runLinearPull, } // --- GitHub push/pull --- @@ -218,6 +227,13 @@ func outputSyncResult(result *tracker.SyncResult, dryRun bool) { // --- ADO implementations --- func runADOPush(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("ado-push") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { return fmt.Errorf("at least one bead ID is required") } @@ -258,6 +274,13 @@ func runADOPush(cmd *cobra.Command, args []string) error { } func runADOPull(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("ado-pull") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { return fmt.Errorf("at least one bead ID or external reference is required") } @@ -300,9 +323,16 @@ func runADOPull(cmd *cobra.Command, args []string) error { // --- Jira implementations --- -func runJiraPush(cmd *cobra.Command, args []string) { +func runJiraPush(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("jira-push") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { - FatalError("at least one bead ID is required") + return HandleError("at least one bead ID is required") } dryRun, _ := cmd.Flags().GetBool("dry-run") if !dryRun { @@ -310,16 +340,16 @@ func runJiraPush(cmd *cobra.Command, args []string) { } if err := ensureStoreActive(); err != nil { - FatalError("database not available: %v", err) + return HandleError("database not available: %v", err) } if err := validateJiraConfig(); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } ctx := rootCtx jt := &jira.Tracker{} if err := jt.Init(ctx, store); err != nil { - FatalError("initializing Jira tracker: %v", err) + return HandleError("initializing Jira tracker: %v", err) } engine := tracker.NewEngine(jt, store, actor) @@ -334,14 +364,22 @@ func runJiraPush(cmd *cobra.Command, args []string) { IssueIDs: args, }) if err != nil { - FatalError("sync failed: %v", err) + return HandleError("sync failed: %v", err) } outputSyncResult(result, dryRun) + return nil } -func runJiraPull(cmd *cobra.Command, args []string) { +func runJiraPull(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("jira-pull") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { - FatalError("at least one bead ID or external reference is required") + return HandleError("at least one bead ID or external reference is required") } dryRun, _ := cmd.Flags().GetBool("dry-run") if !dryRun { @@ -349,16 +387,16 @@ func runJiraPull(cmd *cobra.Command, args []string) { } if err := ensureStoreActive(); err != nil { - FatalError("database not available: %v", err) + return HandleError("database not available: %v", err) } if err := validateJiraConfig(); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } ctx := rootCtx jt := &jira.Tracker{} if err := jt.Init(ctx, store); err != nil { - FatalError("initializing Jira tracker: %v", err) + return HandleError("initializing Jira tracker: %v", err) } engine := tracker.NewEngine(jt, store, actor) @@ -372,16 +410,24 @@ func runJiraPull(cmd *cobra.Command, args []string) { IssueIDs: args, }) if err != nil { - FatalError("sync failed: %v", err) + return HandleError("sync failed: %v", err) } outputSyncResult(result, dryRun) + return nil } // --- Linear implementations --- -func runLinearPush(cmd *cobra.Command, args []string) { +func runLinearPush(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("linear-push") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { - FatalError("at least one bead ID is required") + return HandleError("at least one bead ID is required") } dryRun, _ := cmd.Flags().GetBool("dry-run") if !dryRun { @@ -391,7 +437,7 @@ func runLinearPush(cmd *cobra.Command, args []string) { if lockDir := beads.FindBeadsDir(); lockDir != "" { syncLock, err := linear.AcquireSyncLock(lockDir, true) if err != nil { - FatalError("acquiring sync lock: %v", err) + return HandleError("acquiring sync lock: %v", err) } defer func() { if err := syncLock.Release(); err != nil { @@ -401,25 +447,25 @@ func runLinearPush(cmd *cobra.Command, args []string) { } if err := ensureStoreActive(); err != nil { - FatalError("database not available: %v", err) + return HandleError("database not available: %v", err) } if err := validateLinearConfig(nil); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } ctx := rootCtx teamIDs := getLinearTeamIDs(ctx, nil) if len(teamIDs) > 1 { - FatalError("linear push does not support multiple configured teams\nUse: bd linear sync --push --team ") + return HandleError("linear push does not support multiple configured teams\nUse: bd linear sync --push --team ") } lt := &linear.Tracker{} lt.SetTeamIDs(teamIDs) if err := lt.Init(ctx, store); err != nil { - FatalError("initializing Linear tracker: %v", err) + return HandleError("initializing Linear tracker: %v", err) } if err := lt.ValidatePushStateMappings(ctx); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } engine := tracker.NewEngine(lt, store, actor) @@ -435,14 +481,22 @@ func runLinearPush(cmd *cobra.Command, args []string) { IssueIDs: args, }) if err != nil { - FatalError("sync failed: %v", err) + return HandleError("sync failed: %v", err) } outputSyncResult(result, dryRun) + return nil } -func runLinearPull(cmd *cobra.Command, args []string) { +func runLinearPull(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("linear-pull") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { - FatalError("at least one bead ID or external reference is required") + return HandleError("at least one bead ID or external reference is required") } dryRun, _ := cmd.Flags().GetBool("dry-run") relations, _ := cmd.Flags().GetBool("relations") @@ -453,7 +507,7 @@ func runLinearPull(cmd *cobra.Command, args []string) { if lockDir := beads.FindBeadsDir(); lockDir != "" { syncLock, err := linear.AcquireSyncLock(lockDir, true) if err != nil { - FatalError("acquiring sync lock: %v", err) + return HandleError("acquiring sync lock: %v", err) } defer func() { if err := syncLock.Release(); err != nil { @@ -463,10 +517,10 @@ func runLinearPull(cmd *cobra.Command, args []string) { } if err := ensureStoreActive(); err != nil { - FatalError("database not available: %v", err) + return HandleError("database not available: %v", err) } if err := validateLinearConfig(nil); err != nil { - FatalError("%v", err) + return HandleError("%v", err) } ctx := rootCtx @@ -475,7 +529,7 @@ func runLinearPull(cmd *cobra.Command, args []string) { lt := &linear.Tracker{} lt.SetTeamIDs(teamIDs) if err := lt.Init(ctx, store); err != nil { - FatalError("initializing Linear tracker: %v", err) + return HandleError("initializing Linear tracker: %v", err) } engine := tracker.NewEngine(lt, store, actor) @@ -494,14 +548,22 @@ func runLinearPull(cmd *cobra.Command, args []string) { DependencySources: linearPullDependencySources(relations), }) if err != nil { - FatalError("sync failed: %v", err) + return HandleError("sync failed: %v", err) } outputSyncResult(result, dryRun) + return nil } // --- GitHub implementations --- func runGitHubPush(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("github-push") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { return fmt.Errorf("at least one bead ID is required") } @@ -542,6 +604,13 @@ func runGitHubPush(cmd *cobra.Command, args []string) error { } func runGitHubPull(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("github-pull") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { return fmt.Errorf("at least one bead ID or external reference is required") } @@ -585,6 +654,13 @@ func runGitHubPull(cmd *cobra.Command, args []string) error { // --- GitLab implementations --- func runGitLabPush(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("gitlab-push") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { return fmt.Errorf("at least one bead ID is required") } @@ -625,6 +701,13 @@ func runGitLabPush(cmd *cobra.Command, args []string) error { } func runGitLabPull(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("gitlab-pull") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { return fmt.Errorf("at least one bead ID or external reference is required") } @@ -668,6 +751,13 @@ func runGitLabPull(cmd *cobra.Command, args []string) error { // --- Notion implementations --- func runNotionPush(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("notion-push") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { return fmt.Errorf("at least one bead ID is required") } @@ -715,6 +805,13 @@ func runNotionPush(cmd *cobra.Command, args []string) error { } func runNotionPull(cmd *cobra.Command, args []string) error { + evt := metrics.NewCommandEvent("notion-pull") + defer func() { + if c := metrics.Global(); c != nil { + c.CloseEventAndAdd(evt) + } + }() + if len(args) == 0 { return fmt.Errorf("at least one bead ID or external reference is required") } diff --git a/cmd/bd/tag.go b/cmd/bd/tag.go index aae6d2e3b..69fb48d46 100644 --- a/cmd/bd/tag.go +++ b/cmd/bd/tag.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" ) @@ -18,10 +19,19 @@ Shorthand for 'bd update --add-label