feat: remove daemon subsystem from bd CLI (dolt-test-jjsjn)
Remove the daemon subcommand, --no-daemon flag, and all daemon-related code from bd. With Dolt native backend, there is no daemon. This eliminates the deepest heresy vector where agents see daemon flags and conclude beads has a daemon architecture. Deleted 65+ daemon-specific files (~24.7k lines) including: - daemon.go, daemon_autostart.go, daemon_sync.go, daemon_server.go, etc. - internal/daemon/ package (registry, discovery, kill_*) - doctor/daemon.go, doctor/fix/daemon.go - activity.go (daemon-only activity command) - All corresponding test files Edited core files to remove daemon references: - main.go: removed --no-daemon flag, daemon connection block, imports - context.go: removed DaemonClient, DaemonStatus, NoDaemon fields - direct_mode.go: simplified to remove daemon fallback logic - doctor.go: removed daemon health checks - init.go: removed daemon stop before reinit - reset.go: removed daemon stop logic - worktree.go: removed daemon worktree safety checks Created compatibility stubs: - daemon_deprecated.go: stub variables/functions for 66 files that still reference daemonClient (always nil), enabling gradual cleanup - sync_helpers.go: extracted non-daemon sync functions (export/import) - sync_state.go: extracted sync state management Follow-up: Remove dead `if daemonClient != nil` branches from 66 command files, then delete daemon_deprecated.go and internal/rpc. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Executed-By: beads/polecats/quartz Rig: beads Role: polecats
This commit is contained in:
parent
dccac5a2c9
commit
326976614d
85 changed files with 471 additions and 24666 deletions
|
|
@ -1,897 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/routing"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
||||
var (
|
||||
activityFollow bool
|
||||
activityMol string
|
||||
activitySince string
|
||||
activityType string
|
||||
activityLimit int
|
||||
activityInterval time.Duration
|
||||
activityTown bool
|
||||
activityDetails bool
|
||||
)
|
||||
|
||||
// ActivityEvent represents a formatted activity event for output
|
||||
type ActivityEvent struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Type string `json:"type"`
|
||||
IssueID string `json:"issue_id"`
|
||||
Symbol string `json:"symbol"`
|
||||
Message string `json:"message"`
|
||||
// Optional metadata from richer events
|
||||
OldStatus string `json:"old_status,omitempty"`
|
||||
NewStatus string `json:"new_status,omitempty"`
|
||||
ParentID string `json:"parent_id,omitempty"`
|
||||
StepCount int `json:"step_count,omitempty"`
|
||||
Actor string `json:"actor,omitempty"`
|
||||
// Full issue details (populated when --details is used)
|
||||
Issue *types.IssueDetails `json:"issue,omitempty"`
|
||||
}
|
||||
|
||||
var activityCmd = &cobra.Command{
|
||||
Use: "activity",
|
||||
GroupID: "views",
|
||||
Short: "Show real-time molecule state feed",
|
||||
Long: `Display a real-time feed of issue and molecule state changes.
|
||||
|
||||
This command shows mutations (create, update, delete) as they happen,
|
||||
providing visibility into workflow progress.
|
||||
|
||||
Event symbols:
|
||||
+ created/bonded - New issue or molecule created
|
||||
→ in_progress - Work started on an issue
|
||||
✓ completed - Issue closed or step completed
|
||||
✗ failed - Step or issue failed
|
||||
⊘ deleted - Issue removed
|
||||
|
||||
Examples:
|
||||
bd activity # Show last 100 events
|
||||
bd activity --follow # Real-time streaming
|
||||
bd activity --mol bd-x7k # Filter by molecule prefix
|
||||
bd activity --since 5m # Events from last 5 minutes
|
||||
bd activity --since 1h # Events from last hour
|
||||
bd activity --type update # Only show updates
|
||||
bd activity --limit 50 # Show last 50 events
|
||||
bd activity --town # Aggregated feed from all rigs
|
||||
bd activity --follow --town # Stream all rig activity
|
||||
bd activity --details --json # Full issue details in JSON output`,
|
||||
Run: runActivity,
|
||||
}
|
||||
|
||||
func init() {
|
||||
activityCmd.Flags().BoolVarP(&activityFollow, "follow", "f", false, "Stream events in real-time")
|
||||
activityCmd.Flags().StringVar(&activityMol, "mol", "", "Filter by molecule/issue ID prefix")
|
||||
activityCmd.Flags().StringVar(&activitySince, "since", "", "Show events since duration (e.g., 5m, 1h, 30s)")
|
||||
activityCmd.Flags().StringVar(&activityType, "type", "", "Filter by event type (create, update, delete, comment)")
|
||||
activityCmd.Flags().IntVar(&activityLimit, "limit", 100, "Maximum number of events to show")
|
||||
activityCmd.Flags().DurationVar(&activityInterval, "interval", 500*time.Millisecond, "Polling interval for --follow mode")
|
||||
activityCmd.Flags().BoolVar(&activityTown, "town", false, "Aggregated feed from all rigs (uses routes.jsonl)")
|
||||
activityCmd.Flags().BoolVarP(&activityDetails, "details", "d", false, "Include full issue details in output (works best with --json)")
|
||||
|
||||
rootCmd.AddCommand(activityCmd)
|
||||
}
|
||||
|
||||
func runActivity(cmd *cobra.Command, args []string) {
|
||||
// Parse --since duration
|
||||
var sinceTime time.Time
|
||||
if activitySince != "" {
|
||||
duration, err := parseDurationString(activitySince)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: invalid --since duration: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
sinceTime = time.Now().Add(-duration)
|
||||
}
|
||||
|
||||
// Town-wide aggregated feed
|
||||
if activityTown {
|
||||
if activityFollow {
|
||||
runTownActivityFollow(sinceTime)
|
||||
} else {
|
||||
runTownActivityOnce(sinceTime)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Single-rig activity requires daemon
|
||||
if daemonClient == nil {
|
||||
fmt.Fprintln(os.Stderr, "Error: activity command requires daemon (mutations not available in direct mode)")
|
||||
fmt.Fprintln(os.Stderr, "Hint: Start daemon with 'bd daemons start .' or remove --no-daemon flag")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if activityFollow {
|
||||
runActivityFollow(sinceTime)
|
||||
} else {
|
||||
runActivityOnce(sinceTime)
|
||||
}
|
||||
}
|
||||
|
||||
// runActivityOnce fetches and displays events once
|
||||
func runActivityOnce(sinceTime time.Time) {
|
||||
events, err := fetchMutations(sinceTime)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Apply filters and limit
|
||||
events = filterEvents(events)
|
||||
if len(events) > activityLimit {
|
||||
events = events[len(events)-activityLimit:]
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
formatted := make([]ActivityEvent, 0, len(events))
|
||||
for _, e := range events {
|
||||
var details *types.IssueDetails
|
||||
if activityDetails {
|
||||
details = fetchIssueDetails(daemonClient, e.IssueID)
|
||||
}
|
||||
formatted = append(formatted, formatEventWithDetails(e, details))
|
||||
}
|
||||
outputJSON(formatted)
|
||||
return
|
||||
}
|
||||
|
||||
if len(events) == 0 {
|
||||
fmt.Println("No recent activity")
|
||||
return
|
||||
}
|
||||
|
||||
// For text output with --details, show full issue info
|
||||
for _, e := range events {
|
||||
printEvent(e)
|
||||
if activityDetails {
|
||||
details := fetchIssueDetails(daemonClient, e.IssueID)
|
||||
if details != nil {
|
||||
printEventDetails(details)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runActivityFollow streams events in real-time using filesystem watching.
|
||||
// Falls back to polling if fsnotify is not available.
|
||||
func runActivityFollow(sinceTime time.Time) {
|
||||
// Start from now if no --since specified
|
||||
lastPoll := time.Now().Add(-1 * time.Second)
|
||||
if !sinceTime.IsZero() {
|
||||
lastPoll = sinceTime
|
||||
}
|
||||
|
||||
// First fetch any events since the start time
|
||||
events, err := fetchMutations(sinceTime)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Apply filters and display initial events
|
||||
events = filterEvents(events)
|
||||
for _, e := range events {
|
||||
if jsonOutput {
|
||||
var details *types.IssueDetails
|
||||
if activityDetails {
|
||||
details = fetchIssueDetails(daemonClient, e.IssueID)
|
||||
}
|
||||
data, _ := json.Marshal(formatEventWithDetails(e, details))
|
||||
fmt.Println(string(data))
|
||||
} else {
|
||||
printEvent(e)
|
||||
if activityDetails {
|
||||
details := fetchIssueDetails(daemonClient, e.IssueID)
|
||||
if details != nil {
|
||||
printEventDetails(details)
|
||||
}
|
||||
}
|
||||
}
|
||||
if e.Timestamp.After(lastPoll) {
|
||||
lastPoll = e.Timestamp
|
||||
}
|
||||
}
|
||||
|
||||
// Create filesystem watcher for near-instant wake-up
|
||||
// Falls back to polling internally if fsnotify fails
|
||||
beadsDir := filepath.Dir(dbPath)
|
||||
watcher := NewActivityWatcher(beadsDir, activityInterval)
|
||||
defer func() { _ = watcher.Close() }()
|
||||
|
||||
// Start watching
|
||||
watcher.Start(rootCtx)
|
||||
|
||||
// Track consecutive failures for error reporting
|
||||
consecutiveFailures := 0
|
||||
const failureWarningThreshold = 5
|
||||
lastWarningTime := time.Time{}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-rootCtx.Done():
|
||||
return
|
||||
case _, ok := <-watcher.Events():
|
||||
if !ok {
|
||||
return // Watcher closed
|
||||
}
|
||||
|
||||
newEvents, err := fetchMutations(lastPoll)
|
||||
if err != nil {
|
||||
consecutiveFailures++
|
||||
// Show warning after threshold failures, but not more than once per 30 seconds
|
||||
if consecutiveFailures >= failureWarningThreshold {
|
||||
if time.Since(lastWarningTime) >= 30*time.Second {
|
||||
if jsonOutput {
|
||||
// Emit error event in JSON mode
|
||||
errorEvent := map[string]interface{}{
|
||||
"type": "error",
|
||||
"message": fmt.Sprintf("daemon unreachable (%d failures)", consecutiveFailures),
|
||||
"timestamp": time.Now().Format(time.RFC3339),
|
||||
}
|
||||
data, _ := json.Marshal(errorEvent)
|
||||
fmt.Fprintln(os.Stderr, string(data))
|
||||
} else {
|
||||
timestamp := time.Now().Format("15:04:05")
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s daemon unreachable (%d consecutive failures)\n",
|
||||
timestamp, ui.RenderWarn("!"), consecutiveFailures)
|
||||
}
|
||||
lastWarningTime = time.Now()
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Reset failure counter on success
|
||||
if consecutiveFailures > 0 {
|
||||
if consecutiveFailures >= failureWarningThreshold && !jsonOutput {
|
||||
timestamp := time.Now().Format("15:04:05")
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s daemon reconnected\n", timestamp, ui.RenderPass("✓"))
|
||||
}
|
||||
consecutiveFailures = 0
|
||||
}
|
||||
|
||||
newEvents = filterEvents(newEvents)
|
||||
for _, e := range newEvents {
|
||||
if jsonOutput {
|
||||
var details *types.IssueDetails
|
||||
if activityDetails {
|
||||
details = fetchIssueDetails(daemonClient, e.IssueID)
|
||||
}
|
||||
data, _ := json.Marshal(formatEventWithDetails(e, details))
|
||||
fmt.Println(string(data))
|
||||
} else {
|
||||
printEvent(e)
|
||||
if activityDetails {
|
||||
details := fetchIssueDetails(daemonClient, e.IssueID)
|
||||
if details != nil {
|
||||
printEventDetails(details)
|
||||
}
|
||||
}
|
||||
}
|
||||
if e.Timestamp.After(lastPoll) {
|
||||
lastPoll = e.Timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fetchMutations retrieves mutations from the daemon
|
||||
func fetchMutations(since time.Time) ([]rpc.MutationEvent, error) {
|
||||
var sinceMillis int64
|
||||
if !since.IsZero() {
|
||||
sinceMillis = since.UnixMilli()
|
||||
}
|
||||
|
||||
resp, err := daemonClient.GetMutations(&rpc.GetMutationsArgs{Since: sinceMillis})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get mutations: %w", err)
|
||||
}
|
||||
|
||||
var mutations []rpc.MutationEvent
|
||||
if err := json.Unmarshal(resp.Data, &mutations); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse mutations: %w", err)
|
||||
}
|
||||
|
||||
return mutations, nil
|
||||
}
|
||||
|
||||
// fetchIssueDetails retrieves full issue details from the daemon
|
||||
func fetchIssueDetails(client *rpc.Client, issueID string) *types.IssueDetails {
|
||||
if client == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
resp, err := client.Show(&rpc.ShowArgs{ID: issueID})
|
||||
if err != nil || !resp.Success {
|
||||
return nil
|
||||
}
|
||||
|
||||
var details types.IssueDetails
|
||||
if err := json.Unmarshal(resp.Data, &details); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &details
|
||||
}
|
||||
|
||||
// filterEvents applies --mol and --type filters
|
||||
func filterEvents(events []rpc.MutationEvent) []rpc.MutationEvent {
|
||||
if activityMol == "" && activityType == "" {
|
||||
return events
|
||||
}
|
||||
|
||||
filtered := make([]rpc.MutationEvent, 0, len(events))
|
||||
for _, e := range events {
|
||||
// Filter by molecule/issue ID prefix
|
||||
if activityMol != "" && !strings.HasPrefix(e.IssueID, activityMol) {
|
||||
continue
|
||||
}
|
||||
// Filter by event type
|
||||
if activityType != "" && e.Type != activityType {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, e)
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
// formatEvent converts a mutation event to a formatted activity event
|
||||
func formatEvent(e rpc.MutationEvent) ActivityEvent {
|
||||
return formatEventWithDetails(e, nil)
|
||||
}
|
||||
|
||||
// formatEventWithDetails converts a mutation event to a formatted activity event with optional details
|
||||
func formatEventWithDetails(e rpc.MutationEvent, details *types.IssueDetails) ActivityEvent {
|
||||
symbol, message := getEventDisplay(e)
|
||||
return ActivityEvent{
|
||||
Timestamp: e.Timestamp,
|
||||
Type: e.Type,
|
||||
IssueID: e.IssueID,
|
||||
Symbol: symbol,
|
||||
Message: message,
|
||||
OldStatus: e.OldStatus,
|
||||
NewStatus: e.NewStatus,
|
||||
ParentID: e.ParentID,
|
||||
StepCount: e.StepCount,
|
||||
Actor: e.Actor,
|
||||
Issue: details,
|
||||
}
|
||||
}
|
||||
|
||||
// getEventDisplay returns the symbol and message for an event type
|
||||
func getEventDisplay(e rpc.MutationEvent) (symbol, message string) {
|
||||
// Build context suffix: title and/or assignee
|
||||
context := buildEventContext(e)
|
||||
|
||||
switch e.Type {
|
||||
case rpc.MutationCreate:
|
||||
return "+", fmt.Sprintf("%s created%s", e.IssueID, context)
|
||||
case rpc.MutationUpdate:
|
||||
return "→", fmt.Sprintf("%s updated%s", e.IssueID, context)
|
||||
case rpc.MutationDelete:
|
||||
return "⊘", fmt.Sprintf("%s deleted%s", e.IssueID, context)
|
||||
case rpc.MutationComment:
|
||||
return "💬", fmt.Sprintf("%s comment%s", e.IssueID, context)
|
||||
case rpc.MutationBonded:
|
||||
if e.StepCount > 0 {
|
||||
return "+", fmt.Sprintf("%s bonded (%d steps)%s", e.IssueID, e.StepCount, context)
|
||||
}
|
||||
return "+", fmt.Sprintf("%s bonded%s", e.IssueID, context)
|
||||
case rpc.MutationSquashed:
|
||||
return "◉", fmt.Sprintf("%s SQUASHED%s", e.IssueID, context)
|
||||
case rpc.MutationBurned:
|
||||
return "🔥", fmt.Sprintf("%s burned%s", e.IssueID, context)
|
||||
case rpc.MutationStatus:
|
||||
// Status change with transition info
|
||||
if e.NewStatus == "in_progress" {
|
||||
return "→", fmt.Sprintf("%s started%s", e.IssueID, context)
|
||||
} else if e.NewStatus == "closed" {
|
||||
return "✓", fmt.Sprintf("%s completed%s", e.IssueID, context)
|
||||
} else if e.NewStatus == "open" && e.OldStatus != "" {
|
||||
return "↺", fmt.Sprintf("%s reopened%s", e.IssueID, context)
|
||||
}
|
||||
return "→", fmt.Sprintf("%s → %s%s", e.IssueID, e.NewStatus, context)
|
||||
default:
|
||||
return "•", fmt.Sprintf("%s %s%s", e.IssueID, e.Type, context)
|
||||
}
|
||||
}
|
||||
|
||||
// buildEventContext creates a context string from title and actor/assignee
|
||||
func buildEventContext(e rpc.MutationEvent) string {
|
||||
var parts []string
|
||||
|
||||
// Add truncated title if present
|
||||
if e.Title != "" {
|
||||
title := truncateString(e.Title, 40)
|
||||
parts = append(parts, title)
|
||||
}
|
||||
|
||||
// For status changes, prefer showing actor (who performed the action)
|
||||
// For other events, show assignee
|
||||
if e.Actor != "" {
|
||||
parts = append(parts, "@"+e.Actor)
|
||||
} else if e.Assignee != "" {
|
||||
parts = append(parts, "@"+e.Assignee)
|
||||
}
|
||||
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
return " · " + strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// truncateString truncates a string to maxLen, adding ellipsis if needed
|
||||
func truncateString(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
if maxLen <= 3 {
|
||||
return s[:maxLen]
|
||||
}
|
||||
return s[:maxLen-3] + "..."
|
||||
}
|
||||
|
||||
// printEvent prints a formatted event to stdout
|
||||
func printEvent(e rpc.MutationEvent) {
|
||||
symbol, message := getEventDisplay(e)
|
||||
timestamp := e.Timestamp.Format("15:04:05")
|
||||
|
||||
// Colorize output based on event type
|
||||
var coloredSymbol string
|
||||
switch e.Type {
|
||||
case rpc.MutationCreate, rpc.MutationBonded:
|
||||
coloredSymbol = ui.RenderPass(symbol)
|
||||
case rpc.MutationUpdate:
|
||||
coloredSymbol = ui.RenderWarn(symbol)
|
||||
case rpc.MutationDelete, rpc.MutationBurned:
|
||||
coloredSymbol = ui.RenderFail(symbol)
|
||||
case rpc.MutationComment:
|
||||
coloredSymbol = ui.RenderAccent(symbol)
|
||||
case rpc.MutationSquashed:
|
||||
coloredSymbol = ui.RenderAccent(symbol)
|
||||
case rpc.MutationStatus:
|
||||
// Color based on new status
|
||||
if e.NewStatus == "closed" {
|
||||
coloredSymbol = ui.RenderPass(symbol)
|
||||
} else if e.NewStatus == "in_progress" {
|
||||
coloredSymbol = ui.RenderWarn(symbol)
|
||||
} else {
|
||||
coloredSymbol = ui.RenderAccent(symbol)
|
||||
}
|
||||
default:
|
||||
coloredSymbol = symbol
|
||||
}
|
||||
|
||||
fmt.Printf("[%s] %s %s\n", timestamp, coloredSymbol, message)
|
||||
}
|
||||
|
||||
// printEventDetails prints full issue details for text output with --details
|
||||
func printEventDetails(details *types.IssueDetails) {
|
||||
fmt.Printf("Status: %s Priority: P%d Type: %s\n",
|
||||
details.Status, details.Priority, details.IssueType)
|
||||
if details.Assignee != "" {
|
||||
fmt.Printf("Assignee: %s\n", details.Assignee)
|
||||
}
|
||||
if len(details.Labels) > 0 {
|
||||
fmt.Printf("Labels: %s\n", strings.Join(details.Labels, ", "))
|
||||
}
|
||||
if details.Description != "" {
|
||||
desc := truncateString(details.Description, 80)
|
||||
desc = strings.ReplaceAll(desc, "\n", " ")
|
||||
fmt.Printf("Description: %s\n", desc)
|
||||
}
|
||||
if len(details.Dependencies) > 0 {
|
||||
deps := make([]string, 0, len(details.Dependencies))
|
||||
for _, d := range details.Dependencies {
|
||||
deps = append(deps, d.ID)
|
||||
}
|
||||
fmt.Printf("Depends on: %s\n", strings.Join(deps, ", "))
|
||||
}
|
||||
if len(details.Dependents) > 0 {
|
||||
dependents := make([]string, 0, len(details.Dependents))
|
||||
for _, d := range details.Dependents {
|
||||
dependents = append(dependents, d.ID)
|
||||
}
|
||||
fmt.Printf("Blocked by: %s\n", strings.Join(dependents, ", "))
|
||||
}
|
||||
if len(details.Comments) > 0 {
|
||||
fmt.Printf("Comments: %d\n", len(details.Comments))
|
||||
for _, c := range details.Comments {
|
||||
text := truncateString(c.Text, 60)
|
||||
text = strings.ReplaceAll(text, "\n", " ")
|
||||
fmt.Printf(" @%s: %s\n", c.Author, text)
|
||||
}
|
||||
}
|
||||
fmt.Printf("Created: %s Updated: %s\n",
|
||||
details.CreatedAt.Format("2006-01-02 15:04"), details.UpdatedAt.Format("2006-01-02 15:04"))
|
||||
fmt.Println() // Blank line between events
|
||||
}
|
||||
|
||||
// parseDurationString parses duration strings like "5m", "1h", "30s", "2d"
|
||||
func parseDurationString(s string) (time.Duration, error) {
|
||||
// Try standard Go duration first
|
||||
if d, err := time.ParseDuration(s); err == nil {
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// Handle custom formats like "2d" for days
|
||||
re := regexp.MustCompile(`^(\d+)([dhms])$`)
|
||||
matches := re.FindStringSubmatch(strings.ToLower(s))
|
||||
if len(matches) != 3 {
|
||||
return 0, fmt.Errorf("invalid duration format: %s (use 5m, 1h, 30s, or 2d)", s)
|
||||
}
|
||||
|
||||
value, _ := strconv.Atoi(matches[1])
|
||||
unit := matches[2]
|
||||
|
||||
switch unit {
|
||||
case "d":
|
||||
return time.Duration(value) * 24 * time.Hour, nil
|
||||
case "h":
|
||||
return time.Duration(value) * time.Hour, nil
|
||||
case "m":
|
||||
return time.Duration(value) * time.Minute, nil
|
||||
case "s":
|
||||
return time.Duration(value) * time.Second, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unknown duration unit: %s", unit)
|
||||
}
|
||||
}
|
||||
|
||||
// rigDaemon holds a connection to a rig's daemon
|
||||
type rigDaemon struct {
|
||||
prefix string // e.g., "bd-"
|
||||
rig string // e.g., "beads"
|
||||
client *rpc.Client // nil if daemon not running
|
||||
}
|
||||
|
||||
// discoverRigDaemons finds all rigs via routes.jsonl and connects to their daemons
|
||||
func discoverRigDaemons() []rigDaemon {
|
||||
var daemons []rigDaemon
|
||||
|
||||
// Find town beads directory (uses findTownBeadsDir from create.go)
|
||||
townBeadsDir, err := findTownBeadsDir()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: not in an orchestrator environment (%v)\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Load routes
|
||||
routes, err := routing.LoadRoutes(townBeadsDir)
|
||||
if err != nil || len(routes) == 0 {
|
||||
fmt.Fprintln(os.Stderr, "Error: no routes found in routes.jsonl")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
townRoot := filepath.Dir(townBeadsDir)
|
||||
|
||||
for _, route := range routes {
|
||||
// Resolve beads directory for this route
|
||||
var beadsDir string
|
||||
if route.Path == "." {
|
||||
beadsDir = townBeadsDir
|
||||
} else {
|
||||
beadsDir = filepath.Join(townRoot, route.Path, ".beads")
|
||||
}
|
||||
|
||||
// Follow redirect if present
|
||||
beadsDir = resolveBeadsRedirect(beadsDir)
|
||||
|
||||
// Check if daemon is running
|
||||
socketPath := rpc.ShortSocketPath(filepath.Dir(beadsDir))
|
||||
client, _ := rpc.TryConnect(socketPath)
|
||||
|
||||
rigName := routing.ExtractProjectFromPath(route.Path)
|
||||
if rigName == "" {
|
||||
rigName = "town" // For path="."
|
||||
}
|
||||
|
||||
daemons = append(daemons, rigDaemon{
|
||||
prefix: route.Prefix,
|
||||
rig: rigName,
|
||||
client: client,
|
||||
})
|
||||
}
|
||||
|
||||
return daemons
|
||||
}
|
||||
|
||||
// resolveBeadsRedirect follows a redirect file if present.
|
||||
// Similar to routing.resolveRedirect but simplified for activity use.
|
||||
func resolveBeadsRedirect(beadsDir string) string {
|
||||
redirectFile := filepath.Join(beadsDir, "redirect")
|
||||
data, err := os.ReadFile(redirectFile) // #nosec G304 - redirects are trusted within beads rig paths
|
||||
if err != nil {
|
||||
return beadsDir
|
||||
}
|
||||
|
||||
redirectPath := strings.TrimSpace(string(data))
|
||||
if redirectPath == "" {
|
||||
return beadsDir
|
||||
}
|
||||
|
||||
// Handle relative paths
|
||||
if !filepath.IsAbs(redirectPath) {
|
||||
redirectPath = filepath.Join(beadsDir, redirectPath)
|
||||
}
|
||||
|
||||
redirectPath = filepath.Clean(redirectPath)
|
||||
|
||||
// Verify target exists before returning
|
||||
if info, err := os.Stat(redirectPath); err == nil && info.IsDir() {
|
||||
return redirectPath
|
||||
}
|
||||
|
||||
return beadsDir // Fallback to original if redirect target invalid
|
||||
}
|
||||
|
||||
// fetchTownMutations retrieves mutations from all rig daemons
|
||||
func fetchTownMutations(daemons []rigDaemon, since time.Time) []rpc.MutationEvent {
|
||||
events, _ := fetchTownMutationsWithStatus(daemons, since)
|
||||
return events
|
||||
}
|
||||
|
||||
// findDaemonForIssue finds the appropriate daemon client for an issue ID based on prefix
|
||||
func findDaemonForIssue(daemons []rigDaemon, issueID string) *rpc.Client {
|
||||
for _, d := range daemons {
|
||||
if d.client != nil && strings.HasPrefix(issueID, d.prefix) {
|
||||
return d.client
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchTownMutationsWithStatus retrieves mutations and returns count of responding daemons
|
||||
func fetchTownMutationsWithStatus(daemons []rigDaemon, since time.Time) ([]rpc.MutationEvent, int) {
|
||||
var allEvents []rpc.MutationEvent
|
||||
activeCount := 0
|
||||
|
||||
var sinceMillis int64
|
||||
if !since.IsZero() {
|
||||
sinceMillis = since.UnixMilli()
|
||||
}
|
||||
|
||||
for _, d := range daemons {
|
||||
if d.client == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
resp, err := d.client.GetMutations(&rpc.GetMutationsArgs{Since: sinceMillis})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
activeCount++
|
||||
|
||||
var mutations []rpc.MutationEvent
|
||||
if err := json.Unmarshal(resp.Data, &mutations); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
allEvents = append(allEvents, mutations...)
|
||||
}
|
||||
|
||||
// Sort by timestamp
|
||||
sort.Slice(allEvents, func(i, j int) bool {
|
||||
return allEvents[i].Timestamp.Before(allEvents[j].Timestamp)
|
||||
})
|
||||
|
||||
return allEvents, activeCount
|
||||
}
|
||||
|
||||
// runTownActivityOnce fetches and displays events from all rigs once
|
||||
func runTownActivityOnce(sinceTime time.Time) {
|
||||
daemons := discoverRigDaemons()
|
||||
defer closeDaemons(daemons)
|
||||
|
||||
// Count active daemons
|
||||
activeCount := 0
|
||||
for _, d := range daemons {
|
||||
if d.client != nil {
|
||||
activeCount++
|
||||
}
|
||||
}
|
||||
|
||||
if activeCount == 0 {
|
||||
fmt.Fprintln(os.Stderr, "Error: no rig daemons running")
|
||||
fmt.Fprintln(os.Stderr, "Hint: Start daemons with 'bd daemons start' in each rig")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
events := fetchTownMutations(daemons, sinceTime)
|
||||
|
||||
// Apply filters and limit
|
||||
events = filterEvents(events)
|
||||
if len(events) > activityLimit {
|
||||
events = events[len(events)-activityLimit:]
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
formatted := make([]ActivityEvent, 0, len(events))
|
||||
for _, e := range events {
|
||||
var details *types.IssueDetails
|
||||
if activityDetails {
|
||||
client := findDaemonForIssue(daemons, e.IssueID)
|
||||
details = fetchIssueDetails(client, e.IssueID)
|
||||
}
|
||||
formatted = append(formatted, formatEventWithDetails(e, details))
|
||||
}
|
||||
outputJSON(formatted)
|
||||
return
|
||||
}
|
||||
|
||||
if len(events) == 0 {
|
||||
fmt.Printf("No recent activity across %d rigs\n", activeCount)
|
||||
return
|
||||
}
|
||||
|
||||
for _, e := range events {
|
||||
printEvent(e)
|
||||
if activityDetails {
|
||||
client := findDaemonForIssue(daemons, e.IssueID)
|
||||
details := fetchIssueDetails(client, e.IssueID)
|
||||
if details != nil {
|
||||
printEventDetails(details)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runTownActivityFollow streams events from all rigs in real-time
|
||||
func runTownActivityFollow(sinceTime time.Time) {
|
||||
daemons := discoverRigDaemons()
|
||||
defer closeDaemons(daemons)
|
||||
|
||||
// Count active daemons
|
||||
activeCount := 0
|
||||
var activeRigs []string
|
||||
for _, d := range daemons {
|
||||
if d.client != nil {
|
||||
activeCount++
|
||||
activeRigs = append(activeRigs, d.rig)
|
||||
}
|
||||
}
|
||||
|
||||
if activeCount == 0 {
|
||||
fmt.Fprintln(os.Stderr, "Error: no rig daemons running")
|
||||
fmt.Fprintln(os.Stderr, "Hint: Start daemons with 'bd daemons start' in each rig")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Show which rigs we're monitoring
|
||||
if !jsonOutput {
|
||||
fmt.Printf("Streaming activity from %d rigs: %s\n", activeCount, strings.Join(activeRigs, ", "))
|
||||
}
|
||||
|
||||
// Start from now if no --since specified
|
||||
lastPoll := time.Now().Add(-1 * time.Second)
|
||||
if !sinceTime.IsZero() {
|
||||
lastPoll = sinceTime
|
||||
}
|
||||
|
||||
// First fetch any events since the start time
|
||||
events := fetchTownMutations(daemons, sinceTime)
|
||||
events = filterEvents(events)
|
||||
|
||||
for _, e := range events {
|
||||
if jsonOutput {
|
||||
var details *types.IssueDetails
|
||||
if activityDetails {
|
||||
client := findDaemonForIssue(daemons, e.IssueID)
|
||||
details = fetchIssueDetails(client, e.IssueID)
|
||||
}
|
||||
data, _ := json.Marshal(formatEventWithDetails(e, details))
|
||||
fmt.Println(string(data))
|
||||
} else {
|
||||
printEvent(e)
|
||||
if activityDetails {
|
||||
client := findDaemonForIssue(daemons, e.IssueID)
|
||||
details := fetchIssueDetails(client, e.IssueID)
|
||||
if details != nil {
|
||||
printEventDetails(details)
|
||||
}
|
||||
}
|
||||
}
|
||||
if e.Timestamp.After(lastPoll) {
|
||||
lastPoll = e.Timestamp
|
||||
}
|
||||
}
|
||||
|
||||
// Poll for new events
|
||||
ticker := time.NewTicker(activityInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
// Track failures for warning messages
|
||||
consecutiveFailures := 0
|
||||
const failureWarningThreshold = 5
|
||||
lastWarningTime := time.Time{}
|
||||
lastActiveCount := activeCount
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-rootCtx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
newEvents, currentActive := fetchTownMutationsWithStatus(daemons, lastPoll)
|
||||
|
||||
// Track daemon availability changes
|
||||
if currentActive < lastActiveCount {
|
||||
consecutiveFailures++
|
||||
if consecutiveFailures >= failureWarningThreshold {
|
||||
if time.Since(lastWarningTime) >= 30*time.Second {
|
||||
if !jsonOutput {
|
||||
timestamp := time.Now().Format("15:04:05")
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s some rigs unreachable (%d/%d active)\n",
|
||||
timestamp, ui.RenderWarn("!"), currentActive, len(daemons))
|
||||
}
|
||||
lastWarningTime = time.Now()
|
||||
}
|
||||
}
|
||||
} else if currentActive > lastActiveCount {
|
||||
// Daemon came back
|
||||
if !jsonOutput {
|
||||
timestamp := time.Now().Format("15:04:05")
|
||||
fmt.Fprintf(os.Stderr, "[%s] %s rig reconnected (%d/%d active)\n",
|
||||
timestamp, ui.RenderPass("✓"), currentActive, len(daemons))
|
||||
}
|
||||
consecutiveFailures = 0
|
||||
}
|
||||
lastActiveCount = currentActive
|
||||
|
||||
newEvents = filterEvents(newEvents)
|
||||
|
||||
for _, e := range newEvents {
|
||||
if jsonOutput {
|
||||
var details *types.IssueDetails
|
||||
if activityDetails {
|
||||
client := findDaemonForIssue(daemons, e.IssueID)
|
||||
details = fetchIssueDetails(client, e.IssueID)
|
||||
}
|
||||
data, _ := json.Marshal(formatEventWithDetails(e, details))
|
||||
fmt.Println(string(data))
|
||||
} else {
|
||||
printEvent(e)
|
||||
if activityDetails {
|
||||
client := findDaemonForIssue(daemons, e.IssueID)
|
||||
details := fetchIssueDetails(client, e.IssueID)
|
||||
if details != nil {
|
||||
printEventDetails(details)
|
||||
}
|
||||
}
|
||||
}
|
||||
if e.Timestamp.After(lastPoll) {
|
||||
lastPoll = e.Timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// closeDaemons closes all daemon connections
|
||||
func closeDaemons(daemons []rigDaemon) {
|
||||
for _, d := range daemons {
|
||||
if d.client != nil {
|
||||
if err := d.client.Close(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to close daemon client: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,453 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestParseDurationString tests the duration parsing function
|
||||
func TestParseDurationString(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected time.Duration
|
||||
expectErr bool
|
||||
}{
|
||||
// Standard Go duration formats
|
||||
{"5 minutes", "5m", 5 * time.Minute, false},
|
||||
{"1 hour", "1h", time.Hour, false},
|
||||
{"30 seconds", "30s", 30 * time.Second, false},
|
||||
{"2h30m", "2h30m", 2*time.Hour + 30*time.Minute, false},
|
||||
|
||||
// Custom day format
|
||||
{"2 days", "2d", 2 * 24 * time.Hour, false},
|
||||
{"1 day", "1d", 24 * time.Hour, false},
|
||||
{"7 days", "7d", 7 * 24 * time.Hour, false},
|
||||
|
||||
// Case insensitivity for custom formats
|
||||
{"uppercase D", "3D", 3 * 24 * time.Hour, false},
|
||||
{"uppercase H", "2H", 2 * time.Hour, false},
|
||||
{"uppercase M", "15M", 15 * time.Minute, false},
|
||||
{"uppercase S", "45S", 45 * time.Second, false},
|
||||
|
||||
// Invalid formats
|
||||
{"empty string", "", 0, true},
|
||||
{"invalid unit", "5x", 0, true},
|
||||
{"no number", "m", 0, true},
|
||||
{"text only", "five minutes", 0, true},
|
||||
|
||||
// Note: negative durations are actually valid in Go's time.ParseDuration
|
||||
// so we test it works rather than expecting an error
|
||||
{"negative duration", "-5m", -5 * time.Minute, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := parseDurationString(tt.input)
|
||||
|
||||
if tt.expectErr {
|
||||
if err == nil {
|
||||
t.Errorf("expected error for input %q, got nil", tt.input)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error for input %q: %v", tt.input, err)
|
||||
}
|
||||
if result != tt.expected {
|
||||
t.Errorf("for input %q: expected %v, got %v", tt.input, tt.expected, result)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFilterEvents tests event filtering by --mol and --type
|
||||
func TestFilterEvents(t *testing.T) {
|
||||
// Create test events
|
||||
events := []rpc.MutationEvent{
|
||||
{Type: rpc.MutationCreate, IssueID: "bd-abc123", Timestamp: time.Now()},
|
||||
{Type: rpc.MutationUpdate, IssueID: "bd-abc456", Timestamp: time.Now()},
|
||||
{Type: rpc.MutationDelete, IssueID: "bd-xyz789", Timestamp: time.Now()},
|
||||
{Type: rpc.MutationStatus, IssueID: "bd-abc789", Timestamp: time.Now()},
|
||||
{Type: rpc.MutationComment, IssueID: "bd-def123", Timestamp: time.Now()},
|
||||
}
|
||||
|
||||
// Reset global filter vars before each test
|
||||
defer func() {
|
||||
activityMol = ""
|
||||
activityType = ""
|
||||
}()
|
||||
|
||||
t.Run("no filters returns all events", func(t *testing.T) {
|
||||
activityMol = ""
|
||||
activityType = ""
|
||||
result := filterEvents(events)
|
||||
if len(result) != len(events) {
|
||||
t.Errorf("expected %d events, got %d", len(events), len(result))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("filter by mol prefix", func(t *testing.T) {
|
||||
activityMol = "bd-abc"
|
||||
activityType = ""
|
||||
result := filterEvents(events)
|
||||
// Should match: bd-abc123, bd-abc456, bd-abc789
|
||||
if len(result) != 3 {
|
||||
t.Errorf("expected 3 events matching bd-abc*, got %d", len(result))
|
||||
}
|
||||
for _, e := range result {
|
||||
if e.IssueID[:6] != "bd-abc" {
|
||||
t.Errorf("unexpected event with ID %s", e.IssueID)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("filter by event type", func(t *testing.T) {
|
||||
activityMol = ""
|
||||
activityType = rpc.MutationCreate
|
||||
result := filterEvents(events)
|
||||
if len(result) != 1 {
|
||||
t.Errorf("expected 1 create event, got %d", len(result))
|
||||
}
|
||||
if len(result) > 0 && result[0].Type != rpc.MutationCreate {
|
||||
t.Errorf("expected create event, got %s", result[0].Type)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("filter by both mol and type", func(t *testing.T) {
|
||||
activityMol = "bd-abc"
|
||||
activityType = rpc.MutationUpdate
|
||||
result := filterEvents(events)
|
||||
// Should match: only bd-abc456 (update)
|
||||
if len(result) != 1 {
|
||||
t.Errorf("expected 1 event, got %d", len(result))
|
||||
}
|
||||
if len(result) > 0 {
|
||||
if result[0].IssueID != "bd-abc456" {
|
||||
t.Errorf("expected bd-abc456, got %s", result[0].IssueID)
|
||||
}
|
||||
if result[0].Type != rpc.MutationUpdate {
|
||||
t.Errorf("expected update type, got %s", result[0].Type)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("filter returns empty for no matches", func(t *testing.T) {
|
||||
activityMol = "bd-nomatch"
|
||||
activityType = ""
|
||||
result := filterEvents(events)
|
||||
if len(result) != 0 {
|
||||
t.Errorf("expected 0 events, got %d", len(result))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestGetEventDisplay tests the symbol and message generation for all event types
|
||||
func TestGetEventDisplay(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
event rpc.MutationEvent
|
||||
expectedSymbol string
|
||||
checkMessage func(string) bool
|
||||
}{
|
||||
{
|
||||
name: "create event",
|
||||
event: rpc.MutationEvent{Type: rpc.MutationCreate, IssueID: "bd-123"},
|
||||
expectedSymbol: "+",
|
||||
checkMessage: func(m string) bool { return m == "bd-123 created" },
|
||||
},
|
||||
{
|
||||
name: "update event",
|
||||
event: rpc.MutationEvent{Type: rpc.MutationUpdate, IssueID: "bd-456"},
|
||||
expectedSymbol: "\u2192", // →
|
||||
checkMessage: func(m string) bool { return m == "bd-456 updated" },
|
||||
},
|
||||
{
|
||||
name: "delete event",
|
||||
event: rpc.MutationEvent{Type: rpc.MutationDelete, IssueID: "bd-789"},
|
||||
expectedSymbol: "\u2298", // ⊘
|
||||
checkMessage: func(m string) bool { return m == "bd-789 deleted" },
|
||||
},
|
||||
{
|
||||
name: "comment event",
|
||||
event: rpc.MutationEvent{Type: rpc.MutationComment, IssueID: "bd-abc"},
|
||||
expectedSymbol: "\U0001F4AC", // 💬
|
||||
checkMessage: func(m string) bool { return m == "bd-abc comment" },
|
||||
},
|
||||
{
|
||||
name: "bonded event with step count",
|
||||
event: rpc.MutationEvent{
|
||||
Type: rpc.MutationBonded,
|
||||
IssueID: "bd-mol",
|
||||
StepCount: 5,
|
||||
},
|
||||
expectedSymbol: "+",
|
||||
checkMessage: func(m string) bool { return m == "bd-mol bonded (5 steps)" },
|
||||
},
|
||||
{
|
||||
name: "bonded event without step count",
|
||||
event: rpc.MutationEvent{Type: rpc.MutationBonded, IssueID: "bd-mol2"},
|
||||
expectedSymbol: "+",
|
||||
checkMessage: func(m string) bool { return m == "bd-mol2 bonded" },
|
||||
},
|
||||
{
|
||||
name: "squashed event",
|
||||
event: rpc.MutationEvent{Type: rpc.MutationSquashed, IssueID: "bd-wisp"},
|
||||
expectedSymbol: "\u25C9", // ◉
|
||||
checkMessage: func(m string) bool { return m == "bd-wisp SQUASHED" },
|
||||
},
|
||||
{
|
||||
name: "burned event",
|
||||
event: rpc.MutationEvent{Type: rpc.MutationBurned, IssueID: "bd-burn"},
|
||||
expectedSymbol: "\U0001F525", // 🔥
|
||||
checkMessage: func(m string) bool { return m == "bd-burn burned" },
|
||||
},
|
||||
{
|
||||
name: "status event - in_progress",
|
||||
event: rpc.MutationEvent{
|
||||
Type: rpc.MutationStatus,
|
||||
IssueID: "bd-wip",
|
||||
OldStatus: "open",
|
||||
NewStatus: "in_progress",
|
||||
},
|
||||
expectedSymbol: "\u2192", // →
|
||||
checkMessage: func(m string) bool { return m == "bd-wip started" },
|
||||
},
|
||||
{
|
||||
name: "status event - closed",
|
||||
event: rpc.MutationEvent{
|
||||
Type: rpc.MutationStatus,
|
||||
IssueID: "bd-done",
|
||||
OldStatus: "in_progress",
|
||||
NewStatus: "closed",
|
||||
},
|
||||
expectedSymbol: "\u2713", // ✓
|
||||
checkMessage: func(m string) bool { return m == "bd-done completed" },
|
||||
},
|
||||
{
|
||||
name: "status event - reopened",
|
||||
event: rpc.MutationEvent{
|
||||
Type: rpc.MutationStatus,
|
||||
IssueID: "bd-reopen",
|
||||
OldStatus: "closed",
|
||||
NewStatus: "open",
|
||||
},
|
||||
expectedSymbol: "\u21BA", // ↺
|
||||
checkMessage: func(m string) bool { return m == "bd-reopen reopened" },
|
||||
},
|
||||
{
|
||||
name: "unknown event type",
|
||||
event: rpc.MutationEvent{Type: "custom", IssueID: "bd-custom"},
|
||||
expectedSymbol: "\u2022", // •
|
||||
checkMessage: func(m string) bool { return m == "bd-custom custom" },
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
symbol, message := getEventDisplay(tt.event)
|
||||
|
||||
if symbol != tt.expectedSymbol {
|
||||
t.Errorf("expected symbol %q, got %q", tt.expectedSymbol, symbol)
|
||||
}
|
||||
|
||||
if !tt.checkMessage(message) {
|
||||
t.Errorf("unexpected message: %q", message)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFormatEvent tests the ActivityEvent formatting
|
||||
func TestFormatEvent(t *testing.T) {
|
||||
now := time.Now()
|
||||
event := rpc.MutationEvent{
|
||||
Type: rpc.MutationStatus,
|
||||
IssueID: "bd-test",
|
||||
Timestamp: now,
|
||||
OldStatus: "open",
|
||||
NewStatus: "in_progress",
|
||||
ParentID: "bd-parent",
|
||||
StepCount: 3,
|
||||
}
|
||||
|
||||
result := formatEvent(event)
|
||||
|
||||
if result.Timestamp != now {
|
||||
t.Errorf("expected timestamp %v, got %v", now, result.Timestamp)
|
||||
}
|
||||
if result.Type != rpc.MutationStatus {
|
||||
t.Errorf("expected type %s, got %s", rpc.MutationStatus, result.Type)
|
||||
}
|
||||
if result.IssueID != "bd-test" {
|
||||
t.Errorf("expected issue ID bd-test, got %s", result.IssueID)
|
||||
}
|
||||
if result.OldStatus != "open" {
|
||||
t.Errorf("expected OldStatus 'open', got %s", result.OldStatus)
|
||||
}
|
||||
if result.NewStatus != "in_progress" {
|
||||
t.Errorf("expected NewStatus 'in_progress', got %s", result.NewStatus)
|
||||
}
|
||||
if result.ParentID != "bd-parent" {
|
||||
t.Errorf("expected ParentID 'bd-parent', got %s", result.ParentID)
|
||||
}
|
||||
if result.StepCount != 3 {
|
||||
t.Errorf("expected StepCount 3, got %d", result.StepCount)
|
||||
}
|
||||
if result.Symbol == "" {
|
||||
t.Error("expected non-empty symbol")
|
||||
}
|
||||
if result.Message == "" {
|
||||
t.Error("expected non-empty message")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFormatEventWithDetails tests that issue details are included when provided
|
||||
func TestFormatEventWithDetails(t *testing.T) {
|
||||
now := time.Now()
|
||||
event := rpc.MutationEvent{
|
||||
Type: rpc.MutationCreate,
|
||||
IssueID: "bd-test",
|
||||
Timestamp: now,
|
||||
}
|
||||
|
||||
t.Run("without details", func(t *testing.T) {
|
||||
result := formatEventWithDetails(event, nil)
|
||||
if result.Issue != nil {
|
||||
t.Error("expected nil issue when no details provided")
|
||||
}
|
||||
if result.IssueID != "bd-test" {
|
||||
t.Errorf("expected issue ID bd-test, got %s", result.IssueID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("with details", func(t *testing.T) {
|
||||
details := &types.IssueDetails{
|
||||
Issue: types.Issue{
|
||||
ID: "bd-test",
|
||||
Title: "Test Issue",
|
||||
Description: "A test description",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeTask,
|
||||
Assignee: "testuser",
|
||||
},
|
||||
Labels: []string{"bug", "urgent"},
|
||||
Dependencies: nil,
|
||||
Dependents: nil,
|
||||
}
|
||||
|
||||
result := formatEventWithDetails(event, details)
|
||||
|
||||
if result.Issue == nil {
|
||||
t.Fatal("expected issue details to be included")
|
||||
}
|
||||
if result.Issue.ID != "bd-test" {
|
||||
t.Errorf("expected issue ID bd-test, got %s", result.Issue.ID)
|
||||
}
|
||||
if result.Issue.Title != "Test Issue" {
|
||||
t.Errorf("expected title 'Test Issue', got %s", result.Issue.Title)
|
||||
}
|
||||
if result.Issue.Assignee != "testuser" {
|
||||
t.Errorf("expected assignee 'testuser', got %s", result.Issue.Assignee)
|
||||
}
|
||||
if len(result.Issue.Labels) != 2 {
|
||||
t.Errorf("expected 2 labels, got %d", len(result.Issue.Labels))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestFindDaemonForIssue tests daemon lookup by issue ID prefix
|
||||
func TestFindDaemonForIssue(t *testing.T) {
|
||||
// Create mock daemons (without actual connections)
|
||||
daemons := []rigDaemon{
|
||||
{prefix: "bd-", rig: "beads", client: nil}, // No client
|
||||
{prefix: "app-", rig: "app", client: nil}, // No client
|
||||
{prefix: "test-", rig: "test", client: nil}, // No client
|
||||
}
|
||||
|
||||
t.Run("no matching prefix returns nil", func(t *testing.T) {
|
||||
result := findDaemonForIssue(daemons, "other-123")
|
||||
if result != nil {
|
||||
t.Error("expected nil for non-matching prefix")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("matching prefix but nil client returns nil", func(t *testing.T) {
|
||||
result := findDaemonForIssue(daemons, "bd-abc123")
|
||||
if result != nil {
|
||||
t.Error("expected nil when daemon client is nil")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty daemons list returns nil", func(t *testing.T) {
|
||||
result := findDaemonForIssue([]rigDaemon{}, "bd-abc")
|
||||
if result != nil {
|
||||
t.Error("expected nil for empty daemon list")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestFetchIssueDetails tests the issue details fetching function
|
||||
func TestFetchIssueDetails(t *testing.T) {
|
||||
t.Run("nil client returns nil", func(t *testing.T) {
|
||||
result := fetchIssueDetails(nil, "bd-123")
|
||||
if result != nil {
|
||||
t.Error("expected nil when client is nil")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestFormatEventWithDetailsIncludesComments verifies comments are preserved in details
|
||||
func TestFormatEventWithDetailsIncludesComments(t *testing.T) {
|
||||
now := time.Now()
|
||||
event := rpc.MutationEvent{
|
||||
Type: rpc.MutationUpdate,
|
||||
IssueID: "bd-test",
|
||||
Timestamp: now,
|
||||
}
|
||||
|
||||
details := &types.IssueDetails{
|
||||
Issue: types.Issue{
|
||||
ID: "bd-test",
|
||||
Title: "Test Issue",
|
||||
Status: types.StatusInProgress,
|
||||
},
|
||||
Comments: []*types.Comment{
|
||||
{
|
||||
ID: 1,
|
||||
IssueID: "bd-test",
|
||||
Author: "alice",
|
||||
Text: "First comment with full text that should not be truncated in JSON",
|
||||
CreatedAt: now.Add(-time.Hour),
|
||||
},
|
||||
{
|
||||
ID: 2,
|
||||
IssueID: "bd-test",
|
||||
Author: "bob",
|
||||
Text: "Second comment",
|
||||
CreatedAt: now.Add(-30 * time.Minute),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
result := formatEventWithDetails(event, details)
|
||||
|
||||
if result.Issue == nil {
|
||||
t.Fatal("expected issue details to be included")
|
||||
}
|
||||
if len(result.Issue.Comments) != 2 {
|
||||
t.Errorf("expected 2 comments, got %d", len(result.Issue.Comments))
|
||||
}
|
||||
if result.Issue.Comments[0].Author != "alice" {
|
||||
t.Errorf("expected first comment author 'alice', got %s", result.Issue.Comments[0].Author)
|
||||
}
|
||||
// Verify full text is preserved (not truncated) for JSON output
|
||||
expectedText := "First comment with full text that should not be truncated in JSON"
|
||||
if result.Issue.Comments[0].Text != expectedText {
|
||||
t.Errorf("expected full comment text preserved, got %s", result.Issue.Comments[0].Text)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,233 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
)
|
||||
|
||||
// ActivityWatcher monitors the beads directory for changes using filesystem events.
|
||||
// Falls back to polling if fsnotify fails (some filesystems don't support it).
|
||||
type ActivityWatcher struct {
|
||||
watcher *fsnotify.Watcher
|
||||
watchPaths []string // Paths being watched
|
||||
pollingMode bool // True if using polling fallback
|
||||
pollInterval time.Duration
|
||||
events chan struct{} // Sends wake-up signals on changes
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
|
||||
// Polling state
|
||||
lastModTimes map[string]time.Time
|
||||
}
|
||||
|
||||
// NewActivityWatcher creates a watcher for activity feed updates.
|
||||
// Watches the dolt noms directory for commits, falling back to polling if fsnotify fails.
|
||||
// The beadsDir should be the .beads directory path.
|
||||
// The pollInterval is used for polling fallback mode.
|
||||
func NewActivityWatcher(beadsDir string, pollInterval time.Duration) *ActivityWatcher {
|
||||
aw := &ActivityWatcher{
|
||||
pollInterval: pollInterval,
|
||||
events: make(chan struct{}, 1), // Buffered to avoid blocking
|
||||
lastModTimes: make(map[string]time.Time),
|
||||
}
|
||||
|
||||
// Determine watch paths - prefer dolt noms directory if it exists
|
||||
doltNomsPath := filepath.Join(beadsDir, "dolt", ".dolt", "noms")
|
||||
doltPath := filepath.Join(beadsDir, "dolt", ".dolt")
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
|
||||
// Build list of paths to watch (in priority order)
|
||||
var watchPaths []string
|
||||
if stat, err := os.Stat(doltNomsPath); err == nil && stat.IsDir() {
|
||||
// Watch dolt noms directory for commits
|
||||
watchPaths = append(watchPaths, doltNomsPath)
|
||||
} else if stat, err := os.Stat(doltPath); err == nil && stat.IsDir() {
|
||||
// Fallback to .dolt directory
|
||||
watchPaths = append(watchPaths, doltPath)
|
||||
}
|
||||
// Also watch JSONL for non-dolt or hybrid setups
|
||||
if _, err := os.Stat(jsonlPath); err == nil {
|
||||
watchPaths = append(watchPaths, jsonlPath)
|
||||
}
|
||||
// Watch the beads dir itself as last resort
|
||||
if len(watchPaths) == 0 {
|
||||
watchPaths = append(watchPaths, beadsDir)
|
||||
}
|
||||
|
||||
aw.watchPaths = watchPaths
|
||||
|
||||
// Initialize modification times for polling
|
||||
for _, p := range watchPaths {
|
||||
if stat, err := os.Stat(p); err == nil {
|
||||
aw.lastModTimes[p] = stat.ModTime()
|
||||
}
|
||||
}
|
||||
|
||||
// Try to create fsnotify watcher
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
// Fall back to polling mode
|
||||
aw.pollingMode = true
|
||||
return aw
|
||||
}
|
||||
|
||||
// Add watches for each path
|
||||
watchedAny := false
|
||||
for _, p := range watchPaths {
|
||||
if err := watcher.Add(p); err != nil {
|
||||
// Log but continue - some paths may not be watchable
|
||||
continue
|
||||
}
|
||||
watchedAny = true
|
||||
}
|
||||
|
||||
if !watchedAny {
|
||||
// No paths could be watched, fall back to polling
|
||||
_ = watcher.Close()
|
||||
aw.pollingMode = true
|
||||
return aw
|
||||
}
|
||||
|
||||
aw.watcher = watcher
|
||||
return aw
|
||||
}
|
||||
|
||||
// Events returns the channel that receives wake-up signals when changes are detected.
|
||||
// The channel sends an empty struct for each detected change (debounced).
|
||||
func (aw *ActivityWatcher) Events() <-chan struct{} {
|
||||
return aw.events
|
||||
}
|
||||
|
||||
// IsPolling returns true if the watcher is using polling fallback.
|
||||
func (aw *ActivityWatcher) IsPolling() bool {
|
||||
return aw.pollingMode
|
||||
}
|
||||
|
||||
// Start begins monitoring for changes.
|
||||
// Returns immediately, monitoring happens in background goroutine.
|
||||
func (aw *ActivityWatcher) Start(ctx context.Context) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
aw.cancel = cancel
|
||||
|
||||
if aw.pollingMode {
|
||||
aw.startPolling(ctx)
|
||||
} else {
|
||||
aw.startFSWatch(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// startFSWatch starts fsnotify-based watching.
|
||||
func (aw *ActivityWatcher) startFSWatch(ctx context.Context) {
|
||||
aw.wg.Add(1)
|
||||
go func() {
|
||||
defer aw.wg.Done()
|
||||
|
||||
// Debounce: don't send more than one event per 50ms
|
||||
var lastEvent time.Time
|
||||
debounceWindow := 50 * time.Millisecond
|
||||
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-aw.watcher.Events:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Only trigger on write events
|
||||
if event.Op&fsnotify.Write == 0 && event.Op&fsnotify.Create == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Debounce rapid events
|
||||
now := time.Now()
|
||||
if now.Sub(lastEvent) < debounceWindow {
|
||||
continue
|
||||
}
|
||||
lastEvent = now
|
||||
|
||||
// Send non-blocking wake-up signal
|
||||
select {
|
||||
case aw.events <- struct{}{}:
|
||||
default:
|
||||
// Channel already has a pending event
|
||||
}
|
||||
|
||||
case _, ok := <-aw.watcher.Errors:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// Log errors but continue watching
|
||||
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// startPolling starts polling-based change detection.
|
||||
func (aw *ActivityWatcher) startPolling(ctx context.Context) {
|
||||
aw.wg.Add(1)
|
||||
go func() {
|
||||
defer aw.wg.Done()
|
||||
|
||||
ticker := time.NewTicker(aw.pollInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if aw.checkForChanges() {
|
||||
// Send non-blocking wake-up signal
|
||||
select {
|
||||
case aw.events <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// checkForChanges checks if any watched paths have been modified.
|
||||
func (aw *ActivityWatcher) checkForChanges() bool {
|
||||
aw.mu.Lock()
|
||||
defer aw.mu.Unlock()
|
||||
|
||||
changed := false
|
||||
for _, p := range aw.watchPaths {
|
||||
stat, err := os.Stat(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
lastMod, exists := aw.lastModTimes[p]
|
||||
if !exists || !stat.ModTime().Equal(lastMod) {
|
||||
aw.lastModTimes[p] = stat.ModTime()
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// Close stops the watcher and releases resources.
|
||||
func (aw *ActivityWatcher) Close() error {
|
||||
if aw.cancel != nil {
|
||||
aw.cancel()
|
||||
}
|
||||
aw.wg.Wait()
|
||||
close(aw.events)
|
||||
if aw.watcher != nil {
|
||||
return aw.watcher.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,253 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDaemonAutoStart(t *testing.T) {
|
||||
// Initialize config for tests
|
||||
initConfigForTest(t)
|
||||
|
||||
// Stub out backend checks so they don't interfere with env var testing
|
||||
oldIsDoltBackendFn := isDoltBackendFn
|
||||
oldSingleProcessOnlyBackendFn := singleProcessOnlyBackendFn
|
||||
isDoltBackendFn = func() bool { return false }
|
||||
singleProcessOnlyBackendFn = func() bool { return false }
|
||||
defer func() {
|
||||
isDoltBackendFn = oldIsDoltBackendFn
|
||||
singleProcessOnlyBackendFn = oldSingleProcessOnlyBackendFn
|
||||
}()
|
||||
|
||||
// Save original env
|
||||
origAutoStart := os.Getenv("BEADS_AUTO_START_DAEMON")
|
||||
origNoDaemon := os.Getenv("BEADS_NO_DAEMON")
|
||||
defer func() {
|
||||
if origAutoStart != "" {
|
||||
os.Setenv("BEADS_AUTO_START_DAEMON", origAutoStart)
|
||||
} else {
|
||||
os.Unsetenv("BEADS_AUTO_START_DAEMON")
|
||||
}
|
||||
if origNoDaemon != "" {
|
||||
os.Setenv("BEADS_NO_DAEMON", origNoDaemon)
|
||||
} else {
|
||||
os.Unsetenv("BEADS_NO_DAEMON")
|
||||
}
|
||||
}()
|
||||
|
||||
// Ensure BEADS_NO_DAEMON doesn't interfere with these tests
|
||||
os.Unsetenv("BEADS_NO_DAEMON")
|
||||
|
||||
t.Run("shouldAutoStartDaemon defaults to true", func(t *testing.T) {
|
||||
os.Unsetenv("BEADS_AUTO_START_DAEMON")
|
||||
if !shouldAutoStartDaemon() {
|
||||
t.Error("Expected auto-start to be enabled by default")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("shouldAutoStartDaemon respects false", func(t *testing.T) {
|
||||
os.Setenv("BEADS_AUTO_START_DAEMON", "false")
|
||||
if shouldAutoStartDaemon() {
|
||||
t.Error("Expected auto-start to be disabled when set to 'false'")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("shouldAutoStartDaemon respects 0", func(t *testing.T) {
|
||||
os.Setenv("BEADS_AUTO_START_DAEMON", "0")
|
||||
if shouldAutoStartDaemon() {
|
||||
t.Error("Expected auto-start to be disabled when set to '0'")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("shouldAutoStartDaemon respects no", func(t *testing.T) {
|
||||
os.Setenv("BEADS_AUTO_START_DAEMON", "no")
|
||||
if shouldAutoStartDaemon() {
|
||||
t.Error("Expected auto-start to be disabled when set to 'no'")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("shouldAutoStartDaemon respects off", func(t *testing.T) {
|
||||
os.Setenv("BEADS_AUTO_START_DAEMON", "off")
|
||||
if shouldAutoStartDaemon() {
|
||||
t.Error("Expected auto-start to be disabled when set to 'off'")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("shouldAutoStartDaemon handles case and whitespace", func(t *testing.T) {
|
||||
os.Setenv("BEADS_AUTO_START_DAEMON", " FALSE ")
|
||||
if shouldAutoStartDaemon() {
|
||||
t.Error("Expected auto-start to be disabled when set to ' FALSE '")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("shouldAutoStartDaemon respects true", func(t *testing.T) {
|
||||
os.Setenv("BEADS_AUTO_START_DAEMON", "true")
|
||||
if !shouldAutoStartDaemon() {
|
||||
t.Error("Expected auto-start to be enabled when set to 'true'")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDaemonStartFailureTracking(t *testing.T) {
|
||||
// Reset failure state
|
||||
daemonStartFailures = 0
|
||||
lastDaemonStartAttempt = time.Time{}
|
||||
|
||||
t.Run("canRetryDaemonStart allows first attempt", func(t *testing.T) {
|
||||
if !canRetryDaemonStart() {
|
||||
t.Error("Expected first attempt to be allowed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("exponential backoff after failures", func(t *testing.T) {
|
||||
// Simulate first failure
|
||||
recordDaemonStartFailure()
|
||||
if daemonStartFailures != 1 {
|
||||
t.Errorf("Expected failure count 1, got %d", daemonStartFailures)
|
||||
}
|
||||
|
||||
// Should not allow immediate retry
|
||||
if canRetryDaemonStart() {
|
||||
t.Error("Expected retry to be blocked immediately after failure")
|
||||
}
|
||||
|
||||
// Wait for backoff period (5 seconds for first failure)
|
||||
lastDaemonStartAttempt = time.Now().Add(-6 * time.Second)
|
||||
if !canRetryDaemonStart() {
|
||||
t.Error("Expected retry to be allowed after backoff period")
|
||||
}
|
||||
|
||||
// Simulate second failure
|
||||
recordDaemonStartFailure()
|
||||
if daemonStartFailures != 2 {
|
||||
t.Errorf("Expected failure count 2, got %d", daemonStartFailures)
|
||||
}
|
||||
|
||||
// Should not allow immediate retry (10 second backoff)
|
||||
if canRetryDaemonStart() {
|
||||
t.Error("Expected retry to be blocked immediately after second failure")
|
||||
}
|
||||
|
||||
// Wait for longer backoff
|
||||
lastDaemonStartAttempt = time.Now().Add(-11 * time.Second)
|
||||
if !canRetryDaemonStart() {
|
||||
t.Error("Expected retry to be allowed after longer backoff period")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("exponential backoff durations are correct", func(t *testing.T) {
|
||||
testCases := []struct {
|
||||
failures int
|
||||
expected time.Duration
|
||||
}{
|
||||
{1, 5 * time.Second},
|
||||
{2, 10 * time.Second},
|
||||
{3, 20 * time.Second},
|
||||
{4, 40 * time.Second},
|
||||
{5, 80 * time.Second},
|
||||
{6, 120 * time.Second}, // Capped
|
||||
{10, 120 * time.Second}, // Still capped
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
daemonStartFailures = tc.failures
|
||||
lastDaemonStartAttempt = time.Now()
|
||||
|
||||
// Should not allow retry immediately
|
||||
if canRetryDaemonStart() {
|
||||
t.Errorf("Failures=%d: Expected immediate retry to be blocked", tc.failures)
|
||||
}
|
||||
|
||||
// Should allow retry after expected duration
|
||||
lastDaemonStartAttempt = time.Now().Add(-(tc.expected + time.Second))
|
||||
if !canRetryDaemonStart() {
|
||||
t.Errorf("Failures=%d: Expected retry after %v", tc.failures, tc.expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("recordDaemonStartSuccess resets failures", func(t *testing.T) {
|
||||
daemonStartFailures = 10
|
||||
recordDaemonStartSuccess()
|
||||
if daemonStartFailures != 0 {
|
||||
t.Errorf("Expected failure count to reset to 0, got %d", daemonStartFailures)
|
||||
}
|
||||
})
|
||||
|
||||
// Reset state
|
||||
daemonStartFailures = 0
|
||||
lastDaemonStartAttempt = time.Time{}
|
||||
}
|
||||
|
||||
func TestGetSocketPath(t *testing.T) {
|
||||
// Create temp directory structure
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create temp directory: %v", err)
|
||||
}
|
||||
|
||||
// Set dbPath to temp location
|
||||
originalDbPath := dbPath
|
||||
dbPath = filepath.Join(beadsDir, "test.db")
|
||||
defer func() { dbPath = originalDbPath }()
|
||||
|
||||
t.Run("prefers local socket when it exists", func(t *testing.T) {
|
||||
localSocket := filepath.Join(beadsDir, "bd.sock")
|
||||
|
||||
// Create local socket file
|
||||
if err := os.WriteFile(localSocket, []byte{}, 0600); err != nil {
|
||||
t.Fatalf("Failed to create socket file: %v", err)
|
||||
}
|
||||
defer os.Remove(localSocket)
|
||||
|
||||
socketPath := getSocketPath()
|
||||
if socketPath != localSocket {
|
||||
t.Errorf("Expected local socket %s, got %s", localSocket, socketPath)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("always returns local socket path", func(t *testing.T) {
|
||||
// Ensure no local socket exists
|
||||
localSocket := filepath.Join(beadsDir, "bd.sock")
|
||||
os.Remove(localSocket)
|
||||
|
||||
// Create a fake global socket in temp directory instead of home dir
|
||||
// This avoids issues in sandboxed build environments
|
||||
fakeHome := t.TempDir()
|
||||
globalBeadsDir := filepath.Join(fakeHome, ".beads")
|
||||
if err := os.MkdirAll(globalBeadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create fake global beads directory: %v", err)
|
||||
}
|
||||
globalSocket := filepath.Join(globalBeadsDir, "bd.sock")
|
||||
|
||||
if err := os.WriteFile(globalSocket, []byte{}, 0600); err != nil {
|
||||
t.Fatalf("Failed to create fake global socket file: %v", err)
|
||||
}
|
||||
|
||||
// Note: This test verifies that getSocketPath() returns the local socket
|
||||
// even when a global socket might exist. We can't actually test the real
|
||||
// global socket behavior in sandboxed environments, but the function
|
||||
// logic is still validated.
|
||||
socketPath := getSocketPath()
|
||||
if socketPath != localSocket {
|
||||
t.Errorf("Expected local socket %s, got %s", localSocket, socketPath)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("defaults to local socket when none exist", func(t *testing.T) {
|
||||
// Ensure no local socket exists
|
||||
localSocket := filepath.Join(beadsDir, "bd.sock")
|
||||
os.Remove(localSocket)
|
||||
|
||||
// We can't remove the global socket in sandboxed environments,
|
||||
// but the test still validates that getSocketPath() returns the
|
||||
// local socket path as expected
|
||||
socketPath := getSocketPath()
|
||||
if socketPath != localSocket {
|
||||
t.Errorf("Expected default to local socket %s, got %s", localSocket, socketPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/hooks"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
)
|
||||
|
||||
|
|
@ -25,7 +24,6 @@ type CommandContext struct {
|
|||
DBPath string
|
||||
Actor string
|
||||
JSONOutput bool
|
||||
NoDaemon bool
|
||||
SandboxMode bool
|
||||
AllowStale bool
|
||||
NoDb bool
|
||||
|
|
@ -35,12 +33,10 @@ type CommandContext struct {
|
|||
Quiet bool
|
||||
|
||||
// Runtime state
|
||||
Store storage.Storage
|
||||
DaemonClient *rpc.Client
|
||||
DaemonStatus DaemonStatus
|
||||
RootCtx context.Context
|
||||
RootCancel context.CancelFunc
|
||||
HookRunner *hooks.Runner
|
||||
Store storage.Storage
|
||||
RootCtx context.Context
|
||||
RootCancel context.CancelFunc
|
||||
HookRunner *hooks.Runner
|
||||
|
||||
// Auto-flush state (grouped with protecting mutex)
|
||||
FlushManager *FlushManager
|
||||
|
|
@ -112,7 +108,7 @@ func shouldUseGlobals() bool {
|
|||
// migration period, and they can be gradually replaced with direct
|
||||
// cmdCtx access as files are updated.
|
||||
|
||||
// getStore returns the current storage backend (daemon client or direct SQLite).
|
||||
// getStore returns the current storage backend.
|
||||
// This is the primary way commands should access storage.
|
||||
func getStore() storage.Storage {
|
||||
if shouldUseGlobals() {
|
||||
|
|
@ -145,22 +141,6 @@ func setActor(a string) {
|
|||
actor = a
|
||||
}
|
||||
|
||||
// getDaemonClient returns the RPC client for daemon mode, or nil in direct mode.
|
||||
func getDaemonClient() *rpc.Client {
|
||||
if shouldUseGlobals() {
|
||||
return daemonClient
|
||||
}
|
||||
return cmdCtx.DaemonClient
|
||||
}
|
||||
|
||||
// setDaemonClient updates the daemon client in the CommandContext.
|
||||
func setDaemonClient(c *rpc.Client) {
|
||||
if cmdCtx != nil {
|
||||
cmdCtx.DaemonClient = c
|
||||
}
|
||||
daemonClient = c
|
||||
}
|
||||
|
||||
// isJSONOutput returns true if JSON output mode is enabled.
|
||||
func isJSONOutput() bool {
|
||||
if shouldUseGlobals() {
|
||||
|
|
@ -282,39 +262,7 @@ func setFlushManager(fm *FlushManager) {
|
|||
flushManager = fm
|
||||
}
|
||||
|
||||
// getDaemonStatus returns the current daemon status.
|
||||
func getDaemonStatus() DaemonStatus {
|
||||
if shouldUseGlobals() {
|
||||
return daemonStatus
|
||||
}
|
||||
return cmdCtx.DaemonStatus
|
||||
}
|
||||
|
||||
// setDaemonStatus updates the daemon status.
|
||||
func setDaemonStatus(ds DaemonStatus) {
|
||||
if cmdCtx != nil {
|
||||
cmdCtx.DaemonStatus = ds
|
||||
}
|
||||
daemonStatus = ds
|
||||
}
|
||||
|
||||
// isNoDaemon returns true if daemon mode is disabled.
|
||||
func isNoDaemon() bool {
|
||||
if shouldUseGlobals() {
|
||||
return noDaemon
|
||||
}
|
||||
return cmdCtx.NoDaemon
|
||||
}
|
||||
|
||||
// setNoDaemon updates the no-daemon flag.
|
||||
func setNoDaemon(nd bool) {
|
||||
if cmdCtx != nil {
|
||||
cmdCtx.NoDaemon = nd
|
||||
}
|
||||
noDaemon = nd
|
||||
}
|
||||
|
||||
// isReadonlyMode returns true if read-only mode is enabled.
|
||||
// isJSONOutput returns true if JSON output mode is enabled.
|
||||
func isReadonlyMode() bool {
|
||||
if shouldUseGlobals() {
|
||||
return readonlyMode
|
||||
|
|
@ -546,7 +494,6 @@ func syncCommandContext() {
|
|||
cmdCtx.DBPath = dbPath
|
||||
cmdCtx.Actor = actor
|
||||
cmdCtx.JSONOutput = jsonOutput
|
||||
cmdCtx.NoDaemon = noDaemon
|
||||
cmdCtx.SandboxMode = sandboxMode
|
||||
cmdCtx.AllowStale = allowStale
|
||||
cmdCtx.NoDb = noDb
|
||||
|
|
@ -557,8 +504,6 @@ func syncCommandContext() {
|
|||
|
||||
// Runtime state
|
||||
cmdCtx.Store = store
|
||||
cmdCtx.DaemonClient = daemonClient
|
||||
cmdCtx.DaemonStatus = daemonStatus
|
||||
cmdCtx.RootCtx = rootCtx
|
||||
cmdCtx.RootCancel = rootCancel
|
||||
cmdCtx.HookRunner = hookRunner
|
||||
|
|
|
|||
1065
cmd/bd/daemon.go
1065
cmd/bd/daemon.go
File diff suppressed because it is too large
Load diff
|
|
@ -1,411 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestDaemonAutoImportAfterGitPull tests bd-09b5f2f5 fix
|
||||
// Verifies that daemon automatically imports JSONL after git pull updates it
|
||||
func TestDaemonAutoImportAfterGitPull(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
// Create temp directory with short name to avoid socket path length issues
|
||||
tempDir, err := os.MkdirTemp("", "bd-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
// Create "remote" repository
|
||||
remoteDir := filepath.Join(tempDir, "remote")
|
||||
if err := os.MkdirAll(remoteDir, 0750); err != nil {
|
||||
t.Fatalf("Failed to create remote dir: %v", err)
|
||||
}
|
||||
|
||||
// Initialize remote git repo
|
||||
runGitCmd(t, remoteDir, "init", "--bare", "-b", "master")
|
||||
|
||||
// Create "clone1" repository (Agent A)
|
||||
clone1Dir := filepath.Join(tempDir, "clone1")
|
||||
runGitCmd(t, tempDir, "clone", remoteDir, clone1Dir)
|
||||
configureGit(t, clone1Dir)
|
||||
|
||||
// Initialize beads in clone1
|
||||
clone1BeadsDir := filepath.Join(clone1Dir, ".beads")
|
||||
if err := os.MkdirAll(clone1BeadsDir, 0750); err != nil {
|
||||
t.Fatalf("Failed to create .beads dir: %v", err)
|
||||
}
|
||||
|
||||
clone1DBPath := filepath.Join(clone1BeadsDir, "test.db")
|
||||
clone1Store := newTestStore(t, clone1DBPath)
|
||||
defer clone1Store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
if err := clone1Store.SetMetadata(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("Failed to set prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create an open issue in clone1
|
||||
issue := &types.Issue{
|
||||
Title: "Test daemon auto-import",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if err := clone1Store.CreateIssue(ctx, issue, "agent-a"); err != nil {
|
||||
t.Fatalf("Failed to create issue: %v", err)
|
||||
}
|
||||
issueID := issue.ID
|
||||
|
||||
// Export to JSONL
|
||||
jsonlPath := filepath.Join(clone1BeadsDir, "issues.jsonl")
|
||||
if err := exportIssuesToJSONL(ctx, clone1Store, jsonlPath); err != nil {
|
||||
t.Fatalf("Failed to export: %v", err)
|
||||
}
|
||||
|
||||
// Commit and push from clone1
|
||||
runGitCmd(t, clone1Dir, "add", ".beads")
|
||||
runGitCmd(t, clone1Dir, "commit", "-m", "Add test issue")
|
||||
runGitCmd(t, clone1Dir, "push", "origin", "master")
|
||||
|
||||
// Create "clone2" repository (Agent B)
|
||||
clone2Dir := filepath.Join(tempDir, "clone2")
|
||||
runGitCmd(t, tempDir, "clone", remoteDir, clone2Dir)
|
||||
configureGit(t, clone2Dir)
|
||||
|
||||
// Initialize empty database in clone2
|
||||
clone2BeadsDir := filepath.Join(clone2Dir, ".beads")
|
||||
clone2DBPath := filepath.Join(clone2BeadsDir, "test.db")
|
||||
clone2Store := newTestStore(t, clone2DBPath)
|
||||
defer clone2Store.Close()
|
||||
|
||||
if err := clone2Store.SetMetadata(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("Failed to set prefix: %v", err)
|
||||
}
|
||||
|
||||
// Import initial JSONL in clone2
|
||||
clone2JSONLPath := filepath.Join(clone2BeadsDir, "issues.jsonl")
|
||||
if err := importJSONLToStore(ctx, clone2Store, clone2DBPath, clone2JSONLPath); err != nil {
|
||||
t.Fatalf("Failed to import: %v", err)
|
||||
}
|
||||
|
||||
// Verify issue exists in clone2
|
||||
initialIssue, err := clone2Store.GetIssue(ctx, issueID)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get issue: %v", err)
|
||||
}
|
||||
if initialIssue.Status != types.StatusOpen {
|
||||
t.Errorf("Expected status open, got %s", initialIssue.Status)
|
||||
}
|
||||
|
||||
// NOW THE CRITICAL TEST: Agent A closes the issue and pushes
|
||||
t.Run("DaemonAutoImportsAfterGitPull", func(t *testing.T) {
|
||||
// Agent A closes the issue
|
||||
if err := clone1Store.CloseIssue(ctx, issueID, "Completed", "agent-a", ""); err != nil {
|
||||
t.Fatalf("Failed to close issue: %v", err)
|
||||
}
|
||||
|
||||
// Agent A exports to JSONL
|
||||
if err := exportIssuesToJSONL(ctx, clone1Store, jsonlPath); err != nil {
|
||||
t.Fatalf("Failed to export after close: %v", err)
|
||||
}
|
||||
|
||||
// Agent A commits and pushes
|
||||
runGitCmd(t, clone1Dir, "add", ".beads/issues.jsonl")
|
||||
runGitCmd(t, clone1Dir, "commit", "-m", "Close issue")
|
||||
runGitCmd(t, clone1Dir, "push", "origin", "master")
|
||||
|
||||
// Agent B does git pull (updates JSONL on disk)
|
||||
runGitCmd(t, clone2Dir, "pull")
|
||||
|
||||
// Wait for filesystem to settle after git operations
|
||||
// Windows has lower filesystem timestamp precision (typically 100ms)
|
||||
// and file I/O may be slower, so we need a longer delay
|
||||
if runtime.GOOS == "windows" {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
} else {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Start daemon server in clone2
|
||||
socketPath := filepath.Join(clone2BeadsDir, "bd.sock")
|
||||
os.Remove(socketPath) // Ensure clean state
|
||||
|
||||
server := rpc.NewServer(socketPath, clone2Store, clone2Dir, clone2DBPath)
|
||||
|
||||
// Start server in background
|
||||
serverCtx, serverCancel := context.WithCancel(context.Background())
|
||||
defer serverCancel()
|
||||
|
||||
go func() {
|
||||
if err := server.Start(serverCtx); err != nil {
|
||||
t.Logf("Server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for server to be ready
|
||||
for i := 0; i < 50; i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if _, err := os.Stat(socketPath); err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Simulate a daemon request (like "bd show <issue>")
|
||||
// The daemon should auto-import the updated JSONL before responding
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to connect to daemon: %v", err)
|
||||
}
|
||||
if client == nil {
|
||||
t.Fatal("Client is nil")
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
client.SetDatabasePath(clone2DBPath) // Route to correct database
|
||||
|
||||
// Make a request that triggers auto-import check
|
||||
resp, err := client.Execute("show", map[string]string{"id": issueID})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get issue from daemon: %v", err)
|
||||
}
|
||||
|
||||
// Parse response
|
||||
var issue types.Issue
|
||||
issueJSON, err := json.Marshal(resp.Data)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal response data: %v", err)
|
||||
}
|
||||
if err := json.Unmarshal(issueJSON, &issue); err != nil {
|
||||
t.Fatalf("Failed to unmarshal issue: %v", err)
|
||||
}
|
||||
|
||||
status := issue.Status
|
||||
|
||||
// CRITICAL ASSERTION: Daemon should return CLOSED status from JSONL
|
||||
// not stale OPEN status from SQLite
|
||||
if status != types.StatusClosed {
|
||||
t.Errorf("DAEMON AUTO-IMPORT FAILED: Expected status 'closed' but got '%s'", status)
|
||||
t.Errorf("This means daemon is serving stale SQLite data instead of auto-importing JSONL")
|
||||
|
||||
// Double-check JSONL has correct status
|
||||
jsonlData, _ := os.ReadFile(clone2JSONLPath)
|
||||
t.Logf("JSONL content: %s", string(jsonlData))
|
||||
|
||||
// Double-check what's in SQLite
|
||||
directIssue, _ := clone2Store.GetIssue(ctx, issueID)
|
||||
t.Logf("SQLite status: %s", directIssue.Status)
|
||||
}
|
||||
})
|
||||
|
||||
// Additional test: Verify multiple rapid changes
|
||||
t.Run("DaemonHandlesRapidUpdates", func(t *testing.T) {
|
||||
// Agent A updates priority
|
||||
if err := clone1Store.UpdateIssue(ctx, issueID, map[string]interface{}{
|
||||
"priority": 0,
|
||||
}, "agent-a"); err != nil {
|
||||
t.Fatalf("Failed to update priority: %v", err)
|
||||
}
|
||||
|
||||
if err := exportIssuesToJSONL(ctx, clone1Store, jsonlPath); err != nil {
|
||||
t.Fatalf("Failed to export: %v", err)
|
||||
}
|
||||
|
||||
runGitCmd(t, clone1Dir, "add", ".beads/issues.jsonl")
|
||||
runGitCmd(t, clone1Dir, "commit", "-m", "Update priority")
|
||||
runGitCmd(t, clone1Dir, "push", "origin", "master")
|
||||
|
||||
// Agent B pulls
|
||||
runGitCmd(t, clone2Dir, "pull")
|
||||
|
||||
// Query via daemon - should see priority 0
|
||||
// (Execute forces auto-import synchronously)
|
||||
socketPath := filepath.Join(clone2BeadsDir, "bd.sock")
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to connect to daemon: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
client.SetDatabasePath(clone2DBPath) // Route to correct database
|
||||
|
||||
resp, err := client.Execute("show", map[string]string{"id": issueID})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get issue from daemon: %v", err)
|
||||
}
|
||||
|
||||
var issue types.Issue
|
||||
issueJSON, _ := json.Marshal(resp.Data)
|
||||
json.Unmarshal(issueJSON, &issue)
|
||||
|
||||
if issue.Priority != 0 {
|
||||
t.Errorf("Expected priority 0 after auto-import, got %d", issue.Priority)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestDaemonAutoImportDataCorruption tests the data corruption scenario
|
||||
// where Agent B's daemon overwrites Agent A's changes with stale data
|
||||
func TestDaemonAutoImportDataCorruption(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tempDir, err := os.MkdirTemp("", "bd-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tempDir)
|
||||
|
||||
// Setup remote and two clones
|
||||
remoteDir := filepath.Join(tempDir, "remote")
|
||||
os.MkdirAll(remoteDir, 0750)
|
||||
runGitCmd(t, remoteDir, "init", "--bare", "-b", "master")
|
||||
|
||||
clone1Dir := filepath.Join(tempDir, "clone1")
|
||||
runGitCmd(t, tempDir, "clone", remoteDir, clone1Dir)
|
||||
configureGit(t, clone1Dir)
|
||||
|
||||
clone2Dir := filepath.Join(tempDir, "clone2")
|
||||
runGitCmd(t, tempDir, "clone", remoteDir, clone2Dir)
|
||||
configureGit(t, clone2Dir)
|
||||
|
||||
// Initialize beads in both clones
|
||||
ctx := context.Background()
|
||||
|
||||
// Clone1 setup
|
||||
clone1BeadsDir := filepath.Join(clone1Dir, ".beads")
|
||||
os.MkdirAll(clone1BeadsDir, 0750)
|
||||
clone1DBPath := filepath.Join(clone1BeadsDir, "test.db")
|
||||
clone1Store := newTestStore(t, clone1DBPath)
|
||||
defer clone1Store.Close()
|
||||
clone1Store.SetMetadata(ctx, "issue_prefix", "test")
|
||||
|
||||
// Clone2 setup
|
||||
clone2BeadsDir := filepath.Join(clone2Dir, ".beads")
|
||||
os.MkdirAll(clone2BeadsDir, 0750)
|
||||
clone2DBPath := filepath.Join(clone2BeadsDir, "test.db")
|
||||
clone2Store := newTestStore(t, clone2DBPath)
|
||||
defer clone2Store.Close()
|
||||
clone2Store.SetMetadata(ctx, "issue_prefix", "test")
|
||||
|
||||
// Agent A creates issue and pushes
|
||||
issue2 := &types.Issue{
|
||||
Title: "Shared issue",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
clone1Store.CreateIssue(ctx, issue2, "agent-a")
|
||||
issueID := issue2.ID
|
||||
|
||||
clone1JSONLPath := filepath.Join(clone1BeadsDir, "issues.jsonl")
|
||||
exportIssuesToJSONL(ctx, clone1Store, clone1JSONLPath)
|
||||
runGitCmd(t, clone1Dir, "add", ".beads")
|
||||
runGitCmd(t, clone1Dir, "commit", "-m", "Initial issue")
|
||||
runGitCmd(t, clone1Dir, "push", "origin", "master")
|
||||
|
||||
// Agent B pulls and imports
|
||||
runGitCmd(t, clone2Dir, "pull")
|
||||
clone2JSONLPath := filepath.Join(clone2BeadsDir, "issues.jsonl")
|
||||
importJSONLToStore(ctx, clone2Store, clone2DBPath, clone2JSONLPath)
|
||||
|
||||
// THE CORRUPTION SCENARIO:
|
||||
// 1. Agent A closes the issue and pushes
|
||||
clone1Store.CloseIssue(ctx, issueID, "Done", "agent-a", "")
|
||||
exportIssuesToJSONL(ctx, clone1Store, clone1JSONLPath)
|
||||
runGitCmd(t, clone1Dir, "add", ".beads/issues.jsonl")
|
||||
runGitCmd(t, clone1Dir, "commit", "-m", "Close issue")
|
||||
runGitCmd(t, clone1Dir, "push", "origin", "master")
|
||||
|
||||
// 2. Agent B does git pull (JSONL updated on disk)
|
||||
runGitCmd(t, clone2Dir, "pull")
|
||||
|
||||
// Wait for filesystem to settle after git operations
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// 3. Agent B daemon exports STALE data (if auto-import doesn't work)
|
||||
// This would overwrite Agent A's closure with old "open" status
|
||||
|
||||
// Start daemon in clone2
|
||||
socketPath := filepath.Join(clone2BeadsDir, "bd.sock")
|
||||
os.Remove(socketPath)
|
||||
|
||||
server := rpc.NewServer(socketPath, clone2Store, clone2Dir, clone2DBPath)
|
||||
|
||||
serverCtx, serverCancel := context.WithCancel(context.Background())
|
||||
defer serverCancel()
|
||||
|
||||
go func() {
|
||||
if err := server.Start(serverCtx); err != nil {
|
||||
t.Logf("Server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for server
|
||||
for i := 0; i < 50; i++ {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if _, err := os.Stat(socketPath); err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger daemon operation (should auto-import first)
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to connect: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
client.SetDatabasePath(clone2DBPath)
|
||||
|
||||
resp, err := client.Execute("show", map[string]string{"id": issueID})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get issue: %v", err)
|
||||
}
|
||||
|
||||
var issue types.Issue
|
||||
issueJSON, _ := json.Marshal(resp.Data)
|
||||
json.Unmarshal(issueJSON, &issue)
|
||||
|
||||
status := issue.Status
|
||||
|
||||
// If daemon didn't auto-import, this would be "open" (stale)
|
||||
// With the fix, it should be "closed" (fresh from JSONL)
|
||||
if status != types.StatusClosed {
|
||||
t.Errorf("DATA CORRUPTION DETECTED: Daemon has stale status '%s' instead of 'closed'", status)
|
||||
t.Error("If daemon exports this stale data, it will overwrite Agent A's changes on next push")
|
||||
}
|
||||
|
||||
// Now simulate daemon export (which happens on timer)
|
||||
// With auto-import working, this export should have fresh data
|
||||
exportIssuesToJSONL(ctx, clone2Store, clone2JSONLPath)
|
||||
|
||||
// Read back JSONL to verify it has correct status
|
||||
data, _ := os.ReadFile(clone2JSONLPath)
|
||||
var exportedIssue types.Issue
|
||||
json.NewDecoder(bytes.NewReader(data)).Decode(&exportedIssue)
|
||||
|
||||
if exportedIssue.Status != types.StatusClosed {
|
||||
t.Errorf("CORRUPTION: Exported JSONL has wrong status '%s', would overwrite remote", exportedIssue.Status)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,145 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/sqlite"
|
||||
"github.com/steveyegge/beads/internal/syncbranch"
|
||||
)
|
||||
|
||||
// TestAutoPullDefaultFromYamlConfig verifies that autoPull defaults to true
|
||||
// when sync-branch is configured in config.yaml (not just SQLite).
|
||||
//
|
||||
// This test validates the fix for the bug where daemon.go:111-114 only checked
|
||||
// store.GetConfig("sync.branch") (SQLite), but sync-branch is typically set
|
||||
// in config.yaml (read via viper).
|
||||
//
|
||||
// Fix: daemon.go now uses syncbranch.IsConfigured() which checks env var and
|
||||
// config.yaml (the common case), providing correct autoPull behavior.
|
||||
func TestAutoPullDefaultFromYamlConfig(t *testing.T) {
|
||||
// Create temp directory structure
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create config.yaml with sync-branch set (the user's configuration)
|
||||
configYAML := `# Beads configuration
|
||||
sync-branch: beads-sync
|
||||
issue-prefix: test
|
||||
`
|
||||
configPath := filepath.Join(beadsDir, "config.yaml")
|
||||
if err := os.WriteFile(configPath, []byte(configYAML), 0644); err != nil {
|
||||
t.Fatalf("Failed to write config.yaml: %v", err)
|
||||
}
|
||||
|
||||
// Create a database WITHOUT sync.branch in the config table
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Verify: sync.branch is NOT set in SQLite
|
||||
dbSyncBranch, _ := testStore.GetConfig(ctx, "sync.branch")
|
||||
if dbSyncBranch != "" {
|
||||
t.Fatalf("Expected no sync.branch in database, got %q", dbSyncBranch)
|
||||
}
|
||||
|
||||
// Reinitialize config package to read from our test directory
|
||||
// This is what happens when bd daemon starts and reads config
|
||||
// Use t.Chdir which automatically restores the original directory on test cleanup
|
||||
t.Chdir(tmpDir)
|
||||
|
||||
// Reinitialize viper config to pick up the new config.yaml
|
||||
initConfigForTest(t)
|
||||
|
||||
// Verify: sync.branch is NOT set in SQLite (the scenario we're testing)
|
||||
t.Logf("sync-branch in config.yaml: beads-sync")
|
||||
t.Logf("sync.branch in SQLite: %q (expected empty)", dbSyncBranch)
|
||||
|
||||
// The fix: daemon.go uses syncbranch.IsConfigured() which checks env var and
|
||||
// config.yaml, not just SQLite. This should return true.
|
||||
autoPull := syncbranch.IsConfigured()
|
||||
t.Logf("syncbranch.IsConfigured() = %v", autoPull)
|
||||
|
||||
if !autoPull {
|
||||
t.Errorf("Expected syncbranch.IsConfigured()=true when sync-branch is in config.yaml, got false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoPullDefaultFromEnvVar verifies that env var override works correctly.
|
||||
// This test should PASS because the env var is checked first.
|
||||
func TestAutoPullDefaultFromEnvVar(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create database without sync.branch
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Set env var (highest priority)
|
||||
t.Setenv("BEADS_SYNC_BRANCH", "env-sync-branch")
|
||||
|
||||
// The daemon DOES check env var (line 97-98), so this path works
|
||||
// But it's in a separate code path from the YAML bug
|
||||
autoPullFromEnv := syncbranch.IsConfigured()
|
||||
|
||||
if !autoPullFromEnv {
|
||||
t.Errorf("Expected autoPull=true when BEADS_SYNC_BRANCH is set, got false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoPullDefaultFromSQLite verifies the legacy SQLite path still works.
|
||||
// This test should PASS because the SQLite path works (it's just not used by config.yaml users).
|
||||
func TestAutoPullDefaultFromSQLite(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create database WITH sync.branch
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Set sync.branch in SQLite (legacy configuration)
|
||||
if err := testStore.SetConfig(ctx, "sync.branch", "sqlite-sync-branch"); err != nil {
|
||||
t.Fatalf("Failed to set sync.branch in database: %v", err)
|
||||
}
|
||||
|
||||
// The current daemon code should work for this case
|
||||
var autoPullFromDB bool
|
||||
if syncBranch, err := testStore.GetConfig(ctx, "sync.branch"); err == nil && syncBranch != "" {
|
||||
autoPullFromDB = true
|
||||
}
|
||||
|
||||
if !autoPullFromDB {
|
||||
t.Errorf("Expected autoPull=true when sync.branch is in SQLite, got false")
|
||||
}
|
||||
|
||||
// Verify syncbranch.IsConfiguredWithDB also works
|
||||
autoPullFromHelper := syncbranch.IsConfiguredWithDB(dbPath)
|
||||
if !autoPullFromHelper {
|
||||
t.Errorf("Expected IsConfiguredWithDB=true when sync.branch is in SQLite, got false")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,333 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/storage/sqlite"
|
||||
)
|
||||
|
||||
// TestDaemonAutoSyncFromYAML verifies that daemon.auto-sync is read from config.yaml.
|
||||
func TestDaemonAutoSyncFromYAML(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create config.yaml with daemon.auto-sync: true
|
||||
configYAML := `daemon:
|
||||
auto-sync: true
|
||||
`
|
||||
configPath := filepath.Join(beadsDir, "config.yaml")
|
||||
if err := os.WriteFile(configPath, []byte(configYAML), 0644); err != nil {
|
||||
t.Fatalf("Failed to write config.yaml: %v", err)
|
||||
}
|
||||
|
||||
// Create database without daemon settings
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Change to temp directory and reinitialize config
|
||||
t.Chdir(tmpDir)
|
||||
initConfigForTest(t)
|
||||
|
||||
// Create a mock cobra command
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("auto-commit", false, "")
|
||||
cmd.Flags().Bool("auto-push", false, "")
|
||||
cmd.Flags().Bool("auto-pull", false, "")
|
||||
|
||||
// Test loadDaemonAutoSettings
|
||||
autoCommit, autoPush, autoPull := loadDaemonAutoSettings(cmd, false, false, false)
|
||||
|
||||
// auto-sync: true should enable all three
|
||||
if !autoCommit {
|
||||
t.Errorf("Expected autoCommit=true when daemon.auto-sync=true in YAML, got false")
|
||||
}
|
||||
if !autoPush {
|
||||
t.Errorf("Expected autoPush=true when daemon.auto-sync=true in YAML, got false")
|
||||
}
|
||||
if !autoPull {
|
||||
t.Errorf("Expected autoPull=true when daemon.auto-sync=true in YAML, got false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonAutoCommitOnlyFromYAML verifies that individual daemon.auto-commit works
|
||||
// without enabling auto-push and auto-pull.
|
||||
func TestDaemonAutoCommitOnlyFromYAML(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create config.yaml with only daemon.auto-commit: true
|
||||
configYAML := `daemon:
|
||||
auto-commit: true
|
||||
`
|
||||
configPath := filepath.Join(beadsDir, "config.yaml")
|
||||
if err := os.WriteFile(configPath, []byte(configYAML), 0644); err != nil {
|
||||
t.Fatalf("Failed to write config.yaml: %v", err)
|
||||
}
|
||||
|
||||
// Create database without daemon settings
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Change to temp directory and reinitialize config
|
||||
t.Chdir(tmpDir)
|
||||
initConfigForTest(t)
|
||||
|
||||
// Create a mock cobra command
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("auto-commit", false, "")
|
||||
cmd.Flags().Bool("auto-push", false, "")
|
||||
cmd.Flags().Bool("auto-pull", false, "")
|
||||
|
||||
// Test loadDaemonAutoSettings
|
||||
autoCommit, autoPush, autoPull := loadDaemonAutoSettings(cmd, false, false, false)
|
||||
|
||||
// Individual YAML settings should NOT enable other options
|
||||
if !autoCommit {
|
||||
t.Errorf("Expected autoCommit=true when daemon.auto-commit=true in YAML, got false")
|
||||
}
|
||||
if autoPush {
|
||||
t.Errorf("Expected autoPush=false when only daemon.auto-commit is set in YAML, got true")
|
||||
}
|
||||
if autoPull {
|
||||
t.Errorf("Expected autoPull=false when only daemon.auto-commit is set in YAML, got true")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonIndividualSettingsFromYAML verifies that individual settings can be
|
||||
// set independently via YAML config.
|
||||
func TestDaemonIndividualSettingsFromYAML(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create config.yaml with mixed individual settings
|
||||
configYAML := `daemon:
|
||||
auto-commit: true
|
||||
auto-push: false
|
||||
auto-pull: true
|
||||
`
|
||||
configPath := filepath.Join(beadsDir, "config.yaml")
|
||||
if err := os.WriteFile(configPath, []byte(configYAML), 0644); err != nil {
|
||||
t.Fatalf("Failed to write config.yaml: %v", err)
|
||||
}
|
||||
|
||||
// Create database without daemon settings
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Change to temp directory and reinitialize config
|
||||
t.Chdir(tmpDir)
|
||||
initConfigForTest(t)
|
||||
|
||||
// Create a mock cobra command
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("auto-commit", false, "")
|
||||
cmd.Flags().Bool("auto-push", false, "")
|
||||
cmd.Flags().Bool("auto-pull", false, "")
|
||||
|
||||
// Test loadDaemonAutoSettings
|
||||
autoCommit, autoPush, autoPull := loadDaemonAutoSettings(cmd, false, false, false)
|
||||
|
||||
if !autoCommit {
|
||||
t.Errorf("Expected autoCommit=true, got false")
|
||||
}
|
||||
if autoPush {
|
||||
t.Errorf("Expected autoPush=false, got true")
|
||||
}
|
||||
if !autoPull {
|
||||
t.Errorf("Expected autoPull=true, got false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonEnvVarOverridesYAML verifies that env vars take precedence over YAML config.
|
||||
func TestDaemonEnvVarOverridesYAML(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create config.yaml with daemon.auto-sync: true
|
||||
configYAML := `daemon:
|
||||
auto-sync: true
|
||||
`
|
||||
configPath := filepath.Join(beadsDir, "config.yaml")
|
||||
if err := os.WriteFile(configPath, []byte(configYAML), 0644); err != nil {
|
||||
t.Fatalf("Failed to write config.yaml: %v", err)
|
||||
}
|
||||
|
||||
// Create database
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Change to temp directory and reinitialize config
|
||||
t.Chdir(tmpDir)
|
||||
initConfigForTest(t)
|
||||
|
||||
// Set env var to override YAML (env var takes precedence)
|
||||
t.Setenv("BEADS_AUTO_SYNC", "false")
|
||||
|
||||
// Create a mock cobra command
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("auto-commit", false, "")
|
||||
cmd.Flags().Bool("auto-push", false, "")
|
||||
cmd.Flags().Bool("auto-pull", false, "")
|
||||
|
||||
// Test loadDaemonAutoSettings
|
||||
autoCommit, autoPush, _ := loadDaemonAutoSettings(cmd, false, false, false)
|
||||
|
||||
// Env var BEADS_AUTO_SYNC=false should override YAML auto-sync: true
|
||||
if autoCommit {
|
||||
t.Errorf("Expected autoCommit=false (env var override), got true")
|
||||
}
|
||||
if autoPush {
|
||||
t.Errorf("Expected autoPush=false (env var override), got true")
|
||||
}
|
||||
// auto-pull defaults based on other factors when auto-sync=false
|
||||
}
|
||||
|
||||
// TestDaemonCLIFlagOverridesYAML verifies that CLI flags take precedence over YAML config.
|
||||
func TestDaemonCLIFlagOverridesYAML(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create config.yaml with daemon settings
|
||||
configYAML := `daemon:
|
||||
auto-commit: true
|
||||
auto-push: true
|
||||
`
|
||||
configPath := filepath.Join(beadsDir, "config.yaml")
|
||||
if err := os.WriteFile(configPath, []byte(configYAML), 0644); err != nil {
|
||||
t.Fatalf("Failed to write config.yaml: %v", err)
|
||||
}
|
||||
|
||||
// Create database
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Change to temp directory and reinitialize config
|
||||
t.Chdir(tmpDir)
|
||||
initConfigForTest(t)
|
||||
|
||||
// Create a mock cobra command with flags explicitly set
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("auto-commit", false, "")
|
||||
cmd.Flags().Bool("auto-push", false, "")
|
||||
cmd.Flags().Bool("auto-pull", false, "")
|
||||
|
||||
// Simulate CLI flag being explicitly set
|
||||
_ = cmd.Flags().Set("auto-commit", "false")
|
||||
|
||||
// Test loadDaemonAutoSettings - CLI flag should override YAML config
|
||||
autoCommit, autoPush, autoPull := loadDaemonAutoSettings(cmd, false, false, false)
|
||||
|
||||
// CLI flag --auto-commit=false should override YAML auto-commit: true
|
||||
if autoCommit {
|
||||
t.Errorf("Expected autoCommit=false (CLI flag override), got true")
|
||||
}
|
||||
// auto-push should still come from YAML since flag wasn't changed
|
||||
if !autoPush {
|
||||
t.Errorf("Expected autoPush=true (from YAML), got false")
|
||||
}
|
||||
if autoPull {
|
||||
t.Errorf("Expected autoPull=false (not set), got true")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonIndividualEnvVarOverridesYAML verifies that individual env vars
|
||||
// (BEADS_AUTO_PULL) override individual YAML settings.
|
||||
func TestDaemonIndividualEnvVarOverridesYAML(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads directory: %v", err)
|
||||
}
|
||||
|
||||
// Create config.yaml with auto-commit: true and auto-pull: false
|
||||
configYAML := `daemon:
|
||||
auto-commit: true
|
||||
auto-pull: false
|
||||
`
|
||||
configPath := filepath.Join(beadsDir, "config.yaml")
|
||||
if err := os.WriteFile(configPath, []byte(configYAML), 0644); err != nil {
|
||||
t.Fatalf("Failed to write config.yaml: %v", err)
|
||||
}
|
||||
|
||||
// Create database
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Change to temp directory and reinitialize config
|
||||
t.Chdir(tmpDir)
|
||||
initConfigForTest(t)
|
||||
|
||||
// Set individual env var to override YAML (BEADS_AUTO_PULL should override daemon.auto-pull)
|
||||
t.Setenv("BEADS_AUTO_PULL", "true")
|
||||
|
||||
// Create a mock cobra command
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().Bool("auto-commit", false, "")
|
||||
cmd.Flags().Bool("auto-push", false, "")
|
||||
cmd.Flags().Bool("auto-pull", false, "")
|
||||
|
||||
// Test loadDaemonAutoSettings
|
||||
autoCommit, autoPush, autoPull := loadDaemonAutoSettings(cmd, false, false, false)
|
||||
|
||||
// auto-commit should come from YAML (true)
|
||||
if !autoCommit {
|
||||
t.Errorf("Expected autoCommit=true (from YAML), got false")
|
||||
}
|
||||
// auto-push should be false (not set anywhere)
|
||||
if autoPush {
|
||||
t.Errorf("Expected autoPush=false (not set), got true")
|
||||
}
|
||||
// auto-pull should be true (env var BEADS_AUTO_PULL=true overrides YAML auto-pull: false)
|
||||
if !autoPull {
|
||||
t.Errorf("Expected autoPull=true (env var override), got false")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,680 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/debug"
|
||||
"github.com/steveyegge/beads/internal/lockfile"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
||||
// daemonShutdownTimeout is how long to wait for graceful shutdown before force killing.
|
||||
// Daemon sync operations may involve git commits or database writes that take several
|
||||
// seconds, so we allow enough time for in-flight operations to complete gracefully.
|
||||
const daemonShutdownTimeout = 5 * time.Second
|
||||
|
||||
// daemonShutdownPollInterval is how often to check if daemon has stopped.
|
||||
const daemonShutdownPollInterval = 100 * time.Millisecond
|
||||
|
||||
// daemonShutdownAttempts is the number of poll attempts before force kill.
|
||||
const daemonShutdownAttempts = int(daemonShutdownTimeout / daemonShutdownPollInterval)
|
||||
|
||||
// Daemon start failure tracking for exponential backoff
|
||||
var (
|
||||
lastDaemonStartAttempt time.Time
|
||||
daemonStartFailures int
|
||||
)
|
||||
|
||||
var (
|
||||
executableFn = os.Executable
|
||||
execCommandFn = exec.Command
|
||||
openFileFn = os.OpenFile
|
||||
findProcessFn = os.FindProcess
|
||||
removeFileFn = os.Remove
|
||||
configureDaemonProcessFn = configureDaemonProcess
|
||||
waitForSocketReadinessFn = waitForSocketReadiness
|
||||
startDaemonProcessFn = startDaemonProcess
|
||||
isDaemonRunningFn = isDaemonRunning
|
||||
sendStopSignalFn = sendStopSignal
|
||||
isDoltBackendFn = isDoltBackendImpl
|
||||
singleProcessOnlyBackendFn = singleProcessOnlyBackendImpl
|
||||
)
|
||||
|
||||
// isDoltBackend returns true if the current workspace uses any Dolt backend mode.
|
||||
// The daemon is only needed for SQLite - Dolt has its own sync mechanism.
|
||||
// This is a wrapper that calls isDoltBackendFn for testability.
|
||||
func isDoltBackend() bool {
|
||||
return isDoltBackendFn()
|
||||
}
|
||||
|
||||
// isDoltBackendImpl is the actual implementation of isDoltBackend.
|
||||
func isDoltBackendImpl() bool {
|
||||
beadsDir := ""
|
||||
if dbPath != "" {
|
||||
beadsDir = filepath.Dir(dbPath)
|
||||
} else if found := beads.FindDatabasePath(); found != "" {
|
||||
beadsDir = filepath.Dir(found)
|
||||
} else {
|
||||
beadsDir = beads.FindBeadsDir()
|
||||
}
|
||||
if beadsDir == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
if err != nil || cfg == nil {
|
||||
return false
|
||||
}
|
||||
return cfg.GetBackend() == configfile.BackendDolt
|
||||
}
|
||||
|
||||
// singleProcessOnlyBackend returns true if the current workspace backend is configured
|
||||
// as single-process-only (currently Dolt embedded).
|
||||
// This is a wrapper that calls singleProcessOnlyBackendFn for testability.
|
||||
func singleProcessOnlyBackend() bool {
|
||||
return singleProcessOnlyBackendFn()
|
||||
}
|
||||
|
||||
// singleProcessOnlyBackendImpl is the actual implementation of singleProcessOnlyBackend.
|
||||
//
|
||||
// Best-effort: if we can't determine the backend, we return false and defer to other logic.
|
||||
func singleProcessOnlyBackendImpl() bool {
|
||||
// Prefer dbPath if set; it points to either .beads/<db>.db (sqlite) or .beads/dolt (dolt dir).
|
||||
beadsDir := ""
|
||||
if dbPath != "" {
|
||||
beadsDir = filepath.Dir(dbPath)
|
||||
} else if found := beads.FindDatabasePath(); found != "" {
|
||||
beadsDir = filepath.Dir(found)
|
||||
} else {
|
||||
beadsDir = beads.FindBeadsDir()
|
||||
}
|
||||
if beadsDir == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
if err != nil || cfg == nil {
|
||||
return false
|
||||
}
|
||||
// Use GetCapabilities() to properly handle Dolt server mode
|
||||
return cfg.GetCapabilities().SingleProcessOnly
|
||||
}
|
||||
|
||||
// shouldAutoStartDaemon checks if daemon auto-start is enabled
|
||||
func shouldAutoStartDaemon() bool {
|
||||
// Dolt backend doesn't need daemon - it has its own sync via dolt sql-server.
|
||||
// This applies to both embedded and server modes.
|
||||
if isDoltBackend() {
|
||||
return false
|
||||
}
|
||||
|
||||
// For other backends, check SingleProcessOnly capability
|
||||
if singleProcessOnlyBackend() {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check BEADS_NO_DAEMON first (escape hatch for single-user workflows)
|
||||
noDaemon := strings.ToLower(strings.TrimSpace(os.Getenv("BEADS_NO_DAEMON")))
|
||||
if noDaemon == "1" || noDaemon == "true" || noDaemon == "yes" || noDaemon == "on" {
|
||||
return false // Explicit opt-out
|
||||
}
|
||||
|
||||
// Check if we're in a git worktree without sync-branch configured.
|
||||
// In this case, daemon is unsafe because all worktrees share the same
|
||||
// .beads directory and the daemon would commit to the wrong branch.
|
||||
// When sync-branch is configured, daemon is safe because commits go
|
||||
// to a dedicated branch via an internal worktree.
|
||||
if shouldDisableDaemonForWorktree() {
|
||||
return false
|
||||
}
|
||||
|
||||
// Use viper to read from config file or BEADS_AUTO_START_DAEMON env var
|
||||
// Viper handles BEADS_AUTO_START_DAEMON automatically via BindEnv
|
||||
return config.GetBool("auto-start-daemon") // Defaults to true
|
||||
}
|
||||
|
||||
// restartDaemonForVersionMismatch stops the old daemon and starts a new one
|
||||
// Returns true if restart was successful
|
||||
func restartDaemonForVersionMismatch() bool {
|
||||
// Dolt backend doesn't need daemon - it has its own sync mechanism.
|
||||
if isDoltBackend() {
|
||||
debugLog("dolt backend: skipping daemon restart for version mismatch")
|
||||
return false
|
||||
}
|
||||
|
||||
// For other backends, check SingleProcessOnly capability
|
||||
if singleProcessOnlyBackend() {
|
||||
debugLog("single-process backend: skipping daemon restart for version mismatch")
|
||||
return false
|
||||
}
|
||||
|
||||
pidFile, err := getPIDFilePath()
|
||||
if err != nil {
|
||||
debug.Logf("failed to get PID file path: %v", err)
|
||||
return false
|
||||
}
|
||||
|
||||
socketPath := getSocketPath()
|
||||
|
||||
// Check if daemon is running and stop it
|
||||
forcedKill := false
|
||||
if isRunning, pid := isDaemonRunningFn(pidFile); isRunning {
|
||||
debug.Logf("stopping old daemon (PID %d)", pid)
|
||||
|
||||
process, err := findProcessFn(pid)
|
||||
if err != nil {
|
||||
debug.Logf("failed to find process: %v", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// Send stop signal
|
||||
if err := sendStopSignalFn(process); err != nil {
|
||||
debug.Logf("failed to signal daemon: %v", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// Wait for daemon to stop, then force kill
|
||||
for i := 0; i < daemonShutdownAttempts; i++ {
|
||||
time.Sleep(daemonShutdownPollInterval)
|
||||
if isRunning, _ := isDaemonRunningFn(pidFile); !isRunning {
|
||||
debug.Logf("old daemon stopped successfully")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Force kill if still running
|
||||
if isRunning, _ := isDaemonRunningFn(pidFile); isRunning {
|
||||
debug.Logf("force killing old daemon")
|
||||
_ = process.Kill()
|
||||
forcedKill = true
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up stale socket and PID file after force kill or if not running
|
||||
if forcedKill || !isDaemonRunningQuiet(pidFile) {
|
||||
_ = removeFileFn(socketPath)
|
||||
_ = removeFileFn(pidFile)
|
||||
}
|
||||
|
||||
// Start new daemon with current binary version
|
||||
exe, err := executableFn()
|
||||
if err != nil {
|
||||
debug.Logf("failed to get executable path: %v", err)
|
||||
return false
|
||||
}
|
||||
|
||||
args := []string{"daemon", "start"}
|
||||
cmd := execCommandFn(exe, args...)
|
||||
cmd.Env = append(os.Environ(), "BD_DAEMON_FOREGROUND=1")
|
||||
|
||||
// Set working directory to database directory so daemon finds correct DB
|
||||
if dbPath != "" {
|
||||
cmd.Dir = filepath.Dir(dbPath)
|
||||
}
|
||||
|
||||
configureDaemonProcessFn(cmd)
|
||||
|
||||
devNull, err := openFileFn(os.DevNull, os.O_RDWR, 0)
|
||||
if err == nil {
|
||||
cmd.Stdin = devNull
|
||||
cmd.Stdout = devNull
|
||||
cmd.Stderr = devNull
|
||||
defer func() { _ = devNull.Close() }()
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
debug.Logf("failed to start new daemon: %v", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// Reap the process to avoid zombies
|
||||
go func() { _ = cmd.Wait() }()
|
||||
|
||||
// Wait for daemon to be ready using shared helper
|
||||
if waitForSocketReadinessFn(socketPath, 5*time.Second) {
|
||||
debug.Logf("new daemon started successfully")
|
||||
return true
|
||||
}
|
||||
|
||||
debug.Logf("new daemon failed to become ready")
|
||||
fmt.Fprintf(os.Stderr, "%s Daemon restart timed out (>5s). Running in direct mode.\n", ui.RenderWarn("Warning:"))
|
||||
fmt.Fprintf(os.Stderr, " %s Run 'bd doctor' to diagnose daemon issues\n", ui.RenderMuted("Hint:"))
|
||||
return false
|
||||
}
|
||||
|
||||
// isDaemonRunningQuiet checks if daemon is running without output
|
||||
func isDaemonRunningQuiet(pidFile string) bool {
|
||||
isRunning, _ := isDaemonRunningFn(pidFile)
|
||||
return isRunning
|
||||
}
|
||||
|
||||
// tryAutoStartDaemon attempts to start the daemon in the background
|
||||
// Returns true if daemon was started successfully and socket is ready
|
||||
func tryAutoStartDaemon(socketPath string) bool {
|
||||
// Dolt backend doesn't need daemon - it has its own sync mechanism.
|
||||
if isDoltBackend() {
|
||||
return false
|
||||
}
|
||||
|
||||
// For other backends, check SingleProcessOnly capability
|
||||
if singleProcessOnlyBackend() {
|
||||
return false
|
||||
}
|
||||
|
||||
// Empty dbPath causes filepath.Dir("") to return "." which breaks lock
|
||||
// file operations. This can happen when metadata.json has an empty database
|
||||
// field and no beads.db file exists. Skip daemon start gracefully.
|
||||
if dbPath == "" {
|
||||
debugLog("skipping auto-start: no database path configured")
|
||||
return false
|
||||
}
|
||||
|
||||
if !canRetryDaemonStart() {
|
||||
debugLog("skipping auto-start due to recent failures")
|
||||
return false
|
||||
}
|
||||
|
||||
if isDaemonHealthy(socketPath) {
|
||||
debugLog("daemon already running and healthy")
|
||||
return true
|
||||
}
|
||||
|
||||
lockPath := socketPath + ".startlock"
|
||||
if !acquireStartLock(lockPath, socketPath) {
|
||||
return false
|
||||
}
|
||||
defer func() {
|
||||
if err := os.Remove(lockPath); err != nil && !os.IsNotExist(err) {
|
||||
debugLog("failed to remove lock file: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
if handleExistingSocket(socketPath) {
|
||||
return true
|
||||
}
|
||||
|
||||
socketPath = determineSocketPath(socketPath)
|
||||
return startDaemonProcessFn(socketPath)
|
||||
}
|
||||
|
||||
func debugLog(msg string, args ...interface{}) {
|
||||
debug.Logf(msg, args...)
|
||||
}
|
||||
|
||||
func isDaemonHealthy(socketPath string) bool {
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err == nil && client != nil {
|
||||
_ = client.Close()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func acquireStartLock(lockPath, socketPath string) bool {
|
||||
if err := ensureLockDirectory(lockPath); err != nil {
|
||||
debugLog("failed to ensure lock directory: %v", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// Bounded retry loop to prevent infinite recursion when lock cleanup fails
|
||||
const maxRetries = 3
|
||||
for attempt := 0; attempt < maxRetries; attempt++ {
|
||||
// nolint:gosec // G304: lockPath is derived from secure beads directory
|
||||
lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err == nil {
|
||||
// Successfully acquired lock
|
||||
_, _ = fmt.Fprintf(lockFile, "%d\n", os.Getpid())
|
||||
_ = lockFile.Close() // Best-effort close during startup
|
||||
return true
|
||||
}
|
||||
|
||||
// Lock file exists - check if daemon is actually starting
|
||||
lockPID, pidErr := readPIDFromFile(lockPath)
|
||||
if pidErr != nil || !isPIDAlive(lockPID) {
|
||||
// Stale lock from crashed process - clean up immediately (avoids 5s wait)
|
||||
debugLog("startlock is stale (PID %d dead or unreadable), cleaning up", lockPID)
|
||||
if rmErr := removeFileFn(lockPath); rmErr != nil {
|
||||
debugLog("failed to remove stale lock file: %v", rmErr)
|
||||
return false // Can't acquire lock if we can't clean up
|
||||
}
|
||||
// Continue to next iteration to retry lock acquisition
|
||||
continue
|
||||
}
|
||||
|
||||
// PID is alive - but is daemon actually running/starting?
|
||||
// Use flock-based check as authoritative source (immune to PID reuse)
|
||||
beadsDir := filepath.Dir(dbPath)
|
||||
if running, _ := lockfile.TryDaemonLock(beadsDir); !running {
|
||||
// Daemon lock not held - the start attempt failed or process was reused
|
||||
debugLog("startlock PID %d alive but daemon lock not held, cleaning up", lockPID)
|
||||
if rmErr := removeFileFn(lockPath); rmErr != nil {
|
||||
debugLog("failed to remove orphaned lock file: %v", rmErr)
|
||||
return false // Can't acquire lock if we can't clean up
|
||||
}
|
||||
// Continue to next iteration to retry lock acquisition
|
||||
continue
|
||||
}
|
||||
|
||||
// Daemon lock is held - daemon is legitimately starting, wait for socket
|
||||
debugLog("another process (PID %d) is starting daemon, waiting for readiness", lockPID)
|
||||
if waitForSocketReadiness(socketPath, 5*time.Second) {
|
||||
return true
|
||||
}
|
||||
return handleStaleLock(lockPath)
|
||||
}
|
||||
|
||||
debugLog("failed to acquire start lock after %d attempts", maxRetries)
|
||||
return false
|
||||
}
|
||||
|
||||
func handleStaleLock(lockPath string) bool {
|
||||
lockPID, err := readPIDFromFile(lockPath)
|
||||
|
||||
// Check if PID is dead
|
||||
if err != nil || !isPIDAlive(lockPID) {
|
||||
debugLog("lock is stale (PID %d dead or unreadable), removing", lockPID)
|
||||
if rmErr := removeFileFn(lockPath); rmErr != nil {
|
||||
debugLog("failed to remove stale lock in handleStaleLock: %v", rmErr)
|
||||
}
|
||||
// Return false to let caller retry. DO NOT call tryAutoStartDaemon here
|
||||
// to avoid infinite recursion: acquireStartLock -> handleStaleLock ->
|
||||
// tryAutoStartDaemon -> acquireStartLock -> ...
|
||||
return false
|
||||
}
|
||||
|
||||
// PID is alive - but check daemon lock as authoritative source (immune to PID reuse)
|
||||
beadsDir := filepath.Dir(dbPath)
|
||||
if running, _ := lockfile.TryDaemonLock(beadsDir); !running {
|
||||
debugLog("lock PID %d alive but daemon lock not held, removing", lockPID)
|
||||
if rmErr := removeFileFn(lockPath); rmErr != nil {
|
||||
debugLog("failed to remove orphaned lock in handleStaleLock: %v", rmErr)
|
||||
}
|
||||
// Return false to let caller retry. DO NOT call tryAutoStartDaemon here
|
||||
// to avoid infinite recursion.
|
||||
return false
|
||||
}
|
||||
|
||||
// Daemon lock is held - daemon is genuinely running but socket isn't ready
|
||||
// This shouldn't happen normally, but don't clean up a legitimate lock
|
||||
return false
|
||||
}
|
||||
|
||||
func handleExistingSocket(socketPath string) bool {
|
||||
if _, err := os.Stat(socketPath); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if canDialSocket(socketPath, 200*time.Millisecond) {
|
||||
debugLog("daemon started by another process")
|
||||
return true
|
||||
}
|
||||
|
||||
// Use flock-based check as authoritative source (immune to PID reuse)
|
||||
// If daemon lock is not held, daemon is definitely dead regardless of PID file
|
||||
beadsDir := filepath.Dir(dbPath)
|
||||
if running, pid := lockfile.TryDaemonLock(beadsDir); running {
|
||||
debugLog("daemon lock held (PID %d), waiting for socket", pid)
|
||||
return waitForSocketReadiness(socketPath, 5*time.Second)
|
||||
}
|
||||
|
||||
// Lock not held - daemon is dead, clean up stale artifacts
|
||||
debugLog("socket is stale (daemon lock not held), cleaning up")
|
||||
_ = os.Remove(socketPath) // Best-effort cleanup, file may not exist
|
||||
pidFile := getPIDFileForSocket(socketPath)
|
||||
if pidFile != "" {
|
||||
_ = os.Remove(pidFile) // Best-effort cleanup, file may not exist
|
||||
}
|
||||
// Also clean up daemon.lock file (contains stale metadata)
|
||||
lockFile := filepath.Join(beadsDir, "daemon.lock")
|
||||
_ = os.Remove(lockFile) // Best-effort cleanup
|
||||
return false
|
||||
}
|
||||
|
||||
func determineSocketPath(socketPath string) string {
|
||||
return socketPath
|
||||
}
|
||||
|
||||
// ensureLockDirectory ensures the parent directory exists for the lock file.
|
||||
// Needed when ShortSocketPath routes sockets into /tmp/beads-*/bd.sock.
|
||||
func ensureLockDirectory(lockPath string) error {
|
||||
dir := filepath.Dir(lockPath)
|
||||
if dir == "" {
|
||||
return fmt.Errorf("lock directory missing for %s", lockPath)
|
||||
}
|
||||
if _, err := os.Stat(dir); err == nil {
|
||||
return nil
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
return os.MkdirAll(dir, 0o700)
|
||||
}
|
||||
|
||||
func startDaemonProcess(socketPath string) bool {
|
||||
// Dolt backend doesn't need daemon - it has its own sync mechanism.
|
||||
if isDoltBackend() {
|
||||
debugLog("dolt backend: skipping daemon start")
|
||||
return false
|
||||
}
|
||||
|
||||
// For other backends, check SingleProcessOnly capability
|
||||
if singleProcessOnlyBackend() {
|
||||
debugLog("single-process backend: skipping daemon start")
|
||||
return false
|
||||
}
|
||||
|
||||
// Early check: daemon requires a git repository (unless --local mode)
|
||||
// Skip attempting to start and avoid the 5-second wait if not in git repo
|
||||
if !isGitRepo() {
|
||||
debugLog("not in a git repository, skipping daemon start")
|
||||
if !quietFlag {
|
||||
fmt.Fprintf(os.Stderr, "%s No git repository initialized - running without background sync\n", ui.RenderMuted("Note:"))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
binPath, err := executableFn()
|
||||
if err != nil {
|
||||
binPath = os.Args[0]
|
||||
}
|
||||
|
||||
// Keep sqlite auto-start behavior unchanged: start the daemon via the public
|
||||
// `bd daemon start` entrypoint (it will daemonize itself as needed).
|
||||
args := []string{"daemon", "start"}
|
||||
|
||||
cmd := execCommandFn(binPath, args...)
|
||||
// Mark this as a daemon-foreground child so we don't track/kill based on the
|
||||
// short-lived launcher process PID (see computeDaemonParentPID()).
|
||||
// Also force the daemon to bind the same socket we're probing for readiness,
|
||||
// avoiding any mismatch between workspace-derived paths.
|
||||
cmd.Env = append(os.Environ(),
|
||||
"BD_DAEMON_FOREGROUND=1",
|
||||
"BD_SOCKET="+socketPath,
|
||||
)
|
||||
setupDaemonIO(cmd)
|
||||
|
||||
if dbPath != "" {
|
||||
cmd.Dir = filepath.Dir(dbPath)
|
||||
}
|
||||
|
||||
configureDaemonProcessFn(cmd)
|
||||
if err := cmd.Start(); err != nil {
|
||||
recordDaemonStartFailure()
|
||||
debugLog("failed to start daemon: %v", err)
|
||||
return false
|
||||
}
|
||||
|
||||
go func() { _ = cmd.Wait() }()
|
||||
|
||||
if waitForSocketReadinessFn(socketPath, 5*time.Second) {
|
||||
recordDaemonStartSuccess()
|
||||
return true
|
||||
}
|
||||
|
||||
recordDaemonStartFailure()
|
||||
debugLog("daemon socket not ready after 5 seconds")
|
||||
|
||||
// Check for daemon-error file which contains the actual failure reason
|
||||
beadsDir := filepath.Dir(dbPath)
|
||||
errFile := filepath.Join(beadsDir, "daemon-error")
|
||||
if errContent, err := os.ReadFile(errFile); err == nil && len(errContent) > 0 {
|
||||
// Show the actual error from the daemon
|
||||
fmt.Fprintf(os.Stderr, "%s Daemon failed to start:\n", ui.RenderWarn("Warning:"))
|
||||
fmt.Fprintf(os.Stderr, "%s\n", string(errContent))
|
||||
return false
|
||||
}
|
||||
|
||||
// Emit visible warning so user understands why command was slow
|
||||
fmt.Fprintf(os.Stderr, "%s Daemon took too long to start (>5s). Running in direct mode.\n", ui.RenderWarn("Warning:"))
|
||||
fmt.Fprintf(os.Stderr, " %s Run 'bd doctor' to diagnose daemon issues\n", ui.RenderMuted("Hint:"))
|
||||
return false
|
||||
}
|
||||
|
||||
func setupDaemonIO(cmd *exec.Cmd) {
|
||||
devNull, err := openFileFn(os.DevNull, os.O_RDWR, 0)
|
||||
if err == nil {
|
||||
cmd.Stdout = devNull
|
||||
cmd.Stderr = devNull
|
||||
cmd.Stdin = devNull
|
||||
// Do not close devNull: the daemon process inherits this fd and may
|
||||
// use it beyond the caller's lifetime. Closing on a timer races with
|
||||
// the child process and risks writing to a reused fd number.
|
||||
// A single /dev/null fd is a trivial resource reclaimed at exit.
|
||||
}
|
||||
}
|
||||
|
||||
// getPIDFileForSocket returns the PID file path.
|
||||
// Note: socketPath parameter is unused - PID file is always in .beads directory
|
||||
// (not socket directory, which may be in /tmp for short paths).
|
||||
func getPIDFileForSocket(_ string) string {
|
||||
dir := filepath.Dir(dbPath)
|
||||
return filepath.Join(dir, "daemon.pid")
|
||||
}
|
||||
|
||||
// readPIDFromFile reads a PID from a file
|
||||
func readPIDFromFile(path string) (int, error) {
|
||||
// nolint:gosec // G304: path is derived from secure beads directory
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return pid, nil
|
||||
}
|
||||
|
||||
// isPIDAlive checks if a process with the given PID is running
|
||||
func isPIDAlive(pid int) bool {
|
||||
if pid <= 0 {
|
||||
return false
|
||||
}
|
||||
return isProcessRunning(pid)
|
||||
}
|
||||
|
||||
// canDialSocket attempts a quick dial to the socket with a timeout
|
||||
func canDialSocket(socketPath string, timeout time.Duration) bool {
|
||||
client, err := rpc.TryConnectWithTimeout(socketPath, timeout)
|
||||
if err != nil || client == nil {
|
||||
return false
|
||||
}
|
||||
_ = client.Close() // Best-effort close after health check
|
||||
return true
|
||||
}
|
||||
|
||||
// waitForSocketReadiness waits for daemon socket to be ready by testing actual connections
|
||||
//
|
||||
//nolint:unparam // timeout is configurable even though current callers use 5s
|
||||
func waitForSocketReadiness(socketPath string, timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if canDialSocket(socketPath, 200*time.Millisecond) {
|
||||
return true
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func canRetryDaemonStart() bool {
|
||||
if daemonStartFailures == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
// Exponential backoff: 5s, 10s, 20s, 40s, 80s, 120s (capped at 120s)
|
||||
backoff := time.Duration(5*(1<<uint(daemonStartFailures-1))) * time.Second
|
||||
if backoff > 120*time.Second {
|
||||
backoff = 120 * time.Second
|
||||
}
|
||||
|
||||
return time.Since(lastDaemonStartAttempt) > backoff
|
||||
}
|
||||
|
||||
func recordDaemonStartSuccess() {
|
||||
daemonStartFailures = 0
|
||||
}
|
||||
|
||||
func recordDaemonStartFailure() {
|
||||
lastDaemonStartAttempt = time.Now()
|
||||
daemonStartFailures++
|
||||
// No cap needed - backoff is capped at 120s in canRetryDaemonStart
|
||||
}
|
||||
|
||||
// getSocketPath returns the daemon socket path based on the database location.
|
||||
// If BD_SOCKET env var is set, uses that value instead (enables test isolation).
|
||||
// On Unix systems, uses rpc.ShortSocketPath to avoid exceeding socket path limits
|
||||
// (macOS: 104 chars) by relocating long paths to /tmp/beads-{hash}/ (GH#1001).
|
||||
func getSocketPath() string {
|
||||
// Check environment variable first (enables test isolation)
|
||||
if socketPath := os.Getenv("BD_SOCKET"); socketPath != "" {
|
||||
return socketPath
|
||||
}
|
||||
// Get workspace path (parent of .beads directory)
|
||||
beadsDir := filepath.Dir(dbPath)
|
||||
workspacePath := filepath.Dir(beadsDir)
|
||||
return rpc.ShortSocketPath(workspacePath)
|
||||
}
|
||||
|
||||
// emitVerboseWarning prints a one-line warning when falling back to direct mode
|
||||
func emitVerboseWarning() {
|
||||
switch daemonStatus.FallbackReason {
|
||||
case FallbackConnectFailed:
|
||||
fmt.Fprintf(os.Stderr, "Warning: Daemon unreachable at %s. Running in direct mode. Hint: bd daemon status\n", daemonStatus.SocketPath)
|
||||
case FallbackHealthFailed:
|
||||
fmt.Fprintf(os.Stderr, "Warning: Daemon unhealthy. Falling back to direct mode. Hint: bd daemon status --all\n")
|
||||
case FallbackAutoStartDisabled:
|
||||
fmt.Fprintf(os.Stderr, "Warning: Auto-start disabled (BEADS_AUTO_START_DAEMON=false). Running in direct mode. Hint: bd daemon\n")
|
||||
case FallbackAutoStartFailed:
|
||||
fmt.Fprintf(os.Stderr, "Warning: Failed to auto-start daemon. Running in direct mode. Hint: bd daemon status\n")
|
||||
case FallbackDaemonUnsupported:
|
||||
fmt.Fprintf(os.Stderr, "Warning: Daemon does not support this command yet. Running in direct mode. Hint: update daemon or use local mode.\n")
|
||||
case FallbackWorktreeSafety:
|
||||
// Don't warn - this is expected behavior. User can configure sync-branch to enable daemon.
|
||||
return
|
||||
case FallbackSingleProcessOnly:
|
||||
// Don't warn - daemon is intentionally disabled for single-process backends (e.g., Dolt).
|
||||
return
|
||||
case FallbackFlagNoDaemon:
|
||||
// Don't warn when user explicitly requested --no-daemon
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func getDebounceDuration() time.Duration {
|
||||
duration := config.GetDuration("flush-debounce")
|
||||
if duration == 0 {
|
||||
// If parsing failed, use default
|
||||
return 5 * time.Second
|
||||
}
|
||||
return duration
|
||||
}
|
||||
|
|
@ -1,667 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
)
|
||||
|
||||
func tempSockDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
|
||||
base := "/tmp"
|
||||
if runtime.GOOS == windowsOS {
|
||||
base = os.TempDir()
|
||||
} else if _, err := os.Stat(base); err != nil {
|
||||
base = os.TempDir()
|
||||
}
|
||||
|
||||
d, err := os.MkdirTemp(base, "bd-sock-*")
|
||||
if err != nil {
|
||||
t.Fatalf("MkdirTemp: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.RemoveAll(d) })
|
||||
return d
|
||||
}
|
||||
|
||||
func startTestRPCServer(t *testing.T) (socketPath string, cleanup func()) {
|
||||
t.Helper()
|
||||
|
||||
if isSandboxed() {
|
||||
t.Skip("sandboxed environment blocks unix socket operations")
|
||||
}
|
||||
|
||||
tmpDir := tempSockDir(t)
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
|
||||
t.Fatalf("MkdirAll: %v", err)
|
||||
}
|
||||
|
||||
socketPath = filepath.Join(beadsDir, "bd.sock")
|
||||
db := filepath.Join(beadsDir, "test.db")
|
||||
store := newTestStore(t, db)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
log := newTestLogger()
|
||||
|
||||
server, _, err := startRPCServer(ctx, socketPath, store, tmpDir, db, log)
|
||||
if err != nil {
|
||||
if errors.Is(err, syscall.EPERM) || errors.Is(err, syscall.EACCES) || os.IsPermission(err) {
|
||||
cancel()
|
||||
t.Skipf("unix sockets not permitted in this environment: %v", err)
|
||||
}
|
||||
cancel()
|
||||
t.Fatalf("startRPCServer: %v", err)
|
||||
}
|
||||
|
||||
cleanup = func() {
|
||||
cancel()
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
return socketPath, cleanup
|
||||
}
|
||||
|
||||
func captureStderr(t *testing.T, fn func()) string {
|
||||
t.Helper()
|
||||
|
||||
old := os.Stderr
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatalf("os.Pipe: %v", err)
|
||||
}
|
||||
os.Stderr = w
|
||||
|
||||
var buf bytes.Buffer
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_, _ = io.Copy(&buf, r)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
fn()
|
||||
_ = w.Close()
|
||||
os.Stderr = old
|
||||
<-done
|
||||
_ = r.Close()
|
||||
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_AcquireStartLock_CreatesAndCleansStale(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := t.TempDir()
|
||||
lockPath := filepath.Join(tmpDir, "bd.sock.startlock")
|
||||
pid, err := readPIDFromFile(lockPath)
|
||||
if err == nil || pid != 0 {
|
||||
// lock doesn't exist yet; expect read to fail.
|
||||
}
|
||||
|
||||
if !acquireStartLock(lockPath, filepath.Join(tmpDir, "bd.sock")) {
|
||||
t.Fatalf("expected acquireStartLock to succeed")
|
||||
}
|
||||
got, err := readPIDFromFile(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("readPIDFromFile: %v", err)
|
||||
}
|
||||
if got != os.Getpid() {
|
||||
t.Fatalf("expected lock PID %d, got %d", os.Getpid(), got)
|
||||
}
|
||||
|
||||
// Stale lock: dead/unreadable PID should be removed and recreated.
|
||||
if err := os.WriteFile(lockPath, []byte("0\n"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile: %v", err)
|
||||
}
|
||||
if !acquireStartLock(lockPath, filepath.Join(tmpDir, "bd.sock")) {
|
||||
t.Fatalf("expected acquireStartLock to succeed on stale lock")
|
||||
}
|
||||
got, err = readPIDFromFile(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("readPIDFromFile: %v", err)
|
||||
}
|
||||
if got != os.Getpid() {
|
||||
t.Fatalf("expected recreated lock PID %d, got %d", os.Getpid(), got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_AcquireStartLock_CreatesMissingDir(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := t.TempDir()
|
||||
socketPath := filepath.Join(tmpDir, "missing", "bd.sock")
|
||||
lockPath := socketPath + ".startlock"
|
||||
|
||||
if _, err := os.Stat(filepath.Dir(lockPath)); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected lock dir to be missing before test, got: %v", err)
|
||||
}
|
||||
|
||||
if !acquireStartLock(lockPath, socketPath) {
|
||||
t.Fatalf("expected acquireStartLock to succeed when directory missing")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(lockPath); err != nil {
|
||||
t.Fatalf("expected lock file to exist, stat error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_AcquireStartLock_FailsWhenRemoveFails(t *testing.T) {
|
||||
// This test verifies that acquireStartLock returns false (instead of
|
||||
// recursing infinitely) when os.Remove fails on a stale lock file.
|
||||
|
||||
oldRemove := removeFileFn
|
||||
defer func() { removeFileFn = oldRemove }()
|
||||
|
||||
// Stub removeFileFn to always fail
|
||||
removeFileFn = func(path string) error {
|
||||
return os.ErrPermission
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
lockPath := filepath.Join(tmpDir, "bd.sock.startlock")
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
|
||||
// Create a stale lock file with PID 0 (will be detected as dead)
|
||||
if err := os.WriteFile(lockPath, []byte("0\n"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile: %v", err)
|
||||
}
|
||||
|
||||
// acquireStartLock should return false since it can't remove the stale lock
|
||||
// Previously, this would cause infinite recursion and stack overflow
|
||||
if acquireStartLock(lockPath, socketPath) {
|
||||
t.Fatalf("expected acquireStartLock to fail when remove fails")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_SocketHealthAndReadiness(t *testing.T) {
|
||||
socketPath, cleanup := startTestRPCServer(t)
|
||||
defer cleanup()
|
||||
|
||||
if !canDialSocket(socketPath, 500*time.Millisecond) {
|
||||
t.Fatalf("expected canDialSocket to succeed")
|
||||
}
|
||||
if !isDaemonHealthy(socketPath) {
|
||||
t.Fatalf("expected isDaemonHealthy to succeed")
|
||||
}
|
||||
if !waitForSocketReadiness(socketPath, 500*time.Millisecond) {
|
||||
t.Fatalf("expected waitForSocketReadiness to succeed")
|
||||
}
|
||||
|
||||
missing := filepath.Join(tempSockDir(t), "missing.sock")
|
||||
if canDialSocket(missing, 50*time.Millisecond) {
|
||||
t.Fatalf("expected canDialSocket to fail")
|
||||
}
|
||||
if waitForSocketReadiness(missing, 200*time.Millisecond) {
|
||||
t.Fatalf("expected waitForSocketReadiness to time out")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_HandleExistingSocket(t *testing.T) {
|
||||
socketPath, cleanup := startTestRPCServer(t)
|
||||
defer cleanup()
|
||||
|
||||
if !handleExistingSocket(socketPath) {
|
||||
t.Fatalf("expected handleExistingSocket true for running daemon")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_HandleExistingSocket_StaleCleansUp(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
|
||||
t.Fatalf("MkdirAll: %v", err)
|
||||
}
|
||||
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
if err := os.WriteFile(socketPath, []byte("not-a-socket"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile socket: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(pidFile, []byte("0\n"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile pid: %v", err)
|
||||
}
|
||||
|
||||
if handleExistingSocket(socketPath) {
|
||||
t.Fatalf("expected false for stale socket")
|
||||
}
|
||||
if _, err := os.Stat(socketPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected socket removed")
|
||||
}
|
||||
if _, err := os.Stat(pidFile); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected pidfile removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_TryAutoStartDaemon_EarlyExits(t *testing.T) {
|
||||
oldFailures := daemonStartFailures
|
||||
oldLast := lastDaemonStartAttempt
|
||||
oldDbPath := dbPath
|
||||
defer func() {
|
||||
daemonStartFailures = oldFailures
|
||||
lastDaemonStartAttempt = oldLast
|
||||
dbPath = oldDbPath
|
||||
}()
|
||||
|
||||
// Set up a valid dbPath to pass the empty dbPath check (GH#1288)
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
|
||||
t.Fatalf("MkdirAll: %v", err)
|
||||
}
|
||||
dbPath = filepath.Join(beadsDir, "test.db")
|
||||
|
||||
daemonStartFailures = 1
|
||||
lastDaemonStartAttempt = time.Now()
|
||||
if tryAutoStartDaemon(filepath.Join(tmpDir, "bd.sock")) {
|
||||
t.Fatalf("expected tryAutoStartDaemon to skip due to backoff")
|
||||
}
|
||||
|
||||
daemonStartFailures = 0
|
||||
lastDaemonStartAttempt = time.Time{}
|
||||
socketPath, cleanup := startTestRPCServer(t)
|
||||
defer cleanup()
|
||||
// Update dbPath to match the test server's directory
|
||||
dbPath = filepath.Join(filepath.Dir(socketPath), "test.db")
|
||||
if !tryAutoStartDaemon(socketPath) {
|
||||
t.Fatalf("expected tryAutoStartDaemon true when daemon already healthy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_MiscHelpers(t *testing.T) {
|
||||
if determineSocketPath("/x") != "/x" {
|
||||
t.Fatalf("determineSocketPath should be identity")
|
||||
}
|
||||
|
||||
initConfigForTest(t)
|
||||
old := config.GetDuration("flush-debounce")
|
||||
defer config.Set("flush-debounce", old)
|
||||
|
||||
config.Set("flush-debounce", 0)
|
||||
if got := getDebounceDuration(); got != 5*time.Second {
|
||||
t.Fatalf("expected default debounce 5s, got %v", got)
|
||||
}
|
||||
config.Set("flush-debounce", 2*time.Second)
|
||||
if got := getDebounceDuration(); got != 2*time.Second {
|
||||
t.Fatalf("expected debounce 2s, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_EmitVerboseWarning(t *testing.T) {
|
||||
old := daemonStatus
|
||||
defer func() { daemonStatus = old }()
|
||||
|
||||
daemonStatus.SocketPath = "/tmp/bd.sock"
|
||||
for _, tt := range []struct {
|
||||
reason string
|
||||
shouldWrite bool
|
||||
}{
|
||||
{FallbackConnectFailed, true},
|
||||
{FallbackHealthFailed, true},
|
||||
{FallbackAutoStartDisabled, true},
|
||||
{FallbackAutoStartFailed, true},
|
||||
{FallbackDaemonUnsupported, true},
|
||||
{FallbackWorktreeSafety, false},
|
||||
{FallbackFlagNoDaemon, false},
|
||||
} {
|
||||
t.Run(tt.reason, func(t *testing.T) {
|
||||
daemonStatus.FallbackReason = tt.reason
|
||||
out := captureStderr(t, emitVerboseWarning)
|
||||
if tt.shouldWrite && out == "" {
|
||||
t.Fatalf("expected output")
|
||||
}
|
||||
if !tt.shouldWrite && out != "" {
|
||||
t.Fatalf("expected no output, got %q", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_StartDaemonProcess_Stubbed(t *testing.T) {
|
||||
oldExec := execCommandFn
|
||||
oldWait := waitForSocketReadinessFn
|
||||
oldCfg := configureDaemonProcessFn
|
||||
oldIsDolt := isDoltBackendFn
|
||||
oldSingleProcess := singleProcessOnlyBackendFn
|
||||
defer func() {
|
||||
execCommandFn = oldExec
|
||||
waitForSocketReadinessFn = oldWait
|
||||
configureDaemonProcessFn = oldCfg
|
||||
isDoltBackendFn = oldIsDolt
|
||||
singleProcessOnlyBackendFn = oldSingleProcess
|
||||
}()
|
||||
|
||||
// Stub out backend checks so they don't interfere with this test
|
||||
isDoltBackendFn = func() bool { return false }
|
||||
singleProcessOnlyBackendFn = func() bool { return false }
|
||||
|
||||
execCommandFn = func(string, ...string) *exec.Cmd {
|
||||
return exec.Command(os.Args[0], "-test.run=^$")
|
||||
}
|
||||
waitForSocketReadinessFn = func(string, time.Duration) bool { return true }
|
||||
configureDaemonProcessFn = func(*exec.Cmd) {}
|
||||
|
||||
if !startDaemonProcess(filepath.Join(t.TempDir(), "bd.sock")) {
|
||||
t.Fatalf("expected startDaemonProcess true when readiness stubbed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_StartDaemonProcess_NoGitRepo(t *testing.T) {
|
||||
// Test that startDaemonProcess returns false immediately when not in a git repo
|
||||
tmpDir := t.TempDir()
|
||||
oldDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Getwd: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = os.Chdir(oldDir)
|
||||
}()
|
||||
|
||||
// Change to a temp directory that is NOT a git repo
|
||||
if err := os.Chdir(tmpDir); err != nil {
|
||||
t.Fatalf("Chdir: %v", err)
|
||||
}
|
||||
|
||||
// Capture stderr to verify the message
|
||||
output := captureStderr(t, func() {
|
||||
result := startDaemonProcess(filepath.Join(tmpDir, "bd.sock"))
|
||||
if result {
|
||||
t.Errorf("expected startDaemonProcess to return false when not in git repo")
|
||||
}
|
||||
})
|
||||
|
||||
// Verify the correct message is shown
|
||||
if !strings.Contains(output, "No git repository initialized") {
|
||||
t.Errorf("expected output to contain 'No git repository initialized', got: %q", output)
|
||||
}
|
||||
if !strings.Contains(output, "running without background sync") {
|
||||
t.Errorf("expected output to contain 'running without background sync', got: %q", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_StartDaemonProcess_NoGitRepo_Quiet(t *testing.T) {
|
||||
// Test that startDaemonProcess suppresses the note when quietFlag is true
|
||||
tmpDir := t.TempDir()
|
||||
oldDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("Getwd: %v", err)
|
||||
}
|
||||
oldQuiet := quietFlag
|
||||
defer func() {
|
||||
_ = os.Chdir(oldDir)
|
||||
quietFlag = oldQuiet
|
||||
}()
|
||||
|
||||
// Change to a temp directory that is NOT a git repo
|
||||
if err := os.Chdir(tmpDir); err != nil {
|
||||
t.Fatalf("Chdir: %v", err)
|
||||
}
|
||||
|
||||
// Enable quiet mode
|
||||
quietFlag = true
|
||||
|
||||
// Capture stderr to verify the message is suppressed
|
||||
output := captureStderr(t, func() {
|
||||
result := startDaemonProcess(filepath.Join(tmpDir, "bd.sock"))
|
||||
if result {
|
||||
t.Errorf("expected startDaemonProcess to return false when not in git repo")
|
||||
}
|
||||
})
|
||||
|
||||
// Verify the message is NOT shown in quiet mode
|
||||
if strings.Contains(output, "No git repository initialized") {
|
||||
t.Errorf("expected no output in quiet mode, got: %q", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonAutostart_RestartDaemonForVersionMismatch_Stubbed(t *testing.T) {
|
||||
oldExec := execCommandFn
|
||||
oldWait := waitForSocketReadinessFn
|
||||
oldRun := isDaemonRunningFn
|
||||
oldCfg := configureDaemonProcessFn
|
||||
defer func() {
|
||||
execCommandFn = oldExec
|
||||
waitForSocketReadinessFn = oldWait
|
||||
isDaemonRunningFn = oldRun
|
||||
configureDaemonProcessFn = oldCfg
|
||||
}()
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
|
||||
t.Fatalf("MkdirAll: %v", err)
|
||||
}
|
||||
oldDB := dbPath
|
||||
defer func() { dbPath = oldDB }()
|
||||
dbPath = filepath.Join(beadsDir, "test.db")
|
||||
|
||||
pidFile, err := getPIDFilePath()
|
||||
if err != nil {
|
||||
t.Fatalf("getPIDFilePath: %v", err)
|
||||
}
|
||||
sock := getSocketPath()
|
||||
// Create socket directory if needed (GH#1001 - socket may be in /tmp/beads-{hash}/)
|
||||
sockDir := filepath.Dir(sock)
|
||||
if err := os.MkdirAll(sockDir, 0o750); err != nil {
|
||||
t.Fatalf("MkdirAll sockDir: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(pidFile, []byte("999999\n"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile pid: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(sock, []byte("stale"), 0o600); err != nil {
|
||||
t.Fatalf("WriteFile sock: %v", err)
|
||||
}
|
||||
|
||||
execCommandFn = func(string, ...string) *exec.Cmd {
|
||||
return exec.Command(os.Args[0], "-test.run=^$")
|
||||
}
|
||||
waitForSocketReadinessFn = func(string, time.Duration) bool { return true }
|
||||
isDaemonRunningFn = func(string) (bool, int) { return false, 0 }
|
||||
configureDaemonProcessFn = func(*exec.Cmd) {}
|
||||
|
||||
if !restartDaemonForVersionMismatch() {
|
||||
t.Fatalf("expected restartDaemonForVersionMismatch true when stubbed")
|
||||
}
|
||||
if _, err := os.Stat(pidFile); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected pidfile removed")
|
||||
}
|
||||
if _, err := os.Stat(sock); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected socket removed")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsWispOperation tests the wisp operation detection for auto-daemon-bypass (bd-ta4r)
|
||||
func TestIsWispOperation(t *testing.T) {
|
||||
t.Parallel()
|
||||
// Helper to create a command with parent hierarchy
|
||||
makeCmd := func(names ...string) *cobra.Command {
|
||||
var current *cobra.Command
|
||||
for i, name := range names {
|
||||
cmd := &cobra.Command{Use: name}
|
||||
if i == 0 {
|
||||
current = cmd
|
||||
} else {
|
||||
current.AddCommand(cmd)
|
||||
current = cmd
|
||||
}
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
cmdNames []string // hierarchy: root, child, grandchild...
|
||||
args []string
|
||||
want bool
|
||||
}{
|
||||
// Wisp subcommands
|
||||
{
|
||||
name: "mol wisp (direct)",
|
||||
cmdNames: []string{"bd", "mol", "wisp"},
|
||||
args: []string{},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "mol wisp create",
|
||||
cmdNames: []string{"bd", "mol", "wisp", "create"},
|
||||
args: []string{"some-proto"},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "mol wisp list",
|
||||
cmdNames: []string{"bd", "mol", "wisp", "list"},
|
||||
args: []string{},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "mol wisp gc",
|
||||
cmdNames: []string{"bd", "mol", "wisp", "gc"},
|
||||
args: []string{},
|
||||
want: true,
|
||||
},
|
||||
// mol burn and squash (wisp-only operations)
|
||||
{
|
||||
name: "mol burn",
|
||||
cmdNames: []string{"bd", "mol", "burn"},
|
||||
args: []string{"bd-wisp-abc"},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "mol squash",
|
||||
cmdNames: []string{"bd", "mol", "squash"},
|
||||
args: []string{"bd-wisp-abc"},
|
||||
want: true,
|
||||
},
|
||||
// Ephemeral issue IDs in args (wisp-* pattern)
|
||||
{
|
||||
name: "close with bd-wisp ID",
|
||||
cmdNames: []string{"bd", "close"},
|
||||
args: []string{"bd-wisp-abc123"},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "show with gt-wisp ID",
|
||||
cmdNames: []string{"bd", "show"},
|
||||
args: []string{"gt-wisp-xyz"},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "update with wisp- prefix",
|
||||
cmdNames: []string{"bd", "update"},
|
||||
args: []string{"wisp-test", "--status=closed"},
|
||||
want: true,
|
||||
},
|
||||
// Legacy eph-* pattern (backwards compatibility)
|
||||
{
|
||||
name: "close with legacy bd-eph ID",
|
||||
cmdNames: []string{"bd", "close"},
|
||||
args: []string{"bd-eph-abc123"},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "show with legacy gt-eph ID",
|
||||
cmdNames: []string{"bd", "show"},
|
||||
args: []string{"gt-eph-xyz"},
|
||||
want: true,
|
||||
},
|
||||
// Non-wisp operations (should NOT bypass)
|
||||
{
|
||||
name: "regular show",
|
||||
cmdNames: []string{"bd", "show"},
|
||||
args: []string{"bd-abc123"},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "regular close",
|
||||
cmdNames: []string{"bd", "close"},
|
||||
args: []string{"bd-xyz"},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "mol pour (persistent)",
|
||||
cmdNames: []string{"bd", "mol", "pour"},
|
||||
args: []string{"some-formula"},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "list command",
|
||||
cmdNames: []string{"bd", "list"},
|
||||
args: []string{},
|
||||
want: false,
|
||||
},
|
||||
// Edge cases
|
||||
{
|
||||
name: "flag that looks like wisp ID should be ignored",
|
||||
cmdNames: []string{"bd", "show"},
|
||||
args: []string{"--format=bd-wisp-style", "bd-regular"},
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cmd := makeCmd(tt.cmdNames...)
|
||||
got := isWispOperation(cmd, tt.args)
|
||||
if got != tt.want {
|
||||
t.Errorf("isWispOperation() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTryAutoStartDaemon_EmptyDbPath verifies that tryAutoStartDaemon returns
|
||||
// false early when dbPath is empty, preventing stack overflow from
|
||||
// filepath.Dir("") returning "." (GH#1288)
|
||||
func TestTryAutoStartDaemon_EmptyDbPath(t *testing.T) {
|
||||
// Save and restore global state
|
||||
oldDbPath := dbPath
|
||||
defer func() { dbPath = oldDbPath }()
|
||||
|
||||
// Set dbPath to empty string (simulates corrupted metadata.json)
|
||||
dbPath = ""
|
||||
|
||||
// tryAutoStartDaemon should return false without crashing
|
||||
result := tryAutoStartDaemon("/tmp/test.sock")
|
||||
if result {
|
||||
t.Errorf("tryAutoStartDaemon() = true, want false when dbPath is empty")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetupDaemonIO_DevNullNotClosed verifies that setupDaemonIO does not
|
||||
// close the /dev/null fd, preventing a race where the daemon process writes
|
||||
// to a closed (and potentially reused) fd number.
|
||||
func TestSetupDaemonIO_DevNullNotClosed(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := exec.Command("true")
|
||||
setupDaemonIO(cmd)
|
||||
|
||||
if cmd.Stdout == nil || cmd.Stderr == nil || cmd.Stdin == nil {
|
||||
t.Fatal("setupDaemonIO should set Stdout, Stderr, and Stdin")
|
||||
}
|
||||
|
||||
// The fd should remain valid (not closed) after setup.
|
||||
// Sleep past the old 1-second timer to catch regressions.
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
|
||||
f, ok := cmd.Stdout.(*os.File)
|
||||
if !ok {
|
||||
t.Fatal("Stdout is not an *os.File")
|
||||
}
|
||||
|
||||
// Stat on a closed fd returns an error; on an open fd it succeeds.
|
||||
if _, err := f.Stat(); err != nil {
|
||||
t.Errorf("devNull fd was closed prematurely: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,326 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestComputeDaemonParentPID tests the parent PID computation logic
|
||||
func TestComputeDaemonParentPID(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
envValue string
|
||||
expectedPID int
|
||||
expectsGetppid bool // whether we expect os.Getppid() to be called
|
||||
}{
|
||||
{
|
||||
name: "BD_DAEMON_FOREGROUND not set",
|
||||
envValue: "",
|
||||
expectedPID: 0, // Placeholder - will be replaced with actual Getppid()
|
||||
expectsGetppid: true,
|
||||
},
|
||||
{
|
||||
name: "BD_DAEMON_FOREGROUND=1",
|
||||
envValue: "1",
|
||||
expectedPID: 0,
|
||||
expectsGetppid: false,
|
||||
},
|
||||
{
|
||||
name: "BD_DAEMON_FOREGROUND=0",
|
||||
envValue: "0",
|
||||
expectedPID: 0, // Placeholder - will be replaced with actual Getppid()
|
||||
expectsGetppid: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Save original env
|
||||
oldVal, wasSet := os.LookupEnv("BD_DAEMON_FOREGROUND")
|
||||
defer func() {
|
||||
if wasSet {
|
||||
os.Setenv("BD_DAEMON_FOREGROUND", oldVal)
|
||||
} else {
|
||||
os.Unsetenv("BD_DAEMON_FOREGROUND")
|
||||
}
|
||||
}()
|
||||
|
||||
// Set test env
|
||||
if tt.envValue != "" {
|
||||
os.Setenv("BD_DAEMON_FOREGROUND", tt.envValue)
|
||||
} else {
|
||||
os.Unsetenv("BD_DAEMON_FOREGROUND")
|
||||
}
|
||||
|
||||
result := computeDaemonParentPID()
|
||||
|
||||
if tt.name == "BD_DAEMON_FOREGROUND=1" {
|
||||
if result != 0 {
|
||||
t.Errorf("computeDaemonParentPID() = %d, want 0", result)
|
||||
}
|
||||
} else if tt.expectsGetppid {
|
||||
// When BD_DAEMON_FOREGROUND is not "1", we should get os.Getppid()
|
||||
expectedPID := os.Getppid()
|
||||
if result != expectedPID {
|
||||
t.Errorf("computeDaemonParentPID() = %d, want %d (os.Getppid())", result, expectedPID)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckParentProcessAlive tests parent process alive checking
|
||||
func TestCheckParentProcessAlive(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
parentPID int
|
||||
expected bool
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "PID 0 (not tracked)",
|
||||
parentPID: 0,
|
||||
expected: true,
|
||||
description: "Should return true for untracked (PID 0)",
|
||||
},
|
||||
{
|
||||
name: "PID 1 (init/launchd)",
|
||||
parentPID: 1,
|
||||
expected: true,
|
||||
description: "Should return true for init process",
|
||||
},
|
||||
{
|
||||
name: "current process PID",
|
||||
parentPID: os.Getpid(),
|
||||
expected: true,
|
||||
description: "Should return true for current running process",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := checkParentProcessAlive(tt.parentPID)
|
||||
if result != tt.expected {
|
||||
t.Errorf("checkParentProcessAlive(%d) = %v, want %v (%s)",
|
||||
tt.parentPID, result, tt.expected, tt.description)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckParentProcessAlive_DeadProcess tests with an invalid PID
|
||||
func TestCheckParentProcessAlive_InvalidPID(t *testing.T) {
|
||||
// Use a very high PID that's unlikely to exist
|
||||
invalidPID := 999999
|
||||
result := checkParentProcessAlive(invalidPID)
|
||||
|
||||
// This should return false since the process doesn't exist
|
||||
if result == true {
|
||||
t.Errorf("checkParentProcessAlive(%d) = true, want false (process should not exist)", invalidPID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetPIDFileForSocket tests PID file path derivation from dbPath
|
||||
// Note: The socketPath parameter is ignored; PID file is always in .beads directory
|
||||
func TestGetPIDFileForSocket(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dbPath string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "typical beads directory",
|
||||
dbPath: "/home/user/.beads/issues.db",
|
||||
expected: "/home/user/.beads/daemon.pid",
|
||||
},
|
||||
{
|
||||
name: "root beads directory",
|
||||
dbPath: "/root/.beads/issues.db",
|
||||
expected: "/root/.beads/daemon.pid",
|
||||
},
|
||||
{
|
||||
name: "nested project beads",
|
||||
dbPath: "/home/user/projects/myapp/.beads/issues.db",
|
||||
expected: "/home/user/projects/myapp/.beads/daemon.pid",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Save and restore global dbPath
|
||||
oldDbPath := dbPath
|
||||
defer func() { dbPath = oldDbPath }()
|
||||
|
||||
dbPath = tt.dbPath
|
||||
result := getPIDFileForSocket("ignored")
|
||||
if result != tt.expected {
|
||||
t.Errorf("getPIDFileForSocket() with dbPath=%q = %q, want %q", tt.dbPath, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadPIDFromFile tests reading PID from file
|
||||
func TestReadPIDFromFile(t *testing.T) {
|
||||
t.Run("valid PID", func(t *testing.T) {
|
||||
// Create a temporary file
|
||||
tmpFile, err := os.CreateTemp("", "pid")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
// Write a PID
|
||||
if _, err := tmpFile.WriteString("12345\n"); err != nil {
|
||||
t.Fatalf("Failed to write PID: %v", err)
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
// Read it back
|
||||
pid, err := readPIDFromFile(tmpFile.Name())
|
||||
if err != nil {
|
||||
t.Errorf("readPIDFromFile() returned error: %v", err)
|
||||
}
|
||||
if pid != 12345 {
|
||||
t.Errorf("readPIDFromFile() = %d, want 12345", pid)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nonexistent file", func(t *testing.T) {
|
||||
_, err := readPIDFromFile("/nonexistent/path/to/file")
|
||||
if err == nil {
|
||||
t.Error("readPIDFromFile() should return error for nonexistent file")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid PID content", func(t *testing.T) {
|
||||
tmpFile, err := os.CreateTemp("", "pid")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp file: %v", err)
|
||||
}
|
||||
defer os.Remove(tmpFile.Name())
|
||||
|
||||
if _, err := tmpFile.WriteString("not-a-number\n"); err != nil {
|
||||
t.Fatalf("Failed to write content: %v", err)
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
_, err = readPIDFromFile(tmpFile.Name())
|
||||
if err == nil {
|
||||
t.Error("readPIDFromFile() should return error for invalid content")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestIsPIDAlive tests PID alive checking
|
||||
func TestIsPIDAlive(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
pid int
|
||||
expected bool
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "zero PID",
|
||||
pid: 0,
|
||||
expected: false,
|
||||
description: "PID 0 is invalid",
|
||||
},
|
||||
{
|
||||
name: "negative PID",
|
||||
pid: -1,
|
||||
expected: false,
|
||||
description: "Negative PID is invalid",
|
||||
},
|
||||
{
|
||||
name: "current process",
|
||||
pid: os.Getpid(),
|
||||
expected: true,
|
||||
description: "Current process should be alive",
|
||||
},
|
||||
{
|
||||
name: "invalid PID",
|
||||
pid: 999999,
|
||||
expected: false,
|
||||
description: "Non-existent process should not be alive",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := isPIDAlive(tt.pid)
|
||||
if result != tt.expected {
|
||||
t.Errorf("isPIDAlive(%d) = %v, want %v (%s)",
|
||||
tt.pid, result, tt.expected, tt.description)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestShouldAutoStartDaemon_Disabled tests BEADS_NO_DAEMON environment variable handling
|
||||
func TestShouldAutoStartDaemon_Disabled(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
noDaemonValue string
|
||||
shouldDisable bool
|
||||
description string
|
||||
}{
|
||||
{
|
||||
name: "BEADS_NO_DAEMON=1",
|
||||
noDaemonValue: "1",
|
||||
shouldDisable: true,
|
||||
description: "Should be disabled for BEADS_NO_DAEMON=1",
|
||||
},
|
||||
{
|
||||
name: "BEADS_NO_DAEMON=true",
|
||||
noDaemonValue: "true",
|
||||
shouldDisable: true,
|
||||
description: "Should be disabled for BEADS_NO_DAEMON=true",
|
||||
},
|
||||
{
|
||||
name: "BEADS_NO_DAEMON=yes",
|
||||
noDaemonValue: "yes",
|
||||
shouldDisable: true,
|
||||
description: "Should be disabled for BEADS_NO_DAEMON=yes",
|
||||
},
|
||||
{
|
||||
name: "BEADS_NO_DAEMON=on",
|
||||
noDaemonValue: "on",
|
||||
shouldDisable: true,
|
||||
description: "Should be disabled for BEADS_NO_DAEMON=on",
|
||||
},
|
||||
{
|
||||
name: "BEADS_NO_DAEMON=0",
|
||||
noDaemonValue: "0",
|
||||
shouldDisable: false,
|
||||
description: "Should NOT be disabled for BEADS_NO_DAEMON=0",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Save original env
|
||||
oldVal, wasSet := os.LookupEnv("BEADS_NO_DAEMON")
|
||||
defer func() {
|
||||
if wasSet {
|
||||
os.Setenv("BEADS_NO_DAEMON", oldVal)
|
||||
} else {
|
||||
os.Unsetenv("BEADS_NO_DAEMON")
|
||||
}
|
||||
}()
|
||||
|
||||
// Set test env
|
||||
os.Setenv("BEADS_NO_DAEMON", tt.noDaemonValue)
|
||||
|
||||
result := shouldAutoStartDaemon()
|
||||
|
||||
if tt.shouldDisable && result != false {
|
||||
t.Errorf("shouldAutoStartDaemon() = %v, want false (%s)",
|
||||
result, tt.description)
|
||||
}
|
||||
if !tt.shouldDisable && result == false {
|
||||
t.Logf("shouldAutoStartDaemon() = %v (config-dependent, check passed)", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,194 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// setupDaemonCLITest creates a temp git repo, initializes beads with daemon
|
||||
// support, and returns the directory and env vars for running CLI commands
|
||||
// through the daemon (not direct mode).
|
||||
func setupDaemonCLITest(t *testing.T) (string, []string) {
|
||||
t.Helper()
|
||||
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow integration test in short mode")
|
||||
}
|
||||
if runtime.GOOS == windowsOS {
|
||||
t.Skip("daemon CLI integration test not supported on windows")
|
||||
}
|
||||
|
||||
tmpDir := createTempDirWithCleanup(t)
|
||||
|
||||
// Set up a real git repo so daemon autostart is allowed.
|
||||
if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
|
||||
t.Fatalf("git init failed: %v", err)
|
||||
}
|
||||
_ = runCommandInDir(tmpDir, "git", "config", "user.email", "test@example.com")
|
||||
_ = runCommandInDir(tmpDir, "git", "config", "user.name", "Test User")
|
||||
|
||||
socketPath := filepath.Join(tmpDir, ".beads", "bd.sock")
|
||||
env := []string{
|
||||
"BEADS_TEST_MODE=1",
|
||||
"BEADS_AUTO_START_DAEMON=true",
|
||||
"BEADS_NO_DAEMON=0",
|
||||
"BD_SOCKET=" + socketPath,
|
||||
}
|
||||
|
||||
// Init with default (SQLite) backend.
|
||||
initOut, initErr := runBDExecAllowErrorWithEnv(t, tmpDir, env, "init", "--prefix", "test", "--quiet")
|
||||
if initErr != nil {
|
||||
t.Fatalf("bd init failed: %v\n%s", initErr, initOut)
|
||||
}
|
||||
|
||||
// Always stop daemon on cleanup.
|
||||
t.Cleanup(func() {
|
||||
_, _ = runBDExecAllowErrorWithEnv(t, tmpDir, env, "daemon", "stop")
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
})
|
||||
|
||||
return tmpDir, env
|
||||
}
|
||||
|
||||
// extractJSON finds and parses the first JSON value from output that may
|
||||
// contain non-JSON prefixed lines (e.g., daemon startup messages).
|
||||
// Handles both `{...}` objects and `[{...}]` arrays (returns first element).
|
||||
func extractJSON(t *testing.T, output string) map[string]any {
|
||||
t.Helper()
|
||||
|
||||
// Try array first (bd show/list --json returns arrays).
|
||||
if idx := strings.Index(output, "["); idx >= 0 {
|
||||
var arr []map[string]any
|
||||
if err := json.Unmarshal([]byte(output[idx:]), &arr); err == nil && len(arr) > 0 {
|
||||
return arr[0]
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to plain object.
|
||||
if idx := strings.Index(output, "{"); idx >= 0 {
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(output[idx:]), &m); err == nil {
|
||||
return m
|
||||
}
|
||||
}
|
||||
|
||||
t.Fatalf("no parseable JSON found in output:\n%s", output)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestDaemonCLI_CreateAndUpdate(t *testing.T) {
|
||||
tmpDir, env := setupDaemonCLITest(t)
|
||||
|
||||
// Create an issue via CLI (goes through daemon).
|
||||
createOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "create", "daemon cli test issue", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("bd create failed: %v\n%s", err, createOut)
|
||||
}
|
||||
|
||||
created := extractJSON(t, createOut)
|
||||
id, ok := created["id"].(string)
|
||||
if !ok || id == "" {
|
||||
t.Fatalf("expected id in create output, got: %v", created)
|
||||
}
|
||||
|
||||
// Update status to in_progress.
|
||||
updateOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "update", id, "--status", "in_progress")
|
||||
if err != nil {
|
||||
t.Fatalf("bd update failed: %v\n%s", err, updateOut)
|
||||
}
|
||||
|
||||
// Verify the update via show --json.
|
||||
showOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "show", id, "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("bd show failed: %v\n%s", err, showOut)
|
||||
}
|
||||
|
||||
shown := extractJSON(t, showOut)
|
||||
if status, _ := shown["status"].(string); status != "in_progress" {
|
||||
t.Errorf("expected status 'in_progress', got %q\nfull output: %s", status, showOut)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonCLI_CustomTypeCreate(t *testing.T) {
|
||||
tmpDir, env := setupDaemonCLITest(t)
|
||||
|
||||
// Configure custom types via the CLI (writes to SQLite via daemon).
|
||||
configOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "config", "set", "types.custom", "spike,research")
|
||||
if err != nil {
|
||||
t.Fatalf("bd config set types.custom failed: %v\n%s", err, configOut)
|
||||
}
|
||||
|
||||
// Create an issue with a custom type through the daemon.
|
||||
createOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "create", "test spike issue", "--type", "spike", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("bd create --type spike failed: %v\n%s", err, createOut)
|
||||
}
|
||||
|
||||
created := extractJSON(t, createOut)
|
||||
id, ok := created["id"].(string)
|
||||
if !ok || id == "" {
|
||||
t.Fatalf("expected id in create output, got: %v", created)
|
||||
}
|
||||
|
||||
// Verify the issue has the custom type.
|
||||
showOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "show", id, "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("bd show failed: %v\n%s", err, showOut)
|
||||
}
|
||||
|
||||
shown := extractJSON(t, showOut)
|
||||
if issueType, _ := shown["issue_type"].(string); issueType != "spike" {
|
||||
t.Errorf("expected type 'spike', got %q\nfull output: %s", issueType, showOut)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonCLI_ListAndClose(t *testing.T) {
|
||||
tmpDir, env := setupDaemonCLITest(t)
|
||||
|
||||
// Create two issues.
|
||||
out1, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "create", "first issue", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("create first failed: %v\n%s", err, out1)
|
||||
}
|
||||
created1 := extractJSON(t, out1)
|
||||
id1, _ := created1["id"].(string)
|
||||
|
||||
out2, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "create", "second issue", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("create second failed: %v\n%s", err, out2)
|
||||
}
|
||||
created2 := extractJSON(t, out2)
|
||||
id2, _ := created2["id"].(string)
|
||||
|
||||
// List should show both.
|
||||
listOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "list", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("bd list failed: %v\n%s", err, listOut)
|
||||
}
|
||||
if !strings.Contains(listOut, id1) || !strings.Contains(listOut, id2) {
|
||||
t.Errorf("expected both issue IDs in list output\nid1=%s id2=%s\noutput: %s", id1, id2, listOut)
|
||||
}
|
||||
|
||||
// Close the first issue.
|
||||
closeOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "close", id1)
|
||||
if err != nil {
|
||||
t.Fatalf("bd close failed: %v\n%s", err, closeOut)
|
||||
}
|
||||
|
||||
// Verify it's closed.
|
||||
showOut, err := runBDExecAllowErrorWithEnv(t, tmpDir, env, "show", id1, "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("bd show failed: %v\n%s", err, showOut)
|
||||
}
|
||||
shown := extractJSON(t, showOut)
|
||||
if status, _ := shown["status"].(string); status != "closed" {
|
||||
t.Errorf("expected status 'closed', got %q", status)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
)
|
||||
|
||||
// ensureBeadsDir ensures the local beads directory exists (.beads in the current workspace)
|
||||
func ensureBeadsDir() (string, error) {
|
||||
var beadsDir string
|
||||
if dbPath != "" {
|
||||
beadsDir = filepath.Dir(dbPath)
|
||||
} else {
|
||||
// Use public API to find database (same logic as other commands)
|
||||
if foundDB := beads.FindDatabasePath(); foundDB != "" {
|
||||
dbPath = foundDB // Store it for later use
|
||||
beadsDir = filepath.Dir(foundDB)
|
||||
} else {
|
||||
// No database found - error out instead of falling back to ~/.beads
|
||||
return "", fmt.Errorf("no database path configured (run 'bd init' or set BEADS_DB)")
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
return "", fmt.Errorf("cannot create beads directory: %w", err)
|
||||
}
|
||||
|
||||
return beadsDir, nil
|
||||
}
|
||||
|
||||
// boolToFlag returns the flag string if condition is true, otherwise returns empty string
|
||||
func boolToFlag(condition bool, flag string) string {
|
||||
if condition {
|
||||
return flag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// getEnvInt reads an integer from environment variable with a default value
|
||||
func getEnvInt(key string, defaultValue int) int {
|
||||
if val := os.Getenv(key); val != "" {
|
||||
if parsed, err := strconv.Atoi(val); err == nil {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// getEnvBool reads a boolean from environment variable with a default value
|
||||
func getEnvBool(key string, defaultValue bool) bool {
|
||||
if val := os.Getenv(key); val != "" {
|
||||
return val == "true" || val == "1"
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// getSocketPathForPID determines the socket path for a given PID file.
|
||||
// If BD_SOCKET env var is set, uses that value instead.
|
||||
// Uses rpc.ShortSocketPath to avoid Unix socket path length limits (macOS: 104 chars).
|
||||
func getSocketPathForPID(pidFile string) string {
|
||||
// Check environment variable first (enables test isolation)
|
||||
if socketPath := os.Getenv("BD_SOCKET"); socketPath != "" {
|
||||
return socketPath
|
||||
}
|
||||
// PID file is in .beads/, so workspace is parent of that
|
||||
beadsDir := filepath.Dir(pidFile)
|
||||
workspacePath := filepath.Dir(beadsDir)
|
||||
return rpc.ShortSocketPath(workspacePath)
|
||||
}
|
||||
|
||||
// getPIDFilePath returns the path to the daemon PID file
|
||||
func getPIDFilePath() (string, error) {
|
||||
beadsDir, err := ensureBeadsDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(beadsDir, "daemon.pid"), nil
|
||||
}
|
||||
|
||||
// getLogFilePath returns the path to the daemon log file
|
||||
func getLogFilePath(userPath string) (string, error) {
|
||||
if userPath != "" {
|
||||
return userPath, nil
|
||||
}
|
||||
|
||||
beadsDir, err := ensureBeadsDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(beadsDir, "daemon.log"), nil
|
||||
}
|
||||
|
|
@ -1,173 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestDaemonPanicRecovery verifies that daemon panics are caught, logged, and cleaned up properly
|
||||
func TestDaemonPanicRecovery(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
// Setup git repo and beads
|
||||
initTestGitRepo(t, tmpDir)
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0750); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
// Initialize database
|
||||
oldDBPath := dbPath
|
||||
defer func() { dbPath = oldDBPath }()
|
||||
dbPath = filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// Run bd init
|
||||
rootCmd.SetArgs([]string{"init", "--prefix", "test", "--quiet"})
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
t.Fatalf("Failed to initialize: %v", err)
|
||||
}
|
||||
|
||||
// Create a test that will trigger a panic in daemon
|
||||
// We'll do this by creating a daemon with an invalid configuration
|
||||
// that causes a panic during startup
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
logFile := filepath.Join(beadsDir, "daemon.log")
|
||||
|
||||
// Start daemon in foreground with a goroutine that will panic
|
||||
done := make(chan bool)
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
// Expected panic - test passes
|
||||
done <- true
|
||||
}
|
||||
}()
|
||||
|
||||
// Simulate a panic in daemon code
|
||||
// In real scenarios, this would be an unexpected panic
|
||||
// For testing, we'll just verify the recovery mechanism exists
|
||||
testPanic := func() {
|
||||
panic("test panic for crash recovery")
|
||||
}
|
||||
|
||||
// This would normally be runDaemonLoop, but we're simulating
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
// Log the panic (same as real daemon does)
|
||||
logF, _ := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if logF != nil {
|
||||
logF.WriteString("PANIC recovered: " + r.(string) + "\n")
|
||||
logF.Close()
|
||||
}
|
||||
|
||||
// Write daemon-error file
|
||||
errFile := filepath.Join(beadsDir, "daemon-error")
|
||||
crashReport := "Daemon crashed\nPanic: " + r.(string) + "\n"
|
||||
_ = os.WriteFile(errFile, []byte(crashReport), 0644)
|
||||
|
||||
// Clean up PID file
|
||||
_ = os.Remove(pidFile)
|
||||
|
||||
done <- true
|
||||
}
|
||||
}()
|
||||
|
||||
testPanic()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// Panic was recovered
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Panic recovery test timed out")
|
||||
}
|
||||
|
||||
// Verify daemon-error file was created
|
||||
errFile := filepath.Join(beadsDir, "daemon-error")
|
||||
if _, err := os.Stat(errFile); os.IsNotExist(err) {
|
||||
t.Error("daemon-error file was not created after panic")
|
||||
} else {
|
||||
content, err := os.ReadFile(errFile)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read daemon-error file: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(content), "Panic:") {
|
||||
t.Errorf("daemon-error file missing panic info: %s", string(content))
|
||||
}
|
||||
}
|
||||
|
||||
// Verify log contains panic message
|
||||
if _, err := os.Stat(logFile); err == nil {
|
||||
content, err := os.ReadFile(logFile)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read log file: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(content), "PANIC") {
|
||||
t.Errorf("Log file missing panic message: %s", string(content))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStopDaemonSocketCleanup verifies that forced daemon kill cleans up socket
|
||||
func TestStopDaemonSocketCleanup(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0750); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
|
||||
// Create a fake PID file and socket to simulate stale daemon
|
||||
// Write a PID that doesn't exist
|
||||
fakePID := "999999"
|
||||
if err := os.WriteFile(pidFile, []byte(fakePID), 0644); err != nil {
|
||||
t.Fatalf("Failed to write PID file: %v", err)
|
||||
}
|
||||
|
||||
// Create a stale socket file
|
||||
f, err := os.Create(socketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create socket file: %v", err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
// Verify socket exists before cleanup
|
||||
if _, err := os.Stat(socketPath); os.IsNotExist(err) {
|
||||
t.Fatal("Socket file should exist before cleanup")
|
||||
}
|
||||
|
||||
// Note: We can't fully test stopDaemon here without a running process
|
||||
// But we can verify the socket cleanup logic is present
|
||||
t.Log("Socket cleanup logic verified in stopDaemon function")
|
||||
|
||||
// Manual cleanup to verify the pattern
|
||||
if _, err := os.Stat(socketPath); err == nil {
|
||||
if err := os.Remove(socketPath); err != nil {
|
||||
t.Errorf("Failed to remove socket: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify socket was removed
|
||||
if _, err := os.Stat(socketPath); !os.IsNotExist(err) {
|
||||
t.Error("Socket file should be removed after cleanup")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Debouncer batches rapid events into a single action after a quiet period.
|
||||
// Thread-safe for concurrent triggers.
|
||||
type Debouncer struct {
|
||||
mu sync.Mutex
|
||||
timer *time.Timer
|
||||
duration time.Duration
|
||||
action func()
|
||||
seq uint64 // Sequence number to prevent stale timer fires
|
||||
wg sync.WaitGroup // Tracks in-flight actions for graceful shutdown
|
||||
}
|
||||
|
||||
// NewDebouncer creates a new debouncer with the given duration and action.
|
||||
// The action will be called once after the duration has passed since the last trigger.
|
||||
func NewDebouncer(duration time.Duration, action func()) *Debouncer {
|
||||
return &Debouncer{
|
||||
duration: duration,
|
||||
action: action,
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger schedules the action to run after the debounce duration.
|
||||
// If called multiple times, the timer is reset each time, ensuring
|
||||
// the action only fires once after the last trigger.
|
||||
func (d *Debouncer) Trigger() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if d.timer != nil {
|
||||
if d.timer.Stop() {
|
||||
// Timer was stopped before firing; release WaitGroup for it
|
||||
d.wg.Done()
|
||||
}
|
||||
}
|
||||
|
||||
// Increment sequence number to invalidate any pending timers
|
||||
d.seq++
|
||||
currentSeq := d.seq
|
||||
|
||||
d.wg.Add(1)
|
||||
d.timer = time.AfterFunc(d.duration, func() {
|
||||
defer d.wg.Done()
|
||||
|
||||
d.mu.Lock()
|
||||
// Only fire if this is still the latest trigger
|
||||
if d.seq != currentSeq {
|
||||
d.mu.Unlock()
|
||||
return
|
||||
}
|
||||
d.timer = nil
|
||||
d.mu.Unlock() // Unlock before calling action to avoid holding lock during callback
|
||||
|
||||
// Action runs without lock held. If action panics, the lock is already
|
||||
// released, avoiding a double-unlock that would occur with the previous
|
||||
// defer-based pattern.
|
||||
d.action()
|
||||
})
|
||||
}
|
||||
|
||||
// Cancel stops any pending debounced action.
|
||||
// Safe to call even if no action is pending.
|
||||
// Does NOT wait for an already-executing action to finish.
|
||||
func (d *Debouncer) Cancel() {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
if d.timer != nil {
|
||||
if d.timer.Stop() {
|
||||
// Timer was stopped before firing; release WaitGroup for it
|
||||
d.wg.Done()
|
||||
}
|
||||
d.timer = nil
|
||||
}
|
||||
}
|
||||
|
||||
// CancelAndWait stops any pending debounced action and blocks until any
|
||||
// in-flight action completes. Use this during graceful shutdown to drain
|
||||
// in-flight sync operations (export/import).
|
||||
func (d *Debouncer) CancelAndWait() {
|
||||
d.Cancel()
|
||||
d.wg.Wait()
|
||||
}
|
||||
|
|
@ -1,271 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDebouncer_BatchesMultipleTriggers(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(50*time.Millisecond, func() {
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
t.Cleanup(debouncer.Cancel)
|
||||
|
||||
debouncer.Trigger()
|
||||
debouncer.Trigger()
|
||||
debouncer.Trigger()
|
||||
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if got := atomic.LoadInt32(&count); got != 0 {
|
||||
t.Errorf("action fired too early: got %d, want 0", got)
|
||||
}
|
||||
|
||||
time.Sleep(35 * time.Millisecond)
|
||||
if got := atomic.LoadInt32(&count); got != 1 {
|
||||
t.Errorf("action should have fired once: got %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_ResetsTimerOnSubsequentTriggers(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(50*time.Millisecond, func() {
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
t.Cleanup(debouncer.Cancel)
|
||||
|
||||
debouncer.Trigger()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
|
||||
debouncer.Trigger()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
|
||||
if got := atomic.LoadInt32(&count); got != 0 {
|
||||
t.Errorf("action fired too early after timer reset: got %d, want 0", got)
|
||||
}
|
||||
|
||||
time.Sleep(35 * time.Millisecond)
|
||||
if got := atomic.LoadInt32(&count); got != 1 {
|
||||
t.Errorf("action should have fired once after final timer: got %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_CancelDuringWait(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(50*time.Millisecond, func() {
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
t.Cleanup(debouncer.Cancel)
|
||||
|
||||
debouncer.Trigger()
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
debouncer.Cancel()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := atomic.LoadInt32(&count); got != 0 {
|
||||
t.Errorf("action should not have fired after cancel: got %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_CancelWithNoPendingAction(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(50*time.Millisecond, func() {
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
t.Cleanup(debouncer.Cancel)
|
||||
|
||||
debouncer.Cancel()
|
||||
|
||||
debouncer.Trigger()
|
||||
// Use longer wait to account for Windows timer imprecision
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if got := atomic.LoadInt32(&count); got != 1 {
|
||||
t.Errorf("action should fire normally after cancel with no pending action: got %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_ThreadSafety(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(50*time.Millisecond, func() {
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
t.Cleanup(debouncer.Cancel)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
debouncer.Trigger()
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
time.Sleep(70 * time.Millisecond)
|
||||
|
||||
got := atomic.LoadInt32(&count)
|
||||
if got != 1 {
|
||||
t.Errorf("all concurrent triggers should batch to exactly 1 action: got %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_ConcurrentCancelAndTrigger(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(50*time.Millisecond, func() {
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
t.Cleanup(debouncer.Cancel)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
numGoroutines := 50
|
||||
|
||||
for i := 0; i < numGoroutines; i++ {
|
||||
wg.Add(1)
|
||||
go func(index int) {
|
||||
defer wg.Done()
|
||||
if index%2 == 0 {
|
||||
debouncer.Trigger()
|
||||
} else {
|
||||
debouncer.Cancel()
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
debouncer.Cancel()
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
got := atomic.LoadInt32(&count)
|
||||
if got != 0 && got != 1 {
|
||||
t.Errorf("unexpected action count with concurrent cancel/trigger: got %d, want 0 or 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_MultipleSequentialTriggerCycles(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(30*time.Millisecond, func() {
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
t.Cleanup(debouncer.Cancel)
|
||||
|
||||
awaitCount := func(want int32) {
|
||||
deadline := time.Now().Add(500 * time.Millisecond)
|
||||
for time.Now().Before(deadline) {
|
||||
if got := atomic.LoadInt32(&count); got >= want {
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
got := atomic.LoadInt32(&count)
|
||||
t.Fatalf("timeout waiting for count=%d (got %d)", want, got)
|
||||
}
|
||||
|
||||
debouncer.Trigger()
|
||||
awaitCount(1)
|
||||
|
||||
debouncer.Trigger()
|
||||
awaitCount(2)
|
||||
|
||||
debouncer.Trigger()
|
||||
awaitCount(3)
|
||||
}
|
||||
|
||||
func TestDebouncer_CancelAndWaitDrainsInFlight(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
debouncer := NewDebouncer(10*time.Millisecond, func() {
|
||||
close(started)
|
||||
// Simulate a long-running sync operation
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
close(done)
|
||||
})
|
||||
|
||||
debouncer.Trigger()
|
||||
|
||||
// Wait for the action to start executing
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("action did not start in time")
|
||||
}
|
||||
|
||||
// CancelAndWait should block until the action finishes
|
||||
debouncer.CancelAndWait()
|
||||
|
||||
// Verify the action completed
|
||||
select {
|
||||
case <-done:
|
||||
// Success - action completed before CancelAndWait returned
|
||||
default:
|
||||
t.Error("CancelAndWait returned before in-flight action completed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_CancelAndWaitNoPending(t *testing.T) {
|
||||
debouncer := NewDebouncer(50*time.Millisecond, func() {})
|
||||
|
||||
// CancelAndWait with nothing pending should return immediately
|
||||
waitDone := make(chan struct{})
|
||||
go func() {
|
||||
debouncer.CancelAndWait()
|
||||
close(waitDone)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-waitDone:
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("CancelAndWait blocked with nothing pending")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_CancelAndWaitWithPendingTimer(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(5*time.Second, func() {
|
||||
// This should never fire - timer should be stopped
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
|
||||
debouncer.Trigger()
|
||||
|
||||
// CancelAndWait should stop the timer and return immediately
|
||||
waitDone := make(chan struct{})
|
||||
go func() {
|
||||
debouncer.CancelAndWait()
|
||||
close(waitDone)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-waitDone:
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("CancelAndWait blocked with only a pending (not yet fired) timer")
|
||||
}
|
||||
|
||||
if got := atomic.LoadInt32(&count); got != 0 {
|
||||
t.Errorf("action should not have fired after CancelAndWait: got %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDebouncer_CancelImmediatelyAfterTrigger(t *testing.T) {
|
||||
var count int32
|
||||
debouncer := NewDebouncer(50*time.Millisecond, func() {
|
||||
atomic.AddInt32(&count, 1)
|
||||
})
|
||||
t.Cleanup(debouncer.Cancel)
|
||||
|
||||
debouncer.Trigger()
|
||||
debouncer.Cancel()
|
||||
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
if got := atomic.LoadInt32(&count); got != 0 {
|
||||
t.Errorf("action should not fire after immediate cancel: got %d, want 0", got)
|
||||
}
|
||||
}
|
||||
119
cmd/bd/daemon_deprecated.go
Normal file
119
cmd/bd/daemon_deprecated.go
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
package main
|
||||
|
||||
// daemon_deprecated.go provides stub variables for daemon-related code
|
||||
// that hasn't been fully removed yet from command files.
|
||||
//
|
||||
// The daemon subsystem has been removed. These variables exist only to
|
||||
// allow gradual cleanup of the 66+ files that still reference them.
|
||||
// All daemon branches are dead code (daemonClient is always nil,
|
||||
// daemonStatus is always zero-valued, noDaemon is always false).
|
||||
//
|
||||
// TODO: Remove this file after all `if daemonClient != nil` branches
|
||||
// are cleaned up from command files.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
)
|
||||
|
||||
// DaemonStatus is a deprecated stub. The daemon has been removed.
|
||||
type DaemonStatus struct {
|
||||
Mode string `json:"mode"`
|
||||
Connected bool `json:"connected"`
|
||||
Degraded bool `json:"degraded"`
|
||||
SocketPath string `json:"socket_path,omitempty"`
|
||||
AutoStartEnabled bool `json:"auto_start_enabled"`
|
||||
AutoStartAttempted bool `json:"auto_start_attempted"`
|
||||
AutoStartSucceeded bool `json:"auto_start_succeeded"`
|
||||
FallbackReason string `json:"fallback_reason,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Health string `json:"health,omitempty"`
|
||||
}
|
||||
|
||||
// Deprecated fallback reason constants. The daemon has been removed.
|
||||
const (
|
||||
FallbackNone = "none"
|
||||
FallbackFlagNoDaemon = "flag_no_daemon"
|
||||
FallbackConnectFailed = "connect_failed"
|
||||
FallbackHealthFailed = "health_failed"
|
||||
FallbackWorktreeSafety = "worktree_safety"
|
||||
FallbackSingleProcessOnly = "single_process_only"
|
||||
FallbackAutoStartDisabled = "auto_start_disabled"
|
||||
FallbackAutoStartFailed = "auto_start_failed"
|
||||
FallbackDaemonUnsupported = "daemon_unsupported"
|
||||
FallbackWispOperation = "wisp_operation"
|
||||
)
|
||||
|
||||
var (
|
||||
// daemonClient is always nil. The daemon has been removed.
|
||||
daemonClient *rpc.Client
|
||||
|
||||
// daemonStatus is always zero-valued. The daemon has been removed.
|
||||
daemonStatus DaemonStatus
|
||||
|
||||
// noDaemon is always false. The --no-daemon flag has been removed.
|
||||
noDaemon bool
|
||||
)
|
||||
|
||||
// Deprecated accessor stubs for context.go compatibility.
|
||||
func getDaemonClient() *rpc.Client { return nil }
|
||||
func setDaemonClient(_ *rpc.Client) {}
|
||||
func getDaemonStatus() DaemonStatus { return DaemonStatus{} }
|
||||
func setDaemonStatus(_ DaemonStatus) {}
|
||||
func isNoDaemon() bool { return false }
|
||||
func setNoDaemon(_ bool) {}
|
||||
|
||||
// Deprecated daemon lifecycle stubs.
|
||||
func isDaemonRunning(_ string) (bool, int) { return false, 0 }
|
||||
func stopDaemonQuiet(_ string) {}
|
||||
func getPIDFilePath() (string, error) { return "", nil }
|
||||
func getSocketPath() string { return "" }
|
||||
func emitVerboseWarning() {}
|
||||
func shouldAutoStartDaemon() bool { return false }
|
||||
func singleProcessOnlyBackend() bool { return false }
|
||||
func shouldDisableDaemonForWorktree() bool { return false }
|
||||
func warnWorktreeDaemon(_ string) {}
|
||||
func newSilentLogger() *slog.Logger { return slog.New(slog.DiscardHandler) }
|
||||
func syncBranchPull(_ context.Context, _ storage.Storage, _ *slog.Logger) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func boolToFlag(condition bool, flag string) string {
|
||||
if condition {
|
||||
return flag
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func truncateString(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
if maxLen <= 3 {
|
||||
return s[:maxLen]
|
||||
}
|
||||
return s[:maxLen-3] + "..."
|
||||
}
|
||||
|
||||
func formatUptime(seconds float64) string {
|
||||
if seconds < 60 {
|
||||
return fmt.Sprintf("%.1f seconds", seconds)
|
||||
}
|
||||
if seconds < 3600 {
|
||||
minutes := int(seconds / 60)
|
||||
secs := int(seconds) % 60
|
||||
return fmt.Sprintf("%dm %ds", minutes, secs)
|
||||
}
|
||||
if seconds < 86400 {
|
||||
hours := int(seconds / 3600)
|
||||
minutes := int(seconds/60) % 60
|
||||
return fmt.Sprintf("%dh %dm", hours, minutes)
|
||||
}
|
||||
days := int(seconds / 86400)
|
||||
hours := int(seconds/3600) % 24
|
||||
return fmt.Sprintf("%dd %dh", days, hours)
|
||||
}
|
||||
|
|
@ -1,305 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
)
|
||||
|
||||
// DefaultRemoteSyncInterval is the default interval for periodic remote sync.
|
||||
// Can be overridden via BEADS_REMOTE_SYNC_INTERVAL environment variable.
|
||||
const DefaultRemoteSyncInterval = 30 * time.Second
|
||||
|
||||
// runEventDrivenLoop implements event-driven daemon architecture.
|
||||
// Replaces polling ticker with reactive event handlers for:
|
||||
// - File system changes (JSONL modifications)
|
||||
// - RPC mutations (create, update, delete)
|
||||
// - Git operations (via hooks, optional)
|
||||
// - Parent process monitoring (exit if parent dies)
|
||||
// - Periodic remote sync (to pull updates from other clones)
|
||||
//
|
||||
// The remoteSyncInterval parameter controls how often the daemon pulls from
|
||||
// remote to check for updates from other clones. Use DefaultRemoteSyncInterval
|
||||
// or configure via BEADS_REMOTE_SYNC_INTERVAL environment variable.
|
||||
func runEventDrivenLoop(
|
||||
ctx context.Context,
|
||||
cancel context.CancelFunc,
|
||||
server *rpc.Server,
|
||||
serverErrChan chan error,
|
||||
store storage.Storage,
|
||||
jsonlPath string,
|
||||
doExport func(),
|
||||
doAutoImport func(),
|
||||
autoPull bool,
|
||||
parentPID int,
|
||||
log *slog.Logger,
|
||||
) {
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, daemonSignals...)
|
||||
defer signal.Stop(sigChan)
|
||||
|
||||
// Debounced sync actions
|
||||
exportDebouncer := NewDebouncer(500*time.Millisecond, func() {
|
||||
log.Info("Export triggered by mutation events")
|
||||
doExport()
|
||||
})
|
||||
defer exportDebouncer.CancelAndWait()
|
||||
|
||||
importDebouncer := NewDebouncer(500*time.Millisecond, func() {
|
||||
log.Info("Import triggered by file change")
|
||||
doAutoImport()
|
||||
})
|
||||
defer importDebouncer.CancelAndWait()
|
||||
|
||||
// Start file watcher for JSONL changes
|
||||
watcher, err := NewFileWatcher(jsonlPath, func() {
|
||||
importDebouncer.Trigger()
|
||||
})
|
||||
var fallbackTicker *time.Ticker
|
||||
if err != nil {
|
||||
log.Info("WARNING: File watcher unavailable, using 60s polling fallback", "error", err)
|
||||
watcher = nil
|
||||
// Fallback ticker to check for remote changes when watcher unavailable
|
||||
fallbackTicker = time.NewTicker(60 * time.Second)
|
||||
defer fallbackTicker.Stop()
|
||||
} else {
|
||||
watcher.Start(ctx, log)
|
||||
defer func() { _ = watcher.Close() }()
|
||||
}
|
||||
|
||||
// Handle mutation events from RPC server
|
||||
mutationChan := server.MutationChan()
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-mutationChan:
|
||||
if !ok {
|
||||
// Channel closed (should never happen, but handle defensively)
|
||||
log.Info("Mutation channel closed; exiting listener")
|
||||
return
|
||||
}
|
||||
log.Info("Mutation detected", "type", event.Type, "issue_id", event.IssueID)
|
||||
exportDebouncer.Trigger()
|
||||
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Periodic health check
|
||||
healthTicker := time.NewTicker(60 * time.Second)
|
||||
defer healthTicker.Stop()
|
||||
|
||||
// Periodic remote sync to pull updates from other clones
|
||||
// This is essential for multi-clone workflows where the file watcher only
|
||||
// sees local changes but remote may have updates from other clones.
|
||||
// Default is 30 seconds; configurable via BEADS_REMOTE_SYNC_INTERVAL.
|
||||
// Only enabled when autoPull is true (default when sync.branch is configured).
|
||||
var remoteSyncTicker *time.Ticker
|
||||
if autoPull {
|
||||
remoteSyncInterval := getRemoteSyncInterval(log)
|
||||
if remoteSyncInterval > 0 {
|
||||
remoteSyncTicker = time.NewTicker(remoteSyncInterval)
|
||||
defer remoteSyncTicker.Stop()
|
||||
log.Info("Auto-pull enabled: checking remote periodically", "interval", remoteSyncInterval)
|
||||
} else {
|
||||
log.Info("Auto-pull disabled: remote-sync-interval is 0")
|
||||
}
|
||||
} else {
|
||||
log.Info("Auto-pull disabled: use 'git pull' manually to sync remote changes")
|
||||
}
|
||||
|
||||
// Parent process check (every 10 seconds)
|
||||
parentCheckTicker := time.NewTicker(10 * time.Second)
|
||||
defer parentCheckTicker.Stop()
|
||||
|
||||
// Dropped events safety net (faster recovery than health check)
|
||||
droppedEventsTicker := time.NewTicker(1 * time.Second)
|
||||
defer droppedEventsTicker.Stop()
|
||||
|
||||
// Pre-allocate ticker channels to avoid creating new channels on every
|
||||
// select iteration. A nil channel blocks forever in select, which is the
|
||||
// desired behavior when the corresponding ticker is disabled.
|
||||
var remoteSyncChan <-chan time.Time
|
||||
if remoteSyncTicker != nil {
|
||||
remoteSyncChan = remoteSyncTicker.C
|
||||
}
|
||||
var fallbackChan <-chan time.Time
|
||||
if fallbackTicker != nil {
|
||||
fallbackChan = fallbackTicker.C
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-droppedEventsTicker.C:
|
||||
// Check for dropped mutation events every second
|
||||
dropped := server.ResetDroppedEventsCount()
|
||||
if dropped > 0 {
|
||||
log.Info("WARNING: mutation events were dropped, triggering export", "count", dropped)
|
||||
exportDebouncer.Trigger()
|
||||
}
|
||||
|
||||
case <-healthTicker.C:
|
||||
// Periodic health validation (not sync)
|
||||
checkDaemonHealth(ctx, store, log)
|
||||
|
||||
case <-remoteSyncChan:
|
||||
// Periodic remote sync to pull updates from other clones
|
||||
// This ensures the daemon sees changes pushed by other clones
|
||||
// even when the local file watcher doesn't trigger
|
||||
log.Info("Periodic remote sync: checking for updates")
|
||||
doAutoImport()
|
||||
|
||||
case <-parentCheckTicker.C:
|
||||
// Check if parent process is still alive
|
||||
if !checkParentProcessAlive(parentPID) {
|
||||
log.Info("Parent process died, shutting down daemon", "pid", parentPID)
|
||||
cancel()
|
||||
if err := server.Stop(); err != nil {
|
||||
log.Info("Error stopping server", "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
case <-fallbackChan:
|
||||
log.Info("Fallback ticker: checking for remote changes")
|
||||
importDebouncer.Trigger()
|
||||
|
||||
case sig := <-sigChan:
|
||||
if isReloadSignal(sig) {
|
||||
log.Info("Received reload signal, ignoring")
|
||||
continue
|
||||
}
|
||||
log.Info("Received signal, shutting down...", "signal", sig)
|
||||
cancel()
|
||||
if err := server.Stop(); err != nil {
|
||||
log.Info("Error stopping server", "error", err)
|
||||
}
|
||||
return
|
||||
|
||||
case <-ctx.Done():
|
||||
log.Info("Context canceled, shutting down")
|
||||
if watcher != nil {
|
||||
_ = watcher.Close()
|
||||
}
|
||||
if err := server.Stop(); err != nil {
|
||||
log.Info("Error stopping server", "error", err)
|
||||
}
|
||||
return
|
||||
|
||||
case err := <-serverErrChan:
|
||||
log.Info("RPC server failed", "error", err)
|
||||
cancel()
|
||||
if watcher != nil {
|
||||
_ = watcher.Close()
|
||||
}
|
||||
if stopErr := server.Stop(); stopErr != nil {
|
||||
log.Info("Error stopping server", "error", stopErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkDaemonHealth performs periodic health validation.
|
||||
// Separate from sync operations - just validates state.
|
||||
func checkDaemonHealth(ctx context.Context, store storage.Storage, log *slog.Logger) {
|
||||
// Health check 1: Verify metadata is accessible
|
||||
// This helps detect if external operations (like bd import --force) have modified metadata
|
||||
// Without this, daemon may continue operating with stale metadata cache
|
||||
// Try new key first, fall back to old for migration
|
||||
if _, err := store.GetMetadata(ctx, "jsonl_content_hash"); err != nil {
|
||||
if _, err := store.GetMetadata(ctx, "last_import_hash"); err != nil {
|
||||
log.Info("Health check: metadata read failed", "error", err)
|
||||
// Non-fatal: daemon continues but logs the issue
|
||||
// This helps diagnose stuck states in sandboxed environments
|
||||
}
|
||||
}
|
||||
|
||||
// Health check 2: Database integrity check
|
||||
// Verify the database is accessible and structurally sound
|
||||
if db := store.UnderlyingDB(); db != nil {
|
||||
// Quick integrity check - just verify we can query
|
||||
var result string
|
||||
if err := db.QueryRowContext(ctx, "PRAGMA quick_check(1)").Scan(&result); err != nil {
|
||||
log.Info("Health check: database integrity check failed", "error", err)
|
||||
} else if result != "ok" {
|
||||
log.Info("Health check: database integrity issue", "result", result)
|
||||
}
|
||||
}
|
||||
|
||||
// Health check 3: Disk space check (platform-specific)
|
||||
// Uses checkDiskSpace helper which is implemented per-platform
|
||||
dbPath := store.Path()
|
||||
if dbPath != "" {
|
||||
if availableMB, ok := checkDiskSpace(dbPath); ok {
|
||||
// Warn if less than 100MB available
|
||||
if availableMB < 100 {
|
||||
log.Info("Health check: low disk space warning", "available_mb", availableMB)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Health check 4: Memory usage check
|
||||
// Log warning if memory usage is unusually high
|
||||
var memStats runtime.MemStats
|
||||
runtime.ReadMemStats(&memStats)
|
||||
heapMB := memStats.HeapAlloc / (1024 * 1024)
|
||||
|
||||
// Warn if heap exceeds 500MB (daemon should be lightweight)
|
||||
if heapMB > 500 {
|
||||
log.Info("Health check: high memory usage warning", "heap_mb", heapMB)
|
||||
}
|
||||
}
|
||||
|
||||
// getRemoteSyncInterval returns the interval for periodic remote sync.
|
||||
// Configuration sources (in order of precedence):
|
||||
// 1. BEADS_REMOTE_SYNC_INTERVAL environment variable
|
||||
// 2. remote-sync-interval in .beads/config.yaml
|
||||
// 3. DefaultRemoteSyncInterval (30s)
|
||||
//
|
||||
// Accepts Go duration strings like:
|
||||
// - "30s" (30 seconds)
|
||||
// - "1m" (1 minute)
|
||||
// - "5m" (5 minutes)
|
||||
// - "0" or "0s" (disables periodic sync - use with caution)
|
||||
//
|
||||
// Minimum allowed value is 5 seconds to prevent excessive load.
|
||||
func getRemoteSyncInterval(log *slog.Logger) time.Duration {
|
||||
// config.GetDuration handles both config.yaml and env var (env takes precedence)
|
||||
duration := config.GetDuration("remote-sync-interval")
|
||||
|
||||
// If config returns 0, it could mean:
|
||||
// 1. User explicitly set "0" to disable
|
||||
// 2. Config not found (use default)
|
||||
// Check if there's an explicit value set
|
||||
if duration == 0 {
|
||||
// Check if user explicitly set it to 0 via env var
|
||||
if envVal := os.Getenv("BEADS_REMOTE_SYNC_INTERVAL"); envVal == "0" || envVal == "0s" {
|
||||
log.Info("Warning: remote-sync-interval is 0, periodic remote sync disabled")
|
||||
return 24 * time.Hour * 365
|
||||
}
|
||||
// Otherwise use default
|
||||
return DefaultRemoteSyncInterval
|
||||
}
|
||||
|
||||
// Minimum 5 seconds to prevent excessive load
|
||||
if duration > 0 && duration < 5*time.Second {
|
||||
log.Info("Warning: remote-sync-interval too low, using minimum 5s", "duration", duration)
|
||||
return 5 * time.Second
|
||||
}
|
||||
|
||||
// Log if using non-default value
|
||||
if duration != DefaultRemoteSyncInterval {
|
||||
log.Info("Using custom remote sync interval", "interval", duration)
|
||||
}
|
||||
return duration
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
)
|
||||
|
||||
func singleProcessBackendHelp(backend string) string {
|
||||
b := strings.TrimSpace(backend)
|
||||
if b == "" {
|
||||
b = "unknown"
|
||||
}
|
||||
// Keep this short; Cobra will prefix with "Error:".
|
||||
return fmt.Sprintf("daemon mode is not supported with the current backend (%s). Use a multi-process compatible backend (e.g., `bd init --backend sqlite`) or run commands in direct mode without the daemon", b)
|
||||
}
|
||||
|
||||
// guardDaemonStartForDolt blocks daemon start/restart commands when the current
|
||||
// workspace backend is Dolt, unless --federation is specified.
|
||||
//
|
||||
// Rationale: embedded Dolt is effectively single-writer at the OS-process level. The
|
||||
// daemon architecture relies on multiple processes (CLI + daemon + helper spawns),
|
||||
// which can trigger lock contention and transient "read-only" failures.
|
||||
//
|
||||
// Exception: --federation flag enables dolt sql-server mode which is multi-writer.
|
||||
//
|
||||
// Note: This guard should only be attached to commands that START a daemon process
|
||||
// (start, restart). Read-only commands (status, stop, logs, health, list) are allowed
|
||||
// even with Dolt backend.
|
||||
//
|
||||
// We still allow help output so users can discover the command surface.
|
||||
func guardDaemonStartForDolt(cmd *cobra.Command, _ []string) error {
|
||||
// Allow `--help` for any daemon subcommand.
|
||||
if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil {
|
||||
if help, _ := cmd.Flags().GetBool("help"); help {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Allow `--federation` flag which enables dolt sql-server (multi-writer) mode.
|
||||
if fedFlag := cmd.Flags().Lookup("federation"); fedFlag != nil {
|
||||
if federation, _ := cmd.Flags().GetBool("federation"); federation {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort determine the active workspace backend. If we can't determine it,
|
||||
// don't block (the command will likely fail later anyway).
|
||||
beadsDir := beads.FindBeadsDir()
|
||||
if beadsDir == "" {
|
||||
// Fall back to configured dbPath if set; daemon commands often run from workspace root,
|
||||
// but tests may set BEADS_DB explicitly.
|
||||
if dbPath != "" {
|
||||
beadsDir = filepath.Dir(dbPath)
|
||||
} else if found := beads.FindDatabasePath(); found != "" {
|
||||
beadsDir = filepath.Dir(found)
|
||||
}
|
||||
}
|
||||
if beadsDir == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
if err != nil || cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Use GetCapabilities() to properly handle Dolt server mode
|
||||
if cfg.GetCapabilities().SingleProcessOnly {
|
||||
return fmt.Errorf("%s", singleProcessBackendHelp(cfg.GetBackend()))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
//go:build freebsd && !wasm
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// checkDiskSpace returns the available disk space in MB for the given path.
|
||||
// Returns (availableMB, true) on success, (0, false) on failure.
|
||||
func checkDiskSpace(path string) (uint64, bool) {
|
||||
var stat unix.Statfs_t
|
||||
if err := unix.Statfs(path, &stat); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
if stat.Bavail < 0 {
|
||||
return 0, true
|
||||
}
|
||||
|
||||
availableBytes := uint64(stat.Bavail) * stat.Bsize //nolint:gosec
|
||||
availableMB := availableBytes / (1024 * 1024)
|
||||
|
||||
return availableMB, true
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
//go:build illumos || solaris
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// checkDiskSpace returns the available disk space in MB for the given path.
|
||||
// Returns (availableMB, true) on success, (0, false) on failure.
|
||||
func checkDiskSpace(path string) (uint64, bool) {
|
||||
var stat unix.Statvfs_t
|
||||
if err := unix.Statvfs(path, &stat); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Calculate available space in bytes, then convert to MB.
|
||||
// On Solaris/illumos, Frsize is the fragment size (fundamental block size).
|
||||
availableBytes := stat.Bavail * stat.Frsize
|
||||
availableMB := availableBytes / (1024 * 1024)
|
||||
|
||||
return availableMB, true
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
//go:build !windows && !wasm && !freebsd && !illumos && !solaris
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// checkDiskSpace returns the available disk space in MB for the given path.
|
||||
// Returns (availableMB, true) on success, (0, false) on failure.
|
||||
func checkDiskSpace(path string) (uint64, bool) {
|
||||
var stat unix.Statfs_t
|
||||
if err := unix.Statfs(path, &stat); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Calculate available space in bytes, then convert to MB.
|
||||
// On most unix platforms, Bavail is unsigned but Bsize is signed.
|
||||
availableBytes := stat.Bavail * uint64(stat.Bsize) //nolint:gosec
|
||||
availableMB := availableBytes / (1024 * 1024)
|
||||
|
||||
return availableMB, true
|
||||
}
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
//go:build wasm
|
||||
|
||||
package main
|
||||
|
||||
// checkDiskSpace returns the available disk space in MB for the given path.
|
||||
// Returns (availableMB, true) on success, (0, false) on failure.
|
||||
// WASM builds don't support disk space checks.
|
||||
func checkDiskSpace(path string) (uint64, bool) {
|
||||
return 0, false
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/windows"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// checkDiskSpace returns the available disk space in MB for the given path.
|
||||
// Returns (availableMB, true) on success, (0, false) on failure.
|
||||
func checkDiskSpace(path string) (uint64, bool) {
|
||||
var freeBytesAvailable, totalBytes, totalFreeBytes uint64
|
||||
|
||||
pathPtr, err := windows.UTF16PtrFromString(path)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
err = windows.GetDiskFreeSpaceEx(
|
||||
pathPtr,
|
||||
(*uint64)(unsafe.Pointer(&freeBytesAvailable)),
|
||||
(*uint64)(unsafe.Pointer(&totalBytes)),
|
||||
(*uint64)(unsafe.Pointer(&totalFreeBytes)),
|
||||
)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Convert to MB
|
||||
availableMB := freeBytesAvailable / (1024 * 1024)
|
||||
return availableMB, true
|
||||
}
|
||||
|
|
@ -1,597 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestStartRPCServer verifies RPC server initialization and startup
|
||||
func TestStartRPCServer(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
workspacePath := tmpDir
|
||||
dbPath := testDBPath
|
||||
|
||||
log := createTestLogger(t)
|
||||
|
||||
t.Run("starts successfully with valid paths", func(t *testing.T) {
|
||||
server, serverErrChan, err := startRPCServer(ctx, socketPath, testStore, workspacePath, dbPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("startRPCServer failed: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
// Verify server is ready
|
||||
select {
|
||||
case <-server.WaitReady():
|
||||
// Server is ready
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Server did not become ready within 2 seconds")
|
||||
}
|
||||
|
||||
// Verify socket exists and is connectable
|
||||
conn, err := net.Dial("unix", socketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to connect to socket: %v", err)
|
||||
}
|
||||
conn.Close()
|
||||
|
||||
// Verify no error on channel
|
||||
select {
|
||||
case err := <-serverErrChan:
|
||||
t.Errorf("Unexpected error on serverErrChan: %v", err)
|
||||
default:
|
||||
// Expected - no error yet
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fails with invalid socket path", func(t *testing.T) {
|
||||
invalidSocketPath := "/invalid/nonexistent/path/socket.sock"
|
||||
_, _, err := startRPCServer(ctx, invalidSocketPath, testStore, workspacePath, dbPath, log)
|
||||
if err == nil {
|
||||
t.Error("startRPCServer should fail with invalid socket path")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("socket has restricted permissions", func(t *testing.T) {
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel2()
|
||||
|
||||
socketPath2 := filepath.Join(tmpDir, "bd2.sock")
|
||||
server, _, err := startRPCServer(ctx2, socketPath2, testStore, workspacePath, dbPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("startRPCServer failed: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for socket to be created
|
||||
<-server.WaitReady()
|
||||
|
||||
info, err := os.Stat(socketPath2)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to stat socket: %v", err)
|
||||
}
|
||||
|
||||
// Check permissions (should be 0600 or similar restricted)
|
||||
mode := info.Mode().Perm()
|
||||
// On Unix, should be 0600 (owner read/write only)
|
||||
// Accept 0600 or similar restricted permissions
|
||||
if mode > 0644 {
|
||||
t.Errorf("Socket permissions %o are too permissive", mode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestRunEventLoop verifies the polling-based event loop
|
||||
func TestRunEventLoop(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
workspacePath := tmpDir
|
||||
dbPath := testDBPath
|
||||
log := createTestLogger(t)
|
||||
|
||||
// Start RPC server
|
||||
server, serverErrChan, err := startRPCServer(ctx, socketPath, testStore, workspacePath, dbPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
t.Run("processes ticker ticks", func(t *testing.T) {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
tickCount := 0
|
||||
syncFunc := func() {
|
||||
tickCount++
|
||||
}
|
||||
|
||||
// Run event loop in goroutine with short timeout
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
defer cancel2()
|
||||
|
||||
go func() {
|
||||
runEventLoop(ctx2, cancel2, ticker, syncFunc, server, serverErrChan, 0, log)
|
||||
}()
|
||||
|
||||
// Wait for context to finish
|
||||
<-ctx2.Done()
|
||||
|
||||
if tickCount == 0 {
|
||||
t.Error("Event loop should have processed at least one tick")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("responds to context cancellation", func(t *testing.T) {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
ctx2, cancel2 := context.WithCancel(context.Background())
|
||||
syncCalled := false
|
||||
syncFunc := func() {
|
||||
syncCalled = true
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
runEventLoop(ctx2, cancel2, ticker, syncFunc, server, serverErrChan, 0, log)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// Let it run briefly then cancel
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
cancel2()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// Expected - event loop exited
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Event loop did not exit within 2 seconds")
|
||||
}
|
||||
|
||||
if !syncCalled {
|
||||
t.Error("Sync function should have been called at least once")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("handles parent process death", func(t *testing.T) {
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
ctx2, cancel2 := context.WithCancel(context.Background())
|
||||
defer cancel2()
|
||||
|
||||
syncFunc := func() {}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
// Use an invalid (non-existent) parent PID so event loop thinks parent died
|
||||
runEventLoop(ctx2, cancel2, ticker, syncFunc, server, serverErrChan, 999999, log)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// Event loop should detect dead parent within 10 seconds and exit
|
||||
select {
|
||||
case <-done:
|
||||
// Expected - event loop detected dead parent and exited
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("Event loop did not exit after detecting dead parent")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestRunDaemonLoop_HealthyStartup verifies daemon initialization succeeds with proper setup
|
||||
func TestRunDaemonLoop_HealthyStartup(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
initTestGitRepo(t, tmpDir)
|
||||
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "beads.db") // Use canonical name
|
||||
|
||||
// Save original globals and restore after test
|
||||
oldDBPath := dbPath
|
||||
oldStore := store
|
||||
oldWorkingDir, _ := os.Getwd()
|
||||
|
||||
defer func() {
|
||||
dbPath = oldDBPath
|
||||
store = oldStore
|
||||
os.Chdir(oldWorkingDir)
|
||||
}()
|
||||
|
||||
// Set up for daemon
|
||||
dbPath = testDBPath
|
||||
os.Chdir(tmpDir)
|
||||
|
||||
// Create database first
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
t.Run("initialization succeeds with proper database", func(t *testing.T) {
|
||||
// Note: runDaemonLoop is designed to run indefinitely, so we test
|
||||
// that it doesn't panic during initialization rather than running it fully
|
||||
// The full daemon lifecycle is tested in integration with runEventLoop and runEventDrivenLoop
|
||||
|
||||
// Verify database exists and is accessible
|
||||
store = testStore
|
||||
if _, err := os.Stat(testDBPath); err != nil {
|
||||
t.Errorf("Test database should exist: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("validates database file exists", func(t *testing.T) {
|
||||
// This is more of a setup validation than a runDaemonLoop test
|
||||
// since runDaemonLoop is called from main without returning until shutdown
|
||||
|
||||
invalidDBPath := filepath.Join(tmpDir, "nonexistent", "beads.db")
|
||||
if _, err := os.Stat(invalidDBPath); !os.IsNotExist(err) {
|
||||
t.Error("Invalid database path should not exist")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestCheckDaemonHealth verifies health check operations
|
||||
func TestCheckDaemonHealth_StorageAccess(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
log := createTestLogger(t)
|
||||
|
||||
t.Run("completes without error on healthy storage", func(t *testing.T) {
|
||||
// Should not panic or error
|
||||
checkDaemonHealth(ctx, testStore, log)
|
||||
})
|
||||
|
||||
t.Run("logs appropriately when storage is accessible", func(t *testing.T) {
|
||||
// This just verifies it runs without panic
|
||||
// In a real scenario, we'd check log output
|
||||
checkDaemonHealth(ctx, testStore, log)
|
||||
})
|
||||
}
|
||||
|
||||
// TestIsDaemonHealthy verifies daemon health checking via RPC
|
||||
func TestIsDaemonHealthy(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
workspacePath := tmpDir
|
||||
dbPath := testDBPath
|
||||
log := createTestLogger(t)
|
||||
|
||||
t.Run("returns false for unreachable daemon", func(t *testing.T) {
|
||||
unreachableSocket := filepath.Join(tmpDir, "nonexistent.sock")
|
||||
result := isDaemonHealthy(unreachableSocket)
|
||||
if result != false {
|
||||
t.Error("isDaemonHealthy should return false for unreachable daemon")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returns true for running daemon", func(t *testing.T) {
|
||||
server, _, err := startRPCServer(ctx, socketPath, testStore, workspacePath, dbPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
// Give socket time to be fully ready
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
result := isDaemonHealthy(socketPath)
|
||||
if !result {
|
||||
t.Error("isDaemonHealthy should return true for healthy daemon")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("detects stale socket", func(t *testing.T) {
|
||||
staleSocket := filepath.Join(tmpDir, "stale.sock")
|
||||
|
||||
// Create a stale socket file (not actually listening)
|
||||
f, err := os.Create(staleSocket)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create stale socket: %v", err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
result := isDaemonHealthy(staleSocket)
|
||||
if result != false {
|
||||
t.Error("isDaemonHealthy should return false for stale socket")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestEventLoopSignalHandling tests signal handling in event loop
|
||||
func TestEventLoopSignalHandling(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
t.Run("handles SIGTERM gracefully", func(t *testing.T) {
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
workspacePath := tmpDir
|
||||
dbPath := testDBPath
|
||||
log := createTestLogger(t)
|
||||
|
||||
server, serverErrChan, err := startRPCServer(ctx, socketPath, testStore, workspacePath, dbPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
ctx2, cancel2 := context.WithCancel(context.Background())
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
runEventLoop(ctx2, cancel2, ticker, func() {}, server, serverErrChan, 0, log)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// Let it run, then cancel
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
cancel2()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// Expected - event loop exited
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Event loop did not exit after signal")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// createTestLogger creates a *slog.Logger for testing
|
||||
func createTestLogger(t *testing.T) *slog.Logger {
|
||||
return newTestLogger()
|
||||
}
|
||||
|
||||
// TestDaemonIntegration_SocketCleanup verifies socket cleanup after daemon stops
|
||||
func TestDaemonIntegration_SocketCleanup(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
log := createTestLogger(t)
|
||||
|
||||
socketPath := filepath.Join(tmpDir, "bd1.sock")
|
||||
workspacePath := tmpDir
|
||||
dbPath := testDBPath
|
||||
|
||||
ctx1, cancel1 := context.WithTimeout(ctx, 3*time.Second)
|
||||
|
||||
server, _, err := startRPCServer(ctx1, socketPath, testStore, workspacePath, dbPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start server: %v", err)
|
||||
}
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
// Verify socket exists
|
||||
if _, err := os.Stat(socketPath); err != nil {
|
||||
t.Errorf("Socket should exist: %v", err)
|
||||
}
|
||||
|
||||
// Stop server
|
||||
_ = server.Stop()
|
||||
cancel1()
|
||||
|
||||
// Wait for cleanup
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
// Socket should be gone after cleanup
|
||||
if _, err := os.Stat(socketPath); !os.IsNotExist(err) {
|
||||
t.Logf("Socket still exists after stop (may be cleanup timing): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEventDrivenLoop_PeriodicRemoteSync verifies that the event-driven loop
|
||||
// periodically calls doAutoImport to pull updates from remote.
|
||||
// This is a regression test for the bug where the event-driven daemon mode
|
||||
// would not pull remote changes unless the local JSONL file changed.
|
||||
//
|
||||
// Bug scenario:
|
||||
// 1. Clone A creates an issue and daemon pushes to sync branch
|
||||
// 2. Clone B's daemon only watched local file changes
|
||||
// 3. Clone B would not see the new issue until something triggered local change
|
||||
// 4. With this fix: Clone B's daemon periodically calls doAutoImport
|
||||
func TestEventDrivenLoop_PeriodicRemoteSync(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
// Create JSONL file for file watcher
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
if err := os.WriteFile(jsonlPath, []byte{}, 0644); err != nil {
|
||||
t.Fatalf("Failed to create JSONL file: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
workspacePath := tmpDir
|
||||
dbPath := testDBPath
|
||||
log := createTestLogger(t)
|
||||
|
||||
// Start RPC server
|
||||
server, serverErrChan, err := startRPCServer(ctx, socketPath, testStore, workspacePath, dbPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
// Track how many times doAutoImport is called
|
||||
var importCount int
|
||||
var mu sync.Mutex
|
||||
doAutoImport := func() {
|
||||
mu.Lock()
|
||||
importCount++
|
||||
mu.Unlock()
|
||||
}
|
||||
doExport := func() {}
|
||||
|
||||
// Run event-driven loop with short timeout
|
||||
// The remoteSyncTicker fires every 30s, but we can't wait that long in a test
|
||||
// So we verify the structure is correct and the import debouncer is set up
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel2()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
runEventDrivenLoop(ctx2, cancel2, server, serverErrChan, testStore, jsonlPath, doExport, doAutoImport, true, 0, log)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// Wait for context to finish
|
||||
<-done
|
||||
|
||||
// The loop should have started and be ready to handle periodic syncs
|
||||
// We can't easily test the 30s ticker in unit tests, but we verified
|
||||
// the code structure is correct and doAutoImport is wired up
|
||||
t.Log("Event-driven loop with periodic remote sync started successfully")
|
||||
}
|
||||
|
|
@ -1,512 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/daemon"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
)
|
||||
|
||||
// DaemonStatusResponse is returned for daemon status check
|
||||
type DaemonStatusResponse struct {
|
||||
Running bool `json:"running"`
|
||||
PID int `json:"pid,omitempty"`
|
||||
Started string `json:"started,omitempty"`
|
||||
LogPath string `json:"log_path,omitempty"`
|
||||
AutoCommit bool `json:"auto_commit,omitempty"`
|
||||
AutoPush bool `json:"auto_push,omitempty"`
|
||||
LocalMode bool `json:"local_mode,omitempty"`
|
||||
SyncInterval string `json:"sync_interval,omitempty"`
|
||||
DaemonMode string `json:"daemon_mode,omitempty"`
|
||||
}
|
||||
|
||||
// isDaemonRunning checks if the daemon is currently running
|
||||
func isDaemonRunning(pidFile string) (bool, int) {
|
||||
beadsDir := filepath.Dir(pidFile)
|
||||
return tryDaemonLock(beadsDir)
|
||||
}
|
||||
|
||||
// formatUptime formats uptime seconds into a human-readable string
|
||||
func formatUptime(seconds float64) string {
|
||||
if seconds < 60 {
|
||||
return fmt.Sprintf("%.1f seconds", seconds)
|
||||
}
|
||||
if seconds < 3600 {
|
||||
minutes := int(seconds / 60)
|
||||
secs := int(seconds) % 60
|
||||
return fmt.Sprintf("%dm %ds", minutes, secs)
|
||||
}
|
||||
if seconds < 86400 {
|
||||
hours := int(seconds / 3600)
|
||||
minutes := int(seconds/60) % 60
|
||||
return fmt.Sprintf("%dh %dm", hours, minutes)
|
||||
}
|
||||
days := int(seconds / 86400)
|
||||
hours := int(seconds/3600) % 24
|
||||
return fmt.Sprintf("%dd %dh", days, hours)
|
||||
}
|
||||
|
||||
// showDaemonStatus displays the current daemon status
|
||||
func showDaemonStatus(pidFile string) {
|
||||
if isRunning, pid := isDaemonRunning(pidFile); isRunning {
|
||||
var started string
|
||||
if info, err := os.Stat(pidFile); err == nil {
|
||||
started = info.ModTime().Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
var logPath string
|
||||
if lp, err := getLogFilePath(""); err == nil {
|
||||
if _, err := os.Stat(lp); err == nil {
|
||||
logPath = lp
|
||||
}
|
||||
}
|
||||
|
||||
// Try to get detailed status from daemon via RPC
|
||||
var rpcStatus *rpc.StatusResponse
|
||||
beadsDir := filepath.Dir(pidFile)
|
||||
socketPath := rpc.ShortSocketPath(filepath.Dir(beadsDir))
|
||||
if client, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second); err == nil && client != nil {
|
||||
if status, err := client.Status(); err == nil {
|
||||
rpcStatus = status
|
||||
}
|
||||
_ = client.Close()
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
status := DaemonStatusResponse{
|
||||
Running: true,
|
||||
PID: pid,
|
||||
Started: started,
|
||||
LogPath: logPath,
|
||||
}
|
||||
// Add config from RPC status if available
|
||||
if rpcStatus != nil {
|
||||
status.AutoCommit = rpcStatus.AutoCommit
|
||||
status.AutoPush = rpcStatus.AutoPush
|
||||
status.LocalMode = rpcStatus.LocalMode
|
||||
status.SyncInterval = rpcStatus.SyncInterval
|
||||
status.DaemonMode = rpcStatus.DaemonMode
|
||||
}
|
||||
outputJSON(status)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Daemon is running (PID %d)\n", pid)
|
||||
if started != "" {
|
||||
fmt.Printf(" Started: %s\n", started)
|
||||
}
|
||||
if logPath != "" {
|
||||
fmt.Printf(" Log: %s\n", logPath)
|
||||
}
|
||||
// Display config from RPC status if available
|
||||
if rpcStatus != nil {
|
||||
fmt.Printf(" Mode: %s\n", rpcStatus.DaemonMode)
|
||||
fmt.Printf(" Sync Interval: %s\n", rpcStatus.SyncInterval)
|
||||
fmt.Printf(" Auto-Commit: %v\n", rpcStatus.AutoCommit)
|
||||
fmt.Printf(" Auto-Push: %v\n", rpcStatus.AutoPush)
|
||||
fmt.Printf(" Auto-Pull: %v\n", rpcStatus.AutoPull)
|
||||
if rpcStatus.LocalMode {
|
||||
fmt.Printf(" Local Mode: %v (no git sync)\n", rpcStatus.LocalMode)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if jsonOutput {
|
||||
outputJSON(DaemonStatusResponse{Running: false})
|
||||
return
|
||||
}
|
||||
fmt.Println("Daemon is not running")
|
||||
}
|
||||
}
|
||||
|
||||
// showDaemonHealth displays daemon health information
|
||||
func showDaemonHealth() {
|
||||
beadsDir, err := ensureBeadsDir()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
socketPath := rpc.ShortSocketPath(filepath.Dir(beadsDir))
|
||||
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error connecting to daemon: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if client == nil {
|
||||
// Check if lock is held to provide better diagnostic message
|
||||
running, _ := tryDaemonLock(beadsDir)
|
||||
if running {
|
||||
fmt.Println("Daemon lock is held but connection failed")
|
||||
fmt.Println("This may indicate a crashed daemon. Try: bd daemons killall")
|
||||
} else {
|
||||
fmt.Println("Daemon is not running")
|
||||
fmt.Println("Start with: bd daemon start")
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
health, err := client.Health()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error checking health: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
data, _ := json.MarshalIndent(health, "", " ")
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Daemon Health: %s\n", strings.ToUpper(health.Status))
|
||||
|
||||
fmt.Printf(" Version: %s\n", health.Version)
|
||||
fmt.Printf(" Uptime: %s\n", formatUptime(health.Uptime))
|
||||
fmt.Printf(" DB Response Time: %.2f ms\n", health.DBResponseTime)
|
||||
|
||||
if health.Error != "" {
|
||||
fmt.Printf(" Error: %s\n", health.Error)
|
||||
}
|
||||
|
||||
if health.Status == "unhealthy" {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// showDaemonMetrics displays daemon metrics
|
||||
func showDaemonMetrics() {
|
||||
beadsDir, err := ensureBeadsDir()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
socketPath := rpc.ShortSocketPath(filepath.Dir(beadsDir))
|
||||
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error connecting to daemon: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if client == nil {
|
||||
fmt.Println("Daemon is not running")
|
||||
os.Exit(1)
|
||||
}
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
metrics, err := client.Metrics()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error fetching metrics: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
data, _ := json.MarshalIndent(metrics, "", " ")
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
|
||||
// Human-readable output
|
||||
fmt.Printf("Daemon Metrics\n")
|
||||
fmt.Printf("==============\n\n")
|
||||
|
||||
fmt.Printf("Uptime: %.1f seconds (%.1f minutes)\n", metrics.UptimeSeconds, metrics.UptimeSeconds/60)
|
||||
fmt.Printf("Timestamp: %s\n\n", metrics.Timestamp.Format(time.RFC3339))
|
||||
|
||||
// Connection metrics
|
||||
fmt.Printf("Connection Metrics:\n")
|
||||
fmt.Printf(" Total: %d\n", metrics.TotalConns)
|
||||
fmt.Printf(" Active: %d\n", metrics.ActiveConns)
|
||||
fmt.Printf(" Rejected: %d\n\n", metrics.RejectedConns)
|
||||
|
||||
// System metrics
|
||||
fmt.Printf("System Metrics:\n")
|
||||
fmt.Printf(" Memory Alloc: %d MB\n", metrics.MemoryAllocMB)
|
||||
fmt.Printf(" Memory Sys: %d MB\n", metrics.MemorySysMB)
|
||||
fmt.Printf(" Goroutines: %d\n\n", metrics.GoroutineCount)
|
||||
|
||||
// Operation metrics
|
||||
if len(metrics.Operations) > 0 {
|
||||
fmt.Printf("Operation Metrics:\n")
|
||||
for _, op := range metrics.Operations {
|
||||
fmt.Printf("\n %s:\n", op.Operation)
|
||||
fmt.Printf(" Total Requests: %d\n", op.TotalCount)
|
||||
fmt.Printf(" Successful: %d\n", op.SuccessCount)
|
||||
fmt.Printf(" Errors: %d\n", op.ErrorCount)
|
||||
|
||||
if op.Latency.AvgMS > 0 {
|
||||
fmt.Printf(" Latency:\n")
|
||||
fmt.Printf(" Min: %.3f ms\n", op.Latency.MinMS)
|
||||
fmt.Printf(" Avg: %.3f ms\n", op.Latency.AvgMS)
|
||||
fmt.Printf(" P50: %.3f ms\n", op.Latency.P50MS)
|
||||
fmt.Printf(" P95: %.3f ms\n", op.Latency.P95MS)
|
||||
fmt.Printf(" P99: %.3f ms\n", op.Latency.P99MS)
|
||||
fmt.Printf(" Max: %.3f ms\n", op.Latency.MaxMS)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stopDaemon stops a running daemon
|
||||
func stopDaemon(pidFile string) {
|
||||
isRunning, pid := isDaemonRunning(pidFile)
|
||||
if !isRunning {
|
||||
fmt.Println("Daemon is not running")
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Stopping daemon (PID %d)...\n", pid)
|
||||
|
||||
process, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error finding process: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err := sendStopSignal(process); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error signaling daemon: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
for i := 0; i < daemonShutdownAttempts; i++ {
|
||||
time.Sleep(daemonShutdownPollInterval)
|
||||
if isRunning, _ := isDaemonRunning(pidFile); !isRunning {
|
||||
fmt.Println("Daemon stopped")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "Warning: daemon did not stop after %v, forcing termination\n", daemonShutdownTimeout)
|
||||
|
||||
// Check one more time before killing the process to avoid a race.
|
||||
if isRunning, _ := isDaemonRunning(pidFile); !isRunning {
|
||||
fmt.Println("Daemon stopped")
|
||||
return
|
||||
}
|
||||
|
||||
socketPath := getSocketPathForPID(pidFile)
|
||||
|
||||
if err := process.Kill(); err != nil {
|
||||
// Ignore "process already finished" errors
|
||||
if !strings.Contains(err.Error(), "process already finished") {
|
||||
fmt.Fprintf(os.Stderr, "Error killing process: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up stale artifacts after forced kill
|
||||
_ = os.Remove(pidFile) // Best-effort cleanup, file may not exist
|
||||
|
||||
// Also remove socket file if it exists
|
||||
if _, err := os.Stat(socketPath); err == nil {
|
||||
if err := os.Remove(socketPath); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to remove stale socket: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("Daemon killed")
|
||||
}
|
||||
|
||||
// stopAllDaemons stops all running bd daemons
|
||||
func stopAllDaemons() {
|
||||
// Discover all running daemons using the registry
|
||||
daemons, err := daemon.DiscoverDaemons(nil)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error discovering daemons: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Filter to only alive daemons
|
||||
var alive []daemon.DaemonInfo
|
||||
for _, d := range daemons {
|
||||
if d.Alive {
|
||||
alive = append(alive, d)
|
||||
}
|
||||
}
|
||||
|
||||
if len(alive) == 0 {
|
||||
if jsonOutput {
|
||||
fmt.Println(`{"stopped": 0, "message": "No running daemons found"}`)
|
||||
} else {
|
||||
fmt.Println("No running daemons found")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !jsonOutput {
|
||||
fmt.Printf("Found %d running daemon(s), stopping...\n", len(alive))
|
||||
}
|
||||
|
||||
// Stop all daemons (with force=true for stubborn processes)
|
||||
results := daemon.KillAllDaemons(alive, true)
|
||||
|
||||
if jsonOutput {
|
||||
output, _ := json.MarshalIndent(results, "", " ")
|
||||
fmt.Println(string(output))
|
||||
} else {
|
||||
if results.Stopped > 0 {
|
||||
fmt.Printf("✓ Stopped %d daemon(s)\n", results.Stopped)
|
||||
}
|
||||
if results.Failed > 0 {
|
||||
fmt.Printf("✗ Failed to stop %d daemon(s):\n", results.Failed)
|
||||
for _, f := range results.Failures {
|
||||
fmt.Printf(" - PID %d (%s): %s\n", f.PID, f.Workspace, f.Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if results.Failed > 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// startDaemon starts the daemon (in foreground if requested, otherwise background)
|
||||
func startDaemon(interval time.Duration, autoCommit, autoPush, autoPull, localMode, foreground bool, logFile, pidFile, logLevel string, logJSON, federation bool, federationPort, remotesapiPort int) {
|
||||
logPath, err := getLogFilePath(logFile)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Guardrail: single-process backends (e.g., Dolt embedded) must never spawn a daemon process.
|
||||
// Exception: federation mode runs dolt sql-server which enables multi-writer support.
|
||||
// This should already be blocked by command guards, but keep it defensive.
|
||||
if singleProcessOnlyBackend() && !federation {
|
||||
fmt.Fprintf(os.Stderr, "Error: daemon mode is not supported for single-process backends (e.g., dolt). Hint: use sqlite backend for daemon mode, use --federation for dolt server mode, or run commands in direct mode\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Run in foreground if --foreground flag set or if we're the forked child process
|
||||
if foreground || os.Getenv("BD_DAEMON_FOREGROUND") == "1" {
|
||||
runDaemonLoop(interval, autoCommit, autoPush, autoPull, localMode, logPath, pidFile, logLevel, logJSON, federation, federationPort, remotesapiPort)
|
||||
return
|
||||
}
|
||||
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: cannot resolve executable path: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
args := []string{"daemon", "--start",
|
||||
"--interval", interval.String(),
|
||||
}
|
||||
if autoCommit {
|
||||
args = append(args, "--auto-commit")
|
||||
}
|
||||
if autoPush {
|
||||
args = append(args, "--auto-push")
|
||||
}
|
||||
if autoPull {
|
||||
args = append(args, "--auto-pull")
|
||||
}
|
||||
if localMode {
|
||||
args = append(args, "--local")
|
||||
}
|
||||
if logFile != "" {
|
||||
args = append(args, "--log", logFile)
|
||||
}
|
||||
if logLevel != "" && logLevel != "info" {
|
||||
args = append(args, "--log-level", logLevel)
|
||||
}
|
||||
if logJSON {
|
||||
args = append(args, "--log-json")
|
||||
}
|
||||
if federation {
|
||||
args = append(args, "--federation")
|
||||
if federationPort != 0 && federationPort != 3307 {
|
||||
args = append(args, "--federation-port", strconv.Itoa(federationPort))
|
||||
}
|
||||
if remotesapiPort != 0 && remotesapiPort != 8080 {
|
||||
args = append(args, "--remotesapi-port", strconv.Itoa(remotesapiPort))
|
||||
}
|
||||
}
|
||||
|
||||
cmd := exec.Command(exe, args...) // #nosec G204 - bd daemon command from trusted binary
|
||||
cmd.Env = append(os.Environ(), "BD_DAEMON_FOREGROUND=1")
|
||||
configureDaemonProcess(cmd)
|
||||
|
||||
devNull, err := os.OpenFile(os.DevNull, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error opening /dev/null: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer func() { _ = devNull.Close() }()
|
||||
|
||||
cmd.Stdin = devNull
|
||||
cmd.Stdout = devNull
|
||||
cmd.Stderr = devNull
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error starting daemon: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
expectedPID := cmd.Process.Pid
|
||||
|
||||
if err := cmd.Process.Release(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to release process: %v\n", err)
|
||||
}
|
||||
|
||||
for i := 0; i < 20; i++ {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
// #nosec G304 - controlled path from config
|
||||
if data, err := os.ReadFile(pidFile); err == nil {
|
||||
if pid, err := strconv.Atoi(strings.TrimSpace(string(data))); err == nil && pid == expectedPID {
|
||||
fmt.Printf("Daemon started (PID %d)\n", expectedPID)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "Warning: daemon may have failed to start (PID file not confirmed)\n")
|
||||
fmt.Fprintf(os.Stderr, "Check log file: %s\n", logPath)
|
||||
}
|
||||
|
||||
// setupDaemonLock acquires the daemon lock and writes PID file
|
||||
func setupDaemonLock(pidFile string, dbPath string, log *slog.Logger) (*DaemonLock, error) {
|
||||
beadsDir := filepath.Dir(pidFile)
|
||||
|
||||
// Detect nested .beads directories (e.g., .beads/.beads/.beads/)
|
||||
cleanPath := filepath.Clean(beadsDir)
|
||||
if strings.Contains(cleanPath, string(filepath.Separator)+".beads"+string(filepath.Separator)+".beads") {
|
||||
log.Error("nested .beads directory detected", "path", cleanPath)
|
||||
log.Info("hint: do not run 'bd daemon' from inside .beads/ directory")
|
||||
log.Info("hint: use absolute paths for BEADS_DB or run from workspace root")
|
||||
return nil, fmt.Errorf("nested .beads directory detected")
|
||||
}
|
||||
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
if err == ErrDaemonLocked {
|
||||
log.Info("daemon already running (lock held), exiting")
|
||||
} else {
|
||||
log.Error("acquiring daemon lock", "error", err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
myPID := os.Getpid()
|
||||
// #nosec G304 - controlled path from config
|
||||
if data, err := os.ReadFile(pidFile); err == nil {
|
||||
if pid, err := strconv.Atoi(strings.TrimSpace(string(data))); err == nil && pid == myPID {
|
||||
// PID file is correct, continue
|
||||
} else {
|
||||
log.Warn("PID file has wrong PID, overwriting", "expected", myPID, "got", pid)
|
||||
_ = os.WriteFile(pidFile, []byte(fmt.Sprintf("%d\n", myPID)), 0600)
|
||||
}
|
||||
} else {
|
||||
log.Info("PID file missing after lock acquisition, creating")
|
||||
_ = os.WriteFile(pidFile, []byte(fmt.Sprintf("%d\n", myPID)), 0600)
|
||||
}
|
||||
|
||||
return lock, nil
|
||||
}
|
||||
|
|
@ -1,726 +0,0 @@
|
|||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Daemon Lifecycle Race Condition Tests
|
||||
// =============================================================================
|
||||
//
|
||||
// These tests verify correct daemon lifecycle behavior under race conditions.
|
||||
// Run with: go test -race -run TestDaemonLifecycle -v
|
||||
//
|
||||
// Race conditions being tested:
|
||||
// 1. Startup race with multiple clients connecting simultaneously
|
||||
// 2. Shutdown with pending requests
|
||||
// 3. Crash recovery (simulated panic)
|
||||
// 4. Socket cleanup on crash
|
||||
//
|
||||
// =============================================================================
|
||||
|
||||
// TestDaemonStartupRaceWithClients verifies daemon handles multiple clients
|
||||
// attempting to connect during startup.
|
||||
//
|
||||
// Race condition tested: Daemon is starting up while clients are trying to connect.
|
||||
// Clients should either connect successfully or get a clean rejection.
|
||||
func TestDaemonStartupRaceWithClients(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping startup race test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
const numClients = 20
|
||||
var (
|
||||
connectedCount int32
|
||||
failedCount int32
|
||||
startWg sync.WaitGroup
|
||||
connectWg sync.WaitGroup
|
||||
)
|
||||
|
||||
startWg.Add(1)
|
||||
|
||||
// start clients that will try to connect immediately
|
||||
for i := 0; i < numClients; i++ {
|
||||
connectWg.Add(1)
|
||||
go func(clientID int) {
|
||||
defer connectWg.Done()
|
||||
|
||||
// wait for server to start (but may not be ready)
|
||||
startWg.Wait()
|
||||
|
||||
// try to connect with retries
|
||||
var connected bool
|
||||
for attempt := 0; attempt < 10; attempt++ {
|
||||
conn, err := net.DialTimeout("unix", socketPath, 100*time.Millisecond)
|
||||
if err == nil {
|
||||
connected = true
|
||||
conn.Close()
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
|
||||
if connected {
|
||||
atomic.AddInt32(&connectedCount, 1)
|
||||
} else {
|
||||
atomic.AddInt32(&failedCount, 1)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
// start server
|
||||
server, serverErrChan, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
// signal clients to start connecting
|
||||
startWg.Done()
|
||||
|
||||
// wait for server to be ready
|
||||
select {
|
||||
case <-server.WaitReady():
|
||||
// server is ready
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Server did not become ready")
|
||||
}
|
||||
|
||||
// wait for all clients
|
||||
connectWg.Wait()
|
||||
|
||||
t.Logf("Startup race test: %d connected, %d failed", connectedCount, failedCount)
|
||||
|
||||
// most clients should eventually connect
|
||||
if connectedCount < int32(numClients/2) {
|
||||
t.Errorf("Expected at least %d connections, got %d", numClients/2, connectedCount)
|
||||
}
|
||||
|
||||
// verify no server errors
|
||||
select {
|
||||
case err := <-serverErrChan:
|
||||
t.Errorf("Server error during startup race: %v", err)
|
||||
default:
|
||||
// no error, expected
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonShutdownWithPendingRequests verifies graceful shutdown waits for
|
||||
// pending requests to complete.
|
||||
//
|
||||
// Race condition tested: Daemon is processing requests when shutdown is initiated.
|
||||
// Pending requests should complete, new requests should be rejected.
|
||||
func TestDaemonShutdownWithPendingRequests(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping shutdown test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
server, _, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
const numRequests = 10
|
||||
var (
|
||||
completedCount int32
|
||||
failedCount int32
|
||||
requestWg sync.WaitGroup
|
||||
)
|
||||
|
||||
// start requests
|
||||
for i := 0; i < numRequests; i++ {
|
||||
requestWg.Add(1)
|
||||
go func(reqID int) {
|
||||
defer requestWg.Done()
|
||||
|
||||
client, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second)
|
||||
if err != nil || client == nil {
|
||||
atomic.AddInt32(&failedCount, 1)
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
// send a health check request
|
||||
_, err = client.Health()
|
||||
if err != nil {
|
||||
atomic.AddInt32(&failedCount, 1)
|
||||
} else {
|
||||
atomic.AddInt32(&completedCount, 1)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
// give requests time to start
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// initiate shutdown while requests are in flight
|
||||
shutdownStart := time.Now()
|
||||
if err := server.Stop(); err != nil {
|
||||
t.Logf("Server stop returned error (may be expected): %v", err)
|
||||
}
|
||||
shutdownDuration := time.Since(shutdownStart)
|
||||
|
||||
// wait for all requests to complete
|
||||
requestWg.Wait()
|
||||
|
||||
t.Logf("Shutdown test: %d completed, %d failed, shutdown took %v",
|
||||
completedCount, failedCount, shutdownDuration)
|
||||
|
||||
// shutdown should complete in reasonable time
|
||||
if shutdownDuration > 10*time.Second {
|
||||
t.Errorf("Shutdown took too long: %v", shutdownDuration)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonCrashRecoveryWithPanic verifies daemon recovers from handler panics.
|
||||
//
|
||||
// Race condition tested: A handler panics while other requests are in flight.
|
||||
// The panic should be caught and other requests should continue.
|
||||
func TestDaemonCrashRecoveryWithPanic(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping panic recovery test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
server, _, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
// verify server is healthy before any issues
|
||||
client, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second)
|
||||
if err != nil || client == nil {
|
||||
t.Fatalf("Failed to connect before panic test: %v", err)
|
||||
}
|
||||
|
||||
health, err := client.Health()
|
||||
if err != nil {
|
||||
t.Fatalf("Health check failed before panic: %v", err)
|
||||
}
|
||||
if health.Status != "healthy" {
|
||||
t.Fatalf("Server not healthy before panic: %s", health.Status)
|
||||
}
|
||||
client.Close()
|
||||
|
||||
// the RPC server has panic recovery built in (bd-1048)
|
||||
// send multiple requests to verify server continues working
|
||||
const numRequests = 10
|
||||
var successCount int32
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < numRequests; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
c, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second)
|
||||
if err != nil || c == nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
if _, err := c.Health(); err == nil {
|
||||
atomic.AddInt32(&successCount, 1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// most requests should succeed
|
||||
if successCount < int32(numRequests/2) {
|
||||
t.Errorf("Expected at least %d successful requests, got %d", numRequests/2, successCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSocketCleanupOnCrash verifies socket is cleaned up when daemon crashes.
|
||||
//
|
||||
// Race condition tested: Daemon crashes and leaves socket file behind.
|
||||
// New daemon should clean up stale socket and start successfully.
|
||||
func TestSocketCleanupOnCrash(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping socket cleanup test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
// create a stale socket file (simulating crash)
|
||||
f, err := os.Create(socketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create stale socket: %v", err)
|
||||
}
|
||||
f.Close()
|
||||
|
||||
// verify socket exists
|
||||
if _, err := os.Stat(socketPath); err != nil {
|
||||
t.Fatalf("Stale socket should exist: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
// new daemon should clean up stale socket and start
|
||||
server, _, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start server with stale socket: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if server != nil {
|
||||
_ = server.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
// verify server is working
|
||||
client, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second)
|
||||
if err != nil || client == nil {
|
||||
t.Fatalf("Failed to connect after cleanup: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
health, err := client.Health()
|
||||
if err != nil {
|
||||
t.Fatalf("Health check failed: %v", err)
|
||||
}
|
||||
if health.Status != "healthy" {
|
||||
t.Errorf("Server not healthy after cleanup: %s", health.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConcurrentServerStartStop verifies no race when starting/stopping rapidly.
|
||||
//
|
||||
// Race condition tested: Server Start and Stop called in rapid succession.
|
||||
// Should not cause panics or resource leaks.
|
||||
func TestConcurrentServerStartStop(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping concurrent start/stop test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
const cycles = 5
|
||||
for i := 0; i < cycles; i++ {
|
||||
socketPath := filepath.Join(tmpDir, fmt.Sprintf("bd%d.sock", i))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
|
||||
server, _, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
cancel()
|
||||
t.Logf("Cycle %d: failed to start server (may be expected): %v", i, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// wait for ready or timeout
|
||||
select {
|
||||
case <-server.WaitReady():
|
||||
// ready
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Logf("Cycle %d: server did not become ready", i)
|
||||
}
|
||||
|
||||
// stop server
|
||||
if err := server.Stop(); err != nil {
|
||||
t.Logf("Cycle %d: stop error (may be expected): %v", i, err)
|
||||
}
|
||||
|
||||
cancel()
|
||||
|
||||
// small delay between cycles
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonContextCancellation verifies daemon responds to context cancellation.
|
||||
//
|
||||
// Race condition tested: Context is cancelled while daemon is running.
|
||||
// Daemon should shut down gracefully.
|
||||
func TestDaemonContextCancellation(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping context cancellation test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
server, serverErrChan, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
// verify server is working
|
||||
client, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second)
|
||||
if err != nil || client == nil {
|
||||
t.Fatalf("Failed to connect: %v", err)
|
||||
}
|
||||
client.Close()
|
||||
|
||||
// cancel context
|
||||
cancel()
|
||||
|
||||
// wait for server to detect cancellation
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
// stop server explicitly
|
||||
stopErr := server.Stop()
|
||||
t.Logf("Stop after cancel returned: %v", stopErr)
|
||||
|
||||
// verify no panic occurred
|
||||
select {
|
||||
case err := <-serverErrChan:
|
||||
t.Logf("Server error after cancellation: %v", err)
|
||||
default:
|
||||
// no error, expected
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultipleClientsDuringShutdown verifies clients handle shutdown gracefully.
|
||||
//
|
||||
// Race condition tested: Multiple clients connected when shutdown occurs.
|
||||
// All clients should receive errors, not hang.
|
||||
func TestMultipleClientsDuringShutdown(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping multiple clients shutdown test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
server, _, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
const numClients = 10
|
||||
clients := make([]*rpc.Client, 0, numClients)
|
||||
|
||||
// connect all clients
|
||||
for i := 0; i < numClients; i++ {
|
||||
client, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second)
|
||||
if err != nil || client == nil {
|
||||
t.Logf("Client %d failed to connect: %v", i, err)
|
||||
continue
|
||||
}
|
||||
clients = append(clients, client)
|
||||
}
|
||||
|
||||
t.Logf("Connected %d clients", len(clients))
|
||||
|
||||
// start requests from all clients
|
||||
var wg sync.WaitGroup
|
||||
var completedBeforeShutdown int32
|
||||
var completedAfterShutdown int32
|
||||
var errorCount int32
|
||||
|
||||
shutdownStarted := make(chan struct{})
|
||||
|
||||
for i, client := range clients {
|
||||
wg.Add(1)
|
||||
go func(id int, c *rpc.Client) {
|
||||
defer wg.Done()
|
||||
defer c.Close()
|
||||
|
||||
// keep making requests
|
||||
for j := 0; j < 5; j++ {
|
||||
select {
|
||||
case <-shutdownStarted:
|
||||
// after shutdown started
|
||||
_, err := c.Health()
|
||||
if err == nil {
|
||||
atomic.AddInt32(&completedAfterShutdown, 1)
|
||||
} else {
|
||||
atomic.AddInt32(&errorCount, 1)
|
||||
}
|
||||
default:
|
||||
// before shutdown
|
||||
_, err := c.Health()
|
||||
if err == nil {
|
||||
atomic.AddInt32(&completedBeforeShutdown, 1)
|
||||
}
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}(i, client)
|
||||
}
|
||||
|
||||
// let some requests complete
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// signal shutdown started and stop server
|
||||
close(shutdownStarted)
|
||||
if err := server.Stop(); err != nil {
|
||||
t.Logf("Server stop error: %v", err)
|
||||
}
|
||||
|
||||
// wait for all client goroutines with timeout
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// all clients finished
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("Clients did not finish within timeout")
|
||||
}
|
||||
|
||||
t.Logf("Results: %d before shutdown, %d after shutdown, %d errors",
|
||||
completedBeforeShutdown, completedAfterShutdown, errorCount)
|
||||
}
|
||||
|
||||
// TestServerReadyChannelRace verifies WaitReady channel is safe for concurrent use.
|
||||
//
|
||||
// Race condition tested: Multiple goroutines waiting on WaitReady simultaneously.
|
||||
func TestServerReadyChannelRace(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping ready channel race test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
server, _, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
defer server.Stop()
|
||||
|
||||
const numWaiters = 20
|
||||
var readyCount int32
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := 0; i < numWaiters; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
select {
|
||||
case <-server.WaitReady():
|
||||
atomic.AddInt32(&readyCount, 1)
|
||||
case <-time.After(5 * time.Second):
|
||||
// timeout
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
if readyCount != numWaiters {
|
||||
t.Errorf("Expected %d waiters to receive ready, got %d", numWaiters, readyCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEventLoopConcurrentAccess verifies event loop handles concurrent operations.
|
||||
//
|
||||
// Race condition tested: Multiple operations happening during event loop iteration.
|
||||
func TestEventLoopConcurrentAccess(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping event loop concurrent test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDirForLifecycle(t)
|
||||
socketPath := filepath.Join(tmpDir, "bd.sock")
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
server, serverErrChan, err := startRPCServer(ctx, socketPath, testStore, tmpDir, testDBPath, log)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to start RPC server: %v", err)
|
||||
}
|
||||
defer server.Stop()
|
||||
|
||||
<-server.WaitReady()
|
||||
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
var syncCount int32
|
||||
syncFunc := func() {
|
||||
atomic.AddInt32(&syncCount, 1)
|
||||
}
|
||||
|
||||
// run event loop in goroutine
|
||||
loopCtx, loopCancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer loopCancel()
|
||||
|
||||
go func() {
|
||||
runEventLoop(loopCtx, loopCancel, ticker, syncFunc, server, serverErrChan, 0, log)
|
||||
}()
|
||||
|
||||
// concurrent client operations
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 5; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 5; j++ {
|
||||
c, err := rpc.TryConnectWithTimeout(socketPath, 500*time.Millisecond)
|
||||
if err != nil || c == nil {
|
||||
continue
|
||||
}
|
||||
_, _ = c.Health()
|
||||
c.Close()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
<-loopCtx.Done()
|
||||
|
||||
if syncCount == 0 {
|
||||
t.Error("Event loop sync function was never called")
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to create temp dir for lifecycle tests
|
||||
func makeSocketTempDirForLifecycle(t *testing.T) string {
|
||||
t.Helper()
|
||||
// use /tmp for socket paths to avoid path length issues
|
||||
tmpDir, err := os.MkdirTemp("/tmp", "beads-lifecycle-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
os.RemoveAll(tmpDir)
|
||||
})
|
||||
return tmpDir
|
||||
}
|
||||
|
|
@ -1,478 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/sqlite"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestLocalModeFlags tests command-line flag validation for --local mode
|
||||
func TestLocalModeFlags(t *testing.T) {
|
||||
t.Run("local mode is incompatible with auto-commit", func(t *testing.T) {
|
||||
// These flags cannot be used together
|
||||
localMode := true
|
||||
autoCommit := true
|
||||
|
||||
// Validate the constraint (mirrors daemon.go logic)
|
||||
if localMode && autoCommit {
|
||||
// This is the expected error case
|
||||
t.Log("Correctly detected incompatible flags: --local and --auto-commit")
|
||||
} else {
|
||||
t.Error("Expected --local and --auto-commit to be incompatible")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("local mode is incompatible with auto-push", func(t *testing.T) {
|
||||
localMode := true
|
||||
autoPush := true
|
||||
|
||||
if localMode && autoPush {
|
||||
t.Log("Correctly detected incompatible flags: --local and --auto-push")
|
||||
} else {
|
||||
t.Error("Expected --local and --auto-push to be incompatible")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("local mode alone is valid", func(t *testing.T) {
|
||||
localMode := true
|
||||
autoCommit := false
|
||||
autoPush := false
|
||||
|
||||
valid := !((localMode && autoCommit) || (localMode && autoPush))
|
||||
if !valid {
|
||||
t.Error("Expected --local alone to be valid")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestLocalModeGitCheck tests that git repo check is skipped in local mode
|
||||
func TestLocalModeGitCheck(t *testing.T) {
|
||||
t.Run("git check skipped when local mode enabled", func(t *testing.T) {
|
||||
localMode := true
|
||||
inGitRepo := false // Simulate non-git directory
|
||||
|
||||
// Mirrors daemon.go:176 logic
|
||||
shouldFail := !localMode && !inGitRepo
|
||||
|
||||
if shouldFail {
|
||||
t.Error("Expected git check to be skipped in local mode")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("git check enforced when local mode disabled", func(t *testing.T) {
|
||||
localMode := false
|
||||
inGitRepo := false
|
||||
|
||||
shouldFail := !localMode && !inGitRepo
|
||||
|
||||
if !shouldFail {
|
||||
t.Error("Expected git check to fail in non-local mode without git")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestCreateLocalSyncFunc tests the local-only sync function
|
||||
func TestCreateLocalSyncFunc(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
// Create temp directory (no git)
|
||||
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)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "beads.db")
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
|
||||
// Create store
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, testDBPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create store: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Initialize the database with a prefix
|
||||
if err := testStore.SetConfig(ctx, "issue_prefix", "TEST"); err != nil {
|
||||
t.Fatalf("Failed to set issue prefix: %v", err)
|
||||
}
|
||||
|
||||
// Set global dbPath for findJSONLPath
|
||||
oldDBPath := dbPath
|
||||
defer func() { dbPath = oldDBPath }()
|
||||
dbPath = testDBPath
|
||||
|
||||
// Create a test issue
|
||||
issue := &types.Issue{
|
||||
Title: "Local sync test issue",
|
||||
Description: "Testing local sync",
|
||||
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)
|
||||
}
|
||||
|
||||
// Create logger (test output via newTestLogger)
|
||||
log := newTestLogger()
|
||||
|
||||
// Create and run local sync function
|
||||
doSync := createLocalSyncFunc(ctx, testStore, log)
|
||||
doSync()
|
||||
|
||||
// Verify JSONL was created
|
||||
if _, err := os.Stat(jsonlPath); os.IsNotExist(err) {
|
||||
t.Error("Expected JSONL file to be created by local sync")
|
||||
}
|
||||
|
||||
// Verify JSONL contains the issue
|
||||
content, err := os.ReadFile(jsonlPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read JSONL: %v", err)
|
||||
}
|
||||
if len(content) == 0 {
|
||||
t.Error("Expected JSONL to contain issue data")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateLocalExportFunc tests the local-only export function
|
||||
func TestCreateLocalExportFunc(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "beads.db")
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, testDBPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create store: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Initialize the database with a prefix
|
||||
if err := testStore.SetConfig(ctx, "issue_prefix", "TEST"); err != nil {
|
||||
t.Fatalf("Failed to set issue prefix: %v", err)
|
||||
}
|
||||
|
||||
oldDBPath := dbPath
|
||||
defer func() { dbPath = oldDBPath }()
|
||||
dbPath = testDBPath
|
||||
|
||||
// Create test issues
|
||||
for i := 0; i < 3; i++ {
|
||||
issue := &types.Issue{
|
||||
Title: "Export test issue",
|
||||
Description: "Testing local export",
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
doExport := createLocalExportFunc(ctx, testStore, log)
|
||||
doExport()
|
||||
|
||||
// Verify export
|
||||
content, err := os.ReadFile(jsonlPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read JSONL: %v", err)
|
||||
}
|
||||
|
||||
// Count lines (should have 3 issues)
|
||||
lines := 0
|
||||
for _, b := range content {
|
||||
if b == '\n' {
|
||||
lines++
|
||||
}
|
||||
}
|
||||
if lines != 3 {
|
||||
t.Errorf("Expected 3 issues in JSONL, got %d lines", lines)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateLocalAutoImportFunc tests the local-only import function
|
||||
func TestCreateLocalAutoImportFunc(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "beads.db")
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, testDBPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create store: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Initialize the database with a prefix
|
||||
if err := testStore.SetConfig(ctx, "issue_prefix", "TEST"); err != nil {
|
||||
t.Fatalf("Failed to set issue prefix: %v", err)
|
||||
}
|
||||
|
||||
oldDBPath := dbPath
|
||||
defer func() { dbPath = oldDBPath }()
|
||||
dbPath = testDBPath
|
||||
|
||||
// Write a JSONL file directly (simulating external modification)
|
||||
jsonlContent := `{"id":"TEST-abc","title":"Imported issue","description":"From JSONL","status":"open","priority":1,"issue_type":"task","created_at":"2024-01-01T00:00:00Z","updated_at":"2024-01-01T00:00:00Z"}
|
||||
`
|
||||
if err := os.WriteFile(jsonlPath, []byte(jsonlContent), 0644); err != nil {
|
||||
t.Fatalf("Failed to write JSONL: %v", err)
|
||||
}
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
doImport := createLocalAutoImportFunc(ctx, testStore, log)
|
||||
doImport()
|
||||
|
||||
// Verify issue was imported
|
||||
issues, err := testStore.SearchIssues(ctx, "", types.IssueFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to search issues: %v", err)
|
||||
}
|
||||
|
||||
if len(issues) != 1 {
|
||||
t.Errorf("Expected 1 imported issue, got %d", len(issues))
|
||||
}
|
||||
|
||||
if len(issues) > 0 && issues[0].Title != "Imported issue" {
|
||||
t.Errorf("Expected imported issue title 'Imported issue', got '%s'", issues[0].Title)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLocalModeNoGitOperations verifies local functions don't call git
|
||||
func TestLocalModeNoGitOperations(t *testing.T) {
|
||||
// This test verifies the structure of local functions
|
||||
// They should not contain git operations
|
||||
|
||||
t.Run("createLocalSyncFunc has no git calls", func(t *testing.T) {
|
||||
// The local sync function should only:
|
||||
// - Export to JSONL
|
||||
// - Update metadata
|
||||
// - NOT call gitCommit, gitPush, gitPull, etc.
|
||||
t.Log("Verified: createLocalSyncFunc contains no git operations")
|
||||
})
|
||||
|
||||
t.Run("createLocalExportFunc has no git calls", func(t *testing.T) {
|
||||
t.Log("Verified: createLocalExportFunc contains no git operations")
|
||||
})
|
||||
|
||||
t.Run("createLocalAutoImportFunc has no git calls", func(t *testing.T) {
|
||||
t.Log("Verified: createLocalAutoImportFunc contains no git operations")
|
||||
})
|
||||
}
|
||||
|
||||
// TestLocalModeFingerprintValidationSkipped tests that fingerprint validation is skipped
|
||||
func TestLocalModeFingerprintValidationSkipped(t *testing.T) {
|
||||
t.Run("fingerprint validation skipped in local mode", func(t *testing.T) {
|
||||
localMode := true
|
||||
|
||||
// Mirrors daemon.go:396 logic
|
||||
shouldValidate := !localMode
|
||||
|
||||
if shouldValidate {
|
||||
t.Error("Expected fingerprint validation to be skipped in local mode")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fingerprint validation runs in normal mode", func(t *testing.T) {
|
||||
localMode := false
|
||||
|
||||
shouldValidate := !localMode
|
||||
|
||||
if !shouldValidate {
|
||||
t.Error("Expected fingerprint validation to run in normal mode")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestLocalModeInNonGitDirectory is an integration test for the full flow
|
||||
func TestLocalModeInNonGitDirectory(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
// Create a temp directory WITHOUT git
|
||||
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)
|
||||
}
|
||||
|
||||
// Verify it's not a git repo
|
||||
gitDir := filepath.Join(tmpDir, ".git")
|
||||
if _, err := os.Stat(gitDir); !os.IsNotExist(err) {
|
||||
t.Skip("Test directory unexpectedly has .git")
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "beads.db")
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, testDBPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create store: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Initialize the database with a prefix
|
||||
if err := testStore.SetConfig(ctx, "issue_prefix", "TEST"); err != nil {
|
||||
t.Fatalf("Failed to set issue prefix: %v", err)
|
||||
}
|
||||
|
||||
// Save and restore global state
|
||||
oldDBPath := dbPath
|
||||
defer func() { dbPath = oldDBPath }()
|
||||
dbPath = testDBPath
|
||||
|
||||
// Create an issue
|
||||
issue := &types.Issue{
|
||||
Title: "Non-git directory test",
|
||||
Description: "Testing in directory without git",
|
||||
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)
|
||||
}
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
// Run local sync (should work without git)
|
||||
doSync := createLocalSyncFunc(ctx, testStore, log)
|
||||
doSync()
|
||||
|
||||
// Verify JSONL was created
|
||||
if _, err := os.Stat(jsonlPath); os.IsNotExist(err) {
|
||||
t.Fatal("JSONL file should exist after local sync")
|
||||
}
|
||||
|
||||
// Verify we can read the issue back
|
||||
issues, err := testStore.SearchIssues(ctx, "", types.IssueFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to search issues: %v", err)
|
||||
}
|
||||
if len(issues) != 1 {
|
||||
t.Errorf("Expected 1 issue, got %d", len(issues))
|
||||
}
|
||||
|
||||
t.Log("Local mode works correctly in non-git directory")
|
||||
}
|
||||
|
||||
// TestLocalModeExportImportRoundTrip tests export then import cycle
|
||||
func TestLocalModeExportImportRoundTrip(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(beadsDir, "beads.db")
|
||||
jsonlPath := filepath.Join(beadsDir, "issues.jsonl")
|
||||
|
||||
ctx := context.Background()
|
||||
testStore, err := sqlite.New(ctx, testDBPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create store: %v", err)
|
||||
}
|
||||
defer testStore.Close()
|
||||
|
||||
// Initialize the database with a prefix
|
||||
if err := testStore.SetConfig(ctx, "issue_prefix", "TEST"); err != nil {
|
||||
t.Fatalf("Failed to set issue prefix: %v", err)
|
||||
}
|
||||
|
||||
oldDBPath := dbPath
|
||||
defer func() { dbPath = oldDBPath }()
|
||||
dbPath = testDBPath
|
||||
|
||||
log := newTestLogger()
|
||||
|
||||
// Create issues
|
||||
for i := 0; i < 5; i++ {
|
||||
issue := &types.Issue{
|
||||
Title: "Round trip test",
|
||||
Description: "Testing export/import cycle",
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// Export
|
||||
doExport := createLocalExportFunc(ctx, testStore, log)
|
||||
doExport()
|
||||
|
||||
// Verify JSONL exists
|
||||
if _, err := os.Stat(jsonlPath); os.IsNotExist(err) {
|
||||
t.Fatal("JSONL should exist after export")
|
||||
}
|
||||
|
||||
// Modify JSONL externally (add a new issue)
|
||||
content, _ := os.ReadFile(jsonlPath)
|
||||
newIssue := `{"id":"TEST-ext","title":"External issue","description":"Added externally","status":"open","priority":1,"issue_type":"task","created_at":"2024-01-01T00:00:00Z","updated_at":"2024-01-01T00:00:00Z"}
|
||||
`
|
||||
content = append(content, []byte(newIssue)...)
|
||||
if err := os.WriteFile(jsonlPath, content, 0644); err != nil {
|
||||
t.Fatalf("Failed to modify JSONL: %v", err)
|
||||
}
|
||||
|
||||
// Clear the content hash to force import
|
||||
testStore.SetMetadata(ctx, "jsonl_content_hash", "")
|
||||
|
||||
// Small delay to ensure file mtime changes
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Import
|
||||
doImport := createLocalAutoImportFunc(ctx, testStore, log)
|
||||
doImport()
|
||||
|
||||
// Verify issues exist (import may dedupe if content unchanged)
|
||||
issues, err := testStore.SearchIssues(ctx, "", types.IssueFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to search issues: %v", err)
|
||||
}
|
||||
// Should have at least the original 5 issues
|
||||
if len(issues) < 5 {
|
||||
t.Errorf("Expected at least 5 issues after round trip, got %d", len(issues))
|
||||
}
|
||||
t.Logf("Round trip complete: %d issues in database", len(issues))
|
||||
}
|
||||
|
|
@ -1,245 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrDaemonLocked = errors.New("daemon lock already held by another process")
|
||||
|
||||
// DaemonLockInfo represents the metadata stored in the daemon.lock file
|
||||
type DaemonLockInfo struct {
|
||||
PID int `json:"pid"`
|
||||
ParentPID int `json:"parent_pid,omitempty"` // Parent process ID (0 if not tracked)
|
||||
Database string `json:"database"`
|
||||
Version string `json:"version"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
}
|
||||
|
||||
// DaemonLock represents a held lock on the daemon.lock file
|
||||
type DaemonLock struct {
|
||||
file *os.File
|
||||
path string
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
// Close releases the daemon lock and removes the lock file.
|
||||
// It is safe to call concurrently; only the first call performs the close.
|
||||
func (l *DaemonLock) Close() error {
|
||||
l.closeOnce.Do(func() {
|
||||
if l.file == nil {
|
||||
return
|
||||
}
|
||||
// Closing the file descriptor automatically releases the flock
|
||||
l.closeErr = l.file.Close()
|
||||
l.file = nil
|
||||
|
||||
// Best-effort removal of lock file on clean shutdown
|
||||
// This prevents stale lock files when daemon exits normally
|
||||
if l.path != "" {
|
||||
_ = os.Remove(l.path)
|
||||
}
|
||||
})
|
||||
return l.closeErr
|
||||
}
|
||||
|
||||
// acquireDaemonLock attempts to acquire an exclusive lock on daemon.lock
|
||||
// Returns ErrDaemonLocked if another daemon is already running
|
||||
// dbPath is the full path to the database file (e.g., /path/to/.beads/beads.db)
|
||||
func acquireDaemonLock(beadsDir string, dbPath string) (*DaemonLock, error) {
|
||||
lockPath := filepath.Join(beadsDir, "daemon.lock")
|
||||
|
||||
// Open or create the lock file
|
||||
// #nosec G304 - controlled path from config
|
||||
f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot open lock file: %w", err)
|
||||
}
|
||||
|
||||
// Try to acquire exclusive non-blocking lock
|
||||
if err := flockExclusive(f); err != nil {
|
||||
_ = f.Close()
|
||||
if err == ErrDaemonLocked {
|
||||
return nil, ErrDaemonLocked
|
||||
}
|
||||
return nil, fmt.Errorf("cannot lock file: %w", err)
|
||||
}
|
||||
|
||||
// Write JSON metadata to the lock file
|
||||
lockInfo := DaemonLockInfo{
|
||||
PID: os.Getpid(),
|
||||
ParentPID: os.Getppid(),
|
||||
Database: dbPath,
|
||||
Version: Version,
|
||||
StartedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
_ = f.Truncate(0) // Clear file for fresh write (we hold lock)
|
||||
_, _ = f.Seek(0, 0)
|
||||
encoder := json.NewEncoder(f)
|
||||
encoder.SetIndent("", " ")
|
||||
_ = encoder.Encode(lockInfo) // Write can't fail if Truncate succeeded
|
||||
_ = f.Sync() // Best-effort sync to disk
|
||||
|
||||
// Also write PID file for Windows compatibility (can't read locked files on Windows)
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
_ = os.WriteFile(pidFile, []byte(fmt.Sprintf("%d\n", os.Getpid())), 0600) // Best-effort PID write
|
||||
|
||||
return &DaemonLock{file: f, path: lockPath}, nil
|
||||
}
|
||||
|
||||
// tryDaemonLock attempts to acquire and immediately release the daemon lock
|
||||
// to check if a daemon is running. Returns true if daemon is running.
|
||||
//
|
||||
// This function uses flock semantics for reliable daemon detection:
|
||||
// - If flock succeeds: no daemon is running (stale lock file detected and cleaned up)
|
||||
// - If flock fails with EWOULDBLOCK: daemon is actively running
|
||||
//
|
||||
// Falls back to PID file check for backward compatibility with pre-lock daemons.
|
||||
func tryDaemonLock(beadsDir string) (running bool, pid int) {
|
||||
lockPath := filepath.Join(beadsDir, "daemon.lock")
|
||||
|
||||
// Open lock file with read-write access (required for LockFileEx on Windows)
|
||||
// #nosec G304 - controlled path from config
|
||||
f, err := os.OpenFile(lockPath, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
// No lock file - could be old daemon without lock support
|
||||
// Fall back to PID file check for backward compatibility
|
||||
return checkPIDFile(beadsDir)
|
||||
}
|
||||
|
||||
// Try to acquire lock non-blocking
|
||||
if err := flockExclusive(f); err != nil {
|
||||
_ = f.Close()
|
||||
if err == ErrDaemonLocked {
|
||||
// Lock is held by another process - daemon IS running
|
||||
// Re-open to read metadata (we just closed the file)
|
||||
// #nosec G304 - controlled path from config
|
||||
metaFile, metaErr := os.Open(lockPath)
|
||||
if metaErr == nil {
|
||||
defer func() { _ = metaFile.Close() }()
|
||||
var lockInfo DaemonLockInfo
|
||||
if err := json.NewDecoder(metaFile).Decode(&lockInfo); err == nil {
|
||||
pid = lockInfo.PID
|
||||
} else {
|
||||
// Fallback: try reading as plain integer (old format)
|
||||
_, _ = metaFile.Seek(0, 0)
|
||||
data := make([]byte, 32)
|
||||
n, _ := metaFile.Read(data)
|
||||
if n > 0 {
|
||||
_, _ = fmt.Sscanf(string(data[:n]), "%d", &pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Final fallback to PID file if we couldn't read PID from lock file
|
||||
if pid == 0 {
|
||||
_, pid = checkPIDFile(beadsDir)
|
||||
}
|
||||
return true, pid
|
||||
}
|
||||
// Other errors mean we can't determine status
|
||||
return false, 0
|
||||
}
|
||||
|
||||
// We acquired the lock - daemon is NOT running (stale lock file)
|
||||
// Clean up stale lock file to prevent confusion on next check
|
||||
// Close the file first to release the flock before removing
|
||||
_ = f.Close()
|
||||
_ = os.Remove(lockPath)
|
||||
|
||||
// Also clean up stale PID file if it exists
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
_ = os.Remove(pidFile)
|
||||
|
||||
return false, 0
|
||||
}
|
||||
|
||||
// readDaemonLockInfo reads and parses the daemon lock file
|
||||
// Returns lock info if available, or error if file doesn't exist or can't be parsed
|
||||
func readDaemonLockInfo(beadsDir string) (*DaemonLockInfo, error) {
|
||||
lockPath := filepath.Join(beadsDir, "daemon.lock")
|
||||
|
||||
// #nosec G304 - controlled path from config
|
||||
data, err := os.ReadFile(lockPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var lockInfo DaemonLockInfo
|
||||
if err := json.Unmarshal(data, &lockInfo); err != nil {
|
||||
// Try parsing as old format (plain PID)
|
||||
var pid int
|
||||
if _, err := fmt.Sscanf(string(data), "%d", &pid); err == nil {
|
||||
return &DaemonLockInfo{PID: pid}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("cannot parse lock file: %w", err)
|
||||
}
|
||||
|
||||
return &lockInfo, nil
|
||||
}
|
||||
|
||||
// validateDaemonLock validates that the running daemon matches expected parameters
|
||||
// Returns error if validation fails (mismatch detected)
|
||||
func validateDaemonLock(beadsDir string, expectedDB string) error {
|
||||
lockInfo, err := readDaemonLockInfo(beadsDir)
|
||||
if err != nil {
|
||||
// No lock file or can't read - not an error for validation
|
||||
return nil
|
||||
}
|
||||
|
||||
// Validate database path if specified in lock
|
||||
if lockInfo.Database != "" && expectedDB != "" {
|
||||
if lockInfo.Database != expectedDB {
|
||||
return fmt.Errorf("daemon database mismatch: daemon uses %s but expected %s", lockInfo.Database, expectedDB)
|
||||
}
|
||||
}
|
||||
|
||||
// Version mismatch is a warning, not a hard error (handled elsewhere)
|
||||
// But we return the info for caller to decide
|
||||
if lockInfo.Version != "" && lockInfo.Version != Version {
|
||||
// Not a hard error - version compatibility check happens via RPC
|
||||
// This is just informational
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkPIDFile checks if a daemon is running by reading the PID file.
|
||||
// This is used for backward compatibility with pre-lock daemons.
|
||||
func checkPIDFile(beadsDir string) (running bool, pid int) {
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
// #nosec G304 - controlled path from config
|
||||
data, err := os.ReadFile(pidFile)
|
||||
if err != nil {
|
||||
return false, 0
|
||||
}
|
||||
|
||||
pidVal, err := strconv.Atoi(strings.TrimSpace(string(data)))
|
||||
if err != nil {
|
||||
return false, 0
|
||||
}
|
||||
|
||||
if !isProcessRunning(pidVal) {
|
||||
return false, 0
|
||||
}
|
||||
|
||||
return true, pidVal
|
||||
}
|
||||
|
||||
// cleanupDaemonLockFile removes the daemon.lock file (best-effort)
|
||||
// This is called from panic handlers and other cleanup paths
|
||||
func cleanupDaemonLockFile(beadsDir string) {
|
||||
if beadsDir == "" {
|
||||
return
|
||||
}
|
||||
lockPath := filepath.Join(beadsDir, "daemon.lock")
|
||||
_ = os.Remove(lockPath)
|
||||
}
|
||||
|
|
@ -1,666 +0,0 @@
|
|||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// Daemon Lock Race Condition Tests
|
||||
// =============================================================================
|
||||
//
|
||||
// These tests verify correct behavior of daemon locking under concurrent access.
|
||||
// Run with: go test -race -run TestDaemonLock -v
|
||||
//
|
||||
// Race conditions being tested:
|
||||
// 1. Stale lock file detection (daemon crashed, lock file remains)
|
||||
// 2. Lock file cleanup after crash simulation
|
||||
// 3. Concurrent daemon start attempts (multiple processes racing)
|
||||
// 4. PID reuse scenarios (old PID reused by new process)
|
||||
// 5. flock vs file existence checks (timing windows)
|
||||
//
|
||||
// =============================================================================
|
||||
|
||||
// TestStaleLockFileDetection verifies that stale lock files from crashed daemons
|
||||
// are properly detected via flock semantics.
|
||||
//
|
||||
// Race condition tested: A daemon crashes leaving a lock file, but no flock is held.
|
||||
// The lock file exists but should not prevent a new daemon from starting.
|
||||
func TestStaleLockFileDetection(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
lockPath := filepath.Join(beadsDir, "daemon.lock")
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// simulate a crashed daemon by writing a lock file without holding flock
|
||||
stalePID := 999999 // non-existent PID
|
||||
lockContent := fmt.Sprintf(`{"pid":%d,"database":"%s","version":"test"}`, stalePID, dbPath)
|
||||
if err := os.WriteFile(lockPath, []byte(lockContent), 0600); err != nil {
|
||||
t.Fatalf("Failed to write stale lock file: %v", err)
|
||||
}
|
||||
|
||||
// verify file exists
|
||||
if _, err := os.Stat(lockPath); err != nil {
|
||||
t.Fatalf("Lock file should exist: %v", err)
|
||||
}
|
||||
|
||||
// tryDaemonLock should NOT detect a running daemon since flock is not held
|
||||
running, pid := tryDaemonLock(beadsDir)
|
||||
if running && pid == stalePID {
|
||||
// check if process actually exists
|
||||
if !isProcessRunning(stalePID) {
|
||||
t.Log("tryDaemonLock returned running=true but process is dead (PID file fallback)")
|
||||
// this is the PID file fallback behavior - it's actually correct
|
||||
// to detect this via the running process check
|
||||
}
|
||||
}
|
||||
|
||||
// should be able to acquire the lock since flock is not held
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Should be able to acquire lock over stale file: %v", err)
|
||||
}
|
||||
defer lock.Close()
|
||||
|
||||
// verify lock was acquired
|
||||
if lock == nil || lock.file == nil {
|
||||
t.Fatal("Lock should be valid")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLockFileCleanupAfterCrash simulates a daemon crash and verifies cleanup.
|
||||
//
|
||||
// Race condition tested: Daemon holds flock, then crashes (simulated via close).
|
||||
// New daemon should be able to acquire the lock after the old one releases.
|
||||
func TestLockFileCleanupAfterCrash(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// acquire lock
|
||||
lock1, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
|
||||
// verify daemon is detected as running
|
||||
running, pid := tryDaemonLock(beadsDir)
|
||||
if !running {
|
||||
t.Fatal("Daemon should be detected as running while lock is held")
|
||||
}
|
||||
if pid != os.Getpid() {
|
||||
t.Errorf("PID mismatch: expected %d, got %d", os.Getpid(), pid)
|
||||
}
|
||||
|
||||
// simulate crash by closing file (releases flock)
|
||||
lock1.Close()
|
||||
|
||||
// small delay to ensure OS releases flock
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// new daemon should be able to acquire lock
|
||||
lock2, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock after crash: %v", err)
|
||||
}
|
||||
defer lock2.Close()
|
||||
|
||||
// verify new lock is valid
|
||||
if lock2 == nil || lock2.file == nil {
|
||||
t.Fatal("New lock should be valid")
|
||||
}
|
||||
}
|
||||
|
||||
// TestConcurrentDaemonStartAttempts verifies that only one daemon can acquire the lock
|
||||
// when multiple processes attempt to start simultaneously.
|
||||
//
|
||||
// Race condition tested: Multiple goroutines racing to acquire the daemon lock.
|
||||
// Only one should succeed, others should get ErrDaemonLocked.
|
||||
func TestConcurrentDaemonStartAttempts(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
const numAttempts = 10
|
||||
var (
|
||||
successCount int32
|
||||
lockedCount int32
|
||||
errorCount int32
|
||||
acquiredLock *DaemonLock
|
||||
acquiredLockMu sync.Mutex
|
||||
)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
startSignal := make(chan struct{})
|
||||
|
||||
for i := 0; i < numAttempts; i++ {
|
||||
wg.Add(1)
|
||||
go func(id int) {
|
||||
defer wg.Done()
|
||||
|
||||
// wait for start signal to maximize contention
|
||||
<-startSignal
|
||||
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err == nil {
|
||||
atomic.AddInt32(&successCount, 1)
|
||||
acquiredLockMu.Lock()
|
||||
if acquiredLock == nil {
|
||||
acquiredLock = lock
|
||||
} else {
|
||||
// unexpected - two locks succeeded!
|
||||
t.Errorf("Goroutine %d acquired lock but one already exists", id)
|
||||
lock.Close()
|
||||
}
|
||||
acquiredLockMu.Unlock()
|
||||
} else if err == ErrDaemonLocked {
|
||||
atomic.AddInt32(&lockedCount, 1)
|
||||
} else {
|
||||
atomic.AddInt32(&errorCount, 1)
|
||||
t.Logf("Goroutine %d got unexpected error: %v", id, err)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
// release all goroutines simultaneously
|
||||
close(startSignal)
|
||||
wg.Wait()
|
||||
|
||||
// cleanup
|
||||
acquiredLockMu.Lock()
|
||||
if acquiredLock != nil {
|
||||
acquiredLock.Close()
|
||||
}
|
||||
acquiredLockMu.Unlock()
|
||||
|
||||
// verify exactly one success
|
||||
if successCount != 1 {
|
||||
t.Errorf("Expected exactly 1 successful lock acquisition, got %d", successCount)
|
||||
}
|
||||
|
||||
// verify others got ErrDaemonLocked
|
||||
expectedLocked := int32(numAttempts - 1)
|
||||
if lockedCount != expectedLocked {
|
||||
t.Errorf("Expected %d ErrDaemonLocked errors, got %d", expectedLocked, lockedCount)
|
||||
}
|
||||
|
||||
if errorCount > 0 {
|
||||
t.Errorf("Got %d unexpected errors", errorCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPIDReuseScenario verifies correct behavior when a PID is reused by the OS.
|
||||
//
|
||||
// Race condition tested: Old daemon dies, OS reuses PID for a different process.
|
||||
// Lock should be released when file descriptor closes, regardless of PID.
|
||||
func TestPIDReuseScenario(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
|
||||
// acquire lock
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
|
||||
// get current PID from lock file
|
||||
lockInfo, err := readDaemonLockInfo(beadsDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read lock info: %v", err)
|
||||
}
|
||||
|
||||
originalPID := lockInfo.PID
|
||||
t.Logf("Original lock PID: %d", originalPID)
|
||||
|
||||
// simulate PID reuse by writing a different PID to the PID file
|
||||
// (this simulates the scenario where the OS reused the PID)
|
||||
fakePID := 12345
|
||||
if err := os.WriteFile(pidFile, []byte(strconv.Itoa(fakePID)), 0600); err != nil {
|
||||
t.Fatalf("Failed to write fake PID: %v", err)
|
||||
}
|
||||
|
||||
// flock should still be valid regardless of PID file contents
|
||||
running, _ := tryDaemonLock(beadsDir)
|
||||
if !running {
|
||||
t.Error("Daemon should still be detected as running (flock is held)")
|
||||
}
|
||||
|
||||
// release lock
|
||||
lock.Close()
|
||||
|
||||
// now should be able to acquire
|
||||
lock2, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock after release: %v", err)
|
||||
}
|
||||
lock2.Close()
|
||||
}
|
||||
|
||||
// TestFlockVsFileExistenceRace verifies correct behavior when checking lock status
|
||||
// while another process is acquiring/releasing the lock.
|
||||
//
|
||||
// Race condition tested: Process A is acquiring lock while Process B checks status.
|
||||
// There is a brief window between flock acquisition and PID file write where
|
||||
// running=true but pid=0. This is an expected transient state, not an error.
|
||||
// The lock IS held (running=true), we just can't identify the holder momentarily.
|
||||
func TestFlockVsFileExistenceRace(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
const iterations = 100
|
||||
var (
|
||||
transientStateCount int32 // running=true, pid=0 (expected during lock acquisition)
|
||||
lockAcquired int32
|
||||
lockChecked int32
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
|
||||
for i := 0; i < iterations; i++ {
|
||||
wg.Add(2)
|
||||
|
||||
// goroutine 1: acquire and release lock rapidly
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err == nil {
|
||||
atomic.AddInt32(&lockAcquired, 1)
|
||||
time.Sleep(time.Microsecond * 100)
|
||||
lock.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
// goroutine 2: check lock status
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
running, pid := tryDaemonLock(beadsDir)
|
||||
atomic.AddInt32(&lockChecked, 1)
|
||||
// running=true with pid=0 is a valid transient state during lock acquisition
|
||||
// The lock IS held, we just caught the window before PID was written
|
||||
if running && pid == 0 {
|
||||
atomic.AddInt32(&transientStateCount, 1)
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// Log observations for debugging, but don't fail
|
||||
// A small number of transient states is expected due to the flock-then-write pattern
|
||||
t.Logf("iterations=%d, locks_acquired=%d, locks_checked=%d, transient_states=%d",
|
||||
iterations, lockAcquired, lockChecked, transientStateCount)
|
||||
|
||||
// Sanity check: we should have successfully acquired locks
|
||||
if lockAcquired == 0 {
|
||||
t.Error("No locks were acquired - test environment issue")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLockAcquisitionTimeout verifies that lock acquisition doesn't hang indefinitely.
|
||||
//
|
||||
// Race condition tested: One daemon holds lock, another tries to acquire.
|
||||
// The second should fail quickly with ErrDaemonLocked, not block.
|
||||
func TestLockAcquisitionTimeout(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// acquire lock
|
||||
lock1, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire first lock: %v", err)
|
||||
}
|
||||
defer lock1.Close()
|
||||
|
||||
// try to acquire second lock with timeout
|
||||
done := make(chan bool, 1)
|
||||
go func() {
|
||||
start := time.Now()
|
||||
_, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
elapsed := time.Since(start)
|
||||
if err != ErrDaemonLocked {
|
||||
t.Errorf("Expected ErrDaemonLocked, got: %v", err)
|
||||
}
|
||||
// should return quickly (non-blocking)
|
||||
if elapsed > time.Second {
|
||||
t.Errorf("Lock acquisition took too long: %v (expected < 1s)", elapsed)
|
||||
}
|
||||
done <- true
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// expected
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Lock acquisition timed out (blocked indefinitely)")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLockFilePermissions verifies lock file is created with secure permissions.
|
||||
func TestLockFilePermissions(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
lockPath := filepath.Join(beadsDir, "daemon.lock")
|
||||
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
defer lock.Close()
|
||||
|
||||
info, err := os.Stat(lockPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to stat lock file: %v", err)
|
||||
}
|
||||
|
||||
mode := info.Mode().Perm()
|
||||
if mode != 0600 {
|
||||
t.Errorf("Lock file has wrong permissions: %o (expected 0600)", mode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLockFileContentsAfterReacquire verifies lock file contents are updated correctly
|
||||
// when a new daemon acquires the lock after the previous one releases.
|
||||
func TestLockFileContentsAfterReacquire(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// first daemon acquires lock
|
||||
lock1, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire first lock: %v", err)
|
||||
}
|
||||
|
||||
info1, _ := readDaemonLockInfo(beadsDir)
|
||||
lock1.Close()
|
||||
|
||||
// second daemon acquires lock
|
||||
lock2, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire second lock: %v", err)
|
||||
}
|
||||
defer lock2.Close()
|
||||
|
||||
info2, err := readDaemonLockInfo(beadsDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read second lock info: %v", err)
|
||||
}
|
||||
|
||||
// verify timestamp is updated
|
||||
if info1 != nil && !info2.StartedAt.After(info1.StartedAt) {
|
||||
t.Error("Second lock should have later timestamp")
|
||||
}
|
||||
|
||||
// verify PID matches current process
|
||||
if info2.PID != os.Getpid() {
|
||||
t.Errorf("Lock PID mismatch: expected %d, got %d", os.Getpid(), info2.PID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConcurrentTryDaemonLock verifies tryDaemonLock is safe for concurrent use.
|
||||
//
|
||||
// Race condition tested: Multiple goroutines calling tryDaemonLock simultaneously.
|
||||
// Should not cause data races or panics.
|
||||
func TestConcurrentTryDaemonLock(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// acquire lock to have a running daemon
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
defer lock.Close()
|
||||
|
||||
const numGoroutines = 50
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := 0; i < numGoroutines; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 100; j++ {
|
||||
running, pid := tryDaemonLock(beadsDir)
|
||||
// should always be consistent
|
||||
if running && pid <= 0 {
|
||||
t.Errorf("Inconsistent state: running=%v but pid=%d", running, pid)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// TestLockReleaseOnProcessExit verifies flock is released when process exits.
|
||||
// This test spawns a child process to hold the lock, then verifies it's released.
|
||||
func TestLockReleaseOnProcessExit(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping subprocess test in short mode")
|
||||
}
|
||||
|
||||
// Skip if flock command not available (not available on macOS)
|
||||
if _, err := exec.LookPath("flock"); err != nil {
|
||||
t.Skip("Skipping test: flock command not available (Linux-specific)")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
lockPath := filepath.Join(beadsDir, "daemon.lock")
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// create a helper script that acquires lock and exits
|
||||
helperScript := filepath.Join(tmpDir, "lock_holder.sh")
|
||||
scriptContent := fmt.Sprintf(`#!/bin/bash
|
||||
exec 200>"%s"
|
||||
flock -n 200 || exit 1
|
||||
echo $$ > "%s.pid"
|
||||
sleep 5
|
||||
`, lockPath, lockPath)
|
||||
if err := os.WriteFile(helperScript, []byte(scriptContent), 0755); err != nil {
|
||||
t.Fatalf("Failed to write helper script: %v", err)
|
||||
}
|
||||
|
||||
// start the helper process
|
||||
cmd := exec.Command("/bin/bash", helperScript)
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("Failed to start helper: %v", err)
|
||||
}
|
||||
|
||||
// wait for PID file to be written
|
||||
pidFile := lockPath + ".pid"
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
var helperPID int
|
||||
for time.Now().Before(deadline) {
|
||||
if data, err := os.ReadFile(pidFile); err == nil {
|
||||
if pid, err := strconv.Atoi(strings.TrimSpace(string(data))); err == nil {
|
||||
helperPID = pid
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
if helperPID == 0 {
|
||||
cmd.Process.Kill()
|
||||
t.Fatal("Helper process did not write PID file")
|
||||
}
|
||||
|
||||
// verify we cannot acquire lock while helper holds it
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != ErrDaemonLocked {
|
||||
if lock != nil {
|
||||
lock.Close()
|
||||
}
|
||||
t.Errorf("Expected ErrDaemonLocked while helper holds lock, got: %v", err)
|
||||
}
|
||||
|
||||
// kill the helper process
|
||||
if err := syscall.Kill(helperPID, syscall.SIGKILL); err != nil {
|
||||
t.Logf("Warning: failed to kill helper: %v", err)
|
||||
}
|
||||
cmd.Wait()
|
||||
|
||||
// wait for OS to release flock
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// now we should be able to acquire the lock
|
||||
lock, err = acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock after helper exit: %v", err)
|
||||
}
|
||||
lock.Close()
|
||||
}
|
||||
|
||||
// TestRapidLockAcquireRelease tests rapid lock acquire/release cycles
|
||||
// to ensure no resource leaks or deadlocks.
|
||||
func TestRapidLockAcquireRelease(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
const cycles = 100
|
||||
for i := 0; i < cycles; i++ {
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Cycle %d: failed to acquire lock: %v", i, err)
|
||||
}
|
||||
lock.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// TestLockWithParentPID verifies parent PID tracking in lock info.
|
||||
func TestLockWithParentPID(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
defer lock.Close()
|
||||
|
||||
info, err := readDaemonLockInfo(beadsDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read lock info: %v", err)
|
||||
}
|
||||
|
||||
expectedParentPID := os.Getppid()
|
||||
if info.ParentPID != expectedParentPID {
|
||||
t.Errorf("Parent PID mismatch: expected %d, got %d", expectedParentPID, info.ParentPID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConcurrentClose verifies that calling DaemonLock.Close() concurrently
|
||||
// from multiple goroutines does not race or double-close the file descriptor.
|
||||
//
|
||||
// Race condition tested: signal handler and deferred cleanup both calling Close().
|
||||
// Run with: go test -race -run TestConcurrentClose -v
|
||||
func TestConcurrentClose(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
|
||||
// Simulate signal handler + deferred cleanup racing on Close()
|
||||
const goroutines = 10
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, goroutines)
|
||||
|
||||
wg.Add(goroutines)
|
||||
for i := 0; i < goroutines; i++ {
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
errs[idx] = lock.Close()
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// All calls should return the same error (nil on success)
|
||||
for i, e := range errs {
|
||||
if e != nil {
|
||||
t.Errorf("goroutine %d: Close() returned error: %v", i, e)
|
||||
}
|
||||
}
|
||||
|
||||
// A second round of Close() calls should also be safe (idempotent)
|
||||
for i := 0; i < 5; i++ {
|
||||
if err := lock.Close(); err != nil {
|
||||
t.Errorf("subsequent Close() call %d returned error: %v", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,303 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDaemonLockPreventsMultipleInstances(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// Acquire lock
|
||||
lock1, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire first lock: %v", err)
|
||||
}
|
||||
defer lock1.Close()
|
||||
|
||||
// Try to acquire lock again - should fail
|
||||
lock2, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != ErrDaemonLocked {
|
||||
if lock2 != nil {
|
||||
lock2.Close()
|
||||
}
|
||||
t.Fatalf("Expected ErrDaemonLocked, got: %v", err)
|
||||
}
|
||||
|
||||
// Release first lock
|
||||
lock1.Close()
|
||||
|
||||
// Now should be able to acquire lock
|
||||
lock3, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock after release: %v", err)
|
||||
}
|
||||
lock3.Close()
|
||||
}
|
||||
|
||||
func TestTryDaemonLockDetectsRunning(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// Initially no daemon running
|
||||
running, _ := tryDaemonLock(beadsDir)
|
||||
if running {
|
||||
t.Fatal("Expected no daemon running initially")
|
||||
}
|
||||
|
||||
// Acquire lock
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
defer lock.Close()
|
||||
|
||||
// Now should detect daemon running
|
||||
running, pid := tryDaemonLock(beadsDir)
|
||||
if !running {
|
||||
t.Fatal("Expected daemon to be detected as running")
|
||||
}
|
||||
if pid != os.Getpid() {
|
||||
t.Errorf("Expected PID %d, got %d", os.Getpid(), pid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackwardCompatibilityWithOldDaemon(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Simulate old daemon: PID file exists but no lock file
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
currentPID := os.Getpid()
|
||||
if err := os.WriteFile(pidFile, []byte(fmt.Sprintf("%d", currentPID)), 0600); err != nil {
|
||||
t.Fatalf("Failed to write PID file: %v", err)
|
||||
}
|
||||
|
||||
// tryDaemonLock should detect the old daemon via PID file fallback
|
||||
running, pid := tryDaemonLock(beadsDir)
|
||||
if !running {
|
||||
t.Fatal("Expected old daemon to be detected via PID file")
|
||||
}
|
||||
if pid != currentPID {
|
||||
t.Errorf("Expected PID %d, got %d", currentPID, pid)
|
||||
}
|
||||
|
||||
// Clean up PID file
|
||||
os.Remove(pidFile)
|
||||
|
||||
// Now should report no daemon running
|
||||
running, _ = tryDaemonLock(beadsDir)
|
||||
if running {
|
||||
t.Fatal("Expected no daemon running after PID file removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonLockJSONFormat(t *testing.T) {
|
||||
// Skip on Windows - file locking prevents reading lock file while locked
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Windows file locking prevents reading locked files")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// Acquire lock
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
defer lock.Close()
|
||||
|
||||
// Read the lock file and verify JSON format
|
||||
lockInfo, err := readDaemonLockInfo(beadsDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read lock info: %v", err)
|
||||
}
|
||||
|
||||
if lockInfo.PID != os.Getpid() {
|
||||
t.Errorf("Expected PID %d, got %d", os.Getpid(), lockInfo.PID)
|
||||
}
|
||||
|
||||
if lockInfo.Database != dbPath {
|
||||
t.Errorf("Expected database %s, got %s", dbPath, lockInfo.Database)
|
||||
}
|
||||
|
||||
if lockInfo.Version != Version {
|
||||
t.Errorf("Expected version %s, got %s", Version, lockInfo.Version)
|
||||
}
|
||||
|
||||
if lockInfo.StartedAt.IsZero() {
|
||||
t.Error("Expected non-zero StartedAt timestamp")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDaemonLock(t *testing.T) {
|
||||
// Skip on Windows - file locking prevents reading lock file while locked
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Windows file locking prevents reading locked files")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
|
||||
// No lock file - validation should pass
|
||||
if err := validateDaemonLock(beadsDir, dbPath); err != nil {
|
||||
t.Errorf("Expected no error when no lock file exists, got: %v", err)
|
||||
}
|
||||
|
||||
// Acquire lock with correct database
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire lock: %v", err)
|
||||
}
|
||||
defer lock.Close()
|
||||
|
||||
// Validation should pass with matching database
|
||||
if err := validateDaemonLock(beadsDir, dbPath); err != nil {
|
||||
t.Errorf("Expected no error with matching database, got: %v", err)
|
||||
}
|
||||
|
||||
// Validation should fail with different database
|
||||
wrongDB := filepath.Join(beadsDir, "wrong.db")
|
||||
if err := validateDaemonLock(beadsDir, wrongDB); err == nil {
|
||||
t.Error("Expected error with mismatched database")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultipleDaemonProcessesRace(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping race condition test in short mode")
|
||||
}
|
||||
|
||||
// Find the bd binary
|
||||
bdBinary, err := exec.LookPath("bd")
|
||||
if err != nil {
|
||||
// Try local build (platform-specific)
|
||||
localBinary := "./bd"
|
||||
if runtime.GOOS == "windows" {
|
||||
localBinary = "./bd.exe"
|
||||
}
|
||||
if _, err := os.Stat(localBinary); err == nil {
|
||||
bdBinary = localBinary
|
||||
} else {
|
||||
t.Skip("bd binary not found, skipping race test")
|
||||
}
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
beadsDir := filepath.Dir(dbPath)
|
||||
|
||||
// Initialize a test database with git repo
|
||||
if err := os.MkdirAll(beadsDir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Create git repo
|
||||
cmd := exec.Command("git", "init")
|
||||
cmd.Dir = tmpDir
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatalf("Failed to init git repo: %v", err)
|
||||
}
|
||||
|
||||
// Initialize bd
|
||||
cmd = exec.Command(bdBinary, "init", "--prefix", "test")
|
||||
cmd.Dir = tmpDir
|
||||
cmd.Env = append(os.Environ(), "BEADS_DB="+dbPath)
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to init bd: %v\nOutput: %s", err, out)
|
||||
}
|
||||
|
||||
// Try to start 5 daemons simultaneously
|
||||
numAttempts := 5
|
||||
results := make(chan error, numAttempts)
|
||||
|
||||
for i := 0; i < numAttempts; i++ {
|
||||
go func() {
|
||||
cmd := exec.Command(bdBinary, "daemon", "--interval", "10m")
|
||||
cmd.Dir = tmpDir
|
||||
cmd.Env = append(os.Environ(), "BEADS_DB="+dbPath)
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
results <- err
|
||||
return
|
||||
}
|
||||
|
||||
// Wait a bit for daemon to start
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
// Check if it's still running
|
||||
if cmd.Process != nil {
|
||||
cmd.Process.Kill()
|
||||
}
|
||||
results <- cmd.Wait()
|
||||
}()
|
||||
}
|
||||
|
||||
// Wait for all attempts
|
||||
var successCount int
|
||||
var alreadyRunning int
|
||||
timeout := time.After(5 * time.Second)
|
||||
|
||||
for i := 0; i < numAttempts; i++ {
|
||||
select {
|
||||
case err := <-results:
|
||||
if err == nil {
|
||||
successCount++
|
||||
} else if strings.Contains(err.Error(), "exit status 1") {
|
||||
// Could be "already running" error
|
||||
alreadyRunning++
|
||||
}
|
||||
case <-timeout:
|
||||
t.Fatal("Test timed out waiting for daemon processes")
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up any remaining daemon files
|
||||
os.Remove(filepath.Join(beadsDir, "daemon.pid"))
|
||||
os.Remove(filepath.Join(beadsDir, "daemon.lock"))
|
||||
os.Remove(filepath.Join(beadsDir, "bd.sock"))
|
||||
|
||||
t.Logf("Results: %d success, %d already running", successCount, alreadyRunning)
|
||||
|
||||
// At most one should have succeeded in holding the lock
|
||||
// (though timing means even the first might have exited by the time we checked)
|
||||
if alreadyRunning < numAttempts-1 {
|
||||
t.Logf("Warning: Expected at least %d processes to fail with 'already running', got %d",
|
||||
numAttempts-1, alreadyRunning)
|
||||
t.Log("This could indicate a race condition, but may also be timing-related in tests")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
//go:build unix
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// flockExclusive acquires an exclusive non-blocking lock on the file
|
||||
func flockExclusive(f *os.File) error {
|
||||
err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
|
||||
if err == unix.EWOULDBLOCK {
|
||||
return ErrDaemonLocked
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func flockExclusive(f *os.File) error {
|
||||
// WASM doesn't support file locking
|
||||
// In a WASM environment, we're typically single-process anyway
|
||||
return fmt.Errorf("file locking not supported in WASM")
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// flockExclusive acquires an exclusive non-blocking lock on the file using LockFileEx
|
||||
func flockExclusive(f *os.File) error {
|
||||
// LOCKFILE_EXCLUSIVE_LOCK (2) | LOCKFILE_FAIL_IMMEDIATELY (1) = 3
|
||||
const flags = windows.LOCKFILE_EXCLUSIVE_LOCK | windows.LOCKFILE_FAIL_IMMEDIATELY
|
||||
|
||||
// Create overlapped structure for the entire file
|
||||
ol := &windows.Overlapped{}
|
||||
|
||||
// Lock entire file (0xFFFFFFFF, 0xFFFFFFFF = maximum range)
|
||||
err := windows.LockFileEx(
|
||||
windows.Handle(f.Fd()),
|
||||
flags,
|
||||
0, // reserved
|
||||
0xFFFFFFFF, // number of bytes to lock (low)
|
||||
0xFFFFFFFF, // number of bytes to lock (high)
|
||||
ol,
|
||||
)
|
||||
|
||||
if err == windows.ERROR_LOCK_VIOLATION || err == syscall.EWOULDBLOCK {
|
||||
return ErrDaemonLocked
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
// parseLogLevel converts a log level string to slog.Level.
|
||||
func parseLogLevel(level string) slog.Level {
|
||||
switch strings.ToLower(level) {
|
||||
case "debug":
|
||||
return slog.LevelDebug
|
||||
case "info":
|
||||
return slog.LevelInfo
|
||||
case "warn", "warning":
|
||||
return slog.LevelWarn
|
||||
case "error":
|
||||
return slog.LevelError
|
||||
default:
|
||||
return slog.LevelInfo
|
||||
}
|
||||
}
|
||||
|
||||
// setupDaemonLogger creates a structured logger for the daemon.
|
||||
// Returns the lumberjack logger (for cleanup) and the daemon logger.
|
||||
//
|
||||
// Parameters:
|
||||
// - logPath: path to log file (uses lumberjack for rotation)
|
||||
// - jsonFormat: if true, output JSON; otherwise text format
|
||||
// - level: log level (debug, info, warn, error)
|
||||
func setupDaemonLogger(logPath string, jsonFormat bool, level slog.Level) (*lumberjack.Logger, *slog.Logger) {
|
||||
maxSizeMB := getEnvInt("BEADS_DAEMON_LOG_MAX_SIZE", 50)
|
||||
maxBackups := getEnvInt("BEADS_DAEMON_LOG_MAX_BACKUPS", 7)
|
||||
maxAgeDays := getEnvInt("BEADS_DAEMON_LOG_MAX_AGE", 30)
|
||||
compress := getEnvBool("BEADS_DAEMON_LOG_COMPRESS", true)
|
||||
|
||||
logF := &lumberjack.Logger{
|
||||
Filename: logPath,
|
||||
MaxSize: maxSizeMB,
|
||||
MaxBackups: maxBackups,
|
||||
MaxAge: maxAgeDays,
|
||||
Compress: compress,
|
||||
}
|
||||
|
||||
// Create multi-writer to log to both file and stderr (for foreground mode visibility)
|
||||
var w io.Writer = logF
|
||||
|
||||
// Configure slog handler
|
||||
opts := &slog.HandlerOptions{
|
||||
Level: level,
|
||||
}
|
||||
|
||||
var handler slog.Handler
|
||||
if jsonFormat {
|
||||
handler = slog.NewJSONHandler(w, opts)
|
||||
} else {
|
||||
handler = slog.NewTextHandler(w, opts)
|
||||
}
|
||||
|
||||
return logF, slog.New(handler)
|
||||
}
|
||||
|
||||
// SetupStderrLogger creates a logger that writes to stderr only (no file).
|
||||
// Useful for foreground mode or testing.
|
||||
func SetupStderrLogger(jsonFormat bool, level slog.Level) *slog.Logger {
|
||||
opts := &slog.HandlerOptions{
|
||||
Level: level,
|
||||
}
|
||||
|
||||
var handler slog.Handler
|
||||
if jsonFormat {
|
||||
handler = slog.NewJSONHandler(os.Stderr, opts)
|
||||
} else {
|
||||
handler = slog.NewTextHandler(os.Stderr, opts)
|
||||
}
|
||||
|
||||
return slog.New(handler)
|
||||
}
|
||||
|
||||
// newTestLogger creates a no-op logger for testing.
|
||||
// Logs are discarded - use this when you don't need to verify log output.
|
||||
func newTestLogger() *slog.Logger {
|
||||
return newSilentLogger()
|
||||
}
|
||||
|
||||
// newSilentLogger creates a logger that discards all output.
|
||||
// Use this for operations that need a logger but shouldn't produce output.
|
||||
func newSilentLogger() *slog.Logger {
|
||||
return slog.New(slog.DiscardHandler)
|
||||
}
|
||||
|
||||
// newTestLoggerWithWriter creates a logger that writes to the given writer.
|
||||
// Use this when you need to capture and verify log output in tests.
|
||||
func newTestLoggerWithWriter(w io.Writer) *slog.Logger {
|
||||
return slog.New(slog.NewTextHandler(w, nil))
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestDaemonExitsWhenParentDies verifies that the daemon exits when its parent process dies
|
||||
func TestDaemonExitsWhenParentDies(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
t.Skip("Manual test - requires daemon to be run externally")
|
||||
|
||||
// This is a manual test scenario:
|
||||
// 1. Start a shell process that spawns the daemon
|
||||
// 2. Verify daemon tracks parent PID
|
||||
// 3. Kill the shell process
|
||||
// 4. Verify daemon exits within 10-15 seconds
|
||||
//
|
||||
// To test manually:
|
||||
// $ sh -c 'bd daemon --interval 5s & sleep 100' &
|
||||
// $ SHELL_PID=$!
|
||||
// $ # Check daemon.lock has parent_pid set to SHELL_PID
|
||||
// $ kill $SHELL_PID
|
||||
// $ # Daemon should exit within 10-15 seconds
|
||||
}
|
||||
|
||||
func mustAbs(t *testing.T, path string) string {
|
||||
abs, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get absolute path: %v", err)
|
||||
}
|
||||
return abs
|
||||
}
|
||||
|
||||
// runGitCmd is defined in git_sync_test.go
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLogRotation(t *testing.T) {
|
||||
|
||||
// Set small max size for testing (1 MB)
|
||||
os.Setenv("BEADS_DAEMON_LOG_MAX_SIZE", "1")
|
||||
os.Setenv("BEADS_DAEMON_LOG_MAX_BACKUPS", "2")
|
||||
os.Setenv("BEADS_DAEMON_LOG_MAX_AGE", "7")
|
||||
os.Setenv("BEADS_DAEMON_LOG_COMPRESS", "false") // disable for easier testing
|
||||
defer func() {
|
||||
os.Unsetenv("BEADS_DAEMON_LOG_MAX_SIZE")
|
||||
os.Unsetenv("BEADS_DAEMON_LOG_MAX_BACKUPS")
|
||||
os.Unsetenv("BEADS_DAEMON_LOG_MAX_AGE")
|
||||
os.Unsetenv("BEADS_DAEMON_LOG_COMPRESS")
|
||||
}()
|
||||
|
||||
// Test env parsing
|
||||
maxSize := getEnvInt("BEADS_DAEMON_LOG_MAX_SIZE", 10)
|
||||
if maxSize != 1 {
|
||||
t.Errorf("Expected max size 1, got %d", maxSize)
|
||||
}
|
||||
|
||||
maxBackups := getEnvInt("BEADS_DAEMON_LOG_MAX_BACKUPS", 3)
|
||||
if maxBackups != 2 {
|
||||
t.Errorf("Expected max backups 2, got %d", maxBackups)
|
||||
}
|
||||
|
||||
compress := getEnvBool("BEADS_DAEMON_LOG_COMPRESS", true)
|
||||
if compress {
|
||||
t.Errorf("Expected compress false, got true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetEnvInt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
envValue string
|
||||
defaultValue int
|
||||
expected int
|
||||
}{
|
||||
{"not set", "", 10, 10},
|
||||
{"valid int", "42", 10, 42},
|
||||
{"invalid int", "invalid", 10, 10},
|
||||
{"zero", "0", 10, 0},
|
||||
{"negative", "-5", 10, -5},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.envValue != "" {
|
||||
os.Setenv("TEST_INT", tt.envValue)
|
||||
defer os.Unsetenv("TEST_INT")
|
||||
} else {
|
||||
os.Unsetenv("TEST_INT")
|
||||
}
|
||||
|
||||
result := getEnvInt("TEST_INT", tt.defaultValue)
|
||||
if result != tt.expected {
|
||||
t.Errorf("Expected %d, got %d", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetEnvBool(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
envValue string
|
||||
defaultValue bool
|
||||
expected bool
|
||||
}{
|
||||
{"not set default true", "", true, true},
|
||||
{"not set default false", "", false, false},
|
||||
{"true string", "true", false, true},
|
||||
{"1 string", "1", false, true},
|
||||
{"false string", "false", true, false},
|
||||
{"0 string", "0", true, false},
|
||||
{"invalid string", "invalid", true, false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.envValue != "" {
|
||||
os.Setenv("TEST_BOOL", tt.envValue)
|
||||
defer os.Unsetenv("TEST_BOOL")
|
||||
} else {
|
||||
os.Unsetenv("TEST_BOOL")
|
||||
}
|
||||
|
||||
result := getEnvBool("TEST_BOOL", tt.defaultValue)
|
||||
if result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogFileRotationDefaults(t *testing.T) {
|
||||
// Test default values when no env vars set
|
||||
os.Unsetenv("BEADS_DAEMON_LOG_MAX_SIZE")
|
||||
os.Unsetenv("BEADS_DAEMON_LOG_MAX_BACKUPS")
|
||||
os.Unsetenv("BEADS_DAEMON_LOG_MAX_AGE")
|
||||
os.Unsetenv("BEADS_DAEMON_LOG_COMPRESS")
|
||||
|
||||
maxSize := getEnvInt("BEADS_DAEMON_LOG_MAX_SIZE", 50)
|
||||
if maxSize != 50 {
|
||||
t.Errorf("Expected default max size 50, got %d", maxSize)
|
||||
}
|
||||
|
||||
maxBackups := getEnvInt("BEADS_DAEMON_LOG_MAX_BACKUPS", 7)
|
||||
if maxBackups != 7 {
|
||||
t.Errorf("Expected default max backups 7, got %d", maxBackups)
|
||||
}
|
||||
|
||||
maxAge := getEnvInt("BEADS_DAEMON_LOG_MAX_AGE", 30)
|
||||
if maxAge != 30 {
|
||||
t.Errorf("Expected default max age 30, got %d", maxAge)
|
||||
}
|
||||
|
||||
compress := getEnvBool("BEADS_DAEMON_LOG_COMPRESS", true)
|
||||
if !compress {
|
||||
t.Errorf("Expected default compress true, got false")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
)
|
||||
|
||||
// startRPCServer initializes and starts the RPC server
|
||||
func startRPCServer(ctx context.Context, socketPath string, store storage.Storage, workspacePath string, dbPath string, log *slog.Logger) (*rpc.Server, chan error, error) {
|
||||
// Sync daemon version with CLI version
|
||||
rpc.ServerVersion = Version
|
||||
|
||||
server := rpc.NewServer(socketPath, store, workspacePath, dbPath)
|
||||
serverErrChan := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Info("starting RPC server", "socket", socketPath)
|
||||
if err := server.Start(ctx); err != nil {
|
||||
log.Error("RPC server error", "error", err)
|
||||
serverErrChan <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErrChan:
|
||||
log.Error("RPC server failed to start", "error", err)
|
||||
return nil, nil, err
|
||||
case <-server.WaitReady():
|
||||
log.Info("RPC server ready (socket listening)")
|
||||
case <-time.After(5 * time.Second):
|
||||
log.Warn("server didn't signal ready after 5 seconds (may still be starting)")
|
||||
}
|
||||
|
||||
return server, serverErrChan, nil
|
||||
}
|
||||
|
||||
// checkParentProcessAlive checks if the parent process is still running.
|
||||
// Returns true if parent is alive, false if it died.
|
||||
// Returns true if parent PID is 0 or 1 (not tracked, or adopted by init).
|
||||
func checkParentProcessAlive(parentPID int) bool {
|
||||
if parentPID == 0 {
|
||||
// Parent PID not tracked (older lock files)
|
||||
return true
|
||||
}
|
||||
|
||||
if parentPID == 1 {
|
||||
// Adopted by init/launchd - this is normal for detached daemons on macOS/Linux
|
||||
// Don't treat this as parent death
|
||||
return true
|
||||
}
|
||||
|
||||
// Check if parent process is running
|
||||
return isProcessRunning(parentPID)
|
||||
}
|
||||
|
||||
// runEventLoop runs the daemon event loop (polling mode)
|
||||
func runEventLoop(ctx context.Context, cancel context.CancelFunc, ticker *time.Ticker, doSync func(), server *rpc.Server, serverErrChan chan error, parentPID int, log *slog.Logger) {
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, daemonSignals...)
|
||||
defer signal.Stop(sigChan)
|
||||
|
||||
// Parent process check (every 10 seconds)
|
||||
parentCheckTicker := time.NewTicker(10 * time.Second)
|
||||
defer parentCheckTicker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
doSync()
|
||||
case <-parentCheckTicker.C:
|
||||
// Check if parent process is still alive
|
||||
if !checkParentProcessAlive(parentPID) {
|
||||
log.Info("parent process died, shutting down daemon", "parent_pid", parentPID)
|
||||
cancel()
|
||||
if err := server.Stop(); err != nil {
|
||||
log.Error("stopping server", "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
case sig := <-sigChan:
|
||||
if isReloadSignal(sig) {
|
||||
log.Info("received reload signal, ignoring (daemon continues running)")
|
||||
continue
|
||||
}
|
||||
log.Info("received signal, shutting down gracefully", "signal", sig)
|
||||
cancel()
|
||||
if err := server.Stop(); err != nil {
|
||||
log.Error("stopping RPC server", "error", err)
|
||||
}
|
||||
return
|
||||
case <-ctx.Done():
|
||||
log.Info("context canceled, shutting down")
|
||||
if err := server.Stop(); err != nil {
|
||||
log.Error("stopping RPC server", "error", err)
|
||||
}
|
||||
return
|
||||
case err := <-serverErrChan:
|
||||
log.Error("RPC server failed", "error", err)
|
||||
cancel()
|
||||
if err := server.Stop(); err != nil {
|
||||
log.Error("stopping RPC server", "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
)
|
||||
|
||||
// TestSocketPathEnvOverride verifies that BD_SOCKET env var overrides default socket path.
|
||||
func TestSocketPathEnvOverride(t *testing.T) {
|
||||
// Create isolated temp directory
|
||||
tmpDir := t.TempDir()
|
||||
customSocket := filepath.Join(tmpDir, "custom.sock")
|
||||
|
||||
// Set environment for isolation
|
||||
t.Setenv("BD_SOCKET", customSocket)
|
||||
|
||||
// Verify getSocketPath returns custom path
|
||||
got := getSocketPath()
|
||||
if got != customSocket {
|
||||
t.Errorf("getSocketPath() = %q, want %q", got, customSocket)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSocketPathForPIDEnvOverride verifies that BD_SOCKET env var overrides PID-derived path.
|
||||
func TestSocketPathForPIDEnvOverride(t *testing.T) {
|
||||
// Create isolated temp directory
|
||||
tmpDir := t.TempDir()
|
||||
customSocket := filepath.Join(tmpDir, "custom.sock")
|
||||
|
||||
// Set environment for isolation
|
||||
t.Setenv("BD_SOCKET", customSocket)
|
||||
|
||||
// Verify getSocketPathForPID returns custom path (ignoring pidFile)
|
||||
pidFile := "/some/other/path/daemon.pid"
|
||||
got := getSocketPathForPID(pidFile)
|
||||
if got != customSocket {
|
||||
t.Errorf("getSocketPathForPID(%q) = %q, want %q", pidFile, got, customSocket)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSocketPathDefaultBehavior verifies default behavior when BD_SOCKET is not set.
|
||||
func TestSocketPathDefaultBehavior(t *testing.T) {
|
||||
// Ensure BD_SOCKET is not set (t.Setenv restores after test)
|
||||
t.Setenv("BD_SOCKET", "")
|
||||
|
||||
// Verify getSocketPathForPID derives from PID file path
|
||||
pidFile := "/path/to/.beads/daemon.pid"
|
||||
got := getSocketPathForPID(pidFile)
|
||||
want := "/path/to/.beads/bd.sock"
|
||||
if got != want {
|
||||
t.Errorf("getSocketPathForPID(%q) = %q, want %q", pidFile, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSocketPathForPIDLongPath verifies that long workspace paths use shortened socket paths.
|
||||
// This fixes GH#1001 where pytest temp directories exceeded macOS's 104-byte socket path limit.
|
||||
func TestSocketPathForPIDLongPath(t *testing.T) {
|
||||
t.Setenv("BD_SOCKET", "")
|
||||
|
||||
// Create a path that would exceed the 103-byte limit when .beads/bd.sock is appended
|
||||
// /long/path/.beads/daemon.pid -> workspace is /long/path
|
||||
// socket would be /long/path/.beads/bd.sock
|
||||
longWorkspace := "/" + strings.Repeat("a", 90) // 91 bytes
|
||||
pidFile := filepath.Join(longWorkspace, ".beads", "daemon.pid")
|
||||
|
||||
got := getSocketPathForPID(pidFile)
|
||||
|
||||
// Should NOT be the natural path (which would be too long)
|
||||
naturalPath := filepath.Join(longWorkspace, ".beads", "bd.sock")
|
||||
if got == naturalPath {
|
||||
t.Errorf("getSocketPathForPID should use short path for long workspaces, got natural path %q (%d bytes)",
|
||||
got, len(got))
|
||||
}
|
||||
|
||||
// Should be in /tmp/beads-{hash}/
|
||||
if !strings.HasPrefix(got, "/tmp/beads-") {
|
||||
t.Errorf("getSocketPathForPID(%q) = %q, want path starting with /tmp/beads-", pidFile, got)
|
||||
}
|
||||
|
||||
// Should end with bd.sock
|
||||
if !strings.HasSuffix(got, "/bd.sock") {
|
||||
t.Errorf("getSocketPathForPID(%q) = %q, want path ending with /bd.sock", pidFile, got)
|
||||
}
|
||||
|
||||
// Should be under the limit
|
||||
if len(got) > 103 {
|
||||
t.Errorf("getSocketPathForPID returned path of %d bytes, want <= 103", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// TestSocketPathForPIDClientDaemonAgreement verifies that getSocketPathForPID
|
||||
// returns the same path as rpc.ShortSocketPath for the same workspace.
|
||||
// This is critical - if they disagree, the daemon listens on one path while
|
||||
// the client tries to connect to another, causing connection failures.
|
||||
// This test caught the GH#1001 bug where daemon.go used filepath.Join directly
|
||||
// instead of rpc.ShortSocketPath.
|
||||
func TestSocketPathForPIDClientDaemonAgreement(t *testing.T) {
|
||||
t.Setenv("BD_SOCKET", "")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
workspacePath string
|
||||
}{
|
||||
{"short_path", "/home/user/project"},
|
||||
{"medium_path", "/Users/testuser/Documents/projects/myapp"},
|
||||
{"long_path", "/" + strings.Repeat("a", 90)}, // Forces short socket path
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// What getSocketPathForPID returns (used by daemon operations)
|
||||
pidFile := filepath.Join(tt.workspacePath, ".beads", "daemon.pid")
|
||||
fromPID := getSocketPathForPID(pidFile)
|
||||
|
||||
// What rpc.ShortSocketPath returns (used by client via getSocketPath)
|
||||
fromRPC := rpc.ShortSocketPath(tt.workspacePath)
|
||||
|
||||
if fromPID != fromRPC {
|
||||
t.Errorf("socket path mismatch for workspace %q:\n getSocketPathForPID: %q\n rpc.ShortSocketPath: %q",
|
||||
tt.workspacePath, fromPID, fromRPC)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonLoopSocketPathEnvOverride verifies that the daemon loop respects BD_SOCKET.
|
||||
// This tests the fix for GH#XXXX where filesystems that don't support sockets in .beads/
|
||||
// (e.g., some mounted filesystems) couldn't run the daemon.
|
||||
func TestDaemonLoopSocketPathEnvOverride(t *testing.T) {
|
||||
// Create isolated temp directory
|
||||
tmpDir := t.TempDir()
|
||||
customSocket := filepath.Join(tmpDir, "custom.sock")
|
||||
|
||||
// Set environment for isolation
|
||||
t.Setenv("BD_SOCKET", customSocket)
|
||||
|
||||
// Simulate the daemon loop's socket path determination logic
|
||||
// (same logic as in runDaemonLoop in daemon.go)
|
||||
workspacePath := "/some/workspace"
|
||||
socketPath := os.Getenv("BD_SOCKET")
|
||||
if socketPath == "" {
|
||||
socketPath = rpc.ShortSocketPath(workspacePath)
|
||||
}
|
||||
|
||||
// Verify the daemon would use the custom socket path
|
||||
if socketPath != customSocket {
|
||||
t.Errorf("daemon socket path = %q, want %q", socketPath, customSocket)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonLoopSocketPathDefault verifies default socket path when BD_SOCKET is not set.
|
||||
func TestDaemonLoopSocketPathDefault(t *testing.T) {
|
||||
t.Setenv("BD_SOCKET", "")
|
||||
|
||||
workspacePath := "/home/user/project"
|
||||
|
||||
// Simulate the daemon loop's socket path determination logic
|
||||
socketPath := os.Getenv("BD_SOCKET")
|
||||
if socketPath == "" {
|
||||
socketPath = rpc.ShortSocketPath(workspacePath)
|
||||
}
|
||||
|
||||
// Should use the default path from rpc.ShortSocketPath
|
||||
expected := rpc.ShortSocketPath(workspacePath)
|
||||
if socketPath != expected {
|
||||
t.Errorf("daemon socket path = %q, want %q", socketPath, expected)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonSocketIsolation demonstrates that two test instances can use different sockets.
|
||||
// This is the key pattern for parallel test isolation.
|
||||
func TestDaemonSocketIsolation(t *testing.T) {
|
||||
// Simulate two parallel tests with different socket paths
|
||||
tests := []struct {
|
||||
name string
|
||||
sockSuffix string
|
||||
}{
|
||||
{"instance_a", "a.sock"},
|
||||
{"instance_b", "b.sock"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Each sub-test gets isolated socket path in its own temp dir
|
||||
socketPath := filepath.Join(t.TempDir(), tt.sockSuffix)
|
||||
t.Setenv("BD_SOCKET", socketPath)
|
||||
|
||||
got := getSocketPath()
|
||||
if got != socketPath {
|
||||
t.Errorf("getSocketPath() = %q, want %q", got, socketPath)
|
||||
}
|
||||
|
||||
// Verify paths are unique per instance
|
||||
if !strings.Contains(got, tt.sockSuffix) {
|
||||
t.Errorf("getSocketPath() = %q, want it to contain %q", got, tt.sockSuffix)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,181 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
)
|
||||
|
||||
var daemonStartCmd = &cobra.Command{
|
||||
Use: "start",
|
||||
Short: "Start the background daemon",
|
||||
Long: `Start the background daemon that automatically syncs issues with git remote.
|
||||
|
||||
The daemon will:
|
||||
- Poll for changes at configurable intervals (default: 5 seconds)
|
||||
- Export pending database changes to JSONL
|
||||
- Auto-commit changes if --auto-commit flag set
|
||||
- Auto-push commits if --auto-push flag set
|
||||
- Pull remote changes periodically
|
||||
- Auto-import when remote changes detected
|
||||
|
||||
Federation mode (--federation):
|
||||
- Starts dolt sql-server for multi-writer support
|
||||
- Exposes remotesapi on port 8080 for peer-to-peer push/pull
|
||||
- Enables real-time sync between Gas Towns
|
||||
|
||||
Examples:
|
||||
bd daemon start # Start with defaults
|
||||
bd daemon start --auto-commit # Enable auto-commit
|
||||
bd daemon start --auto-push # Enable auto-push (implies --auto-commit)
|
||||
bd daemon start --foreground # Run in foreground (for systemd/supervisord)
|
||||
bd daemon start --local # Local-only mode (no git sync)
|
||||
bd daemon start --federation # Enable federation mode (dolt sql-server)`,
|
||||
PreRunE: guardDaemonStartForDolt,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
interval, _ := cmd.Flags().GetDuration("interval")
|
||||
autoCommit, _ := cmd.Flags().GetBool("auto-commit")
|
||||
autoPush, _ := cmd.Flags().GetBool("auto-push")
|
||||
autoPull, _ := cmd.Flags().GetBool("auto-pull")
|
||||
localMode, _ := cmd.Flags().GetBool("local")
|
||||
logFile, _ := cmd.Flags().GetString("log")
|
||||
foreground, _ := cmd.Flags().GetBool("foreground")
|
||||
logLevel, _ := cmd.Flags().GetString("log-level")
|
||||
logJSON, _ := cmd.Flags().GetBool("log-json")
|
||||
federation, _ := cmd.Flags().GetBool("federation")
|
||||
federationPort, _ := cmd.Flags().GetInt("federation-port")
|
||||
remotesapiPort, _ := cmd.Flags().GetInt("remotesapi-port")
|
||||
|
||||
// NOTE: Only load daemon auto-settings from the database in foreground mode.
|
||||
//
|
||||
// In background mode, `bd daemon start` spawns a child process to run the
|
||||
// daemon loop. Opening the database here in the parent process can briefly
|
||||
// hold Dolt's LOCK file long enough for the child to time out and fall back
|
||||
// to read-only mode (100ms lock timeout), which can break startup.
|
||||
//
|
||||
// In background mode, auto-settings are loaded in the actual daemon process
|
||||
// (the BD_DAEMON_FOREGROUND=1 child spawned by startDaemon).
|
||||
if foreground {
|
||||
autoCommit, autoPush, autoPull = loadDaemonAutoSettings(cmd, autoCommit, autoPush, autoPull)
|
||||
} else {
|
||||
// In background mode, load YAML/env settings for the startup message
|
||||
// (full settings including database are loaded in the child process)
|
||||
if yamlCommit, yamlPush, yamlPull, hasSettings := loadYAMLDaemonSettings(); hasSettings {
|
||||
autoCommit, autoPush, autoPull = yamlCommit, yamlPush, yamlPull
|
||||
}
|
||||
}
|
||||
|
||||
if interval <= 0 {
|
||||
fmt.Fprintf(os.Stderr, "Error: interval must be positive (got %v)\n", interval)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
pidFile, err := getPIDFilePath()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Skip daemon-running check if we're the forked child (BD_DAEMON_FOREGROUND=1)
|
||||
if os.Getenv("BD_DAEMON_FOREGROUND") != "1" {
|
||||
// Check if daemon is already running
|
||||
if isRunning, pid := isDaemonRunning(pidFile); isRunning {
|
||||
// Check if running daemon has compatible version
|
||||
socketPath := getSocketPathForPID(pidFile)
|
||||
if client, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second); err == nil && client != nil {
|
||||
health, healthErr := client.Health()
|
||||
_ = client.Close()
|
||||
|
||||
// If we can check version and it's compatible, exit successfully (idempotent)
|
||||
if healthErr == nil && health.Compatible {
|
||||
fmt.Printf("Daemon already running (PID %d, version %s)\n", pid, health.Version)
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// Version mismatch - auto-stop old daemon
|
||||
if healthErr == nil && !health.Compatible {
|
||||
fmt.Fprintf(os.Stderr, "Warning: daemon version mismatch (daemon: %s, client: %s)\n", health.Version, Version)
|
||||
fmt.Fprintf(os.Stderr, "Stopping old daemon and starting new one...\n")
|
||||
stopDaemon(pidFile)
|
||||
}
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: daemon already running (PID %d)\n", pid)
|
||||
fmt.Fprintf(os.Stderr, "Use 'bd daemon stop' to stop it first\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate --local mode constraints
|
||||
if localMode {
|
||||
if autoCommit {
|
||||
fmt.Fprintf(os.Stderr, "Error: --auto-commit cannot be used with --local mode\n")
|
||||
fmt.Fprintf(os.Stderr, "Hint: --local mode runs without git, so commits are not possible\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
if autoPush {
|
||||
fmt.Fprintf(os.Stderr, "Error: --auto-push cannot be used with --local mode\n")
|
||||
fmt.Fprintf(os.Stderr, "Hint: --local mode runs without git, so pushes are not possible\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Validate we're in a git repo (skip in local mode)
|
||||
if !localMode && !isGitRepo() {
|
||||
fmt.Fprintf(os.Stderr, "Error: not in a git repository\n")
|
||||
fmt.Fprintf(os.Stderr, "Hint: run 'git init' to initialize a repository, or use --local for local-only mode\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Check for upstream if auto-push enabled
|
||||
if autoPush && !gitHasUpstream() {
|
||||
fmt.Fprintf(os.Stderr, "Error: no upstream configured (required for --auto-push)\n")
|
||||
fmt.Fprintf(os.Stderr, "Hint: git push -u origin <branch-name>\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Warn if starting daemon in a git worktree
|
||||
if dbPath == "" {
|
||||
if foundDB := beads.FindDatabasePath(); foundDB != "" {
|
||||
dbPath = foundDB
|
||||
}
|
||||
}
|
||||
if dbPath != "" {
|
||||
warnWorktreeDaemon(dbPath)
|
||||
}
|
||||
|
||||
// Start daemon
|
||||
if localMode {
|
||||
fmt.Printf("Starting bd daemon in LOCAL mode (interval: %v, no git sync)\n", interval)
|
||||
} else if federation {
|
||||
fmt.Printf("Starting bd daemon in FEDERATION mode (interval: %v, dolt sql-server with remotesapi)\n", interval)
|
||||
} else {
|
||||
fmt.Printf("Starting bd daemon (interval: %v, auto-commit: %v, auto-push: %v, auto-pull: %v)\n",
|
||||
interval, autoCommit, autoPush, autoPull)
|
||||
}
|
||||
if logFile != "" {
|
||||
fmt.Printf("Logging to: %s\n", logFile)
|
||||
}
|
||||
|
||||
startDaemon(interval, autoCommit, autoPush, autoPull, localMode, foreground, logFile, pidFile, logLevel, logJSON, federation, federationPort, remotesapiPort)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
daemonStartCmd.Flags().Duration("interval", 5*time.Second, "Sync check interval")
|
||||
daemonStartCmd.Flags().Bool("auto-commit", false, "Automatically commit changes")
|
||||
daemonStartCmd.Flags().Bool("auto-push", false, "Automatically push commits")
|
||||
daemonStartCmd.Flags().Bool("auto-pull", false, "Automatically pull from remote")
|
||||
daemonStartCmd.Flags().Bool("local", false, "Run in local-only mode (no git required, no sync)")
|
||||
daemonStartCmd.Flags().String("log", "", "Log file path (default: .beads/daemon.log)")
|
||||
daemonStartCmd.Flags().Bool("foreground", false, "Run in foreground (don't daemonize)")
|
||||
daemonStartCmd.Flags().String("log-level", "info", "Log level (debug, info, warn, error)")
|
||||
daemonStartCmd.Flags().Bool("log-json", false, "Output logs in JSON format")
|
||||
daemonStartCmd.Flags().Bool("federation", false, "Enable federation mode (runs dolt sql-server)")
|
||||
daemonStartCmd.Flags().Int("federation-port", 3307, "MySQL port for federation mode dolt sql-server")
|
||||
daemonStartCmd.Flags().Int("remotesapi-port", 8080, "remotesapi port for peer-to-peer sync in federation mode")
|
||||
}
|
||||
|
|
@ -1,444 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/daemon"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
)
|
||||
|
||||
// DaemonStatusReport is a single daemon status entry for JSON output
|
||||
type DaemonStatusReport struct {
|
||||
Workspace string `json:"workspace"`
|
||||
PID int `json:"pid,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Issue string `json:"issue,omitempty"`
|
||||
Started string `json:"started,omitempty"`
|
||||
UptimeSeconds float64 `json:"uptime_seconds,omitempty"`
|
||||
AutoCommit bool `json:"auto_commit,omitempty"`
|
||||
AutoPush bool `json:"auto_push,omitempty"`
|
||||
AutoPull bool `json:"auto_pull,omitempty"`
|
||||
LocalMode bool `json:"local_mode,omitempty"`
|
||||
SyncInterval string `json:"sync_interval,omitempty"`
|
||||
DaemonMode string `json:"daemon_mode,omitempty"`
|
||||
LogPath string `json:"log_path,omitempty"`
|
||||
VersionMismatch bool `json:"version_mismatch,omitempty"`
|
||||
IsCurrent bool `json:"is_current,omitempty"`
|
||||
}
|
||||
|
||||
// DaemonStatusAllResponse is returned for --all mode
|
||||
type DaemonStatusAllResponse struct {
|
||||
Total int `json:"total"`
|
||||
Healthy int `json:"healthy"`
|
||||
Outdated int `json:"outdated"`
|
||||
Stale int `json:"stale"`
|
||||
Unresponsive int `json:"unresponsive"`
|
||||
Daemons []DaemonStatusReport `json:"daemons"`
|
||||
}
|
||||
|
||||
var daemonStatusCmd = &cobra.Command{
|
||||
Use: "status",
|
||||
Short: "Show daemon status",
|
||||
Long: `Show status of the current workspace's daemon, or all daemons with --all.
|
||||
|
||||
Examples:
|
||||
bd daemon status # Current workspace daemon
|
||||
bd daemon status --all # All running daemons`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
showAll, _ := cmd.Flags().GetBool("all")
|
||||
|
||||
if showAll {
|
||||
showAllDaemonsStatus(cmd)
|
||||
} else {
|
||||
showCurrentDaemonStatus()
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
daemonStatusCmd.Flags().Bool("all", false, "Show status of all daemons")
|
||||
daemonStatusCmd.Flags().StringSlice("search", nil, "Directories to search for daemons (with --all)")
|
||||
}
|
||||
|
||||
// shortenPath replaces home directory with ~ for display
|
||||
func shortenPath(p string) string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return p
|
||||
}
|
||||
if strings.HasPrefix(p, home) {
|
||||
return "~" + p[len(home):]
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// formatRelativeTime formats a time as relative (e.g., "2h ago")
|
||||
func formatRelativeTime(t time.Time) string {
|
||||
d := time.Since(t)
|
||||
if d < time.Minute {
|
||||
return "just now"
|
||||
} else if d < time.Hour {
|
||||
mins := int(d.Minutes())
|
||||
if mins == 1 {
|
||||
return "1m ago"
|
||||
}
|
||||
return fmt.Sprintf("%dm ago", mins)
|
||||
} else if d < 24*time.Hour {
|
||||
hours := int(d.Hours())
|
||||
if hours == 1 {
|
||||
return "1h ago"
|
||||
}
|
||||
return fmt.Sprintf("%dh ago", hours)
|
||||
}
|
||||
days := int(d.Hours() / 24)
|
||||
if days == 1 {
|
||||
return "1d ago"
|
||||
}
|
||||
return fmt.Sprintf("%dd ago", days)
|
||||
}
|
||||
|
||||
// formatBoolIcon returns a styled checkmark or dash for boolean values
|
||||
func formatBoolIcon(enabled bool) string {
|
||||
if enabled {
|
||||
return ui.RenderPass(ui.IconPass)
|
||||
}
|
||||
return ui.RenderMuted("-")
|
||||
}
|
||||
|
||||
// renderDaemonStatusIcon renders status with semantic styling
|
||||
func renderDaemonStatusIcon(status string) string {
|
||||
switch status {
|
||||
case "healthy", "running":
|
||||
return ui.RenderPass(ui.IconPass + " " + status)
|
||||
case "outdated", "version_mismatch":
|
||||
return ui.RenderWarn(ui.IconWarn + " outdated")
|
||||
case "stale":
|
||||
return ui.RenderWarn(ui.IconWarn + " stale")
|
||||
case "unresponsive":
|
||||
return ui.RenderFail(ui.IconFail + " unresponsive")
|
||||
case "not_running":
|
||||
return ui.RenderMuted("○ not running")
|
||||
default:
|
||||
return status
|
||||
}
|
||||
}
|
||||
|
||||
// showCurrentDaemonStatus shows detailed status for current workspace daemon
|
||||
func showCurrentDaemonStatus() {
|
||||
pidFile, err := getPIDFilePath()
|
||||
if err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": err.Error()})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
beadsDir := filepath.Dir(pidFile)
|
||||
workspacePath := filepath.Dir(beadsDir)
|
||||
socketPath := rpc.ShortSocketPath(workspacePath)
|
||||
|
||||
// Check if daemon is running
|
||||
isRunning, pid := isDaemonRunning(pidFile)
|
||||
if !isRunning {
|
||||
if jsonOutput {
|
||||
outputJSON(DaemonStatusReport{
|
||||
Workspace: workspacePath,
|
||||
Status: "not_running",
|
||||
})
|
||||
} else {
|
||||
fmt.Printf("%s\n\n", renderDaemonStatusIcon("not_running"))
|
||||
fmt.Printf(" Workspace: %s\n", shortenPath(workspacePath))
|
||||
fmt.Printf("\n To start: bd daemon start\n")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Get detailed status via RPC
|
||||
var rpcStatus *rpc.StatusResponse
|
||||
if client, err := rpc.TryConnectWithTimeout(socketPath, 1*time.Second); err == nil && client != nil {
|
||||
if status, err := client.Status(); err == nil {
|
||||
rpcStatus = status
|
||||
}
|
||||
_ = client.Close()
|
||||
}
|
||||
|
||||
// Get started time from PID file
|
||||
var startedTime time.Time
|
||||
if info, err := os.Stat(pidFile); err == nil {
|
||||
startedTime = info.ModTime()
|
||||
}
|
||||
|
||||
// Determine daemon version and check for mismatch
|
||||
daemonVersion := ""
|
||||
versionMismatch := false
|
||||
if rpcStatus != nil {
|
||||
daemonVersion = rpcStatus.Version
|
||||
if daemonVersion != "" && daemonVersion != Version {
|
||||
versionMismatch = true
|
||||
}
|
||||
}
|
||||
|
||||
// Determine status
|
||||
status := "running"
|
||||
issue := ""
|
||||
if versionMismatch {
|
||||
status = "outdated"
|
||||
issue = fmt.Sprintf("daemon %s != cli %s", daemonVersion, Version)
|
||||
}
|
||||
|
||||
// Get log path
|
||||
logPath := filepath.Join(beadsDir, "daemon.log")
|
||||
if _, err := os.Stat(logPath); err != nil {
|
||||
logPath = ""
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
report := DaemonStatusReport{
|
||||
Workspace: workspacePath,
|
||||
PID: pid,
|
||||
Version: daemonVersion,
|
||||
Status: status,
|
||||
Issue: issue,
|
||||
LogPath: logPath,
|
||||
VersionMismatch: versionMismatch,
|
||||
IsCurrent: true,
|
||||
}
|
||||
if !startedTime.IsZero() {
|
||||
report.Started = startedTime.Format(time.RFC3339)
|
||||
}
|
||||
if rpcStatus != nil {
|
||||
report.UptimeSeconds = rpcStatus.UptimeSeconds
|
||||
report.AutoCommit = rpcStatus.AutoCommit
|
||||
report.AutoPush = rpcStatus.AutoPush
|
||||
report.AutoPull = rpcStatus.AutoPull
|
||||
report.LocalMode = rpcStatus.LocalMode
|
||||
report.SyncInterval = rpcStatus.SyncInterval
|
||||
report.DaemonMode = rpcStatus.DaemonMode
|
||||
}
|
||||
outputJSON(report)
|
||||
return
|
||||
}
|
||||
|
||||
// Human-readable output with semantic styling
|
||||
// Status line
|
||||
versionStr := ""
|
||||
if daemonVersion != "" {
|
||||
versionStr = fmt.Sprintf(", v%s", daemonVersion)
|
||||
}
|
||||
if versionMismatch {
|
||||
fmt.Printf("%s (PID %d%s)\n", renderDaemonStatusIcon("outdated"), pid, versionStr)
|
||||
fmt.Printf(" %s\n\n", ui.RenderWarn(fmt.Sprintf("CLI version: %s", Version)))
|
||||
} else {
|
||||
fmt.Printf("%s (PID %d%s)\n\n", renderDaemonStatusIcon("running"), pid, versionStr)
|
||||
}
|
||||
|
||||
// Details
|
||||
fmt.Printf(" Workspace: %s\n", shortenPath(workspacePath))
|
||||
if !startedTime.IsZero() {
|
||||
fmt.Printf(" Started: %s (%s)\n", startedTime.Format("2006-01-02 15:04:05"), formatRelativeTime(startedTime))
|
||||
}
|
||||
|
||||
if rpcStatus != nil {
|
||||
fmt.Printf(" Mode: %s\n", rpcStatus.DaemonMode)
|
||||
fmt.Printf(" Interval: %s\n", rpcStatus.SyncInterval)
|
||||
|
||||
// Compact sync flags display
|
||||
syncFlags := []string{}
|
||||
if rpcStatus.AutoCommit {
|
||||
syncFlags = append(syncFlags, ui.RenderPass(ui.IconPass)+" commit")
|
||||
}
|
||||
if rpcStatus.AutoPush {
|
||||
syncFlags = append(syncFlags, ui.RenderPass(ui.IconPass)+" push")
|
||||
}
|
||||
if rpcStatus.AutoPull {
|
||||
syncFlags = append(syncFlags, ui.RenderPass(ui.IconPass)+" pull")
|
||||
}
|
||||
if len(syncFlags) > 0 {
|
||||
fmt.Printf(" Sync: %s\n", strings.Join(syncFlags, " "))
|
||||
} else {
|
||||
fmt.Printf(" Sync: %s\n", ui.RenderMuted("none"))
|
||||
}
|
||||
|
||||
if rpcStatus.LocalMode {
|
||||
fmt.Printf(" Local: %s\n", ui.RenderWarn("yes (no git sync)"))
|
||||
}
|
||||
}
|
||||
|
||||
if logPath != "" {
|
||||
// Show relative path for log
|
||||
relLog := ".beads/daemon.log"
|
||||
fmt.Printf(" Log: %s\n", relLog)
|
||||
}
|
||||
|
||||
// Show hint about other daemons
|
||||
daemons, err := daemon.DiscoverDaemons(nil)
|
||||
if err == nil {
|
||||
aliveCount := 0
|
||||
for _, d := range daemons {
|
||||
if d.Alive {
|
||||
aliveCount++
|
||||
}
|
||||
}
|
||||
if aliveCount > 1 {
|
||||
fmt.Printf("\n %s\n", ui.RenderMuted(fmt.Sprintf("%d other daemon(s) running (bd daemon status --all)", aliveCount-1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// showAllDaemonsStatus shows status of all daemons
|
||||
func showAllDaemonsStatus(cmd *cobra.Command) {
|
||||
searchRoots, _ := cmd.Flags().GetStringSlice("search")
|
||||
|
||||
// Discover daemons
|
||||
daemons, err := daemon.DiscoverDaemons(searchRoots)
|
||||
if err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": err.Error()})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error discovering daemons: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Auto-cleanup stale sockets
|
||||
if cleaned, err := daemon.CleanupStaleSockets(daemons); err == nil && cleaned > 0 && !jsonOutput {
|
||||
fmt.Fprintf(os.Stderr, "Cleaned up %d stale socket(s)\n", cleaned)
|
||||
}
|
||||
|
||||
// Get current workspace to mark it
|
||||
currentWorkspace := ""
|
||||
if pidFile, err := getPIDFilePath(); err == nil {
|
||||
beadsDir := filepath.Dir(pidFile)
|
||||
currentWorkspace = filepath.Dir(beadsDir)
|
||||
}
|
||||
|
||||
currentVersion := Version
|
||||
var reports []DaemonStatusReport
|
||||
healthyCount := 0
|
||||
outdatedCount := 0
|
||||
staleCount := 0
|
||||
unresponsiveCount := 0
|
||||
|
||||
for _, d := range daemons {
|
||||
report := DaemonStatusReport{
|
||||
Workspace: d.WorkspacePath,
|
||||
PID: d.PID,
|
||||
Version: d.Version,
|
||||
IsCurrent: d.WorkspacePath == currentWorkspace,
|
||||
}
|
||||
|
||||
if !d.Alive {
|
||||
report.Status = "stale"
|
||||
report.Issue = d.Error
|
||||
staleCount++
|
||||
} else if d.Version != "" && d.Version != currentVersion {
|
||||
report.Status = "outdated"
|
||||
report.Issue = fmt.Sprintf("daemon %s != cli %s", d.Version, currentVersion)
|
||||
report.VersionMismatch = true
|
||||
outdatedCount++
|
||||
} else {
|
||||
report.Status = "healthy"
|
||||
healthyCount++
|
||||
}
|
||||
|
||||
reports = append(reports, report)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
outputJSON(DaemonStatusAllResponse{
|
||||
Total: len(reports),
|
||||
Healthy: healthyCount,
|
||||
Outdated: outdatedCount,
|
||||
Stale: staleCount,
|
||||
Unresponsive: unresponsiveCount,
|
||||
Daemons: reports,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Human-readable output
|
||||
if len(reports) == 0 {
|
||||
fmt.Println("No daemons found")
|
||||
return
|
||||
}
|
||||
|
||||
// Summary line
|
||||
fmt.Printf("Daemons: %d total", len(reports))
|
||||
if healthyCount > 0 {
|
||||
fmt.Printf(", %s", ui.RenderPass(fmt.Sprintf("%d healthy", healthyCount)))
|
||||
}
|
||||
if outdatedCount > 0 {
|
||||
fmt.Printf(", %s", ui.RenderWarn(fmt.Sprintf("%d outdated", outdatedCount)))
|
||||
}
|
||||
if staleCount > 0 {
|
||||
fmt.Printf(", %s", ui.RenderWarn(fmt.Sprintf("%d stale", staleCount)))
|
||||
}
|
||||
if unresponsiveCount > 0 {
|
||||
fmt.Printf(", %s", ui.RenderFail(fmt.Sprintf("%d unresponsive", unresponsiveCount)))
|
||||
}
|
||||
fmt.Println()
|
||||
fmt.Println()
|
||||
|
||||
// Table
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||
_, _ = fmt.Fprintln(w, " WORKSPACE\tPID\tVERSION\tSTATUS")
|
||||
|
||||
for _, r := range reports {
|
||||
workspace := shortenPath(r.Workspace)
|
||||
if workspace == "" {
|
||||
workspace = "(unknown)"
|
||||
}
|
||||
|
||||
// Add arrow for current workspace
|
||||
prefix := " "
|
||||
if r.IsCurrent {
|
||||
prefix = ui.RenderAccent("→ ")
|
||||
}
|
||||
|
||||
pidStr := "-"
|
||||
if r.PID != 0 {
|
||||
pidStr = fmt.Sprintf("%d", r.PID)
|
||||
}
|
||||
|
||||
version := r.Version
|
||||
if version == "" {
|
||||
version = "-"
|
||||
}
|
||||
|
||||
// Render status with icon and color
|
||||
var statusDisplay string
|
||||
switch r.Status {
|
||||
case "healthy":
|
||||
statusDisplay = ui.RenderPass(ui.IconPass + " healthy")
|
||||
case "outdated":
|
||||
statusDisplay = ui.RenderWarn(ui.IconWarn + " outdated")
|
||||
// Add version hint
|
||||
statusDisplay += ui.RenderMuted(fmt.Sprintf(" (cli: %s)", currentVersion))
|
||||
case "stale":
|
||||
statusDisplay = ui.RenderWarn(ui.IconWarn + " stale")
|
||||
case "unresponsive":
|
||||
statusDisplay = ui.RenderFail(ui.IconFail + " unresponsive")
|
||||
default:
|
||||
statusDisplay = r.Status
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(w, "%s%s\t%s\t%s\t%s\n",
|
||||
prefix, workspace, pidStr, version, statusDisplay)
|
||||
}
|
||||
_ = w.Flush()
|
||||
|
||||
// Exit with error if there are issues
|
||||
if outdatedCount > 0 || staleCount > 0 || unresponsiveCount > 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,330 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/syncbranch"
|
||||
)
|
||||
|
||||
// syncBranchCommitAndPush commits JSONL to the sync branch using a worktree.
|
||||
// Returns true if changes were committed, false if no changes or sync.branch not configured.
|
||||
// This is a convenience wrapper that calls syncBranchCommitAndPushWithOptions with default options.
|
||||
func syncBranchCommitAndPush(ctx context.Context, store storage.Storage, autoPush bool, log *slog.Logger) (bool, error) {
|
||||
return syncBranchCommitAndPushWithOptions(ctx, store, autoPush, false, log)
|
||||
}
|
||||
|
||||
// syncBranchCommitAndPushWithOptions commits JSONL to the sync branch using a worktree.
|
||||
// Returns true if changes were committed, false if no changes or sync.branch not configured.
|
||||
// If forceOverwrite is true, the local JSONL is copied to the worktree without merging,
|
||||
// which is necessary for delete mutations to be properly reflected in the sync branch.
|
||||
func syncBranchCommitAndPushWithOptions(ctx context.Context, store storage.Storage, autoPush, forceOverwrite bool, log *slog.Logger) (bool, error) {
|
||||
// Check if any remote exists (bd-biwp: support local-only repos)
|
||||
if !hasGitRemote(ctx) {
|
||||
return true, nil // Skip sync branch commit/push in local-only mode
|
||||
}
|
||||
|
||||
// Guard: Skip if sync-branch == current-branch (GH#1258)
|
||||
if shouldSkipDueToSameBranch(ctx, store, "sync-branch commit", log) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Get sync branch configuration (supports BEADS_SYNC_BRANCH override)
|
||||
syncBranch, err := syncbranch.Get(ctx, store)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to get sync branch: %w", err)
|
||||
}
|
||||
|
||||
// If no sync branch configured, caller should use regular commit logic
|
||||
if syncBranch == "" {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Skip JSONL sync branch operations in dolt-native mode (bd-ats9.3.1)
|
||||
// Dolt handles sync through its own Push/Pull methods, not JSONL
|
||||
if !ShouldExportJSONL(ctx, store) {
|
||||
return true, nil // Signal "handled" to prevent fallback to regular git commit
|
||||
}
|
||||
|
||||
log.Info("Using sync branch", "branch", syncBranch)
|
||||
|
||||
// Get main repo root (for worktrees, this is the main repo, not worktree)
|
||||
repoRoot, err := git.GetMainRepoRoot()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to get main repo root: %w", err)
|
||||
}
|
||||
|
||||
// Use GetGitCommonDir() instead of GetGitDir() for worktree creation.
|
||||
// In a bare repo + worktree setup, GetGitDir() returns the worktree-specific
|
||||
// path (e.g., .git/worktrees/main), but we need the common git directory
|
||||
// to create new worktrees. GetGitCommonDir() always returns the bare repo's
|
||||
// .git directory. GH#1500
|
||||
gitDir, err := git.GetGitCommonDir()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to get git common dir: %w", err)
|
||||
}
|
||||
|
||||
// Worktree path is under .git/beads-worktrees/<branch>
|
||||
worktreePath := filepath.Join(gitDir, "beads-worktrees", syncBranch)
|
||||
|
||||
// Initialize worktree manager
|
||||
wtMgr := git.NewWorktreeManager(repoRoot)
|
||||
|
||||
// Ensure worktree exists and is healthy
|
||||
// CreateBeadsWorktree now performs a full health check internally and
|
||||
// automatically repairs unhealthy worktrees by removing and recreating them
|
||||
if err := wtMgr.CreateBeadsWorktree(syncBranch, worktreePath); err != nil {
|
||||
return false, fmt.Errorf("failed to create worktree: %w", err)
|
||||
}
|
||||
|
||||
// Sync JSONL file to worktree
|
||||
// Get the actual JSONL path
|
||||
jsonlPath := findJSONLPath()
|
||||
if jsonlPath == "" {
|
||||
return false, fmt.Errorf("beads storage file not found")
|
||||
}
|
||||
|
||||
// Convert absolute path to relative path from repo root
|
||||
jsonlRelPath, err := filepath.Rel(repoRoot, jsonlPath)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to get relative JSONL path: %w", err)
|
||||
}
|
||||
|
||||
// Use SyncJSONLToWorktreeWithOptions to pass forceOverwrite flag.
|
||||
// When forceOverwrite is true (mutation-triggered sync, especially delete),
|
||||
// the local JSONL is copied directly without merging, ensuring deletions
|
||||
// are properly reflected in the sync branch.
|
||||
syncOpts := git.SyncOptions{ForceOverwrite: forceOverwrite}
|
||||
if err := wtMgr.SyncJSONLToWorktreeWithOptions(worktreePath, jsonlRelPath, syncOpts); err != nil {
|
||||
return false, fmt.Errorf("failed to sync JSONL to worktree: %w", err)
|
||||
}
|
||||
|
||||
// Check for changes in worktree
|
||||
// GH#810: Normalize path for bare repo worktrees
|
||||
normalizedRelPath := git.NormalizeBeadsRelPath(jsonlRelPath)
|
||||
worktreeJSONLPath := filepath.Join(worktreePath, normalizedRelPath)
|
||||
hasChanges, err := gitHasChangesInWorktree(ctx, worktreePath, worktreeJSONLPath)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to check for changes in worktree: %w", err)
|
||||
}
|
||||
|
||||
if !hasChanges {
|
||||
log.Info("No changes to commit in sync branch")
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Commit in worktree
|
||||
message := fmt.Sprintf("bd daemon sync: %s", time.Now().Format("2006-01-02 15:04:05"))
|
||||
if err := gitCommitInWorktree(ctx, worktreePath, worktreeJSONLPath, message); err != nil {
|
||||
return false, fmt.Errorf("failed to commit in worktree: %w", err)
|
||||
}
|
||||
log.Info("Committed changes to sync branch", "branch", syncBranch)
|
||||
|
||||
// Push if enabled
|
||||
if autoPush {
|
||||
// Get configured remote from bd config (sync.remote), default to empty (will use git config)
|
||||
configuredRemote, _ := store.GetConfig(ctx, "sync.remote")
|
||||
if err := gitPushFromWorktree(ctx, worktreePath, syncBranch, configuredRemote); err != nil {
|
||||
return false, fmt.Errorf("failed to push from worktree: %w", err)
|
||||
}
|
||||
log.Info("Pushed sync branch to remote", "branch", syncBranch)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// getGitRoot returns the git repository root directory
|
||||
func getGitRoot(ctx context.Context) (string, error) {
|
||||
cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get git root: %w", err)
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
|
||||
// gitHasChangesInWorktree checks if there are changes in the worktree
|
||||
func gitHasChangesInWorktree(ctx context.Context, worktreePath, filePath string) (bool, error) {
|
||||
// Make filePath relative to worktree
|
||||
relPath, err := filepath.Rel(worktreePath, filePath)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to make path relative: %w", err)
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "status", "--porcelain", relPath) // #nosec G204 - worktreePath and relPath are derived from trusted git operations
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("git status failed in worktree: %w", err)
|
||||
}
|
||||
return len(strings.TrimSpace(string(output))) > 0, nil
|
||||
}
|
||||
|
||||
// gitCommitInWorktree commits changes in the worktree
|
||||
func gitCommitInWorktree(ctx context.Context, worktreePath, filePath, message string) error {
|
||||
// Make filePath relative to worktree
|
||||
relPath, err := filepath.Rel(worktreePath, filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to make path relative: %w", err)
|
||||
}
|
||||
|
||||
// Stage the file
|
||||
// Use --sparse to work correctly with sparse-checkout enabled worktrees (fixes #1076)
|
||||
addCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "add", "--sparse", relPath) // #nosec G204 - worktreePath and relPath are derived from trusted git operations
|
||||
if err := addCmd.Run(); err != nil {
|
||||
return fmt.Errorf("git add failed in worktree: %w", err)
|
||||
}
|
||||
|
||||
// Build commit args with config-based author and signing options (GH#1051)
|
||||
// Also use --no-verify to skip hooks (pre-commit hook would fail in worktree context)
|
||||
// The worktree is internal to bd sync, so we don't need to run bd's pre-commit hook
|
||||
args := []string{"-C", worktreePath, "commit", "--no-verify"}
|
||||
|
||||
// Add --author if configured (GH#1051: apply git.author config to daemon commits)
|
||||
if author := config.GetString("git.author"); author != "" {
|
||||
args = append(args, "--author", author)
|
||||
}
|
||||
|
||||
// Add --no-gpg-sign if configured
|
||||
if config.GetBool("git.no-gpg-sign") {
|
||||
args = append(args, "--no-gpg-sign")
|
||||
}
|
||||
|
||||
args = append(args, "-m", message)
|
||||
|
||||
commitCmd := exec.CommandContext(ctx, "git", args...) // #nosec G204 - args built from trusted config values
|
||||
output, err := commitCmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("git commit failed in worktree: %w\n%s", err, output)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// gitPushFromWorktree pushes the sync branch from the worktree.
|
||||
// If push fails due to remote having newer commits, it will fetch, rebase, and retry.
|
||||
// The configuredRemote parameter allows passing the bd config sync.remote value.
|
||||
func gitPushFromWorktree(ctx context.Context, worktreePath, branch, configuredRemote string) error {
|
||||
// Use configured remote if provided, otherwise check git branch config
|
||||
remote := configuredRemote
|
||||
if remote == "" {
|
||||
remoteCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "config", "--get", fmt.Sprintf("branch.%s.remote", branch)) // #nosec G204 - worktreePath and branch are from config
|
||||
remoteOutput, err := remoteCmd.Output()
|
||||
if err != nil {
|
||||
// If no remote configured, default to "origin" and set up tracking
|
||||
remoteOutput = []byte("origin\n")
|
||||
}
|
||||
remote = strings.TrimSpace(string(remoteOutput))
|
||||
}
|
||||
|
||||
// Push with explicit remote and branch, set upstream if not set
|
||||
cmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "push", "--set-upstream", remote, branch) // #nosec G204 - worktreePath, remote, and branch are from config
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
// Check if push failed due to remote having newer commits
|
||||
outputStr := string(output)
|
||||
if strings.Contains(outputStr, "fetch first") || strings.Contains(outputStr, "non-fast-forward") {
|
||||
// Fetch and rebase, then retry push
|
||||
fetchCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "fetch", remote, branch) // #nosec G204
|
||||
if fetchOutput, fetchErr := fetchCmd.CombinedOutput(); fetchErr != nil {
|
||||
return fmt.Errorf("git fetch failed in worktree: %w\n%s", fetchErr, fetchOutput)
|
||||
}
|
||||
|
||||
// Rebase local commits on top of remote
|
||||
rebaseCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "rebase", remote+"/"+branch) // #nosec G204
|
||||
if rebaseOutput, rebaseErr := rebaseCmd.CombinedOutput(); rebaseErr != nil {
|
||||
// If rebase fails (conflict), abort and return error
|
||||
abortCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "rebase", "--abort") // #nosec G204
|
||||
_ = abortCmd.Run()
|
||||
return fmt.Errorf("git rebase failed in worktree (sync branch may have conflicts): %w\n%s", rebaseErr, rebaseOutput)
|
||||
}
|
||||
|
||||
// Retry push after successful rebase
|
||||
retryCmd := exec.CommandContext(ctx, "git", "-C", worktreePath, "push", "--set-upstream", remote, branch) // #nosec G204
|
||||
if retryOutput, retryErr := retryCmd.CombinedOutput(); retryErr != nil {
|
||||
retryOutputStr := string(retryOutput)
|
||||
if isPushPermissionDenied(retryOutputStr) {
|
||||
showPushPermissionGuidance()
|
||||
}
|
||||
return fmt.Errorf("git push failed after rebase: %w\n%s", retryErr, retryOutput)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
// Check for permission denied errors
|
||||
if isPushPermissionDenied(outputStr) {
|
||||
showPushPermissionGuidance()
|
||||
}
|
||||
return fmt.Errorf("git push failed from worktree: %w\n%s", err, output)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// syncBranchPull pulls changes from the sync branch into the worktree
|
||||
// Returns true if pull was performed, false if sync.branch not configured
|
||||
func syncBranchPull(ctx context.Context, store storage.Storage, log *slog.Logger) (bool, error) {
|
||||
// Check if any remote exists (bd-biwp: support local-only repos)
|
||||
if !hasGitRemote(ctx) {
|
||||
return true, nil // Skip sync branch pull in local-only mode
|
||||
}
|
||||
|
||||
// Guard: Skip if sync-branch == current-branch (GH#1258)
|
||||
if shouldSkipDueToSameBranch(ctx, store, "sync-branch pull", log) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Get sync branch configuration (supports BEADS_SYNC_BRANCH override)
|
||||
syncBranch, err := syncbranch.Get(ctx, store)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to get sync branch: %w", err)
|
||||
}
|
||||
|
||||
// If no sync branch configured, caller should use regular pull logic
|
||||
if syncBranch == "" {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Skip JSONL sync branch operations in dolt-native mode (bd-ats9.3.1)
|
||||
// Dolt handles sync through its own Push/Pull methods, not JSONL
|
||||
if !ShouldExportJSONL(ctx, store) {
|
||||
return true, nil // Signal "handled" to prevent fallback to regular git pull
|
||||
}
|
||||
|
||||
// Get main repo root (for worktrees, this is the main repo, not worktree)
|
||||
repoRoot, err := git.GetMainRepoRoot()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to get main repo root: %w", err)
|
||||
}
|
||||
|
||||
// Get the actual JSONL path
|
||||
jsonlPath := findJSONLPath()
|
||||
if jsonlPath == "" {
|
||||
return false, fmt.Errorf("beads storage file not found")
|
||||
}
|
||||
|
||||
// GH#1358: Use content-based merge (same as manual sync) instead of simple git pull.
|
||||
// This prevents daemon from failing on merge conflicts and entering backoff loops.
|
||||
// PullFromSyncBranch handles divergence gracefully with 3-way content merges,
|
||||
// designed to never fail due to git merge conflicts.
|
||||
result, err := syncbranch.PullFromSyncBranch(ctx, repoRoot, syncBranch, jsonlPath, false)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to pull from sync branch: %w", err)
|
||||
}
|
||||
|
||||
if result.Pulled {
|
||||
log.Info("Pulled sync branch", "branch", syncBranch,
|
||||
"fast_forward", result.FastForwarded, "merged", result.Merged)
|
||||
} else {
|
||||
log.Info("Sync branch is up to date", "branch", syncBranch)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,232 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/storage/sqlite"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestSyncBranchPull_DivergedHistory tests that daemon pull handles diverged sync branches.
|
||||
// This simulates the scenario from GH#1358 where:
|
||||
// 1. Two developers both make changes while daemon is running
|
||||
// 2. Developer A's daemon pushes first (succeeds)
|
||||
// 3. Developer B's daemon tries to push - fails due to divergence, leaves worktree dirty
|
||||
// 4. Developer B's daemon tries to pull on next cycle - FAILS with "unmerged files" error
|
||||
//
|
||||
// This test should FAIL with old code (simple git pull) and PASS with fix (PullFromSyncBranch).
|
||||
func TestSyncBranchPull_DivergedHistory(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Create bare remote repository
|
||||
tmpDir := t.TempDir()
|
||||
remoteDir := filepath.Join(tmpDir, "remote")
|
||||
if err := os.MkdirAll(remoteDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create remote dir: %v", err)
|
||||
}
|
||||
runGitCmd(t, remoteDir, "init", "--bare", "-b", "master")
|
||||
|
||||
syncBranch := "beads-sync"
|
||||
|
||||
// === Developer A Setup ===
|
||||
devADir := filepath.Join(tmpDir, "devA")
|
||||
runGitCmd(t, tmpDir, "clone", remoteDir, devADir)
|
||||
configureGit(t, devADir)
|
||||
|
||||
devABeadsDir := filepath.Join(devADir, ".beads")
|
||||
if err := os.MkdirAll(devABeadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create devA .beads dir: %v", err)
|
||||
}
|
||||
|
||||
devADBPath := filepath.Join(devABeadsDir, "test.db")
|
||||
storeA, err := sqlite.New(ctx, devADBPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storeA: %v", err)
|
||||
}
|
||||
defer storeA.Close()
|
||||
|
||||
if err := storeA.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("Failed to set prefix for A: %v", err)
|
||||
}
|
||||
if err := storeA.SetConfig(ctx, "sync.branch", syncBranch); err != nil {
|
||||
t.Fatalf("Failed to set sync.branch for A: %v", err)
|
||||
}
|
||||
|
||||
// Create and push initial state
|
||||
issueA1 := &types.Issue{
|
||||
Title: "Initial issue",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if err := storeA.CreateIssue(ctx, issueA1, "devA"); err != nil {
|
||||
t.Fatalf("Failed to create issue in devA: %v", err)
|
||||
}
|
||||
|
||||
devAJSONLPath := filepath.Join(devABeadsDir, "issues.jsonl")
|
||||
if err := exportToJSONLWithStore(ctx, storeA, devAJSONLPath); err != nil {
|
||||
t.Fatalf("Failed to export for devA: %v", err)
|
||||
}
|
||||
|
||||
initMainBranch(t, devADir)
|
||||
runGitCmd(t, devADir, "push", "origin", "master")
|
||||
|
||||
if err := os.Chdir(devADir); err != nil {
|
||||
t.Fatalf("Failed to chdir to devA: %v", err)
|
||||
}
|
||||
oldDBPath := dbPath
|
||||
dbPath = devADBPath
|
||||
logA, _ := newTestSyncBranchLogger()
|
||||
if _, err := syncBranchCommitAndPush(ctx, storeA, true, logA); err != nil {
|
||||
t.Fatalf("DevA initial push failed: %v", err)
|
||||
}
|
||||
dbPath = oldDBPath
|
||||
t.Log("✓ DevA pushed initial state")
|
||||
|
||||
git.ResetCaches()
|
||||
|
||||
// === Developer B Setup ===
|
||||
devBDir := filepath.Join(tmpDir, "devB")
|
||||
runGitCmd(t, tmpDir, "clone", remoteDir, devBDir)
|
||||
configureGit(t, devBDir)
|
||||
|
||||
devBBeadsDir := filepath.Join(devBDir, ".beads")
|
||||
if err := os.MkdirAll(devBBeadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create devB .beads dir: %v", err)
|
||||
}
|
||||
|
||||
devBDBPath := filepath.Join(devBBeadsDir, "test.db")
|
||||
storeB, err := sqlite.New(ctx, devBDBPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storeB: %v", err)
|
||||
}
|
||||
defer storeB.Close()
|
||||
|
||||
if err := storeB.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("Failed to set prefix for B: %v", err)
|
||||
}
|
||||
if err := storeB.SetConfig(ctx, "sync.branch", syncBranch); err != nil {
|
||||
t.Fatalf("Failed to set sync.branch for B: %v", err)
|
||||
}
|
||||
|
||||
// DevB pulls initial state
|
||||
if err := os.Chdir(devBDir); err != nil {
|
||||
t.Fatalf("Failed to chdir to devB: %v", err)
|
||||
}
|
||||
dbPath = devBDBPath
|
||||
logB, _ := newTestSyncBranchLogger()
|
||||
if _, err := syncBranchPull(ctx, storeB, logB); err != nil {
|
||||
t.Logf("DevB initial pull warning: %v", err)
|
||||
}
|
||||
dbPath = oldDBPath
|
||||
t.Log("✓ DevB pulled initial state")
|
||||
|
||||
git.ResetCaches()
|
||||
|
||||
// === SIMULATE CONCURRENT CHANGES (the key to reproducing GH#1358) ===
|
||||
|
||||
// DevA creates issue (simulating daemon auto-export)
|
||||
if err := os.Chdir(devADir); err != nil {
|
||||
t.Fatalf("Failed to chdir to devA: %v", err)
|
||||
}
|
||||
issueA2 := &types.Issue{
|
||||
Title: "DevA change",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeBug,
|
||||
CreatedAt: time.Now().Add(time.Second),
|
||||
UpdatedAt: time.Now().Add(time.Second),
|
||||
}
|
||||
if err := storeA.CreateIssue(ctx, issueA2, "devA"); err != nil {
|
||||
t.Fatalf("Failed to create issue in devA: %v", err)
|
||||
}
|
||||
if err := exportToJSONLWithStore(ctx, storeA, devAJSONLPath); err != nil {
|
||||
t.Fatalf("Failed to export for devA: %v", err)
|
||||
}
|
||||
|
||||
// DevA daemon pushes (succeeds - first to push)
|
||||
dbPath = devADBPath
|
||||
if _, err := syncBranchCommitAndPush(ctx, storeA, true, logA); err != nil {
|
||||
t.Fatalf("DevA push failed: %v", err)
|
||||
}
|
||||
dbPath = oldDBPath
|
||||
t.Log("✓ DevA pushed change (remote now ahead of DevB)")
|
||||
|
||||
git.ResetCaches()
|
||||
|
||||
// DevB creates DIFFERENT issue (simulating daemon auto-export, without pulling first)
|
||||
if err := os.Chdir(devBDir); err != nil {
|
||||
t.Fatalf("Failed to chdir to devB: %v", err)
|
||||
}
|
||||
issueB := &types.Issue{
|
||||
Title: "DevB change",
|
||||
Status: types.StatusInProgress,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeFeature,
|
||||
CreatedAt: time.Now().Add(2 * time.Second),
|
||||
UpdatedAt: time.Now().Add(2 * time.Second),
|
||||
}
|
||||
if err := storeB.CreateIssue(ctx, issueB, "devB"); err != nil {
|
||||
t.Fatalf("Failed to create issue in devB: %v", err)
|
||||
}
|
||||
devBJSONLPath := filepath.Join(devBBeadsDir, "issues.jsonl")
|
||||
if err := exportToJSONLWithStore(ctx, storeB, devBJSONLPath); err != nil {
|
||||
t.Fatalf("Failed to export for devB: %v", err)
|
||||
}
|
||||
|
||||
// DevB daemon tries to push - this will FAIL and potentially leave worktree dirty
|
||||
dbPath = devBDBPath
|
||||
_, pushErr := syncBranchCommitAndPush(ctx, storeB, true, logB)
|
||||
dbPath = oldDBPath
|
||||
if pushErr != nil {
|
||||
t.Logf("✓ DevB push failed as expected (divergence): %v", pushErr)
|
||||
} else {
|
||||
t.Log("DevB push succeeded (may have auto-rebased)")
|
||||
}
|
||||
|
||||
git.ResetCaches()
|
||||
|
||||
// === THE CRITICAL TEST: DevB daemon tries to PULL on next cycle ===
|
||||
// With OLD code (simple git pull): This FAILS with "unmerged files"
|
||||
// With FIX (PullFromSyncBranch): This SUCCEEDS with content-based merge
|
||||
|
||||
if err := os.Chdir(devBDir); err != nil {
|
||||
t.Fatalf("Failed to chdir to devB: %v", err)
|
||||
}
|
||||
|
||||
dbPath = devBDBPath
|
||||
pulled, pullErr := syncBranchPull(ctx, storeB, logB)
|
||||
dbPath = oldDBPath
|
||||
|
||||
if pullErr != nil {
|
||||
if strings.Contains(pullErr.Error(), "unmerged files") ||
|
||||
strings.Contains(pullErr.Error(), "Pulling is not possible") {
|
||||
t.Fatalf("❌ GH#1358 REPRODUCED: Daemon pull failed with unmerged files error: %v", pullErr)
|
||||
} else {
|
||||
t.Errorf("DevB pull failed with unexpected error: %v", pullErr)
|
||||
}
|
||||
} else {
|
||||
t.Log("✅ GH#1358 FIXED: DevB pull succeeded despite divergence")
|
||||
if pulled {
|
||||
t.Log("✅ Content-based merge handled divergence successfully")
|
||||
}
|
||||
// Test PASSES - fix is working!
|
||||
}
|
||||
|
||||
git.ResetCaches()
|
||||
}
|
||||
|
|
@ -1,911 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage/sqlite"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func TestExportToJSONLWithStore(t *testing.T) {
|
||||
// Isolate global config (other tests may set sync.mode=dolt-native, which disables JSONL export).
|
||||
config.ResetForTesting()
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize() returned error: %v", err)
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath := filepath.Join(tmpDir, ".beads", "issues.jsonl")
|
||||
|
||||
// Create storage
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set issue_prefix to prevent "database not initialized" errors
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create test issue
|
||||
issue := &types.Issue{
|
||||
ID: "test-1",
|
||||
Title: "Test Issue",
|
||||
Description: "Test description",
|
||||
IssueType: types.TypeBug,
|
||||
Priority: 1,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue: %v", err)
|
||||
}
|
||||
|
||||
// Export to JSONL
|
||||
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("exportToJSONLWithStore failed: %v", err)
|
||||
}
|
||||
|
||||
// Verify file exists
|
||||
if _, err := os.Stat(jsonlPath); os.IsNotExist(err) {
|
||||
t.Fatal("JSONL file was not created")
|
||||
}
|
||||
|
||||
// Read and verify content
|
||||
data, err := os.ReadFile(jsonlPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read JSONL: %v", err)
|
||||
}
|
||||
|
||||
var exported types.Issue
|
||||
if err := json.Unmarshal(data, &exported); err != nil {
|
||||
t.Fatalf("failed to unmarshal JSONL: %v", err)
|
||||
}
|
||||
|
||||
if exported.ID != "test-1" {
|
||||
t.Errorf("expected ID 'test-1', got %s", exported.ID)
|
||||
}
|
||||
if exported.Title != "Test Issue" {
|
||||
t.Errorf("expected title 'Test Issue', got %s", exported.Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportToJSONLWithStore_EmptyDatabase(t *testing.T) {
|
||||
// Isolate global config (other tests may set sync.mode=dolt-native, which disables JSONL export).
|
||||
config.ResetForTesting()
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize() returned error: %v", err)
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath := filepath.Join(tmpDir, ".beads", "issues.jsonl")
|
||||
|
||||
// Create storage (empty)
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Create existing JSONL with content
|
||||
if err := os.MkdirAll(filepath.Dir(jsonlPath), 0755); err != nil {
|
||||
t.Fatalf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
existingIssue := &types.Issue{
|
||||
ID: "existing-1",
|
||||
Title: "Existing",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeBug,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
data, _ := json.Marshal(existingIssue)
|
||||
if err := os.WriteFile(jsonlPath, append(data, '\n'), 0644); err != nil {
|
||||
t.Fatalf("failed to write existing JSONL: %v", err)
|
||||
}
|
||||
|
||||
// Should refuse to export empty DB over non-empty JSONL
|
||||
err = exportToJSONLWithStore(ctx, store, jsonlPath)
|
||||
if err == nil {
|
||||
t.Fatal("expected error when exporting empty DB over non-empty JSONL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportToJSONLWithStore(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath := filepath.Join(tmpDir, ".beads", "issues.jsonl")
|
||||
|
||||
// Create storage first to initialize database
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set issue_prefix to prevent "database not initialized" errors
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create JSONL with test data
|
||||
if err := os.MkdirAll(filepath.Dir(jsonlPath), 0755); err != nil {
|
||||
t.Fatalf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
issue := &types.Issue{
|
||||
ID: "test-1",
|
||||
Title: "Test Issue",
|
||||
Description: "Test description",
|
||||
IssueType: types.TypeBug,
|
||||
Priority: 1,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
data, _ := json.Marshal(issue)
|
||||
if err := os.WriteFile(jsonlPath, append(data, '\n'), 0644); err != nil {
|
||||
t.Fatalf("failed to write JSONL: %v", err)
|
||||
}
|
||||
|
||||
// Import from JSONL
|
||||
if err := importToJSONLWithStore(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("importToJSONLWithStore failed: %v", err)
|
||||
}
|
||||
|
||||
// Verify issue was imported
|
||||
imported, err := store.GetIssue(ctx, "test-1")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get imported issue: %v", err)
|
||||
}
|
||||
|
||||
if imported.Title != "Test Issue" {
|
||||
t.Errorf("expected title 'Test Issue', got %s", imported.Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportToJSONLWithStore_LargeDescription(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath := filepath.Join(tmpDir, ".beads", "issues.jsonl")
|
||||
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(jsonlPath), 0755); err != nil {
|
||||
t.Fatalf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
// Create an issue with a description larger than the default 64KB scanner buffer
|
||||
largeDesc := strings.Repeat("x", 100*1024) // 100KB
|
||||
issue := &types.Issue{
|
||||
ID: "test-large",
|
||||
Title: "Large Issue",
|
||||
Description: largeDesc,
|
||||
IssueType: types.TypeBug,
|
||||
Priority: 1,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
data, _ := json.Marshal(issue)
|
||||
if err := os.WriteFile(jsonlPath, append(data, '\n'), 0644); err != nil {
|
||||
t.Fatalf("failed to write JSONL: %v", err)
|
||||
}
|
||||
|
||||
if err := importToJSONLWithStore(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("importToJSONLWithStore failed on large JSONL line: %v", err)
|
||||
}
|
||||
|
||||
imported, err := store.GetIssue(ctx, "test-large")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get imported issue: %v", err)
|
||||
}
|
||||
|
||||
if len(imported.Description) != 100*1024 {
|
||||
t.Errorf("expected description length %d, got %d", 100*1024, len(imported.Description))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportImportRoundTrip(t *testing.T) {
|
||||
// Isolate global config (other tests may set sync.mode=dolt-native, which disables JSONL export).
|
||||
config.ResetForTesting()
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize() returned error: %v", err)
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath := filepath.Join(tmpDir, ".beads", "issues.jsonl")
|
||||
|
||||
// Create storage and add issues
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set issue_prefix to prevent "database not initialized" errors
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create multiple issues with dependencies
|
||||
issue1 := &types.Issue{
|
||||
ID: "test-1",
|
||||
Title: "Issue 1",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeBug,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
issue2 := &types.Issue{
|
||||
ID: "test-2",
|
||||
Title: "Issue 2",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeFeature,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := store.CreateIssue(ctx, issue1, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue1: %v", err)
|
||||
}
|
||||
if err := store.CreateIssue(ctx, issue2, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue2: %v", err)
|
||||
}
|
||||
|
||||
// Add dependency
|
||||
dep := &types.Dependency{
|
||||
IssueID: "test-2",
|
||||
DependsOnID: "test-1",
|
||||
Type: types.DepBlocks,
|
||||
}
|
||||
if err := store.AddDependency(ctx, dep, "test"); err != nil {
|
||||
t.Fatalf("failed to add dependency: %v", err)
|
||||
}
|
||||
|
||||
// Add labels
|
||||
if err := store.AddLabel(ctx, "test-1", "bug", "test"); err != nil {
|
||||
t.Fatalf("failed to add label: %v", err)
|
||||
}
|
||||
|
||||
// Export
|
||||
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("export failed: %v", err)
|
||||
}
|
||||
|
||||
// Create new database
|
||||
dbPath2 := filepath.Join(tmpDir, ".beads", "beads2.db")
|
||||
store2, err := sqlite.New(context.Background(), dbPath2)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store2: %v", err)
|
||||
}
|
||||
defer store2.Close()
|
||||
|
||||
// Set issue_prefix for second database
|
||||
if err := store2.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix for store2: %v", err)
|
||||
}
|
||||
|
||||
// Import
|
||||
if err := importToJSONLWithStore(ctx, store2, jsonlPath); err != nil {
|
||||
t.Fatalf("import failed: %v", err)
|
||||
}
|
||||
|
||||
// Verify issues
|
||||
imported1, err := store2.GetIssue(ctx, "test-1")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get imported issue1: %v", err)
|
||||
}
|
||||
if imported1.Title != "Issue 1" {
|
||||
t.Errorf("expected title 'Issue 1', got %s", imported1.Title)
|
||||
}
|
||||
|
||||
imported2, err := store2.GetIssue(ctx, "test-2")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get imported issue2: %v", err)
|
||||
}
|
||||
if imported2.Title != "Issue 2" {
|
||||
t.Errorf("expected title 'Issue 2', got %s", imported2.Title)
|
||||
}
|
||||
|
||||
// Verify dependency
|
||||
deps, err := store2.GetDependencies(ctx, "test-2")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get dependencies: %v", err)
|
||||
}
|
||||
if len(deps) != 1 || deps[0].ID != "test-1" {
|
||||
t.Errorf("expected dependency test-2 -> test-1, got %v", deps)
|
||||
}
|
||||
|
||||
// Verify labels
|
||||
labels, err := store2.GetLabels(ctx, "test-1")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get labels: %v", err)
|
||||
}
|
||||
if len(labels) != 1 || labels[0] != "bug" {
|
||||
t.Errorf("expected label 'bug', got %v", labels)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExportUpdatesMetadata verifies that export updates last_import_hash metadata (bd-ymj fix)
|
||||
func TestExportUpdatesMetadata(t *testing.T) {
|
||||
// Isolate global config (other tests may set sync.mode=dolt-native, which disables JSONL export).
|
||||
config.ResetForTesting()
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize() returned error: %v", err)
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath := filepath.Join(tmpDir, ".beads", "issues.jsonl")
|
||||
|
||||
// Create storage
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set issue_prefix
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create test issue
|
||||
issue := &types.Issue{
|
||||
ID: "test-1",
|
||||
Title: "Test Issue",
|
||||
Description: "Test description",
|
||||
IssueType: types.TypeBug,
|
||||
Priority: 1,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue: %v", err)
|
||||
}
|
||||
|
||||
// First export
|
||||
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("first export failed: %v", err)
|
||||
}
|
||||
|
||||
// Update metadata using the actual daemon helper function (bd-ar2.3 fix)
|
||||
// This verifies that updateExportMetadata (used by createExportFunc and createSyncFunc) works correctly
|
||||
mockLogger := newTestLogger()
|
||||
updateExportMetadata(ctx, store, jsonlPath, mockLogger, "")
|
||||
|
||||
// Verify metadata was set (renamed from last_import_hash to jsonl_content_hash - bd-39o)
|
||||
lastHash, err := store.GetMetadata(ctx, "jsonl_content_hash")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get jsonl_content_hash: %v", err)
|
||||
}
|
||||
if lastHash == "" {
|
||||
t.Error("expected jsonl_content_hash to be set after export")
|
||||
}
|
||||
|
||||
lastTime, err := store.GetMetadata(ctx, "last_import_time")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get last_import_time: %v", err)
|
||||
}
|
||||
if lastTime == "" {
|
||||
t.Error("expected last_import_time to be set after export")
|
||||
}
|
||||
|
||||
// Second export should succeed without "content has changed" error
|
||||
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("second export failed (metadata not updated properly): %v", err)
|
||||
}
|
||||
|
||||
// Verify validatePreExport doesn't fail with "content has changed"
|
||||
if err := validatePreExport(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("validatePreExport failed after metadata update: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateExportMetadataMultiRepo(t *testing.T) {
|
||||
// Isolate global config (other tests may set sync.mode=dolt-native, which disables JSONL export).
|
||||
config.ResetForTesting()
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize() returned error: %v", err)
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath1 := filepath.Join(tmpDir, "repo1", ".beads", "issues.jsonl")
|
||||
jsonlPath2 := filepath.Join(tmpDir, "repo2", ".beads", "issues.jsonl")
|
||||
|
||||
// Create storage
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set issue_prefix
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create test issues for each repo
|
||||
issue1 := &types.Issue{
|
||||
ID: "test-1",
|
||||
Title: "Test Issue 1",
|
||||
Description: "Repo 1 issue",
|
||||
IssueType: types.TypeBug,
|
||||
Priority: 1,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
SourceRepo: "repo1",
|
||||
}
|
||||
issue2 := &types.Issue{
|
||||
ID: "test-2",
|
||||
Title: "Test Issue 2",
|
||||
Description: "Repo 2 issue",
|
||||
IssueType: types.TypeBug,
|
||||
Priority: 1,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
SourceRepo: "repo2",
|
||||
}
|
||||
|
||||
if err := store.CreateIssue(ctx, issue1, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue1: %v", err)
|
||||
}
|
||||
if err := store.CreateIssue(ctx, issue2, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue2: %v", err)
|
||||
}
|
||||
|
||||
// Create directories for JSONL files
|
||||
if err := os.MkdirAll(filepath.Dir(jsonlPath1), 0755); err != nil {
|
||||
t.Fatalf("failed to create dir for jsonlPath1: %v", err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(jsonlPath2), 0755); err != nil {
|
||||
t.Fatalf("failed to create dir for jsonlPath2: %v", err)
|
||||
}
|
||||
|
||||
// Export issues to JSONL files
|
||||
if err := exportToJSONLWithStore(ctx, store, jsonlPath1); err != nil {
|
||||
t.Fatalf("failed to export to jsonlPath1: %v", err)
|
||||
}
|
||||
if err := exportToJSONLWithStore(ctx, store, jsonlPath2); err != nil {
|
||||
t.Fatalf("failed to export to jsonlPath2: %v", err)
|
||||
}
|
||||
|
||||
// Create mock logger
|
||||
mockLogger := newTestLogger()
|
||||
|
||||
// Update metadata for each repo with different keys (bd-ar2.2 multi-repo support)
|
||||
updateExportMetadata(ctx, store, jsonlPath1, mockLogger, jsonlPath1)
|
||||
updateExportMetadata(ctx, store, jsonlPath2, mockLogger, jsonlPath2)
|
||||
|
||||
// Verify per-repo metadata was set with correct keys (bd-web8: keys are sanitized)
|
||||
// Renamed from last_import_hash to jsonl_content_hash (bd-39o)
|
||||
hash1Key := "jsonl_content_hash:" + sanitizeMetadataKey(jsonlPath1)
|
||||
hash1, err := store.GetMetadata(ctx, hash1Key)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get %s: %v", hash1Key, err)
|
||||
}
|
||||
if hash1 == "" {
|
||||
t.Errorf("expected %s to be set", hash1Key)
|
||||
}
|
||||
|
||||
hash2Key := "jsonl_content_hash:" + sanitizeMetadataKey(jsonlPath2)
|
||||
hash2, err := store.GetMetadata(ctx, hash2Key)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get %s: %v", hash2Key, err)
|
||||
}
|
||||
if hash2 == "" {
|
||||
t.Errorf("expected %s to be set", hash2Key)
|
||||
}
|
||||
|
||||
// Verify that single-repo metadata key is NOT set (we're using per-repo keys)
|
||||
globalHash, err := store.GetMetadata(ctx, "jsonl_content_hash")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get jsonl_content_hash: %v", err)
|
||||
}
|
||||
if globalHash != "" {
|
||||
t.Error("expected global jsonl_content_hash to not be set when using per-repo keys")
|
||||
}
|
||||
|
||||
// Note: last_import_mtime removed in bd-v0y fix (git doesn't preserve mtime)
|
||||
}
|
||||
|
||||
// TestExportWithMultiRepoConfigUpdatesAllMetadata verifies that export with multi-repo
|
||||
// config correctly updates metadata for ALL JSONL files with proper keySuffix (bd-ar2.8)
|
||||
func TestExportWithMultiRepoConfigUpdatesAllMetadata(t *testing.T) {
|
||||
// Isolate global config (other tests may set sync.mode=dolt-native, which disables JSONL export).
|
||||
config.ResetForTesting()
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize() returned error: %v", err)
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
primaryDir := filepath.Join(tmpDir, "primary")
|
||||
additionalDir := filepath.Join(tmpDir, "additional")
|
||||
|
||||
// Set up directory structure
|
||||
for _, dir := range []string{primaryDir, additionalDir} {
|
||||
beadsDir := filepath.Join(dir, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("failed to create %s: %v", beadsDir, err)
|
||||
}
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(primaryDir, ".beads", "beads.db")
|
||||
primaryJSONL := filepath.Join(primaryDir, ".beads", "issues.jsonl")
|
||||
additionalJSONL := filepath.Join(additionalDir, ".beads", "issues.jsonl")
|
||||
|
||||
// Create storage
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set issue_prefix
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create test issues
|
||||
issue1 := &types.Issue{
|
||||
ID: "test-1",
|
||||
Title: "Primary Issue",
|
||||
Description: "Issue in primary repo",
|
||||
IssueType: types.TypeBug,
|
||||
Priority: 1,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
SourceRepo: primaryDir,
|
||||
}
|
||||
issue2 := &types.Issue{
|
||||
ID: "test-2",
|
||||
Title: "Additional Issue",
|
||||
Description: "Issue in additional repo",
|
||||
IssueType: types.TypeFeature,
|
||||
Priority: 2,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
SourceRepo: additionalDir,
|
||||
}
|
||||
|
||||
if err := store.CreateIssue(ctx, issue1, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue1: %v", err)
|
||||
}
|
||||
if err := store.CreateIssue(ctx, issue2, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue2: %v", err)
|
||||
}
|
||||
|
||||
// Export to both JSONL files
|
||||
if err := exportToJSONLWithStore(ctx, store, primaryJSONL); err != nil {
|
||||
t.Fatalf("failed to export to primary JSONL: %v", err)
|
||||
}
|
||||
if err := exportToJSONLWithStore(ctx, store, additionalJSONL); err != nil {
|
||||
t.Fatalf("failed to export to additional JSONL: %v", err)
|
||||
}
|
||||
|
||||
// Simulate multi-repo export flow (as in createExportFunc)
|
||||
// This tests the full integration: getMultiRepoJSONLPaths -> getRepoKeyForPath -> updateExportMetadata
|
||||
mockLogger := newTestLogger()
|
||||
|
||||
// Simulate multi-repo mode with stable keys
|
||||
multiRepoPaths := []string{primaryJSONL, additionalJSONL}
|
||||
repoKeys := []string{primaryDir, additionalDir}
|
||||
|
||||
for i, path := range multiRepoPaths {
|
||||
repoKey := repoKeys[i]
|
||||
updateExportMetadata(ctx, store, path, mockLogger, repoKey)
|
||||
}
|
||||
|
||||
// Verify metadata for primary repo (bd-web8: keys are sanitized, bd-39o: renamed key)
|
||||
primaryHashKey := "jsonl_content_hash:" + sanitizeMetadataKey(primaryDir)
|
||||
primaryHash, err := store.GetMetadata(ctx, primaryHashKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get %s: %v", primaryHashKey, err)
|
||||
}
|
||||
if primaryHash == "" {
|
||||
t.Errorf("expected %s to be set after export", primaryHashKey)
|
||||
}
|
||||
|
||||
primaryTimeKey := "last_import_time:" + sanitizeMetadataKey(primaryDir)
|
||||
primaryTime, err := store.GetMetadata(ctx, primaryTimeKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get %s: %v", primaryTimeKey, err)
|
||||
}
|
||||
if primaryTime == "" {
|
||||
t.Errorf("expected %s to be set after export", primaryTimeKey)
|
||||
}
|
||||
|
||||
// Note: last_import_mtime removed in bd-v0y fix (git doesn't preserve mtime)
|
||||
|
||||
// Verify metadata for additional repo (bd-web8: keys are sanitized, bd-39o: renamed key)
|
||||
additionalHashKey := "jsonl_content_hash:" + sanitizeMetadataKey(additionalDir)
|
||||
additionalHash, err := store.GetMetadata(ctx, additionalHashKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get %s: %v", additionalHashKey, err)
|
||||
}
|
||||
if additionalHash == "" {
|
||||
t.Errorf("expected %s to be set after export", additionalHashKey)
|
||||
}
|
||||
|
||||
additionalTimeKey := "last_import_time:" + sanitizeMetadataKey(additionalDir)
|
||||
additionalTime, err := store.GetMetadata(ctx, additionalTimeKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get %s: %v", additionalTimeKey, err)
|
||||
}
|
||||
if additionalTime == "" {
|
||||
t.Errorf("expected %s to be set after export", additionalTimeKey)
|
||||
}
|
||||
|
||||
// Note: last_import_mtime removed in bd-v0y fix (git doesn't preserve mtime)
|
||||
|
||||
// Note: In this test both JSONL files have the same content (all issues),
|
||||
// so hashes will be identical. In real multi-repo mode, ExportToMultiRepo
|
||||
// filters by SourceRepo, so hashes would differ. What matters here is that
|
||||
// metadata is set with correct per-repo keys.
|
||||
|
||||
// Verify global metadata keys are NOT set (multi-repo mode uses suffixed keys)
|
||||
globalHash, err := store.GetMetadata(ctx, "jsonl_content_hash")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get jsonl_content_hash: %v", err)
|
||||
}
|
||||
if globalHash != "" {
|
||||
t.Error("expected global jsonl_content_hash to not be set in multi-repo mode")
|
||||
}
|
||||
|
||||
// Test that subsequent exports don't fail with "content has changed" error
|
||||
if err := exportToJSONLWithStore(ctx, store, primaryJSONL); err != nil {
|
||||
t.Errorf("second export to primary JSONL failed (metadata not updated properly): %v", err)
|
||||
}
|
||||
if err := exportToJSONLWithStore(ctx, store, additionalJSONL); err != nil {
|
||||
t.Errorf("second export to additional JSONL failed (metadata not updated properly): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateExportMetadataInvalidKeySuffix verifies that invalid keySuffix is rejected (bd-ar2.12)
|
||||
func TestUpdateExportMetadataInvalidKeySuffix(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath := filepath.Join(tmpDir, ".beads", "issues.jsonl")
|
||||
|
||||
// Create storage
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set issue_prefix
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create test issue
|
||||
issue := &types.Issue{
|
||||
ID: "test-1",
|
||||
Title: "Test Issue",
|
||||
Description: "Test description",
|
||||
IssueType: types.TypeBug,
|
||||
Priority: 1,
|
||||
Status: types.StatusOpen,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := store.CreateIssue(ctx, issue, "test"); err != nil {
|
||||
t.Fatalf("failed to create issue: %v", err)
|
||||
}
|
||||
|
||||
// Export to JSONL
|
||||
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("export failed: %v", err)
|
||||
}
|
||||
|
||||
// Create mock logger
|
||||
mockLogger := newTestLogger()
|
||||
|
||||
// Update metadata with keySuffix containing ':' (bd-web8: should be auto-sanitized)
|
||||
// This simulates Windows absolute paths like "C:\Users\..."
|
||||
keySuffixWithColon := "C:/Users/repo/path"
|
||||
updateExportMetadata(ctx, store, jsonlPath, mockLogger, keySuffixWithColon)
|
||||
|
||||
// Verify metadata WAS set with sanitized key (colons replaced with underscores)
|
||||
// bd-39o: renamed from last_import_hash to jsonl_content_hash
|
||||
sanitized := sanitizeMetadataKey(keySuffixWithColon)
|
||||
sanitizedKey := "jsonl_content_hash:" + sanitized
|
||||
hash, err := store.GetMetadata(ctx, sanitizedKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get metadata: %v", err)
|
||||
}
|
||||
if hash == "" {
|
||||
t.Errorf("expected metadata to be set with sanitized key %s", sanitizedKey)
|
||||
}
|
||||
|
||||
// Verify that the original unsanitized key was NOT used
|
||||
unsanitizedKey := "jsonl_content_hash:" + keySuffixWithColon
|
||||
unsanitizedHash, err := store.GetMetadata(ctx, unsanitizedKey)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to check unsanitized key: %v", err)
|
||||
}
|
||||
if unsanitizedHash != "" {
|
||||
t.Errorf("expected unsanitized key %s to NOT be set", unsanitizedKey)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExportToJSONLWithStore_IncludesTombstones verifies that tombstones are included
|
||||
// in JSONL export by the daemon. This is a regression test for the bug where
|
||||
// exportToJSONLWithStore used an empty IssueFilter (IncludeTombstones: false),
|
||||
// causing deleted issues to not propagate via sync branch to other clones.
|
||||
//
|
||||
// Bug scenario:
|
||||
// 1. User runs `bd delete <issue>` with daemon active
|
||||
// 2. Database correctly marks issue as tombstone
|
||||
// 3. Main .beads/issues.jsonl correctly shows status:"tombstone"
|
||||
// 4. But sync branch worktree JSONL showed status:"open" (bug)
|
||||
// 5. Other clones would not see the deletion
|
||||
func TestExportToJSONLWithStore_IncludesTombstones(t *testing.T) {
|
||||
// Not parallel: mutates global config state for isolation.
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := filepath.Join(tmpDir, ".beads", "beads.db")
|
||||
jsonlPath := filepath.Join(tmpDir, ".beads", "issues.jsonl")
|
||||
|
||||
// Isolate global config (other tests may set sync.mode=dolt-native, which disables JSONL export).
|
||||
config.ResetForTesting()
|
||||
if err := config.Initialize(); err != nil {
|
||||
t.Fatalf("config.Initialize() returned error: %v", err)
|
||||
}
|
||||
|
||||
// Create storage
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create store: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Set issue_prefix to prevent "database not initialized" errors
|
||||
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
||||
t.Fatalf("failed to set issue_prefix: %v", err)
|
||||
}
|
||||
|
||||
// Create an open issue
|
||||
openIssue := &types.Issue{
|
||||
ID: "test-1",
|
||||
Title: "Open Issue",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if err := store.CreateIssue(ctx, openIssue, "test"); err != nil {
|
||||
t.Fatalf("failed to create open issue: %v", err)
|
||||
}
|
||||
|
||||
// Create a tombstone issue (deleted)
|
||||
tombstoneIssue := &types.Issue{
|
||||
ID: "test-2",
|
||||
Title: "Deleted Issue",
|
||||
Status: types.StatusTombstone,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if err := store.CreateIssue(ctx, tombstoneIssue, "test"); err != nil {
|
||||
t.Fatalf("failed to create tombstone issue: %v", err)
|
||||
}
|
||||
|
||||
// Export to JSONL using daemon's export function
|
||||
if err := exportToJSONLWithStore(ctx, store, jsonlPath); err != nil {
|
||||
t.Fatalf("exportToJSONLWithStore failed: %v", err)
|
||||
}
|
||||
|
||||
// Read and parse the exported JSONL
|
||||
data, err := os.ReadFile(jsonlPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read JSONL: %v", err)
|
||||
}
|
||||
|
||||
// Parse JSONL (one JSON object per line)
|
||||
lines := splitJSONLLines(data)
|
||||
if len(lines) != 2 {
|
||||
t.Fatalf("expected 2 issues in JSONL, got %d", len(lines))
|
||||
}
|
||||
|
||||
// Verify both issues are present (including tombstone)
|
||||
var foundOpen, foundTombstone bool
|
||||
for _, line := range lines {
|
||||
var issue types.Issue
|
||||
if err := json.Unmarshal(line, &issue); err != nil {
|
||||
t.Fatalf("failed to unmarshal issue: %v", err)
|
||||
}
|
||||
if issue.ID == "test-1" && issue.Status == types.StatusOpen {
|
||||
foundOpen = true
|
||||
}
|
||||
if issue.ID == "test-2" && issue.Status == types.StatusTombstone {
|
||||
foundTombstone = true
|
||||
}
|
||||
}
|
||||
|
||||
if !foundOpen {
|
||||
t.Error("expected open issue (test-1) to be in JSONL export")
|
||||
}
|
||||
if !foundTombstone {
|
||||
t.Error("expected tombstone issue (test-2) to be in JSONL export - tombstones must be included for sync propagation")
|
||||
}
|
||||
}
|
||||
|
||||
// splitJSONLLines splits JSONL content into individual JSON lines
|
||||
func splitJSONLLines(data []byte) [][]byte {
|
||||
var lines [][]byte
|
||||
var currentLine []byte
|
||||
for _, b := range data {
|
||||
if b == '\n' {
|
||||
if len(currentLine) > 0 {
|
||||
lines = append(lines, currentLine)
|
||||
currentLine = nil
|
||||
}
|
||||
} else {
|
||||
currentLine = append(currentLine, b)
|
||||
}
|
||||
}
|
||||
if len(currentLine) > 0 {
|
||||
lines = append(lines, currentLine)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
|
@ -1,847 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/sqlite"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// windowsOS constant moved to test_helpers_test.go
|
||||
|
||||
func initTestGitRepo(t testing.TB, dir string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command("git", "init")
|
||||
cmd.Dir = dir
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatalf("Failed to init git repo: %v", err)
|
||||
}
|
||||
|
||||
// Configure git for tests
|
||||
configCmds := [][]string{
|
||||
{"git", "config", "user.email", "test@example.com"},
|
||||
{"git", "config", "user.name", "Test User"},
|
||||
}
|
||||
for _, args := range configCmds {
|
||||
cmd := exec.Command(args[0], args[1:]...)
|
||||
cmd.Dir = dir
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Logf("Warning: git config failed: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeSocketTempDir(t testing.TB) string {
|
||||
t.Helper()
|
||||
|
||||
base := "/tmp"
|
||||
if runtime.GOOS == windowsOS {
|
||||
base = os.TempDir()
|
||||
} else if _, err := os.Stat(base); err != nil {
|
||||
base = os.TempDir()
|
||||
}
|
||||
|
||||
tmpDir, err := os.MkdirTemp(base, "bd-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
return tmpDir
|
||||
}
|
||||
|
||||
func TestGetPIDFilePath(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
saveAndRestoreGlobals(t)
|
||||
|
||||
dbPath = filepath.Join(tmpDir, ".beads", "test.db")
|
||||
pidFile, err := getPIDFilePath()
|
||||
if err != nil {
|
||||
t.Fatalf("getPIDFilePath failed: %v", err)
|
||||
}
|
||||
|
||||
expected := filepath.Join(tmpDir, ".beads", "daemon.pid")
|
||||
if pidFile != expected {
|
||||
t.Errorf("Expected PID file %s, got %s", expected, pidFile)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Dir(pidFile)); os.IsNotExist(err) {
|
||||
t.Error("Expected beads directory to be created")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLogFilePath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
set func(t *testing.T) (userPath, dbFile, expected string)
|
||||
}{
|
||||
{
|
||||
name: "user specified path",
|
||||
set: func(t *testing.T) (string, string, string) {
|
||||
userDir := t.TempDir()
|
||||
dbDir := t.TempDir()
|
||||
userPath := filepath.Join(userDir, "bd.log")
|
||||
dbFile := filepath.Join(dbDir, ".beads", "test.db")
|
||||
return userPath, dbFile, userPath
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "default with dbPath",
|
||||
set: func(t *testing.T) (string, string, string) {
|
||||
dbDir := t.TempDir()
|
||||
dbFile := filepath.Join(dbDir, ".beads", "test.db")
|
||||
return "", dbFile, filepath.Join(dbDir, ".beads", "daemon.log")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
userPath, dbFile, expected := tt.set(t)
|
||||
|
||||
saveAndRestoreGlobals(t)
|
||||
dbPath = dbFile
|
||||
|
||||
result, err := getLogFilePath(userPath)
|
||||
if err != nil {
|
||||
t.Fatalf("getLogFilePath failed: %v", err)
|
||||
}
|
||||
if result != expected {
|
||||
t.Errorf("Expected %s, got %s", expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsDaemonRunning_NotRunning(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := t.TempDir()
|
||||
pidFile := filepath.Join(tmpDir, "test.pid")
|
||||
|
||||
isRunning, pid := isDaemonRunning(pidFile)
|
||||
if isRunning {
|
||||
t.Errorf("Expected daemon not running, got running with PID %d", pid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsDaemonRunning_StalePIDFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := t.TempDir()
|
||||
pidFile := filepath.Join(tmpDir, "test.pid")
|
||||
|
||||
if err := os.WriteFile(pidFile, []byte("99999"), 0600); err != nil {
|
||||
t.Fatalf("Failed to write PID file: %v", err)
|
||||
}
|
||||
|
||||
isRunning, pid := isDaemonRunning(pidFile)
|
||||
if isRunning {
|
||||
t.Errorf("Expected daemon not running (stale PID), got running with PID %d", pid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsDaemonRunning_CurrentProcess(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := t.TempDir()
|
||||
pidFile := filepath.Join(tmpDir, "test.pid")
|
||||
|
||||
// Acquire the daemon lock to simulate a running daemon
|
||||
beadsDir := filepath.Dir(pidFile)
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
lock, err := acquireDaemonLock(beadsDir, dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to acquire daemon lock: %v", err)
|
||||
}
|
||||
defer lock.Close()
|
||||
|
||||
currentPID := os.Getpid()
|
||||
isRunning, pid := isDaemonRunning(pidFile)
|
||||
if !isRunning {
|
||||
t.Error("Expected daemon running (lock held)")
|
||||
}
|
||||
if pid != currentPID {
|
||||
t.Errorf("Expected PID %d, got %d", currentPID, pid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonIntegration(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(dbDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(dbDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
saveAndRestoreGlobals(t)
|
||||
store = testStore
|
||||
dbPath = testDBPath
|
||||
|
||||
ctx := context.Background()
|
||||
testIssue := &types.Issue{
|
||||
Title: "Test daemon issue",
|
||||
Description: "Test description",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
}
|
||||
if err := testStore.CreateIssue(ctx, testIssue, "test"); err != nil {
|
||||
t.Fatalf("Failed to create test issue: %v", err)
|
||||
}
|
||||
|
||||
pidFile := filepath.Join(dbDir, "daemon.pid")
|
||||
_ = pidFile
|
||||
|
||||
if isRunning, _ := isDaemonRunning(pidFile); isRunning {
|
||||
t.Fatal("Daemon should not be running at start of test")
|
||||
}
|
||||
|
||||
t.Run("start requires git repo", func(t *testing.T) {
|
||||
if isGitRepo() {
|
||||
t.Skip("Already in a git repo, skipping this test")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("status shows not running", func(t *testing.T) {
|
||||
if isRunning, _ := isDaemonRunning(pidFile); isRunning {
|
||||
t.Error("Daemon should not be running")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDaemonPIDFileManagement(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := t.TempDir()
|
||||
pidFile := filepath.Join(tmpDir, "daemon.pid")
|
||||
|
||||
testPID := 12345
|
||||
if err := os.WriteFile(pidFile, []byte(strconv.Itoa(testPID)), 0600); err != nil {
|
||||
t.Fatalf("Failed to write PID file: %v", err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(pidFile)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read PID file: %v", err)
|
||||
}
|
||||
|
||||
readPID, err := strconv.Atoi(strings.TrimSpace(string(data)))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse PID: %v", err)
|
||||
}
|
||||
|
||||
if readPID != testPID {
|
||||
t.Errorf("Expected PID %d, got %d", testPID, readPID)
|
||||
}
|
||||
|
||||
if err := os.Remove(pidFile); err != nil {
|
||||
t.Fatalf("Failed to remove PID file: %v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(pidFile); !os.IsNotExist(err) {
|
||||
t.Error("PID file should be removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonLogFileCreation(t *testing.T) {
|
||||
t.Parallel()
|
||||
tmpDir := t.TempDir()
|
||||
logPath := filepath.Join(tmpDir, "test.log")
|
||||
|
||||
logF, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to open log file: %v", err)
|
||||
}
|
||||
defer logF.Close()
|
||||
|
||||
timestamp := time.Now().Format("2006-01-02 15:04:05")
|
||||
msg := "Test log message"
|
||||
_, err = fmt.Fprintf(logF, "[%s] %s\n", timestamp, msg)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to write to log file: %v", err)
|
||||
}
|
||||
|
||||
logF.Sync()
|
||||
|
||||
content, err := os.ReadFile(logPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read log file: %v", err)
|
||||
}
|
||||
|
||||
if !strings.Contains(string(content), msg) {
|
||||
t.Errorf("Log file should contain message: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonIntervalParsing(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
input string
|
||||
expected time.Duration
|
||||
}{
|
||||
{"5m", 5 * time.Minute},
|
||||
{"1h", 1 * time.Hour},
|
||||
{"30s", 30 * time.Second},
|
||||
{"2m30s", 2*time.Minute + 30*time.Second},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
d, err := time.ParseDuration(tt.input)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to parse duration %s: %v", tt.input, err)
|
||||
}
|
||||
if d != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, d)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonRPCServerIntegration(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(dbDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(dbDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
testIssue := &types.Issue{
|
||||
Title: "Test RPC issue",
|
||||
Description: "Test RPC integration",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
}
|
||||
if err := testStore.CreateIssue(ctx, testIssue, "test"); err != nil {
|
||||
t.Fatalf("Failed to create test issue: %v", err)
|
||||
}
|
||||
|
||||
if testIssue.ID == "" {
|
||||
t.Fatal("Issue ID should be set after creation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonConcurrentOperations(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(dbDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(dbDir, "test.db")
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
defer testStore.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
numGoroutines := 10
|
||||
errChan := make(chan error, numGoroutines)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := 0; i < numGoroutines; i++ {
|
||||
wg.Add(1)
|
||||
go func(n int) {
|
||||
defer wg.Done()
|
||||
|
||||
issue := &types.Issue{
|
||||
Title: fmt.Sprintf("Concurrent issue %d", n),
|
||||
Description: "Test concurrent operations",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
}
|
||||
|
||||
if err := testStore.CreateIssue(ctx, issue, "test"); err != nil {
|
||||
errChan <- fmt.Errorf("goroutine %d create failed: %w", n, err)
|
||||
return
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{
|
||||
"status": types.StatusInProgress,
|
||||
}
|
||||
if err := testStore.UpdateIssue(ctx, issue.ID, updates, "test"); err != nil {
|
||||
errChan <- fmt.Errorf("goroutine %d update failed: %w", n, err)
|
||||
return
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errChan)
|
||||
|
||||
for err := range errChan {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
issues, err := testStore.SearchIssues(ctx, "", types.IssueFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to search issues: %v", err)
|
||||
}
|
||||
|
||||
if len(issues) != numGoroutines {
|
||||
t.Errorf("Expected %d issues, got %d", numGoroutines, len(issues))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonSocketCleanupOnShutdown(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
socketPath := filepath.Join(tmpDir, "test.sock")
|
||||
testDBPath := filepath.Join(tmpDir, "test.db")
|
||||
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
server := newMockDaemonServer(socketPath, testStore)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
serverDone := make(chan error, 1)
|
||||
go func() {
|
||||
serverDone <- server.Start(ctx)
|
||||
}()
|
||||
|
||||
// Wait for server to be ready
|
||||
if err := server.WaitReady(2 * time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Verify socket exists (with retry for filesystem sync)
|
||||
var socketFound bool
|
||||
var lastErr error
|
||||
for i := 0; i < 10; i++ {
|
||||
if _, err := os.Stat(socketPath); err == nil {
|
||||
socketFound = true
|
||||
break
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if !socketFound {
|
||||
t.Fatalf("Socket should exist after server is ready (path=%s, err=%v)", socketPath, lastErr)
|
||||
}
|
||||
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case <-serverDone:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Error("Server did not shut down within timeout")
|
||||
}
|
||||
|
||||
testStore.Close()
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
if _, err := os.Stat(socketPath); !os.IsNotExist(err) {
|
||||
t.Error("Socket should be cleaned up after shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonServerStartFailureSocketExists(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
socketPath := filepath.Join(tmpDir, "test.sock")
|
||||
testDBPath := filepath.Join(tmpDir, "test.db")
|
||||
|
||||
testStore1, err := sqlite.New(context.Background(), testDBPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
defer testStore1.Close()
|
||||
|
||||
server1 := newMockDaemonServer(socketPath, testStore1)
|
||||
|
||||
ctx1, cancel1 := context.WithCancel(context.Background())
|
||||
defer cancel1()
|
||||
|
||||
go server1.Start(ctx1)
|
||||
|
||||
// Wait for server to be ready
|
||||
if err := server1.WaitReady(2 * time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Verify socket exists (with retry for filesystem sync)
|
||||
var socketFound bool
|
||||
for i := 0; i < 10; i++ {
|
||||
if _, err := os.Stat(socketPath); err == nil {
|
||||
socketFound = true
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if !socketFound {
|
||||
t.Fatal("Socket should exist for first server")
|
||||
}
|
||||
|
||||
testStore2, err := sqlite.New(context.Background(), filepath.Join(tmpDir, "test2.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create second test database: %v", err)
|
||||
}
|
||||
defer testStore2.Close()
|
||||
|
||||
server2 := newMockDaemonServer(socketPath, testStore2)
|
||||
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel2()
|
||||
|
||||
startErr := make(chan error, 1)
|
||||
go func() {
|
||||
startErr <- server2.Start(ctx2)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-startErr:
|
||||
if err == nil {
|
||||
t.Error("Expected second server to fail to start, but it succeeded")
|
||||
}
|
||||
case <-time.After(1 * time.Second):
|
||||
}
|
||||
|
||||
cancel1()
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
|
||||
func TestDaemonGracefulShutdown(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := makeSocketTempDir(t)
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
socketPath := filepath.Join(tmpDir, "test.sock")
|
||||
testDBPath := filepath.Join(tmpDir, "test.db")
|
||||
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
server := newMockDaemonServer(socketPath, testStore)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
serverDone := make(chan error, 1)
|
||||
startTime := time.Now()
|
||||
|
||||
go func() {
|
||||
serverDone <- server.Start(ctx)
|
||||
}()
|
||||
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case err := <-serverDone:
|
||||
shutdownDuration := time.Since(startTime)
|
||||
|
||||
if err != nil && err != context.Canceled {
|
||||
t.Errorf("Server returned unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if shutdownDuration > 3*time.Second {
|
||||
t.Errorf("Shutdown took too long: %v", shutdownDuration)
|
||||
}
|
||||
|
||||
testStore.Close()
|
||||
|
||||
if _, err := os.Stat(socketPath); !os.IsNotExist(err) {
|
||||
t.Error("Socket should be cleaned up after graceful shutdown")
|
||||
}
|
||||
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Server did not shut down gracefully within timeout")
|
||||
}
|
||||
}
|
||||
|
||||
type mockDaemonServer struct {
|
||||
socketPath string
|
||||
store storage.Storage
|
||||
listener net.Listener
|
||||
mu sync.Mutex
|
||||
shutdown bool
|
||||
ready chan error
|
||||
}
|
||||
|
||||
func newMockDaemonServer(socketPath string, store storage.Storage) *mockDaemonServer {
|
||||
return &mockDaemonServer{
|
||||
socketPath: socketPath,
|
||||
store: store,
|
||||
ready: make(chan error, 1),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *mockDaemonServer) WaitReady(timeout time.Duration) error {
|
||||
select {
|
||||
case err := <-s.ready:
|
||||
return err
|
||||
case <-time.After(timeout):
|
||||
return fmt.Errorf("server did not become ready within %v", timeout)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *mockDaemonServer) Start(ctx context.Context) error {
|
||||
if err := os.MkdirAll(filepath.Dir(s.socketPath), 0750); err != nil {
|
||||
return fmt.Errorf("failed to create socket directory: %w", err)
|
||||
}
|
||||
|
||||
// Check if socket already exists
|
||||
if _, err := os.Stat(s.socketPath); err == nil {
|
||||
// Socket exists - try to connect to see if server is running
|
||||
conn, err := net.Dial("unix", s.socketPath)
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
startErr := fmt.Errorf("socket already in use: %s", s.socketPath)
|
||||
s.ready <- startErr
|
||||
return startErr
|
||||
}
|
||||
// Socket is stale, remove it
|
||||
_ = os.Remove(s.socketPath)
|
||||
}
|
||||
|
||||
var err error
|
||||
s.listener, err = net.Listen("unix", s.socketPath)
|
||||
if err != nil {
|
||||
startErr := fmt.Errorf("failed to listen on socket: %w", err)
|
||||
s.ready <- startErr
|
||||
return startErr
|
||||
}
|
||||
|
||||
// Signal that server is ready
|
||||
s.ready <- nil
|
||||
|
||||
// Set up cleanup before accepting connections
|
||||
defer func() {
|
||||
s.listener.Close()
|
||||
os.Remove(s.socketPath)
|
||||
}()
|
||||
|
||||
doneChan := make(chan struct{})
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
s.mu.Lock()
|
||||
s.shutdown = true
|
||||
s.mu.Unlock()
|
||||
s.listener.Close()
|
||||
close(doneChan)
|
||||
}()
|
||||
|
||||
for {
|
||||
conn, err := s.listener.Accept()
|
||||
if err != nil {
|
||||
s.mu.Lock()
|
||||
shutdown := s.shutdown
|
||||
s.mu.Unlock()
|
||||
if shutdown {
|
||||
<-doneChan
|
||||
return ctx.Err()
|
||||
}
|
||||
return fmt.Errorf("failed to accept connection: %w", err)
|
||||
}
|
||||
conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// TestMutationToExportLatency tests the latency from mutation to JSONL export
|
||||
// Target: <500ms for single mutation, verify batching for rapid mutations
|
||||
//
|
||||
// NOTE: This test currently tests the existing auto-flush mechanism with debounce.
|
||||
// Once bd-85 (event-driven daemon) is fully implemented and enabled by default,
|
||||
// this test should verify <500ms latency instead of the current debounce-based timing.
|
||||
func TestMutationToExportLatency(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
|
||||
t.Skip("Skipping until event-driven daemon (bd-85) is fully implemented")
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
dbDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(dbDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create beads dir: %v", err)
|
||||
}
|
||||
|
||||
testDBPath := filepath.Join(dbDir, "test.db")
|
||||
jsonlPath := filepath.Join(dbDir, "issues.jsonl")
|
||||
|
||||
// Initialize git repo (required for auto-flush)
|
||||
initTestGitRepo(t, tmpDir)
|
||||
|
||||
testStore := newTestStore(t, testDBPath)
|
||||
|
||||
// Configure test environment - save/restore all globals atomically
|
||||
saveAndRestoreGlobals(t)
|
||||
origDebounce := config.GetDuration("flush-debounce")
|
||||
t.Cleanup(func() {
|
||||
config.Set("flush-debounce", origDebounce)
|
||||
clearAutoFlushState()
|
||||
})
|
||||
|
||||
dbPath = testDBPath
|
||||
store = testStore
|
||||
storeMutex.Lock()
|
||||
storeActive = true
|
||||
storeMutex.Unlock()
|
||||
autoFlushEnabled = true
|
||||
// Use fast debounce for testing (500ms to match event-driven target)
|
||||
config.Set("flush-debounce", 500*time.Millisecond)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Get JSONL mod time
|
||||
getModTime := func() time.Time {
|
||||
info, err := os.Stat(jsonlPath)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return info.ModTime()
|
||||
}
|
||||
|
||||
// Test 1: Single mutation latency with markDirtyAndScheduleFlush
|
||||
t.Run("SingleMutationLatency", func(t *testing.T) {
|
||||
initialModTime := getModTime()
|
||||
|
||||
// Create issue through store
|
||||
issue := &types.Issue{
|
||||
Title: "Latency test issue",
|
||||
Description: "Testing export latency",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
if err := testStore.CreateIssue(ctx, issue, "test"); err != nil {
|
||||
t.Fatalf("Failed to create issue: %v", err)
|
||||
}
|
||||
|
||||
// Manually trigger flush (simulating what CLI commands do)
|
||||
markDirtyAndScheduleFlush()
|
||||
|
||||
// Wait for JSONL file to be updated (with timeout)
|
||||
timeout := time.After(2 * time.Second) // 500ms debounce + margin
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
var updated bool
|
||||
var latency time.Duration
|
||||
for !updated {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
modTime := getModTime()
|
||||
if modTime.After(initialModTime) {
|
||||
latency = time.Since(start)
|
||||
updated = true
|
||||
}
|
||||
case <-timeout:
|
||||
t.Fatal("JSONL file not updated within 2 seconds")
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("Single mutation export latency: %v", latency)
|
||||
|
||||
// Verify <1s latency (500ms debounce + export time)
|
||||
if latency > 1*time.Second {
|
||||
t.Errorf("Latency %v exceeds 1s threshold", latency)
|
||||
}
|
||||
})
|
||||
|
||||
// Test 2: Rapid mutations should batch
|
||||
t.Run("RapidMutationBatching", func(t *testing.T) {
|
||||
preTestModTime := getModTime()
|
||||
|
||||
// Create 5 issues rapidly
|
||||
numIssues := 5
|
||||
start := time.Now()
|
||||
|
||||
for i := 0; i < numIssues; i++ {
|
||||
issue := &types.Issue{
|
||||
Title: fmt.Sprintf("Batch test issue %d", i),
|
||||
Description: "Testing batching",
|
||||
Status: types.StatusOpen,
|
||||
Priority: 1,
|
||||
IssueType: types.TypeTask,
|
||||
}
|
||||
if err := testStore.CreateIssue(ctx, issue, "test"); err != nil {
|
||||
t.Fatalf("Failed to create issue %d: %v", i, err)
|
||||
}
|
||||
// Trigger flush for each
|
||||
markDirtyAndScheduleFlush()
|
||||
// Small delay to ensure they're separate operations
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
creationDuration := time.Since(start)
|
||||
t.Logf("Created %d issues in %v", numIssues, creationDuration)
|
||||
|
||||
// Wait for JSONL update
|
||||
timeout := time.After(2 * time.Second) // 500ms debounce + margin
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
var updated bool
|
||||
for !updated {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
modTime := getModTime()
|
||||
if modTime.After(preTestModTime) {
|
||||
updated = true
|
||||
}
|
||||
case <-timeout:
|
||||
t.Fatal("JSONL file not updated within 2 seconds")
|
||||
}
|
||||
}
|
||||
|
||||
totalLatency := time.Since(start)
|
||||
t.Logf("All mutations exported in %v", totalLatency)
|
||||
|
||||
// Verify batching: rapid calls to markDirty within debounce window
|
||||
// should result in single flush after ~500ms
|
||||
if totalLatency > 2*time.Second {
|
||||
t.Errorf("Batching failed: total latency %v exceeds 2s", totalLatency)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
//go:build unix || linux || darwin
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var daemonSignals = []os.Signal{syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP}
|
||||
|
||||
// configureDaemonProcess sets up platform-specific process attributes for daemon
|
||||
func configureDaemonProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
}
|
||||
|
||||
func sendStopSignal(process *os.Process) error {
|
||||
return process.Signal(syscall.SIGTERM)
|
||||
}
|
||||
|
||||
func isReloadSignal(sig os.Signal) bool {
|
||||
return sig == syscall.SIGHUP
|
||||
}
|
||||
|
||||
// isProcessRunning checks if a process with the given PID is running.
|
||||
// Permission-aware: handles EPERM (operation not permitted) correctly.
|
||||
//
|
||||
// In sandboxed environments, syscall.Kill may return EPERM even when the process
|
||||
// exists. We treat EPERM as "process exists but we can't signal it", which means
|
||||
// it's still running from our perspective.
|
||||
//
|
||||
// Implements bd-e0o: Phase 3 permission-aware process checks for GH #353
|
||||
func isProcessRunning(pid int) bool {
|
||||
err := syscall.Kill(pid, 0)
|
||||
if err == nil {
|
||||
// No error = process exists and we can signal it
|
||||
return true
|
||||
}
|
||||
if err == syscall.EPERM {
|
||||
// EPERM = operation not permitted
|
||||
// Process exists but we don't have permission to signal it
|
||||
// This happens in sandboxed environments (Codex, containers)
|
||||
// Treat this as "process is running"
|
||||
return true
|
||||
}
|
||||
// ESRCH = no such process
|
||||
// Any other error = process not running
|
||||
return false
|
||||
}
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
//go:build unix
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestIsProcessRunning_SelfCheck verifies that we can always detect our own process
|
||||
func TestIsProcessRunning_SelfCheck(t *testing.T) {
|
||||
myPID := os.Getpid()
|
||||
if !isProcessRunning(myPID) {
|
||||
t.Errorf("isProcessRunning(%d) returned false for our own PID", myPID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsProcessRunning_Init verifies that PID 1 (init/systemd/launchd) is always running
|
||||
func TestIsProcessRunning_Init(t *testing.T) {
|
||||
// PID 1 should always be running on Unix systems
|
||||
if !isProcessRunning(1) {
|
||||
t.Errorf("isProcessRunning(1) returned false, but init/systemd should always be running")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsProcessRunning_NonexistentProcess verifies that we correctly detect dead processes
|
||||
func TestIsProcessRunning_NonexistentProcess(t *testing.T) {
|
||||
// Pick a PID that's very unlikely to exist (max PID on most systems is < 100000)
|
||||
impossiblePID := 9999999
|
||||
if isProcessRunning(impossiblePID) {
|
||||
t.Errorf("isProcessRunning(%d) returned true for likely nonexistent PID", impossiblePID)
|
||||
t.Logf("If this fails, the test PID may actually exist on this system")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsProcessRunning_ParentProcess verifies that we can detect our parent process
|
||||
func TestIsProcessRunning_ParentProcess(t *testing.T) {
|
||||
parentPID := os.Getppid()
|
||||
if parentPID == 0 {
|
||||
t.Skip("Parent PID is 0 (orphaned process), skipping test")
|
||||
}
|
||||
if parentPID == 1 {
|
||||
t.Skip("Parent PID is 1 (adopted by init), skipping test")
|
||||
}
|
||||
|
||||
// Our parent process should be running (it spawned us)
|
||||
if !isProcessRunning(parentPID) {
|
||||
t.Errorf("isProcessRunning(%d) returned false for our parent process", parentPID)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
// WASM doesn't support signals or process management
|
||||
var daemonSignals = []os.Signal{}
|
||||
|
||||
func configureDaemonProcess(cmd *exec.Cmd) {
|
||||
// No-op in WASM
|
||||
}
|
||||
|
||||
func sendStopSignal(process *os.Process) error {
|
||||
return fmt.Errorf("daemon operations not supported in WASM")
|
||||
}
|
||||
|
||||
func isReloadSignal(sig os.Signal) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func isProcessRunning(pid int) bool {
|
||||
return false
|
||||
}
|
||||
|
|
@ -1,368 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
)
|
||||
|
||||
// FileWatcher monitors JSONL and git ref changes using filesystem events or polling.
|
||||
type FileWatcher struct {
|
||||
watcher *fsnotify.Watcher
|
||||
debouncer *Debouncer
|
||||
jsonlPath string
|
||||
parentDir string
|
||||
pollingMode bool
|
||||
lastModTime time.Time
|
||||
lastExists bool
|
||||
lastSize int64
|
||||
pollInterval time.Duration
|
||||
gitRefsPath string
|
||||
gitHeadPath string
|
||||
lastHeadModTime time.Time
|
||||
lastHeadExists bool
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup // Track goroutines for graceful shutdown
|
||||
// Log deduplication: track last log times to avoid duplicate messages
|
||||
lastFileLogTime time.Time
|
||||
lastGitRefLogTime time.Time
|
||||
logDedupeWindow time.Duration
|
||||
logMu sync.Mutex
|
||||
}
|
||||
|
||||
// NewFileWatcher creates a file watcher for the given JSONL path.
|
||||
// onChanged is called when the file or git refs change, after debouncing.
|
||||
// Falls back to polling mode if fsnotify fails (controlled by BEADS_WATCHER_FALLBACK env var).
|
||||
func NewFileWatcher(jsonlPath string, onChanged func()) (*FileWatcher, error) {
|
||||
fw := &FileWatcher{
|
||||
jsonlPath: jsonlPath,
|
||||
parentDir: filepath.Dir(jsonlPath),
|
||||
debouncer: NewDebouncer(500*time.Millisecond, onChanged),
|
||||
pollInterval: 5 * time.Second,
|
||||
logDedupeWindow: 500 * time.Millisecond, // Deduplicate logs within this window
|
||||
}
|
||||
|
||||
// Get initial file state for polling fallback
|
||||
if stat, err := os.Stat(jsonlPath); err == nil {
|
||||
fw.lastModTime = stat.ModTime()
|
||||
fw.lastExists = true
|
||||
fw.lastSize = stat.Size()
|
||||
}
|
||||
|
||||
// Check if fallback is disabled
|
||||
fallbackEnv := os.Getenv("BEADS_WATCHER_FALLBACK")
|
||||
fallbackDisabled := fallbackEnv == "false" || fallbackEnv == "0"
|
||||
|
||||
// Store git paths for filtering using worktree-aware detection
|
||||
gitDir, err := git.GetGitDir()
|
||||
if err != nil {
|
||||
// Not a git repo, skip git path setup
|
||||
fw.gitRefsPath = ""
|
||||
fw.gitHeadPath = ""
|
||||
} else {
|
||||
fw.gitRefsPath = filepath.Join(gitDir, "refs", "heads")
|
||||
fw.gitHeadPath = filepath.Join(gitDir, "HEAD")
|
||||
}
|
||||
|
||||
// Get initial git HEAD state for polling
|
||||
if stat, err := os.Stat(fw.gitHeadPath); err == nil {
|
||||
fw.lastHeadModTime = stat.ModTime()
|
||||
fw.lastHeadExists = true
|
||||
}
|
||||
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
if fallbackDisabled {
|
||||
return nil, fmt.Errorf("fsnotify.NewWatcher() failed and BEADS_WATCHER_FALLBACK is disabled: %w", err)
|
||||
}
|
||||
// Fall back to polling mode
|
||||
fmt.Fprintf(os.Stderr, "Warning: fsnotify.NewWatcher() failed (%v), falling back to polling mode (%v interval)\n", err, fw.pollInterval)
|
||||
fmt.Fprintf(os.Stderr, "Set BEADS_WATCHER_FALLBACK=false to disable this fallback and require fsnotify\n")
|
||||
fw.pollingMode = true
|
||||
return fw, nil
|
||||
}
|
||||
|
||||
fw.watcher = watcher
|
||||
|
||||
// Watch the parent directory (catches creates/renames)
|
||||
if err := watcher.Add(fw.parentDir); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to watch parent directory %s: %v\n", fw.parentDir, err)
|
||||
}
|
||||
|
||||
// Watch the JSONL file (may not exist yet)
|
||||
if err := watcher.Add(jsonlPath); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
// File doesn't exist yet - rely on parent dir watch
|
||||
fmt.Fprintf(os.Stderr, "Info: JSONL file %s doesn't exist yet, watching parent directory\n", jsonlPath)
|
||||
} else {
|
||||
_ = watcher.Close()
|
||||
if fallbackDisabled {
|
||||
return nil, fmt.Errorf("failed to watch JSONL and BEADS_WATCHER_FALLBACK is disabled: %w", err)
|
||||
}
|
||||
// Fall back to polling mode
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to watch JSONL (%v), falling back to polling mode (%v interval)\n", err, fw.pollInterval)
|
||||
fmt.Fprintf(os.Stderr, "Set BEADS_WATCHER_FALLBACK=false to disable this fallback and require fsnotify\n")
|
||||
fw.pollingMode = true
|
||||
fw.watcher = nil
|
||||
return fw, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Also watch .git/refs/heads and .git/HEAD for branch changes (best effort)
|
||||
if fw.gitRefsPath != "" {
|
||||
_ = watcher.Add(fw.gitRefsPath) // Ignore error - not all setups have this
|
||||
}
|
||||
if fw.gitHeadPath != "" {
|
||||
_ = watcher.Add(fw.gitHeadPath) // Ignore error - not all setups have this
|
||||
}
|
||||
|
||||
return fw, nil
|
||||
}
|
||||
|
||||
// shouldLogFileChange returns true if enough time has passed since last file change log
|
||||
func (fw *FileWatcher) shouldLogFileChange() bool {
|
||||
fw.logMu.Lock()
|
||||
defer fw.logMu.Unlock()
|
||||
now := time.Now()
|
||||
if now.Sub(fw.lastFileLogTime) >= fw.logDedupeWindow {
|
||||
fw.lastFileLogTime = now
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// shouldLogGitRefChange returns true if enough time has passed since last git ref change log
|
||||
func (fw *FileWatcher) shouldLogGitRefChange() bool {
|
||||
fw.logMu.Lock()
|
||||
defer fw.logMu.Unlock()
|
||||
now := time.Now()
|
||||
if now.Sub(fw.lastGitRefLogTime) >= fw.logDedupeWindow {
|
||||
fw.lastGitRefLogTime = now
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Start begins monitoring filesystem events or polling.
|
||||
// Runs in background goroutine until context is canceled.
|
||||
// Should only be called once per FileWatcher instance.
|
||||
func (fw *FileWatcher) Start(ctx context.Context, log *slog.Logger) {
|
||||
// Create internal cancel so Close can stop goroutines
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
fw.cancel = cancel
|
||||
|
||||
if fw.pollingMode {
|
||||
fw.startPolling(ctx, log)
|
||||
return
|
||||
}
|
||||
|
||||
fw.wg.Add(1)
|
||||
go func() {
|
||||
defer fw.wg.Done()
|
||||
jsonlBase := filepath.Base(fw.jsonlPath)
|
||||
|
||||
for {
|
||||
select {
|
||||
case event, ok := <-fw.watcher.Events:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Handle parent directory events (file create/replace)
|
||||
if event.Name == filepath.Join(fw.parentDir, jsonlBase) && event.Op&fsnotify.Create != 0 {
|
||||
log.Info("JSONL file created", "path", event.Name)
|
||||
// Ensure we're watching the file directly
|
||||
_ = fw.watcher.Add(fw.jsonlPath)
|
||||
fw.debouncer.Trigger()
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle JSONL write/chmod events
|
||||
if event.Name == fw.jsonlPath && event.Op&(fsnotify.Write|fsnotify.Create|fsnotify.Chmod) != 0 {
|
||||
if fw.shouldLogFileChange() {
|
||||
log.Info("File change detected", "path", event.Name)
|
||||
}
|
||||
fw.debouncer.Trigger()
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle JSONL removal/rename (e.g., git checkout)
|
||||
if event.Name == fw.jsonlPath && (event.Op&fsnotify.Remove != 0 || event.Op&fsnotify.Rename != 0) {
|
||||
log.Info("JSONL removed/renamed, re-establishing watch")
|
||||
_ = fw.watcher.Remove(fw.jsonlPath)
|
||||
// Retry with exponential backoff in a separate goroutine
|
||||
// to avoid blocking the event loop (which could cause
|
||||
// dropped events if the fsnotify buffer fills).
|
||||
fw.wg.Add(1)
|
||||
go func() {
|
||||
defer fw.wg.Done()
|
||||
fw.reEstablishWatch(ctx, log)
|
||||
}()
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle .git/HEAD changes (branch switches)
|
||||
if event.Name == fw.gitHeadPath && event.Op&(fsnotify.Write|fsnotify.Create) != 0 {
|
||||
log.Info("Git HEAD change detected", "path", event.Name)
|
||||
fw.debouncer.Trigger()
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle git ref changes (only events under gitRefsPath)
|
||||
// Fix: check gitRefsPath is not empty, otherwise HasPrefix("any", "") is always true
|
||||
if fw.gitRefsPath != "" && event.Op&fsnotify.Write != 0 && strings.HasPrefix(event.Name, fw.gitRefsPath) {
|
||||
if fw.shouldLogGitRefChange() {
|
||||
log.Info("Git ref change detected", "path", event.Name)
|
||||
}
|
||||
fw.debouncer.Trigger()
|
||||
continue
|
||||
}
|
||||
|
||||
case err, ok := <-fw.watcher.Errors:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
log.Info("Watcher error", "error", err)
|
||||
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// reEstablishWatch attempts to re-add the JSONL watch with exponential backoff.
|
||||
func (fw *FileWatcher) reEstablishWatch(ctx context.Context, log *slog.Logger) {
|
||||
delays := []time.Duration{50 * time.Millisecond, 100 * time.Millisecond, 200 * time.Millisecond, 400 * time.Millisecond}
|
||||
|
||||
for _, delay := range delays {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(delay):
|
||||
if err := fw.watcher.Add(fw.jsonlPath); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
log.Info("JSONL still missing, retrying...", "delay", delay)
|
||||
continue
|
||||
}
|
||||
log.Info("Failed to re-watch JSONL", "delay", delay, "error", err)
|
||||
return
|
||||
}
|
||||
// Success!
|
||||
log.Info("Successfully re-established JSONL watch", "delay", delay)
|
||||
fw.debouncer.Trigger()
|
||||
return
|
||||
}
|
||||
}
|
||||
log.Info("Failed to re-establish JSONL watch after all retries")
|
||||
}
|
||||
|
||||
// startPolling begins polling for file changes using a ticker.
|
||||
func (fw *FileWatcher) startPolling(ctx context.Context, log *slog.Logger) {
|
||||
log.Info("Starting polling mode", "interval", fw.pollInterval)
|
||||
ticker := time.NewTicker(fw.pollInterval)
|
||||
fw.wg.Add(1)
|
||||
go func() {
|
||||
defer fw.wg.Done()
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
changed := false
|
||||
|
||||
// Check JSONL file
|
||||
stat, err := os.Stat(fw.jsonlPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
// File disappeared
|
||||
if fw.lastExists {
|
||||
fw.lastExists = false
|
||||
fw.lastModTime = time.Time{}
|
||||
fw.lastSize = 0
|
||||
log.Info("File missing (polling)", "path", fw.jsonlPath)
|
||||
changed = true
|
||||
}
|
||||
} else {
|
||||
log.Info("Polling error", "error", err)
|
||||
}
|
||||
} else {
|
||||
// File exists
|
||||
if !fw.lastExists {
|
||||
// File appeared
|
||||
fw.lastExists = true
|
||||
fw.lastModTime = stat.ModTime()
|
||||
fw.lastSize = stat.Size()
|
||||
log.Info("File appeared (polling)", "path", fw.jsonlPath)
|
||||
changed = true
|
||||
} else if !stat.ModTime().Equal(fw.lastModTime) || stat.Size() != fw.lastSize {
|
||||
// File exists and existed before - check for changes
|
||||
fw.lastModTime = stat.ModTime()
|
||||
fw.lastSize = stat.Size()
|
||||
log.Info("File change detected (polling)", "path", fw.jsonlPath)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
|
||||
// Check .git/HEAD for branch changes (only if git paths are available)
|
||||
if fw.gitHeadPath != "" {
|
||||
headStat, err := os.Stat(fw.gitHeadPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
if fw.lastHeadExists {
|
||||
fw.lastHeadExists = false
|
||||
fw.lastHeadModTime = time.Time{}
|
||||
log.Info("Git HEAD missing (polling)", "path", fw.gitHeadPath)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
// Ignore other errors for HEAD - it's optional
|
||||
} else {
|
||||
// HEAD exists
|
||||
if !fw.lastHeadExists {
|
||||
// HEAD appeared
|
||||
fw.lastHeadExists = true
|
||||
fw.lastHeadModTime = headStat.ModTime()
|
||||
log.Info("Git HEAD appeared (polling)", "path", fw.gitHeadPath)
|
||||
changed = true
|
||||
} else if !headStat.ModTime().Equal(fw.lastHeadModTime) {
|
||||
// HEAD changed (branch switch)
|
||||
fw.lastHeadModTime = headStat.ModTime()
|
||||
log.Info("Git HEAD change detected (polling)", "path", fw.gitHeadPath)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if changed {
|
||||
fw.debouncer.Trigger()
|
||||
}
|
||||
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Close stops the file watcher and releases resources.
|
||||
func (fw *FileWatcher) Close() error {
|
||||
// Stop background goroutines
|
||||
if fw.cancel != nil {
|
||||
fw.cancel()
|
||||
}
|
||||
// Wait for goroutines to finish before cleanup
|
||||
fw.wg.Wait()
|
||||
fw.debouncer.Cancel()
|
||||
if fw.watcher != nil {
|
||||
return fw.watcher.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,317 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestFileWatcher_PlatformSpecificAPI verifies that fsnotify is using the correct
|
||||
// platform-specific file watching mechanism:
|
||||
// - Linux: inotify
|
||||
// - macOS: FSEvents (via kqueue in fsnotify)
|
||||
// - Windows: ReadDirectoryChangesW
|
||||
//
|
||||
// This test ensures the watcher works correctly with the native OS API.
|
||||
func TestFileWatcher_PlatformSpecificAPI(t *testing.T) {
|
||||
t.Parallel()
|
||||
// Skip in short mode - platform tests can be slower
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping platform-specific test in short mode")
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
// Create initial JSONL file
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var callCount int32
|
||||
onChange := func() {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create FileWatcher on %s: %v", runtime.GOOS, err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
// Verify we're using fsnotify (not polling) on supported platforms
|
||||
if fw.pollingMode {
|
||||
t.Logf("Warning: Running in polling mode on %s (expected fsnotify)", runtime.GOOS)
|
||||
// Don't fail - some environments may not support fsnotify
|
||||
} else {
|
||||
// Verify watcher was created
|
||||
if fw.watcher == nil {
|
||||
t.Fatal("watcher is nil but pollingMode is false")
|
||||
}
|
||||
t.Logf("Using fsnotify on %s (expected native API: %s)", runtime.GOOS, expectedAPI())
|
||||
}
|
||||
|
||||
// Override debounce duration for faster tests
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
// Start the watcher
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
// Wait for watcher to be ready
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Test 1: Basic file modification
|
||||
t.Run("FileModification", func(t *testing.T) {
|
||||
beforeCount := atomic.LoadInt32(&callCount)
|
||||
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}\n{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for debounce + processing using event-driven wait
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) > beforeCount
|
||||
})
|
||||
})
|
||||
|
||||
// Test 2: Multiple rapid changes (stress test for platform API)
|
||||
t.Run("RapidChanges", func(t *testing.T) {
|
||||
beforeCount := atomic.LoadInt32(&callCount)
|
||||
|
||||
// Make 10 rapid changes
|
||||
for i := 0; i < 10; i++ {
|
||||
content := make([]byte, i+1)
|
||||
for j := range content {
|
||||
content[j] = byte('{')
|
||||
}
|
||||
if err := os.WriteFile(jsonlPath, content, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Wait for debounce using event-driven wait
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
count := atomic.LoadInt32(&callCount) - beforeCount
|
||||
// Should have debounced to very few calls
|
||||
if count < 1 {
|
||||
return false
|
||||
}
|
||||
if count > 5 {
|
||||
t.Logf("Platform %s: High onChange count (%d) after rapid changes - may indicate debouncing issue", runtime.GOOS, count)
|
||||
}
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
// Test 3: Large file write (platform-specific buffering)
|
||||
t.Run("LargeFileWrite", func(t *testing.T) {
|
||||
beforeCount := atomic.LoadInt32(&callCount)
|
||||
|
||||
// Write a larger file (1KB)
|
||||
largeContent := make([]byte, 1024)
|
||||
for i := range largeContent {
|
||||
largeContent[i] = byte('x')
|
||||
}
|
||||
if err := os.WriteFile(jsonlPath, largeContent, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for debounce + processing using event-driven wait
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) > beforeCount
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// TestFileWatcher_PlatformFallback verifies polling fallback works on all platforms.
|
||||
// This is important because some environments (containers, network filesystems) may
|
||||
// not support native file watching APIs.
|
||||
func TestFileWatcher_PlatformFallback(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var callCount int32
|
||||
onChange := func() {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create FileWatcher on %s: %v", runtime.GOOS, err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
// Force polling mode to test fallback
|
||||
fw.pollingMode = true
|
||||
fw.pollInterval = 50 * time.Millisecond
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
t.Logf("Testing polling fallback on %s", runtime.GOOS)
|
||||
|
||||
// Wait for polling to start
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Modify file
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}\n{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for polling interval + debounce using event-driven wait
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) >= 1
|
||||
})
|
||||
}
|
||||
|
||||
// TestFileWatcher_CrossPlatformEdgeCases tests edge cases that may behave
|
||||
// differently across platforms.
|
||||
func TestFileWatcher_CrossPlatformEdgeCases(t *testing.T) {
|
||||
t.Parallel()
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping edge case tests in short mode")
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var callCount int32
|
||||
onChange := func() {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Test: File truncation
|
||||
t.Run("FileTruncation", func(t *testing.T) {
|
||||
if fw.pollingMode {
|
||||
t.Skip("Skipping fsnotify test in polling mode")
|
||||
}
|
||||
|
||||
beforeCount := atomic.LoadInt32(&callCount)
|
||||
|
||||
// Write larger content
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}\n{}\n{}\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for first write
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) > beforeCount
|
||||
})
|
||||
|
||||
beforeCount = atomic.LoadInt32(&callCount)
|
||||
|
||||
// Truncate to smaller size
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Check if truncation was detected
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
count := atomic.LoadInt32(&callCount) - beforeCount
|
||||
if count < 1 {
|
||||
t.Logf("Platform %s: File truncation not detected (count=%d)", runtime.GOOS, count)
|
||||
}
|
||||
})
|
||||
|
||||
// Test: Append operation
|
||||
t.Run("FileAppend", func(t *testing.T) {
|
||||
if fw.pollingMode {
|
||||
t.Skip("Skipping fsnotify test in polling mode")
|
||||
}
|
||||
|
||||
beforeCount := atomic.LoadInt32(&callCount)
|
||||
|
||||
// Append to file
|
||||
f, err := os.OpenFile(jsonlPath, os.O_APPEND|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.WriteString("\n{}"); err != nil {
|
||||
f.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for append to be detected using event-driven wait
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) > beforeCount
|
||||
})
|
||||
})
|
||||
|
||||
// Test: Permission change (may not trigger on all platforms)
|
||||
t.Run("PermissionChange", func(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Skipping permission test on Windows")
|
||||
}
|
||||
if fw.pollingMode {
|
||||
t.Skip("Skipping fsnotify test in polling mode")
|
||||
}
|
||||
|
||||
beforeCount := atomic.LoadInt32(&callCount)
|
||||
|
||||
// Change permissions
|
||||
if err := os.Chmod(jsonlPath, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// Permission changes typically don't trigger WRITE events
|
||||
// Log for informational purposes
|
||||
count := atomic.LoadInt32(&callCount) - beforeCount
|
||||
t.Logf("Platform %s: Permission change resulted in %d onChange calls (expected: 0)", runtime.GOOS, count)
|
||||
})
|
||||
}
|
||||
|
||||
// expectedAPI returns the expected native file watching API for the platform.
|
||||
func expectedAPI() string {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
return "inotify"
|
||||
case "darwin":
|
||||
return "FSEvents (via kqueue)"
|
||||
case "windows":
|
||||
return "ReadDirectoryChangesW"
|
||||
case "freebsd", "openbsd", "netbsd", "dragonfly":
|
||||
return "kqueue"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,401 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// newMockLogger creates a *slog.Logger that does nothing
|
||||
func newMockLogger() *slog.Logger {
|
||||
return newTestLogger()
|
||||
}
|
||||
|
||||
func TestFileWatcher_JSONLChangeDetection(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
// Create initial JSONL file
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Track onChange calls
|
||||
var callCount int32
|
||||
var mu sync.Mutex
|
||||
var callTimes []time.Time
|
||||
|
||||
onChange := func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
callTimes = append(callTimes, time.Now())
|
||||
}
|
||||
|
||||
// Create watcher with short debounce for testing
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
// Override debounce duration for faster tests
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
// Start the watcher
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
// Wait for watcher to be ready
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Modify the file
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}\n{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for debounce + processing using event-driven wait
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) >= 1
|
||||
})
|
||||
}
|
||||
|
||||
func TestFileWatcher_MultipleChangesDebounced(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var callCount int32
|
||||
onChange := func() {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
// Short debounce for testing
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Make multiple rapid changes
|
||||
for i := 0; i < 5; i++ {
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Wait for debounce using event-driven wait
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) >= 1
|
||||
})
|
||||
|
||||
count := atomic.LoadInt32(&callCount)
|
||||
// Should have debounced multiple changes into 1-2 calls, not 5
|
||||
if count > 3 {
|
||||
t.Errorf("Expected debouncing to reduce calls to ≤3, got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileWatcher_GitRefChangeDetection(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, ".beads", "issues.jsonl")
|
||||
gitRefsPath := filepath.Join(dir, ".git", "refs", "heads")
|
||||
|
||||
// Create directory structure
|
||||
if err := os.MkdirAll(filepath.Dir(jsonlPath), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(gitRefsPath, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var callCount int32
|
||||
var mu sync.Mutex
|
||||
var sources []string
|
||||
onChange := func() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
sources = append(sources, "onChange")
|
||||
}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
// Skip test if in polling mode (git ref watching not supported in polling mode)
|
||||
if fw.pollingMode {
|
||||
t.Skip("Git ref watching not available in polling mode")
|
||||
}
|
||||
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
// Verify git refs path is being watched
|
||||
if fw.watcher == nil {
|
||||
t.Fatal("watcher is nil")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// First, verify watcher is working by modifying JSONL
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) >= 1
|
||||
})
|
||||
|
||||
// Reset counter for git ref test
|
||||
atomic.StoreInt32(&callCount, 0)
|
||||
|
||||
// Simulate git ref change (branch update)
|
||||
// NOTE: fsnotify behavior for git refs can be platform-specific and unreliable
|
||||
// This test verifies the code path but may be skipped on some platforms
|
||||
refFile := filepath.Join(gitRefsPath, "main")
|
||||
if err := os.WriteFile(refFile, []byte("abc123"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for event detection + debounce (may not work on all platforms)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
count := atomic.LoadInt32(&callCount)
|
||||
if count < 1 {
|
||||
// Git ref watching can be unreliable with fsnotify in some environments
|
||||
t.Logf("Warning: git ref change not detected (count=%d) - this may be platform-specific fsnotify behavior", count)
|
||||
t.Skip("Git ref watching appears not to work in this environment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileWatcher_FileRemovalAndRecreation(t *testing.T) {
|
||||
t.Parallel()
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping file removal test in short mode")
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var callCount int32
|
||||
onChange := func() {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
// Skip test if in polling mode (separate test for polling)
|
||||
if fw.pollingMode {
|
||||
t.Skip("File removal/recreation not testable via fsnotify in polling mode")
|
||||
}
|
||||
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// First verify watcher is working
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) >= 1
|
||||
})
|
||||
|
||||
// Reset for removal test
|
||||
atomic.StoreInt32(&callCount, 0)
|
||||
|
||||
// Remove the file (simulates git checkout)
|
||||
if err := os.Remove(jsonlPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for removal to be detected + debounce
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
|
||||
// Recreate the file
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}\n{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for recreation to be detected + file re-watch + debounce (may not work on all platforms)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
count := atomic.LoadInt32(&callCount)
|
||||
if count < 1 {
|
||||
// File removal/recreation behavior can be platform-specific
|
||||
t.Logf("Warning: file removal+recreation not detected (count=%d) - this may be platform-specific", count)
|
||||
t.Skip("File removal/recreation watching appears not to work reliably in this environment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileWatcher_PollingFallback(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var callCount int32
|
||||
onChange := func() {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
// Force polling mode
|
||||
fw.pollingMode = true
|
||||
fw.pollInterval = 50 * time.Millisecond
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Modify file
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}\n{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for polling interval + debounce
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) >= 1
|
||||
})
|
||||
|
||||
count := atomic.LoadInt32(&callCount)
|
||||
if count < 1 {
|
||||
t.Errorf("Expected polling to detect file change, got %d calls", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileWatcher_PollingFileDisappearance(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var callCount int32
|
||||
onChange := func() {
|
||||
atomic.AddInt32(&callCount, 1)
|
||||
}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fw.Close()
|
||||
|
||||
fw.pollingMode = true
|
||||
fw.pollInterval = 50 * time.Millisecond
|
||||
fw.debouncer.duration = 10 * time.Millisecond
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Remove file
|
||||
if err := os.Remove(jsonlPath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for polling to detect disappearance
|
||||
waitFor(t, 200*time.Millisecond, 2*time.Millisecond, func() bool {
|
||||
return atomic.LoadInt32(&callCount) >= 1
|
||||
})
|
||||
|
||||
count := atomic.LoadInt32(&callCount)
|
||||
if count < 1 {
|
||||
t.Errorf("Expected polling to detect file disappearance, got %d calls", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileWatcher_Close(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
jsonlPath := filepath.Join(dir, "test.jsonl")
|
||||
|
||||
if err := os.WriteFile(jsonlPath, []byte("{}"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
onChange := func() {}
|
||||
|
||||
fw, err := NewFileWatcher(jsonlPath, onChange)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
fw.Start(ctx, newMockLogger())
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
// Close should not error
|
||||
if err := fw.Close(); err != nil {
|
||||
t.Errorf("Close() returned error: %v", err)
|
||||
}
|
||||
|
||||
// Second close should be safe
|
||||
if err := fw.Close(); err != nil {
|
||||
t.Errorf("Second Close() returned error: %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
const stillActive = 259
|
||||
|
||||
var daemonSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
|
||||
|
||||
// configureDaemonProcess sets up platform-specific process attributes for daemon
|
||||
func configureDaemonProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP,
|
||||
HideWindow: true,
|
||||
}
|
||||
}
|
||||
|
||||
// sendStopSignal sends a graceful shutdown signal to the daemon process on Windows.
|
||||
//
|
||||
// On Windows, SIGTERM is not supported and always fails, causing an immediate
|
||||
// fallback to TerminateProcess (Kill) which interrupts in-flight operations.
|
||||
// Instead, we use GenerateConsoleCtrlEvent with CTRL_BREAK_EVENT, which is the
|
||||
// standard Windows mechanism for graceful shutdown. The daemon process is created
|
||||
// with CREATE_NEW_PROCESS_GROUP (see configureDaemonProcess), so its process
|
||||
// group ID equals its PID. The daemon's signal handler receives this as
|
||||
// os.Interrupt and performs a clean shutdown.
|
||||
func sendStopSignal(process *os.Process) error {
|
||||
// CTRL_BREAK_EVENT is delivered to all processes in the target process group.
|
||||
// Since the daemon was started with CREATE_NEW_PROCESS_GROUP, its group ID
|
||||
// is its own PID. This triggers os.Interrupt in the daemon's signal handler.
|
||||
return windows.GenerateConsoleCtrlEvent(windows.CTRL_BREAK_EVENT, uint32(process.Pid))
|
||||
}
|
||||
|
||||
func isReloadSignal(os.Signal) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func isProcessRunning(pid int) bool {
|
||||
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer windows.CloseHandle(handle)
|
||||
|
||||
var code uint32
|
||||
if err := windows.GetExitCodeProcess(handle, &code); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return code == stillActive
|
||||
}
|
||||
|
|
@ -1,709 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/daemon"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
)
|
||||
|
||||
// fileRotated checks if the file at path is a different file than f (log rotation).
|
||||
// Uses os.SameFile for cross-platform inode/file identity comparison.
|
||||
func fileRotated(f *os.File, path string) bool {
|
||||
fInfo, err := f.Stat()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
pathInfo, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false // path gone; not rotated yet
|
||||
}
|
||||
return !os.SameFile(fInfo, pathInfo)
|
||||
}
|
||||
|
||||
// JSON response types for daemons commands
|
||||
|
||||
// DaemonStopResponse is returned when a daemon is stopped
|
||||
type DaemonStopResponse struct {
|
||||
Workspace string `json:"workspace"`
|
||||
PID int `json:"pid"`
|
||||
Stopped bool `json:"stopped"`
|
||||
}
|
||||
|
||||
// DaemonRestartResponse is returned when a daemon is restarted
|
||||
type DaemonRestartResponse struct {
|
||||
Workspace string `json:"workspace"`
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
// DaemonLogsResponse is returned for daemon logs in JSON mode
|
||||
type DaemonLogsResponse struct {
|
||||
Workspace string `json:"workspace"`
|
||||
LogPath string `json:"log_path"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// DaemonKillallEmptyResponse is returned when no daemons are running
|
||||
type DaemonKillallEmptyResponse struct {
|
||||
Stopped int `json:"stopped"`
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
|
||||
// DaemonHealthReport is a single daemon health report entry
|
||||
type DaemonHealthReport struct {
|
||||
Workspace string `json:"workspace"`
|
||||
SocketPath string `json:"socket_path"`
|
||||
PID int `json:"pid,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Issue string `json:"issue,omitempty"`
|
||||
VersionMismatch bool `json:"version_mismatch,omitempty"`
|
||||
}
|
||||
|
||||
// DaemonHealthResponse is returned for daemon health check
|
||||
type DaemonHealthResponse struct {
|
||||
Total int `json:"total"`
|
||||
Healthy int `json:"healthy"`
|
||||
Stale int `json:"stale"`
|
||||
Mismatched int `json:"mismatched"`
|
||||
Unresponsive int `json:"unresponsive"`
|
||||
Daemons []DaemonHealthReport `json:"daemons"`
|
||||
}
|
||||
|
||||
// daemonsCmd is no longer needed — "daemons" is now a Cobra alias on daemonCmd.
|
||||
// See daemon.go for the primary command definition.
|
||||
var daemonsListCmd = &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List all running bd daemons",
|
||||
Long: `List all running bd daemons with metadata including workspace path, PID, version,
|
||||
uptime, last activity, and exclusive lock status.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
searchRoots, _ := cmd.Flags().GetStringSlice("search")
|
||||
// Use global jsonOutput set by PersistentPreRun
|
||||
// Discover daemons
|
||||
daemons, err := daemon.DiscoverDaemons(searchRoots)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error discovering daemons: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// Auto-cleanup stale sockets (unless --no-cleanup flag is set)
|
||||
noCleanup, _ := cmd.Flags().GetBool("no-cleanup")
|
||||
if !noCleanup {
|
||||
cleaned, err := daemon.CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to cleanup stale sockets: %v\n", err)
|
||||
} else if cleaned > 0 && !jsonOutput {
|
||||
fmt.Fprintf(os.Stderr, "Cleaned up %d stale socket(s)\n", cleaned)
|
||||
}
|
||||
}
|
||||
// Filter to only alive daemons
|
||||
var aliveDaemons []daemon.DaemonInfo
|
||||
for _, d := range daemons {
|
||||
if d.Alive {
|
||||
aliveDaemons = append(aliveDaemons, d)
|
||||
}
|
||||
}
|
||||
if jsonOutput {
|
||||
data, _ := json.MarshalIndent(aliveDaemons, "", " ")
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
// Human-readable table output
|
||||
if len(aliveDaemons) == 0 {
|
||||
fmt.Println("No running daemons found")
|
||||
return
|
||||
}
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||
_, _ = fmt.Fprintln(w, "WORKSPACE\tPID\tVERSION\tUPTIME\tLAST ACTIVITY\tLOCK")
|
||||
for _, d := range aliveDaemons {
|
||||
workspace := d.WorkspacePath
|
||||
if workspace == "" {
|
||||
workspace = "(unknown)"
|
||||
}
|
||||
uptime := formatDaemonDuration(d.UptimeSeconds)
|
||||
lastActivity := "(unknown)"
|
||||
if d.LastActivityTime != "" {
|
||||
if t, err := time.Parse(time.RFC3339, d.LastActivityTime); err == nil {
|
||||
lastActivity = formatDaemonRelativeTime(t)
|
||||
}
|
||||
}
|
||||
lock := "-"
|
||||
if d.ExclusiveLockActive {
|
||||
lock = fmt.Sprintf("🔒 %s", d.ExclusiveLockHolder)
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, "%s\t%d\t%s\t%s\t%s\t%s\n",
|
||||
workspace, d.PID, d.Version, uptime, lastActivity, lock)
|
||||
}
|
||||
_ = w.Flush()
|
||||
},
|
||||
}
|
||||
|
||||
func formatDaemonDuration(seconds float64) string {
|
||||
d := time.Duration(seconds * float64(time.Second))
|
||||
if d < time.Minute {
|
||||
return fmt.Sprintf("%.0fs", d.Seconds())
|
||||
} else if d < time.Hour {
|
||||
return fmt.Sprintf("%.0fm", d.Minutes())
|
||||
} else if d < 24*time.Hour {
|
||||
return fmt.Sprintf("%.1fh", d.Hours())
|
||||
}
|
||||
return fmt.Sprintf("%.1fd", d.Hours()/24)
|
||||
}
|
||||
func formatDaemonRelativeTime(t time.Time) string {
|
||||
d := time.Since(t)
|
||||
if d < time.Minute {
|
||||
return "just now"
|
||||
} else if d < time.Hour {
|
||||
return fmt.Sprintf("%.0fm ago", d.Minutes())
|
||||
} else if d < 24*time.Hour {
|
||||
return fmt.Sprintf("%.1fh ago", d.Hours())
|
||||
}
|
||||
return fmt.Sprintf("%.1fd ago", d.Hours()/24)
|
||||
}
|
||||
|
||||
var daemonsStopCmd = &cobra.Command{
|
||||
Use: "stop <workspace-path|pid>",
|
||||
Short: "Stop a specific bd daemon",
|
||||
Long: `Stop a specific bd daemon gracefully by workspace path or PID.
|
||||
Sends shutdown command via RPC, with SIGTERM fallback if RPC fails.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
target := args[0]
|
||||
// Use global jsonOutput set by PersistentPreRun
|
||||
// Discover all daemons
|
||||
daemons, err := daemon.DiscoverDaemons(nil)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error discovering daemons: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// Find matching daemon by workspace path or PID
|
||||
// Use PathsEqual for case-insensitive comparison on macOS/Windows (GH#869)
|
||||
var targetDaemon *daemon.DaemonInfo
|
||||
for _, d := range daemons {
|
||||
if utils.PathsEqual(d.WorkspacePath, target) || fmt.Sprintf("%d", d.PID) == target {
|
||||
targetDaemon = &d
|
||||
break
|
||||
}
|
||||
}
|
||||
if targetDaemon == nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": "daemon not found"})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: daemon not found for %s\n", target)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
// Stop the daemon
|
||||
if err := daemon.StopDaemon(*targetDaemon); err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": err.Error()})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error stopping daemon: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
if jsonOutput {
|
||||
outputJSON(DaemonStopResponse{
|
||||
Workspace: targetDaemon.WorkspacePath,
|
||||
PID: targetDaemon.PID,
|
||||
Stopped: true,
|
||||
})
|
||||
} else {
|
||||
fmt.Printf("Stopped daemon for %s (PID %d)\n", targetDaemon.WorkspacePath, targetDaemon.PID)
|
||||
}
|
||||
},
|
||||
}
|
||||
var daemonsRestartCmd = &cobra.Command{
|
||||
Use: "restart <workspace-path|pid>",
|
||||
Short: "Restart a specific bd daemon",
|
||||
Long: `Restart a specific bd daemon by workspace path or PID.
|
||||
Stops the daemon gracefully, then starts a new one.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
PreRunE: guardDaemonStartForDolt,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
target := args[0]
|
||||
searchRoots, _ := cmd.Flags().GetStringSlice("search")
|
||||
// Use global jsonOutput set by PersistentPreRun
|
||||
// Discover daemons
|
||||
daemons, err := daemon.DiscoverDaemons(searchRoots)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error discovering daemons: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// Find the target daemon
|
||||
// Use PathsEqual for case-insensitive comparison on macOS/Windows (GH#869)
|
||||
var targetDaemon *daemon.DaemonInfo
|
||||
for _, d := range daemons {
|
||||
if utils.PathsEqual(d.WorkspacePath, target) || fmt.Sprintf("%d", d.PID) == target {
|
||||
targetDaemon = &d
|
||||
break
|
||||
}
|
||||
}
|
||||
if targetDaemon == nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": "daemon not found"})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: daemon not found for %s\n", target)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
workspace := targetDaemon.WorkspacePath
|
||||
|
||||
// Guardrail: don't (re)start daemons for single-process backends (e.g., embedded Dolt).
|
||||
// This command may be run from a different workspace, so check the target workspace.
|
||||
// Note: Dolt server mode supports multi-process, so GetCapabilities() is used.
|
||||
targetBeadsDir := beads.FollowRedirect(filepath.Join(workspace, ".beads"))
|
||||
if cfg, err := configfile.Load(targetBeadsDir); err == nil && cfg != nil {
|
||||
if cfg.GetCapabilities().SingleProcessOnly {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": fmt.Sprintf("daemon mode is not supported for backend %q (single-process only)", cfg.GetBackend())})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: cannot restart daemon for workspace %s: backend %q is single-process-only\n", workspace, cfg.GetBackend())
|
||||
fmt.Fprintf(os.Stderr, "Hint: initialize the workspace with sqlite backend for daemon mode (e.g. `bd init --backend sqlite`)\n")
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Stop the daemon
|
||||
if !jsonOutput {
|
||||
fmt.Printf("Stopping daemon for workspace: %s (PID %d)\n", workspace, targetDaemon.PID)
|
||||
}
|
||||
if err := daemon.StopDaemon(*targetDaemon); err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": err.Error()})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error stopping daemon: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
// Wait a moment for cleanup
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
// Start a new daemon by executing 'bd daemon' in the workspace directory
|
||||
if !jsonOutput {
|
||||
fmt.Printf("Starting new daemon for workspace: %s\n", workspace)
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": fmt.Sprintf("cannot resolve executable: %v", err)})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: cannot resolve executable: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
// Check if workspace-local bd binary exists (preferred)
|
||||
localBd := filepath.Join(workspace, "bd")
|
||||
_, localErr := os.Stat(localBd)
|
||||
bdPath := exe
|
||||
if localErr == nil {
|
||||
// Use local bd binary if it exists
|
||||
bdPath = localBd
|
||||
}
|
||||
// Use bd daemon command with proper working directory
|
||||
// The daemon will fork itself into the background
|
||||
daemonCmd := &exec.Cmd{
|
||||
Path: bdPath,
|
||||
Args: []string{bdPath, "daemon"},
|
||||
Dir: workspace,
|
||||
Env: os.Environ(),
|
||||
}
|
||||
if err := daemonCmd.Start(); err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": fmt.Sprintf("failed to start daemon: %v", err)})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error starting daemon: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
// Don't wait for daemon to exit (it will fork and continue in background)
|
||||
// Use timeout to prevent goroutine leak if daemon never completes
|
||||
go func() {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_ = daemonCmd.Wait()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// Daemon exited normally (forked successfully)
|
||||
case <-time.After(10 * time.Second):
|
||||
// Timeout - daemon should have forked by now
|
||||
if daemonCmd.Process != nil {
|
||||
_ = daemonCmd.Process.Kill()
|
||||
}
|
||||
}
|
||||
}()
|
||||
if jsonOutput {
|
||||
outputJSON(DaemonRestartResponse{
|
||||
Workspace: workspace,
|
||||
Action: "restarted",
|
||||
})
|
||||
} else {
|
||||
fmt.Printf("Successfully restarted daemon for workspace: %s\n", workspace)
|
||||
}
|
||||
},
|
||||
}
|
||||
var daemonsLogsCmd = &cobra.Command{
|
||||
Use: "logs <workspace-path|pid>",
|
||||
Short: "View logs for a specific bd daemon",
|
||||
Long: `View logs for a specific bd daemon by workspace path or PID.
|
||||
Supports tail mode (last N lines) and follow mode (like tail -f).`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
target := args[0]
|
||||
// Use global jsonOutput set by PersistentPreRun
|
||||
follow, _ := cmd.Flags().GetBool("follow")
|
||||
lines, _ := cmd.Flags().GetInt("lines")
|
||||
// Discover all daemons
|
||||
daemons, err := daemon.DiscoverDaemons(nil)
|
||||
if err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": err.Error()})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error discovering daemons: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
// Find matching daemon by workspace path or PID
|
||||
// Use PathsEqual for case-insensitive comparison on macOS/Windows (GH#869)
|
||||
var targetDaemon *daemon.DaemonInfo
|
||||
for _, d := range daemons {
|
||||
if utils.PathsEqual(d.WorkspacePath, target) || fmt.Sprintf("%d", d.PID) == target {
|
||||
targetDaemon = &d
|
||||
break
|
||||
}
|
||||
}
|
||||
if targetDaemon == nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": "daemon not found"})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: daemon not found for %s\n", target)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
// Determine log file path
|
||||
logPath := filepath.Join(filepath.Dir(targetDaemon.SocketPath), "daemon.log")
|
||||
// Check if log file exists
|
||||
if _, err := os.Stat(logPath); err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": "log file not found"})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error: log file not found: %s\n", logPath)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
if jsonOutput {
|
||||
// JSON mode: read entire file
|
||||
// #nosec G304 - controlled path from daemon discovery
|
||||
content, err := os.ReadFile(logPath)
|
||||
if err != nil {
|
||||
outputJSON(map[string]string{"error": err.Error()})
|
||||
os.Exit(1)
|
||||
}
|
||||
outputJSON(DaemonLogsResponse{
|
||||
Workspace: targetDaemon.WorkspacePath,
|
||||
LogPath: logPath,
|
||||
Content: string(content),
|
||||
})
|
||||
return
|
||||
}
|
||||
// Human-readable mode
|
||||
if follow {
|
||||
tailFollow(logPath)
|
||||
} else {
|
||||
if err := tailLines(logPath, lines); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error reading log file: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func tailLines(filePath string, n int) error {
|
||||
// #nosec G304 - controlled path from daemon discovery
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
// Read all lines
|
||||
var lines []string
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// Print last N lines
|
||||
start := 0
|
||||
if len(lines) > n {
|
||||
start = len(lines) - n
|
||||
}
|
||||
for i := start; i < len(lines); i++ {
|
||||
fmt.Println(lines[i])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func tailFollow(filePath string) {
|
||||
// Set up signal handling for graceful exit
|
||||
sigCh := make(chan os.Signal, 1)
|
||||
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
|
||||
defer signal.Stop(sigCh)
|
||||
|
||||
// #nosec G304 - controlled path from daemon discovery
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error opening log file: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Seek to end
|
||||
_, _ = file.Seek(0, io.SeekEnd)
|
||||
reader := bufio.NewReader(file)
|
||||
|
||||
for {
|
||||
// Check for signal before each iteration
|
||||
select {
|
||||
case <-sigCh:
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
// Check for log rotation: file at path is now a different file
|
||||
if fileRotated(file, filePath) {
|
||||
// File rotated — reopen
|
||||
file.Close()
|
||||
// #nosec G304 - controlled path from daemon discovery
|
||||
file, err = os.Open(filePath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error reopening rotated log file: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
reader.Reset(file)
|
||||
continue
|
||||
}
|
||||
|
||||
// Check for truncation: current position > file size
|
||||
if pos, err := file.Seek(0, io.SeekCurrent); err == nil {
|
||||
if info, err := file.Stat(); err == nil && pos > info.Size() {
|
||||
// File was truncated — seek to beginning
|
||||
_, _ = file.Seek(0, io.SeekStart)
|
||||
reader.Reset(file)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Normal EOF — wait for more content, but respect signals
|
||||
select {
|
||||
case <-sigCh:
|
||||
return
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Error reading log file: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Print(strings.TrimRight(line, "\n\r") + "\n")
|
||||
}
|
||||
}
|
||||
|
||||
var daemonsKillallCmd = &cobra.Command{
|
||||
Use: "killall",
|
||||
Short: "Stop all running bd daemons",
|
||||
Long: `Stop all running bd daemons gracefully via RPC, falling back to SIGTERM/SIGKILL.
|
||||
Uses escalating shutdown strategy: RPC (2s) → SIGTERM (3s) → SIGKILL (1s).`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
searchRoots, _ := cmd.Flags().GetStringSlice("search")
|
||||
// Use global jsonOutput set by PersistentPreRun
|
||||
force, _ := cmd.Flags().GetBool("force")
|
||||
// Discover all daemons
|
||||
daemons, err := daemon.DiscoverDaemons(searchRoots)
|
||||
if err != nil {
|
||||
if jsonOutput {
|
||||
outputJSON(map[string]string{"error": err.Error()})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error discovering daemons: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
// Filter to alive daemons only
|
||||
var aliveDaemons []daemon.DaemonInfo
|
||||
for _, d := range daemons {
|
||||
if d.Alive {
|
||||
aliveDaemons = append(aliveDaemons, d)
|
||||
}
|
||||
}
|
||||
if len(aliveDaemons) == 0 {
|
||||
if jsonOutput {
|
||||
outputJSON(DaemonKillallEmptyResponse{
|
||||
Stopped: 0,
|
||||
Failed: 0,
|
||||
})
|
||||
} else {
|
||||
fmt.Println("No running daemons found")
|
||||
}
|
||||
return
|
||||
}
|
||||
// Kill all daemons
|
||||
results := daemon.KillAllDaemons(aliveDaemons, force)
|
||||
if jsonOutput {
|
||||
outputJSON(results)
|
||||
} else {
|
||||
fmt.Printf("Stopped: %d\n", results.Stopped)
|
||||
fmt.Printf("Failed: %d\n", results.Failed)
|
||||
if len(results.Failures) > 0 {
|
||||
fmt.Println("\nFailures:")
|
||||
for _, f := range results.Failures {
|
||||
fmt.Printf(" %s (PID %d): %s\n", f.Workspace, f.PID, f.Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
if results.Failed > 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
},
|
||||
}
|
||||
var daemonsHealthCmd = &cobra.Command{
|
||||
Use: "health",
|
||||
Short: "Check health of all bd daemons",
|
||||
Long: `Check health of all running bd daemons and report any issues including
|
||||
stale sockets, version mismatches, and unresponsive daemons.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
searchRoots, _ := cmd.Flags().GetStringSlice("search")
|
||||
// Use global jsonOutput set by PersistentPreRun
|
||||
// Discover daemons
|
||||
daemons, err := daemon.DiscoverDaemons(searchRoots)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error discovering daemons: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
var reports []DaemonHealthReport
|
||||
healthyCount := 0
|
||||
staleCount := 0
|
||||
mismatchCount := 0
|
||||
unresponsiveCount := 0
|
||||
currentVersion := Version
|
||||
for _, d := range daemons {
|
||||
report := DaemonHealthReport{
|
||||
Workspace: d.WorkspacePath,
|
||||
SocketPath: d.SocketPath,
|
||||
PID: d.PID,
|
||||
Version: d.Version,
|
||||
}
|
||||
if !d.Alive {
|
||||
report.Status = "stale"
|
||||
report.Issue = d.Error
|
||||
staleCount++
|
||||
} else if d.Version != currentVersion {
|
||||
report.Status = "version_mismatch"
|
||||
report.Issue = fmt.Sprintf("daemon version %s != client version %s", d.Version, currentVersion)
|
||||
report.VersionMismatch = true
|
||||
mismatchCount++
|
||||
} else {
|
||||
report.Status = "healthy"
|
||||
healthyCount++
|
||||
}
|
||||
reports = append(reports, report)
|
||||
}
|
||||
if jsonOutput {
|
||||
outputJSON(DaemonHealthResponse{
|
||||
Total: len(reports),
|
||||
Healthy: healthyCount,
|
||||
Stale: staleCount,
|
||||
Mismatched: mismatchCount,
|
||||
Unresponsive: unresponsiveCount,
|
||||
Daemons: reports,
|
||||
})
|
||||
return
|
||||
}
|
||||
// Human-readable output
|
||||
if len(reports) == 0 {
|
||||
fmt.Println("No daemons found")
|
||||
return
|
||||
}
|
||||
fmt.Printf("Health Check Summary:\n")
|
||||
fmt.Printf(" Total: %d\n", len(reports))
|
||||
fmt.Printf(" Healthy: %d\n", healthyCount)
|
||||
fmt.Printf(" Stale: %d\n", staleCount)
|
||||
fmt.Printf(" Mismatched: %d\n", mismatchCount)
|
||||
fmt.Printf(" Unresponsive: %d\n\n", unresponsiveCount)
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||
_, _ = fmt.Fprintln(w, "WORKSPACE\tPID\tVERSION\tSTATUS\tISSUE")
|
||||
for _, r := range reports {
|
||||
workspace := r.Workspace
|
||||
if workspace == "" {
|
||||
workspace = "(unknown)"
|
||||
}
|
||||
pidStr := "-"
|
||||
if r.PID != 0 {
|
||||
pidStr = fmt.Sprintf("%d", r.PID)
|
||||
}
|
||||
version := r.Version
|
||||
if version == "" {
|
||||
version = "-"
|
||||
}
|
||||
status := r.Status
|
||||
issue := r.Issue
|
||||
if issue == "" {
|
||||
issue = "-"
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n",
|
||||
workspace, pidStr, version, status, issue)
|
||||
}
|
||||
_ = w.Flush()
|
||||
// Exit with error if there are any issues
|
||||
if staleCount > 0 || mismatchCount > 0 || unresponsiveCount > 0 {
|
||||
os.Exit(1)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
// Add multi-daemon subcommands to daemonCmd (primary location)
|
||||
daemonCmd.AddCommand(daemonsListCmd)
|
||||
daemonCmd.AddCommand(daemonsHealthCmd)
|
||||
daemonCmd.AddCommand(daemonsStopCmd)
|
||||
daemonCmd.AddCommand(daemonsLogsCmd)
|
||||
daemonCmd.AddCommand(daemonsKillallCmd)
|
||||
daemonCmd.AddCommand(daemonsRestartCmd)
|
||||
|
||||
// "daemons" backwards compatibility is handled by Aliases on daemonCmd
|
||||
// (see daemon.go). No separate daemonsCmd needed.
|
||||
|
||||
// Flags for list command
|
||||
daemonsListCmd.Flags().StringSlice("search", nil, "Directories to search for daemons (default: home, /tmp, cwd)")
|
||||
daemonsListCmd.Flags().Bool("no-cleanup", false, "Skip auto-cleanup of stale sockets")
|
||||
// Flags for health command
|
||||
daemonsHealthCmd.Flags().StringSlice("search", nil, "Directories to search for daemons (default: home, /tmp, cwd)")
|
||||
// Flags for stop command
|
||||
// Flags for logs command
|
||||
daemonsLogsCmd.Flags().BoolP("follow", "f", false, "Follow log output (like tail -f)")
|
||||
daemonsLogsCmd.Flags().IntP("lines", "n", 50, "Number of lines to show from end of log")
|
||||
// Flags for killall command
|
||||
daemonsKillallCmd.Flags().StringSlice("search", nil, "Directories to search for daemons (default: home, /tmp, cwd)")
|
||||
daemonsKillallCmd.Flags().Bool("force", false, "Use SIGKILL immediately if graceful shutdown fails")
|
||||
// Flags for restart command
|
||||
daemonsRestartCmd.Flags().StringSlice("search", nil, "Directories to search for daemons (default: home, /tmp, cwd)")
|
||||
}
|
||||
|
|
@ -1,122 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFormatDaemonDuration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
seconds float64
|
||||
expected string
|
||||
}{
|
||||
{"zero", 0, "0s"},
|
||||
{"seconds", 45, "45s"},
|
||||
{"minutes", 90.5, "2m"},
|
||||
{"hours", 3661, "1.0h"},
|
||||
{"days", 86400, "1.0d"},
|
||||
{"mixed", 93784, "1.1d"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := formatDaemonDuration(tt.seconds)
|
||||
if got != tt.expected {
|
||||
t.Errorf("formatDaemonDuration(%f) = %q, want %q", tt.seconds, got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatDaemonRelativeTime(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ago time.Duration
|
||||
expected string
|
||||
}{
|
||||
{"just now", 5 * time.Second, "just now"},
|
||||
{"minutes ago", 3 * time.Minute, "3m ago"},
|
||||
{"hours ago", 2 * time.Hour, "2.0h ago"},
|
||||
{"days ago", 25 * time.Hour, "1.0d ago"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
testTime := time.Now().Add(-tt.ago)
|
||||
got := formatDaemonRelativeTime(testTime)
|
||||
if got != tt.expected {
|
||||
t.Errorf("formatDaemonRelativeTime(%v) = %q, want %q", testTime, got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileRotated_SameFile(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "test.log")
|
||||
if err := os.WriteFile(path, []byte("hello\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if fileRotated(f, path) {
|
||||
t.Error("fileRotated should return false for the same file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileRotated_DifferentFile(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "test.log")
|
||||
if err := os.WriteFile(path, []byte("original\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Simulate rotation: rename old, create new at same path
|
||||
rotated := filepath.Join(tmp, "test.log.1")
|
||||
if err := os.Rename(path, rotated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("new content\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !fileRotated(f, path) {
|
||||
t.Error("fileRotated should return true after rotation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileRotated_PathGone(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
path := filepath.Join(tmp, "test.log")
|
||||
if err := os.WriteFile(path, []byte("hello\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Remove the file at path
|
||||
os.Remove(path)
|
||||
|
||||
// When path is gone, fileRotated returns false (not rotated yet)
|
||||
if fileRotated(f, path) {
|
||||
t.Error("fileRotated should return false when path is gone")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDaemonsFormatFunctions tests the formatting helpers
|
||||
// Integration tests for the actual commands are in daemon_test.go
|
||||
|
|
@ -13,47 +13,16 @@ import (
|
|||
)
|
||||
|
||||
// ensureDirectMode makes sure the CLI is operating in direct-storage mode.
|
||||
// If the daemon is active, it is cleanly disconnected and the shared store is opened.
|
||||
func ensureDirectMode(reason string) error {
|
||||
if getDaemonClient() != nil {
|
||||
if err := fallbackToDirectMode(reason); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func ensureDirectMode(_ string) error {
|
||||
return ensureStoreActive()
|
||||
}
|
||||
|
||||
// fallbackToDirectMode disables the daemon client and ensures a local store is ready.
|
||||
func fallbackToDirectMode(reason string) error {
|
||||
disableDaemonForFallback(reason)
|
||||
// fallbackToDirectMode ensures a local store is ready.
|
||||
// With the daemon removed, this simply ensures the store is active.
|
||||
func fallbackToDirectMode(_ string) error {
|
||||
return ensureStoreActive()
|
||||
}
|
||||
|
||||
// disableDaemonForFallback closes the daemon client and updates status metadata.
|
||||
func disableDaemonForFallback(reason string) {
|
||||
if client := getDaemonClient(); client != nil {
|
||||
_ = client.Close()
|
||||
setDaemonClient(nil)
|
||||
}
|
||||
|
||||
ds := getDaemonStatus()
|
||||
ds.Mode = "direct"
|
||||
ds.Connected = false
|
||||
ds.Degraded = true
|
||||
if reason != "" {
|
||||
ds.Detail = reason
|
||||
}
|
||||
if ds.FallbackReason == FallbackNone {
|
||||
ds.FallbackReason = FallbackDaemonUnsupported
|
||||
}
|
||||
setDaemonStatus(ds)
|
||||
|
||||
if reason != "" {
|
||||
debug.Logf("Debug: %s\n", reason)
|
||||
}
|
||||
}
|
||||
|
||||
// ensureStoreActive guarantees that a storage backend is initialized and tracked.
|
||||
// Uses the factory to respect metadata.json backend configuration (SQLite, Dolt embedded, or Dolt server).
|
||||
func ensureStoreActive() error {
|
||||
|
|
|
|||
|
|
@ -83,7 +83,6 @@ This command checks:
|
|||
- If Claude plugin is current (when running in Claude Code)
|
||||
- Multiple database files
|
||||
- Multiple JSONL files
|
||||
- Daemon health (version mismatches, stale processes)
|
||||
- Database-JSONL sync status
|
||||
- File permissions
|
||||
- Circular dependencies
|
||||
|
|
@ -445,27 +444,7 @@ func runDiagnostics(path string) doctorResult {
|
|||
result.OverallOK = false
|
||||
}
|
||||
|
||||
// Check 8a: Git sync setup (informational - explains why daemon might not start)
|
||||
gitSyncCheck := convertWithCategory(doctor.CheckGitSyncSetup(path), doctor.CategoryRuntime)
|
||||
result.Checks = append(result.Checks, gitSyncCheck)
|
||||
// Don't fail overall check for git sync warning - beads works fine without git
|
||||
|
||||
// Check 8b: Daemon health
|
||||
daemonCheck := convertWithCategory(doctor.CheckDaemonStatus(path, Version), doctor.CategoryRuntime)
|
||||
result.Checks = append(result.Checks, daemonCheck)
|
||||
if daemonCheck.Status == statusWarning || daemonCheck.Status == statusError {
|
||||
result.OverallOK = false
|
||||
}
|
||||
|
||||
// Check 8b: Daemon auto-sync (only warn, don't fail overall)
|
||||
autoSyncCheck := convertWithCategory(doctor.CheckDaemonAutoSync(path), doctor.CategoryRuntime)
|
||||
result.Checks = append(result.Checks, autoSyncCheck)
|
||||
// Note: Don't set OverallOK = false for this - it's a performance hint, not a failure
|
||||
|
||||
// Check 8c: Legacy daemon config (warn about deprecated options)
|
||||
legacyDaemonConfigCheck := convertWithCategory(doctor.CheckLegacyDaemonConfig(path), doctor.CategoryRuntime)
|
||||
result.Checks = append(result.Checks, legacyDaemonConfigCheck)
|
||||
// Note: Don't set OverallOK = false for this - deprecated options still work
|
||||
|
||||
// Federation health checks (bd-wkumz.6)
|
||||
// Check 8d: Federation remotesapi port accessibility
|
||||
|
|
@ -492,10 +471,6 @@ func runDiagnostics(path string) doctorResult {
|
|||
doltModeCheck := convertWithCategory(doctor.CheckDoltServerModeMismatch(path), doctor.CategoryFederation)
|
||||
result.Checks = append(result.Checks, doltModeCheck)
|
||||
|
||||
// Check 8i: Hydrated repo daemons (warn if multi-repo hydration configured but daemons not running)
|
||||
hydratedRepoDaemonsCheck := convertWithCategory(doctor.CheckHydratedRepoDaemons(path), doctor.CategoryRuntime)
|
||||
result.Checks = append(result.Checks, hydratedRepoDaemonsCheck)
|
||||
// Note: Don't set OverallOK = false for this - it's a performance/freshness hint
|
||||
|
||||
// Check 9: Database-JSONL sync
|
||||
syncCheck := convertWithCategory(doctor.CheckDatabaseJSONLSync(path), doctor.CategoryData)
|
||||
|
|
|
|||
|
|
@ -1,388 +0,0 @@
|
|||
package doctor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/steveyegge/beads/internal/daemon"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/storage/factory"
|
||||
"github.com/steveyegge/beads/internal/syncbranch"
|
||||
)
|
||||
|
||||
// CheckDaemonStatus checks the health of the daemon for a workspace.
|
||||
// It checks for stale sockets, multiple daemons, and version mismatches.
|
||||
func CheckDaemonStatus(path string, cliVersion string) DoctorCheck {
|
||||
// Normalize path for reliable comparison (handles symlinks)
|
||||
wsNorm, err := filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
// Fallback to absolute path if EvalSymlinks fails
|
||||
wsNorm, _ = filepath.Abs(path)
|
||||
}
|
||||
|
||||
// Use global daemon discovery (registry-based)
|
||||
daemons, err := daemon.DiscoverDaemons(nil)
|
||||
if err != nil {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Health",
|
||||
Status: StatusWarning,
|
||||
Message: "Unable to check daemon health",
|
||||
Detail: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
// Filter to this workspace using normalized paths
|
||||
var workspaceDaemons []daemon.DaemonInfo
|
||||
for _, d := range daemons {
|
||||
dPath, err := filepath.EvalSymlinks(d.WorkspacePath)
|
||||
if err != nil {
|
||||
dPath, _ = filepath.Abs(d.WorkspacePath)
|
||||
}
|
||||
if dPath == wsNorm {
|
||||
workspaceDaemons = append(workspaceDaemons, d)
|
||||
}
|
||||
}
|
||||
|
||||
// Check for stale socket directly (catches cases where RPC failed so WorkspacePath is empty)
|
||||
socketPath := rpc.ShortSocketPath(path)
|
||||
legacySocketPath := filepath.Join(resolveBeadsDir(filepath.Join(path, ".beads")), "bd.sock")
|
||||
staleSocket := ""
|
||||
if _, err := os.Stat(socketPath); err == nil {
|
||||
staleSocket = socketPath
|
||||
} else if socketPath != legacySocketPath {
|
||||
if _, err := os.Stat(legacySocketPath); err == nil {
|
||||
staleSocket = legacySocketPath
|
||||
}
|
||||
}
|
||||
if staleSocket != "" && len(workspaceDaemons) == 0 {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Health",
|
||||
Status: StatusWarning,
|
||||
Message: "Stale daemon socket detected",
|
||||
Detail: fmt.Sprintf("Socket exists at %s but daemon is not responding", staleSocket),
|
||||
Fix: "Run 'bd daemons killall' to clean up stale sockets",
|
||||
}
|
||||
}
|
||||
|
||||
if len(workspaceDaemons) == 0 {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Health",
|
||||
Status: StatusOK,
|
||||
Message: "No daemon running (will auto-start on next command)",
|
||||
}
|
||||
}
|
||||
|
||||
// Warn if multiple daemons for same workspace
|
||||
if len(workspaceDaemons) > 1 {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Health",
|
||||
Status: StatusWarning,
|
||||
Message: fmt.Sprintf("Multiple daemons detected for this workspace (%d)", len(workspaceDaemons)),
|
||||
Fix: "Run 'bd daemons killall' to clean up duplicate daemons",
|
||||
}
|
||||
}
|
||||
|
||||
// Check for stale or version mismatched daemons
|
||||
for _, d := range workspaceDaemons {
|
||||
if !d.Alive {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Health",
|
||||
Status: StatusWarning,
|
||||
Message: "Stale daemon detected",
|
||||
Detail: fmt.Sprintf("PID %d is not alive", d.PID),
|
||||
Fix: "Run 'bd daemons killall' to clean up stale daemons",
|
||||
}
|
||||
}
|
||||
|
||||
if d.Version != cliVersion {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Health",
|
||||
Status: StatusWarning,
|
||||
Message: fmt.Sprintf("Version mismatch (daemon: %s, CLI: %s)", d.Version, cliVersion),
|
||||
Fix: "Run 'bd daemons killall' to restart daemons with current version",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Health",
|
||||
Status: StatusOK,
|
||||
Message: fmt.Sprintf("Daemon running (PID %d, version %s)", workspaceDaemons[0].PID, workspaceDaemons[0].Version),
|
||||
}
|
||||
}
|
||||
|
||||
// CheckVersionMismatch checks if the database version matches the CLI version.
|
||||
// Returns a warning message if there's a mismatch, or empty string if versions match or can't be read.
|
||||
func CheckVersionMismatch(db *sql.DB, cliVersion string) string {
|
||||
var dbVersion string
|
||||
err := db.QueryRow("SELECT value FROM metadata WHERE key = 'bd_version'").Scan(&dbVersion)
|
||||
if err != nil {
|
||||
return "" // Can't read version, skip
|
||||
}
|
||||
|
||||
if dbVersion != "" && dbVersion != cliVersion {
|
||||
return fmt.Sprintf("Version mismatch (CLI: %s, database: %s)", cliVersion, dbVersion)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// CheckGitSyncSetup checks if git repository and sync-branch are configured for daemon sync.
|
||||
// This is informational - beads works fine without git sync, but users may want to enable it.
|
||||
func CheckGitSyncSetup(path string) DoctorCheck {
|
||||
// Check if we're in a git repository
|
||||
_, err := git.GetGitDir()
|
||||
if err != nil {
|
||||
return DoctorCheck{
|
||||
Name: "Git Sync Setup",
|
||||
Status: StatusWarning,
|
||||
Message: "No git repository (background sync unavailable)",
|
||||
Detail: "The daemon requires a git repository for background sync. Without it, beads runs in direct mode.",
|
||||
Fix: "Run 'git init' to enable background sync",
|
||||
Category: CategoryRuntime,
|
||||
}
|
||||
}
|
||||
|
||||
// Git repo exists - check if sync-branch is configured
|
||||
if !syncbranch.IsConfigured() {
|
||||
return DoctorCheck{
|
||||
Name: "Git Sync Setup",
|
||||
Status: StatusOK,
|
||||
Message: "Git repository detected (sync-branch not configured)",
|
||||
Detail: "Beads commits directly to current branch. For team collaboration or to keep beads changes isolated, consider using a sync-branch.",
|
||||
Fix: "Run 'bd config set sync.branch beads-sync' to use a dedicated branch for beads metadata",
|
||||
Category: CategoryRuntime,
|
||||
}
|
||||
}
|
||||
|
||||
return DoctorCheck{
|
||||
Name: "Git Sync Setup",
|
||||
Status: StatusOK,
|
||||
Message: "Git repository and sync-branch configured",
|
||||
Category: CategoryRuntime,
|
||||
}
|
||||
}
|
||||
|
||||
// CheckDaemonAutoSync checks if daemon has auto-commit/auto-push enabled when
|
||||
// sync-branch is configured. Missing auto-sync slows down agent workflows.
|
||||
func CheckDaemonAutoSync(path string) DoctorCheck {
|
||||
_, beadsDir := getBackendAndBeadsDir(path)
|
||||
socketPath := rpc.ShortSocketPath(filepath.Dir(beadsDir))
|
||||
|
||||
// Check if daemon is running
|
||||
if _, err := os.Stat(socketPath); os.IsNotExist(err) {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Auto-Sync",
|
||||
Status: StatusOK,
|
||||
Message: "Daemon not running (will use defaults on next start)",
|
||||
}
|
||||
}
|
||||
|
||||
// Check if sync-branch is configured
|
||||
ctx := context.Background()
|
||||
store, err := factory.NewFromConfigWithOptions(ctx, beadsDir, factory.Options{ReadOnly: true})
|
||||
if err != nil {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Auto-Sync",
|
||||
Status: StatusOK,
|
||||
Message: "Could not check config (database unavailable)",
|
||||
}
|
||||
}
|
||||
defer func() { _ = store.Close() }()
|
||||
|
||||
syncBranch, _ := store.GetConfig(ctx, "sync.branch")
|
||||
if syncBranch == "" {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Auto-Sync",
|
||||
Status: StatusOK,
|
||||
Message: "No sync-branch configured (auto-sync not applicable)",
|
||||
}
|
||||
}
|
||||
|
||||
// Sync-branch is configured - check daemon's auto-commit/auto-push status
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err != nil || client == nil {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Auto-Sync",
|
||||
Status: StatusWarning,
|
||||
Message: "Could not connect to daemon to check auto-sync status",
|
||||
}
|
||||
}
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
status, err := client.Status()
|
||||
if err != nil {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Auto-Sync",
|
||||
Status: StatusWarning,
|
||||
Message: "Could not get daemon status",
|
||||
Detail: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
if !status.AutoCommit || !status.AutoPush {
|
||||
var missing []string
|
||||
if !status.AutoCommit {
|
||||
missing = append(missing, "auto-commit")
|
||||
}
|
||||
if !status.AutoPush {
|
||||
missing = append(missing, "auto-push")
|
||||
}
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Auto-Sync",
|
||||
Status: StatusWarning,
|
||||
Message: fmt.Sprintf("Daemon running without %v (slows agent workflows)", missing),
|
||||
Detail: "With sync-branch configured, auto-commit and auto-push should be enabled",
|
||||
Fix: "Restart daemon: bd daemon stop . && bd daemon start",
|
||||
}
|
||||
}
|
||||
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Auto-Sync",
|
||||
Status: StatusOK,
|
||||
Message: "Auto-commit and auto-push enabled",
|
||||
}
|
||||
}
|
||||
|
||||
// CheckLegacyDaemonConfig checks for deprecated daemon config options and
|
||||
// encourages migration to the unified daemon.auto-sync setting.
|
||||
func CheckLegacyDaemonConfig(path string) DoctorCheck {
|
||||
_, beadsDir := getBackendAndBeadsDir(path)
|
||||
|
||||
ctx := context.Background()
|
||||
store, err := factory.NewFromConfigWithOptions(ctx, beadsDir, factory.Options{ReadOnly: true})
|
||||
if err != nil {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Config",
|
||||
Status: StatusOK,
|
||||
Message: "Could not check config (database unavailable)",
|
||||
}
|
||||
}
|
||||
defer func() { _ = store.Close() }()
|
||||
|
||||
// Check for deprecated individual settings
|
||||
var legacySettings []string
|
||||
|
||||
if val, _ := store.GetConfig(ctx, "daemon.auto_commit"); val != "" {
|
||||
legacySettings = append(legacySettings, "daemon.auto_commit")
|
||||
}
|
||||
if val, _ := store.GetConfig(ctx, "daemon.auto_push"); val != "" {
|
||||
legacySettings = append(legacySettings, "daemon.auto_push")
|
||||
}
|
||||
|
||||
if len(legacySettings) > 0 {
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Config",
|
||||
Status: StatusWarning,
|
||||
Message: fmt.Sprintf("Deprecated config options found: %v", legacySettings),
|
||||
Detail: "These options still work but are deprecated. Use daemon.auto-sync for read/write mode or daemon.auto-pull for read-only mode.",
|
||||
Fix: "Run: bd config delete daemon.auto_commit && bd config delete daemon.auto_push && bd config set daemon.auto-sync true",
|
||||
}
|
||||
}
|
||||
|
||||
return DoctorCheck{
|
||||
Name: "Daemon Config",
|
||||
Status: StatusOK,
|
||||
Message: "Using current config format",
|
||||
}
|
||||
}
|
||||
|
||||
// CheckHydratedRepoDaemons checks if daemons are running for all repos
|
||||
// configured in repos.additional. Without running daemons, JSONL files won't
|
||||
// be kept updated, causing multi-repo hydration to become stale (bd-fix-routing).
|
||||
func CheckHydratedRepoDaemons(path string) DoctorCheck {
|
||||
beadsDir := filepath.Join(path, ".beads")
|
||||
|
||||
ctx := context.Background()
|
||||
// Use factory to respect backend configuration (bd-m2jr: SQLite fallback fix)
|
||||
store, err := factory.NewFromConfig(ctx, beadsDir)
|
||||
if err != nil {
|
||||
return DoctorCheck{
|
||||
Name: "Hydrated Repo Daemons",
|
||||
Status: StatusOK,
|
||||
Message: "Could not check config (database unavailable)",
|
||||
}
|
||||
}
|
||||
defer func() { _ = store.Close() }()
|
||||
|
||||
// Get repos.additional from config
|
||||
additionalReposStr, _ := store.GetConfig(ctx, "repos.additional")
|
||||
if additionalReposStr == "" {
|
||||
return DoctorCheck{
|
||||
Name: "Hydrated Repo Daemons",
|
||||
Status: StatusOK,
|
||||
Message: "No additional repos configured (N/A)",
|
||||
}
|
||||
}
|
||||
|
||||
// Parse additional repos (stored as JSON array string)
|
||||
var additionalRepos []string
|
||||
if err := unmarshalConfigValue(additionalReposStr, &additionalRepos); err != nil {
|
||||
return DoctorCheck{
|
||||
Name: "Hydrated Repo Daemons",
|
||||
Status: StatusWarning,
|
||||
Message: "Could not parse repos.additional config",
|
||||
Detail: err.Error(),
|
||||
}
|
||||
}
|
||||
|
||||
if len(additionalRepos) == 0 {
|
||||
return DoctorCheck{
|
||||
Name: "Hydrated Repo Daemons",
|
||||
Status: StatusOK,
|
||||
Message: "No additional repos configured (N/A)",
|
||||
}
|
||||
}
|
||||
|
||||
// Check each additional repo for running daemon
|
||||
var missingDaemons []string
|
||||
for _, repoPath := range additionalRepos {
|
||||
// Expand ~ to home directory
|
||||
expandedPath := expandPath(repoPath)
|
||||
|
||||
// Construct socket path
|
||||
socketPath := rpc.ShortSocketPath(expandedPath)
|
||||
|
||||
// Try to connect to daemon
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err == nil && client != nil {
|
||||
_ = client.Close()
|
||||
// Daemon is running, all good
|
||||
} else {
|
||||
// No daemon running
|
||||
missingDaemons = append(missingDaemons, repoPath)
|
||||
}
|
||||
}
|
||||
|
||||
if len(missingDaemons) > 0 {
|
||||
return DoctorCheck{
|
||||
Name: "Hydrated Repo Daemons",
|
||||
Status: StatusWarning,
|
||||
Message: fmt.Sprintf("Daemons not running in %d hydrated repo(s)", len(missingDaemons)),
|
||||
Detail: fmt.Sprintf("Missing daemons in: %v", missingDaemons),
|
||||
Fix: "For each repo, run: cd <repo> && bd daemon start --local",
|
||||
}
|
||||
}
|
||||
|
||||
return DoctorCheck{
|
||||
Name: "Hydrated Repo Daemons",
|
||||
Status: StatusOK,
|
||||
Message: fmt.Sprintf("All %d hydrated repo(s) have running daemons", len(additionalRepos)),
|
||||
}
|
||||
}
|
||||
|
||||
// unmarshalConfigValue unmarshals a JSON config value
|
||||
func unmarshalConfigValue(value string, target interface{}) error {
|
||||
// Config values are stored as JSON
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unmarshal JSON into target
|
||||
return json.Unmarshal([]byte(value), target)
|
||||
}
|
||||
|
|
@ -1,291 +0,0 @@
|
|||
package doctor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/storage/sqlite"
|
||||
)
|
||||
|
||||
func TestCheckDaemonStatus(t *testing.T) {
|
||||
t.Run("no beads directory", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
check := CheckDaemonStatus(tmpDir, "1.0.0")
|
||||
|
||||
// Should return OK when no .beads directory (daemon not needed)
|
||||
if check.Status != StatusOK {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusOK)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("beads directory exists", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.Mkdir(beadsDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
check := CheckDaemonStatus(tmpDir, "1.0.0")
|
||||
|
||||
// Should check daemon status - may be OK or warning depending on daemon state
|
||||
if check.Name != "Daemon Health" {
|
||||
t.Errorf("Name = %q, want %q", check.Name, "Daemon Health")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCheckGitSyncSetup(t *testing.T) {
|
||||
t.Run("not in git repository", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
oldDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = os.Chdir(oldDir)
|
||||
git.ResetCaches()
|
||||
}()
|
||||
|
||||
if err := os.Chdir(tmpDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
check := CheckGitSyncSetup(tmpDir)
|
||||
|
||||
if check.Status != StatusWarning {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusWarning)
|
||||
}
|
||||
if check.Name != "Git Sync Setup" {
|
||||
t.Errorf("Name = %q, want %q", check.Name, "Git Sync Setup")
|
||||
}
|
||||
if check.Fix == "" {
|
||||
t.Error("Expected Fix to contain instructions")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("in git repository without sync-branch", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
oldDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = os.Chdir(oldDir)
|
||||
git.ResetCaches()
|
||||
}()
|
||||
|
||||
// Initialize git repo
|
||||
cmd := exec.Command("git", "init", "--initial-branch=main")
|
||||
cmd.Dir = tmpDir
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatalf("Failed to init git repo: %v", err)
|
||||
}
|
||||
|
||||
if err := os.Chdir(tmpDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
check := CheckGitSyncSetup(tmpDir)
|
||||
|
||||
if check.Status != StatusOK {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusOK)
|
||||
}
|
||||
if check.Name != "Git Sync Setup" {
|
||||
t.Errorf("Name = %q, want %q", check.Name, "Git Sync Setup")
|
||||
}
|
||||
// Should mention sync-branch not configured
|
||||
if check.Detail == "" {
|
||||
t.Error("Expected Detail to contain sync-branch hint")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCheckDaemonAutoSync(t *testing.T) {
|
||||
t.Run("no daemon socket", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.Mkdir(beadsDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
check := CheckDaemonAutoSync(tmpDir)
|
||||
|
||||
if check.Status != StatusOK {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusOK)
|
||||
}
|
||||
if check.Message != "Daemon not running (will use defaults on next start)" {
|
||||
t.Errorf("Message = %q, want 'Daemon not running...'", check.Message)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no sync-branch configured", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.Mkdir(beadsDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Create database without sync-branch config
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
store, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = store.Close() }()
|
||||
|
||||
// Create a fake socket file to simulate daemon running
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
if err := os.WriteFile(socketPath, []byte{}, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
check := CheckDaemonAutoSync(tmpDir)
|
||||
|
||||
// Should return OK because no sync-branch means auto-sync not applicable
|
||||
if check.Status != StatusOK {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusOK)
|
||||
}
|
||||
if check.Message != "No sync-branch configured (auto-sync not applicable)" {
|
||||
t.Errorf("Message = %q, want 'No sync-branch...'", check.Message)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("sync-branch configured but cannot connect", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.Mkdir(beadsDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Create database with sync-branch config
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
store, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetConfig(ctx, "sync.branch", "beads-sync"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = store.Close()
|
||||
|
||||
// Create a fake socket file (not a real daemon)
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
if err := os.WriteFile(socketPath, []byte{}, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
check := CheckDaemonAutoSync(tmpDir)
|
||||
|
||||
// Should return warning because can't connect to fake socket
|
||||
if check.Status != StatusWarning {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusWarning)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCheckHydratedRepoDaemons(t *testing.T) {
|
||||
t.Run("no additional repos configured", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.Mkdir(beadsDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Create database without repos.additional config
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
store, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = store.Close() }()
|
||||
|
||||
check := CheckHydratedRepoDaemons(tmpDir)
|
||||
|
||||
if check.Status != StatusOK {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusOK)
|
||||
}
|
||||
if check.Name != "Hydrated Repo Daemons" {
|
||||
t.Errorf("Name = %q, want %q", check.Name, "Hydrated Repo Daemons")
|
||||
}
|
||||
// Should say no additional repos configured
|
||||
if check.Message != "No additional repos configured (N/A)" {
|
||||
t.Errorf("Message = %q, want 'No additional repos configured (N/A)'", check.Message)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("additional repos configured but no daemons running", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.Mkdir(beadsDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Create a fake additional repo directory
|
||||
additionalRepo := t.TempDir()
|
||||
additionalBeadsDir := filepath.Join(additionalRepo, ".beads")
|
||||
if err := os.Mkdir(additionalBeadsDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Create database with repos.additional config
|
||||
dbPath := filepath.Join(beadsDir, "beads.db")
|
||||
ctx := context.Background()
|
||||
store, err := sqlite.New(ctx, dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = store.Close() }()
|
||||
|
||||
// Set repos.additional config (stored as JSON array)
|
||||
reposJSON := `["` + additionalRepo + `"]`
|
||||
if err := store.SetConfig(ctx, "repos.additional", reposJSON); err != nil {
|
||||
t.Fatalf("failed to set repos.additional: %v", err)
|
||||
}
|
||||
|
||||
check := CheckHydratedRepoDaemons(tmpDir)
|
||||
|
||||
// Should return warning because no daemon is running in additional repo
|
||||
if check.Status != StatusWarning {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusWarning)
|
||||
}
|
||||
if check.Name != "Hydrated Repo Daemons" {
|
||||
t.Errorf("Name = %q, want %q", check.Name, "Hydrated Repo Daemons")
|
||||
}
|
||||
// Should mention missing daemons
|
||||
if check.Fix == "" {
|
||||
t.Error("Expected Fix to contain remediation steps")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("database unavailable", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.Mkdir(beadsDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Don't create database - should handle gracefully
|
||||
|
||||
check := CheckHydratedRepoDaemons(tmpDir)
|
||||
|
||||
// When database is unavailable, GetConfig returns empty string,
|
||||
// so the check reports "No additional repos configured" which is OK status
|
||||
if check.Status != StatusOK {
|
||||
t.Errorf("Status = %q, want %q", check.Status, StatusOK)
|
||||
}
|
||||
// The function returns early when no config is found, treating it as "no repos"
|
||||
if !contains(check.Message, "No additional repos configured") {
|
||||
t.Errorf("Message = %q, want message about no additional repos", check.Message)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
package fix
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
)
|
||||
|
||||
// Daemon fixes daemon issues (stale sockets, version mismatches, duplicates)
|
||||
// by running bd daemons killall
|
||||
func Daemon(path string) error {
|
||||
// Validate workspace
|
||||
if err := validateBeadsWorkspace(path); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
socketPath := rpc.ShortSocketPath(path)
|
||||
legacySocketPath := filepath.Join(path, ".beads", "bd.sock")
|
||||
|
||||
// Check if there's actually a socket or daemon issue to fix
|
||||
hasSocket := false
|
||||
if _, err := os.Stat(socketPath); err == nil {
|
||||
hasSocket = true
|
||||
} else if socketPath != legacySocketPath {
|
||||
// Also check legacy path for backwards compatibility
|
||||
if _, err := os.Stat(legacySocketPath); err == nil {
|
||||
hasSocket = true
|
||||
}
|
||||
}
|
||||
|
||||
if !hasSocket {
|
||||
// No socket, nothing to clean up
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get bd binary path
|
||||
bdBinary, err := getBdBinary()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Run bd daemons killall to clean up stale daemons
|
||||
cmd := newBdCmd(bdBinary, "daemons", "killall")
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("failed to clean up daemons: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -36,9 +36,6 @@ func DatabaseIntegrity(path string) error {
|
|||
return doltCorruptionRecovery(absPath, beadsDir)
|
||||
}
|
||||
|
||||
// Best-effort: stop any running daemon to reduce the chance of DB file locks.
|
||||
_ = Daemon(absPath)
|
||||
|
||||
// Resolve database path (respects metadata.json database override).
|
||||
var dbPath string
|
||||
if cfg, err := configfile.Load(beadsDir); err == nil && cfg != nil && cfg.Database != "" {
|
||||
|
|
@ -74,12 +71,7 @@ func DatabaseIntegrity(path string) error {
|
|||
ts := time.Now().UTC().Format("20060102T150405Z")
|
||||
backupDB := dbPath + "." + ts + ".corrupt.backup.db"
|
||||
if err := moveFile(dbPath, backupDB); err != nil {
|
||||
// Retry once after attempting to kill daemons again (helps on platforms with strict file locks).
|
||||
_ = Daemon(absPath)
|
||||
if err2 := moveFile(dbPath, backupDB); err2 != nil {
|
||||
// Prefer the original error (more likely root cause).
|
||||
return fmt.Errorf("failed to back up database: %w", err)
|
||||
}
|
||||
return fmt.Errorf("failed to back up database: %w", err)
|
||||
}
|
||||
for _, suffix := range []string{"-wal", "-shm", "-journal"} {
|
||||
sidecar := dbPath + suffix
|
||||
|
|
|
|||
|
|
@ -106,16 +106,6 @@ func TestMergeDriver_Validation(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// TestDaemon_Validation tests Daemon validation
|
||||
func TestDaemon_Validation(t *testing.T) {
|
||||
t.Run("no socket - nothing to do", func(t *testing.T) {
|
||||
dir := setupTestWorkspace(t)
|
||||
err := Daemon(dir)
|
||||
if err != nil {
|
||||
t.Errorf("expected no error when no socket exists, got: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestDBJSONLSync_Validation tests DBJSONLSync validation
|
||||
func TestDBJSONLSync_Validation(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@ func TestFixFunctions_RequireBeadsDir(t *testing.T) {
|
|||
}{
|
||||
{"GitHooks", GitHooks},
|
||||
{"MergeDriver", MergeDriver},
|
||||
{"Daemon", Daemon},
|
||||
{"DBJSONLSync", DBJSONLSync},
|
||||
{"DatabaseVersion", DatabaseVersion},
|
||||
{"SchemaCompatibility", SchemaCompatibility},
|
||||
|
|
|
|||
|
|
@ -237,8 +237,6 @@ func applyFixList(path string, fixes []doctorCheck) {
|
|||
err = doctor.FixLastTouchedTracking()
|
||||
case "Git Hooks":
|
||||
err = fix.GitHooks(path)
|
||||
case "Daemon Health":
|
||||
err = fix.Daemon(path)
|
||||
case "DB-JSONL Sync":
|
||||
err = fix.DBJSONLSync(path)
|
||||
case "Sync Divergence":
|
||||
|
|
|
|||
|
|
@ -1,120 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func runBDExecAllowErrorWithEnv(t *testing.T, dir string, extraEnv []string, args ...string) (string, error) {
|
||||
t.Helper()
|
||||
|
||||
cmd := exec.Command(testBD, args...)
|
||||
cmd.Dir = dir
|
||||
|
||||
// Start from a clean-ish environment, then apply overrides.
|
||||
// NOTE: we keep os.Environ() so PATH etc still work for git/dolt.
|
||||
env := append([]string{}, os.Environ()...)
|
||||
env = append(env, extraEnv...)
|
||||
cmd.Env = env
|
||||
|
||||
out, err := cmd.CombinedOutput()
|
||||
return string(out), err
|
||||
}
|
||||
|
||||
func TestDoltDaemonAutostart_NoTimeoutOnCreate(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow integration test in short mode")
|
||||
}
|
||||
if runtime.GOOS == windowsOS {
|
||||
t.Skip("dolt daemon integration test not supported on windows")
|
||||
}
|
||||
|
||||
tmpDir := createTempDirWithCleanup(t)
|
||||
|
||||
// Set up a real git repo so daemon autostart is allowed.
|
||||
if err := runCommandInDir(tmpDir, "git", "init"); err != nil {
|
||||
t.Fatalf("git init failed: %v", err)
|
||||
}
|
||||
_ = runCommandInDir(tmpDir, "git", "config", "user.email", "test@example.com")
|
||||
_ = runCommandInDir(tmpDir, "git", "config", "user.name", "Test User")
|
||||
|
||||
socketPath := filepath.Join(tmpDir, ".beads", "bd.sock")
|
||||
env := []string{
|
||||
"BEADS_TEST_MODE=1",
|
||||
"BEADS_AUTO_START_DAEMON=true",
|
||||
"BEADS_NO_DAEMON=0",
|
||||
"BD_SOCKET=" + socketPath,
|
||||
}
|
||||
|
||||
// Init dolt backend.
|
||||
initOut, initErr := runBDExecAllowErrorWithEnv(t, tmpDir, env, "init", "--backend", "dolt", "--prefix", "test", "--quiet")
|
||||
if initErr != nil {
|
||||
// If dolt backend isn't available in this build, skip rather than fail.
|
||||
// (Some environments may build without dolt support.)
|
||||
lower := strings.ToLower(initOut)
|
||||
if strings.Contains(lower, "dolt") && (strings.Contains(lower, "not supported") || strings.Contains(lower, "not available") || strings.Contains(lower, "unknown")) {
|
||||
t.Skipf("dolt backend not available: %s", initOut)
|
||||
}
|
||||
t.Fatalf("bd init --backend dolt failed: %v\n%s", initErr, initOut)
|
||||
}
|
||||
|
||||
// Always stop daemon on cleanup (best effort) so temp dir can be removed.
|
||||
t.Cleanup(func() {
|
||||
_, _ = runBDExecAllowErrorWithEnv(t, tmpDir, env, "daemon", "stop")
|
||||
// Give the daemon a moment to release any locks/files.
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
})
|
||||
|
||||
// Create should auto-start daemon and should NOT fall back with a timeout warning.
|
||||
createOut, createErr := runBDExecAllowErrorWithEnv(t, tmpDir, env, "create", "dolt daemon autostart test", "--json")
|
||||
if createErr != nil {
|
||||
t.Fatalf("bd create failed: %v\n%s", createErr, createOut)
|
||||
}
|
||||
if strings.Contains(createOut, "Daemon took too long to start") || strings.Contains(createOut, "Running in direct mode") {
|
||||
t.Fatalf("unexpected daemon fallback on dolt create; output:\n%s", createOut)
|
||||
}
|
||||
|
||||
// Verify daemon reports running (via JSON output).
|
||||
statusOut, statusErr := runBDExecAllowErrorWithEnv(t, tmpDir, env, "daemon", "status", "--json")
|
||||
if statusErr != nil {
|
||||
t.Fatalf("bd daemon status failed: %v\n%s", statusErr, statusOut)
|
||||
}
|
||||
|
||||
// We accept either the legacy DaemonStatusResponse shape (daemon_lifecycle.go)
|
||||
// or the newer DaemonStatusReport shape (daemon_status.go), depending on flags/routes.
|
||||
// Here we just assert it isn't obviously "not_running".
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(statusOut), &m); err != nil {
|
||||
// Sometimes status may print warnings before JSON; try from first '{'.
|
||||
if idx := strings.Index(statusOut, "{"); idx >= 0 {
|
||||
if err2 := json.Unmarshal([]byte(statusOut[idx:]), &m); err2 != nil {
|
||||
t.Fatalf("failed to parse daemon status JSON: %v\n%s", err2, statusOut)
|
||||
}
|
||||
} else {
|
||||
t.Fatalf("failed to parse daemon status JSON: %v\n%s", err, statusOut)
|
||||
}
|
||||
}
|
||||
|
||||
// Check "running" boolean (legacy) or "status" string (new).
|
||||
if runningVal, ok := m["running"]; ok {
|
||||
if b, ok := runningVal.(bool); ok && !b {
|
||||
t.Fatalf("expected daemon running=true, got: %s", statusOut)
|
||||
}
|
||||
} else if statusVal, ok := m["status"]; ok {
|
||||
if s, ok := statusVal.(string); ok && (s == "not_running" || s == "stale" || s == "unresponsive") {
|
||||
t.Fatalf("expected daemon to be running/healthy, got status=%q; full: %s", s, statusOut)
|
||||
}
|
||||
} else {
|
||||
// If schema changes again, this will fail loudly and force an update.
|
||||
t.Fatalf("unexpected daemon status JSON shape (missing running/status): %s", statusOut)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,135 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func writeDoltWorkspace(t *testing.T, workspaceDir string) (beadsDir string, doltDir string) {
|
||||
t.Helper()
|
||||
beadsDir = filepath.Join(workspaceDir, ".beads")
|
||||
doltDir = filepath.Join(beadsDir, "dolt")
|
||||
if err := os.MkdirAll(doltDir, 0o700); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
|
||||
metadata := `{
|
||||
"database": "dolt",
|
||||
"backend": "dolt"
|
||||
}`
|
||||
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(metadata), 0o600); err != nil {
|
||||
t.Fatalf("write metadata.json: %v", err)
|
||||
}
|
||||
return beadsDir, doltDir
|
||||
}
|
||||
|
||||
func TestDoltSingleProcess_ShouldAutoStartDaemonFalse(t *testing.T) {
|
||||
oldDBPath := dbPath
|
||||
t.Cleanup(func() { dbPath = oldDBPath })
|
||||
dbPath = ""
|
||||
|
||||
ws := t.TempDir()
|
||||
beadsDir, _ := writeDoltWorkspace(t, ws)
|
||||
|
||||
t.Setenv("BEADS_DIR", beadsDir)
|
||||
// Ensure the finder sees a workspace root (and not the repo running tests).
|
||||
oldWD, _ := os.Getwd()
|
||||
_ = os.Chdir(ws)
|
||||
t.Cleanup(func() { _ = os.Chdir(oldWD) })
|
||||
|
||||
if shouldAutoStartDaemon() {
|
||||
t.Fatalf("expected shouldAutoStartDaemon() to be false for dolt backend")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoltSingleProcess_TryAutoStartDoesNotCreateStartlock(t *testing.T) {
|
||||
oldDBPath := dbPath
|
||||
t.Cleanup(func() { dbPath = oldDBPath })
|
||||
dbPath = ""
|
||||
|
||||
ws := t.TempDir()
|
||||
beadsDir, _ := writeDoltWorkspace(t, ws)
|
||||
t.Setenv("BEADS_DIR", beadsDir)
|
||||
|
||||
socketPath := filepath.Join(ws, "bd.sock")
|
||||
lockPath := socketPath + ".startlock"
|
||||
|
||||
ok := tryAutoStartDaemon(socketPath)
|
||||
if ok {
|
||||
t.Fatalf("expected tryAutoStartDaemon() to return false for dolt backend")
|
||||
}
|
||||
if _, err := os.Stat(lockPath); err == nil {
|
||||
t.Fatalf("expected startlock not to be created for dolt backend: %s", lockPath)
|
||||
} else if !os.IsNotExist(err) {
|
||||
t.Fatalf("stat startlock: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoltSingleProcess_DaemonGuardBlocksStartCommand(t *testing.T) {
|
||||
oldDBPath := dbPath
|
||||
t.Cleanup(func() { dbPath = oldDBPath })
|
||||
dbPath = ""
|
||||
|
||||
ws := t.TempDir()
|
||||
beadsDir, _ := writeDoltWorkspace(t, ws)
|
||||
t.Setenv("BEADS_DIR", beadsDir)
|
||||
|
||||
// Use daemonStartCmd which has the guard attached.
|
||||
// Ensure help and federation flags exist (cobra adds them during execution).
|
||||
cmd := daemonStartCmd
|
||||
cmd.Flags().Bool("help", false, "help")
|
||||
// Note: federation flag is already registered in init()
|
||||
err := guardDaemonStartForDolt(cmd, nil)
|
||||
if err == nil {
|
||||
t.Fatalf("expected daemon guard error for dolt backend without --federation")
|
||||
}
|
||||
// Guardrail wording may evolve; assert a stable intent.
|
||||
if !strings.Contains(err.Error(), "daemon mode is not supported") {
|
||||
t.Fatalf("expected error to mention daemon mode unsupported, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// This test uses a helper subprocess because startDaemon calls os.Exit on failure.
|
||||
func TestDoltSingleProcess_StartDaemonGuardrailExitsNonZero(t *testing.T) {
|
||||
if os.Getenv("BD_TEST_HELPER_STARTDAEMON") == "1" {
|
||||
// Helper mode: set up environment and invoke startDaemon (should os.Exit(1)).
|
||||
ws := os.Getenv("BD_TEST_WORKSPACE")
|
||||
_, doltDir := writeDoltWorkspace(t, ws)
|
||||
// Ensure FindDatabasePath can resolve.
|
||||
_ = os.Chdir(ws)
|
||||
_ = os.Setenv("BEADS_DB", doltDir)
|
||||
dbPath = ""
|
||||
|
||||
pidFile := filepath.Join(ws, ".beads", "daemon.pid")
|
||||
startDaemon(5*time.Second, false, false, false, false, false, "", pidFile, "info", false, false, 0, 0)
|
||||
return
|
||||
}
|
||||
|
||||
ws := t.TempDir()
|
||||
// Pre-create workspace structure so helper can just use it.
|
||||
_, doltDir := writeDoltWorkspace(t, ws)
|
||||
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatalf("os.Executable: %v", err)
|
||||
}
|
||||
|
||||
cmd := exec.Command(exe, "-test.run", "^TestDoltSingleProcess_StartDaemonGuardrailExitsNonZero$", "-test.v")
|
||||
cmd.Env = append(os.Environ(),
|
||||
"BD_TEST_HELPER_STARTDAEMON=1",
|
||||
"BD_TEST_WORKSPACE="+ws,
|
||||
"BEADS_DB="+doltDir,
|
||||
)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err == nil {
|
||||
t.Fatalf("expected non-zero exit; output:\n%s", string(out))
|
||||
}
|
||||
if !strings.Contains(string(out), "daemon mode is not supported") {
|
||||
t.Fatalf("expected output to mention daemon unsupported; got:\n%s", string(out))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -164,23 +164,6 @@ variable.`,
|
|||
beadsDirForInit = beads.FollowRedirect(localBeadsDir)
|
||||
}
|
||||
|
||||
// Stop any running daemon before reinitializing (bd-7h7).
|
||||
// A running daemon caches the old database in memory. If we create a new
|
||||
// database without stopping it, bd commands routed through the daemon
|
||||
// (e.g., bd stats) will show stale counts from the old cached data.
|
||||
pidFile, pidErr := getPIDFilePath()
|
||||
if pidErr == nil {
|
||||
if isRunning, _ := isDaemonRunning(pidFile); isRunning {
|
||||
if !quiet {
|
||||
fmt.Fprintf(os.Stderr, "→ Stopping running daemon before reinitializing...\n")
|
||||
}
|
||||
stopDaemonQuiet(pidFile)
|
||||
if !quiet {
|
||||
fmt.Fprintf(os.Stderr, "✓ Daemon stopped\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine storage path.
|
||||
//
|
||||
// IMPORTANT: In Dolt mode, we must NOT create a SQLite database file.
|
||||
|
|
|
|||
276
cmd/bd/main.go
276
cmd/bd/main.go
|
|
@ -23,7 +23,6 @@ import (
|
|||
"github.com/steveyegge/beads/internal/debug"
|
||||
"github.com/steveyegge/beads/internal/hooks"
|
||||
"github.com/steveyegge/beads/internal/molecules"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/factory"
|
||||
"github.com/steveyegge/beads/internal/storage/memory"
|
||||
|
|
@ -31,15 +30,10 @@ import (
|
|||
)
|
||||
|
||||
var (
|
||||
dbPath string
|
||||
actor string
|
||||
store storage.Storage
|
||||
jsonOutput bool
|
||||
daemonStatus DaemonStatus // Tracks daemon connection state for current command
|
||||
|
||||
// Daemon mode
|
||||
daemonClient *rpc.Client // RPC client when daemon is running
|
||||
noDaemon bool // Force direct mode (no daemon)
|
||||
dbPath string
|
||||
actor string
|
||||
store storage.Storage
|
||||
jsonOutput bool
|
||||
|
||||
// Signal-aware context for graceful cancellation
|
||||
rootCtx context.Context
|
||||
|
|
@ -206,10 +200,9 @@ func init() {
|
|||
rootCmd.PersistentFlags().StringVar(&dbPath, "db", "", "Database path (default: auto-discover .beads/*.db)")
|
||||
rootCmd.PersistentFlags().StringVar(&actor, "actor", "", "Actor name for audit trail (default: $BD_ACTOR, git user.name, $USER)")
|
||||
rootCmd.PersistentFlags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
|
||||
rootCmd.PersistentFlags().BoolVar(&noDaemon, "no-daemon", false, "Force direct storage mode, bypass daemon if running")
|
||||
rootCmd.PersistentFlags().BoolVar(&noAutoFlush, "no-auto-flush", false, "Disable automatic JSONL sync after CRUD operations")
|
||||
rootCmd.PersistentFlags().BoolVar(&noAutoImport, "no-auto-import", false, "Disable automatic JSONL import when newer than DB")
|
||||
rootCmd.PersistentFlags().BoolVar(&sandboxMode, "sandbox", false, "Sandbox mode: disables daemon and auto-sync")
|
||||
rootCmd.PersistentFlags().BoolVar(&sandboxMode, "sandbox", false, "Sandbox mode: disables auto-sync")
|
||||
rootCmd.PersistentFlags().BoolVar(&allowStale, "allow-stale", false, "Allow operations on potentially stale data (skip staleness check)")
|
||||
rootCmd.PersistentFlags().BoolVar(&noDb, "no-db", false, "Use no-db mode: load from JSONL, no SQLite")
|
||||
rootCmd.PersistentFlags().BoolVar(&readonlyMode, "readonly", false, "Read-only mode: block write operations (for worker sandboxes)")
|
||||
|
|
@ -294,14 +287,6 @@ var rootCmd = &cobra.Command{
|
|||
WasSet bool
|
||||
}{jsonOutput, true}
|
||||
}
|
||||
if !cmd.Flags().Changed("no-daemon") {
|
||||
noDaemon = config.GetBool("no-daemon")
|
||||
} else {
|
||||
flagOverrides["no-daemon"] = struct {
|
||||
Value interface{}
|
||||
WasSet bool
|
||||
}{noDaemon, true}
|
||||
}
|
||||
if !cmd.Flags().Changed("no-auto-flush") {
|
||||
noAutoFlush = config.GetBool("no-auto-flush")
|
||||
} else {
|
||||
|
|
@ -385,7 +370,6 @@ var rootCmd = &cobra.Command{
|
|||
// signalOrchestratorActivity) to avoid spawning git subprocesses for simple commands
|
||||
// like "bd version" that don't need database access.
|
||||
noDbCommands := []string{
|
||||
cmdDaemon,
|
||||
"__complete", // Cobra's internal completion command (shell completions work without db)
|
||||
"__completeNoDesc", // Cobra's completion without descriptions (used by fish)
|
||||
"bash",
|
||||
|
|
@ -442,11 +426,7 @@ var rootCmd = &cobra.Command{
|
|||
}
|
||||
|
||||
// Performance profiling setup
|
||||
// When --profile is enabled, force direct mode to capture actual database operations
|
||||
// rather than just RPC serialization/network overhead. This gives accurate profiles
|
||||
// of the storage layer, query performance, and business logic.
|
||||
if profileEnabled {
|
||||
noDaemon = true
|
||||
timestamp := time.Now().Format("20060102-150405")
|
||||
if f, _ := os.Create(fmt.Sprintf("bd-profile-%s-%s.prof", cmd.Name(), timestamp)); f != nil {
|
||||
profileFile = f
|
||||
|
|
@ -459,8 +439,7 @@ var rootCmd = &cobra.Command{
|
|||
}
|
||||
|
||||
// Auto-detect sandboxed environment (Phase 2 for GH #353)
|
||||
// Only auto-enable if user hasn't explicitly set --sandbox or --no-daemon
|
||||
if !cmd.Flags().Changed("sandbox") && !cmd.Flags().Changed("no-daemon") {
|
||||
if !cmd.Flags().Changed("sandbox") {
|
||||
if isSandboxed() {
|
||||
sandboxMode = true
|
||||
fmt.Fprintf(os.Stderr, "ℹ️ Sandbox detected, using direct mode\n")
|
||||
|
|
@ -469,7 +448,6 @@ var rootCmd = &cobra.Command{
|
|||
|
||||
// If sandbox mode is set, enable all sandbox flags
|
||||
if sandboxMode {
|
||||
noDaemon = true
|
||||
noAutoFlush = true
|
||||
noAutoImport = true
|
||||
// Use shorter lock timeout in sandbox mode unless explicitly set
|
||||
|
|
@ -478,12 +456,6 @@ var rootCmd = &cobra.Command{
|
|||
}
|
||||
}
|
||||
|
||||
// Force direct mode for human-only interactive commands
|
||||
// edit: can take minutes in $EDITOR, daemon connection times out (GH #227)
|
||||
if cmd.Name() == "edit" {
|
||||
noDaemon = true
|
||||
}
|
||||
|
||||
// Set auto-flush based on flag (invert no-auto-flush)
|
||||
autoFlushEnabled = !noAutoFlush
|
||||
|
||||
|
|
@ -500,7 +472,7 @@ var rootCmd = &cobra.Command{
|
|||
// Set actor for audit trail
|
||||
actor = getActorWithGit()
|
||||
|
||||
// Skip daemon and SQLite initialization - we're in memory mode
|
||||
// Skip SQLite initialization - we're in memory mode
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -549,7 +521,7 @@ var rootCmd = &cobra.Command{
|
|||
}
|
||||
|
||||
// Allow read-only commands to auto-bootstrap from JSONL (GH#b09)
|
||||
// This enables `bd --no-daemon show` after cold-start when DB is missing.
|
||||
// This enables `bd show` after cold-start when DB is missing.
|
||||
// IMPORTANT: Only auto-bootstrap for SQLite backend. If metadata.json says
|
||||
// the backend is Dolt, we must NOT silently create a SQLite database —
|
||||
// that causes Classic contamination. Error out instead so the user can
|
||||
|
|
@ -598,8 +570,7 @@ var rootCmd = &cobra.Command{
|
|||
os.Exit(1)
|
||||
}
|
||||
// For import/setup commands, set default database path
|
||||
// Invariant: dbPath must always be absolute for filepath.Rel() compatibility
|
||||
// in daemon sync-branch code path. Use CanonicalizePath for OS-agnostic
|
||||
// Invariant: dbPath must always be absolute. Use CanonicalizePath for OS-agnostic
|
||||
// handling (symlinks, case normalization on macOS).
|
||||
//
|
||||
// IMPORTANT: Use FindBeadsDir() to get the correct .beads directory,
|
||||
|
|
@ -621,224 +592,6 @@ var rootCmd = &cobra.Command{
|
|||
// Best-effort tracking - failures are silent
|
||||
trackBdVersion()
|
||||
|
||||
// Initialize daemon status
|
||||
socketPath := getSocketPath()
|
||||
daemonStatus = DaemonStatus{
|
||||
Mode: "direct",
|
||||
Connected: false,
|
||||
Degraded: true,
|
||||
SocketPath: socketPath,
|
||||
AutoStartEnabled: shouldAutoStartDaemon(),
|
||||
FallbackReason: FallbackNone,
|
||||
}
|
||||
|
||||
// Doctor should always run in direct mode. It's specifically used to diagnose and
|
||||
// repair daemon/DB issues, so attempting to connect to (or auto-start) a daemon
|
||||
// can add noise and timeouts.
|
||||
if cmd.Name() == "doctor" {
|
||||
noDaemon = true
|
||||
}
|
||||
|
||||
// Restore should always run in direct mode. It performs git checkouts to read
|
||||
// historical issue data, which could conflict with daemon operations.
|
||||
if cmd.Name() == "restore" {
|
||||
noDaemon = true
|
||||
}
|
||||
|
||||
// Wisp operations auto-bypass daemon
|
||||
// Wisps are ephemeral (Ephemeral=true) and never exported to JSONL,
|
||||
// so daemon can't help anyway. This reduces friction in wisp workflows.
|
||||
if isWispOperation(cmd, args) {
|
||||
noDaemon = true
|
||||
daemonStatus.FallbackReason = FallbackWispOperation
|
||||
debug.Logf("wisp operation detected, using direct mode")
|
||||
}
|
||||
|
||||
// Embedded Dolt is single-process-only; never use daemon/RPC.
|
||||
// (Dolt server mode supports multi-process and won't trigger this.)
|
||||
// This must be checked after dbPath is resolved.
|
||||
if !noDaemon && singleProcessOnlyBackend() {
|
||||
noDaemon = true
|
||||
daemonStatus.AutoStartEnabled = false
|
||||
daemonStatus.FallbackReason = FallbackSingleProcessOnly
|
||||
daemonStatus.Detail = "backend is single-process-only (embedded dolt): daemon mode disabled; using direct mode"
|
||||
debug.Logf("single-process backend detected, using direct mode")
|
||||
}
|
||||
|
||||
// Try to connect to daemon first (unless --no-daemon flag is set or worktree safety check fails)
|
||||
if noDaemon {
|
||||
// Only set FallbackFlagNoDaemon if not already set by auto-bypass logic
|
||||
if daemonStatus.FallbackReason == FallbackNone {
|
||||
daemonStatus.FallbackReason = FallbackFlagNoDaemon
|
||||
debug.Logf("--no-daemon flag set, using direct mode")
|
||||
}
|
||||
} else if shouldDisableDaemonForWorktree() {
|
||||
// In a git worktree without sync-branch configured - daemon is unsafe
|
||||
// because all worktrees share the same .beads directory and the daemon
|
||||
// would commit to whatever branch its working directory has checked out.
|
||||
daemonStatus.FallbackReason = FallbackWorktreeSafety
|
||||
debug.Logf("git worktree detected without sync-branch, using direct mode for safety")
|
||||
} else {
|
||||
// Attempt daemon connection
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err == nil && client != nil {
|
||||
// Set expected database path for validation
|
||||
if dbPath != "" {
|
||||
absDBPath, _ := filepath.Abs(dbPath)
|
||||
client.SetDatabasePath(absDBPath)
|
||||
}
|
||||
|
||||
// Perform health check
|
||||
health, healthErr := client.Health()
|
||||
if healthErr == nil && health.Status == statusHealthy {
|
||||
// Check version compatibility
|
||||
if !health.Compatible {
|
||||
debug.Logf("daemon version mismatch (daemon: %s, client: %s), restarting daemon",
|
||||
health.Version, Version)
|
||||
_ = client.Close()
|
||||
|
||||
// Kill old daemon and restart with new version
|
||||
if restartDaemonForVersionMismatch() {
|
||||
// Retry connection after restart
|
||||
client, err = rpc.TryConnect(socketPath)
|
||||
if err == nil && client != nil {
|
||||
if dbPath != "" {
|
||||
absDBPath, _ := filepath.Abs(dbPath)
|
||||
client.SetDatabasePath(absDBPath)
|
||||
}
|
||||
health, healthErr = client.Health()
|
||||
if healthErr == nil && health.Status == statusHealthy {
|
||||
client.SetActor(actor)
|
||||
daemonClient = client
|
||||
daemonStatus.Mode = cmdDaemon
|
||||
daemonStatus.Connected = true
|
||||
daemonStatus.Degraded = false
|
||||
daemonStatus.Health = health.Status
|
||||
debug.Logf("connected to restarted daemon (version: %s)", health.Version)
|
||||
warnWorktreeDaemon(dbPath)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
// If restart failed, fall through to direct mode
|
||||
daemonStatus.FallbackReason = FallbackHealthFailed
|
||||
daemonStatus.Detail = fmt.Sprintf("version mismatch (daemon: %s, client: %s) and restart failed",
|
||||
health.Version, Version)
|
||||
} else {
|
||||
// Daemon is healthy and compatible - use it
|
||||
client.SetActor(actor)
|
||||
daemonClient = client
|
||||
daemonStatus.Mode = cmdDaemon
|
||||
daemonStatus.Connected = true
|
||||
daemonStatus.Degraded = false
|
||||
daemonStatus.Health = health.Status
|
||||
debug.Logf("connected to daemon at %s (health: %s)", socketPath, health.Status)
|
||||
// Warn if using daemon with git worktrees
|
||||
warnWorktreeDaemon(dbPath)
|
||||
return // Skip direct storage initialization
|
||||
}
|
||||
} else {
|
||||
// Health check failed or daemon unhealthy
|
||||
_ = client.Close()
|
||||
daemonStatus.FallbackReason = FallbackHealthFailed
|
||||
if healthErr != nil {
|
||||
daemonStatus.Detail = healthErr.Error()
|
||||
debug.Logf("daemon health check failed: %v", healthErr)
|
||||
} else {
|
||||
daemonStatus.Health = health.Status
|
||||
daemonStatus.Detail = health.Error
|
||||
debug.Logf("daemon unhealthy (status=%s): %s", health.Status, health.Error)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Connection failed
|
||||
daemonStatus.FallbackReason = FallbackConnectFailed
|
||||
if err != nil {
|
||||
daemonStatus.Detail = err.Error()
|
||||
debug.Logf("daemon connect failed at %s: %v", socketPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Daemon not running or unhealthy - try auto-start if enabled
|
||||
if daemonStatus.AutoStartEnabled {
|
||||
daemonStatus.AutoStartAttempted = true
|
||||
debug.Logf("attempting to auto-start daemon")
|
||||
startTime := time.Now()
|
||||
if tryAutoStartDaemon(socketPath) {
|
||||
// Retry connection after auto-start
|
||||
client, err := rpc.TryConnect(socketPath)
|
||||
if err == nil && client != nil {
|
||||
// Set expected database path for validation
|
||||
if dbPath != "" {
|
||||
absDBPath, _ := filepath.Abs(dbPath)
|
||||
client.SetDatabasePath(absDBPath)
|
||||
}
|
||||
|
||||
// Check health of auto-started daemon
|
||||
health, healthErr := client.Health()
|
||||
if healthErr == nil && health.Status == statusHealthy {
|
||||
client.SetActor(actor)
|
||||
daemonClient = client
|
||||
daemonStatus.Mode = cmdDaemon
|
||||
daemonStatus.Connected = true
|
||||
daemonStatus.Degraded = false
|
||||
daemonStatus.AutoStartSucceeded = true
|
||||
daemonStatus.Health = health.Status
|
||||
daemonStatus.FallbackReason = FallbackNone
|
||||
elapsed := time.Since(startTime).Milliseconds()
|
||||
debug.Logf("auto-start succeeded; connected at %s in %dms", socketPath, elapsed)
|
||||
// Warn if using daemon with git worktrees
|
||||
warnWorktreeDaemon(dbPath)
|
||||
return // Skip direct storage initialization
|
||||
} else {
|
||||
// Auto-started daemon is unhealthy
|
||||
_ = client.Close()
|
||||
daemonStatus.FallbackReason = FallbackHealthFailed
|
||||
if healthErr != nil {
|
||||
daemonStatus.Detail = healthErr.Error()
|
||||
} else {
|
||||
daemonStatus.Health = health.Status
|
||||
daemonStatus.Detail = health.Error
|
||||
}
|
||||
debug.Logf("auto-started daemon is unhealthy; falling back to direct mode")
|
||||
}
|
||||
} else {
|
||||
// Auto-start completed but connection still failed
|
||||
daemonStatus.FallbackReason = FallbackAutoStartFailed
|
||||
if err != nil {
|
||||
daemonStatus.Detail = err.Error()
|
||||
}
|
||||
// Check for daemon-error file to provide better error message
|
||||
if beadsDir := filepath.Dir(socketPath); beadsDir != "" {
|
||||
errFile := filepath.Join(beadsDir, "daemon-error")
|
||||
// nolint:gosec // G304: errFile is derived from secure beads directory
|
||||
if errMsg, readErr := os.ReadFile(errFile); readErr == nil && len(errMsg) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "\n%s\n", string(errMsg))
|
||||
daemonStatus.Detail = string(errMsg)
|
||||
}
|
||||
}
|
||||
debug.Logf("auto-start did not yield a running daemon; falling back to direct mode")
|
||||
}
|
||||
} else {
|
||||
// Auto-start itself failed
|
||||
daemonStatus.FallbackReason = FallbackAutoStartFailed
|
||||
debug.Logf("auto-start failed; falling back to direct mode")
|
||||
}
|
||||
} else {
|
||||
// Auto-start disabled - preserve the actual failure reason
|
||||
// Don't override connect_failed or health_failed with auto_start_disabled
|
||||
// This preserves important diagnostic info (daemon crashed vs not running)
|
||||
debug.Logf("auto-start disabled by BEADS_AUTO_START_DAEMON")
|
||||
}
|
||||
|
||||
// Emit BD_VERBOSE warning if falling back to direct mode
|
||||
if os.Getenv("BD_VERBOSE") != "" {
|
||||
emitVerboseWarning()
|
||||
}
|
||||
|
||||
debug.Logf("using direct mode (reason: %s)", daemonStatus.FallbackReason)
|
||||
}
|
||||
|
||||
// Check if this is a read-only command (GH#804)
|
||||
// Read-only commands open SQLite in read-only mode to avoid modifying
|
||||
// the database file (which breaks file watchers).
|
||||
|
|
@ -846,13 +599,11 @@ var rootCmd = &cobra.Command{
|
|||
|
||||
// Auto-migrate database on version bump
|
||||
// Skip for read-only commands - they can't write anyway
|
||||
// Do this AFTER daemon check but BEFORE opening database for main operation
|
||||
// This ensures: 1) no daemon has DB open, 2) we don't open DB twice
|
||||
if !useReadOnly {
|
||||
autoMigrateOnVersionBump(filepath.Dir(dbPath))
|
||||
}
|
||||
|
||||
// Fall back to direct storage access
|
||||
// Initialize direct storage access
|
||||
var err error
|
||||
var needsBootstrap bool // Track if DB needs initial import (GH#b09)
|
||||
beadsDir := filepath.Dir(dbPath)
|
||||
|
|
@ -1026,13 +777,6 @@ var rootCmd = &cobra.Command{
|
|||
return
|
||||
}
|
||||
|
||||
// Close daemon client if we're using it
|
||||
if daemonClient != nil {
|
||||
_ = daemonClient.Close()
|
||||
return
|
||||
}
|
||||
|
||||
// Otherwise, handle direct mode cleanup
|
||||
// Shutdown flush manager (performs final flush if needed)
|
||||
// Skip if sync command already handled export and restore (sync.branch mode)
|
||||
if flushManager != nil && !skipFinalFlush {
|
||||
|
|
|
|||
|
|
@ -8,35 +8,8 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
// DaemonStatus captures daemon connection state for the current command
|
||||
type DaemonStatus struct {
|
||||
Mode string `json:"mode"` // "daemon" or "direct"
|
||||
Connected bool `json:"connected"`
|
||||
Degraded bool `json:"degraded"`
|
||||
SocketPath string `json:"socket_path,omitempty"`
|
||||
AutoStartEnabled bool `json:"auto_start_enabled"`
|
||||
AutoStartAttempted bool `json:"auto_start_attempted"`
|
||||
AutoStartSucceeded bool `json:"auto_start_succeeded"`
|
||||
FallbackReason string `json:"fallback_reason,omitempty"` // "none","flag_no_daemon","connect_failed","health_failed","auto_start_disabled","auto_start_failed"
|
||||
Detail string `json:"detail,omitempty"` // short diagnostic
|
||||
Health string `json:"health,omitempty"` // "healthy","degraded","unhealthy"
|
||||
}
|
||||
|
||||
// Fallback reason constants
|
||||
const (
|
||||
FallbackNone = "none"
|
||||
FallbackFlagNoDaemon = "flag_no_daemon"
|
||||
FallbackConnectFailed = "connect_failed"
|
||||
FallbackHealthFailed = "health_failed"
|
||||
FallbackWorktreeSafety = "worktree_safety"
|
||||
FallbackSingleProcessOnly = "single_process_only"
|
||||
cmdDaemon = "daemon"
|
||||
cmdImport = "import"
|
||||
statusHealthy = "healthy"
|
||||
FallbackAutoStartDisabled = "auto_start_disabled"
|
||||
FallbackAutoStartFailed = "auto_start_failed"
|
||||
FallbackDaemonUnsupported = "daemon_unsupported"
|
||||
FallbackWispOperation = "wisp_operation"
|
||||
cmdImport = "import"
|
||||
)
|
||||
|
||||
// Command group IDs for help organization
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import (
|
|||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
|
|
@ -94,18 +93,6 @@ type resetItem struct {
|
|||
func collectResetItems(gitCommonDir, beadsDir string) []resetItem {
|
||||
var items []resetItem
|
||||
|
||||
// Check for running daemon
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
if _, err := os.Stat(pidFile); err == nil {
|
||||
if isRunning, pid := isDaemonRunning(pidFile); isRunning {
|
||||
items = append(items, resetItem{
|
||||
Type: "daemon",
|
||||
Path: pidFile,
|
||||
Description: fmt.Sprintf("Stop running daemon (PID %d)", pid),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Check for git hooks (hooks are in common git dir, shared across worktrees)
|
||||
hookNames := []string{"pre-commit", "post-merge", "pre-push", "post-checkout"}
|
||||
hooksDir := filepath.Join(gitCommonDir, "hooks")
|
||||
|
|
@ -231,13 +218,6 @@ func performReset(items []resetItem, _, beadsDir string) {
|
|||
|
||||
for _, item := range items {
|
||||
switch item.Type {
|
||||
case "daemon":
|
||||
pidFile := filepath.Join(beadsDir, "daemon.pid")
|
||||
stopDaemonQuiet(pidFile)
|
||||
if !jsonOutput {
|
||||
fmt.Printf("%s Stopped daemon\n", ui.RenderPass("✓"))
|
||||
}
|
||||
|
||||
case "hook":
|
||||
if err := os.Remove(item.Path); err != nil {
|
||||
errors = append(errors, fmt.Sprintf("failed to remove hook %s: %v", item.Path, err))
|
||||
|
|
@ -308,32 +288,6 @@ func performReset(items []resetItem, _, beadsDir string) {
|
|||
}
|
||||
}
|
||||
|
||||
// stopDaemonQuiet stops the daemon without printing status messages
|
||||
func stopDaemonQuiet(pidFile string) {
|
||||
isRunning, pid := isDaemonRunning(pidFile)
|
||||
if !isRunning {
|
||||
return
|
||||
}
|
||||
|
||||
process, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_ = sendStopSignal(process) // Best-effort graceful stop
|
||||
|
||||
// Wait for daemon to stop gracefully
|
||||
for i := 0; i < daemonShutdownAttempts; i++ {
|
||||
time.Sleep(daemonShutdownPollInterval)
|
||||
if isRunning, _ := isDaemonRunning(pidFile); !isRunning {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Force kill if still running
|
||||
_ = process.Kill() // Best-effort force kill, process may have already exited
|
||||
}
|
||||
|
||||
func removeGitattributesEntry() error {
|
||||
// #nosec G304 -- fixed path
|
||||
content, err := os.ReadFile(".gitattributes")
|
||||
|
|
|
|||
300
cmd/bd/sync_helpers.go
Normal file
300
cmd/bd/sync_helpers.go
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// getRepoKeyForPath extracts the stable repo identifier from a JSONL path.
|
||||
// For single-repo mode, returns empty string (no suffix needed).
|
||||
// For multi-repo mode, extracts the repo path (e.g., ".", "../frontend").
|
||||
func getRepoKeyForPath(jsonlPath string) string {
|
||||
multiRepo := config.GetMultiRepoConfig()
|
||||
if multiRepo == nil {
|
||||
return "" // Single-repo mode
|
||||
}
|
||||
|
||||
const suffix = "/.beads/issues.jsonl"
|
||||
if strings.HasSuffix(jsonlPath, suffix) {
|
||||
repoPath := strings.TrimSuffix(jsonlPath, suffix)
|
||||
|
||||
primaryPath := multiRepo.Primary
|
||||
if primaryPath == "" {
|
||||
primaryPath = "."
|
||||
}
|
||||
if repoPath == primaryPath {
|
||||
return primaryPath
|
||||
}
|
||||
|
||||
for _, additional := range multiRepo.Additional {
|
||||
if repoPath == additional {
|
||||
return additional
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// sanitizeMetadataKey replaces characters that conflict with metadata key format.
|
||||
func sanitizeMetadataKey(key string) string {
|
||||
return strings.ReplaceAll(key, ":", "_")
|
||||
}
|
||||
|
||||
// getDebounceDuration returns the configured flush debounce duration.
|
||||
func getDebounceDuration() time.Duration {
|
||||
duration := config.GetDuration("flush-debounce")
|
||||
if duration == 0 {
|
||||
return 5 * time.Second
|
||||
}
|
||||
return duration
|
||||
}
|
||||
|
||||
// exportToJSONLWithStore exports issues to JSONL using the provided store.
|
||||
// If multi-repo mode is configured, routes issues to their respective JSONL files.
|
||||
// Otherwise, exports to a single JSONL file.
|
||||
func exportToJSONLWithStore(ctx context.Context, store storage.Storage, jsonlPath string) error {
|
||||
// Try multi-repo export first
|
||||
if mrStore, ok := store.(storage.MultiRepoStorage); ok {
|
||||
results, err := mrStore.ExportToMultiRepo(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("multi-repo export failed: %w", err)
|
||||
}
|
||||
if results != nil {
|
||||
// Multi-repo mode active - export succeeded
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Single-repo mode - use existing logic
|
||||
// Get all issues including tombstones for sync propagation
|
||||
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{IncludeTombstones: true})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get issues: %w", err)
|
||||
}
|
||||
|
||||
// Safety check: prevent exporting empty database over non-empty JSONL
|
||||
if len(issues) == 0 {
|
||||
existingCount, err := countIssuesInJSONL(jsonlPath)
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
return fmt.Errorf("warning: failed to read existing JSONL: %w", err)
|
||||
}
|
||||
} else if existingCount > 0 {
|
||||
return fmt.Errorf("refusing to export empty database over non-empty JSONL file (database: 0 issues, JSONL: %d issues). This would result in data loss", existingCount)
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by ID for consistent output
|
||||
slices.SortFunc(issues, func(a, b *types.Issue) int {
|
||||
return cmp.Compare(a.ID, b.ID)
|
||||
})
|
||||
|
||||
// Populate dependencies for all issues
|
||||
allDeps, err := store.GetAllDependencyRecords(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get dependencies: %w", err)
|
||||
}
|
||||
for _, issue := range issues {
|
||||
issue.Dependencies = allDeps[issue.ID]
|
||||
}
|
||||
|
||||
// Populate labels for all issues
|
||||
for _, issue := range issues {
|
||||
labels, err := store.GetLabels(ctx, issue.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get labels for %s: %w", issue.ID, err)
|
||||
}
|
||||
issue.Labels = labels
|
||||
}
|
||||
|
||||
// Populate comments for all issues
|
||||
for _, issue := range issues {
|
||||
comments, err := store.GetIssueComments(ctx, issue.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get comments for %s: %w", issue.ID, err)
|
||||
}
|
||||
issue.Comments = comments
|
||||
}
|
||||
|
||||
// Create temp file for atomic write
|
||||
dir := filepath.Dir(jsonlPath)
|
||||
base := filepath.Base(jsonlPath)
|
||||
tempFile, err := os.CreateTemp(dir, base+".tmp.*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temp file: %w", err)
|
||||
}
|
||||
tempPath := tempFile.Name()
|
||||
|
||||
// Use defer pattern for proper cleanup
|
||||
var writeErr error
|
||||
defer func() {
|
||||
_ = tempFile.Close()
|
||||
if writeErr != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
}
|
||||
}()
|
||||
|
||||
// Write JSONL
|
||||
for _, issue := range issues {
|
||||
data, marshalErr := json.Marshal(issue)
|
||||
if marshalErr != nil {
|
||||
writeErr = fmt.Errorf("failed to marshal issue %s: %w", issue.ID, marshalErr)
|
||||
return writeErr
|
||||
}
|
||||
if _, writeErr = tempFile.Write(data); writeErr != nil {
|
||||
writeErr = fmt.Errorf("failed to write issue %s: %w", issue.ID, writeErr)
|
||||
return writeErr
|
||||
}
|
||||
if _, writeErr = tempFile.WriteString("\n"); writeErr != nil {
|
||||
writeErr = fmt.Errorf("failed to write newline: %w", writeErr)
|
||||
return writeErr
|
||||
}
|
||||
}
|
||||
|
||||
// Close before rename
|
||||
if writeErr = tempFile.Close(); writeErr != nil {
|
||||
writeErr = fmt.Errorf("failed to close temp file: %w", writeErr)
|
||||
return writeErr
|
||||
}
|
||||
|
||||
// Atomic rename
|
||||
if writeErr = os.Rename(tempPath, jsonlPath); writeErr != nil {
|
||||
writeErr = fmt.Errorf("failed to rename temp file: %w", writeErr)
|
||||
return writeErr
|
||||
}
|
||||
|
||||
// Update export_hashes for all exported issues
|
||||
for _, issue := range issues {
|
||||
if issue.ContentHash != "" {
|
||||
if err := store.SetExportHash(ctx, issue.ID, issue.ContentHash); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to set export hash for %s: %v\n", issue.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// importToJSONLWithStore imports issues from JSONL using the provided store.
|
||||
func importToJSONLWithStore(ctx context.Context, store storage.Storage, jsonlPath string) error {
|
||||
// Try multi-repo import first
|
||||
if mrStore, ok := store.(storage.MultiRepoStorage); ok {
|
||||
results, err := mrStore.HydrateFromMultiRepo(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("multi-repo import failed: %w", err)
|
||||
}
|
||||
if results != nil {
|
||||
// Multi-repo mode active - import succeeded
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Single-repo mode - use existing logic
|
||||
file, err := os.Open(jsonlPath) // #nosec G304 - controlled path from config
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open JSONL: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var issues []*types.Issue
|
||||
scanner := bufio.NewScanner(file)
|
||||
const maxScannerBuffer = 1024 * 1024 // 1MB
|
||||
scanner.Buffer(make([]byte, 0, maxScannerBuffer), maxScannerBuffer)
|
||||
lineNum := 0
|
||||
|
||||
for scanner.Scan() {
|
||||
lineNum++
|
||||
line := scanner.Text()
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var issue types.Issue
|
||||
if err := json.Unmarshal([]byte(line), &issue); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to parse JSONL line %d: %v\n", lineNum, err)
|
||||
continue
|
||||
}
|
||||
issue.SetDefaults()
|
||||
|
||||
// Migrate old JSONL format: auto-correct deleted status to tombstone
|
||||
if issue.Status == types.Status("deleted") && issue.DeletedAt != nil {
|
||||
issue.Status = types.StatusTombstone
|
||||
}
|
||||
|
||||
// Fix: Any non-tombstone issue with deleted_at set is malformed
|
||||
if issue.Status != types.StatusTombstone && issue.DeletedAt != nil {
|
||||
issue.Status = types.StatusTombstone
|
||||
}
|
||||
|
||||
if issue.Status == types.StatusClosed && issue.ClosedAt == nil {
|
||||
now := time.Now()
|
||||
issue.ClosedAt = &now
|
||||
}
|
||||
|
||||
// Ensure tombstones have deleted_at set
|
||||
if issue.Status == types.StatusTombstone && issue.DeletedAt == nil {
|
||||
now := time.Now()
|
||||
issue.DeletedAt = &now
|
||||
}
|
||||
|
||||
issues = append(issues, &issue)
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return fmt.Errorf("failed to read JSONL: %w", err)
|
||||
}
|
||||
|
||||
opts := ImportOptions{
|
||||
DryRun: false,
|
||||
SkipUpdate: false,
|
||||
Strict: false,
|
||||
SkipPrefixValidation: true,
|
||||
}
|
||||
|
||||
_, err = importIssuesCore(ctx, "", store, issues, opts)
|
||||
return err
|
||||
}
|
||||
|
||||
// updateExportMetadata updates jsonl_content_hash and related metadata after a successful export.
|
||||
func updateExportMetadata(ctx context.Context, store storage.Storage, jsonlPath string, log *slog.Logger, keySuffix string) {
|
||||
if keySuffix != "" {
|
||||
keySuffix = sanitizeMetadataKey(keySuffix)
|
||||
}
|
||||
|
||||
currentHash, err := computeJSONLHash(jsonlPath)
|
||||
if err != nil {
|
||||
log.Info("Warning: failed to compute JSONL hash for metadata update", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
hashKey := "jsonl_content_hash"
|
||||
timeKey := "last_import_time"
|
||||
if keySuffix != "" {
|
||||
hashKey += ":" + keySuffix
|
||||
timeKey += ":" + keySuffix
|
||||
}
|
||||
|
||||
if err := store.SetMetadata(ctx, hashKey, currentHash); err != nil {
|
||||
log.Info("Warning: failed to update metadata", "key", hashKey, "error", err)
|
||||
log.Info("Next export may require running 'bd import' first")
|
||||
}
|
||||
|
||||
exportTime := time.Now().Format(time.RFC3339Nano)
|
||||
if err := store.SetMetadata(ctx, timeKey, exportTime); err != nil {
|
||||
log.Info("Warning: failed to update metadata", "key", timeKey, "error", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -8,7 +8,7 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
// SyncState tracks daemon sync health for backoff and user hints.
|
||||
// SyncState tracks sync health for backoff and user hints.
|
||||
// Stored in .beads/sync-state.json (gitignored, local-only).
|
||||
type SyncState struct {
|
||||
LastFailure time.Time `json:"last_failure,omitempty"`
|
||||
|
|
@ -112,7 +112,6 @@ func ClearSyncState(beadsDir string) error {
|
|||
|
||||
// RecordSyncFailure updates the sync state after a failure.
|
||||
// Returns the duration until next retry.
|
||||
// Thread-safe: holds lock for entire load-modify-save operation to prevent races.
|
||||
func RecordSyncFailure(beadsDir string, reason string) time.Duration {
|
||||
syncStateMu.Lock()
|
||||
defer syncStateMu.Unlock()
|
||||
|
|
@ -157,20 +156,16 @@ func ShouldSkipSync(beadsDir string) bool {
|
|||
|
||||
// ResetBackoffOnDaemonStart resets backoff counters when daemon starts,
|
||||
// but preserves NeedsManualSync flag so hints still show.
|
||||
// This allows a fresh start while keeping user informed of conflicts.
|
||||
// Thread-safe: holds lock for entire load-modify-save operation to prevent races.
|
||||
func ResetBackoffOnDaemonStart(beadsDir string) {
|
||||
syncStateMu.Lock()
|
||||
defer syncStateMu.Unlock()
|
||||
|
||||
state := loadSyncStateUnlocked(beadsDir)
|
||||
|
||||
// Nothing to reset
|
||||
if state.FailureCount == 0 && !state.NeedsManualSync {
|
||||
return
|
||||
}
|
||||
|
||||
// Reset backoff but preserve NeedsManualSync
|
||||
needsManual := state.NeedsManualSync
|
||||
reason := state.FailureReason
|
||||
|
||||
|
|
@ -1,9 +1,11 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
|
@ -250,3 +252,30 @@ func runCommandInDirWithOutput(dir string, name string, args ...string) (string,
|
|||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
|
||||
// captureStderr captures stderr output from fn and returns it as a string.
|
||||
func captureStderr(t *testing.T, fn func()) string {
|
||||
t.Helper()
|
||||
|
||||
old := os.Stderr
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatalf("os.Pipe: %v", err)
|
||||
}
|
||||
os.Stderr = w
|
||||
|
||||
var buf bytes.Buffer
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_, _ = io.Copy(&buf, r)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
fn()
|
||||
_ = w.Close()
|
||||
os.Stderr = old
|
||||
<-done
|
||||
_ = r.Close()
|
||||
|
||||
return buf.String()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,12 +4,10 @@ import (
|
|||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
"github.com/steveyegge/beads/internal/syncbranch"
|
||||
)
|
||||
|
||||
// isGitWorktree detects if the current directory is in a git worktree.
|
||||
|
|
@ -18,37 +16,6 @@ func isGitWorktree() bool {
|
|||
return git.IsWorktree()
|
||||
}
|
||||
|
||||
// shouldDisableDaemonForWorktree returns true if daemon should be disabled
|
||||
// due to being in a git worktree without sync-branch configured.
|
||||
//
|
||||
// The daemon is unsafe in worktrees because all worktrees share the same
|
||||
// .beads directory, and the daemon commits to whatever branch its working
|
||||
// directory has checked out - which can cause commits to go to the wrong branch.
|
||||
//
|
||||
// However, when sync-branch is configured, the daemon commits to a dedicated
|
||||
// branch (e.g., "beads-metadata") using an internal worktree, so the user's
|
||||
// current branch is never affected. This makes daemon mode safe in worktrees.
|
||||
//
|
||||
// Returns:
|
||||
// - true: Disable daemon (in worktree without sync-branch)
|
||||
// - false: Allow daemon (not in worktree, or sync-branch is configured)
|
||||
func shouldDisableDaemonForWorktree() bool {
|
||||
// If not in a worktree, daemon is safe
|
||||
if !isGitWorktree() {
|
||||
return false
|
||||
}
|
||||
|
||||
// In a worktree - check if sync-branch is configured
|
||||
// IsConfiguredWithDB checks env var, config.yaml, AND database config
|
||||
if syncbranch.IsConfiguredWithDB("") {
|
||||
// Sync-branch is configured, daemon is safe (commits go to dedicated branch)
|
||||
return false
|
||||
}
|
||||
|
||||
// In worktree without sync-branch - daemon is unsafe, disable it
|
||||
return true
|
||||
}
|
||||
|
||||
// gitRevParse runs git rev-parse with the given flag and returns the trimmed output.
|
||||
// This is a helper for CLI utilities that need git command execution.
|
||||
func gitRevParse(flag string) string {
|
||||
|
|
@ -69,49 +36,6 @@ func getWorktreeGitDir() string {
|
|||
return gitDir
|
||||
}
|
||||
|
||||
// warnWorktreeDaemon prints a warning if using daemon with worktrees without sync-branch.
|
||||
// Call this only when daemon mode is actually active (connected).
|
||||
//
|
||||
// With the new worktree safety logic, this warning should rarely appear because:
|
||||
// - Daemon is auto-disabled in worktrees without sync-branch
|
||||
// - When sync-branch is configured, daemon is safe (commits go to dedicated branch)
|
||||
//
|
||||
// This warning is kept as a safety net for edge cases where daemon might still
|
||||
// be connected in a worktree (e.g., daemon started in main repo, then user cd's to worktree).
|
||||
func warnWorktreeDaemon(dbPathForWarning string) {
|
||||
if !isGitWorktree() {
|
||||
return
|
||||
}
|
||||
|
||||
// If sync-branch is configured, daemon is safe in worktrees - no warning needed
|
||||
if syncbranch.IsConfiguredWithDB("") {
|
||||
return
|
||||
}
|
||||
|
||||
gitDir := getWorktreeGitDir()
|
||||
beadsDir := filepath.Dir(dbPathForWarning)
|
||||
if beadsDir == "." || beadsDir == "" {
|
||||
beadsDir = dbPathForWarning
|
||||
}
|
||||
|
||||
fmt.Fprintln(os.Stderr)
|
||||
fmt.Fprintln(os.Stderr, "╔══════════════════════════════════════════════════════════════════════════╗")
|
||||
fmt.Fprintln(os.Stderr, "║ WARNING: Git worktree detected with daemon mode ║")
|
||||
fmt.Fprintln(os.Stderr, "╠══════════════════════════════════════════════════════════════════════════╣")
|
||||
fmt.Fprintln(os.Stderr, "║ Git worktrees share the same .beads directory, which can cause the ║")
|
||||
fmt.Fprintln(os.Stderr, "║ daemon to commit/push to the wrong branch. ║")
|
||||
fmt.Fprintln(os.Stderr, "║ ║")
|
||||
fmt.Fprintf(os.Stderr, "║ Shared database: %-55s ║\n", truncateForBox(beadsDir, 55))
|
||||
fmt.Fprintf(os.Stderr, "║ Worktree git dir: %-54s ║\n", truncateForBox(gitDir, 54))
|
||||
fmt.Fprintln(os.Stderr, "║ ║")
|
||||
fmt.Fprintln(os.Stderr, "║ RECOMMENDED SOLUTIONS: ║")
|
||||
fmt.Fprintln(os.Stderr, "║ 1. Configure sync-branch: bd config set sync-branch beads-metadata ║")
|
||||
fmt.Fprintln(os.Stderr, "║ 2. Use --no-daemon flag: bd --no-daemon <command> ║")
|
||||
fmt.Fprintln(os.Stderr, "║ 3. Disable daemon mode: export BEADS_NO_DAEMON=1 ║")
|
||||
fmt.Fprintln(os.Stderr, "╚══════════════════════════════════════════════════════════════════════════╝")
|
||||
fmt.Fprintln(os.Stderr)
|
||||
}
|
||||
|
||||
// truncateForBox truncates a path to fit in the warning box
|
||||
func truncateForBox(path string, maxLen int) string {
|
||||
if len(path) <= maxLen {
|
||||
|
|
|
|||
|
|
@ -1,455 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/config"
|
||||
"github.com/steveyegge/beads/internal/git"
|
||||
|
||||
// Import SQLite driver for test database creation
|
||||
_ "github.com/ncruces/go-sqlite3/driver"
|
||||
_ "github.com/ncruces/go-sqlite3/embed"
|
||||
)
|
||||
|
||||
// TestShouldDisableDaemonForWorktree tests the worktree daemon disable logic.
|
||||
// The function should return true (disable daemon) when:
|
||||
// - In a git worktree AND sync-branch is NOT configured
|
||||
// The function should return false (allow daemon) when:
|
||||
// - Not in a worktree (regular repo)
|
||||
// - In a worktree but sync-branch IS configured
|
||||
func TestShouldDisableDaemonForWorktree(t *testing.T) {
|
||||
// Initialize config for tests
|
||||
initConfigForTest(t)
|
||||
|
||||
// Save and restore environment variables
|
||||
origSyncBranch := os.Getenv("BEADS_SYNC_BRANCH")
|
||||
defer func() {
|
||||
if origSyncBranch != "" {
|
||||
os.Setenv("BEADS_SYNC_BRANCH", origSyncBranch)
|
||||
} else {
|
||||
os.Unsetenv("BEADS_SYNC_BRANCH")
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("returns false in regular repo without sync-branch", func(t *testing.T) {
|
||||
// Create a regular git repo (not a worktree) using existing helper
|
||||
repoPath, cleanup := setupGitRepo(t)
|
||||
defer cleanup()
|
||||
_ = repoPath // repoPath is the current directory after setupGitRepo
|
||||
|
||||
// No sync-branch configured
|
||||
os.Unsetenv("BEADS_SYNC_BRANCH")
|
||||
|
||||
result := shouldDisableDaemonForWorktree()
|
||||
if result {
|
||||
t.Error("Expected shouldDisableDaemonForWorktree() to return false in regular repo")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returns false in regular repo with sync-branch", func(t *testing.T) {
|
||||
// Create a regular git repo (not a worktree) using existing helper
|
||||
_, cleanup := setupGitRepo(t)
|
||||
defer cleanup()
|
||||
|
||||
// Sync-branch configured
|
||||
os.Setenv("BEADS_SYNC_BRANCH", "beads-metadata")
|
||||
|
||||
result := shouldDisableDaemonForWorktree()
|
||||
if result {
|
||||
t.Error("Expected shouldDisableDaemonForWorktree() to return false in regular repo with sync-branch")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returns true in worktree without sync-branch", func(t *testing.T) {
|
||||
// Create a git repo with a worktree
|
||||
mainDir, worktreeDir := setupWorktreeTestRepo(t)
|
||||
|
||||
// Change to the worktree directory
|
||||
origDir, _ := os.Getwd()
|
||||
defer func() {
|
||||
_ = os.Chdir(origDir)
|
||||
// Reset git caches after changing directory
|
||||
git.ResetCaches()
|
||||
// Reinitialize config to restore original state
|
||||
config.ResetForTesting()
|
||||
_ = config.Initialize()
|
||||
}()
|
||||
if err := os.Chdir(worktreeDir); err != nil {
|
||||
t.Fatalf("Failed to change to worktree dir: %v", err)
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
// Reset git caches after changing directory (required for IsWorktree to re-detect)
|
||||
git.ResetCaches()
|
||||
|
||||
// Set BEADS_DIR to the test's .beads directory to prevent
|
||||
// git repo detection from finding the project's .beads
|
||||
origBeadsDir := os.Getenv("BEADS_DIR")
|
||||
os.Setenv("BEADS_DIR", mainDir+"/.beads")
|
||||
defer func() {
|
||||
if origBeadsDir != "" {
|
||||
os.Setenv("BEADS_DIR", origBeadsDir)
|
||||
} else {
|
||||
os.Unsetenv("BEADS_DIR")
|
||||
}
|
||||
}()
|
||||
|
||||
// No sync-branch configured
|
||||
os.Unsetenv("BEADS_SYNC_BRANCH")
|
||||
|
||||
// Reinitialize config to pick up the new directory's config.yaml
|
||||
initConfigForTest(t)
|
||||
|
||||
// Debug: verify we're actually in a worktree
|
||||
isWorktree := isGitWorktree()
|
||||
t.Logf("isGitWorktree() = %v, worktreeDir = %s", isWorktree, worktreeDir)
|
||||
|
||||
result := shouldDisableDaemonForWorktree()
|
||||
if !result {
|
||||
t.Errorf("Expected shouldDisableDaemonForWorktree() to return true in worktree without sync-branch (isWorktree=%v)", isWorktree)
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
cleanupTestWorktree(t, mainDir, worktreeDir)
|
||||
})
|
||||
|
||||
t.Run("returns false in worktree with sync-branch configured", func(t *testing.T) {
|
||||
// Create a git repo with a worktree
|
||||
mainDir, worktreeDir := setupWorktreeTestRepo(t)
|
||||
|
||||
// Change to the worktree directory
|
||||
origDir, _ := os.Getwd()
|
||||
defer func() {
|
||||
_ = os.Chdir(origDir)
|
||||
git.ResetCaches()
|
||||
config.ResetForTesting()
|
||||
_ = config.Initialize()
|
||||
}()
|
||||
if err := os.Chdir(worktreeDir); err != nil {
|
||||
t.Fatalf("Failed to change to worktree dir: %v", err)
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
// Reset git caches after changing directory
|
||||
git.ResetCaches()
|
||||
|
||||
// Reinitialize config to pick up the new directory's config.yaml
|
||||
initConfigForTest(t)
|
||||
|
||||
// Sync-branch configured via environment variable
|
||||
os.Setenv("BEADS_SYNC_BRANCH", "beads-metadata")
|
||||
|
||||
result := shouldDisableDaemonForWorktree()
|
||||
if result {
|
||||
t.Error("Expected shouldDisableDaemonForWorktree() to return false in worktree with sync-branch")
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
cleanupTestWorktree(t, mainDir, worktreeDir)
|
||||
})
|
||||
|
||||
t.Run("returns false in worktree with sync-branch in database config", func(t *testing.T) {
|
||||
// Create a git repo with a worktree AND a database with sync.branch config
|
||||
mainDir, worktreeDir := setupWorktreeTestRepoWithDB(t, "beads-metadata")
|
||||
|
||||
// Change to the worktree directory
|
||||
origDir, _ := os.Getwd()
|
||||
defer func() {
|
||||
_ = os.Chdir(origDir)
|
||||
git.ResetCaches()
|
||||
config.ResetForTesting()
|
||||
_ = config.Initialize()
|
||||
}()
|
||||
if err := os.Chdir(worktreeDir); err != nil {
|
||||
t.Fatalf("Failed to change to worktree dir: %v", err)
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
// Reset git caches after changing directory
|
||||
git.ResetCaches()
|
||||
|
||||
// Reinitialize config to pick up the new directory's config.yaml
|
||||
initConfigForTest(t)
|
||||
|
||||
// NO env var or config.yaml sync-branch - only database config
|
||||
os.Unsetenv("BEADS_SYNC_BRANCH")
|
||||
|
||||
result := shouldDisableDaemonForWorktree()
|
||||
if result {
|
||||
t.Error("Expected shouldDisableDaemonForWorktree() to return false in worktree with sync-branch in database")
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
cleanupTestWorktree(t, mainDir, worktreeDir)
|
||||
})
|
||||
}
|
||||
|
||||
// TestShouldAutoStartDaemonWorktreeIntegration tests that shouldAutoStartDaemon
|
||||
// respects the worktree+sync-branch logic.
|
||||
func TestShouldAutoStartDaemonWorktreeIntegration(t *testing.T) {
|
||||
// Initialize config for tests
|
||||
initConfigForTest(t)
|
||||
|
||||
// Save and restore environment variables
|
||||
origNoDaemon := os.Getenv("BEADS_NO_DAEMON")
|
||||
origAutoStart := os.Getenv("BEADS_AUTO_START_DAEMON")
|
||||
origSyncBranch := os.Getenv("BEADS_SYNC_BRANCH")
|
||||
defer func() {
|
||||
restoreTestEnv("BEADS_NO_DAEMON", origNoDaemon)
|
||||
restoreTestEnv("BEADS_AUTO_START_DAEMON", origAutoStart)
|
||||
restoreTestEnv("BEADS_SYNC_BRANCH", origSyncBranch)
|
||||
}()
|
||||
|
||||
t.Run("disables auto-start in worktree without sync-branch", func(t *testing.T) {
|
||||
// Create a git repo with a worktree
|
||||
mainDir, worktreeDir := setupWorktreeTestRepo(t)
|
||||
|
||||
// Change to the worktree directory
|
||||
origDir, _ := os.Getwd()
|
||||
defer func() {
|
||||
_ = os.Chdir(origDir)
|
||||
git.ResetCaches()
|
||||
config.ResetForTesting()
|
||||
_ = config.Initialize()
|
||||
}()
|
||||
if err := os.Chdir(worktreeDir); err != nil {
|
||||
t.Fatalf("Failed to change to worktree dir: %v", err)
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
// Reset git caches after changing directory
|
||||
git.ResetCaches()
|
||||
|
||||
// Set BEADS_DIR to the test's .beads directory to prevent
|
||||
// git repo detection from finding the project's .beads
|
||||
origBeadsDir := os.Getenv("BEADS_DIR")
|
||||
os.Setenv("BEADS_DIR", mainDir+"/.beads")
|
||||
defer func() {
|
||||
if origBeadsDir != "" {
|
||||
os.Setenv("BEADS_DIR", origBeadsDir)
|
||||
} else {
|
||||
os.Unsetenv("BEADS_DIR")
|
||||
}
|
||||
}()
|
||||
|
||||
// Clear all daemon-related env vars
|
||||
os.Unsetenv("BEADS_NO_DAEMON")
|
||||
os.Unsetenv("BEADS_AUTO_START_DAEMON")
|
||||
os.Unsetenv("BEADS_SYNC_BRANCH")
|
||||
|
||||
// Reinitialize config to pick up the new directory's config.yaml
|
||||
initConfigForTest(t)
|
||||
|
||||
result := shouldAutoStartDaemon()
|
||||
if result {
|
||||
t.Error("Expected shouldAutoStartDaemon() to return false in worktree without sync-branch")
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
cleanupTestWorktree(t, mainDir, worktreeDir)
|
||||
})
|
||||
|
||||
t.Run("enables auto-start in worktree with sync-branch", func(t *testing.T) {
|
||||
// Create a git repo with a worktree
|
||||
mainDir, worktreeDir := setupWorktreeTestRepo(t)
|
||||
|
||||
// Change to the worktree directory
|
||||
origDir, _ := os.Getwd()
|
||||
defer func() {
|
||||
_ = os.Chdir(origDir)
|
||||
git.ResetCaches()
|
||||
config.ResetForTesting()
|
||||
_ = config.Initialize()
|
||||
}()
|
||||
if err := os.Chdir(worktreeDir); err != nil {
|
||||
t.Fatalf("Failed to change to worktree dir: %v", err)
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
// Reset git caches after changing directory
|
||||
git.ResetCaches()
|
||||
|
||||
// Reinitialize config to pick up the new directory's config.yaml
|
||||
initConfigForTest(t)
|
||||
|
||||
// Clear daemon env vars but set sync-branch
|
||||
os.Unsetenv("BEADS_NO_DAEMON")
|
||||
os.Unsetenv("BEADS_AUTO_START_DAEMON")
|
||||
os.Setenv("BEADS_SYNC_BRANCH", "beads-metadata")
|
||||
|
||||
result := shouldAutoStartDaemon()
|
||||
if !result {
|
||||
t.Error("Expected shouldAutoStartDaemon() to return true in worktree with sync-branch")
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
cleanupTestWorktree(t, mainDir, worktreeDir)
|
||||
})
|
||||
|
||||
t.Run("BEADS_NO_DAEMON still takes precedence in worktree", func(t *testing.T) {
|
||||
// Create a git repo with a worktree
|
||||
mainDir, worktreeDir := setupWorktreeTestRepo(t)
|
||||
|
||||
// Change to the worktree directory
|
||||
origDir, _ := os.Getwd()
|
||||
defer func() {
|
||||
_ = os.Chdir(origDir)
|
||||
git.ResetCaches()
|
||||
config.ResetForTesting()
|
||||
_ = config.Initialize()
|
||||
}()
|
||||
if err := os.Chdir(worktreeDir); err != nil {
|
||||
t.Fatalf("Failed to change to worktree dir: %v", err)
|
||||
}
|
||||
git.ResetCaches()
|
||||
|
||||
// Reset git caches after changing directory
|
||||
git.ResetCaches()
|
||||
|
||||
// Reinitialize config to pick up the new directory's config.yaml
|
||||
initConfigForTest(t)
|
||||
|
||||
// Set BEADS_NO_DAEMON (should override everything)
|
||||
os.Setenv("BEADS_NO_DAEMON", "1")
|
||||
os.Setenv("BEADS_SYNC_BRANCH", "beads-metadata")
|
||||
|
||||
result := shouldAutoStartDaemon()
|
||||
if result {
|
||||
t.Error("Expected BEADS_NO_DAEMON=1 to disable auto-start even with sync-branch")
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
cleanupTestWorktree(t, mainDir, worktreeDir)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper functions for worktree daemon tests
|
||||
|
||||
func restoreTestEnv(key, value string) {
|
||||
if value != "" {
|
||||
os.Setenv(key, value)
|
||||
} else {
|
||||
os.Unsetenv(key)
|
||||
}
|
||||
}
|
||||
|
||||
// setupWorktreeTestRepo creates a git repo with a worktree for testing.
|
||||
// Returns the main repo directory and worktree directory.
|
||||
// Caller is responsible for cleanup via cleanupTestWorktree.
|
||||
//
|
||||
// IMPORTANT: This function also reinitializes the config package to use the
|
||||
// temp directory's config, avoiding interference from the beads project's own config.
|
||||
func setupWorktreeTestRepo(t *testing.T) (mainDir, worktreeDir string) {
|
||||
t.Helper()
|
||||
|
||||
// Create main repo directory
|
||||
mainDir = t.TempDir()
|
||||
|
||||
// Initialize git repo with 'main' as default branch (modern git convention)
|
||||
cmd := exec.Command("git", "init", "--initial-branch=main")
|
||||
cmd.Dir = mainDir
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to init git repo: %v\n%s", err, output)
|
||||
}
|
||||
|
||||
// Configure git user for commits
|
||||
cmd = exec.Command("git", "config", "user.email", "test@test.com")
|
||||
cmd.Dir = mainDir
|
||||
_ = cmd.Run()
|
||||
|
||||
cmd = exec.Command("git", "config", "user.name", "Test User")
|
||||
cmd.Dir = mainDir
|
||||
_ = cmd.Run()
|
||||
|
||||
// Create .beads directory with empty config (no sync-branch)
|
||||
beadsDir := mainDir + "/.beads"
|
||||
if err := os.MkdirAll(beadsDir, 0755); err != nil {
|
||||
t.Fatalf("Failed to create .beads dir: %v", err)
|
||||
}
|
||||
// Create minimal config.yaml without sync-branch
|
||||
configContent := "# Test config\nissue-prefix: \"test\"\n"
|
||||
if err := os.WriteFile(beadsDir+"/config.yaml", []byte(configContent), 0644); err != nil {
|
||||
t.Fatalf("Failed to create config.yaml: %v", err)
|
||||
}
|
||||
|
||||
// Create initial commit (required for worktrees)
|
||||
if err := os.WriteFile(mainDir+"/README.md", []byte("# Test\n"), 0644); err != nil {
|
||||
t.Fatalf("Failed to create test file: %v", err)
|
||||
}
|
||||
|
||||
cmd = exec.Command("git", "add", ".")
|
||||
cmd.Dir = mainDir
|
||||
_ = cmd.Run()
|
||||
|
||||
cmd = exec.Command("git", "commit", "-m", "Initial commit")
|
||||
cmd.Dir = mainDir
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to create initial commit: %v\n%s", err, output)
|
||||
}
|
||||
|
||||
// Create a branch for the worktree
|
||||
cmd = exec.Command("git", "branch", "feature-branch")
|
||||
cmd.Dir = mainDir
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to create branch: %v\n%s", err, output)
|
||||
}
|
||||
|
||||
// Create worktree directory (must be outside main repo)
|
||||
worktreeDir = t.TempDir()
|
||||
|
||||
// Add worktree
|
||||
cmd = exec.Command("git", "worktree", "add", worktreeDir, "feature-branch")
|
||||
cmd.Dir = mainDir
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("Failed to create worktree: %v\n%s", err, output)
|
||||
}
|
||||
|
||||
return mainDir, worktreeDir
|
||||
}
|
||||
|
||||
// cleanupTestWorktree removes a worktree created by setupWorktreeTestRepo.
|
||||
func cleanupTestWorktree(t *testing.T, mainDir, worktreeDir string) {
|
||||
t.Helper()
|
||||
|
||||
// Remove worktree
|
||||
cmd := exec.Command("git", "worktree", "remove", worktreeDir, "--force")
|
||||
cmd.Dir = mainDir
|
||||
_ = cmd.Run() // Best effort cleanup
|
||||
}
|
||||
|
||||
// setupWorktreeTestRepoWithDB creates a git repo with a worktree AND a database
|
||||
// that has sync.branch configured. This tests the database config path.
|
||||
func setupWorktreeTestRepoWithDB(t *testing.T, syncBranch string) (mainDir, worktreeDir string) {
|
||||
t.Helper()
|
||||
|
||||
// First create the basic worktree repo
|
||||
mainDir, worktreeDir = setupWorktreeTestRepo(t)
|
||||
|
||||
// Now create a database with sync.branch config
|
||||
beadsDir := mainDir + "/.beads"
|
||||
dbPath := beadsDir + "/beads.db"
|
||||
|
||||
// Create a minimal SQLite database with the config table and sync.branch value
|
||||
db, err := sql.Open("sqlite3", dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to open database: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
// Create config table
|
||||
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT)`)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create config table: %v", err)
|
||||
}
|
||||
|
||||
// Insert sync.branch config
|
||||
_, err = db.Exec(`INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)`, "sync.branch", syncBranch)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to insert sync.branch config: %v", err)
|
||||
}
|
||||
|
||||
return mainDir, worktreeDir
|
||||
}
|
||||
|
|
@ -1,447 +0,0 @@
|
|||
package daemon
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/beads"
|
||||
"github.com/steveyegge/beads/internal/lockfile"
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
)
|
||||
|
||||
// walkWithDepth walks a directory tree with depth limiting
|
||||
func walkWithDepth(root string, currentDepth, maxDepth int, fn func(path string, info os.FileInfo) error) error {
|
||||
if currentDepth > maxDepth {
|
||||
return nil
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
// Skip directories we can't read
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
path := filepath.Join(root, entry.Name())
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip common directories that won't have beads databases
|
||||
if info.IsDir() {
|
||||
name := entry.Name()
|
||||
if strings.HasPrefix(name, ".") && name != ".beads" {
|
||||
continue // Skip hidden dirs except .beads
|
||||
}
|
||||
if name == "node_modules" || name == "vendor" || name == ".git" {
|
||||
continue
|
||||
}
|
||||
// Recurse into subdirectory
|
||||
if err := walkWithDepth(path, currentDepth+1, maxDepth, fn); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Process file
|
||||
if err := fn(path, info); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DaemonInfo represents metadata about a discovered daemon
|
||||
type DaemonInfo struct {
|
||||
WorkspacePath string
|
||||
DatabasePath string
|
||||
SocketPath string
|
||||
PID int
|
||||
Version string
|
||||
UptimeSeconds float64
|
||||
LastActivityTime string
|
||||
ExclusiveLockActive bool
|
||||
ExclusiveLockHolder string
|
||||
Alive bool
|
||||
Error string
|
||||
}
|
||||
|
||||
// DiscoverDaemons discovers running bd daemons using the registry
|
||||
// Falls back to filesystem scanning if searchRoots is explicitly provided (for compatibility)
|
||||
func DiscoverDaemons(searchRoots []string) ([]DaemonInfo, error) {
|
||||
// If searchRoots is explicitly provided, use legacy filesystem scan
|
||||
// This maintains compatibility for any callers that explicitly specify paths
|
||||
if len(searchRoots) > 0 {
|
||||
return discoverDaemonsLegacy(searchRoots)
|
||||
}
|
||||
|
||||
// Use registry-based discovery (instant, no filesystem scanning)
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
// Fall back to legacy discovery if registry unavailable
|
||||
return discoverDaemonsLegacy(nil)
|
||||
}
|
||||
|
||||
return registry.List()
|
||||
}
|
||||
|
||||
// discoverDaemonsLegacy scans the filesystem for running bd daemons (legacy method)
|
||||
// It searches common locations and uses the Status RPC endpoint to gather metadata
|
||||
func discoverDaemonsLegacy(searchRoots []string) ([]DaemonInfo, error) {
|
||||
var daemons []DaemonInfo
|
||||
seen := make(map[string]bool)
|
||||
|
||||
// If no search roots provided, use common locations
|
||||
if len(searchRoots) == 0 {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get home directory: %w", err)
|
||||
}
|
||||
searchRoots = []string{
|
||||
home,
|
||||
"/tmp",
|
||||
}
|
||||
// Also add current directory if in a git repo
|
||||
if cwd, err := os.Getwd(); err == nil {
|
||||
searchRoots = append(searchRoots, cwd)
|
||||
}
|
||||
}
|
||||
|
||||
// Search for .beads/bd.sock files (limit depth to avoid traversing entire filesystem)
|
||||
for _, root := range searchRoots {
|
||||
maxDepth := 10 // Limit recursion depth
|
||||
if err := walkWithDepth(root, 0, maxDepth, func(path string, info os.FileInfo) error {
|
||||
// Skip if not a socket file
|
||||
if info.Name() != "bd.sock" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Skip if already seen this socket
|
||||
if seen[path] {
|
||||
return nil
|
||||
}
|
||||
seen[path] = true
|
||||
|
||||
// Try to connect and get status
|
||||
daemon := discoverDaemon(path)
|
||||
daemons = append(daemons, daemon)
|
||||
|
||||
return nil
|
||||
}); err != nil {
|
||||
// Continue searching other roots even if one fails
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return daemons, nil
|
||||
}
|
||||
|
||||
// discoverDaemon attempts to connect to a daemon socket and retrieve its status
|
||||
func discoverDaemon(socketPath string) DaemonInfo {
|
||||
daemon := DaemonInfo{
|
||||
SocketPath: socketPath,
|
||||
Alive: false,
|
||||
}
|
||||
|
||||
// Fast probe: check daemon lock before attempting RPC if socket doesn't exist
|
||||
// This eliminates unnecessary connection attempts when no daemon is running
|
||||
// If socket exists, we proceed with RPC for backwards compatibility
|
||||
_, err := os.Stat(socketPath)
|
||||
socketExists := err == nil
|
||||
|
||||
if !socketExists {
|
||||
beadsDir := filepath.Dir(socketPath)
|
||||
running, _ := lockfile.TryDaemonLock(beadsDir)
|
||||
if !running {
|
||||
daemon.Error = "daemon lock not held and socket missing"
|
||||
// Check for daemon-error file
|
||||
if errMsg := checkDaemonErrorFile(socketPath); errMsg != "" {
|
||||
daemon.Error = errMsg
|
||||
}
|
||||
return daemon
|
||||
}
|
||||
}
|
||||
|
||||
// Try to connect with short timeout
|
||||
client, err := rpc.TryConnectWithTimeout(socketPath, 500*time.Millisecond)
|
||||
if err != nil {
|
||||
daemon.Error = fmt.Sprintf("failed to connect: %v", err)
|
||||
// Check for daemon-error file
|
||||
if errMsg := checkDaemonErrorFile(socketPath); errMsg != "" {
|
||||
daemon.Error = errMsg
|
||||
}
|
||||
return daemon
|
||||
}
|
||||
if client == nil {
|
||||
daemon.Error = "daemon not responding or unhealthy"
|
||||
// Check for daemon-error file
|
||||
if errMsg := checkDaemonErrorFile(socketPath); errMsg != "" {
|
||||
daemon.Error = errMsg
|
||||
}
|
||||
return daemon
|
||||
}
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
// Get status
|
||||
status, err := client.Status()
|
||||
if err != nil {
|
||||
daemon.Error = fmt.Sprintf("failed to get status: %v", err)
|
||||
return daemon
|
||||
}
|
||||
|
||||
// Populate daemon info from status
|
||||
daemon.Alive = true
|
||||
daemon.WorkspacePath = status.WorkspacePath
|
||||
daemon.DatabasePath = status.DatabasePath
|
||||
daemon.PID = status.PID
|
||||
daemon.Version = status.Version
|
||||
daemon.UptimeSeconds = status.UptimeSeconds
|
||||
daemon.LastActivityTime = status.LastActivityTime
|
||||
daemon.ExclusiveLockActive = status.ExclusiveLockActive
|
||||
daemon.ExclusiveLockHolder = status.ExclusiveLockHolder
|
||||
|
||||
return daemon
|
||||
}
|
||||
|
||||
// FindDaemonByWorkspace finds a daemon serving a specific workspace
|
||||
func FindDaemonByWorkspace(workspacePath string) (*DaemonInfo, error) {
|
||||
// Determine the correct .beads directory location
|
||||
// For worktrees, .beads is in the main repository root, not the worktree
|
||||
beadsDir := findBeadsDirForWorkspace(workspacePath)
|
||||
|
||||
// Try short socket path first (GH#1001 - avoids macOS 104-char limit)
|
||||
// This is computed from the workspace path, not the beads dir
|
||||
mainWorkspace := filepath.Dir(beadsDir) // Get workspace from .beads dir
|
||||
shortSocketPath := rpc.ShortSocketPath(mainWorkspace)
|
||||
if _, err := os.Stat(shortSocketPath); err == nil {
|
||||
daemon := discoverDaemon(shortSocketPath)
|
||||
if daemon.Alive {
|
||||
return &daemon, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Try legacy socket path in .beads directory (backwards compatibility)
|
||||
legacySocketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
if legacySocketPath != shortSocketPath {
|
||||
if _, err := os.Stat(legacySocketPath); err == nil {
|
||||
daemon := discoverDaemon(legacySocketPath)
|
||||
if daemon.Alive {
|
||||
return &daemon, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to discovering all daemons
|
||||
daemons, err := DiscoverDaemons([]string{workspacePath})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, daemon := range daemons {
|
||||
// Use PathsEqual for case-insensitive comparison on macOS/Windows (GH#869)
|
||||
if utils.PathsEqual(daemon.WorkspacePath, workspacePath) && daemon.Alive {
|
||||
return &daemon, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("no daemon found for workspace: %s", workspacePath)
|
||||
}
|
||||
|
||||
// findBeadsDirForWorkspace determines the correct .beads directory for a workspace.
|
||||
// For worktrees, this is the main repository root; for regular repos, it's the workspace itself.
|
||||
//
|
||||
// This function delegates to beads.GetRepoContextForWorkspace() for proper resolution
|
||||
// including worktree detection and path validation (DMN-001).
|
||||
func findBeadsDirForWorkspace(workspacePath string) string {
|
||||
// Use the centralized RepoContext API for workspace resolution
|
||||
rc, err := beads.GetRepoContextForWorkspace(workspacePath)
|
||||
if err != nil {
|
||||
// Fallback to simple path join if context resolution fails
|
||||
// This maintains backward compatibility for edge cases
|
||||
return filepath.Join(workspacePath, ".beads")
|
||||
}
|
||||
return rc.BeadsDir
|
||||
}
|
||||
|
||||
// getRepoContextForWorkspace returns the full RepoContext for a workspace.
|
||||
// This provides access to RepoRoot, BeadsDir, and worktree status for operations
|
||||
// that need more than just the .beads directory path.
|
||||
//
|
||||
// Returns an error if the workspace cannot be resolved or validated.
|
||||
func getRepoContextForWorkspace(workspacePath string) (*beads.RepoContext, error) {
|
||||
rc, err := beads.GetRepoContextForWorkspace(workspacePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot resolve workspace context: %w", err)
|
||||
}
|
||||
// Validate the context is still valid (paths exist)
|
||||
if err := rc.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("workspace context is stale: %w", err)
|
||||
}
|
||||
return rc, nil
|
||||
}
|
||||
|
||||
// checkDaemonErrorFile checks for a daemon-error file in the .beads directory
|
||||
func checkDaemonErrorFile(socketPath string) string {
|
||||
// Socket path is typically .beads/bd.sock, so get the parent dir
|
||||
beadsDir := filepath.Dir(socketPath)
|
||||
errFile := filepath.Join(beadsDir, "daemon-error")
|
||||
|
||||
data, err := os.ReadFile(errFile)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return string(data)
|
||||
}
|
||||
|
||||
// CleanupStaleSockets removes socket files and PID files for dead daemons
|
||||
func CleanupStaleSockets(daemons []DaemonInfo) (int, error) {
|
||||
cleaned := 0
|
||||
for _, daemon := range daemons {
|
||||
if !daemon.Alive && daemon.SocketPath != "" {
|
||||
// Remove stale socket file
|
||||
if err := os.Remove(daemon.SocketPath); err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
return cleaned, fmt.Errorf("failed to remove stale socket %s: %w", daemon.SocketPath, err)
|
||||
}
|
||||
} else {
|
||||
cleaned++
|
||||
}
|
||||
|
||||
// Also remove associated PID file if it exists
|
||||
socketDir := filepath.Dir(daemon.SocketPath)
|
||||
pidFile := filepath.Join(socketDir, "daemon.pid")
|
||||
if err := os.Remove(pidFile); err != nil {
|
||||
// Ignore errors for PID file - it may not exist
|
||||
if !os.IsNotExist(err) {
|
||||
// Log warning but don't fail
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return cleaned, nil
|
||||
}
|
||||
|
||||
// StopDaemon gracefully stops a daemon by sending shutdown command via RPC
|
||||
// Falls back to SIGTERM if RPC fails
|
||||
func StopDaemon(daemon DaemonInfo) error {
|
||||
if !daemon.Alive {
|
||||
return fmt.Errorf("daemon is not running")
|
||||
}
|
||||
|
||||
// Try graceful shutdown via RPC first
|
||||
client, err := rpc.TryConnectWithTimeout(daemon.SocketPath, 500*time.Millisecond)
|
||||
if err == nil && client != nil {
|
||||
defer func() { _ = client.Close() }()
|
||||
if err := client.Shutdown(); err == nil {
|
||||
// Wait a bit for daemon to shut down
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to SIGTERM if RPC failed
|
||||
return killProcess(daemon.PID)
|
||||
}
|
||||
|
||||
// KillAllFailure represents a failure to kill a specific daemon
|
||||
type KillAllFailure struct {
|
||||
Workspace string `json:"workspace"`
|
||||
PID int `json:"pid"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// KillAllResults contains results from KillAllDaemons
|
||||
type KillAllResults struct {
|
||||
Stopped int `json:"stopped"`
|
||||
Failed int `json:"failed"`
|
||||
Failures []KillAllFailure `json:"failures,omitempty"`
|
||||
}
|
||||
|
||||
// KillAllDaemons stops all provided daemons, using force if RPC/SIGTERM fail
|
||||
func KillAllDaemons(daemons []DaemonInfo, force bool) KillAllResults {
|
||||
results := KillAllResults{
|
||||
Failures: []KillAllFailure{},
|
||||
}
|
||||
|
||||
for _, daemon := range daemons {
|
||||
if !daemon.Alive {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := stopDaemonWithTimeout(daemon); err != nil {
|
||||
if force {
|
||||
// Try force kill
|
||||
if err := forceKillProcess(daemon.PID); err != nil {
|
||||
results.Failed++
|
||||
results.Failures = append(results.Failures, KillAllFailure{
|
||||
Workspace: daemon.WorkspacePath,
|
||||
PID: daemon.PID,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
results.Failed++
|
||||
results.Failures = append(results.Failures, KillAllFailure{
|
||||
Workspace: daemon.WorkspacePath,
|
||||
PID: daemon.PID,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
}
|
||||
results.Stopped++
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// stopDaemonWithTimeout tries RPC shutdown, then SIGTERM with timeout, then SIGKILL
|
||||
func stopDaemonWithTimeout(daemon DaemonInfo) error {
|
||||
// Try RPC shutdown first (2 second timeout)
|
||||
client, err := rpc.TryConnectWithTimeout(daemon.SocketPath, 2*time.Second)
|
||||
if err == nil && client != nil {
|
||||
defer func() { _ = client.Close() }()
|
||||
if err := client.Shutdown(); err == nil {
|
||||
// Wait and verify process died
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
if !isProcessAlive(daemon.PID) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try graceful kill with 3 second timeout
|
||||
if err := killProcess(daemon.PID); err != nil {
|
||||
return fmt.Errorf("kill process failed: %w", err)
|
||||
}
|
||||
|
||||
// Wait up to 3 seconds for process to die
|
||||
for i := 0; i < 30; i++ {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if !isProcessAlive(daemon.PID) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful kill timeout, try force kill with 1 second timeout
|
||||
if err := forceKillProcess(daemon.PID); err != nil {
|
||||
return fmt.Errorf("force kill failed: %w", err)
|
||||
}
|
||||
|
||||
// Wait up to 1 second for process to die
|
||||
for i := 0; i < 10; i++ {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if !isProcessAlive(daemon.PID) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("process %d did not die after force kill", daemon.PID)
|
||||
}
|
||||
|
|
@ -1,398 +0,0 @@
|
|||
//go:build integration
|
||||
// +build integration
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/rpc"
|
||||
"github.com/steveyegge/beads/internal/storage/sqlite"
|
||||
)
|
||||
|
||||
func TestDiscoverDaemon(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
workspace := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(workspace, 0755)
|
||||
|
||||
// Start daemon
|
||||
dbPath := filepath.Join(workspace, "test.db")
|
||||
socketPath := filepath.Join(workspace, "bd.sock")
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create storage: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
server := rpc.NewServer(socketPath, store, tmpDir, dbPath)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go server.Start(ctx)
|
||||
<-server.WaitReady()
|
||||
defer server.Stop()
|
||||
|
||||
// Test discoverDaemon directly
|
||||
daemon := discoverDaemon(socketPath)
|
||||
if !daemon.Alive {
|
||||
t.Errorf("daemon not alive: %s", daemon.Error)
|
||||
}
|
||||
if daemon.PID != os.Getpid() {
|
||||
t.Errorf("wrong PID: expected %d, got %d", os.Getpid(), daemon.PID)
|
||||
}
|
||||
if daemon.UptimeSeconds <= 0 {
|
||||
t.Errorf("invalid uptime: %f", daemon.UptimeSeconds)
|
||||
}
|
||||
if daemon.WorkspacePath != tmpDir {
|
||||
t.Errorf("wrong workspace: expected %s, got %s", tmpDir, daemon.WorkspacePath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindDaemonByWorkspace(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
workspace := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(workspace, 0755)
|
||||
|
||||
// Start daemon
|
||||
dbPath := filepath.Join(workspace, "test.db")
|
||||
socketPath := filepath.Join(workspace, "bd.sock")
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create storage: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
server := rpc.NewServer(socketPath, store, tmpDir, dbPath)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go server.Start(ctx)
|
||||
<-server.WaitReady()
|
||||
defer server.Stop()
|
||||
|
||||
// Find daemon by workspace
|
||||
daemon, err := FindDaemonByWorkspace(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to find daemon: %v", err)
|
||||
}
|
||||
if daemon == nil {
|
||||
t.Fatal("daemon not found")
|
||||
}
|
||||
if !daemon.Alive {
|
||||
t.Errorf("daemon not alive: %s", daemon.Error)
|
||||
}
|
||||
if daemon.WorkspacePath != tmpDir {
|
||||
t.Errorf("wrong workspace: expected %s, got %s", tmpDir, daemon.WorkspacePath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create stale socket file
|
||||
stalePath := filepath.Join(tmpDir, "stale.sock")
|
||||
if err := os.WriteFile(stalePath, []byte{}, 0644); err != nil {
|
||||
t.Fatalf("failed to create stale socket: %v", err)
|
||||
}
|
||||
|
||||
daemons := []DaemonInfo{
|
||||
{
|
||||
SocketPath: stalePath,
|
||||
Alive: false,
|
||||
},
|
||||
}
|
||||
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 1 {
|
||||
t.Errorf("expected 1 cleaned, got %d", cleaned)
|
||||
}
|
||||
|
||||
// Verify socket was removed
|
||||
if _, err := os.Stat(stalePath); !os.IsNotExist(err) {
|
||||
t.Error("stale socket still exists")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkWithDepth(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create test directory structure
|
||||
// tmpDir/
|
||||
// file1.txt
|
||||
// dir1/
|
||||
// file2.txt
|
||||
// dir2/
|
||||
// file3.txt
|
||||
// dir3/
|
||||
// file4.txt
|
||||
|
||||
os.WriteFile(filepath.Join(tmpDir, "file1.txt"), []byte("test"), 0644)
|
||||
os.MkdirAll(filepath.Join(tmpDir, "dir1", "dir2", "dir3"), 0755)
|
||||
os.WriteFile(filepath.Join(tmpDir, "dir1", "file2.txt"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, "dir1", "dir2", "file3.txt"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, "dir1", "dir2", "dir3", "file4.txt"), []byte("test"), 0644)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
maxDepth int
|
||||
wantFiles int
|
||||
}{
|
||||
{"depth 0", 0, 1}, // Only file1.txt
|
||||
{"depth 1", 1, 2}, // file1.txt, file2.txt
|
||||
{"depth 2", 2, 3}, // file1.txt, file2.txt, file3.txt
|
||||
{"depth 3", 3, 4}, // All files
|
||||
{"depth 10", 10, 4}, // All files (max depth not reached)
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var foundFiles []string
|
||||
fn := func(path string, info os.FileInfo) error {
|
||||
if !info.IsDir() {
|
||||
foundFiles = append(foundFiles, path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := walkWithDepth(tmpDir, 0, tt.maxDepth, fn)
|
||||
if err != nil {
|
||||
t.Fatalf("walkWithDepth failed: %v", err)
|
||||
}
|
||||
|
||||
if len(foundFiles) != tt.wantFiles {
|
||||
t.Errorf("Expected %d files, got %d: %v", tt.wantFiles, len(foundFiles), foundFiles)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkWithDepth_SkipsHiddenDirs(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create hidden directories (should skip)
|
||||
os.MkdirAll(filepath.Join(tmpDir, ".git"), 0755)
|
||||
os.MkdirAll(filepath.Join(tmpDir, ".hidden"), 0755)
|
||||
os.MkdirAll(filepath.Join(tmpDir, "node_modules"), 0755)
|
||||
os.MkdirAll(filepath.Join(tmpDir, "vendor"), 0755)
|
||||
|
||||
// Create .beads directory (should NOT skip)
|
||||
os.MkdirAll(filepath.Join(tmpDir, ".beads"), 0755)
|
||||
|
||||
// Add files
|
||||
os.WriteFile(filepath.Join(tmpDir, ".git", "config"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, ".hidden", "secret"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, "node_modules", "package.json"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, ".beads", "beads.db"), []byte("test"), 0644)
|
||||
|
||||
var foundFiles []string
|
||||
fn := func(path string, info os.FileInfo) error {
|
||||
if !info.IsDir() {
|
||||
foundFiles = append(foundFiles, filepath.Base(path))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := walkWithDepth(tmpDir, 0, 5, fn)
|
||||
if err != nil {
|
||||
t.Fatalf("walkWithDepth failed: %v", err)
|
||||
}
|
||||
|
||||
// Should only find beads.db from .beads directory
|
||||
if len(foundFiles) != 1 || foundFiles[0] != "beads.db" {
|
||||
t.Errorf("Expected only beads.db, got: %v", foundFiles)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemons_Registry(t *testing.T) {
|
||||
// Test registry-based discovery (no search roots)
|
||||
daemons, err := DiscoverDaemons(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("DiscoverDaemons failed: %v", err)
|
||||
}
|
||||
|
||||
// Should return empty list (no daemons running in test environment)
|
||||
// Just verify it doesn't error
|
||||
_ = daemons
|
||||
}
|
||||
|
||||
func TestDiscoverDaemons_Legacy(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow daemon discovery test in short mode")
|
||||
}
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
|
||||
// Start a test daemon
|
||||
dbPath := filepath.Join(beadsDir, "test.db")
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
store, err := sqlite.New(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create storage: %v", err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
server := rpc.NewServer(socketPath, store, tmpDir, dbPath)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go server.Start(ctx)
|
||||
<-server.WaitReady()
|
||||
defer server.Stop()
|
||||
|
||||
// Test legacy discovery with explicit search roots
|
||||
daemons, err := DiscoverDaemons([]string{tmpDir})
|
||||
if err != nil {
|
||||
t.Fatalf("DiscoverDaemons failed: %v", err)
|
||||
}
|
||||
|
||||
if len(daemons) != 1 {
|
||||
t.Fatalf("Expected 1 daemon, got %d", len(daemons))
|
||||
}
|
||||
|
||||
daemon := daemons[0]
|
||||
if !daemon.Alive {
|
||||
t.Errorf("Daemon not alive: %s", daemon.Error)
|
||||
}
|
||||
if daemon.WorkspacePath != tmpDir {
|
||||
t.Errorf("Wrong workspace path: expected %s, got %s", tmpDir, daemon.WorkspacePath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDaemonErrorFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
|
||||
// Test 1: No error file exists
|
||||
errMsg := checkDaemonErrorFile(socketPath)
|
||||
if errMsg != "" {
|
||||
t.Errorf("Expected empty error message, got: %s", errMsg)
|
||||
}
|
||||
|
||||
// Test 2: Error file exists with content
|
||||
errorFilePath := filepath.Join(beadsDir, "daemon-error")
|
||||
expectedError := "failed to start: database locked"
|
||||
os.WriteFile(errorFilePath, []byte(expectedError), 0644)
|
||||
|
||||
errMsg = checkDaemonErrorFile(socketPath)
|
||||
if errMsg != expectedError {
|
||||
t.Errorf("Expected error message %q, got %q", expectedError, errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStopDaemon_NotAlive(t *testing.T) {
|
||||
daemon := DaemonInfo{
|
||||
Alive: false,
|
||||
}
|
||||
|
||||
err := StopDaemon(daemon)
|
||||
if err == nil {
|
||||
t.Error("Expected error when stopping non-alive daemon")
|
||||
}
|
||||
if err.Error() != "daemon is not running" {
|
||||
t.Errorf("Unexpected error message: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllDaemons_Empty(t *testing.T) {
|
||||
results := KillAllDaemons([]DaemonInfo{}, false)
|
||||
if results.Stopped != 0 || results.Failed != 0 {
|
||||
t.Errorf("Expected 0 stopped and 0 failed, got %d stopped and %d failed", results.Stopped, results.Failed)
|
||||
}
|
||||
if len(results.Failures) != 0 {
|
||||
t.Errorf("Expected empty failures list, got %d failures", len(results.Failures))
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllDaemons_NotAlive(t *testing.T) {
|
||||
daemons := []DaemonInfo{
|
||||
{Alive: false, WorkspacePath: "/test", PID: 12345},
|
||||
}
|
||||
|
||||
results := KillAllDaemons(daemons, false)
|
||||
if results.Stopped != 0 || results.Failed != 0 {
|
||||
t.Errorf("Expected 0 stopped and 0 failed for dead daemon, got %d stopped and %d failed", results.Stopped, results.Failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindDaemonByWorkspace_NotFound(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Try to find daemon in directory without any daemon
|
||||
daemon, err := FindDaemonByWorkspace(tmpDir)
|
||||
if err == nil {
|
||||
t.Error("Expected error when daemon not found")
|
||||
}
|
||||
if daemon != nil {
|
||||
t.Error("Expected nil daemon when not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemon_SocketMissing(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
socketPath := filepath.Join(tmpDir, "nonexistent.sock")
|
||||
|
||||
// Try to discover daemon on non-existent socket
|
||||
daemon := discoverDaemon(socketPath)
|
||||
if daemon.Alive {
|
||||
t.Error("Expected daemon to not be alive for missing socket")
|
||||
}
|
||||
if daemon.SocketPath != socketPath {
|
||||
t.Errorf("Expected socket path %s, got %s", socketPath, daemon.SocketPath)
|
||||
}
|
||||
if daemon.Error == "" {
|
||||
t.Error("Expected error message when daemon not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets_AlreadyRemoved(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create stale daemon with non-existent socket
|
||||
stalePath := filepath.Join(tmpDir, "nonexistent.sock")
|
||||
|
||||
daemons := []DaemonInfo{
|
||||
{
|
||||
SocketPath: stalePath,
|
||||
Alive: false,
|
||||
},
|
||||
}
|
||||
|
||||
// Should succeed even if socket doesn't exist
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 0 {
|
||||
t.Errorf("expected 0 cleaned (socket didn't exist), got %d", cleaned)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets_AliveDaemon(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
socketPath := filepath.Join(tmpDir, "alive.sock")
|
||||
|
||||
daemons := []DaemonInfo{
|
||||
{
|
||||
SocketPath: socketPath,
|
||||
Alive: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Should not remove socket for alive daemon
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 0 {
|
||||
t.Errorf("expected 0 cleaned (daemon alive), got %d", cleaned)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,815 +0,0 @@
|
|||
package daemon
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Unit tests for discovery.go that run without the integration tag
|
||||
// These tests focus on pure functions and edge cases that don't require real daemons
|
||||
|
||||
func TestWalkWithDepth_Basic(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create test directory structure
|
||||
// tmpDir/
|
||||
// file1.txt
|
||||
// dir1/
|
||||
// file2.txt
|
||||
// dir2/
|
||||
// file3.txt
|
||||
// dir3/
|
||||
// file4.txt
|
||||
|
||||
os.WriteFile(filepath.Join(tmpDir, "file1.txt"), []byte("test"), 0644)
|
||||
os.MkdirAll(filepath.Join(tmpDir, "dir1", "dir2", "dir3"), 0755)
|
||||
os.WriteFile(filepath.Join(tmpDir, "dir1", "file2.txt"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, "dir1", "dir2", "file3.txt"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, "dir1", "dir2", "dir3", "file4.txt"), []byte("test"), 0644)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
maxDepth int
|
||||
wantFiles int
|
||||
}{
|
||||
{"depth 0", 0, 1}, // Only file1.txt
|
||||
{"depth 1", 1, 2}, // file1.txt, file2.txt
|
||||
{"depth 2", 2, 3}, // file1.txt, file2.txt, file3.txt
|
||||
{"depth 3", 3, 4}, // All files
|
||||
{"depth 10", 10, 4}, // All files (max depth not reached)
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var foundFiles []string
|
||||
fn := func(path string, info os.FileInfo) error {
|
||||
if !info.IsDir() {
|
||||
foundFiles = append(foundFiles, path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := walkWithDepth(tmpDir, 0, tt.maxDepth, fn)
|
||||
if err != nil {
|
||||
t.Fatalf("walkWithDepth failed: %v", err)
|
||||
}
|
||||
|
||||
if len(foundFiles) != tt.wantFiles {
|
||||
t.Errorf("Expected %d files, got %d: %v", tt.wantFiles, len(foundFiles), foundFiles)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkWithDepth_SkipsHiddenDirs(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create hidden directories (should skip)
|
||||
os.MkdirAll(filepath.Join(tmpDir, ".git"), 0755)
|
||||
os.MkdirAll(filepath.Join(tmpDir, ".hidden"), 0755)
|
||||
os.MkdirAll(filepath.Join(tmpDir, "node_modules"), 0755)
|
||||
os.MkdirAll(filepath.Join(tmpDir, "vendor"), 0755)
|
||||
|
||||
// Create .beads directory (should NOT skip)
|
||||
os.MkdirAll(filepath.Join(tmpDir, ".beads"), 0755)
|
||||
|
||||
// Add files
|
||||
os.WriteFile(filepath.Join(tmpDir, ".git", "config"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, ".hidden", "secret"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, "node_modules", "package.json"), []byte("test"), 0644)
|
||||
os.WriteFile(filepath.Join(tmpDir, ".beads", "beads.db"), []byte("test"), 0644)
|
||||
|
||||
var foundFiles []string
|
||||
fn := func(path string, info os.FileInfo) error {
|
||||
if !info.IsDir() {
|
||||
foundFiles = append(foundFiles, filepath.Base(path))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err := walkWithDepth(tmpDir, 0, 5, fn)
|
||||
if err != nil {
|
||||
t.Fatalf("walkWithDepth failed: %v", err)
|
||||
}
|
||||
|
||||
// Should only find beads.db from .beads directory
|
||||
if len(foundFiles) != 1 || foundFiles[0] != "beads.db" {
|
||||
t.Errorf("Expected only beads.db, got: %v", foundFiles)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkWithDepth_UnreadableDir(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Try to walk a non-existent directory - should not error, just return
|
||||
err := walkWithDepth(filepath.Join(tmpDir, "nonexistent"), 0, 5, func(path string, info os.FileInfo) error {
|
||||
t.Error("should not be called for non-existent directory")
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("walkWithDepth should handle unreadable directories gracefully: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkWithDepth_CallbackError(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
os.WriteFile(filepath.Join(tmpDir, "file.txt"), []byte("test"), 0644)
|
||||
|
||||
callbackErr := os.ErrInvalid
|
||||
fn := func(path string, info os.FileInfo) error {
|
||||
return callbackErr
|
||||
}
|
||||
|
||||
err := walkWithDepth(tmpDir, 0, 5, fn)
|
||||
if err != callbackErr {
|
||||
t.Errorf("Expected callback error to propagate, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkWithDepth_MaxDepthExceeded(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create deep nesting
|
||||
os.MkdirAll(filepath.Join(tmpDir, "a", "b", "c", "d", "e"), 0755)
|
||||
os.WriteFile(filepath.Join(tmpDir, "a", "b", "c", "d", "e", "deep.txt"), []byte("test"), 0644)
|
||||
|
||||
// Start at currentDepth > maxDepth should immediately return
|
||||
var foundFiles []string
|
||||
fn := func(path string, info os.FileInfo) error {
|
||||
foundFiles = append(foundFiles, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
err := walkWithDepth(tmpDir, 10, 5, fn)
|
||||
if err != nil {
|
||||
t.Fatalf("walkWithDepth failed: %v", err)
|
||||
}
|
||||
|
||||
if len(foundFiles) != 0 {
|
||||
t.Errorf("Expected 0 files when currentDepth > maxDepth, got: %v", foundFiles)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDaemonErrorFile_NoFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
|
||||
// Test with no error file
|
||||
errMsg := checkDaemonErrorFile(socketPath)
|
||||
if errMsg != "" {
|
||||
t.Errorf("Expected empty error message, got: %s", errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDaemonErrorFile_WithContent(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
|
||||
// Create error file
|
||||
errorFilePath := filepath.Join(beadsDir, "daemon-error")
|
||||
expectedError := "failed to start: database locked"
|
||||
os.WriteFile(errorFilePath, []byte(expectedError), 0644)
|
||||
|
||||
errMsg := checkDaemonErrorFile(socketPath)
|
||||
if errMsg != expectedError {
|
||||
t.Errorf("Expected error message %q, got %q", expectedError, errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDaemonErrorFile_EmptyFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
|
||||
// Create empty error file
|
||||
errorFilePath := filepath.Join(beadsDir, "daemon-error")
|
||||
os.WriteFile(errorFilePath, []byte{}, 0644)
|
||||
|
||||
errMsg := checkDaemonErrorFile(socketPath)
|
||||
if errMsg != "" {
|
||||
t.Errorf("Expected empty message for empty file, got: %s", errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets_Basic(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create stale socket file
|
||||
stalePath := filepath.Join(tmpDir, "stale.sock")
|
||||
if err := os.WriteFile(stalePath, []byte{}, 0644); err != nil {
|
||||
t.Fatalf("failed to create stale socket: %v", err)
|
||||
}
|
||||
|
||||
daemons := []DaemonInfo{
|
||||
{
|
||||
SocketPath: stalePath,
|
||||
Alive: false,
|
||||
},
|
||||
}
|
||||
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 1 {
|
||||
t.Errorf("expected 1 cleaned, got %d", cleaned)
|
||||
}
|
||||
|
||||
// Verify socket was removed
|
||||
if _, err := os.Stat(stalePath); !os.IsNotExist(err) {
|
||||
t.Error("stale socket still exists")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets_AlreadyRemoved(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Stale daemon with non-existent socket
|
||||
stalePath := filepath.Join(tmpDir, "nonexistent.sock")
|
||||
|
||||
daemons := []DaemonInfo{
|
||||
{
|
||||
SocketPath: stalePath,
|
||||
Alive: false,
|
||||
},
|
||||
}
|
||||
|
||||
// Should succeed even if socket doesn't exist
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 0 {
|
||||
t.Errorf("expected 0 cleaned (socket didn't exist), got %d", cleaned)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets_AliveDaemon(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
socketPath := filepath.Join(tmpDir, "alive.sock")
|
||||
os.WriteFile(socketPath, []byte{}, 0644)
|
||||
|
||||
daemons := []DaemonInfo{
|
||||
{
|
||||
SocketPath: socketPath,
|
||||
Alive: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Should not remove socket for alive daemon
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 0 {
|
||||
t.Errorf("expected 0 cleaned (daemon alive), got %d", cleaned)
|
||||
}
|
||||
|
||||
// Verify socket still exists
|
||||
if _, err := os.Stat(socketPath); os.IsNotExist(err) {
|
||||
t.Error("socket should not have been removed for alive daemon")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets_WithPIDFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create stale socket and PID file
|
||||
stalePath := filepath.Join(tmpDir, "bd.sock")
|
||||
pidPath := filepath.Join(tmpDir, "daemon.pid")
|
||||
os.WriteFile(stalePath, []byte{}, 0644)
|
||||
os.WriteFile(pidPath, []byte("12345"), 0644)
|
||||
|
||||
daemons := []DaemonInfo{
|
||||
{
|
||||
SocketPath: stalePath,
|
||||
Alive: false,
|
||||
},
|
||||
}
|
||||
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 1 {
|
||||
t.Errorf("expected 1 cleaned, got %d", cleaned)
|
||||
}
|
||||
|
||||
// Verify both socket and PID file were removed
|
||||
if _, err := os.Stat(stalePath); !os.IsNotExist(err) {
|
||||
t.Error("socket should be removed")
|
||||
}
|
||||
if _, err := os.Stat(pidPath); !os.IsNotExist(err) {
|
||||
t.Error("PID file should be removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets_EmptySocket(t *testing.T) {
|
||||
daemons := []DaemonInfo{
|
||||
{
|
||||
SocketPath: "",
|
||||
Alive: false,
|
||||
},
|
||||
}
|
||||
|
||||
// Should handle empty socket path gracefully
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 0 {
|
||||
t.Errorf("expected 0 cleaned (empty socket path), got %d", cleaned)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStopDaemon_NotAlive(t *testing.T) {
|
||||
daemon := DaemonInfo{
|
||||
Alive: false,
|
||||
}
|
||||
|
||||
err := StopDaemon(daemon)
|
||||
if err == nil {
|
||||
t.Error("Expected error when stopping non-alive daemon")
|
||||
}
|
||||
if err.Error() != "daemon is not running" {
|
||||
t.Errorf("Unexpected error message: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllDaemons_Empty(t *testing.T) {
|
||||
results := KillAllDaemons([]DaemonInfo{}, false)
|
||||
if results.Stopped != 0 || results.Failed != 0 {
|
||||
t.Errorf("Expected 0 stopped and 0 failed, got %d stopped and %d failed", results.Stopped, results.Failed)
|
||||
}
|
||||
if len(results.Failures) != 0 {
|
||||
t.Errorf("Expected empty failures list, got %d failures", len(results.Failures))
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllDaemons_NotAlive(t *testing.T) {
|
||||
daemons := []DaemonInfo{
|
||||
{Alive: false, WorkspacePath: "/test", PID: 12345},
|
||||
}
|
||||
|
||||
results := KillAllDaemons(daemons, false)
|
||||
if results.Stopped != 0 || results.Failed != 0 {
|
||||
t.Errorf("Expected 0 stopped and 0 failed for dead daemon, got %d stopped and %d failed", results.Stopped, results.Failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllDaemons_MultipleNotAlive(t *testing.T) {
|
||||
daemons := []DaemonInfo{
|
||||
{Alive: false, WorkspacePath: "/test1", PID: 12345},
|
||||
{Alive: false, WorkspacePath: "/test2", PID: 12346},
|
||||
{Alive: false, WorkspacePath: "/test3", PID: 12347},
|
||||
}
|
||||
|
||||
results := KillAllDaemons(daemons, false)
|
||||
if results.Stopped != 0 || results.Failed != 0 {
|
||||
t.Errorf("Expected 0 stopped and 0 failed for dead daemons, got %d stopped and %d failed", results.Stopped, results.Failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemon_SocketMissing(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
socketPath := filepath.Join(tmpDir, "nonexistent.sock")
|
||||
|
||||
// Try to discover daemon on non-existent socket
|
||||
daemon := discoverDaemon(socketPath)
|
||||
if daemon.Alive {
|
||||
t.Error("Expected daemon to not be alive for missing socket")
|
||||
}
|
||||
if daemon.SocketPath != socketPath {
|
||||
t.Errorf("Expected socket path %s, got %s", socketPath, daemon.SocketPath)
|
||||
}
|
||||
if daemon.Error == "" {
|
||||
t.Error("Expected error message when daemon not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemon_SocketExistsButNotListening(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
|
||||
// Create a regular file (not a socket)
|
||||
os.WriteFile(socketPath, []byte{}, 0644)
|
||||
|
||||
daemon := discoverDaemon(socketPath)
|
||||
if daemon.Alive {
|
||||
t.Error("Expected daemon to not be alive for non-socket file")
|
||||
}
|
||||
if daemon.Error == "" {
|
||||
t.Error("Expected error message for failed connection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemon_WithErrorFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
|
||||
// Create error file but no socket
|
||||
errorFilePath := filepath.Join(beadsDir, "daemon-error")
|
||||
expectedError := "startup failed: port in use"
|
||||
os.WriteFile(errorFilePath, []byte(expectedError), 0644)
|
||||
|
||||
daemon := discoverDaemon(socketPath)
|
||||
if daemon.Alive {
|
||||
t.Error("Expected daemon to not be alive")
|
||||
}
|
||||
if daemon.Error != expectedError {
|
||||
t.Errorf("Expected error %q, got %q", expectedError, daemon.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonInfoStruct(t *testing.T) {
|
||||
// Verify DaemonInfo struct fields
|
||||
info := DaemonInfo{
|
||||
WorkspacePath: "/test/workspace",
|
||||
DatabasePath: "/test/workspace/.beads/beads.db",
|
||||
SocketPath: "/test/workspace/.beads/bd.sock",
|
||||
PID: 12345,
|
||||
Version: "0.19.0",
|
||||
UptimeSeconds: 3600.5,
|
||||
LastActivityTime: "2024-01-01T12:00:00Z",
|
||||
ExclusiveLockActive: true,
|
||||
ExclusiveLockHolder: "user@host",
|
||||
Alive: true,
|
||||
Error: "",
|
||||
}
|
||||
|
||||
if info.WorkspacePath != "/test/workspace" {
|
||||
t.Errorf("WorkspacePath mismatch")
|
||||
}
|
||||
if info.PID != 12345 {
|
||||
t.Errorf("PID mismatch")
|
||||
}
|
||||
if info.Version != "0.19.0" {
|
||||
t.Errorf("Version mismatch")
|
||||
}
|
||||
if info.UptimeSeconds != 3600.5 {
|
||||
t.Errorf("UptimeSeconds mismatch")
|
||||
}
|
||||
if !info.Alive {
|
||||
t.Errorf("Alive mismatch")
|
||||
}
|
||||
if !info.ExclusiveLockActive {
|
||||
t.Errorf("ExclusiveLockActive mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllFailureStruct(t *testing.T) {
|
||||
failure := KillAllFailure{
|
||||
Workspace: "/test",
|
||||
PID: 12345,
|
||||
Error: "connection refused",
|
||||
}
|
||||
|
||||
if failure.Workspace != "/test" {
|
||||
t.Errorf("Workspace mismatch")
|
||||
}
|
||||
if failure.PID != 12345 {
|
||||
t.Errorf("PID mismatch")
|
||||
}
|
||||
if failure.Error != "connection refused" {
|
||||
t.Errorf("Error mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllResultsStruct(t *testing.T) {
|
||||
results := KillAllResults{
|
||||
Stopped: 5,
|
||||
Failed: 2,
|
||||
Failures: []KillAllFailure{
|
||||
{Workspace: "/test1", PID: 111, Error: "error1"},
|
||||
{Workspace: "/test2", PID: 222, Error: "error2"},
|
||||
},
|
||||
}
|
||||
|
||||
if results.Stopped != 5 {
|
||||
t.Errorf("Stopped mismatch")
|
||||
}
|
||||
if results.Failed != 2 {
|
||||
t.Errorf("Failed mismatch")
|
||||
}
|
||||
if len(results.Failures) != 2 {
|
||||
t.Errorf("Failures count mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindDaemonByWorkspace_NotFound(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Try to find daemon in directory without any daemon
|
||||
daemon, err := FindDaemonByWorkspace(tmpDir)
|
||||
if err == nil {
|
||||
t.Error("Expected error when daemon not found")
|
||||
}
|
||||
if daemon != nil {
|
||||
t.Error("Expected nil daemon when not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindBeadsDirForWorkspace_RegularRepo(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Test with a regular directory (no git repo)
|
||||
beadsDir := findBeadsDirForWorkspace(tmpDir)
|
||||
|
||||
expected := filepath.Join(tmpDir, ".beads")
|
||||
if beadsDir != expected {
|
||||
t.Errorf("Expected %s, got %s", expected, beadsDir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindBeadsDirForWorkspace_NonexistentDir(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
nonexistent := filepath.Join(tmpDir, "nonexistent")
|
||||
|
||||
// Should fall back gracefully
|
||||
beadsDir := findBeadsDirForWorkspace(nonexistent)
|
||||
|
||||
expected := filepath.Join(nonexistent, ".beads")
|
||||
if beadsDir != expected {
|
||||
t.Errorf("Expected %s, got %s", expected, beadsDir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemons_Registry(t *testing.T) {
|
||||
// Test registry-based discovery (no search roots)
|
||||
daemons, err := DiscoverDaemons(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("DiscoverDaemons failed: %v", err)
|
||||
}
|
||||
|
||||
// Just verify it doesn't error - actual daemons depend on environment
|
||||
_ = daemons
|
||||
}
|
||||
|
||||
func TestDiscoverDaemons_EmptySearchRoots(t *testing.T) {
|
||||
// Empty slice should use registry
|
||||
daemons, err := DiscoverDaemons([]string{})
|
||||
if err != nil {
|
||||
t.Fatalf("DiscoverDaemons failed: %v", err)
|
||||
}
|
||||
// Just verify no error
|
||||
_ = daemons
|
||||
}
|
||||
|
||||
func TestDiscoverDaemons_LegacyWithTempDir(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping slow daemon discovery test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create a fake .beads directory (no daemon running)
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
|
||||
// Test legacy discovery with explicit search root
|
||||
daemons, err := DiscoverDaemons([]string{tmpDir})
|
||||
if err != nil {
|
||||
t.Fatalf("DiscoverDaemons failed: %v", err)
|
||||
}
|
||||
|
||||
// Should find no alive daemons
|
||||
for _, d := range daemons {
|
||||
if d.Alive {
|
||||
t.Errorf("Found unexpected alive daemon: %+v", d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemonsLegacy_WithSocketFile(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping daemon discovery test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
|
||||
// Create a socket file (fake, not real socket)
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
os.WriteFile(socketPath, []byte{}, 0644)
|
||||
|
||||
// Discovery should find it but report not alive
|
||||
daemons, err := discoverDaemonsLegacy([]string{tmpDir})
|
||||
if err != nil {
|
||||
t.Fatalf("discoverDaemonsLegacy failed: %v", err)
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, d := range daemons {
|
||||
if d.SocketPath == socketPath {
|
||||
found = true
|
||||
if d.Alive {
|
||||
t.Error("Expected daemon not to be alive for fake socket")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("Expected to find the socket file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemonsLegacy_MultipleRoots(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping daemon discovery test in short mode")
|
||||
}
|
||||
|
||||
tmpDir1 := t.TempDir()
|
||||
tmpDir2 := t.TempDir()
|
||||
|
||||
beadsDir1 := filepath.Join(tmpDir1, ".beads")
|
||||
beadsDir2 := filepath.Join(tmpDir2, ".beads")
|
||||
os.MkdirAll(beadsDir1, 0755)
|
||||
os.MkdirAll(beadsDir2, 0755)
|
||||
|
||||
// Create socket files in both
|
||||
os.WriteFile(filepath.Join(beadsDir1, "bd.sock"), []byte{}, 0644)
|
||||
os.WriteFile(filepath.Join(beadsDir2, "bd.sock"), []byte{}, 0644)
|
||||
|
||||
daemons, err := discoverDaemonsLegacy([]string{tmpDir1, tmpDir2})
|
||||
if err != nil {
|
||||
t.Fatalf("discoverDaemonsLegacy failed: %v", err)
|
||||
}
|
||||
|
||||
// Should find both sockets
|
||||
if len(daemons) < 2 {
|
||||
t.Errorf("Expected at least 2 daemons, got %d", len(daemons))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemonsLegacy_DuplicateSockets(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping daemon discovery test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
os.WriteFile(socketPath, []byte{}, 0644)
|
||||
|
||||
// Search same root twice - should deduplicate
|
||||
daemons, err := discoverDaemonsLegacy([]string{tmpDir, tmpDir})
|
||||
if err != nil {
|
||||
t.Fatalf("discoverDaemonsLegacy failed: %v", err)
|
||||
}
|
||||
|
||||
// Count unique socket paths
|
||||
count := 0
|
||||
for _, d := range daemons {
|
||||
if d.SocketPath == socketPath {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("Expected 1 unique socket, got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverDaemonsLegacy_NonSocketFile(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping daemon discovery test in short mode")
|
||||
}
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
|
||||
// Create files that are NOT bd.sock
|
||||
os.WriteFile(filepath.Join(beadsDir, "beads.db"), []byte{}, 0644)
|
||||
os.WriteFile(filepath.Join(beadsDir, "other.sock"), []byte{}, 0644)
|
||||
|
||||
daemons, err := discoverDaemonsLegacy([]string{tmpDir})
|
||||
if err != nil {
|
||||
t.Fatalf("discoverDaemonsLegacy failed: %v", err)
|
||||
}
|
||||
|
||||
// Should not find any sockets
|
||||
for _, d := range daemons {
|
||||
if filepath.Base(d.SocketPath) != "bd.sock" {
|
||||
t.Errorf("Found non-bd.sock file: %s", d.SocketPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindDaemonByWorkspace_WithSocketFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
beadsDir := filepath.Join(tmpDir, ".beads")
|
||||
os.MkdirAll(beadsDir, 0755)
|
||||
|
||||
// Create a fake socket file
|
||||
socketPath := filepath.Join(beadsDir, "bd.sock")
|
||||
os.WriteFile(socketPath, []byte{}, 0644)
|
||||
|
||||
// Should not find alive daemon (fake socket)
|
||||
daemon, err := FindDaemonByWorkspace(tmpDir)
|
||||
if err == nil {
|
||||
t.Error("Expected error for fake socket")
|
||||
}
|
||||
if daemon != nil && daemon.Alive {
|
||||
t.Error("Expected daemon not to be alive")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStopDaemon_AliveButNoSocket(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
socketPath := filepath.Join(tmpDir, "nonexistent.sock")
|
||||
|
||||
daemon := DaemonInfo{
|
||||
Alive: true,
|
||||
SocketPath: socketPath,
|
||||
PID: 99999, // Non-existent PID
|
||||
}
|
||||
|
||||
// Should fail when trying to stop (can't connect)
|
||||
err := StopDaemon(daemon)
|
||||
// The error is expected since there's no real daemon
|
||||
if err == nil {
|
||||
// If no error, we likely couldn't kill the non-existent process
|
||||
// which is fine - the test validates we tried
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllDaemons_MixedAlive(t *testing.T) {
|
||||
daemons := []DaemonInfo{
|
||||
{Alive: false, WorkspacePath: "/test1", PID: 12345},
|
||||
{Alive: true, WorkspacePath: "/test2", PID: 99999, SocketPath: "/nonexistent.sock"},
|
||||
{Alive: false, WorkspacePath: "/test3", PID: 12346},
|
||||
}
|
||||
|
||||
// Try without force - the alive daemon with non-existent PID will fail
|
||||
results := KillAllDaemons(daemons, false)
|
||||
|
||||
// Only 1 alive daemon was attempted, and it likely failed
|
||||
// Dead daemons are skipped
|
||||
if results.Stopped+results.Failed != 1 {
|
||||
t.Errorf("Expected 1 total attempt (1 alive daemon), got %d stopped + %d failed", results.Stopped, results.Failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKillAllDaemons_WithForce(t *testing.T) {
|
||||
daemons := []DaemonInfo{
|
||||
{Alive: true, WorkspacePath: "/test", PID: 99999, SocketPath: "/nonexistent.sock"},
|
||||
}
|
||||
|
||||
// Try with force - should try both regular kill and force kill
|
||||
results := KillAllDaemons(daemons, true)
|
||||
|
||||
// Even with force, non-existent PID will fail
|
||||
// Just verify the results struct is populated correctly
|
||||
if results.Stopped+results.Failed != 1 {
|
||||
t.Errorf("Expected 1 total attempt, got %d stopped + %d failed", results.Stopped, results.Failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupStaleSockets_Multiple(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
// Create multiple stale sockets
|
||||
sock1 := filepath.Join(tmpDir, "sock1.sock")
|
||||
sock2 := filepath.Join(tmpDir, "sock2.sock")
|
||||
sock3 := filepath.Join(tmpDir, "sock3.sock")
|
||||
os.WriteFile(sock1, []byte{}, 0644)
|
||||
os.WriteFile(sock2, []byte{}, 0644)
|
||||
os.WriteFile(sock3, []byte{}, 0644)
|
||||
|
||||
daemons := []DaemonInfo{
|
||||
{SocketPath: sock1, Alive: false},
|
||||
{SocketPath: sock2, Alive: false},
|
||||
{SocketPath: sock3, Alive: true}, // This one is alive, should not be cleaned
|
||||
}
|
||||
|
||||
cleaned, err := CleanupStaleSockets(daemons)
|
||||
if err != nil {
|
||||
t.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
if cleaned != 2 {
|
||||
t.Errorf("expected 2 cleaned, got %d", cleaned)
|
||||
}
|
||||
|
||||
// Verify sock1 and sock2 removed, sock3 remains
|
||||
if _, err := os.Stat(sock1); !os.IsNotExist(err) {
|
||||
t.Error("sock1 should be removed")
|
||||
}
|
||||
if _, err := os.Stat(sock2); !os.IsNotExist(err) {
|
||||
t.Error("sock2 should be removed")
|
||||
}
|
||||
if _, err := os.Stat(sock3); os.IsNotExist(err) {
|
||||
t.Error("sock3 should remain (alive daemon)")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
//go:build unix
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func killProcess(pid int) error {
|
||||
if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {
|
||||
return fmt.Errorf("failed to send SIGTERM to PID %d: %w", pid, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func forceKillProcess(pid int) error {
|
||||
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil {
|
||||
return fmt.Errorf("failed to send SIGKILL to PID %d: %w", pid, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isProcessAlive(pid int) bool {
|
||||
// On Unix, sending signal 0 checks if process exists
|
||||
err := syscall.Kill(pid, 0)
|
||||
return err == nil
|
||||
}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
//go:build js && wasm
|
||||
|
||||
package daemon
|
||||
|
||||
import "fmt"
|
||||
|
||||
// WASM doesn't support process management, so these are stubs
|
||||
// Daemon mode is not supported in WASM environments
|
||||
|
||||
func killProcess(pid int) error {
|
||||
return fmt.Errorf("daemon operations not supported in WASM")
|
||||
}
|
||||
|
||||
func forceKillProcess(pid int) error {
|
||||
return fmt.Errorf("daemon operations not supported in WASM")
|
||||
}
|
||||
|
||||
func isProcessAlive(pid int) bool {
|
||||
return false
|
||||
}
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
//go:build windows
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func killProcess(pid int) error {
|
||||
// On Windows, there's no SIGTERM equivalent for console processes.
|
||||
// The graceful RPC shutdown is already attempted before this function is called.
|
||||
// Use os.Process.Kill() which calls TerminateProcess - the reliable Windows API.
|
||||
proc, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to find process %d: %w", pid, err)
|
||||
}
|
||||
if err := proc.Kill(); err != nil {
|
||||
return fmt.Errorf("failed to kill PID %d: %w", pid, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func forceKillProcess(pid int) error {
|
||||
// On Windows, Kill() already uses TerminateProcess which is forceful
|
||||
return killProcess(pid)
|
||||
}
|
||||
|
||||
func isProcessAlive(pid int) bool {
|
||||
// On Windows, FindProcess always succeeds, but we can check if the process
|
||||
// is actually running by trying to get its exit code via Wait with WNOHANG.
|
||||
// A simpler approach: try to open the process and check for errors.
|
||||
proc, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// On Windows, we need to actually check if the process exists.
|
||||
// Signal(nil) on Windows returns an error if process doesn't exist.
|
||||
// However, os.Process.Signal is not implemented on Windows.
|
||||
// Use a different approach: try to kill with signal 0 equivalent.
|
||||
// Actually, on Windows we can check via process handle opening.
|
||||
// The simplest reliable way is to use tasklist.
|
||||
//
|
||||
// Note: os.FindProcess on Windows always succeeds regardless of whether
|
||||
// the process exists. We need to actually try to interact with it.
|
||||
// Using Release() and checking the error doesn't work either.
|
||||
//
|
||||
// Fall back to tasklist for reliability.
|
||||
return isProcessAliveTasklist(pid, proc)
|
||||
}
|
||||
|
||||
func isProcessAliveTasklist(pid int, _ *os.Process) bool {
|
||||
// Use Windows API via tasklist to check if process exists
|
||||
// This is the most reliable method on Windows
|
||||
cmd := exec.Command("tasklist", "/FI", fmt.Sprintf("PID eq %d", pid), "/NH")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// Check if output contains the PID (tasklist returns "INFO: No tasks..." if not found)
|
||||
return containsSubstring(string(output), fmt.Sprintf("%d", pid))
|
||||
}
|
||||
|
||||
func containsSubstring(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
@ -1,274 +0,0 @@
|
|||
package daemon
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/lockfile"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
)
|
||||
|
||||
// RegistryEntry represents a daemon entry in the registry
|
||||
type RegistryEntry struct {
|
||||
WorkspacePath string `json:"workspace_path"`
|
||||
SocketPath string `json:"socket_path"`
|
||||
DatabasePath string `json:"database_path"`
|
||||
PID int `json:"pid"`
|
||||
Version string `json:"version"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
}
|
||||
|
||||
// Registry manages the global daemon registry file
|
||||
type Registry struct {
|
||||
path string
|
||||
lockPath string
|
||||
mu sync.Mutex // in-process mutex (cross-process uses file lock)
|
||||
}
|
||||
|
||||
// NewRegistry creates a new registry instance
|
||||
// The registry is stored in ~/.beads/registry.json
|
||||
func NewRegistry() (*Registry, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get home directory: %w", err)
|
||||
}
|
||||
|
||||
beadsDir := filepath.Join(home, ".beads")
|
||||
if err := os.MkdirAll(beadsDir, 0750); err != nil {
|
||||
return nil, fmt.Errorf("failed to create .beads directory: %w", err)
|
||||
}
|
||||
|
||||
registryPath := filepath.Join(beadsDir, "registry.json")
|
||||
lockPath := filepath.Join(beadsDir, "registry.lock")
|
||||
return &Registry{path: registryPath, lockPath: lockPath}, nil
|
||||
}
|
||||
|
||||
// withFileLock executes fn while holding an exclusive file lock on the registry.
|
||||
// This provides cross-process synchronization for read-modify-write operations.
|
||||
func (r *Registry) withFileLock(fn func() error) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
// Open or create lock file
|
||||
// nolint:gosec // G304: controlled path from config
|
||||
lockFile, err := os.OpenFile(r.lockPath, os.O_CREATE|os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open lock file: %w", err)
|
||||
}
|
||||
defer func() { _ = lockFile.Close() }()
|
||||
|
||||
// Acquire exclusive lock (blocking)
|
||||
if err := lockfile.FlockExclusiveBlocking(lockFile); err != nil {
|
||||
return fmt.Errorf("failed to acquire lock: %w", err)
|
||||
}
|
||||
defer func() { _ = lockfile.FlockUnlock(lockFile) }()
|
||||
|
||||
return fn()
|
||||
}
|
||||
|
||||
// readEntriesLocked reads all entries from the registry file.
|
||||
// Caller must hold the file lock.
|
||||
// Handles missing, empty, or corrupted registry files gracefully.
|
||||
func (r *Registry) readEntriesLocked() ([]RegistryEntry, error) {
|
||||
data, err := os.ReadFile(r.path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return []RegistryEntry{}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("failed to read registry: %w", err)
|
||||
}
|
||||
|
||||
// Handle empty file or file with only whitespace/null bytes
|
||||
// This can happen if the file was created but never written to, or was corrupted
|
||||
trimmed := make([]byte, 0, len(data))
|
||||
for _, b := range data {
|
||||
if b != 0 && b != ' ' && b != '\t' && b != '\n' && b != '\r' {
|
||||
trimmed = append(trimmed, b)
|
||||
}
|
||||
}
|
||||
if len(trimmed) == 0 {
|
||||
return []RegistryEntry{}, nil
|
||||
}
|
||||
|
||||
var entries []RegistryEntry
|
||||
if err := json.Unmarshal(data, &entries); err != nil {
|
||||
// If registry is corrupted, treat as empty rather than failing
|
||||
// A corrupted registry just means we'll need to rediscover daemons
|
||||
return []RegistryEntry{}, nil
|
||||
}
|
||||
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// writeEntriesLocked writes all entries to the registry file atomically.
|
||||
// Caller must hold the file lock.
|
||||
func (r *Registry) writeEntriesLocked(entries []RegistryEntry) error {
|
||||
// Ensure we always write an array, never null
|
||||
if entries == nil {
|
||||
entries = []RegistryEntry{}
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(entries, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal registry: %w", err)
|
||||
}
|
||||
|
||||
// Write atomically: write to temp file, then rename
|
||||
dir := filepath.Dir(r.path)
|
||||
tmpFile, err := os.CreateTemp(dir, "registry-*.json.tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temp file: %w", err)
|
||||
}
|
||||
tmpPath := tmpFile.Name()
|
||||
|
||||
// Write data to temp file
|
||||
if _, err := tmpFile.Write(data); err != nil {
|
||||
_ = tmpFile.Close()
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("failed to write temp file: %w", err)
|
||||
}
|
||||
|
||||
// Sync to disk before rename
|
||||
if err := tmpFile.Sync(); err != nil {
|
||||
_ = tmpFile.Close()
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("failed to sync temp file: %w", err)
|
||||
}
|
||||
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("failed to close temp file: %w", err)
|
||||
}
|
||||
|
||||
// Atomic rename
|
||||
if err := os.Rename(tmpPath, r.path); err != nil {
|
||||
_ = os.Remove(tmpPath)
|
||||
return fmt.Errorf("failed to rename temp file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// readEntries reads all entries from the registry file (with locking).
|
||||
func (r *Registry) readEntries() ([]RegistryEntry, error) {
|
||||
var entries []RegistryEntry
|
||||
err := r.withFileLock(func() error {
|
||||
var readErr error
|
||||
entries, readErr = r.readEntriesLocked()
|
||||
return readErr
|
||||
})
|
||||
return entries, err
|
||||
}
|
||||
|
||||
// writeEntries writes all entries to the registry file (with locking).
|
||||
func (r *Registry) writeEntries(entries []RegistryEntry) error {
|
||||
return r.withFileLock(func() error {
|
||||
return r.writeEntriesLocked(entries)
|
||||
})
|
||||
}
|
||||
|
||||
// Register adds a daemon to the registry
|
||||
func (r *Registry) Register(entry RegistryEntry) error {
|
||||
return r.withFileLock(func() error {
|
||||
entries, err := r.readEntriesLocked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove any existing entry for this workspace or PID
|
||||
// Use PathsEqual for case-insensitive comparison on macOS/Windows (GH#869)
|
||||
filtered := []RegistryEntry{}
|
||||
for _, e := range entries {
|
||||
if !utils.PathsEqual(e.WorkspacePath, entry.WorkspacePath) && e.PID != entry.PID {
|
||||
filtered = append(filtered, e)
|
||||
}
|
||||
}
|
||||
|
||||
// Add new entry
|
||||
filtered = append(filtered, entry)
|
||||
|
||||
return r.writeEntriesLocked(filtered)
|
||||
})
|
||||
}
|
||||
|
||||
// Unregister removes a daemon from the registry
|
||||
func (r *Registry) Unregister(workspacePath string, pid int) error {
|
||||
return r.withFileLock(func() error {
|
||||
entries, err := r.readEntriesLocked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Filter out entries matching workspace or PID
|
||||
// Use PathsEqual for case-insensitive comparison on macOS/Windows (GH#869)
|
||||
filtered := []RegistryEntry{}
|
||||
for _, e := range entries {
|
||||
if !utils.PathsEqual(e.WorkspacePath, workspacePath) && e.PID != pid {
|
||||
filtered = append(filtered, e)
|
||||
}
|
||||
}
|
||||
|
||||
return r.writeEntriesLocked(filtered)
|
||||
})
|
||||
}
|
||||
|
||||
// List returns all daemons from the registry, automatically cleaning up stale entries
|
||||
func (r *Registry) List() ([]DaemonInfo, error) {
|
||||
var daemons []DaemonInfo
|
||||
|
||||
err := r.withFileLock(func() error {
|
||||
entries, err := r.readEntriesLocked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var aliveEntries []RegistryEntry
|
||||
|
||||
for _, entry := range entries {
|
||||
// Check if process is still alive
|
||||
if !isProcessAlive(entry.PID) {
|
||||
// Stale entry - skip and don't add to alive list
|
||||
continue
|
||||
}
|
||||
|
||||
// Process is alive, add to both lists
|
||||
aliveEntries = append(aliveEntries, entry)
|
||||
|
||||
// Try to connect and get current status
|
||||
daemon := discoverDaemon(entry.SocketPath)
|
||||
|
||||
// If connection failed but process is alive, still include basic info
|
||||
if !daemon.Alive {
|
||||
daemon.Alive = true // Process exists, socket just might not be ready
|
||||
daemon.WorkspacePath = entry.WorkspacePath
|
||||
daemon.DatabasePath = entry.DatabasePath
|
||||
daemon.SocketPath = entry.SocketPath
|
||||
daemon.PID = entry.PID
|
||||
daemon.Version = entry.Version
|
||||
}
|
||||
|
||||
daemons = append(daemons, daemon)
|
||||
}
|
||||
|
||||
// Clean up stale entries from registry
|
||||
if len(aliveEntries) != len(entries) {
|
||||
if err := r.writeEntriesLocked(aliveEntries); err != nil {
|
||||
// Log warning but don't fail - we still have the daemon list
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to cleanup stale registry entries: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return daemons, err
|
||||
}
|
||||
|
||||
// Clear removes all entries from the registry (for testing)
|
||||
func (r *Registry) Clear() error {
|
||||
return r.writeEntries([]RegistryEntry{})
|
||||
}
|
||||
|
|
@ -1,405 +0,0 @@
|
|||
package daemon
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRegistryBasics(t *testing.T) {
|
||||
// Create temporary directory for test registry
|
||||
tmpDir := t.TempDir()
|
||||
registryPath := filepath.Join(tmpDir, ".beads", "registry.json")
|
||||
|
||||
// Override the registry path for testing (platform-specific)
|
||||
homeEnv := "HOME"
|
||||
if runtime.GOOS == "windows" {
|
||||
homeEnv = "USERPROFILE"
|
||||
}
|
||||
oldHome := os.Getenv(homeEnv)
|
||||
os.Setenv(homeEnv, tmpDir)
|
||||
defer os.Setenv(homeEnv, oldHome)
|
||||
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create registry: %v", err)
|
||||
}
|
||||
|
||||
// Test 1: Registry should start empty
|
||||
entries, err := registry.List()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to list entries: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Errorf("Expected empty registry, got %d entries", len(entries))
|
||||
}
|
||||
|
||||
// Test 2: Register a daemon
|
||||
entry := RegistryEntry{
|
||||
WorkspacePath: "/test/workspace",
|
||||
SocketPath: "/test/workspace/.beads/bd.sock",
|
||||
DatabasePath: "/test/workspace/.beads/beads.db",
|
||||
PID: 12345,
|
||||
Version: "0.19.0",
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := registry.Register(entry); err != nil {
|
||||
t.Fatalf("Failed to register entry: %v", err)
|
||||
}
|
||||
|
||||
// Test 3: Verify registry file was created
|
||||
if _, err := os.Stat(registryPath); os.IsNotExist(err) {
|
||||
t.Error("Registry file was not created")
|
||||
}
|
||||
|
||||
// Test 4: Read back the entry (note: process won't be alive, so List won't return it)
|
||||
// Instead, use readEntries to verify it was written
|
||||
rawEntries, err := registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 1 {
|
||||
t.Errorf("Expected 1 entry in registry, got %d", len(rawEntries))
|
||||
}
|
||||
if rawEntries[0].WorkspacePath != entry.WorkspacePath {
|
||||
t.Errorf("Expected workspace %s, got %s", entry.WorkspacePath, rawEntries[0].WorkspacePath)
|
||||
}
|
||||
if rawEntries[0].PID != entry.PID {
|
||||
t.Errorf("Expected PID %d, got %d", entry.PID, rawEntries[0].PID)
|
||||
}
|
||||
|
||||
// Test 5: Register another daemon for same workspace (should replace)
|
||||
entry2 := entry
|
||||
entry2.PID = 54321
|
||||
if err := registry.Register(entry2); err != nil {
|
||||
t.Fatalf("Failed to register second entry: %v", err)
|
||||
}
|
||||
|
||||
rawEntries, err = registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 1 {
|
||||
t.Errorf("Expected 1 entry after replacement, got %d", len(rawEntries))
|
||||
}
|
||||
if rawEntries[0].PID != 54321 {
|
||||
t.Errorf("Expected new PID 54321, got %d", rawEntries[0].PID)
|
||||
}
|
||||
|
||||
// Test 6: Unregister
|
||||
if err := registry.Unregister(entry2.WorkspacePath, entry2.PID); err != nil {
|
||||
t.Fatalf("Failed to unregister: %v", err)
|
||||
}
|
||||
|
||||
rawEntries, err = registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 0 {
|
||||
t.Errorf("Expected empty registry after unregister, got %d entries", len(rawEntries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryMultipleDaemons(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
oldHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", tmpDir)
|
||||
defer os.Setenv("HOME", oldHome)
|
||||
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create registry: %v", err)
|
||||
}
|
||||
|
||||
// Register multiple daemons
|
||||
for i := 1; i <= 3; i++ {
|
||||
entry := RegistryEntry{
|
||||
WorkspacePath: filepath.Join("/test", "workspace", string(rune('a'+i-1))),
|
||||
SocketPath: filepath.Join("/test", "workspace", string(rune('a'+i-1)), ".beads/bd.sock"),
|
||||
DatabasePath: filepath.Join("/test", "workspace", string(rune('a'+i-1)), ".beads/beads.db"),
|
||||
PID: 10000 + i,
|
||||
Version: "0.19.0",
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
if err := registry.Register(entry); err != nil {
|
||||
t.Fatalf("Failed to register entry %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
rawEntries, err := registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 3 {
|
||||
t.Errorf("Expected 3 entries, got %d", len(rawEntries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryStaleCleanup(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
oldHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", tmpDir)
|
||||
defer os.Setenv("HOME", oldHome)
|
||||
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create registry: %v", err)
|
||||
}
|
||||
|
||||
// Register a daemon with a PID that doesn't exist
|
||||
staleEntry := RegistryEntry{
|
||||
WorkspacePath: "/test/workspace",
|
||||
SocketPath: "/test/workspace/.beads/bd.sock",
|
||||
DatabasePath: "/test/workspace/.beads/beads.db",
|
||||
PID: 99999, // Unlikely to exist
|
||||
Version: "0.19.0",
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := registry.Register(staleEntry); err != nil {
|
||||
t.Fatalf("Failed to register stale entry: %v", err)
|
||||
}
|
||||
|
||||
// List should clean up the stale entry
|
||||
daemons, err := registry.List()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to list: %v", err)
|
||||
}
|
||||
|
||||
// Should return empty since the process doesn't exist
|
||||
if len(daemons) != 0 {
|
||||
t.Errorf("Expected 0 daemons after cleanup, got %d", len(daemons))
|
||||
}
|
||||
|
||||
// Verify registry file was cleaned up
|
||||
rawEntries, err := registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 0 {
|
||||
t.Errorf("Expected empty registry after cleanup, got %d entries", len(rawEntries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryEmptyArrayNotNull(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
registryPath := filepath.Join(tmpDir, ".beads", "registry.json")
|
||||
|
||||
// Override the registry path for testing (platform-specific)
|
||||
homeEnv := "HOME"
|
||||
if runtime.GOOS == "windows" {
|
||||
homeEnv = "USERPROFILE"
|
||||
}
|
||||
oldHome := os.Getenv(homeEnv)
|
||||
os.Setenv(homeEnv, tmpDir)
|
||||
defer os.Setenv(homeEnv, oldHome)
|
||||
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create registry: %v", err)
|
||||
}
|
||||
|
||||
// Clear registry
|
||||
if err := registry.Clear(); err != nil {
|
||||
t.Fatalf("Failed to clear registry: %v", err)
|
||||
}
|
||||
|
||||
// Read the file and verify it's [] not null
|
||||
data, err := os.ReadFile(registryPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read registry file: %v", err)
|
||||
}
|
||||
|
||||
content := string(data)
|
||||
if content != "[]" && content != "[\n]" {
|
||||
t.Errorf("Expected empty array [], got: %s", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryCorruptedFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
registryPath := filepath.Join(tmpDir, ".beads", "registry.json")
|
||||
|
||||
homeEnv := "HOME"
|
||||
if runtime.GOOS == "windows" {
|
||||
homeEnv = "USERPROFILE"
|
||||
}
|
||||
oldHome := os.Getenv(homeEnv)
|
||||
os.Setenv(homeEnv, tmpDir)
|
||||
defer os.Setenv(homeEnv, oldHome)
|
||||
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create registry: %v", err)
|
||||
}
|
||||
|
||||
// Create a corrupted registry file
|
||||
os.MkdirAll(filepath.Dir(registryPath), 0755)
|
||||
os.WriteFile(registryPath, []byte("invalid json{{{"), 0644)
|
||||
|
||||
// bd-qn5: Corrupted registry should be treated as empty, not an error
|
||||
// This allows bd doctor to work gracefully when registry is corrupted
|
||||
entries, err := registry.readEntries()
|
||||
if err != nil {
|
||||
t.Errorf("Expected corrupted registry to be treated as empty, got error: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Errorf("Expected empty entries for corrupted registry, got %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
// bd-qn5: Test for the specific null bytes case that was reported
|
||||
func TestRegistryNullBytesFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
registryPath := filepath.Join(tmpDir, ".beads", "registry.json")
|
||||
|
||||
homeEnv := "HOME"
|
||||
if runtime.GOOS == "windows" {
|
||||
homeEnv = "USERPROFILE"
|
||||
}
|
||||
oldHome := os.Getenv(homeEnv)
|
||||
os.Setenv(homeEnv, tmpDir)
|
||||
defer os.Setenv(homeEnv, oldHome)
|
||||
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create registry: %v", err)
|
||||
}
|
||||
|
||||
// Create a file with null bytes (the reported error case)
|
||||
os.MkdirAll(filepath.Dir(registryPath), 0755)
|
||||
os.WriteFile(registryPath, []byte{0, 0, 0, 0}, 0644)
|
||||
|
||||
// Should treat as empty, not error
|
||||
entries, err := registry.readEntries()
|
||||
if err != nil {
|
||||
t.Errorf("Expected null-byte registry to be treated as empty, got error: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Errorf("Expected empty entries for null-byte registry, got %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryUnregisterNonExistent(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
oldHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", tmpDir)
|
||||
defer os.Setenv("HOME", oldHome)
|
||||
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create registry: %v", err)
|
||||
}
|
||||
|
||||
// Unregister from empty registry should succeed
|
||||
err = registry.Unregister("/nonexistent/workspace", 99999)
|
||||
if err != nil {
|
||||
t.Errorf("Unregister should succeed even if entry doesn't exist: %v", err)
|
||||
}
|
||||
|
||||
// Verify registry is still empty
|
||||
rawEntries, err := registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 0 {
|
||||
t.Errorf("Expected empty registry, got %d entries", len(rawEntries))
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistryPathNormalization tests that paths are canonicalized for consistent
|
||||
// matching across symlinks and case-insensitive filesystems (GH#880).
|
||||
func TestRegistryPathNormalization(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
oldHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", tmpDir)
|
||||
defer os.Setenv("HOME", oldHome)
|
||||
|
||||
registry, err := NewRegistry()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create registry: %v", err)
|
||||
}
|
||||
|
||||
// Create a real directory for symlink test
|
||||
realPath := filepath.Join(tmpDir, "real-workspace")
|
||||
if err := os.MkdirAll(realPath, 0755); err != nil {
|
||||
t.Fatalf("Failed to create real workspace: %v", err)
|
||||
}
|
||||
|
||||
// Canonicalize realPath too (on macOS, /var -> /private/var)
|
||||
if canonReal, err := filepath.EvalSymlinks(realPath); err == nil {
|
||||
realPath = canonReal
|
||||
}
|
||||
|
||||
// Create a symlink to it
|
||||
symlinkPath := filepath.Join(tmpDir, "symlink-workspace")
|
||||
if err := os.Symlink(realPath, symlinkPath); err != nil {
|
||||
t.Skipf("Cannot create symlink (platform limitation): %v", err)
|
||||
}
|
||||
|
||||
// Register using the symlink path
|
||||
entry := RegistryEntry{
|
||||
WorkspacePath: symlinkPath,
|
||||
SocketPath: filepath.Join(symlinkPath, ".beads/bd.sock"),
|
||||
DatabasePath: filepath.Join(symlinkPath, ".beads/beads.db"),
|
||||
PID: 12345,
|
||||
Version: "0.43.0",
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := registry.Register(entry); err != nil {
|
||||
t.Fatalf("Failed to register entry: %v", err)
|
||||
}
|
||||
|
||||
// Read back entry - path is stored as-is (PathsEqual handles comparison)
|
||||
rawEntries, err := registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 1 {
|
||||
t.Fatalf("Expected 1 entry, got %d", len(rawEntries))
|
||||
}
|
||||
|
||||
// Now register using the real path - should detect as same workspace and replace
|
||||
// (PathsEqual handles symlink resolution for comparison)
|
||||
entry2 := RegistryEntry{
|
||||
WorkspacePath: realPath,
|
||||
SocketPath: filepath.Join(realPath, ".beads/bd.sock"),
|
||||
DatabasePath: filepath.Join(realPath, ".beads/beads.db"),
|
||||
PID: 54321,
|
||||
Version: "0.43.0",
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := registry.Register(entry2); err != nil {
|
||||
t.Fatalf("Failed to register second entry: %v", err)
|
||||
}
|
||||
|
||||
// Should still have only 1 entry (replaced, not added)
|
||||
rawEntries, err = registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 1 {
|
||||
t.Errorf("Expected 1 entry after registering same workspace via different path, got %d", len(rawEntries))
|
||||
}
|
||||
if rawEntries[0].PID != 54321 {
|
||||
t.Errorf("Expected PID 54321, got %d", rawEntries[0].PID)
|
||||
}
|
||||
|
||||
// Test unregister using symlink path - should match the canonicalized path
|
||||
if err := registry.Unregister(symlinkPath, 54321); err != nil {
|
||||
t.Fatalf("Failed to unregister via symlink: %v", err)
|
||||
}
|
||||
|
||||
rawEntries, err = registry.readEntries()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read entries: %v", err)
|
||||
}
|
||||
if len(rawEntries) != 0 {
|
||||
t.Errorf("Expected empty registry after unregister, got %d entries", len(rawEntries))
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue