refactor: remove multi-rig routing from beads

Remove the entire multi-rig routing engine (routes.go, route resolution,
prefix-based dispatch) and cross-rig commands (move, refile). All bd
commands now operate on the local rig only.

Deleted: internal/routing/routes.go, cmd/bd/move.go, cmd/bd/refile.go,
and 5 associated test files.

Simplified: routed.go, close.go, create.go, dep.go, gate.go, list.go,
ready.go, promote.go, show.go, show_display.go.

Retained: contributor routing (routing.go, routing_read.go) is unchanged.

Resolves: bd-8hc5

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
beads/crew/emma 2026-03-27 19:53:13 -07:00 • committed by Steve Yegge
commit d7629204f9
19 changed files with 38 additions and 3514 deletions

View file

@ -101,27 +101,20 @@ create, update, show, or close operation).`,
FatalErrorRespectJSON("--suggest-next only works when closing a single issue")
}
// Resolve partial IDs first, handling cross-rig routing
// Resolve partial IDs
var resolvedIDs []string
var routedArgs []string // IDs that need cross-repo routing
// Direct mode - check routing for each ID
for _, id := range args {
if needsRouting(id) {
routedArgs = append(routedArgs, id)
} else {
resolved, err := utils.ResolvePartialID(ctx, store, id)
if err != nil {
FatalErrorRespectJSON("resolving ID %s: %v", id, err)
}
resolvedIDs = append(resolvedIDs, resolved)
resolved, err := utils.ResolvePartialID(ctx, store, id)
if err != nil {
FatalErrorRespectJSON("resolving ID %s: %v", id, err)
}
resolvedIDs = append(resolvedIDs, resolved)
}
// Direct mode
closedIssues := []*types.Issue{}
closedCount := 0
// Handle local IDs
for _, id := range resolvedIDs {
// Get issue for checks (nil issue is handled by validateIssueClosable)
issue, _ := store.GetIssue(ctx, id)
@ -197,82 +190,6 @@ create, update, show, or close operation).`,
}
}
// Handle routed IDs (cross-rig)
for _, id := range routedArgs {
result, err := resolveAndGetIssueWithRouting(ctx, store, id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
continue
}
if result == nil || result.Issue == nil {
if result != nil {
result.Close()
}
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)
continue
}
if err := validateIssueClosable(result.ResolvedID, result.Issue, force); err != nil {
result.Close()
fmt.Fprintf(os.Stderr, "%s\n", err)
continue
}
// Check gate satisfaction for machine-checkable gates (GH#1467)
if !force {
if err := checkGateSatisfaction(result.Issue); err != nil {
result.Close()
fmt.Fprintf(os.Stderr, "cannot close %s: %s\n", id, err)
continue
}
}
// Check if issue has open blockers (GH#962)
if !force {
blocked, blockers, err := result.Store.IsBlocked(ctx, result.ResolvedID)
if err != nil {
result.Close()
fmt.Fprintf(os.Stderr, "Error checking blockers for %s: %v\n", id, err)
continue
}
if blocked && len(blockers) > 0 {
result.Close()
fmt.Fprintf(os.Stderr, "cannot close %s: blocked by open issues %v (use --force to override)\n", id, blockers)
continue
}
}
if err := result.Store.CloseIssue(ctx, result.ResolvedID, reason, actor, session); err != nil {
result.Close()
fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", id, err)
continue
}
closedCount++
// Auto-close parent molecule if all steps are now complete
autoCloseCompletedMolecule(ctx, result.Store, result.ResolvedID, actor, session)
// Run hooks (best effort: hooks run only if re-fetch succeeds)
closedIssue, _ := result.Store.GetIssue(ctx, result.ResolvedID)
if closedIssue != nil && hookRunner != nil {
// Fire on_update only if status actually changed (GH#2630)
if result.Issue == nil || result.Issue.Status != types.StatusClosed {
hookRunner.Run(hooks.EventUpdate, closedIssue)
}
hookRunner.Run(hooks.EventClose, closedIssue)
}
if jsonOutput {
if closedIssue != nil {
closedIssues = append(closedIssues, closedIssue)
}
} else {
fmt.Printf("%s Closed %s: %s\n", ui.RenderPass("✓"), formatFeedbackID(result.ResolvedID, result.Issue.Title), reason)
}
result.Close()
}
// Handle --suggest-next flag in direct mode
if suggestNext && len(resolvedIDs) == 1 && closedCount > 0 {
unblocked, err := store.GetNewlyUnblockedByClose(ctx, resolvedIDs[0])
@ -360,7 +277,7 @@ create, update, show, or close operation).`,
// Exit non-zero if no issues were actually closed (close guard
// and other soft failures should surface as non-zero exit codes for scripting)
totalAttempted := len(resolvedIDs) + len(routedArgs)
totalAttempted := len(resolvedIDs)
if totalAttempted > 0 && closedCount == 0 {
os.Exit(1)
}

View file

@ -11,7 +11,6 @@ import (
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/hooks"
@ -159,8 +158,6 @@ var createCmd = &cobra.Command{
waitsForGate, _ := cmd.Flags().GetString("waits-for-gate")
forceCreate, _ := cmd.Flags().GetBool("force")
repoOverride, _ := cmd.Flags().GetString("repo")
rigOverride, _ := cmd.Flags().GetString("rig")
prefixOverride, _ := cmd.Flags().GetString("prefix")
wisp, _ := cmd.Flags().GetBool("ephemeral")
noHistory, _ := cmd.Flags().GetBool("no-history")
if wisp && noHistory {
@ -330,13 +327,6 @@ var createCmd = &cobra.Command{
if len(deps) > 0 {
fmt.Printf(" Dependencies: %s\n", strings.Join(deps, ", "))
}
if rigOverride != "" || prefixOverride != "" {
rig := rigOverride
if rig == "" {
rig = prefixOverride
}
fmt.Printf(" Target rig: %s\n", rig)
}
if eventCategory != "" {
fmt.Printf(" Event category: %s\n", eventCategory)
}
@ -344,47 +334,6 @@ var createCmd = &cobra.Command{
return
}
// Auto-route based on explicit ID prefix (if no explicit --rig/--prefix provided)
// When creating an issue with --id=pq-xxx, automatically route to the database
// that handles the pq- prefix based on routes.jsonl
if explicitID != "" && rigOverride == "" && prefixOverride == "" {
prefix := routing.ExtractPrefix(explicitID)
if prefix != "" {
// Load routes from town level
townBeadsDir, err := findTownBeadsDir()
if err == nil {
routes, err := routing.LoadTownRoutes(townBeadsDir)
if err == nil && len(routes) > 0 {
// Check if this prefix matches a route to a different rig
for _, route := range routes {
if route.Prefix == prefix && route.Path != "" && route.Path != "." {
// Found a matching route - auto-route to that rig
rigName := routing.ExtractProjectFromPath(route.Path)
if rigName != "" {
createInRig(cmd, rigName, explicitID, title, description, issueType, priority, design, acceptance, notes, assignee, labels, externalRef, specID, wisp, noHistory)
return
}
}
}
}
}
}
}
// Handle --rig or --prefix flag: create issue in a different rig
// Both flags use the same forgiving lookup (accepts rig names or prefixes)
targetRig := rigOverride
if prefixOverride != "" {
if targetRig != "" {
FatalError("cannot specify both --rig and --prefix flags")
}
targetRig = prefixOverride
}
if targetRig != "" {
createInRig(cmd, targetRig, explicitID, title, description, issueType, priority, design, acceptance, notes, assignee, labels, externalRef, specID, wisp, noHistory)
return
}
// Get estimate if provided
var estimatedMinutes *int
if cmd.Flags().Changed("estimate") {
@ -829,8 +778,6 @@ func init() {
createCmd.Flags().String("waits-for-gate", "all-children", "Gate type: all-children (wait for all) or any-children (wait for first)")
createCmd.Flags().Bool("force", false, "Force creation even if prefix doesn't match database prefix")
createCmd.Flags().String("repo", "", "Target repository for issue (overrides auto-routing)")
createCmd.Flags().String("rig", "", "Create issue in a different rig (e.g., --rig beads)")
createCmd.Flags().String("prefix", "", "Create issue in rig by prefix (e.g., --prefix bd- or --prefix bd or --prefix beads)")
createCmd.Flags().IntP("estimate", "e", 0, "Time estimate in minutes (e.g., 60 for 1 hour)")
createCmd.Flags().Bool("ephemeral", false, "Create as ephemeral (short-lived, subject to TTL compaction)")
createCmd.Flags().Bool("no-history", false, "Skip Dolt commit history without making GC-eligible (for permanent agent beads)")
@ -857,184 +804,6 @@ func init() {
rootCmd.AddCommand(createCmd)
}
// createInRig creates an issue in a different rig using --rig flag or auto-routing.
// This directly creates in the target rig's database.
func createInRig(cmd *cobra.Command, rigName, explicitID, title, description, issueType string, priority int, design, acceptance, notes, assignee string, labels []string, externalRef, specID string, wisp, noHistory bool) {
ctx := rootCtx
// Find the town-level beads directory (where routes.jsonl lives)
townBeadsDir, err := findTownBeadsDir()
if err != nil {
FatalError("cannot use --rig: %v", err)
}
// Resolve the target rig's beads directory and prefix
targetBeadsDir, targetPrefix, err := routing.ResolveBeadsDirForRig(rigName, townBeadsDir)
if err != nil {
FatalError("%v", err)
}
// Open storage for the target rig using factory to respect backend config
targetStore, err := newDoltStoreFromConfig(ctx, targetBeadsDir)
if err != nil {
FatalError("failed to open rig %q database: %v", rigName, err)
}
defer func() {
if err := targetStore.Close(); err != nil {
fmt.Fprintf(os.Stderr, "warning: failed to close rig database: %v\n", err)
}
}()
// Prepare prefix override from routes.jsonl for cross-rig creation
// Strip trailing hyphen - database stores prefix without it (e.g., "aops" not "aops-")
var prefixOverride string
if targetPrefix != "" {
prefixOverride = strings.TrimSuffix(targetPrefix, "-")
}
var externalRefPtr *string
if externalRef != "" {
externalRefPtr = &externalRef
}
// Extract event-specific flags (bd-xwvo fix)
eventCategory, _ := cmd.Flags().GetString("event-category")
eventActor, _ := cmd.Flags().GetString("event-actor")
eventTarget, _ := cmd.Flags().GetString("event-target")
eventPayload, _ := cmd.Flags().GetString("event-payload")
// Extract molecule/agent flags (bd-xwvo fix)
molTypeStr, _ := cmd.Flags().GetString("mol-type")
var molType types.MolType
if molTypeStr != "" {
molType = types.MolType(molTypeStr)
}
// Extract wisp type (TTL classification for ephemeral wisps)
wispTypeStr, _ := cmd.Flags().GetString("wisp-type")
var wispType types.WispType
if wispTypeStr != "" {
wispType = types.WispType(wispTypeStr)
}
// Extract time-based scheduling flags (bd-xwvo fix)
var dueAt *time.Time
dueStr, _ := cmd.Flags().GetString("due")
if dueStr != "" {
t, err := timeparsing.ParseRelativeTime(dueStr, time.Now())
if err != nil {
FatalError("invalid --due format %q", dueStr)
}
dueAt = &t
}
var deferUntil *time.Time
deferStr, _ := cmd.Flags().GetString("defer")
if deferStr != "" {
t, err := timeparsing.ParseRelativeTime(deferStr, time.Now())
if err != nil {
FatalError("invalid --defer format %q", deferStr)
}
deferUntil = &t
}
// Parse --metadata for cross-rig creation
var metadata json.RawMessage
if cmd.Flags().Changed("metadata") {
metadataValue, _ := cmd.Flags().GetString("metadata")
var metadataJSON string
if strings.HasPrefix(metadataValue, "@") {
filePath := metadataValue[1:]
// #nosec G304 -- user explicitly provides file path via @file.json syntax
data, err := os.ReadFile(filePath)
if err != nil {
FatalError("failed to read metadata file %s: %v", filePath, err)
}
metadataJSON = string(data)
} else {
metadataJSON = metadataValue
}
if !json.Valid([]byte(metadataJSON)) {
FatalError("invalid JSON in --metadata: must be valid JSON")
}
metadata = json.RawMessage(metadataJSON)
}
// Create issue with explicit ID if provided, otherwise CreateIssue will generate one
issue := &types.Issue{
ID: explicitID, // Set explicit ID if provided (empty string if not)
Title: title,
Description: description,
Design: design,
AcceptanceCriteria: acceptance,
Notes: notes,
SpecID: specID,
Status: types.StatusOpen,
Priority: priority,
IssueType: types.IssueType(issueType).Normalize(),
Assignee: assignee,
ExternalRef: externalRefPtr,
Ephemeral: wisp,
NoHistory: noHistory,
CreatedBy: getActorWithGit(),
Owner: getOwner(),
// Event fields (bd-xwvo fix)
EventKind: eventCategory,
Actor: eventActor,
Target: eventTarget,
Payload: eventPayload,
// Molecule/agent fields (bd-xwvo fix)
MolType: molType,
WispType: wispType,
// Time scheduling fields (bd-xwvo fix)
DueAt: dueAt,
DeferUntil: deferUntil,
Metadata: metadata,
// Cross-rig routing: use route prefix instead of database config
PrefixOverride: prefixOverride,
}
if err := targetStore.CreateIssue(ctx, issue, actor); err != nil {
FatalError("failed to create issue in rig %q: %v", rigName, err)
}
// Add labels if specified
for _, label := range labels {
if err := targetStore.AddLabel(ctx, issue.ID, label, actor); err != nil {
WarnError("failed to add label %s: %v", label, err)
}
}
// Get silent flag
silent, _ := cmd.Flags().GetBool("silent")
if jsonOutput {
outputJSON(issue)
} else if silent {
fmt.Println(issue.ID)
} else {
fmt.Printf("%s Created issue in rig %q: %s\n", ui.RenderPass("✓"), rigName, formatFeedbackID(issue.ID, issue.Title))
fmt.Printf(" Priority: P%d\n", issue.Priority)
fmt.Printf(" Status: %s\n", issue.Status)
}
}
// findTownBeadsDir finds the town-level .beads directory (where routes.jsonl lives).
// It follows the active beads directory for this command so nested towns do not
// override the authoritative routing context.
func findTownBeadsDir() (string, error) {
currentBeadsDir := resolveCommandBeadsDir(dbPath)
if currentBeadsDir == "" {
currentBeadsDir = beads.FindBeadsDir()
}
townBeadsDir := routing.ResolveTownBeadsDir(currentBeadsDir)
if townBeadsDir == "" {
return "", fmt.Errorf("no routes.jsonl found for current beads directory")
}
return townBeadsDir, nil
}
// formatTimeForRPC converts a *time.Time to RFC3339 string for RPC calls.
// Returns empty string if t is nil, to distinguish "not set" from "set to zero".
func formatTimeForRPC(t *time.Time) string {

View file

@ -4,7 +4,6 @@ package main
import (
"context"
"os"
"path/filepath"
"testing"
@ -47,145 +46,3 @@ func TestGetRoutingConfigValue_YAMLPrecedence(t *testing.T) {
t.Fatalf("getRoutingConfigValue() = %q, want %q", got, "maintainer")
}
}
func TestFindTownBeadsDir_PrefersCurrentBeadsDirOverNestedTownCWD(t *testing.T) {
outerTownDir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
outerMayorDir := filepath.Join(outerTownDir, "mayor")
if err := os.MkdirAll(outerMayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerMayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
outerBeadsDir := filepath.Join(outerTownDir, ".beads")
if err := os.MkdirAll(outerBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"gt-","path":"rigs/outer"}
`), 0600); err != nil {
t.Fatal(err)
}
outerRigBeadsDir := filepath.Join(outerTownDir, "outer-worktree", ".beads")
if err := os.MkdirAll(outerRigBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerRigBeadsDir, "metadata.json"), []byte(`{"backend":"dolt","dolt_database":"outer"}`), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerRigBeadsDir, "config.yaml"), []byte("backend: dolt\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerRigBeadsDir, "dolt.db"), []byte{}, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"gt-","path":"rigs/outer"}
`), 0600); err != nil {
t.Fatal(err)
}
innerTownDir := filepath.Join(outerTownDir, "nested-town")
innerMayorDir := filepath.Join(innerTownDir, "mayor")
if err := os.MkdirAll(innerMayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(innerMayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
innerBeadsDir := filepath.Join(innerTownDir, ".beads")
if err := os.MkdirAll(innerBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(innerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"gt-","path":"rigs/inner"}
`), 0600); err != nil {
t.Fatal(err)
}
workerDir := filepath.Join(innerTownDir, "crew", "worker")
if err := os.MkdirAll(workerDir, 0750); err != nil {
t.Fatal(err)
}
t.Chdir(workerDir)
t.Setenv("BEADS_DIR", outerRigBeadsDir)
oldDBPath := dbPath
dbPath = ""
t.Cleanup(func() { dbPath = oldDBPath })
got, err := findTownBeadsDir()
if err != nil {
t.Fatalf("findTownBeadsDir() error = %v", err)
}
if got != outerBeadsDir {
t.Fatalf("findTownBeadsDir() = %s, want %s", got, outerBeadsDir)
}
}
func TestFindTownBeadsDir_PrefersExplicitDBPathOverBEADSDir(t *testing.T) {
outerTownDir := t.TempDir()
outerMayorDir := filepath.Join(outerTownDir, "mayor")
if err := os.MkdirAll(outerMayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerMayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
outerBeadsDir := filepath.Join(outerTownDir, ".beads")
if err := os.MkdirAll(outerBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"gt-","path":"rigs/outer"}
`), 0600); err != nil {
t.Fatal(err)
}
outerRigBeadsDir := filepath.Join(outerTownDir, "outer-worktree", ".beads")
outerDBPath := filepath.Join(outerRigBeadsDir, "dolt")
writeTestMetadata(t, outerDBPath, "outer_db")
innerTownDir := filepath.Join(outerTownDir, "nested-town")
innerMayorDir := filepath.Join(innerTownDir, "mayor")
if err := os.MkdirAll(innerMayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(innerMayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
innerBeadsDir := filepath.Join(innerTownDir, ".beads")
if err := os.MkdirAll(innerBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(innerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"gt-","path":"rigs/inner"}
`), 0600); err != nil {
t.Fatal(err)
}
workerDir := filepath.Join(innerTownDir, "crew", "worker")
if err := os.MkdirAll(workerDir, 0750); err != nil {
t.Fatal(err)
}
t.Chdir(workerDir)
t.Setenv("BEADS_DIR", innerBeadsDir)
oldDBPath := dbPath
dbPath = outerDBPath
t.Cleanup(func() { dbPath = oldDBPath })
got, err := findTownBeadsDir()
if err != nil {
t.Fatalf("findTownBeadsDir() error = %v", err)
}
if got != outerBeadsDir {
t.Fatalf("findTownBeadsDir() = %s, want %s", got, outerBeadsDir)
}
}

