fix(beads): prevent routes.jsonl corruption and add doctor check for rig-level routes.jsonl (#377)

* fix(beads): prevent routes.jsonl corruption from bd auto-export

When issues.jsonl doesn't exist, bd's auto-export mechanism writes
issue data to routes.jsonl, corrupting the routing configuration.

Changes:
- install.go: Create issues.jsonl before routes.jsonl at town level
- manager.go: Create issues.jsonl in rig beads; don't create routes.jsonl
  (rig-level routes.jsonl breaks bd's walk-up routing to town routes)
- Add integration tests for routes.jsonl corruption prevention

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(doctor): add check to detect and fix rig-level routes.jsonl

Add RigRoutesJSONLCheck to detect routes.jsonl files in rig .beads
directories. These files break bd's walk-up routing to town-level
routes.jsonl, causing cross-rig routing failures.

The fix unconditionally deletes rig-level routes.jsonl files since
bd will auto-export to issues.jsonl on next run.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test(rig): add verification that routes.jsonl does NOT exist in rig .beads

Add explicit test assertion and detailed comment explaining why rig-level
routes.jsonl files must not exist (breaks bd walk-up routing to town routes).

Also verify that issues.jsonl DOES exist (prevents bd auto-export corruption).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(doctor): ensure town root route exists in routes.jsonl

The RoutesCheck now detects and fixes missing town root routes (hq- -> .).
This can happen when routes.jsonl is corrupted or was created without the
town route during initialization.

Changes:
- Detect missing hq- route in Run()
- Add hq- route in Fix() when missing
- Handle case where routes.jsonl is corrupted (regenerate with town route)
- Add comprehensive unit tests for route detection and fixing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test(beads): fix routing integration test for routes.jsonl corruption

The TestBeadsRoutingFromTownRoot test was failing because bd's auto-export
mechanism writes issue data to routes.jsonl when issues.jsonl doesn't exist.
This corrupts the routing configuration.

Fix: Create empty issues.jsonl after bd init to prevent corruption.
This mirrors what gt install does to prevent the same bug.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: julianknutsen <julianknutsen@users.noreply.github>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen
2026-01-12 09:45:26 +00:00
committed by GitHub
parent a1008f6f58
commit 043a6abc59
10 changed files with 984 additions and 24 deletions

View File

@@ -112,6 +112,14 @@ func initBeadsDBWithPrefix(t *testing.T, dir, prefix string) {
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("bd init failed in %s: %v\n%s", dir, err, output)
}
// Create empty issues.jsonl to prevent bd auto-export from corrupting routes.jsonl.
// Without this, bd create writes issue data to routes.jsonl (the first .jsonl file
// it finds), corrupting the routing configuration. This mirrors what gt install does.
issuesPath := filepath.Join(dir, ".beads", "issues.jsonl")
if err := os.WriteFile(issuesPath, []byte(""), 0644); err != nil {
t.Fatalf("create issues.jsonl in %s: %v", dir, err)
}
}
func createTestIssue(t *testing.T, dir, title string) *beads.Issue {

View File

@@ -132,6 +132,7 @@ func runDoctor(cmd *cobra.Command, args []string) error {
d.Register(doctor.NewPrefixConflictCheck())
d.Register(doctor.NewPrefixMismatchCheck())
d.Register(doctor.NewRoutesCheck())
d.Register(doctor.NewRigRoutesJSONLCheck())
d.Register(doctor.NewOrphanSessionCheck())
d.Register(doctor.NewOrphanProcessCheck())
d.Register(doctor.NewWispGCCheck())

View File

@@ -378,6 +378,17 @@ func initTownBeads(townPath string) error {
fmt.Printf(" %s Could not verify repo fingerprint: %v\n", style.Dim.Render("⚠"), err)
}
// Ensure issues.jsonl exists BEFORE creating routes.jsonl.
// bd init creates beads.db but not issues.jsonl in SQLite mode.
// If routes.jsonl is created first, bd's auto-export will write issues to routes.jsonl,
// corrupting it. Creating an empty issues.jsonl prevents this.
issuesJSONL := filepath.Join(townPath, ".beads", "issues.jsonl")
if _, err := os.Stat(issuesJSONL); os.IsNotExist(err) {
if err := os.WriteFile(issuesJSONL, []byte{}, 0644); err != nil {
fmt.Printf(" %s Could not create issues.jsonl: %v\n", style.Dim.Render("⚠"), err)
}
}
// Ensure routes.jsonl has an explicit town-level mapping for hq-* beads.
// This keeps hq-* operations stable even when invoked from rig worktrees.
if err := beads.AppendRoute(townPath, beads.Route{Prefix: "hq-", Path: "."}); err != nil {

View File

@@ -341,6 +341,49 @@ func TestRigAddInitializesBeads(t *testing.T) {
t.Errorf("config.yaml doesn't contain expected prefix, got: %s", string(content))
}
}
// =========================================================================
// IMPORTANT: Verify routes.jsonl does NOT exist in the rig's .beads directory
// =========================================================================
//
// WHY WE DON'T CREATE routes.jsonl IN RIG DIRECTORIES:
//
// 1. BD'S WALK-UP ROUTING MECHANISM:
// When bd needs to find routing configuration, it walks up the directory
// tree looking for a .beads directory with routes.jsonl. It stops at the
// first routes.jsonl it finds. If a rig has its own routes.jsonl, bd will
// use that and NEVER reach the town-level routes.jsonl, breaking cross-rig
// routing entirely.
//
// 2. TOWN-LEVEL ROUTING IS THE SOURCE OF TRUTH:
// All routing configuration belongs in the town's .beads/routes.jsonl.
// This single file contains prefix->path mappings for ALL rigs, enabling
// bd to route issue IDs like "tr-123" to the correct rig directory.
//
// 3. HISTORICAL BUG - BD AUTO-EXPORT CORRUPTION:
// There was a bug where bd's auto-export feature would write issue data
// to routes.jsonl if issues.jsonl didn't exist. This corrupted routing
// config with issue JSON objects. We now create empty issues.jsonl files
// proactively to prevent this, but we also verify routes.jsonl doesn't
// exist as a defense-in-depth measure.
//
// 4. DOCTOR CHECK EXISTS:
// The "rig-routes-jsonl" doctor check detects and can fix (delete) any
// routes.jsonl files that appear in rig .beads directories.
//
// If you're modifying rig creation and thinking about adding routes.jsonl
// to the rig's .beads directory - DON'T. It will break cross-rig routing.
// =========================================================================
rigRoutesPath := filepath.Join(beadsDir, "routes.jsonl")
if _, err := os.Stat(rigRoutesPath); err == nil {
t.Errorf("routes.jsonl should NOT exist in rig .beads directory (breaks bd walk-up routing)")
}
// Verify issues.jsonl DOES exist (prevents bd auto-export corruption)
rigIssuesPath := filepath.Join(beadsDir, "issues.jsonl")
if _, err := os.Stat(rigIssuesPath); err != nil {
t.Errorf("issues.jsonl should exist in rig .beads directory (prevents auto-export corruption): %v", err)
}
}
// TestRigAddUpdatesRoutes verifies that routes.jsonl is updated

View File

@@ -0,0 +1,174 @@
//go:build integration
// Package cmd contains integration tests for routes.jsonl corruption prevention.
//
// Run with: go test -tags=integration ./internal/cmd -run TestRoutesJSONLCorruption -v
//
// Bug: bd's auto-export writes issue data to routes.jsonl when issues.jsonl doesn't exist,
// corrupting the routing configuration.
package cmd
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// TestRoutesJSONLCorruption tests that routes.jsonl is not corrupted by bd auto-export.
func TestRoutesJSONLCorruption(t *testing.T) {
// Skip if bd is not available
if _, err := exec.LookPath("bd"); err != nil {
t.Skip("bd not installed, skipping test")
}
t.Run("TownLevelRoutesNotCorrupted", func(t *testing.T) {
// Test that gt install creates issues.jsonl before routes.jsonl
// so that bd auto-export doesn't corrupt routes.jsonl
tmpDir := t.TempDir()
townRoot := filepath.Join(tmpDir, "test-town")
gtBinary := buildGT(t)
// Install town
cmd := exec.Command(gtBinary, "install", townRoot, "--name", "test-town")
cmd.Env = append(os.Environ(), "HOME="+tmpDir)
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("gt install failed: %v\nOutput: %s", err, output)
}
// Verify issues.jsonl exists
issuesPath := filepath.Join(townRoot, ".beads", "issues.jsonl")
if _, err := os.Stat(issuesPath); os.IsNotExist(err) {
t.Error("issues.jsonl should exist after gt install")
}
// Verify routes.jsonl exists and has valid content
routesPath := filepath.Join(townRoot, ".beads", "routes.jsonl")
routesContent, err := os.ReadFile(routesPath)
if err != nil {
t.Fatalf("failed to read routes.jsonl: %v", err)
}
// routes.jsonl should contain routing config, not issue data
if !strings.Contains(string(routesContent), `"prefix"`) {
t.Errorf("routes.jsonl should contain prefix routing, got: %s", routesContent)
}
if strings.Contains(string(routesContent), `"title"`) {
t.Errorf("routes.jsonl should NOT contain issue data (title field), got: %s", routesContent)
}
// Create an issue and verify routes.jsonl is still valid
cmd = exec.Command("bd", "--no-daemon", "-q", "create", "--type", "task", "--title", "test issue")
cmd.Dir = townRoot
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("bd create failed: %v\nOutput: %s", err, output)
}
// Re-read routes.jsonl - it should NOT be corrupted
routesContent, err = os.ReadFile(routesPath)
if err != nil {
t.Fatalf("failed to read routes.jsonl after create: %v", err)
}
if strings.Contains(string(routesContent), `"title"`) {
t.Errorf("routes.jsonl was corrupted with issue data after bd create: %s", routesContent)
}
if !strings.Contains(string(routesContent), `"prefix"`) {
t.Errorf("routes.jsonl lost its routing config: %s", routesContent)
}
})
t.Run("RigLevelNoRoutesJSONL", func(t *testing.T) {
// Test that gt rig add does NOT create routes.jsonl in rig beads
// (rig-level routes.jsonl breaks bd's walk-up routing to town routes)
tmpDir := t.TempDir()
townRoot := filepath.Join(tmpDir, "test-town")
gtBinary := buildGT(t)
// Create a test repo (createTestGitRepo returns the path)
repoDir := createTestGitRepo(t, "test-repo")
// Install town
cmd := exec.Command(gtBinary, "install", townRoot, "--name", "test-town")
cmd.Env = append(os.Environ(), "HOME="+tmpDir)
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("gt install failed: %v\nOutput: %s", err, output)
}
// Add a rig
cmd = exec.Command(gtBinary, "rig", "add", "testrig", repoDir)
cmd.Dir = townRoot
cmd.Env = append(os.Environ(), "HOME="+tmpDir)
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("gt rig add failed: %v\nOutput: %s", err, output)
}
// Verify rig beads directory exists
rigBeadsDir := filepath.Join(townRoot, "testrig", ".beads")
if _, err := os.Stat(rigBeadsDir); os.IsNotExist(err) {
t.Fatal("rig .beads directory should exist")
}
// Verify issues.jsonl exists in rig beads
rigIssuesPath := filepath.Join(rigBeadsDir, "issues.jsonl")
if _, err := os.Stat(rigIssuesPath); os.IsNotExist(err) {
t.Error("issues.jsonl should exist in rig beads")
}
// Verify routes.jsonl does NOT exist in rig beads
rigRoutesPath := filepath.Join(rigBeadsDir, "routes.jsonl")
if _, err := os.Stat(rigRoutesPath); err == nil {
t.Error("routes.jsonl should NOT exist in rig beads (breaks walk-up routing)")
}
})
t.Run("CorruptionReproduction", func(t *testing.T) {
// This test reproduces the bug: if issues.jsonl doesn't exist,
// bd auto-export writes to routes.jsonl
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
os.MkdirAll(beadsDir, 0755)
// Initialize beads
cmd := exec.Command("bd", "--no-daemon", "init", "--prefix", "test", "--quiet")
cmd.Dir = tmpDir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("bd init failed: %v\nOutput: %s", err, output)
}
// Remove issues.jsonl if it exists (to simulate the bug condition)
issuesPath := filepath.Join(beadsDir, "issues.jsonl")
os.Remove(issuesPath)
// Create routes.jsonl with valid routing config
routesPath := filepath.Join(beadsDir, "routes.jsonl")
routesContent := `{"prefix":"test-","path":"."}`
if err := os.WriteFile(routesPath, []byte(routesContent+"\n"), 0644); err != nil {
t.Fatalf("failed to write routes.jsonl: %v", err)
}
// Create an issue - this triggers auto-export
cmd = exec.Command("bd", "--no-daemon", "-q", "create", "--type", "task", "--title", "bug reproduction")
cmd.Dir = tmpDir
cmd.CombinedOutput() // Ignore error - we're testing the corruption
// Check if routes.jsonl was corrupted
newRoutesContent, err := os.ReadFile(routesPath)
if err != nil {
t.Fatalf("failed to read routes.jsonl: %v", err)
}
// If routes.jsonl contains "title", it was corrupted with issue data
if strings.Contains(string(newRoutesContent), `"title"`) {
t.Log("BUG REPRODUCED: routes.jsonl was corrupted with issue data")
t.Log("Content:", string(newRoutesContent))
// This is expected behavior WITHOUT the fix
// The test passes if the fix prevents this
}
})
}
// Note: createTestGitRepo is defined in rig_integration_test.go

