: refactor to use RunE, emit usage metrics, skip metrics in CI

(cherry picked from commit 9596c7233d)
This commit is contained in:
coffeegoddd☕️✨ 2026-06-15 13:43:02 -07:00 • committed by CI Bot
commit d7d7a34607
200 changed files with 6846 additions and 4520 deletions

View file

@ -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

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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:

View file

@ -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

View file

@ -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

View file

@ -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`

View file

@ -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 <token>' 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

View file

@ -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 <id> --assignee <name>'.
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
},
}

View file

@ -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 <entry-id>",
Short: "Append a label entry referencing an existing interaction",
Args: cobra.ExactArgs(1),
Run: func(_ *cobra.Command, args []string) {
Use: "label <entry-id>",
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)

View file

@ -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

View file

@ -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 <path>' 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 <path>' 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.")

View file

@ -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

View file

@ -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 {

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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 <id> --status all'.
// Unlike plain 'bd list', children includes closed issues by default (GH#2477).
var childrenCmd = &cobra.Command{
Use: "children <parent-id>",
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{})
},
}

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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 <issue-id>.
var commentsMisplacedListCmd = &cobra.Command{
Use: "list",
Short: "Invalid — use bd comments <issue-id> to list comments",
Run: func(cmd *cobra.Command, args []string) {
FatalErrorRespectJSON(`"bd comments list" is not valid.
Use: "list",
Short: "Invalid — use bd comments <issue-id> 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 <issue-id>
@ -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
},
}

View file

@ -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
},
}

View file

@ -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 <key> <value>",
Short: "Set a configuration value",
Args: cobra.ExactArgs(2),
Run: func(_ *cobra.Command, args []string) {
Use: "set <key> <value>",
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 <key>",
Short: "Get a configuration value",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
Use: "get <key>",
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 <key>",
Short: "Delete a configuration value",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
Use: "unset <key>",
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 <key> <value>' 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.

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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) {

View file

@ -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
},
}

View file

@ -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

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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) {

View file

@ -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)")
}
}

View file

@ -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))

View file

@ -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
},
}

View file

@ -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

View file

@ -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:<project>:<capability>
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
},
}

View file

@ -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
},
}

View file

@ -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()
}

View file

@ -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
}

View file

@ -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)

View file

@ -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.

View file

@ -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.

View file

@ -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() {

View file

@ -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.

View file

@ -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)

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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)
}
}

View file

@ -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)
}
}

View file

@ -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")
}

View file

@ -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 <name>",
Short: "Remove a federation peer",
Args: cobra.ExactArgs(1),
Run: runFederationRemovePeer,
Use: "remove-peer <name>",
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 {

View file

@ -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.

View file

@ -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.

View file

@ -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")
}

View file

@ -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
},
}

View file

@ -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 <name|path> [--all]")
return HandleErrorWithHint("formula name or path required", "Usage: bd formula convert <name|path> [--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() {

View file

@ -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 <gate-id>' 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
},
}

View file

@ -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.

View file

@ -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 {

View file

@ -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
},
}

View file

@ -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 <token>' or GITHUB_TOKEN environment variable")
return HandleError("github.token is not configured. Set via 'bd config set github.token <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

View file

@ -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

View file

@ -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=",

View file

@ -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
},
}

View file

@ -253,15 +253,10 @@ func loadEmbeddedCustomTypes() []string {
return config.GetCustomTypesFromYAML()
}
// createIssuesFromGraph handles `bd create --graph <plan-file>`.
// 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 {

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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 <id> 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
},
}

View file

@ -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)

View file

@ -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() {

View file

@ -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 <name>\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"
}

View file

@ -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 {

371
cmd/bd/init_metrics_test.go Normal file
View file

@ -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)
}
}
}

View file

@ -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)
},
}

View file

@ -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)
}
}

View file

@ -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.

View file

@ -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
},
}

View file

@ -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
},
}

View file

@ -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 <TEAM_ID>")
}
// 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 \"<ID>\"")
fmt.Println(" bd config set linear.team_ids \"<ID1>,<ID2>\" # multiple teams")
return nil
}
// resolveBeadsDirForStaleness returns the active beads directory for

View file

@ -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
},
}

View file

@ -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()
},
}

View file

@ -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
},
}

View file

@ -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
}

View file

@ -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) {

View file

@ -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
},
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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
},
}

View file

@ -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 <holder>: 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)

View file

@ -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()
},
}

View file

@ -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
},
}

View file

@ -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)

View file

@ -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)

View file

@ -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.

Some files were not shown because too many files have changed in this diff Show more