View file

@ -5,25 +5,14 @@ import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/routing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
// getBeadsDir returns the .beads directory path, derived from the global dbPath.
func getBeadsDir() string {
if dbPath != "" {
return filepath.Dir(dbPath)
}
return ""
}
// resolveIDWithRouting resolves a partial issue ID using prefix-based routing.
// It returns the resolved full ID and the store that contains the issue.
// If the issue routes to a different database, a routed store is returned
@ -277,14 +266,7 @@ Examples:
var toCleanup func()
toID, _, toCleanup, err = resolveIDWithRouting(ctx, store, dependsOnArg)
if err != nil {
// Resolution failed - try auto-converting to external ref
beadsDir := getBeadsDir()
if extRef := routing.ResolveToExternalRef(dependsOnArg, beadsDir); extRef != "" {
toID = extRef
isExternalRef = true
} else {
FatalErrorRespectJSON("resolving dependency ID %s: %v", dependsOnArg, err)
}
FatalErrorRespectJSON("resolving dependency ID %s: %v", dependsOnArg, err)
} else {
defer toCleanup()
}
@ -403,14 +385,6 @@ Examples:
FatalErrorRespectJSON("%v", err)
}
// Resolve external references (cross-rig dependencies)
// GetDependenciesWithMetadata only returns local issues, so we need to
// fetch raw dependency records and resolve external refs separately
if direction == "down" {
externalIssues := resolveExternalDependencies(ctx, depStore, fullID, typeFilter)
issues = append(issues, externalIssues...)
}
// Apply type filter if specified
if typeFilter != "" {
var filtered []*types.IssueWithDependencyMetadata
@ -505,13 +479,7 @@ var depRemoveCmd = &cobra.Command{
var toCleanup func()
toID, _, toCleanup, err = resolveIDWithRouting(ctx, store, args[1])
if err != nil {
// Resolution failed - try auto-converting to external ref
beadsDir := getBeadsDir()
if extRef := routing.ResolveToExternalRef(args[1], beadsDir); extRef != "" {
toID = extRef
} else {
FatalErrorRespectJSON("resolving dependency ID %s: %v", args[1], err)
}
FatalErrorRespectJSON("resolving dependency ID %s: %v", args[1], err)
} else {
defer toCleanup()
}
@ -1068,106 +1036,6 @@ func ParseExternalRef(ref string) (project, capability string) {
return parts[1], parts[2]
}
// resolveExternalDependencies fetches issue metadata for external (cross-rig) dependencies.
// It queries raw dependency records, finds external refs, and resolves them via routing.
func resolveExternalDependencies(ctx context.Context, depStore storage.DoltStorage, issueID string, typeFilter string) []*types.IssueWithDependencyMetadata {
if depStore == nil {
return nil
}
// Get raw dependency records to find external refs
deps, err := depStore.GetDependencyRecords(ctx, issueID)
if err != nil {
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] GetDependencyRecords error: %v\n", err)
}
return nil // Silently fail - local deps still work
}
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] found %d raw deps for %s\n", len(deps), issueID)
}
var result []*types.IssueWithDependencyMetadata
beadsDir := getBeadsDir()
for _, dep := range deps {
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] checking dep: %s -> %s (%s)\n", dep.IssueID, dep.DependsOnID, dep.Type)
}
// Skip non-external refs (already handled by GetDependenciesWithMetadata)
if !IsExternalRef(dep.DependsOnID) {
continue
}
// Apply type filter early if specified
if typeFilter != "" && string(dep.Type) != typeFilter {
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] skipping due to type filter: %s != %s\n", dep.Type, typeFilter)
}
continue
}
// Parse external ref: external:<project>:<issue-id>
project, targetID := ParseExternalRef(dep.DependsOnID)
if project == "" || targetID == "" {
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] failed to parse external ref: %s\n", dep.DependsOnID)
}
continue
}
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] parsed: project=%s, targetID=%s\n", project, targetID)
}
// Resolve the beads directory for this project via routing
targetBeadsDir, _, err := routing.ResolveBeadsDirForRig(project, beadsDir)
if err != nil {
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] routing error for %s: %v\n", project, err)
}
continue // Project not configured in routes
}
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] resolved beads dir: %s\n", targetBeadsDir)
}
// Open storage for the target rig (auto-detect backend from metadata.json)
targetStore, err := dolt.NewFromConfig(ctx, targetBeadsDir)
if err != nil {
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] failed to open target db %s: %v\n", targetBeadsDir, err)
}
continue // Can't open target database
}
// Fetch the issue from the target rig
issue, err := targetStore.GetIssue(ctx, targetID)
_ = targetStore.Close() // Best effort cleanup
if err != nil || issue == nil {
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] issue not found: %s (err=%v)\n", targetID, err)
}
continue // Issue not found in target
}
if isVerbose() {
fmt.Fprintf(os.Stderr, "[external-deps] resolved issue: %s - %s\n", issue.ID, issue.Title)
}
// Convert to IssueWithDependencyMetadata
result = append(result, &types.IssueWithDependencyMetadata{
Issue: *issue,
DependencyType: dep.Type,
})
}
return result
}
func init() {
// dep command shorthand flag
depCmd.Flags().StringP("blocks", "b", "", "Issue ID that this issue blocks (shorthand for: bd dep add <blocked> <blocker>)")

View file

@ -1,354 +0,0 @@
//go:build cgo
package main
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// TestResolveExternalDepsViaRouting tests that external dependency references
// (e.g., "external:other-project:op-42zaq") are resolved via prefix routes to show
// the actual issue details from the target database.
//
// This is the core fix for bd-k0pfm: bd show should resolve cross-database deps.
func TestResolveExternalDepsViaRouting(t *testing.T) {
ctx := context.Background()
// Create temp directory structure:
// tmpDir/
// .beads/
// beads.db (town database - local)
// routes.jsonl
// rig/
// .beads/
// beads.db (remote rig database)
tmpDir := t.TempDir()
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0755); err != nil {
t.Fatalf("Failed to create town beads dir: %v", err)
}
rigBeadsDir := filepath.Join(tmpDir, "rig", ".beads")
if err := os.MkdirAll(rigBeadsDir, 0755); err != nil {
t.Fatalf("Failed to create rig beads dir: %v", err)
}
// Initialize town database (local store)
townDBPath := filepath.Join(townBeadsDir, "dolt")
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
// Initialize rig database (remote store)
rigDBPath := filepath.Join(rigBeadsDir, "dolt")
rigStore := newTestStoreIsolatedDB(t, rigDBPath, "gt")
// Create an issue in the remote rig database
remoteIssue := &types.Issue{
ID: "gt-remote1",
Title: "Remote issue for cross-db dep test",
IssueType: types.TypeTask,
Status: types.StatusOpen,
Priority: 1,
}
if err := rigStore.CreateIssue(ctx, remoteIssue, "test"); err != nil {
t.Fatalf("Failed to create remote issue: %v", err)
}
// Close rig store to release lock before routing opens it
rigStore.Close()
// Create a local issue that depends on the remote issue via external ref
localIssue := &types.Issue{
ID: "hq-local1",
Title: "Local issue with external dep",
IssueType: types.TypeTask,
Status: types.StatusOpen,
Priority: 1,
}
if err := townStore.CreateIssue(ctx, localIssue, "test"); err != nil {
t.Fatalf("Failed to create local issue: %v", err)
}
// Add external dependency: local issue depends on "external:rig:gt-remote1"
dep := &types.Dependency{
IssueID: "hq-local1",
DependsOnID: "external:rig:gt-remote1",
Type: types.DepBlocks,
}
if err := townStore.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("Failed to add external dependency: %v", err)
}
// Create routes.jsonl in town .beads directory
routesContent := `{"prefix":"gt-","path":"rig"}`
routesPath := filepath.Join(townBeadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte(routesContent), 0644); err != nil {
t.Fatalf("Failed to write routes.jsonl: %v", err)
}
// Set up global state for routing to work
oldDbPath := dbPath
dbPath = townDBPath
t.Cleanup(func() { dbPath = oldDbPath })
oldStore := store
store = townStore
t.Cleanup(func() { store = oldStore })
// Change to tmpDir so routing can find town root via CWD
oldWd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
t.Cleanup(func() { _ = os.Chdir(oldWd) })
// Verify: GetDependenciesWithMetadata should NOT return the external dep
// (because it JOINs on issues table and external refs aren't there)
depsWithMeta, err := townStore.GetDependenciesWithMetadata(ctx, "hq-local1")
if err != nil {
t.Fatalf("GetDependenciesWithMetadata failed: %v", err)
}
if len(depsWithMeta) != 0 {
t.Errorf("Expected 0 deps from GetDependenciesWithMetadata (external ref not in local issues table), got %d", len(depsWithMeta))
}
// Verify: resolveExternalDepsViaRouting SHOULD resolve the external dep
resolved, err := resolveExternalDepsViaRouting(ctx, townStore, "hq-local1")
if err != nil {
t.Fatalf("resolveExternalDepsViaRouting failed: %v", err)
}
if len(resolved) != 1 {
t.Fatalf("Expected 1 resolved external dep, got %d", len(resolved))
}
resolvedDep := resolved[0]
if resolvedDep.Issue.ID != "gt-remote1" {
t.Errorf("Expected resolved dep ID %q, got %q", "gt-remote1", resolvedDep.Issue.ID)
}
if resolvedDep.Issue.Title != "Remote issue for cross-db dep test" {
t.Errorf("Expected resolved dep title %q, got %q", "Remote issue for cross-db dep test", resolvedDep.Issue.Title)
}
if resolvedDep.DependencyType != types.DepBlocks {
t.Errorf("Expected dependency type %q, got %q", types.DepBlocks, resolvedDep.DependencyType)
}
t.Logf("Successfully resolved external dep: %s -> %s: %s",
localIssue.ID, resolvedDep.Issue.ID, resolvedDep.Issue.Title)
}
// TestResolveExternalDepsUnresolvable tests that unresolvable external deps
// produce placeholder entries rather than being silently dropped.
func TestResolveExternalDepsUnresolvable(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0755); err != nil {
t.Fatalf("Failed to create town beads dir: %v", err)
}
townDBPath := filepath.Join(townBeadsDir, "dolt")
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
// Create a local issue with an external dep to a non-existent target
localIssue := &types.Issue{
ID: "hq-orphan1",
Title: "Issue with unresolvable external dep",
IssueType: types.TypeTask,
Status: types.StatusOpen,
Priority: 1,
}
if err := townStore.CreateIssue(ctx, localIssue, "test"); err != nil {
t.Fatalf("Failed to create local issue: %v", err)
}
dep := &types.Dependency{
IssueID: "hq-orphan1",
DependsOnID: "external:nonexistent:fake-id",
Type: types.DepBlocks,
}
if err := townStore.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("Failed to add external dependency: %v", err)
}
// Set up global state
oldDbPath := dbPath
dbPath = townDBPath
t.Cleanup(func() { dbPath = oldDbPath })
oldStore := store
store = townStore
t.Cleanup(func() { store = oldStore })
oldWd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
t.Cleanup(func() { _ = os.Chdir(oldWd) })
// Should produce a placeholder for the unresolvable dep
resolved, err := resolveExternalDepsViaRouting(ctx, townStore, "hq-orphan1")
if err != nil {
t.Fatalf("resolveExternalDepsViaRouting failed: %v", err)
}
if len(resolved) != 1 {
t.Fatalf("Expected 1 placeholder dep, got %d", len(resolved))
}
placeholder := resolved[0]
if placeholder.Issue.ID != "external:nonexistent:fake-id" {
t.Errorf("Expected placeholder ID to be the external ref, got %q", placeholder.Issue.ID)
}
if !strings.Contains(placeholder.Issue.Title, "unresolved") {
t.Errorf("Expected placeholder title to contain 'unresolved', got %q", placeholder.Issue.Title)
}
}
// TestResolveBlockedByRefs tests that blocked-by lists with external refs
// are resolved to human-readable strings.
func TestResolveBlockedByRefs(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0755); err != nil {
t.Fatalf("Failed to create town beads dir: %v", err)
}
rigBeadsDir := filepath.Join(tmpDir, "rig", ".beads")
if err := os.MkdirAll(rigBeadsDir, 0755); err != nil {
t.Fatalf("Failed to create rig beads dir: %v", err)
}
townDBPath := filepath.Join(townBeadsDir, "dolt")
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
rigDBPath := filepath.Join(rigBeadsDir, "dolt")
rigStore := newTestStoreIsolatedDB(t, rigDBPath, "gt")
remoteIssue := &types.Issue{
ID: "gt-blocker1",
Title: "Blocking issue in remote rig",
IssueType: types.TypeTask,
Status: types.StatusOpen,
Priority: 0,
}
if err := rigStore.CreateIssue(ctx, remoteIssue, "test"); err != nil {
t.Fatalf("Failed to create remote issue: %v", err)
}
rigStore.Close()
routesContent := `{"prefix":"gt-","path":"rig"}`
routesPath := filepath.Join(townBeadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte(routesContent), 0644); err != nil {
t.Fatalf("Failed to write routes.jsonl: %v", err)
}
oldDbPath := dbPath
dbPath = townDBPath
t.Cleanup(func() { dbPath = oldDbPath })
oldStore := store
store = townStore
t.Cleanup(func() { store = oldStore })
oldWd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
t.Cleanup(func() { _ = os.Chdir(oldWd) })
// Test with mixed refs
refs := []string{"hq-local1", "external:rig:gt-blocker1"}
resolved := resolveBlockedByRefs(ctx, refs)
if len(resolved) != 2 {
t.Fatalf("Expected 2 resolved refs, got %d", len(resolved))
}
// First ref should pass through unchanged
if resolved[0] != "hq-local1" {
t.Errorf("Expected first ref to be %q, got %q", "hq-local1", resolved[0])
}
// Second ref should be resolved to show issue ID and title
if !strings.Contains(resolved[1], "gt-blocker1") {
t.Errorf("Expected second ref to contain issue ID 'gt-blocker1', got %q", resolved[1])
}
if !strings.Contains(resolved[1], "Blocking issue in remote rig") {
t.Errorf("Expected second ref to contain issue title, got %q", resolved[1])
}
}
// TestNoExternalDeps verifies that resolveExternalDepsViaRouting returns nil
// when there are no external deps (common case - no performance overhead).
func TestNoExternalDeps(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatalf("Failed to create beads dir: %v", err)
}
dbFile := filepath.Join(beadsDir, "dolt")
testStore := newTestStoreIsolatedDB(t, dbFile, "test")
// Create two local issues with a local dependency
issue1 := &types.Issue{
ID: "test-a",
Title: "Issue A",
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
issue2 := &types.Issue{
ID: "test-b",
Title: "Issue B",
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
if err := testStore.CreateIssue(ctx, issue1, "test"); err != nil {
t.Fatal(err)
}
if err := testStore.CreateIssue(ctx, issue2, "test"); err != nil {
t.Fatal(err)
}
dep := &types.Dependency{
IssueID: "test-a",
DependsOnID: "test-b",
Type: types.DepBlocks,
}
if err := testStore.AddDependency(ctx, dep, "test"); err != nil {
t.Fatal(err)
}
oldDbPath := dbPath
dbPath = dbFile
t.Cleanup(func() { dbPath = oldDbPath })
// No external deps — should return nil quickly
resolved, err := resolveExternalDepsViaRouting(ctx, testStore, "test-a")
if err != nil {
t.Fatalf("resolveExternalDepsViaRouting failed: %v", err)
}
if resolved != nil {
t.Errorf("Expected nil for no external deps, got %d entries", len(resolved))
}
}

View file

@ -11,9 +11,6 @@ import (
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/routing"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
@ -729,49 +726,11 @@ func checkTimer(gate *types.Issue, now time.Time) (resolved, escalated bool, rea
// checkBeadGate checks if a cross-rig bead gate is satisfied.
// await_id format: <rig>:<bead-id> (e.g., "other-project:op-abc123")
// Returns (satisfied, reason).
func checkBeadGate(ctx context.Context, awaitID string) (bool, string) {
// Parse await_id format: <rig>:<bead-id>
parts := strings.SplitN(awaitID, ":", 2)
if len(parts) != 2 {
return false, fmt.Sprintf("invalid await_id format: expected <rig>:<bead-id>, got %q", awaitID)
}
rigName := parts[0]
beadID := parts[1]
if rigName == "" || beadID == "" {
return false, "await_id missing rig name or bead ID"
}
// Resolve the target rig's beads directory
currentBeadsDir := beads.FindBeadsDir()
if currentBeadsDir == "" {
return false, "could not find current beads directory"
}
targetBeadsDir, _, err := routing.ResolveBeadsDirForRig(rigName, currentBeadsDir)
if err != nil {
return false, fmt.Sprintf("rig %q not found: %v", rigName, err)
}
// Open the target database (read-only) using storage factory
// This supports both Dolt and legacy SQLite backends in the target rig.
targetStore, err := dolt.NewFromConfigWithOptions(ctx, targetBeadsDir, &dolt.Config{ReadOnly: true})
if err != nil {
return false, fmt.Sprintf("failed to open database for rig %q: %v", rigName, err)
}
defer func() { _ = targetStore.Close() }()
// Check if the target bead exists and is closed
issue, err := targetStore.GetIssue(ctx, beadID)
if err != nil {
return false, fmt.Sprintf("bead %s not found in rig %s: %v", beadID, rigName, err)
}
if issue.Status == types.StatusClosed {
return true, fmt.Sprintf("target bead %s is closed", beadID)
}
return false, fmt.Sprintf("target bead %s status is %q (waiting for closed)", beadID, string(issue.Status))
//
// Multi-rig routing has been removed, so cross-rig bead gates cannot be resolved.
// This always returns false with a descriptive message.
func checkBeadGate(_ context.Context, awaitID string) (bool, string) {
return false, fmt.Sprintf("cross-rig bead gate %q cannot be checked (multi-rig routing removed)", awaitID)
}
// closeGate closes a gate issue with the given reason

View file

@ -760,27 +760,15 @@ var listCmd = &cobra.Command{
ctx := rootCtx
// Handle --rig flag: query a different rig's database
rigOverride, _ := cmd.Flags().GetString("rig")
activeStore := store
if rigOverride != "" {
rigStore, err := openStoreForRig(ctx, rigOverride)
if err != nil {
FatalError("%v", err)
}
defer func() { _ = rigStore.Close() }() // Best effort cleanup
activeStore = rigStore
} else {
// Keep list/read behavior aligned with bd create routing decisions.
// Contributor auto-routing should read from the same target repo.
routedStore, routed, err := openRoutedReadStore(ctx, activeStore)
if err != nil {
FatalError("%v", err)
}
if routed {
defer func() { _ = routedStore.Close() }()
activeStore = routedStore
}
// Contributor auto-routing: read from the same target repo as bd create.
routedStore, routed, err := openRoutedReadStore(ctx, activeStore)
if err != nil {
FatalError("%v", err)
}
if routed {
defer func() { _ = routedStore.Close() }()
activeStore = routedStore
}
// Direct mode
@ -1043,9 +1031,6 @@ func init() {
// Ready filter: show only issues ready to be worked on (bd-ihu31)
listCmd.Flags().Bool("ready", false, "Show only ready issues (status=open, excludes hooked/in_progress/blocked/deferred)")
// Cross-rig routing: query a different rig's database (bd-rgdjr)
listCmd.Flags().String("rig", "", "Query a different rig's database (e.g., --rig my-project, --rig gt-, --rig gt)")
// Note: --json flag is defined as a persistent flag in main.go, not here
rootCmd.AddCommand(listCmd)
}

View file

@ -1,288 +0,0 @@
package main
import (
"context"
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/routing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
var moveCmd = &cobra.Command{
Use: "move <issue-id> --to <rig|prefix>",
GroupID: "issues",
Short: "Move an issue to a different rig with dependency remapping",
Long: `Move an issue from one rig to another, updating dependencies.
This command:
1. Creates a new issue in the target rig with the same content
2. Updates dependencies that reference the old ID (see below)
3. Closes the source issue with a redirect note
The target rig can be specified as:
- A rig name: beads, my-project
- A prefix: bd-, mp-
- A prefix without hyphen: bd, mp
Dependency handling for cross-rig moves:
- Issues that depend ON the moved issue: updated to external refs
- Issues that the moved issue DEPENDS ON: removed (recreate manually in target)
Note: Labels are copied. Comments and event history are not transferred.
Examples:
bd move hq-c21fj --to beads # Move to beads by rig name
bd move hq-q3tki --to mp- # Move to my-project by prefix
bd move hq-1h2to --to mp # Move to my-project (prefix without hyphen)`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
CheckReadonly("move")
sourceID := args[0]
targetRig, _ := cmd.Flags().GetString("to")
if targetRig == "" {
FatalError("--to flag is required. Specify target rig (e.g., --to beads, --to gt-)")
}
keepOpen, _ := cmd.Flags().GetBool("keep-open")
skipDeps, _ := cmd.Flags().GetBool("skip-deps")
ctx := rootCtx
// Step 1: Get the source issue (via routing if needed)
result, err := resolveAndGetIssueWithRouting(ctx, store, sourceID)
if err != nil {
FatalError("failed to find source issue: %v", err)
}
if result == nil || result.Issue == nil {
FatalError("source issue %s not found", sourceID)
}
defer result.Close()
sourceIssue := result.Issue
resolvedSourceID := result.ResolvedID
sourceStore := result.Store
// Warn if source issue is already closed
if sourceIssue.Status == types.StatusClosed {
fmt.Fprintf(os.Stderr, "%s Source issue %s is already closed\n", ui.RenderWarn("⚠"), resolvedSourceID)
}
// Warn if ephemeral
if sourceIssue.Ephemeral {
fmt.Fprintf(os.Stderr, "%s Source issue %s is ephemeral (wisp). Moving ephemeral issues may not be appropriate.\n", ui.RenderWarn("⚠"), resolvedSourceID)
}
// Step 2: Find the town-level beads directory
townBeadsDir, err := findTownBeadsDir()
if err != nil {
FatalError("cannot move: %v", err)
}
// Step 3: Resolve the target rig's beads directory
targetBeadsDir, targetPrefix, err := routing.ResolveBeadsDirForRig(targetRig, townBeadsDir)
if err != nil {
FatalError("%v", err)
}
// Check we're not moving to the same rig
sourcePrefix := routing.ExtractPrefix(resolvedSourceID)
if sourcePrefix == targetPrefix {
FatalError("source issue %s is already in rig %q", resolvedSourceID, targetRig)
}
// Step 4: Open storage for the target rig
// Use factory to respect backend configuration (bd-m2jr: SQLite fallback fix)
targetStore, err := dolt.NewFromConfig(ctx, targetBeadsDir)
if err != nil {
FatalError("failed to open target rig database: %v", err)
}
defer func() {
if err := targetStore.Close(); err != nil {
fmt.Fprintf(os.Stderr, "warning: failed to close target rig database: %v\n", err)
}
}()
// Step 5: Create the new issue in target rig (copy all fields)
newIssue := &types.Issue{
// Don't copy ID - let target rig generate new one
Title: sourceIssue.Title,
Description: sourceIssue.Description,
Design: sourceIssue.Design,
AcceptanceCriteria: sourceIssue.AcceptanceCriteria,
Notes: sourceIssue.Notes,
Status: types.StatusOpen, // Always start as open
Priority: sourceIssue.Priority,
IssueType: sourceIssue.IssueType,
Assignee: sourceIssue.Assignee,
ExternalRef: sourceIssue.ExternalRef,
EstimatedMinutes: sourceIssue.EstimatedMinutes,
SourceRepo: sourceIssue.SourceRepo,
Ephemeral: sourceIssue.Ephemeral,
MolType: sourceIssue.MolType,
DueAt: sourceIssue.DueAt,
DeferUntil: sourceIssue.DeferUntil,
CreatedBy: actor,
}
// Append moved note to description
if newIssue.Description != "" {
newIssue.Description += "\n\n"
}
newIssue.Description += fmt.Sprintf("(Moved from %s)", resolvedSourceID)
if err := targetStore.CreateIssue(ctx, newIssue, actor); err != nil {
FatalError("failed to create issue in target rig: %v", err)
}
newID := newIssue.ID
// Step 6: Copy labels if any
labels, err := sourceStore.GetLabels(ctx, resolvedSourceID)
if err == nil && len(labels) > 0 {
for _, label := range labels {
if err := targetStore.AddLabel(ctx, newID, label, actor); err != nil {
WarnError("failed to copy label %s: %v", label, err)
}
}
}
// Step 7: Remap dependencies in the source store
// targetRig is used to create external references for cross-rig moves
var depsRemapped int
if !skipDeps {
depsRemapped, err = remapDependencies(ctx, sourceStore, resolvedSourceID, newID, targetRig, actor)
if err != nil {
WarnError("failed to remap some dependencies: %v", err)
}
}
// Step 8: Close the source issue (unless --keep-open)
if !keepOpen {
closeReason := fmt.Sprintf("Moved to %s", newID)
if err := sourceStore.CloseIssue(ctx, resolvedSourceID, closeReason, actor, ""); err != nil {
WarnError("failed to close source issue: %v", err)
}
}
// Embedded mode: flush Dolt commits on both stores.
if isEmbeddedDolt {
if sourceStore != nil {
if _, err := sourceStore.CommitPending(ctx, actor); err != nil {
WarnError("failed to commit source store: %v", err)
}
}
if targetStore != nil {
if _, err := targetStore.CommitPending(ctx, actor); err != nil {
WarnError("failed to commit target store: %v", err)
}
}
}
// Output
if jsonOutput {
outputJSON(map[string]interface{}{
"source": resolvedSourceID,
"target": newID,
"closed": !keepOpen,
"deps_remapped": depsRemapped,
})
} else {
fmt.Printf("%s Moved %s → %s\n", ui.RenderPass("✓"), resolvedSourceID, newID)
if depsRemapped > 0 {
fmt.Printf(" Remapped %d dependencies\n", depsRemapped)
}
if !keepOpen {
fmt.Printf(" Source issue closed\n")
}
}
},
}
// remapDependencies updates all dependencies in the store that reference oldID to use newID.
// For cross-rig moves (which is the only supported case), dependencies TO the old ID are
// converted to external references. Dependencies FROM the old ID are removed since they
// can't be recreated in the source store.
// Returns the number of dependencies remapped.
func remapDependencies(ctx context.Context, s storage.DoltStorage, oldID, newID, targetRig, actor string) (int, error) {
count := 0
// Get dependencies where oldID is the issue (oldID depends on something)
// These must be removed since the new issue is in a different rig's store
depsFrom, err := s.GetDependencyRecords(ctx, oldID)
if err != nil {
return count, fmt.Errorf("getting dependencies from %s: %w", oldID, err)
}
// Remove deps FROM the old ID (user needs to recreate in target rig)
for _, dep := range depsFrom {
if err := s.RemoveDependency(ctx, oldID, dep.DependsOnID, actor); err != nil {
fmt.Fprintf(os.Stderr, " warning: failed to remove dep %s->%s: %v\n", oldID, dep.DependsOnID, err)
}
}
if len(depsFrom) > 0 {
fmt.Fprintf(os.Stderr, " note: %d dependencies FROM %s were removed (recreate in target rig if needed)\n", len(depsFrom), oldID)
}
// Get dependents (issues that depend on oldID)
dependents, err := s.GetDependents(ctx, oldID)
if err != nil {
return count, fmt.Errorf("getting dependents of %s: %w", oldID, err)
}
// For each issue that depends on oldID, update to use external ref to newID
for _, dependent := range dependents {
// Get the dependency record to preserve type/metadata
depRecords, err := s.GetDependencyRecords(ctx, dependent.ID)
if err != nil {
fmt.Fprintf(os.Stderr, " warning: failed to get deps for %s: %v\n", dependent.ID, err)
continue
}
for _, dep := range depRecords {
if dep.DependsOnID != oldID {
continue
}
// Remove old dependency
if err := s.RemoveDependency(ctx, dependent.ID, oldID, actor); err != nil {
fmt.Fprintf(os.Stderr, " warning: failed to remove dep %s->%s: %v\n", dependent.ID, oldID, err)
continue
}
// Point to external reference in target rig
externalRef := fmt.Sprintf("external:%s:%s", targetRig, newID)
// Add new dependency with external ref
newDep := &types.Dependency{
IssueID: dependent.ID,
DependsOnID: externalRef,
Type: dep.Type,
CreatedBy: actor,
Metadata: dep.Metadata,
ThreadID: dep.ThreadID,
}
if err := s.AddDependency(ctx, newDep, actor); err != nil {
fmt.Fprintf(os.Stderr, " warning: failed to add dep %s->%s: %v\n", dependent.ID, externalRef, err)
continue
}
count++
}
}
return count, nil
}
func init() {
moveCmd.Flags().String("to", "", "Target rig or prefix (required)")
moveCmd.Flags().Bool("keep-open", false, "Keep the source issue open (don't close it)")
moveCmd.Flags().Bool("skip-deps", false, "Skip dependency remapping")
moveCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(moveCmd)
}

View file

@ -1,85 +0,0 @@
//go:build embeddeddolt
package main
import (
"os"
"os/exec"
"strings"
"testing"
)
func TestEmbeddedMove(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "mv")
// NOTE: move and refile require a multi-rig town layout (findTownBeadsDir,
// routing.ResolveBeadsDirForRig, dolt.NewFromConfig for target). The single-rig
// embedded test harness cannot set this up. Tests here cover error paths and
// flag validation; cross-rig functionality needs a dedicated multi-rig test harness.
t.Run("move_requires_to_flag", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Move no-to", "--type", "task")
cmd := exec.Command(bd, "move", issue.ID)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected move without --to to fail, got: %s", out)
}
if !strings.Contains(string(out), "--to") {
t.Errorf("expected error about --to flag: %s", out)
}
})
t.Run("move_nonexistent_source", func(t *testing.T) {
cmd := exec.Command(bd, "move", "mv-nonexistent999", "--to", "other")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected move of nonexistent issue to fail, got: %s", out)
}
_ = out
})
t.Run("move_same_rig_fails", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Move same rig", "--type", "task")
cmd := exec.Command(bd, "move", issue.ID, "--to", "mv")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected move to same rig to fail, got: %s", out)
}
if !strings.Contains(string(out), "already in rig") {
t.Logf("same-rig error: %s", out)
}
})
t.Run("move_cross_rig_skipped", func(t *testing.T) {
t.Skip("requires multi-rig town layout (findTownBeadsDir + routing.ResolveBeadsDirForRig)")
})
t.Run("move_keep_open_skipped", func(t *testing.T) {
t.Skip("requires multi-rig town layout")
})
t.Run("move_skip_deps_skipped", func(t *testing.T) {
t.Skip("requires multi-rig town layout")
})
t.Run("move_json_skipped", func(t *testing.T) {
t.Skip("requires multi-rig town layout")
})
}
// TestEmbeddedMoveConcurrent is skipped — move requires multi-rig setup.
func TestEmbeddedMoveConcurrent(t *testing.T) {
t.Skip("requires multi-rig town layout for concurrent move testing")
}