View File

@@ -0,0 +1,180 @@
package doctor
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/gastown/internal/beads"
"github.com/steveyegge/gastown/internal/config"
)
// RigRoutesJSONLCheck detects and fixes routes.jsonl files in rig .beads directories.
//
// Rig-level routes.jsonl files are problematic because:
// 1. bd's routing walks up to find town root (via mayor/town.json) and uses town-level routes.jsonl
// 2. If a rig has its own routes.jsonl, bd uses it and never finds town routes, breaking cross-rig routing
// 3. These files often exist due to a bug where bd's auto-export wrote issue data to routes.jsonl
//
// Fix: Delete routes.jsonl unconditionally. The SQLite database (beads.db) is the source
// of truth, and bd will auto-export to issues.jsonl on next run.
type RigRoutesJSONLCheck struct {
FixableCheck
// affectedRigs tracks which rigs have routes.jsonl
affectedRigs []rigRoutesInfo
}
type rigRoutesInfo struct {
rigName string
routesPath string
}
// NewRigRoutesJSONLCheck creates a new check for rig-level routes.jsonl files.
func NewRigRoutesJSONLCheck() *RigRoutesJSONLCheck {
return &RigRoutesJSONLCheck{
FixableCheck: FixableCheck{
BaseCheck: BaseCheck{
CheckName: "rig-routes-jsonl",
CheckDescription: "Check for routes.jsonl in rig .beads directories",
CheckCategory: CategoryConfig,
},
},
}
}
// Run checks for routes.jsonl files in rig .beads directories.
func (c *RigRoutesJSONLCheck) Run(ctx *CheckContext) *CheckResult {
c.affectedRigs = nil // Reset
// Get list of rigs from multiple sources
rigDirs := c.findRigDirectories(ctx.TownRoot)
if len(rigDirs) == 0 {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "No rigs to check",
Category: c.Category(),
}
}
var problems []string
for _, rigDir := range rigDirs {
rigName := filepath.Base(rigDir)
beadsDir := filepath.Join(rigDir, ".beads")
routesPath := filepath.Join(beadsDir, beads.RoutesFileName)
// Check if routes.jsonl exists in this rig's .beads directory
if _, err := os.Stat(routesPath); os.IsNotExist(err) {
continue // Good - no rig-level routes.jsonl
}
// routes.jsonl exists - it should be deleted
problems = append(problems, fmt.Sprintf("%s: has routes.jsonl (will delete - breaks cross-rig routing)", rigName))
c.affectedRigs = append(c.affectedRigs, rigRoutesInfo{
rigName: rigName,
routesPath: routesPath,
})
}
if len(c.affectedRigs) == 0 {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: fmt.Sprintf("No rig-level routes.jsonl files (%d rigs checked)", len(rigDirs)),
Category: c.Category(),
}
}
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: fmt.Sprintf("%d rig(s) have routes.jsonl (breaks routing)", len(c.affectedRigs)),
Details: problems,
FixHint: "Run 'gt doctor --fix' to delete these files",
Category: c.Category(),
}
}
// Fix deletes routes.jsonl files in rig .beads directories.
// The SQLite database (beads.db) is the source of truth - bd will auto-export
// to issues.jsonl on next run.
func (c *RigRoutesJSONLCheck) Fix(ctx *CheckContext) error {
// Re-run check to populate affectedRigs if needed
if len(c.affectedRigs) == 0 {
result := c.Run(ctx)
if result.Status == StatusOK {
return nil // Nothing to fix
}
}
for _, info := range c.affectedRigs {
if err := os.Remove(info.routesPath); err != nil {
return fmt.Errorf("deleting %s: %w", info.routesPath, err)
}
}
return nil
}
// findRigDirectories finds all rig directories in the town.
func (c *RigRoutesJSONLCheck) findRigDirectories(townRoot string) []string {
var rigDirs []string
seen := make(map[string]bool)
// Source 1: rigs.json registry
rigsPath := filepath.Join(townRoot, "mayor", "rigs.json")
if rigsConfig, err := config.LoadRigsConfig(rigsPath); err == nil {
for rigName := range rigsConfig.Rigs {
rigPath := filepath.Join(townRoot, rigName)
if _, err := os.Stat(rigPath); err == nil && !seen[rigPath] {
rigDirs = append(rigDirs, rigPath)
seen[rigPath] = true
}
}
}
// Source 2: routes.jsonl (for rigs that may not be in registry)
townBeadsDir := filepath.Join(townRoot, ".beads")
if routes, err := beads.LoadRoutes(townBeadsDir); err == nil {
for _, route := range routes {
if route.Path == "." || route.Path == "" {
continue // Skip town root
}
// Extract rig name (first path component)
parts := strings.Split(route.Path, "/")
if len(parts) > 0 && parts[0] != "" {
rigPath := filepath.Join(townRoot, parts[0])
if _, err := os.Stat(rigPath); err == nil && !seen[rigPath] {
rigDirs = append(rigDirs, rigPath)
seen[rigPath] = true
}
}
}
}
// Source 3: Look for directories with .beads subdirs (for unregistered rigs)
entries, err := os.ReadDir(townRoot)
if err == nil {
for _, entry := range entries {
if !entry.IsDir() {
continue
}
// Skip known non-rig directories
if entry.Name() == "mayor" || entry.Name() == ".beads" || entry.Name() == ".git" {
continue
}
rigPath := filepath.Join(townRoot, entry.Name())
beadsDir := filepath.Join(rigPath, ".beads")
if _, err := os.Stat(beadsDir); err == nil && !seen[rigPath] {
rigDirs = append(rigDirs, rigPath)
seen[rigPath] = true
}
}
}
return rigDirs
}

