Files
beads/internal/storage/storage.go
Aarya Reddy bd5fc214c3 feat(ready,blocked): Add --parent flag for scoping by epic/bead desce… (#743)
* feat(ready,blocked): Add --parent flag for scoping by epic/bead descendants

Add --parent flag to `bd ready` and `bd blocked` CLI commands and MCP tools
to filter results to all descendants of a specific epic or bead.

## Backward Compatibility

- CLI: New optional --parent flag; existing usage unchanged
- RPC: New `blocked` operation added (was missing); existing operations unchanged
- MCP: New optional `parent` parameter; existing calls work as before
- Storage interface: GetBlockedIssues signature changed to accept WorkFilter
  - All callers updated to pass empty filter for existing behavior
  - Empty WorkFilter{} returns identical results to previous implementation

## Implementation Details

SQLite uses recursive CTE to traverse parent-child hierarchy:

    WITH RECURSIVE descendants AS (
        SELECT issue_id FROM dependencies
        WHERE type = 'parent-child' AND depends_on_id = ?
        UNION ALL
        SELECT d.issue_id FROM dependencies d
        JOIN descendants dt ON d.depends_on_id = dt.issue_id
        WHERE d.type = 'parent-child'
    )
    SELECT issue_id FROM descendants

MemoryStorage implements equivalent recursive traversal with visited-set
cycle protection via collectDescendants helper.

Parent filter composes with existing filters (priority, labels, assignee, etc.)
as an additional WHERE clause - all filters are AND'd together.

## RPC Blocked Support

MCP beads_blocked() existed but daemon client raised NotImplementedError.
Added OpBlocked and handleBlocked to enable daemon RPC path, which was
previously broken. Now both CLI and daemon clients work for blocked queries.

## Changes

- internal/types/types.go: Add ParentID *string to WorkFilter
- internal/storage/sqlite/ready.go: Add recursive CTE for parent filtering
- internal/storage/memory/memory.go: Add getAllDescendants/collectDescendants
- internal/storage/storage.go: Update GetBlockedIssues interface signature
- cmd/bd/ready.go: Add --parent flag to ready and blocked commands
- internal/rpc/protocol.go: Add OpBlocked constant and BlockedArgs type
- internal/rpc/server_issues_epics.go: Add handleBlocked RPC handler
- internal/rpc/client.go: Add Blocked client method
- integrations/beads-mcp/: Add BlockedParams model and parent parameter

## Usage

  bd ready --parent bd-abc              # All ready descendants
  bd ready --parent bd-abc --priority 1 # Combined with other filters
  bd blocked --parent bd-abc            # All blocked descendants

## Testing

Added 4 test cases for parent filtering:
- TestParentIDFilterDescendants: Verifies recursive traversal (grandchildren)
- TestParentIDWithOtherFilters: Verifies composition with priority filter
- TestParentIDWithBlockedDescendants: Verifies blocked issues excluded from ready
- TestParentIDEmptyParent: Verifies empty result for childless parent

* fix: Correct blockedCmd indentation and suppress gosec false positive

- Fix syntax error from incorrect indentation in blockedCmd Run function
- Add nolint:gosec comment for GetBlockedIssues SQL formatting (G201)
  The filterSQL variable contains only parameterized WHERE clauses with
  ? placeholders, not user input
2025-12-25 21:11:58 -08:00

214 lines
9.5 KiB
Go

// Package storage defines the interface for issue storage backends.
package storage
import (
"context"
"database/sql"
"github.com/steveyegge/beads/internal/types"
)
// Transaction provides atomic multi-operation support within a single database transaction.
//
// The Transaction interface exposes a subset of Storage methods that execute within
// a single database transaction. This enables atomic workflows where multiple operations
// must either all succeed or all fail (e.g., creating issues with dependencies and labels).
//
// # Transaction Semantics
//
// - All operations within the transaction share the same database connection
// - Changes are not visible to other connections until commit
// - If any operation returns an error, the transaction is rolled back
// - If the callback function panics, the transaction is rolled back
// - On successful return from the callback, the transaction is committed
//
// # SQLite Specifics
//
// - Uses BEGIN IMMEDIATE mode to acquire write lock early
// - This prevents deadlocks when multiple operations compete for the same lock
// - IMMEDIATE mode serializes concurrent transactions properly
//
// # Example Usage
//
// err := store.RunInTransaction(ctx, func(tx storage.Transaction) error {
// // Create parent issue
// if err := tx.CreateIssue(ctx, parentIssue, actor); err != nil {
// return err // Triggers rollback
// }
// // Create child issue
// if err := tx.CreateIssue(ctx, childIssue, actor); err != nil {
// return err // Triggers rollback
// }
// // Add dependency between them
// if err := tx.AddDependency(ctx, dep, actor); err != nil {
// return err // Triggers rollback
// }
// return nil // Triggers commit
// })
type Transaction interface {
// Issue operations
CreateIssue(ctx context.Context, issue *types.Issue, actor string) error
CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error
UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error
CloseIssue(ctx context.Context, id string, reason string, actor string) error
DeleteIssue(ctx context.Context, id string) error
GetIssue(ctx context.Context, id string) (*types.Issue, error) // For read-your-writes within transaction
SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) // For read-your-writes within transaction
// Dependency operations
AddDependency(ctx context.Context, dep *types.Dependency, actor string) error
RemoveDependency(ctx context.Context, issueID, dependsOnID string, actor string) error
// Label operations
AddLabel(ctx context.Context, issueID, label, actor string) error
RemoveLabel(ctx context.Context, issueID, label, actor string) error
// Config operations (for atomic config + issue workflows)
SetConfig(ctx context.Context, key, value string) error
GetConfig(ctx context.Context, key string) (string, error)
// Metadata operations (for internal state like import hashes)
SetMetadata(ctx context.Context, key, value string) error
GetMetadata(ctx context.Context, key string) (string, error)
// Comment operations
AddComment(ctx context.Context, issueID, actor, comment string) error
}
// Storage defines the interface for issue storage backends
type Storage interface {
// Issues
CreateIssue(ctx context.Context, issue *types.Issue, actor string) error
CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error
GetIssue(ctx context.Context, id string) (*types.Issue, error)
GetIssueByExternalRef(ctx context.Context, externalRef string) (*types.Issue, error)
UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error
CloseIssue(ctx context.Context, id string, reason string, actor string) error
DeleteIssue(ctx context.Context, id string) error
SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error)
// Dependencies
AddDependency(ctx context.Context, dep *types.Dependency, actor string) error
RemoveDependency(ctx context.Context, issueID, dependsOnID string, actor string) error
GetDependencies(ctx context.Context, issueID string) ([]*types.Issue, error)
GetDependents(ctx context.Context, issueID string) ([]*types.Issue, error)
GetDependencyRecords(ctx context.Context, issueID string) ([]*types.Dependency, error)
GetAllDependencyRecords(ctx context.Context) (map[string][]*types.Dependency, error)
GetDependencyCounts(ctx context.Context, issueIDs []string) (map[string]*types.DependencyCounts, error)
GetDependencyTree(ctx context.Context, issueID string, maxDepth int, showAllPaths bool, reverse bool) ([]*types.TreeNode, error)
DetectCycles(ctx context.Context) ([][]*types.Issue, error)
// Labels
AddLabel(ctx context.Context, issueID, label, actor string) error
RemoveLabel(ctx context.Context, issueID, label, actor string) error
GetLabels(ctx context.Context, issueID string) ([]string, error)
GetLabelsForIssues(ctx context.Context, issueIDs []string) (map[string][]string, error)
GetIssuesByLabel(ctx context.Context, label string) ([]*types.Issue, error)
// Ready Work & Blocking
GetReadyWork(ctx context.Context, filter types.WorkFilter) ([]*types.Issue, error)
GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error)
GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error)
GetStaleIssues(ctx context.Context, filter types.StaleFilter) ([]*types.Issue, error)
GetNewlyUnblockedByClose(ctx context.Context, closedIssueID string) ([]*types.Issue, error) // GH#679
// Events
AddComment(ctx context.Context, issueID, actor, comment string) error
GetEvents(ctx context.Context, issueID string, limit int) ([]*types.Event, error)
// Comments
AddIssueComment(ctx context.Context, issueID, author, text string) (*types.Comment, error)
GetIssueComments(ctx context.Context, issueID string) ([]*types.Comment, error)
GetCommentsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Comment, error)
// Statistics
GetStatistics(ctx context.Context) (*types.Statistics, error)
// Dirty tracking (for incremental JSONL export)
GetDirtyIssues(ctx context.Context) ([]string, error)
GetDirtyIssueHash(ctx context.Context, issueID string) (string, error) // For timestamp-only dedup (bd-164)
ClearDirtyIssuesByID(ctx context.Context, issueIDs []string) error
// Export hash tracking (for timestamp-only dedup, bd-164)
GetExportHash(ctx context.Context, issueID string) (string, error)
SetExportHash(ctx context.Context, issueID, contentHash string) error
ClearAllExportHashes(ctx context.Context) error
// JSONL file integrity (bd-160)
GetJSONLFileHash(ctx context.Context) (string, error)
SetJSONLFileHash(ctx context.Context, fileHash string) error
// ID Generation
GetNextChildID(ctx context.Context, parentID string) (string, error)
// Config
SetConfig(ctx context.Context, key, value string) error
GetConfig(ctx context.Context, key string) (string, error)
GetAllConfig(ctx context.Context) (map[string]string, error)
DeleteConfig(ctx context.Context, key string) error
GetCustomStatuses(ctx context.Context) ([]string, error) // Custom status states from status.custom config
// Metadata (for internal state like import hashes)
SetMetadata(ctx context.Context, key, value string) error
GetMetadata(ctx context.Context, key string) (string, error)
// Prefix rename operations
UpdateIssueID(ctx context.Context, oldID, newID string, issue *types.Issue, actor string) error
RenameDependencyPrefix(ctx context.Context, oldPrefix, newPrefix string) error
RenameCounterPrefix(ctx context.Context, oldPrefix, newPrefix string) error
// Transactions
//
// RunInTransaction executes a function within a database transaction.
// The Transaction interface provides atomic multi-operation support.
//
// Transaction behavior:
// - If fn returns nil, the transaction is committed
// - If fn returns an error, the transaction is rolled back
// - If fn panics, the transaction is rolled back and the panic is re-raised
// - Uses BEGIN IMMEDIATE for SQLite to acquire write lock early
//
// Example:
// err := store.RunInTransaction(ctx, func(tx storage.Transaction) error {
// if err := tx.CreateIssue(ctx, issue, actor); err != nil {
// return err // Triggers rollback
// }
// return nil // Triggers commit
// })
RunInTransaction(ctx context.Context, fn func(tx Transaction) error) error
// Lifecycle
Close() error
// Database path (for daemon validation)
Path() string
// UnderlyingDB returns the underlying *sql.DB connection
// This is provided for extensions (like VC) that need to create their own tables
// in the same database. Extensions should use foreign keys to reference core tables.
// WARNING: Direct database access bypasses the storage layer. Use with caution.
UnderlyingDB() *sql.DB
// UnderlyingConn returns a single connection from the pool for scoped use.
// Useful for migrations and DDL operations that benefit from explicit connection lifetime.
// The caller MUST close the connection when done to return it to the pool.
// For general queries, prefer UnderlyingDB() which manages the pool automatically.
UnderlyingConn(ctx context.Context) (*sql.Conn, error)
}
// Config holds database configuration
type Config struct {
Backend string // "sqlite" or "postgres"
// SQLite config
Path string // database file path
// PostgreSQL config
Host string
Port int
Database string
User string
Password string
SSLMode string
}