fix(dolt): an env-inherited server yields to the project's declared endpoint on an identity mismatch

An agent session carries its own workspace's Dolt server in its
environment (BEADS_DOLT_SERVER_HOST/PORT). Run inside a different
checkout whose .beads explicitly declares its own server, bd took the
env's endpoint (env outranks config.yaml and metadata.json), found
another project's database there, and the identity guard refused
(PROJECT IDENTITY MISMATCH): the project was unusable from that session,
and the refusal was misread as a broken workspace.

New now opens through openWithEnvEndpointFallback. On the identity
refusal, when the port came from the environment and the project's own
.beads declares a different endpoint (config.yaml dolt.host/dolt.port,
else metadata.json dolt_server_host/dolt_server_port; bd's port-file
bookkeeping is no declaration), it retries once there. The retry is
verified like any open: on a match bd proceeds with a note on stderr;
if the declared endpoint serves another project too, the original
refusal stands. A port from any other source, a socket, a gateway and
the shared server are untouched. No schema change.

The refusal is now a typed error (projectIdentityMismatch) with its
message unchanged.

Tests (fake servers, no live endpoints): the declared endpoint is opened
and used, with a note, for a config.yaml host:port or a bare port; a
declared endpoint that serves another project too returns the env
server's original refusal; a config-sourced port, a project declaring
nothing or the env's own endpoint, and any other error open once as
before; metadata.json declarations are read. Mutants dropping the retry,
the env-source condition, or returning the retry's error fail.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-10-14 18:31:05 +00:00
commit 643615c26a
5 changed files with 287 additions and 1 deletions

View file

@ -509,6 +509,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- A server endpoint inherited from the environment (`BEADS_DOLT_SERVER_PORT`)
no longer locks bd out of a project that declares its own: when the env's
server answers with another project's database (PROJECT IDENTITY MISMATCH)
and the project's `.beads` explicitly declares a different endpoint
(`config.yaml` `dolt.host`/`dolt.port`, else `metadata.json`
`dolt_server_host`/`dolt_server_port`), bd retries once on that endpoint,
verifies the project's identity there, and proceeds with a note on stderr;
if that endpoint serves another project too, it refuses with the original
error. An agent session carrying its own workspace's server in its
environment can now run bd inside a different checkout. Ports from any
other source, sockets, gateways and the shared server are unchanged.
- **`bd gate list` works over a connected HTTP workspace** (S20). The
workspace-wide listing built a raw `SearchIssues` filter, which the HTTP
backend refuses, so gc's `renudge-stale-human-gates` order failed on every

View file

