* fix(configfile): carry graph_mode and graph_* binding through Save Graph-preview builds of bd persist a per-workspace format in metadata.json: "graph_mode": "link" plus graph_scope_url, graph_authority_id, graph_workspace, graph_schema_version and graph_ready, beside an ordinary Dolt backend. configfile.Config had no such fields, so every Save, and Load's config.json -> metadata.json migration, rewrote the file without them, turning a graph workspace's metadata into an ordinary Issue workspace's. Config now carries the marker and the binding as omitempty fields, so a Save round-trips them unchanged and metadata.json written for an ordinary workspace is byte-for-byte what it was. GetGraphMode resolves the marker: absent or "dependency" is the historical default, "link" is recognized, and any other value is an error rather than a fallback to the Issue store. Nothing in this build opens a non-default mode; the CLI refusal follows in the next commit. Ported from the donnabox fork commit deea8d57df (graph_mode.go, graph_mode_test.go and the configfile.go fields), without any graph code. The binding-survives-Save and omitted-from-ordinary-metadata tests are new. Co-authored-by: Donna Box <dbox@boxenllc.com> Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(cli): refuse graph_mode workspaces before opening them A workspace whose metadata.json declares a graph_mode other than "dependency" holds a graph database behind an ordinary Dolt backend, and nothing else in its metadata says so. bd admitted it like any current workspace: `bd list` ran the Issue schema initialization against the graph database (beads_graph_<id>), `bd init --force` wrote a .gitignore and a .beads/dolt root into it, `bd dolt start` started a server for it, and `bd doctor` reported on it as an Issue store. guardLegacyUpgradeWorkspace, the admission check every store-opening command, store-less command with workspace effects, init, doctor and bootstrap already run before touching a workspace, now refuses such a workspace first, before the legacy classifications that would admit it or report it as a legacy store to migrate. An unknown graph_mode value is refused the same way. The refusal is a typed error naming the workspace and the format, rendered with a hint (as JSON under --json) and exit code 16, ExitUnsupportedWorkspaceFormat, so a wrapper can tell "needs a different bd build" from a generic failure. `bd version`, `bd --version`, `bd help` and completion stay exempt, as they are for legacy workspaces. validateConfiguredBackend refuses the same metadata, which covers the store-open paths that skip command admission (routed writes, cross-repository reads, create --repo). Tests: guard and store-factory unit tests; a subprocess e2e test that show/list/create/context/where/dolt start/doctor/bootstrap/init are refused with exit 16 and leave .beads byte-identical (metadata.json and legacy config.json, link and unknown markers, embedded and server layouts), and that store-less commands still run; an embedded test that an ordinary workspace, with the marker absent or "dependency", still creates and lists issues and keeps the marker through a metadata.json rewrite. The guard hunk and graph_mode_admission_e2e_test.go are ported from the donnabox fork commit deea8d57df; the exit code, rendering, store factory backstop and remaining tests are new. Co-authored-by: Donna Box <dbox@boxenllc.com> Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(cli): refuse graph workspaces reached outside command admission Command admission refuses a graph_mode workspace a command runs in, but bd also reaches workspaces before or without admission: a create --repo target, the path --db or BEADS_DB names, and the stores the factories open for routed and cross-repository work. On those paths a workspace marked only by a legacy config.json was changed before anything refused it: configfile.Load migrates config.json into metadata.json before the format check sees the loaded metadata, and create --repo initialized such a target as a new workspace. Where the refusal did come, create reported it with exit 1 rather than 16. - checkDiscoveredWorkspaceFormat checks a workspace's metadata as configfile.LoadForDiscovery reads it, which never rewrites it. ensureBeadsDirForPath, the dry-run target open and the four store factories (cgo and nocgo builds) run it before their own load. - resolveBeadsDirForDBPath and findDatabaseInBeadsDir locate a workspace with LoadForDiscovery, so resolving --db, BEADS_DB or a create target no longer migrates it. - bd create renders a refused target as the workspace refusal, exit 16 with its hint, on the initializing and both dry-run paths. A dry run without --parent opens no target, so it now checks a local one before rendering the preview (checkRepoTargetFormat). - bd bootstrap, when discovery finds no workspace, reads each .beads from the working directory up to the repository root without migrating it and refuses one in a format this build cannot open, the way commands without a workspace already do. A .beads marked only by config.json is passed over by discovery, so bootstrap reported "no workspace" there instead of exit 16. The walk now returns its candidates (undiscoveredWorkspaceCandidates) to both checks: handing it the check as a func(string) error made gosec's G702 taint analysis connect BEADS_DIR to every func(string) error that runs git. - backendNameForErrorFraming reads with LoadForDiscovery, and loadDoltBackendConfig, bd dolt status and bd dolt show refuse a graph workspace before their migrating configfile.Load. Admission refuses first on every path that reaches them today; this keeps a new caller from migrating a legacy config.json before the refusal. - The CHANGELOG entry and the configfile comment now claim what holds: a routed read fails without touching a graph workspace but not with code 16, and a Save keeps only the known graph_* fields, with the tags graph-preview builds declare. workspace_gate.go no longer lists the pre-gate discovery reads as migrating. - New e2e rows run create --repo from a workspace and from outside one, create --dry-run with and without --parent, --db, BEADS_DB, init --proxied-server, bootstrap in a workspace nested in a graph one, and the hook shim's bd hooks run pre-commit against every fixture; each refusal must exit 16 and name the format and the hint. bootstrap in a workspace marked only by config.json now refuses like the other commands. The store factory test also runs on a config.json graph workspace, TestWorkspaceMetadataReadersLeaveGraphWorkspaceUnchanged covers the framing, bd dolt loader and diagnostic reads, and TestNocgoStoreFactoriesRefuseGraphWorkspace covers the CGO_ENABLED=0 factories; bazel.yml's pure lane runs it by name (PURE_CMD_BD_TESTS, pinned in scripts/ci_workflow_test.go). Measured with gocyclo/gocognit: every function this changes stays below the PR's worst changed function (guardLegacyUpgradeWorkspaceForInit 29/28, resolveBeadsDirForDBPath 26/36); showDoltConfig is 19/31 (was 18/30) and guardUndiscoveredLegacyWorkspace 3/3 (was 9/12). Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Donna Box <dbox@boxenllc.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
4035 lines
185 KiB
Go
4035 lines
185 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"os/exec"
|
|
"os/user"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/cmd/bd/doctor"
|
|
"github.com/steveyegge/beads/cmd/bd/setup"
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"github.com/steveyegge/beads/internal/doltserver"
|
|
"github.com/steveyegge/beads/internal/git"
|
|
"github.com/steveyegge/beads/internal/gitenv"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/backends"
|
|
"github.com/steveyegge/beads/internal/storage/dbproxy/proxy"
|
|
"github.com/steveyegge/beads/internal/storage/dolt"
|
|
"github.com/steveyegge/beads/internal/storage/schema"
|
|
"github.com/steveyegge/beads/internal/templates/agents"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
"github.com/steveyegge/beads/internal/utils"
|
|
"github.com/steveyegge/beads/issueops"
|
|
"golang.org/x/term"
|
|
)
|
|
|
|
// applyInitGatewayCredential routes the hand-built init Dolt config through the
|
|
// gateway credential machinery. When BEADS_DOLT_CREDENTIAL_COMMAND is configured,
|
|
// its short-lived token becomes the connection username, the config is marked as
|
|
// targeting an authenticating gateway server (so the store skips schema init and
|
|
// the SHOW/CREATE DATABASE probe), and local auto-start is disabled — a gateway
|
|
// server is externally managed, and spawning a local dolt server would shadow it.
|
|
//
|
|
// It runs only when the config targets a server (ServerMode). An embedded init
|
|
// never presents a username, so an ambient credential command must not run — or
|
|
// fail — an embedded open. This mirrors the canonical open path
|
|
// (internal/storage/dolt/open.go), which gates the command on
|
|
// IsDoltServerMode()||IsSharedServerMode(). Without this gate, a plain embedded
|
|
// `bd init` on a host that exports BEADS_DOLT_CREDENTIAL_COMMAND would drag the
|
|
// gateway machinery into an ordinary local init and abort it with a misleading
|
|
// provisioning-contract error, leaving a half-initialized .beads/. Gateway init
|
|
// always reaches here with ServerMode set: init forces server mode for a shared
|
|
// server and hard-fails a remote dolt host that lacks server mode.
|
|
//
|
|
// The main command path applies this via applyResolvedConfig; init builds its own
|
|
// config and must mirror the behavior. Within server mode it is still a no-op when
|
|
// no command is configured or when a --server-user flag already preset the
|
|
// username. It fails closed: a configured-but-failing command aborts init.
|
|
func applyInitGatewayCredential(ctx context.Context, beadsDir string, doltCfg *dolt.Config) error {
|
|
if !doltCfg.ServerMode {
|
|
return nil
|
|
}
|
|
fileCfg, _ := configfile.Load(beadsDir)
|
|
if fileCfg == nil {
|
|
fileCfg = configfile.DefaultConfig()
|
|
}
|
|
applied, err := dolt.ApplyGatewayCredential(ctx, fileCfg, doltCfg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if applied {
|
|
// ApplyGatewayCredential sets DisableAutoStart, but the hand-built init
|
|
// config path never runs ApplyCLIAutoStart to translate that into the
|
|
// AutoStart field the store's auto-start block actually consults.
|
|
doltCfg.AutoStart = false
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolveInitIssuePrefix decides which issue_prefix init would set. readErr is
|
|
// the error (if any) from reading the workspace's identity out of the database.
|
|
//
|
|
// Non-gateway (legacy, unchanged): if none is configured yet, return the
|
|
// sanitized prefix (dots -> underscores so issue IDs stay valid identifiers); if
|
|
// one exists, return "" — there is nothing to set, because init must not clobber
|
|
// a prefix a shared database already carries. readErr is ignored here, exactly
|
|
// as legacy init ignored it. Gateway: the prefix is server-provisioned, so an
|
|
// existing value is adopted. A missing value is a provisioning-contract
|
|
// violation — bd will not choose a prefix for a hosted database — but only when
|
|
// the read genuinely succeeded and returned empty: a read error means we could
|
|
// not consult the server, so it is surfaced as the transient failure it is
|
|
// rather than misdiagnosed as an unprovisioned database.
|
|
//
|
|
// Whether the prefix may be WRITTEN is not decided here: that is the same
|
|
// question as whether the substrate is unidentified, and issueops.Bootstrapper
|
|
// answers it inside the transaction it writes in.
|
|
func resolveInitIssuePrefix(gateway bool, existing, dbName, prefix string, readErr error) (value string, err error) {
|
|
if existing != "" {
|
|
return "", nil
|
|
}
|
|
if gateway {
|
|
if readErr != nil {
|
|
return "", fmt.Errorf(
|
|
"reading issue_prefix from hosted database %q: %w", dbName, readErr)
|
|
}
|
|
return "", fmt.Errorf(
|
|
"hosted database %q has no issue_prefix -- provisioning-contract violation; "+
|
|
"bd will not choose one for a hosted database (re-provision server-side, then re-run init)",
|
|
dbName)
|
|
}
|
|
return strings.ReplaceAll(prefix, ".", "_"), nil
|
|
}
|
|
|
|
// resolveInitProjectID decides init's project identity by reconciling the local
|
|
// metadata.json id (localID; "" when none is set yet) with the _project_id read
|
|
// from the database (adoptedFromDB; "" when absent or not consulted). readErr is
|
|
// the error, if any, from that read. changed reports whether the resolved id
|
|
// differs from localID, so the caller can surface the reconciliation.
|
|
//
|
|
// Gateway: the hosted database's identity is server-authoritative, so an adopted
|
|
// server id always wins and is reconciled onto local even when localID is already
|
|
// set. A re-init or orchestrator-preseeded workspace must not keep a stale local
|
|
// id: for Gateway specifically, init's CreateIfMissing:true open still skips the
|
|
// storage identity verifier (store.go verifyProjectIdentity/newServerMode — see
|
|
// its dbAlreadyExisted comment for why Gateway is exempt from the
|
|
// otherwise-CreateIfMissing:true check), so a stale id would be saved as success
|
|
// and every later normal open would then hard-fail with PROJECT IDENTITY
|
|
// MISMATCH. This CreateIfMissing skip is Gateway-only: a non-gateway
|
|
// CreateIfMissing:true init against an already-existing database now DOES run
|
|
// the verifier (GH#4637 Part A) and fails before reaching this reconciliation.
|
|
// A missing server id is a provisioning-contract violation bd will not mint
|
|
// over — even when a local id already exists — and a read error is surfaced as
|
|
// the transient failure it is, so a flaky connection is not misdiagnosed as an
|
|
// unprovisioned database.
|
|
//
|
|
// Non-gateway (legacy, unchanged): a non-empty localID is kept as-is (readErr
|
|
// ignored, exactly as before); otherwise an adopted id wins (another rig already
|
|
// chose it; minting a new one would break cross-project verification), else a
|
|
// fresh identity is generated.
|
|
func resolveInitProjectID(gateway bool, localID, adoptedFromDB, dbName string, readErr error) (value string, changed bool, err error) {
|
|
if gateway {
|
|
if adoptedFromDB != "" {
|
|
return adoptedFromDB, adoptedFromDB != localID, nil
|
|
}
|
|
if readErr != nil {
|
|
return "", false, fmt.Errorf(
|
|
"reading project identity (_project_id) from hosted database %q: %w", dbName, readErr)
|
|
}
|
|
return "", false, fmt.Errorf(
|
|
"hosted database %q has no provisioned project identity (_project_id) -- "+
|
|
"provisioning-contract violation; bd will not mint an identity for a hosted database",
|
|
dbName)
|
|
}
|
|
if localID != "" {
|
|
return localID, false, nil
|
|
}
|
|
if adoptedFromDB != "" {
|
|
return adoptedFromDB, true, nil
|
|
}
|
|
return configfile.GenerateProjectID(), true, nil
|
|
}
|
|
|
|
// shouldConsultInitProjectID reports whether init must read _project_id from the
|
|
// database before resolving the local identity.
|
|
//
|
|
// Gateway: always — the hosted server owns the identity, so init reconciles it on
|
|
// every run, including a re-init or preseeded metadata.json that already carries a
|
|
// project_id. Skipping the read when a local id was already set was the bug that
|
|
// let init save a stale id and made every later normal open hard-fail PROJECT
|
|
// IDENTITY MISMATCH.
|
|
//
|
|
// Non-gateway (legacy, unchanged): only when no local id exists yet and the
|
|
// database is a pre-existing shared/bootstrapped one worth adopting from
|
|
// (--database set or bootstrapped-from-remote). A fresh local-only init mints its
|
|
// own id without a read.
|
|
func shouldConsultInitProjectID(gateway bool, localID, database string, bootstrappedFromRemote bool) bool {
|
|
if gateway {
|
|
return true
|
|
}
|
|
return localID == "" && (database != "" || bootstrappedFromRemote)
|
|
}
|
|
|
|
// shouldWriteProjectIDLocally reports whether init should write _project_id back
|
|
// to the database. Non-gateway writes it for cross-project verification; gateway
|
|
// does not — the identity is server-authoritative, and the credential may be
|
|
// read-only.
|
|
func shouldWriteProjectIDLocally(gateway bool, projectID string) bool {
|
|
return !gateway && projectID != ""
|
|
}
|
|
|
|
// shouldWriteInitStateToDB reports whether init may write clone-local tracking
|
|
// state into the database — the bd_version / repo_id / clone_id / last_import_time
|
|
// metadata and the initial-state Dolt commit.
|
|
//
|
|
// Non-gateway (legacy, unchanged): true — these writes give diagnostics accurate
|
|
// data and leave a clean, committed working set.
|
|
//
|
|
// Gateway: false. The database is a shared, server-owned store: repo_id and
|
|
// clone_id are per-clone fingerprints that cross-project verification (doctor,
|
|
// migrate) reads back, so a last-init-wins overwrite there produces false mismatch
|
|
// diagnostics for every other clone; and the credential may be read-only, in which
|
|
// case each write and the DOLT_COMMIT would merely spew per-init warnings. In
|
|
// gateway mode bd adopts and verifies server state instead of writing it, exactly
|
|
// as shouldWriteProjectIDLocally already suppresses the _project_id write-back.
|
|
func shouldWriteInitStateToDB(gateway bool) bool {
|
|
return !gateway
|
|
}
|
|
|
|
// shouldInitSharedGlobalDB reports whether init should manage the local shared
|
|
// Dolt server and provision its beads_global database — starting the server,
|
|
// creating the global database, initializing its schema, and seeding its config.
|
|
//
|
|
// Shared-server mode owns that local infrastructure, so it does. Gateway mode
|
|
// does not: a gateway connects to a remote authenticating server that provisions
|
|
// databases server-side under no-create/no-schema/no-write semantics. Running the
|
|
// shared-global path there would either start a shadow local server or drive
|
|
// create/schema/write operations against the gateway — the global initializer
|
|
// rebuilds its own dolt.Config without the Gateway flag and with CreateIfMissing
|
|
// set, so it cannot preserve gateway semantics. init therefore skips the whole
|
|
// shared-global path whenever the connection is gateway-managed, mirroring how
|
|
// shouldWriteInitStateToDB / shouldWriteProjectIDLocally already suppress
|
|
// server-owned writes.
|
|
func shouldInitSharedGlobalDB(sharedServer, sharedServerMode, gateway bool) bool {
|
|
return (sharedServer || sharedServerMode) && !gateway
|
|
}
|
|
|
|
// externalServerUnreachableMessage returns the message for an --external init
|
|
// whose server could not be dialed, or "" when err is any other failure.
|
|
//
|
|
// --external declares the server managed outside bd, so init starts none. The
|
|
// store's own advice for a dead local server, "bd dolt start", would start the
|
|
// very server --external says bd must not, and the store words this failure
|
|
// differently per route (shared server, socket, remote host, auto-start pinned
|
|
// off). One message serves them all: it names the endpoint that was dialed and
|
|
// says that bd did not start a server.
|
|
//
|
|
// A dial to port 0 is the exception. The store leaves a zero port zero for
|
|
// auto-start to fill in, so it means nothing named a port: the address is a
|
|
// placeholder, not an endpoint. The message says so and how to name one, and
|
|
// offers no default, since on a shared machine whatever listens on a default
|
|
// port may belong to another project (GH#2098, GH#2372).
|
|
func externalServerUnreachableMessage(err error) string {
|
|
var opErr *net.OpError
|
|
if !errors.As(err, &opErr) || opErr.Op != "dial" {
|
|
return ""
|
|
}
|
|
if addr, ok := opErr.Addr.(*net.TCPAddr); ok && addr.Port == 0 {
|
|
return fmt.Sprintf("Error: failed to open Dolt store: %v\n\n"+
|
|
"--external declares the Dolt server externally managed, so bd did not start one, and no port was named for it.\n"+
|
|
"Name the server's port with --server-port or BEADS_DOLT_SERVER_PORT.\n", opErr)
|
|
}
|
|
endpoint := "the configured endpoint"
|
|
if opErr.Addr != nil {
|
|
endpoint = opErr.Addr.String()
|
|
}
|
|
return fmt.Sprintf("Error: failed to open Dolt store: %v\n\n"+
|
|
"--external declares the Dolt server at %s externally managed, so bd did not start one.\n"+
|
|
"Start that server, or point init at the right endpoint.\n", opErr, endpoint)
|
|
}
|
|
|
|
// warnHalfIdentifiedSubstrate reports a substrate carrying one identity marker
|
|
// and not the other.
|
|
//
|
|
// Both halves are named because they fail differently. Without a project id,
|
|
// cross-project verification has nothing to compare and each rig mints its own
|
|
// local one, so the divergence is invisible until something backfills the
|
|
// database. Without a prefix, the substrate cannot name an issue and every
|
|
// later open reports the workspace as uninitialized.
|
|
func warnHalfIdentifiedSubstrate(found issueops.VerifyIdentityResult) {
|
|
if isQuiet() {
|
|
return
|
|
}
|
|
switch {
|
|
case found.Prefix != "" && found.ProjectID == "":
|
|
fmt.Fprintf(os.Stderr, "%s the database has an issue prefix (%s) but no project identity.\n"+
|
|
" bd will not complete a half-identified database. This workspace's metadata.json now carries a\n"+
|
|
" project id that only THIS clone knows; another clone's init will mint a different one, and the\n"+
|
|
" first `bd doctor --fix` will backfill the database from whichever clone ran it — after which the\n"+
|
|
" others refuse to open with PROJECT IDENTITY MISMATCH.\n"+
|
|
" Settle it deliberately: run `bd doctor --fix` from the clone whose identity should win, then\n"+
|
|
" re-init the others.\n",
|
|
ui.RenderWarn("WARNING:"), found.Prefix)
|
|
case found.ProjectID != "" && found.Prefix == "":
|
|
fmt.Fprintf(os.Stderr, "%s the database has a project identity but no issue prefix.\n"+
|
|
" bd will not complete a half-identified database, and a substrate with no prefix cannot name an\n"+
|
|
" issue: later commands will report this workspace as uninitialized.\n"+
|
|
" Set it deliberately with `bd config set issue_prefix <prefix>`.\n",
|
|
ui.RenderWarn("WARNING:"))
|
|
}
|
|
}
|
|
|
|
// seedInitWorkspaceIdentity records the workspace's identity through
|
|
// issueops.Bootstrapper, or adopts the one already on the substrate.
|
|
//
|
|
// VERIFY, THEN BOOTSTRAP OR ADOPT. The role REFUSES an already-identified
|
|
// substrate, so asking first is how a front door tells a workspace it may
|
|
// identify from one it must leave alone. That refusal is what makes `bd init`
|
|
// safe to run against a database another rig is already minting ids in: before
|
|
// this, the proxied route rewrote both markers every time.
|
|
//
|
|
// found is the identity the caller already read with InitVerifier, in the same
|
|
// snapshot it read the prefix in. projectID is "" only when init composed no
|
|
// metadata.json — an explicit BEADS_DIR whose Dolt data lives elsewhere — and the
|
|
// workspace's own metadata.json is then the place to ask.
|
|
func seedInitWorkspaceIdentity(
|
|
ctx context.Context,
|
|
store storage.DoltStorage,
|
|
found issueops.VerifyIdentityResult,
|
|
prefix, projectID, beadsDir string,
|
|
) error {
|
|
if store == nil {
|
|
return nil
|
|
}
|
|
if found.Prefix != "" || found.ProjectID != "" {
|
|
// Adopt. The caller has already reconciled metadata.json against
|
|
// found.ProjectID; re-stamping the substrate would say nothing new.
|
|
//
|
|
// A HALF-IDENTIFIED SUBSTRATE IS SAID OUT LOUD. Bootstrapper refuses to
|
|
// complete one on purpose — it cannot tell a half-written bootstrap
|
|
// from a deliberately half-provisioned database, and guessing wrong
|
|
// destroys the one it did not mean — so init cannot fix this and must
|
|
// not leave the operator thinking it did. Silence here is what arms the
|
|
// failure: with no _project_id to adopt, every rig's init mints a
|
|
// DIFFERENT local one, and the first `bd doctor --fix` backfills the
|
|
// database from whichever rig ran it, after which every other rig's
|
|
// open hard-fails PROJECT IDENTITY MISMATCH with advice that
|
|
// misdiagnoses the cause.
|
|
warnHalfIdentifiedSubstrate(found)
|
|
return nil
|
|
}
|
|
if projectID == "" {
|
|
// No metadata.json was composed on this path. Take the id the workspace
|
|
// already records so the substrate and the file agree, and mint one only
|
|
// when neither exists: a prefix without an identity is the
|
|
// half-bootstrapped state the role refuses to complete later.
|
|
if existing, err := configfile.Load(beadsDir); err == nil && existing != nil {
|
|
projectID = existing.ProjectID
|
|
}
|
|
if projectID == "" {
|
|
projectID = configfile.GenerateProjectID()
|
|
}
|
|
}
|
|
|
|
bootstrapper, err := store.Bootstrapper()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to reach the workspace identity: %v", err)
|
|
}
|
|
_, err = bootstrapper.Bootstrap(ctx, issueops.BootstrapRequest{
|
|
Prefix: prefix,
|
|
ProjectID: projectID,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("failed to record the workspace identity: %v", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolveUserHomeDir returns the user's home directory.
|
|
//
|
|
// It prefers the OS account database over $HOME so the guard keys off the real
|
|
// account home even when $HOME has been repointed — which happens constantly in
|
|
// this repo's own tests, and in any sandbox that fakes a home. Both sources are
|
|
// best-effort: in a CGO-free build user.Current() falls back to os.UserHomeDir()
|
|
// (i.e. $HOME on Unix) itself, so this is a preference, not a guarantee of
|
|
// $HOME-independence. Mirrors the home resolution in internal/beads'
|
|
// isPathInSafeBoundary.
|
|
//
|
|
// A package var so tests can stub it.
|
|
var resolveUserHomeDir = func() string {
|
|
if u, err := user.Current(); err == nil && u.HomeDir != "" {
|
|
return u.HomeDir
|
|
}
|
|
home, _ := os.UserHomeDir()
|
|
return home
|
|
}
|
|
|
|
// isUserHomeDir reports whether dir is the user's home directory (path-boundary
|
|
// comparison, symlink/case tolerant). Used to guard `bd init` against turning
|
|
// $HOME into a git repo (GH#4635).
|
|
func isUserHomeDir(dir string) bool {
|
|
home := resolveUserHomeDir()
|
|
return home != "" && utils.PathsEqual(dir, home)
|
|
}
|
|
|
|
// isGitWorkTreeRoot reports whether dir is itself the top level of a git work
|
|
// tree. It asks through initArtifactGitCommand, the way init's own `git init`
|
|
// decision does, so git's routing environment is scrubbed: an inherited
|
|
// GIT_DIR or GIT_WORK_TREE cannot vouch for a directory that init's probe will
|
|
// then find untracked and `git init`. And the top level must be dir itself: a
|
|
// home that merely sits inside an ancestor's work tree was never tracked on
|
|
// purpose, and init would still install agent files into it.
|
|
func isGitWorkTreeRoot(dir string) bool {
|
|
out, err := initArtifactGitCommand(dir, "rev-parse", "--show-toplevel").Output()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return utils.PathsEqual(strings.TrimSpace(string(out)), dir)
|
|
}
|
|
|
|
// guardInitInHomeDir refuses `bd init` directly in the user's home directory
|
|
// when that directory is not itself a git repository and the caller did not
|
|
// name a BEADS_DIR.
|
|
//
|
|
// `bd init` sets up the directory it runs in as a project: it runs `git init`
|
|
// there unless it finds a repository, and installs agent files (CLAUDE.md,
|
|
// AGENTS.md, .gitignore, .agents/, .codex/, .cursor/, .claude/settings.json).
|
|
// In the home directory most of those are the agents' user-wide settings, so
|
|
// bd's hooks would run in every project — a silent footgun, especially under
|
|
// --non-interactive, which auto-engages whenever stdin is not a TTY, i.e.
|
|
// whenever an agent runs init (GH#4635). A real project is virtually never the
|
|
// home directory itself.
|
|
//
|
|
// This runs as the first thing in init's RunE, ahead of every path that has an
|
|
// effect: the proxied dispatch (runInitProxiedServer -> EnsureGitRepo -> git
|
|
// init), the --reinit-local/--force pre-checks (countExistingIssues opens a
|
|
// real store, which creates the data directory and can run migrations), and
|
|
// the mode globals RunE sets on itself. A guard placed after any of those
|
|
// refuses only after the damage it exists to prevent.
|
|
//
|
|
// Fail-open by construction: an unresolvable home, a working directory that is
|
|
// not home, or a home that is itself a git repository all mean "not the case
|
|
// this guards", and init proceeds unchanged.
|
|
//
|
|
// A caller-supplied BEADS_DIR is the opt-out the refusal offers, and keepHomeClean
|
|
// holds it to what the refusal promises. Init proceeds, but does not set the
|
|
// home directory up as a project: an explicit BEADS_DIR already skips the
|
|
// `git init`, and keepHomeClean tells RunE to skip the agent files and the
|
|
// project .gitignore too. Without that, the recommended escape hatch still
|
|
// installed the user-wide agent settings the refusal exists to keep out of
|
|
// $HOME.
|
|
//
|
|
// keepHomeClean also means "outside every repository". It is only ever true
|
|
// when the home is not itself a work-tree root, so any repository git finds
|
|
// from here is not the home's own: one enclosing it (a dotfiles or monorepo
|
|
// checkout above it), or one an inherited GIT_DIR names. The opt-out must not
|
|
// set that repository up as the project either: no hooks, no beads.role or
|
|
// fork setup, no Dolt remote taken from its origin, and no bootstrap commit,
|
|
// which would stage the legacy ~/.beads and whatever agent files the home
|
|
// already has into it. Each route gates those on keepHomeClean where it
|
|
// reaches them. Flags that ask for a change there still make it: --stealth
|
|
// and --setup-exclude write its .git/info/exclude, and the interactive
|
|
// --contributor and --team wizards work in it.
|
|
//
|
|
// The opt-out check reads beadsDirFromCaller, NOT os.Getenv("BEADS_DIR"). By the
|
|
// time this runs the root PersistentPreRunE has already exported a beads dir it
|
|
// discovered for itself, and beads.FindBeadsDir() accepts any ancestor .beads/
|
|
// holding a config.yaml — including this project's own legacy user-level
|
|
// ~/.beads/config.yaml. Keying off the live environment therefore made the
|
|
// guard fail open for exactly the long-standing users most likely to have
|
|
// scaffolding in $HOME worth not clobbering. `bd -C <dir> init` exported one
|
|
// too, and that one does not even move the working directory the scaffolding
|
|
// lands in.
|
|
//
|
|
// Refusals carry ExitHomeDirRefused so a script can branch on the number, like
|
|
// init's three other refusal classes. The message is printed here rather than
|
|
// returned so the exit code is the error's whole payload; docs/recovery/
|
|
// init-safety.md#init-home-refused is the recovery playbook it points at.
|
|
func guardInitInHomeDir() (keepHomeClean bool, err error) {
|
|
cwd, wdErr := os.Getwd()
|
|
if wdErr != nil || !isUserHomeDir(cwd) || isGitWorkTreeRoot(cwd) {
|
|
return false, nil
|
|
}
|
|
if beadsDirFromCaller != "" {
|
|
return true, nil
|
|
}
|
|
fmt.Fprintf(os.Stderr, "%s\n", homeDirRefusalMessage(cwd))
|
|
return false, &exitError{Code: ExitHomeDirRefused}
|
|
}
|
|
|
|
// homeDirRefusalMessage is the What/Why/Next refusal text for a `bd init` run
|
|
// directly in an untracked home directory.
|
|
//
|
|
// The BEADS_DIR escape hatch is described as what it is: not the refused init
|
|
// with the guard lifted, but a different one that sets up only the workspace
|
|
// the caller names (see keepHomeClean in guardInitInHomeDir). Saying "set
|
|
// BEADS_DIR if you really mean it" without that caveat sends the user somewhere
|
|
// they did not intend to go. The `mkdir -p` is load-bearing, not decoration:
|
|
// init refuses a BEADS_DIR whose parent directory does not exist yet.
|
|
func homeDirRefusalMessage(cwd string) string {
|
|
return fmt.Sprintf(`bd init refuses: %s is your home directory, and it is not itself a git repository.
|
|
|
|
Why: init sets up the directory it runs in as a project: it runs
|
|
'git init' there unless it finds a repository, and installs agent
|
|
files (CLAUDE.md, AGENTS.md, .gitignore, .claude/, .codex/,
|
|
.cursor/, .agents/). In your home directory most of those are
|
|
user-wide agent settings, so bd's hooks would run in every project.
|
|
A project is virtually never the home directory itself.
|
|
|
|
Next:
|
|
Initialize a project instead (recommended):
|
|
cd ~/some-project && bd init
|
|
|
|
Keep the workspace in a directory you name, without setting up your
|
|
home directory as a project:
|
|
mkdir -p <dir> && BEADS_DIR=<dir>/.beads bd init
|
|
(a BEADS_DIR you name runs a DIFFERENT init: no git init, agent
|
|
files, .gitignore, hooks or commit here or in a repository around
|
|
it; the workspace lives in <dir>)
|
|
|
|
Recovery playbook:
|
|
docs/recovery/init-safety.md#init-home-refused`, cwd)
|
|
}
|
|
|
|
var initCmd = &cobra.Command{
|
|
Use: "init",
|
|
GroupID: "setup",
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
Short: "Initialize bd in the current directory",
|
|
Long: `Initialize bd in the current directory by creating a .beads/ directory
|
|
and its storage (a Dolt database by default). Optionally specify a custom issue prefix.
|
|
|
|
Dolt is the default and only supported storage backend, with full version
|
|
control (history, branching, sync).
|
|
|
|
Use --database to specify an existing server database name, overriding the
|
|
default prefix-based naming. This is useful when an external tool (e.g. an orchestrator)
|
|
has already created the database.
|
|
|
|
With --stealth: configures per-repository git settings for invisible beads usage:
|
|
• .git/info/exclude to prevent beads files from being committed
|
|
Perfect for personal use without affecting repo collaborators.
|
|
To set up a specific AI tool, run: bd setup <claude|cursor|aider|...> --stealth
|
|
|
|
By default, beads uses an embedded Dolt engine (no external server needed).
|
|
Pass --server to use an external dolt sql-server instead. In server mode,
|
|
set connection details with --server-host, --server-port, and --server-user.
|
|
Password should be set via BEADS_DOLT_PASSWORD environment variable.
|
|
|
|
Auto-export is optional. When enabled, bd exports issues to
|
|
.beads/issues.jsonl after write commands (throttled to once per 60s). This is
|
|
for viewers (bv), interchange, and issue-level migration; not backup.
|
|
Cross-machine sync and backups use Dolt remotes/backups, not JSONL import/export.
|
|
To enable: bd config set export.auto true
|
|
|
|
Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|
Skips all interactive prompts, using sensible defaults:
|
|
• Role defaults to "maintainer" (override with --role)
|
|
• Fork exclude auto-configured when fork detected
|
|
• Auto-export left at default (disabled)
|
|
• --contributor and --team flags are rejected (wizards require interaction)
|
|
Also auto-detected when stdin is not a terminal or CI=true is set.`,
|
|
RunE: func(cmd *cobra.Command, _ []string) (retErr error) {
|
|
// First, before anything with an effect: never turn $HOME into a git
|
|
// repo or install agent files into it (GH#4635). See
|
|
// guardInitInHomeDir for why the position matters.
|
|
keepHomeClean, homeErr := guardInitInHomeDir()
|
|
if homeErr != nil {
|
|
return homeErr
|
|
}
|
|
|
|
prefix, _ := cmd.Flags().GetString("prefix")
|
|
quiet, _ := cmd.Flags().GetBool("quiet")
|
|
contributor, _ := cmd.Flags().GetBool("contributor")
|
|
team, _ := cmd.Flags().GetBool("team")
|
|
stealth, _ := cmd.Flags().GetBool("stealth")
|
|
skipHooks, _ := cmd.Flags().GetBool("skip-hooks")
|
|
skipAgents, _ := cmd.Flags().GetBool("skip-agents")
|
|
force, _ := cmd.Flags().GetBool("force")
|
|
reinitLocal, _ := cmd.Flags().GetBool("reinit-local")
|
|
initIfMissing, _ := cmd.Flags().GetBool("init-if-missing")
|
|
discardRemote, _ := cmd.Flags().GetBool("discard-remote")
|
|
recreateMissing, _ := cmd.Flags().GetBool("recreate-missing")
|
|
// Assigned here, beside the flag read, and deliberately NOT beside the
|
|
// guard it gates: runInit dispatches to runInitProxiedServer and
|
|
// returns well before that point, while runInitProxiedServer calls
|
|
// checkExistingBeadsData, which reads this global. Assigning it later
|
|
// left --recreate-missing inert on the --proxied-server route, so the
|
|
// refusal told the operator to pass the flag they had just passed. Keep
|
|
// every route that can reach the guard downstream of this line.
|
|
initAllowRecreateMissing = recreateMissing
|
|
nonInteractiveFlag, _ := cmd.Flags().GetBool("non-interactive")
|
|
roleFlag, _ := cmd.Flags().GetString("role")
|
|
fromJSONL, _ := cmd.Flags().GetBool("from-jsonl")
|
|
initRemote, _ := cmd.Flags().GetString("remote")
|
|
initRemoteChanged := cmd.Flags().Changed("remote")
|
|
// Dolt server connection flags
|
|
backendFlag, _ := cmd.Flags().GetString("backend")
|
|
initServerMode, _ := cmd.Flags().GetBool("server")
|
|
serverHost, _ := cmd.Flags().GetString("server-host")
|
|
serverPort, _ := cmd.Flags().GetInt("server-port")
|
|
serverSocket, _ := cmd.Flags().GetString("server-socket")
|
|
serverUser, _ := cmd.Flags().GetString("server-user")
|
|
database, _ := cmd.Flags().GetString("database")
|
|
destroyToken, _ := cmd.Flags().GetString("destroy-token")
|
|
// Keep the exact input the former destructive-confirmation block used:
|
|
// before config/dirname fallback and before normalization.
|
|
destroyTokenPrefix := prefix
|
|
|
|
// The caller named a BEADS_DIR from an untracked home directory: the
|
|
// opt-out the home refusal offers, held to what it promises. Skipping
|
|
// the agent files and hooks here covers both routes (the proxied one
|
|
// reads both from its input); the project .gitignore, the role and
|
|
// fork setup, the origin-derived Dolt remote and the bootstrap commit
|
|
// are gated on keepHomeClean where each route reaches them, because
|
|
// any repository around the home is not the project's (see
|
|
// guardInitInHomeDir).
|
|
if keepHomeClean {
|
|
skipAgents = true
|
|
skipHooks = true
|
|
if !quiet {
|
|
fmt.Fprintln(os.Stderr, "Note: this is your home directory, so init sets up only the workspace BEADS_DIR names: no agent files, .gitignore, hooks or commit here or in a repository around it.")
|
|
fmt.Fprintln(os.Stderr, " To install an agent integration for every project on purpose: bd setup <recipe> --global")
|
|
}
|
|
}
|
|
|
|
// --force is a deprecated alias for --reinit-local. They share
|
|
// semantics for the local data-safety guard; both refuse remote
|
|
// divergence unless --discard-remote is also passed. See
|
|
// engdocs/adr/0002-init-safety-invariants.md.
|
|
if force && !reinitLocal {
|
|
fmt.Fprintf(os.Stderr, "%s --force is deprecated; use --reinit-local instead.\n", ui.RenderWarn("DeprecationWarning:"))
|
|
fmt.Fprintf(os.Stderr, " See 'bd help init-safety' for the init flag surface.\n\n")
|
|
reinitLocal = true
|
|
}
|
|
|
|
// dc-6jaq: "init" is in noDbCommands, so PersistentPreRunE returns at
|
|
// the skip-store early return before its freeze gate ever runs, and
|
|
// init.go calls neither CheckReadonly nor the gate itself. That left
|
|
// the single most destructive command in the CLI free to run during a
|
|
// migration: `bd init --reinit-local` (or its --force alias) drops and
|
|
// recreates the very database the marker is protecting, permanently,
|
|
// and exited 0 without consulting the marker. Gate the destructive
|
|
// variants here — the earliest point where every one of them is
|
|
// resolved and nothing has been written yet, and ahead of the
|
|
// --proxied-server branch below, which reaches its own writes without
|
|
// passing through the init mutation gate at all.
|
|
//
|
|
// A plain first-time init is deliberately not gated: it creates a new
|
|
// database rather than touching the frozen one, and an existing
|
|
// workspace already refuses it via checkExistingBeadsData.
|
|
if reinitLocal || discardRemote {
|
|
op := "init --reinit-local"
|
|
if discardRemote {
|
|
op = "init --discard-remote"
|
|
}
|
|
if err := migrationFreezeGateFor(cmd, op, resolveInitBeadsDir()); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
sharedServer, _ := cmd.Flags().GetBool("shared-server")
|
|
externalServer, _ := cmd.Flags().GetBool("external")
|
|
debugMode, _ := cmd.Flags().GetBool("debug")
|
|
initProxiedServer, _ := cmd.Flags().GetBool("proxied-server")
|
|
initTeamServer, _ := cmd.Flags().GetBool("team-server")
|
|
serverConfigPath, _ := cmd.Flags().GetString("proxied-server-config-path")
|
|
serverLogPath, _ := cmd.Flags().GetString("proxied-server-log-path")
|
|
serverRootPath, _ := cmd.Flags().GetString("proxied-server-root-path")
|
|
serverProxyPort, _ := cmd.Flags().GetInt("proxied-server-port")
|
|
serverProxyIdleTimeout, _ := cmd.Flags().GetDuration("proxied-server-idle-timeout")
|
|
idleTimeoutSet := cmd.Flags().Changed("proxied-server-idle-timeout")
|
|
externalHost, _ := cmd.Flags().GetString("proxied-server-external-host")
|
|
externalPort, _ := cmd.Flags().GetInt("proxied-server-external-port")
|
|
externalSocketPath, _ := cmd.Flags().GetString("proxied-server-external-socket-path")
|
|
externalUser, _ := cmd.Flags().GetString("proxied-server-external-user")
|
|
externalTLS, _ := cmd.Flags().GetBool("proxied-server-external-tls")
|
|
externalTLSCACertPath, _ := cmd.Flags().GetString("proxied-server-external-tls-ca-cert-path")
|
|
externalTLSCertPath, _ := cmd.Flags().GetString("proxied-server-external-tls-cert-path")
|
|
externalTLSKeyPath, _ := cmd.Flags().GetString("proxied-server-external-tls-key-path")
|
|
externalTLSServerName, _ := cmd.Flags().GetString("proxied-server-external-tls-server-name")
|
|
externalTLSSkipVerify, _ := cmd.Flags().GetBool("proxied-server-external-tls-skip-verify")
|
|
externalKeepAlive, _ := cmd.Flags().GetDuration("proxied-server-external-keep-alive")
|
|
if os.Getenv("BEADS_DOLT_PROXIED_SERVER") == "1" {
|
|
initProxiedServer = true
|
|
}
|
|
|
|
initEvt := metrics.NewCommandEvent("init-" + resolveInitDoltMode(initProxiedServer, sharedServer, initServerMode))
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(initEvt)
|
|
}
|
|
}()
|
|
|
|
if initProxiedServer && initServerMode {
|
|
return fmt.Errorf("--server and --proxied-server are mutually exclusive")
|
|
}
|
|
if initProxiedServer {
|
|
if sharedServer || externalServer ||
|
|
serverHost != "" || serverPort != 0 || serverSocket != "" || serverUser != "" || cmd.Flags().Changed("server-tls") {
|
|
return fmt.Errorf("--proxied-server cannot be combined with --shared-server, --external, or any --server-* flag")
|
|
}
|
|
}
|
|
if initTeamServer && !initProxiedServer {
|
|
return fmt.Errorf("--team-server requires --proxied-server")
|
|
}
|
|
if serverConfigPath != "" {
|
|
if !initProxiedServer {
|
|
return fmt.Errorf("--proxied-server-config-path requires --proxied-server")
|
|
}
|
|
if !filepath.IsAbs(serverConfigPath) {
|
|
return fmt.Errorf("--proxied-server-config-path must be an absolute path, got %q", serverConfigPath)
|
|
}
|
|
if err := validateProxiedServerConfig(serverConfigPath); err != nil {
|
|
return fmt.Errorf("--proxied-server-config-path %v", err)
|
|
}
|
|
}
|
|
if serverLogPath != "" {
|
|
if !initProxiedServer {
|
|
return fmt.Errorf("--proxied-server-log-path requires --proxied-server")
|
|
}
|
|
if !filepath.IsAbs(serverLogPath) {
|
|
return fmt.Errorf("--proxied-server-log-path must be an absolute path, got %q", serverLogPath)
|
|
}
|
|
if err := validateProxiedServerLogPath(serverLogPath); err != nil {
|
|
return fmt.Errorf("--proxied-server-log-path %v", err)
|
|
}
|
|
}
|
|
if serverRootPath != "" {
|
|
if !initProxiedServer {
|
|
return fmt.Errorf("--proxied-server-root-path requires --proxied-server")
|
|
}
|
|
if !filepath.IsAbs(serverRootPath) {
|
|
return fmt.Errorf("--proxied-server-root-path must be an absolute path, got %q", serverRootPath)
|
|
}
|
|
if err := validateProxiedServerRootPath(serverRootPath); err != nil {
|
|
return fmt.Errorf("--proxied-server-root-path %v", err)
|
|
}
|
|
}
|
|
if serverProxyPort != 0 {
|
|
if !initProxiedServer {
|
|
return fmt.Errorf("--proxied-server-port requires --proxied-server")
|
|
}
|
|
if serverProxyPort < 1 || serverProxyPort > 65535 {
|
|
return fmt.Errorf("--proxied-server-port must be between 1 and 65535, got %d", serverProxyPort)
|
|
}
|
|
}
|
|
if idleTimeoutSet {
|
|
if !initProxiedServer {
|
|
return fmt.Errorf("--proxied-server-idle-timeout requires --proxied-server")
|
|
}
|
|
if serverProxyIdleTimeout < 0 {
|
|
return fmt.Errorf("--proxied-server-idle-timeout must be 0 (never) or a positive duration, got %s", serverProxyIdleTimeout)
|
|
}
|
|
if serverProxyIdleTimeout == 0 {
|
|
serverProxyIdleTimeout = proxy.IdleTimeoutNever
|
|
}
|
|
}
|
|
|
|
externalProvided := externalHost != "" || externalPort != 0 || externalSocketPath != "" ||
|
|
externalUser != "" ||
|
|
externalTLS || externalTLSCACertPath != "" || externalTLSCertPath != "" || externalTLSKeyPath != "" ||
|
|
externalTLSServerName != "" || externalTLSSkipVerify || externalKeepAlive != 0
|
|
if externalProvided && !initProxiedServer {
|
|
return fmt.Errorf("--proxied-server-external-* flags require --proxied-server")
|
|
}
|
|
if externalProvided && serverConfigPath != "" {
|
|
return fmt.Errorf("--proxied-server-external-* flags cannot be combined with --proxied-server-config-path (external mode has no managed dolt sql-server to configure)")
|
|
}
|
|
if externalProvided && debugMode {
|
|
return fmt.Errorf("--debug cannot be combined with --proxied-server-external-* (debug applies to the managed dolt sql-server only)")
|
|
}
|
|
var externalConfig *configfile.ExternalDoltConfig
|
|
if externalProvided {
|
|
cfg := configfile.ExternalDoltConfig{
|
|
Host: externalHost,
|
|
Port: externalPort,
|
|
Socket: externalSocketPath,
|
|
User: externalUser,
|
|
TLSRequired: externalTLS,
|
|
TLSCACert: externalTLSCACertPath,
|
|
TLSCert: externalTLSCertPath,
|
|
TLSKey: externalTLSKeyPath,
|
|
TLSServerName: externalTLSServerName,
|
|
TLSSkipVerify: externalTLSSkipVerify,
|
|
KeepAlivePeriod: externalKeepAlive,
|
|
}
|
|
if err := cfg.Validate(); err != nil {
|
|
return fmt.Errorf("--proxied-server-external-*: %v", err)
|
|
}
|
|
externalConfig = &cfg
|
|
}
|
|
|
|
// Backend selection: Dolt is the only supported backend.
|
|
if !configfile.IsSupportedBackend(backendFlag) {
|
|
switch backendFlag {
|
|
case configfile.BackendPostgres, configfile.BackendMySQL:
|
|
return fmt.Errorf("storage backend %q is no longer supported: %s; the supported backend is \"dolt\" (default)", backendFlag, configfile.RemovedBackendRationale)
|
|
case configfile.BackendSQLite:
|
|
return fmt.Errorf("storage backend %q is no longer supported: %s; the supported backend is \"dolt\" (default)", backendFlag, configfile.RemovedSQLiteRationale)
|
|
}
|
|
return fmt.Errorf("unknown backend %q: the supported backend is \"dolt\" (default)", backendFlag)
|
|
}
|
|
// A registered extension backend passes IsSupportedBackend so its
|
|
// existing workspaces can be opened, but init provisions Dolt only and
|
|
// would otherwise create the workspace and persist backend: dolt. Reject
|
|
// it here rather than silently creating the wrong workspace; downstream
|
|
// registrants supply their own workspace-creation path.
|
|
if backends.Registered(backendFlag) {
|
|
return fmt.Errorf("backend %q cannot be created by bd init; it can only open an existing workspace (bd init provisions \"dolt\", the default)", backendFlag)
|
|
}
|
|
for _, legacyFlag := range removedBackendInitFlags {
|
|
if cmd.Flags().Changed(legacyFlag.name) {
|
|
return fmt.Errorf("--%s belonged to %s: %s; use --backend=dolt (the default)", legacyFlag.name, legacyFlag.origin, legacyFlag.rationale)
|
|
}
|
|
}
|
|
// Validate --database format early, before any side effects.
|
|
if database != "" {
|
|
if err := dolt.ValidateDatabaseName(database); err != nil {
|
|
return fmt.Errorf("invalid database name %q: %v", database, err)
|
|
}
|
|
}
|
|
|
|
// Resolve non-interactive mode: flag > env var > terminal detection.
|
|
// This must be computed before any interactive prompts.
|
|
nonInteractive := isNonInteractiveInit(nonInteractiveFlag)
|
|
|
|
// Validate --role flag value
|
|
if roleFlag != "" {
|
|
switch roleFlag {
|
|
case "maintainer", "contributor":
|
|
// valid
|
|
default:
|
|
return fmt.Errorf("invalid --role %q: must be \"maintainer\" or \"contributor\"", roleFlag)
|
|
}
|
|
}
|
|
|
|
// Fail-fast: contributor/team wizards require interaction
|
|
if nonInteractive && contributor {
|
|
return fmt.Errorf("--contributor requires interactive prompts and cannot be used with --non-interactive")
|
|
}
|
|
if nonInteractive && team {
|
|
return fmt.Errorf("--team requires interactive prompts and cannot be used with --non-interactive")
|
|
}
|
|
|
|
// Dolt is the only supported backend.
|
|
backend := configfile.BackendDolt
|
|
|
|
// Also treat BEADS_DOLT_SERVER_MODE=1 env var as --server.
|
|
if os.Getenv("BEADS_DOLT_SERVER_MODE") == "1" {
|
|
initServerMode = true
|
|
}
|
|
|
|
// Shared server mode still uses a Dolt sql-server, so it must select
|
|
// the server-backed store path during init. Without this, init can
|
|
// persist shared-server intent in YAML while still creating an embedded
|
|
// store and recording dolt_mode=embedded in metadata.json (GH#2946).
|
|
if sharedServer || strings.EqualFold(os.Getenv("BEADS_DOLT_SHARED_SERVER"), "true") || os.Getenv("BEADS_DOLT_SHARED_SERVER") == "1" {
|
|
initServerMode = true
|
|
}
|
|
|
|
// Set serverMode so !usesSQLServer() returns the correct value.
|
|
// Both the global and cmdCtx must be set because PersistentPreRun
|
|
// creates a fresh cmdCtx (with ServerMode=false) before Run executes.
|
|
serverMode = initServerMode
|
|
proxiedServerMode = initProxiedServer
|
|
if cmdCtx != nil {
|
|
cmdCtx.ServerMode = initServerMode
|
|
cmdCtx.ProxiedServerMode = initProxiedServer
|
|
}
|
|
|
|
if initProxiedServer {
|
|
if beadsDir := resolveInitBeadsDir(); beadsDir != "" {
|
|
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
|
|
return handleWorkspaceGuardError(err)
|
|
}
|
|
}
|
|
if err := runInitProxiedServer(cmd, rootCtx, initProxiedServerInput{
|
|
prefix: prefix,
|
|
database: database,
|
|
roleFlag: roleFlag,
|
|
initRemote: initRemote,
|
|
initRemoteChanged: initRemoteChanged,
|
|
destroyToken: destroyToken,
|
|
serverConfigPath: serverConfigPath,
|
|
serverLogPath: serverLogPath,
|
|
serverRootPath: serverRootPath,
|
|
serverProxyPort: serverProxyPort,
|
|
serverProxyIdleTimeout: serverProxyIdleTimeout,
|
|
externalConfig: externalConfig,
|
|
quiet: quiet,
|
|
stealth: stealth,
|
|
skipHooks: skipHooks,
|
|
skipAgents: skipAgents,
|
|
keepHomeClean: keepHomeClean,
|
|
reinitLocal: reinitLocal,
|
|
contributor: contributor,
|
|
team: team,
|
|
teamServer: initTeamServer,
|
|
fromJSONL: fromJSONL,
|
|
nonInteractive: nonInteractive,
|
|
}); err != nil {
|
|
// runInitProxiedServer runs the same checkExistingBeadsData
|
|
// the route below does, but it runs it inside itself — so
|
|
// --init-if-missing used to end here as a plain exit-1
|
|
// "Aborting.", and its mismatch guards never ran at all. The
|
|
// check happens before any .beads/ write, so nothing has been
|
|
// touched by the time we get this error.
|
|
if initIfMissing && !reinitLocal && errors.Is(err, errWorkspaceAlreadyInitialized) {
|
|
return resolveInitIfMissingAlreadyInitialized(cmd, database, prefix, quiet)
|
|
}
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Propagate --shared-server flag to env so that IsSharedServerMode(),
|
|
// ResolveDoltDir(), and DefaultConfig() all see shared mode immediately
|
|
// (before config.yaml exists). Safe: init runs once and exits.
|
|
if sharedServer {
|
|
_ = os.Setenv("BEADS_DOLT_SHARED_SERVER", "1")
|
|
}
|
|
|
|
if debugMode {
|
|
_ = os.Setenv("BEADS_DOLT_DEBUG", "1")
|
|
}
|
|
|
|
// Initialize config (PersistentPreRun doesn't run for init command).
|
|
// This must happen before validation that depends on server/embedded
|
|
// mode so dolt.mode from config.yaml is treated like --server.
|
|
if err := config.Initialize(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to initialize config: %v\n", err)
|
|
// Non-fatal - continue with defaults
|
|
}
|
|
|
|
// Re-init inherits the existing workspace's connection mode (#3885).
|
|
//
|
|
// This must be seeded HERE, with the other mode sources, not patched
|
|
// onto cfg.DoltMode where it is persisted further down: everything
|
|
// between the two points — which engine init opens, which database
|
|
// name rules apply, where the data lands — reads the process mode. A
|
|
// late fixup would write "server" into metadata.json describing a
|
|
// database that init had just built embedded, trading a silent
|
|
// downgrade for a silent mismatch.
|
|
//
|
|
// Only applies when this invocation names no mode of its own, so an
|
|
// explicit --server/--shared-server/--proxied-server, the BEADS_DOLT_*
|
|
// env vars, and a global dolt.mode all still win.
|
|
if !initServerMode && !initModeExplicitlyRequested(cmd) {
|
|
inheritServer, inheritErr := inheritWorkspaceDoltMode()
|
|
if inheritErr != nil {
|
|
return inheritErr
|
|
}
|
|
if inheritServer {
|
|
initServerMode = true
|
|
serverMode = true
|
|
if cmdCtx != nil {
|
|
cmdCtx.ServerMode = true
|
|
}
|
|
if !quiet {
|
|
fmt.Fprintln(os.Stderr, "Preserving server mode from the existing .beads/metadata.json.")
|
|
}
|
|
}
|
|
}
|
|
|
|
// config.yaml fallback for dolt.mode: if --server wasn't passed and
|
|
// env var didn't set it, check config.yaml for dolt.mode: server.
|
|
if !initServerMode {
|
|
if modeVal := config.GetYamlConfig("dolt.mode"); strings.EqualFold(modeVal, "server") {
|
|
initServerMode = true
|
|
serverMode = initServerMode
|
|
if cmdCtx != nil {
|
|
cmdCtx.ServerMode = initServerMode
|
|
}
|
|
}
|
|
}
|
|
|
|
// Explicit connection flags outrank stale BEADS_DOLT_SERVER_* values
|
|
// (GH#5177). This must run AFTER every source of server mode has been
|
|
// consulted above: --server, BEADS_DOLT_SERVER_MODE, --shared-server,
|
|
// workspace inheritance, and config.yaml dolt.mode. In embedded mode
|
|
// the flags are still recorded in metadata.json, but promoting them
|
|
// into the environment would trip init's own remote-host guard below.
|
|
if initServerMode {
|
|
restoreServerConnEnv, err := promoteExplicitServerConnFlags(cmd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer restoreServerConnEnv()
|
|
}
|
|
|
|
// Reject hyphens in --database for embedded mode. Must run AFTER
|
|
// serverMode is set above — otherwise !usesSQLServer() always returns
|
|
// true and incorrectly rejects server-mode names (GH#3231).
|
|
if database != "" && strings.ContainsRune(database, '-') && !usesSQLServer() {
|
|
return fmt.Errorf("database name %q contains hyphens which are invalid in embedded mode; use underscores instead (e.g. %q)",
|
|
database, sanitizeDBName(database))
|
|
}
|
|
|
|
// Hard fail: if a remote dolt.host is configured, server mode MUST
|
|
// be active — embedded mode has no host. dolt.port alone is ambient
|
|
// plumbing (e.g. test harnesses) and is not treated as server intent.
|
|
if !initServerMode {
|
|
configHost := config.GetYamlConfig("dolt.host")
|
|
envHost := os.Getenv("BEADS_DOLT_SERVER_HOST")
|
|
configPort := config.GetYamlConfig("dolt.port")
|
|
envPort := os.Getenv("BEADS_DOLT_SERVER_PORT")
|
|
|
|
if conflict := detectInitRemoteHostConflict(configHost, envHost, configPort, envPort); conflict != nil {
|
|
detail := fmt.Sprintf("dolt.host (%s) is", conflict.host)
|
|
if conflict.includesPort {
|
|
detail = fmt.Sprintf("dolt.host (%s) and dolt.port are", conflict.host)
|
|
}
|
|
return fmt.Errorf("%s set via %s but server mode is not enabled.\n"+
|
|
" Embedded mode has no host/port — these settings require server mode.\n"+
|
|
" Set dolt.mode: server in %s or pass --server to bd init.",
|
|
detail, conflict.source, config.UserConfigYamlDisplayPath())
|
|
}
|
|
}
|
|
|
|
// Historical workspaces need an explicit sealed-copy bridge. This runs
|
|
// before init's existing-workspace checks so even --force cannot create
|
|
// or rewrite state beside a source that has not been preserved.
|
|
if beadsDir := resolveInitBeadsDir(); beadsDir != "" {
|
|
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, initServerMode); err != nil {
|
|
return handleWorkspaceGuardError(err)
|
|
}
|
|
}
|
|
|
|
// Safety guard: check for existing beads data.
|
|
// This prevents accidental re-initialization. --force and
|
|
// --reinit-local both bypass this local-only guard; they do NOT
|
|
// authorize cross-boundary operations on remote history (see
|
|
// CheckRemoteSafety at cmd/bd/init_safety.go and
|
|
// engdocs/adr/0002-init-safety-invariants.md), nor recreating a
|
|
// missing server-mode database (guardMissingServerDatabase below;
|
|
// engdocs/adr/0004-missing-database-guard-signal.md).
|
|
if reinitLocal {
|
|
// be-5up5 round 2 (review of PR #5791): --reinit-local/--force skip
|
|
// checkExistingBeadsData entirely, and the typed confirmation below
|
|
// keys on countExistingIssues, which returns 0/err in exactly the
|
|
// missing-database case — so `bd init --force` against a lost
|
|
// server-side database used to create a fresh empty one with no
|
|
// prompt and no destroy token. Those flags authorize destroying a
|
|
// database that exists; only --recreate-missing authorizes creating
|
|
// one where the configured database has gone missing.
|
|
if err := guardMissingServerDatabase(prefix); err != nil {
|
|
return fmt.Errorf("%v", err)
|
|
}
|
|
}
|
|
if !reinitLocal {
|
|
if err := checkExistingBeadsData(prefix); err != nil {
|
|
// --init-if-missing makes init idempotent, but ONLY for the
|
|
// benign "workspace already initialized" case. An operational
|
|
// error from the check (e.g. an unreadable .beads/embeddeddolt
|
|
// directory) must still abort rather than be masked as a
|
|
// successful skip.
|
|
if initIfMissing && errors.Is(err, errWorkspaceAlreadyInitialized) {
|
|
return resolveInitIfMissingAlreadyInitialized(cmd, database, prefix, quiet)
|
|
}
|
|
return fmt.Errorf("%v", err)
|
|
}
|
|
}
|
|
|
|
// Check BEADS_DB environment variable if --db flag not set
|
|
// (PersistentPreRun doesn't run for init command)
|
|
if dbPath == "" {
|
|
if envDB := os.Getenv("BEADS_DB"); envDB != "" {
|
|
dbPath = envDB
|
|
}
|
|
}
|
|
|
|
// Determine prefix with precedence: flag > config > auto-detect from git > auto-detect from directory name
|
|
if prefix == "" {
|
|
// Try to get from config file
|
|
prefix = config.GetString("issue-prefix")
|
|
}
|
|
|
|
// auto-detect prefix from directory name
|
|
if prefix == "" {
|
|
// Auto-detect from directory name
|
|
cwd, err := os.Getwd()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get current directory: %v", err)
|
|
}
|
|
prefix = filepath.Base(cwd)
|
|
}
|
|
|
|
// Normalize prefix before storing it in config or deriving the Dolt
|
|
// database name. Dots are not valid in issue prefixes and must match the
|
|
// underscore form used for DoltDatabase/metadata.json. Leading dots
|
|
// produce invalid names (e.g. ".claude" -> "claude"), the trailing
|
|
// hyphen is added automatically during ID generation, and a leading
|
|
// non-letter is prefixed with "bd_" so the derived MySQL identifier is
|
|
// valid (directory names like "001" are common in temp dirs).
|
|
prefix = normalizeIssuePrefix(prefix)
|
|
remoteDivergenceConfirmed := false
|
|
|
|
// Cross-boundary safety (bd-q83 / ADR 0002): check remote state
|
|
// BEFORE any filesystem side-effects so a refusal exits cleanly.
|
|
// We only refuse here; bootstrap decisions happen later once
|
|
// beadsDir is computed. See CheckRemoteSafety in init_safety.go.
|
|
{
|
|
var earlySyncURL string
|
|
earlyRemoteSource := initSyncRemoteNone
|
|
earlyRemoteHasDoltData := false
|
|
var earlyProbeNote string
|
|
earlySyncURL, earlyRemoteSource = resolveInitConfiguredSyncRemote(initRemote, initRemoteChanged, resolveSyncRemote)
|
|
if earlyRemoteSource == initSyncRemoteExplicit {
|
|
// An explicit --remote is intent to bootstrap or wire that URL,
|
|
// but it is not proof that the remote already contains Dolt
|
|
// history. --from-jsonl is the exception: it selects a local
|
|
// source and skips cloning, so we must probe now rather than
|
|
// silently wiring a populated remote to orphan local history.
|
|
if fromJSONL {
|
|
hasData, err := gitRemoteHasDoltDataRefStatus(earlySyncURL)
|
|
earlyRemoteHasDoltData, earlyProbeNote = resolveRemoteHasDoltDataProbe(earlySyncURL, hasData, err)
|
|
}
|
|
} else if earlyRemoteSource == initSyncRemoteConfigured {
|
|
// Probe refs/dolt/data — do NOT treat mere presence of
|
|
// sync.remote as proof of remote history (GH#4861). A git
|
|
// remote with only ordinary branches must not refuse
|
|
// --reinit-local / local init.
|
|
hasData, err := gitRemoteHasDoltDataRefStatus(earlySyncURL)
|
|
earlyRemoteHasDoltData, earlyProbeNote = resolveRemoteHasDoltDataProbe(earlySyncURL, hasData, err)
|
|
} else if earlyRemoteSource == initSyncRemoteNone && !stealth && !keepHomeClean && isGitRepo() && !isBareGitRepo() {
|
|
// Not under keepHomeClean: a repository git finds from the
|
|
// home is not the project's, so its origin is not this
|
|
// workspace's remote (see guardInitInHomeDir).
|
|
if originURL, err := gitOriginGetURL(); err == nil && originURL != "" {
|
|
earlySyncURL = normalizeRemoteURL(originURL)
|
|
hasData, probeErr := gitOriginHasDoltDataRefStatus()
|
|
earlyRemoteHasDoltData, earlyProbeNote = resolveRemoteHasDoltDataProbe(earlySyncURL, hasData, probeErr)
|
|
}
|
|
}
|
|
if earlySyncURL != "" {
|
|
if earlyProbeNote != "" {
|
|
fmt.Fprintf(os.Stderr, "%s %s\n", ui.RenderWarn("!"), earlyProbeNote)
|
|
}
|
|
earlyDecision := CheckRemoteSafety(RemoteSafetyInput{
|
|
Force: force,
|
|
ReinitLocal: reinitLocal,
|
|
FromJSONL: fromJSONL,
|
|
DiscardRemote: discardRemote,
|
|
DestroyToken: destroyToken,
|
|
ExpectedToken: FormatDestroyToken(prefix),
|
|
RemoteHasDoltData: earlyRemoteHasDoltData,
|
|
IsInteractive: term.IsTerminal(int(os.Stdin.Fd())),
|
|
})
|
|
if _, err := handleRemoteSafetyDecision(earlyDecision, prefix, earlySyncURL, destroyToken, func() (bool, error) {
|
|
switch earlyRemoteSource {
|
|
case initSyncRemoteExplicit, initSyncRemoteConfigured:
|
|
return gitRemoteHasDoltDataRefStatus(earlySyncURL)
|
|
default:
|
|
return gitOriginHasDoltDataRefStatus()
|
|
}
|
|
}, earlyRemoteHasDoltData, &remoteDivergenceConfirmed); err != nil {
|
|
// The early guard refuses and confirms only; bootstrap
|
|
// selection happens later after beadsDir/dbName are known.
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
// Determine beadsDir first (used for all storage path calculations).
|
|
// BEADS_DIR takes precedence, otherwise use CWD/.beads (with redirect support).
|
|
// This must be computed BEFORE initDBPath to ensure consistent path resolution
|
|
// (avoiding macOS /var -> /private/var symlink issues when directory creation
|
|
// happens between path computations).
|
|
var beadsDirForInit string
|
|
if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" {
|
|
beadsDirForInit = utils.CanonicalizePath(envBeadsDir)
|
|
} else {
|
|
beadsDirForInit = beads.GetWorktreeFallbackBeadsDir()
|
|
if beadsDirForInit == "" {
|
|
localBeadsDir := filepath.Join(".", ".beads")
|
|
beadsDirForInit = beads.FollowRedirect(localBeadsDir)
|
|
}
|
|
}
|
|
|
|
// Plan the storage root for gate acquisition without side effects.
|
|
// The operational path is resolved after the destructive preflight.
|
|
plannedDBPath := dbPath
|
|
if plannedDBPath == "" {
|
|
// Plan the physical-root gate without creating a shared-server
|
|
// directory before destructive reinit confirmation.
|
|
plannedDBPath = doltserver.DoltDirPath(beadsDirForInit)
|
|
}
|
|
|
|
// Determine if we should create .beads/ directory in CWD or main repo root
|
|
// For worktrees, .beads should always be in the main repository root
|
|
cwd, err := os.Getwd()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get current directory: %v", err)
|
|
}
|
|
|
|
// KNOWN GAP: this is the live BEADS_DIR, which may be one the root
|
|
// pre-run exported for itself rather than one the caller named — the
|
|
// distinction beadsDirFromCaller (main.go) exists for, and the one
|
|
// guardInitInHomeDir keys on. So a discovered beads dir counts as
|
|
// explicit here and skips the git init below. Left unchanged on
|
|
// purpose: reconciling init's caller-intent reads (this,
|
|
// beadsDirFromCaller, beadsDirProvidedAtStartup) changes init well
|
|
// beyond the home guard and belongs in its own change.
|
|
hasExplicitBeadsDir := os.Getenv("BEADS_DIR") != ""
|
|
|
|
// Use the beadsDir computed earlier (before any directory creation)
|
|
// to ensure consistent path representation.
|
|
beadsDir := beadsDirForInit
|
|
|
|
if initProxiedServer && externalConfig == nil {
|
|
if err := validateManagedProxiedServerConfigAtInit(beadsDir, serverConfigPath, serverRootPath); err != nil {
|
|
return fmt.Errorf("managed proxied-server config: %w", err)
|
|
}
|
|
}
|
|
|
|
// Prevent nested .beads directories
|
|
// Check if current working directory is inside a .beads directory
|
|
if strings.Contains(filepath.Clean(cwd), string(filepath.Separator)+".beads"+string(filepath.Separator)) ||
|
|
strings.HasSuffix(filepath.Clean(cwd), string(filepath.Separator)+".beads") {
|
|
fmt.Fprintf(os.Stderr, "Error: cannot initialize bd inside a .beads directory\n")
|
|
fmt.Fprintf(os.Stderr, "Current directory: %s\n", cwd)
|
|
fmt.Fprintf(os.Stderr, "Please run 'bd init' from outside the .beads directory.\n")
|
|
return &exitError{Code: 1}
|
|
}
|
|
|
|
// Convert the workspace to an absolute path before gate planning.
|
|
beadsDirAbs, err := filepath.Abs(beadsDir)
|
|
if err != nil {
|
|
beadsDirAbs = filepath.Clean(beadsDir)
|
|
}
|
|
// Workspace operation gate: bd init REPLACES/creates workspace state,
|
|
// so it holds the workspace gate (plus any resolvable physical-root
|
|
// gates, e.g. a shared-server dolt dir) EXCLUSIVELY for the rest of
|
|
// init. init is in noDbCommands, so the PersistentPreRunE chokepoint
|
|
// never covers it — this is its own acquisition site. The workspace
|
|
// gate file lives BESIDE .beads (<parent>/.beads.gate.lock), so it
|
|
// works before .beads exists; the acquisition must come before any
|
|
// directory writes below, and before acquireEmbeddedLock (lock
|
|
// ordering: gates rank before every other beads lock).
|
|
plannedDBPathAbs, err := filepath.Abs(plannedDBPath)
|
|
if err != nil {
|
|
plannedDBPathAbs = filepath.Clean(plannedDBPath)
|
|
}
|
|
// Physical-root gates guard DIRECTORIES. With --db the path can be
|
|
// a database FILE; gating it verbatim would create
|
|
// <file>.gate.lock and leave the directory that actually holds the
|
|
// data ungated, so normalize to the containing directory. A
|
|
// nonexistent path is assumed to be a directory (the default
|
|
// resolver paths are all dolt data dirs).
|
|
if fi, statErr := os.Stat(plannedDBPathAbs); statErr == nil && !fi.IsDir() {
|
|
plannedDBPathAbs = filepath.Dir(plannedDBPathAbs)
|
|
}
|
|
initGateHandle, gateErr := acquireInitMutationGate(rootCtx, beadsDirAbs, plannedDBPathAbs, func() error {
|
|
return runInitReinitPreflight(reinitLocal, destroyTokenPrefix, destroyToken)
|
|
})
|
|
if gateErr != nil {
|
|
return gateErr
|
|
}
|
|
defer func() { _ = initGateHandle.Release() }()
|
|
|
|
// Resolve the operational storage path only after held-gate preflight
|
|
// succeeds. ResolveDoltDir retains its mkdir-on-use behavior for a
|
|
// real shared-server initialization.
|
|
initDBPath := dbPath
|
|
if initDBPath == "" {
|
|
initDBPath = doltserver.ResolveDoltDir(beadsDirForInit)
|
|
}
|
|
initDBDir := filepath.Dir(initDBPath)
|
|
initDBDirAbs, err := filepath.Abs(initDBDir)
|
|
if err != nil {
|
|
initDBDirAbs = filepath.Clean(initDBDir)
|
|
}
|
|
|
|
// Do not mutate the repository for stealth mode until a destructive
|
|
// reinit has passed its held-gate confirmation. Remote safety above
|
|
// still evaluates the flag before this point.
|
|
if stealth {
|
|
if err := setupStealthModeAt(cwd, !quiet); err != nil {
|
|
return fmt.Errorf("setting up stealth mode: %v", err)
|
|
}
|
|
|
|
// In stealth mode, skip git hooks installation since we handle it
|
|
// globally.
|
|
skipHooks = true
|
|
}
|
|
|
|
// Always create local .beads/ when using default location (CWD/.beads).
|
|
// The local directory is needed for metadata.json, config.yaml,
|
|
// .gitignore, and hooks — regardless of where dolt data lives.
|
|
// Only skip when BEADS_DIR explicitly points outside the project.
|
|
//
|
|
// Previous logic only created .beads/ when the dolt data dir was a
|
|
// subdirectory of .beads/, which broke server mode with external
|
|
// BEADS_DOLT_DATA_DIR or BEADS_DOLT_* env vars (GH#2519).
|
|
useLocalBeads := !hasExplicitBeadsDir || filepath.Clean(initDBDirAbs) == filepath.Clean(beadsDirAbs)
|
|
|
|
if useLocalBeads {
|
|
// Create .beads directory with owner-only permissions (0700).
|
|
if err := os.MkdirAll(beadsDir, config.BeadsDirPerm); err != nil {
|
|
if os.IsPermission(err) {
|
|
if runtime.GOOS == "windows" {
|
|
return fmt.Errorf("failed to create .beads directory: %v\n\n"+
|
|
"Windows Controlled Folder Access may be blocking bd.exe.\n"+
|
|
"To fix: Open Windows Security > Virus & threat protection >\n"+
|
|
"Ransomware protection > Allow an app through Controlled folder access\n"+
|
|
"and add bd.exe (typically %%USERPROFILE%%\\go\\bin\\bd.exe).", err)
|
|
} else {
|
|
return fmt.Errorf("failed to create .beads directory: %v\n\n"+
|
|
"Permission denied. Check directory ownership and permissions:\n"+
|
|
" ls -la %s\n"+
|
|
" chmod 755 %s", err, filepath.Dir(beadsDir), filepath.Dir(beadsDir))
|
|
}
|
|
}
|
|
return fmt.Errorf("failed to create .beads directory: %v", err)
|
|
}
|
|
|
|
// Fix permissions on pre-existing .beads/ directories that may
|
|
// have been created with a permissive umask (GH#3391).
|
|
if fixed, err := config.FixBeadsDirPermissions(beadsDir); err != nil {
|
|
if !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not fix .beads permissions: %v\n", err)
|
|
}
|
|
} else if fixed && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Fixed .beads permissions to %04o\n", config.BeadsDirPerm)
|
|
}
|
|
|
|
// On Linux btrfs, disable transparent compression on .beads/ so that
|
|
// dolt's hot append-only write path (under .beads/dolt/ or
|
|
// .beads/embeddeddolt/) does not trigger kworker thrashing from
|
|
// read-modify-write-recompress cycles. New files created inside this
|
|
// directory inherit FS_NOCOW_FL automatically, so setting it here —
|
|
// before dolt writes anything — covers both server and embedded modes.
|
|
// No-op on non-Linux and non-btrfs filesystems (GH nocow-beads-dolt-init).
|
|
if err := applyNoCOW(beadsDir); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set FS_NOCOW_FL on %s: %v\n", beadsDir, err)
|
|
}
|
|
|
|
// Create/update .gitignore in .beads directory: full template when
|
|
// missing, append-only for missing required patterns otherwise —
|
|
// never a wholesale rewrite, which destroyed local rules (bd-kaaz3)
|
|
if err := doctor.EnsureGitignoreForBeadsDir(beadsDir); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to create/update .gitignore: %v\n", err)
|
|
// Non-fatal - continue anyway
|
|
}
|
|
|
|
// Add .dolt/ and *.db to project-root .gitignore (GH#2034)
|
|
// Prevents users from accidentally committing Dolt database files.
|
|
// Skip when BEADS_DIR points outside the current directory — the CWD
|
|
// may not be a repo we should mutate (e.g. running from a worktree
|
|
// with an external BEADS_DIR). When BEADS_DIR points to the same
|
|
// repo's .beads/, the gitignore update is still appropriate.
|
|
// Also skip it in an untracked home directory (keepHomeClean): a
|
|
// BEADS_DIR the caller names under $HOME is still "local" by this
|
|
// test, and ~/.gitignore is not this init's to edit (GH#4635).
|
|
cwdAbs, _ := filepath.Abs(cwd)
|
|
beadsDirIsLocal := strings.HasPrefix(beadsDirAbs, filepath.Clean(cwdAbs)+string(filepath.Separator))
|
|
if beadsDirIsLocal && !keepHomeClean {
|
|
if stealth {
|
|
// Stealth mode: route Dolt-file ignore patterns into .git/info/exclude instead
|
|
// of a tracked .gitignore so collaborators never see beads-related changes.
|
|
if err := addProjectPatternsToGitExclude(cwd, doctor.ProjectGitignorePatterns, !quiet); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to update git exclude: %v\n", err)
|
|
// Non-fatal - continue anyway
|
|
}
|
|
// bd init --stealth is safe to re-run: clean up any beads section an earlier
|
|
// (non-stealth or pre-fix) run leaked into the tracked .gitignore.
|
|
if removed, err := removeBeadsProjectGitignoreSection(cwd); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to clean project .gitignore: %v\n", err)
|
|
// Non-fatal - continue anyway
|
|
} else if removed && !quiet {
|
|
fmt.Printf(" %s Removed leaked beads section from tracked .gitignore\n", ui.RenderPass("✓"))
|
|
}
|
|
} else if err := doctor.EnsureProjectGitignore(cwd); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to update project .gitignore: %v\n", err)
|
|
// Non-fatal - continue anyway
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
// Ensure git is initialized — bd requires git for role config, sync branches,
|
|
// hooks, worktrees, and fingerprint computation. git init is idempotent so
|
|
// safe to call even if already in a git repo.
|
|
// Skip when BEADS_DIR is explicitly set — the caller may be creating a
|
|
// standalone .beads/ directory outside any git repo.
|
|
if !hasExplicitBeadsDir && initArtifactGitCommand(cwd, "rev-parse", "--git-dir").Run() != nil {
|
|
gitInitCmd := initArtifactGitCommand(cwd, "init")
|
|
if output, err := gitInitCmd.CombinedOutput(); err != nil {
|
|
return fmt.Errorf("failed to initialize git repository: %v\n%s", err, output)
|
|
}
|
|
// Clear cached git context so subsequent operations (e.g. hook
|
|
// installation) see the newly-created repository (GH#2899).
|
|
git.ResetCaches()
|
|
if !quiet {
|
|
fmt.Printf(" %s Initialized git repository\n", ui.RenderPass("✓"))
|
|
}
|
|
}
|
|
|
|
// Ensure storage directory exists (.beads/dolt).
|
|
// In server mode, dolt.New() connects via TCP and doesn't create local directories,
|
|
// so we create the marker directory explicitly.
|
|
// In embedded mode the engine creates its own directories under .beads/embeddeddolt/,
|
|
// so skip this to avoid leaving an empty .beads/dolt/ artifact (GH#2903).
|
|
if initServerMode {
|
|
if err := os.MkdirAll(initDBPath, config.BeadsDirPerm); err != nil {
|
|
return fmt.Errorf("failed to create storage directory %s: %v", initDBPath, err)
|
|
}
|
|
// Linux btrfs: disable compression on the dolt data dir to avoid
|
|
// kworker thrashing on the append-only write path. Best-effort; a
|
|
// non-btrfs filesystem returns nil from applyNoCOW.
|
|
if err := applyNoCOW(initDBPath); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set FS_NOCOW_FL on %s: %v\n", initDBPath, err)
|
|
}
|
|
}
|
|
|
|
ctx := rootCtx
|
|
|
|
// Create Dolt storage backend
|
|
storagePath := doltserver.ResolveDoltDir(beadsDir)
|
|
// Respect existing config's database name to avoid creating phantom catalog
|
|
// entries when a user has renamed their database (GH#2051).
|
|
dbName := ""
|
|
if existingCfg, _ := configfile.Load(beadsDir); existingCfg != nil && existingCfg.DoltDatabase != "" {
|
|
dbName = existingCfg.DoltDatabase
|
|
} else if prefix != "" {
|
|
// Sanitize hyphens to underscores for SQL-idiomatic database names.
|
|
// Dots were already normalized in prefix above so issue_prefix and
|
|
// DoltDatabase stay in lockstep.
|
|
// Must match the sanitization applied to metadata.json DoltDatabase
|
|
// field (line below), otherwise init creates a database with one name
|
|
// but metadata.json records a different name, causing reopens to fail.
|
|
dbName = dbNameFromPrefix(prefix)
|
|
} else {
|
|
dbName = "beads"
|
|
}
|
|
// --database flag overrides all prefix-based naming. This allows callers
|
|
// (e.g. an orchestrator) to specify a pre-existing database name, preventing orphan
|
|
// database creation when the database was already created externally.
|
|
if database != "" {
|
|
dbName = database
|
|
}
|
|
|
|
// Validate the auto-derived database name early so we can surface a clear,
|
|
// actionable error instead of a cryptic failure from the storage layer.
|
|
// The --database flag is already validated above; this catches cases where
|
|
// the directory name produces an invalid identifier after sanitization
|
|
// (e.g. spaces, '@', '!' that survive the hyphen/dot replacement).
|
|
// Skip when dbName came from an existing config — it was valid when stored.
|
|
if database == "" {
|
|
if existingCfg, _ := configfile.Load(beadsDir); existingCfg == nil || existingCfg.DoltDatabase == "" {
|
|
if err := dolt.ValidateDatabaseName(dbName); err != nil {
|
|
dirName := filepath.Base(cwd)
|
|
fmt.Fprintf(os.Stderr, "Error: directory name %q produces an invalid database name %q.\n", dirName, dbName)
|
|
fmt.Fprintf(os.Stderr, "Re-run with a valid prefix: bd init --prefix <name>\n")
|
|
fmt.Fprintf(os.Stderr, "(Database names must start with a letter or underscore and contain only letters, digits, underscores, or hyphens.)\n")
|
|
return &exitError{Code: 1}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Auto-bootstrap from remote if sync.remote (or deprecated
|
|
// sync.git-remote) is configured, or git origin has Dolt data
|
|
// (refs/dolt/data). This makes bd init and bd bootstrap
|
|
// interchangeable — both clone from the remote when one exists.
|
|
//
|
|
// Cross-boundary safety (bd-q83 / ADR 0002): when the caller
|
|
// passes --force or --reinit-local and the remote already has
|
|
// refs/dolt/data, we must refuse — the new local identity would
|
|
// orphan-push over the team's history on first write. The
|
|
// CheckRemoteSafety chokepoint encodes this invariant; any future
|
|
// flag that can interact with remote history must route through
|
|
// it rather than adding another `&& !someFlag` here.
|
|
syncResolutionURL, syncRemoteSource := resolveInitConfiguredSyncRemote(initRemote, initRemoteChanged, resolveSyncRemote)
|
|
syncURL := syncResolutionURL
|
|
syncURLFromConfig := syncURL != "" && syncRemoteSource != initSyncRemoteNone // true when URL came from explicit user config
|
|
bootstrappedFromRemote := false
|
|
syncFromRemote := false
|
|
syncURLFromGitOrigin := false
|
|
remoteHasDoltData := false
|
|
var lateProbeNote string
|
|
|
|
if syncURL != "" {
|
|
// sync.remote was explicitly configured. Treat it as bootstrap-
|
|
// from-remote intent unless --from-jsonl selected a local JSONL
|
|
// source. CheckRemoteSafety still enforces that local-source
|
|
// flags can't silently fight a configured remote.
|
|
// Trust the URL format as-is: normalizeRemoteURL would convert
|
|
// http:// to git+http:// and break Dolt remotesapi endpoints
|
|
// configured explicitly by the user (GH#3339).
|
|
if syncRemoteSource == initSyncRemoteExplicit && !fromJSONL {
|
|
syncFromRemote = true
|
|
} else if syncRemoteSource == initSyncRemoteConfigured || syncRemoteSource == initSyncRemoteExplicit {
|
|
// Always verify refs/dolt/data rather than assuming history
|
|
// from a configured URL alone (GH#4861).
|
|
hasData, err := gitRemoteHasDoltDataRefStatus(syncURL)
|
|
remoteHasDoltData, lateProbeNote = resolveRemoteHasDoltDataProbe(syncURL, hasData, err)
|
|
}
|
|
if lateProbeNote != "" {
|
|
fmt.Fprintf(os.Stderr, "%s %s\n", ui.RenderWarn("!"), lateProbeNote)
|
|
}
|
|
if !syncFromRemote {
|
|
decision := CheckRemoteSafety(RemoteSafetyInput{
|
|
Force: force,
|
|
ReinitLocal: reinitLocal,
|
|
FromJSONL: fromJSONL,
|
|
DiscardRemote: discardRemote,
|
|
DestroyToken: destroyToken,
|
|
ExpectedToken: FormatDestroyToken(prefix),
|
|
RemoteHasDoltData: remoteHasDoltData,
|
|
IsInteractive: term.IsTerminal(int(os.Stdin.Fd())),
|
|
})
|
|
bootstrap, err := handleRemoteSafetyDecision(decision, prefix, syncURL, destroyToken, func() (bool, error) {
|
|
return gitRemoteHasDoltDataRefStatus(syncURL)
|
|
}, remoteHasDoltData, &remoteDivergenceConfirmed)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
syncFromRemote = bootstrap
|
|
if !bootstrap && decision.Action == ActionNoRemoteData && !quiet {
|
|
// Skipping the clone (because the probe came back clean)
|
|
// loses the explanation cloneFromRemoteWithMode used to
|
|
// print via isEmptyRemoteCloneError. Say it here instead.
|
|
fmt.Printf(" %s Remote has no Dolt data yet; initialized a fresh local database\n", ui.RenderWarn("!"))
|
|
}
|
|
}
|
|
} else if syncRemoteSource == initSyncRemoteNone && !stealth && !keepHomeClean && isGitRepo() && !isBareGitRepo() {
|
|
// keepHomeClean: as in the early remote check above.
|
|
if originURL, err := gitOriginGetURL(); err == nil && originURL != "" {
|
|
syncURL = normalizeRemoteURL(originURL)
|
|
syncURLFromGitOrigin = true
|
|
hasData, probeErr := gitOriginHasDoltDataRefStatus()
|
|
remoteHasDoltData, lateProbeNote = resolveRemoteHasDoltDataProbe(syncURL, hasData, probeErr)
|
|
if lateProbeNote != "" {
|
|
fmt.Fprintf(os.Stderr, "%s %s\n", ui.RenderWarn("!"), lateProbeNote)
|
|
}
|
|
|
|
decision := CheckRemoteSafety(RemoteSafetyInput{
|
|
Force: force,
|
|
ReinitLocal: reinitLocal,
|
|
FromJSONL: fromJSONL,
|
|
DiscardRemote: discardRemote,
|
|
DestroyToken: destroyToken,
|
|
ExpectedToken: FormatDestroyToken(prefix),
|
|
RemoteHasDoltData: remoteHasDoltData,
|
|
IsInteractive: term.IsTerminal(int(os.Stdin.Fd())),
|
|
})
|
|
|
|
bootstrap, err := handleRemoteSafetyDecision(decision, prefix, syncURL, destroyToken, gitOriginHasDoltDataRefStatus, remoteHasDoltData, &remoteDivergenceConfirmed)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if bootstrap {
|
|
if probeErr != nil {
|
|
// The fail-closed UNKNOWN kept the refusal gate shut
|
|
// above, but reaching here means no override flag was
|
|
// passed and there is no local history to protect —
|
|
// and the bootstrap clone would run against the same
|
|
// origin the probe could not reach, turning every
|
|
// credential-less clone of a private repo into a hard
|
|
// init failure. Fall back to a fresh local database,
|
|
// which is what init did here before the probe existed.
|
|
if !quiet {
|
|
fmt.Printf(" %s Could not verify the git origin's Dolt history; initialized a fresh local database\n", ui.RenderWarn("!"))
|
|
}
|
|
} else {
|
|
syncFromRemote = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if syncFromRemote {
|
|
// A raw https:// forge URL would route through Dolt's remotesapi
|
|
// client and spin forever (#4421); its git+ form routes through
|
|
// the git remote factory. Non-forge URLs are untouched (GH#3339).
|
|
syncURL = doltRemoteURL(syncURL)
|
|
cloneCfg := initTimeCloneConfig(initServerMode, serverHost, serverPort, serverSocket, serverUser, dbName)
|
|
disposition, err := runInitRemoteClone(syncURL, func(remoteURL string) error {
|
|
return cloneFromRemoteWithMode(ctx, beadsDir, remoteURL, dbName, cloneCfg, initRemoteCloneMode(initServerMode, externalServer))
|
|
})
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: failed to clone remote %q: %v\n", syncURL, err)
|
|
fmt.Fprintf(os.Stderr, "Hint: verify the URL is reachable and any credentials are valid, or omit --remote to initialize a fresh local database.\n")
|
|
return &exitError{Code: 1}
|
|
}
|
|
if disposition == initRemoteCloneFresh {
|
|
if !quiet {
|
|
fmt.Printf(" %s Remote has no Dolt data yet; initialized a fresh local database\n", ui.RenderWarn("!"))
|
|
}
|
|
syncFromRemote = false
|
|
} else {
|
|
bootstrappedFromRemote = true
|
|
// Creation-consent for the migration-consent gate
|
|
// (schema/migrate_consent.go): this invocation just CLONED the
|
|
// database into a workspace that did not exist before, so the
|
|
// operator's `bd init --remote` is consent for its schema —
|
|
// the same principle that exempts a fresh `bd init`. The
|
|
// #4259 remote-migrate gate is unaffected (consent is not its
|
|
// designated-migrator override), so the smart-gate /
|
|
// designated-migrator flows keep their exact behavior.
|
|
schema.SetLocalMigrateConsent(true)
|
|
if !quiet {
|
|
fmt.Printf(" %s Bootstrapped from remote: %s\n", ui.RenderPass("✓"), syncURL)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Build config. Beads always uses dolt sql-server.
|
|
// AutoStart is enabled during init — we need a server to initialize the database —
|
|
// except under --external: that server is managed outside bd, so bd must not start
|
|
// one of its own on the endpoint the caller named.
|
|
//
|
|
// Port resolution for init: use ONLY project-local sources (env var, port file)
|
|
// to prevent cross-project data leakage (GH#2336). DefaultConfig falls through
|
|
// to config.yaml / global config, which may resolve to another project's server
|
|
// because metadata.json doesn't exist yet during init. For fresh inits, port 0
|
|
// forces auto-start to allocate an ephemeral port for THIS project.
|
|
// The source travels with the port. applyConfigDefaults reads a nonzero
|
|
// ServerPort with no source as a caller assertion (be-wf9a.1), and none
|
|
// of the three resolutions below is one: they are an ambient env var and
|
|
// two pieces of bd's own bookkeeping. Mislabeling them makes auto-start
|
|
// refuse to retarget a stale port the user never chose (GH#4052).
|
|
initPort := 0
|
|
initPortSource := doltserver.PortSourceUnset
|
|
initPortShared := false
|
|
if p := os.Getenv("BEADS_DOLT_SERVER_PORT"); p != "" {
|
|
if port, err := strconv.Atoi(p); err == nil && port > 0 {
|
|
initPort = port
|
|
initPortSource = doltserver.PortSourceEnv
|
|
}
|
|
}
|
|
if initPort == 0 {
|
|
if port := doltserver.ReadPortFile(beadsDir); port > 0 {
|
|
initPort = port
|
|
initPortSource = doltserver.PortSourcePortFile
|
|
}
|
|
}
|
|
// Shared server mode intentionally uses a common port for all projects.
|
|
if initPort == 0 && doltserver.IsSharedServerMode() {
|
|
initPort = doltserver.DefaultSharedServerPort
|
|
initPortSource = doltserver.PortSourceSharedServerDefault
|
|
// Mirrors doltserver.DefaultConfig's own shared-mode fill. It makes
|
|
// newServerMode fail closed if the shared server is down and
|
|
// auto-start brings up a repo-local one instead — a different
|
|
// database, never a benign port refresh (GH#4052).
|
|
initPortShared = true
|
|
}
|
|
doltCfg := &dolt.Config{
|
|
Path: storagePath,
|
|
BeadsDir: beadsDir,
|
|
Database: dbName,
|
|
ServerPort: initPort,
|
|
ServerPortSource: initPortSource,
|
|
ServerPortSharedServer: initPortShared,
|
|
ServerMode: initServerMode,
|
|
ProxiedServer: initProxiedServer,
|
|
CreateIfMissing: true, // bd init is the only path that should create databases
|
|
OpenedByInit: true, // shapes the identity-mismatch advice (GH#5558)
|
|
AutoStart: initServerMode && !externalServer && os.Getenv("BEADS_DOLT_AUTO_START") != "0",
|
|
ServerTLS: initDoltServerTLSFromEnv(),
|
|
}
|
|
if serverHost != "" {
|
|
doltCfg.ServerHost = serverHost
|
|
}
|
|
if serverPort != 0 {
|
|
// `bd init --server-port` IS a caller assertion — and it must
|
|
// replace the source resolved above, not inherit it, or an
|
|
// explicitly flagged port would carry a port-file provenance.
|
|
doltCfg.ServerPort = serverPort
|
|
doltCfg.ServerPortSource = doltserver.PortSourceCallerExplicit
|
|
doltCfg.ServerPortSharedServer = false
|
|
}
|
|
if serverSocket != "" {
|
|
doltCfg.ServerSocket = serverSocket
|
|
}
|
|
if serverUser != "" {
|
|
doltCfg.ServerUser = serverUser
|
|
}
|
|
|
|
// Route through the gateway credential machinery: when a credential
|
|
// command is configured, its token becomes the connection username and
|
|
// gateway semantics (no schema init, no CREATE DATABASE, no auto-start)
|
|
// apply. No-op — and byte-identical to legacy init — when unconfigured.
|
|
if err := applyInitGatewayCredential(ctx, beadsDir, doltCfg); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: resolving dolt credential command: %v\n", err)
|
|
return &exitError{Code: 1}
|
|
}
|
|
|
|
initLock, err := acquireEmbeddedLock(beadsDir, initServerMode || initProxiedServer)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
return &exitError{Code: 1}
|
|
}
|
|
defer initLock.Unlock()
|
|
|
|
// WARNING: DO NOT remove, delete, or modify files inside Dolt's .dolt/
|
|
// directory — including noms/LOCK files. These are Dolt-internal files.
|
|
// Removing them WILL cause unrecoverable data corruption and data loss.
|
|
// Dolt manages these files itself; external interference is never safe.
|
|
|
|
// In shared server mode, ensure the shared server is running before
|
|
// opening the store. EnsureRunning won't auto-start because
|
|
// ResolveServerMode returns ServerModeExternal, so start it
|
|
// explicitly via the shared server directory (GH#2946).
|
|
//
|
|
// --external skips this: the server is managed outside bd (e.g.
|
|
// Docker, systemd, testcontainers). The caller is responsible for
|
|
// ensuring the server is reachable and the port file exists.
|
|
//
|
|
// Gateway mode also skips this: it connects to a remote authenticating
|
|
// server and must not start a local shared server or create/write
|
|
// beads_global (see shouldInitSharedGlobalDB).
|
|
if !externalServer && shouldInitSharedGlobalDB(sharedServer, doltserver.IsSharedServerMode(), doltCfg.Gateway) {
|
|
if sharedDir, err := doltserver.SharedServerDir(); err == nil {
|
|
state, _ := doltserver.IsRunning(sharedDir)
|
|
if state == nil || !state.Running {
|
|
if _, startErr := doltserver.Start(sharedDir); startErr != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: failed to start shared Dolt server: %v\n", startErr)
|
|
return &exitError{Code: 1}
|
|
}
|
|
if !quiet {
|
|
fmt.Printf(" %s Shared Dolt server started\n", ui.RenderPass("✓"))
|
|
}
|
|
} else if debugMode {
|
|
fmt.Fprintf(os.Stderr, "Warning: shared Dolt server (PID %d, port %d) is already running without debug flags.\n", state.PID, state.Port)
|
|
fmt.Fprintf(os.Stderr, " Restart to pick up debug mode:\n")
|
|
fmt.Fprintf(os.Stderr, " bd dolt stop && bd dolt start\n")
|
|
}
|
|
}
|
|
|
|
// Ensure the global beads_global database exists on the shared server.
|
|
// This is idempotent — safe to run on every init.
|
|
globalHost := configfile.DefaultDoltServerHost
|
|
if serverHost != "" {
|
|
globalHost = serverHost
|
|
}
|
|
globalPort := initPort
|
|
if globalPort == 0 {
|
|
globalPort = doltserver.DefaultSharedServerPort
|
|
}
|
|
globalUser := configfile.DefaultDoltServerUser
|
|
if serverUser != "" {
|
|
globalUser = serverUser
|
|
}
|
|
if err := doltserver.EnsureGlobalDatabase(globalHost, globalPort, globalUser, ""); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to create global database: %v\n", err)
|
|
// Non-fatal — project init should succeed even if global DB creation fails
|
|
} else if !quiet {
|
|
fmt.Printf(" %s Global database %s available\n", ui.RenderPass("✓"), doltserver.GlobalDatabaseName)
|
|
}
|
|
}
|
|
|
|
store, err := newDoltStore(ctx, doltCfg)
|
|
if err != nil {
|
|
// #4259: the remote-migrate gate refused to auto-apply pending
|
|
// migrations. When init just bootstrapped the clone, the REMOTE is
|
|
// what is behind this binary — the gate's generic "adopt: bd
|
|
// bootstrap" remedy is circular, and init has not yet written
|
|
// metadata.json/config.yaml, so without finalization the workspace
|
|
// is stranded where not even the gate's own unlock commands can
|
|
// open it (bd-4mpy7).
|
|
var gateErr *schema.RemoteMigrateGateError
|
|
if errors.As(err, &gateErr) {
|
|
if bootstrappedFromRemote {
|
|
// Leave the workspace in the same finalized state the
|
|
// bd bootstrap sync path produces (GH#3201) so
|
|
// `bd migrate --force` (or BD_ALLOW_REMOTE_MIGRATE=1) and
|
|
// `bd dolt push` can open the cloned database.
|
|
fcfg := initTimeCloneConfig(initServerMode, serverHost, serverPort, serverSocket, serverUser, dbName)
|
|
if ferr := finalizeSyncedBootstrap(beadsDir, syncURL, fcfg, dbName); ferr != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to finalize bootstrapped workspace: %v\n", ferr)
|
|
}
|
|
}
|
|
if jsonOutput {
|
|
handleRemoteMigrateGateJSON(gateErr)
|
|
} else if bootstrappedFromRemote {
|
|
printBootstrapRemoteBehindGuidance(os.Stderr, gateErr, syncURL, "bd init")
|
|
} else {
|
|
fmt.Fprint(os.Stderr, gateErr.UserMessage())
|
|
printInitJoinGuidance(os.Stderr, gateErr)
|
|
}
|
|
return &exitError{Code: 1}
|
|
}
|
|
if externalServer {
|
|
if msg := externalServerUnreachableMessage(err); msg != "" {
|
|
fmt.Fprint(os.Stderr, msg)
|
|
return &exitError{Code: 1}
|
|
}
|
|
}
|
|
fmt.Fprintf(os.Stderr, "Error: failed to open Dolt store: %v\n", err)
|
|
return &exitError{Code: 1}
|
|
}
|
|
|
|
// Initialize global database schema and config in shared-server mode.
|
|
// Opens a separate store connection to beads_global with CreateIfMissing
|
|
// to trigger schema migration, then seeds the issue prefix and project ID.
|
|
// Skipped in gateway mode: initGlobalDatabaseConfig rebuilds its config
|
|
// without the Gateway flag, so it would run create/schema/write operations
|
|
// against the authenticating gateway (see shouldInitSharedGlobalDB).
|
|
if shouldInitSharedGlobalDB(sharedServer, doltserver.IsSharedServerMode(), doltCfg.Gateway) {
|
|
initGlobalDatabaseConfig(ctx, doltCfg, quiet)
|
|
}
|
|
|
|
// Configure the remote in the Dolt store so bd dolt push/pull work
|
|
// immediately after init/bootstrap. A git origin is a valid Dolt
|
|
// remote even before refs/dolt/data exists; the first bd dolt push
|
|
// creates that ref. This keeps the default path durable without
|
|
// falling back to JSONL-as-sync. Gateway mode skips it: the hosted
|
|
// server owns the database, so DOLT_REMOTE('add', ...) must not run
|
|
// against it (see shouldWriteInitDoltRemote).
|
|
// The URL is routed here too, not just on the clone path: the
|
|
// no-Dolt-data-yet case (the pre-first-push wiring this is for) never
|
|
// clones, so without routing a raw https forge URL would be stored
|
|
// verbatim in dolt_remotes and the *first* `bd dolt push` would take
|
|
// it to the remotesapi client — the #4421 storm, one leg further down
|
|
// (#5743).
|
|
if shouldWriteInitDoltRemote(doltCfg.Gateway, syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin, isDoltLocalOnly()) {
|
|
configureInitDoltRemote(ctx, store, doltRemoteURL(syncURL), quiet)
|
|
}
|
|
|
|
// === CONFIGURATION METADATA (Pattern A: Fatal) ===
|
|
// Configuration metadata is essential for core functionality and must succeed.
|
|
// These settings define fundamental behavior (issue IDs, sync workflow).
|
|
// Failure here indicates a serious problem that prevents normal operation.
|
|
|
|
// Read the workspace's identity ONCE, through issueops.InitVerifier. The
|
|
// prefix this init adopts and the project id it reconciles against come
|
|
// from ONE SNAPSHOT, so they cannot land either side of another rig's
|
|
// write, and an UNREADABLE identity is an error rather than an empty one
|
|
// the gateway paths would misdiagnose as an unprovisioned database.
|
|
initVerifier, err := store.InitVerifier()
|
|
if err != nil {
|
|
_ = store.Close()
|
|
return fmt.Errorf("failed to reach the workspace identity: %v", err)
|
|
}
|
|
dbIdentity, identityReadErr := initVerifier.VerifyIdentity(ctx, issueops.VerifyIdentityRequest{})
|
|
|
|
// Sanitize dots to underscores so issue IDs (e.g. "GPUPolynomials_jl-1")
|
|
// remain valid identifiers. Must match DoltDatabase sanitization above.
|
|
// In gateway mode the prefix is server-provisioned: adopt an existing one,
|
|
// refuse to invent a missing one. A read error is surfaced as a transient
|
|
// failure rather than misread as an unprovisioned (contract-violating) db.
|
|
// seedInitWorkspaceIdentity, below, is where issuePrefix lands.
|
|
issuePrefix, err := resolveInitIssuePrefix(doltCfg.Gateway, dbIdentity.Prefix, dbName, prefix, identityReadErr)
|
|
if err != nil {
|
|
_ = store.Close()
|
|
return err
|
|
}
|
|
|
|
// === TRACKING METADATA (Pattern B: Warn and Continue) ===
|
|
// Tracking metadata enhances functionality (diagnostics, version checks, collision detection)
|
|
// but the system works without it. Failures here degrade gracefully - we warn but continue.
|
|
// Belt-and-suspenders: write then verify read-back for each field.
|
|
|
|
// Tracking metadata (bd_version, repo_id, clone_id) is clone-local state.
|
|
// In gateway mode it must not be written into the shared, server-owned
|
|
// database: repo_id/clone_id are per-clone fingerprints and a last-init-wins
|
|
// overwrite feeds false cross-project mismatch diagnostics, while a read-only
|
|
// credential would only warn per field.
|
|
if shouldWriteInitStateToDB(doltCfg.Gateway) {
|
|
// Store bd version in clone-local metadata (dolt-ignored, no merge conflicts)
|
|
if err := store.SetLocalMetadata(ctx, "bd_version", Version); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to write bd_version local metadata: %v\n", err)
|
|
}
|
|
|
|
// Compute and store repository fingerprint (FR-015)
|
|
repoID, err := beads.ComputeRepoID()
|
|
if err != nil {
|
|
if !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not compute repository ID: %v\n", err)
|
|
}
|
|
} else {
|
|
if verifyMetadata(ctx, store, "repo_id", repoID) && !quiet {
|
|
fmt.Printf(" Repository ID: %s\n", repoID[:8])
|
|
}
|
|
}
|
|
|
|
// Compute and store clone-specific ID (FR-016: skip on failure)
|
|
cloneID, err := beads.GetCloneID()
|
|
if err != nil {
|
|
if !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not compute clone ID: %v\n", err)
|
|
}
|
|
} else {
|
|
if verifyMetadata(ctx, store, "clone_id", cloneID) && !quiet {
|
|
fmt.Printf(" Clone ID: %s\n", cloneID)
|
|
}
|
|
}
|
|
}
|
|
|
|
// bootstrapProjectID is the identity seedInitWorkspaceIdentity will
|
|
// record, resolved inside the metadata.json block below because that is
|
|
// where local and database identities are reconciled. It stays "" when
|
|
// that block does not run, and the seeding step falls back to the
|
|
// workspace's own metadata.json.
|
|
bootstrapProjectID := ""
|
|
|
|
// Create or preserve metadata.json for database metadata (bd-zai fix)
|
|
if useLocalBeads {
|
|
// First, check if metadata.json already exists
|
|
existingCfg, err := configfile.Load(beadsDir)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to load existing metadata.json: %v\n", err)
|
|
}
|
|
|
|
var cfg *configfile.Config
|
|
if existingCfg != nil {
|
|
// Preserve existing config
|
|
cfg = existingCfg
|
|
} else {
|
|
cfg = configfile.DefaultConfig()
|
|
}
|
|
|
|
// Resolve the project identity UUID (GH#2372). It is stored in both
|
|
// metadata.json and the database and verified on every connection to
|
|
// detect cross-project leakage.
|
|
//
|
|
// Consult the database _project_id and adopt it when:
|
|
// - --database is set and the database already exists on a
|
|
// shared remote Dolt server (GH#2922), or
|
|
// - we just bootstrapped from a remote whose Dolt history
|
|
// already carried a _project_id, or
|
|
// - we are connected to an authenticating gateway server, whose
|
|
// database identity is provisioned server-side.
|
|
// In all cases another rig — or the hosted server — has already
|
|
// chosen an identity; minting a new one and writing it back would
|
|
// overwrite the source identity and cause cross-project verification
|
|
// to fail on subsequent pulls. In gateway mode bd refuses to mint one
|
|
// at all (a missing identity is a provisioning-contract violation),
|
|
// and because the hosted server is authoritative it reconciles the
|
|
// identity on every init — even a re-init or preseeded workspace whose
|
|
// metadata.json already carries a stale project_id. This reconciliation
|
|
// depends on Gateway's CreateIfMissing:true open skipping the storage
|
|
// identity verifier (store.go newServerMode/verifyProjectIdentity) —
|
|
// Gateway-only, not init in general: a non-gateway CreateIfMissing:true
|
|
// init against an already-existing database now runs the verifier
|
|
// (GH#4637 Part A) and fails before this code runs at all. Without the
|
|
// Gateway skip, init would save the stale id as success and every later
|
|
// normal open would hard-fail with PROJECT IDENTITY MISMATCH.
|
|
//
|
|
// The id comes from the single InitVerifier read taken beside the
|
|
// prefix; shouldConsultInitProjectID still decides whether to USE it.
|
|
adoptedFromDB := ""
|
|
if store != nil && shouldConsultInitProjectID(doltCfg.Gateway, cfg.ProjectID, database, bootstrappedFromRemote) {
|
|
adoptedFromDB = dbIdentity.ProjectID
|
|
}
|
|
localID := cfg.ProjectID
|
|
resolvedID, identityChanged, err := resolveInitProjectID(doltCfg.Gateway, localID, adoptedFromDB, dbName, identityReadErr)
|
|
if err != nil {
|
|
_ = store.Close()
|
|
return err
|
|
}
|
|
if identityChanged && adoptedFromDB != "" && !quiet {
|
|
if localID == "" {
|
|
fmt.Printf(" %s Adopted project identity from existing database\n", ui.RenderPass("✓"))
|
|
} else {
|
|
fmt.Printf(" %s Reconciled local project identity with hosted database\n", ui.RenderPass("✓"))
|
|
}
|
|
}
|
|
cfg.ProjectID = resolvedID
|
|
|
|
// Always store backend explicitly in metadata.json
|
|
cfg.Backend = backend
|
|
// Metadata.json.database should point to the Dolt directory (not beads.db).
|
|
// Backward-compat: older dolt setups left this as "beads.db", which is misleading.
|
|
if backend == configfile.BackendDolt {
|
|
if cfg.Database == "" || cfg.Database == beads.CanonicalDatabaseName {
|
|
cfg.Database = "dolt"
|
|
}
|
|
|
|
// Set SQL database name. --database flag takes precedence over prefix-based
|
|
// naming to avoid cross-rig contamination (bd-u8rda). Only set prefix-based
|
|
// name if not already configured — overwriting a user-renamed database
|
|
// creates phantom catalog entries that crash information_schema (GH#2051).
|
|
if database != "" {
|
|
cfg.DoltDatabase = database
|
|
} else if cfg.DoltDatabase == "" && prefix != "" {
|
|
// Sanitize hyphens to underscores for SQL-idiomatic names (GH#2142).
|
|
// Dots were already normalized in prefix above.
|
|
// Must match the sanitization applied to dbName above,
|
|
// otherwise init creates a database with one name but metadata.json
|
|
// records a different name, causing reopens to fail.
|
|
cfg.DoltDatabase = strings.ReplaceAll(prefix, "-", "_")
|
|
}
|
|
|
|
if sharedServer || doltserver.IsSharedServerMode() {
|
|
cfg.GlobalDoltDatabase = doltserver.GlobalDatabaseName
|
|
cfg.GlobalProjectID = doltserver.GlobalProjectID
|
|
}
|
|
|
|
// Persist the connection mode matching this build.
|
|
priorMode := ""
|
|
if existingCfg != nil {
|
|
priorMode = strings.ToLower(strings.TrimSpace(existingCfg.DoltMode))
|
|
}
|
|
switch {
|
|
case usesProxiedServer():
|
|
cfg.DoltMode = configfile.DoltModeProxiedServer
|
|
case usesSQLServer():
|
|
cfg.DoltMode = configfile.DoltModeServer
|
|
default:
|
|
cfg.DoltMode = configfile.DoltModeEmbedded
|
|
}
|
|
// A mode change on an existing workspace is never silent
|
|
// (#3885). By this point the inheritance above has already
|
|
// preserved the old mode unless something explicitly asked to
|
|
// change it, so reaching here with a different mode means the
|
|
// user asked — but they still get told, because the change
|
|
// rewrites where this project's data lives.
|
|
if priorMode != "" && priorMode != cfg.DoltMode && !quiet {
|
|
fmt.Fprintf(os.Stderr,
|
|
"Connection mode changed: %s -> %s (recorded in .beads/metadata.json).\n",
|
|
priorMode, cfg.DoltMode)
|
|
}
|
|
|
|
if !usesProxiedServer() {
|
|
if serverHost != "" {
|
|
cfg.DoltServerHost = serverHost
|
|
}
|
|
if serverPort != 0 {
|
|
cfg.DoltServerPort = serverPort
|
|
}
|
|
if serverSocket != "" {
|
|
cfg.DoltServerSocket = serverSocket
|
|
}
|
|
if serverUser != "" {
|
|
cfg.DoltServerUser = serverUser
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
if err := cfg.Save(beadsDir); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to create metadata.json: %v\n", err)
|
|
// Non-fatal - continue anyway
|
|
}
|
|
|
|
// The write itself happens once, below this block, through
|
|
// seedInitWorkspaceIdentity; this is where its id is decided.
|
|
bootstrapProjectID = cfg.ProjectID
|
|
|
|
// Create config.yaml template (prefix is stored in DB, not config.yaml)
|
|
if err := createConfigYaml(beadsDir, false, ""); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to create config.yaml: %v\n", err)
|
|
// Non-fatal - continue anyway
|
|
}
|
|
|
|
// Persist sync.remote to config.yaml so fresh clones can
|
|
// bootstrap from it (the Dolt database is gitignored).
|
|
// Must run AFTER createConfigYaml which creates the file.
|
|
// Persist the effective remote so future bootstrap and hooks know
|
|
// Dolt, not JSONL, is the cross-machine sync path. Plain git
|
|
// origins are valid here: the first push creates refs/dolt/data,
|
|
// and bootstrap resolves such a URL by probing refs/dolt/data
|
|
// rather than rejecting it (#5743).
|
|
if err := persistInitSyncRemote(beadsDir, initRemote, syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin); err != nil {
|
|
return fmt.Errorf("failed to persist sync.remote to config.yaml: %v", err)
|
|
}
|
|
|
|
// Enable shared server mode if requested via flag OR env var (GH#2377).
|
|
// Persist to config.yaml so the project continues working without the env var.
|
|
if sharedServer || doltserver.IsSharedServerMode() {
|
|
if err := config.SetYamlConfig("dolt.shared-server", "true"); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to enable shared server mode: %v\n", err)
|
|
} else if !quiet {
|
|
fmt.Printf(" %s Shared server mode enabled\n", ui.RenderPass("✓"))
|
|
}
|
|
}
|
|
|
|
if debugMode {
|
|
if err := config.SetYamlConfig("dolt.debug", "true"); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to persist dolt.debug: %v\n", err)
|
|
} else if !quiet {
|
|
serverDir := doltserver.ResolveServerDir(beadsDir)
|
|
fmt.Printf(" %s Debug mode enabled\n", ui.RenderPass("✓"))
|
|
fmt.Printf(" Server log: %s\n", doltserver.LogPath(serverDir))
|
|
fmt.Printf(" Profile dir: %s\n", doltserver.DebugProfileDir(beadsDir))
|
|
fmt.Printf(" Note: cpu.pprof is written when the server exits cleanly (bd dolt stop).\n")
|
|
}
|
|
}
|
|
|
|
// In stealth mode, persist no-git-ops: true so bd prime
|
|
// automatically uses stealth session-close protocol (GH#2159)
|
|
if stealth {
|
|
if err := config.SaveConfigValue("no-git-ops", true, beadsDir); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set no-git-ops in config: %v\n", err)
|
|
}
|
|
}
|
|
|
|
// Create README.md
|
|
if err := createReadme(beadsDir); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to create README.md: %v\n", err)
|
|
// Non-fatal - continue anyway
|
|
}
|
|
}
|
|
|
|
// Seed the workspace's identity, through issueops.Bootstrapper, in the
|
|
// one place this route writes it. Gateway mode skips it: the identity
|
|
// is server-authoritative and the credential may be read-only, so bd
|
|
// adopts what it verified rather than writing it back.
|
|
if shouldWriteInitStateToDB(doltCfg.Gateway) {
|
|
if err := seedInitWorkspaceIdentity(ctx, store, dbIdentity, issuePrefix, bootstrapProjectID, beadsDir); err != nil {
|
|
_ = store.Close()
|
|
return err
|
|
}
|
|
}
|
|
|
|
// Initialize last_import_time metadata to mark the database as synced.
|
|
// This prevents bd doctor from reporting "No last_import_time recorded in database"
|
|
// after init completes. Sets the metadata to current time in RFC3339 format.
|
|
// (mybd-9gw: sync divergence fix). Skipped in gateway mode: this is client-local
|
|
// sync state that must not be written into the shared, server-owned database.
|
|
//
|
|
// It is NOT part of the bootstrap, and neither are the fingerprints
|
|
// above: those four values are refreshed on EVERY init, adopt or not,
|
|
// while the identity is written once and adopted forever.
|
|
if shouldWriteInitStateToDB(doltCfg.Gateway) {
|
|
if err := store.SetMetadata(ctx, "last_import_time", time.Now().Format(time.RFC3339)); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to initialize last_import_time: %v\n", err)
|
|
// Non-fatal - continue anyway
|
|
}
|
|
}
|
|
|
|
// Import from local JSONL if requested (GH#2023).
|
|
// This must run after the store is created and prefix is set.
|
|
if fromJSONL {
|
|
localJSONLPath := configuredImportJSONLPath(beadsDir)
|
|
if _, statErr := os.Stat(localJSONLPath); os.IsNotExist(statErr) {
|
|
_ = store.Close()
|
|
return fmt.Errorf("--from-jsonl specified but %s does not exist", localJSONLPath)
|
|
}
|
|
issueCount, importErr := importFromLocalJSONL(ctx, store, localJSONLPath)
|
|
if importErr != nil {
|
|
_ = store.Close()
|
|
return fmt.Errorf("failed to import from JSONL: %v", importErr)
|
|
}
|
|
if !quiet {
|
|
fmt.Printf(" Imported %d issues from %s\n", issueCount, localJSONLPath)
|
|
}
|
|
}
|
|
|
|
// projectRoleRepo is isInitRoleGitRepo held to keepHomeClean. The role,
|
|
// the fork routing (which also creates ~/.beads-planning) and the fork
|
|
// exclude below all write into the repository that probe finds, and
|
|
// under keepHomeClean that repository encloses the home instead of
|
|
// holding the project (see guardInitInHomeDir).
|
|
projectRoleRepo := func() bool { return !keepHomeClean && isInitRoleGitRepo(ctx) }
|
|
|
|
// Prompt for contributor mode if:
|
|
// - In a git repo (needed to set beads.role config)
|
|
// - Interactive terminal (stdin is TTY) and not --non-interactive
|
|
// - No explicit --contributor or --team flag provided
|
|
// - No explicit --role flag provided
|
|
if projectRoleRepo() && !contributor && !team && roleFlag == "" && !nonInteractive && shouldPromptForRole() {
|
|
promptedContributor, err := promptContributorMode()
|
|
if err != nil {
|
|
if isCanceled(err) {
|
|
fmt.Fprintln(os.Stderr, "Setup canceled.")
|
|
_ = store.Close()
|
|
return errCanceled()
|
|
}
|
|
// Non-fatal: warn but continue with default behavior
|
|
if !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to prompt for role: %v\n", err)
|
|
}
|
|
} else if promptedContributor {
|
|
contributor = true // Triggers contributor wizard below
|
|
}
|
|
} else if projectRoleRepo() && !contributor && !team {
|
|
// If prompt was skipped (non-interactive or CI environment),
|
|
// ensure beads.role is set to avoid "not configured" warning
|
|
// during diagnostics. Use --role flag if provided, otherwise default.
|
|
role := roleFlag
|
|
if role == "" {
|
|
role = "maintainer"
|
|
}
|
|
if _, hasRole := getBeadsRole(); !hasRole {
|
|
if err := setBeadsRole(role); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set default beads.role: %v\n", err)
|
|
}
|
|
} else if roleFlag != "" {
|
|
// Explicit --role flag overrides existing role
|
|
if err := setBeadsRole(role); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Run contributor wizard if --contributor flag is set or user chose contributor
|
|
if contributor {
|
|
if err := runContributorWizard(ctx, store); err != nil {
|
|
canceled := isCanceled(err)
|
|
if canceled {
|
|
fmt.Fprintln(os.Stderr, "Setup canceled.")
|
|
}
|
|
_ = store.Close()
|
|
if canceled {
|
|
return errCanceled()
|
|
}
|
|
return fmt.Errorf("running contributor wizard: %v", err)
|
|
}
|
|
|
|
// Contributor setup must also pin role detection to contributor.
|
|
// Without this, SSH remotes can be inferred as maintainer and bypass routing.
|
|
if projectRoleRepo() {
|
|
if err := setBeadsRole("contributor"); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role=contributor: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Run team wizard if --team flag is set
|
|
if team {
|
|
if err := runTeamWizard(ctx, store); err != nil {
|
|
canceled := isCanceled(err)
|
|
if canceled {
|
|
fmt.Fprintln(os.Stderr, "Setup canceled.")
|
|
}
|
|
_ = store.Close()
|
|
if canceled {
|
|
return errCanceled()
|
|
}
|
|
return fmt.Errorf("running team wizard: %v", err)
|
|
}
|
|
}
|
|
|
|
// Safety net: ensure beads.role is always set when in a git repo (GH#2950).
|
|
// Earlier code paths may skip role-setting when BEADS_DIR is set,
|
|
// promptContributorMode fails, or edge-case flag combinations are used.
|
|
// This guarantees every init leaves a usable role-configured state.
|
|
//
|
|
// The gate and the pair answer on the same boundary: isInitRoleGitRepo
|
|
// scrubs inherited routing and config suppression exactly as
|
|
// getBeadsRole/setBeadsRole do, so the gate cannot open on a repository
|
|
// the write will then fail to reach. Gating on the inherited isGitRepo()
|
|
// instead is what used to make this safety net write the role into a
|
|
// redirected repository.
|
|
if projectRoleRepo() {
|
|
if _, hasRole := getBeadsRole(); !hasRole {
|
|
fallbackRole := "maintainer"
|
|
if roleFlag != "" {
|
|
fallbackRole = roleFlag
|
|
}
|
|
if err := setBeadsRole(fallbackRole); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role=%s: %v\n", fallbackRole, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Auto-configure contributor routing for fork repos (bd-umbf Child 1).
|
|
// Non-interactive, idempotent; only fires when upstream remote detected
|
|
// and routing.contributor is not already set.
|
|
// This gate also enables planning-repository creation and config.yaml updates.
|
|
if !contributor && projectRoleRepo() {
|
|
if err := autoConfigureForkContributor(ctx, store, quiet || nonInteractive, roleFlag); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to auto-configure fork contributor routing: %v\n", err)
|
|
}
|
|
}
|
|
|
|
// Auto-commit Dolt state so bd doctor doesn't warn about uncommitted
|
|
// changes and users don't need a separate "bd vc commit" step. Init
|
|
// intentionally writes issue_prefix to config, while ordinary Commit
|
|
// excludes config to avoid sweeping unrelated stale values. Skip this in
|
|
// gateway mode: the shared server owns its history and the credential may
|
|
// be read-only, so bd must not issue DOLT_ADD/DOLT_COMMIT against it.
|
|
if shouldWriteInitStateToDB(doltCfg.Gateway) {
|
|
if err := commitInitState(ctx, store); err != nil {
|
|
// Non-fatal: some setups (e.g. no tables yet) may have nothing to commit
|
|
if !strings.Contains(err.Error(), "nothing to commit") {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to commit initial state: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
if err := store.Close(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to close database: %v\n", err)
|
|
}
|
|
|
|
if initServerMode {
|
|
if err := doltserver.MarkDoltDirCompatible(storagePath); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to write Dolt compatibility marker at %s: %v\n", storagePath, err)
|
|
}
|
|
}
|
|
|
|
// WARNING: DO NOT remove, delete, or modify files inside Dolt's .dolt/
|
|
// directory — including noms/LOCK files. These are Dolt-internal files.
|
|
// Removing them WILL cause unrecoverable data corruption and data loss.
|
|
// Dolt manages these files itself; external interference is never safe.
|
|
|
|
// Fork detection: offer to configure .git/info/exclude (GH#742)
|
|
setupExclude, _ := cmd.Flags().GetBool("setup-exclude")
|
|
if setupExclude {
|
|
// Manual flag - always configure
|
|
if err := setupForkExcludeAt(cwd, !quiet); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
|
}
|
|
} else if !stealth && projectRoleRepo() {
|
|
// Auto-detect fork and prompt (skip if stealth - it handles exclude already)
|
|
if isFork, upstreamURL := detectForkSetup(); isFork {
|
|
if nonInteractive {
|
|
// In non-interactive mode, auto-configure fork exclude
|
|
if err := setupForkExcludeAt(cwd, !quiet); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
|
}
|
|
} else {
|
|
shouldExclude, err := promptForkExclude(upstreamURL, quiet)
|
|
if err != nil {
|
|
if isCanceled(err) {
|
|
fmt.Fprintln(os.Stderr, "Setup canceled.")
|
|
return errCanceled()
|
|
}
|
|
}
|
|
if shouldExclude {
|
|
if err := setupForkExcludeAt(cwd, !quiet); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Auto-export prompt: disabled by default, let users opt in
|
|
// interactively for viewers and other JSONL integrations (GH#4062).
|
|
// In non-interactive mode the default (disabled) is kept.
|
|
if !nonInteractive && !quiet {
|
|
wantExport, err := promptAutoExport()
|
|
if err != nil && isCanceled(err) {
|
|
fmt.Fprintln(os.Stderr, "Setup canceled.")
|
|
return errCanceled()
|
|
}
|
|
if wantExport {
|
|
if err := config.SetYamlConfig("export.auto", "true"); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to enable auto-export: %v\n", err)
|
|
} else {
|
|
fmt.Printf(" %s Auto-export enabled -> .beads/issues.jsonl\n", ui.RenderPass("✓"))
|
|
}
|
|
} else if !quiet {
|
|
fmt.Printf(" %s Auto-export disabled (enable later with: bd config set export.auto true)\n", ui.RenderPass("✓"))
|
|
}
|
|
}
|
|
|
|
runEmbeddedInitHooks(rootCtx, cwd, beadsDir, skipHooks, quiet)
|
|
|
|
// Initialize version tracking: create .local_version file during bd init
|
|
// instead of deferring it to the first bd command.
|
|
// This ensures no "Version Tracking" warning from bd doctor after init.
|
|
if useLocalBeads {
|
|
localVersionPath := filepath.Join(beadsDir, ".local_version")
|
|
if err := writeLocalVersion(localVersionPath, Version); err != nil && !quiet {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to initialize version tracking: %v\n", err)
|
|
// Non-fatal - initialization still succeeded
|
|
}
|
|
}
|
|
|
|
// Add agent instructions to AGENTS.md (or custom filename via --agents-file)
|
|
// Skip in stealth mode (user wants invisible setup) or when explicitly skipped
|
|
if !stealth && !skipAgents {
|
|
agentsTemplate, _ := cmd.Flags().GetString("agents-template")
|
|
agentsProfileStr, _ := cmd.Flags().GetString("agents-profile")
|
|
agentsProfile := agents.Profile(agentsProfileStr)
|
|
agentsFile, _ := cmd.Flags().GetString("agents-file")
|
|
|
|
// Validate and persist custom agents filename
|
|
if agentsFile != "" {
|
|
if err := config.ValidateAgentsFile(agentsFile); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: invalid --agents-file: %v\n", err)
|
|
return
|
|
}
|
|
if err := config.SetYamlConfig("agents.file", agentsFile); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to persist agents.file to config: %v\n", err)
|
|
}
|
|
}
|
|
|
|
// Use flag value directly if provided (honoring user intent even if
|
|
// config persistence failed), otherwise read from config/default.
|
|
resolvedAgentsFile := agentsFile
|
|
if resolvedAgentsFile == "" {
|
|
resolvedAgentsFile = config.SafeAgentsFile()
|
|
}
|
|
if isBareGitRepo() {
|
|
if !quiet {
|
|
fmt.Printf(" Skipping %s generation in bare repository\n", resolvedAgentsFile)
|
|
}
|
|
} else {
|
|
renderOpts := agents.RenderOpts{HasRemote: shouldConfigureInitDoltRemote(syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin, isDoltLocalOnly()), NoPush: config.GetBool("no-push")}
|
|
addAgentsInstructions(resolvedAgentsFile, !quiet, agentsTemplate, agentsProfile, renderOpts)
|
|
}
|
|
}
|
|
|
|
// Auto-setup Claude hooks, Codex, and Cursor project integration. Skip in
|
|
// stealth mode or when agents are skipped.
|
|
if !stealth && !skipAgents && !isBareGitRepo() {
|
|
// --quiet drops the installers' progress like every other init
|
|
// message; failures still reach stderr (the installers' own
|
|
// error lines and the warnings below), quiet or not.
|
|
installOut := setup.ProjectInstallOutput{}
|
|
if quiet {
|
|
installOut = setup.QuietProjectInstallOutput()
|
|
}
|
|
if err := setup.InstallClaudeProjectTo(stealth, installOut); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to setup Claude hooks: %v\n", err)
|
|
// Non-fatal - continue with init
|
|
}
|
|
if err := setup.InstallCodexProjectTo(installOut); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to setup Codex integration: %v\n", err)
|
|
// Non-fatal - continue with init
|
|
}
|
|
if err := setup.InstallCursorProjectTo(installOut); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to setup Cursor integration: %v\n", err)
|
|
// Non-fatal - continue with init
|
|
}
|
|
}
|
|
|
|
// Not under keepHomeClean: the repository git finds from the home is
|
|
// not the project's, and the commit would stage the legacy ~/.beads
|
|
// and the home's own agent files into it (see guardInitInHomeDir).
|
|
if !stealth && useLocalBeads && !keepHomeClean {
|
|
commitEmbeddedInitArtifacts(cwd, quiet)
|
|
}
|
|
|
|
// Check for missing git upstream and warn if not configured.
|
|
// Only warn when remotes exist (has origin but no upstream).
|
|
// Skip for brand-new repos with no remotes — the warning is noise there.
|
|
// Skip under keepHomeClean too: that advice is for a repository that
|
|
// is not the project's.
|
|
if isGitRepo() && !keepHomeClean && !quiet {
|
|
if gitHasAnyRemotes() && !gitHasUpstream() {
|
|
fmt.Fprintf(os.Stderr, "\n%s Git upstream not configured\n", ui.RenderWarn("⚠"))
|
|
fmt.Fprintf(os.Stderr, " For sync workflows, set your upstream with:\n")
|
|
fmt.Fprintf(os.Stderr, " %s\n\n", ui.RenderAccent("git remote add upstream <repo-url>"))
|
|
}
|
|
if !stealth && !initRemoteChanged && !shouldWireInitRemote(syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin) {
|
|
printInitNoDoltRemoteWarning(true)
|
|
}
|
|
}
|
|
|
|
// Skip output if quiet mode
|
|
if quiet {
|
|
return
|
|
}
|
|
|
|
if bootstrappedFromRemote {
|
|
fmt.Printf("\n%s bd initialized from git remote!\n\n", ui.RenderPass("✓"))
|
|
} else {
|
|
fmt.Printf("\n%s bd initialized successfully!\n\n", ui.RenderPass("✓"))
|
|
}
|
|
fmt.Printf(" Backend: %s\n", ui.RenderAccent(backend))
|
|
if !usesSQLServer() {
|
|
fmt.Printf(" Mode: %s\n", ui.RenderAccent("embedded"))
|
|
} else {
|
|
host := serverHost
|
|
if host == "" {
|
|
host = configfile.DefaultDoltServerHost
|
|
}
|
|
port := serverPort
|
|
if port == 0 {
|
|
port = doltserver.DefaultConfig(beadsDir).Port
|
|
}
|
|
user := serverUser
|
|
if user == "" {
|
|
user = configfile.DefaultDoltServerUser
|
|
}
|
|
fmt.Printf(" Mode: %s\n", ui.RenderAccent("server"))
|
|
fmt.Printf(" Server: %s\n", ui.RenderAccent(fmt.Sprintf("%s@%s:%d", user, host, port)))
|
|
// Warn when using the default localhost — this is the #1 misconfiguration
|
|
// for setups where Dolt runs on a remote machine (e.g., over Tailscale).
|
|
if serverHost == "" && os.Getenv("BEADS_DOLT_SERVER_HOST") == "" {
|
|
fmt.Fprintf(os.Stderr, "\n %s Server host defaulted to %s.\n", ui.RenderWarn("⚠"), configfile.DefaultDoltServerHost)
|
|
fmt.Fprintf(os.Stderr, " If your Dolt server is remote, set BEADS_DOLT_SERVER_HOST or pass --server-host.\n")
|
|
}
|
|
}
|
|
// Advertise the prefix that issue IDs will actually use. When the database
|
|
// already carries a provisioned issue_prefix — gateway adoption of a
|
|
// server-provisioned value, or a shared database another rig already
|
|
// configured — that value, not the caller-derived local prefix, is what
|
|
// appears in IDs, so the summary must show it instead of a prefix that
|
|
// will never be minted.
|
|
effectivePrefix := prefix
|
|
if dbIdentity.Prefix != "" {
|
|
effectivePrefix = dbIdentity.Prefix
|
|
}
|
|
fmt.Printf(" Database: %s\n", ui.RenderAccent(dbName))
|
|
fmt.Printf(" Issue prefix: %s\n", ui.RenderAccent(effectivePrefix))
|
|
fmt.Printf(" Issues will be named: %s\n\n", ui.RenderAccent(effectivePrefix+"-<hash> (e.g., "+effectivePrefix+"-a3f2dd)"))
|
|
fmt.Printf("Run %s to get started.\n\n", ui.RenderAccent("bd quickstart"))
|
|
|
|
// Detect backup files from a previous session (GH#2327).
|
|
// This catches the branch-switch scenario: user ran bd init on a new
|
|
// branch and the database was created fresh, but backup JSONL files
|
|
// exist from a prior backup on this or another branch.
|
|
if !bootstrappedFromRemote && dolt.HasBackupFiles(beadsDir) {
|
|
fmt.Printf(" %s Backup files detected in .beads/backup/\n", ui.RenderWarn("!"))
|
|
fmt.Printf(" To restore issues from a previous backup, run:\n")
|
|
fmt.Printf(" %s\n\n", ui.RenderAccent("bd backup restore"))
|
|
}
|
|
|
|
// Run limited diagnostics to verify init succeeded.
|
|
// Skipped in embedded mode: diagnostics use dolt.NewFromConfigWithOptions
|
|
// which auto-starts a dolt sql-server. Embedded init already validates
|
|
// the database via initSchema.
|
|
if usesSQLServer() {
|
|
doctorResult := runInitDiagnostics(cwd)
|
|
hasIssues := false
|
|
for _, check := range doctorResult.Checks {
|
|
if check.Status != statusOK {
|
|
hasIssues = true
|
|
break
|
|
}
|
|
}
|
|
if hasIssues {
|
|
fmt.Printf("%s Setup incomplete. Some issues were detected:\n", ui.RenderWarn("⚠"))
|
|
for _, check := range doctorResult.Checks {
|
|
if check.Status != statusOK {
|
|
fmt.Printf(" • %s: %s\n", check.Name, check.Message)
|
|
}
|
|
}
|
|
fmt.Printf("\nRun %s to see details and fix these issues.\n\n", ui.RenderAccent("bd doctor --fix"))
|
|
}
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
initCmd.Flags().StringP("prefix", "p", "", "Issue prefix (default: current directory name)")
|
|
initCmd.Flags().BoolP("quiet", "q", false, "Suppress output (quiet mode)")
|
|
initCmd.Flags().Bool("contributor", false, "Run OSS contributor setup wizard")
|
|
initCmd.Flags().Bool("team", false, "Run team workflow setup wizard")
|
|
initCmd.Flags().Bool("stealth", false, "Enable stealth mode: keep beads files out of git via .git/info/exclude (sets no-git-ops)")
|
|
initCmd.Flags().Bool("setup-exclude", false, "Configure .git/info/exclude to keep beads files local (for forks)")
|
|
initCmd.Flags().Bool("skip-hooks", false, "Skip git hooks installation")
|
|
initCmd.Flags().Bool("skip-agents", false, "Skip AGENTS.md and Claude/Codex/Cursor setup generation")
|
|
initCmd.Flags().Bool("force", false, "Deprecated alias for --reinit-local. Bypasses only the LOCAL data-safety guard; does NOT authorize remote divergence or recreating a missing server-mode database (see 'bd help init-safety').")
|
|
initCmd.Flags().Bool("reinit-local", false, "Re-initialize local .beads/ over existing local data. Does NOT authorize remote divergence (see --discard-remote) or recreating a missing server-mode database (see --recreate-missing).")
|
|
initCmd.Flags().Bool("discard-remote", false, "Authorize discarding the configured remote's Dolt history when re-initializing. Requires --destroy-token in non-interactive mode; see 'bd help init-safety'.")
|
|
initCmd.Flags().Bool("recreate-missing", false, "Explicitly authorize creating a fresh, empty database when this project's configured server-mode database is missing or unreachable. Opt-in per invocation only; never implied by --force, config, or env (see 'bd help init-safety').")
|
|
initCmd.Flags().Bool("from-jsonl", false, "Import issues from configured import.path; refuses remote history unless --discard-remote authorizes replacement")
|
|
initCmd.Flags().Bool("init-if-missing", false, "If the workspace is already initialized, skip init and exit 0 instead of failing (idempotent init for scaffolds)")
|
|
initCmd.Flags().String("destroy-token", "", "Explicit confirmation token for destructive re-init in non-interactive mode (format: 'DESTROY-<prefix>')")
|
|
initCmd.Flags().String("agents-template", "", "Path to custom AGENTS.md template (overrides embedded default)")
|
|
initCmd.Flags().String("agents-profile", "", "AGENTS.md profile: 'minimal' (default, pointer to bd prime) or 'full' (complete command reference)")
|
|
initCmd.Flags().String("agents-file", "", "Custom filename for agent instructions (default: AGENTS.md)")
|
|
initCmd.Flags().String("remote", "", "Dolt remote URL to clone from and persist as sync.remote")
|
|
|
|
// Non-interactive mode for CI/cloud agents
|
|
initCmd.Flags().Bool("non-interactive", false, "Skip all interactive prompts (auto-detected in CI or non-TTY environments)")
|
|
initCmd.Flags().String("role", "", "Set beads role without prompting: \"maintainer\" or \"contributor\"")
|
|
|
|
// Backend selection: Dolt is the default and only supported backend.
|
|
initCmd.Flags().String("backend", "", "Storage backend: dolt (default). Removed backends (postgres, mysql, sqlite) print migration guidance.")
|
|
// Keep the short-lived removed-backend flags as hidden parser tombstones. A
|
|
// legacy invocation can then reach the backend rollback guidance instead of
|
|
// failing early with an opaque "unknown flag" error. The current backend rejects
|
|
// these flags explicitly above; they are never consumed as connection data.
|
|
for _, legacyFlag := range removedBackendInitFlags {
|
|
initCmd.Flags().String(legacyFlag.name, "", legacyFlag.usage)
|
|
_ = initCmd.Flags().MarkHidden(legacyFlag.name)
|
|
}
|
|
|
|
// Dolt server connection flags
|
|
initCmd.Flags().Bool("server", false, "Use external dolt sql-server instead of embedded engine")
|
|
initCmd.Flags().String("server-host", "", "Dolt server host (default: 127.0.0.1)")
|
|
initCmd.Flags().Bool("server-tls", false, "Require TLS for the init-time Dolt server connection (overrides BEADS_DOLT_SERVER_TLS for this run; not persisted - set the env var or credentials file for later commands)")
|
|
initCmd.Flags().Int("server-port", 0, "Dolt server port (default: 3307)")
|
|
initCmd.Flags().String("server-socket", "", "Unix domain socket path (overrides host/port; pass '' to ignore an ambient BEADS_DOLT_SERVER_SOCKET and use TCP)")
|
|
initCmd.Flags().String("server-user", "", "Dolt server MySQL user (default: root)")
|
|
initCmd.Flags().Bool("shared-server", false, "Enable shared Dolt server mode (all projects share one server at ~/.beads/shared-server/)")
|
|
initCmd.Flags().Bool("external", false, "Server is externally managed (skip server startup); use with --shared-server or --server")
|
|
initCmd.Flags().Bool("debug", false, "Run the managed Dolt sql-server with --loglevel=debug and CPU profiling (--prof cpu). Persisted to config.yaml as dolt.debug. No effect on externally-managed servers.")
|
|
initCmd.Flags().Bool("proxied-server", false, "[EXPERIMENTAL] Use a per-workspace proxied dolt sql-server (proxy + child dolt) rooted at .beads/dolt")
|
|
initCmd.Flags().Bool("team-server", false, "[EXPERIMENTAL] The shared database's schema is managed by beads-team-server (bts): bd never creates the database or runs schema migrations, only verifies the schema version (proxied-server mode only). Not related to --team.")
|
|
initCmd.Flags().String("proxied-server-config-path", "", "[EXPERIMENTAL] Absolute path to an existing dolt sql-server YAML config (proxied-server mode only). When set, bd uses this file instead of auto-generating one. Relative paths are rejected. Managed mode requires listener.host to be a numeric loopback IP (hostnames including localhost, non-loopback addresses, listener.socket, remotesapi, and cluster config are rejected); the same policy applies to BEADS_PROXIED_SERVER_CONFIG.")
|
|
initCmd.Flags().String("proxied-server-log-path", "", "[EXPERIMENTAL] Absolute path to the proxied dolt sql-server log file (proxied-server mode only). Default: <beadsDir>/dolt/server.log. Relative paths are rejected.")
|
|
initCmd.Flags().String("proxied-server-root-path", "", "[EXPERIMENTAL] Absolute directory holding the proxied dolt sql-server's lockfiles, pidfiles, and child .dolt repository (proxied-server mode only). Default: <beadsDir>/dolt. May not exist yet — bd will create it. Relative paths are rejected.")
|
|
initCmd.Flags().Int("proxied-server-port", 0, "[EXPERIMENTAL] Fixed TCP port for the proxy's loopback listener (proxied-server mode only). Default 0 = an OS-assigned free port. Startup fails if the port is already in use.")
|
|
initCmd.Flags().Duration("proxied-server-idle-timeout", 0, "[EXPERIMENTAL] Idle duration after which the proxy shuts down its loopback listener and backend (proxied-server mode only). Omit for the built-in default (30s); 0 keeps the proxy and backend alive indefinitely; a positive value sets the window.")
|
|
initCmd.Flags().String("proxied-server-external-host", "", "[EXPERIMENTAL] Hostname or IP of an externally-managed dolt sql-server the proxy should front (proxied-server mode only). Mutually exclusive with --proxied-server-external-socket-path.")
|
|
initCmd.Flags().Int("proxied-server-external-port", 0, "[EXPERIMENTAL] TCP port of the externally-managed dolt sql-server (proxied-server mode only). Required when --proxied-server-external-host is set.")
|
|
initCmd.Flags().String("proxied-server-external-socket-path", "", "[EXPERIMENTAL] Absolute unix socket path of the externally-managed dolt sql-server (proxied-server mode only). Mutually exclusive with --proxied-server-external-host. Relative paths are rejected.")
|
|
initCmd.Flags().String("proxied-server-external-user", "", "[EXPERIMENTAL] MySQL user for the externally-managed dolt sql-server (proxied-server mode only). Defaults to \"root\" when empty. Password is read at runtime from $BEADS_PROXIED_SERVER_EXTERNAL_PASSWORD and is never persisted to disk.")
|
|
initCmd.Flags().Bool("proxied-server-external-tls", false, "[EXPERIMENTAL] Require TLS when connecting to the externally-managed dolt sql-server (proxied-server mode only).")
|
|
initCmd.Flags().String("proxied-server-external-tls-ca-cert-path", "", "[EXPERIMENTAL] Absolute path to a CA certificate (PEM) used to verify the externally-managed dolt sql-server. Empty uses the system trust store. Relative paths are rejected.")
|
|
initCmd.Flags().String("proxied-server-external-tls-cert-path", "", "[EXPERIMENTAL] Absolute path to a client TLS certificate (for mTLS to the externally-managed dolt sql-server). Must be paired with --proxied-server-external-tls-key-path. Relative paths are rejected.")
|
|
initCmd.Flags().String("proxied-server-external-tls-key-path", "", "[EXPERIMENTAL] Absolute path to the client TLS private key (for mTLS to the externally-managed dolt sql-server). Must be paired with --proxied-server-external-tls-cert-path. Relative paths are rejected.")
|
|
initCmd.Flags().String("proxied-server-external-tls-server-name", "", "[EXPERIMENTAL] Server name to verify in the external dolt sql-server's TLS certificate. Defaults to the external host. Required with a unix socket unless --proxied-server-external-tls-skip-verify is set.")
|
|
initCmd.Flags().Bool("proxied-server-external-tls-skip-verify", false, "[EXPERIMENTAL] Skip TLS certificate verification for the external dolt sql-server. Insecure; testing only.")
|
|
initCmd.Flags().Duration("proxied-server-external-keep-alive", 0, "[EXPERIMENTAL] TCP keepalive period for the proxy→external connection. Zero uses the package default (30s).")
|
|
|
|
rootCmd.AddCommand(initCmd)
|
|
}
|
|
|
|
var removedBackendInitFlags = []struct {
|
|
name string
|
|
usage string
|
|
origin string
|
|
rationale string
|
|
}{
|
|
{name: "pg-url", usage: "Legacy PostgreSQL connection URL (removed backend compatibility only)", origin: "the removed PostgreSQL/MySQL initialization paths", rationale: configfile.RemovedBackendRationale},
|
|
{name: "pg-schema", usage: "Legacy PostgreSQL schema (removed backend compatibility only)", origin: "the removed PostgreSQL/MySQL initialization paths", rationale: configfile.RemovedBackendRationale},
|
|
{name: "mysql-url", usage: "Legacy MySQL connection URL (removed backend compatibility only)", origin: "the removed PostgreSQL/MySQL initialization paths", rationale: configfile.RemovedBackendRationale},
|
|
{name: "mysql-database", usage: "Legacy MySQL database (removed backend compatibility only)", origin: "the removed PostgreSQL/MySQL initialization paths", rationale: configfile.RemovedBackendRationale},
|
|
{name: "sqlite-path", usage: "Legacy SQLite database file (removed backend compatibility only)", origin: "the removed SQLite initialization path", rationale: configfile.RemovedSQLiteRationale},
|
|
}
|
|
|
|
// migrateOldDatabases detects and migrates old database files to beads.db
|
|
func migrateOldDatabases(targetPath string, quiet bool) error {
|
|
targetDir := filepath.Dir(targetPath)
|
|
targetName := filepath.Base(targetPath)
|
|
|
|
// If target already exists, no migration needed
|
|
if _, err := os.Stat(targetPath); err == nil {
|
|
return nil
|
|
}
|
|
|
|
// Create .beads directory if it doesn't exist
|
|
if err := os.MkdirAll(targetDir, 0750); err != nil {
|
|
return fmt.Errorf("failed to create .beads directory: %w", err)
|
|
}
|
|
|
|
// Look for existing .db files in the .beads directory
|
|
pattern := filepath.Join(targetDir, "*.db")
|
|
matches, err := filepath.Glob(pattern)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to search for existing databases: %w", err)
|
|
}
|
|
|
|
// Filter out the target file name and any backup files
|
|
var oldDBs []string
|
|
for _, match := range matches {
|
|
baseName := filepath.Base(match)
|
|
if baseName != targetName && !strings.HasSuffix(baseName, ".backup.db") {
|
|
oldDBs = append(oldDBs, match)
|
|
}
|
|
}
|
|
|
|
if len(oldDBs) == 0 {
|
|
// No old databases to migrate
|
|
return nil
|
|
}
|
|
|
|
if len(oldDBs) > 1 {
|
|
// Multiple databases found - ambiguous, require manual intervention
|
|
return fmt.Errorf("multiple database files found in %s: %v\nPlease manually rename the correct database to %s and remove others",
|
|
targetDir, oldDBs, targetName)
|
|
}
|
|
|
|
// Migrate the single old database
|
|
oldDB := oldDBs[0]
|
|
if !quiet {
|
|
fmt.Fprintf(os.Stderr, "→ Migrating database: %s → %s\n", filepath.Base(oldDB), targetName)
|
|
}
|
|
|
|
// Rename the old database to the new canonical name
|
|
if err := os.Rename(oldDB, targetPath); err != nil {
|
|
return fmt.Errorf("failed to migrate database %s to %s: %w", oldDB, targetPath, err)
|
|
}
|
|
|
|
if !quiet {
|
|
fmt.Fprintf(os.Stderr, "✓ Database migration complete\n\n")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// errWorkspaceAlreadyInitialized marks the benign "this workspace already has a
|
|
// database" outcome from checkExistingBeadsData. --init-if-missing treats only
|
|
// this case as an idempotent skip; any other error from the check is operational
|
|
// (e.g. an unreadable .beads/embeddeddolt directory) and must still abort rather
|
|
// than be silently masked as success.
|
|
var errWorkspaceAlreadyInitialized = errors.New("workspace already initialized")
|
|
|
|
// workspaceExistsError carries a user-facing "already initialized" message while
|
|
// still matching errWorkspaceAlreadyInitialized via errors.Is, so callers can
|
|
// distinguish the benign case without the sentinel text leaking into the message.
|
|
type workspaceExistsError struct{ msg string }
|
|
|
|
func (e *workspaceExistsError) Error() string { return e.msg }
|
|
func (e *workspaceExistsError) Is(target error) bool {
|
|
return target == errWorkspaceAlreadyInitialized
|
|
}
|
|
|
|
// alreadyInitialized builds a workspaceExistsError from a formatted message.
|
|
func alreadyInitialized(format string, args ...any) error {
|
|
return &workspaceExistsError{msg: fmt.Sprintf(format, args...)}
|
|
}
|
|
|
|
// checkExistingBeadsDataAt checks for existing database at a specific beadsDir path.
|
|
// This is extracted to support both BEADS_DIR and CWD-based resolution.
|
|
//
|
|
// A returned error that matches errWorkspaceAlreadyInitialized means a database
|
|
// already exists (the benign, idempotent-skip case); any other error is
|
|
// operational and must not be treated as success.
|
|
|
|
func checkExistingBeadsDataAt(beadsDir string, prefix string) error {
|
|
// Check if .beads directory exists
|
|
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
|
|
return nil // No .beads directory, safe to init
|
|
}
|
|
|
|
// metadata.json is authoritative for the configured backend, so resolve it once
|
|
// and dispatch. Removed-backend tombstones are marked by metadata
|
|
// alone — there is no local Dolt directory to inspect — so a plain
|
|
// `bd init` (which defaults to Dolt) must not silently repoint a live SQL
|
|
// workspace to a fresh embedded Dolt DB and orphan its issues. --reinit-local
|
|
// /--force bypass this (handled by the caller). Invalid metadata must fail closed:
|
|
// without an explicit reinitialization request, init may not overwrite the only
|
|
// marker for an external or otherwise nonlocal database.
|
|
cfg, cfgErr := configfile.LoadForDiscovery(beadsDir)
|
|
if cfgErr != nil {
|
|
return fmt.Errorf("failed to load %s: %w; refusing to reinitialize automatically (restore the metadata or use --reinit-local after safeguarding existing data)", configfile.ConfigPath(beadsDir), cfgErr)
|
|
}
|
|
if cfg != nil {
|
|
if guardErr := validateConfiguredBackend(cfg, beadsDir); guardErr != nil {
|
|
return guardErr
|
|
}
|
|
}
|
|
|
|
if cfg != nil && cfg.GetBackend() == configfile.BackendDolt {
|
|
if cfg.IsDoltProxiedServerMode() {
|
|
proxiedRoot, rootErr := resolveProxiedServerRootPath(beadsDir)
|
|
if rootErr != nil {
|
|
return fmt.Errorf("resolve proxied server root: %w", rootErr)
|
|
}
|
|
if info, statErr := os.Stat(proxiedRoot); statErr == nil && info.IsDir() {
|
|
return alreadyInitialized(`
|
|
%s Found existing Dolt database: %s
|
|
|
|
This workspace is already initialized.
|
|
|
|
To use the existing database:
|
|
Just run bd commands normally (e.g., %s)
|
|
|
|
Aborting.`, ui.RenderWarn("⚠"), proxiedRoot, ui.RenderAccent("bd list"))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Embedded mode stores databases under `.beads/embeddeddolt/<db>/`.
|
|
// Use the target workspace metadata rather than ambient process state so
|
|
// init guards remain deterministic even when another test or earlier
|
|
// command has rebound global server-mode state.
|
|
if !cfg.IsDoltServerMode() {
|
|
embeddedRoot := filepath.Join(beadsDir, "embeddeddolt")
|
|
entries, err := os.ReadDir(embeddedRoot)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil // No embedded root -> fresh clone, safe to init
|
|
}
|
|
return fmt.Errorf("failed to read embedded dolt directory %s: %w", embeddedRoot, err)
|
|
}
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() {
|
|
continue
|
|
}
|
|
if info, statErr := os.Stat(filepath.Join(embeddedRoot, entry.Name(), ".dolt")); statErr == nil && info.IsDir() {
|
|
location := filepath.Join(embeddedRoot, entry.Name())
|
|
return alreadyInitialized(`
|
|
%s Found existing Dolt database: %s
|
|
|
|
This workspace is already initialized.
|
|
|
|
To use the existing database:
|
|
Just run bd commands normally (e.g., %s)
|
|
|
|
If the database is genuinely corrupt and unrecoverable:
|
|
bd export > issue-export.jsonl # Export issue records first
|
|
bd init --reinit-local --prefix %s # Then reinitialize
|
|
|
|
Aborting.`, ui.RenderWarn("⚠"), location, ui.RenderAccent("bd list"), prefix)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Check both the local database AND server mode config.
|
|
// In server mode the local dolt/ directory may hold no database for
|
|
// this project — the data lives on the Dolt sql-server. Checking only
|
|
// the directory would miss server-mode installations.
|
|
doltPath := doltserver.ResolveDoltDir(beadsDir)
|
|
dbName := cfg.GetDoltDatabase()
|
|
|
|
// Probe THIS PROJECT's database directory, not the Dolt data directory
|
|
// that merely holds it: a data dir contains one subdirectory per
|
|
// database, each with its own .dolt.
|
|
//
|
|
// Statting the data dir instead made the FR-010 branch below
|
|
// unreachable on every initialized workspace, because the data dir
|
|
// always exists there — shared-server mode MkdirAlls the
|
|
// machine-global one in SharedDoltDir(), per-project mode MkdirAlls it
|
|
// in ensureDoltInit. So the branch never ran, and both
|
|
// --recreate-missing opt-ins inside it were dead code: the escape
|
|
// hatch named by the flag help, `bd help init-safety`,
|
|
// docs/recovery/init-safety.md and the guard's own refusal text all
|
|
// pointed at a command that could not reach its own opt-in, leaving
|
|
// the operator circling between two refusals. Same probe, and the same
|
|
// reason, as guardMissingServerDatabaseAt. Pinned by
|
|
// TestInitGuard_ExistingProjectMissingServerDB_DataDirPresent_Refuses
|
|
// and TestInitGuard_RecreateMissing_ReachesOptIn_DataDirPresent.
|
|
//
|
|
// The data-dir stat does not go away, it stops being the gate: making
|
|
// the branch reachable also exposes states it used to shadow, and
|
|
// permitting those would be a new fail-open policy rather than a fix.
|
|
// The permit condition below keeps it to what the old probe already
|
|
// allowed, plus the explicit opt-in. Pinned by
|
|
// TestInitGuard_NoProjectID_DataDirPresent_StillBlocks.
|
|
localDatabaseExists := false
|
|
if info, err := os.Stat(filepath.Join(doltPath, dbName, ".dolt")); err == nil && info.IsDir() {
|
|
localDatabaseExists = true
|
|
}
|
|
// The data directory is still read, but only to keep this fix from
|
|
// widening what fails OPEN. See the permit condition below.
|
|
doltDirExists := false
|
|
if info, err := os.Stat(doltPath); err == nil && info.IsDir() {
|
|
doltDirExists = true
|
|
}
|
|
if localDatabaseExists || cfg.IsDoltServerMode() {
|
|
// For server mode, distinguish "DB exists" from "DB missing" (FR-010).
|
|
if cfg.IsDoltServerMode() && !localDatabaseExists {
|
|
host := cfg.GetDoltServerHost()
|
|
port := doltserver.DefaultConfig(beadsDir).Port
|
|
password := cfg.GetDoltServerPassword()
|
|
user := cfg.GetDoltServerUser()
|
|
|
|
// localDatabaseExists==false is ambiguous in server mode: it's the
|
|
// normal state both for a genuine fresh clone (GH#2433) and for an
|
|
// existing project whose server-side database was lost or is
|
|
// unreachable (be-5up5: 2026-08-11 fleet-wide data loss). project_id
|
|
// is written by a real prior `bd init`, so a non-empty value here is
|
|
// taken as the latter — recovery, not a fresh clone.
|
|
//
|
|
// Known limit: project_id was minted by GH#2372, so a workspace
|
|
// initialized before that carries none and is indistinguishable
|
|
// here from a fresh clone. Such workspaces FAIL OPEN — init will
|
|
// still create the database. Accepted deliberately: failing closed
|
|
// would block legitimate first inits on every pre-GH#2372 clone,
|
|
// and this guard's job is to stop a silent recreate where we can
|
|
// PROVE prior initialization, not to guess where we cannot.
|
|
//
|
|
// SETTLED by ADR-0004 (engdocs/adr/0004-missing-database-guard-signal.md).
|
|
// project_id is a weak proof of prior LOCAL init: .beads/metadata.json
|
|
// is git-tracked by default (see GitignoreTemplate in
|
|
// cmd/bd/doctor/gitignore.go, which says so in as many words), so a
|
|
// fresh clone inherits one and is refused here with a recovery
|
|
// message. That is ACCEPTED, not a gap awaiting a fix: absence of
|
|
// local state cannot distinguish "never initialized here" from
|
|
// "initialized here, storage since lost", and the second is the
|
|
// shape of the 2026-08-11 loss. The failure direction is the safe
|
|
// one — it never recreates a database silently — and
|
|
// --recreate-missing is the permanent, documented resolution path,
|
|
// reachable since the probe fix above. Read the ADR before
|
|
// reopening this; the data-directory and local-marker alternatives
|
|
// are recorded there as rejected, with reasons.
|
|
existingProject := cfg.ProjectID != ""
|
|
|
|
result := checkDatabaseOnServer(host, port, user, password, dbName, cfg.GetDoltServerTLS())
|
|
if result.Reachable && !result.Exists && result.Err == nil {
|
|
// Server is up but DB doesn't exist.
|
|
if existingProject && !initAllowRecreateMissing {
|
|
return initGuardMissingServerDBMessage(dbName, host, port, prefix, true)
|
|
}
|
|
// Fresh clone (GH#2433) or explicit --recreate-missing opt-in —
|
|
// there's no local database to protect. Allow init to proceed so
|
|
// the user can bootstrap (e.g. via --from-jsonl).
|
|
if initAllowRecreateMissing || !doltDirExists {
|
|
return nil
|
|
}
|
|
// Reached only with no project_id AND a local Dolt data
|
|
// directory present. The old data-dir probe blocked this
|
|
// state by never arriving here at all; it keeps being
|
|
// blocked, by the same message as before. Permitting it
|
|
// would be a new fail-open policy on workspaces that
|
|
// predate project_id (GH#2372) — exactly the population
|
|
// this guard exists for — and choosing the replacement
|
|
// signal is be-5pjhd's call, not this fix's.
|
|
}
|
|
if result.Reachable && result.Exists {
|
|
// Server up and DB exists — fall through to "already initialized" error.
|
|
} else {
|
|
// Either the server was unreachable or errored during the
|
|
// check, OR the block above adjudicated a reachable server
|
|
// that positively confirmed the database is gone and fell
|
|
// through without returning (no project_id, local Dolt data
|
|
// directory present). Do not give this branch
|
|
// unreachability-specific text, telemetry or error wrapping
|
|
// without first re-reading that fall-through: on that path
|
|
// the server answered authoritatively, and the two guards
|
|
// below are correct for both cases only because their
|
|
// conditions do not mention reachability.
|
|
if existingProject && !initAllowRecreateMissing {
|
|
return initGuardMissingServerDBMessage(dbName, host, port, prefix, true)
|
|
}
|
|
// Fresh clone with committed metadata.json but no local dolt/
|
|
// directory, or explicit --recreate-missing opt-in — allow init
|
|
// to proceed so the user can bootstrap the database (e.g. via
|
|
// --from-jsonl). Same narrowing as the reachable-server branch
|
|
// above, for the same reason.
|
|
if initAllowRecreateMissing || !doltDirExists {
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
|
|
location := doltPath
|
|
if cfg.IsDoltServerMode() {
|
|
host := cfg.GetDoltServerHost()
|
|
port := doltserver.DefaultConfig(beadsDir).Port
|
|
location = fmt.Sprintf("dolt server at %s:%d", host, port)
|
|
}
|
|
return alreadyInitialized(`
|
|
%s Found existing Dolt database: %s
|
|
|
|
This workspace is already initialized.
|
|
|
|
To use the existing database:
|
|
Just run bd commands normally (e.g., %s)
|
|
|
|
If the database is genuinely corrupt and unrecoverable:
|
|
bd export > issue-export.jsonl # Export issue records first
|
|
bd init --reinit-local --prefix %s # Then reinitialize
|
|
|
|
Aborting.`, ui.RenderWarn("⚠"), location, ui.RenderAccent("bd list"), prefix)
|
|
}
|
|
// Backend is Dolt but no dolt directory exists yet — this is a fresh
|
|
// clone. Any beads.db file is a legacy SQLite artifact, not the active
|
|
// database. Skip the SQLite checks below and allow init to proceed.
|
|
return nil
|
|
}
|
|
|
|
// Check for redirect file - if present, check the redirect target
|
|
redirectTarget := beads.FollowRedirect(beadsDir)
|
|
if redirectTarget != beadsDir {
|
|
targetDBPath := filepath.Join(redirectTarget, beads.CanonicalDatabaseName)
|
|
if _, err := os.Stat(targetDBPath); err == nil {
|
|
return alreadyInitialized(`
|
|
%s Cannot init: redirect target already has database
|
|
|
|
Local .beads redirects to: %s
|
|
That location already has: %s
|
|
|
|
The redirect target is already initialized. Running init here would overwrite it.
|
|
|
|
To use the existing database:
|
|
Just run bd commands normally (e.g., %s)
|
|
The redirect will route to the canonical database.
|
|
|
|
If the database is genuinely corrupt and unrecoverable:
|
|
bd export > issue-export.jsonl # Export issue records first
|
|
bd init --reinit-local --prefix %s # Then reinitialize
|
|
|
|
Aborting.`, ui.RenderWarn("⚠"), redirectTarget, targetDBPath, ui.RenderAccent("bd list"), prefix)
|
|
}
|
|
return nil // Redirect target has no database - safe to init
|
|
}
|
|
|
|
// Check for existing database file (no redirect case)
|
|
dbPath := filepath.Join(beadsDir, beads.CanonicalDatabaseName)
|
|
if _, err := os.Stat(dbPath); err == nil {
|
|
return alreadyInitialized(`
|
|
%s Found existing database: %s
|
|
|
|
This workspace is already initialized.
|
|
|
|
To use the existing database:
|
|
Just run bd commands normally (e.g., %s)
|
|
|
|
If the database is genuinely corrupt and unrecoverable:
|
|
bd export > issue-export.jsonl # Export issue records first
|
|
bd init --reinit-local --prefix %s # Then reinitialize
|
|
|
|
Aborting.`, ui.RenderWarn("⚠"), dbPath, ui.RenderAccent("bd list"), prefix)
|
|
}
|
|
|
|
return nil // No database found, safe to init
|
|
}
|
|
|
|
// countExistingIssues attempts to connect to the existing database and count
|
|
// issues. Returns 0 if the database is unreachable or empty. Used by --force
|
|
// safeguard to show users what they're about to destroy.
|
|
func countExistingIssues(_ string) (int, error) {
|
|
var beadsDir string
|
|
if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" {
|
|
beadsDir = utils.CanonicalizePath(envBeadsDir)
|
|
} else {
|
|
beadsDir = beads.FindBeadsDir()
|
|
if beadsDir == "" {
|
|
return 0, nil
|
|
}
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
store, err := newDoltStoreFromConfig(ctx, beadsDir)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer func() { _ = store.Close() }()
|
|
|
|
stats, err := store.GetStatistics(ctx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if stats == nil {
|
|
return 0, nil
|
|
}
|
|
return stats.TotalIssues, nil
|
|
}
|
|
|
|
// runInitReinitPreflight confirms the destructive local replacement while the
|
|
// caller holds init's complete exclusive gate set.
|
|
func runInitReinitPreflight(reinitLocal bool, prefix, destroyToken string) error {
|
|
if !reinitLocal {
|
|
return nil
|
|
}
|
|
count, err := countExistingIssues(prefix)
|
|
if err != nil || count == 0 {
|
|
return nil
|
|
}
|
|
|
|
fmt.Fprintf(os.Stderr, "\n%s Re-initializing will destroy the existing database.\n\n", ui.RenderWarn("WARNING:"))
|
|
fmt.Fprintf(os.Stderr, " Existing issues: %d\n\n", count)
|
|
fmt.Fprintf(os.Stderr, " This action CANNOT be undone. All issues, dependencies, and\n")
|
|
fmt.Fprintf(os.Stderr, " Dolt commit history will be permanently lost.\n\n")
|
|
fmt.Fprintf(os.Stderr, " Before proceeding, consider:\n")
|
|
fmt.Fprintf(os.Stderr, " bd export > issue-export.jsonl # Export issue records, not full DB state\n")
|
|
fmt.Fprintf(os.Stderr, " bd dolt status # Check if this is a server config issue\n\n")
|
|
if term.IsTerminal(int(os.Stdin.Fd())) {
|
|
fmt.Fprintf(os.Stderr, "Type 'destroy %d issues' to confirm: ", count)
|
|
scanner := bufio.NewScanner(os.Stdin)
|
|
scanner.Scan()
|
|
expected := fmt.Sprintf("destroy %d issues", count)
|
|
if strings.TrimSpace(scanner.Text()) != expected {
|
|
fmt.Fprintf(os.Stderr, "\nAborted. Database was NOT modified.\n")
|
|
return &exitError{Code: ExitLocalExistsRefused}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Non-interactive (piped input, AI agent, etc.)
|
|
//
|
|
// ADR invariant (engdocs/adr/0002-init-safety-invariants.md): runtime
|
|
// error text must not echo a complete destructive invocation. See
|
|
// 'bd help init-safety' for the token format. This closes the
|
|
// 58f5989bf failure class where an agent copy-pasted the suggestion.
|
|
expectedToken := FormatDestroyToken(prefix)
|
|
if destroyToken == expectedToken {
|
|
fmt.Fprintf(os.Stderr, "Destroy token accepted. Proceeding with re-initialization.\n")
|
|
return nil
|
|
}
|
|
fmt.Fprintf(os.Stderr, "Refusing to destroy %d issues in non-interactive mode.\n", count)
|
|
fmt.Fprintf(os.Stderr, " See 'bd help init-safety' for the required --destroy-token format.\n")
|
|
fmt.Fprintf(os.Stderr, " Or export issue records first: bd export > issue-export.jsonl\n")
|
|
return &exitError{Code: ExitDestroyTokenMissing}
|
|
}
|
|
|
|
// checkExistingBeadsData checks for existing database files
|
|
// and returns an error if found (safety guard for bd-emg)
|
|
//
|
|
// Note: This only blocks when a database already exists (workspace is initialized).
|
|
// Fresh clones without a database are allowed — init will create the database.
|
|
//
|
|
// For worktrees, checks the main repository root instead of current directory
|
|
// since worktrees should share the database with the main repository.
|
|
//
|
|
// For redirects, checks the redirect target and errors if it already has a database.
|
|
// This prevents accidentally overwriting an existing canonical database (GH#bd-0qel).
|
|
// normalizeIssuePrefix applies the prefix normalization rules shared by the
|
|
// init path and the --init-if-missing mismatch guard: strip leading dots, drop
|
|
// the trailing hyphen, convert dots to underscores, and prepend "bd_" when the
|
|
// result would not start with a SQL-identifier-safe character. Keeping this in
|
|
// one place ensures the mismatch check derives exactly the same name init does.
|
|
func normalizeIssuePrefix(prefix string) string {
|
|
prefix = strings.TrimLeft(prefix, ".")
|
|
prefix = strings.TrimRight(prefix, "-")
|
|
prefix = strings.ReplaceAll(prefix, ".", "_")
|
|
if len(prefix) > 0 && !((prefix[0] >= 'a' && prefix[0] <= 'z') || (prefix[0] >= 'A' && prefix[0] <= 'Z') || prefix[0] == '_') {
|
|
prefix = "bd_" + prefix
|
|
}
|
|
return prefix
|
|
}
|
|
|
|
// dbNameFromPrefix derives the Dolt database name from a normalized issue
|
|
// prefix (hyphens become underscores), matching how init records DoltDatabase.
|
|
func dbNameFromPrefix(prefix string) string {
|
|
return strings.ReplaceAll(prefix, "-", "_")
|
|
}
|
|
|
|
// initIfMissingPrefixMismatch reports whether an explicit --prefix request
|
|
// conflicts with the existing workspace, in which case --init-if-missing must
|
|
// abort rather than silently skip (otherwise the requested prefix is ignored).
|
|
// existingDBName is the existing workspace's recorded Dolt database name;
|
|
// requestedPrefix is the raw, un-normalized --prefix value. Returns false when
|
|
// the existing name is unknown so an undeterminable state falls through to the
|
|
// benign skip.
|
|
func initIfMissingPrefixMismatch(existingDBName, requestedPrefix string) bool {
|
|
if existingDBName == "" {
|
|
return false
|
|
}
|
|
requested := dbNameFromPrefix(normalizeIssuePrefix(requestedPrefix))
|
|
return requested != "" && !strings.EqualFold(existingDBName, requested)
|
|
}
|
|
|
|
// resolveInitIfMissingAlreadyInitialized decides what --init-if-missing does
|
|
// once the workspace is known to be initialized already: nil for the benign
|
|
// skip (message printed here), or the abort for a request that would be
|
|
// silently ignored by skipping.
|
|
//
|
|
// Guard against masking a genuine mismatch: an explicit --prefix or --database
|
|
// that does not match the existing workspace must abort, since silently
|
|
// skipping would ignore the request and reuse a different database. --database
|
|
// is the authoritative selector, so it is checked even when --prefix is also
|
|
// set.
|
|
//
|
|
// Both init routes share this: the embedded/server route reaches it from its
|
|
// own checkExistingBeadsData, the proxied-server route from the identical check
|
|
// inside runInitProxiedServer. Before that wiring existed, --init-if-missing was
|
|
// simply inert on the proxied route — an already-initialized workspace exited 1
|
|
// with the "Aborting." banner, and the two mismatch guards this delegates to had
|
|
// never once run.
|
|
func resolveInitIfMissingAlreadyInitialized(cmd *cobra.Command, database, prefix string, quiet bool) error {
|
|
existing := existingWorkspaceDBName()
|
|
if cmd.Flags().Changed("database") {
|
|
if initIfMissingDatabaseMismatch(existing, database) {
|
|
return fmt.Errorf("workspace already initialized as database %q, but --database %q was requested.\nRemove --database (or pass a matching value) to reuse the existing workspace", existing, database)
|
|
}
|
|
} else if cmd.Flags().Changed("prefix") {
|
|
if initIfMissingPrefixMismatch(existing, prefix) {
|
|
return fmt.Errorf("workspace already initialized as database %q, but --prefix %q was requested.\nRemove --prefix (or pass a matching value) to reuse the existing workspace", existing, prefix)
|
|
}
|
|
}
|
|
if !quiet {
|
|
fmt.Fprintln(os.Stderr, "Skipping init: workspace already initialized.")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// initIfMissingDatabaseMismatch reports whether an explicit --database request
|
|
// conflicts with the existing workspace. --database is the authoritative database
|
|
// selector (it overrides prefix-based naming later in init), so an explicit
|
|
// mismatch must abort --init-if-missing rather than silently reuse a different
|
|
// database. existingDBName is the existing workspace's recorded Dolt database
|
|
// name; requestedDatabase is the raw --database value. Returns false when either
|
|
// is unknown so an undeterminable state falls through to the benign skip.
|
|
func initIfMissingDatabaseMismatch(existingDBName, requestedDatabase string) bool {
|
|
if existingDBName == "" || requestedDatabase == "" {
|
|
return false
|
|
}
|
|
return !strings.EqualFold(existingDBName, requestedDatabase)
|
|
}
|
|
|
|
// resolveInitBeadsDir resolves the .beads directory that init would target,
|
|
// using the same precedence as checkExistingBeadsData (BEADS_DIR > worktree
|
|
// fallback > CWD). Returns "" when it cannot be determined.
|
|
func resolveInitBeadsDir() string {
|
|
if envBeadsDir := os.Getenv("BEADS_DIR"); envBeadsDir != "" {
|
|
return utils.CanonicalizePath(envBeadsDir)
|
|
}
|
|
cwd, err := os.Getwd()
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
if isGitRepo() && git.IsWorktree() {
|
|
return beads.GetWorktreeFallbackBeadsDir()
|
|
}
|
|
return filepath.Join(cwd, ".beads")
|
|
}
|
|
|
|
// existingWorkspaceDBName returns the Dolt database name explicitly recorded
|
|
// for the already-initialized workspace at the init target, or "" if it cannot
|
|
// be determined. It reads the raw DoltDatabase field rather than
|
|
// GetDoltDatabase() on purpose: the getter falls back to a default name (and an
|
|
// env override), which would manufacture a phantom value and trigger false
|
|
// mismatches. An unset value safely falls through to the benign skip.
|
|
func existingWorkspaceDBName() string {
|
|
beadsDir := resolveInitBeadsDir()
|
|
if beadsDir == "" {
|
|
return ""
|
|
}
|
|
cfg, err := configfile.LoadForDiscovery(beadsDir)
|
|
if err != nil || cfg == nil {
|
|
return ""
|
|
}
|
|
return cfg.DoltDatabase
|
|
}
|
|
|
|
// existingWorkspaceDoltMode returns the connection mode recorded in the
|
|
// already-initialized workspace's metadata.json, or "" if there is none.
|
|
//
|
|
// Like existingWorkspaceDBName it reads the raw field rather than a getter: a
|
|
// getter that defaults to embedded would make "no recorded mode" and
|
|
// "deliberately embedded" indistinguishable, and this value is used to decide
|
|
// whether a re-init is about to change modes.
|
|
func existingWorkspaceDoltMode() string {
|
|
beadsDir := resolveInitBeadsDir()
|
|
if beadsDir == "" {
|
|
return ""
|
|
}
|
|
cfg, err := configfile.LoadForDiscovery(beadsDir)
|
|
if err != nil || cfg == nil {
|
|
return ""
|
|
}
|
|
// Matched case-insensitively by callers, mirroring configfile's own
|
|
// IsServerMode/IsProxiedServerMode comparisons.
|
|
return strings.ToLower(strings.TrimSpace(cfg.DoltMode))
|
|
}
|
|
|
|
// inheritWorkspaceDoltMode is the decision half of #3885's fix: what a bare
|
|
// re-init adopts from the workspace it is re-initializing. It returns
|
|
// inheritServer=true when the workspace records server mode.
|
|
//
|
|
// Proxied-server is deliberately an error, not an inheritance: the dedicated
|
|
// proxied init path (runInitProxiedServer) dispatches on the explicit flag
|
|
// BEFORE the inheritance point in RunE, so inheriting by mutating only the
|
|
// process-mode globals would build the database embedded while metadata.json
|
|
// kept claiming proxied-server — the exact silent mismatch inheritance exists
|
|
// to prevent. The mode is experimental and dark-launched; a re-init of such a
|
|
// workspace must name it explicitly so it routes through the real init path.
|
|
func inheritWorkspaceDoltMode() (bool, error) {
|
|
switch existingWorkspaceDoltMode() {
|
|
case configfile.DoltModeServer:
|
|
return true, nil
|
|
case configfile.DoltModeProxiedServer:
|
|
return false, fmt.Errorf("this workspace is recorded as proxied-server in .beads/metadata.json; " +
|
|
"re-run with --proxied-server to keep it, or name another mode explicitly to change it")
|
|
default:
|
|
return false, nil
|
|
}
|
|
}
|
|
|
|
// initModeExplicitlyRequested reports whether this invocation names a
|
|
// connection mode of its own, as opposed to falling back to the build default.
|
|
//
|
|
// Only an explicit request may change an existing workspace's mode. Without
|
|
// this distinction a bare `bd init --from-jsonl --reinit-local` on a
|
|
// server-mode project runs embedded and rewrites dolt_mode to embedded, which
|
|
// is #3885: the project comes back half-configured and the user is told
|
|
// nothing.
|
|
func initModeExplicitlyRequested(cmd *cobra.Command) bool {
|
|
for _, name := range []string{"server", "shared-server", "proxied-server"} {
|
|
if f := cmd.Flags().Lookup(name); f != nil && f.Changed {
|
|
return true
|
|
}
|
|
}
|
|
for _, env := range []string{
|
|
"BEADS_DOLT_SERVER_MODE",
|
|
"BEADS_DOLT_SHARED_SERVER",
|
|
"BEADS_DOLT_PROXIED_SERVER",
|
|
} {
|
|
if os.Getenv(env) != "" {
|
|
return true
|
|
}
|
|
}
|
|
// A global config.yaml `dolt.mode` is a deliberate statement about this
|
|
// machine, so it counts as explicit too — the seeding block above already
|
|
// treats it like --server.
|
|
return config.GetYamlConfig("dolt.mode") != ""
|
|
}
|
|
|
|
// guardMissingServerDatabaseAt is the be-5up5 refusal, narrowed to the single
|
|
// question --reinit-local/--force must NOT be able to answer for you: is this
|
|
// an already-initialized server-mode project whose configured database is
|
|
// missing or unconfirmable?
|
|
//
|
|
// It exists because those flags bypass checkExistingBeadsData entirely (see the
|
|
// !reinitLocal gate in the init command), and the reinit path's own typed
|
|
// confirmation keys on countExistingIssues — which returns 0 or an error in
|
|
// exactly the case this guard is about, so no prompt fires either. That left
|
|
// `bd init --force` against a lost database creating a fresh empty one with no
|
|
// prompt and no destroy token: the precise reflex of the 2026-08-11 fleet-wide
|
|
// data loss, reached by the flag a panicking operator is most likely to try.
|
|
//
|
|
// --reinit-local/--force authorize destroying a database that EXISTS. They do
|
|
// not authorize inventing an empty one where the configured database has gone
|
|
// missing. Only the explicit, per-invocation --recreate-missing does that,
|
|
// which is what keeps that flag's "never implied by --force" help text true.
|
|
//
|
|
// Deliberately narrow: it answers only the missing-database question and
|
|
// returns nil for every other state, so it never resurrects the
|
|
// "already initialized" refusal that --reinit-local is legitimately meant to
|
|
// bypass.
|
|
func guardMissingServerDatabaseAt(beadsDir string, prefix string) error {
|
|
if initAllowRecreateMissing {
|
|
return nil
|
|
}
|
|
if beadsDir == "" {
|
|
return nil
|
|
}
|
|
if _, err := os.Stat(beadsDir); os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
|
|
cfg, cfgErr := configfile.LoadForDiscovery(beadsDir)
|
|
if cfgErr != nil || cfg == nil {
|
|
// Unreadable or absent metadata is the caller's problem, not this
|
|
// guard's: without it we cannot prove the workspace was ever
|
|
// initialized, and this guard only ever fires on proof that it was.
|
|
return nil
|
|
}
|
|
if cfg.GetBackend() != configfile.BackendDolt || !cfg.IsDoltServerMode() {
|
|
return nil
|
|
}
|
|
host := cfg.GetDoltServerHost()
|
|
port := doltserver.DefaultConfig(beadsDir).Port
|
|
dbName := cfg.GetDoltDatabase()
|
|
doltPath := doltserver.ResolveDoltDir(beadsDir)
|
|
|
|
// TIER 1 (ADR-0004, engdocs/adr/0004-missing-database-guard-signal.md).
|
|
// Local data means data belonging to THIS project, which is what
|
|
// --reinit-local exists to override. Test for this project's own database
|
|
// directory, not the data directory that merely holds it: a Dolt data dir
|
|
// contains one subdirectory per database, each with its own .dolt.
|
|
//
|
|
// Statting the data dir itself made this guard a no-op in shared-server
|
|
// mode, where ResolveDoltDir returns the machine-global
|
|
// ~/.beads/shared-server/dolt and SharedDoltDir() MkdirAlls it — so the
|
|
// stat always succeeded and checkDatabaseOnServer below was never reached.
|
|
// Shared-server is the topology of the 2026-08-11 data loss, so that was
|
|
// the primary case going unguarded. Pinned by
|
|
// TestInitGuard_SharedServerMode_MissingServerDB_Refuses.
|
|
//
|
|
// This probe runs BEFORE the project_id check below, and unconditionally.
|
|
// It used to run after an early `return nil` on empty project_id, which
|
|
// made this guard — the safety net for --reinit-local/--force — weaker
|
|
// than the plain-`bd init` guard it backstops: a pre-GH#2372 workspace
|
|
// (no project_id) whose local database was lost was protected under
|
|
// `bd init` and waved straight through under --force.
|
|
if info, err := os.Stat(filepath.Join(doltPath, dbName, ".dolt")); err == nil && info.IsDir() {
|
|
return nil
|
|
}
|
|
|
|
// TIER 2 (ADR-0004). No local database for this project. project_id is
|
|
// written by a real prior `bd init`, so a non-empty value is what
|
|
// separates recovery from a genuine fresh clone. It is imperfect —
|
|
// .beads/metadata.json is git-tracked by default, so a clone inherits one
|
|
// it never earned — and that is accepted deliberately: absence of local
|
|
// state cannot distinguish "never initialized here" from "initialized
|
|
// here, storage since lost", and the second is the 2026-08-11 shape.
|
|
// --recreate-missing is the resolution path for both, and it returned nil
|
|
// at the top of this function.
|
|
if cfg.ProjectID == "" {
|
|
// Same coarse-directory permit condition checkExistingBeadsDataAt
|
|
// applies, so the two guards agree: allow only when NOTHING local
|
|
// exists. A data dir with no database in it still says this
|
|
// workspace touched local Dolt storage.
|
|
//
|
|
// Accepted asymmetry (ADR-0004): in owned mode doltPath is
|
|
// per-project and this is a meaningful second signal. In
|
|
// same-machine shared-server mode it is the machine-global
|
|
// ~/.beads/shared-server/dolt, true once ANY project has used the
|
|
// shared server, so this cell is more conservative there. That fails
|
|
// toward refuse, is resolved the same documented way, and affects a
|
|
// population that only shrinks — every successful init mints a
|
|
// project_id. Do not re-litigate it without reading the ADR.
|
|
if info, err := os.Stat(doltPath); err != nil || !info.IsDir() {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
result := checkDatabaseOnServer(host, port, cfg.GetDoltServerUser(), cfg.GetDoltServerPassword(), dbName, cfg.GetDoltServerTLS())
|
|
if result.Reachable && result.Exists && result.Err == nil {
|
|
// The database is there. Whatever happens next is the ordinary
|
|
// reinit path's business, not this guard's.
|
|
return nil
|
|
}
|
|
// Unlike the plain-init guard, this one is reachable with an empty
|
|
// project_id — the pre-GH#2372 cell permitted just above only when nothing
|
|
// local exists. Tell the message which evidence it actually has.
|
|
return initGuardMissingServerDBMessage(dbName, host, port, prefix, cfg.ProjectID != "")
|
|
}
|
|
|
|
// guardMissingServerDatabase resolves the init target the same way
|
|
// checkExistingBeadsData does, then applies guardMissingServerDatabaseAt.
|
|
func guardMissingServerDatabase(prefix string) error {
|
|
beadsDir := resolveInitBeadsDir()
|
|
if beadsDir == "" {
|
|
return nil
|
|
}
|
|
return guardMissingServerDatabaseAt(beadsDir, prefix)
|
|
}
|
|
|
|
func checkExistingBeadsData(prefix string) error {
|
|
beadsDir := resolveInitBeadsDir()
|
|
if beadsDir == "" {
|
|
return nil // Can't determine target, allow init to proceed
|
|
}
|
|
return checkExistingBeadsDataAt(beadsDir, prefix)
|
|
}
|
|
|
|
// isNonInteractiveInit returns true if init should run without interactive prompts.
|
|
// Precedence: explicit flag > BD_NON_INTERACTIVE env > CI env > terminal detection.
|
|
// Setting BD_NON_INTERACTIVE=0 or BD_NON_INTERACTIVE=false explicitly forces
|
|
// interactive mode, overriding CI detection and terminal checks.
|
|
func isNonInteractiveInit(flagValue bool) bool {
|
|
if flagValue {
|
|
return true
|
|
}
|
|
if v := os.Getenv("BD_NON_INTERACTIVE"); v != "" {
|
|
if v == "1" || v == "true" {
|
|
return true
|
|
}
|
|
// Explicit BD_NON_INTERACTIVE=0/false forces interactive mode,
|
|
// overriding CI and terminal detection.
|
|
return false
|
|
}
|
|
if v := os.Getenv("CI"); v == "true" || v == "1" {
|
|
return true
|
|
}
|
|
return !term.IsTerminal(int(os.Stdin.Fd()))
|
|
}
|
|
|
|
// shouldPromptForRole returns true if we should prompt the user for their role.
|
|
// Skips prompt in non-interactive contexts (CI, scripts, piped input).
|
|
func shouldPromptForRole() bool {
|
|
return term.IsTerminal(int(os.Stdin.Fd()))
|
|
}
|
|
|
|
// isInitRoleGitRepo uses the same CWD and routing policy as getBeadsRole/setBeadsRole,
|
|
// including their suppression scrub: rev-parse is config-sensitive through
|
|
// safe.directory, so retaining suppression here could answer false for a
|
|
// repository that is only reachable via a global safe.directory entry and skip
|
|
// the role write the pair would have completed.
|
|
func isInitRoleGitRepo(ctx context.Context) bool {
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir")
|
|
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
|
|
return cmd.Run() == nil
|
|
}
|
|
|
|
// getBeadsRole reads the beads.role git config value.
|
|
// Returns the role and true if configured, or empty string and false if not set.
|
|
//
|
|
// Both halves of the pair run on the same authority boundary as every role
|
|
// reader so init cannot report a role it wrote into a different repository:
|
|
// an inherited GIT_DIR would redirect setBeadsRole's write, and inherited
|
|
// config suppression would blind the read that decides whether to write at
|
|
// all.
|
|
//
|
|
// Selection is then the working directory or a containing ancestor. The scrub
|
|
// drops GIT_CEILING_DIRECTORIES along with the redirects, so it removes a
|
|
// bound rather than installing one: measured from a non-repository directory
|
|
// nested under a repository, `git config beads.role <value>` fails "not in a
|
|
// git directory" while a ceiling below that repository is inherited, and
|
|
// writes the repository's local config once the ceiling is scrubbed. cmd.Dir
|
|
// is still not threaded through the pair, because no production path chdirs
|
|
// away from the invocation directory before these run. Two residuals remain:
|
|
// upward discovery from an unintended cwd, and `bd -C <dir>`, which redirects
|
|
// project selection by setting BEADS_DIR without chdir-ing
|
|
// (applyChangeDirSelection), so init can act on another project's workspace
|
|
// while the pair still reads and writes beads.role in the invocation
|
|
// repository; -C requires an existing beads project at the target, so that
|
|
// pairing arises on re-init rather than first init, and the GH#2950 safety net
|
|
// records the same BEADS_DIR skew. Threading init's resolved project root
|
|
// through the pair would close that one, but it is a behavior change rather
|
|
// than a boundary fix. clearWorktreeGitRoutingEnv discloses the same widening
|
|
// for the bd worktree commands.
|
|
func getBeadsRole() (string, bool) {
|
|
cmd := exec.Command("git", "config", "--get", "beads.role")
|
|
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
role := strings.TrimSpace(string(output))
|
|
if role == "" {
|
|
return "", false
|
|
}
|
|
return role, true
|
|
}
|
|
|
|
// setBeadsRole writes the beads.role git config value. See getBeadsRole for
|
|
// why the pair shares the role-authority environment boundary.
|
|
func setBeadsRole(role string) error {
|
|
cmd := exec.Command("git", "config", "beads.role", role)
|
|
cmd.Env = gitenv.ScrubRoutingAndSuppression(os.Environ())
|
|
return cmd.Run()
|
|
}
|
|
|
|
// promptContributorMode prompts the user to determine if they are a contributor.
|
|
// Returns true if the user indicates they are a contributor, false otherwise.
|
|
//
|
|
// Behavior:
|
|
// - If beads.role is already set: shows current role, offers to change
|
|
// - If not set: prompts "Contributing to someone else's repo? [y/N]"
|
|
// - Sets git config beads.role based on answer
|
|
func promptContributorMode() (isContributor bool, err error) {
|
|
ctx := getRootContext()
|
|
reader := bufio.NewReader(os.Stdin)
|
|
|
|
// Check if role is already configured
|
|
existingRole, hasRole := getBeadsRole()
|
|
if hasRole {
|
|
fmt.Printf("\n%s Already configured as: %s\n", ui.RenderAccent("▶"), ui.RenderBold(existingRole))
|
|
fmt.Print("Change role? [y/N]: ")
|
|
|
|
response, err := readLineWithContext(ctx, reader, os.Stdin)
|
|
if err != nil {
|
|
return false, fmt.Errorf("failed to read input: %w", err)
|
|
}
|
|
response = strings.TrimSpace(strings.ToLower(response))
|
|
|
|
if response != "y" && response != "yes" {
|
|
// Keep existing role
|
|
return existingRole == "contributor", nil
|
|
}
|
|
// Fall through to re-prompt
|
|
fmt.Println()
|
|
}
|
|
|
|
// Prompt for role
|
|
fmt.Print("Contributing to someone else's repo? [y/N]: ")
|
|
|
|
response, err := readLineWithContext(ctx, reader, os.Stdin)
|
|
if err != nil {
|
|
return false, fmt.Errorf("failed to read input: %w", err)
|
|
}
|
|
response = strings.TrimSpace(strings.ToLower(response))
|
|
|
|
isContributor = response == "y" || response == "yes"
|
|
|
|
// Set the role in git config
|
|
role := "maintainer"
|
|
if isContributor {
|
|
role = "contributor"
|
|
}
|
|
|
|
if err := setBeadsRole(role); err != nil {
|
|
return isContributor, fmt.Errorf("failed to set beads.role config: %w", err)
|
|
}
|
|
|
|
return isContributor, nil
|
|
}
|
|
|
|
// promptAutoExport asks the user whether to enable optional auto-export.
|
|
// Returns true to enable it, false to leave it disabled.
|
|
func promptAutoExport() (bool, error) {
|
|
fmt.Printf("\n%s Auto-export can keep .beads/issues.jsonl up to date after write commands.\n", ui.RenderAccent("▶"))
|
|
fmt.Println(" This optional JSONL export is useful for viewers (bv), interchange, and issue-level migration.")
|
|
fmt.Println(" Dolt remotes/backups handle cross-machine sync and backup.")
|
|
fmt.Print("\nEnable auto-export? [y/N]: ")
|
|
|
|
reader := bufio.NewReader(os.Stdin)
|
|
response, err := readLineWithContext(getRootContext(), reader, os.Stdin)
|
|
if err != nil {
|
|
if isCanceled(err) {
|
|
return true, err
|
|
}
|
|
response = ""
|
|
}
|
|
response = strings.TrimSpace(strings.ToLower(response))
|
|
|
|
// Default to no. Users and integrations can enable it explicitly.
|
|
return response == "y" || response == "yes", nil
|
|
}
|
|
|
|
func shouldWireInitRemote(syncURL string, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin bool) bool {
|
|
// A git origin is a valid Dolt remote even before refs/dolt/data exists:
|
|
// the first `bd dolt push` creates the Dolt ref on that git remote. We
|
|
// still keep explicit empty --remote as an opt-out because that leaves
|
|
// syncURL empty and syncURLFromGitOrigin false.
|
|
return syncURL != "" && (syncFromRemote || syncURLFromConfig || syncURLFromGitOrigin)
|
|
}
|
|
|
|
func shouldConfigureInitDoltRemote(syncURL string, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin, localOnly bool) bool {
|
|
return !localOnly && shouldWireInitRemote(syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin)
|
|
}
|
|
|
|
// shouldWriteInitDoltRemote reports whether init should actually configure (write)
|
|
// the Dolt "origin" remote on the store. It layers gateway suppression on top of
|
|
// shouldConfigureInitDoltRemote: a gateway is a passive client of a server-owned
|
|
// database, so AddRemote's CALL DOLT_REMOTE('add', ...) would mutate shared remote
|
|
// state on a writable credential (or merely warn per-init on a read-only one) —
|
|
// exactly the server-owned write the other gateway gates (shouldInitSharedGlobalDB,
|
|
// shouldWriteInitStateToDB, shouldWriteProjectIDLocally) already suppress. The
|
|
// rendered agent-instruction HasRemote flag intentionally keeps using the raw
|
|
// shouldConfigureInitDoltRemote decision, since the git remote still exists for
|
|
// documentation even when gateway sync does not use dolt push.
|
|
func shouldWriteInitDoltRemote(gateway bool, syncURL string, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin, localOnly bool) bool {
|
|
return !gateway && shouldConfigureInitDoltRemote(syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin, localOnly)
|
|
}
|
|
|
|
// resolveRemoteHasDoltDataProbe fails closed: a probe error is UNKNOWN, and
|
|
// ADR-0002 treats unknown as has-data (refuse) rather than no-data. Returns
|
|
// the resolved bool for CheckRemoteSafety plus a note naming the probe
|
|
// failure (empty on success) so the caller can tell the user why.
|
|
func resolveRemoteHasDoltDataProbe(syncURL string, hasData bool, err error) (bool, string) {
|
|
if err != nil {
|
|
return true, fmt.Sprintf("could not verify refs/dolt/data on %s (%v); treating remote as having Dolt history", syncURL, err)
|
|
}
|
|
return hasData, ""
|
|
}
|
|
|
|
// handleRemoteSafetyDecision applies a CheckRemoteSafety decision at an init
|
|
// remote-divergence checkpoint. It returns (bootstrap, err): bootstrap is true
|
|
// when the caller should clone/bootstrap from the remote, and err is a non-nil
|
|
// *exitError when init must abort with a specific exit code.
|
|
//
|
|
// It must NOT call os.Exit: this runs inside the init RunE body, whose deferred
|
|
// metrics CloseEventAndAdd only fires on a normal return. Every refusal path
|
|
// returns an *exitError so the caller can propagate it up through RunE and keep
|
|
// the usage-metrics close intact (see errors.go).
|
|
func handleRemoteSafetyDecision(decision RemoteSafetyDecision, prefix, syncURL, destroyToken string, remoteHasDoltData func() (bool, error), observedRemoteHasDoltData bool, confirmed *bool) (bool, error) {
|
|
switch decision.Action {
|
|
case ActionRefuseDivergence, ActionRequireDestroyToken:
|
|
fmt.Fprintf(os.Stderr, "\n%s\n\n", decision.UserMessage)
|
|
return false, &exitError{Code: decision.ExitCode}
|
|
case ActionBootstrap:
|
|
return true, nil
|
|
case ActionProceedWithDivergence:
|
|
if decision.Reason == "authorized-divergence" && term.IsTerminal(int(os.Stdin.Fd())) && destroyToken == "" && !*confirmed {
|
|
expected := FormatDestroyToken(prefix)
|
|
fmt.Fprintf(os.Stderr, "\n%s You are about to discard the remote's Dolt history.\n\n", ui.RenderWarn("WARNING:"))
|
|
fmt.Fprintf(os.Stderr, " Remote: %s\n", syncURL)
|
|
fmt.Fprintf(os.Stderr, " Type %q to confirm: ", expected)
|
|
scanner := bufio.NewScanner(os.Stdin)
|
|
scanner.Scan()
|
|
if strings.TrimSpace(scanner.Text()) != expected {
|
|
fmt.Fprintf(os.Stderr, "\nAborted. See 'bd help init-safety' for details.\n")
|
|
return false, &exitError{Code: ExitDestroyTokenMissing}
|
|
}
|
|
*confirmed = true
|
|
}
|
|
if remoteHasDoltData != nil {
|
|
// A probe error here is UNKNOWN, not "changed" — a transient
|
|
// network blip on the confirmation probe must not abort a
|
|
// destroy-token flow the user already confirmed.
|
|
if current, err := remoteHasDoltData(); err == nil && current != observedRemoteHasDoltData {
|
|
fmt.Fprintf(os.Stderr, "\nAborted: remote state changed during confirmation. Re-run to re-verify intent.\n")
|
|
return false, &exitError{Code: ExitRemoteDivergenceRefused}
|
|
}
|
|
}
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
func configureInitDoltRemote(ctx context.Context, store storage.DoltStorage, syncURL string, quiet bool) {
|
|
hasRemote, _ := store.HasRemote(ctx, "origin")
|
|
if hasRemote {
|
|
return
|
|
}
|
|
if err := store.AddRemote(ctx, "origin", syncURL); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to add remote 'origin': %v\n", err)
|
|
return
|
|
}
|
|
if !quiet {
|
|
fmt.Printf(" %s Configured Dolt remote: origin → %s\n", ui.RenderPass("✓"), syncURL)
|
|
}
|
|
}
|
|
|
|
func printInitNoDoltRemoteWarning(withExportNote bool) {
|
|
fmt.Fprintf(os.Stderr, "\n%s No Dolt remote configured\n", ui.RenderWarn("⚠"))
|
|
if withExportNote {
|
|
fmt.Fprintln(os.Stderr, " Issues are stored in local Dolt. .beads/issues.jsonl is an export,")
|
|
fmt.Fprintln(os.Stderr, " not cross-machine sync or the source of truth.")
|
|
}
|
|
if originURL, err := gitOriginGetURL(); err == nil && originURL != "" {
|
|
fmt.Fprintln(os.Stderr, " To use your git origin for durable sync, run:")
|
|
fmt.Fprintf(os.Stderr, " %s\n", ui.RenderAccent("bd dolt remote add origin "+normalizeRemoteURL(originURL)))
|
|
fmt.Fprintf(os.Stderr, " %s\n\n", ui.RenderAccent("bd dolt push"))
|
|
return
|
|
}
|
|
fmt.Fprintln(os.Stderr, " To enable durable sync, add a git origin and then run:")
|
|
fmt.Fprintf(os.Stderr, " %s\n", ui.RenderAccent("bd dolt push"))
|
|
}
|
|
|
|
type initSyncRemoteSource int
|
|
|
|
const (
|
|
initSyncRemoteNone initSyncRemoteSource = iota
|
|
initSyncRemoteExplicit
|
|
initSyncRemoteConfigured
|
|
)
|
|
|
|
func resolveInitConfiguredSyncRemote(initRemote string, initRemoteChanged bool, resolveConfiguredRemote func() string) (string, initSyncRemoteSource) {
|
|
if initRemoteChanged {
|
|
return initRemote, initSyncRemoteExplicit
|
|
}
|
|
if syncURL := resolveConfiguredRemote(); syncURL != "" {
|
|
return syncURL, initSyncRemoteConfigured
|
|
}
|
|
return "", initSyncRemoteNone
|
|
}
|
|
|
|
func initRemoteCloneMode(initServerMode, externalServer bool) remoteCloneMode {
|
|
if !initServerMode {
|
|
return remoteCloneEmbedded
|
|
}
|
|
if externalServer {
|
|
return remoteCloneExternalServer
|
|
}
|
|
return remoteCloneCLI
|
|
}
|
|
|
|
// serverConnEnvMutation is one pending change to the process environment.
|
|
// unset records the "remove this variable" case, which is distinct from
|
|
// setting it to the empty string for every downstream resolver.
|
|
type serverConnEnvMutation struct {
|
|
key string
|
|
value string
|
|
unset bool
|
|
}
|
|
|
|
// resolveExplicitServerConnEnv turns the explicit --server-* flags into the
|
|
// set of environment changes promoteExplicitServerConnFlags will apply. It
|
|
// validates every flag before returning, so a later invalid flag cannot leave
|
|
// an earlier valid one already applied to the process environment.
|
|
//
|
|
// Because a socket outranks host/port everywhere downstream, selecting TCP
|
|
// explicitly (--server-host or --server-port) also clears an ambient
|
|
// BEADS_DOLT_SERVER_SOCKET unless --server-socket was itself given. An
|
|
// explicitly empty --server-socket clears the ambient socket too: empty is
|
|
// the documented "use TCP" value (see configfile.GetDoltServerSocket).
|
|
// Changed-but-empty host/user and out-of-range port values fail explicitly
|
|
// rather than being silently ignored.
|
|
func resolveExplicitServerConnEnv(cmd *cobra.Command) ([]serverConnEnvMutation, error) {
|
|
var muts []serverConnEnvMutation
|
|
if cmd.Flags().Changed("server-host") {
|
|
v, _ := cmd.Flags().GetString("server-host")
|
|
if v == "" {
|
|
return nil, fmt.Errorf("--server-host cannot be empty; omit the flag to use BEADS_DOLT_SERVER_HOST or the default (%s)", configfile.DefaultDoltServerHost)
|
|
}
|
|
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_HOST", value: v})
|
|
}
|
|
if cmd.Flags().Changed("server-port") {
|
|
v, _ := cmd.Flags().GetInt("server-port")
|
|
if v < 1 || v > 65535 {
|
|
return nil, fmt.Errorf("--server-port must be between 1 and 65535, got %d; omit the flag to use BEADS_DOLT_SERVER_PORT or the default (%d)", v, configfile.DefaultDoltServerPort)
|
|
}
|
|
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_PORT", value: strconv.Itoa(v)})
|
|
}
|
|
if cmd.Flags().Changed("server-user") {
|
|
v, _ := cmd.Flags().GetString("server-user")
|
|
if v == "" {
|
|
return nil, fmt.Errorf("--server-user cannot be empty; omit the flag to use BEADS_DOLT_SERVER_USER or the default (%s)", configfile.DefaultDoltServerUser)
|
|
}
|
|
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_USER", value: v})
|
|
}
|
|
switch {
|
|
case cmd.Flags().Changed("server-socket"):
|
|
v, _ := cmd.Flags().GetString("server-socket")
|
|
if v == "" {
|
|
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_SOCKET", unset: true})
|
|
} else {
|
|
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_SOCKET", value: v})
|
|
}
|
|
case cmd.Flags().Changed("server-host") || cmd.Flags().Changed("server-port"):
|
|
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_SOCKET", unset: true})
|
|
}
|
|
if cmd.Flags().Changed("server-tls") {
|
|
v, _ := cmd.Flags().GetBool("server-tls")
|
|
tls := "0"
|
|
if v {
|
|
tls = "1"
|
|
}
|
|
muts = append(muts, serverConnEnvMutation{key: "BEADS_DOLT_SERVER_TLS", value: tls})
|
|
}
|
|
return muts, nil
|
|
}
|
|
|
|
// promoteExplicitServerConnFlags makes an explicit --server-host/--server-port/
|
|
// --server-user/--server-socket/--server-tls flag outrank the corresponding
|
|
// BEADS_DOLT_SERVER_* environment variable. Every downstream resolver
|
|
// (configfile getters, doltserver DefaultConfig) consults the environment
|
|
// first, so without promotion a stale shell-profile value silently redirects
|
|
// init to a different server than the one named on the command line.
|
|
//
|
|
// Callers must invoke this only once server mode is resolved: in embedded
|
|
// mode the connection flags are recorded in metadata.json but must not reach
|
|
// the environment, or init trips its own "embedded mode has no host/port"
|
|
// guard.
|
|
//
|
|
// The returned restore function puts the environment back exactly as it was,
|
|
// including variables that were absent. One CLI process runs one init, so the
|
|
// mutation is invisible there, but any in-process caller (the test binary, an
|
|
// embedding host) would otherwise inherit this invocation's overrides.
|
|
// Callers should defer it on every return path.
|
|
//
|
|
// Nothing here is persisted to metadata.json (TLS in particular stays
|
|
// env/credentials-file configured, per bd dolt help).
|
|
func promoteExplicitServerConnFlags(cmd *cobra.Command) (func(), error) {
|
|
noop := func() {}
|
|
muts, err := resolveExplicitServerConnEnv(cmd)
|
|
if err != nil {
|
|
return noop, err
|
|
}
|
|
if len(muts) == 0 {
|
|
return noop, nil
|
|
}
|
|
|
|
type savedEnv struct {
|
|
value string
|
|
present bool
|
|
}
|
|
saved := make(map[string]savedEnv, len(muts))
|
|
restore := func() {
|
|
for key, prev := range saved {
|
|
// Nothing actionable remains if the restore itself fails: the
|
|
// process is either exiting or already past the init it scoped.
|
|
if prev.present {
|
|
_ = os.Setenv(key, prev.value)
|
|
continue
|
|
}
|
|
_ = os.Unsetenv(key)
|
|
}
|
|
}
|
|
|
|
for _, mut := range muts {
|
|
if _, seen := saved[mut.key]; !seen {
|
|
value, present := os.LookupEnv(mut.key)
|
|
saved[mut.key] = savedEnv{value: value, present: present}
|
|
}
|
|
var applyErr error
|
|
if mut.unset {
|
|
applyErr = os.Unsetenv(mut.key)
|
|
} else {
|
|
applyErr = os.Setenv(mut.key, mut.value)
|
|
}
|
|
if applyErr != nil {
|
|
restore()
|
|
return noop, fmt.Errorf("applying %s: %w", mut.key, applyErr)
|
|
}
|
|
}
|
|
return restore, nil
|
|
}
|
|
|
|
func initDoltServerTLSFromEnv() bool {
|
|
return (&configfile.Config{}).GetDoltServerTLS()
|
|
}
|
|
|
|
func initTimeCloneConfig(serverMode bool, serverHost string, serverPort int, serverSocket, serverUser, dbName string) *configfile.Config {
|
|
cfg := configfile.DefaultConfig()
|
|
cfg.Backend = configfile.BackendDolt
|
|
cfg.DoltDatabase = dbName
|
|
if serverMode {
|
|
cfg.DoltMode = configfile.DoltModeServer
|
|
cfg.DoltServerHost = configfile.DefaultDoltServerHost
|
|
cfg.DoltServerUser = configfile.DefaultDoltServerUser
|
|
} else {
|
|
cfg.DoltMode = configfile.DoltModeEmbedded
|
|
}
|
|
if serverHost != "" {
|
|
cfg.DoltServerHost = serverHost
|
|
}
|
|
if serverPort != 0 {
|
|
cfg.DoltServerPort = serverPort
|
|
}
|
|
if serverSocket != "" {
|
|
cfg.DoltServerSocket = serverSocket
|
|
}
|
|
if serverUser != "" {
|
|
cfg.DoltServerUser = serverUser
|
|
}
|
|
return cfg
|
|
}
|
|
|
|
func persistInitSyncRemote(beadsDir, initRemote, syncURL string, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin bool) error {
|
|
if initRemote != "" {
|
|
return config.SetYamlConfigInDir(beadsDir, "sync.remote", initRemote)
|
|
}
|
|
if !shouldWireInitRemote(syncURL, syncFromRemote, syncURLFromConfig, syncURLFromGitOrigin) {
|
|
return nil
|
|
}
|
|
if existing := config.GetStringFromDir(beadsDir, "sync.remote"); existing != "" {
|
|
return nil
|
|
}
|
|
return config.SetYamlConfigInDir(beadsDir, "sync.remote", syncURL)
|
|
}
|
|
|
|
func isEmptyRemoteCloneError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
msg := strings.ToLower(err.Error())
|
|
return strings.Contains(msg, "contains no dolt data")
|
|
}
|
|
|
|
type initStateCommitter interface {
|
|
CommitWithConfig(context.Context, string) error
|
|
}
|
|
|
|
// commitInitState commits the configuration init deliberately created as well
|
|
// as the initial schema state. The ordinary Commit contract excludes config to
|
|
// avoid sweeping unrelated stale values, so using it here leaves every fresh
|
|
// database dirty immediately after a successful init.
|
|
func commitInitState(ctx context.Context, store initStateCommitter) error {
|
|
return store.CommitWithConfig(ctx, "bd init")
|
|
}
|
|
|
|
// verifyMetadata writes a metadata field and verifies the write succeeded.
|
|
// Returns true if write+verify succeeded, false with warning if either failed.
|
|
func verifyMetadata(ctx context.Context, store storage.DoltStorage, key, value string) bool {
|
|
if err := store.SetMetadata(ctx, key, value); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to write %s metadata: %v\n", key, err)
|
|
if usesSQLServer() {
|
|
fmt.Fprintf(os.Stderr, " Run 'bd doctor --fix' to repair.\n")
|
|
}
|
|
return false
|
|
}
|
|
// Verify read-back
|
|
readBack, err := store.GetMetadata(ctx, key)
|
|
if err != nil || readBack != value {
|
|
fmt.Fprintf(os.Stderr, "Warning: %s metadata write did not persist (wrote %q, read %q)\n", key, value, readBack)
|
|
if usesSQLServer() {
|
|
fmt.Fprintf(os.Stderr, " Run 'bd doctor --fix' to repair.\n")
|
|
}
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// initGlobalDatabaseConfig opens a store connection to the beads_global database
|
|
// and seeds its configuration (issue prefix, project ID). The database must already
|
|
// exist (created by EnsureGlobalDatabase). This function is idempotent — it only
|
|
// sets config values that are not already present.
|
|
func initGlobalDatabaseConfig(ctx context.Context, projectCfg *dolt.Config, quiet bool) {
|
|
globalCfg := &dolt.Config{
|
|
Path: projectCfg.Path,
|
|
BeadsDir: projectCfg.BeadsDir,
|
|
Database: doltserver.GlobalDatabaseName,
|
|
ServerHost: projectCfg.ServerHost,
|
|
ServerPort: projectCfg.ServerPort,
|
|
// projectCfg has been through applyConfigDefaults, so its port is
|
|
// resolved and its source is accurate; copy both. Dropping the source
|
|
// here would re-label the copy caller-explicit on the way into the
|
|
// second dolt.New.
|
|
ServerPortSource: projectCfg.ServerPortSource,
|
|
ServerPortSharedServer: projectCfg.ServerPortSharedServer,
|
|
ServerUser: projectCfg.ServerUser,
|
|
ServerPassword: projectCfg.ServerPassword,
|
|
ServerMode: true,
|
|
CreateIfMissing: true,
|
|
AutoStart: false, // server is already running
|
|
}
|
|
|
|
globalStore, err := newDoltStore(ctx, globalCfg)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to open global database: %v\n", err)
|
|
// The gate's own block prescribes `bd migrate schema`, which migrates
|
|
// the PROJECT database — on this path that leaves the global database
|
|
// exactly as refused. Name the command that actually reaches it
|
|
// (#5920); this warning is the only place the global refusal surfaces.
|
|
if schema.IsRemoteMigrateGateError(err) {
|
|
fmt.Fprintf(os.Stderr,
|
|
" The global database is shared by every workspace on this server. To migrate it, run:\n %s\n",
|
|
schema.SharedConsentCommandGlobal)
|
|
}
|
|
return
|
|
}
|
|
defer func() { _ = globalStore.Close() }()
|
|
|
|
// Set issue prefix (only if not already configured)
|
|
existing, _ := globalStore.GetConfig(ctx, "issue_prefix")
|
|
if existing == "" {
|
|
if err := globalStore.SetConfig(ctx, "issue_prefix", doltserver.GlobalIssuePrefix); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set global issue prefix: %v\n", err)
|
|
}
|
|
}
|
|
|
|
// Set well-known project ID for the global database
|
|
existingID, _ := globalStore.GetMetadata(ctx, "_project_id")
|
|
if existingID == "" {
|
|
if err := globalStore.SetMetadata(ctx, "_project_id", doltserver.GlobalProjectID); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to set global project ID: %v\n", err)
|
|
}
|
|
}
|
|
|
|
if !quiet {
|
|
fmt.Printf(" %s Global database schema initialized\n", ui.RenderPass("✓"))
|
|
}
|
|
}
|
|
|
|
func resolveInitDoltMode(proxiedFlag, sharedFlag, serverFlag bool) string {
|
|
if proxiedFlag || os.Getenv("BEADS_DOLT_PROXIED_SERVER") == "1" {
|
|
return "proxied-server"
|
|
}
|
|
shared := os.Getenv("BEADS_DOLT_SHARED_SERVER")
|
|
if sharedFlag || shared == "1" || strings.EqualFold(shared, "true") {
|
|
return "shared-server"
|
|
}
|
|
if serverFlag || os.Getenv("BEADS_DOLT_SERVER_MODE") == "1" {
|
|
return "server"
|
|
}
|
|
return "embedded"
|
|
}
|
|
|
|
// commitEmbeddedInitArtifacts stages the local init artifacts and preserves the
|
|
// optional-add and nonfatal commit behavior of the embedded bootstrap.
|
|
func commitEmbeddedInitArtifacts(workDir string, quiet bool) {
|
|
if initArtifactGitCommand(workDir, "rev-parse", "--git-dir").Run() != nil {
|
|
if !quiet {
|
|
fmt.Fprintln(os.Stderr, "Note: skipped bootstrap commit because Git could not resolve the selected repository.")
|
|
}
|
|
return
|
|
}
|
|
gitAddCmd := initArtifactGitCommand(workDir, "add", ".beads/")
|
|
if _, addErr := gitAddCmd.CombinedOutput(); addErr == nil {
|
|
// Also stage the agents file if it exists
|
|
agentsFileToStage := config.SafeAgentsFile()
|
|
if _, statErr := os.Stat(filepath.Join(workDir, agentsFileToStage)); statErr == nil {
|
|
agentsCmd := initArtifactGitCommand(workDir, "add", agentsFileToStage)
|
|
_ = agentsCmd.Run()
|
|
}
|
|
// Also stage Claude settings if created by init
|
|
claudeSettingsPath := filepath.Join(".claude", "settings.json")
|
|
if _, statErr := os.Stat(filepath.Join(workDir, claudeSettingsPath)); statErr == nil {
|
|
claudeCmd := initArtifactGitCommand(workDir, "add", claudeSettingsPath)
|
|
_ = claudeCmd.Run()
|
|
}
|
|
// Also stage CLAUDE.md if created by setup
|
|
if _, statErr := os.Stat(filepath.Join(workDir, "CLAUDE.md")); statErr == nil {
|
|
claudeMdCmd := initArtifactGitCommand(workDir, "add", "CLAUDE.md")
|
|
_ = claudeMdCmd.Run()
|
|
}
|
|
// Also stage Codex and Cursor project integration files if created
|
|
// by setup. Cursor project hooks/rules are meant to be committed
|
|
// (a no-op git add if .cursor/ is gitignored in this repo).
|
|
for _, path := range []string{".agents", ".codex", ".cursor"} {
|
|
if _, statErr := os.Stat(filepath.Join(workDir, path)); statErr == nil {
|
|
codexCmd := initArtifactGitCommand(workDir, "add", path)
|
|
_ = codexCmd.Run()
|
|
}
|
|
}
|
|
// Also stage .gitignore if modified by EnsureProjectGitignore
|
|
if _, statErr := os.Stat(filepath.Join(workDir, ".gitignore")); statErr == nil {
|
|
giCmd := initArtifactGitCommand(workDir, "add", ".gitignore")
|
|
_ = giCmd.Run()
|
|
}
|
|
// Hooks installed by this init can call back into bd. Skip all
|
|
// of them for the bootstrap commit to avoid self-deadlocking
|
|
// while init still owns the embedded Dolt lock. --no-verify
|
|
// alone does not skip prepare-commit-msg.
|
|
commitArgs := []string{"-c", "core.hooksPath=", "commit", "--no-verify", "-m", "bd init: initialize beads issue tracking"}
|
|
commitCmd := initArtifactGitCommand(workDir, commitArgs...)
|
|
if commitOut, commitErr := commitCmd.CombinedOutput(); commitErr != nil {
|
|
if !quiet && !strings.Contains(string(commitOut), "nothing to commit") {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to commit beads files: %v\n", commitErr)
|
|
}
|
|
} else if !quiet {
|
|
fmt.Printf(" %s Committed beads files to git\n", ui.RenderPass("✓"))
|
|
}
|
|
// WARNING: DO NOT remove, delete, or modify files inside Dolt's .dolt/
|
|
// directory — including noms/LOCK files. These are Dolt-internal files.
|
|
// Removing them WILL cause unrecoverable data corruption and data loss.
|
|
// Dolt manages these files itself; external interference is never safe.
|
|
}
|
|
}
|
|
|
|
func initArtifactGitCommand(workDir string, args ...string) *exec.Cmd {
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir, cmd.Env = workDir, gitenv.ScrubRouting(os.Environ())
|
|
return cmd
|
|
}
|