diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d1656c7d..91a4af14e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Write commands now refuse to run while a MIGRATION-FREEZE sentinel sits + at the town root** (dc-6jaq), mirroring the gate the gt CLI already applies + to `gt mail send`/`nudge`/`sling`/`assign`. `bd create`/`update`/`close`/ + `remember`/`import` and every other command gated by `CheckReadonly` + (~120 call sites, `bd q` included) now print `⛔ town is frozen for + migration (by )` and exit 1 instead of writing to a store mid- + migration. The check runs twice: once early in the root command, before + version-bump auto-migration or JSONL auto-import can touch the store, and + again at each write command's own chokepoint. Read commands (`list`, + `show`, `ready`, …) and `--dry-run`/`--inspect` previews are unaffected — + diagnosis must still work during a freeze. Clear the freeze with + `gt migrate thaw`. + - **`bd reclaim` summarizes the leases its replica guard declined instead of naming every one, every run** (wy-sp2l4). A lease granted by another replica is by construction never reclaimed here, so the audit was not a one-off: it diff --git a/cmd/bd/close.go b/cmd/bd/close.go index 08e4f16ad..358016b99 100644 --- a/cmd/bd/close.go +++ b/cmd/bd/close.go @@ -49,8 +49,7 @@ the flags appear in the command line.`, SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - CheckReadonly("close") - CheckMigrationFreeze("close") + CheckReadonly("close") // also covers CheckMigrationFreeze (dc-6jaq) evt := metrics.NewCommandEvent("close") defer func() { diff --git a/cmd/bd/create.go b/cmd/bd/create.go index 6ad419011..6f181e8c0 100644 --- a/cmd/bd/create.go +++ b/cmd/bd/create.go @@ -51,8 +51,7 @@ var createCmd = &cobra.Command{ SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - CheckReadonly("create") - CheckMigrationFreeze("create") + CheckReadonly("create") // also covers CheckMigrationFreeze (dc-6jaq) evt := metrics.NewCommandEvent("create") defer func() { diff --git a/cmd/bd/errors.go b/cmd/bd/errors.go index 433adc42a..0cab94bb5 100644 --- a/cmd/bd/errors.go +++ b/cmd/bd/errors.go @@ -126,17 +126,27 @@ func WarnError(format string, args ...interface{}) { } // CheckReadonly aborts the command when bd is running in read-only mode (the -// worker-sandbox posture, see readonlyMode). 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 +// 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. 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) } // CheckMigrationFreeze aborts the command when a MIGRATION-FREEZE sentinel is @@ -148,6 +158,21 @@ func CheckReadonly(operation string) { // 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. +// +// 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). +// 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 +// call would let a version-bump migration or a JSONL auto-import slip +// through a freeze first (the most dangerous writes here, since they +// run against the very store the freeze protects). +// 3. import.go directly — bd import (runImport) is not gated by +// 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) { diff --git a/cmd/bd/import.go b/cmd/bd/import.go index dae5250f7..7f048a832 100644 --- a/cmd/bd/import.go +++ b/cmd/bd/import.go @@ -117,6 +117,10 @@ func init() { } func runImport(cmd *cobra.Command, args []string) error { + // Explicit call, not inherited from CheckReadonly: runImport doesn't call + // 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") evt := metrics.NewCommandEvent("import") diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 256290078..b5075ccf8 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -1378,6 +1378,25 @@ var rootCmd = &cobra.Command{ policy := effectiveRootStorePolicy(cmd.Name(), readonlyMode) useReadOnly := policy.readOnly || previewMode + // dc-6jaq: consult the MIGRATION-FREEZE sentinel 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 + // maybeAutoImportJSONL (imports into the store when empty) all run + // before the command's RunE, where CheckReadonly would otherwise + // catch a frozen write first. By then the most dangerous writes this + // gate exists to prevent would already be done. useReadOnly already + // carries the exact classification a freeze must not block (strict + // --readonly, a command on the read-only allowlist, or an explicit + // --dry-run/--inspect preview) — reusing it here means there is no + // second, independently-maintained list of "write" commands to drift + // out of sync with the one useReadOnly is built from. CheckReadonly + // (and therefore this same freeze check) still runs again per-command + // once RunE is reached; this is the earlier, store-open-safe half. + if !useReadOnly { + CheckMigrationFreeze(strings.TrimPrefix(cmd.CommandPath(), cmd.Root().Name()+" ")) + } + // Track bd version changes unless strict readonly forbids repository mutation. // Best-effort tracking - failures are silent. // diff --git a/cmd/bd/memory.go b/cmd/bd/memory.go index 536bcfb06..dd1501fbf 100644 --- a/cmd/bd/memory.go +++ b/cmd/bd/memory.go @@ -257,8 +257,7 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - CheckReadonly("remember") - CheckMigrationFreeze("remember") + CheckReadonly("remember") // also covers CheckMigrationFreeze (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 b148fab4a..47494675a 100644 --- a/cmd/bd/migration_freeze_gate_test.go +++ b/cmd/bd/migration_freeze_gate_test.go @@ -45,10 +45,18 @@ func migrationFreezeEnv(dir string) []string { // exit code. Only a failure to launch the process fails the test; nonzero // exits are returned to the caller for assertion. func runBDMigrationFreeze(t *testing.T, bd, dir string, args ...string) (stdout, stderr string, exitCode int) { + t.Helper() + return runBDMigrationFreezeWithEnv(t, bd, dir, nil, args...) +} + +// runBDMigrationFreezeWithEnv is runBDMigrationFreeze plus caller-supplied +// environment variables layered on top of the hermetic base env (e.g. +// BD_DEBUG=1, for tests that need to observe debug.Logf output). +func runBDMigrationFreezeWithEnv(t *testing.T, bd, dir string, extraEnv []string, args ...string) (stdout, stderr string, exitCode int) { t.Helper() cmd := exec.Command(bd, args...) cmd.Dir = dir - cmd.Env = migrationFreezeEnv(dir) + cmd.Env = append(migrationFreezeEnv(dir), extraEnv...) var outBuf, errBuf bytes.Buffer cmd.Stdout = &outBuf cmd.Stderr = &errBuf @@ -169,3 +177,119 @@ func TestCreateNotBlockedWithoutFreeze(t *testing.T) { t.Fatalf("bd create --json returned no id:\n%s", stdout) } } + +// 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 +// "bd q" (quick.go) is create's own documented shorthand and called +// CheckReadonly directly rather than going through create's RunE — so it +// was never gated even though create was. Now that CheckReadonly itself +// folds in the freeze check, every one of its ~120 call sites is covered +// automatically, "q" included. +func TestQuickBlockedDuringMigrationFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + freezeTown(t, dir, "mayor", "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) + } + if !strings.Contains(stderr, "frozen for migration") { + t.Errorf("stderr missing 'frozen for migration':\n%s", stderr) + } + if strings.TrimSpace(stdout) != "" { + t.Errorf("stdout should be empty when blocked, got:\n%s", stdout) + } +} + +// TestLabelAddBlockedDuringMigrationFreeze checks a second, unrelated write +// command that was never part of the original hand-picked five either — +// evidence the fold-into-CheckReadonly fix covers the write surface +// generally, not just the one bypass ("bd q") review happened to name. +func TestLabelAddBlockedDuringMigrationFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + + stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "create", "pre-freeze issue for label", "-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) + } + + freezeTown(t, dir, "mayor", "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) + } + if !strings.Contains(stderr, "frozen for migration") { + t.Errorf("stderr missing 'frozen for migration':\n%s", stderr) + } +} + +// TestAutoMigrateSkippedDuringMigrationFreeze is the structural ordering +// check (dc-6jaq review, ask #2): a frozen write must be blocked before +// PersistentPreRunE's own store-touching side effects run, not after, from +// inside the write command's own RunE. autoMigrateOnVersionBump +// (version_tracking.go) opens its own store connection and can apply a real +// schema migration — the most dangerous write in this path — and ran +// unconditionally for every non-preview command before this fix, freeze or +// not. +// +// An old .local_version forces trackBdVersion to detect a version "bump" so +// autoMigrateOnVersionBump's body actually does something observable +// instead of short-circuiting on "no upgrade detected" — then BD_DEBUG=1 +// surfaces its unconditional "auto-migrate:"-prefixed debug.Logf lines, so +// their absence is direct evidence the function was never entered. +func TestAutoMigrateSkippedDuringMigrationFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + + localVersionPath := filepath.Join(dir, ".beads", localVersionFile) + if err := os.WriteFile(localVersionPath, []byte("0.0.1\n"), 0644); err != nil { + t.Fatalf("writing fake old %s: %v", localVersionFile, err) + } + + freezeTown(t, dir, "mayor", "dolt v2 migration") + + stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, []string{"BD_DEBUG=1"}, + "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 !strings.Contains(stderr, "frozen for migration") { + t.Errorf("stderr missing '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 "+ + "'auto-migrate:' debug log line in stderr) — the freeze check must fire before it, "+ + "not after, from inside create's own RunE:\n%s", stderr) + } +} + +// TestAutoMigrateStillRunsWithoutFreeze is the companion regression-safety +// check for the ask-#2 fix: without a freeze sentinel, the new early gate in +// PersistentPreRunE must not interfere with autoMigrateOnVersionBump's normal +// version-bump reconciliation. +func TestAutoMigrateStillRunsWithoutFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + + localVersionPath := filepath.Join(dir, ".beads", localVersionFile) + if err := os.WriteFile(localVersionPath, []byte("0.0.1\n"), 0644); err != nil { + t.Fatalf("writing fake old %s: %v", localVersionFile, err) + } + + stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, []string{"BD_DEBUG=1"}, + "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) + } + 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/update.go b/cmd/bd/update.go index ee88733d8..35233060d 100644 --- a/cmd/bd/update.go +++ b/cmd/bd/update.go @@ -99,8 +99,7 @@ pointless).`, SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - CheckReadonly("update") - CheckMigrationFreeze("update") + CheckReadonly("update") // also covers CheckMigrationFreeze (dc-6jaq) evt := metrics.NewCommandEvent("update") defer func() { diff --git a/internal/migration/freeze.go b/internal/migration/freeze.go index dc0e41de2..58dbe34b9 100644 --- a/internal/migration/freeze.go +++ b/internal/migration/freeze.go @@ -54,7 +54,11 @@ func Read(townRoot string) *Info { func parse(content string) *Info { content = strings.TrimSpace(content) if content == "" { - return &Info{Timestamp: time.Now()} + // No recorded timestamp to parse (e.g. an empty sentinel 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) info := &Info{} diff --git a/internal/migration/freeze_test.go b/internal/migration/freeze_test.go index 06c2ec804..35969cf36 100644 --- a/internal/migration/freeze_test.go +++ b/internal/migration/freeze_test.go @@ -59,6 +59,24 @@ func TestReadNotFrozenReturnsNil(t *testing.T) { } } +func TestReadEmptyContentDoesNotFabricateTimestamp(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(FilePath(dir), []byte(""), 0644); err != nil { + t.Fatalf("writing empty sentinel: %v", err) + } + + info := Read(dir) + if info == nil { + t.Fatalf("Read(%q) = nil for empty-but-present sentinel, want non-nil Info", dir) + } + 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) + } +} + func TestReadMalformedContentDoesNotPanic(t *testing.T) { dir := t.TempDir() if err := os.WriteFile(FilePath(dir), []byte("not tab separated at all"), 0644); err != nil {