* fix(migration): vendor-neutral freeze marker discovery and exit code 14
The MIGRATION-FREEZE gate keyed on a gastown town root: findTownRoot walked
cwd ancestors for mayor/town.json and fell back to GT_TOWN_ROOT/GT_ROOT, and
the refusal told users to run `gt migrate thaw` — a CLI that does not ship
with bd. Key on the marker file itself instead: walk cwd to the filesystem
root looking for MIGRATION-FREEZE, with BD_MIGRATION_FREEZE_FILE as an
authoritative override (and therefore an opt-out). The on-disk contract is
unchanged, so a marker written at a town root — an ancestor of every rig cwd
— is still found with no configuration.
The refusal now names the marker's own path, so "remove that file" is always
actionable, and exits 14 (ExitMigrationFrozen) rather than 1 so scripts can
tell "someone is migrating, come back later" from a generic failure.
Fixes a real bug on the way: the root PersistentPreRunE called os.Exit(1)
from inside a function holding a live defer that closes the store and
releases the workspace gates. Both that call site and runImport now return
&exitError{ExitMigrationFrozen}; only CheckReadonly's void signature keeps
the documented flush-then-exit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(migration): cover marker discovery, exit 14, and the returned refusal
The gate tests scaffolded a fake town root (mayor/town.json) in every
workspace; deleting that scaffolding is itself the vendor-neutrality proof at
setup level — the gate now keys on the marker file alone.
New coverage: an ancestor marker blocks a write in a nested workspace;
BD_MIGRATION_FREEZE_FILE is authoritative in both directions (existing file
freezes with no marker in the tree, missing file thaws despite one); the
refusal names the marker's real path and never prints a vendor-coupled
substring; bd import blocks too; an empty `touch`ed marker produces no
"(by )" artifact.
TestMigrationFreezeErrorReturnsInsteadOfExiting is the direct regression test
for the defer-skip bug — it calls the gate in the shape of the PersistentPreRunE
call site and asserts the caller's deferred cleanup ran. If the refusal ever
goes back to os.Exit, the test binary dies mid-run.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs(configuration): document the migration freeze marker and exit code 14
Operators had no user-facing description of the freeze gate at all — the only
recovery instruction bd printed pointed at a CLI that does not ship with it.
Add a Migration Freeze section covering the marker filename, the ancestor
walk, the optional tab-separated payload, the BD_MIGRATION_FREEZE_FILE
override, and the exit code scripts branch on.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(migration): key the freeze on the target workspace, fail closed, cover the skip-store bypass
Review round on #6043. The gate had the right idea and the wrong anchor.
Target-workspace keying. Find walked the process working directory only, so
every invocation that names a workspace from outside it — BEADS_DIR=... bd
create, bd -C <dir> (which sets BEADS_DIR and never chdirs), a daemon or cron
with an unrelated cwd — walked the wrong ancestry and wrote straight through a
freeze. Find now takes the directories to cover and PersistentPreRunE passes
the resolved workspace; FindFrom walks a named tree without consulting cwd.
Skip-store bypass. init and bootstrap are in noDbCommands, so the root hook
returns before the gate and neither file calls CheckReadonly. bd init
--reinit-local destroyed and recreated the very database the marker protects,
exit 0, marker never read. Both now gate themselves, init at the one point
every destructive variant passes through (ahead of --proxied-server, which
reaches its writes without taking the init mutation gate at all).
Fail closed. A stat error on the marker or an ancestor read as "not frozen",
indistinguishable from the documented opt-out. Find now reports it and the
refusal says bd could not tell, rather than assuming an open workspace.
Marker hardening. Only a regular file is a marker (a directory named
MIGRATION-FREEZE no longer freezes a tree), the read is capped, markers found
by the walk in a world-writable sticky directory are ignored (/tmp: forgeable
by anyone, undeletable by the victim the refusal instructs), and the payload is
sanitized before it reaches a terminal. parse splits before trimming, so a
marker recording a reason but no operator keeps its fields instead of sliding
the timestamp into the operator slot.
One walk per invocation, hoisted into commandFreeze; PostRunE reads the same
answer and stands its own maintenance down, so a read run during a freeze no
longer leaves an auto-commit, tip metadata, backup, export or push in the
store being migrated.
Cobra no longer appends "Error: exit code 14" and a usage dump to the refusal
on the commands that set neither Silence flag.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(migration): add the probe and targeted-gate entry points, with coverage
migrationFreezeActive is the silent probe for diagnosis paths that keep
running while frozen but must skip their own writes; migrationFreezeErrorFor
refuses against a workspace the command was handed rather than the one it was
launched in. Both are the surface the doctor-gate work (#6056) already calls,
under the names and signatures it expects, so that merge resolves errors.go to
this branch with its own callers untouched.
Covered by a test that pins both against the gate rather than leaving them as
uncalled code.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(migration): stop the tip-freeze test leaking process globals
recordTipShown's no-freeze branch records a pending tip write in
commandDidWriteTipMetadata/commandTipIDsShown — the same globals
PersistentPostRunE reads to decide whether to apply one. Leaving them set
handed TestPersistentPostRunE_ClearsOnErrorPath a pending write and a nil
store, which it dereferenced: a panic that only appeared in a full-package run.
Restore all three globals, and assert on both of recordTipShown's branches
rather than on whichever one the resolved dolt auto-commit mode selects — the
immediate-write branch is not the one taken once an earlier test in the
package has turned auto-commit on.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(migration): honor a symlinked freeze marker on the authoritative env path
The MIGRATION-FREEZE hardening keyed "is this a marker?" on os.Lstat +
IsRegular(), which is false for a symlink. A marker that is a symlink --
including one named by the authoritative BD_MIGRATION_FREEZE_FILE -- was
therefore read as "not frozen" and writes proceeded silently at exit 0:
a fail-open in the one gate that must never fail open (review Finding 1,
PR #6043).
statMarker now takes a `trusted` flag:
- On the operator-named BD_MIGRATION_FREEZE_FILE path it follows the link
with os.Stat and freezes when the target is a regular marker, so an
indirection like `current -> releases/N` works as intended.
- On the untrusted ancestor walk it still refuses to follow a symlink
(anything the walk passed through could otherwise redirect the gate),
but now emits a one-line stderr warning so the skip is visible instead
of a silent bypass.
Adds symlink coverage to freeze_test.go (env follows to a real marker,
dangling env symlink stays unfrozen, walk symlink is ignored with a
warning) and documents the regular-file requirement plus the env-path
symlink exception in the Migration Freeze reference.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
422 lines
12 KiB
Go
422 lines
12 KiB
Go
package main
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"math/rand"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type tipMetadataReader interface {
|
|
GetLocalMetadata(context.Context, string) (string, error)
|
|
}
|
|
|
|
type tipMetadataWriter interface {
|
|
SetLocalMetadata(context.Context, string, string) error
|
|
}
|
|
|
|
type tipMetadataStore interface {
|
|
tipMetadataReader
|
|
tipMetadataWriter
|
|
}
|
|
|
|
// Tip represents a contextual hint that can be shown to users after successful commands
|
|
type Tip struct {
|
|
ID string
|
|
Condition func() bool // Should this tip be eligible?
|
|
Message string // The tip message to display
|
|
Frequency time.Duration // Minimum gap between showings
|
|
Priority int // Higher = shown first when eligible
|
|
Probability float64 // 0.0 to 1.0 - chance of showing when eligible
|
|
}
|
|
|
|
var (
|
|
// tips is the registry of all available tips
|
|
tips []Tip
|
|
|
|
// tipsMutex protects the tips registry for thread-safe access
|
|
tipsMutex sync.RWMutex
|
|
|
|
// tipRand is the random number generator for probability rolls
|
|
// Can be seeded deterministically via BEADS_TIP_SEED for testing
|
|
tipRand *rand.Rand
|
|
|
|
// tipRandOnce ensures we only initialize the RNG once
|
|
tipRandOnce sync.Once
|
|
)
|
|
|
|
// initTipRand initializes the random number generator for tip selection
|
|
// Uses BEADS_TIP_SEED env var for deterministic testing if set
|
|
func initTipRand() {
|
|
tipRandOnce.Do(func() {
|
|
seed := time.Now().UnixNano()
|
|
if seedStr := os.Getenv("BEADS_TIP_SEED"); seedStr != "" {
|
|
if parsedSeed, err := strconv.ParseInt(seedStr, 10, 64); err == nil {
|
|
seed = parsedSeed
|
|
}
|
|
}
|
|
// Use deprecated rand.NewSource for Go 1.19 compatibility
|
|
// nolint:gosec,staticcheck // G404: deterministic seed via env var is intentional for testing
|
|
tipRand = rand.New(rand.NewSource(seed))
|
|
})
|
|
}
|
|
|
|
// maybeShowTip selects and displays an eligible tip based on priority and probability
|
|
// Respects --json and --quiet flags
|
|
func maybeShowTip(store tipMetadataStore) {
|
|
// Skip tips in JSON output mode or quiet mode
|
|
if jsonOutput || quietFlag {
|
|
return
|
|
}
|
|
|
|
// Initialize RNG if needed
|
|
initTipRand()
|
|
|
|
// Select next tip
|
|
tip := selectNextTip(store)
|
|
if tip == nil {
|
|
return
|
|
}
|
|
|
|
// Display tip to stdout (informational, not an error)
|
|
_, _ = fmt.Fprintf(os.Stdout, "\n💡 Tip: %s\n", tip.Message)
|
|
|
|
// Record that we showed this tip
|
|
recordTipShown(store, tip.ID)
|
|
}
|
|
|
|
// selectNextTip finds the next tip to show based on conditions, frequency, priority, and probability
|
|
// Returns nil if no tip should be shown
|
|
func selectNextTip(store tipMetadataReader) *Tip {
|
|
if store == nil {
|
|
return nil
|
|
}
|
|
|
|
now := time.Now()
|
|
var eligibleTips []Tip
|
|
|
|
// Lock for reading the tip registry
|
|
tipsMutex.RLock()
|
|
defer tipsMutex.RUnlock()
|
|
|
|
// Filter to eligible tips (condition + frequency check)
|
|
for _, tip := range tips {
|
|
// Check if tip's condition is met
|
|
if !tip.Condition() {
|
|
continue
|
|
}
|
|
|
|
// Check if enough time has passed since last showing
|
|
lastShown := getLastShown(store, tip.ID)
|
|
if !lastShown.IsZero() && now.Sub(lastShown) < tip.Frequency {
|
|
continue
|
|
}
|
|
|
|
eligibleTips = append(eligibleTips, tip)
|
|
}
|
|
|
|
if len(eligibleTips) == 0 {
|
|
return nil
|
|
}
|
|
|
|
// Sort by priority (highest first)
|
|
slices.SortFunc(eligibleTips, func(a, b Tip) int {
|
|
return cmp.Compare(b.Priority, a.Priority) // descending order
|
|
})
|
|
|
|
// Apply probability roll (in priority order)
|
|
// Higher priority tips get first chance to show
|
|
for i := range eligibleTips {
|
|
if tipRand.Float64() < eligibleTips[i].Probability {
|
|
return &eligibleTips[i]
|
|
}
|
|
}
|
|
|
|
return nil // No tips won probability roll
|
|
}
|
|
|
|
// getLastShown retrieves the timestamp when a tip was last shown
|
|
// Returns zero time if never shown
|
|
func getLastShown(store tipMetadataReader, tipID string) time.Time {
|
|
key := fmt.Sprintf("tip_%s_last_shown", tipID)
|
|
value, err := store.GetLocalMetadata(context.Background(), key)
|
|
if err != nil || value == "" {
|
|
return time.Time{}
|
|
}
|
|
|
|
// Parse RFC3339 timestamp
|
|
t, err := time.Parse(time.RFC3339, value)
|
|
if err != nil {
|
|
return time.Time{}
|
|
}
|
|
|
|
return t
|
|
}
|
|
|
|
// recordTipShown records the timestamp when a tip was shown
|
|
func recordTipShown(store tipMetadataWriter, tipID string) {
|
|
if store == nil || tipID == "" {
|
|
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.
|
|
if mode, err := getDoltAutoCommitMode(); err == nil && mode == doltAutoCommitOn {
|
|
commandDidWriteTipMetadata = true
|
|
if commandTipIDsShown == nil {
|
|
commandTipIDsShown = make(map[string]struct{})
|
|
}
|
|
commandTipIDsShown[tipID] = struct{}{}
|
|
return
|
|
}
|
|
|
|
key := fmt.Sprintf("tip_%s_last_shown", tipID)
|
|
value := time.Now().Format(time.RFC3339)
|
|
|
|
// Non-critical metadata, ok to fail silently.
|
|
// If it succeeds, track the write for tip auto-commit behavior.
|
|
if err := store.SetLocalMetadata(context.Background(), key, value); err == nil {
|
|
commandDidWriteTipMetadata = true
|
|
if commandTipIDsShown == nil {
|
|
commandTipIDsShown = make(map[string]struct{})
|
|
}
|
|
commandTipIDsShown[tipID] = struct{}{}
|
|
}
|
|
}
|
|
|
|
// InjectTip adds a dynamic tip to the registry at runtime.
|
|
// This enables tips to be programmatically added based on detected conditions.
|
|
//
|
|
// Parameters:
|
|
// - id: Unique identifier for the tip (used for frequency tracking)
|
|
// - message: The tip message to display to the user
|
|
// - priority: Higher values = shown first when eligible (e.g., 100 for critical, 30 for suggestions)
|
|
// - frequency: Minimum time between showings (e.g., 24*time.Hour for daily)
|
|
// - probability: Chance of showing when eligible (0.0 to 1.0)
|
|
// - condition: Function that returns true when tip should be eligible
|
|
//
|
|
// Example usage:
|
|
//
|
|
// // Critical security update - always show
|
|
// InjectTip("security_update", "CRITICAL: Security update available!", 100, 0, 1.0, func() bool { return true })
|
|
//
|
|
// // New version available - frequent but not always
|
|
// InjectTip("upgrade_available", "New version available", 90, 7*24*time.Hour, 0.8, func() bool { return true })
|
|
//
|
|
// // Feature suggestion - occasional
|
|
// InjectTip("try_filters", "Try using filters", 50, 14*24*time.Hour, 0.4, func() bool { return true })
|
|
func InjectTip(id, message string, priority int, frequency time.Duration, probability float64, condition func() bool) {
|
|
tipsMutex.Lock()
|
|
defer tipsMutex.Unlock()
|
|
|
|
// Check if tip with this ID already exists - update it if so
|
|
for i, tip := range tips {
|
|
if tip.ID == id {
|
|
tips[i] = Tip{
|
|
ID: id,
|
|
Condition: condition,
|
|
Message: message,
|
|
Frequency: frequency,
|
|
Priority: priority,
|
|
Probability: probability,
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
// Add new tip
|
|
tips = append(tips, Tip{
|
|
ID: id,
|
|
Condition: condition,
|
|
Message: message,
|
|
Frequency: frequency,
|
|
Priority: priority,
|
|
Probability: probability,
|
|
})
|
|
}
|
|
|
|
// RemoveTip removes a tip from the registry by ID.
|
|
// This is useful for removing dynamically injected tips when they are no longer relevant.
|
|
// It is safe to call with a non-existent ID (no-op).
|
|
func RemoveTip(id string) {
|
|
tipsMutex.Lock()
|
|
defer tipsMutex.Unlock()
|
|
|
|
for i, tip := range tips {
|
|
if tip.ID == id {
|
|
tips = append(tips[:i], tips[i+1:]...)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// isClaudeDetected checks if the user is running within a Claude Code environment.
|
|
// Detection methods:
|
|
// - CLAUDE_CODE environment variable (set by Claude Code)
|
|
// - ANTHROPIC_CLI environment variable
|
|
// - Presence of ~/.claude directory (Claude Code config)
|
|
func isClaudeDetected() bool {
|
|
// Check environment variables set by Claude Code
|
|
if os.Getenv("CLAUDE_CODE") != "" || os.Getenv("ANTHROPIC_CLI") != "" {
|
|
return true
|
|
}
|
|
|
|
// Check if ~/.claude directory exists (Claude Code stores config here)
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if _, err := os.Stat(filepath.Join(home, ".claude")); err == nil {
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// isClaudeSetupComplete checks if the beads Claude integration is properly configured.
|
|
// Returns true if the beads plugin is installed (provides hooks via plugin.json),
|
|
// or if hooks were manually installed via 'bd setup claude'.
|
|
func isClaudeSetupComplete() bool {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
// Check if beads plugin is installed - plugin now provides hooks automatically
|
|
settingsPath := filepath.Join(home, ".claude", "settings.json")
|
|
// #nosec G304 - path is constructed from user home directory
|
|
if data, err := os.ReadFile(settingsPath); err == nil {
|
|
var settings map[string]interface{}
|
|
if err := json.Unmarshal(data, &settings); err == nil {
|
|
if enabledPlugins, ok := settings["enabledPlugins"].(map[string]interface{}); ok {
|
|
for key, value := range enabledPlugins {
|
|
if strings.Contains(strings.ToLower(key), "beads") {
|
|
if enabled, ok := value.(bool); ok && enabled {
|
|
return true // Plugin installed - provides hooks
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Check for manual hooks installation via 'bd setup claude'
|
|
// Global hooks in settings.json
|
|
if hasBeadsPrimeHooks(settingsPath) {
|
|
return true
|
|
}
|
|
|
|
// Project-level hooks in .claude/settings.local.json
|
|
localSettingsPath := filepath.Join(home, ".claude", "settings.local.json")
|
|
if hasBeadsPrimeHooks(localSettingsPath) {
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// hasBeadsPrimeHooks checks if a settings file has bd prime hooks configured
|
|
func hasBeadsPrimeHooks(settingsPath string) bool {
|
|
// #nosec G304 - path is constructed from user home directory
|
|
data, err := os.ReadFile(settingsPath)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
var settings map[string]interface{}
|
|
if err := json.Unmarshal(data, &settings); err != nil {
|
|
return false
|
|
}
|
|
|
|
hooks, ok := settings["hooks"].(map[string]interface{})
|
|
if !ok {
|
|
return false
|
|
}
|
|
|
|
// Check SessionStart and PreCompact for "bd prime"
|
|
for _, event := range []string{"SessionStart", "PreCompact"} {
|
|
eventHooks, ok := hooks[event].([]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
|
|
for _, hook := range eventHooks {
|
|
hookMap, ok := hook.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
commands, ok := hookMap["hooks"].([]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
for _, cmd := range commands {
|
|
cmdMap, ok := cmd.(map[string]interface{})
|
|
if !ok {
|
|
continue
|
|
}
|
|
cmdStr, _ := cmdMap["command"].(string)
|
|
if cmdStr == "bd prime" || cmdStr == "bd prime --stealth" {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// initDefaultTips registers the built-in tips.
|
|
// Called during initialization to populate the tip registry.
|
|
func initDefaultTips() {
|
|
// Claude setup tip - suggest installing the beads plugin when Claude is detected
|
|
// but the integration is not configured
|
|
InjectTip(
|
|
"claude_setup",
|
|
"Install the beads plugin for automatic workflow context, or run 'bd setup claude' for CLI-only mode",
|
|
100, // Highest priority - this is important for Claude users
|
|
24*time.Hour, // Daily minimum gap
|
|
0.6, // 60% chance when eligible (~4 times per week)
|
|
func() bool {
|
|
return isClaudeDetected() && !isClaudeSetupComplete()
|
|
},
|
|
)
|
|
|
|
// Sync conflict tip - ALWAYS show when sync has failed and needs manual intervention
|
|
// This is a proactive health check that trumps educational tips (ox-cli pattern)
|
|
InjectTip(
|
|
"sync_conflict",
|
|
"Run 'bd dolt pull' to resolve sync conflict",
|
|
200, // Higher than Claude setup - sync issues are urgent
|
|
0, // No frequency limit - always show when applicable
|
|
1.0, // 100% probability - always show when condition is true
|
|
syncConflictCondition,
|
|
)
|
|
}
|
|
|
|
// syncConflictCondition checks if there's a sync conflict that needs manual resolution.
|
|
// Sync conflict tracking was removed — always returns false.
|
|
func syncConflictCondition() bool {
|
|
return false
|
|
}
|
|
|
|
// init initializes the tip system with default tips
|
|
func init() {
|
|
initDefaultTips()
|
|
}
|