View file

@ -1,238 +0,0 @@
//go:build cgo
package main
import (
"context"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
)
func TestRemapDependencies(t *testing.T) {
tmpDir := t.TempDir()
dbPath := filepath.Join(tmpDir, "test.db")
testStore, err := dolt.New(context.Background(), &dolt.Config{Path: dbPath})
if err != nil {
t.Skipf("skipping: Dolt server not available: %v", err)
}
defer testStore.Close()
ctx := context.Background()
// Initialize database with prefix
if err := testStore.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("Failed to set issue_prefix: %v", err)
}
// Create some issues
issueA := &types.Issue{
ID: "test-aaa",
Title: "Issue A (to be moved)",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
issueB := &types.Issue{
ID: "test-bbb",
Title: "Issue B (depends on A)",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
issueC := &types.Issue{
ID: "test-ccc",
Title: "Issue C (A depends on it)",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
for _, issue := range []*types.Issue{issueA, issueB, issueC} {
if err := testStore.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("Failed to create issue %s: %v", issue.ID, err)
}
}
// B depends on A (B is blocked by A)
dep1 := &types.Dependency{
IssueID: issueB.ID,
DependsOnID: issueA.ID,
Type: types.DepBlocks,
}
if err := testStore.AddDependency(ctx, dep1, "test"); err != nil {
t.Fatalf("Failed to add dep B->A: %v", err)
}
// A depends on C (A is blocked by C)
dep2 := &types.Dependency{
IssueID: issueA.ID,
DependsOnID: issueC.ID,
Type: types.DepBlocks,
}
if err := testStore.AddDependency(ctx, dep2, "test"); err != nil {
t.Fatalf("Failed to add dep A->C: %v", err)
}
// Now remap: A moves from test-aaa to other-xxx (CROSS-rig, different prefix)
// This simulates moving from one rig to another
newID := "other-xxx"
count, err := remapDependencies(ctx, testStore, issueA.ID, newID, "other", "test-actor")
if err != nil {
t.Fatalf("remapDependencies failed: %v", err)
}
// For cross-rig moves:
// - B->A becomes B->external:other:other-xxx (1 remapped)
// - A->C is removed (cross-rig, can't recreate in source store)
if count != 1 {
t.Errorf("Expected 1 dependency remapped (B->external ref), got %d", count)
}
// Verify B now depends on external ref (not test-aaa)
bDepRecords, err := testStore.GetDependencyRecords(ctx, issueB.ID)
if err != nil {
t.Fatalf("GetDependencyRecords(B) failed: %v", err)
}
expectedExtRef := "external:other:other-xxx"
foundNewDep := false
for _, dep := range bDepRecords {
if dep.DependsOnID == expectedExtRef {
foundNewDep = true
}
if dep.DependsOnID == issueA.ID {
t.Errorf("B still depends on old ID %s", issueA.ID)
}
}
if !foundNewDep {
t.Errorf("B should depend on external ref %s, but doesn't. Has: %v", expectedExtRef, bDepRecords)
}
// Verify old A->C dependency was removed
aDeps, err := testStore.GetDependencyRecords(ctx, issueA.ID)
if err != nil {
t.Fatalf("GetDependencyRecords(A) failed: %v", err)
}
if len(aDeps) != 0 {
t.Errorf("Expected old issue A to have 0 dependencies after remap, got %d", len(aDeps))
}
}
func TestRemapDependencies_NoDeps(t *testing.T) {
tmpDir := t.TempDir()
dbPath := filepath.Join(tmpDir, "test.db")
testStore, err := dolt.New(context.Background(), &dolt.Config{Path: dbPath})
if err != nil {
t.Skipf("skipping: Dolt server not available: %v", err)
}
defer testStore.Close()
ctx := context.Background()
// Initialize database with prefix
if err := testStore.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("Failed to set issue_prefix: %v", err)
}
// Create an issue with no dependencies
issue := &types.Issue{
ID: "test-lonely",
Title: "Lonely issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
if err := testStore.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
count, err := remapDependencies(ctx, testStore, issue.ID, "other-id", "other", "test-actor")
if err != nil {
t.Fatalf("remapDependencies failed: %v", err)
}
if count != 0 {
t.Errorf("Expected 0 dependencies remapped for issue with no deps, got %d", count)
}
}
func TestRemapDependencies_PreservesMetadata(t *testing.T) {
tmpDir := t.TempDir()
dbPath := filepath.Join(tmpDir, "test.db")
testStore, err := dolt.New(context.Background(), &dolt.Config{Path: dbPath})
if err != nil {
t.Skipf("skipping: Dolt server not available: %v", err)
}
defer testStore.Close()
ctx := context.Background()
// Initialize database with prefix
if err := testStore.SetConfig(ctx, "issue_prefix", "test"); err != nil {
t.Fatalf("Failed to set issue_prefix: %v", err)
}
// Create issues
issueA := &types.Issue{
ID: "test-aaa",
Title: "Issue A",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
issueB := &types.Issue{
ID: "test-bbb",
Title: "Issue B",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
for _, issue := range []*types.Issue{issueA, issueB} {
if err := testStore.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("Failed to create issue %s: %v", issue.ID, err)
}
}
// Create dependency with metadata (B depends on A)
dep := &types.Dependency{
IssueID: issueB.ID,
DependsOnID: issueA.ID,
Type: types.DepDiscoveredFrom,
Metadata: `{"reason": "found during work"}`,
}
if err := testStore.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("Failed to add dep: %v", err)
}
// Remap: A moves to other-xxx (cross-rig)
newID := "other-xxx"
_, err = remapDependencies(ctx, testStore, issueA.ID, newID, "other", "test-actor")
if err != nil {
t.Fatalf("remapDependencies failed: %v", err)
}
// Verify metadata was preserved on the new external ref dependency
bDepRecords, err := testStore.GetDependencyRecords(ctx, issueB.ID)
if err != nil {
t.Fatalf("GetDependencyRecords(B) failed: %v", err)
}
if len(bDepRecords) != 1 {
t.Fatalf("Expected 1 dependency, got %d", len(bDepRecords))
}
expectedExtRef := "external:other:other-xxx"
if bDepRecords[0].DependsOnID != expectedExtRef {
t.Errorf("Expected depends_on_id=%s, got %s", expectedExtRef, bDepRecords[0].DependsOnID)
}
if bDepRecords[0].Type != types.DepDiscoveredFrom {
t.Errorf("Expected type=discovered-from, got %s", bDepRecords[0].Type)
}
// Compare as normalized JSON (MySQL/Dolt normalizes JSON whitespace on storage)
if bDepRecords[0].Metadata != `{"reason":"found during work"}` && bDepRecords[0].Metadata != `{"reason": "found during work"}` {
t.Errorf("Metadata not preserved: got %s", bDepRecords[0].Metadata)
}
}

View file

@ -40,12 +40,6 @@ Examples:
diagHint())
}
// Handle cross-rig routing
if needsRouting(id) {
promoteRouted(id, reason)
return
}
fullID, err := utils.ResolvePartialID(ctx, store, id)
if err != nil {
FatalErrorRespectJSON("resolving %s: %v", id, err)
@ -96,53 +90,6 @@ Examples:
},
}
// promoteRouted handles promotion for cross-rig routed issues.
func promoteRouted(id, reason string) {
result, err := resolveAndGetIssueWithRouting(rootCtx, store, id)
if err != nil {
FatalErrorRespectJSON("resolving %s: %v", id, err)
}
if result == nil || result.Issue == nil {
if result != nil {
result.Close()
}
FatalErrorRespectJSON("issue %s not found", id)
}
defer result.Close()
if !result.Issue.Ephemeral {
FatalErrorRespectJSON("%s is not a wisp (already persistent)", id)
}
if err := result.Store.PromoteFromEphemeral(rootCtx, result.ResolvedID, actor); err != nil {
FatalErrorRespectJSON("promoting %s: %v", id, err)
}
comment := "Promoted from wisp to permanent bead"
if reason != "" {
comment += ": " + reason
}
if err := result.Store.AddComment(rootCtx, result.ResolvedID, actor, comment); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to add promotion comment to %s: %v\n", id, err)
}
// Embedded mode: flush Dolt commit.
if isEmbeddedDolt {
if _, err := result.Store.CommitPending(rootCtx, actor); err != nil {
FatalErrorRespectJSON("failed to commit: %v", err)
}
}
if jsonOutput {
updated, _ := result.Store.GetIssue(rootCtx, result.ResolvedID)
if updated != nil {
outputJSON(updated)
}
} else {
fmt.Printf("%s Promoted %s to permanent bead\n", ui.RenderPass("✓"), result.ResolvedID)
}
}
func init() {
promoteCmd.Flags().StringP("reason", "r", "", "Reason for promotion")
promoteCmd.ValidArgsFunction = issueIDCompletion

View file

@ -61,7 +61,6 @@ This is useful for agents executing molecules to see which steps can run next.`,
includeDeferred, _ := cmd.Flags().GetBool("include-deferred")
includeEphemeral, _ := cmd.Flags().GetBool("include-ephemeral")
excludeTypeStrs, _ := cmd.Flags().GetStringSlice("exclude-type")
rigOverride, _ := cmd.Flags().GetString("rig")
var molType *types.MolType
if molTypeStr != "" {
mt := types.MolType(molTypeStr)
@ -153,26 +152,15 @@ This is useful for agents executing molecules to see which steps can run next.`,
// Direct mode
ctx := rootCtx
// Handle --rig flag: query a different rig's database
activeStore := store
if rigOverride != "" {
rigStore, err := openStoreForRig(ctx, rigOverride)
if err != nil {
FatalError("%v", err)
}
defer func() { _ = rigStore.Close() }()
activeStore = rigStore
} else {
// Keep ready/read behavior aligned with bd create routing decisions.
// Contributor auto-routing should read from the same target repo.
routedStore, routed, err := openRoutedReadStore(ctx, activeStore)
if err != nil {
FatalError("%v", err)
}
if routed {
defer func() { _ = routedStore.Close() }()
activeStore = routedStore
}
// Contributor auto-routing: read from the same target repo as bd create.
routedStore, routed, err := openRoutedReadStore(ctx, activeStore)
if err != nil {
FatalError("%v", err)
}
if routed {
defer func() { _ = routedStore.Close() }()
activeStore = routedStore
}
issues, err := activeStore.GetReadyWork(ctx, filter)
@ -329,10 +317,8 @@ var blockedCmd = &cobra.Command{
if blockedBy == nil {
blockedBy = []string{}
}
// Resolve external refs to show real issue info (bd-k0pfm)
resolved := resolveBlockedByRefs(ctx, blockedBy)
fmt.Printf(" Blocked by %d open dependencies: %v\n",
issue.BlockedByCount, resolved)
issue.BlockedByCount, blockedBy)
fmt.Println()
}
},
@ -552,7 +538,6 @@ func init() {
readyCmd.Flags().Bool("include-ephemeral", false, "Include ephemeral issues (wisps) in results")
readyCmd.Flags().Bool("gated", false, "Find molecules ready for gate-resume dispatch")
readyCmd.Flags().StringSlice("exclude-type", nil, "Exclude issue types from results (comma-separated or repeatable, e.g., --exclude-type=convoy,epic)")
readyCmd.Flags().String("rig", "", "Query a different rig's database (e.g., --rig my-project, --rig gt-, --rig gt)")
// Metadata filtering (GH#1406)
readyCmd.Flags().StringArray("metadata-field", nil, "Filter by metadata field (key=value, repeatable)")
readyCmd.Flags().String("has-metadata-key", "", "Filter issues that have this metadata key set")

View file

@ -1,171 +0,0 @@
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/routing"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
var refileCmd = &cobra.Command{
Use: "refile <source-id> <target-rig>",
GroupID: "issues",
Short: "Move an issue to a different rig",
Long: `Move an issue from one rig to another.
This creates a new issue in the target rig with the same content,
then closes the source issue with a reference to the new location.
The target rig can be specified as:
- A rig name: beads, my-project
- A prefix: bd-, mp-
- A prefix without hyphen: bd, mp
Examples:
bd refile bd-8hea my-project # Move to my-project by rig name
bd refile bd-8hea mp- # Move to my-project by prefix
bd refile bd-8hea mp # Move to my-project (prefix without hyphen)`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
CheckReadonly("refile")
sourceID := args[0]
targetRig := args[1]
keepOpen, _ := cmd.Flags().GetBool("keep-open")
ctx := rootCtx
// Step 1: Get the source issue (via routing if needed)
result, err := resolveAndGetIssueWithRouting(ctx, store, sourceID)
if err != nil {
FatalError("failed to find source issue: %v", err)
}
if result == nil || result.Issue == nil {
FatalError("source issue %s not found", sourceID)
}
defer result.Close()
sourceIssue := result.Issue
resolvedSourceID := result.ResolvedID
// Warn if source issue is already closed
if sourceIssue.Status == types.StatusClosed {
fmt.Fprintf(os.Stderr, "%s Source issue %s is already closed\n", ui.RenderWarn("⚠"), resolvedSourceID)
}
// Step 2: Find the town-level beads directory
townBeadsDir, err := findTownBeadsDir()
if err != nil {
FatalError("cannot refile: %v", err)
}
// Step 3: Resolve the target rig's beads directory
targetBeadsDir, targetPrefix, err := routing.ResolveBeadsDirForRig(targetRig, townBeadsDir)
if err != nil {
FatalError("%v", err)
}
// Check we're not refiling to the same rig
sourcePrefix := routing.ExtractPrefix(resolvedSourceID)
if sourcePrefix == targetPrefix {
FatalError("source issue %s is already in rig %q", resolvedSourceID, targetRig)
}
// Step 4: Open storage for the target rig
targetStore, err := dolt.NewFromConfig(ctx, targetBeadsDir)
if err != nil {
FatalError("failed to open target rig database: %v", err)
}
defer func() {
if err := targetStore.Close(); err != nil {
fmt.Fprintf(os.Stderr, "warning: failed to close target rig database: %v\n", err)
}
}()
// Step 5: Create the new issue in target rig (copy all fields)
newIssue := &types.Issue{
// Don't copy ID - let target rig generate new one
Title: sourceIssue.Title,
Description: sourceIssue.Description,
Design: sourceIssue.Design,
AcceptanceCriteria: sourceIssue.AcceptanceCriteria,
Status: types.StatusOpen, // Always start as open
Priority: sourceIssue.Priority,
IssueType: sourceIssue.IssueType,
Assignee: sourceIssue.Assignee,
ExternalRef: sourceIssue.ExternalRef,
EstimatedMinutes: sourceIssue.EstimatedMinutes,
SourceRepo: sourceIssue.SourceRepo,
Ephemeral: sourceIssue.Ephemeral,
MolType: sourceIssue.MolType,
CreatedBy: actor,
}
// Append refiled note to description
if newIssue.Description != "" {
newIssue.Description += "\n\n"
}
newIssue.Description += fmt.Sprintf("(Refiled from %s)", resolvedSourceID)
if err := targetStore.CreateIssue(ctx, newIssue, actor); err != nil {
FatalError("failed to create issue in target rig: %v", err)
}
// Step 6: Copy labels if any
labels, err := result.Store.GetLabels(ctx, resolvedSourceID)
if err == nil && len(labels) > 0 {
for _, label := range labels {
if err := targetStore.AddLabel(ctx, newIssue.ID, label, actor); err != nil {
WarnError("failed to copy label %s: %v", label, err)
}
}
}
// Step 7: Close the source issue (unless --keep-open)
if !keepOpen {
closeReason := fmt.Sprintf("Refiled to %s", newIssue.ID)
if err := result.Store.CloseIssue(ctx, resolvedSourceID, closeReason, actor, ""); err != nil {
WarnError("failed to close source issue: %v", err)
}
}
// Embedded mode: flush Dolt commits on both stores.
if isEmbeddedDolt {
if result.Store != nil {
if _, err := result.Store.CommitPending(ctx, actor); err != nil {
WarnError("failed to commit source store: %v", err)
}
}
if targetStore != nil {
if _, err := targetStore.CommitPending(ctx, actor); err != nil {
WarnError("failed to commit target store: %v", err)
}
}
}
// Output
if jsonOutput {
outputJSON(map[string]interface{}{
"source": resolvedSourceID,
"target": newIssue.ID,
"closed": !keepOpen,
})
} else {
fmt.Printf("%s Refiled %s → %s\n", ui.RenderPass("✓"), resolvedSourceID, newIssue.ID)
if !keepOpen {
fmt.Printf(" Source issue closed\n")
}
}
},
}
func init() {
refileCmd.Flags().Bool("keep-open", false, "Keep the source issue open (don't close it)")
refileCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(refileCmd)
}

