* fix(init): name --recreate-missing in the refusal without a paste-ready command The missing-server-database refusal added in #5791 ended with a complete `bd init --recreate-missing --prefix <prefix>` line. ADR 0002 Invariant 4 keeps complete destructive invocations out of bd error output, and this refusal also fires when the server merely could not be reached: a stopped server, a wrong port and a wrong data dir all look the same from here, and recreating in any of them strands the real data behind an empty database of the same name. The line also echoed the raw --prefix flag value, so a run without --prefix printed `--prefix ` with nothing after it. The refusal now names the flag and points to `bd help init-safety`, which keeps the full invocation behind the diagnosis it requires. The unused prefix parameter stays as `_` so the guard call sites are unchanged. Also: - --force / --reinit-local flag help, `bd help init-safety` and the init guard comment now say neither flag authorizes recreating a missing server-mode database; the --recreate-missing stanza says to rule out a stopped server or wrong port/data dir and restore first. - bootstrap.go comments no longer describe #5791 as open and unmerged. - TestInitGuardMissingServerDBMessage_RefusalTextNoEcho pins the wording for both evidence arms, with and without a prefix. - TestInitGuard_RecreateMissingE2ECreatesMissingServerDB runs the real binary against a live server lacking the database: refused without the flag, created with it. The unit tests flip initAllowRecreateMissing directly, so nothing exercised the documented command end to end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(recovery): init-missing-server-db covers both evidence arms and the flag limits The init-missing-server-db section described only the project_id arm of the guard. Under --reinit-local or --force a workspace that predates project_id is also refused when its local Dolt data directory survives, and the refusal then cites that directory instead of metadata.json. "What happened" now covers both arms. "Limits worth knowing" replaces the stale "fails open" bullet with a table of which local state meets the refusal under bd init and under --reinit-local / --force, and what --recreate-missing changes. The init-force-refused section now says --force / --reinit-local bypass only the local data-safety guard, not this refusal or the remote one, and step 3 says why the refusal names --recreate-missing without printing the command (ADR 0002 Invariant 4). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(adr): mark ADR 0004 Accepted now that #5791 has landed ADR 0004 (the missing-database guard signal) still read "Proposed" after the guards implementing it merged in #5791, and its Consequences said checkExistingBeadsDataAt "does not change" although the same PR gave it the Tier 1 probe ahead of project_id. Record the acceptance and say what the PR already changed; DOC_INVENTORY.md follows the status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
184 lines
8.5 KiB
Go
184 lines
8.5 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
"github.com/steveyegge/beads/internal/storage/doltutil"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
)
|
|
|
|
// initGuardDBCheck holds the result of checking whether a database exists on a
|
|
// Dolt server. Extracted from checkExistingBeadsDataAt for testability.
|
|
type initGuardDBCheck struct {
|
|
Exists bool // database found via SHOW DATABASES
|
|
Reachable bool // server responded to ping
|
|
Err error
|
|
}
|
|
|
|
// checkDatabaseOnServer opens a temporary connection to the Dolt server and
|
|
// checks whether the named database exists via SHOW DATABASES. The connection
|
|
// is closed before returning.
|
|
//
|
|
// Returns Reachable=false when the server cannot be reached (FR-030), so the
|
|
// caller can fall through to existing "already initialized" behavior.
|
|
func checkDatabaseOnServer(host string, port int, user, password, dbName string, tls bool) initGuardDBCheck {
|
|
dsn := doltutil.ServerDSN{
|
|
Host: host,
|
|
Port: port,
|
|
User: user,
|
|
Password: password,
|
|
TLS: tls,
|
|
}.String()
|
|
|
|
db, err := sql.Open("mysql", dsn)
|
|
if err != nil {
|
|
return initGuardDBCheck{Reachable: false, Err: err}
|
|
}
|
|
defer db.Close()
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
// Ping first to verify reachability — sql.Open is lazy.
|
|
if err := db.PingContext(ctx); err != nil {
|
|
return initGuardDBCheck{Reachable: false, Err: err}
|
|
}
|
|
|
|
// Iterate SHOW DATABASES (not LIKE, to avoid underscore wildcard issues).
|
|
rows, err := db.QueryContext(ctx, "SHOW DATABASES")
|
|
if err != nil {
|
|
// Server reachable but query failed — treat as unreachable to avoid
|
|
// false negatives on permissions issues.
|
|
return initGuardDBCheck{Reachable: true, Err: err}
|
|
}
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
var name string
|
|
if err := rows.Scan(&name); err != nil {
|
|
return initGuardDBCheck{Reachable: true, Err: err}
|
|
}
|
|
if name == dbName {
|
|
return initGuardDBCheck{Exists: true, Reachable: true}
|
|
}
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return initGuardDBCheck{Reachable: true, Err: err}
|
|
}
|
|
|
|
return initGuardDBCheck{Exists: false, Reachable: true}
|
|
}
|
|
|
|
// initGuardServerMessage builds the error message for the init guard when the
|
|
// server is reachable but the database does not exist (FR-010, FR-011).
|
|
// Extracted as a pure function for unit testing without a real database.
|
|
//
|
|
// GH#2363: The message deliberately avoids suggesting `bd init --force` because
|
|
// that command destroys all existing issue data. An AI agent running inside a
|
|
// git hook blindly followed the previous suggestion and wiped a production
|
|
// database. Instead we guide the user toward safe diagnostic commands.
|
|
func initGuardServerMessage(dbName, host string, port int, prefix, syncRemote string) error {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "\n%s Database %q not found on server at %s:%d.\n", ui.RenderWarn("⚠"), dbName, host, port)
|
|
b.WriteString("The server is running but this database hasn't been created yet.\n")
|
|
|
|
b.WriteString("\nDiagnose with:\n")
|
|
b.WriteString(" bd doctor # check project health\n")
|
|
b.WriteString(" bd dolt status # inspect Dolt server state\n")
|
|
|
|
b.WriteString("\nIf this is an existing project, fresh clone, or shared-server recovery, run:\n")
|
|
b.WriteString(" bd bootstrap\n")
|
|
b.WriteString("This is the safe entry point for existing-project recovery and may recover or initialize depending on detected state.\n")
|
|
|
|
if syncRemote != "" {
|
|
fmt.Fprintf(&b, "\nTip: sync.remote is configured (%s).\n", syncRemote)
|
|
b.WriteString("Run bd bootstrap to recover from the configured remote, or use --dry-run to inspect the plan first.\n")
|
|
} else {
|
|
b.WriteString("\nIf this is a brand-new project, create the database with:\n")
|
|
fmt.Fprintf(&b, " bd init --prefix %s\n", prefix)
|
|
b.WriteString("\nIf bd bootstrap cannot find the expected remote automatically, set sync.remote\n")
|
|
b.WriteString("in .beads/config.yaml and re-run bd bootstrap.\n")
|
|
}
|
|
|
|
b.WriteString("\n⚠ Caution: bd init --force destroys ALL existing issues. Do not\n")
|
|
b.WriteString("use --force unless you are certain the database should be recreated.\n")
|
|
|
|
b.WriteString("\nAborting.")
|
|
return errors.New(b.String())
|
|
}
|
|
|
|
// initAllowRecreateMissing is threaded from --recreate-missing for the
|
|
// duration of a single `bd init` invocation (be-5up5). It must only ever be
|
|
// set from that explicit per-invocation flag — never from a config key, env
|
|
// var, or implied by --force/--reinit-local — because it authorizes the one
|
|
// thing this file's guard exists to prevent: creating a fresh database when
|
|
// an existing project's configured one is missing or unreachable.
|
|
var initAllowRecreateMissing bool
|
|
|
|
// initGuardMissingServerDBMessage builds the refusal error for be-5up5: a
|
|
// workspace with evidence of prior initialization whose configured
|
|
// server-mode database is absent or the server could not be reached to
|
|
// confirm. This differs from initGuardServerMessage above, which would be used
|
|
// where there is no evidence either way about prior initialization and
|
|
// `bd bootstrap` is a reasonable next step — it has no production caller
|
|
// today, so the contrast is one of intent, not of two live code paths. Here
|
|
// prior initialization is already established, so recommending bootstrap would
|
|
// route straight back into the same class of silent-empty-database creation
|
|
// this guard exists to stop (2026-08-11 fleet-wide data loss). Point at
|
|
// restore-from-export instead, and require the explicit --recreate-missing
|
|
// opt-in before bd init will create anything.
|
|
//
|
|
// haveProjectID selects which evidence the message may cite. The plain-init
|
|
// guard only reaches this message with a project_id in hand, but the
|
|
// --reinit-local/--force guard also reaches it for a workspace that predates
|
|
// project_id (GH#2372) and is proven only by its local Dolt storage. Naming
|
|
// metadata.json in that cell would assert evidence the caller does not have,
|
|
// misdirecting an operator who audits metadata.json mid-recovery.
|
|
//
|
|
// The --recreate-missing opt-in is named by flag only, never as a paste-ready
|
|
// command line (ADR 0002 Invariant 4). This refusal also fires when the server
|
|
// merely could not be reached to confirm, so whoever reads it may not yet know
|
|
// which case they are in, and a one-liner copied out of the error skips the
|
|
// diagnosis it asks for. The full invocation lives in `bd help init-safety` and
|
|
// docs/recovery/init-safety.md. The blank string parameter is the raw --prefix
|
|
// value that one-liner used to echo; it is ignored now, and kept only so the
|
|
// guard call sites stay unchanged.
|
|
func initGuardMissingServerDBMessage(dbName, host string, port int, _ string, haveProjectID bool) error {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "\n%s Database %q not found on server at %s:%d (or the server could not be reached to confirm).\n", ui.RenderWarn("⚠"), dbName, host, port)
|
|
if haveProjectID {
|
|
b.WriteString("This workspace was already initialized (metadata.json has a project_id from a prior\n")
|
|
b.WriteString("bd init), so this looks like a recovery situation, not a fresh clone: the configured\n")
|
|
b.WriteString("database is missing from the server, or the server could not be reached to check.\n")
|
|
} else {
|
|
b.WriteString("This workspace shows evidence of prior initialization (local Dolt storage is present,\n")
|
|
b.WriteString("though metadata.json carries no project_id — the shape of a workspace predating\n")
|
|
b.WriteString("GH#2372), so this looks like a recovery situation, not a fresh clone: the configured\n")
|
|
b.WriteString("database is missing from the server, or the server could not be reached to check.\n")
|
|
}
|
|
|
|
b.WriteString("\nbd init will NOT create an empty database here — that would strand any existing\n")
|
|
b.WriteString("issue data behind a new, empty database of the same name.\n")
|
|
|
|
b.WriteString("\nDiagnose with:\n")
|
|
b.WriteString(" bd doctor # check project health\n")
|
|
b.WriteString(" bd dolt status # inspect Dolt server state\n")
|
|
|
|
b.WriteString("\nTo recover existing data, restore from an export rather than creating fresh:\n")
|
|
b.WriteString(" bd backup restore # if a local backup snapshot exists\n")
|
|
b.WriteString(" Check .beads/backup/ for a JSONL export you can import manually.\n")
|
|
|
|
b.WriteString("\nCreate a fresh, empty database at this name (only if you are certain no\n")
|
|
b.WriteString("recoverable data exists):\n")
|
|
b.WriteString(" See 'bd help init-safety' for the --recreate-missing workflow.\n")
|
|
|
|
b.WriteString("\nAborting.")
|
|
return errors.New(b.String())
|
|
}
|