@ -27,6 +27,7 @@ go_library(
"dependencies.go",
"dependency_editor.go",
"edgereader.go",
"env_endpoint_fallback.go",
"ephemeral_routing.go",
"errors.go",
"events.go",
@ -214,6 +215,7 @@ go_test(
"dualwrite_history_contract_test.go",
"edge_reader_contract_test.go",
"empty_commit_test.go",
"env_endpoint_fallback_test.go",
"ephemeral_routing_test.go",
"errors_test.go",
"event_commit_boundary_test.go",

View file

@ -0,0 +1,115 @@
package dolt
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/doltserver"
)
// projectIdentityMismatch is verifyProjectIdentity's refusal: the database the
// resolved endpoint serves belongs to another project.
type projectIdentityMismatch struct{ err error }
func (e *projectIdentityMismatch) Error() string { return e.err.Error() }
// isProjectIdentityMismatch reports whether err is verifyProjectIdentity's
// refusal.
func isProjectIdentityMismatch(err error) bool {
var m *projectIdentityMismatch
return errors.As(err, &m)
}
// declaredEndpoint is the server endpoint a project's own .beads declares.
type declaredEndpoint struct {
host string
port int
source doltserver.PortSource
}
// envEndpointFallbackNote receives the note the fallback prints when it opens
// the project's own endpoint instead of the inherited one. A var so tests can
// capture it.
var envEndpointFallbackNote io.Writer = os.Stderr
// openWithEnvEndpointFallback opens cfg with open and, when the open is
// refused for a project identity mismatch on an endpoint that came from the
// environment (BEADS_DOLT_SERVER_PORT, an agent's inherited server for
// ANOTHER project), retries once on the endpoint the project's own .beads
// explicitly declares, when it declares one that differs. A session that
// carries its own workspace's server in its environment and runs bd inside a
// different checkout otherwise reached the wrong server, and the identity
// guard refused (gascity mc-3gbed). The retry is verified exactly as the
// first open was: a project whose declared endpoint serves another project
// too is refused, with the original error. A note on stderr names the switch.
func openWithEnvEndpointFallback(ctx context.Context, cfg *Config, open func(context.Context, *Config) (*DoltStore, error)) (*DoltStore, error) {
store, err := open(ctx, cfg)
if err == nil || !isProjectIdentityMismatch(err) {
return store, err
}
alt, ok := envEndpointFallback(cfg)
if !ok {
return nil, err
}
retry := *cfg
retry.ServerHost, retry.ServerPort, retry.ServerPortSource = alt.host, alt.port, alt.source
altStore, altErr := open(ctx, &retry)
if altErr != nil {
return nil, err
}
if w := envEndpointFallbackNote; w != nil {
fmt.Fprintf(w, "bd: the inherited server %s (BEADS_DOLT_SERVER_PORT) serves another project; using this project's own endpoint %s from %s\n", //nolint:errcheck // best-effort note
net.JoinHostPort(cfg.ServerHost, strconv.Itoa(cfg.ServerPort)), net.JoinHostPort(alt.host, strconv.Itoa(alt.port)), alt.source)
}
*cfg = retry
return altStore, nil
}
// envEndpointFallback reports the endpoint to retry when cfg's came from the
// environment: the one the project's own .beads explicitly declares
// (config.yaml dolt.port, else metadata.json dolt_server_port, with the
// matching host, 127.0.0.1 by default), when it differs from cfg's. bd's own
// port-file bookkeeping is not a declaration and does not count; nor does a
// socket, a gateway, or the shared server.
func envEndpointFallback(cfg *Config) (declaredEndpoint, bool) {
if cfg == nil || cfg.ServerPortSource != doltserver.PortSourceEnv || cfg.BeadsDir == "" ||
cfg.ServerSocket != "" || cfg.Gateway || cfg.Database == doltserver.GlobalDatabaseName ||
doltserver.IsSharedServerModeForDir(cfg.BeadsDir) {
return declaredEndpoint{}, false
}
alt, ok := projectDeclaredEndpoint(cfg.BeadsDir)
if !ok || (alt.host == cfg.ServerHost && alt.port == cfg.ServerPort) {
return declaredEndpoint{}, false
}
return alt, true
}
// projectDeclaredEndpoint reads the endpoint beadsDir's own config explicitly
// declares.
func projectDeclaredEndpoint(beadsDir string) (declaredEndpoint, bool) {
if raw := strings.TrimSpace(config.GetStringFromDir(beadsDir, "dolt.port")); raw != "" {
if port, err := strconv.Atoi(raw); err == nil && port > 0 {
host := strings.TrimSpace(config.GetStringFromDir(beadsDir, "dolt.host"))
return declaredEndpoint{host: hostOrLoopback(host), port: port, source: doltserver.PortSourceConfigYaml}, true
}
}
if meta, err := configfile.Load(beadsDir); err == nil && meta != nil && meta.DoltServerPort > 0 {
return declaredEndpoint{host: hostOrLoopback(meta.DoltServerHost), port: meta.DoltServerPort, source: doltserver.PortSourceMetadataJSON}, true
}
return declaredEndpoint{}, false
}
func hostOrLoopback(host string) string {
if host = strings.TrimSpace(host); host != "" {
return host
}
return "127.0.0.1"
}

View file

@ -0,0 +1,152 @@
package dolt
import (
"bytes"
"context"
"errors"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/steveyegge/beads/internal/doltserver"
)
// fakeServers answers an open by the endpoint it targets: a store, the
// identity refusal, or another error. Endpoints not listed refuse to connect.
type fakeServers struct {
stores map[string]*DoltStore
foreign map[string]bool // the server holds another project: its id is "other-" + the endpoint
opened []string
otherErrs map[string]error
}
func (f *fakeServers) open(_ context.Context, cfg *Config) (*DoltStore, error) {
addr := net.JoinHostPort(cfg.ServerHost, strconv.Itoa(cfg.ServerPort))
f.opened = append(f.opened, addr)
switch {
case f.foreign[addr]:
return nil, projectIdentityMismatchError("local-project", "other-"+addr, "beads", false)
case f.otherErrs[addr] != nil:
return nil, f.otherErrs[addr]
case f.stores[addr] != nil:
return f.stores[addr], nil
}
return nil, errors.New("connection refused")
}
// beadsDirWith is a .beads dir whose config.yaml holds yaml (none when empty).
func beadsDirWith(t *testing.T, yaml string) string {
t.Helper()
dir := filepath.Join(t.TempDir(), ".beads")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if yaml != "" {
if err := os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(yaml), 0o644); err != nil {
t.Fatal(err)
}
}
return dir
}
func captureFallbackNote(t *testing.T) *bytes.Buffer {
t.Helper()
var buf bytes.Buffer
prev := envEndpointFallbackNote
envEndpointFallbackNote = &buf
t.Cleanup(func() { envEndpointFallbackNote = prev })
return &buf
}
// TestEnvEndpointYieldsToTheProjectsDeclaredEndpointOnIdentityMismatch
// (gascity mc-3gbed). Kills the inherited BEADS_DOLT_SERVER_PORT of another
// workspace winning over the project's own explicit endpoint: on the identity
// refusal from the env's server, the project's declared endpoint is opened
// and verified, and used, with a note; a declared endpoint that serves
// another project too is refused with the original error.
func TestEnvEndpointYieldsToTheProjectsDeclaredEndpointOnIdentityMismatch(t *testing.T) {
own := &DoltStore{}
for _, c := range []struct {
name string
yaml string
foreign []string
wantOpen []string
want *DoltStore
}{
{"the declared endpoint is the project's", "dolt:\n host: 127.0.0.1\n port: 3307\n", []string{"127.0.0.1:45865"}, []string{"127.0.0.1:45865", "127.0.0.1:3307"}, own},
{"the declared port, the loopback by default", "dolt.port: 3307\n", []string{"127.0.0.1:45865"}, []string{"127.0.0.1:45865", "127.0.0.1:3307"}, own},
{"the declared endpoint serves another project too", "dolt.port: 3307\n", []string{"127.0.0.1:45865", "127.0.0.1:3307"}, []string{"127.0.0.1:45865", "127.0.0.1:3307"}, nil},
} {
t.Run(c.name, func(t *testing.T) {
note := captureFallbackNote(t)
f := &fakeServers{stores: map[string]*DoltStore{"127.0.0.1:3307": own}, foreign: map[string]bool{}}
for _, a := range c.foreign {
f.foreign[a] = true
}
cfg := &Config{BeadsDir: beadsDirWith(t, c.yaml), ServerHost: "127.0.0.1", ServerPort: 45865, ServerPortSource: doltserver.PortSourceEnv}
got, err := openWithEnvEndpointFallback(context.Background(), cfg, f.open)
if strings.Join(f.opened, " ") != strings.Join(c.wantOpen, " ") {
t.Fatalf("opened %v, want %v", f.opened, c.wantOpen)
}
if c.want == nil {
if got != nil || !isProjectIdentityMismatch(err) || !strings.Contains(err.Error(), "other-127.0.0.1:45865") || cfg.ServerPort != 45865 || note.Len() != 0 {
t.Fatalf("got %v, %v, cfg port %d, note %q; want the original refusal (the env server's), cfg untouched, no note", got, err, cfg.ServerPort, note.String())
}
return
}
if err != nil || got != c.want || cfg.ServerPort != 3307 || cfg.ServerPortSource == doltserver.PortSourceEnv || !strings.Contains(note.String(), "127.0.0.1:3307") {
t.Fatalf("got %v, %v, cfg %s:%d (%s), note %q; want the project's store, cfg on its endpoint, a note", got, err, cfg.ServerHost, cfg.ServerPort, cfg.ServerPortSource, note.String())
}
})
}
}
// TestEnvEndpointFallbackStaysNarrow (gascity mc-3gbed). Kills a fallback
// that second-guesses anything but the case it is for: a port that did not
// come from the environment, a project that declares nothing, or declares
// the env's own endpoint, and any error but the identity refusal, all open
// once and return as before.
func TestEnvEndpointFallbackStaysNarrow(t *testing.T) {
for _, c := range []struct {
name string
yaml string
source doltserver.PortSource
other bool // the env's server fails with another error
}{
{"a port from the project's config", "dolt.port: 3307\n", doltserver.PortSourceConfigYaml, false},
{"a project that declares nothing", "", doltserver.PortSourceEnv, false},
{"a project that declares the env's endpoint", "dolt.port: 45865\n", doltserver.PortSourceEnv, false},
{"another error", "dolt.port: 3307\n", doltserver.PortSourceEnv, true},
} {
t.Run(c.name, func(t *testing.T) {
note := captureFallbackNote(t)
f := &fakeServers{stores: map[string]*DoltStore{"127.0.0.1:3307": {}}, foreign: map[string]bool{}, otherErrs: map[string]error{}}
if c.other {
f.otherErrs["127.0.0.1:45865"] = errors.New("server down")
} else {
f.foreign["127.0.0.1:45865"] = true
}
cfg := &Config{BeadsDir: beadsDirWith(t, c.yaml), ServerHost: "127.0.0.1", ServerPort: 45865, ServerPortSource: c.source}
if _, err := openWithEnvEndpointFallback(context.Background(), cfg, f.open); err == nil || len(f.opened) != 1 || note.Len() != 0 {
t.Fatalf("err %v, opened %v, note %q; want the first open's error, one open, no note", err, f.opened, note.String())
}
})
}
}
// TestProjectDeclaredEndpointReadsMetadataJSON: a project that declares its
// server in metadata.json (dolt_server_host/port) is honored when its
// config.yaml declares none.
func TestProjectDeclaredEndpointReadsMetadataJSON(t *testing.T) {
dir := beadsDirWith(t, "")
if err := os.WriteFile(filepath.Join(dir, "metadata.json"), []byte(`{"dolt_server_host":"10.0.0.5","dolt_server_port":3307}`), 0o644); err != nil {
t.Fatal(err)
}
got, ok := projectDeclaredEndpoint(dir)
if !ok || got.host != "10.0.0.5" || got.port != 3307 || got.source != doltserver.PortSourceMetadataJSON {
t.Fatalf("declared endpoint %+v, %v; want metadata.json's 10.0.0.5:3307", got, ok)
}
}

View file

@ -1793,7 +1793,7 @@ func New(ctx context.Context, cfg *Config) (*DoltStore, error) {
cfg.Database, addr)
}
return newServerMode(ctx, cfg)
return openWithEnvEndpointFallback(ctx, cfg, newServerMode)
}
// resolveLocalActiveDatabaseDir returns an authoritative local path only for
@ -2451,6 +2451,11 @@ func (s *DoltStore) verifyProjectIdentity(ctx context.Context, beadsDir string,
// init instead. Every other open, CreateIfMissing or not, keeps its original
// text.
func projectIdentityMismatchError(localID, dbID, database string, openedByInit bool) error {
return &projectIdentityMismatch{err: projectIdentityMismatchMessage(localID, dbID, database, openedByInit)}
}
// projectIdentityMismatchMessage is projectIdentityMismatchError's text.
func projectIdentityMismatchMessage(localID, dbID, database string, openedByInit bool) error {
if openedByInit {
return fmt.Errorf(
"PROJECT IDENTITY MISMATCH — refusing to initialize against an existing database\n\n"+