beads/cmd/bd/direct_mode.go
Julian Knutsen 2f1e8be3ca
feat(backends): registry Remote + OpenWith options; beads.OpenBestAvailableWith for embedders (#7188)
* feat(backends): registry Remote + optional OpenWith(ctx, dir, OpenOptions)

Slice S1: backends.Backend gains Remote bool and an optional
OpenWith(ctx, beadsDir, OpenOptions{Credential, HTTPClient, UserAgent}) so a
registered extension backend can honor a per-open credential instead of
dialing with a process-global client — the motivating case is one embedder
process serving many workspaces with distinct credentials. Open keeps
working unmodified for every existing backend: Backend.OpenWithOptions calls
OpenWith when present, otherwise falls back to Open and ignores
HTTPClient/UserAgent, but refuses (ErrCredentialWithoutOpenWith) rather than
silently dropping a non-nil Credential.

Public beads.OpenBestAvailableWith(ctx, beadsDir, opts) carries this through
the SDK surface (mirrored in beads_nocgo.go and aliased in backend/backend.go
and beads.go); OpenBestAvailable is now that call with a zero OpenOptions,
identical to its prior behavior for Dolt, embedded Dolt, and every registered
backend. The plain-Dolt path (no registered backend) applies the same
Credential refusal, since Dolt has no per-open credential seam either.

doltserver.ResolvePhysicalRoots now checks backends.IsRemote(cfg.GetBackend())
before every Dolt-mode branch, including the shared-server check (which reads
only env/config.yaml and never consults cfg) — without this ordering, a global
BEADS_DOLT_SHARED_SERVER=1 would hijack a remote-backend workspace into
reporting a bogus local Dolt root it will never open.

Tests: backends_test new file open_with_test.go covers OpenWithOptions
dispatch/back-compat/Credential refusal and Remote/IsRemote; root package
open_backend_selection_test.go adds a fake OpenWith registrant proving
dispatch and option pass-through through OpenBestAvailableWith, zero-options
back-compat for every path (registered w/ and w/o OpenWith, plain Dolt), and
the Credential-without-OpenWith refusal on both paths; doltserver
physical_root_test.go adds the registered-remote-backend case including the
shared-server-override ordering regression test. Verified under both cgo and
nocgo builds. Live-mutated each new guard (the Credential refusal, the
OpenWith dispatch, the ResolvePhysicalRoots remote-backend case, and the
plain-Dolt Credential refusal) one at a time and confirmed RED before
reverting to GREEN.

No HTTP client code added; that is a later slice.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fixup(backends): address Opus review findings on OpenWith (M1-M3, L1-L2)

- M1: frame cmd/bd store-open errors for remote backends as unreachable
  server failures instead of Dolt-shaped "failed to open database"
  advice (openStoreErrorMessage, backendNameForErrorFraming), with tests.
- M2: rewrite the OpenBestAvailable/OpenBestAvailableWith back-compat
  subtest to assert fixed expected outcomes (error identity/message,
  returned store behavior) now that the two functions are identical,
  instead of comparing them to each other.
- M3: document and enforce the OpenWith contract: an implementation that
  receives a non-nil Credential it cannot type-assert to its expected
  type must refuse with the new ErrUnsupportedCredential sentinel,
  verified with a fake registrant.
- L1: document that a nil OpenOptions.Credential means the backend's
  default/ambient auth, and that multi-tenant embedders must pass a
  non-nil Credential (RequireCredential deferred to S2).
- L2: fail closed on HTTPClient/UserAgent passed to a backend without
  OpenWith, mirroring the existing Credential refusal, via new
  ErrHTTPClientWithoutOpenWith/ErrUserAgentWithoutOpenWith sentinels.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/37195230844
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

* fix(backends): keep the store-open error chain through the remote framing

Maintainer review fixes for the adopted PR (iteration 1).

openStoreErrorMessage returned a string, so ensureStoreActiveWithContext
rebuilt its error from text (%s) where base wrapped the open error with %w,
and the chain ended at the CLI's framing. Prime tells a store-open timeout
apart from a generic "storage unavailable" only through
errors.Is(err, context.DeadlineExceeded) on what ensureStoreActiveWithContext
returns (cmd/bd/prime.go), so the flattening silently downgraded that
diagnostic for every backend, Dolt included, not just the new Remote ones.

Replace the helper with openStoreError, which returns an error wrapping err
with %w on both arms. The message text is unchanged: "failed to open
database: <err>" for Dolt and any registered backend that is not Remote,
"failed to reach remote backend %q: <err>" for a Remote one. direct_mode.go
wraps the result with %w ahead of its Hint line; main.go keeps printing it
through HandleError("%v", ...), which only formats.

Tests:

- TestOpenStoreErrorFramesRemoteBackends (renamed from
  TestOpenStoreErrorMessageFramesRemoteBackends) now also asserts errors.Is
  on every arm, and the exact original text for the non-Remote arms.
- TestEnsureStoreActiveKeepsOpenErrorChain drives the real
  ensureStoreActiveWithContext against a registered backend whose open
  outlives its context, for a local and a Remote backend, and requires
  errors.Is(err, context.DeadlineExceeded) plus the framing prefix and the
  Hint line.
- TestFormatMemoriesForPrimeTimesOutOpeningRegisteredBackend is the
  unstubbed twin of TestFormatMemoriesForPrimeTimesOutOpeningStore and
  requires the timeout banner, not the "storage unavailable" one.

Measured at this head: turning direct_mode.go's outer %w into %v reddens
both chain-test rows and the prime test; turning the helper's %w into %v
reddens the framing test as well.

Non-gating cleanup in the same area:

- beads_cgo.go, beads_nocgo.go: OpenBestAvailableWith's doc and dispatch
  comments said only a non-nil Credential is refused. The code also refuses
  a non-nil HTTPClient and a non-empty UserAgent, each with its own
  ErrXWithoutOpenWith sentinel.
- internal/doltserver/physical_root.go: the Mode doc lists "remote-backend",
  and the RemoteBackend doc covers a registered Remote backend as well as a
  Dolt server on a non-local host.
- open_backend_selection_test.go: the plain-Dolt refusal test is a table
  over Credential, HTTPClient and UserAgent (renamed
  TestOpenBestAvailableWithRefusesPerOpenOptionsOnPlainDolt). Disabling the
  nocgo HTTPClient arm or the cgo UserAgent arm reddens only that row. The
  zero-options test's comment had the delegation backwards and pointed at
  beads.go; OpenBestAvailable delegates to OpenBestAvailableWith in
  beads_cgo.go and beads_nocgo.go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-04 09:34:36 -07:00

65 lines
1.8 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"github.com/steveyegge/beads/internal/beads"
)
// ErrNoBeadsDatabase reports that no beads workspace could be resolved at all,
// as distinct from a workspace whose storage failed to open. Callers that must
// tell "nothing here" apart from "the store is broken" — `bd prime`'s memory
// injection, for one — match on it with errors.Is rather than on the message.
var ErrNoBeadsDatabase = errors.New("no beads database found")
// ensureDirectMode makes sure the CLI is operating in direct-storage mode.
func ensureDirectMode(_ string) error {
return ensureStoreActive()
}
// ensureStoreActive guarantees that a storage backend is initialized and tracked.
// Uses the factory to respect metadata.json backend configuration.
func ensureStoreActive() error {
return ensureStoreActiveWithContext(getRootContext())
}
func ensureStoreActiveWithContext(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
lockStore()
active := isStoreActive() && getStore() != nil
unlockStore()
if active {
return nil
}
// Find the .beads directory
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
return fmt.Errorf("%w.\n"+
"Hint: run 'bd init' to create a database in the current directory", ErrNoBeadsDatabase)
}
// Use the factory to create the appropriate backend
// based on metadata.json configuration and build tags
store, err := newDoltStoreFromConfig(ctx, beadsDir)
if err != nil {
return fmt.Errorf("%w\nHint: %s", openStoreError(backendNameForErrorFraming(beadsDir), err), diagHint())
}
// Update the database path for compatibility with code that expects it
if dbPath := beads.FindDatabasePath(); dbPath != "" {
setDBPath(dbPath)
}
lockStore()
setStore(store)
setStoreActive(true)
unlockStore()
return nil
}