View file

@ -1,74 +0,0 @@
//go:build embeddeddolt
package main
import (
"os"
"os/exec"
"testing"
)
func TestEmbeddedRefile(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "rf")
// NOTE: refile requires a multi-rig town layout (findTownBeadsDir,
// routing.ResolveBeadsDirForRig, dolt.NewFromConfig for target).
// Tests here cover error paths; cross-rig functionality needs a
// dedicated multi-rig test harness.
t.Run("refile_requires_two_args", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Refile one arg", "--type", "task")
cmd := exec.Command(bd, "refile", issue.ID)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected refile with one arg to fail, got: %s", out)
}
})
t.Run("refile_nonexistent_source", func(t *testing.T) {
cmd := exec.Command(bd, "refile", "rf-nonexistent999", "other")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected refile of nonexistent to fail, got: %s", out)
}
_ = out
})
t.Run("refile_same_rig_fails", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Refile same rig", "--type", "task")
cmd := exec.Command(bd, "refile", issue.ID, "rf")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected refile to same rig to fail, got: %s", out)
}
_ = out
})
t.Run("refile_cross_rig_skipped", func(t *testing.T) {
t.Skip("requires multi-rig town layout")
})
t.Run("refile_keep_open_skipped", func(t *testing.T) {
t.Skip("requires multi-rig town layout")
})
t.Run("refile_json_skipped", func(t *testing.T) {
t.Skip("requires multi-rig town layout")
})
}
func TestEmbeddedRefileConcurrent(t *testing.T) {
t.Skip("requires multi-rig town layout for concurrent refile testing")
}

