test(cmd/bd): pin the command tree and representative --help output (#7675)

* test(cmd/bd): pin the command tree and representative --help output

Add two in-process goldens for the bd command surface, so any added,
removed, hidden or reworded command or flag fails until the goldens are
regenerated and shows up as a reviewed testdata diff:

- TestCommandTreeGolden walks the whole cobra tree (hidden commands
  included) and records, per command, Use, Aliases, Short, Long, Example,
  group, hidden/deprecated state, runnability and annotations, plus every
  local and persistent flag it defines (name, shorthand, type, default,
  usage, hidden, deprecation, annotations). Output is sorted and rendered
  twice to prove it is deterministic.
- TestCommandHelpGolden runs `bd <cmd> --help` through rootCmd for root,
  create, show, list, update, close, version, versions, config and serve.
  --help returns before the root pre-run, so no store is opened; color
  escapes are stripped. The snapshots are byte-identical to a built bd
  binary's --help output.

Both run from a fresh ordinary (dependency-mode) workspace: a
.beads/metadata.json with no graph marker and no database behind it.

The tree is primed the way the binary is (main()'s help command and its
--all/--doc/--list/--docs-root flags, ExecuteC's completion command), and
cobra's history-dependent pieces (the lazily added per-command --help flag,
the __complete request commands) are excluded, so the result does not
depend on which in-process tests ran first. The help runs reset every flag
afterwards so a later in-process command does not inherit --help.

docs/cli-docs.pin holds check-doc-flags at the v1.2.2 release, so drift on
main is not caught there; these goldens are the live guard. They pin the
cgo build (the !cgo build swaps in a federation stub). Regenerate with
BD_UPDATE_GOLDEN=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cmd/bd): keep the command goldens from merging flags into the shared tree

TestCommandTreeGolden read each command's flags through
LocalNonPersistentFlags, and TestCommandHelpGolden dispatches
`bd serve --help`. Both run cobra's mergePersistentFlags, which copies
every inherited persistent flag (--json, --db, ...) into the command's
own flag set for the rest of the process. TestServeFlags pins serveCmd's
exact flag set, so it failed whenever a golden test ran before it in the
same test binary: tree then serve flags, help then serve flags, and
-test.shuffle seeds 2 and 3, on the PR head and on its merge with main.
CI passes only because bd_test's 16 Bazel shards happen to run them in
different processes. Of 37 candidate tests, TestServeFlags is the only
one affected.

- goldenLocalFlags reads the set LocalNonPersistentFlags reports without
  calling it: c.Flags() minus c's own persistent flags and minus
  inherited copies. Like cobra, it treats a flag as inherited only if it
  is the nearest ancestor's own *pflag.Flag, so copies left by an
  earlier in-process execution are skipped and a flag that shadows an
  inherited one still renders.
- TestCommandTreeGolden fails if rendering changes the number of flags
  in any command's flag set.
- TestCommandHelpGolden calls restoreServeGlobals, which re-registers
  serveCmd's flags after the `bd serve --help` dispatch.

Review minors:
- The regeneration command (doc comment, failure-message constant,
  tree.golden header) sets CGO_ENABLED=1. Without cgo the file does not
  build, so the command matches no test and exits 0.
- enterOrdinaryWorkspaceForGolden calls isolateBeadsDirForTest.
- renderCommandHelpGolden's comment says when the ANSI strip matters.
- cmd/bd/AGENTS.md lists the goldens under "Adding a command" and
  "Guard tests".

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
This commit is contained in:
Julian Knutsen 2026-10-19 05:56:15 +00:00 • committed by GitHub
commit 36f81bab1c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 8738 additions and 0 deletions

View file

@ -38,6 +38,10 @@ Which tier a test belongs in, and which command runs it, is decided by
6. Regenerate the CLI reference with `scripts/generate-cli-docs.sh`;
`scripts/check-cli-docs-drift.sh` fails a PR whose command-surface change
leaves the generated docs stale.
7. Regenerate the command-surface goldens and review the testdata diff:
`BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'`.
`TestCommandTreeGolden` fails on any added, removed or reworded command or
flag until you do.
Prefer a flag on an existing command over a new command, and route
recovery/repair operations to `bd doctor --fix`; see the CLI design principles
@ -85,6 +89,9 @@ no linter enforces it).
or serialize the call under `stdioMutex`.
- `TestCorpusGolden` (`protocol/`) — no unreviewed change to the `--json`
wire shapes.
- `TestCommandTreeGolden` and `TestCommandHelpGolden` — no unreviewed change
to the command tree (every command and flag, hidden ones included) or to
the pinned `--help` output in `testdata/command_tree/`.
Fresh-workspace command fixtures call `isolateBeadsDirForTest(t)` before
setup or dispatch and must not use `t.Parallel()`.

View file

