diff --git a/cmd/bd/bootstrap.go b/cmd/bd/bootstrap.go
index 8e6fd19e9..95ba55b57 100644
--- a/cmd/bd/bootstrap.go
+++ b/cmd/bd/bootstrap.go
@@ -156,6 +156,19 @@ Examples:
// Resolve non-interactive mode: flag > env var > CI env > terminal detection.
nonInteractive := isNonInteractiveBootstrap(yesFlag || nonInteractiveFlag)
+ // dc-6jaq: "bootstrap" is in noDbCommands, so PersistentPreRunE
+ // returns at the skip-store early return before its freeze gate, and
+ // bootstrap.go calls neither CheckReadonly nor the gate itself — yet
+ // it writes, and the first of those writes (the metadata repair below)
+ // lands before its own confirmation prompt and before it takes any
+ // workspace gate. --dry-run is exempt because it genuinely does not
+ // write; every other invocation is refused while a marker is active.
+ if !dryRun {
+ if err := migrationFreezeGateFor(cmd, "bootstrap"); err != nil {
+ return err
+ }
+ }
+
// Find beads directory
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
diff --git a/cmd/bd/close.go b/cmd/bd/close.go
index 358016b99..d87223c3d 100644
--- a/cmd/bd/close.go
+++ b/cmd/bd/close.go
@@ -49,7 +49,7 @@ the flags appear in the command line.`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
- CheckReadonly("close") // also covers CheckMigrationFreeze (dc-6jaq)
+ CheckReadonly("close") // also covers the migration freeze check (dc-6jaq)
evt := metrics.NewCommandEvent("close")
defer func() {
diff --git a/cmd/bd/create.go b/cmd/bd/create.go
index 2f6956656..3d97cea34 100644
--- a/cmd/bd/create.go
+++ b/cmd/bd/create.go
@@ -52,7 +52,7 @@ var createCmd = &cobra.Command{
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
- CheckReadonly("create") // also covers CheckMigrationFreeze (dc-6jaq)
+ CheckReadonly("create") // also covers the migration freeze check (dc-6jaq)
evt := metrics.NewCommandEvent("create")
defer func() {
diff --git a/cmd/bd/doctor_gastown_guard.go b/cmd/bd/doctor_gastown_guard.go
deleted file mode 100644
index 5b70b0336..000000000
--- a/cmd/bd/doctor_gastown_guard.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package main
-
-import (
- "os"
- "path/filepath"
-)
-
-// isOrchestratorRoot returns true when path looks like a multi-project
-// orchestrator workspace root (not a single-project beads repo).
-//
-// Detection: presence of both:
-// 1. .beads/routes.jsonl (cross-project routing config)
-// 2. mayor/town.json (orchestrator configuration)
-//
-// This prevents bd doctor --fix from running at the workspace root,
-// where repairs should go through the orchestrator's own doctor command.
-func isOrchestratorRoot(path string) bool {
- if path == "" {
- return false
- }
-
- routes := filepath.Join(path, ".beads", "routes.jsonl")
- townJSON := filepath.Join(path, "mayor", "town.json")
-
- if _, err := os.Stat(routes); err != nil {
- return false
- }
- if _, err := os.Stat(townJSON); err != nil {
- return false
- }
-
- return true
-}
-
-// findTownRoot walks up from the current working directory looking for
-// mayor/town.json — the same primary marker gt's own workspace package uses
-// (see gastownhall/gastown internal/cmd/handoff.go's detectTownRootFromCwd).
-// Falls back to GT_TOWN_ROOT then GT_ROOT (gt's env-var fallback chain,
-// already how the rest of this codebase detects an orchestrator — see
-// formula.go, molecules.go, doltserver.go) when cwd detection fails, e.g. a
-// detached worktree or a cwd outside the town tree entirely.
-//
-// Used by CheckMigrationFreeze (dc-6jaq) to find the MIGRATION-FREEZE
-// sentinel; unlike isOrchestratorRoot above this only needs the mayor/
-// marker, not also .beads/routes.jsonl, since a rig-level bd invocation's
-// cwd is never itself the orchestrator root.
-func findTownRoot() string {
- if cwd, err := os.Getwd(); err == nil {
- path := cwd
- for {
- if _, statErr := os.Stat(filepath.Join(path, "mayor", "town.json")); statErr == nil {
- return path
- }
- parent := filepath.Dir(path)
- if parent == path {
- break
- }
- path = parent
- }
- }
-
- for _, envName := range []string{"GT_TOWN_ROOT", "GT_ROOT"} {
- envRoot := os.Getenv(envName)
- if envRoot == "" {
- continue
- }
- if _, err := os.Stat(filepath.Join(envRoot, "mayor", "town.json")); err == nil {
- return envRoot
- }
- }
-
- return ""
-}
diff --git a/cmd/bd/doctor_orchestrator_guard.go b/cmd/bd/doctor_orchestrator_guard.go
new file mode 100644
index 000000000..fffb4dc4b
--- /dev/null
+++ b/cmd/bd/doctor_orchestrator_guard.go
@@ -0,0 +1,33 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+)
+
+// isOrchestratorRoot returns true when path looks like a multi-project
+// orchestrator workspace root (not a single-project beads repo).
+//
+// Detection: presence of both:
+// 1. .beads/routes.jsonl (cross-project routing config)
+// 2. mayor/town.json (orchestrator configuration)
+//
+// This prevents bd doctor --fix from running at the workspace root,
+// where repairs should go through the orchestrator's own doctor command.
+func isOrchestratorRoot(path string) bool {
+ if path == "" {
+ return false
+ }
+
+ routes := filepath.Join(path, ".beads", "routes.jsonl")
+ townJSON := filepath.Join(path, "mayor", "town.json")
+
+ if _, err := os.Stat(routes); err != nil {
+ return false
+ }
+ if _, err := os.Stat(townJSON); err != nil {
+ return false
+ }
+
+ return true
+}
diff --git a/cmd/bd/doctor_gastown_guard_test.go b/cmd/bd/doctor_orchestrator_guard_test.go
similarity index 100%
rename from cmd/bd/doctor_gastown_guard_test.go
rename to cmd/bd/doctor_orchestrator_guard_test.go
diff --git a/cmd/bd/errors.go b/cmd/bd/errors.go
index 0cab94bb5..02bea8351 100644
--- a/cmd/bd/errors.go
+++ b/cmd/bd/errors.go
@@ -6,8 +6,12 @@ import (
"fmt"
"os"
+ "github.com/spf13/cobra"
+
+ "github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/migration"
+ "github.com/steveyegge/beads/internal/ui"
)
type exitError struct {
@@ -125,44 +129,75 @@ func WarnError(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "Warning: "+format+"\n", args...)
}
+// ExitMigrationFrozen is the exit code for a write refused because a
+// migration freeze marker is active (dc-6jaq). Stable value so scripts can
+// branch on "someone is migrating this workspace, come back later" without
+// grep'ing stderr, instead of reading it as a generic failure (1) worth
+// retrying immediately.
+const ExitMigrationFrozen = 14
+
// CheckReadonly aborts the command when bd is running in read-only mode (the
-// worker-sandbox posture, see readonlyMode), or when a MIGRATION-FREEZE
-// sentinel is active at the town root (dc-6jaq, folded in here rather than
-// requiring every write command to remember a second call — see
-// CheckMigrationFreeze below). This is the chokepoint essentially every
-// write command already calls first, so folding the freeze check in here
-// covers the whole write surface at once, including commands added after
-// this comment is written — not just a hand-picked list that rots (one
-// concrete instance the hand-picked list missed: "bd q", cmd/bd/quick.go,
-// the create alias). It exits via os.Exit and so cannot run the per-command
-// deferred CloseEventAndAdd — a command blocked here records no
-// cli_command event of its own (it never actually ran). It does flush
-// metrics first, so events already queued earlier in this run are still
-// written and scheduled for upload rather than stranded until the next
-// clean exit.
+// worker-sandbox posture, see readonlyMode), or when a migration freeze
+// marker is active (dc-6jaq, folded in here rather than requiring every write
+// command to remember a second call — see migrationFreezeError below). This
+// is the chokepoint essentially every write command already calls first, so
+// folding the freeze check in here covers the whole write surface at once,
+// including commands added after this comment is written — not just a
+// hand-picked list that rots (one concrete instance the hand-picked list
+// missed: "bd q", cmd/bd/quick.go, the create alias). It exits via os.Exit
+// and so cannot run the per-command deferred CloseEventAndAdd — a command
+// blocked here records no cli_command event of its own (it never actually
+// ran). It does flush metrics first, so events already queued earlier in this
+// run are still written and scheduled for upload rather than stranded until
+// the next clean exit. Callers that CAN return an error (the root
+// PersistentPreRunE, runImport) call migrationFreezeError directly instead,
+// so their deferred cleanup still runs.
func CheckReadonly(operation string) {
if readonlyMode {
fmt.Fprintf(os.Stderr, "Error: operation '%s' is not allowed in read-only mode\n", operation)
metrics.CloseAndFlush()
os.Exit(1)
}
- CheckMigrationFreeze(operation)
+ if err := migrationFreezeError(operation); err != nil {
+ metrics.CloseAndFlush()
+ os.Exit(ExitMigrationFrozen)
+ }
}
-// CheckMigrationFreeze aborts the command when a MIGRATION-FREEZE sentinel is
-// present at the town root (dc-6jaq). The gt CLI already refuses to write
-// under the same sentinel (gt mail send, gt nudge, gt sling, gt assign);
-// mail-poller/daemon patrols that also write via bd are stopped separately
-// via the migration playbook's plist-unload step, so this closes the
-// remaining gap: a human typing 'bd create'/'bd update' etc. mid-migration,
-// bypassing the gt-layer gate. Same exit-via-os.Exit tradeoff as
-// CheckReadonly above — no cli_command event for a command blocked here,
-// but queued metrics are still flushed.
+// freezeSearchRoots returns the directories whose ancestry the freeze lookup
+// must cover in addition to the working directory: the resolved workspace, so
+// the gate keys on the store being written rather than on the caller's shell.
+// Without it, `BEADS_DIR=/work/repo/.beads bd create` run from $HOME, `bd -C
+// /work/repo create` (which sets BEADS_DIR and never chdirs), and any daemon
+// or cron job with an unrelated cwd all walk the wrong tree and write straight
+// through a freeze.
+//
+// PersistentPreRunE exports BEADS_DIR as part of selecting the workspace
+// (prepareSelectedCommandContext), so by the time a command's RunE reaches
+// CheckReadonly this is a cheap env read. The FindBeadsDir fallback covers the
+// callers that run before that — and returns "" rather than erroring when
+// there is no workspace at all, which Find skips.
+func freezeSearchRoots() []string {
+ if dir := os.Getenv("BEADS_DIR"); dir != "" {
+ return []string{dir}
+ }
+ if dir := beads.FindBeadsDir(); dir != "" {
+ return []string{dir}
+ }
+ return nil
+}
+
+// migrationFreezeError reports the active migration freeze, if any: it
+// returns nil when writes are not frozen, and otherwise prints the refusal to
+// stderr and returns an ExitMigrationFrozen exit error. The refusal names the
+// marker's own path, so the recovery instruction ("remove that file") is
+// always actionable without knowing what created it.
//
// Three callers, each closing a different hole:
// 1. CheckReadonly above — the per-command chokepoint covering the write
// surface at large (create/update/close/... and everything that calls
-// CheckReadonly, ~120 sites).
+// CheckReadonly, ~120 sites). Only that caller turns this error into an
+// os.Exit, because its void signature leaves it nothing else to do.
// 2. The root PersistentPreRunE in main.go, before autoMigrateOnVersionBump
// and maybeAutoImportJSONL — those run as store-open side effects
// *before* any RunE, so waiting for a write command's own CheckReadonly
@@ -173,25 +208,109 @@ func CheckReadonly(operation string) {
// CheckReadonly at all today (a pre-existing, separate gap: readonlyMode
// doesn't block it either), so it cannot inherit the freeze check from
// caller 1 and needs its own explicit call.
-func CheckMigrationFreeze(operation string) {
- townRoot := findTownRoot()
- if !migration.IsFrozen(townRoot) {
- return
+func migrationFreezeError(operation string) error {
+ return migrationFreezeRefusal(operation, migration.Find(freezeSearchRoots()...))
+}
+
+// migrationFreezeRefusal renders an already-resolved lookup. Callers that
+// need the same Result for more than the refusal — PersistentPreRunE, which
+// also derives frozenForMaintenance from it — resolve once and pass it here,
+// so a single walk answers the whole invocation and the two readings cannot
+// disagree about a marker that appeared or vanished between them.
+func migrationFreezeRefusal(operation string, res migration.Result) error {
+ if !res.Frozen() {
+ return nil
}
- info := migration.Read(townRoot)
- operator := "unknown"
+ if res.Err != nil {
+ // Fail closed: bd could not tell whether a marker is present (a
+ // permission error on the marker or a directory above it). An
+ // undeterminable gate is not an open gate, and saying so beats
+ // writing into a workspace that may be mid-migration.
+ fmt.Fprint(os.Stderr, "⛔ ERROR: cannot determine whether this workspace is frozen for migration.\n")
+ fmt.Fprintf(os.Stderr, " %s\n", ui.SanitizeForTerminal(res.Err.Error()))
+ fmt.Fprintf(os.Stderr, " bd %s is blocked until the marker can be read.\n", operation)
+ fmt.Fprintf(os.Stderr, " Fix the permissions, or set %s to a path bd can stat.\n", migration.EnvFreezeFile)
+ return &exitError{Code: ExitMigrationFrozen}
+ }
+
+ // The marker can live in a directory bd does not control, so its payload
+ // is untrusted input on its way to a terminal. parse already keeps it to
+ // one line; sanitizing strips ANSI and control bytes on top of that.
+ operator := ""
reason := ""
- if info != nil {
- operator = info.Operator
- reason = info.Reason
+ if info := migration.ReadFile(res.Path); info != nil {
+ operator = ui.SanitizeForTerminal(info.Operator)
+ reason = ui.SanitizeForTerminal(info.Reason)
}
- fmt.Fprintf(os.Stderr, "⛔ ERROR: town is frozen for migration (by %s).\n", operator)
+ if operator != "" {
+ fmt.Fprintf(os.Stderr, "⛔ ERROR: workspace is frozen for migration (by %s).\n", operator)
+ } else {
+ // An empty or unparseable marker (a bare `touch`) records no
+ // operator; say nothing rather than printing "(by )".
+ fmt.Fprint(os.Stderr, "⛔ ERROR: workspace is frozen for migration.\n")
+ }
if reason != "" {
fmt.Fprintf(os.Stderr, " Reason: %s\n", reason)
}
- fmt.Fprintf(os.Stderr, " bd %s is blocked. Clear the freeze: gt migrate thaw\n", operation)
- metrics.CloseAndFlush()
- os.Exit(1)
+ fmt.Fprintf(os.Stderr, " bd %s is blocked by the freeze marker at %s.\n", operation, res.Path)
+ if res.FromEnv {
+ fmt.Fprintf(os.Stderr, " To resume writes, remove that file or unset %s.\n", migration.EnvFreezeFile)
+ } else {
+ // Name the variable on this path too: when the marker sits in a
+ // directory the caller cannot write to, pointing the variable
+ // elsewhere is the only recovery available to them.
+ fmt.Fprint(os.Stderr, " To resume writes, remove that file.\n")
+ fmt.Fprintf(os.Stderr, " If you cannot remove it, set %s to a path bd should check instead.\n", migration.EnvFreezeFile)
+ }
+ return &exitError{Code: ExitMigrationFrozen}
+}
+
+// migrationFreezeGate is the RunE-side entry point: it renders the refusal and,
+// because the refusal has already said everything worth saying, suppresses
+// cobra's own error and usage rendering for this invocation.
+//
+// Without the suppression a freeze refusal on any command that does not set
+// SilenceErrors/SilenceUsage statically — duplicate, supersede, dep
+// relate/unrelate, backup init/sync/remove/restore, ado sync, migrate-personal,
+// batch — is followed by "Error: exit code 14" (exitError's placeholder text)
+// and a full usage dump, so a clean refusal reads like a syntax error. Setting
+// the flags here rather than on each command covers the ones added after this
+// comment too. main() exits on the exitError before its own SilenceErrors
+// branch, so nothing prints the placeholder.
+func migrationFreezeGate(cmd *cobra.Command, operation string, res migration.Result) error {
+ err := migrationFreezeRefusal(operation, res)
+ if err != nil && cmd != nil {
+ cmd.SilenceErrors = true
+ cmd.SilenceUsage = true
+ }
+ return err
+}
+
+// migrationFreezeGateFor resolves the freeze and gates in one step, for the
+// callers that have no Result to thread: the skip-store commands (bd init,
+// bd bootstrap), which return from PersistentPreRunE long before it resolves
+// one, and any command handed an explicit target path.
+func migrationFreezeGateFor(cmd *cobra.Command, operation string, extraRoots ...string) error {
+ return migrationFreezeGate(cmd, operation, migration.Find(freezeRootsWith(extraRoots)...))
+}
+
+// migrationFreezeErrorFor is migrationFreezeError against extra roots, for
+// callers that hold a target path but no *cobra.Command to silence — a command
+// given a workspace to operate on that is not the one it was launched in.
+func migrationFreezeErrorFor(operation string, extraRoots ...string) error {
+ return migrationFreezeRefusal(operation, migration.Find(freezeRootsWith(extraRoots)...))
+}
+
+// migrationFreezeActive is the print-nothing probe for code that must SKIP a
+// write during a freeze rather than refuse the whole command — the diagnosis
+// paths that keep running while frozen but must not apply version tracking or
+// schema auto-migration.
+func migrationFreezeActive() bool {
+ return migration.Find(freezeSearchRoots()...).Frozen()
+}
+
+func freezeRootsWith(extraRoots []string) []string {
+ return append(freezeSearchRoots(), extraRoots...)
}
diff --git a/cmd/bd/import.go b/cmd/bd/import.go
index 7f048a832..dca3a3cef 100644
--- a/cmd/bd/import.go
+++ b/cmd/bd/import.go
@@ -121,7 +121,13 @@ func runImport(cmd *cobra.Command, args []string) error {
// CheckReadonly at all (a separate, pre-existing gap — readonlyMode
// doesn't gate bd import either), so it can't pick up the freeze check
// folded into CheckReadonly the way create/update/close/remember do.
- CheckMigrationFreeze("import")
+ // The path that makes this call load-bearing rather than redundant is
+ // `bd import --dry-run`: a preview sets useReadOnly, so it skips the early
+ // gate in PersistentPreRunE, and runImport is the only chokepoint left.
+ // Plain `bd import` is already stopped by that early gate.
+ if err := migrationFreezeGateFor(cmd, "import"); err != nil {
+ return err
+ }
evt := metrics.NewCommandEvent("import")
defer func() {
diff --git a/cmd/bd/init.go b/cmd/bd/init.go
index b3f4a2e7b..45e4b23cf 100644
--- a/cmd/bd/init.go
+++ b/cmd/bd/init.go
@@ -399,6 +399,32 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
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")
diff --git a/cmd/bd/main.go b/cmd/bd/main.go
index f504918c5..4c7b8235f 100644
--- a/cmd/bd/main.go
+++ b/cmd/bd/main.go
@@ -132,6 +132,15 @@ var (
// This is used for tip-commit message formatting.
commandTipIDsShown map[string]struct{}
+ // commandFreeze is the migration-freeze lookup for this invocation,
+ // resolved once in PersistentPreRunE (dc-6jaq). Both hooks read it: the
+ // pre-run gate refuses writes from it, and PersistentPostRunE skips its
+ // own maintenance writes — auto-commit, tip metadata, backup, export,
+ // push — so a read command run during a freeze does not leave a new Dolt
+ // commit in the store being migrated. Zero value means "not frozen",
+ // which is the right default for the paths that never resolve it.
+ commandFreeze migration.Result
+
// commandSpan is the root OTel span for the current command execution.
// All storage and AI spans are nested as children of this span.
commandSpan oteltrace.Span
@@ -938,6 +947,7 @@ var rootCmd = &cobra.Command{
commandDidExplicitDoltCommit = false
commandDidWriteTipMetadata = false
commandTipIDsShown = make(map[string]struct{})
+ commandFreeze = migration.Result{}
// Set up signal-aware context with batch commit flush on shutdown.
// Unlike signal.NotifyContext, this also handles SIGHUP and flushes
@@ -1424,7 +1434,7 @@ var rootCmd = &cobra.Command{
policy := effectiveRootStorePolicy(cmd.Name(), readonlyMode)
useReadOnly := policy.readOnly || previewMode
- // dc-6jaq: consult the MIGRATION-FREEZE sentinel here, before any of
+ // dc-6jaq: consult the migration freeze marker here, before any of
// this hook's own store-touching side effects — trackBdVersion below
// (writes .local_version), autoMigrateOnVersionBump (opens its own
// store connection and can apply a schema migration), and
@@ -1438,13 +1448,27 @@ var rootCmd = &cobra.Command{
// "write" commands to drift out of sync with the one useReadOnly is
// built from. An explicit --dry-run/--inspect preview also sets
// useReadOnly and so skips this early gate the same way, but is NOT
- // exempt overall: CheckReadonly's own freeze check runs again,
- // unconditionally, at the per-command chokepoint once RunE is
- // reached, and that later call has no preview awareness — so a
- // preview on a frozen town still exits 1 there, fail-closed, same as
- // strict --readonly already blocks `create --dry-run` today.
+ // exempt overall: the per-command chokepoint checks again once RunE
+ // is reached, with no preview awareness — CheckReadonly for the ~120
+ // commands that call it, and runImport's own call for `bd import
+ // --dry-run`, which is not one of them. So a preview on a frozen
+ // workspace still exits ExitMigrationFrozen there, fail-closed, same
+ // as strict --readonly already blocks `create --dry-run` today.
+ // Returning the refusal rather than exiting is load-bearing: the
+ // gates acquired above are released by this hook's deferred cleanup,
+ // which os.Exit would skip.
+ //
+ // One lookup answers the whole invocation: the walk is a stat per
+ // ancestor of both the cwd and the resolved workspace, and resolving
+ // it twice a statement apart would not only pay for it twice but let
+ // the two readings disagree about a marker that appeared or vanished
+ // in between (write allowed but maintenance skipped, or the reverse).
+ // PostRunE reads the same answer via commandFreeze.
+ commandFreeze = migration.Find(beadsDir)
if !useReadOnly {
- CheckMigrationFreeze(strings.TrimPrefix(cmd.CommandPath(), cmd.Root().Name()+" "))
+ if err := migrationFreezeGate(cmd, strings.TrimPrefix(cmd.CommandPath(), cmd.Root().Name()+" "), commandFreeze); err != nil {
+ return err
+ }
}
// dc-6jaq (review round 2, ask #1): a command classified read-only —
@@ -1454,14 +1478,12 @@ var rootCmd = &cobra.Command{
// writes against the (possibly frozen) store, run regardless of the
// command's own classification — so "the command is a read" must not
// imply "these side effects may still run". Reproduced pre-fix:
- // freeze the town, seed .local_version with a stale version, run
+ // freeze the workspace, seed .local_version with a stale version, run
// `bd list` — exit 0 (correct, it's a read), but .local_version was
// silently rewritten mid-freeze anyway. Skip both calls under an
- // active freeze without blocking the read itself. Short-circuits on
- // !policy.runMaintenance (strict --readonly) so the IsFrozen/
- // findTownRoot filesystem walk isn't paid on that path, where these
- // calls are already skipped for an unrelated reason.
- frozenForMaintenance := policy.runMaintenance && migration.IsFrozen(findTownRoot())
+ // active freeze without blocking the read itself. Reuses the single
+ // lookup resolved above rather than repeating the walk.
+ frozenForMaintenance := policy.runMaintenance && commandFreeze.Frozen()
// Track bd version changes unless strict readonly forbids repository mutation.
// Best-effort tracking - failures are silent.
@@ -1870,7 +1892,16 @@ var rootCmd = &cobra.Command{
uowProvider = nil
}
} else {
- if runsPostCommandMaintenance(cmd.Name(), readonlyMode) {
+ // dc-6jaq: the freeze covers this hook's own writes too. A read is
+ // allowed through a freeze, but the maintenance that trails it is
+ // not the user's command — auto-commit, the tip_*_last_shown
+ // metadata write and its separate Dolt commit, auto-backup,
+ // auto-export and auto-push all mutate the very store being
+ // migrated, and `bd list` on a frozen workspace reaches every one
+ // of them. Guarding the outer block keeps that promise in one
+ // place instead of six. Writes never get here at all: they were
+ // refused in PersistentPreRunE.
+ if runsPostCommandMaintenance(cmd.Name(), readonlyMode) && !commandFreeze.Frozen() {
// Dolt auto-commit: after a successful write command (and after final flush),
// create a Dolt commit so changes don't remain only in the working set.
if commandDidWrite.Load() && !commandDidExplicitDoltCommit {
diff --git a/cmd/bd/memory.go b/cmd/bd/memory.go
index dd1501fbf..ef4746358 100644
--- a/cmd/bd/memory.go
+++ b/cmd/bd/memory.go
@@ -257,7 +257,7 @@ Examples:
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
- CheckReadonly("remember") // also covers CheckMigrationFreeze (dc-6jaq)
+ CheckReadonly("remember") // also covers the migration freeze check (dc-6jaq)
evt := metrics.NewCommandEvent("remember")
defer func() {
diff --git a/cmd/bd/migration_freeze_gate_test.go b/cmd/bd/migration_freeze_gate_test.go
index 9b6e3c362..ae74990a1 100644
--- a/cmd/bd/migration_freeze_gate_test.go
+++ b/cmd/bd/migration_freeze_gate_test.go
@@ -1,6 +1,7 @@
-// Tests for the MIGRATION-FREEZE write gate (dc-6jaq): bd write commands must
-// refuse to run while a MIGRATION-FREEZE sentinel sits at the town root, the
-// same gate the gt CLI already applies to gt mail send/nudge/sling/assign.
+// Tests for the migration freeze write gate (dc-6jaq): bd write commands must
+// refuse to run, with exit code ExitMigrationFrozen, while a MIGRATION-FREEZE
+// marker sits in the working directory or any ancestor of it — or at the path
+// named by BD_MIGRATION_FREEZE_FILE, which is authoritative when set.
//
// This file MUST NOT carry a cgo build tag: it exercises the default sqlite
// backend via a bd binary built with the gms_pure_go tag (mirrors
@@ -10,6 +11,7 @@ package main
import (
"bytes"
+ "context"
"encoding/json"
"errors"
"os"
@@ -17,17 +19,46 @@ import (
"path/filepath"
"strings"
"testing"
+
+ "github.com/steveyegge/beads/internal/migration"
)
+// vendorNeutralBans are substrings the refusal must never print. The gate used
+// to key on a gastown town root and tell users to run `gt migrate thaw`, a CLI
+// that does not ship with bd; nothing about the OSS binary's write refusal may
+// name another vendor's product again.
+var vendorNeutralBans = []string{"gt ", "gt migrate", "thaw", "town", "mayor", "GT_"}
+
+func assertVendorNeutral(t *testing.T, stderr string) {
+ t.Helper()
+ for _, banned := range vendorNeutralBans {
+ if strings.Contains(stderr, banned) {
+ t.Errorf("refusal contains vendor-coupled substring %q:\n%s", banned, stderr)
+ }
+ }
+}
+
// migrationFreezeEnv returns a hermetic environment for bd subprocess runs:
-// no inherited BEADS_* variables, HOME pinned to the test dir, metrics and
+// no inherited BEADS_*/GT_* variables, HOME pinned to the test dir, metrics and
// daemons disabled.
+//
+// The freeze override is pinned to a path that cannot exist, not merely
+// stripped. Because the gate walks every ancestor to the filesystem root, a
+// stray MIGRATION-FREEZE anywhere above TMPDIR would otherwise fail these
+// tests at `bd init` — and the pin is authoritative, so it also holds the walk
+// off while a test is setting its workspace up. Tests that actually exercise
+// the walk layer freezeWalkEnv on top. (TestMain pins the same variable for
+// the whole package, since the walk makes every write-subprocess suite here
+// equally sensitive to an ambient marker; this is the belt to that's braces.)
func migrationFreezeEnv(dir string) []string {
var env []string
for _, e := range os.Environ() {
if strings.HasPrefix(e, "BEADS_") || strings.HasPrefix(e, "GT_") {
continue
}
+ if strings.HasPrefix(e, migration.EnvFreezeFile+"=") {
+ continue
+ }
env = append(env, e)
}
return append(env,
@@ -38,9 +69,22 @@ func migrationFreezeEnv(dir string) []string {
"BD_DISABLE_EVENT_FLUSH=1",
"BEADS_NO_DAEMON=1",
"BEADS_DOLT_AUTO_START=0",
+ migration.EnvFreezeFile+"="+filepath.Join(dir, "no-such-freeze-marker"),
)
}
+// freezeWalkEnv clears the override so the subprocess uses the ancestor walk.
+func freezeWalkEnv() []string {
+ return []string{migration.EnvFreezeFile + "="}
+}
+
+// runBDFrozen runs bd with the ancestor walk enabled — the mode every
+// marker-on-disk test needs.
+func runBDFrozen(t *testing.T, bd, dir string, args ...string) (stdout, stderr string, exitCode int) {
+ t.Helper()
+ return runBDMigrationFreezeWithEnv(t, bd, dir, freezeWalkEnv(), args...)
+}
+
// runBDMigrationFreeze runs the bd binary and returns stdout, stderr, and the
// exit code. Only a failure to launch the process fails the test; nonzero
// exits are returned to the caller for assertion.
@@ -70,62 +114,65 @@ func runBDMigrationFreezeWithEnv(t *testing.T, bd, dir string, extraEnv []string
return outBuf.String(), errBuf.String(), 0
}
-// setupMigrationFreezeWorkspace builds bd and initializes a fresh sqlite-
-// backed database in a temp dir that also carries mayor/town.json, so the
-// same directory doubles as a bd workspace and a fake town root — findTownRoot
-// finds it at walk-up distance 0.
-func setupMigrationFreezeWorkspace(t *testing.T) (bd, dir string) {
+// setupMigrationFreezeWorkspaceIn builds bd and initializes a fresh sqlite-
+// backed database in dir. The workspace needs nothing but itself: the gate
+// keys on the freeze marker file, not on any orchestrator structure around it.
+func setupMigrationFreezeWorkspaceIn(t *testing.T, dir string) (bd string) {
t.Helper()
bd = buildBDForInitTests(t)
- dir = t.TempDir()
runGitForBootstrapTest(t, dir, "init", "-q")
runGitForBootstrapTest(t, dir, "config", "core.hooksPath", ".git/hooks")
- if err := os.MkdirAll(filepath.Join(dir, "mayor"), 0755); err != nil {
- t.Fatalf("creating mayor dir: %v", err)
- }
- if err := os.WriteFile(filepath.Join(dir, "mayor", "town.json"), []byte("{}"), 0644); err != nil {
- t.Fatalf("writing mayor/town.json: %v", err)
- }
-
stdout, stderr, code := runBDMigrationFreeze(t, bd, dir,
"init", "--prefix", "test", "--quiet", "--non-interactive", "--skip-hooks", "--skip-agents")
if code != 0 {
t.Fatalf("bd init failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
- return bd, dir
+ return bd
}
-// freezeTown writes a MIGRATION-FREEZE sentinel at dir (the fake town root).
-func freezeTown(t *testing.T, dir, operator, reason string) {
+func setupMigrationFreezeWorkspace(t *testing.T) (bd, dir string) {
t.Helper()
+ dir = t.TempDir()
+ return setupMigrationFreezeWorkspaceIn(t, dir), dir
+}
+
+// writeFreezeMarker writes a MIGRATION-FREEZE marker in dir and returns its path.
+func writeFreezeMarker(t *testing.T, dir, operator, reason string) string {
+ t.Helper()
+ path := filepath.Join(dir, migration.FileName)
content := operator + "\t2026-08-16T12:00:00Z\t" + reason + "\n"
- if err := os.WriteFile(filepath.Join(dir, "MIGRATION-FREEZE"), []byte(content), 0644); err != nil {
- t.Fatalf("writing MIGRATION-FREEZE: %v", err)
+ if err := os.WriteFile(path, []byte(content), 0644); err != nil {
+ t.Fatalf("writing %s: %v", path, err)
}
+ return path
}
func TestCreateBlockedDuringMigrationFreeze(t *testing.T) {
bd, dir := setupMigrationFreezeWorkspace(t)
- freezeTown(t, dir, "mayor", "dolt v2 migration")
+ writeFreezeMarker(t, dir, "migrator", "dolt v2 migration")
- stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "create", "should not be created", "-p", "2")
+ stdout, stderr, code := runBDFrozen(t, bd, dir, "create", "should not be created", "-p", "2")
- if code != 1 {
- t.Fatalf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr)
}
- if !strings.Contains(stderr, "frozen for migration") {
- t.Errorf("stderr missing 'frozen for migration':\n%s", stderr)
- }
- if !strings.Contains(stderr, "mayor") {
- t.Errorf("stderr missing operator 'mayor':\n%s", stderr)
- }
- if !strings.Contains(stderr, "dolt v2 migration") {
- t.Errorf("stderr missing reason 'dolt v2 migration':\n%s", stderr)
- }
- if !strings.Contains(stderr, "gt migrate thaw") {
- t.Errorf("stderr missing recovery hint 'gt migrate thaw':\n%s", stderr)
+ for _, want := range []string{
+ "workspace is frozen for migration",
+ "migrator",
+ "dolt v2 migration",
+ // The marker's real path, not just its name: that is what makes
+ // "remove that file" actionable. Matched from the workspace
+ // directory's own name down, so a symlinked temp root (macOS
+ // /var → /private/var) doesn't fail the assertion.
+ filepath.Join(filepath.Base(dir), migration.FileName),
+ "To resume writes, remove that file",
+ } {
+ if !strings.Contains(stderr, want) {
+ t.Errorf("stderr missing %q:\n%s", want, stderr)
+ }
}
+ assertVendorNeutral(t, stderr)
if strings.TrimSpace(stdout) != "" {
t.Errorf("stdout should be empty when blocked, got:\n%s", stdout)
}
@@ -146,26 +193,222 @@ func TestUpdateBlockedDuringMigrationFreeze(t *testing.T) {
t.Fatalf("parsing create --json output: %v\n%s", err, stdout)
}
- freezeTown(t, dir, "athos", "server migration in progress")
+ writeFreezeMarker(t, dir, "athos", "server migration in progress")
- stdout, stderr, code = runBDMigrationFreeze(t, bd, dir, "update", issue.ID, "-p", "1")
- if code != 1 {
- t.Fatalf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
+ stdout, stderr, code = runBDFrozen(t, bd, dir, "update", issue.ID, "-p", "1")
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr)
}
- if !strings.Contains(stderr, "frozen for migration") {
- t.Errorf("stderr missing 'frozen for migration':\n%s", stderr)
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing 'workspace is frozen for migration':\n%s", stderr)
+ }
+}
+
+// TestWriteBlockedByAncestorFreezeMarker is the vendor-neutrality change made
+// observable: the marker sits in the workspace's PARENT, with no orchestrator
+// structure anywhere, and still freezes writes. That is exactly the shape of a
+// marker written above a set of sibling repos.
+func TestWriteBlockedByAncestorFreezeMarker(t *testing.T) {
+ root := t.TempDir()
+ work := filepath.Join(root, "repo")
+ if err := os.MkdirAll(work, 0755); err != nil {
+ t.Fatalf("creating %s: %v", work, err)
+ }
+ bd := setupMigrationFreezeWorkspaceIn(t, work)
+ writeFreezeMarker(t, root, "migrator", "tree-wide migration")
+
+ stdout, stderr, code := runBDFrozen(t, bd, work, "create", "should not be created", "-p", "2")
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d (marker one level above the workspace)\nstdout:\n%s\nstderr:\n%s",
+ code, ExitMigrationFrozen, stdout, stderr)
+ }
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing 'workspace is frozen for migration':\n%s", stderr)
+ }
+ assertVendorNeutral(t, stderr)
+}
+
+// TestMigrationFreezeFileEnvOverride pins both directions of
+// BD_MIGRATION_FREEZE_FILE: set to an existing file it freezes a workspace
+// with no marker anywhere above it, and set to a missing path it does NOT
+// freeze even with a marker right there — that second half is what makes the
+// variable a usable opt-out.
+func TestMigrationFreezeFileEnvOverride(t *testing.T) {
+ bd, dir := setupMigrationFreezeWorkspace(t)
+ elsewhere := t.TempDir()
+ override := filepath.Join(elsewhere, "freeze-marker")
+ if err := os.WriteFile(override, []byte("migrator\t2026-08-16T12:00:00Z\tout-of-tree freeze\n"), 0644); err != nil {
+ t.Fatalf("writing override marker: %v", err)
+ }
+
+ t.Run("existing override file blocks with no marker in the tree", func(t *testing.T) {
+ stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir,
+ []string{migration.EnvFreezeFile + "=" + override},
+ "create", "should not be created", "-p", "2")
+
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr)
+ }
+ for _, want := range []string{
+ "workspace is frozen for migration",
+ "out-of-tree freeze",
+ override,
+ "or unset " + migration.EnvFreezeFile,
+ } {
+ if !strings.Contains(stderr, want) {
+ t.Errorf("stderr missing %q:\n%s", want, stderr)
+ }
+ }
+ assertVendorNeutral(t, stderr)
+ })
+
+ t.Run("missing override file wins over a marker in the workspace", func(t *testing.T) {
+ writeFreezeMarker(t, dir, "migrator", "should be ignored")
+ t.Cleanup(func() { _ = os.Remove(filepath.Join(dir, migration.FileName)) })
+
+ stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir,
+ []string{migration.EnvFreezeFile + "=" + filepath.Join(elsewhere, "no-such-marker")},
+ "create", "normal issue", "-p", "2", "--json")
+
+ if code != 0 {
+ t.Fatalf("exit code = %d, want 0 — the override must skip the ancestor walk entirely\nstdout:\n%s\nstderr:\n%s",
+ code, stdout, stderr)
+ }
+ })
+}
+
+// TestFreezeKeysOnTargetWorkspaceNotCwd is the core-contract test: the gate
+// must follow the store being written, not the shell the caller happens to be
+// sitting in. Both shapes here target a frozen workspace from an unrelated
+// working directory, and neither one chdirs — `bd -C` only sets BEADS_DIR.
+// Before this, both walked the caller's ancestry, found nothing, and wrote
+// straight through the freeze.
+func TestFreezeKeysOnTargetWorkspaceNotCwd(t *testing.T) {
+ frozenRoot := t.TempDir()
+ work := filepath.Join(frozenRoot, "repo")
+ if err := os.MkdirAll(work, 0755); err != nil {
+ t.Fatalf("creating %s: %v", work, err)
+ }
+ bd := setupMigrationFreezeWorkspaceIn(t, work)
+ writeFreezeMarker(t, frozenRoot, "migrator", "cross-tree migration")
+
+ // The caller's cwd is nowhere near the frozen tree.
+ outside := t.TempDir()
+
+ t.Run("BEADS_DIR", func(t *testing.T) {
+ stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, outside,
+ append(freezeWalkEnv(), "BEADS_DIR="+filepath.Join(work, ".beads")),
+ "create", "should not be created", "-p", "2")
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d — BEADS_DIR named a frozen workspace\nstdout:\n%s\nstderr:\n%s",
+ code, ExitMigrationFrozen, stdout, stderr)
+ }
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing the refusal:\n%s", stderr)
+ }
+ })
+
+ t.Run("-C", func(t *testing.T) {
+ stdout, stderr, code := runBDFrozen(t, bd, outside,
+ "-C", work, "create", "should not be created", "-p", "2")
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d — -C named a frozen workspace\nstdout:\n%s\nstderr:\n%s",
+ code, ExitMigrationFrozen, stdout, stderr)
+ }
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing the refusal:\n%s", stderr)
+ }
+ })
+}
+
+// TestInitReinitBlockedDuringMigrationFreeze covers the skip-store bypass, the
+// sharpest hole of the lot: `init` is in noDbCommands, so PersistentPreRunE
+// returns before its freeze gate, and init.go calls neither CheckReadonly nor
+// the gate. `bd init --reinit-local` therefore destroyed and recreated the
+// very database the marker was protecting — permanently, exit 0, marker never
+// consulted.
+func TestInitReinitBlockedDuringMigrationFreeze(t *testing.T) {
+ bd, dir := setupMigrationFreezeWorkspace(t)
+
+ stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "create", "issue that must survive", "-p", "2", "--json")
+ if code != 0 {
+ t.Fatalf("setup bd create failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
+ }
+ var issue struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal([]byte(stdout), &issue); err != nil || issue.ID == "" {
+ t.Fatalf("parsing create --json output: %v\n%s", err, stdout)
+ }
+
+ writeFreezeMarker(t, dir, "migrator", "dolt v2 migration")
+
+ stdout, stderr, code = runBDFrozen(t, bd, dir,
+ "init", "--prefix", "test", "--reinit-local", "--non-interactive", "--quiet", "--skip-hooks", "--skip-agents")
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d — a destructive reinit must not run during a freeze\nstdout:\n%s\nstderr:\n%s",
+ code, ExitMigrationFrozen, stdout, stderr)
+ }
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing the refusal:\n%s", stderr)
+ }
+ assertVendorNeutral(t, stderr)
+
+ // The database must still be there, with its issue in it.
+ if err := os.Remove(filepath.Join(dir, migration.FileName)); err != nil {
+ t.Fatalf("removing freeze marker: %v", err)
+ }
+ stdout, stderr, code = runBDMigrationFreeze(t, bd, dir, "show", issue.ID, "--json")
+ if code != 0 {
+ t.Fatalf("bd show after the refused reinit failed (exit %d) — the data was destroyed anyway:\nstdout:\n%s\nstderr:\n%s",
+ code, stdout, stderr)
+ }
+}
+
+// TestFreezeRefusalHasNoUsageDump: the refusal is returned as an error now, so
+// cobra renders it — and on a command that sets neither SilenceErrors nor
+// SilenceUsage (duplicate, supersede, dep relate/unrelate, backup *, ado sync,
+// migrate-personal, batch) that means "Error: exit code 14" plus a full usage
+// block after the clean refusal, making it read like a syntax error. Every
+// other freeze test uses a silenced command, so nothing else catches this.
+func TestFreezeRefusalHasNoUsageDump(t *testing.T) {
+ bd, dir := setupMigrationFreezeWorkspace(t)
+ writeFreezeMarker(t, dir, "migrator", "dolt v2 migration")
+
+ for _, tc := range []struct {
+ name string
+ args []string
+ }{
+ {name: "duplicate", args: []string{"duplicate", "test-aaaa", "--of", "test-bbbb"}},
+ {name: "relate", args: []string{"dep", "relate", "test-aaaa", "test-bbbb"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ stdout, stderr, code := runBDFrozen(t, bd, dir, tc.args...)
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr)
+ }
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Fatalf("stderr missing the refusal:\n%s", stderr)
+ }
+ if strings.Contains(stderr, "exit code 14") {
+ t.Errorf("cobra printed the exitError placeholder after the refusal:\n%s", stderr)
+ }
+ if strings.Contains(stderr, "Usage:") || strings.Contains(stdout, "Usage:") {
+ t.Errorf("cobra dumped usage after a clean refusal — it reads as a syntax error:\nstdout:\n%s\nstderr:\n%s", stdout, stderr)
+ }
+ })
}
}
// TestCreateNotBlockedWithoutFreeze is the regression-safety check: normal bd
-// usage (no MIGRATION-FREEZE sentinel present, the overwhelming common case)
-// must be completely unaffected by this gate.
+// usage (no freeze marker present, the overwhelming common case) must be
+// completely unaffected by this gate.
func TestCreateNotBlockedWithoutFreeze(t *testing.T) {
bd, dir := setupMigrationFreezeWorkspace(t)
stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "create", "normal issue", "-p", "2", "--json")
if code != 0 {
- t.Fatalf("bd create failed (exit %d) with no freeze sentinel present:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
+ t.Fatalf("bd create failed (exit %d) with no freeze marker present:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
var issue struct {
ID string `json:"id"`
@@ -178,6 +421,269 @@ func TestCreateNotBlockedWithoutFreeze(t *testing.T) {
}
}
+// TestWorkspaceUsableAfterMigrationFreezeBlockedWrite is the end-to-end half of the
+// defer-skip fix (see TestMigrationFreezeErrorReturnsInsteadOfExiting for the
+// direct proof). The root PersistentPreRunE takes the workspace and
+// physical-root gates and closes the store before releasing them in a defer;
+// the freeze refusal used to os.Exit straight through that defer. A workspace
+// must be immediately usable after a blocked write.
+func TestWorkspaceUsableAfterMigrationFreezeBlockedWrite(t *testing.T) {
+ bd, dir := setupMigrationFreezeWorkspace(t)
+ marker := writeFreezeMarker(t, dir, "migrator", "dolt v2 migration")
+
+ stdout, stderr, code := runBDFrozen(t, bd, dir, "create", "should not be created", "-p", "2")
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr)
+ }
+
+ if err := os.Remove(marker); err != nil {
+ t.Fatalf("removing freeze marker: %v", err)
+ }
+
+ stdout, stderr, code = runBDMigrationFreeze(t, bd, dir, "create", "post-thaw issue", "-p", "2", "--json")
+ if code != 0 {
+ t.Fatalf("bd create after the freeze was lifted failed (exit %d) — the blocked run left the workspace wedged:\nstdout:\n%s\nstderr:\n%s",
+ code, stdout, stderr)
+ }
+}
+
+// TestMigrationFreezeErrorReturnsInsteadOfExiting is the direct regression
+// test for the defer-skip bug: migrationFreezeError must RETURN its refusal so
+// callers that hold live cleanup (the root PersistentPreRunE closes the store
+// and releases the workspace gates from a defer; runImport finalizes its
+// metrics event) still run it. If the function ever goes back to os.Exit, this
+// test binary dies mid-run and the whole package fails — which is the point.
+func TestMigrationFreezeErrorReturnsInsteadOfExiting(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, migration.FileName),
+ []byte("migrator\t2026-08-16T12:00:00Z\tschema move\n"), 0644); err != nil {
+ t.Fatalf("writing freeze marker: %v", err)
+ }
+ t.Chdir(dir)
+ t.Setenv(migration.EnvFreezeFile, "") // unset: exercise the ancestor walk
+
+ // The shape of the PersistentPreRunE call site: a named return with a
+ // deferred cleanup that only fires on the error path.
+ cleanupRan := false
+ var gateErr error
+ stderr := captureStderr(t, func() {
+ gateErr = func() (retErr error) {
+ defer func() {
+ if retErr != nil {
+ cleanupRan = true
+ }
+ }()
+ return migrationFreezeError("create")
+ }()
+ })
+
+ if gateErr == nil {
+ t.Fatalf("migrationFreezeError returned nil with a freeze marker in the working directory")
+ }
+ if !cleanupRan {
+ t.Errorf("the caller's deferred cleanup did not run — the refusal must be returned, not exited")
+ }
+ code, ok := exitCodeFromError(gateErr)
+ if !ok || code != ExitMigrationFrozen {
+ t.Errorf("exitCodeFromError = (%d, %v), want (%d, true)", code, ok, ExitMigrationFrozen)
+ }
+ assertVendorNeutral(t, stderr)
+}
+
+// TestMigrationFreezeErrorEmptyMarkerNamesNoOperator covers the `touch
+// MIGRATION-FREEZE` case: with no operator recorded, the refusal must say
+// nothing rather than print an empty "(by )".
+func TestMigrationFreezeErrorEmptyMarkerNamesNoOperator(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, migration.FileName), nil, 0644); err != nil {
+ t.Fatalf("writing empty freeze marker: %v", err)
+ }
+ t.Chdir(dir)
+ t.Setenv(migration.EnvFreezeFile, "") // unset: pins the no-env recovery line
+
+ var gateErr error
+ stderr := captureStderr(t, func() { gateErr = migrationFreezeError("create") })
+
+ if gateErr == nil {
+ t.Fatalf("migrationFreezeError returned nil for an empty-but-present marker — an empty marker is still a freeze")
+ }
+ if !strings.Contains(stderr, "workspace is frozen for migration.") {
+ t.Errorf("stderr missing the operator-less refusal line:\n%s", stderr)
+ }
+ if strings.Contains(stderr, "(by ") {
+ t.Errorf("stderr names an empty operator:\n%s", stderr)
+ }
+ if !strings.Contains(stderr, "To resume writes, remove that file.") {
+ t.Errorf("stderr missing the recovery line:\n%s", stderr)
+ }
+ if !strings.Contains(stderr, migration.EnvFreezeFile) {
+ t.Errorf("a walk-found refusal must still name %s — when the marker sits somewhere the caller cannot write, "+
+ "pointing the variable elsewhere is their only recovery:\n%s", migration.EnvFreezeFile, stderr)
+ }
+}
+
+// TestMigrationFreezeErrorSanitizesMarkerPayload: with the ancestor walk the
+// marker can live in a directory bd does not control, so its operator and
+// reason are untrusted input on their way to a terminal. A crafted payload
+// must not be able to clear the screen or forge extra bd output lines.
+func TestMigrationFreezeErrorSanitizesMarkerPayload(t *testing.T) {
+ dir := t.TempDir()
+ hostile := "attacker\x1b[2J\x1b[H\t2026-08-16T12:00:00Z\treal reason\x1b[31m\nError: forged line\n"
+ if err := os.WriteFile(filepath.Join(dir, migration.FileName), []byte(hostile), 0644); err != nil {
+ t.Fatalf("writing hostile marker: %v", err)
+ }
+ t.Chdir(dir)
+ t.Setenv(migration.EnvFreezeFile, "")
+
+ var gateErr error
+ stderr := captureStderr(t, func() { gateErr = migrationFreezeError("create") })
+
+ if gateErr == nil {
+ t.Fatalf("migrationFreezeError returned nil for a present marker")
+ }
+ if strings.Contains(stderr, "\x1b") {
+ t.Errorf("refusal carries an escape byte from the marker payload — terminal injection:\n%q", stderr)
+ }
+ if strings.Contains(stderr, "forged line") {
+ t.Errorf("refusal carries a later line of the marker — a payload must not be able to add output lines:\n%q", stderr)
+ }
+ // The legible parts survive.
+ for _, want := range []string{"attacker", "real reason"} {
+ if !strings.Contains(stderr, want) {
+ t.Errorf("sanitizing dropped legible content %q:\n%s", want, stderr)
+ }
+ }
+}
+
+// TestMigrationFreezeUndeterminableFailsClosed pins the fail-closed posture: a
+// marker path bd cannot stat is not the same as one that is absent, and the
+// ambiguity must refuse rather than silently disarm the gate.
+func TestMigrationFreezeUndeterminableFailsClosed(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("running as root: permission bits do not deny the stat")
+ }
+ locked := filepath.Join(t.TempDir(), "locked")
+ if err := os.Mkdir(locked, 0755); err != nil {
+ t.Fatalf("creating %s: %v", locked, err)
+ }
+ marker := filepath.Join(locked, migration.FileName)
+ if err := os.WriteFile(marker, nil, 0644); err != nil {
+ t.Fatalf("writing marker: %v", err)
+ }
+ if err := os.Chmod(locked, 0000); err != nil {
+ t.Fatalf("chmod: %v", err)
+ }
+ t.Cleanup(func() { _ = os.Chmod(locked, 0755) })
+ t.Setenv(migration.EnvFreezeFile, marker)
+
+ var gateErr error
+ stderr := captureStderr(t, func() { gateErr = migrationFreezeError("create") })
+
+ if gateErr == nil {
+ t.Fatalf("migrationFreezeError returned nil for an unstattable authoritative marker — that is a silent bypass")
+ }
+ code, ok := exitCodeFromError(gateErr)
+ if !ok || code != ExitMigrationFrozen {
+ t.Errorf("exitCodeFromError = (%d, %v), want (%d, true)", code, ok, ExitMigrationFrozen)
+ }
+ if !strings.Contains(stderr, "cannot determine") {
+ t.Errorf("the refusal must say bd could not tell, not claim a freeze it did not observe:\n%s", stderr)
+ }
+ assertVendorNeutral(t, stderr)
+}
+
+// TestRecordTipShownSkippedDuringFreeze covers the PostRunE maintenance half of
+// the freeze promise at its one immediate-write site: with dolt auto-commit
+// off, recordTipShown writes tip_*_last_shown to the store the moment a tip is
+// displayed rather than deferring to PersistentPostRunE, so the guard there
+// does not cover it. Showing a tip must never write into a frozen workspace.
+func TestRecordTipShownSkippedDuringFreeze(t *testing.T) {
+ // These are the same process globals PersistentPostRunE reads to decide
+ // whether to apply a deferred tip write, and a later test in this package
+ // invokes that hook with no store open. Restore all three or this test
+ // hands it a pending write and a nil store to dereference.
+ savedFreeze, savedFlag, savedIDs := commandFreeze, commandDidWriteTipMetadata, commandTipIDsShown
+ t.Cleanup(func() {
+ commandFreeze, commandDidWriteTipMetadata, commandTipIDsShown = savedFreeze, savedFlag, savedIDs
+ })
+
+ // recordTipShown has two branches: with dolt auto-commit on it records the
+ // write for PostRunE to apply, otherwise it writes immediately. A freeze
+ // has to stop both, so assert on both signals rather than on whichever
+ // branch this process's resolved config happens to select.
+ reset := func() *fakeTipMetadataWriter {
+ commandDidWriteTipMetadata = false
+ commandTipIDsShown = make(map[string]struct{})
+ return &fakeTipMetadataWriter{}
+ }
+ recorded := func(w *fakeTipMetadataWriter) bool {
+ return w.calls > 0 || commandDidWriteTipMetadata || len(commandTipIDsShown) > 0
+ }
+
+ frozen := reset()
+ commandFreeze = migration.Result{Path: filepath.Join(t.TempDir(), migration.FileName)}
+ recordTipShown(frozen, "some-tip")
+ if recorded(frozen) {
+ t.Errorf("recordTipShown recorded a tip write during a freeze (calls=%d, pending=%v, ids=%d)",
+ frozen.calls, commandDidWriteTipMetadata, len(commandTipIDsShown))
+ }
+
+ thawed := reset()
+ commandFreeze = migration.Result{}
+ recordTipShown(thawed, "some-tip")
+ if !recorded(thawed) {
+ t.Errorf("recordTipShown recorded nothing with no freeze active — the guard must not be unconditional")
+ }
+}
+
+// TestMigrationFreezeProbeAndTargetedGate pins the two entry points that exist
+// for callers outside PersistentPreRunE: the silent probe used by diagnosis
+// paths that must keep running while frozen but skip their own writes, and the
+// targeted refusal for a command handed a workspace other than the one it was
+// launched in (`bd doctor /frozen/repo`). Both must agree with the gate.
+func TestMigrationFreezeProbeAndTargetedGate(t *testing.T) {
+ unrelated := t.TempDir()
+ frozenRoot := t.TempDir()
+ writeFreezeMarker(t, frozenRoot, "migrator", "cross-tree migration")
+ target := filepath.Join(frozenRoot, "repo")
+ if err := os.MkdirAll(target, 0755); err != nil {
+ t.Fatalf("creating %s: %v", target, err)
+ }
+ t.Chdir(unrelated)
+ t.Setenv(migration.EnvFreezeFile, "")
+ t.Setenv("BEADS_DIR", "")
+
+ if migrationFreezeActive() {
+ t.Errorf("migrationFreezeActive() = true with an unrelated cwd and no marker above it")
+ }
+
+ var gateErr error
+ stderr := captureStderr(t, func() { gateErr = migrationFreezeErrorFor("doctor --fix", target) })
+ if gateErr == nil {
+ t.Fatalf("migrationFreezeErrorFor returned nil for a frozen target — a named workspace must be checked")
+ }
+ code, ok := exitCodeFromError(gateErr)
+ if !ok || code != ExitMigrationFrozen {
+ t.Errorf("exitCodeFromError = (%d, %v), want (%d, true)", code, ok, ExitMigrationFrozen)
+ }
+ if !strings.Contains(stderr, "doctor --fix") {
+ t.Errorf("refusal does not name the operation it was given:\n%s", stderr)
+ }
+
+ // The probe agrees once the frozen tree is the one bd resolved.
+ t.Chdir(target)
+ if !migrationFreezeActive() {
+ t.Errorf("migrationFreezeActive() = false inside a frozen tree")
+ }
+}
+
+type fakeTipMetadataWriter struct{ calls int }
+
+func (f *fakeTipMetadataWriter) SetLocalMetadata(_ context.Context, _, _ string) error {
+ f.calls++
+ return nil
+}
+
// TestQuickBlockedDuringMigrationFreeze regression-checks the sharpest gap
// flagged in review of the original gate (dc-6jaq, PR #5826): the gate
// hand-picked five commands (create, update, close, remember, import), but
@@ -188,14 +694,14 @@ func TestCreateNotBlockedWithoutFreeze(t *testing.T) {
// automatically, "q" included.
func TestQuickBlockedDuringMigrationFreeze(t *testing.T) {
bd, dir := setupMigrationFreezeWorkspace(t)
- freezeTown(t, dir, "mayor", "dolt v2 migration")
+ writeFreezeMarker(t, dir, "migrator", "dolt v2 migration")
- stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "q", "should not be created")
- if code != 1 {
- t.Fatalf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
+ stdout, stderr, code := runBDFrozen(t, bd, dir, "q", "should not be created")
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr)
}
- if !strings.Contains(stderr, "frozen for migration") {
- t.Errorf("stderr missing 'frozen for migration':\n%s", stderr)
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing 'workspace is frozen for migration':\n%s", stderr)
}
if strings.TrimSpace(stdout) != "" {
t.Errorf("stdout should be empty when blocked, got:\n%s", stdout)
@@ -220,14 +726,54 @@ func TestLabelAddBlockedDuringMigrationFreeze(t *testing.T) {
t.Fatalf("parsing create --json output: %v\n%s", err, stdout)
}
- freezeTown(t, dir, "mayor", "dolt v2 migration")
+ writeFreezeMarker(t, dir, "migrator", "dolt v2 migration")
- stdout, stderr, code = runBDMigrationFreeze(t, bd, dir, "label", "add", issue.ID, "should-not-be-added")
- if code != 1 {
- t.Fatalf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
+ stdout, stderr, code = runBDFrozen(t, bd, dir, "label", "add", issue.ID, "should-not-be-added")
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr)
}
- if !strings.Contains(stderr, "frozen for migration") {
- t.Errorf("stderr missing 'frozen for migration':\n%s", stderr)
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing 'workspace is frozen for migration':\n%s", stderr)
+ }
+}
+
+// TestImportBlockedDuringMigrationFreeze covers bd import both ways round.
+//
+// Plain `bd import` is stopped by the early gate in PersistentPreRunE, like
+// any other write. The `--dry-run` row is the one that pins runImport's OWN
+// call: a preview sets useReadOnly, so it skips the early gate, and runImport
+// never calls CheckReadonly — delete the check from import.go and only this
+// row goes red. It also pins the claim the PreRunE comment makes about
+// previews being re-blocked at the per-command chokepoint, which for import is
+// exactly that call and nothing else.
+func TestImportBlockedDuringMigrationFreeze(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ args []string
+ }{
+ {name: "import", args: []string{"import"}},
+ {name: "import --dry-run", args: []string{"import", "--dry-run"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ bd, dir := setupMigrationFreezeWorkspace(t)
+ jsonlPath := filepath.Join(dir, "incoming.jsonl")
+ if err := os.WriteFile(jsonlPath,
+ []byte(`{"id":"test-zzzz","title":"should not be imported","status":"open","priority":2,"issue_type":"task"}`+"\n"),
+ 0644); err != nil {
+ t.Fatalf("writing import fixture: %v", err)
+ }
+ writeFreezeMarker(t, dir, "migrator", "dolt v2 migration")
+
+ args := append(append([]string{}, tc.args...), jsonlPath)
+ stdout, stderr, code := runBDFrozen(t, bd, dir, args...)
+ if code != ExitMigrationFrozen {
+ t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr)
+ }
+ if !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing 'workspace is frozen for migration':\n%s", stderr)
+ }
+ assertVendorNeutral(t, stderr)
+ })
}
}
@@ -251,7 +797,7 @@ func TestLabelAddBlockedDuringMigrationFreeze(t *testing.T) {
// freeze — exit 0, no refusal), but the same two maintenance side effects
// must still be skipped, because they are this hook's own writes and run
// independently of the command's classification. Reproduced pre-fix:
-// freeze the town, seed .local_version with a stale version, run
+// freeze the workspace, seed .local_version with a stale version, run
// `BD_DEBUG=1 bd list` — exit 0, but the "auto-migrate:" line appeared and
// .local_version was rewritten to the current version anyway.
func TestAutoMigrateSkippedDuringMigrationFreeze(t *testing.T) {
@@ -261,7 +807,7 @@ func TestAutoMigrateSkippedDuringMigrationFreeze(t *testing.T) {
wantExit int
wantBlocked bool
}{
- {name: "create", args: []string{"create", "should not be created", "-p", "2"}, wantExit: 1, wantBlocked: true},
+ {name: "create", args: []string{"create", "should not be created", "-p", "2"}, wantExit: ExitMigrationFrozen, wantBlocked: true},
{name: "list", args: []string{"list"}, wantExit: 0, wantBlocked: false},
}
@@ -274,15 +820,15 @@ func TestAutoMigrateSkippedDuringMigrationFreeze(t *testing.T) {
t.Fatalf("writing fake old %s: %v", localVersionFile, err)
}
- freezeTown(t, dir, "mayor", "dolt v2 migration")
+ writeFreezeMarker(t, dir, "migrator", "dolt v2 migration")
- stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, []string{"BD_DEBUG=1"}, tt.args...)
+ stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, append(freezeWalkEnv(), "BD_DEBUG=1"), tt.args...)
if code != tt.wantExit {
t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, tt.wantExit, stdout, stderr)
}
- if tt.wantBlocked && !strings.Contains(stderr, "frozen for migration") {
- t.Errorf("stderr missing 'frozen for migration':\n%s", stderr)
+ if tt.wantBlocked && !strings.Contains(stderr, "workspace is frozen for migration") {
+ t.Errorf("stderr missing 'workspace is frozen for migration':\n%s", stderr)
}
if strings.Contains(stderr, "auto-migrate:") {
t.Errorf("autoMigrateOnVersionBump ran its store-opening body during a freeze (found an "+
@@ -306,7 +852,7 @@ func TestAutoMigrateSkippedDuringMigrationFreeze(t *testing.T) {
}
// TestAutoMigrateStillRunsWithoutFreeze is the companion regression-safety
-// check for the ask-#2 fix: without a freeze sentinel, the new early gate in
+// check for the ask-#2 fix: without a freeze marker, the new early gate in
// PersistentPreRunE must not interfere with autoMigrateOnVersionBump's normal
// version-bump reconciliation.
func TestAutoMigrateStillRunsWithoutFreeze(t *testing.T) {
@@ -321,7 +867,7 @@ func TestAutoMigrateStillRunsWithoutFreeze(t *testing.T) {
"create", "normal issue", "-p", "2", "--json")
if code != 0 {
- t.Fatalf("bd create failed (exit %d) with no freeze sentinel present:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
+ t.Fatalf("bd create failed (exit %d) with no freeze marker present:\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if !strings.Contains(stderr, "auto-migrate:") {
t.Errorf("expected autoMigrateOnVersionBump to run (an 'auto-migrate:' debug log line) when not frozen, got none:\nstderr:\n%s", stderr)
diff --git a/cmd/bd/test_repo_beads_guard_test.go b/cmd/bd/test_repo_beads_guard_test.go
index 35c5193eb..5149084b8 100644
--- a/cmd/bd/test_repo_beads_guard_test.go
+++ b/cmd/bd/test_repo_beads_guard_test.go
@@ -11,6 +11,7 @@ import (
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/doltserver"
"github.com/steveyegge/beads/internal/metrics"
+ "github.com/steveyegge/beads/internal/migration"
"github.com/steveyegge/beads/internal/testutil"
)
@@ -139,6 +140,15 @@ func testMainInner(m *testing.M) int {
_ = os.Setenv(metrics.EnvDisableMetrics, "1")
_ = os.Setenv(metrics.EnvDisableEventFlush, "1")
+ // Pin the migration-freeze override to a path that cannot exist (dc-6jaq).
+ // The freeze gate walks every ancestor of the workspace and of the cwd up
+ // to the filesystem root, so a stray MIGRATION-FREEZE above TMPDIR — or in
+ // a developer's home, or exported by their shell — would refuse every
+ // write in every subprocess suite in this package with exit 14. The
+ // override is authoritative, so pinning it here holds the walk off
+ // globally; the freeze tests that need the walk clear it per-run.
+ _ = os.Setenv(migration.EnvFreezeFile, filepath.Join(tmp, "no-such-freeze-marker"))
+
// Also reset viper state that was loaded by main.go's init().
config.ResetForTesting()
diff --git a/cmd/bd/tips.go b/cmd/bd/tips.go
index cd7866591..70a7e7512 100644
--- a/cmd/bd/tips.go
+++ b/cmd/bd/tips.go
@@ -167,6 +167,14 @@ func recordTipShown(store tipMetadataWriter, tipID string) {
return
}
+ // dc-6jaq: with dolt auto-commit off this writes to the store immediately
+ // rather than deferring to PersistentPostRunE, so the freeze guard there
+ // does not cover it. Showing a tip is never worth a write into a workspace
+ // someone is migrating, and the tip itself still prints.
+ if commandFreeze.Frozen() {
+ return
+ }
+
// If dolt auto-commit is enabled, defer the metadata write so it can be
// committed as a separate Dolt commit in PostRun.
// This avoids tip metadata getting bundled into the main command commit.
diff --git a/cmd/bd/update.go b/cmd/bd/update.go
index a52369359..8fb3ffc04 100644
--- a/cmd/bd/update.go
+++ b/cmd/bd/update.go
@@ -99,7 +99,7 @@ pointless).`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
- CheckReadonly("update") // also covers CheckMigrationFreeze (dc-6jaq)
+ CheckReadonly("update") // also covers the migration freeze check (dc-6jaq)
evt := metrics.NewCommandEvent("update")
defer func() {
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index 2a79a6280..bd3995a26 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -5,7 +5,7 @@ description: Complete reference for bd configuration across config.yaml and data
Complete configuration reference for beads.
-Last reviewed: 2026-07-10
+Last reviewed: 2026-08-28
Freshness source: `cmd/bd/main.go`, `cmd/bd/config.go`, and `internal/configfile/`.
@@ -456,6 +456,7 @@ Selected commonly-used variables:
| `BD_NO_PAGER`, `BD_PAGER` | Pager behavior |
| `BD_NON_INTERACTIVE` | Disable prompts |
| `BD_DEBUG` | Enable debug logging |
+| `BD_MIGRATION_FREEZE_FILE` | Check this exact path for the freeze marker instead of walking ancestor directories; authoritative when set (see [Migration Freeze](#migration-freeze)) |
| `BEADS_DIR` | Force the active beads workspace directory |
| `BEADS_ACTOR` | Actor identity (preferred over `BD_ACTOR`, which is a deprecated alias) |
| `BEADS_IDENTITY` | Sender identity for `bd mail` |
@@ -467,6 +468,44 @@ Integration secrets follow tracker-specific conventions: `LINEAR_API_KEY`, `GITH
`bd config show` will display the source of every effective key, making overrides explicit.
+## Migration Freeze
+
+Maintenance that runs outside `bd` — moving a database to a new host, rewriting schema by hand — needs a way to stop writes for its duration without uninstalling the tool. Create a file named `MIGRATION-FREEZE` and every write command refuses to run until you delete it.
+
+bd looks for the marker in the workspace directory and in the working directory, plus every ancestor of each, so one file above a tree of repositories freezes all of them at once — and targeting a frozen workspace from elsewhere (`BEADS_DIR=…`, `bd -C …`) is refused the same way.
+
+Markers found in a world-writable sticky directory such as `/tmp` are ignored: anyone on a shared machine could plant one there, and the sticky bit would stop you removing it. Put the marker at the root of the tree you are freezing.
+
+A freeze marker must be a regular file. A directory or a symlink named `MIGRATION-FREEZE` that the ancestor walk finds is ignored — the symlink with a one-line warning on stderr, so a stray link never disarms the gate in silence. To drive the freeze through an indirection on purpose, name that link with `BD_MIGRATION_FREEZE_FILE` (below), which bd follows.
+
+```bash
+touch MIGRATION-FREEZE # the file's existence is the whole signal
+
+# Optional payload: operator, RFC3339 timestamp, and reason, tab-separated
+# on one line. bd echoes it back in the refusal.
+printf 'alice\t2026-08-16T12:00:00Z\tmoving to the new server\n' > MIGRATION-FREEZE
+
+bd create "new work"
+# ⛔ ERROR: workspace is frozen for migration (by alice).
+# Reason: moving to the new server
+# bd create is blocked by the freeze marker at /work/MIGRATION-FREEZE.
+# To resume writes, remove that file.
+
+rm MIGRATION-FREEZE # thaw
+```
+
+Blocked commands exit **14** — a stable code scripts branch on to tell "someone is migrating this workspace, come back later" from a generic failure worth an immediate retry. That includes the destructive ones: `bd init --reinit-local` and `bd bootstrap` are refused too.
+
+Reads (`bd list`, `bd show`, `bd ready`, …) keep working during a freeze, and bd's own background maintenance stands down with them — version-bump migration, JSONL auto-import, Dolt auto-commit, auto-backup, auto-export and auto-push are all skipped, so running a read does not leave a commit in the store you are migrating.
+
+