feat(bd): remove daemon infrastructure (w-bd-001)

Remove daemon/RPC subsystem and Gas Town detection heuristics from beads.
The daemon functionality has been superseded by Gas Town's deacon/daemon system.

Removed:
- IsDaemonManaged/IsDaemonManagedFor and Gas Town detection functions
- GasTownPort constant and GT_ROOT-based server directory resolution
- Daemon PID file checks in IsRunning, reclaimPort, KillStaleServers
- Daemon guard in Stop/StopWithForce
- Gas Town bypass in forkIdleMonitor and RunIdleMonitor
- Python bd_daemon_client.py RPC client and test_daemon_health_check.py
- Python test_multi_repo.py daemon integration test
- Daemon socket preference in create_bd_client
- Daemon client cleanup tracking in MCP server
- Daemon-related gitignore patterns and doctor fix ordering

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
EC2 Default User 2026-03-04 20:22:28 +00:00
commit b3decc2659
17 changed files with 52 additions and 1506 deletions

View file

@ -499,7 +499,7 @@ func runDiagnostics(path string) doctorResult {
result.Checks = append(result.Checks, roleCheck)
// Don't fail overall check for role config, just warn - URL heuristic fallback still works
// Check 7e: Stale lock files (bootstrap, sync, daemon, startup)
// Check 7e: Stale lock files (bootstrap, sync, startup)
staleLockCheck := convertDoctorCheck(doctor.CheckStaleLockFiles(path))
result.Checks = append(result.Checks, staleLockCheck)
if staleLockCheck.Status == statusWarning || staleLockCheck.Status == statusError {

View file

@ -53,10 +53,6 @@ dolt-monitor.pid
*.db-shm
db.sqlite
bd.db
daemon.lock
daemon.log
daemon-*.log.gz
daemon.pid
# NOTE: Do NOT add negation patterns here.
# They would override fork protection in .git/info/exclude.
# Config files (metadata.json, config.yaml) are tracked by git by default

View file

@ -206,7 +206,6 @@ func applyFixList(path string, fixes []doctorCheck) {
order := []string{
"Lock Files",
"Permissions",
"Daemon Health",
"Database Config",
"Config Values",
"Database Integrity",

View file

@ -14,7 +14,7 @@ import (
//
//nolint:unparam // path reserved for future use
func runPollutionCheck(_ string, clean bool, yes bool) {
// Ensure we have a store initialized (uses direct mode, no daemon support yet)
// Ensure we have a store initialized
if err := ensureDirectMode("pollution check requires direct mode"); err != nil {
FatalError("%v", err)
}

View file

@ -270,20 +270,6 @@ required. Use this command for explicit control or diagnostics.`,
}
serverDir := doltserver.ResolveServerDir(beadsDir)
if doltserver.IsDaemonManagedFor(beadsDir) {
// Check if daemon's server is already accepting connections
cfg := doltserver.DefaultConfig(serverDir)
addr := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
conn, err := net.DialTimeout("tcp", addr, 500*time.Millisecond)
if err == nil {
_ = conn.Close()
fmt.Printf("Dolt server already running on port %d (managed by Gas Town daemon)\n", cfg.Port)
return
}
fmt.Fprintf(os.Stderr, "Warning: Dolt server is normally managed by the Gas Town daemon,\n"+
"but no server found on port %d. Starting one.\n\n", cfg.Port)
}
state, err := doltserver.Start(serverDir)
if err != nil {
if strings.Contains(err.Error(), "already running") {
@ -306,10 +292,7 @@ var doltStopCmd = &cobra.Command{
Long: `Stop the dolt sql-server managed by beads for the current project.
This sends a graceful shutdown signal. The server will restart automatically
on the next bd command unless auto-start is disabled.
Under Gas Town, the server is managed by the gt daemon and cannot be stopped
via bd. Use 'gt dolt stop' instead.`,
on the next bd command unless auto-start is disabled.`,
Run: func(cmd *cobra.Command, args []string) {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
@ -430,9 +413,6 @@ one tracked by the current project's PID file.`,
killed, err := doltserver.KillStaleServers(beadsDir)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
if doltserver.IsDaemonManagedFor(beadsDir) {
fmt.Fprintf(os.Stderr, "\nUnder Gas Town, use 'gt dolt' commands to manage the server.\n")
}
os.Exit(1)
}
@ -897,7 +877,7 @@ func isTimeoutError(err error) bool {
func init() {
doltSetCmd.Flags().Bool("update-config", false, "Also write to config.yaml for team-wide defaults")
doltStopCmd.Flags().Bool("force", false, "Force stop even when managed by Gas Town daemon")
doltStopCmd.Flags().Bool("force", false, "Force stop the server")
doltPushCmd.Flags().Bool("force", false, "Force push (overwrite remote changes)")
doltCommitCmd.Flags().StringP("message", "m", "", "Commit message (default: auto-generated)")
doltIdleMonitorCmd.Flags().String("beads-dir", "", "Path to .beads directory")

View file

@ -351,7 +351,7 @@ environment variable.`,
BeadsDir: beadsDir,
Database: dbName,
CreateIfMissing: true, // bd init is the only path that should create databases
AutoStart: !doltserver.IsDaemonManaged() && os.Getenv("BEADS_DOLT_AUTO_START") != "0",
AutoStart: os.Getenv("BEADS_DOLT_AUTO_START") != "0",
}
if serverHost != "" {
doltCfg.ServerHost = serverHost

View file

@ -29,7 +29,7 @@ func withStorage(ctx context.Context, store *dolt.DoltStore, dbPath string, fn s
if store != nil {
return fn(store)
} else if dbPath != "" {
// Daemon mode: open read-only connection
// Open read-only connection
roStore, err := dolt.New(ctx, &dolt.Config{Path: dbPath, ReadOnly: true})
if err != nil {
return err

View file

@ -509,13 +509,9 @@ var rootCmd = &cobra.Command{
doltCfg.ServerTLS = cfg.GetDoltServerTLS()
}
// Auto-start: enabled by default for standalone users.
// Disabled under Gas Town (which manages its own server) or by explicit config.
// Gas Town detection uses GT_ROOT and a filesystem heuristic fallback.
// Auto-start: enabled by default.
// Can be disabled by explicit config or env var.
doltCfg.AutoStart = true
if doltserver.IsDaemonManaged() {
doltCfg.AutoStart = false
}
if os.Getenv("BEADS_DOLT_AUTO_START") == "0" {
doltCfg.AutoStart = false
}

View file

@ -871,75 +871,21 @@ def create_bd_client(
no_auto_import: Optional[bool] = None,
working_dir: Optional[str] = None,
) -> BdClientBase:
"""Create a bd client (daemon or CLI-based).
"""Create a bd CLI client.
Args:
prefer_daemon: If True, attempt to use daemon client first, fall back to CLI
bd_path: Path to bd executable (for CLI client)
beads_dir: Path to .beads directory (for CLI client)
beads_db: Path to beads database (deprecated, for CLI client)
prefer_daemon: Deprecated, ignored. Kept for API compatibility.
bd_path: Path to bd executable
beads_dir: Path to .beads directory
beads_db: Path to beads database (deprecated)
actor: Actor name for audit trail
no_auto_flush: Disable auto-flush (CLI only)
no_auto_import: Disable auto-import (CLI only)
no_auto_flush: Disable auto-flush
no_auto_import: Disable auto-import
working_dir: Working directory for database discovery
Returns:
BdClientBase implementation (daemon or CLI)
Note:
If prefer_daemon is True and daemon is not running, falls back to CLI client.
To check if daemon is running without falling back, use BdDaemonClient directly.
BdClientBase implementation (CLI)
"""
if prefer_daemon:
try:
from .bd_daemon_client import BdDaemonClient
from pathlib import Path
# Check if daemon socket exists before creating client
# Walk up from working_dir to find .beads/bd.sock, then check global
search_dir = Path(working_dir) if working_dir else Path.cwd()
socket_found = False
current = search_dir.resolve()
while True:
local_beads_dir = current / ".beads"
if local_beads_dir.is_dir():
sock_path = local_beads_dir / "bd.sock"
if sock_path.exists():
socket_found = True
break
# Found .beads but no socket - check global before giving up
break
# Move up one directory
parent = current.parent
if parent == current:
# Reached filesystem root - check global
break
current = parent
# If no local socket, check global daemon socket at ~/.beads/bd.sock
if not socket_found:
global_sock_path = Path.home() / ".beads" / "bd.sock"
if global_sock_path.exists():
socket_found = True
if socket_found:
# Daemon is running, use it
client = BdDaemonClient(
working_dir=working_dir,
actor=actor,
)
return client
# No socket found, fall through to CLI client
except ImportError:
# Daemon client not available (shouldn't happen but be defensive)
pass
except Exception:
# If daemon setup fails for any reason, fall back to CLI
pass
# Use CLI client
return BdCliClient(
bd_path=bd_path,
beads_dir=beads_dir,

View file

@ -1,601 +0,0 @@
"""Client for interacting with bd daemon via RPC over Unix socket."""
import asyncio
import json
import os
import socket
from pathlib import Path
from typing import Any, Dict, List, Optional
from .bd_client import BdClientBase, BdError
from .models import (
AddDependencyParams,
BlockedIssue,
BlockedParams,
ClaimIssueParams,
CloseIssueParams,
CreateIssueParams,
InitParams,
Issue,
ListIssuesParams,
ReadyWorkParams,
ReopenIssueParams,
ShowIssueParams,
Stats,
UpdateIssueParams,
)
class DaemonError(Exception):
"""Base exception for daemon client errors."""
pass
class DaemonNotRunningError(DaemonError):
"""Raised when daemon is not running."""
pass
class DaemonConnectionError(DaemonError):
"""Raised when connection to daemon fails."""
pass
class BdDaemonClient(BdClientBase):
"""Client for calling bd daemon via RPC over Unix socket."""
socket_path: str | None
working_dir: str
actor: str | None
timeout: float
def __init__(
self,
socket_path: str | None = None,
working_dir: str | None = None,
actor: str | None = None,
timeout: float = 30.0,
):
"""Initialize daemon client.
Args:
socket_path: Path to daemon Unix socket (optional, will auto-discover if not provided)
working_dir: Working directory for database discovery (optional)
actor: Actor name for audit trail (optional)
timeout: Socket timeout in seconds (default: 30.0)
"""
self.socket_path = socket_path
self.working_dir = working_dir or os.getcwd()
self.actor = actor
self.timeout = timeout
async def _find_socket_path(self) -> str:
"""Find daemon socket path by searching for .beads directory.
Checks local .beads/bd.sock first, then falls back to global ~/.beads/bd.sock.
Returns:
Path to bd.sock file
Raises:
DaemonNotRunningError: If no .beads directory or socket file found
"""
if self.socket_path:
return self.socket_path
# Walk up from working_dir to find .beads/bd.sock
current = Path(self.working_dir).resolve()
while True:
beads_dir = current / ".beads"
if beads_dir.is_dir():
sock_path = beads_dir / "bd.sock"
if sock_path.exists():
return str(sock_path)
# Found .beads but no socket - check global before failing
break
# Move up one directory
parent = current.parent
if parent == current:
# Reached filesystem root - check global
break
current = parent
# Check for global daemon socket at ~/.beads/bd.sock
home = Path.home()
global_sock_path = home / ".beads" / "bd.sock"
if global_sock_path.exists():
return str(global_sock_path)
# No socket found anywhere
raise DaemonNotRunningError(
"Daemon socket not found. Is the daemon running? Try: bd daemon start"
)
async def _send_request(self, operation: str, args: Dict[str, Any]) -> Any:
"""Send RPC request to daemon and get response.
Args:
operation: RPC operation name (e.g., "create", "list")
args: Operation-specific arguments
Returns:
Parsed response data
Raises:
DaemonNotRunningError: If daemon is not running
DaemonConnectionError: If connection fails
DaemonError: If request fails
"""
sock_path = await self._find_socket_path()
# Build request
request = {
"operation": operation,
"args": args,
"cwd": self.working_dir,
}
if self.actor:
request["actor"] = self.actor
# Connect to socket and send request
try:
reader, writer = await asyncio.wait_for(
asyncio.open_unix_connection(sock_path),
timeout=self.timeout,
)
except FileNotFoundError:
raise DaemonNotRunningError(
f"Daemon socket not found: {sock_path}. Is the daemon running?"
)
except asyncio.TimeoutError:
raise DaemonConnectionError(
f"Timeout connecting to daemon at {sock_path}"
)
except Exception as e:
raise DaemonConnectionError(
f"Failed to connect to daemon at {sock_path}: {e}"
)
try:
# Send request as newline-delimited JSON
request_json = json.dumps(request) + "\n"
writer.write(request_json.encode())
await writer.drain()
# Read response (also newline-delimited JSON)
try:
response_line = await asyncio.wait_for(
reader.readline(),
timeout=self.timeout,
)
except asyncio.TimeoutError:
raise DaemonError(
f"Timeout waiting for response from daemon (operation: {operation})"
)
if not response_line:
raise DaemonError("Daemon closed connection without responding")
response = json.loads(response_line.decode())
# Check for errors
if not response.get("success"):
error = response.get("error", "Unknown error")
raise DaemonError(f"Daemon returned error: {error}")
# Return data
return response.get("data", {})
finally:
writer.close()
await writer.wait_closed()
async def ping(self) -> Dict[str, Any]:
"""Ping daemon to check if it's running.
Returns:
Dict with "message" and "version" fields
Raises:
DaemonNotRunningError: If daemon is not running
DaemonConnectionError: If connection fails
DaemonError: If request fails
"""
data = await self._send_request("ping", {})
result = json.loads(data) if isinstance(data, str) else data
return dict(result)
async def health(self) -> Dict[str, Any]:
"""Get daemon health status.
Returns:
Dict with health info including:
- status: "healthy" | "degraded" | "unhealthy"
- version: daemon version string
- uptime: uptime in seconds
- db_response_time_ms: database ping time
- active_connections: number of active connections
- memory_bytes: memory usage
Raises:
DaemonNotRunningError: If daemon is not running
DaemonConnectionError: If connection fails
DaemonError: If request fails
"""
data = await self._send_request("health", {})
result = json.loads(data) if isinstance(data, str) else data
return dict(result)
async def quickstart(self) -> str:
"""Get quickstart guide.
Note: Daemon RPC doesn't support quickstart command.
Returns static guide text pointing users to CLI.
Returns:
Quickstart guide text
"""
return (
"Beads (bd) Quickstart\n\n"
"To get started with beads, please refer to the documentation or use the CLI:\n"
" bd quickstart\n\n"
"For MCP usage, try 'beads list' or 'beads create'."
)
async def init(self, params: Optional[InitParams] = None) -> str:
"""Initialize new beads database (not typically used via daemon).
Args:
params: Initialization parameters (optional)
Returns:
Success message
Note:
This command is typically run via CLI, not daemon
"""
params = params or InitParams()
args: Dict[str, Any] = {}
if params.prefix:
args["prefix"] = params.prefix
result = await self._send_request("init", args)
return str(result) if result else "Initialized"
async def create(self, params: CreateIssueParams) -> Issue:
"""Create a new issue.
Args:
params: Issue creation parameters
Returns:
Created issue
"""
args = {
"title": params.title,
"issue_type": params.issue_type,
"priority": params.priority if params.priority is not None else 2,
}
if params.id:
args["id"] = params.id
if params.description:
args["description"] = params.description
if params.design:
args["design"] = params.design
if params.acceptance:
args["acceptance_criteria"] = params.acceptance
if params.assignee:
args["assignee"] = params.assignee
if params.labels:
args["labels"] = params.labels
if params.deps:
args["dependencies"] = params.deps
data = await self._send_request("create", args)
return Issue(**(json.loads(data) if isinstance(data, str) else data))
async def update(self, params: UpdateIssueParams) -> Issue:
"""Update an existing issue.
Args:
params: Issue update parameters
Returns:
Updated issue
"""
args: Dict[str, Any] = {"id": params.issue_id}
if params.status:
args["status"] = params.status
if params.priority is not None:
args["priority"] = params.priority
if params.design is not None:
args["design"] = params.design
if params.acceptance_criteria is not None:
args["acceptance_criteria"] = params.acceptance_criteria
if params.notes is not None:
args["notes"] = params.notes
if params.assignee is not None:
args["assignee"] = params.assignee
if params.title is not None:
args["title"] = params.title
if params.description is not None:
args["description"] = params.description
data = await self._send_request("update", args)
return Issue(**(json.loads(data) if isinstance(data, str) else data))
async def claim(self, params: ClaimIssueParams) -> Issue:
"""Atomically claim an issue.
Tries daemon RPC first. If daemon path does not support claim semantics,
falls back to CLI `bd update <id> --claim` to preserve atomic behavior.
Args:
params: Claim parameters
Returns:
Claimed issue
"""
args: Dict[str, Any] = {"id": params.issue_id, "claim": True}
try:
data = await self._send_request("update", args)
return Issue(**(json.loads(data) if isinstance(data, str) else data))
except Exception:
# Fallback to CLI path to guarantee atomic claim semantics.
from .bd_client import BdCliClient
cli = BdCliClient(actor=self.actor, working_dir=self.working_dir)
return await cli.claim(params)
async def close(self, params: CloseIssueParams) -> List[Issue]:
"""Close an issue.
Args:
params: Close parameters
Returns:
List containing the closed issue
"""
args = {"id": params.issue_id}
if params.reason:
args["reason"] = params.reason
data = await self._send_request("close", args)
issue = Issue(**(json.loads(data) if isinstance(data, str) else data))
return [issue]
async def reopen(self, params: ReopenIssueParams) -> List[Issue]:
"""Reopen one or more closed issues.
Args:
params: Reopen parameters with issue IDs
Returns:
List of reopened issues
Note:
Reopen operation may not be implemented in daemon RPC yet
"""
# Note: reopen operation may not be in RPC protocol yet
# This is a placeholder for when it's added
raise NotImplementedError("Reopen operation not yet supported via daemon")
async def list_issues(self, params: Optional[ListIssuesParams] = None) -> List[Issue]:
"""List issues with optional filters.
Args:
params: List filter parameters (optional)
Returns:
List of matching issues
"""
params = params or ListIssuesParams()
args: Dict[str, Any] = {}
if params.status:
args["status"] = params.status
if params.priority is not None:
args["priority"] = params.priority
if params.issue_type:
args["issue_type"] = params.issue_type
if params.assignee:
args["assignee"] = params.assignee
if params.labels:
args["labels"] = params.labels
if params.labels_any:
args["labels_any"] = params.labels_any
if params.query:
args["query"] = params.query
if params.unassigned:
args["unassigned"] = params.unassigned
if params.limit:
args["limit"] = params.limit
data = await self._send_request("list", args)
issues_data = json.loads(data) if isinstance(data, str) else data
if issues_data is None:
return []
return [Issue(**issue) for issue in issues_data]
async def show(self, params: ShowIssueParams) -> Issue:
"""Show detailed issue information.
Args:
params: Show parameters with issue_id
Returns:
Issue details
"""
args = {"id": params.issue_id}
data = await self._send_request("show", args)
return Issue(**(json.loads(data) if isinstance(data, str) else data))
async def ready(self, params: Optional[ReadyWorkParams] = None) -> List[Issue]:
"""Get ready work (issues with no blockers).
Args:
params: Ready work filter parameters (optional)
Returns:
List of ready issues
"""
params = params or ReadyWorkParams()
args: Dict[str, Any] = {}
if params.assignee:
args["assignee"] = params.assignee
if params.priority is not None:
args["priority"] = params.priority
if params.labels:
args["labels"] = params.labels
if params.labels_any:
args["labels_any"] = params.labels_any
if params.unassigned:
args["unassigned"] = params.unassigned
if params.sort_policy:
args["sort_policy"] = params.sort_policy
if params.limit:
args["limit"] = params.limit
# Parent filtering (descendants of a bead/epic)
if params.parent_id:
args["parent_id"] = params.parent_id
data = await self._send_request("ready", args)
issues_data = json.loads(data) if isinstance(data, str) else data
if issues_data is None:
return []
return [Issue(**issue) for issue in issues_data]
async def stats(self) -> Stats:
"""Get repository statistics.
Returns:
Statistics object
"""
data = await self._send_request("stats", {})
stats_data = json.loads(data) if isinstance(data, str) else data
if stats_data is None:
stats_data = {}
return Stats(**stats_data)
async def blocked(self, params: Optional[BlockedParams] = None) -> List[BlockedIssue]:
"""Get blocked issues.
Args:
params: Query parameters (optional)
Returns:
List of blocked issues with their blockers
"""
params = params or BlockedParams()
args: Dict[str, Any] = {}
if params.parent_id:
args["parent_id"] = params.parent_id
data = await self._send_request("blocked", args)
issues_data = json.loads(data) if isinstance(data, str) else data
if issues_data is None:
return []
return [BlockedIssue(**issue) for issue in issues_data]
async def inspect_migration(self) -> dict[str, Any]:
"""Get migration plan and database state for agent analysis.
Returns:
Migration plan dict with registered_migrations, warnings, etc.
Note:
This falls back to CLI since migrations are rare operations
"""
raise NotImplementedError("inspect_migration not supported via daemon - use CLI client")
async def get_schema_info(self) -> dict[str, Any]:
"""Get current database schema for inspection.
Returns:
Schema info dict with tables, version, config, sample IDs, etc.
Note:
This falls back to CLI since schema inspection is a rare operation
"""
raise NotImplementedError("get_schema_info not supported via daemon - use CLI client")
async def repair_deps(self, fix: bool = False) -> dict[str, Any]:
"""Find and optionally fix orphaned dependency references.
Args:
fix: If True, automatically remove orphaned dependencies
Returns:
Dict with orphans_found, orphans list, and fixed count if fix=True
Note:
This falls back to CLI since repair operations are rare
"""
raise NotImplementedError("repair_deps not supported via daemon - use CLI client")
async def detect_pollution(self, clean: bool = False) -> dict[str, Any]:
"""Detect test issues that leaked into production database.
Args:
clean: If True, delete detected test issues
Returns:
Dict with detected test issues and deleted count if clean=True
Note:
This falls back to CLI since pollution detection is a rare operation
"""
raise NotImplementedError("detect_pollution not supported via daemon - use CLI client")
async def validate(self, checks: str | None = None, fix_all: bool = False) -> dict[str, Any]:
"""Run database validation checks.
Args:
checks: Comma-separated list of checks (orphans,duplicates,pollution,conflicts)
fix_all: If True, auto-fix all fixable issues
Returns:
Dict with validation results for each check
Note:
This falls back to CLI since validation is a rare operation
"""
raise NotImplementedError("validate not supported via daemon - use CLI client")
async def add_dependency(self, params: AddDependencyParams) -> None:
"""Add a dependency between issues.
Args:
params: Dependency parameters
"""
args = {
"from_id": params.issue_id,
"to_id": params.depends_on_id,
"dep_type": params.dep_type,
}
await self._send_request("dep_add", args)
async def is_daemon_running(self) -> bool:
"""Check if daemon is running.
Returns:
True if daemon is running and responsive
"""
try:
await self.ping()
return True
except (DaemonNotRunningError, DaemonConnectionError, DaemonError):
return False
def cleanup(self) -> None:
"""Close daemon client connections and cleanup resources.
This is called during MCP server shutdown to ensure clean termination.
Since we use asyncio.open_unix_connection which closes per-request,
there's no persistent connection to close. This method is a no-op
but exists for API consistency.
"""
# No persistent connections to close - each request opens/closes its own
pass

View file

@ -71,7 +71,6 @@ logging.basicConfig(
T = TypeVar("T")
# Global state for cleanup
_daemon_clients: list[Any] = []
_cleanup_done = False
# Persistent workspace context (survives across MCP tool calls)
@ -132,28 +131,16 @@ IMPORTANT: Call context(workspace_root='...') to set your workspace before any w
def cleanup() -> None:
"""Clean up resources on exit.
Closes daemon connections and removes temp files.
Safe to call multiple times.
"""
global _cleanup_done
if _cleanup_done:
return
_cleanup_done = True
logger.info("Cleaning up beads-mcp resources...")
# Close all daemon client connections
for client in _daemon_clients:
try:
if hasattr(client, 'cleanup'):
client.cleanup()
logger.debug(f"Closed daemon client: {client}")
except Exception as e:
logger.warning(f"Error closing daemon client: {e}")
_daemon_clients.clear()
logger.info("Cleanup complete")

View file

@ -1,158 +0,0 @@
#!/usr/bin/env python3
"""Integration test for multi-repo daemon support.
Tests that the daemon can handle operations across multiple repositories
simultaneously using per-request cwd context.
"""
import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
# Add src to path for imports
sys.path.insert(0, str(Path(__file__).parent / "src"))
from beads_mcp.bd_daemon_client import BdDaemonClient
from beads_mcp.models import CreateIssueParams, ListIssuesParams
async def main():
"""Run multi-repo integration test."""
print("=== Multi-Repo Daemon Integration Test ===\n")
# Create two temporary repositories
with tempfile.TemporaryDirectory() as tmpdir:
repo1 = Path(tmpdir) / "repo1"
repo2 = Path(tmpdir) / "repo2"
repo1.mkdir()
repo2.mkdir()
print(f"Created test repositories:")
print(f" repo1: {repo1}")
print(f" repo2: {repo2}\n")
# Initialize bd in both repos
print("Initializing beads in both repos...")
subprocess.run(["bd", "init", "--prefix", "r1"], cwd=repo1, check=True, capture_output=True)
subprocess.run(["bd", "init", "--prefix", "r2"], cwd=repo2, check=True, capture_output=True)
print("✅ Initialized\n")
# Find or start daemon in beads project
beads_project = Path(__file__).parent.parent.parent
beads_socket = beads_project / ".beads" / "bd.sock"
print("Checking daemon status...")
if not beads_socket.exists():
print("Starting daemon in beads project...")
subprocess.run(["bd", "daemon", "start"], cwd=beads_project, check=True, capture_output=True)
await asyncio.sleep(1) # Give daemon time to start
print("✅ Daemon started\n")
else:
print(f"✅ Daemon socket found at {beads_socket}\n")
# Create daemon clients for each repo, pointing to beads project socket
print("Creating daemon clients...")
client1 = BdDaemonClient(socket_path=str(beads_socket), working_dir=str(repo1))
client2 = BdDaemonClient(socket_path=str(beads_socket), working_dir=str(repo2))
print("✅ Clients created\n")
# Test 1: Create issues in both repos concurrently
print("Test 1: Creating issues concurrently in both repos...")
params1 = CreateIssueParams(
title="Issue in repo1",
description="This should go to repo1 database",
priority=1,
issue_type="task"
)
params2 = CreateIssueParams(
title="Issue in repo2",
description="This should go to repo2 database",
priority=1,
issue_type="task"
)
issue1, issue2 = await asyncio.gather(
client1.create(params1),
client2.create(params2)
)
print(f" ✅ Created {issue1.id} in repo1")
print(f" ✅ Created {issue2.id} in repo2")
assert issue1.id.startswith("r1-"), f"Expected r1- prefix, got {issue1.id}"
assert issue2.id.startswith("r2-"), f"Expected r2- prefix, got {issue2.id}"
print()
# Test 2: List issues from each repo - should be isolated
print("Test 2: Verifying issue isolation between repos...")
list_params = ListIssuesParams()
issues1 = await client1.list_issues(list_params)
issues2 = await client2.list_issues(list_params)
print(f" repo1 issues: {[i.id for i in issues1]}")
print(f" repo2 issues: {[i.id for i in issues2]}")
assert len(issues1) == 1, f"Expected 1 issue in repo1, got {len(issues1)}"
assert len(issues2) == 1, f"Expected 1 issue in repo2, got {len(issues2)}"
assert issues1[0].id == issue1.id, "repo1 issue mismatch"
assert issues2[0].id == issue2.id, "repo2 issue mismatch"
print(" ✅ Issues are properly isolated\n")
# Test 3: Rapid concurrent operations
print("Test 3: Rapid concurrent operations across repos...")
tasks = []
for i in range(5):
p1 = CreateIssueParams(
title=f"Concurrent issue {i} in repo1",
priority=2,
issue_type="task"
)
p2 = CreateIssueParams(
title=f"Concurrent issue {i} in repo2",
priority=2,
issue_type="task"
)
tasks.append(client1.create(p1))
tasks.append(client2.create(p2))
created = await asyncio.gather(*tasks)
print(f" ✅ Created {len(created)} issues concurrently")
# Verify counts
issues1 = await client1.list_issues(list_params)
issues2 = await client2.list_issues(list_params)
print(f" repo1 total: {len(issues1)} issues")
print(f" repo2 total: {len(issues2)} issues")
assert len(issues1) == 6, f"Expected 6 issues in repo1, got {len(issues1)}"
assert len(issues2) == 6, f"Expected 6 issues in repo2, got {len(issues2)}"
print(" ✅ All concurrent operations succeeded\n")
# Test 4: Verify prefixes are correct
print("Test 4: Verifying all prefixes are correct...")
for issue in issues1:
assert issue.id.startswith("r1-"), f"repo1 issue has wrong prefix: {issue.id}"
for issue in issues2:
assert issue.id.startswith("r2-"), f"repo2 issue has wrong prefix: {issue.id}"
print(" ✅ All prefixes correct\n")
print("=== All Tests Passed! ===")
print("\nSummary:")
print(" ✅ Per-request context routing works")
print(" ✅ Multiple repos are properly isolated")
print(" ✅ Concurrent operations succeed")
print(" ✅ Daemon handles rapid context switching")
if __name__ == "__main__":
try:
asyncio.run(main())
except Exception as e:
print(f"\n❌ Test failed: {e}", file=sys.stderr)
import traceback
traceback.print_exc()
sys.exit(1)

View file

@ -1,305 +0,0 @@
"""Tests for daemon health check and reconnection logic."""
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from beads_mcp.bd_client import BdError
from beads_mcp.bd_daemon_client import (
BdDaemonClient,
DaemonConnectionError,
DaemonError,
DaemonNotRunningError,
)
from beads_mcp.tools import _get_client, _health_check_client, _reconnect_client
@pytest.mark.asyncio
async def test_daemon_client_ping_success():
"""Test successful ping to daemon."""
client = BdDaemonClient(socket_path="/tmp/bd.sock", working_dir="/tmp/test")
with patch.object(client, '_send_request', new_callable=AsyncMock) as mock_send:
mock_send.return_value = {"message": "pong", "version": "0.9.10"}
result = await client.ping()
assert result["message"] == "pong"
assert result["version"] == "0.9.10"
mock_send.assert_called_once_with("ping", {})
@pytest.mark.asyncio
async def test_daemon_client_ping_connection_error():
"""Test ping when daemon connection fails."""
client = BdDaemonClient(socket_path="/tmp/bd.sock", working_dir="/tmp/test")
with patch.object(client, '_send_request', new_callable=AsyncMock) as mock_send:
mock_send.side_effect = DaemonConnectionError("Connection failed")
with pytest.raises(DaemonConnectionError):
await client.ping()
@pytest.mark.asyncio
async def test_daemon_client_health_success():
"""Test successful health check to daemon."""
client = BdDaemonClient(socket_path="/tmp/bd.sock", working_dir="/tmp/test")
with patch.object(client, '_send_request', new_callable=AsyncMock) as mock_send:
mock_send.return_value = {
"status": "healthy",
"version": "0.9.10",
"uptime": 123.45,
"db_response_time_ms": 2.5,
"active_connections": 3,
"memory_bytes": 104857600,
}
result = await client.health()
assert result["status"] == "healthy"
assert result["version"] == "0.9.10"
assert result["uptime"] == 123.45
mock_send.assert_called_once_with("health", {})
@pytest.mark.asyncio
async def test_daemon_client_health_unhealthy():
"""Test health check when daemon is unhealthy."""
client = BdDaemonClient(socket_path="/tmp/bd.sock", working_dir="/tmp/test")
with patch.object(client, '_send_request', new_callable=AsyncMock) as mock_send:
mock_send.return_value = {
"status": "unhealthy",
"error": "Database connection failed",
}
result = await client.health()
assert result["status"] == "unhealthy"
assert "error" in result
@pytest.mark.asyncio
async def test_health_check_client_daemon_client_healthy():
"""Test health check for healthy daemon client."""
client = BdDaemonClient(socket_path="/tmp/bd.sock", working_dir="/tmp/test")
with patch.object(client, 'ping', new_callable=AsyncMock) as mock_ping:
mock_ping.return_value = {"message": "pong", "version": "0.9.10"}
result = await _health_check_client(client)
assert result is True
mock_ping.assert_called_once()
@pytest.mark.asyncio
async def test_health_check_client_daemon_client_unhealthy():
"""Test health check for unhealthy daemon client."""
client = BdDaemonClient(socket_path="/tmp/bd.sock", working_dir="/tmp/test")
with patch.object(client, 'ping', new_callable=AsyncMock) as mock_ping:
mock_ping.side_effect = DaemonConnectionError("Connection failed")
result = await _health_check_client(client)
assert result is False
@pytest.mark.asyncio
async def test_health_check_client_cli_client():
"""Test health check for CLI client (always returns True)."""
from beads_mcp.bd_client import BdClient
client = BdClient(bd_path="/usr/bin/bd", beads_db="/tmp/test.db")
result = await _health_check_client(client)
# CLI clients don't have ping, so they're always considered healthy
assert result is True
@pytest.mark.asyncio
async def test_reconnect_client_success():
"""Test successful reconnection after failure."""
from beads_mcp.bd_client import create_bd_client
with (
patch('beads_mcp.tools.create_bd_client') as mock_create,
patch('beads_mcp.tools._health_check_client', new_callable=AsyncMock) as mock_health,
patch('beads_mcp.tools._register_client_for_cleanup') as mock_register,
):
mock_client = MagicMock()
mock_create.return_value = mock_client
mock_health.return_value = True
result = await _reconnect_client("/tmp/test")
assert result == mock_client
mock_create.assert_called_once_with(prefer_daemon=True, working_dir="/tmp/test")
mock_register.assert_called_once_with(mock_client)
@pytest.mark.asyncio
async def test_reconnect_client_retry_with_backoff():
"""Test reconnection with exponential backoff on failure."""
# Need to patch asyncio.sleep in the actual module where it's called
import beads_mcp.tools as tools_module
with (
patch.object(tools_module, 'create_bd_client') as mock_create,
patch.object(tools_module, '_health_check_client', new_callable=AsyncMock) as mock_health,
patch.object(tools_module, '_register_client_for_cleanup') as mock_register,
):
mock_client = MagicMock()
# Raise exception first two times, succeed third time
mock_create.side_effect = [
Exception("Connection failed"),
Exception("Connection failed"),
mock_client,
]
mock_health.return_value = True
# Mock asyncio.sleep to track calls
sleep_calls = []
async def mock_sleep(duration):
sleep_calls.append(duration)
# Don't actually sleep in tests
return
with patch.object(asyncio, 'sleep', side_effect=mock_sleep):
result = await _reconnect_client("/tmp/test", max_retries=3)
assert result == mock_client
assert mock_create.call_count == 3
assert len(sleep_calls) == 2
# Verify exponential backoff: 0.1s, 0.2s
assert sleep_calls[0] == 0.1
assert sleep_calls[1] == 0.2
@pytest.mark.asyncio
async def test_reconnect_client_max_retries_exceeded():
"""Test reconnection failure after max retries."""
with (
patch('beads_mcp.tools.create_bd_client') as mock_create,
patch('beads_mcp.tools._health_check_client', new_callable=AsyncMock) as mock_health,
patch('asyncio.sleep', new_callable=AsyncMock),
):
mock_client = MagicMock()
mock_create.return_value = mock_client
mock_health.return_value = False # Always fail health check
with pytest.raises(BdError, match="Failed to connect to daemon after 3 attempts"):
await _reconnect_client("/tmp/test", max_retries=3)
assert mock_create.call_count == 3
@pytest.mark.asyncio
async def test_get_client_uses_cached_healthy_client(monkeypatch):
"""Test that _get_client returns cached client if healthy."""
from beads_mcp import tools
# Set up environment
monkeypatch.setenv("BEADS_WORKING_DIR", "/tmp/test")
mock_client = MagicMock()
mock_client._check_version = AsyncMock()
with (
patch('beads_mcp.tools._canonicalize_path', return_value="/tmp/test"),
patch('beads_mcp.tools._health_check_client', new_callable=AsyncMock) as mock_health,
):
mock_health.return_value = True
# Add mock client to pool and mark as version checked
tools._connection_pool["/tmp/test"] = mock_client
tools._version_checked.add("/tmp/test")
result = await _get_client()
assert result == mock_client
mock_health.assert_called_once_with(mock_client)
@pytest.mark.asyncio
async def test_get_client_reconnects_on_stale_connection(monkeypatch):
"""Test that _get_client reconnects when cached client is stale."""
from beads_mcp import tools
# Set up environment
monkeypatch.setenv("BEADS_WORKING_DIR", "/tmp/test")
old_client = MagicMock()
new_client = MagicMock()
new_client._check_version = AsyncMock()
with (
patch('beads_mcp.tools._canonicalize_path', return_value="/tmp/test"),
patch('beads_mcp.tools._health_check_client', new_callable=AsyncMock) as mock_health,
patch('beads_mcp.tools._reconnect_client', new_callable=AsyncMock) as mock_reconnect,
):
# First health check fails (stale), reconnect returns new client
mock_health.return_value = False
mock_reconnect.return_value = new_client
# Add old client to pool
tools._connection_pool["/tmp/test"] = old_client
tools._version_checked.add("/tmp/test")
result = await _get_client()
assert result == new_client
assert tools._connection_pool["/tmp/test"] == new_client
# Version check is performed after reconnect, so it's back in the set
assert "/tmp/test" in tools._version_checked
mock_reconnect.assert_called_once_with("/tmp/test")
@pytest.mark.asyncio
async def test_get_client_creates_new_client_if_not_cached(monkeypatch):
"""Test that _get_client creates new client if not in pool."""
from beads_mcp import tools
# Clear pool
tools._connection_pool.clear()
tools._version_checked.clear()
# Set up environment
monkeypatch.setenv("BEADS_WORKING_DIR", "/tmp/test")
mock_client = MagicMock()
mock_client._check_version = AsyncMock()
with (
patch('beads_mcp.tools._canonicalize_path', return_value="/tmp/test"),
patch('beads_mcp.tools.create_bd_client', return_value=mock_client) as mock_create,
patch('beads_mcp.tools._register_client_for_cleanup') as mock_register,
):
result = await _get_client()
assert result == mock_client
assert tools._connection_pool["/tmp/test"] == mock_client
mock_create.assert_called_once_with(prefer_daemon=True, working_dir="/tmp/test")
mock_register.assert_called_once_with(mock_client)
@pytest.mark.asyncio
async def test_get_client_no_workspace_error():
"""Test that _get_client raises error if no workspace is set."""
from beads_mcp import tools
# Clear context
tools.current_workspace.set(None)
with patch.dict('os.environ', {}, clear=True):
# Mock auto-detection to fail
with patch("beads_mcp.tools._find_beads_db_in_tree", return_value=None):
with pytest.raises(BdError, match="No beads workspace found"):
await _get_client()

View file

@ -13,112 +13,60 @@ def test_cleanup_handlers_registered():
# Server is already imported, so handlers are already registered
# We can verify the cleanup function and signal handler exist
import beads_mcp.server as server
# Verify cleanup function exists and is callable
assert hasattr(server, 'cleanup')
assert callable(server.cleanup)
# Verify signal handler exists and is callable
assert hasattr(server, 'signal_handler')
assert callable(server.signal_handler)
# Verify global state exists
assert hasattr(server, '_daemon_clients')
assert hasattr(server, '_cleanup_done')
def test_cleanup_function_safe_to_call_multiple_times():
"""Test that cleanup function can be called multiple times safely."""
from beads_mcp.server import cleanup, _daemon_clients
# Mock client
mock_client = MagicMock()
_daemon_clients.append(mock_client)
# Call cleanup multiple times
cleanup()
cleanup()
cleanup()
# Client should only be cleaned up once
assert mock_client.cleanup.call_count == 1
assert len(_daemon_clients) == 0
from beads_mcp.server import cleanup
def test_cleanup_handles_client_errors_gracefully():
"""Test that cleanup continues even if a client raises an error."""
from beads_mcp.server import cleanup, _daemon_clients
# Reset state
import beads_mcp.server as server
server._cleanup_done = False
# Create mock clients - one that raises, one that doesn't
failing_client = MagicMock()
failing_client.cleanup.side_effect = Exception("Connection failed")
good_client = MagicMock()
_daemon_clients.clear()
_daemon_clients.extend([failing_client, good_client])
# Cleanup should not raise
# Call cleanup multiple times - should not raise
cleanup()
cleanup()
cleanup()
# Both clients should have been attempted
assert failing_client.cleanup.called
assert good_client.cleanup.called
assert len(_daemon_clients) == 0
def test_signal_handler_calls_cleanup():
"""Test that signal handler calls cleanup and exits."""
from beads_mcp.server import signal_handler
with patch('beads_mcp.server.cleanup') as mock_cleanup:
with patch('sys.exit') as mock_exit:
# Call signal handler
signal_handler(signal.SIGTERM, None)
# Verify cleanup was called
assert mock_cleanup.called
# Verify exit was called
assert mock_exit.called
@pytest.mark.asyncio
async def test_client_registration_on_first_use():
"""Test that client is registered for cleanup on first use."""
from beads_mcp.server import _daemon_clients
# Clear existing clients
_daemon_clients.clear()
# Reset connection pool state
import beads_mcp.tools as tools
tools._connection_pool.clear()
# Note: Actually testing client registration requires a more complex setup
# since _get_client() needs a valid workspace context. The key behavior
# (cleanup list management) is already tested in other lifecycle tests.
# This test verifies the cleanup infrastructure exists.
assert isinstance(_daemon_clients, list)
def test_cleanup_logs_lifecycle_events(caplog):
"""Test that cleanup logs informative messages."""
import logging
from beads_mcp.server import cleanup
# Reset state
import beads_mcp.server as server
server._cleanup_done = False
server._daemon_clients.clear()
with caplog.at_level(logging.INFO):
cleanup()
# Check for lifecycle log messages
log_messages = [record.message for record in caplog.records]
assert any("Cleaning up" in msg for msg in log_messages)

View file

@ -2,9 +2,7 @@
// It provides transparent auto-start so that `bd init` and `bd <command>` work
// without manual server management.
//
// Under Gas Town (GT_ROOT set, or detected via filesystem heuristic),
// all worktrees share a single server on port 3307.
// In standalone mode, the default port is 3307 (configfile.DefaultDoltServerPort),
// The default port is 3307 (configfile.DefaultDoltServerPort),
// matching shared Homebrew Dolt servers. If another project's Dolt server already
// occupies port 3307, Start falls back to DerivePort for per-project isolation
// (hash-derived, range 13307–14306). Users with explicit port config in
@ -44,18 +42,9 @@ const (
portRangeSize = 1000
)
// GasTownPort is the fixed port used when running under Gas Town (GT_ROOT set).
// All worktrees share this single server instead of each getting a derived port.
const GasTownPort = 3307
// resolveServerDir returns the canonical server directory for dolt state files.
// Under Gas Town (GT_ROOT set), all server operations use $GT_ROOT/.beads/
// so that N worktrees share one server instead of spawning N servers.
// Outside Gas Town, returns beadsDir unchanged.
// Returns beadsDir unchanged.
func resolveServerDir(beadsDir string) string {
if gtRoot := os.Getenv("GT_ROOT"); gtRoot != "" {
return filepath.Join(gtRoot, ".beads")
}
return beadsDir
}
@ -117,11 +106,8 @@ func monitorPidPath(beadsDir string) string {
}
// MaxDoltServers is the hard ceiling on concurrent dolt sql-server processes.
// Under Gas Town, only 1 is allowed. Standalone allows up to 3 (e.g., multiple projects).
// Allows up to 3 (e.g., multiple projects).
func maxDoltServers() int {
if IsDaemonManaged() {
return 1
}
return 3
}
@ -169,7 +155,7 @@ func isPortAvailable(host string, port int) bool {
// reclaimPort ensures the canonical port is available for use.
// If the port is busy:
// - If our dolt server (same data dir or daemon-managed) → return its PID for adoption
// - If our dolt server (same data dir) → return its PID for adoption
// - If a stale/orphan dolt sql-server holds it → kill it and reclaim
// - If a non-dolt process holds it → return error (don't silently use another port)
//
@ -200,16 +186,6 @@ func reclaimPort(host string, port int, beadsDir string) (adoptPID int, err erro
// It's a dolt process. Check if it's one we should adopt.
// Under Gas Town, check the daemon PID file first
if gtRoot := os.Getenv("GT_ROOT"); gtRoot != "" {
daemonPidFile := filepath.Join(gtRoot, "daemon", "dolt.pid")
if data, readErr := os.ReadFile(daemonPidFile); readErr == nil { //nolint:gosec // G304: path constructed from trusted GT_ROOT env
if daemonPID, parseErr := strconv.Atoi(strings.TrimSpace(string(data))); parseErr == nil && daemonPID == pid {
return pid, nil // daemon-managed server — adopt it
}
}
}
// Check if the process is using our data directory (CWD matches our dolt dir).
// dolt sql-server is started with cmd.Dir = doltDir, so CWD is the data dir.
doltDir := ResolveDoltDir(beadsDir)
@ -255,7 +231,7 @@ func writePortFile(beadsDir string, port int) error {
}
// DefaultConfig returns config with sensible defaults.
// Priority: env var > metadata.json > config.yaml / global config > port file > Gas Town fixed port > DerivePort.
// Priority: env var > metadata.json > config.yaml / global config > port file > DerivePort.
//
// The port file (dolt-server.port) is written by Start() with the actual port
// the server is listening on. Consulting it here ensures that commands
@ -302,12 +278,7 @@ func DefaultConfig(beadsDir string) *Config {
}
if cfg.Port == 0 {
// Under Gas Town, use fixed port so all worktrees share one server.
if os.Getenv("GT_ROOT") != "" {
cfg.Port = GasTownPort
} else {
cfg.Port = DerivePort(beadsDir)
}
cfg.Port = DerivePort(beadsDir)
}
return cfg
@ -315,31 +286,7 @@ func DefaultConfig(beadsDir string) *Config {
// IsRunning checks if a managed server is running for this beadsDir.
// Returns a State with Running=true if a valid dolt process is found.
// Under Gas Town (GT_ROOT set), checks the daemon PID file first since the
// daemon writes to $GT_ROOT/daemon/dolt.pid, not .beads/dolt-server.pid.
func IsRunning(beadsDir string) (*State, error) {
// Under Gas Town, check daemon PID file first — the daemon manages
// the server and writes its PID to a different location.
if gtRoot := os.Getenv("GT_ROOT"); gtRoot != "" {
daemonPidFile := filepath.Join(gtRoot, "daemon", "dolt.pid")
if data, readErr := os.ReadFile(daemonPidFile); readErr == nil { //nolint:gosec // G304: path constructed from trusted GT_ROOT env
if pid, parseErr := strconv.Atoi(strings.TrimSpace(string(data))); parseErr == nil && pid > 0 {
if isProcessAlive(pid) && isDoltProcess(pid) {
port := readPortFile(beadsDir)
if port == 0 {
port = GasTownPort
}
return &State{
Running: true,
PID: pid,
Port: port,
DataDir: ResolveDoltDir(beadsDir),
}, nil
}
}
}
}
data, err := os.ReadFile(pidPath(beadsDir))
if err != nil {
if os.IsNotExist(err) {
@ -386,8 +333,6 @@ func IsRunning(beadsDir string) (*State, error) {
// EnsureRunning starts the server if it is not already running.
// This is the main auto-start entry point. Thread-safe via file lock.
// Under Gas Town (GT_ROOT set), resolves to the canonical server directory
// so all worktrees share one server.
// Returns the port the server is listening on.
func EnsureRunning(beadsDir string) (int, error) {
serverDir := resolveServerDir(beadsDir)
@ -500,14 +445,12 @@ func Start(beadsDir string) (*State, error) {
}
}
if adoptPID > 0 {
// Existing server is ours (same data dir or daemon-managed) — adopt it
// Existing server is ours (same data dir) — adopt it
_ = logFile.Close()
_ = os.WriteFile(pidPath(beadsDir), []byte(strconv.Itoa(adoptPID)), 0600)
_ = writePortFile(beadsDir, actualPort)
touchActivity(beadsDir)
if !IsDaemonManagedFor(beadsDir) {
forkIdleMonitor(beadsDir)
}
forkIdleMonitor(beadsDir)
return &State{Running: true, PID: adoptPID, Port: actualPort, DataDir: doltDir}, nil
}
@ -557,12 +500,9 @@ func Start(beadsDir string) (*State, error) {
pid, actualPort, err, logPath(beadsDir))
}
// Touch activity and fork idle monitor (skip under Gas Town where
// the daemon manages server lifecycle)
// Touch activity and fork idle monitor
touchActivity(beadsDir)
if !IsDaemonManagedFor(beadsDir) {
forkIdleMonitor(beadsDir)
}
forkIdleMonitor(beadsDir)
return &State{
Running: true,
@ -572,123 +512,6 @@ func Start(beadsDir string) (*State, error) {
}, nil
}
// IsDaemonManaged returns true if the dolt server is managed by the Gas Town
// daemon. Checks GT_ROOT first, then falls back to filesystem heuristics
// that detect Gas Town structure from the working directory.
// This handles cases where GT_ROOT is not set but the process is running
// inside a Gas Town workspace (crew sessions, residual tmux sessions, etc.).
func IsDaemonManaged() bool {
return isDaemonManaged("")
}
// IsDaemonManagedFor is like IsDaemonManaged but also checks the beadsDir
// path for Gas Town indicators. Use this when beadsDir is available.
func IsDaemonManagedFor(beadsDir string) bool {
return isDaemonManaged(beadsDir)
}
func isDaemonManaged(beadsDir string) bool {
if os.Getenv("GT_ROOT") != "" {
return true
}
return isGasTownContext(beadsDir)
}
// gasTownPathSegments are directory names distinctive to Gas Town rig worktrees.
// A standalone beads project would never have these in its path.
var gasTownPathSegments = []string{
"crew",
"polecats",
"refinery",
"witness",
"deacon",
"mayor",
}
// gasTownRootMarkers are subdirectory names that identify a Gas Town root
// or rig directory. Presence of 2+ of these as siblings is definitive.
var gasTownRootMarkers = []string{
"daemon",
"deacon",
"warrants",
"mayor",
"crew",
"refinery",
}
// isGasTownContext detects Gas Town workspace from the working directory
// and optionally from the beadsDir path.
func isGasTownContext(beadsDir string) bool {
if wd, err := os.Getwd(); err == nil {
if HasGasTownPathSegment(wd) {
return true
}
if walkUpForGasTownRoot(wd) {
return true
}
}
if beadsDir != "" {
if HasGasTownPathSegment(beadsDir) {
return true
}
if walkUpForGasTownRoot(filepath.Dir(beadsDir)) {
return true
}
}
return false
}
// HasGasTownPathSegment reports whether path contains a directory component
// that is distinctive to Gas Town workspaces.
func HasGasTownPathSegment(path string) bool {
// Split into directory components to avoid substring false positives
// (e.g., "screwdriver" should not match "crew").
parts := strings.Split(filepath.ToSlash(path), "/")
for _, part := range parts {
for _, seg := range gasTownPathSegments {
if part == seg {
return true
}
}
}
return false
}
// isGasTownRoot checks if dir is a Gas Town root by looking for 2+
// distinctive Gas Town subdirectories as siblings.
func isGasTownRoot(dir string) bool {
count := 0
for _, marker := range gasTownRootMarkers {
info, err := os.Stat(filepath.Join(dir, marker))
if err == nil && info.IsDir() {
count++
if count >= 2 {
return true
}
}
}
return false
}
// walkUpForGasTownRoot walks up from dir checking each ancestor
// (including dir itself) for Gas Town root markers.
func walkUpForGasTownRoot(dir string) bool {
abs, err := filepath.Abs(dir)
if err != nil {
return false
}
for {
if isGasTownRoot(abs) {
return true
}
parent := filepath.Dir(abs)
if parent == abs {
return false
}
abs = parent
}
}
// FlushWorkingSet connects to the running Dolt server and commits any uncommitted
// working set changes across all databases. This prevents data loss when the server
// is about to be stopped or restarted. Returns nil if there's nothing to flush or
@ -771,17 +594,12 @@ func FlushWorkingSet(host string, port int) error {
}
// Stop gracefully stops the managed server and its idle monitor.
// Under Gas Town (GT_ROOT set), refuses to stop the daemon-managed server
// unless force is true.
func Stop(beadsDir string) error {
return StopWithForce(beadsDir, false)
}
// StopWithForce is like Stop but allows overriding the Gas Town daemon guard.
// StopWithForce is like Stop but with an optional force flag.
func StopWithForce(beadsDir string, force bool) error {
if !force && IsDaemonManagedFor(beadsDir) {
return fmt.Errorf("Dolt server is managed by the Gas Town daemon.\nUse 'gt dolt stop' instead, or pass --force to override.")
}
state, err := IsRunning(beadsDir)
if err != nil {
@ -820,13 +638,7 @@ func LogPath(beadsDir string) string {
}
// KillStaleServers finds and kills orphan dolt sql-server processes
// not tracked by the canonical PID file. Under Gas Town, the canonical
// server is at $GT_ROOT/.beads/ or $GT_ROOT/daemon/dolt.pid (daemon-managed);
// in standalone mode, beadsDir is used.
//
// Under Gas Town, if no canonical PID can be identified from either location,
// this function refuses to kill anything to avoid accidentally killing the
// daemon-managed server.
// not tracked by the canonical PID file.
// Returns the PIDs of killed processes.
func KillStaleServers(beadsDir string) ([]int, error) {
allPIDs := listDoltProcessPIDs()
@ -844,22 +656,6 @@ func KillStaleServers(beadsDir string) ([]int, error) {
}
}
}
// Under Gas Town, also check the daemon-managed PID file
if gtRoot := os.Getenv("GT_ROOT"); gtRoot != "" {
daemonPidFile := filepath.Join(gtRoot, "daemon", "dolt.pid")
if data, readErr := os.ReadFile(daemonPidFile); readErr == nil { //nolint:gosec // G304: path constructed from trusted GT_ROOT env
if pid, parseErr := strconv.Atoi(strings.TrimSpace(string(data))); parseErr == nil && pid > 0 {
canonicalPIDs[pid] = true
}
}
}
// Under Gas Town, if we can't identify any canonical server, refuse to
// kill anything. Without knowing which process is canonical, we'd kill
// all dolt servers including the daemon-managed one.
if IsDaemonManagedFor(beadsDir) && len(canonicalPIDs) == 0 {
return nil, fmt.Errorf("under Gas Town but no canonical PID file found\n\nThe Dolt server is likely managed by the gt daemon. Use 'gt dolt' commands instead.\nTo force kill all dolt servers: pkill -f 'dolt sql-server'")
}
var killed []int
for _, pid := range allPIDs {
@ -867,7 +663,7 @@ func KillStaleServers(beadsDir string) ([]int, error) {
continue
}
if canonicalPIDs[pid] {
continue // preserve canonical/daemon-managed server
continue // preserve canonical server
}
if proc, findErr := os.FindProcess(pid); findErr == nil {
_ = proc.Kill()
@ -1058,15 +854,7 @@ func stopServerProcess(beadsDir string) error {
// forkIdleMonitor starts the idle monitor as a detached process.
// It runs `bd dolt idle-monitor --beads-dir=<dir>` in the background.
// Under Gas Town, the idle monitor is not forked — the daemon handles lifecycle.
func forkIdleMonitor(beadsDir string) {
// Under Gas Town, the daemon manages server lifecycle (health checks,
// restart on crash, etc.). Don't fork a beads idle monitor that could
// interfere by stopping the shared server.
if IsDaemonManagedFor(beadsDir) {
return
}
// Don't fork if there's already a monitor running
if isMonitorRunning(beadsDir) {
return
@ -1148,15 +936,10 @@ func ReadActivityTime(beadsDir string) time.Time {
// (watchdog behavior).
//
// idleTimeout of 0 means monitoring is disabled (exits immediately).
// Under Gas Town, exits immediately — the daemon handles server lifecycle.
func RunIdleMonitor(beadsDir string, idleTimeout time.Duration) {
if idleTimeout == 0 {
return
}
// Belt and suspenders: don't run under Gas Town even if somehow forked.
if IsDaemonManagedFor(beadsDir) {
return
}
// Tracks when we stopped the server for idle timeout. Zero means we
// haven't performed an idle shutdown (or the server was restarted since).

View file

@ -86,14 +86,13 @@ func NewFromConfigWithOptions(ctx context.Context, beadsDir string, cfg *Config)
//
// Priority (highest to lowest):
// 1. BEADS_TEST_MODE=1 → always false (tests own the server lifecycle)
// 2. IsDaemonManaged() → always false (Gas Town manages the server)
// 3. BEADS_DOLT_AUTO_START=0 → always false (explicit env opt-out)
// 4. explicitPort == true → always false (metadata.json has explicit port;
// 2. BEADS_DOLT_AUTO_START=0 → always false (explicit env opt-out)
// 3. explicitPort == true → always false (metadata.json has explicit port;
// auto-starting a different server would create shadow databases)
// 5. current == true → true (caller option wins over config file,
// 4. current == true → true (caller option wins over config file,
// per NewFromConfigWithOptions contract)
// 6. doltAutoStartCfg == "false"/"0"/"off" → false (config.yaml opt-out)
// 7. default → true (standalone user; safe default)
// 5. doltAutoStartCfg == "false"/"0"/"off" → false (config.yaml opt-out)
// 6. default → true (standalone user; safe default)
//
// doltAutoStartCfg is the raw value of the "dolt.auto-start" key from config.yaml
// (pass config.GetString("dolt.auto-start") at the call site).
@ -106,9 +105,6 @@ func resolveAutoStart(current bool, doltAutoStartCfg string, explicitPort bool)
if os.Getenv("BEADS_TEST_MODE") == "1" {
return false
}
if doltserver.IsDaemonManaged() {
return false
}
if os.Getenv("BEADS_DOLT_AUTO_START") == "0" {
return false
}

View file

@ -600,30 +600,9 @@ func newServerMode(ctx context.Context, cfg *Config) (*DoltStore, error) {
return nil, fmt.Errorf("Dolt server auto-started but still unreachable at %s: %w\n\n"+
"Check logs: %s", addr, dialErr, doltserver.LogPath(beadsDir))
}
} else if doltserver.IsDaemonManaged() && os.Getenv("BEADS_TEST_MODE") != "1" {
// Gas Town detected (GT_ROOT or filesystem heuristic) — delegate
// server start to gt, which manages the lifecycle properly.
// Skip in test mode: tests manage their own server via testutil.EnsureDoltContainerForTestMain.
gtBin, lookErr := exec.LookPath("gt")
if lookErr != nil {
return nil, fmt.Errorf("Dolt server unreachable at %s (Gas Town detected but 'gt' not found in PATH): %w\n\n"+
"Start the server with: gt dolt start", addr, dialErr)
}
cmd := exec.CommandContext(ctx, gtBin, "dolt", "start")
if out, runErr := cmd.CombinedOutput(); runErr != nil {
return nil, fmt.Errorf("Dolt server unreachable at %s and 'gt dolt start' failed: %w\n\ngt output: %s",
addr, runErr, strings.TrimSpace(string(out)))
}
// Retry connection after gt started the server
conn, dialErr = net.DialTimeout("tcp", addr, 3*time.Second)
if dialErr != nil {
breaker.RecordFailure()
return nil, fmt.Errorf("Dolt server still unreachable at %s after 'gt dolt start': %w",
addr, dialErr)
}
} else {
breaker.RecordFailure()
return nil, fmt.Errorf("Dolt server unreachable at %s: %w\n\nThe Dolt server may not be running. Try:\n bd dolt start # Start a local server\n gt dolt start # If using Gas Town",
return nil, fmt.Errorf("Dolt server unreachable at %s: %w\n\nThe Dolt server may not be running. Try:\n bd dolt start",
addr, dialErr)
}
}