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. + + +A `bd serve` process started before the marker appeared keeps accepting HTTP writes: the freeze is a CLI-invocation gate, and a running server never re-reads it. Stop the server before you freeze. + + +If bd cannot tell whether a marker is present — a permission error on the marker or on a directory above it — it refuses the write and says so, rather than assuming the workspace is open. + +`BD_MIGRATION_FREEZE_FILE` names one explicit path to consult instead of walking ancestors, for markers that live outside the tree. It is authoritative: when it is set, nothing else is checked. Because you name that path deliberately, it may be a symlink — bd follows it and freezes when the link resolves to a regular marker file — so an indirection such as `current -> releases/42/MIGRATION-FREEZE` works as the authoritative signal. + ## Security: Where Secrets Live - Tokens and API keys are never stored in the Dolt database — database config is pushed to remotes, which would expose secrets and trip GitHub secret scanning. `bd config set` routes secret keys to the local `config.yaml` instead. diff --git a/internal/migration/freeze.go b/internal/migration/freeze.go index 58dbe34b9..dbafddff3 100644 --- a/internal/migration/freeze.go +++ b/internal/migration/freeze.go @@ -1,77 +1,289 @@ -// Package migration provides read-side access to the town-wide -// MIGRATION-FREEZE write-freeze sentinel used during Gas Town dolt -// migrations. The sentinel file itself is created and removed by the gt CLI -// (see gt migrate freeze/thaw, gastownhall/gastown's internal/migration -// package) — bd only reads it, before a write command runs, to refuse -// human-typed writes that would bypass the gt-layer gate (dc-6jaq). +// Package migration provides read-side access to the MIGRATION-FREEZE +// write-freeze marker. The marker is a plain file that an operator — or an +// external orchestration tool driving a migration — creates to stop writes +// against a workspace, and removes to resume them. bd only ever reads it, +// before a write command runs, so a human typing 'bd create'/'bd update' +// mid-migration cannot slip a write past whatever quiesced the workspace +// (dc-6jaq). package migration import ( + "errors" + "fmt" + "io" + "io/fs" "os" "path/filepath" "strings" + "syscall" "time" ) -// FileName is the freeze sentinel placed at the town root. +// FileName is the name of the freeze marker file. bd looks for it in a start +// directory and every ancestor up to the filesystem root, so a marker placed +// at the top of a multi-repo tree freezes every workspace beneath it. const FileName = "MIGRATION-FREEZE" -// Info is the parsed contents of a MIGRATION-FREEZE file. +// EnvFreezeFile names an explicit freeze-marker path. When set and non-empty +// it is authoritative: bd checks that path only and skips the ancestor walk, +// so it doubles as the hook for markers that live outside any workspace tree +// and as an opt-out (point it at a path that does not exist). +const EnvFreezeFile = "BD_MIGRATION_FREEZE_FILE" + +// maxMarkerSize caps how much of a marker bd will read. The payload is one +// short line; anything larger is a mistake or a hostile file (the ancestor +// walk can reach directories bd does not control), and a freeze must not turn +// into a multi-gigabyte allocation. +const maxMarkerSize = 64 << 10 + +// Info is the parsed contents of a freeze marker. type Info struct { - Operator string // who initiated the freeze (e.g. "mayor", a username) + Operator string // who initiated the freeze (a username, a tool name) Reason string // human-readable migration reason Timestamp time.Time // when the freeze was set } -// FilePath returns the full path to the freeze sentinel file. -func FilePath(townRoot string) string { - return filepath.Join(townRoot, FileName) +// Result is the outcome of a freeze lookup. +type Result struct { + // Path is the active marker's path, or "" when no marker was found. + Path string + + // FromEnv reports that Path — or, when the lookup failed, the path that + // failed — came from EnvFreezeFile rather than an ancestor walk. Callers + // use it to add "or unset BD_MIGRATION_FREEZE_FILE" to a refusal. + FromEnv bool + + // Err reports that the lookup could not be completed: a path that is + // neither present nor absent as far as bd can tell (a permission error on + // the marker or a directory above it). Callers must treat a non-nil Err as + // frozen — an undeterminable gate is not an open gate — and say so. + Err error } -// IsFrozen reports whether a migration freeze is currently active. -func IsFrozen(townRoot string) bool { - if townRoot == "" { +// Frozen reports whether writes must be refused: either a marker was found or +// the lookup could not be completed. +func (r Result) Frozen() bool { return r.Path != "" || r.Err != nil } + +// Find looks for an active freeze marker and reports what it found. +// +// EnvFreezeFile, when set, is authoritative and the only path consulted. +// Otherwise Find walks the current working directory to the filesystem root, +// then does the same for each directory in also, stopping at the first marker. +// +// Passing the resolved workspace in also is what keys the gate on the store +// being written rather than on the caller's shell: `BEADS_DIR=/work/repo/.beads +// bd create` run from $HOME, `bd -C /work/repo create` (which sets BEADS_DIR +// without ever chdir'ing), and a daemon with an unrelated cwd must all still +// be stopped by /work/MIGRATION-FREEZE. +func Find(also ...string) Result { + if r, handled := lookupEnvOverride(); handled { + return r + } + + starts := make([]string, 0, len(also)+1) + if cwd, err := os.Getwd(); err == nil { + starts = append(starts, cwd) + } + starts = append(starts, also...) + return walkAll(starts) +} + +// FindFrom looks for an active freeze marker in dir and its ancestors only, +// ignoring the process working directory. Use it when the caller's cwd is not +// part of the operation — a command handed an explicit target path — and in +// tests that must exercise the walk without depending on process state. +// EnvFreezeFile still wins when set. +func FindFrom(dir string) Result { + if r, handled := lookupEnvOverride(); handled { + return r + } + return walkAll([]string{dir}) +} + +// lookupEnvOverride resolves EnvFreezeFile. The second return reports whether +// the variable was set at all; when it was, its answer is final and no walk +// runs — that is what makes the variable a usable opt-out. +func lookupEnvOverride() (Result, bool) { + override := os.Getenv(EnvFreezeFile) + if override == "" { + return Result{}, false + } + switch found, err := statMarker(override, true); { + case err != nil: + return Result{FromEnv: true, Err: err}, true + case found: + return Result{Path: override, FromEnv: true}, true + default: + return Result{FromEnv: true}, true + } +} + +// walkAll walks each start directory to the filesystem root, returning the +// first marker found. Duplicate and empty starts are skipped, as are ancestors +// already visited by an earlier start. +func walkAll(starts []string) Result { + seen := make(map[string]bool) + for _, start := range starts { + if start == "" { + continue + } + dir, err := filepath.Abs(start) + if err != nil { + continue + } + for { + if !seen[dir] { + seen[dir] = true + switch found, statErr := statMarker(filepath.Join(dir, FileName), false); { + case statErr != nil: + return Result{Err: statErr} + case found && !inUntrustedDir(dir): + return Result{Path: filepath.Join(dir, FileName)} + } + } + parent := filepath.Dir(dir) + if parent == dir { + break + } + dir = parent + } + } + return Result{} +} + +// statMarker reports whether path is a usable freeze marker. A missing path is +// simply not a marker; so is a directory or a device named MIGRATION-FREEZE, +// which the walk can otherwise hit in vendored fixtures or an extracted +// archive. Any other stat failure — a permission error on the marker or on a +// directory above it — is returned, because "bd cannot tell" must not read as +// "not frozen". +// +// trusted separates the operator-named EnvFreezeFile path from one the untrusted +// ancestor walk stumbled onto, which decides how a symlink is treated. os.Lstat +// does not follow links, so a symlink is neither regular nor absent; left alone +// it would silently fail OPEN — the one direction a write gate must never take. +// On the trusted path a symlink is honored (resolved with os.Stat, so a link to +// a real regular marker still freezes): the operator named it, and an +// indirection like `current -> releases/N` is exactly what EnvFreezeFile is +// for. On the untrusted walk a symlink is NOT followed — anything the walk +// merely passed through could otherwise redirect the gate — but the skip is +// announced on stderr so it is visible rather than a silent bypass. +func statMarker(path string, trusted bool) (bool, error) { + info, err := os.Lstat(path) + if err != nil { + return classifyMarkerStatErr(path, err) + } + switch { + case info.Mode().IsRegular(): + return true, nil + case info.Mode()&os.ModeSymlink != 0: + return statSymlinkMarker(path, trusted) + default: + // A directory, device, socket, or similar named MIGRATION-FREEZE is not + // a marker. + return false, nil + } +} + +// statSymlinkMarker decides a symlink found where a marker was expected. On the +// untrusted walk it refuses to follow but warns, so an ignored would-be marker +// never disappears in silence. On the operator-named path it follows the link +// with os.Stat and honors a regular target; a dangling or non-regular target is +// simply not a marker, and an unreadable one stays fail-closed. +func statSymlinkMarker(path string, trusted bool) (bool, error) { + if !trusted { + fmt.Fprintf(os.Stderr, + "bd: ignoring symlinked %s at %s; a freeze marker must be a regular file (set %s to honor a symlink)\n", + FileName, path, EnvFreezeFile) + return false, nil + } + info, err := os.Stat(path) + if err != nil { + return classifyMarkerStatErr(path, err) + } + return info.Mode().IsRegular(), nil +} + +// classifyMarkerStatErr maps a stat/lstat error to the (found, err) a marker +// lookup reports: a genuinely-absent path (ENOENT/EINVAL, or ENOTDIR when a +// component of the path is not a directory) is "not a marker"; anything else is +// undeterminable and returned so the caller treats it as frozen. +func classifyMarkerStatErr(path string, err error) (bool, error) { + switch { + case errors.Is(err, fs.ErrNotExist), errors.Is(err, fs.ErrInvalid): + return false, nil + case errors.Is(err, syscall.ENOTDIR): + // A component of path is not a directory, so the marker cannot exist + // here. That is an answer, not a failure. + return false, nil + default: + return false, fmt.Errorf("checking for a %s marker at %s: %w", FileName, path, err) + } +} + +// inUntrustedDir reports whether dir is a world-writable sticky directory — +// /tmp and its kin. The ancestor walk reaches those on the way to the root, +// and a marker there is both forgeable by any local account and, thanks to the +// sticky bit, undeletable by the victim the refusal tells to delete it. An +// explicit BD_MIGRATION_FREEZE_FILE is exempt: that path is the operator's own +// stated intent, not something the walk stumbled onto. +func inUntrustedDir(dir string) bool { + info, err := os.Stat(dir) + if err != nil { return false } - _, err := os.Stat(FilePath(townRoot)) - return err == nil + mode := info.Mode() + return mode.IsDir() && mode&os.ModeSticky != 0 && mode.Perm()&0o002 != 0 } -// Read parses the freeze sentinel. Returns nil if not frozen or unreadable. -func Read(townRoot string) *Info { - if townRoot == "" { +// ReadFile parses the freeze marker at path. Returns nil when the file is +// missing or unreadable. At most maxMarkerSize bytes are read. +func ReadFile(path string) *Info { + if path == "" { return nil } - data, err := os.ReadFile(FilePath(townRoot)) + f, err := os.Open(path) //nolint:gosec // G304: path comes from Find/FindFrom — an ancestor walk for a fixed filename, or the operator's own BD_MIGRATION_FREEZE_FILE + if err != nil { + return nil + } + defer func() { _ = f.Close() }() + + data, err := io.ReadAll(io.LimitReader(f, maxMarkerSize)) if err != nil { return nil } return parse(string(data)) } -// parse mirrors gt's own freeze-file format: operator, RFC3339 timestamp, -// and reason, tab-separated on a single line. +// parse reads the marker's optional payload: operator, RFC3339 timestamp, and +// reason, tab-separated on a single line. Every field is optional — an empty +// file is a valid freeze, and so is one that records a reason but no operator. func parse(content string) *Info { - content = strings.TrimSpace(content) - if content == "" { - // No recorded timestamp to parse (e.g. an empty sentinel file, such + // Only the first line is payload. Taking it before splitting keeps a + // multi-line file from smuggling extra lines into Reason, and trimming + // per-field afterwards (rather than trimming the whole string first) + // preserves a leading empty operator instead of shifting the timestamp + // into it. + line, _, _ := strings.Cut(content, "\n") + line = strings.TrimRight(line, "\r") + if strings.TrimSpace(line) == "" { + // No recorded timestamp to parse (e.g. an empty marker file, such // as one created with `touch`) — leave Timestamp at its zero value // rather than fabricating "now": a caller that ever inspects it // should not be told the freeze started at check-time. return &Info{} } - parts := strings.SplitN(content, "\t", 3) + + parts := strings.SplitN(line, "\t", 3) info := &Info{} - if len(parts) >= 1 { - info.Operator = parts[0] - } + info.Operator = strings.TrimSpace(parts[0]) if len(parts) >= 2 { - if t, err := time.Parse(time.RFC3339, parts[1]); err == nil { + if t, err := time.Parse(time.RFC3339, strings.TrimSpace(parts[1])); err == nil { info.Timestamp = t } } if len(parts) >= 3 { - info.Reason = parts[2] + info.Reason = strings.TrimSpace(parts[2]) } return info } diff --git a/internal/migration/freeze_test.go b/internal/migration/freeze_test.go index 35969cf36..0c092d31e 100644 --- a/internal/migration/freeze_test.go +++ b/internal/migration/freeze_test.go @@ -1,47 +1,406 @@ package migration import ( + "io" "os" "path/filepath" + "runtime" + "strings" "testing" "time" ) -func TestIsFrozen(t *testing.T) { +// pinNoOverride neutralizes an inherited BD_MIGRATION_FREEZE_FILE without +// making it authoritative. Find/FindFrom short-circuit on a set variable, so a +// developer who exported the documented opt-out would otherwise see every +// walk-based test in this file fail on a healthy checkout. +func pinNoOverride(t *testing.T) { + t.Helper() + t.Setenv(EnvFreezeFile, "") +} + +// writeMarker writes a freeze marker at dir/MIGRATION-FREEZE and returns its path. +func writeMarker(t *testing.T, dir, content string) string { + t.Helper() + path := filepath.Join(dir, FileName) + if err := os.WriteFile(path, []byte(content), 0644); err != nil { + t.Fatalf("writing marker at %s: %v", path, err) + } + return path +} + +// captureStderr runs f with os.Stderr redirected to a pipe and returns what it +// wrote. These tests run sequentially (no t.Parallel), so swapping the +// process-global stderr for the duration of one call is safe here. +func captureStderr(t *testing.T, f func()) string { + t.Helper() + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("os.Pipe: %v", err) + } + old := os.Stderr + os.Stderr = w + defer func() { os.Stderr = old }() + + f() + + if err := w.Close(); err != nil { + t.Fatalf("closing stderr pipe: %v", err) + } + os.Stderr = old + out, err := io.ReadAll(r) + if err != nil { + t.Fatalf("reading captured stderr: %v", err) + } + return string(out) +} + +// TestFindFromWalkTerminates covers the walk's not-found exit. FindFrom takes +// the start directory explicitly, so this runs without touching process state +// and without the "a real marker might exist above TMPDIR" caveat that forced +// the old no-marker test to pin the override and skip the walk entirely. +// Breaking the `parent == dir` termination — hanging at /, or returning the +// root candidate — fails here instead of passing the whole suite. +func TestFindFromWalkTerminates(t *testing.T) { + pinNoOverride(t) + + // An absolute path that does not exist: every ancestor up to / is walked, + // nothing is found, and the loop must stop at the root. + deep := filepath.Join(t.TempDir(), "a", "b", "c", "d") + res := FindFrom(deep) + if res.Err != nil { + t.Fatalf("FindFrom(%q).Err = %v, want nil", deep, res.Err) + } + if res.Path != "" { + t.Fatalf("FindFrom(%q).Path = %q, want \"\" — no marker exists anywhere above a fresh temp dir", deep, res.Path) + } + if res.Frozen() { + t.Errorf("Frozen() = true for an empty result") + } +} + +func TestFindFromMarkerInStartDir(t *testing.T) { + pinNoOverride(t) dir := t.TempDir() + want := writeMarker(t, dir, "operator\t2026-08-16T12:00:00Z\tmigrating\n") - if IsFrozen(dir) { - t.Fatalf("IsFrozen(%q) = true before sentinel written, want false", dir) + res := FindFrom(dir) + if !res.Frozen() { + t.Fatalf("FindFrom(%q) = %+v, want the marker in the start directory", dir, res) } - - if err := os.WriteFile(FilePath(dir), []byte("mayor\t2026-08-16T12:00:00Z\tdolt v2 migration\n"), 0644); err != nil { - t.Fatalf("writing sentinel: %v", err) + if !sameFile(t, res.Path, want) { + t.Errorf("Path = %q, want %q", res.Path, want) } - - if !IsFrozen(dir) { - t.Fatalf("IsFrozen(%q) = false after sentinel written, want true", dir) + if res.FromEnv { + t.Errorf("FromEnv = true for a walk-found marker") } } -func TestIsFrozenEmptyTownRoot(t *testing.T) { - if IsFrozen("") { - t.Fatalf("IsFrozen(\"\") = true, want false (no town root to check)") +func TestFindFromWalksUpToGrandparent(t *testing.T) { + pinNoOverride(t) + root := t.TempDir() + want := writeMarker(t, root, "") + deep := filepath.Join(root, "rig", "repo") + if err := os.MkdirAll(deep, 0755); err != nil { + t.Fatalf("creating %s: %v", deep, err) + } + + res := FindFrom(deep) + if !res.Frozen() { + t.Fatalf("FindFrom(%q) = %+v, want the marker two levels up at %q", deep, res, want) + } + if !sameFile(t, res.Path, want) { + t.Errorf("Path = %q, want %q", res.Path, want) } } -func TestReadParsesOperatorReasonTimestamp(t *testing.T) { +// TestFindWalksExtraRootsNotJustCwd is the target-workspace contract: a caller +// whose working directory is nowhere near the frozen tree must still be +// stopped when it names that tree. This is the `BEADS_DIR=... bd create` and +// `bd -C ` shape, neither of which chdirs. +func TestFindWalksExtraRootsNotJustCwd(t *testing.T) { + pinNoOverride(t) + unrelated := t.TempDir() + frozenRoot := t.TempDir() + want := writeMarker(t, frozenRoot, "operator\t\treason\n") + workspace := filepath.Join(frozenRoot, "repo", ".beads") + if err := os.MkdirAll(workspace, 0755); err != nil { + t.Fatalf("creating %s: %v", workspace, err) + } + t.Chdir(unrelated) + + if res := Find(); res.Frozen() { + t.Fatalf("Find() with an unrelated cwd = %+v, want not frozen (guards the test's own premise)", res) + } + + res := Find(workspace) + if !res.Frozen() { + t.Fatalf("Find(%q) = %+v, want the marker above the named workspace", workspace, res) + } + if !sameFile(t, res.Path, want) { + t.Errorf("Path = %q, want %q", res.Path, want) + } +} + +// TestFindEnvOverrideAuthoritative pins both directions of the override: an +// existing file freezes even with no ancestor marker, and a missing file does +// NOT freeze even when an ancestor marker exists. The second half is what +// makes the variable a usable opt-out. +func TestFindEnvOverrideAuthoritative(t *testing.T) { + t.Run("existing file freezes without any ancestor marker", func(t *testing.T) { + work := t.TempDir() + override := filepath.Join(t.TempDir(), "freeze-marker") + if err := os.WriteFile(override, []byte("operator\t\treason\n"), 0644); err != nil { + t.Fatalf("writing override marker: %v", err) + } + t.Chdir(work) + t.Setenv(EnvFreezeFile, override) + + res := Find() + if res.Path != override { + t.Errorf("Path = %q, want the override path %q", res.Path, override) + } + if !res.FromEnv { + t.Errorf("FromEnv = false, want true — the refusal needs it to offer the unset hint") + } + }) + + t.Run("missing file wins over an ancestor marker", func(t *testing.T) { + root := t.TempDir() + writeMarker(t, root, "operator\t\treason\n") + deep := filepath.Join(root, "nested") + if err := os.MkdirAll(deep, 0755); err != nil { + t.Fatalf("creating %s: %v", deep, err) + } + t.Chdir(deep) + t.Setenv(EnvFreezeFile, filepath.Join(root, "no-such-marker")) + + res := Find() + if res.Frozen() { + t.Errorf("Find() = %+v, want not frozen — the override must skip the ancestor walk entirely", res) + } + }) + + t.Run("override also outranks an explicitly named workspace", func(t *testing.T) { + root := t.TempDir() + writeMarker(t, root, "") + t.Chdir(t.TempDir()) + t.Setenv(EnvFreezeFile, filepath.Join(root, "no-such-marker")) + + if res := Find(root); res.Frozen() { + t.Errorf("Find(%q) = %+v, want not frozen", root, res) + } + }) +} + +// TestLookupFailureIsFrozen is the fail-closed contract: a marker path bd +// cannot resolve is not the same as a marker that is absent, and the ambiguity +// must not silently disarm the gate. +func TestLookupFailureIsFrozen(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX directory permissions do not produce the same stat failure on Windows") + } + if os.Geteuid() == 0 { + t.Skip("running as root: permission bits do not deny the stat") + } + + t.Run("env override in an unreadable directory", func(t *testing.T) { + locked := filepath.Join(t.TempDir(), "locked") + if err := os.Mkdir(locked, 0755); err != nil { + t.Fatalf("creating %s: %v", locked, err) + } + override := filepath.Join(locked, FileName) + if err := os.WriteFile(override, nil, 0644); err != nil { + t.Fatalf("writing override 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(EnvFreezeFile, override) + + res := Find() + if res.Err == nil { + t.Fatalf("Find() = %+v, want a lookup error for an unstattable authoritative path", res) + } + if !res.Frozen() { + t.Errorf("Frozen() = false on a lookup failure — an undeterminable gate must not read as an open one") + } + if !res.FromEnv { + t.Errorf("FromEnv = false, want true so the refusal can name the variable") + } + }) + + t.Run("unreadable ancestor during the walk", func(t *testing.T) { + locked := filepath.Join(t.TempDir(), "locked") + nested := filepath.Join(locked, "repo") + if err := os.MkdirAll(nested, 0755); err != nil { + t.Fatalf("creating %s: %v", nested, err) + } + if err := os.Chmod(locked, 0000); err != nil { + t.Fatalf("chmod: %v", err) + } + t.Cleanup(func() { _ = os.Chmod(locked, 0755) }) + pinNoOverride(t) + + res := FindFrom(nested) + if res.Err == nil { + t.Fatalf("FindFrom(%q) = %+v, want a lookup error for an unreadable ancestor", nested, res) + } + if !res.Frozen() { + t.Errorf("Frozen() = false on a lookup failure") + } + }) +} + +// TestNonRegularMarkerIsNotAFreeze covers the vendored-fixture / extracted- +// archive case: a *directory* named MIGRATION-FREEZE must not freeze every +// workspace below it with an unreadable, unremovable-sounding refusal. +func TestNonRegularMarkerIsNotAFreeze(t *testing.T) { + pinNoOverride(t) + root := t.TempDir() + if err := os.Mkdir(filepath.Join(root, FileName), 0755); err != nil { + t.Fatalf("creating marker directory: %v", err) + } + nested := filepath.Join(root, "repo") + if err := os.MkdirAll(nested, 0755); err != nil { + t.Fatalf("creating %s: %v", nested, err) + } + + if res := FindFrom(nested); res.Frozen() { + t.Errorf("FindFrom(%q) = %+v, want not frozen — a directory is not a marker", nested, res) + } +} + +// TestEnvOverrideFollowsSymlink is the fail-open regression on the authoritative +// path: an operator who points BD_MIGRATION_FREEZE_FILE through an indirection +// symlink (the `current -> releases/N` pattern the variable exists for) must +// still be frozen when the link resolves to a real marker. os.Lstat alone would +// see the link, not the regular file it targets, and wave the write through. +func TestEnvOverrideFollowsSymlink(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation needs privilege on Windows") + } + dir := t.TempDir() + target := filepath.Join(dir, "real-marker") + if err := os.WriteFile(target, []byte("alice\t\tmigrating\n"), 0644); err != nil { + t.Fatalf("writing target marker: %v", err) + } + link := filepath.Join(dir, "current-freeze") + if err := os.Symlink(target, link); err != nil { + t.Fatalf("creating symlink: %v", err) + } + t.Chdir(t.TempDir()) + t.Setenv(EnvFreezeFile, link) + + res := Find() + if !res.Frozen() { + t.Fatalf("Find() with %s at a symlink to a real marker = %+v, want frozen — the authoritative path must follow the link", EnvFreezeFile, res) + } + if res.Path != link { + t.Errorf("Path = %q, want the operator-named path %q", res.Path, link) + } + if !res.FromEnv { + t.Errorf("FromEnv = false, want true") + } +} + +// TestEnvOverrideDanglingSymlinkNotFrozen keeps the opt-out honest: a symlink +// whose target does not exist is the same as naming a missing path — no marker, +// no freeze — not an undeterminable failure that would fail closed. +func TestEnvOverrideDanglingSymlinkNotFrozen(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation needs privilege on Windows") + } + dir := t.TempDir() + link := filepath.Join(dir, "current-freeze") + if err := os.Symlink(filepath.Join(dir, "no-such-target"), link); err != nil { + t.Fatalf("creating dangling symlink: %v", err) + } + t.Chdir(t.TempDir()) + t.Setenv(EnvFreezeFile, link) + + res := Find() + if res.Frozen() { + t.Errorf("Find() with %s at a dangling symlink = %+v, want not frozen", EnvFreezeFile, res) + } +} + +// TestWalkSymlinkMarkerIgnoredWithWarning is the untrusted-walk half of the +// symlink rule: a symlink named MIGRATION-FREEZE that the ancestor walk hits is +// NOT followed — otherwise anything the walk merely passed through could +// redirect the gate — but the skip must be announced, not a silent fail-open. +func TestWalkSymlinkMarkerIgnoredWithWarning(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation needs privilege on Windows") + } + pinNoOverride(t) + root := t.TempDir() + target := filepath.Join(t.TempDir(), "real-marker") + if err := os.WriteFile(target, nil, 0644); err != nil { + t.Fatalf("writing target marker: %v", err) + } + if err := os.Symlink(target, filepath.Join(root, FileName)); err != nil { + t.Fatalf("creating symlink marker: %v", err) + } + nested := filepath.Join(root, "repo") + if err := os.MkdirAll(nested, 0755); err != nil { + t.Fatalf("creating %s: %v", nested, err) + } + + var res Result + stderr := captureStderr(t, func() { res = FindFrom(nested) }) + if res.Frozen() { + t.Errorf("FindFrom(%q) = %+v, want not frozen — a symlinked marker on the untrusted walk is not followed", nested, res) + } + if !strings.Contains(stderr, FileName) || !strings.Contains(stderr, "symlink") { + t.Errorf("stderr = %q, want a warning naming the ignored symlinked %s so the skip is not silent", stderr, FileName) + } +} + +// TestStickyWorldWritableMarkerIgnored covers the shared-machine denial of +// service: /tmp is world-writable and sticky, so any local account can drop a +// marker there that freezes every workspace below it AND that the victim +// cannot delete. Markers found by the walk in such a directory are ignored. +func TestStickyWorldWritableMarkerIgnored(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("no sticky bit on Windows") + } + pinNoOverride(t) + root := t.TempDir() + writeMarker(t, root, "attacker\t\tdenial of service\n") + if err := os.Chmod(root, os.ModeSticky|0777); err != nil { + t.Fatalf("chmod sticky+world-writable: %v", err) + } + t.Cleanup(func() { _ = os.Chmod(root, 0755) }) + nested := filepath.Join(root, "repo") + if err := os.MkdirAll(nested, 0755); err != nil { + t.Fatalf("creating %s: %v", nested, err) + } + + if res := FindFrom(nested); res.Frozen() { + t.Errorf("FindFrom(%q) = %+v, want not frozen — a marker in a sticky world-writable directory is forgeable and undeletable", nested, res) + } + + // The operator's own explicit path is exempt: naming it is intent. + override := filepath.Join(root, FileName) + t.Setenv(EnvFreezeFile, override) + if res := Find(); !res.Frozen() { + t.Errorf("Find() with %s=%q = %+v, want frozen — an explicitly named marker is not second-guessed", EnvFreezeFile, override, res) + } +} + +func TestReadFileParsesOperatorTimestampReason(t *testing.T) { dir := t.TempDir() ts := "2026-08-16T12:00:00Z" - if err := os.WriteFile(FilePath(dir), []byte("mayor\t"+ts+"\tdolt v2 migration\n"), 0644); err != nil { - t.Fatalf("writing sentinel: %v", err) - } + path := writeMarker(t, dir, "operator\t"+ts+"\tdolt v2 migration\n") - info := Read(dir) + info := ReadFile(path) if info == nil { - t.Fatalf("Read(%q) = nil, want parsed Info", dir) + t.Fatalf("ReadFile(%q) = nil, want parsed Info", path) } - if info.Operator != "mayor" { - t.Errorf("Operator = %q, want %q", info.Operator, "mayor") + if info.Operator != "operator" { + t.Errorf("Operator = %q, want %q", info.Operator, "operator") } if info.Reason != "dolt v2 migration" { t.Errorf("Reason = %q, want %q", info.Reason, "dolt v2 migration") @@ -52,49 +411,128 @@ func TestReadParsesOperatorReasonTimestamp(t *testing.T) { } } -func TestReadNotFrozenReturnsNil(t *testing.T) { +// TestReadFileLeadingEmptyOperatorKeepsFields is the field-shift regression: a +// marker that records a timestamp and reason but no operator must keep them in +// their own fields, not slide the timestamp into Operator and drop Reason. +func TestReadFileLeadingEmptyOperatorKeepsFields(t *testing.T) { dir := t.TempDir() - if info := Read(dir); info != nil { - t.Fatalf("Read(%q) = %+v, want nil (no sentinel present)", dir, info) + ts := "2026-08-16T12:00:00Z" + path := writeMarker(t, dir, "\t"+ts+"\tdisk swap\n") + + info := ReadFile(path) + if info == nil { + t.Fatalf("ReadFile(%q) = nil, want parsed Info", path) + } + if info.Operator != "" { + t.Errorf("Operator = %q, want \"\" — the payload records no operator", info.Operator) + } + if info.Reason != "disk swap" { + t.Errorf("Reason = %q, want %q — a leading empty field must not shift the rest", info.Reason, "disk swap") + } + wantTS, _ := time.Parse(time.RFC3339, ts) + if !info.Timestamp.Equal(wantTS) { + t.Errorf("Timestamp = %v, want %v", info.Timestamp, wantTS) } } -func TestReadEmptyContentDoesNotFabricateTimestamp(t *testing.T) { +// TestReadFileTakesFirstLineOnly keeps a multi-line marker from smuggling +// extra lines into Reason, which is echoed to a terminal. +func TestReadFileTakesFirstLineOnly(t *testing.T) { dir := t.TempDir() - if err := os.WriteFile(FilePath(dir), []byte(""), 0644); err != nil { - t.Fatalf("writing empty sentinel: %v", err) - } + path := writeMarker(t, dir, "operator\t\treal reason\nError: spoofed second line\n") - info := Read(dir) + info := ReadFile(path) if info == nil { - t.Fatalf("Read(%q) = nil for empty-but-present sentinel, want non-nil Info", dir) + t.Fatalf("ReadFile(%q) = nil, want parsed Info", path) + } + if info.Reason != "real reason" { + t.Errorf("Reason = %q, want %q (no trailing lines)", info.Reason, "real reason") + } + if strings.Contains(info.Reason, "spoofed") || strings.Contains(info.Operator, "spoofed") { + t.Errorf("parsed fields carry a later line: %+v", info) + } +} + +func TestReadFileCRLF(t *testing.T) { + dir := t.TempDir() + path := writeMarker(t, dir, "operator\t\twindows reason\r\n") + + info := ReadFile(path) + if info == nil { + t.Fatalf("ReadFile(%q) = nil", path) + } + if info.Reason != "windows reason" { + t.Errorf("Reason = %q, want %q (CR stripped)", info.Reason, "windows reason") + } +} + +// TestReadFileCapsSize keeps a hostile or accidental giant marker from turning +// the refusal into a full-size allocation. +func TestReadFileCapsSize(t *testing.T) { + dir := t.TempDir() + huge := strings.Repeat("x", maxMarkerSize*2) + path := writeMarker(t, dir, "operator\t\t"+huge+"\n") + + info := ReadFile(path) + if info == nil { + t.Fatalf("ReadFile(%q) = nil", path) + } + if len(info.Reason) > maxMarkerSize { + t.Errorf("len(Reason) = %d, want <= %d — the read must be capped", len(info.Reason), maxMarkerSize) + } +} + +func TestReadFileMissingReturnsNil(t *testing.T) { + dir := t.TempDir() + if info := ReadFile(filepath.Join(dir, FileName)); info != nil { + t.Fatalf("ReadFile = %+v, want nil (no marker present)", info) + } + if info := ReadFile(""); info != nil { + t.Fatalf("ReadFile(\"\") = %+v, want nil", info) + } +} + +func TestReadFileEmptyContentDoesNotFabricateTimestamp(t *testing.T) { + dir := t.TempDir() + path := writeMarker(t, dir, "") + + info := ReadFile(path) + if info == nil { + t.Fatalf("ReadFile(%q) = nil for an empty-but-present marker, want non-nil Info", path) } if !info.Timestamp.IsZero() { t.Errorf("Timestamp = %v, want zero value (no recorded timestamp to report — must not fabricate one)", info.Timestamp) } if info.Operator != "" || info.Reason != "" { - t.Errorf("Operator/Reason = %q/%q, want both empty for an empty sentinel", info.Operator, info.Reason) + t.Errorf("Operator/Reason = %q/%q, want both empty for an empty marker", info.Operator, info.Reason) } } -func TestReadMalformedContentDoesNotPanic(t *testing.T) { +func TestReadFileMalformedContentDoesNotPanic(t *testing.T) { dir := t.TempDir() - if err := os.WriteFile(FilePath(dir), []byte("not tab separated at all"), 0644); err != nil { - t.Fatalf("writing sentinel: %v", err) - } - info := Read(dir) + path := writeMarker(t, dir, "not tab separated at all") + + info := ReadFile(path) if info == nil { - t.Fatalf("Read(%q) = nil for malformed-but-present sentinel, want non-nil Info with best-effort fields", dir) + t.Fatalf("ReadFile(%q) = nil for a malformed-but-present marker, want non-nil Info with best-effort fields", path) } if info.Operator != "not tab separated at all" { t.Errorf("Operator = %q, want the whole line back (no tabs to split on)", info.Operator) } } -func TestFilePathJoinsTownRoot(t *testing.T) { - got := FilePath("/some/town/root") - want := filepath.Join("/some/town/root", "MIGRATION-FREEZE") - if got != want { - t.Errorf("FilePath = %q, want %q", got, want) +// sameFile compares two paths by identity rather than string equality: on +// macOS t.TempDir() lives under /var, a symlink to /private/var, so the walk's +// filepath.Abs spelling can differ from the one the test holds. +func sameFile(t *testing.T, a, b string) bool { + t.Helper() + ai, err := os.Stat(a) + if err != nil { + t.Fatalf("stat %s: %v", a, err) } + bi, err := os.Stat(b) + if err != nil { + t.Fatalf("stat %s: %v", b, err) + } + return os.SameFile(ai, bi) }