View file

@ -4,11 +4,8 @@ import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/beads/internal/routing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
@ -27,14 +24,6 @@ func isNotFoundErr(err error) bool {
return false
}
// beadsDirOverride returns true if BEADS_DIR is explicitly set in the environment.
// When set, BEADS_DIR specifies the exact database to use and prefix-based routing
// must be skipped. This matches bd list's behavior (which never routes) and the
// contract expected by all orchestrator callers that set BEADS_DIR (GH#663).
func beadsDirOverride() bool {
return os.Getenv("BEADS_DIR") != ""
}
// RoutedResult contains the result of a routed issue lookup
type RoutedResult struct {
Issue *types.Issue
@ -51,64 +40,19 @@ func (r *RoutedResult) Close() {
}
}
// resolveAndGetIssueWithRouting resolves a partial ID and gets the issue,
// using routes.jsonl for prefix-based routing if needed.
// This enables cross-repo issue lookups (e.g., `bd show gt-xyz` from ~/gt).
//
// When the ID's prefix routes to a different beads directory, the routed store
// is used directly — the local store is NOT checked first. This prevents
// mutations (close, update) from hitting phantom copies in the wrong database
// (bd-7vk). When routing does not apply (same directory or no route match),
// the local store is used as before.
// resolveAndGetIssueWithRouting resolves a partial ID and gets the issue.
// Tries the local store first, then falls back to contributor auto-routing.
//
// Returns a RoutedResult containing the issue, resolved ID, and the store to use.
// The caller MUST call result.Close() when done to release any routed storage.
func resolveAndGetIssueWithRouting(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
if dbPath == "" {
// No routing without a database path - use local store
return resolveAndGetFromStore(ctx, localStore, id, false)
}
// BEADS_DIR explicitly set — use local store, skip prefix routing (GH#663)
if beadsDirOverride() {
return resolveAndGetFromStore(ctx, localStore, id, false)
}
// Check if this ID routes to a different beads directory.
beadsDir := filepath.Dir(dbPath)
targetDir, routed, routeErr := routing.ResolveBeadsDirForID(ctx, id, beadsDir)
// Redirects may resolve back to the same .beads directory but with a different
// dolt_database. ResolveBeadsDirForID sets BEADS_DOLT_SERVER_DATABASE when a
// redirect changes the database, so we check for that too.
routesDifferently := routeErr == nil && routed && (targetDir != beadsDir || os.Getenv("BEADS_DOLT_SERVER_DATABASE") != "")
// When routing says this ID belongs to a different database, go directly
// to the routed store. Checking the local store first would risk finding
// phantom/duplicate copies in the wrong database (bd-7vk).
if routesDifferently {
routedStore, err := newDoltStoreFromConfig(ctx, targetDir)
if err != nil {
return nil, fmt.Errorf("opening routed store at %s: %w", targetDir, err)
}
result, err := resolveAndGetFromStore(ctx, routedStore, id, true)
if err != nil {
_ = routedStore.Close()
return nil, err
}
result.closeFn = func() { _ = routedStore.Close() }
return result, nil
}
// No cross-database routing — try local store first.
// Try local store first.
result, err := resolveAndGetFromStore(ctx, localStore, id, false)
if err == nil {
return result, nil
}
// If not found locally, try contributor auto-routing as fallback (GH#2345).
// Commands like show/update/close use this function but previously never
// checked the auto-routed store, so issues created via contributor
// auto-routing were invisible to them.
if isNotFoundErr(err) {
if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id); autoErr == nil {
return autoResult, nil
@ -141,7 +85,7 @@ func resolveAndGetFromStore(ctx context.Context, s storage.DoltStorage, id strin
}
// resolveViaAutoRouting attempts to find an issue using contributor auto-routing.
// This is the fallback when prefix-based routing and local store both fail (GH#2345).
// This is the fallback when the local store doesn't have the issue (GH#2345).
// Returns a RoutedResult if the issue is found in the auto-routed store.
func resolveViaAutoRouting(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
routedStore, routed, err := openRoutedReadStore(ctx, localStore)
@ -158,82 +102,13 @@ func resolveViaAutoRouting(ctx context.Context, localStore storage.DoltStorage,
return result, nil
}
// openStoreForRig opens a read-only storage connection to a different rig's database.
// The rigOrPrefix parameter accepts any format: "beads", "bd-", "bd", etc.
// Returns the opened storage (caller must close) or an error.
func openStoreForRig(ctx context.Context, rigOrPrefix string) (storage.DoltStorage, error) {
townBeadsDir, err := findTownBeadsDir()
if err != nil {
return nil, fmt.Errorf("cannot resolve rig: %v", err)
}
targetBeadsDir, _, err := routing.ResolveBeadsDirForRig(rigOrPrefix, townBeadsDir)
if err != nil {
return nil, err
}
targetStore, err := newReadOnlyStoreFromConfig(ctx, targetBeadsDir)
if err != nil {
return nil, fmt.Errorf("failed to open rig %q database: %v", rigOrPrefix, err)
}
return targetStore, nil
}
// getIssueWithRouting gets an issue, using prefix-based routing when the ID
// belongs to a different beads directory. When routing applies, the routed
// store is used directly (the local store is not checked first, preventing
// phantom-copy issues — bd-7vk). When routing does not apply, the local
// store is used.
// getIssueWithRouting gets an issue by exact ID.
// Tries the local store first, then falls back to contributor auto-routing.
//
// Returns a RoutedResult containing the issue and the store to use for related queries.
// The caller MUST call result.Close() when done to release any routed storage.
func getIssueWithRouting(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
if dbPath == "" || beadsDirOverride() {
// No routing without a database path, or BEADS_DIR explicitly set (GH#663)
issue, err := localStore.GetIssue(ctx, id)
if err != nil {
return nil, err
}
return &RoutedResult{
Issue: issue,
Store: localStore,
Routed: false,
ResolvedID: id,
}, nil
}
// Check if this ID routes to a different beads directory.
beadsDir := filepath.Dir(dbPath)
targetDir, routed, routeErr := routing.ResolveBeadsDirForID(ctx, id, beadsDir)
// Redirects may resolve back to the same .beads directory but with a different
// dolt_database. ResolveBeadsDirForID sets BEADS_DOLT_SERVER_DATABASE when a
// redirect changes the database, so we check for that too.
routesDifferently := routeErr == nil && routed && (targetDir != beadsDir || os.Getenv("BEADS_DOLT_SERVER_DATABASE") != "")
if routesDifferently {
routedStore, err := newDoltStoreFromConfig(ctx, targetDir)
if err != nil {
return nil, fmt.Errorf("opening routed store at %s: %w", targetDir, err)
}
routedIssue, routedErr := routedStore.GetIssue(ctx, id)
if routedErr != nil || routedIssue == nil {
_ = routedStore.Close()
if routedErr != nil {
return nil, routedErr
}
return nil, storage.ErrNotFound
}
return &RoutedResult{
Issue: routedIssue,
Store: routedStore,
Routed: true,
ResolvedID: id,
closeFn: func() { _ = routedStore.Close() },
}, nil
}
// No cross-database routing — try local store first.
// Try local store first.
issue, err := localStore.GetIssue(ctx, id)
if err == nil {
return &RoutedResult{
@ -253,135 +128,3 @@ func getIssueWithRouting(ctx context.Context, localStore storage.DoltStorage, id
return nil, err
}
// getRoutedStoreForID returns a storage connection for an issue ID if routing is needed.
// Returns nil if no routing is needed (issue should be in local store).
// The caller is responsible for closing the returned storage.
func getRoutedStoreForID(ctx context.Context, id string) (*routing.RoutedStorage, error) {
if dbPath == "" || beadsDirOverride() {
return nil, nil
}
beadsDir := filepath.Dir(dbPath)
// Use GetRoutedStorageWithOpener with dolt to respect backend configuration (bd-m2jr)
return routing.GetRoutedStorageWithOpener(ctx, id, beadsDir, newDoltStoreFromConfig)
}
// needsRouting checks if an ID would be routed to a different beads directory.
// This is used to decide whether to use direct store access for cross-repo lookups.
func needsRouting(id string) bool {
if dbPath == "" || beadsDirOverride() {
return false
}
beadsDir := filepath.Dir(dbPath)
targetDir, routed, err := routing.ResolveBeadsDirForID(context.Background(), id, beadsDir)
if err != nil || !routed {
return false
}
// Check if the routed directory is different from the current one
return targetDir != beadsDir
}
// resolveExternalDepsViaRouting resolves external dependency references by following
// prefix routes to locate and query the target database.
//
// GetDependenciesWithMetadata uses a JOIN between dependencies and issues tables,
// so external refs (e.g., "external:other-project:op-42zaq") that don't exist in the local
// issues table are silently dropped. This function fills in those gaps by:
// 1. Getting raw dependency records
// 2. Filtering for external refs
// 3. Extracting the issue ID from each ref
// 4. Using routing to look up the issue in the target database
//
// Returns a slice of IssueWithDependencyMetadata for resolved external deps.
func resolveExternalDepsViaRouting(ctx context.Context, issueStore storage.DoltStorage, issueID string) ([]*types.IssueWithDependencyMetadata, error) {
// Get raw dependency records to find external refs
deps, err := issueStore.GetDependencyRecords(ctx, issueID)
if err != nil {
return nil, err
}
// Filter for external refs
var externalDeps []*types.Dependency
for _, dep := range deps {
if strings.HasPrefix(dep.DependsOnID, "external:") {
externalDeps = append(externalDeps, dep)
}
}
if len(externalDeps) == 0 {
return nil, nil
}
var results []*types.IssueWithDependencyMetadata
for _, dep := range externalDeps {
// Parse external:project:id — the third part is the actual issue ID
parts := strings.SplitN(dep.DependsOnID, ":", 3)
if len(parts) != 3 || parts[2] == "" {
continue
}
targetID := parts[2]
// Use routing to resolve the target issue
result, routeErr := resolveAndGetIssueWithRouting(ctx, store, targetID)
if routeErr != nil || result == nil || result.Issue == nil {
// Can't resolve — create a placeholder with the external ref as ID
results = append(results, &types.IssueWithDependencyMetadata{
Issue: types.Issue{
ID: dep.DependsOnID,
Title: "(unresolved external dependency)",
Status: types.StatusOpen,
},
DependencyType: dep.Type,
})
if result != nil {
result.Close()
}
continue
}
results = append(results, &types.IssueWithDependencyMetadata{
Issue: *result.Issue,
DependencyType: dep.Type,
})
result.Close()
}
return results, nil
}
// resolveBlockedByRefs takes a list of blocker IDs (which may include external refs
// like "external:other-project:op-42zaq") and resolves them to human-readable strings.
// Local IDs pass through unchanged. External refs are resolved via routing to show
// the actual issue ID and title from the target database.
func resolveBlockedByRefs(ctx context.Context, refs []string) []string {
resolved := make([]string, 0, len(refs))
for _, ref := range refs {
if !strings.HasPrefix(ref, "external:") {
resolved = append(resolved, ref)
continue
}
// Parse external:project:id
parts := strings.SplitN(ref, ":", 3)
if len(parts) != 3 || parts[2] == "" {
resolved = append(resolved, ref)
continue
}
targetID := parts[2]
result, err := resolveAndGetIssueWithRouting(ctx, store, targetID)
if err != nil || result == nil || result.Issue == nil {
// Can't resolve — show the raw issue ID from the ref
resolved = append(resolved, targetID)
if result != nil {
result.Close()
}
continue
}
resolved = append(resolved, fmt.Sprintf("%s: %s", result.Issue.ID, result.Issue.Title))
result.Close()
}
return resolved
}

View file

@ -146,11 +146,7 @@ var showCmd = &cobra.Command{
// Get dependencies with metadata (dependency_type field)
details.Dependencies, _ = issueStore.GetDependenciesWithMetadata(ctx, issue.ID) // Best effort: show issue even if deps unavailable
// Resolve external deps via routing (bd-k0pfm)
if externalDeps, err := resolveExternalDepsViaRouting(ctx, issueStore, issue.ID); err == nil {
details.Dependencies = append(details.Dependencies, externalDeps...)
}
details.Dependents, _ = issueStore.GetDependentsWithMetadata(ctx, issue.ID) // Best effort: show issue even if dependents unavailable
details.Dependents, _ = issueStore.GetDependentsWithMetadata(ctx, issue.ID) // Best effort: show issue even if dependents unavailable
details.Comments, _ = issueStore.GetIssueComments(ctx, issue.ID) // Best effort: show issue even if comments unavailable
@ -240,14 +236,6 @@ var showCmd = &cobra.Command{
// Show dependencies - grouped by dependency type for clarity
depsWithMeta, _ := issueStore.GetDependenciesWithMetadata(ctx, issue.ID) // Best effort: show issue even if deps unavailable
// Resolve external deps via routing (bd-k0pfm)
// GetDependenciesWithMetadata JOINs on issues table, so external refs
// (e.g., "external:other-project:gt-42zaq") are silently dropped.
// Resolve them via prefix routes and merge into the dep list.
if externalDeps, err := resolveExternalDepsViaRouting(ctx, issueStore, issue.ID); err == nil {
depsWithMeta = append(depsWithMeta, externalDeps...)
}
if len(depsWithMeta) > 0 {
// Group by dependency type
var blocks, parent, discovered []*types.IssueWithDependencyMetadata

View file

@ -124,11 +124,6 @@ func displayShowIssueReturn(ctx context.Context, issueID string) *types.Issue {
relatedSeen := make(map[string]*types.IssueWithDependencyMetadata)
depsWithMeta, _ := issueStore.GetDependenciesWithMetadata(ctx, issue.ID)
// Resolve external deps via routing (bd-k0pfm)
if externalDeps, err := resolveExternalDepsViaRouting(ctx, issueStore, issue.ID); err == nil {
depsWithMeta = append(depsWithMeta, externalDeps...)
}
if len(depsWithMeta) > 0 {
var blocks, parent, discovered []*types.IssueWithDependencyMetadata
for _, dep := range depsWithMeta {

View file

@ -1,557 +0,0 @@
package routing
import (
"bufio"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
// RoutesFileName is the name of the routes configuration file
const RoutesFileName = "routes.jsonl"
// Route represents a prefix-to-path routing rule
type Route struct {
Prefix string `json:"prefix"` // Issue ID prefix (e.g., "gt-")
Path string `json:"path"` // Relative path to .beads directory
}
// LoadRoutes loads routes from routes.jsonl in the given beads directory.
// Returns an empty slice if the file doesn't exist.
func LoadRoutes(beadsDir string) ([]Route, error) {
routesPath := filepath.Join(beadsDir, RoutesFileName)
file, err := os.Open(routesPath) //nolint:gosec // routesPath is constructed from known beadsDir
if err != nil {
if os.IsNotExist(err) {
return nil, nil // No routes file is not an error
}
return nil, err
}
defer file.Close()
var routes []Route
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue // Skip empty lines and comments
}
var route Route
if err := json.Unmarshal([]byte(line), &route); err != nil {
continue // Skip malformed lines
}
if route.Prefix != "" && route.Path != "" {
routes = append(routes, route)
}
}
return routes, scanner.Err()
}
// LoadTownRoutes loads routes from the town-level routes.jsonl.
// It first checks the given beadsDir, then walks up to find the town root
// and loads routes from there. This is useful for multi-rig setups (orchestrator workspaces)
// where routes.jsonl lives at <town-root>/.beads/ rather than in individual rig directories.
// Returns routes and nil error on success, or nil routes if not in a town or no routes found.
func LoadTownRoutes(beadsDir string) ([]Route, error) {
routes, _ := findTownRoutes(beadsDir)
return routes, nil
}
// ResolveTownBeadsDir returns the authoritative routes-bearing .beads directory
// for the current routing context.
func ResolveTownBeadsDir(currentBeadsDir string) string {
if currentBeadsDir != "" {
routes, err := LoadRoutes(currentBeadsDir)
if err == nil && len(routes) > 0 {
return currentBeadsDir
}
}
_, townRoot := findTownRoutes(currentBeadsDir)
if townRoot == "" {
return ""
}
townBeadsDir := filepath.Join(townRoot, ".beads")
routes, err := LoadRoutes(townBeadsDir)
if err != nil || len(routes) == 0 {
return ""
}
return townBeadsDir
}
// ExtractPrefix extracts the prefix from an issue ID.
// For "gt-abc123", returns "gt-".
// For "bd-abc123", returns "bd-".
// Returns empty string if no prefix found.
// Delegates to types.ExtractPrefix — kept here for caller convenience.
func ExtractPrefix(id string) string {
return types.ExtractPrefix(id)
}
// ExtractProjectFromPath extracts the project name from a route path.
// For "beads/mayor/rig", returns "beads".
// For "my-project/crew/max", returns "my-project".
func ExtractProjectFromPath(path string) string {
// Get the first component of the path
parts := strings.Split(path, "/")
if len(parts) > 0 && parts[0] != "" {
return parts[0]
}
return ""
}
// LookupRigByName finds a route by rig name (first path component).
// For example, LookupRigByName("beads", beadsDir) would find the route
// with path "beads/mayor/rig" and return it.
//
// Returns the matching route and true if found, or zero Route and false if not.
func LookupRigByName(rigName, beadsDir string) (Route, bool) {
routes, err := LoadRoutes(beadsDir)
if err != nil || len(routes) == 0 {
return Route{}, false
}
for _, route := range routes {
project := ExtractProjectFromPath(route.Path)
if project == rigName {
return route, true
}
}
return Route{}, false
}
// LookupRigForgiving finds a route using flexible matching.
// Accepts any of these formats and normalizes them:
// - "bd-" (exact prefix)
// - "bd" (prefix without hyphen, will try "bd-")
// - "beads" (rig name)
//
// This provides good agent UX - meet them where they are.
// It searches for routes.jsonl in the current beads dir first, then at the town level.
func LookupRigForgiving(input, beadsDir string) (Route, bool) {
route, _, found := lookupRigForgivingWithTown(input, beadsDir)
return route, found
}
// lookupRigForgivingWithTown finds a route with flexible matching and returns the town root.
// Returns (route, townRoot, found).
func lookupRigForgivingWithTown(input, beadsDir string) (Route, string, bool) {
routes, townRoot := findTownRoutes(beadsDir)
if len(routes) == 0 {
return Route{}, "", false
}
// Normalize: remove trailing hyphen for comparison
normalized := strings.TrimSuffix(input, "-")
for _, route := range routes {
// Try exact prefix match (with or without hyphen)
prefixBase := strings.TrimSuffix(route.Prefix, "-")
if normalized == prefixBase || input == route.Prefix {
return route, townRoot, true
}
// Try rig name match
project := ExtractProjectFromPath(route.Path)
if input == project {
return route, townRoot, true
}
}
return Route{}, "", false
}
// ResolveBeadsDirForRig returns the beads directory for a given rig identifier.
// This is used by --rig and --prefix flags to create issues in a different rig.
//
// The input is forgiving - accepts any of:
// - "beads", "my-project" (rig names)
// - "bd-", "mp-" (exact prefixes)
// - "bd", "mp" (prefixes without hyphen)
//
// Parameters:
// - rigOrPrefix: rig name or prefix in any format
// - currentBeadsDir: the current .beads directory (used to find routes.jsonl)
//
// Returns:
// - beadsDir: the target .beads directory path
// - prefix: the issue prefix for that rig (e.g., "bd-")
// - err: error if rig not found or path doesn't exist
func ResolveBeadsDirForRig(rigOrPrefix, currentBeadsDir string) (beadsDir string, prefix string, err error) {
route, townRoot, found := lookupRigForgivingWithTown(rigOrPrefix, currentBeadsDir)
if !found {
return "", "", fmt.Errorf("rig or prefix %q not found in routes.jsonl", rigOrPrefix)
}
// Resolve the target beads directory
var targetPath string
if route.Path == "." {
// Special case: "." means the town beads directory
targetPath = filepath.Join(townRoot, ".beads")
} else {
// Normal path resolution relative to town root
targetPath = filepath.Join(townRoot, route.Path, ".beads")
}
// Follow redirect, preserving source dolt_database
rInfo := beads.ResolveRedirect(targetPath)
targetPath = rInfo.TargetDir
if rInfo.WasRedirected && rInfo.SourceDatabase != "" && os.Getenv("BEADS_DOLT_SERVER_DATABASE") == "" {
_ = os.Setenv("BEADS_DOLT_SERVER_DATABASE", rInfo.SourceDatabase)
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] Preserved source dolt_database %q across redirect for rig %q\n", rInfo.SourceDatabase, rigOrPrefix)
}
}
// Verify the target exists
if info, statErr := os.Stat(targetPath); statErr != nil || !info.IsDir() {
return "", "", fmt.Errorf("rig %q beads directory not found: %s", rigOrPrefix, targetPath)
}
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] Rig %q -> prefix %s, path %s (townRoot=%s)\n", rigOrPrefix, route.Prefix, targetPath, townRoot)
}
return targetPath, route.Prefix, nil
}
// ResolveToExternalRef attempts to convert a foreign issue ID to an external reference
// using routes.jsonl for prefix-based routing.
//
// If the ID's prefix matches a route, returns "external:<project>:<id>".
// Otherwise, returns empty string (no route found).
//
// Example: If routes.jsonl has {"prefix": "bd-", "path": "beads/mayor/rig"}
// then ResolveToExternalRef("bd-abc", beadsDir) returns "external:beads:bd-abc"
func ResolveToExternalRef(id, beadsDir string) string {
routes, err := LoadRoutes(beadsDir)
if err != nil || len(routes) == 0 {
return ""
}
prefix := ExtractPrefix(id)
if prefix == "" {
return ""
}
for _, route := range routes {
if route.Prefix == prefix {
project := ExtractProjectFromPath(route.Path)
if project != "" {
return fmt.Sprintf("external:%s:%s", project, id)
}
}
}
return ""
}
// ResolveBeadsDirForID determines which beads directory contains the given issue ID.
// It first checks the local beads directory, then consults routes.jsonl for prefix-based routing.
// If routes.jsonl is not found locally, it searches up to the town root.
//
// When a redirect is followed, the source directory's dolt_database is preserved via
// BEADS_DOLT_SERVER_DATABASE env var so GetDoltDatabase() picks it up automatically.
// This prevents the redirect target's database from overriding the source's.
//
// Parameters:
// - ctx: context for database operations
// - id: the issue ID to look up
// - currentBeadsDir: the current/local .beads directory path
//
// Returns:
// - beadsDir: the resolved .beads directory path
// - routed: true if the ID was routed to a different directory
// - err: any error encountered
func ResolveBeadsDirForID(ctx context.Context, id, currentBeadsDir string) (string, bool, error) {
// Step 1: Check for routes.jsonl based on ID prefix
// First try local, then walk up to find town-level routes
routes, townRoot := findTownRoutes(currentBeadsDir)
if len(routes) > 0 {
prefix := ExtractPrefix(id)
if prefix != "" {
for _, route := range routes {
if route.Prefix == prefix {
// Found a matching route - resolve the path
var targetPath string
if route.Path == "." {
// Special case: "." means the town beads directory
targetPath = filepath.Join(townRoot, ".beads")
} else {
// Normal path resolution relative to town root
targetPath = filepath.Join(townRoot, route.Path, ".beads")
}
// Follow redirect, preserving source dolt_database
rInfo := beads.ResolveRedirect(targetPath)
targetPath = rInfo.TargetDir
if rInfo.WasRedirected && rInfo.SourceDatabase != "" && os.Getenv("BEADS_DOLT_SERVER_DATABASE") == "" {
_ = os.Setenv("BEADS_DOLT_SERVER_DATABASE", rInfo.SourceDatabase)
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] Preserved source dolt_database %q across redirect for %s\n", rInfo.SourceDatabase, id)
}
}
// Verify the target exists
if info, err := os.Stat(targetPath); err == nil && info.IsDir() {
// Debug logging
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] ID %s matched prefix %s -> %s (townRoot=%s)\n", id, prefix, targetPath, townRoot)
}
return targetPath, true, nil
} else if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] ID %s matched prefix %s but target %s not found: %v\n", id, prefix, targetPath, err)
}
}
}
}
}
// Step 2: No route matched or no routes file - use local store
return currentBeadsDir, false, nil
}
// findTownRoot walks up from startDir looking for a town root.
// Returns the town root path, or empty string if not found.
// A town root is identified by the presence of mayor/town.json.
func findTownRoot(startDir string) string {
current := startDir
for {
// Check for primary marker (mayor/town.json)
if _, err := os.Stat(filepath.Join(current, "mayor", "town.json")); err == nil {
return current
}
parent := filepath.Dir(current)
if parent == current {
return "" // Reached filesystem root
}
current = parent
}
}
// findTownRootFromCWD walks up from the current working directory looking for a town root.
// This is used to handle symlinked .beads directories correctly.
// By starting from CWD instead of the beads directory path, we find the correct
// town root even when .beads is a symlink that points elsewhere.
func findTownRootFromCWD() string {
cwd, err := os.Getwd()
if err != nil {
return ""
}
return findTownRoot(cwd)
}
func canonicalizeRoutingBeadsDir(beadsDir string) string {
if beadsDir == "" {
return ""
}
return utils.NormalizePathForComparison(beads.ResolveRedirect(beadsDir).TargetDir)
}
func findTownRootForBeadsDirFromCWD(currentBeadsDir string) string {
targetBeadsDir := canonicalizeRoutingBeadsDir(currentBeadsDir)
if targetBeadsDir == "" {
return ""
}
cwd, err := os.Getwd()
if err != nil {
return ""
}
current := cwd
for {
if _, err := os.Stat(filepath.Join(current, "mayor", "town.json")); err == nil {
candidateBeadsDir := filepath.Join(current, ".beads")
if info, statErr := os.Stat(candidateBeadsDir); statErr == nil && info.IsDir() {
if canonicalizeRoutingBeadsDir(candidateBeadsDir) == targetBeadsDir {
return current
}
}
}
parent := filepath.Dir(current)
if parent == current {
return ""
}
current = parent
}
}
func findNearestTownRoutesFromPath(startDir string) ([]Route, string) {
if startDir == "" {
return nil, ""
}
current := startDir
for {
if _, err := os.Stat(filepath.Join(current, "mayor", "town.json")); err == nil {
townBeadsDir := filepath.Join(current, ".beads")
routes, loadErr := LoadRoutes(townBeadsDir)
if loadErr == nil && len(routes) > 0 {
return routes, current
}
}
parent := filepath.Dir(current)
if parent == current {
return nil, ""
}
current = parent
}
}
func findNearestTownRoutesFromCWD() ([]Route, string) {
cwd, err := os.Getwd()
if err != nil {
return nil, ""
}
return findNearestTownRoutesFromPath(cwd)
}
// findTownRoutes searches for routes.jsonl at the town level.
// It walks up from currentBeadsDir to find the town root, then loads routes
// from <townRoot>/.beads/routes.jsonl.
// Returns (routes, townRoot). Returns nil routes if not in an orchestrator town or no routes found.
//
// IMPORTANT: This function handles symlinked .beads directories correctly.
// When .beads is a symlink (e.g., <town-root>/.beads -> <town-root>/olympus/.beads),
// we must use findTownRoot() starting from CWD to determine the actual town root
// rather than starting from currentBeadsDir, which may be the resolved symlink path.
func findTownRoutes(currentBeadsDir string) ([]Route, string) {
// First try the current beads dir (works if we're already at town level)
routes, err := LoadRoutes(currentBeadsDir)
if err == nil && len(routes) > 0 {
// When routes come from currentBeadsDir, the town root must belong to that
// same .beads owner. In nested town layouts, blindly using the nearest CWD
// town can pair outer routes with an inner mayor/town.json and route to the
// wrong tree.
townRoot := findTownRootForBeadsDirFromCWD(currentBeadsDir)
if townRoot != "" {
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] findTownRoutes: found routes in %s, townRoot=%s (matched route source)\n", currentBeadsDir, townRoot)
}
return routes, townRoot
}
if townRoot = findTownRoot(filepath.Dir(currentBeadsDir)); townRoot != "" {
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] findTownRoutes: found routes in %s, townRoot=%s (via currentBeadsDir ancestry)\n", currentBeadsDir, townRoot)
}
return routes, townRoot
}
// Fallback to parent dir if not in a town structure (for non-orchestrator repos)
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] findTownRoutes: found routes in %s, townRoot=%s (fallback to parent dir)\n", currentBeadsDir, filepath.Dir(currentBeadsDir))
}
return routes, filepath.Dir(currentBeadsDir)
}
if currentBeadsDir != "" {
routes, townRoot := findNearestTownRoutesFromPath(filepath.Dir(currentBeadsDir))
if len(routes) > 0 && townRoot != "" {
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] findTownRoutes: loaded routes from %s, townRoot=%s (via currentBeadsDir ancestry)\n", filepath.Join(townRoot, ".beads"), townRoot)
}
return routes, townRoot
}
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] findTownRoutes: no routes found for authoritative beads dir %s\n", currentBeadsDir)
}
return nil, ""
}
// Walk up town roots from CWD until we find one that actually has routes.
routes, townRoot := findNearestTownRoutesFromCWD()
if len(routes) == 0 || townRoot == "" {
return nil, "" // Not in a town
}
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] findTownRoutes: loaded routes from %s, townRoot=%s\n", filepath.Join(townRoot, ".beads"), townRoot)
}
return routes, townRoot
}
// RoutedStorage represents a storage connection that may have been routed
// to a different beads directory than the local one.
type RoutedStorage struct {
Storage storage.DoltStorage
BeadsDir string
Routed bool // true if this is a routed (non-local) storage
}
// Close closes the storage connection
func (rs *RoutedStorage) Close() error {
if rs.Storage != nil {
return rs.Storage.Close()
}
return nil
}
// StorageOpener is a function that opens storage for a given beads directory.
// This allows callers to provide custom storage opening logic (e.g., using factory).
type StorageOpener func(ctx context.Context, beadsDir string) (storage.DoltStorage, error)
// GetRoutedStorageForID returns a storage connection for the given issue ID.
// If the ID matches a route, it opens a connection to the routed database.
// Otherwise, it returns nil (caller should use their existing storage).
//
// DEPRECATED: Use GetRoutedStorageWithOpener for proper backend support.
// The caller is responsible for closing the returned RoutedStorage.
func GetRoutedStorageForID(ctx context.Context, id, currentBeadsDir string) (*RoutedStorage, error) {
return GetRoutedStorageWithOpener(ctx, id, currentBeadsDir, nil)
}
// GetRoutedStorageWithOpener returns a storage connection for the given issue ID.
// If the ID matches a route, it opens a connection to the routed database.
// The opener function is used to create storage; if nil, an error is returned.
// Otherwise, it returns nil (caller should use their existing storage).
//
// The caller is responsible for closing the returned RoutedStorage.
func GetRoutedStorageWithOpener(ctx context.Context, id, currentBeadsDir string, opener StorageOpener) (*RoutedStorage, error) {
beadsDir, routed, err := ResolveBeadsDirForID(ctx, id, currentBeadsDir)
if err != nil {
return nil, err
}
if !routed {
return nil, nil // No routing needed, caller should use existing storage
}
// Check if target is same as current - no need to open a new store
if beadsDir == currentBeadsDir {
return nil, nil // Same directory, caller should use existing storage
}
// Open storage for the routed directory
if opener == nil {
return nil, fmt.Errorf("no storage opener provided for routed storage (use GetRoutedStorageWithOpener with an explicit opener)")
}
store, err := opener(ctx, beadsDir)
if err != nil {
return nil, err
}
return &RoutedStorage{
Storage: store,
BeadsDir: beadsDir,
Routed: true,
}, nil
}