View File

@@ -0,0 +1,206 @@
package doctor
import (
"os"
"path/filepath"
"testing"
)
func TestRigRoutesJSONLCheck_Run(t *testing.T) {
t.Run("no rigs returns OK", func(t *testing.T) {
tmpDir := t.TempDir()
// Create minimal town structure
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
check := NewRigRoutesJSONLCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK, got %v: %s", result.Status, result.Message)
}
})
t.Run("rig without routes.jsonl returns OK", func(t *testing.T) {
tmpDir := t.TempDir()
// Create rig with .beads but no routes.jsonl
rigBeads := filepath.Join(tmpDir, "myrig", ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatal(err)
}
check := NewRigRoutesJSONLCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK, got %v: %s", result.Status, result.Message)
}
})
t.Run("rig with routes.jsonl warns", func(t *testing.T) {
tmpDir := t.TempDir()
rigBeads := filepath.Join(tmpDir, "myrig", ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl (any content - will be deleted)
if err := os.WriteFile(filepath.Join(rigBeads, "routes.jsonl"), []byte(`{"prefix":"x-","path":"."}`+"\n"), 0644); err != nil {
t.Fatal(err)
}
check := NewRigRoutesJSONLCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Errorf("expected StatusWarning, got %v: %s", result.Status, result.Message)
}
if len(result.Details) == 0 {
t.Error("expected details about the issue")
}
})
t.Run("multiple rigs with routes.jsonl reports all", func(t *testing.T) {
tmpDir := t.TempDir()
// Create two rigs with routes.jsonl
for _, rigName := range []string{"rig1", "rig2"} {
rigBeads := filepath.Join(tmpDir, rigName, ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(rigBeads, "routes.jsonl"), []byte(`{"prefix":"x-","path":"."}`+"\n"), 0644); err != nil {
t.Fatal(err)
}
}
check := NewRigRoutesJSONLCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Errorf("expected StatusWarning, got %v", result.Status)
}
if len(result.Details) != 2 {
t.Errorf("expected 2 details, got %d: %v", len(result.Details), result.Details)
}
})
}
func TestRigRoutesJSONLCheck_Fix(t *testing.T) {
t.Run("deletes routes.jsonl unconditionally", func(t *testing.T) {
tmpDir := t.TempDir()
rigBeads := filepath.Join(tmpDir, "myrig", ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl with any content
routesPath := filepath.Join(rigBeads, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte(`{"id":"test-abc123","title":"Test Issue"}`+"\n"), 0644); err != nil {
t.Fatal(err)
}
check := NewRigRoutesJSONLCheck()
ctx := &CheckContext{TownRoot: tmpDir}
// Run check first to populate affectedRigs
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Fatalf("expected StatusWarning, got %v", result.Status)
}
// Fix
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix() error: %v", err)
}
// Verify routes.jsonl is gone
if _, err := os.Stat(routesPath); !os.IsNotExist(err) {
t.Error("routes.jsonl should have been deleted")
}
})
t.Run("fix is idempotent", func(t *testing.T) {
tmpDir := t.TempDir()
rigBeads := filepath.Join(tmpDir, "myrig", ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatal(err)
}
check := NewRigRoutesJSONLCheck()
ctx := &CheckContext{TownRoot: tmpDir}
// First run - should pass (no routes.jsonl)
result := check.Run(ctx)
if result.Status != StatusOK {
t.Fatalf("expected StatusOK, got %v", result.Status)
}
// Fix should be no-op
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix() error on clean state: %v", err)
}
})
}
func TestRigRoutesJSONLCheck_FindRigDirectories(t *testing.T) {
t.Run("finds rigs from multiple sources", func(t *testing.T) {
tmpDir := t.TempDir()
// Create mayor directory
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
// Create town-level .beads with routes.jsonl
townBeads := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeads, 0755); err != nil {
t.Fatal(err)
}
routes := `{"prefix":"rig1-","path":"rig1/mayor/rig"}` + "\n"
if err := os.WriteFile(filepath.Join(townBeads, "routes.jsonl"), []byte(routes), 0644); err != nil {
t.Fatal(err)
}
// Create rig1 (from routes.jsonl)
if err := os.MkdirAll(filepath.Join(tmpDir, "rig1", ".beads"), 0755); err != nil {
t.Fatal(err)
}
// Create rig2 (unregistered but has .beads)
if err := os.MkdirAll(filepath.Join(tmpDir, "rig2", ".beads"), 0755); err != nil {
t.Fatal(err)
}
check := NewRigRoutesJSONLCheck()
rigs := check.findRigDirectories(tmpDir)
if len(rigs) != 2 {
t.Errorf("expected 2 rigs, got %d: %v", len(rigs), rigs)
}
})
t.Run("excludes mayor and .beads directories", func(t *testing.T) {
tmpDir := t.TempDir()
// Create directories that should be excluded
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor", ".beads"), 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Join(tmpDir, ".beads"), 0755); err != nil {
t.Fatal(err)
}
check := NewRigRoutesJSONLCheck()
rigs := check.findRigDirectories(tmpDir)
if len(rigs) != 0 {
t.Errorf("expected 0 rigs (mayor and .beads should be excluded), got %d: %v", len(rigs), rigs)
}
})
}

