beads/cmd/bd/errors.go
Athos Bernardes 4bfee305ba
bd: honor MIGRATION-FREEZE sentinel on write commands (#5826)
* fix(dc-6jaq): bd honors MIGRATION-FREEZE sentinel on write commands

Mirrors gt CLI's existing town-wide write-freeze gate (gastownhall/gastown
internal/cmd/root.go persistentPreRun + internal/migration/freeze.go on
branch feat/migrate-freeze-thaw) into bd, closing the residual gap noted in
dc-qcd2/B2: gt mail send/nudge/sling/assign already refuse writes under a
MIGRATION-FREEZE sentinel at the town root, and continuous bd writers
(mail-poller, daemon patrols) are stopped separately via the migration
playbook's plist-unload step — but a human typing 'bd create'/'bd update'
etc. mid-migration could still write directly to dolt, bypassing the
gt-layer gate entirely.

Adds internal/migration (IsFrozen/Read, read-only — the sentinel itself is
still created/removed by gt migrate freeze/thaw) and CheckMigrationFreeze
next to the existing CheckReadonly in cmd/bd/errors.go, wired into the 5
commands the story named: create, update, close, remember, import.
findTownRoot (doctor_gastown_guard.go) walks up from cwd for mayor/town.json
— the same primary marker gt's own workspace package checks — falling back
to GT_TOWN_ROOT/GT_ROOT, matching this codebase's existing orchestrator-
detection convention (formula.go, molecules.go, doltserver.go already use
GT_ROOT the same way).