View file

@ -1,10 +1,7 @@
package routing
import (
"context"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
)
@ -94,60 +91,6 @@ func TestDetectUserRole_Fallback(t *testing.T) {
}
}
func TestExtractPrefix(t *testing.T) {
tests := []struct {
id string
want string
}{
{"gt-abc123", "gt-"},
{"bd-xyz", "bd-"},
{"hq-1234", "hq-"},
{"abc123", ""}, // No hyphen
{"", ""}, // Empty string
{"-abc", "-"}, // Starts with hyphen
}
for _, tt := range tests {
t.Run(tt.id, func(t *testing.T) {
got := ExtractPrefix(tt.id)
if got != tt.want {
t.Errorf("ExtractPrefix(%q) = %q, want %q", tt.id, got, tt.want)
}
})
}
}
func TestExtractProjectFromPath(t *testing.T) {
tests := []struct {
path string
want string
}{
{"beads/mayor/rig", "beads"},
{"my-project/crew/max", "my-project"},
{"simple", "simple"},
{"", ""},
{"/absolute/path", ""}, // Starts with /, first component is empty
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
got := ExtractProjectFromPath(tt.path)
if got != tt.want {
t.Errorf("ExtractProjectFromPath(%q) = %q, want %q", tt.path, got, tt.want)
}
})
}
}
func TestResolveToExternalRef(t *testing.T) {
// This test is limited since it requires a routes.jsonl file
// Just test that it returns empty string for nonexistent directory
got := ResolveToExternalRef("bd-abc", "/nonexistent/path")
if got != "" {
t.Errorf("ResolveToExternalRef() = %q, want empty string for nonexistent path", got)
}
}
type gitCall struct {
repo string
args []string
@ -359,668 +302,3 @@ func TestDetectUserRole_UpstreamSameRepoStillMaintainer(t *testing.T) {
t.Fatalf("expected %s, got %s", Maintainer, role)
}
}
// TestFindTownRoutes_SymlinkedBeadsDir verifies that findTownRoutes correctly
// handles symlinked .beads directories by using findTownRootFromCWD() instead of
// walking up from the beadsDir path.
//
// Scenario: <town>/.beads is a symlink to <town>/olympus/.beads
// Before fix: walking up from <town>/olympus/.beads finds <town>/olympus (WRONG)
// After fix: findTownRootFromCWD() walks up from CWD to find mayor/town.json at <town>
func TestFindTownRoutes_SymlinkedBeadsDir(t *testing.T) {
// Create temporary directory structure simulating an orchestrator workspace:
// tmpDir/
// mayor/
// town.json <- town root marker
// olympus/ <- actual beads storage
// .beads/
// routes.jsonl
// .beads -> olympus/.beads <- symlink
// daedalus/
// mayor/
// rig/
// .beads/ <- target rig
tmpDir, err := os.MkdirTemp("", "routing-symlink-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
// Resolve symlinks in tmpDir (macOS /var -> /private/var)
tmpDir, err = filepath.EvalSymlinks(tmpDir)
if err != nil {
t.Fatal(err)
}
// Create mayor/town.json to mark town root
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(mayorDir, 0750); err != nil {
t.Fatal(err)
}
townJSON := filepath.Join(mayorDir, "town.json")
if err := os.WriteFile(townJSON, []byte(`{"name": "test-town"}`), 0600); err != nil {
t.Fatal(err)
}
// Create olympus/.beads with routes.jsonl
olympusBeadsDir := filepath.Join(tmpDir, "olympus", ".beads")
if err := os.MkdirAll(olympusBeadsDir, 0750); err != nil {
t.Fatal(err)
}
routesContent := `{"prefix": "gt-", "path": "daedalus/mayor/rig"}
`
routesPath := filepath.Join(olympusBeadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte(routesContent), 0600); err != nil {
t.Fatal(err)
}
// Create daedalus/mayor/rig/.beads as target rig
daedalusBeadsDir := filepath.Join(tmpDir, "daedalus", "mayor", "rig", ".beads")
if err := os.MkdirAll(daedalusBeadsDir, 0750); err != nil {
t.Fatal(err)
}
// Create metadata.json so the rig is recognized as valid
if err := os.WriteFile(filepath.Join(daedalusBeadsDir, "metadata.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
// Create symlink: tmpDir/.beads -> olympus/.beads
symlinkPath := filepath.Join(tmpDir, ".beads")
if err := os.Symlink(olympusBeadsDir, symlinkPath); err != nil {
t.Skip("Cannot create symlinks on this system (may require admin on Windows)")
}
// Change to the town root directory - this simulates the user running bd from ~/gt
// The fix uses findTownRootFromCWD() which needs CWD to be inside the town
t.Chdir(tmpDir)
// Simulate what happens when FindBeadsDir() returns the resolved symlink path
// (this is what CanonicalizePath does)
resolvedBeadsDir := olympusBeadsDir // This is what would be passed to findTownRoutes
// Call findTownRoutes with the resolved symlink path
routes, townRoot := findTownRoutes(resolvedBeadsDir)
// Verify we got the routes
if len(routes) == 0 {
t.Fatal("findTownRoutes returned no routes")
}
// Verify the town root is correct (should be tmpDir, NOT tmpDir/olympus)
if townRoot != tmpDir {
t.Errorf("findTownRoutes returned wrong townRoot:\n got: %s\n want: %s", townRoot, tmpDir)
}
// Verify route resolution works - the route should resolve to the correct path
expectedRigPath := filepath.Join(tmpDir, "daedalus", "mayor", "rig", ".beads")
for _, route := range routes {
if route.Prefix == "gt-" {
actualPath := filepath.Join(townRoot, route.Path, ".beads")
if actualPath != expectedRigPath {
t.Errorf("Route resolution failed:\n got: %s\n want: %s", actualPath, expectedRigPath)
}
}
}
}
// TestResolveBeadsDirForRig_FollowsRedirect verifies that ResolveBeadsDirForRig
// correctly follows redirect files when resolving rig paths.
func TestResolveBeadsDirForRig_FollowsRedirect(t *testing.T) {
tmpDir := t.TempDir()
// Resolve symlinks in tmpDir (macOS /var -> /private/var)
tmpDir, err := filepath.EvalSymlinks(tmpDir)
if err != nil {
t.Fatal(err)
}
// Create town structure:
// tmpDir/
// mayor/
// town.json
// .beads/
// routes.jsonl
// project/
// .beads/
// redirect <- points to actual/.beads
// actual/
// .beads/ <- real beads directory
// Create mayor/town.json to mark town root
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(mayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(mayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
// Create town-level .beads with routes.jsonl
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0750); err != nil {
t.Fatal(err)
}
routesContent := `{"prefix": "proj-", "path": "project"}
`
if err := os.WriteFile(filepath.Join(townBeadsDir, "routes.jsonl"), []byte(routesContent), 0600); err != nil {
t.Fatal(err)
}
// Create stub project/.beads with redirect
stubBeadsDir := filepath.Join(tmpDir, "project", ".beads")
if err := os.MkdirAll(stubBeadsDir, 0750); err != nil {
t.Fatal(err)
}
// Create actual/.beads as the real target
actualBeadsDir := filepath.Join(tmpDir, "actual", ".beads")
if err := os.MkdirAll(actualBeadsDir, 0750); err != nil {
t.Fatal(err)
}
// Write redirect file pointing to actual/.beads
redirectContent := "# Redirect to actual storage location\n" + actualBeadsDir + "\n"
if err := os.WriteFile(filepath.Join(stubBeadsDir, "redirect"), []byte(redirectContent), 0600); err != nil {
t.Fatal(err)
}
// Change to town root (required for findTownRootFromCWD)
t.Chdir(tmpDir)
// Test ResolveBeadsDirForRig
resolvedDir, prefix, err := ResolveBeadsDirForRig("proj-", townBeadsDir)
if err != nil {
t.Fatalf("ResolveBeadsDirForRig() error = %v", err)
}
if prefix != "proj-" {
t.Errorf("ResolveBeadsDirForRig() prefix = %q, want %q", prefix, "proj-")
}
// The resolved directory should be the actual target, not the stub
resolvedResolved, _ := filepath.EvalSymlinks(resolvedDir)
actualResolved, _ := filepath.EvalSymlinks(actualBeadsDir)
if resolvedResolved != actualResolved {
t.Errorf("ResolveBeadsDirForRig() did not follow redirect:\n got: %s\n want: %s", resolvedDir, actualBeadsDir)
}
}
// TestResolveBeadsDirForID_FollowsRedirect verifies that ResolveBeadsDirForID
// correctly follows redirect files when resolving issue ID lookups.
func TestResolveBeadsDirForID_FollowsRedirect(t *testing.T) {
tmpDir := t.TempDir()
// Resolve symlinks in tmpDir (macOS /var -> /private/var)
tmpDir, err := filepath.EvalSymlinks(tmpDir)
if err != nil {
t.Fatal(err)
}
// Create town structure with redirect
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(mayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(mayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
// Create town-level .beads with routes.jsonl
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0750); err != nil {
t.Fatal(err)
}
routesContent := `{"prefix": "test-", "path": "myproject"}
`
if err := os.WriteFile(filepath.Join(townBeadsDir, "routes.jsonl"), []byte(routesContent), 0600); err != nil {
t.Fatal(err)
}
// Create stub myproject/.beads with redirect
stubBeadsDir := filepath.Join(tmpDir, "myproject", ".beads")
if err := os.MkdirAll(stubBeadsDir, 0750); err != nil {
t.Fatal(err)
}
// Create actual target directory
actualBeadsDir := filepath.Join(tmpDir, "storage", ".beads")
if err := os.MkdirAll(actualBeadsDir, 0750); err != nil {
t.Fatal(err)
}
// Write redirect file
if err := os.WriteFile(filepath.Join(stubBeadsDir, "redirect"), []byte(actualBeadsDir+"\n"), 0600); err != nil {
t.Fatal(err)
}
// Change to town root
t.Chdir(tmpDir)
// Test ResolveBeadsDirForID with an ID that matches the route prefix
ctx := context.Background()
resolvedDir, routed, err := ResolveBeadsDirForID(ctx, "test-abc123", townBeadsDir)
if err != nil {
t.Fatalf("ResolveBeadsDirForID() error = %v", err)
}
if !routed {
t.Error("ResolveBeadsDirForID() routed = false, want true")
}
// The resolved directory should be the actual target, not the stub
resolvedResolved, _ := filepath.EvalSymlinks(resolvedDir)
actualResolved, _ := filepath.EvalSymlinks(actualBeadsDir)
if resolvedResolved != actualResolved {
t.Errorf("ResolveBeadsDirForID() did not follow redirect:\n got: %s\n want: %s", resolvedDir, actualBeadsDir)
}
}
// TestResolveBeadsDirForRig_FollowsRelativeRedirectFromRigRoot verifies that
// relative redirect paths are resolved from the rig root (parent of .beads),
// not from the .beads directory itself.
func TestResolveBeadsDirForRig_FollowsRelativeRedirectFromRigRoot(t *testing.T) {
tmpDir := t.TempDir()
tmpDir, err := filepath.EvalSymlinks(tmpDir)
if err != nil {
t.Fatal(err)
}
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(mayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(mayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0750); err != nil {
t.Fatal(err)
}
routesContent := `{"prefix": "crom-", "path": "crom"}
`
if err := os.WriteFile(filepath.Join(townBeadsDir, "routes.jsonl"), []byte(routesContent), 0600); err != nil {
t.Fatal(err)
}
stubBeadsDir := filepath.Join(tmpDir, "crom", ".beads")
if err := os.MkdirAll(stubBeadsDir, 0750); err != nil {
t.Fatal(err)
}
actualBeadsDir := filepath.Join(tmpDir, "crom", "mayor", "rig", ".beads")
if err := os.MkdirAll(actualBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(stubBeadsDir, "redirect"), []byte("mayor/rig/.beads\n"), 0600); err != nil {
t.Fatal(err)
}
t.Chdir(tmpDir)
resolvedDir, prefix, err := ResolveBeadsDirForRig("crom-", townBeadsDir)
if err != nil {
t.Fatalf("ResolveBeadsDirForRig() error = %v", err)
}
if prefix != "crom-" {
t.Errorf("ResolveBeadsDirForRig() prefix = %q, want %q", prefix, "crom-")
}
resolvedResolved, _ := filepath.EvalSymlinks(resolvedDir)
actualResolved, _ := filepath.EvalSymlinks(actualBeadsDir)
if resolvedResolved != actualResolved {
t.Errorf("ResolveBeadsDirForRig() should resolve redirect relative to rig root:\n got: %s\n want: %s", resolvedDir, actualBeadsDir)
}
}
// TestResolveBeadsDirForID_FollowsRelativeRedirectFromRigRoot verifies that
// ID-based prefix routing resolves relative redirects from the rig root.
func TestResolveBeadsDirForID_FollowsRelativeRedirectFromRigRoot(t *testing.T) {
tmpDir := t.TempDir()
tmpDir, err := filepath.EvalSymlinks(tmpDir)
if err != nil {
t.Fatal(err)
}
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(mayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(mayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0750); err != nil {
t.Fatal(err)
}
routesContent := `{"prefix": "crom-", "path": "crom"}
`
if err := os.WriteFile(filepath.Join(townBeadsDir, "routes.jsonl"), []byte(routesContent), 0600); err != nil {
t.Fatal(err)
}
stubBeadsDir := filepath.Join(tmpDir, "crom", ".beads")
if err := os.MkdirAll(stubBeadsDir, 0750); err != nil {
t.Fatal(err)
}
actualBeadsDir := filepath.Join(tmpDir, "crom", "mayor", "rig", ".beads")
if err := os.MkdirAll(actualBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(stubBeadsDir, "redirect"), []byte("mayor/rig/.beads\n"), 0600); err != nil {
t.Fatal(err)
}
crewDir := filepath.Join(tmpDir, "crom", "crew", "flynn")
if err := os.MkdirAll(crewDir, 0750); err != nil {
t.Fatal(err)
}
t.Chdir(crewDir)
ctx := context.Background()
resolvedDir, routed, err := ResolveBeadsDirForID(ctx, "crom-rig-crom", stubBeadsDir)
if err != nil {
t.Fatalf("ResolveBeadsDirForID() error = %v", err)
}
if !routed {
t.Fatal("ResolveBeadsDirForID() routed = false, want true")
}
resolvedResolved, _ := filepath.EvalSymlinks(resolvedDir)
actualResolved, _ := filepath.EvalSymlinks(actualBeadsDir)
if resolvedResolved != actualResolved {
t.Errorf("ResolveBeadsDirForID() should resolve redirect relative to rig root:\n got: %s\n want: %s", resolvedDir, actualBeadsDir)
}
}
func TestResolveTownBeadsDir_PrefersCurrentBeadsDirOverNestedTownCWD(t *testing.T) {
tmpDir := t.TempDir()
outerMayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(outerMayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerMayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
outerTownBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(outerTownBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerTownBeadsDir, "routes.jsonl"), []byte(`{"prefix":"gt-","path":"rigs/outer"}
`), 0600); err != nil {
t.Fatal(err)
}
outerRigBeadsDir := filepath.Join(tmpDir, "outer-worktree", ".beads")
if err := os.MkdirAll(outerRigBeadsDir, 0750); err != nil {
t.Fatal(err)
}
innerTownDir := filepath.Join(tmpDir, "nested-town")
innerMayorDir := filepath.Join(innerTownDir, "mayor")
if err := os.MkdirAll(innerMayorDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(innerMayorDir, "town.json"), []byte(`{}`), 0600); err != nil {
t.Fatal(err)
}
innerBeadsDir := filepath.Join(innerTownDir, ".beads")
if err := os.MkdirAll(innerBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(innerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"gt-","path":"rigs/inner"}
`), 0600); err != nil {
t.Fatal(err)
}
workerDir := filepath.Join(innerTownDir, "crew", "worker")
if err := os.MkdirAll(workerDir, 0750); err != nil {
t.Fatal(err)
}
t.Chdir(workerDir)
if got := ResolveTownBeadsDir(outerRigBeadsDir); got != outerTownBeadsDir {
t.Fatalf("ResolveTownBeadsDir() = %s, want %s", got, outerTownBeadsDir)
}
}
func setupNestedTownRoutingFixture(t *testing.T) (string, string) {
t.Helper()
tmpDir := t.TempDir()
tmpDir, err := filepath.EvalSymlinks(tmpDir)
if err != nil {
t.Fatal(err)
}
outerTownBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(outerTownBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tmpDir, "mayor", "town.json"), []byte(`{"name":"outer-town"}`), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerTownBeadsDir, "routes.jsonl"), []byte(`{"prefix":"crom-","path":"crom"}`+"\n"), 0600); err != nil {
t.Fatal(err)
}
outerTarget := filepath.Join(tmpDir, "crom", ".beads")
if err := os.MkdirAll(outerTarget, 0750); err != nil {
t.Fatal(err)
}
outerRigBeadsDir := filepath.Join(tmpDir, "outer-worktree", ".beads")
if err := os.MkdirAll(outerRigBeadsDir, 0750); err != nil {
t.Fatal(err)
}
nestedTownRoot := filepath.Join(tmpDir, "beads")
if err := os.MkdirAll(filepath.Join(nestedTownRoot, "mayor"), 0750); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(nestedTownRoot, ".beads"), 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(nestedTownRoot, "mayor", "town.json"), []byte(`{"name":"inner-town"}`), 0600); err != nil {
t.Fatal(err)
}
innerTarget := filepath.Join(nestedTownRoot, "crom", ".beads")
if err := os.MkdirAll(innerTarget, 0750); err != nil {
t.Fatal(err)
}
worktreeDir := filepath.Join(nestedTownRoot, "polecats", "obsidian", "beads")
if err := os.MkdirAll(worktreeDir, 0750); err != nil {
t.Fatal(err)
}
t.Chdir(worktreeDir)
return outerRigBeadsDir, outerTarget
}
func TestResolveBeadsDirForRig_UsesOuterTownRootFromNestedTownCWD(t *testing.T) {
outerBeadsDir, outerTarget := setupNestedTownRoutingFixture(t)
resolvedDir, prefix, err := ResolveBeadsDirForRig("crom-", outerBeadsDir)
if err != nil {
t.Fatalf("ResolveBeadsDirForRig() error = %v", err)
}
if prefix != "crom-" {
t.Fatalf("ResolveBeadsDirForRig() prefix = %q, want %q", prefix, "crom-")
}
resolvedResolved, _ := filepath.EvalSymlinks(resolvedDir)
outerResolved, _ := filepath.EvalSymlinks(outerTarget)
if resolvedResolved != outerResolved {
t.Errorf("ResolveBeadsDirForRig() should use outer town root:\n got: %s\n want: %s", resolvedDir, outerTarget)
}
}
func TestResolveBeadsDirForID_UsesOuterTownRootFromNestedTownCWD(t *testing.T) {
outerBeadsDir, outerTarget := setupNestedTownRoutingFixture(t)
ctx := context.Background()
resolvedDir, routed, err := ResolveBeadsDirForID(ctx, "crom-abc123", outerBeadsDir)
if err != nil {
t.Fatalf("ResolveBeadsDirForID() error = %v", err)
}
if !routed {
t.Fatal("ResolveBeadsDirForID() routed = false, want true")
}
resolvedResolved, _ := filepath.EvalSymlinks(resolvedDir)
outerResolved, _ := filepath.EvalSymlinks(outerTarget)
if resolvedResolved != outerResolved {
t.Errorf("ResolveBeadsDirForID() should use outer town root:\n got: %s\n want: %s", resolvedDir, outerTarget)
}
}
func TestResolveBeadsDirForID_DoesNotUseCWDRoutesWhenCurrentBeadsDirIsAuthoritative(t *testing.T) {
tmpDir := t.TempDir()
authoritativeBeadsDir := filepath.Join(tmpDir, "explicit", ".beads")
if err := os.MkdirAll(authoritativeBeadsDir, 0750); err != nil {
t.Fatal(err)
}
nestedTownDir := filepath.Join(tmpDir, "nested-town")
if err := os.MkdirAll(filepath.Join(nestedTownDir, "mayor"), 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(nestedTownDir, "mayor", "town.json"), []byte(`{"name":"inner-town"}`), 0600); err != nil {
t.Fatal(err)
}
innerBeadsDir := filepath.Join(nestedTownDir, ".beads")
if err := os.MkdirAll(innerBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(innerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"crom-","path":"crom"}`+"\n"), 0600); err != nil {
t.Fatal(err)
}
innerTarget := filepath.Join(nestedTownDir, "crom", ".beads")
if err := os.MkdirAll(innerTarget, 0750); err != nil {
t.Fatal(err)
}
workerDir := filepath.Join(nestedTownDir, "crew", "worker")
if err := os.MkdirAll(workerDir, 0750); err != nil {
t.Fatal(err)
}
t.Chdir(workerDir)
ctx := context.Background()
resolvedDir, routed, err := ResolveBeadsDirForID(ctx, "crom-abc123", authoritativeBeadsDir)
if err != nil {
t.Fatalf("ResolveBeadsDirForID() error = %v", err)
}
if routed {
t.Fatal("ResolveBeadsDirForID() routed = true, want false")
}
if resolvedDir != authoritativeBeadsDir {
t.Fatalf("ResolveBeadsDirForID() = %s, want %s", resolvedDir, authoritativeBeadsDir)
}
if got := ResolveTownBeadsDir(authoritativeBeadsDir); got != "" {
t.Fatalf("ResolveTownBeadsDir() = %s, want empty string", got)
}
if innerTarget == resolvedDir {
t.Fatal("ResolveBeadsDirForID() should not drift to CWD town routes")
}
}
func TestResolveBeadsDirForID_UsesOuterTownRootWithNestedTownAndRedirectedRouteSource(t *testing.T) {
tmpDir := t.TempDir()
tmpDir, err := filepath.EvalSymlinks(tmpDir)
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tmpDir, "mayor", "town.json"), []byte(`{"name":"outer-town"}`), 0600); err != nil {
t.Fatal(err)
}
routerBeadsDir := filepath.Join(tmpDir, "router", ".beads")
if err := os.MkdirAll(routerBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(routerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"crom-","path":"crom"}`+"\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(routerBeadsDir, filepath.Join(tmpDir, ".beads")); err != nil {
t.Skip("Cannot create symlinks on this system")
}
outerStubBeadsDir := filepath.Join(tmpDir, "crom", ".beads")
if err := os.MkdirAll(outerStubBeadsDir, 0750); err != nil {
t.Fatal(err)
}
outerActualTarget := filepath.Join(tmpDir, "crom", "mayor", "rig", ".beads")
if err := os.MkdirAll(outerActualTarget, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(outerStubBeadsDir, "redirect"), []byte("mayor/rig/.beads\n"), 0600); err != nil {
t.Fatal(err)
}
nestedTownDir := filepath.Join(tmpDir, "beads")
if err := os.MkdirAll(filepath.Join(nestedTownDir, "mayor"), 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(nestedTownDir, "mayor", "town.json"), []byte(`{"name":"inner-town"}`), 0600); err != nil {
t.Fatal(err)
}
innerBeadsDir := filepath.Join(nestedTownDir, ".beads")
if err := os.MkdirAll(innerBeadsDir, 0750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(innerBeadsDir, "routes.jsonl"), []byte(`{"prefix":"crom-","path":"crom"}`+"\n"), 0600); err != nil {
t.Fatal(err)
}
innerTarget := filepath.Join(nestedTownDir, "crom", ".beads")
if err := os.MkdirAll(innerTarget, 0750); err != nil {
t.Fatal(err)
}
worktreeDir := filepath.Join(nestedTownDir, "polecats", "obsidian", "beads")
if err := os.MkdirAll(worktreeDir, 0750); err != nil {
t.Fatal(err)
}
t.Chdir(worktreeDir)
ctx := context.Background()
resolvedDir, routed, err := ResolveBeadsDirForID(ctx, "crom-abc123", routerBeadsDir)
if err != nil {
t.Fatalf("ResolveBeadsDirForID() error = %v", err)
}
if !routed {
t.Fatal("ResolveBeadsDirForID() routed = false, want true")
}
resolvedResolved, _ := filepath.EvalSymlinks(resolvedDir)
outerResolved, _ := filepath.EvalSymlinks(outerActualTarget)
innerResolved, _ := filepath.EvalSymlinks(innerTarget)
if resolvedResolved != outerResolved {
t.Fatalf("ResolveBeadsDirForID() should use outer redirected target:\n got: %s\n want: %s", resolvedDir, outerActualTarget)
}
if resolvedResolved == innerResolved {
t.Fatal("ResolveBeadsDirForID() drifted to nested CWD town root")
}
}