Files
gastown/internal/doctor/routes_check.go
Julian Knutsen 043a6abc59 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>
2026-01-12 01:45:26 -08:00

291 lines
8.0 KiB
Go

package doctor
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/gastown/internal/beads"
"github.com/steveyegge/gastown/internal/config"
)
// RoutesCheck verifies that beads routing is properly configured.
// It checks that routes.jsonl exists, all rigs have routing entries,
// and all routes point to valid locations.
type RoutesCheck struct {
FixableCheck
}
// NewRoutesCheck creates a new routes configuration check.
func NewRoutesCheck() *RoutesCheck {
return &RoutesCheck{
FixableCheck: FixableCheck{
BaseCheck: BaseCheck{
CheckName: "routes-config",
CheckDescription: "Check beads routing configuration",
CheckCategory: CategoryConfig,
},
},
}
}
// Run checks the beads routing configuration.
func (c *RoutesCheck) Run(ctx *CheckContext) *CheckResult {
beadsDir := filepath.Join(ctx.TownRoot, ".beads")
routesPath := filepath.Join(beadsDir, beads.RoutesFileName)
// Check if .beads directory exists
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: "No .beads directory at town root",
FixHint: "Run 'bd init' to initialize beads",
}
}
// Check if routes.jsonl exists
if _, err := os.Stat(routesPath); os.IsNotExist(err) {
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: "No routes.jsonl file (prefix routing not configured)",
FixHint: "Run 'gt doctor --fix' to create routes.jsonl",
}
}
// Load existing routes
routes, err := beads.LoadRoutes(beadsDir)
if err != nil {
return &CheckResult{
Name: c.Name(),
Status: StatusError,
Message: fmt.Sprintf("Failed to load routes.jsonl: %v", err),
}
}
// Build maps of existing routes
routeByPrefix := make(map[string]string) // prefix -> path
routeByPath := make(map[string]string) // path -> prefix
for _, r := range routes {
routeByPrefix[r.Prefix] = r.Path
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 - 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 missingRigs []string
var invalidRoutes []string
// Check each rig has a route (by path, not just prefix from rigs.json)
for rigName, rigEntry := range rigsConfig.Rigs {
expectedPath := rigName + "/mayor/rig"
// Check if there's already a route for this rig (by path)
if _, hasRoute := routeByPath[expectedPath]; hasRoute {
// Rig already has a route, even if prefix differs from rigs.json
continue
}
// No route by path - check by prefix from rigs.json
prefix := ""
if rigEntry.BeadsConfig != nil && rigEntry.BeadsConfig.Prefix != "" {
prefix = rigEntry.BeadsConfig.Prefix + "-"
}
if prefix != "" {
if _, found := routeByPrefix[prefix]; !found {
missingRigs = append(missingRigs, rigName)
details = append(details, fmt.Sprintf("Rig '%s' (prefix: %s) has no routing entry", rigName, prefix))
}
}
}
// Check each route points to a valid location
for _, r := range routes {
rigPath := filepath.Join(ctx.TownRoot, r.Path)
beadsPath := filepath.Join(rigPath, ".beads")
// Special case: "." path is town root, already checked
if r.Path == "." {
continue
}
// Check if the path exists
if _, err := os.Stat(rigPath); os.IsNotExist(err) {
invalidRoutes = append(invalidRoutes, r.Prefix)
details = append(details, fmt.Sprintf("Route %s -> %s: path does not exist", r.Prefix, r.Path))
continue
}
// Check if .beads directory exists (or redirect file)
redirectPath := filepath.Join(beadsPath, "redirect")
_, beadsErr := os.Stat(beadsPath)
_, redirectErr := os.Stat(redirectPath)
if os.IsNotExist(beadsErr) && os.IsNotExist(redirectErr) {
invalidRoutes = append(invalidRoutes, r.Prefix)
details = append(details, fmt.Sprintf("Route %s -> %s: no .beads directory", r.Prefix, r.Path))
}
}
// Determine result
if missingTownRoute || len(missingRigs) > 0 || len(invalidRoutes) > 0 {
status := StatusWarning
var messageParts []string
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: strings.Join(messageParts, ", "),
Details: details,
FixHint: "Run 'gt doctor --fix' to add missing routes",
}
}
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: fmt.Sprintf("Routes configured correctly (%d routes)", len(routes)),
}
}
// checkRoutesValid checks that existing routes point to valid locations.
func (c *RoutesCheck) checkRoutesValid(ctx *CheckContext, routes []beads.Route) *CheckResult {
var details []string
var invalidCount int
for _, r := range routes {
if r.Path == "." {
continue // Town root is valid
}
rigPath := filepath.Join(ctx.TownRoot, r.Path)
if _, err := os.Stat(rigPath); os.IsNotExist(err) {
invalidCount++
details = append(details, fmt.Sprintf("Route %s -> %s: path does not exist", r.Prefix, r.Path))
}
}
if invalidCount > 0 {
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: fmt.Sprintf("%d invalid route(s) in routes.jsonl", invalidCount),
Details: details,
FixHint: "Remove invalid routes or recreate the missing rigs",
}
}
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: fmt.Sprintf("Routes configured correctly (%d routes)", len(routes)),
}
}
// Fix attempts to add missing routing entries.
func (c *RoutesCheck) Fix(ctx *CheckContext) error {
beadsDir := filepath.Join(ctx.TownRoot, ".beads")
// Ensure .beads directory exists
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
return fmt.Errorf(".beads directory does not exist; run 'bd init' first")
}
// Load existing routes
routes, err := beads.LoadRoutes(beadsDir)
if err != nil {
routes = []beads.Route{} // Start fresh if can't load
}
// Build map of existing prefixes
routeMap := make(map[string]bool)
for _, r := range routes {
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 - just write town root route if we added it
if modified {
return beads.WriteRoutes(beadsDir, routes)
}
return nil
}
// Add missing routes for each rig
for rigName, rigEntry := range rigsConfig.Rigs {
prefix := ""
if rigEntry.BeadsConfig != nil && rigEntry.BeadsConfig.Prefix != "" {
prefix = rigEntry.BeadsConfig.Prefix + "-"
}
if prefix != "" && !routeMap[prefix] {
// Verify the rig path exists before adding
rigPath := filepath.Join(ctx.TownRoot, rigName, "mayor", "rig")
if _, err := os.Stat(rigPath); err == nil {
route := beads.Route{
Prefix: prefix,
Path: rigName + "/mayor/rig",
}
routes = append(routes, route)
routeMap[prefix] = true
modified = true
}
}
}
if modified {
return beads.WriteRoutes(beadsDir, routes)
}
return nil
}