@ -605,6 +605,7 @@ go_test(
"cobra_flag_reset_test.go",
"codex_hook_test.go",
"command_telemetry_test.go",
"command_tree_golden_test.go",
"comment_promote_embedded_test.go",
"comment_proxied_integration_test.go",
"comment_reserved_word_test.go",

View file

@ -0,0 +1,444 @@
//go:build cgo
// cgo only: the goldens pin the cgo build, which every lane that runs this
// package's full suite compiles. The !cgo build replaces the federation
// subtree with a one-command stub (federation_nocgo.go), so its tree differs
// by design.
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"github.com/charmbracelet/x/ansi"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// The committed command-surface goldens. Regenerate after an intentional CLI
// change, then review the diff like code:
//
// BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'
//
// CGO_ENABLED=1 because this file builds only with cgo: with cgo off the
// command matches no test, exits 0 and leaves the goldens as they were.
const (
commandTreeGoldenPath = "testdata/command_tree/tree.golden"
commandHelpGoldenDir = "testdata/command_tree/help"
commandGoldenRegen = "BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'"
)
// commandHelpGoldenArgs is the representative set of commands whose exact
// --help output is pinned, each as the argv after "bd". The tree golden
// covers every command's metadata; these cover the rendering (usage line,
// flag table layout, inherited global flags, root command groups).
var commandHelpGoldenArgs = [][]string{
{},
{"create"},
{"show"},
{"list"},
{"update"},
{"close"},
{"version"},
{"versions"},
{"config"},
{"serve"},
}
// TestCommandTreeGolden pins the whole bd command tree: for every command and
// subcommand, hidden ones included, its Use, Aliases, Short, Long, Example,
// group, hidden/deprecated state, runnability and annotations, and every
// local and persistent flag it defines (name, shorthand, type, default,
// usage, hidden, deprecation, annotations). Any added, removed or reworded
// command or flag fails this test until the golden is regenerated, so the
// change shows up as a reviewed testdata diff. It reads the in-memory tree
// only: no store or subprocess.
//
// docs/cli-docs.pin pins the generated CLI reference (and check-doc-flags)
// to a release, so drift on main is not caught there; this golden is the
// live guard for the command surface.
func TestCommandTreeGolden(t *testing.T) {
pkgDir := enterOrdinaryWorkspaceForGolden(t)
primeCommandTreeForGolden()
flagCounts := commandFlagCounts(rootCmd)
got := renderCommandTreeGolden(rootCmd)
// A renderer that iterated a map would pass on the run that regenerated
// the golden and flake afterwards.
if again := renderCommandTreeGolden(rootCmd); again != got {
t.Fatalf("command tree rendering is not deterministic:\n%s", goldenLineDiff(got, again))
}
// Nor may rendering change the tree it reads: tests sharing this binary
// pin a command's exact flag set (TestServeFlags). See goldenLocalFlags.
if after := commandFlagCounts(rootCmd); after != flagCounts {
t.Fatalf("rendering the command tree added flags to a command's own flag set:\n%s", goldenLineDiff(flagCounts, after))
}
checkCommandGolden(t, pkgDir, commandTreeGoldenPath, got)
}
// TestCommandHelpGolden pins the exact `bd <command> --help` output of a
// representative set of commands, executed in-process through the real root
// command. --help returns before the root pre-run, so no store is opened.
// Color escapes are stripped so the snapshot is independent of terminal
// detection; otherwise the snapshots are byte-identical to what a built bd
// prints.
func TestCommandHelpGolden(t *testing.T) {
pkgDir := enterOrdinaryWorkspaceForGolden(t)
// Parsing `bd serve --help` merges the root's persistent flags into
// serveCmd's own flag set, which TestServeFlags pins; restoreServeGlobals
// re-registers that set afterwards.
restoreServeGlobals(t)
want := map[string]bool{}
for _, args := range commandHelpGoldenArgs {
name := strings.Join(append([]string{"bd"}, args...), "_")
file := name + ".golden"
want[file] = true
t.Run(name, func(t *testing.T) {
checkCommandGolden(t, pkgDir, filepath.Join(commandHelpGoldenDir, file), renderCommandHelpGolden(t, args))
})
}
// The directory holds exactly the listed snapshots: a command dropped
// from the list must not leave a stale file that still looks pinned.
dir := filepath.Join(pkgDir, commandHelpGoldenDir)
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("read %s: %v", commandHelpGoldenDir, err)
}
for _, e := range entries {
if want[e.Name()] {
continue
}
if os.Getenv("BD_UPDATE_GOLDEN") == "1" {
if err := os.Remove(filepath.Join(dir, e.Name())); err != nil {
t.Fatalf("remove stale help golden %s: %v", e.Name(), err)
}
t.Logf("removed stale help golden %s", e.Name())
continue
}
t.Errorf("%s/%s is not in commandHelpGoldenArgs; delete it or regenerate with %s", commandHelpGoldenDir, e.Name(), commandGoldenRegen)
}
}
// enterOrdinaryWorkspaceForGolden moves the test into a fresh ordinary
// (dependency-mode) workspace: a .beads/metadata.json with no graph marker
// and no database behind it, so nothing can be read from or written to a
// store. It returns the package directory, where the goldens live.
func enterOrdinaryWorkspaceForGolden(t *testing.T) string {
t.Helper()
isolateBeadsDirForTest(t)
pkgDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
ws := t.TempDir()
beadsDir := filepath.Join(ws, ".beads")
if err := os.Mkdir(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"dolt"}`), 0o600); err != nil {
t.Fatal(err)
}
t.Chdir(ws)
return pkgDir
}
// primeCommandTreeForGolden completes the tree the way the bd binary does
// before it dispatches: main() adds cobra's help command and its
// --all/--doc/--list/--docs-root flags, and ExecuteC adds the completion
// command. All three are idempotent, so the tree is the same whether or not
// an earlier in-process test already executed rootCmd.
func primeCommandTreeForGolden() {
rootCmd.InitDefaultHelpCmd()
registerHelpAllFlag()
rootCmd.InitDefaultCompletionCmd()
}
// renderCommandTreeGolden walks cmd's tree depth first, children sorted by
// name, and renders one block per command.
func renderCommandTreeGolden(root *cobra.Command) string {
var b strings.Builder
b.WriteString("# bd command tree (cgo build), pinned by TestCommandTreeGolden.\n")
b.WriteString("# Regenerate after an intentional CLI change:\n")
b.WriteString("# " + commandGoldenRegen + "\n")
var walk func(*cobra.Command)
walk = func(c *cobra.Command) {
writeCommandGoldenBlock(&b, c)
children := append([]*cobra.Command(nil), c.Commands()...)
sort.Slice(children, func(i, j int) bool { return children[i].Name() < children[j].Name() })
for _, sub := range children {
// cobra adds the hidden shell-completion request commands only
// for an execution that invokes them, and then never removes
// them: whether they are present depends on test history, not
// on the bd surface.
if sub.Name() == cobra.ShellCompRequestCmd || sub.Name() == cobra.ShellCompNoDescRequestCmd {
continue
}
walk(sub)
}
}
walk(root)
return b.String()
}
func writeCommandGoldenBlock(b *strings.Builder, c *cobra.Command) {
fmt.Fprintf(b, "\n%s\n", c.CommandPath())
fmt.Fprintf(b, " use: %q\n", c.Use)
if len(c.Aliases) > 0 {
fmt.Fprintf(b, " aliases: %q\n", c.Aliases)
}
fmt.Fprintf(b, " short: %q\n", c.Short)
if c.GroupID != "" {
fmt.Fprintf(b, " group: %q\n", c.GroupID)
}
fmt.Fprintf(b, " hidden: %t\n", c.Hidden)
if c.Deprecated != "" {
fmt.Fprintf(b, " deprecated: %q\n", c.Deprecated)
}
fmt.Fprintf(b, " runnable: %t\n", c.Runnable())
if c.DisableFlagParsing {
b.WriteString(" disable-flag-parsing: true\n")
}
if len(c.ValidArgs) > 0 {
fmt.Fprintf(b, " valid-args: %q\n", c.ValidArgs)
}
if len(c.Annotations) > 0 {
fmt.Fprintf(b, " annotations: %s\n", formatGoldenAnnotations(c.Annotations))
}
writeGoldenTextBlock(b, "long", c.Long)
writeGoldenTextBlock(b, "example", c.Example)
for _, line := range commandGoldenFlagLines(c.PersistentFlags()) {
fmt.Fprintf(b, " persistent-flag %s\n", line)
}
for _, line := range commandGoldenFlagLines(goldenLocalFlags(c)) {
fmt.Fprintf(b, " flag %s\n", line)
}
}
// goldenLocalFlags returns the non-persistent flags c registers itself,
// including any that shadow an inherited flag: the set
// c.LocalNonPersistentFlags() reports, read without calling it. That
// accessor, like LocalFlags and InheritedFlags, runs cobra's
// mergePersistentFlags, which copies every inherited persistent flag into
// c.Flags() for the rest of the process. Over the whole tree that would leave
// `bd serve` carrying the root's --json, --db and the rest, and break
// TestServeFlags (see TestNoSubcommandShadowsRootJSONFlag).
//
// c.Flags() may already hold such copies from an earlier in-process
// execution. They are recognized by identity, the way cobra itself tells
// them apart: an inherited flag is the nearest ancestor's own *pflag.Flag of
// that name, and a shadowing flag is a different one.
func goldenLocalFlags(c *cobra.Command) *pflag.FlagSet {
local := pflag.NewFlagSet(c.Name(), pflag.ContinueOnError)
c.Flags().VisitAll(func(f *pflag.Flag) {
if c.PersistentFlags().Lookup(f.Name) != nil {
return // rendered as a persistent-flag line
}
for p := c.Parent(); p != nil; p = p.Parent() {
if inherited := p.PersistentFlags().Lookup(f.Name); inherited != nil {
if inherited == f {
return
}
break
}
}
local.AddFlag(f)
})
return local
}
// commandFlagCounts renders how many flags each command's own flag set holds,
// one line per command, read without merging anything into it.
func commandFlagCounts(root *cobra.Command) string {
var b strings.Builder
var walk func(*cobra.Command)
walk = func(c *cobra.Command) {
n := 0
c.Flags().VisitAll(func(*pflag.Flag) { n++ })
fmt.Fprintf(&b, "%s %d\n", c.CommandPath(), n)
for _, sub := range c.Commands() {
walk(sub)
}
}
walk(root)
return b.String()
}
// writeGoldenTextBlock writes a multi-line field one source line per golden
// line, behind a "|" gutter so leading whitespace and blank lines survive.
func writeGoldenTextBlock(b *strings.Builder, name, text string) {
if text == "" {
return
}
fmt.Fprintf(b, " %s:\n", name)
for _, line := range strings.Split(text, "\n") {
if line == "" {
b.WriteString(" |\n")
continue
}
fmt.Fprintf(b, " | %s\n", line)
}
}
// commandGoldenFlagLines renders each flag of fs on one line, sorted by name.
// cobra's own lazily added --help flag (FlagSetByCobraAnnotation) is skipped:
// it exists only on commands an earlier in-process execution reached.
func commandGoldenFlagLines(fs *pflag.FlagSet) []string {
var flags []*pflag.Flag
fs.VisitAll(func(f *pflag.Flag) {
if _, byCobra := f.Annotations[cobra.FlagSetByCobraAnnotation]; byCobra {
return
}
flags = append(flags, f)
})
sort.Slice(flags, func(i, j int) bool { return flags[i].Name < flags[j].Name })
lines := make([]string, 0, len(flags))
for _, f := range flags {
var b strings.Builder
fmt.Fprintf(&b, "--%s", f.Name)
if f.Shorthand != "" {
fmt.Fprintf(&b, " -%s", f.Shorthand)
}
fmt.Fprintf(&b, " type=%s default=%q", f.Value.Type(), f.DefValue)
if f.NoOptDefVal != "" && !implicitNoOptDefault(f) {
fmt.Fprintf(&b, " no-opt-default=%q", f.NoOptDefVal)
}
if f.Hidden {
b.WriteString(" hidden")
}
if f.Deprecated != "" {
fmt.Fprintf(&b, " deprecated=%q", f.Deprecated)
}
if f.ShorthandDeprecated != "" {
fmt.Fprintf(&b, " shorthand-deprecated=%q", f.ShorthandDeprecated)
}
if len(f.Annotations) > 0 {
fmt.Fprintf(&b, " annotations=%s", formatGoldenAnnotations(f.Annotations))
}
fmt.Fprintf(&b, " usage=%q", f.Usage)
lines = append(lines, b.String())
}
return lines
}
// implicitNoOptDefault reports whether f's NoOptDefVal is the one pflag gives
// every flag of its type (a bare --bool means true, a bare --count adds one),
// which would only repeat the type on each line.
func implicitNoOptDefault(f *pflag.Flag) bool {
switch f.Value.Type() {
case "bool":
return f.NoOptDefVal == "true"
case "count":
return f.NoOptDefVal == "+1"
}
return false
}
// formatGoldenAnnotations renders a command's or a flag's annotations sorted
// by key.
func formatGoldenAnnotations[V string | []string](m map[string]V) string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%s=%q", k, m[k]))
}
return "{" + strings.Join(parts, " ") + "}"
}
// renderCommandHelpGolden runs `bd <args> --help` through rootCmd in-process
// and returns its stdout with color escapes stripped. cobra keeps the parsed
// --help value on the shared tree, so every flag is put back afterwards: a
// later in-process `bd create ...` must not print help instead.
//
// internal/ui decides color once, at init, from CLICOLOR_FORCE and whether the
// test binary's stdout is a terminal. CI never gives it one, so there the
// strip removes nothing; it is what keeps a run from a terminal matching the
// goldens.
func renderCommandHelpGolden(t *testing.T, args []string) string {
t.Helper()
argv := append(append([]string(nil), args...), "--help")
primeCommandTreeForGolden()
var execErr error
out := captureStdout(t, func() error {
rootCmd.SetArgs(argv)
defer rootCmd.SetArgs(nil)
defer resetCommandFlags(rootCmd)
_, execErr = rootCmd.ExecuteC()
return nil
})
if execErr != nil {
t.Fatalf("bd %s: %v", strings.Join(argv, " "), execErr)
}
return ansi.Strip(out)
}
// checkCommandGolden compares got with the golden at rel under pkgDir, or
// rewrites the golden when BD_UPDATE_GOLDEN=1 (the package's shared golden
// switch).
func checkCommandGolden(t *testing.T, pkgDir, rel, got string) {
t.Helper()
path := filepath.Join(pkgDir, rel)
if os.Getenv("BD_UPDATE_GOLDEN") == "1" {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("mkdir %s: %v", filepath.Dir(rel), err)
}
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatalf("write golden %s: %v", rel, err)
}
t.Logf("updated golden %s", rel)
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read golden %s (regenerate with %s): %v", rel, commandGoldenRegen, err)
}
if bytes.Equal([]byte(got), want) {
return
}
t.Errorf("bd command surface drifted from %s.\n%s\nIf the change is intended, regenerate with\n %s\nand review the testdata diff.",
rel, goldenLineDiff(string(want), got), commandGoldenRegen)
}
// goldenLineDiff reports the region where want and got differ: the common
// leading and trailing lines are trimmed and the rest is shown as -/+ lines,
// capped so a large drift stays readable (the reviewed artifact is the
// regenerated testdata diff, not this message).
func goldenLineDiff(want, got string) string {
const maxLines = 40
w := strings.Split(want, "\n")
g := strings.Split(got, "\n")
pre := 0
for pre < len(w) && pre < len(g) && w[pre] == g[pre] {
pre++
}
suf := 0
for suf < len(w)-pre && suf < len(g)-pre && w[len(w)-1-suf] == g[len(g)-1-suf] {
suf++
}
var b strings.Builder
fmt.Fprintf(&b, "first difference at line %d:\n", pre+1)
write := func(sign string, lines []string) {
for i, line := range lines {
if i == maxLines {
fmt.Fprintf(&b, "%s ... (%d more lines)\n", sign, len(lines)-maxLines)
return
}
fmt.Fprintf(&b, "%s %s\n", sign, line)
}
}
write("-", w[pre:len(w)-suf])
write("+", g[pre:len(g)-suf])
return b.String()
}

View file

@ -0,0 +1,163 @@
Issues chained together like beads. A lightweight issue tracker with first-class dependency support.
Usage:
bd [flags]
bd [command]
Working With Issues:
assign Assign an issue to someone
children List child beads of a parent
close Close one or more issues
comment Add a comment to an issue
comments View or manage comments on an issue
create Create a new issue (or batch from markdown/graph JSON)
create-form Create a new issue using an interactive form
delete Delete one or more issues and clean up references
edit Edit an issue field in $EDITOR
gate Manage async coordination gates
heartbeat Refresh the lease on an issue you hold in_progress
label Manage issue labels
link Link two issues with a dependency
list List issues
merge-slot Manage merge-slot gates for serialized conflict resolution
note Append a note to an issue
priority Set the priority of an issue
promote Promote a wisp to a permanent bead
provenance Append-only provenance event log
q Quick capture: create issue and output only ID
query Query issues using a simple query language
reclaim Revert stale-lease in_progress issues back to ready (dead-worker recovery)
reopen Reopen one or more closed issues
search Search issues by text query
set-state Set operational state (creates event + updates label)
show Show issue details
state Query the current value of a state dimension
tag Add a label to an issue
todo Manage TODO items (convenience wrapper for task issues)
unclaim Release a claimed issue
update Update one or more issues
Views & Reports:
count Count issues matching filters
diff Show changes between two commits or branches
find-duplicates Find semantically similar issues using text analysis or AI
history Show version history for an issue
lint Check issues for missing template sections
stale Show stale issues (not updated recently)
status Show issue database overview and statistics
statuses List valid issue statuses
types List valid issue types
versions List the recorded versions of a bead
Dependencies & Structure:
dep Manage dependencies
duplicate Mark an issue as a duplicate of another
duplicates Find and optionally merge duplicate issues
epic Epic management commands
graph Display issue dependency graph
supersede Mark an issue as superseded by a replacement issue
swarm Swarm management for structured epics
Sync & Data:
backup Back up your beads database
branch List or create branches
conflicts Inspect and resolve live merge conflicts
export Export issues to JSONL format
federation Manage peer-to-peer federation with other workspaces
import Import issues from a JSONL file or stdin into the database
restore Restore the pre-compaction content of a compacted issue
sync Pull, check for conflicts, repair is_blocked, and push (the federation loop)
vc Version control operations
Setup & Configuration:
bootstrap Non-destructive database setup for fresh clones and recovery
config Manage configuration settings
connect Attach this workspace to a remote bd serve over HTTP
context Show effective backend identity and repository context
dolt Configure Dolt database settings
forget Remove a persistent memory
hooks Manage git hooks for beads integration
human Show essential commands for human users
info Show database information
init Initialize bd in the current directory
kv Key-value store commands
memories List or search persistent memories
migrate-personal Move personal planning issues from the project database to your planning repo
onboard Display minimal snippet for agent instructions file
prime Output AI-optimized workflow context
quickstart Quick start guide for bd
recall Retrieve a specific memory
remember Store a persistent memory
setup Setup integration with AI editors
where Show active beads location
Maintenance:
batch Run multiple write operations in a single database transaction
compact Squash old Dolt commits to reduce history size
doctor Check and fix beads installation health (start here)
events Read and manage the durable events journal
flatten Squash all Dolt history into a single commit
gc Garbage collect: decay old issues, compact Dolt commits, run Dolt GC
migrate Database migration commands
ping Check database connectivity
preflight Show PR readiness checklist
prune Delete old closed beads to reclaim space and shrink exports
purge Delete closed ephemeral beads to reclaim space
recompute-blocked Recompute is_blocked for all issues (repairs stale flags after a pull)
rename-prefix Rename the issue prefix for all issues in the database
rules Audit and compact Claude rules
sql Execute raw SQL against the beads database
upgrade Check and manage bd version upgrades
worktree Manage git worktrees for parallel development
Integrations & Advanced:
admin Administrative commands for database maintenance
jira Jira integration commands
linear Linear integration commands
repo Manage multiple repository configuration
Additional Commands:
ado Azure DevOps integration commands
audit Record and label agent interactions (append-only JSONL)
blocked Show blocked issues
completion Generate the autocompletion script for the specified shell
cook Compile a formula into a proto (ephemeral by default)
defer Defer one or more issues for later
formula Manage workflow formulas
github GitHub integration commands
gitlab GitLab integration commands
help Help about any command
init-safety Explain bd init flag semantics and the destroy-token format
mail Delegate to mail provider (e.g., gt mail)
metrics Show or change anonymous usage-metrics settings
mol Molecule commands (work templates)
notion Notion integration commands
orphans Identify orphaned issues (referenced in commits but still open)
ready Show ready work (open, no active blockers)
rename Rename an issue ID
schema Print the JSON Schema for bd's --json / export output
serve Serve the beads HTTP API over loopback
ship Publish a capability for cross-project dependencies
undefer Undefer one or more issues (restore to open)
version Print version information
Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
-h, --help help for bd
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output
-V, --version Print version information
Use "bd [command] --help" for more information about a command.

View file

@ -0,0 +1,57 @@
Close one or more issues.
If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation). This fallback only applies in
interactive sessions (stdin is a terminal); in scripts and agent sessions a
missing ID is an error, so a command built from an empty variable cannot
silently close an unrelated issue. Set BD_LAST_TOUCHED_FALLBACK=1 to allow
the fallback anywhere, or =0 to disable it entirely.
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.
Closing a molecule's last open step also closes the molecule's root, with
the reason "all steps complete", when the root is a poured molecule, a wisp,
or an epic labeled "template"; any other epic stays open as close-eligible
work. A root that would refuse its own close (an open blocker, a pin, another
assignee) stays open with a warning, and the step's close stands. Under
--json, the step's entry names the closed root (auto_closed_molecule) or the
refusal (molecule_auto_close_refusal). --continue claims the next ready step
in the molecule for you; add --no-auto to only show it.
Usage:
bd close [id...] [flags]
Aliases:
close, done
Flags:
--claim-next Automatically claim the next highest priority available issue
--continue Auto-advance to next step in molecule
-f, --force Force close pinned issues or unsatisfied gates
-h, --help help for close
--if-revision bd show --json Apply the write only if the issue's current revision equals this value (the decimal int64 from bd show --json's "revision" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures).
--no-auto With --continue, show next step but don't claim it
-r, --reason string Reason for closing
--reason-file string Read close reason from file (use - for stdin)
--session string Claude Code session ID (or set CLAUDE_SESSION_ID env var)
--suggest-next Show newly unblocked issues after closing
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output

View file

@ -0,0 +1,122 @@
Manage configuration settings for external integrations and preferences.
Configuration is stored per-project in the beads database and is version-control-friendly.
Common namespaces:
- export.* Auto-export settings (stored in config.yaml)
- import.* JSONL import settings (stored in config.yaml)
- jira.* Jira integration settings
- linear.* Linear integration settings
- github.* GitHub integration settings
- gitlab.* GitLab integration settings
- ado.* Azure DevOps integration settings
- notion.* Notion integration settings
- custom.* Custom integration settings
- status.* Issue status configuration
- claim.* Claim arbitration settings (pool-aware claiming)
- doctor.suppress.* Suppress specific bd doctor warnings (GH#1095)
- lint.* Additional per-type lint sections (stored in config.yaml)
Auto-Export (config.yaml):
Optional JSONL export to .beads/issues.jsonl after write commands (throttled).
Useful for viewers (bv), interchange, and issue-level migration; not a backup.
It is not cross-machine sync; use bd dolt push/pull with a Dolt remote.
Disabled by default. Enable only for integrations that need fresh JSONL.
Auto-staging is separate and disabled by default.
Keys:
export.auto Enable/disable auto-export (default: false)
export.path Output filename relative to .beads/ (default: issues.jsonl)
export.interval Minimum time between exports (default: 60s)
export.git-add Auto-stage the export file (default: false)
Auto-Import (config.yaml):
Reads .beads/issues.jsonl by default when a JSONL import path is implied.
Use a relative filename/path so the import stays within the project .beads/
directory and remains portable across machines.
Keys:
import.path Input filename relative to .beads/ (default: issues.jsonl)
Custom Status States:
You can define custom status states for multi-step pipelines using the
status.custom config key. Statuses should be comma-separated.
Example:
bd config set status.custom "awaiting_review,awaiting_testing,awaiting_docs"
This enables issues to use statuses like 'awaiting_review' in addition to
the built-in statuses (open, in_progress, blocked, deferred, closed).
Claim Pools:
A dispatcher can pre-assign issues to a pool pseudo-assignee (e.g.
"fable-crew") and let any actor take them with --claim. List the pool
aliases in the claim.pools config key, comma-separated:
bd config set claim.pools "fable-crew,night-crew"
Issues assigned to a real actor (or to an alias not in the list) keep
their anti-steal protection. Pool takes carry the normal lease; note
that if a taker's lease expires, bd reclaim returns the issue to the
unassigned pool, not to the pool alias it was dispatched to.
Suppressing Doctor Warnings:
Suppress specific bd doctor warnings by check name slug:
bd config set doctor.suppress.pending-migrations true
bd config set doctor.suppress.git-hooks true
Check names are converted to slugs: "Git Hooks" → "git-hooks".
Only warnings are suppressed (errors and passing checks always show).
To unsuppress: bd config unset doctor.suppress.<slug>
Examples:
bd config set export.auto true # Enable auto-export for viewer integrations
bd config set export.path "beads.jsonl" # Custom export filename
bd config set import.path "beads.jsonl" # Custom import filename
bd config set export.git-add true # Also stage the export file
bd config set jira.url "https://company.atlassian.net"
bd config set jira.project "PROJ"
bd config set status.custom "awaiting_review,awaiting_testing"
bd config set claim.pools "fable-crew,night-crew" # Pool aliases claimable by any actor
bd config set doctor.suppress.pending-migrations true
bd config set dolt.debug true # Enable Dolt sql-server debug mode (loglevel=debug, --prof cpu)
bd config set dolt.local-only true # Skip wiring a Dolt sync remote during bd init
bd config set lint.sections.epic "Standards scorecard, Cost" # Extra sections bd lint requires for epics
bd config get export.auto
bd config list
bd config unset jira.url
Usage:
bd config [command]
Available Commands:
apply Reconcile system state to match configuration
drift Detect config-vs-reality inconsistencies
get Get a configuration value
list List all configuration
set Set a configuration value
set-many Set multiple configuration values in one operation
show Show all effective configuration with provenance
unset Delete a configuration value
validate Validate sync-related configuration
Flags:
-h, --help help for config
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output
Use "bd config [command] --help" for more information about a command.

View file

@ -0,0 +1,72 @@
Create a new issue (or batch from markdown/graph JSON)
Usage:
bd create [title] [flags]
Aliases:
create, new
Flags:
--acceptance string Acceptance criteria
--allow-empty-description Allow empty description input from stdin or file
--append-notes string Append to existing notes (with newline separator)
-a, --assignee string Assignee
--body-file string Read description from file (use - for stdin)
--context string Additional context for the issue
--defer string Defer until date (issue hidden from bd ready until then). Same formats as --due
--deps strings Dependencies as 'type:id' or bare 'id'. Bare 'id', 'depends-on:id', and 'blocked-by:id' all make THIS issue depend on id; 'blocks:id' reverses direction (id depends on this issue). E.g. 'blocked-by:bd-20,discovered-from:bd-15'
-d, --description string Issue description
--design string Design notes
--design-file string Read design from file (use - for stdin)
--dry-run Preview what would be created without actually creating
--due string Due date/time. Formats: +6h, +1d, +2w, tomorrow, next monday, 2025-01-15
--ephemeral Create as ephemeral (short-lived, subject to TTL compaction)
-e, --estimate int Time estimate in minutes (e.g., 60 for 1 hour)
--event-actor string Entity URI who caused this event (requires --type=event)
--event-category string Event category (e.g., patrol.muted, agent.started) (requires --type=event)
--event-payload string Event-specific JSON data (requires --type=event)
--event-target string Entity URI or bead ID affected (requires --type=event)
--external-ref string External reference (e.g., 'gh-9', 'jira-ABC', Linear URL)
-f, --file string Create one issue per ## heading (### fields attach to that issue); for title plus description-from-file, use --body-file
--force Force creation even if prefix doesn't match database prefix
--graph string Create a graph of issues with dependencies from JSON plan file
-h, --help help for create
--id string Explicit issue ID (e.g., 'bd-42' for partitioning)
-l, --labels strings Labels (comma-separated)
--metadata string Set custom metadata (JSON object, or @file.json to read from file)
--mol-type string Molecule type: swarm (multi-agent), patrol (recurring ops), work (default)
--no-history Skip Dolt commit history without making GC-eligible (for permanent agent beads)
--no-inherit-labels Don't inherit labels from parent issue
--notes string Notes
--parent string Parent issue ID for hierarchical child (e.g., 'bd-a3f8e9')
-p, --priority string Priority (0-4 or P0-P4, 0=highest) (default "2")
--repo string Target repository for issue (overrides auto-routing)
--silent Output only the issue ID (for scripting)
--skills string Required skills for this issue
--spec-id string Link to specification document
-s, --status string Initial status
--stdin Read description from stdin (alias for --body-file -)
--storage-class string Storage class: versioned, unversioned, or ephemeral (default: storage-class.<type> config, else versioned)
--title string Issue title (alternative to positional argument)
-t, --type string Issue type (bug|feature|task|epic|chore|decision|spike|story|milestone); custom types require types.custom config; aliases: enhancement/feat→feature, dec/adr→decision (default "task")
--validate Validate description contains required sections for issue type
--waits-for string Spawner issue ID to wait for (creates waits-for dependency for fanout gate)
--waits-for-gate string Gate type: all-children (wait for all) or any-children (wait for first) (default "all-children")
--wisp-type string Wisp type for TTL-based compaction: heartbeat, ping, patrol, gc_report, recovery, error, escalation
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output

View file

@ -0,0 +1,89 @@
List issues
Usage:
bd list [flags]
Flags:
--all Show all issues including closed (overrides default filter)
-a, --assignee string Filter by assignee
--brief Omit the free-form text (description, design, acceptance criteria, notes, payload, waiters) from each row. Filters that read those fields, such as --desc-contains, still select on them. An omitted field is indistinguishable from an empty one in --json; fetch a whole issue with bd show.
--closed-after string Filter issues closed after date (YYYY-MM-DD or RFC3339)
--closed-before string Filter issues closed before date (YYYY-MM-DD or RFC3339)
--created-after string Filter issues created after date (YYYY-MM-DD or RFC3339)
--created-before string Filter issues created before date (YYYY-MM-DD or RFC3339)
--defer-after string Filter issues deferred after date (supports relative: +6h, tomorrow)
--defer-before string Filter issues deferred before date (supports relative: +6h, tomorrow)
--deferred Show only issues with defer_until set
--deps string[="scheduling"] Annotate tree with dependency edges and order siblings by them: 'scheduling' (bare --deps) or 'all'
--desc-contains string Filter by description substring (case-insensitive)
--due-after string Filter issues due after date (supports relative: +6h, tomorrow)
--due-before string Filter issues due before date (supports relative: +6h, tomorrow)
--empty-description Filter issues with empty or missing description
--exclude-label strings Exclude issues that have ANY of these labels
--exclude-type strings Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic)
--external-contains string Filter by external ref substring (case-insensitive)
--external-ref string Filter by exact external_ref value
--flat Disable tree format and use legacy flat list output
--format string Export the dependency graph of the listed issues: 'digraph' (edge list for golang.org/x/tools/cmd/digraph), 'dot' (Graphviz), or a Go template rendered once per edge over .IssueID, .DependsOnID, .Type, .Issue, .Dependency. 'json' is the exception and does not export the graph: it is equivalent to --json, which also wins when both flags are given. 'digraph' and templates print nothing when no listed issue depends on another; 'dot' still prints the nodes
--has-metadata-key string Filter issues that have this metadata key set
-h, --help help for list
--id string Filter by specific issue IDs (comma-separated or repeated, e.g., bd-1,bd-5,bd-10)
--include-comments Populate each row's comments field with full comment bodies in JSON output (--json only; costs one query per row that has comments). Without it, a row with comments carries comments_omitted=true, so an absent comments field is never mistaken for having none. Text output is unaffected either way.
--include-ephemeral Include ephemeral wisp-plane rows in output (normally hidden)
--include-gates Include gate issues in output (normally hidden)
--include-infra Include infrastructure beads (agent/role/message) in output
--include-templates Include template molecules in output
-l, --label strings Filter by labels (AND: must have ALL). Can combine with --label-any
--label-any strings Filter by labels (OR: must have AT LEAST ONE). Can combine with --label
--label-pattern string Filter by label glob pattern (e.g., 'tech-*' matches tech-debt, tech-legacy)
--label-regex string Filter by label regex pattern (e.g., 'tech-(debt|legacy)')
-n, --limit int Limit results (an explicit --limit always wins, 0 meaning unlimited; otherwise --all is unlimited; otherwise a configured list.limit applies; otherwise unlimited when piped, else 20 in agent mode at a terminal, else 50) (default 50)
--long Show detailed multi-line output for each issue
--max-rows int Hard upper bound on rows returned. Returns a non-zero exit (code 2) and an error to stderr if exceeded. 0 disables (the default). Overrides BEADS_MAX_ROWS for this invocation. Useful in CI/agent rigs that want a circuit breaker against pathological queries. Honored on both the direct and the --proxied-server route.
--metadata-field stringArray Filter by metadata field (key=value, repeatable)
--mol-type string Filter by molecule type: swarm, patrol, or work
--no-assignee Filter issues with no assignee
--no-labels Filter issues with no labels
--no-pager Disable pager output
--no-parent Exclude child issues (show only top-level issues)
--no-pinned Exclude pinned issues
--notes-contains string Filter by notes substring (case-insensitive)
--offset int Skip the first N matching results (0-based). Only supported under --proxied-server.
--overdue Show only issues with due_at in the past (not closed)
--parent string Filter by parent issue ID (shows children of specified issue)
--pinned Show only pinned issues
--pretty Display issues in a tree format with status/priority symbols
-p, --priority string Priority (0-4 or P0-P4, 0=highest)
--priority-max string Filter by maximum priority (inclusive, 0-4 or P0-P4)
--priority-min string Filter by minimum priority (inclusive, 0-4 or P0-P4)
--ready Show only ready issues (no active blockers, same semantics as bd ready)
-r, --reverse Invert the sort field's default direction (created/updated/closed default to newest-first, so --sort updated --reverse is oldest-first)
--skip-labels Skip label hydration. The labels field in output will be empty regardless of actual labels. Use only when the caller does not depend on label data. Cannot combine with --label, --label-any, --label-pattern, --label-regex, --exclude-label, or --no-labels.
--sort string Sort by field: priority, created, updated, closed, status, id, title, type, assignee
--spec string Filter by spec_id prefix
-s, --status string Filter by stored status (open, in_progress, blocked, deferred, closed). Comma-separated or repeated for multiple: --status open,in_progress
--title string Filter by title text (case-insensitive substring match)
--title-contains string Filter by title substring (case-insensitive)
--tree Hierarchical tree format (default: true; use --flat to disable) (default true)
-t, --type string Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate, convoy). Aliases: mr→merge-request, feat→feature, mol→molecule, dec/adr→decision
--updated-after string Filter issues updated after date (YYYY-MM-DD or RFC3339)
--updated-before string Filter issues updated before date (YYYY-MM-DD or RFC3339)
-w, --watch Watch for changes and auto-update display (implies --pretty)
--wisp-type string Filter by wisp type: heartbeat, ping, patrol, gc_report, recovery, error, escalation
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output

View file

@ -0,0 +1,119 @@
Serve the beads HTTP API — the same work surface the CLI answers, for
automation clients that would otherwise fork a bd subprocess per call.
The wire contract is described by an OpenAPI document (/v0); GET
/v0/beads/context reports which operations this build actually implements.
DEPLOYMENT
Pass an explicit port. The default 127.0.0.1:0 takes an ephemeral one, which
is right for ad-hoc and test use — where the bound address printed on stdout
is read immediately — but carries no mutual exclusion: two serves against one
workspace then run side by side on different ports with no way to enumerate
them. On a fixed port the second one fails to bind, which is the intended
behavior. Concurrent serves are data-safe either way; claims are arbitrated
in the SQL server.
Run it under a supervisor. bd shuts down gracefully on SIGHUP as well as
SIGINT and SIGTERM, so closing the terminal of a foreground bd serve stops it.
PROBES
GET /healthz is LIVENESS only: it answers from the process and never touches
the database, so it stays green while the database is unreachable. For
readiness use GET /v0/beads/ready?limit=1 — a real query, where 200 means
ready and 503 means live but not ready.
AUTHENTICATION
Optional, and off by default on loopback — where the trust model is the
loopback boundary itself, the same one the database behind it already relies
on. --auth-token-file turns it on: every operation except GET /healthz then
requires an "Authorization: Bearer <token>" header, GET /v0/beads/context
included, because it reports the repo root, beads directory and database name.
The file holds ONE TOKEN PER LINE and every line is accepted. That is the
rotation mechanism: write the new token alongside the old, roll the clients
over, then delete the old line. The file is re-read while the server runs, so
both the addition and the removal take effect within about a second and
neither needs a restart. Write it atomically (a temp file plus rename; a
Kubernetes secret mount already does this).
There is deliberately no --auth-token flag. A credential passed as an
argument is readable by every local user in the process listing.
--allow-non-loopback REQUIRES a token file. Beyond loopback, reaching the
address would otherwise be the whole authorization: any peer could read every
issue and claim work as any actor. --insecure-no-auth is the explicit,
auditable way to say you meant that anyway.
The Host allowlist is what a service deployment usually trips over first. The
DNS-rebinding check answers only to loopback spellings and the bind address,
so a client dialing a service name gets 400 on every request; enumerate the
names it dials with --allowed-host (repeatable). Matching is exact — no
wildcards — and the startup log line prints the effective allowlist.
WHAT THIS DOES NOT DO
No TLS. Even with a token, the credential and every issue body travel in
plaintext, so a deployment beyond loopback has to supply confidentiality
itself — a service mesh, or a network boundary you already trust.
Hooks do not fire. A hook is a user-controlled subprocess per mutation: in a
concurrent server that is an unbounded latency multiplier and an orphaned
child at shutdown, and its working-directory-derived hook lookup is
meaningless in a server process. A CLI claim runs on_update; an HTTP claim
does not.
The per-command auto-commit machinery does not run. Durability is per request:
a successful claim commits inside its own transaction, exactly as a proxied
CLI claim does today.
An actor on an HTTP request is caller-asserted provenance for the audit trail,
not authenticated identity — the same thing it has always been on the CLI,
where any local process can pass any --actor.
It does not run under --readonly, and refuses to start rather than binding.
Every server it binds publishes the issue-claim operation, and the capability
set it advertises is a property of the build rather than of the flags on the
process that started it — so a read-only server would advertise a write it
could never land.
DESTRUCTIVE OPERATIONS
POST /v0/beads/issues:sweep deletes closed beads in bulk — the operation
behind bd purge and bd prune — and nothing it deletes comes back. It shares
the library surface those commands call, so it inherits their guards: pinned
beads are never swept, and a durable sweep with neither a cutoff nor an id
pattern is refused rather than clearing every closed bead in the workspace.
Combined with the trust model above, that means anyone who can reach this
address can erase closed work; bind it accordingly.
Usage:
bd serve [flags]
Flags:
--addr string Address to bind as IP:PORT; the host must be a numeric IP literal, and port 0 takes an ephemeral port (default "127.0.0.1:0")
--allow-non-loopback Permit a bind beyond loopback. Requires --auth-token-file, since reaching the address would otherwise be the whole authorization
--allowed-host stringArray Additional Host header value to answer to, e.g. a service DNS name. Repeatable; matched exactly, with no wildcards
--auth-token-file string Require an Authorization: Bearer token from this file, one token per line, all accepted. Re-read while running, so rewriting it rotates tokens without a restart (env BEADS_SERVE_TOKEN_FILE)
-h, --help help for serve
--insecure-no-auth Serve a non-loopback bind with NO authentication. Every peer that can reach the address gets full read and claim access
--large-apply-ceiling duration Whole-run budget for a POST issues:batchApply request over 100 items (a ceiling, not a target; requests at or under 100 items are unaffected). Must be positive. The orchestrator's stop grace must be at least this long plus 5s, or an external SIGKILL can cut off an in-flight large apply a graceful drain would otherwise have waited out; see engdocs/SERVE_RUNBOOK.md (default 5m0s)
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output

View file

@ -0,0 +1,41 @@
Show issue details
Usage:
bd show [id...] [--id=<id>...] [--current] [flags]
Aliases:
show, view
Flags:
--as-of string Show issue as it existed at a specific commit hash or branch (requires Dolt; commit hashes must be the full 32-character hash from 'bd history', not a prefix)
--brief-deps Reduce each dependency to its identity fields in JSON output (--json only; drops description, design, notes and acceptance criteria)
--children Show only the children of this issue
--comments-tail int Render only the last N comments in text output, preceded by one elision line naming how many older ones were hidden (text output only; 0, the default, renders every comment unchanged; N must be >= 0)
--current Show the currently active issue (in-progress, hooked, or last touched)
-h, --help help for show
--id stringArray Issue ID (use for IDs that look like flags, e.g., --id=gt--xyz)
--include-comments Stream full comment bodies in JSON output (--json only; may be slow on issues with many comments). Without it the comments field is absent entirely, not truncated: an issue with comments carries comment_count and comments_omitted=true, so check those before reading an absent comments field as none.
--include-dependents Stream full dependent issues in JSON output (--json only; may be slow on hub beads)
--local-time Show timestamps in local time instead of UTC (date-only fields are always local)
--long Show all available fields (extended metadata, agent identity, gate fields, etc.)
--refs Show issues that reference this issue (reverse lookup)
--short Show compact one-line output per issue
--thread Show full conversation thread (for messages)
-w, --watch Watch for changes and auto-refresh display
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output

View file

@ -0,0 +1,78 @@
Update one or more issues.
If no issue ID is provided, updates the last touched issue (from most recent
create, update, show, or close operation). This fallback only applies in
interactive sessions (stdin is a terminal); in scripts and agent sessions a
missing ID is an error, so a command built from an empty variable cannot
silently mutate an unrelated issue. Set BD_LAST_TOUCHED_FALLBACK=1 to allow
the fallback anywhere, or =0 to disable it entirely.
Updates are applied per issue ID, not atomically across IDs: when some IDs
fail, the remaining issues are still updated, every failed ID is reported on
stderr, and the command exits nonzero.
Exit codes: 1 for general failures; 13 when every failure is a stale
--if-assignee/--if-status guard (the precondition no longer held, nothing was
written — another actor won the race, so retrying the same guard is
pointless).
Usage:
bd update [id...] [flags]
Flags:
--acceptance string Acceptance criteria
-l, --add-label strings Add labels (repeatable); -l matches bd create -l
--allow-empty-description Allow empty description replacement when reading from stdin or file
--append-notes string Append to existing notes (with newline separator)
-a, --assignee string Assignee
--await-id string Set gate await_id (e.g., GitHub run ID for gh:run gates)
--body-file string Read description from file (use - for stdin)
--claim Atomically claim the issue (sets assignee to you, status to in_progress; idempotent if already claimed by you; issues assigned to a pool alias listed in the claim.pools config are claimable too)
--clear-notes Clear the notes field (--notes "" is refused: an empty value is usually a dead command substitution)
--defer string Defer until date (empty to clear). Issue hidden from bd ready until then, then auto-wakes to open
-d, --description string Issue description
--design string Design notes
--design-file string Read design from file (use - for stdin)
--due string Due date/time (empty to clear). Formats: +6h, +1d, +2w, tomorrow, next monday, 2025-01-15
--ephemeral Mark issue as ephemeral (wisp) - not exported to JSONL
-e, --estimate int Time estimate in minutes (e.g., 60 for 1 hour)
--external-ref string External reference (e.g., 'gh-9', 'jira-ABC', Linear URL)
--force Override refusals: let -a/--assignee overwrite another actor's live in_progress claim (use only for abandoned claims — crashed agent, expired lease; prefer bd reclaim), let -s/--status move the issue into closed (or a configured done status) despite open children or a live blocker (same as bd close --force), and let --notes overwrite existing non-empty notes (use --append-notes to preserve history instead)
-h, --help help for update
--history Clear no-history flag (re-enable Dolt commit history)
--if-assignee string Apply the update only if the current assignee equals this value (--if-assignee '' requires unassigned); a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim
--if-revision bd show --json Apply the write only if the issue's current revision equals this value (the decimal int64 from bd show --json's "revision" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures). Composes with --if-assignee/--if-status: all guards present must hold.
--if-status string Apply the update only if the current status equals this value; a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim
--metadata string Set custom metadata (JSON object, or @file.json to read from file)
--no-history Mark issue as no-history (skip Dolt commits, not GC-eligible)
--notes string Replace the notes field (requires --force over existing non-empty notes; --clear-notes clears; --append-notes appends instead)
--parent string New parent issue ID (reparents the issue, use empty string to remove parent)
--persistent Mark issue as persistent (promote wisp to regular issue)
-p, --priority string Priority (0-4 or P0-P4, 0=highest)
--remove-label strings Remove labels (repeatable)
--session string Claude Code session ID for status=closed (or set CLAUDE_SESSION_ID env var)
--set-labels strings Set labels, replacing all existing (repeatable)
--set-metadata stringArray Set metadata key=value (repeatable, e.g., --set-metadata team=platform)
--spec-id string Link to specification document
-s, --status string New status
--stdin Read description from stdin (alias for --body-file -)
--title string New title
-t, --type string New type (bug|feature|task|epic|chore|decision|spike|story|milestone); custom types require types.custom config; aliases: enhancement/feat→feature, dec/adr→decision
--unset-metadata stringArray Remove metadata key (repeatable, e.g., --unset-metadata team)
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output

View file

@ -0,0 +1,24 @@
Print version information
Usage:
bd version [flags]
Flags:
-h, --help help for version
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output

View file

@ -0,0 +1,60 @@
List the versions recorded for a bead by versioned history.
Recording is off by default. Turn it on with:
bd config set versioned-history.enabled true
That writes the setting into the store, so every client of that store agrees
about whether a write is recorded, and it is the setting this command reports.
BD_VERSIONED_HISTORY_ENABLED=1 (or a value in config.yaml) also turns recording
on for the writes a process makes, but it says nothing about the store, and
this command only reads, so it does not consult them.
Either source turning it on is enough for a writer; neither can switch the
other off. The consequence worth knowing: once the store setting says on,
BD_VERSIONED_HISTORY_ENABLED=0 will not turn recording off for one run. Turn
it off where it was turned on:
bd config set versioned-history.enabled false
Only beads created while recording is on, or that enter the issues plane
while it is on (a wisp promoted or made persistent), are versioned. A bead
already on the issues plane when recording was turned on is legacy: editing
it records nothing (the write fence, design §16.2b), and nothing is
backfilled.
Turning recording off does not hide what was already recorded — this command
still lists it, and says that recording is currently off.
A caution while the feature is young: keep recording ON for every writer of a
shared store, or leave it off for all of them. A write from a client with
recording off advances nothing, and the next recorded write mints a version
that absorbs that unrecorded change under its own actor — the revisions stay
contiguous and the listing looks gapless when it is not.
Examples:
bd versions bd-123
bd versions bd-123 --json
Usage:
bd versions <id> [flags]
Flags:
-h, --help help for versions
Global Flags:
--actor string Actor name for audit trail (default: $BEADS_ACTOR, git user.name, $USER)
--cpu-profile Generate CPU profile for performance analysis
--database string Run against a different server database for this invocation, without changing the project's configured database (proxied-server mode only)
--db string Database path (default: auto-discover .beads/*.db). In proxied-server mode, a value that isn't an existing path is treated as a database name override (see --database)
-C, --directory string Change to this directory before running the command (like git -C)
--dolt-auto-commit string Dolt auto-commit policy (off|on|batch). 'on': commit after each write. 'batch': defer commits to bd dolt commit; uncommitted changes persist in the working set until then (a live batch-mode bd process also flushes on SIGTERM/SIGHUP, except in proxied-server mode, where bd dolt commit is the only flush point). In proxied-server mode the deferral covers the writes the CLI makes on that route, including config and version metadata; explicit commit points (bd batch, bd mol bond/pour/squash, bd mol wisp create, and the wisp half of bd mol burn) still commit, and a bd serve process on the same database is unaffected. Default: on. Override via config key dolt.auto-commit
--global Use the global shared-server database (beads_global)
--ignore-schema-skew Proceed despite forward schema drift (some queries may fail)
--json Output in JSON format
--mem-profile string Write heap profile to FILE on exit (also respects BEADS_MEM_PROFILE)
--no-color Disable color output (also: NO_COLOR=1 or CLICOLOR=0)
-q, --quiet Suppress non-essential output (errors only)
--readonly Read-only mode: block write operations (for worker sandboxes)
--sandbox Sandbox mode: disables Dolt auto-push
-v, --verbose Enable verbose/debug output

7461
cmd/bd/testdata/command_tree/tree.golden vendored Normal file

File diff suppressed because it is too large Load diff