beads/examples/library-usage
Jim Wordelman bc9d854ebb
feat(stats): --no-blocked flag skips blocked-count computation; fix Blocked:0 red render (be-nnqp, be-4b63) (#4022)
* feat(stats): add --no-blocked flag; fix Blocked:0 red render (be-nnqp, be-4b63)

- types.go: BlockedIssues int → *int (nil when --no-blocked skips computation)
- storage: add FastStatisticsStore interface + GetStatisticsNoBlocked to DoltStorage;
  implement in DoltStore and EmbeddedDoltStore (ScanIssueCountsInTx only, no blocked traversal)
- status.go: --no-blocked flag (no short alias), BlockedCountSkipped bool in StatusOutput;
  fast path calls GetStatisticsNoBlocked; human output renders "(skipped)" in muted style
- be-4b63: Blocked:0 now renders plain text; only Blocked:N>0 uses RenderFail (red)
- nil-guard BlockedIssues callers: getAssignedStatistics, status_test.go, queries_test.go,
  examples/library-usage/main.go

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(cli): regen CLI reference for `bd status --no-blocked`

Regenerates docs/CLI_REFERENCE.md and the website CLI reference pages
(`website/docs/cli-reference/status.md` and the version-1.0.0 / 1.0.4
snapshots) from the live `bd help` output so the doc-flags freshness
check passes.

Picks up the new `--no-blocked` flag, the updated `--no-activity`
description ("Skip git activity summary"), and the matching example
lines added in ddf53438c.

Fixes the CI "Check doc flags freshness" failure on PR #4022.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: release gate PASS for be-nnqp+be-4b63 (bd stats --no-blocked)

* fix(stats): ReadyIssues *int, data-derived skip render, proxied-server warning

Address the adjudicated cross-vendor review on PR #4022:

- internal/types.Statistics.ReadyIssues is now *int, mirroring BlockedIssues:
  nil when --no-blocked skips the computation (readiness needs the blocked
  set), populated by all three backends' full GetStatistics, by
  issueops.GetStatisticsInTx, and by buildAssignedStats. Left nil only in
  the *NoBlocked fast-path variants. JSON now emits `"ready_issues": null`
  instead of a fake 0 a CI consumer could misread as "nothing ready".
- renderStatus derives "(skipped)" rendering from the data itself
  (stats.BlockedIssues/ReadyIssues == nil) instead of the noBlocked flag,
  fixing the --assigned + --no-blocked contradiction where fully-recomputed
  stats were mislabeled as skipped. The noBlocked parameter is gone from
  renderStatus entirely; both call sites (status.go, status_proxied_server.go)
  simplified accordingly.
- Proxied-server mode now prints a one-line stderr warning when --no-blocked
  is passed but not honored, instead of silently discarding the flag; the
  flag's help string documents the limitation.

Agent-Signature: claude-sonnet-medium on behalf of maphew

* test(stats): cover GetStatisticsNoBlocked nil semantics and renderStatus skip branch

- internal/storage/dolt: new TestGetStatisticsNoBlocked_LeavesBlockedAndReadyNil
  asserts the --no-blocked fast path leaves BlockedIssues/ReadyIssues nil
  while the full GetStatistics path on the same store populates both.
- cmd/bd: new TestGetStatisticsNoBlocked (storage-level, same assertion via
  the CLI-facing store handle), TestRenderStatus_SkipJSONEmitsNullNotZero
  (asserts blocked_count_skipped:true plus literal `"blocked_issues": null`
  / `"ready_issues": null` in the JSON envelope),
  TestRenderStatus_SkipHumanRendersSkippedNotZero (asserts the "(skipped)"
  human branch renders for both fields), and
  TestRenderStatus_AssignedIgnoresSkipEvenWithNoBlockedFlag (guards the
  --assigned + --no-blocked fix: fully-populated stats never render
  "(skipped)").
- Update existing statistics assertions in
  internal/storage/conformance/audit_search-counts-stats.go,
  internal/storage/dolt/queries_test.go, and
  internal/storage/domain/db/ready_helpers*_test.go for
  ReadyIssues's int -> *int change.

Agent-Signature: claude-sonnet-medium on behalf of maphew

* docs(cli): drop --no-blocked doc lines from CLI_REFERENCE.md/status.md (pinned-generator policy)

CI's "Check doc flags freshness" job builds bd from the release pin in
docs/cli-docs.pin (currently v1.1.0) to regenerate docs/CLI_REFERENCE.md
and docs/cli-reference/status.md, not from this branch's HEAD. v1.1.0
predates --no-blocked entirely, so the pinned generator's output omits
every --no-blocked reference (use case bullet, both example lines, the
flag description) and also reverts the --no-activity flag description
wording, flagging both files as stale relative to it. Same trap PR #3920
hit for --mem-profile.

Applied the exact patch CI generated and uploaded as the
cli-docs-freshness-patch artifact on the failing job
(run 30063539327 / job 89390739992) verbatim to both files; the lines
will reappear automatically once the pin advances past a release that
includes --no-blocked.

Agent-Signature: claude-sonnet-medium on behalf of maphew

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: matt wilkie <maphew@gmail.com>
2026-07-23 23:52:39 -07:00
..
go.mod Bump Go to 1.26.5 (#4942) 2026-07-23 18:54:32 -07:00
go.sum Bump Go to 1.26.5 (#4942) 2026-07-23 18:54:32 -07:00
main.go feat(stats): --no-blocked flag skips blocked-count computation; fix Blocked:0 red render (be-nnqp, be-4b63) (#4022) 2026-07-23 23:52:39 -07:00
main_test.go test: reconcile the sqlite-era tests the reapply left asserting live support 2026-07-18 02:43:57 +00:00
README.md feat(engine): guarded write ops — atomic metadata merge, row-version CAS, typed dep errors + events, bd close delegation (#4911) 2026-07-21 18:13:03 -07:00

Beads Library Usage Example

This example demonstrates using Beads as a Go library in external projects (like VC).

Why Use Beads as a Library?

Instead of spawning bd CLI processes:

  • ✅ Direct API access - Call functions directly instead of parsing JSON output
  • ✅ Type safety - Compile-time checking of types and interfaces
  • ✅ Performance - No process spawn overhead
  • ✅ Transactions - Access to database transactions for complex operations
  • ✅ Shared database - Multiple components can use same database connection
  • ✅ Error handling - Proper Go error types instead of parsing stderr

Installation

In your Go project:

go get github.com/steveyegge/beads@latest

Basic Usage

package main

import (
    "context"
    "log"
    
    "github.com/steveyegge/beads"
)

func main() {
    ctx := context.Background()
    
    // Find the workspace and open its configured Dolt implementation
    beadsDir := beads.FindBeadsDir()
    store, err := beads.OpenBestAvailable(ctx, beadsDir)
    if err != nil {
        log.Fatal(err)
    }
    defer store.Close()
    
    // Get ready work
    ready, err := store.GetReadyWork(ctx, beads.WorkFilter{
        Status: beads.StatusOpen,
        Limit: 10,
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Process ready issues...
}

Running This Example

# From this directory
cd examples/library-usage

# Make sure there's a Beads database
bd init --prefix demo

# Run the example
go run main.go

Available Operations

The beads.Storage interface provides:

Issues

  • CreateIssue(ctx, issue, actor) - Create a new issue
  • CreateIssues(ctx, issues, actor) - Batch create issues
  • GetIssue(ctx, id) - Get issue by ID
  • UpdateIssue(ctx, id, updates, actor) - Update issue fields
  • UpdateIssueChecked(ctx, id, updates, actor, opts) - Update with an optional optimistic-concurrency (CAS) precondition (opts.ExpectedVersion); see Concurrency below
  • CloseIssue(ctx, id, reason, actor) - Close an issue
  • SearchIssues(ctx, query, filter) - Search with filters

Dependencies

  • AddDependency(ctx, dep, actor) - Add dependency between issues
  • RemoveDependency(ctx, issueID, dependsOnID, actor) - Remove dependency
  • GetDependencies(ctx, issueID) - Get what this issue depends on
  • GetDependents(ctx, issueID) - Get what depends on this issue
  • GetDependencyTree(ctx, issueID, maxDepth, showAllPaths) - Visualize tree

Labels

  • AddLabel(ctx, issueID, label, actor) - Add label to issue
  • RemoveLabel(ctx, issueID, label, actor) - Remove label
  • GetLabels(ctx, issueID) - Get all labels for an issue
  • GetIssuesByLabel(ctx, label) - Find issues with label

Ready Work & Blocking

  • GetReadyWork(ctx, filter) - Find issues with no blockers
  • GetBlockedIssues(ctx) - Find blocked issues with blocker info
  • GetEpicsEligibleForClosure(ctx) - Find completable epics

Comments & Events

  • AddIssueComment(ctx, issueID, author, text) - Add comment
  • GetIssueComments(ctx, issueID) - Get all comments
  • GetEvents(ctx, issueID, limit) - Get audit trail

Statistics

  • GetStatistics(ctx) - Get aggregate metrics

Concurrency & Metadata

  • UpdateIssueChecked(ctx, id, updates, actor, opts) - Like UpdateIssue, but when opts.ExpectedVersion is set the update proceeds only if the issue's current RowVersion still matches, else it refuses with beads.ErrVersionMismatch. The version read and the write share one transaction (a true compare-and-swap). RowVersion is surfaced read-only on Issue reads.
  • MergeMetadata(ctx, issueID, key, value, actor) - Atomically merge a single key into an issue's metadata JSON. Two concurrent merges of different keys both survive rather than clobbering each other.

Implementer note (interface change): UpdateIssueChecked and MergeMetadata are now required methods on the beads.Storage interface. Code that only consumes beads.Storage needs no change, but any external type that implements beads.Storage (a custom store, mock, or proxy) must add these two methods to compile. If you only need the base behavior, UpdateIssueChecked with a nil opts.ExpectedVersion is identical to UpdateIssue, and MergeMetadata can be layered over a read-modify-write of the issue's metadata.

Types

All types are exported via the beads package:

// Core types
beads.Issue
beads.Status (Open, InProgress, Closed, Blocked)
beads.IssueType (Bug, Feature, Task, Epic, Chore)
beads.Priority (0-4)

// Relationships
beads.Dependency
beads.DependencyType (Blocks, Related, ParentChild, DiscoveredFrom)

// Metadata
beads.Label
beads.Comment
beads.Event

// Queries
beads.IssueFilter
beads.WorkFilter
beads.BlockedIssue
beads.EpicStatus
beads.Statistics

VC Integration Example

For VC (VibeCoder), the integration would look like:

// In VC's storage layer
type VCStorage struct {
    beads beads.Storage
}

func NewVCStorage(ctx context.Context, beadsDir string) (*VCStorage, error) {
    store, err := beads.OpenBestAvailable(ctx, beadsDir)
    if err != nil {
        return nil, err
    }
    
    return &VCStorage{beads: store}, nil
}

// Claim ready work for executor
func (s *VCStorage) ClaimWork(ctx context.Context, executorID string) (*beads.Issue, error) {
    ready, err := s.beads.GetReadyWork(ctx, beads.WorkFilter{
        Status: beads.StatusOpen,
        Limit: 1,
    })
    if err != nil {
        return nil, err
    }
    
    if len(ready) == 0 {
        return nil, nil // No work available
    }
    
    issue := ready[0]
    
    // Claim it
    updates := map[string]interface{}{
        "status": beads.StatusInProgress,
        "assignee": executorID,
    }
    
    if err := s.beads.UpdateIssue(ctx, issue.ID, updates, executorID); err != nil {
        return nil, err
    }
    
    return issue, nil
}

Best Practices

  1. Context - Always pass context.Context for cancellation support
  2. Actor - Provide meaningful actor strings for audit trail
  3. Error handling - Check all errors; database operations can fail
  4. Close - Always defer store.Close() after opening
  5. Transactions - For complex multi-step operations, consider using the underlying database connection directly

See Also