Merge origin/main into fix/205-address-claude-startup-issues

Resolved conflict in internal/witness/manager.go:
- Kept session import (used by PR code)
- Kept PR's more accurate comment for PID check
- Removed duplicate sessionName method introduced by merge
This commit is contained in:
gastown/crew/joe
2026-01-06 19:04:29 -08:00
committed by Steve Yegge
59 changed files with 7161 additions and 725 deletions
+208
View File
@@ -2,6 +2,7 @@ package doctor
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
@@ -225,3 +226,210 @@ func (c *PrefixConflictCheck) Run(ctx *CheckContext) *CheckResult {
FixHint: "Use 'bd rename-prefix <new-prefix>' in one of the conflicting rigs to resolve",
}
}
// PrefixMismatchCheck detects when rigs.json has a different prefix than what
// routes.jsonl actually uses for a rig. This can happen when:
// - deriveBeadsPrefix() generates a different prefix than what's in the beads DB
// - Someone manually edited rigs.json with the wrong prefix
// - The beads were initialized before auto-derive existed with a different prefix
type PrefixMismatchCheck struct {
FixableCheck
}
// NewPrefixMismatchCheck creates a new prefix mismatch check.
func NewPrefixMismatchCheck() *PrefixMismatchCheck {
return &PrefixMismatchCheck{
FixableCheck: FixableCheck{
BaseCheck: BaseCheck{
CheckName: "prefix-mismatch",
CheckDescription: "Check for prefix mismatches between rigs.json and routes.jsonl",
},
},
}
}
// Run checks for prefix mismatches between rigs.json and routes.jsonl.
func (c *PrefixMismatchCheck) Run(ctx *CheckContext) *CheckResult {
beadsDir := filepath.Join(ctx.TownRoot, ".beads")
// Load routes.jsonl
routes, err := beads.LoadRoutes(beadsDir)
if err != nil {
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: fmt.Sprintf("Could not load routes.jsonl: %v", err),
}
}
if len(routes) == 0 {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "No routes configured (nothing to check)",
}
}
// Load rigs.json
rigsPath := filepath.Join(ctx.TownRoot, "mayor", "rigs.json")
rigsConfig, err := loadRigsConfig(rigsPath)
if err != nil {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "No rigs.json found (nothing to check)",
}
}
// Build map of route path -> prefix from routes.jsonl
routePrefixByPath := make(map[string]string)
for _, r := range routes {
// Normalize: strip trailing hyphen from prefix for comparison
prefix := strings.TrimSuffix(r.Prefix, "-")
routePrefixByPath[r.Path] = prefix
}
// Check each rig in rigs.json against routes.jsonl
var mismatches []string
mismatchData := make(map[string][2]string) // rigName -> [rigsJsonPrefix, routesPrefix]
for rigName, rigEntry := range rigsConfig.Rigs {
// Skip rigs without beads config
if rigEntry.BeadsConfig == nil || rigEntry.BeadsConfig.Prefix == "" {
continue
}
rigsJsonPrefix := rigEntry.BeadsConfig.Prefix
expectedPath := rigName + "/mayor/rig"
// Find the route for this rig
routePrefix, hasRoute := routePrefixByPath[expectedPath]
if !hasRoute {
// No route for this rig - routes-config check handles this
continue
}
// Compare prefixes (both should be without trailing hyphen)
if rigsJsonPrefix != routePrefix {
mismatches = append(mismatches, rigName)
mismatchData[rigName] = [2]string{rigsJsonPrefix, routePrefix}
}
}
if len(mismatches) == 0 {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "No prefix mismatches found",
}
}
// Build details
var details []string
for _, rigName := range mismatches {
data := mismatchData[rigName]
details = append(details, fmt.Sprintf("Rig '%s': rigs.json says '%s', routes.jsonl uses '%s'",
rigName, data[0], data[1]))
}
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: fmt.Sprintf("%d prefix mismatch(es) between rigs.json and routes.jsonl", len(mismatches)),
Details: details,
FixHint: "Run 'gt doctor --fix' to update rigs.json with correct prefixes",
}
}
// Fix updates rigs.json to match the prefixes in routes.jsonl.
func (c *PrefixMismatchCheck) Fix(ctx *CheckContext) error {
beadsDir := filepath.Join(ctx.TownRoot, ".beads")
// Load routes.jsonl
routes, err := beads.LoadRoutes(beadsDir)
if err != nil || len(routes) == 0 {
return nil // Nothing to fix
}
// Load rigs.json
rigsPath := filepath.Join(ctx.TownRoot, "mayor", "rigs.json")
rigsConfig, err := loadRigsConfig(rigsPath)
if err != nil {
return nil // Nothing to fix
}
// Build map of route path -> prefix from routes.jsonl
routePrefixByPath := make(map[string]string)
for _, r := range routes {
prefix := strings.TrimSuffix(r.Prefix, "-")
routePrefixByPath[r.Path] = prefix
}
// Update each rig's prefix to match routes.jsonl
modified := false
for rigName, rigEntry := range rigsConfig.Rigs {
expectedPath := rigName + "/mayor/rig"
routePrefix, hasRoute := routePrefixByPath[expectedPath]
if !hasRoute {
continue
}
// Ensure BeadsConfig exists
if rigEntry.BeadsConfig == nil {
rigEntry.BeadsConfig = &rigsConfigBeadsConfig{}
}
if rigEntry.BeadsConfig.Prefix != routePrefix {
rigEntry.BeadsConfig.Prefix = routePrefix
rigsConfig.Rigs[rigName] = rigEntry
modified = true
}
}
if modified {
return saveRigsConfig(rigsPath, rigsConfig)
}
return nil
}
// rigsConfigEntry is a local type for loading rigs.json without importing config package
// to avoid circular dependencies and keep the check self-contained.
type rigsConfigEntry struct {
GitURL string `json:"git_url"`
LocalRepo string `json:"local_repo,omitempty"`
AddedAt string `json:"added_at"` // Keep as string to preserve format
BeadsConfig *rigsConfigBeadsConfig `json:"beads,omitempty"`
}
type rigsConfigBeadsConfig struct {
Repo string `json:"repo"`
Prefix string `json:"prefix"`
}
type rigsConfigFile struct {
Version int `json:"version"`
Rigs map[string]rigsConfigEntry `json:"rigs"`
}
func loadRigsConfig(path string) (*rigsConfigFile, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var cfg rigsConfigFile
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, err
}
return &cfg, nil
}
func saveRigsConfig(path string, cfg *rigsConfigFile) error {
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0644)
}
+216
View File
@@ -99,3 +99,219 @@ func TestBeadsDatabaseCheck_PopulatedDatabase(t *testing.T) {
t.Errorf("expected StatusOK for populated db, got %v", result.Status)
}
}
func TestNewPrefixMismatchCheck(t *testing.T) {
check := NewPrefixMismatchCheck()
if check.Name() != "prefix-mismatch" {
t.Errorf("expected name 'prefix-mismatch', got %q", check.Name())
}
if !check.CanFix() {
t.Error("expected CanFix to return true")
}
}
func TestPrefixMismatchCheck_NoRoutes(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
check := NewPrefixMismatchCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK for no routes, got %v", result.Status)
}
}
func TestPrefixMismatchCheck_NoRigsJson(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl
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)
}
check := NewPrefixMismatchCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK when no rigs.json, got %v", result.Status)
}
}
func TestPrefixMismatchCheck_Matching(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(mayorDir, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl with gt- prefix
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 rigs.json with matching gt prefix
rigsPath := filepath.Join(mayorDir, "rigs.json")
rigsContent := `{
"version": 1,
"rigs": {
"gastown": {
"git_url": "https://github.com/example/gastown",
"beads": {
"prefix": "gt"
}
}
}
}`
if err := os.WriteFile(rigsPath, []byte(rigsContent), 0644); err != nil {
t.Fatal(err)
}
check := NewPrefixMismatchCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK for matching prefixes, got %v: %s", result.Status, result.Message)
}
}
func TestPrefixMismatchCheck_Mismatch(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(mayorDir, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl with gt- prefix
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 rigs.json with WRONG prefix (ga instead of gt)
rigsPath := filepath.Join(mayorDir, "rigs.json")
rigsContent := `{
"version": 1,
"rigs": {
"gastown": {
"git_url": "https://github.com/example/gastown",
"beads": {
"prefix": "ga"
}
}
}
}`
if err := os.WriteFile(rigsPath, []byte(rigsContent), 0644); err != nil {
t.Fatal(err)
}
check := NewPrefixMismatchCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Errorf("expected StatusWarning for prefix mismatch, got %v: %s", result.Status, result.Message)
}
if len(result.Details) != 1 {
t.Errorf("expected 1 detail, got %d", len(result.Details))
}
}
func TestPrefixMismatchCheck_Fix(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(beadsDir, 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(mayorDir, 0755); err != nil {
t.Fatal(err)
}
// Create routes.jsonl with gt- prefix
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 rigs.json with WRONG prefix (ga instead of gt)
rigsPath := filepath.Join(mayorDir, "rigs.json")
rigsContent := `{
"version": 1,
"rigs": {
"gastown": {
"git_url": "https://github.com/example/gastown",
"beads": {
"prefix": "ga"
}
}
}
}`
if err := os.WriteFile(rigsPath, []byte(rigsContent), 0644); err != nil {
t.Fatal(err)
}
check := NewPrefixMismatchCheck()
ctx := &CheckContext{TownRoot: tmpDir}
// First verify there's a mismatch
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Fatalf("expected mismatch before fix, got %v", result.Status)
}
// Fix it
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix() failed: %v", err)
}
// Verify it's now fixed
result = check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK after fix, got %v: %s", result.Status, result.Message)
}
// Verify rigs.json was updated
data, err := os.ReadFile(rigsPath)
if err != nil {
t.Fatal(err)
}
cfg, err := loadRigsConfig(rigsPath)
if err != nil {
t.Fatalf("failed to load fixed rigs.json: %v (content: %s)", err, data)
}
if cfg.Rigs["gastown"].BeadsConfig.Prefix != "gt" {
t.Errorf("expected prefix 'gt' after fix, got %q", cfg.Rigs["gastown"].BeadsConfig.Prefix)
}
}
+27 -38
View File
@@ -145,34 +145,36 @@ func getPatrolMoleculeDesc(title string) string {
// PatrolHooksWiredCheck verifies that hooks trigger patrol execution.
type PatrolHooksWiredCheck struct {
BaseCheck
FixableCheck
}
// NewPatrolHooksWiredCheck creates a new patrol hooks wired check.
func NewPatrolHooksWiredCheck() *PatrolHooksWiredCheck {
return &PatrolHooksWiredCheck{
BaseCheck: BaseCheck{
CheckName: "patrol-hooks-wired",
CheckDescription: "Check if hooks trigger patrol execution",
FixableCheck: FixableCheck{
BaseCheck: BaseCheck{
CheckName: "patrol-hooks-wired",
CheckDescription: "Check if hooks trigger patrol execution",
},
},
}
}
// Run checks if patrol hooks are wired.
func (c *PatrolHooksWiredCheck) Run(ctx *CheckContext) *CheckResult {
// Check for daemon config which manages patrols
daemonConfigPath := filepath.Join(ctx.TownRoot, "mayor", "daemon.json")
daemonConfigPath := config.DaemonPatrolConfigPath(ctx.TownRoot)
relPath, _ := filepath.Rel(ctx.TownRoot, daemonConfigPath)
if _, err := os.Stat(daemonConfigPath); os.IsNotExist(err) {
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: "Daemon config not found",
FixHint: "Run 'gt daemon start' to start the daemon",
Message: fmt.Sprintf("%s not found", relPath),
FixHint: "Run 'gt doctor --fix' to create default config, or 'gt daemon start' to start the daemon",
}
}
// Check daemon config for patrol configuration
data, err := os.ReadFile(daemonConfigPath)
cfg, err := config.LoadDaemonPatrolConfig(daemonConfigPath)
if err != nil {
return &CheckResult{
Name: c.Name(),
@@ -182,48 +184,35 @@ func (c *PatrolHooksWiredCheck) Run(ctx *CheckContext) *CheckResult {
}
}
var config map[string]interface{}
if err := json.Unmarshal(data, &config); err != nil {
if len(cfg.Patrols) > 0 {
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: "Invalid daemon config format",
Details: []string{err.Error()},
Status: StatusOK,
Message: fmt.Sprintf("Daemon configured with %d patrol(s)", len(cfg.Patrols)),
}
}
// Check for patrol entries
if patrols, ok := config["patrols"]; ok {
if patrolMap, ok := patrols.(map[string]interface{}); ok && len(patrolMap) > 0 {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: fmt.Sprintf("Daemon configured with %d patrol(s)", len(patrolMap)),
}
}
}
// Check if heartbeat is enabled (triggers deacon patrol)
if heartbeat, ok := config["heartbeat"]; ok {
if hb, ok := heartbeat.(map[string]interface{}); ok {
if enabled, ok := hb["enabled"].(bool); ok && enabled {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "Daemon heartbeat enabled (triggers patrols)",
}
}
if cfg.Heartbeat != nil && cfg.Heartbeat.Enabled {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "Daemon heartbeat enabled (triggers patrols)",
}
}
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: "Patrol hooks not configured in daemon",
FixHint: "Configure patrols in mayor/daemon.json or run 'gt daemon start'",
Message: fmt.Sprintf("Configure patrols in %s or run 'gt daemon start'", relPath),
FixHint: "Run 'gt doctor --fix' to create default config",
}
}
// Fix creates the daemon patrol config with defaults.
func (c *PatrolHooksWiredCheck) Fix(ctx *CheckContext) error {
return config.EnsureDaemonPatrolConfig(ctx.TownRoot)
}
// PatrolNotStuckCheck detects wisps that have been in_progress too long.
type PatrolNotStuckCheck struct {
BaseCheck
+180
View File
@@ -359,3 +359,183 @@ func TestPatrolRolesHavePromptsCheck_EmptyRigsConfig(t *testing.T) {
t.Errorf("Message = %q, want 'No rigs configured'", result.Message)
}
}
func TestNewPatrolHooksWiredCheck(t *testing.T) {
check := NewPatrolHooksWiredCheck()
if check == nil {
t.Fatal("NewPatrolHooksWiredCheck() returned nil")
}
if check.Name() != "patrol-hooks-wired" {
t.Errorf("Name() = %q, want %q", check.Name(), "patrol-hooks-wired")
}
if !check.CanFix() {
t.Error("CanFix() should return true")
}
}
func TestPatrolHooksWiredCheck_NoDaemonConfig(t *testing.T) {
tmpDir := t.TempDir()
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(mayorDir, 0755); err != nil {
t.Fatalf("mkdir mayor: %v", err)
}
check := NewPatrolHooksWiredCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Errorf("Status = %v, want Warning", result.Status)
}
if result.FixHint == "" {
t.Error("FixHint should not be empty")
}
}
func TestPatrolHooksWiredCheck_ValidConfig(t *testing.T) {
tmpDir := t.TempDir()
cfg := config.NewDaemonPatrolConfig()
path := config.DaemonPatrolConfigPath(tmpDir)
if err := config.SaveDaemonPatrolConfig(path, cfg); err != nil {
t.Fatalf("SaveDaemonPatrolConfig: %v", err)
}
check := NewPatrolHooksWiredCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("Status = %v, want OK", result.Status)
}
}
func TestPatrolHooksWiredCheck_EmptyPatrols(t *testing.T) {
tmpDir := t.TempDir()
cfg := &config.DaemonPatrolConfig{
Type: "daemon-patrol-config",
Version: 1,
Patrols: map[string]config.PatrolConfig{},
}
path := config.DaemonPatrolConfigPath(tmpDir)
if err := config.SaveDaemonPatrolConfig(path, cfg); err != nil {
t.Fatalf("SaveDaemonPatrolConfig: %v", err)
}
check := NewPatrolHooksWiredCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Errorf("Status = %v, want Warning (no patrols configured)", result.Status)
}
}
func TestPatrolHooksWiredCheck_HeartbeatEnabled(t *testing.T) {
tmpDir := t.TempDir()
cfg := &config.DaemonPatrolConfig{
Type: "daemon-patrol-config",
Version: 1,
Heartbeat: &config.HeartbeatConfig{
Enabled: true,
Interval: "3m",
},
Patrols: map[string]config.PatrolConfig{},
}
path := config.DaemonPatrolConfigPath(tmpDir)
if err := config.SaveDaemonPatrolConfig(path, cfg); err != nil {
t.Fatalf("SaveDaemonPatrolConfig: %v", err)
}
check := NewPatrolHooksWiredCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("Status = %v, want OK (heartbeat enabled triggers patrols)", result.Status)
}
}
func TestPatrolHooksWiredCheck_Fix(t *testing.T) {
tmpDir := t.TempDir()
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(mayorDir, 0755); err != nil {
t.Fatalf("mkdir mayor: %v", err)
}
check := NewPatrolHooksWiredCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusWarning {
t.Fatalf("Initial Status = %v, want Warning", result.Status)
}
err := check.Fix(ctx)
if err != nil {
t.Fatalf("Fix() error = %v", err)
}
path := config.DaemonPatrolConfigPath(tmpDir)
loaded, err := config.LoadDaemonPatrolConfig(path)
if err != nil {
t.Fatalf("LoadDaemonPatrolConfig: %v", err)
}
if loaded.Type != "daemon-patrol-config" {
t.Errorf("Type = %q, want 'daemon-patrol-config'", loaded.Type)
}
if len(loaded.Patrols) != 3 {
t.Errorf("Patrols count = %d, want 3", len(loaded.Patrols))
}
result = check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("After Fix(), Status = %v, want OK", result.Status)
}
}
func TestPatrolHooksWiredCheck_FixPreservesExisting(t *testing.T) {
tmpDir := t.TempDir()
existing := &config.DaemonPatrolConfig{
Type: "daemon-patrol-config",
Version: 1,
Patrols: map[string]config.PatrolConfig{
"custom": {Enabled: true, Agent: "custom-agent"},
},
}
path := config.DaemonPatrolConfigPath(tmpDir)
if err := config.SaveDaemonPatrolConfig(path, existing); err != nil {
t.Fatalf("SaveDaemonPatrolConfig: %v", err)
}
check := NewPatrolHooksWiredCheck()
ctx := &CheckContext{TownRoot: tmpDir}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("Status = %v, want OK (has patrols)", result.Status)
}
err := check.Fix(ctx)
if err != nil {
t.Fatalf("Fix() error = %v", err)
}
loaded, err := config.LoadDaemonPatrolConfig(path)
if err != nil {
t.Fatalf("LoadDaemonPatrolConfig: %v", err)
}
if len(loaded.Patrols) != 1 {
t.Errorf("Patrols count = %d, want 1 (should preserve existing)", len(loaded.Patrols))
}
if _, ok := loaded.Patrols["custom"]; !ok {
t.Error("existing custom patrol was overwritten")
}
}
+211
View File
@@ -7,6 +7,8 @@ import (
"os/exec"
"path/filepath"
"strings"
"github.com/steveyegge/gastown/internal/config"
)
// RigIsGitRepoCheck verifies the rig has a valid mayor/rig git clone.
@@ -865,6 +867,214 @@ func (c *BeadsConfigValidCheck) Fix(ctx *CheckContext) error {
return nil
}
// BeadsRedirectCheck verifies that rig-level beads redirect exists for tracked beads.
// When a repo has .beads/ tracked in git (at mayor/rig/.beads), the rig root needs
// a redirect file pointing to that location.
type BeadsRedirectCheck struct {
FixableCheck
}
// NewBeadsRedirectCheck creates a new beads redirect check.
func NewBeadsRedirectCheck() *BeadsRedirectCheck {
return &BeadsRedirectCheck{
FixableCheck: FixableCheck{
BaseCheck: BaseCheck{
CheckName: "beads-redirect",
CheckDescription: "Verify rig-level beads redirect for tracked beads",
},
},
}
}
// Run checks if the rig-level beads redirect exists when needed.
func (c *BeadsRedirectCheck) Run(ctx *CheckContext) *CheckResult {
// Only applies when checking a specific rig
if ctx.RigName == "" {
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "No rig specified (skipping redirect check)",
}
}
rigPath := ctx.RigPath()
mayorRigBeads := filepath.Join(rigPath, "mayor", "rig", ".beads")
rigBeadsDir := filepath.Join(rigPath, ".beads")
redirectPath := filepath.Join(rigBeadsDir, "redirect")
// Check if this rig has tracked beads (mayor/rig/.beads exists)
if _, err := os.Stat(mayorRigBeads); os.IsNotExist(err) {
// No tracked beads - check if rig/.beads exists (local beads)
if _, err := os.Stat(rigBeadsDir); os.IsNotExist(err) {
return &CheckResult{
Name: c.Name(),
Status: StatusError,
Message: "No .beads directory found at rig root",
Details: []string{
"Beads database not initialized for this rig",
"This prevents issue tracking for this rig",
},
FixHint: "Run 'gt doctor --fix --rig " + ctx.RigName + "' to initialize beads",
}
}
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "Rig uses local beads (no redirect needed)",
}
}
// Tracked beads exist - check for conflicting local beads
hasLocalData := hasBeadsData(rigBeadsDir)
redirectExists := false
if _, err := os.Stat(redirectPath); err == nil {
redirectExists = true
}
// Case: Local beads directory has actual data (not just redirect)
if hasLocalData && !redirectExists {
return &CheckResult{
Name: c.Name(),
Status: StatusError,
Message: "Conflicting local beads found with tracked beads",
Details: []string{
"Tracked beads exist at: mayor/rig/.beads",
"Local beads with data exist at: .beads/",
"Fix will remove local beads and create redirect to tracked beads",
},
FixHint: "Run 'gt doctor --fix --rig " + ctx.RigName + "' to fix",
}
}
// Case: No redirect file (but no conflicting data)
if !redirectExists {
return &CheckResult{
Name: c.Name(),
Status: StatusError,
Message: "Missing rig-level beads redirect for tracked beads",
Details: []string{
"Tracked beads exist at: mayor/rig/.beads",
"Missing redirect at: .beads/redirect",
"Without this redirect, bd commands from rig root won't find beads",
},
FixHint: "Run 'gt doctor --fix' to create the redirect",
}
}
// Verify redirect points to correct location
content, err := os.ReadFile(redirectPath)
if err != nil {
return &CheckResult{
Name: c.Name(),
Status: StatusWarning,
Message: fmt.Sprintf("Could not read redirect file: %v", err),
}
}
target := strings.TrimSpace(string(content))
if target != "mayor/rig/.beads" {
return &CheckResult{
Name: c.Name(),
Status: StatusError,
Message: fmt.Sprintf("Redirect points to %q, expected mayor/rig/.beads", target),
FixHint: "Run 'gt doctor --fix --rig " + ctx.RigName + "' to correct the redirect",
}
}
return &CheckResult{
Name: c.Name(),
Status: StatusOK,
Message: "Rig-level beads redirect is correctly configured",
}
}
// Fix creates or corrects the rig-level beads redirect, or initializes beads if missing.
func (c *BeadsRedirectCheck) Fix(ctx *CheckContext) error {
if ctx.RigName == "" {
return nil
}
rigPath := ctx.RigPath()
mayorRigBeads := filepath.Join(rigPath, "mayor", "rig", ".beads")
rigBeadsDir := filepath.Join(rigPath, ".beads")
redirectPath := filepath.Join(rigBeadsDir, "redirect")
// Check if tracked beads exist
hasTrackedBeads := true
if _, err := os.Stat(mayorRigBeads); os.IsNotExist(err) {
hasTrackedBeads = false
}
// Check if local beads exist
hasLocalBeads := true
if _, err := os.Stat(rigBeadsDir); os.IsNotExist(err) {
hasLocalBeads = false
}
// Case 1: No beads at all - initialize with bd init
if !hasTrackedBeads && !hasLocalBeads {
// Get the rig's beads prefix from rigs.json (falls back to "gt" if not found)
prefix := config.GetRigPrefix(ctx.TownRoot, ctx.RigName)
// Create .beads directory
if err := os.MkdirAll(rigBeadsDir, 0755); err != nil {
return fmt.Errorf("creating .beads directory: %w", err)
}
// Run bd init with the configured prefix
cmd := exec.Command("bd", "init", "--prefix", prefix)
cmd.Dir = rigPath
if output, err := cmd.CombinedOutput(); err != nil {
// bd might not be installed - create minimal config.yaml
configPath := filepath.Join(rigBeadsDir, "config.yaml")
configContent := fmt.Sprintf("prefix: %s\n", prefix)
if writeErr := os.WriteFile(configPath, []byte(configContent), 0644); writeErr != nil {
return fmt.Errorf("bd init failed (%v) and fallback config creation failed: %w", err, writeErr)
}
// Continue - minimal config created
} else {
_ = output // bd init succeeded
}
return nil
}
// Case 2: Tracked beads exist - create redirect (may need to remove conflicting local beads)
if hasTrackedBeads {
// Check if local beads have conflicting data
if hasLocalBeads && hasBeadsData(rigBeadsDir) {
// Remove conflicting local beads directory
if err := os.RemoveAll(rigBeadsDir); err != nil {
return fmt.Errorf("removing conflicting local beads: %w", err)
}
}
// Create .beads directory if needed
if err := os.MkdirAll(rigBeadsDir, 0755); err != nil {
return fmt.Errorf("creating .beads directory: %w", err)
}
// Write redirect file
if err := os.WriteFile(redirectPath, []byte("mayor/rig/.beads\n"), 0644); err != nil {
return fmt.Errorf("writing redirect file: %w", err)
}
}
return nil
}
// hasBeadsData checks if a beads directory has actual data (issues.jsonl, issues.db, config.yaml)
// as opposed to just being a redirect-only directory.
func hasBeadsData(beadsDir string) bool {
// Check for actual beads data files
dataFiles := []string{"issues.jsonl", "issues.db", "config.yaml"}
for _, f := range dataFiles {
if _, err := os.Stat(filepath.Join(beadsDir, f)); err == nil {
return true
}
}
return false
}
// RigChecks returns all rig-level health checks.
func RigChecks() []Check {
return []Check{
@@ -877,5 +1087,6 @@ func RigChecks() []Check {
NewMayorCloneExistsCheck(),
NewPolecatClonesValidCheck(),
NewBeadsConfigValidCheck(),
NewBeadsRedirectCheck(),
}
}
+455
View File
@@ -0,0 +1,455 @@
package doctor
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestNewBeadsRedirectCheck(t *testing.T) {
check := NewBeadsRedirectCheck()
if check.Name() != "beads-redirect" {
t.Errorf("expected name 'beads-redirect', got %q", check.Name())
}
if !check.CanFix() {
t.Error("expected CanFix to return true")
}
}
func TestBeadsRedirectCheck_NoRigSpecified(t *testing.T) {
tmpDir := t.TempDir()
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: ""}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK when no rig specified, got %v", result.Status)
}
if !strings.Contains(result.Message, "skipping") {
t.Errorf("expected message about skipping, got %q", result.Message)
}
}
func TestBeadsRedirectCheck_NoBeadsAtAll(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
if err := os.MkdirAll(rigDir, 0755); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
result := check.Run(ctx)
if result.Status != StatusError {
t.Errorf("expected StatusError when no beads exist (fixable), got %v", result.Status)
}
}
func TestBeadsRedirectCheck_LocalBeadsOnly(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create local beads at rig root (no mayor/rig/.beads)
localBeads := filepath.Join(rigDir, ".beads")
if err := os.MkdirAll(localBeads, 0755); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK for local beads (no redirect needed), got %v", result.Status)
}
if !strings.Contains(result.Message, "local beads") {
t.Errorf("expected message about local beads, got %q", result.Message)
}
}
func TestBeadsRedirectCheck_TrackedBeadsMissingRedirect(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create tracked beads at mayor/rig/.beads
trackedBeads := filepath.Join(rigDir, "mayor", "rig", ".beads")
if err := os.MkdirAll(trackedBeads, 0755); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
result := check.Run(ctx)
if result.Status != StatusError {
t.Errorf("expected StatusError for missing redirect, got %v", result.Status)
}
if !strings.Contains(result.Message, "Missing") {
t.Errorf("expected message about missing redirect, got %q", result.Message)
}
}
func TestBeadsRedirectCheck_TrackedBeadsCorrectRedirect(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create tracked beads at mayor/rig/.beads
trackedBeads := filepath.Join(rigDir, "mayor", "rig", ".beads")
if err := os.MkdirAll(trackedBeads, 0755); err != nil {
t.Fatal(err)
}
// Create rig-level .beads with correct redirect
rigBeads := filepath.Join(rigDir, ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatal(err)
}
redirectPath := filepath.Join(rigBeads, "redirect")
if err := os.WriteFile(redirectPath, []byte("mayor/rig/.beads\n"), 0644); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
result := check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK for correct redirect, got %v", result.Status)
}
if !strings.Contains(result.Message, "correctly configured") {
t.Errorf("expected message about correct config, got %q", result.Message)
}
}
func TestBeadsRedirectCheck_TrackedBeadsWrongRedirect(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create tracked beads at mayor/rig/.beads
trackedBeads := filepath.Join(rigDir, "mayor", "rig", ".beads")
if err := os.MkdirAll(trackedBeads, 0755); err != nil {
t.Fatal(err)
}
// Create rig-level .beads with wrong redirect
rigBeads := filepath.Join(rigDir, ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatal(err)
}
redirectPath := filepath.Join(rigBeads, "redirect")
if err := os.WriteFile(redirectPath, []byte("wrong/path\n"), 0644); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
result := check.Run(ctx)
if result.Status != StatusError {
t.Errorf("expected StatusError for wrong redirect (fixable), got %v", result.Status)
}
if !strings.Contains(result.Message, "wrong/path") {
t.Errorf("expected message to contain wrong path, got %q", result.Message)
}
}
func TestBeadsRedirectCheck_FixWrongRedirect(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create tracked beads at mayor/rig/.beads
trackedBeads := filepath.Join(rigDir, "mayor", "rig", ".beads")
if err := os.MkdirAll(trackedBeads, 0755); err != nil {
t.Fatal(err)
}
// Create rig-level .beads with wrong redirect
rigBeads := filepath.Join(rigDir, ".beads")
if err := os.MkdirAll(rigBeads, 0755); err != nil {
t.Fatal(err)
}
redirectPath := filepath.Join(rigBeads, "redirect")
if err := os.WriteFile(redirectPath, []byte("wrong/path\n"), 0644); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
// Verify fix is needed
result := check.Run(ctx)
if result.Status != StatusError {
t.Fatalf("expected StatusError before fix, got %v", result.Status)
}
// Apply fix
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify redirect was corrected
content, err := os.ReadFile(redirectPath)
if err != nil {
t.Fatalf("redirect file not found: %v", err)
}
if string(content) != "mayor/rig/.beads\n" {
t.Errorf("redirect content = %q, want 'mayor/rig/.beads\\n'", string(content))
}
// Verify check now passes
result = check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK after fix, got %v", result.Status)
}
}
func TestBeadsRedirectCheck_Fix(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create tracked beads at mayor/rig/.beads
trackedBeads := filepath.Join(rigDir, "mayor", "rig", ".beads")
if err := os.MkdirAll(trackedBeads, 0755); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
// Verify fix is needed
result := check.Run(ctx)
if result.Status != StatusError {
t.Fatalf("expected StatusError before fix, got %v", result.Status)
}
// Apply fix
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify redirect file was created
redirectPath := filepath.Join(rigDir, ".beads", "redirect")
content, err := os.ReadFile(redirectPath)
if err != nil {
t.Fatalf("redirect file not created: %v", err)
}
expected := "mayor/rig/.beads\n"
if string(content) != expected {
t.Errorf("redirect content = %q, want %q", string(content), expected)
}
// Verify check now passes
result = check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK after fix, got %v", result.Status)
}
}
func TestBeadsRedirectCheck_FixNoOp_LocalBeads(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create only local beads (no tracked beads)
localBeads := filepath.Join(rigDir, ".beads")
if err := os.MkdirAll(localBeads, 0755); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
// Fix should be a no-op
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify no redirect was created
redirectPath := filepath.Join(rigDir, ".beads", "redirect")
if _, err := os.Stat(redirectPath); !os.IsNotExist(err) {
t.Error("redirect file should not be created for local beads")
}
}
func TestBeadsRedirectCheck_FixInitBeads(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create rig directory (no beads at all)
if err := os.MkdirAll(rigDir, 0755); err != nil {
t.Fatal(err)
}
// Create mayor/rigs.json with prefix for the rig
mayorDir := filepath.Join(tmpDir, "mayor")
if err := os.MkdirAll(mayorDir, 0755); err != nil {
t.Fatal(err)
}
rigsJSON := `{
"version": 1,
"rigs": {
"testrig": {
"git_url": "https://example.com/test.git",
"beads": {
"prefix": "tr"
}
}
}
}`
if err := os.WriteFile(filepath.Join(mayorDir, "rigs.json"), []byte(rigsJSON), 0644); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
// Verify fix is needed
result := check.Run(ctx)
if result.Status != StatusError {
t.Fatalf("expected StatusError before fix, got %v", result.Status)
}
// Apply fix - this will run 'bd init' if available, otherwise create config.yaml
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify .beads directory was created
beadsDir := filepath.Join(rigDir, ".beads")
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
t.Fatal(".beads directory not created")
}
// Verify beads was initialized (either by bd init or fallback)
// bd init creates config.yaml, fallback creates config.yaml with prefix
configPath := filepath.Join(beadsDir, "config.yaml")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
t.Fatal("config.yaml not created")
}
// Verify check now passes (local beads exist)
result = check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK after fix, got %v", result.Status)
}
}
func TestBeadsRedirectCheck_ConflictingLocalBeads(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create tracked beads at mayor/rig/.beads
trackedBeads := filepath.Join(rigDir, "mayor", "rig", ".beads")
if err := os.MkdirAll(trackedBeads, 0755); err != nil {
t.Fatal(err)
}
// Add some content to tracked beads
if err := os.WriteFile(filepath.Join(trackedBeads, "issues.jsonl"), []byte(`{"id":"tr-1"}`), 0644); err != nil {
t.Fatal(err)
}
// Create conflicting local beads with actual data
localBeads := filepath.Join(rigDir, ".beads")
if err := os.MkdirAll(localBeads, 0755); err != nil {
t.Fatal(err)
}
// Add data to local beads (this is the conflict)
if err := os.WriteFile(filepath.Join(localBeads, "issues.jsonl"), []byte(`{"id":"local-1"}`), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(localBeads, "config.yaml"), []byte("prefix: local\n"), 0644); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
// Check should detect conflicting beads
result := check.Run(ctx)
if result.Status != StatusError {
t.Errorf("expected StatusError for conflicting beads, got %v", result.Status)
}
if !strings.Contains(result.Message, "Conflicting") {
t.Errorf("expected message about conflicting beads, got %q", result.Message)
}
}
func TestBeadsRedirectCheck_FixConflictingLocalBeads(t *testing.T) {
tmpDir := t.TempDir()
rigName := "testrig"
rigDir := filepath.Join(tmpDir, rigName)
// Create tracked beads at mayor/rig/.beads
trackedBeads := filepath.Join(rigDir, "mayor", "rig", ".beads")
if err := os.MkdirAll(trackedBeads, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(trackedBeads, "issues.jsonl"), []byte(`{"id":"tr-1"}`), 0644); err != nil {
t.Fatal(err)
}
// Create conflicting local beads with actual data
localBeads := filepath.Join(rigDir, ".beads")
if err := os.MkdirAll(localBeads, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(localBeads, "issues.jsonl"), []byte(`{"id":"local-1"}`), 0644); err != nil {
t.Fatal(err)
}
check := NewBeadsRedirectCheck()
ctx := &CheckContext{TownRoot: tmpDir, RigName: rigName}
// Verify fix is needed
result := check.Run(ctx)
if result.Status != StatusError {
t.Fatalf("expected StatusError before fix, got %v", result.Status)
}
// Apply fix - should remove conflicting local beads and create redirect
if err := check.Fix(ctx); err != nil {
t.Fatalf("Fix failed: %v", err)
}
// Verify local issues.jsonl was removed
if _, err := os.Stat(filepath.Join(localBeads, "issues.jsonl")); !os.IsNotExist(err) {
t.Error("local issues.jsonl should have been removed")
}
// Verify redirect was created
redirectPath := filepath.Join(localBeads, "redirect")
content, err := os.ReadFile(redirectPath)
if err != nil {
t.Fatalf("redirect file not created: %v", err)
}
if string(content) != "mayor/rig/.beads\n" {
t.Errorf("redirect content = %q, want 'mayor/rig/.beads\\n'", string(content))
}
// Verify check now passes
result = check.Run(ctx)
if result.Status != StatusOK {
t.Errorf("expected StatusOK after fix, got %v", result.Status)
}
}