* perf(git): locate the repository in-process instead of running git rev-parse Every bd invocation resolved the process-wide git context (beads directory discovery reads it) with `git rev-parse --git-dir --git-common-dir --show-toplevel`: one git subprocess per bd call before any work. Tools that call bd hundreds of times (gascity's doctor issues ~250 bd calls per run) paid it on every call. On Linux, initGitContext now first runs discoverGitInProcess, which mirrors Git's discovery walk (physical cwd, .git as directory or gitfile, bare-dir check, filesystem-boundary stop) and produces byte-for-byte what rev-parse prints for ordinary repositories (top and subdirectories), linked worktrees (absolute or relative gitfile, symlinked targets), submodules (core.worktree pointing back at the gitfile's directory), nested repositories and no repository. Both answers feed one shared normalization (gitContextFromRevParse), so downstream values are unchanged. It declines, and git runs exactly as before, whenever it cannot prove the answer: GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR / GIT_CEILING_DIRECTORIES / GIT_DISCOVERY_ACROSS_FILESYSTEM / GIT_OBJECT_DIRECTORY / GIT_CONFIG_PARAMETERS / GIT_CONFIG_COUNT in the environment; a symlinked .git, an invalid gitfile or git directory, a cwd inside a git directory; repository config with core.worktree (other than the submodule shape), core.bare, extensions, include directives, a format version above 1 or unmodeled syntax; any path not owned by the effective uid (safe.directory is git's to evaluate), or root under sudo. darwin and windows keep the subprocess (case folding and ownership semantics). Tests compare discoverGitFrom with real `git rev-parse` output across those layouts, pin every decline case, and check the resulting cached context equals the subprocess-derived one. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(cli): resolve the git user.name actor fallback only when needed PersistentPreRunE assigned `actor = getActorWithGit()` for every command, which, with no --actor / BEADS_ACTOR / BD_ACTOR / config actor, runs `git config user.name`: the second git subprocess of every bd call, paid by read-only commands that never consult the actor. The pre-run now calls deferActorGitFallback, which marks an empty actor as pending; currentActor (and getActorWithGit, getActor) resolve it on first use with the unchanged priority order and store it in the global and the CommandContext copy, as the eager assignment did. Command code reads the actor through currentActor() instead of the raw global (a mechanical rewrite of every read site the compiler reported; writes, the flag binding and the pre-run config binding keep the raw variable). setActor cancels a pending fallback. The telemetry span's bd.actor attribute is still set, but only for a recording span, so a noop span does not force the lookup. With the in-process repository discovery from the previous commit, a read-only `bd list` / `bd show` now starts no git process at startup, in the main checkout and in a linked worktree; a write asks git for user.name once (bd create previously asked once, now still once) and records the same value. Measured on 50 sequential `bd list` calls: 100 -> 0 git execs (embedded and proxied-server workspaces, main checkout and worktree). TestEmbeddedReadOnlyCommandsSpawnNoGit counts git execs through a PATH shim; TestDeferredActorGitFallback pins the deferral semantics. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(git): decline in-process discovery on any config line git might read differently Review follow-ups to the in-process repository discovery. - The repository config scanner was looser than git: a config starting with a UTF-8 BOM followed by `[core] worktree = /other` made git report /other while discovery returned the cwd repository, and `[ core ]` or `!!! = x` (which git refuses) were accepted. scanGitConfig (gitconfig_linux.go) now skips a leading BOM exactly as git does and accepts only a narrow grammar: blank/comment lines, `[section]` / `[section "sub"]` headers at column 0, and `key` / `key = value` lines inside a section, with values free of backslashes and unbalanced quotes. Any other line declines to git. - Walk from getcwd(2) (syscall.Getwd), as git does, instead of os.Getwd, which trusts $PWD when it names the same inode (bind-mount aliases). - Resolve relative gitfile and commondir targets without filepath.Join's lexical Clean, so "link/.." resolves physically like git's realpath. - A mount-boundary stop reports its own reason in the not-a-repository error. - Tests: every decline case (BOM + core.worktree, malformed headers and keys, keys before a section, escapes, continuations, bare repositories, a commondir inside .git, ...) now also checks that what startup derives equals git's answer; BOM and CRLF/comment configs are equivalence cases; the no-repository case must be answered in-process instead of skipping; a $PWD alias test pins the getcwd walk. - The exec-count test drops every GIT_* variable except the config-file selectors, so a runner exporting GIT_CONFIG_PARAMETERS & co. cannot make it fail spuriously. - Comment the two places that touch the raw actor before the deferral. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(backup): decide embedded auto-backup's git-remote probe without git In an embedded workspace whose backup.enabled is unset, maybeAutoBackup asks isBackupAutoEnabled -> primeHasGitRemote after every command, reads included. That built a RepoContext (`git -C .beads rev-parse --git-common-dir`) and ran `git remote`: two git processes per read even after the startup calls were gone. The throttle cannot short-circuit it: without a remote no backup ever runs, so there is no backup state to throttle on. Both probes are now answered in-process when provable, and the subprocess remains the fallback, so the decision and every warning/notice downstream of it are unchanged: - internal/beads getGitCommonDirForPath uses git.CommonDirInProcess (the discovery walk from the given directory, git's spelling). - primeHasGitRemote uses git.HasRemoteInProcess in the same directory primeGitCmd would run git in (primeGitDir, factored out). It answers only when every config file `git remote` reads -- system (GIT_CONFIG_SYSTEM, or /etc/gitconfig and <prefix>/etc/gitconfig of the git on PATH), global (GIT_CONFIG_GLOBAL, or XDG and ~/.gitconfig) and the repository's own -- is absent or within scanGitConfig's grammar and include-free, no GIT_CONFIG_PARAMETERS/COUNT/GIT_CONFIG or discovery override is set, and no legacy .git/remotes or .git/branches entries exist. A remote seen only in a system-config candidate declines. Remote names outside [A-Za-z0-9._-] decline. Tests compare HasRemoteInProcess with `git remote` (no remote, local, worktree, submodule, remote.pushDefault only, global remote, no repo) and pin the declines (global include, malformed global, command-line config); CommonDirInProcess is compared with `git -C dir rev-parse --git-common-dir`. TestEmbeddedReadOnlyCommandsSpawnNoGit now runs with backup.enabled at its default, with and without a git remote, and still expects zero git processes for list/show. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1256 lines
36 KiB
Go
1256 lines
36 KiB
Go
// Package main implements the bd CLI swarm management commands.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
)
|
|
|
|
var swarmCmd = &cobra.Command{
|
|
Use: "swarm",
|
|
GroupID: "deps",
|
|
Short: "Swarm management for structured epics",
|
|
Long: `Swarm management commands for coordinating parallel work on epics.
|
|
|
|
A swarm is a structured body of work defined by an epic and its children,
|
|
with dependencies forming a DAG (directed acyclic graph) of work.`,
|
|
}
|
|
|
|
// SwarmAnalysis holds the results of analyzing an epic's structure for swarming.
|
|
type SwarmAnalysis struct {
|
|
EpicID string `json:"epic_id"`
|
|
EpicTitle string `json:"epic_title"`
|
|
TotalIssues int `json:"total_issues"`
|
|
ClosedIssues int `json:"closed_issues"`
|
|
ReadyFronts []ReadyFront `json:"ready_fronts"`
|
|
MaxParallelism int `json:"max_parallelism"`
|
|
EstimatedSessions int `json:"estimated_sessions"`
|
|
Warnings []string `json:"warnings"`
|
|
Errors []string `json:"errors"`
|
|
Swarmable bool `json:"swarmable"`
|
|
Issues map[string]*IssueNode `json:"issues,omitempty"` // Only included with --verbose
|
|
}
|
|
|
|
// ReadyFront represents a group of issues that can be worked on in parallel.
|
|
type ReadyFront struct {
|
|
Wave int `json:"wave"`
|
|
Issues []string `json:"issues"`
|
|
Titles []string `json:"titles,omitempty"` // Only for human output
|
|
}
|
|
|
|
// IssueNode represents an issue in the dependency graph.
|
|
type IssueNode struct {
|
|
ID string `json:"id"`
|
|
Title string `json:"title"`
|
|
Status string `json:"status"`
|
|
Priority int `json:"priority"`
|
|
DependsOn []string `json:"depends_on"` // What this issue depends on
|
|
DependedOnBy []string `json:"depended_on_by"` // What depends on this issue
|
|
Wave int `json:"wave"` // Which ready front this belongs to (-1 if blocked by cycle)
|
|
}
|
|
|
|
// SwarmStorage defines the storage interface needed by swarm commands.
|
|
type SwarmStorage interface {
|
|
GetIssue(context.Context, string) (*types.Issue, error)
|
|
GetDependents(context.Context, string) ([]*types.Issue, error)
|
|
GetDependencyRecords(context.Context, string) ([]*types.Dependency, error)
|
|
}
|
|
|
|
// findExistingSwarm returns the swarm molecule for an epic, if one exists.
|
|
// Returns nil if no swarm molecule is linked to the epic.
|
|
func findExistingSwarm(ctx context.Context, s SwarmStorage, epicID string) (*types.Issue, error) {
|
|
// Get all issues that depend on the epic
|
|
dependents, err := s.GetDependents(ctx, epicID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get epic dependents: %w", err)
|
|
}
|
|
|
|
// Find a swarm molecule with relates-to dependency to this epic
|
|
for _, dep := range dependents {
|
|
// Only consider molecules (GetDependents doesn't populate mol_type, so we fetch full issue)
|
|
if dep.IssueType != "molecule" {
|
|
continue
|
|
}
|
|
|
|
// Get full issue to check mol_type
|
|
fullIssue, err := s.GetIssue(ctx, dep.ID)
|
|
if err != nil || fullIssue == nil {
|
|
continue
|
|
}
|
|
if fullIssue.MolType != types.MolTypeSwarm {
|
|
continue
|
|
}
|
|
|
|
// Verify it's linked via relates-to
|
|
deps, err := s.GetDependencyRecords(ctx, dep.ID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, d := range deps {
|
|
if d.DependsOnID == epicID && d.Type == types.DepRelatesTo {
|
|
return fullIssue, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil, nil
|
|
}
|
|
|
|
// getEpicChildren returns all child issues of an epic (via parent-child dependencies).
|
|
func getEpicChildren(ctx context.Context, s SwarmStorage, epicID string) ([]*types.Issue, error) {
|
|
// Get all issues that depend on the epic
|
|
allDependents, err := s.GetDependents(ctx, epicID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get epic dependents: %w", err)
|
|
}
|
|
|
|
// Filter to only parent-child relationships by checking each dependent's dependency records
|
|
var children []*types.Issue
|
|
for _, dependent := range allDependents {
|
|
deps, err := s.GetDependencyRecords(ctx, dependent.ID)
|
|
if err != nil {
|
|
continue // Skip issues we can't query
|
|
}
|
|
for _, dep := range deps {
|
|
if dep.DependsOnID == epicID && dep.Type == types.DepParentChild {
|
|
children = append(children, dependent)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
return children, nil
|
|
}
|
|
|
|
var swarmValidateCmd = &cobra.Command{
|
|
Use: "validate [epic-id]",
|
|
Short: "Validate epic structure for swarming",
|
|
Long: `Validate an epic's structure to ensure it's ready for swarm execution.
|
|
|
|
Checks for:
|
|
- Correct dependency direction (requirement-based, not temporal)
|
|
- Orphaned issues (roots with no dependents)
|
|
- Missing dependencies (leaves that should depend on something)
|
|
- Cycles (impossible to resolve)
|
|
- Disconnected subgraphs
|
|
|
|
Reports:
|
|
- Ready fronts (waves of parallel work)
|
|
- Estimated worker-sessions
|
|
- Maximum parallelism
|
|
- Warnings for potential issues
|
|
|
|
Examples:
|
|
bd swarm validate gt-epic-123 # Validate epic structure
|
|
bd swarm validate gt-epic-123 --verbose # Include detailed issue graph`,
|
|
Args: cobra.ExactArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
if usesProxiedServer() {
|
|
return runSwarmValidateProxiedServer(cmd, rootCtx, args)
|
|
}
|
|
evt := metrics.NewCommandEvent("swarm-validate")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
ctx := rootCtx
|
|
verbose, _ := cmd.Flags().GetBool("verbose")
|
|
|
|
if store == nil {
|
|
return HandleErrorRespectJSON("no database connection")
|
|
}
|
|
|
|
epicID, err := utils.ResolvePartialID(ctx, store, args[0])
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("epic '%s' not found: %v", args[0], err)
|
|
}
|
|
|
|
epic, err := store.GetIssue(ctx, epicID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to get epic: %v", err)
|
|
}
|
|
if epic == nil {
|
|
return HandleErrorRespectJSON("epic '%s' not found", epicID)
|
|
}
|
|
|
|
if epic.IssueType != types.TypeEpic && epic.IssueType != "molecule" {
|
|
return HandleErrorRespectJSON("'%s' is not an epic or molecule (type: %s)", epicID, epic.IssueType)
|
|
}
|
|
|
|
analysis, err := analyzeEpicForSwarm(ctx, store, epic)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to analyze epic: %v", err)
|
|
}
|
|
|
|
if !verbose {
|
|
analysis.Issues = nil
|
|
}
|
|
|
|
if jsonOutput {
|
|
if jerr := outputJSON(analysis); jerr != nil {
|
|
return jerr
|
|
}
|
|
if !analysis.Swarmable {
|
|
return SilentExit()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
renderSwarmAnalysis(analysis)
|
|
|
|
if !analysis.Swarmable {
|
|
return SilentExit()
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// analyzeEpicForSwarm performs structural analysis of an epic for swarm execution.
|
|
func analyzeEpicForSwarm(ctx context.Context, s SwarmStorage, epic *types.Issue) (*SwarmAnalysis, error) {
|
|
analysis := &SwarmAnalysis{
|
|
EpicID: epic.ID,
|
|
EpicTitle: epic.Title,
|
|
Swarmable: true,
|
|
Issues: make(map[string]*IssueNode),
|
|
}
|
|
|
|
// Get all child issues of the epic
|
|
childIssues, err := getEpicChildren(ctx, s, epic.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(childIssues) == 0 {
|
|
analysis.Warnings = append(analysis.Warnings, "Epic has no children")
|
|
return analysis, nil
|
|
}
|
|
|
|
analysis.TotalIssues = len(childIssues)
|
|
|
|
// Build the issue graph
|
|
for _, issue := range childIssues {
|
|
node := &IssueNode{
|
|
ID: issue.ID,
|
|
Title: issue.Title,
|
|
Status: string(issue.Status),
|
|
Priority: issue.Priority,
|
|
DependsOn: []string{},
|
|
DependedOnBy: []string{},
|
|
Wave: -1, // Will be set later
|
|
}
|
|
analysis.Issues[issue.ID] = node
|
|
|
|
if issue.Status == types.StatusClosed {
|
|
analysis.ClosedIssues++
|
|
}
|
|
}
|
|
|
|
// Build dependency relationships (only within the epic's children)
|
|
childIDSet := make(map[string]bool)
|
|
for _, issue := range childIssues {
|
|
childIDSet[issue.ID] = true
|
|
}
|
|
|
|
for _, issue := range childIssues {
|
|
deps, err := s.GetDependencyRecords(ctx, issue.ID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get dependencies for %s: %w", issue.ID, err)
|
|
}
|
|
|
|
node := analysis.Issues[issue.ID]
|
|
for _, dep := range deps {
|
|
// Only consider dependencies within the epic (not parent-child to epic itself)
|
|
if dep.DependsOnID == epic.ID && dep.Type == types.DepParentChild {
|
|
continue // Skip the parent relationship to the epic
|
|
}
|
|
// Only track blocking dependencies
|
|
if !dep.Type.AffectsReadyWork() {
|
|
continue
|
|
}
|
|
// Only track dependencies within the epic's children
|
|
if childIDSet[dep.DependsOnID] {
|
|
node.DependsOn = append(node.DependsOn, dep.DependsOnID)
|
|
if targetNode, ok := analysis.Issues[dep.DependsOnID]; ok {
|
|
targetNode.DependedOnBy = append(targetNode.DependedOnBy, issue.ID)
|
|
}
|
|
}
|
|
// External dependencies to issues outside the epic
|
|
if !childIDSet[dep.DependsOnID] && dep.DependsOnID != epic.ID {
|
|
// Check if it's an external ref
|
|
if strings.HasPrefix(dep.DependsOnID, "external:") {
|
|
analysis.Warnings = append(analysis.Warnings,
|
|
fmt.Sprintf("%s has external dependency: %s", issue.ID, dep.DependsOnID))
|
|
} else {
|
|
analysis.Warnings = append(analysis.Warnings,
|
|
fmt.Sprintf("%s depends on %s (outside epic)", issue.ID, dep.DependsOnID))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Detect structural issues
|
|
detectStructuralIssues(analysis, childIssues)
|
|
|
|
// Compute ready fronts (waves of parallel work)
|
|
computeReadyFronts(analysis)
|
|
|
|
// Set swarmable based on errors
|
|
analysis.Swarmable = len(analysis.Errors) == 0
|
|
|
|
return analysis, nil
|
|
}
|
|
|
|
// issueIsClosed reports whether id is closed. Closed issues count as satisfied
|
|
// and are excluded from cycle detection and ready-front scheduling (GH#4564).
|
|
func issueIsClosed(analysis *SwarmAnalysis, id string) bool {
|
|
n, ok := analysis.Issues[id]
|
|
return ok && n.Status == string(types.StatusClosed)
|
|
}
|
|
|
|
// detectStructuralIssues looks for common problems in the dependency graph.
|
|
//
|
|
//nolint:unparam // issues reserved for future use
|
|
func detectStructuralIssues(analysis *SwarmAnalysis, _ []*types.Issue) {
|
|
// 1. Find roots (issues with no dependencies within the epic)
|
|
// These are the starting points. Having multiple roots is normal.
|
|
var roots []string
|
|
for id, node := range analysis.Issues {
|
|
if len(node.DependsOn) == 0 {
|
|
roots = append(roots, id)
|
|
}
|
|
}
|
|
|
|
// 2. Find leaves (issues that nothing depends on within the epic)
|
|
// Multiple leaves might indicate missing dependencies or just multiple end points.
|
|
var leaves []string
|
|
for id, node := range analysis.Issues {
|
|
if len(node.DependedOnBy) == 0 {
|
|
leaves = append(leaves, id)
|
|
}
|
|
}
|
|
|
|
// 3. Detect potential dependency inversions
|
|
// Heuristic: If a "foundation" or "setup" issue has no dependents, it might be inverted.
|
|
// Heuristic: If an "integration" or "final" issue depends on nothing, it might be inverted.
|
|
for id, node := range analysis.Issues {
|
|
lowerTitle := strings.ToLower(node.Title)
|
|
|
|
// Foundation-like issues should have dependents
|
|
if len(node.DependedOnBy) == 0 {
|
|
if strings.Contains(lowerTitle, "foundation") ||
|
|
strings.Contains(lowerTitle, "setup") ||
|
|
strings.Contains(lowerTitle, "base") ||
|
|
strings.Contains(lowerTitle, "core") {
|
|
analysis.Warnings = append(analysis.Warnings,
|
|
fmt.Sprintf("%s (%s) has no dependents - should other issues depend on it?",
|
|
id, node.Title))
|
|
}
|
|
}
|
|
|
|
// Integration-like issues should have dependencies
|
|
if len(node.DependsOn) == 0 {
|
|
if strings.Contains(lowerTitle, "integration") ||
|
|
strings.Contains(lowerTitle, "final") ||
|
|
strings.Contains(lowerTitle, "test") {
|
|
analysis.Warnings = append(analysis.Warnings,
|
|
fmt.Sprintf("%s (%s) has no dependencies - should it depend on implementation?",
|
|
id, node.Title))
|
|
}
|
|
}
|
|
}
|
|
|
|
// 4. Check for disconnected subgraphs
|
|
// Start from roots and see if we can reach all nodes
|
|
visited := make(map[string]bool)
|
|
var dfs func(id string)
|
|
dfs = func(id string) {
|
|
if visited[id] {
|
|
return
|
|
}
|
|
visited[id] = true
|
|
if node, ok := analysis.Issues[id]; ok {
|
|
for _, depID := range node.DependedOnBy {
|
|
dfs(depID)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Visit from all roots
|
|
for _, root := range roots {
|
|
dfs(root)
|
|
}
|
|
|
|
// Check for unvisited nodes (disconnected from roots)
|
|
var disconnected []string
|
|
for id := range analysis.Issues {
|
|
if !visited[id] {
|
|
disconnected = append(disconnected, id)
|
|
}
|
|
}
|
|
|
|
if len(disconnected) > 0 {
|
|
analysis.Warnings = append(analysis.Warnings,
|
|
fmt.Sprintf("Disconnected issues (not reachable from roots): %v", disconnected))
|
|
}
|
|
|
|
// 5. Detect cycles using simple DFS
|
|
// (The main DetectCycles in storage is more sophisticated, but we do a simple check here)
|
|
// Closed issues are excluded: a closed cycle must not block open children (GH#4564).
|
|
inProgress := make(map[string]bool)
|
|
completed := make(map[string]bool)
|
|
var cyclePath []string
|
|
hasCycle := false
|
|
|
|
var detectCycle func(id string) bool
|
|
detectCycle = func(id string) bool {
|
|
if issueIsClosed(analysis, id) {
|
|
return false
|
|
}
|
|
if completed[id] {
|
|
return false
|
|
}
|
|
if inProgress[id] {
|
|
hasCycle = true
|
|
return true
|
|
}
|
|
inProgress[id] = true
|
|
cyclePath = append(cyclePath, id)
|
|
|
|
if node, ok := analysis.Issues[id]; ok {
|
|
for _, depID := range node.DependsOn {
|
|
if detectCycle(depID) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
cyclePath = cyclePath[:len(cyclePath)-1]
|
|
inProgress[id] = false
|
|
completed[id] = true
|
|
return false
|
|
}
|
|
|
|
for id := range analysis.Issues {
|
|
if issueIsClosed(analysis, id) {
|
|
continue
|
|
}
|
|
if !completed[id] {
|
|
if detectCycle(id) {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if hasCycle {
|
|
analysis.Errors = append(analysis.Errors,
|
|
fmt.Sprintf("Dependency cycle detected involving: %v", cyclePath))
|
|
}
|
|
}
|
|
|
|
// computeReadyFronts calculates the waves of parallel work.
|
|
// Closed issues are excluded from waves and do not block dependents (GH#4564):
|
|
// a closed dependency is treated as already satisfied for ready-front purposes.
|
|
func computeReadyFronts(analysis *SwarmAnalysis) {
|
|
if len(analysis.Errors) > 0 {
|
|
// Can't compute ready fronts if there are cycles
|
|
return
|
|
}
|
|
|
|
isClosed := func(id string) bool {
|
|
return issueIsClosed(analysis, id)
|
|
}
|
|
|
|
// Kahn's algorithm over open issues only; in-degree counts open blockers.
|
|
inDegree := make(map[string]int)
|
|
for id, node := range analysis.Issues {
|
|
if isClosed(id) {
|
|
continue
|
|
}
|
|
openBlockers := 0
|
|
for _, depID := range node.DependsOn {
|
|
if !isClosed(depID) {
|
|
openBlockers++
|
|
}
|
|
}
|
|
inDegree[id] = openBlockers
|
|
}
|
|
|
|
// Wave 0: open issues with no open dependencies
|
|
var currentWave []string
|
|
for id, degree := range inDegree {
|
|
if degree == 0 {
|
|
currentWave = append(currentWave, id)
|
|
analysis.Issues[id].Wave = 0
|
|
}
|
|
}
|
|
|
|
wave := 0
|
|
for len(currentWave) > 0 {
|
|
// Sort for deterministic output
|
|
sort.Strings(currentWave)
|
|
|
|
// Build titles for this wave
|
|
var titles []string
|
|
for _, id := range currentWave {
|
|
if node, ok := analysis.Issues[id]; ok {
|
|
titles = append(titles, node.Title)
|
|
}
|
|
}
|
|
|
|
front := ReadyFront{
|
|
Wave: wave,
|
|
Issues: currentWave,
|
|
Titles: titles,
|
|
}
|
|
analysis.ReadyFronts = append(analysis.ReadyFronts, front)
|
|
|
|
// Track max parallelism
|
|
if len(currentWave) > analysis.MaxParallelism {
|
|
analysis.MaxParallelism = len(currentWave)
|
|
}
|
|
|
|
// Find next wave among open dependents
|
|
var nextWave []string
|
|
for _, id := range currentWave {
|
|
if node, ok := analysis.Issues[id]; ok {
|
|
for _, dependentID := range node.DependedOnBy {
|
|
if isClosed(dependentID) {
|
|
continue
|
|
}
|
|
if _, tracked := inDegree[dependentID]; !tracked {
|
|
continue
|
|
}
|
|
inDegree[dependentID]--
|
|
if inDegree[dependentID] == 0 {
|
|
nextWave = append(nextWave, dependentID)
|
|
analysis.Issues[dependentID].Wave = wave + 1
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
currentWave = nextWave
|
|
wave++
|
|
}
|
|
|
|
// Estimated sessions ≈ remaining open issues (each issue is roughly one session)
|
|
openCount := 0
|
|
for id := range analysis.Issues {
|
|
if !isClosed(id) {
|
|
openCount++
|
|
}
|
|
}
|
|
analysis.EstimatedSessions = openCount
|
|
}
|
|
|
|
// renderSwarmAnalysis outputs human-readable analysis.
|
|
func renderSwarmAnalysis(analysis *SwarmAnalysis) {
|
|
fmt.Printf("\n%s Swarm Analysis: %s\n", ui.RenderAccent("🐝"), analysis.EpicTitle)
|
|
fmt.Printf(" Epic ID: %s\n", analysis.EpicID)
|
|
fmt.Printf(" Total issues: %d (%d closed)\n", analysis.TotalIssues, analysis.ClosedIssues)
|
|
|
|
if analysis.TotalIssues == 0 {
|
|
fmt.Printf("\n%s Epic has no children to swarm\n\n", ui.RenderWarn("⚠"))
|
|
return
|
|
}
|
|
|
|
// Ready fronts
|
|
if len(analysis.ReadyFronts) > 0 {
|
|
fmt.Printf("\n%s Ready Fronts (waves of parallel work):\n", ui.RenderPass("📊"))
|
|
for _, front := range analysis.ReadyFronts {
|
|
fmt.Printf(" Wave %d: %d issues\n", front.Wave+1, len(front.Issues))
|
|
for i, id := range front.Issues {
|
|
title := ""
|
|
if i < len(front.Titles) {
|
|
title = front.Titles[i]
|
|
}
|
|
fmt.Printf(" • %s: %s\n", ui.RenderID(id), title)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Summary stats
|
|
fmt.Printf("\n%s Summary:\n", ui.RenderAccent("📈"))
|
|
fmt.Printf(" Estimated worker-sessions: %d\n", analysis.EstimatedSessions)
|
|
fmt.Printf(" Max parallelism: %d\n", analysis.MaxParallelism)
|
|
fmt.Printf(" Total waves: %d\n", len(analysis.ReadyFronts))
|
|
|
|
// Warnings
|
|
if len(analysis.Warnings) > 0 {
|
|
fmt.Printf("\n%s Warnings:\n", ui.RenderWarn("⚠"))
|
|
for _, warning := range analysis.Warnings {
|
|
fmt.Printf(" • %s\n", warning)
|
|
}
|
|
}
|
|
|
|
// Errors
|
|
if len(analysis.Errors) > 0 {
|
|
fmt.Printf("\n%s Errors:\n", ui.RenderFail("❌"))
|
|
for _, err := range analysis.Errors {
|
|
fmt.Printf(" • %s\n", err)
|
|
}
|
|
}
|
|
|
|
// Final verdict
|
|
fmt.Println()
|
|
if analysis.Swarmable {
|
|
fmt.Printf("%s Swarmable: YES\n\n", ui.RenderPass("✓"))
|
|
} else {
|
|
fmt.Printf("%s Swarmable: NO (fix errors first)\n\n", ui.RenderFail("✗"))
|
|
}
|
|
}
|
|
|
|
// SwarmStatus holds the current status of a swarm (computed from beads).
|
|
type SwarmStatus struct {
|
|
EpicID string `json:"epic_id"`
|
|
EpicTitle string `json:"epic_title"`
|
|
TotalIssues int `json:"total_issues"`
|
|
Completed []StatusIssue `json:"completed"`
|
|
Active []StatusIssue `json:"active"`
|
|
Ready []StatusIssue `json:"ready"`
|
|
Blocked []StatusIssue `json:"blocked"`
|
|
Progress float64 `json:"progress_percent"`
|
|
ActiveCount int `json:"active_count"`
|
|
ReadyCount int `json:"ready_count"`
|
|
BlockedCount int `json:"blocked_count"`
|
|
}
|
|
|
|
// StatusIssue represents an issue in swarm status output.
|
|
type StatusIssue struct {
|
|
ID string `json:"id"`
|
|
Title string `json:"title"`
|
|
Assignee string `json:"assignee,omitempty"`
|
|
BlockedBy []string `json:"blocked_by,omitempty"`
|
|
ClosedAt string `json:"closed_at,omitempty"`
|
|
}
|
|
|
|
var swarmStatusCmd = &cobra.Command{
|
|
Use: "status [epic-or-swarm-id]",
|
|
Short: "Show current swarm status",
|
|
Long: `Show the current status of a swarm, computed from beads.
|
|
|
|
Accepts either:
|
|
- An epic ID (shows status for that epic's children)
|
|
- A swarm molecule ID (follows the link to find the epic)
|
|
|
|
Displays issues grouped by state:
|
|
- Completed: Closed issues
|
|
- Active: Issues currently in_progress (with assignee)
|
|
- Ready: Open issues with all dependencies satisfied
|
|
- Blocked: Open issues waiting on dependencies
|
|
|
|
The status is COMPUTED from beads, not stored separately.
|
|
If beads changes, status changes.
|
|
|
|
Examples:
|
|
bd swarm status gt-epic-123 # Show swarm status by epic
|
|
bd swarm status gt-swarm-456 # Show status via swarm molecule
|
|
bd swarm status gt-epic-123 --json # Machine-readable output`,
|
|
Args: cobra.ExactArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
if usesProxiedServer() {
|
|
return runSwarmStatusProxiedServer(cmd, rootCtx, args)
|
|
}
|
|
evt := metrics.NewCommandEvent("swarm-status")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
ctx := rootCtx
|
|
|
|
if store == nil {
|
|
return HandleErrorRespectJSON("no database connection")
|
|
}
|
|
|
|
issueID, err := utils.ResolvePartialID(ctx, store, args[0])
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("issue '%s' not found: %v", args[0], err)
|
|
}
|
|
|
|
issue, err := store.GetIssue(ctx, issueID)
|
|
if err != nil {
|
|
if errors.Is(err, storage.ErrNotFound) {
|
|
return HandleErrorRespectJSON("issue '%s' not found", issueID)
|
|
}
|
|
return HandleErrorRespectJSON("failed to get issue: %v", err)
|
|
}
|
|
|
|
var epic *types.Issue
|
|
|
|
if issue.IssueType == "molecule" && issue.MolType == types.MolTypeSwarm {
|
|
deps, err := store.GetDependencyRecords(ctx, issue.ID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to get swarm dependencies: %v", err)
|
|
}
|
|
for _, dep := range deps {
|
|
if dep.Type == types.DepRelatesTo {
|
|
epic, err = store.GetIssue(ctx, dep.DependsOnID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to get linked epic: %v", err)
|
|
}
|
|
break
|
|
}
|
|
}
|
|
if epic == nil {
|
|
return HandleErrorRespectJSON("swarm molecule '%s' has no linked epic", issueID)
|
|
}
|
|
} else if issue.IssueType == types.TypeEpic || issue.IssueType == "molecule" {
|
|
epic = issue
|
|
} else {
|
|
return HandleErrorRespectJSON("'%s' is not an epic or swarm molecule (type: %s)", issueID, issue.IssueType)
|
|
}
|
|
|
|
status, err := getSwarmStatus(ctx, store, epic)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to get swarm status: %v", err)
|
|
}
|
|
|
|
if jsonOutput {
|
|
return outputJSON(status)
|
|
}
|
|
|
|
renderSwarmStatus(status)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// getSwarmStatus computes current swarm status from beads.
|
|
func getSwarmStatus(ctx context.Context, s SwarmStorage, epic *types.Issue) (*SwarmStatus, error) {
|
|
status := &SwarmStatus{
|
|
EpicID: epic.ID,
|
|
EpicTitle: epic.Title,
|
|
Completed: []StatusIssue{},
|
|
Active: []StatusIssue{},
|
|
Ready: []StatusIssue{},
|
|
Blocked: []StatusIssue{},
|
|
}
|
|
|
|
// Get all child issues of the epic
|
|
childIssues, err := getEpicChildren(ctx, s, epic.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
status.TotalIssues = len(childIssues)
|
|
if len(childIssues) == 0 {
|
|
return status, nil
|
|
}
|
|
|
|
// Build set of child IDs for filtering
|
|
childIDSet := make(map[string]bool)
|
|
for _, issue := range childIssues {
|
|
childIDSet[issue.ID] = true
|
|
}
|
|
|
|
// Build dependency map (within epic children only)
|
|
dependsOn := make(map[string][]string)
|
|
for _, issue := range childIssues {
|
|
deps, err := s.GetDependencyRecords(ctx, issue.ID)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, dep := range deps {
|
|
// Skip parent-child to epic itself
|
|
if dep.DependsOnID == epic.ID && dep.Type == types.DepParentChild {
|
|
continue
|
|
}
|
|
// Only track blocking dependencies within children
|
|
if !dep.Type.AffectsReadyWork() {
|
|
continue
|
|
}
|
|
if childIDSet[dep.DependsOnID] {
|
|
dependsOn[issue.ID] = append(dependsOn[issue.ID], dep.DependsOnID)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Categorize each issue
|
|
for _, issue := range childIssues {
|
|
si := StatusIssue{
|
|
ID: issue.ID,
|
|
Title: issue.Title,
|
|
Assignee: issue.Assignee,
|
|
}
|
|
|
|
switch issue.Status {
|
|
case types.StatusClosed:
|
|
if issue.ClosedAt != nil {
|
|
si.ClosedAt = issue.ClosedAt.Format("2006-01-02 15:04")
|
|
}
|
|
status.Completed = append(status.Completed, si)
|
|
|
|
case types.StatusInProgress:
|
|
status.Active = append(status.Active, si)
|
|
|
|
default: // open or other
|
|
// Check if blocked by open dependencies
|
|
deps := dependsOn[issue.ID]
|
|
var blockers []string
|
|
for _, depID := range deps {
|
|
depIssue, _ := s.GetIssue(ctx, depID)
|
|
if depIssue != nil && depIssue.Status != types.StatusClosed {
|
|
blockers = append(blockers, depID)
|
|
}
|
|
}
|
|
|
|
if len(blockers) > 0 {
|
|
si.BlockedBy = blockers
|
|
status.Blocked = append(status.Blocked, si)
|
|
} else {
|
|
status.Ready = append(status.Ready, si)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Sort each category by ID for consistent output
|
|
sort.Slice(status.Completed, func(i, j int) bool {
|
|
return utils.NaturalCompareIDs(status.Completed[i].ID, status.Completed[j].ID) < 0
|
|
})
|
|
sort.Slice(status.Active, func(i, j int) bool {
|
|
return utils.NaturalCompareIDs(status.Active[i].ID, status.Active[j].ID) < 0
|
|
})
|
|
sort.Slice(status.Ready, func(i, j int) bool {
|
|
return utils.NaturalCompareIDs(status.Ready[i].ID, status.Ready[j].ID) < 0
|
|
})
|
|
sort.Slice(status.Blocked, func(i, j int) bool {
|
|
return utils.NaturalCompareIDs(status.Blocked[i].ID, status.Blocked[j].ID) < 0
|
|
})
|
|
|
|
// Compute counts and progress
|
|
status.ActiveCount = len(status.Active)
|
|
status.ReadyCount = len(status.Ready)
|
|
status.BlockedCount = len(status.Blocked)
|
|
if status.TotalIssues > 0 {
|
|
status.Progress = float64(len(status.Completed)) / float64(status.TotalIssues) * 100
|
|
}
|
|
|
|
return status, nil
|
|
}
|
|
|
|
// renderSwarmStatus outputs human-readable swarm status.
|
|
func renderSwarmStatus(status *SwarmStatus) {
|
|
fmt.Printf("\n%s Ready Front Analysis: %s\n\n", ui.RenderAccent("🐝"), status.EpicTitle)
|
|
|
|
// Completed
|
|
fmt.Printf("Completed: ")
|
|
if len(status.Completed) == 0 {
|
|
fmt.Printf("(none)\n")
|
|
} else {
|
|
for i, issue := range status.Completed {
|
|
if i > 0 {
|
|
fmt.Printf(" ")
|
|
}
|
|
fmt.Printf("%s %s\n", ui.RenderPass("✓"), ui.RenderID(issue.ID))
|
|
}
|
|
}
|
|
|
|
// Active
|
|
fmt.Printf("Active: ")
|
|
if len(status.Active) == 0 {
|
|
fmt.Printf("(none)\n")
|
|
} else {
|
|
var parts []string
|
|
for _, issue := range status.Active {
|
|
part := fmt.Sprintf("⟳ %s", issue.ID)
|
|
if issue.Assignee != "" {
|
|
part += fmt.Sprintf(" [%s]", issue.Assignee)
|
|
}
|
|
parts = append(parts, part)
|
|
}
|
|
fmt.Printf("%s\n", strings.Join(parts, ", "))
|
|
}
|
|
|
|
// Ready
|
|
fmt.Printf("Ready: ")
|
|
if len(status.Ready) == 0 {
|
|
if len(status.Blocked) > 0 {
|
|
// Find what's blocking
|
|
needed := make(map[string]bool)
|
|
for _, b := range status.Blocked {
|
|
for _, dep := range b.BlockedBy {
|
|
needed[dep] = true
|
|
}
|
|
}
|
|
var neededList []string
|
|
for dep := range needed {
|
|
neededList = append(neededList, dep)
|
|
}
|
|
sort.Strings(neededList)
|
|
fmt.Printf("(none - waiting for %s)\n", strings.Join(neededList, ", "))
|
|
} else {
|
|
fmt.Printf("(none)\n")
|
|
}
|
|
} else {
|
|
var parts []string
|
|
for _, issue := range status.Ready {
|
|
parts = append(parts, fmt.Sprintf("○ %s", issue.ID))
|
|
}
|
|
fmt.Printf("%s\n", strings.Join(parts, ", "))
|
|
}
|
|
|
|
// Blocked
|
|
fmt.Printf("Blocked: ")
|
|
if len(status.Blocked) == 0 {
|
|
fmt.Printf("(none)\n")
|
|
} else {
|
|
for i, issue := range status.Blocked {
|
|
if i > 0 {
|
|
fmt.Printf(" ")
|
|
}
|
|
blockerStr := strings.Join(issue.BlockedBy, ", ")
|
|
fmt.Printf("◌ %s (needs %s)\n", issue.ID, blockerStr)
|
|
}
|
|
}
|
|
|
|
// Progress summary
|
|
fmt.Printf("\nProgress: %d/%d complete", len(status.Completed), status.TotalIssues)
|
|
if status.ActiveCount > 0 {
|
|
fmt.Printf(", %d/%d active", status.ActiveCount, status.TotalIssues)
|
|
}
|
|
fmt.Printf(" (%.0f%%)\n\n", status.Progress)
|
|
}
|
|
|
|
var swarmCreateCmd = &cobra.Command{
|
|
Use: "create [epic-id]",
|
|
Short: "Create a swarm molecule from an epic",
|
|
Long: `Create a swarm molecule to orchestrate parallel work on an epic.
|
|
|
|
The swarm molecule:
|
|
- Links to the epic it orchestrates
|
|
- Has mol_type=swarm for discovery
|
|
- Specifies a coordinator (optional)
|
|
- Can be picked up by any coordinator agent
|
|
|
|
If given a single issue (not an epic), it will be auto-wrapped:
|
|
- Creates an epic with that issue as its only child
|
|
- Then creates the swarm molecule for that epic
|
|
|
|
Examples:
|
|
bd swarm create bd-epic-123 # Create swarm for epic
|
|
bd swarm create bd-epic-123 --coordinator=observer/ # With specific coordinator
|
|
bd swarm create bd-task-456 # Auto-wrap single issue`,
|
|
Args: cobra.ExactArgs(1),
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
if usesProxiedServer() {
|
|
return HandleErrorRespectJSON("swarm create is not supported in proxied-server mode")
|
|
}
|
|
CheckReadonly("swarm create")
|
|
|
|
evt := metrics.NewCommandEvent("swarm-create")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
ctx := rootCtx
|
|
coordinator, _ := cmd.Flags().GetString("coordinator")
|
|
force, _ := cmd.Flags().GetBool("force")
|
|
|
|
if store == nil {
|
|
return HandleErrorRespectJSON("no database connection")
|
|
}
|
|
|
|
inputID, err := utils.ResolvePartialID(ctx, store, args[0])
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("issue '%s' not found: %v", args[0], err)
|
|
}
|
|
|
|
issue, err := store.GetIssue(ctx, inputID)
|
|
if err != nil {
|
|
if errors.Is(err, storage.ErrNotFound) {
|
|
return HandleErrorRespectJSON("issue '%s' not found", inputID)
|
|
}
|
|
return HandleErrorRespectJSON("failed to get issue: %v", err)
|
|
}
|
|
|
|
var epicID string
|
|
var epicTitle string
|
|
|
|
if issue.IssueType == types.TypeEpic || issue.IssueType == "molecule" {
|
|
epicID = issue.ID
|
|
epicTitle = issue.Title
|
|
} else {
|
|
if !jsonOutput {
|
|
fmt.Printf("Auto-wrapping single issue as epic...\n")
|
|
}
|
|
|
|
wrapperEpic := &types.Issue{
|
|
Title: fmt.Sprintf("Swarm Epic: %s", issue.Title),
|
|
Description: fmt.Sprintf("Auto-generated epic to wrap single issue %s for swarm execution.", issue.ID),
|
|
Status: types.StatusOpen,
|
|
Priority: issue.Priority,
|
|
IssueType: types.TypeEpic,
|
|
CreatedBy: currentActor(),
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, wrapperEpic, currentActor()); err != nil {
|
|
return HandleErrorRespectJSON("failed to create wrapper epic: %v", err)
|
|
}
|
|
|
|
dep := &types.Dependency{
|
|
IssueID: issue.ID,
|
|
DependsOnID: wrapperEpic.ID,
|
|
Type: types.DepParentChild,
|
|
CreatedBy: currentActor(),
|
|
}
|
|
if err := store.AddDependency(ctx, dep, currentActor()); err != nil {
|
|
return HandleErrorRespectJSON("failed to link issue to epic: %v", err)
|
|
}
|
|
|
|
epicID = wrapperEpic.ID
|
|
epicTitle = wrapperEpic.Title
|
|
|
|
if !jsonOutput {
|
|
fmt.Printf("Created wrapper epic: %s\n", epicID)
|
|
}
|
|
}
|
|
|
|
existingSwarm, err := findExistingSwarm(ctx, store, epicID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to check for existing swarm: %v", err)
|
|
}
|
|
if existingSwarm != nil && !force {
|
|
if jsonOutput {
|
|
if jerr := outputJSON(map[string]interface{}{
|
|
"error": "swarm already exists",
|
|
"existing_id": existingSwarm.ID,
|
|
"existing_title": existingSwarm.Title,
|
|
}); jerr != nil {
|
|
return jerr
|
|
}
|
|
return SilentExit()
|
|
}
|
|
fmt.Printf("%s Swarm already exists: %s\n", ui.RenderWarn("⚠"), ui.RenderID(existingSwarm.ID))
|
|
fmt.Printf(" Use --force to create another.\n")
|
|
return SilentExit()
|
|
}
|
|
|
|
epic, err := store.GetIssue(ctx, epicID)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to get epic: %v", err)
|
|
}
|
|
|
|
analysis, err := analyzeEpicForSwarm(ctx, store, epic)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to analyze epic: %v", err)
|
|
}
|
|
|
|
if !analysis.Swarmable {
|
|
if jsonOutput {
|
|
if jerr := outputJSON(map[string]interface{}{
|
|
"error": "epic is not swarmable",
|
|
"analysis": analysis,
|
|
}); jerr != nil {
|
|
return jerr
|
|
}
|
|
return SilentExit()
|
|
}
|
|
fmt.Printf("\n%s Epic is not swarmable. Fix errors first:\n", ui.RenderFail("✗"))
|
|
for _, e := range analysis.Errors {
|
|
fmt.Printf(" • %s\n", e)
|
|
}
|
|
return SilentExit()
|
|
}
|
|
|
|
swarmMol := &types.Issue{
|
|
Title: fmt.Sprintf("Swarm: %s", epicTitle),
|
|
Description: fmt.Sprintf("Swarm molecule orchestrating epic %s.\n\nEpic: %s\nCoordinator: %s", epicID, epicID, coordinator),
|
|
Status: types.StatusOpen,
|
|
Priority: epic.Priority,
|
|
IssueType: "molecule",
|
|
MolType: types.MolTypeSwarm,
|
|
Assignee: coordinator,
|
|
CreatedBy: currentActor(),
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, swarmMol, currentActor()); err != nil {
|
|
return HandleErrorRespectJSON("failed to create swarm molecule: %v", err)
|
|
}
|
|
|
|
dep := &types.Dependency{
|
|
IssueID: swarmMol.ID,
|
|
DependsOnID: epicID,
|
|
Type: types.DepRelatesTo,
|
|
CreatedBy: currentActor(),
|
|
}
|
|
if err := store.AddDependency(ctx, dep, currentActor()); err != nil {
|
|
return HandleErrorRespectJSON("failed to link swarm to epic: %v", err)
|
|
}
|
|
|
|
commandDidWrite.Store(true)
|
|
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{
|
|
"swarm_id": swarmMol.ID,
|
|
"epic_id": epicID,
|
|
"coordinator": coordinator,
|
|
"analysis": analysis,
|
|
})
|
|
}
|
|
fmt.Printf("\n%s Created swarm molecule: %s\n", ui.RenderPass("✓"), ui.RenderID(swarmMol.ID))
|
|
fmt.Printf(" Epic: %s (%s)\n", epicID, epicTitle)
|
|
if coordinator != "" {
|
|
fmt.Printf(" Coordinator: %s\n", coordinator)
|
|
}
|
|
fmt.Printf(" Total issues: %d\n", analysis.TotalIssues)
|
|
fmt.Printf(" Max parallelism: %d\n", analysis.MaxParallelism)
|
|
fmt.Printf(" Waves: %d\n", len(analysis.ReadyFronts))
|
|
return nil
|
|
},
|
|
}
|
|
|
|
var swarmListCmd = &cobra.Command{
|
|
Use: "list",
|
|
Short: "List all swarm molecules",
|
|
Long: `List all swarm molecules with their status.
|
|
|
|
Shows each swarm molecule with:
|
|
- Progress (completed/total issues)
|
|
- Active workers
|
|
- Epic ID and title
|
|
|
|
Examples:
|
|
bd swarm list # List all swarms
|
|
bd swarm list --json # Machine-readable output`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
if usesProxiedServer() {
|
|
return HandleErrorRespectJSON("swarm list is not supported in proxied-server mode")
|
|
}
|
|
evt := metrics.NewCommandEvent("swarm-list")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
ctx := rootCtx
|
|
|
|
if store == nil {
|
|
return HandleErrorRespectJSON("no database connection")
|
|
}
|
|
|
|
swarmType := types.MolTypeSwarm
|
|
filter := types.IssueFilter{
|
|
MolType: &swarmType,
|
|
}
|
|
swarms, err := store.SearchIssues(ctx, "", filter)
|
|
if err != nil {
|
|
return HandleErrorRespectJSON("failed to list swarms: %v", err)
|
|
}
|
|
|
|
if len(swarms) == 0 {
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{"swarms": []interface{}{}})
|
|
}
|
|
fmt.Printf("No swarm molecules found.\n")
|
|
return nil
|
|
}
|
|
|
|
// Build output with status for each swarm
|
|
type SwarmListItem struct {
|
|
ID string `json:"id"`
|
|
Title string `json:"title"`
|
|
EpicID string `json:"epic_id"`
|
|
EpicTitle string `json:"epic_title"`
|
|
Status string `json:"status"`
|
|
Coordinator string `json:"coordinator"`
|
|
Total int `json:"total_issues"`
|
|
Completed int `json:"completed_issues"`
|
|
Active int `json:"active_issues"`
|
|
Progress float64 `json:"progress_percent"`
|
|
}
|
|
|
|
var items []SwarmListItem
|
|
for _, swarm := range swarms {
|
|
item := SwarmListItem{
|
|
ID: swarm.ID,
|
|
Title: swarm.Title,
|
|
Status: string(swarm.Status),
|
|
Coordinator: swarm.Assignee,
|
|
}
|
|
|
|
// Find linked epic via relates-to dependency
|
|
deps, err := store.GetDependencyRecords(ctx, swarm.ID)
|
|
if err == nil {
|
|
for _, dep := range deps {
|
|
if dep.Type == types.DepRelatesTo {
|
|
item.EpicID = dep.DependsOnID
|
|
epic, err := store.GetIssue(ctx, dep.DependsOnID)
|
|
if err == nil && epic != nil {
|
|
item.EpicTitle = epic.Title
|
|
// Get swarm status for this epic
|
|
status, err := getSwarmStatus(ctx, store, epic)
|
|
if err == nil {
|
|
item.Total = status.TotalIssues
|
|
item.Completed = len(status.Completed)
|
|
item.Active = status.ActiveCount
|
|
item.Progress = status.Progress
|
|
}
|
|
}
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
items = append(items, item)
|
|
}
|
|
|
|
if jsonOutput {
|
|
return outputJSON(map[string]interface{}{"swarms": items})
|
|
}
|
|
|
|
fmt.Printf("\n%s Active Swarms (%d)\n\n", ui.RenderAccent("🐝"), len(items))
|
|
for _, item := range items {
|
|
progressStr := fmt.Sprintf("%d/%d", item.Completed, item.Total)
|
|
if item.Active > 0 {
|
|
progressStr += fmt.Sprintf(", %d active", item.Active)
|
|
}
|
|
|
|
fmt.Printf("%s %s\n", ui.RenderID(item.ID), item.Title)
|
|
if item.EpicID != "" {
|
|
fmt.Printf(" Epic: %s (%s)\n", item.EpicID, item.EpicTitle)
|
|
}
|
|
fmt.Printf(" Progress: %s (%.0f%%)\n", progressStr, item.Progress)
|
|
if item.Coordinator != "" {
|
|
fmt.Printf(" Coordinator: %s\n", item.Coordinator)
|
|
}
|
|
fmt.Println()
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
swarmValidateCmd.Flags().Bool("verbose", false, "Include detailed issue graph in output")
|
|
swarmCreateCmd.Flags().String("coordinator", "", "Coordinator address (e.g., my-project/witness)")
|
|
swarmCreateCmd.Flags().Bool("force", false, "Create new swarm even if one already exists")
|
|
|
|
swarmCmd.AddCommand(swarmValidateCmd)
|
|
swarmCmd.AddCommand(swarmStatusCmd)
|
|
swarmCmd.AddCommand(swarmCreateCmd)
|
|
swarmCmd.AddCommand(swarmListCmd)
|
|
rootCmd.AddCommand(swarmCmd)
|
|
}
|