Verified via clean-baseline diff against origin/main: one pre-existing,
unrelated test failure (TestUpdateStrayMetadataPositionalRefusedBeforeWrite/
TestUpdateSetMetadataRepeatedFlagStillWrites, "embedded Dolt requires a CGO
build" under CGO_ENABLED=0) reproduces identically with zero changes present
— confirmed environment-specific, not a regression from this change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(dc-6jaq): address review — fold freeze check into CheckReadonly, gate before store-open side effects

bee-ghosttrack's review (PR #5826, 2026-08-20) found two structural gaps in
the original gate:

1. Only 5 of ~120 CheckReadonly call sites were gated (create, update,
   close, remember, import) — a hand-picked list that rots. Sharpest
   instance: `bd q` (quick.go), create's own documented shorthand, called
   CheckReadonly directly and was never gated even though create was.

   Fix: fold CheckMigrationFreeze into CheckReadonly itself, so every call
   site inherits it automatically — one chokepoint, not a list to maintain.
   `bd import` keeps its own explicit CheckMigrationFreeze call: runImport
   never called CheckReadonly to begin with (a separate, pre-existing gap —
   readonlyMode doesn't gate it either), so it can't inherit from
   CheckReadonly.

2. The gate fired inside each write command's RunE, but PersistentPreRunE's
   own store-touching side effects — autoMigrateOnVersionBump (a real schema
   migration against the shared store) and maybeAutoImportJSONL — run
   unconditionally for non-preview commands *before* any RunE. A frozen
   `bd create` on a version-bumped binary could trigger both before ever
   printing the refusal.

   Fix: an early freeze check in the root PersistentPreRunE, placed right
   after the read-only/preview classification (useReadOnly) is resolved and
   before trackBdVersion/autoMigrateOnVersionBump/maybeAutoImportJSONL run.
   Reuses useReadOnly rather than a second write-command list — mirrors the
   existing isForcedMigrate/#4259 precedent for "must run before store open".

Also: parse("") no longer fabricates a time.Now() timestamp for an empty
sentinel file (nit); CHANGELOG entry added.

New tests: bd q and a second, previously-ungated write command (label add)
blocked during freeze; an ordering test forces a version-bump detection and
uses BD_DEBUG=1 to confirm autoMigrateOnVersionBump's body is never entered
while frozen (a companion test confirms it still runs normally without a
freeze). Verified via git stash that the four new tests fail against the
pre-fix commit — they catch what's described above, not passing vacuously.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(dc-6jaq): address round-2 review — skip maintenance writes while frozen, correct preview claim

Reviewer bee-ghosttrack re-verified a01f914b7 (build/vet/14 tests green,
MERGE-AFTER-FIXES) with two remaining asks:

1. The early freeze gate only covered write commands (`if !useReadOnly`),
   but trackBdVersion/autoMigrateOnVersionBump ran regardless via
   policy.runMaintenance — so a classified read (e.g. `bd list`) still
   rewrote .local_version and could auto-migrate the frozen store.
   Reproduced: freeze + seed a stale .local_version + `bd list` exits 0
   but the auto-migrate debug line fires anyway. Fixed by gating both
   calls on migration.IsFrozen(findTownRoot()) without blocking the read
   itself, short-circuited behind policy.runMaintenance so the extra
   filesystem walk isn't paid on the strict-readonly path where these
   calls are already skipped.

2. CHANGELOG and a main.go comment claimed --dry-run/--inspect previews
   are unaffected by a freeze. False: create's own CheckReadonly call
   still runs the (non-preview-aware) freeze check at RunE, so
   `create --dry-run` on a frozen town exits 1. Per reviewer's own
   recommendation, corrected the claim rather than making the chokepoint
   preview-aware — fail-closed already, and consistent with what strict
   --readonly does to previews today.

Extended TestAutoMigrateSkippedDuringMigrationFreeze with a `list`
subtest covering both: exit 0 (not blocked) and no auto-migrate/write
side effect (maintenance skipped), plus a .local_version-unchanged
assertion on both subtests to make the skip observable beyond the debug
log line.

Verified: CGO_ENABLED=0 go build/vet clean; go test ./internal/migration/...
6/6; scripts/test.sh (CGO-built bd, canonical CI flags) on all 7 gate
tests in cmd/bd — 9/9 including both new list-case assertions — green.//
Out of scope per reviewer: bd doctor --fix bypassing readonly/freeze
(pre-existing, separate follow-up).

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 05:51:32 -07:00

197 lines
6.4 KiB
Go

package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/migration"
)
type exitError struct {
Code int
}
func (e *exitError) Error() string {
return fmt.Sprintf("exit code %d", e.Code)
}
func exitCodeFromError(err error) (int, bool) {
var ee *exitError
if errors.As(err, &ee) {
return ee.Code, true
}
return 0, false
}
func activeWorkspaceNotFoundError() string {
return "no active beads workspace found"
}
func activeWorkspaceNotFoundMessage() string {
return "No active beads workspace found."
}
func diagHint() string {
return workspaceDiagHint(true)
}
func whereDiagHint() string {
return workspaceDiagHint(false)
}
func workspaceDiagHint(includeWhere bool) string {
if includeWhere {
if !usesSQLServer() {
return "run 'bd where' to inspect the resolved workspace, or 'bd init' to create a new database"
}
return "run 'bd where' to inspect the resolved workspace, run 'bd doctor' to diagnose, or 'bd init' to create a new database"
}
if !usesSQLServer() {
return "check BEADS_DIR/worktree setup, or run 'bd init' to create a new database"
}
return "check BEADS_DIR/worktree setup, run 'bd doctor' to diagnose, or run 'bd init' to create a new database"
}
func buildJSONError(message, hint string) interface{} {
inner := map[string]interface{}{
"error": message,
}
if hint != "" {
inner["hint"] = hint
}
if jsonEnvelopeEnabled() {
return map[string]interface{}{
"schema_version": JSONSchemaVersion,
"data": inner,
}
}
inner["schema_version"] = JSONSchemaVersion
return inner
}
func jsonStderrError(message, hint string) {
encoder := json.NewEncoder(os.Stderr)
encoder.SetIndent("", " ")
_ = encoder.Encode(buildJSONError(message, hint))
}
func jsonStdoutError(message, hint string) {
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
_ = encoder.Encode(buildJSONError(message, hint))
}
func HandleError(format string, args ...interface{}) error {
fmt.Fprintf(os.Stderr, "Error: "+format+"\n", args...)
return &exitError{Code: 1}
}
func HandleErrorRespectJSON(format string, args ...interface{}) error {
if jsonOutput {
jsonStdoutError(fmt.Sprintf(format, args...), "")
return &exitError{Code: 1}
}
return HandleError(format, args...)
}
func HandleErrorWithHint(message, hint string) error {
if jsonOutput {
jsonStderrError(message, hint)
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", message) //nolint:gosec // G705: stderr, not a browser context
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint) //nolint:gosec // G705: stderr, not a browser context
}
return &exitError{Code: 1}
}
func HandleErrorWithHintRespectJSON(message, hint string) error {
if jsonOutput {
jsonStdoutError(message, hint)
} else {
fmt.Fprintf(os.Stderr, "Error: %s\n", message)
fmt.Fprintf(os.Stderr, "Hint: %s\n", hint)
}
return &exitError{Code: 1}
}
func SilentExit() error {
return &exitError{Code: 1}
}
func WarnError(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "Warning: "+format+"\n", args...)
}
// 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.
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
// 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.
//
// 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) {
return
}
info := migration.Read(townRoot)
operator := "unknown"
reason := ""
if info != nil {
operator = info.Operator
reason = info.Reason
}
fmt.Fprintf(os.Stderr, "⛔ ERROR: town is frozen for migration (by %s).\n", operator)
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)
}