View File

@@ -4,6 +4,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/gastown/internal/beads"
"github.com/steveyegge/gastown/internal/config"
@@ -72,15 +73,32 @@ func (c *RoutesCheck) Run(ctx *CheckContext) *CheckResult {
routeByPath[r.Path] = r.Prefix
}
var details []string
var missingTownRoute bool
// Check town root route exists (hq- -> .)
if _, hasTownRoute := routeByPrefix["hq-"]; !hasTownRoute {
missingTownRoute = true
details = append(details, "Town root route (hq- -> .) is missing")
}
// Load rigs registry
rigsPath := filepath.Join(ctx.TownRoot, "mayor", "rigs.json")
rigsConfig, err := config.LoadRigsConfig(rigsPath)
if err != nil {
// No rigs config is fine - just check existing routes are valid
// No rigs config - check for missing town route and validate existing routes
if missingTownRoute {
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: "Town root route is missing",
Details: details,
FixHint: "Run 'gt doctor --fix' to add missing routes",
}
}
return c.checkRoutesValid(ctx, routes)
}
var details []string
var missingRigs []string
var invalidRoutes []string
@@ -137,22 +155,24 @@ func (c *RoutesCheck) Run(ctx *CheckContext) *CheckResult {
}
// Determine result
if len(missingRigs) > 0 || len(invalidRoutes) > 0 {
if missingTownRoute || len(missingRigs) > 0 || len(invalidRoutes) > 0 {
status := StatusWarning
message := ""
var messageParts []string
if len(missingRigs) > 0 && len(invalidRoutes) > 0 {
message = fmt.Sprintf("%d rig(s) missing routes, %d invalid route(s)", len(missingRigs), len(invalidRoutes))
} else if len(missingRigs) > 0 {
message = fmt.Sprintf("%d rig(s) missing routing entries", len(missingRigs))
} else {
message = fmt.Sprintf("%d invalid route(s) in routes.jsonl", len(invalidRoutes))
if missingTownRoute {
messageParts = append(messageParts, "town root route missing")
}
if len(missingRigs) > 0 {
messageParts = append(messageParts, fmt.Sprintf("%d rig(s) missing routes", len(missingRigs)))
}
if len(invalidRoutes) > 0 {
messageParts = append(messageParts, fmt.Sprintf("%d invalid route(s)", len(invalidRoutes)))
}
return &CheckResult{
Name: c.Name(),
Status: status,
Message: message,
Message: strings.Join(messageParts, ", "),
Details: details,
FixHint: "Run 'gt doctor --fix' to add missing routes",
}
@@ -220,16 +240,27 @@ func (c *RoutesCheck) Fix(ctx *CheckContext) error {
routeMap[r.Prefix] = true
}
// Ensure town root route exists (hq- -> .)
// This is normally created by gt install but may be missing if routes.jsonl was corrupted
modified := false
if !routeMap["hq-"] {
routes = append(routes, beads.Route{Prefix: "hq-", Path: "."})
routeMap["hq-"] = true
modified = true
}
// Load rigs registry
rigsPath := filepath.Join(ctx.TownRoot, "mayor", "rigs.json")
rigsConfig, err := config.LoadRigsConfig(rigsPath)
if err != nil {
// No rigs config, nothing to fix
// No rigs config - just write town root route if we added it
if modified {
return beads.WriteRoutes(beadsDir, routes)
}
return nil
}
// Add missing routes for each rig
modified := false
for rigName, rigEntry := range rigsConfig.Rigs {
prefix := ""
if rigEntry.BeadsConfig != nil && rigEntry.BeadsConfig.Prefix != "" {

View File

@@ -0,0 +1,304 @@
package doctor
import (
"os"
"path/filepath"
"testing"
)
func TestRoutesCheck_MissingTownRoute(t *testing.T) {
t.Run("detects missing town root route", func(t *testing.T) {
tmpDir := t.TempDir()
// Create .beads directory with routes.jsonl missing the hq- route
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl with only a rig route (no hq- route)
routesPath := filepath.Join(beadsDir, "routes.jsonl")
routesContent := `{"prefix": "gt-", "path": "gastown/mayor/rig"}
`
if err := os.WriteFile(routesPath, []byte(routesContent), 0644); err != nil {
t.Fatal(err)
}
// Create mayor directory
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
check := NewRoutesCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Errorf("expected StatusWarning, got %v: %s", result.Status, result.Message)
}
// When no rigs.json exists, the message comes from the early return path
if result.Message != "Town root route is missing" {
t.Errorf("expected 'Town root route is missing', got %s", result.Message)
}
})
t.Run("passes when town root route exists", func(t *testing.T) {
tmpDir := t.TempDir()
// Create .beads directory with valid routes.jsonl
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl with hq- route
routesPath := filepath.Join(beadsDir, "routes.jsonl")
routesContent := `{"prefix": "hq-", "path": "."}
`
if err := os.WriteFile(routesPath, []byte(routesContent), 0644); err != nil {
t.Fatal(err)
}
// Create mayor directory
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
check := NewRoutesCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK, got %v: %s", result.Status, result.Message)
}
})
}
func TestRoutesCheck_FixRestoresTownRoute(t *testing.T) {
t.Run("fix adds missing town root route", func(t *testing.T) {
tmpDir := t.TempDir()
// Create .beads directory with empty routes.jsonl
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
// Create empty routes.jsonl
routesPath := filepath.Join(beadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte(""), 0644); err != nil {
t.Fatal(err)
}
// Create mayor directory (no rigs.json needed for this test)
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
check := NewRoutesCheck()
ctx := &CheckContext{TownRoot: tmpDir}
// Run fix
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify routes.jsonl now contains hq- route
content, err := os.ReadFile(routesPath)
if err != nil {
t.Fatalf("Failed to read routes.jsonl: %v", err)
}
if len(content) == 0 {
t.Error("routes.jsonl is still empty after fix")
}
contentStr := string(content)
if contentStr != `{"prefix":"hq-","path":"."}
` {
t.Errorf("unexpected routes.jsonl content: %s", contentStr)
}
// Verify the check now passes
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK after fix, got %v: %s", result.Status, result.Message)
}
})
t.Run("fix preserves existing routes while adding town route", func(t *testing.T) {
tmpDir := t.TempDir()
// Create .beads directory
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
// Create rig directory structure for route validation
rigPath := filepath.Join(tmpDir, "myrig", "mayor", "rig", ".beads")
if err := os.MkdirAll(rigPath, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl with only a rig route (no hq- route)
routesPath := filepath.Join(beadsDir, "routes.jsonl")
routesContent := `{"prefix": "my-", "path": "myrig/mayor/rig"}
`
if err := os.WriteFile(routesPath, []byte(routesContent), 0644); err != nil {
t.Fatal(err)
}
// Create mayor directory
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
check := NewRoutesCheck()
ctx := &CheckContext{TownRoot: tmpDir}
// Run fix
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify routes.jsonl now contains both routes
content, err := os.ReadFile(routesPath)
if err != nil {
t.Fatalf("Failed to read routes.jsonl: %v", err)
}
contentStr := string(content)
// Should have both the original rig route and the new hq- route
if contentStr != `{"prefix":"my-","path":"myrig/mayor/rig"}
{"prefix":"hq-","path":"."}
` {
t.Errorf("unexpected routes.jsonl content: %s", contentStr)
}
})
t.Run("fix does not duplicate existing town route", func(t *testing.T) {
tmpDir := t.TempDir()
// Create .beads directory with valid routes.jsonl
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl with hq- route already present
routesPath := filepath.Join(beadsDir, "routes.jsonl")
originalContent := `{"prefix": "hq-", "path": "."}
`
if err := os.WriteFile(routesPath, []byte(originalContent), 0644); err != nil {
t.Fatal(err)
}
// Create mayor directory
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
check := NewRoutesCheck()
ctx := &CheckContext{TownRoot: tmpDir}
// Run fix (should be a no-op)
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify routes.jsonl is unchanged (no duplicate)
content, err := os.ReadFile(routesPath)
if err != nil {
t.Fatalf("Failed to read routes.jsonl: %v", err)
}
// File should be unchanged - fix doesn't write when no modifications needed
if string(content) != originalContent {
t.Errorf("routes.jsonl was modified when it shouldn't have been: %s", string(content))
}
})
}
func TestRoutesCheck_CorruptedRoutesJsonl(t *testing.T) {
t.Run("corrupted routes.jsonl results in empty routes", func(t *testing.T) {
tmpDir := t.TempDir()
// Create .beads directory with corrupted routes.jsonl
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
// Create corrupted routes.jsonl (malformed lines are skipped by LoadRoutes)
routesPath := filepath.Join(beadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte("not valid json"), 0644); err != nil {
t.Fatal(err)
}
// Create mayor directory
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
check := NewRoutesCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
// Corrupted/malformed lines are skipped, resulting in empty routes
// This triggers the "Town root route is missing" warning
if result.Status != StatusWarning {
t.Errorf("expected StatusWarning, got %v: %s", result.Status, result.Message)
}
if result.Message != "Town root route is missing" {
t.Errorf("expected 'Town root route is missing', got %s", result.Message)
}
})
t.Run("fix regenerates corrupted routes.jsonl with town route", func(t *testing.T) {
tmpDir := t.TempDir()
// Create .beads directory with corrupted routes.jsonl
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
// Create corrupted routes.jsonl
routesPath := filepath.Join(beadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte("not valid json"), 0644); err != nil {
t.Fatal(err)
}
// Create mayor directory
if err := os.MkdirAll(filepath.Join(tmpDir, "mayor"), 0755); err != nil {
t.Fatal(err)
}
check := NewRoutesCheck()
ctx := &CheckContext{TownRoot: tmpDir}
// Run fix
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify routes.jsonl now contains hq- route
content, err := os.ReadFile(routesPath)
if err != nil {
t.Fatalf("Failed to read routes.jsonl: %v", err)
}
contentStr := string(content)
if contentStr != `{"prefix":"hq-","path":"."}
` {
t.Errorf("unexpected routes.jsonl content after fix: %s", contentStr)
}
// Verify the check now passes
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK after fix, got %v: %s", result.Status, result.Message)
}
})
}

View File

@@ -635,19 +635,21 @@ func (m *Manager) initBeads(rigPath, prefix string) error {
// Ignore errors - fingerprint is optional for functionality
_, _ = migrateCmd.CombinedOutput()
// Add route from rig beads to town beads for cross-database resolution.
// This allows rig beads to resolve hq-* prefixed beads (role beads, etc.)
// that are stored in town beads.
townRoute := beads.Route{Prefix: "hq-", Path: ".."}
if err := beads.AppendRouteToDir(beadsDir, townRoute); err != nil {
// Non-fatal: role slot set will fail but agent beads still work
fmt.Printf(" ⚠ Could not add route to town beads: %v\n", err)
// Ensure issues.jsonl exists to prevent bd auto-export from corrupting other files.
// bd init creates beads.db but not issues.jsonl in SQLite mode.
// Without issues.jsonl, bd's auto-export might write issues to other .jsonl files.
issuesJSONL := filepath.Join(beadsDir, "issues.jsonl")
if _, err := os.Stat(issuesJSONL); os.IsNotExist(err) {
if err := os.WriteFile(issuesJSONL, []byte{}, 0644); err != nil {
// Non-fatal but log it
fmt.Printf(" ⚠ Could not create issues.jsonl: %v\n", err)
}
}
typesCmd := exec.Command("bd", "config", "set", "types.custom", constants.BeadsCustomTypes)
typesCmd.Dir = rigPath
typesCmd.Env = filteredEnv
_, _ = typesCmd.CombinedOutput()
// NOTE: We intentionally do NOT create routes.jsonl in rig beads.
// bd's routing walks up to find town root (via mayor/town.json) and uses
// town-level routes.jsonl for prefix-based routing. Rig-level routes.jsonl
// would prevent this walk-up and break cross-rig routing.
return nil
}