feat(hooks): implement thin shim pattern (GH#615)

Replace full shell script hooks with thin shims that delegate to
'bd hooks run <hook-name>'. This eliminates hook version drift -
upgrading bd automatically updates hook behavior.

Changes:
- Add 'bd hooks run' subcommand with hook logic in Go
- Convert templates to minimal shims (~17 lines each)
- Shims use '# bd-shim v1' marker (format version, not bd version)
- Update version checking to recognize shim format
- Shims are never marked as "outdated"

Benefits:
- No more manual 'bd hooks install --force' after upgrades
- Hook logic always matches installed bd version
- Follows pattern used by husky, pre-commit, lefthook

Migration: Run 'bd hooks install --force' one final time.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Steve Yegge
2025-12-20 02:38:12 -08:00
parent b4bc682d93
commit 3050fd2ef8
6 changed files with 358 additions and 314 deletions

View File

@@ -33,12 +33,14 @@ func getEmbeddedHooks() (map[string]string, error) {
}
const hookVersionPrefix = "# bd-hooks-version: "
const shimVersionPrefix = "# bd-shim "
// HookStatus represents the status of a single git hook
type HookStatus struct {
Name string
Installed bool
Version string
IsShim bool // true if this is a thin shim (version-agnostic)
Outdated bool
}
@@ -64,16 +66,18 @@ func CheckGitHooks() []HookStatus {
// Check if hook exists
hookPath := filepath.Join(gitDir, "hooks", hookName)
version, err := getHookVersion(hookPath)
versionInfo, err := getHookVersion(hookPath)
if err != nil {
// Hook doesn't exist or couldn't be read
status.Installed = false
} else {
status.Installed = true
status.Version = version
status.Version = versionInfo.Version
status.IsShim = versionInfo.IsShim
// Check if outdated (compare to current bd version)
if version != "" && version != Version {
// Thin shims are never outdated (they delegate to bd)
// Legacy hooks are outdated if version differs from current bd version
if !versionInfo.IsShim && versionInfo.Version != "" && versionInfo.Version != Version {
status.Outdated = true
}
}
@@ -84,12 +88,18 @@ func CheckGitHooks() []HookStatus {
return statuses
}
// hookVersionInfo contains version information extracted from a hook file
type hookVersionInfo struct {
Version string // bd version (for legacy hooks) or shim version
IsShim bool // true if this is a thin shim
}
// getHookVersion extracts the version from a hook file
func getHookVersion(path string) (string, error) {
func getHookVersion(path string) (hookVersionInfo, error) {
// #nosec G304 -- hook path constrained to .git/hooks directory
file, err := os.Open(path)
if err != nil {
return "", err
return hookVersionInfo{}, err
}
defer file.Close()
@@ -98,15 +108,21 @@ func getHookVersion(path string) (string, error) {
lineCount := 0
for scanner.Scan() && lineCount < 10 {
line := scanner.Text()
// Check for thin shim marker first
if strings.HasPrefix(line, shimVersionPrefix) {
version := strings.TrimSpace(strings.TrimPrefix(line, shimVersionPrefix))
return hookVersionInfo{Version: version, IsShim: true}, nil
}
// Check for legacy version marker
if strings.HasPrefix(line, hookVersionPrefix) {
version := strings.TrimSpace(strings.TrimPrefix(line, hookVersionPrefix))
return version, nil
return hookVersionInfo{Version: version, IsShim: false}, nil
}
lineCount++
}
// No version found (old hook)
return "", nil
return hookVersionInfo{}, nil
}
// FormatHookWarnings returns a formatted warning message if hooks are outdated
@@ -275,6 +291,8 @@ var hooksListCmd = &cobra.Command{
for _, status := range statuses {
if !status.Installed {
fmt.Printf(" ✗ %s: not installed\n", status.Name)
} else if status.IsShim {
fmt.Printf(" ✓ %s: installed (shim %s)\n", status.Name, status.Version)
} else if status.Outdated {
fmt.Printf(" ⚠ %s: installed (version %s, current: %s) - outdated\n",
status.Name, status.Version, Version)
@@ -383,6 +401,295 @@ func uninstallHooks() error {
return nil
}
// =============================================================================
// Hook Implementation Functions (called by thin shims via 'bd hooks run')
// =============================================================================
// runPreCommitHook flushes pending changes to JSONL before commit.
// Returns 0 on success (or if not applicable), non-zero on error.
func runPreCommitHook() int {
// Check if we're in a bd workspace
if _, err := os.Stat(".beads"); os.IsNotExist(err) {
return 0 // Not a bd workspace, nothing to do
}
// Check if sync-branch is configured (changes go to separate branch)
if hookGetSyncBranch() != "" {
return 0 // Skip - changes synced to separate branch
}
// Flush pending changes to JSONL
// Use --flush-only to skip git operations (we're already in a git hook)
cmd := exec.Command("bd", "sync", "--flush-only")
if err := cmd.Run(); err != nil {
fmt.Fprintln(os.Stderr, "Warning: Failed to flush bd changes to JSONL")
fmt.Fprintln(os.Stderr, "Run 'bd sync --flush-only' manually to diagnose")
// Don't block the commit - user may have removed beads or have other issues
}
// Stage all tracked JSONL files
for _, f := range []string{".beads/beads.jsonl", ".beads/issues.jsonl", ".beads/deletions.jsonl"} {
if _, err := os.Stat(f); err == nil {
gitAdd := exec.Command("git", "add", f)
_ = gitAdd.Run() // Ignore errors - file may not exist
}
}
return 0
}
// runPostMergeHook imports JSONL after pull/merge.
// Returns 0 on success (or if not applicable), non-zero on error.
func runPostMergeHook() int {
// Skip during rebase
if isRebaseInProgress() {
return 0
}
// Check if we're in a bd workspace
if _, err := os.Stat(".beads"); os.IsNotExist(err) {
return 0
}
// Check if any JSONL file exists
if !hasBeadsJSONL() {
return 0
}
// Run bd sync --import-only --no-git-history
cmd := exec.Command("bd", "sync", "--import-only", "--no-git-history")
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintln(os.Stderr, "Warning: Failed to sync bd changes after merge")
fmt.Fprintln(os.Stderr, string(output))
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Run 'bd doctor --fix' to diagnose and repair")
// Don't fail the merge, just warn
}
// Run quick health check
healthCmd := exec.Command("bd", "doctor", "--check-health")
_ = healthCmd.Run() // Ignore errors
return 0
}
// runPrePushHook prevents pushing stale JSONL.
// Returns 0 to allow push, non-zero to block.
func runPrePushHook() int {
// Check if we're in a bd workspace
if _, err := os.Stat(".beads"); os.IsNotExist(err) {
return 0
}
// Skip if bd sync is already in progress (prevents circular error)
if os.Getenv("BD_SYNC_IN_PROGRESS") != "" {
return 0
}
// Check if sync-branch is configured
if hookGetSyncBranch() != "" {
return 0 // Skip - changes synced to separate branch
}
// Flush pending bd changes
flushCmd := exec.Command("bd", "sync", "--flush-only")
_ = flushCmd.Run() // Ignore errors
// Check for uncommitted JSONL changes
files := []string{}
for _, f := range []string{".beads/beads.jsonl", ".beads/issues.jsonl", ".beads/deletions.jsonl"} {
// Check if file exists or is tracked
if _, err := os.Stat(f); err == nil {
files = append(files, f)
} else {
// Check if tracked by git
checkCmd := exec.Command("git", "ls-files", "--error-unmatch", f)
if checkCmd.Run() == nil {
files = append(files, f)
}
}
}
if len(files) == 0 {
return 0
}
// Check for uncommitted changes using git status
args := append([]string{"status", "--porcelain", "--"}, files...)
statusCmd := exec.Command("git", args...)
output, _ := statusCmd.Output()
if len(output) > 0 {
fmt.Fprintln(os.Stderr, "❌ Error: Uncommitted changes detected")
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Before pushing, ensure all changes are committed. This includes:")
fmt.Fprintln(os.Stderr, " • bd JSONL updates (run 'bd sync')")
fmt.Fprintln(os.Stderr, " • any other modified files (run 'git status' to review)")
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Run 'bd sync' to commit these changes:")
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, " bd sync")
fmt.Fprintln(os.Stderr, "")
return 1
}
return 0
}
// runPostCheckoutHook imports JSONL after branch checkout.
// args: [previous-HEAD, new-HEAD, flag] where flag=1 for branch checkout
// Returns 0 on success (or if not applicable), non-zero on error.
func runPostCheckoutHook(args []string) int {
// Only run on branch checkouts (flag=1)
if len(args) >= 3 && args[2] != "1" {
return 0
}
// Skip during rebase
if isRebaseInProgress() {
return 0
}
// Check if we're in a bd workspace
if _, err := os.Stat(".beads"); os.IsNotExist(err) {
return 0
}
// Detect git worktree and show warning
if isGitWorktree() {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "╔══════════════════════════════════════════════════════════════════════════╗")
fmt.Fprintln(os.Stderr, "║ Welcome to beads in git worktree! ║")
fmt.Fprintln(os.Stderr, "╠══════════════════════════════════════════════════════════════════════════╣")
fmt.Fprintln(os.Stderr, "║ Note: Daemon mode is not recommended with git worktrees. ║")
fmt.Fprintln(os.Stderr, "║ Worktrees share the same database, and the daemon may commit changes ║")
fmt.Fprintln(os.Stderr, "║ to the wrong branch. ║")
fmt.Fprintln(os.Stderr, "║ ║")
fmt.Fprintln(os.Stderr, "║ RECOMMENDED: Disable daemon for this session: ║")
fmt.Fprintln(os.Stderr, "║ export BEADS_NO_DAEMON=1 ║")
fmt.Fprintln(os.Stderr, "║ ║")
fmt.Fprintln(os.Stderr, "║ For more information: ║")
fmt.Fprintln(os.Stderr, "║ - Run: bd doctor ║")
fmt.Fprintln(os.Stderr, "║ - Read: docs/GIT_INTEGRATION.md (lines 10-53) ║")
fmt.Fprintln(os.Stderr, "╚══════════════════════════════════════════════════════════════════════════╝")
fmt.Fprintln(os.Stderr, "")
}
// Check if any JSONL file exists
if !hasBeadsJSONL() {
return 0
}
// Run bd sync --import-only --no-git-history
cmd := exec.Command("bd", "sync", "--import-only", "--no-git-history")
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintln(os.Stderr, "Warning: Failed to sync bd changes after checkout")
fmt.Fprintln(os.Stderr, string(output))
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Run 'bd doctor --fix' to diagnose and repair")
// Don't fail the checkout, just warn
}
// Run quick health check
healthCmd := exec.Command("bd", "doctor", "--check-health")
_ = healthCmd.Run() // Ignore errors
return 0
}
// =============================================================================
// Hook Helper Functions
// =============================================================================
// hookGetSyncBranch returns the configured sync branch for hook context.
// This is a simplified version that doesn't require context.
func hookGetSyncBranch() string {
// Check environment variable first
if branch := os.Getenv("BEADS_SYNC_BRANCH"); branch != "" {
return branch
}
// Check config.yaml
configPath := ".beads/config.yaml"
data, err := os.ReadFile(configPath) // #nosec G304 -- config path is hardcoded
if err != nil {
return ""
}
// Simple YAML parsing for sync-branch
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "sync-branch:") {
value := strings.TrimPrefix(line, "sync-branch:")
value = strings.TrimSpace(value)
value = strings.Trim(value, `"'`)
return value
}
}
return ""
}
// isRebaseInProgress checks if a rebase is in progress.
func isRebaseInProgress() bool {
if _, err := os.Stat(".git/rebase-merge"); err == nil {
return true
}
if _, err := os.Stat(".git/rebase-apply"); err == nil {
return true
}
return false
}
// hasBeadsJSONL checks if any JSONL file exists in .beads/.
func hasBeadsJSONL() bool {
for _, f := range []string{".beads/beads.jsonl", ".beads/issues.jsonl", ".beads/deletions.jsonl"} {
if _, err := os.Stat(f); err == nil {
return true
}
}
return false
}
var hooksRunCmd = &cobra.Command{
Use: "run <hook-name> [args...]",
Short: "Execute a git hook (called by thin shims)",
Long: `Execute the logic for a git hook. This command is typically called by
thin shim scripts installed in .git/hooks/.
Supported hooks:
- pre-commit: Flush pending changes to JSONL before commit
- post-merge: Import JSONL after pull/merge
- pre-push: Prevent pushing stale JSONL
- post-checkout: Import JSONL after branch checkout
The thin shim pattern ensures hook logic is always in sync with the
installed bd version - upgrading bd automatically updates hook behavior.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
hookName := args[0]
hookArgs := args[1:]
var exitCode int
switch hookName {
case "pre-commit":
exitCode = runPreCommitHook()
case "post-merge":
exitCode = runPostMergeHook()
case "pre-push":
exitCode = runPrePushHook()
case "post-checkout":
exitCode = runPostCheckoutHook(hookArgs)
default:
fmt.Fprintf(os.Stderr, "Unknown hook: %s\n", hookName)
os.Exit(1)
}
os.Exit(exitCode)
},
}
func init() {
hooksInstallCmd.Flags().Bool("force", false, "Overwrite existing hooks without backup")
hooksInstallCmd.Flags().Bool("shared", false, "Install hooks to .beads-hooks/ (versioned) instead of .git/hooks/")
@@ -390,6 +697,7 @@ func init() {
hooksCmd.AddCommand(hooksInstallCmd)
hooksCmd.AddCommand(hooksUninstallCmd)
hooksCmd.AddCommand(hooksListCmd)
hooksCmd.AddCommand(hooksRunCmd)
rootCmd.AddCommand(hooksCmd)
}

View File

@@ -267,8 +267,12 @@ func TestHooksCheckGitHooks(t *testing.T) {
if !status.Installed {
t.Errorf("Hook %s should be installed", status.Name)
}
if status.Version != Version {
t.Errorf("Hook %s version mismatch: got %s, want %s", status.Name, status.Version, Version)
// Thin shims use version format "v1" (shim format version, not bd version)
if !status.IsShim {
t.Errorf("Hook %s should be a thin shim", status.Name)
}
if status.Version != "v1" {
t.Errorf("Hook %s shim version mismatch: got %s, want v1", status.Name, status.Version)
}
if status.Outdated {
t.Errorf("Hook %s should not be outdated", status.Name)

View File

@@ -1,89 +1,16 @@
#!/bin/sh
# bd-hooks-version: 0.30.7
# bd-shim v1
#
# bd (beads) post-checkout hook
# bd (beads) post-checkout hook - thin shim
#
# This hook syncs the bd database after a branch checkout:
# 1. Checks if any .beads/*.jsonl file was updated
# 2. Runs 'bd sync --import-only --no-git-history' to import changes
#
# Arguments provided by git:
# $1 = ref of previous HEAD
# $2 = ref of new HEAD
# $3 = flag (1 if branch checkout, 0 if file checkout)
#
# Install: cp examples/git-hooks/post-checkout .git/hooks/post-checkout && chmod +x .git/hooks/post-checkout
# Only run on branch checkouts
if [ "$3" != "1" ]; then
exit 0
fi
# Skip during rebase - git checks out commits during rebase and we must not
# modify working tree files (like deletions.jsonl) or the rebase will fail
if [ -d .git/rebase-merge ] || [ -d .git/rebase-apply ]; then
exit 0
fi
# This shim delegates to 'bd hooks run post-checkout' which contains
# the actual hook logic. This pattern ensures hook behavior is always
# in sync with the installed bd version - no manual updates needed.
# Check if bd is available
if ! command -v bd >/dev/null 2>&1; then
# Silently skip - post-checkout is called frequently
exit 0
fi
# Check if we're in a bd workspace
if [ ! -d .beads ]; then
exit 0
fi
# Detect git worktree: compare --git-dir and --git-common-dir
GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
GIT_COMMON_DIR=$(git rev-parse --git-common-dir 2>/dev/null)
if [ -n "$GIT_DIR" ] && [ -n "$GIT_COMMON_DIR" ]; then
GIT_DIR_ABS=$(cd "$GIT_DIR" 2>/dev/null && pwd || echo "$GIT_DIR")
GIT_COMMON_DIR_ABS=$(cd "$GIT_COMMON_DIR" 2>/dev/null && pwd || echo "$GIT_COMMON_DIR")
if [ "$GIT_DIR_ABS" != "$GIT_COMMON_DIR_ABS" ]; then
# We're in a git worktree
cat >&2 <<'EOF'
╔══════════════════════════════════════════════════════════════════════════╗
║ Welcome to beads in git worktree! ║
╠══════════════════════════════════════════════════════════════════════════╣
║ Note: Daemon mode is not recommended with git worktrees. ║
║ Worktrees share the same database, and the daemon may commit changes ║
║ to the wrong branch. ║
║ ║
║ RECOMMENDED: Disable daemon for this session: ║
║ export BEADS_NO_DAEMON=1 ║
║ ║
║ For more information: ║
║ - Run: bd doctor ║
║ - Read: docs/GIT_INTEGRATION.md (lines 10-53) ║
║ ║
║ Issue tracking: bd-dc9 ║
╚══════════════════════════════════════════════════════════════════════════╝
EOF
fi
fi
# Check if any JSONL file exists in .beads/
if ! ls .beads/*.jsonl >/dev/null 2>&1; then
exit 0
fi
# Run bd sync --import-only --no-git-history to import the updated JSONL
# --no-git-history prevents writes to deletions.jsonl (critical during rebase)
if ! output=$(bd sync --import-only --no-git-history 2>&1); then
echo "Warning: Failed to sync bd changes after checkout" >&2
echo "$output" >&2
echo "" >&2
echo "Run 'bd doctor --fix' to diagnose and repair" >&2
# Don't fail the checkout, just warn
fi
# Run quick health check (silent on success, hints if issues found)
# This catches version mismatches, outdated hooks, etc.
bd doctor --check-health 2>/dev/null || true
exit 0
exec bd hooks run post-checkout "$@"

View File

@@ -1,56 +1,18 @@
#!/bin/sh
# bd-hooks-version: 0.30.7
# bd-shim v1
#
# bd (beads) post-merge hook
# bd (beads) post-merge hook - thin shim
#
# This hook syncs the bd database after a git pull or merge:
# 1. Checks if any .beads/*.jsonl file was updated
# 2. Runs 'bd sync --import-only --no-git-history' to import changes
#
# Installation:
# cp examples/git-hooks/post-merge .git/hooks/post-merge
# chmod +x .git/hooks/post-merge
#
# Or use the install script:
# examples/git-hooks/install.sh
# Skip during rebase - git may run post-merge during rebase operations
# and we must not modify working tree files or the rebase will fail
if [ -d .git/rebase-merge ] || [ -d .git/rebase-apply ]; then
exit 0
fi
# This shim delegates to 'bd hooks run post-merge' which contains
# the actual hook logic. This pattern ensures hook behavior is always
# in sync with the installed bd version - no manual updates needed.
# Check if bd is available
if ! command -v bd >/dev/null 2>&1; then
echo "Warning: bd command not found, skipping post-merge sync" >&2
echo "Warning: bd command not found in PATH, skipping post-merge hook" >&2
echo " Install bd: brew install steveyegge/tap/bd" >&2
echo " Or add bd to your PATH" >&2
exit 0
fi
# Check if we're in a bd workspace
if [ ! -d .beads ]; then
# Not a bd workspace, nothing to do
exit 0
fi
# Check if any JSONL file exists in .beads/
if ! ls .beads/*.jsonl >/dev/null 2>&1; then
exit 0
fi
# Run bd sync --import-only --no-git-history to import the updated JSONL
# --no-git-history prevents writes to deletions.jsonl during hook operations
# This is more robust than direct import as it handles all edge cases
# Capture both stdout and stderr to show user what went wrong
if ! output=$(bd sync --import-only --no-git-history 2>&1); then
echo "Warning: Failed to sync bd changes after merge" >&2
echo "$output" >&2
echo "" >&2
echo "Run 'bd doctor --fix' to diagnose and repair" >&2
# Don't fail the merge, just warn
fi
# Run quick health check (silent on success, hints if issues found)
# This catches version mismatches, outdated hooks, etc.
bd doctor --check-health 2>/dev/null || true
exit 0
exec bd hooks run post-merge "$@"

View File

@@ -1,63 +1,18 @@
#!/bin/sh
# bd-hooks-version: 0.30.7
# bd-shim v1
#
# bd (beads) pre-commit hook
# bd (beads) pre-commit hook - thin shim
#
# This hook ensures that any pending bd issue changes are flushed to
# .beads/issues.jsonl before the commit is created, preventing the
# race condition where daemon auto-flush fires after the commit.
#
# When sync-branch is configured in config.yaml, .beads changes are committed
# to a separate branch via worktree, so auto-staging is skipped.
#
# Installation:
# cp examples/git-hooks/pre-commit .git/hooks/pre-commit
# chmod +x .git/hooks/pre-commit
#
# Or use the install script:
# examples/git-hooks/install.sh
# This shim delegates to 'bd hooks run pre-commit' which contains
# the actual hook logic. This pattern ensures hook behavior is always
# in sync with the installed bd version - no manual updates needed.
# Check if bd is available
if ! command -v bd >/dev/null 2>&1; then
echo "Warning: bd command not found, skipping pre-commit flush" >&2
echo "Warning: bd command not found in PATH, skipping pre-commit hook" >&2
echo " Install bd: brew install steveyegge/tap/bd" >&2
echo " Or add bd to your PATH" >&2
exit 0
fi
# Check if we're in a bd workspace
if [ ! -d .beads ]; then
# Not a bd workspace, nothing to do
exit 0
fi
# Check if sync-branch is configured in config.yaml or env var
# If so, .beads changes go to a separate branch via worktree, not the current branch
SYNC_BRANCH="${BEADS_SYNC_BRANCH:-}"
if [ -z "$SYNC_BRANCH" ] && [ -f .beads/config.yaml ]; then
# Extract sync-branch value from YAML (handles quoted and unquoted values)
# Use head -1 to only take first match if file is malformed
SYNC_BRANCH=$(grep -E '^sync-branch:' .beads/config.yaml 2>/dev/null | head -1 | sed 's/^sync-branch:[[:space:]]*//' | sed 's/^["'"'"']//' | sed 's/["'"'"']$//')
fi
if [ -n "$SYNC_BRANCH" ]; then
# sync-branch is configured, skip flush and auto-staging
# Changes are synced to the separate branch via 'bd sync'
exit 0
fi
# Flush pending changes to JSONL
# Use --flush-only to skip git operations (we're already in a git hook)
# Suppress output unless there's an error
# Note: We warn but don't fail - this allows commits to proceed even if
# beads has issues (e.g., user removed .beads from their branch)
if ! bd sync --flush-only >/dev/null 2>&1; then
echo "Warning: Failed to flush bd changes to JSONL" >&2
echo "Run 'bd sync --flush-only' manually to diagnose" >&2
# Don't block the commit - user may have removed beads or have other issues
fi
# Stage all tracked JSONL files (beads.jsonl, issues.jsonl for backward compat, deletions.jsonl for deletion propagation)
# git add is harmless if file doesn't exist
for f in .beads/beads.jsonl .beads/issues.jsonl .beads/deletions.jsonl; do
[ -f "$f" ] && git add "$f" 2>/dev/null || true
done
exit 0
exec bd hooks run pre-commit "$@"

View File

@@ -1,130 +1,18 @@
#!/bin/sh
# bd-hooks-version: 0.30.7
# bd-shim v1
#
# bd (beads) pre-push hook
# bd (beads) pre-push hook - thin shim
#
# This hook prevents pushing stale JSONL by:
# 1. Flushing any pending in-memory changes to JSONL (if bd available)
# 2. Checking for uncommitted changes (staged, unstaged, untracked, deleted)
# 3. Failing the push with clear instructions if changes found
#
# When sync-branch is configured in config.yaml, .beads changes are committed
# to a separate branch via worktree, so the uncommitted check is skipped.
#
# The pre-commit hook already exports changes, but this catches:
# - Changes made between commit and push
# - Pending debounced flushes (5s daemon delay)
#
# Installation:
# cp examples/git-hooks/pre-push .git/hooks/pre-push
# chmod +x .git/hooks/pre-push
#
# Or use the install script:
# examples/git-hooks/install.sh
# This shim delegates to 'bd hooks run pre-push' which contains
# the actual hook logic. This pattern ensures hook behavior is always
# in sync with the installed bd version - no manual updates needed.
# Check if we're in a bd workspace
if [ ! -d .beads ]; then
# Not a bd workspace, nothing to do
# Check if bd is available
if ! command -v bd >/dev/null 2>&1; then
echo "Warning: bd command not found in PATH, skipping pre-push hook" >&2
echo " Install bd: brew install steveyegge/tap/bd" >&2
echo " Or add bd to your PATH" >&2
exit 0
fi
# Skip if bd sync is already in progress (GH#532: prevents circular error)
# bd sync sets this env var when pushing from worktree
if [ -n "$BD_SYNC_IN_PROGRESS" ]; then
exit 0
fi
# Check if sync-branch is configured in config.yaml or env var
# If so, .beads changes go to a separate branch via worktree, not the current branch
SYNC_BRANCH="${BEADS_SYNC_BRANCH:-}"
if [ -z "$SYNC_BRANCH" ] && [ -f .beads/config.yaml ]; then
# Extract sync-branch value from YAML (handles quoted and unquoted values)
# Use head -1 to only take first match if file is malformed
SYNC_BRANCH=$(grep -E '^sync-branch:' .beads/config.yaml 2>/dev/null | head -1 | sed 's/^sync-branch:[[:space:]]*//' | sed 's/^["'"'"']//' | sed 's/["'"'"']$//')
fi
if [ -n "$SYNC_BRANCH" ]; then
# sync-branch is configured, skip .beads uncommitted check
# Changes are synced to the separate branch, not this one
exit 0
fi
# Optionally flush pending bd changes so they surface in JSONL
# This prevents the race where a debounced flush lands after the check
if command -v bd >/dev/null 2>&1; then
bd sync --flush-only >/dev/null 2>&1 || true
fi
# Collect all tracked or existing JSONL files (beads.jsonl, issues.jsonl for backward compat, deletions.jsonl for deletion propagation)
FILES=""
for f in .beads/beads.jsonl .beads/issues.jsonl .beads/deletions.jsonl; do
# Include file if it exists in working tree OR is tracked by git (even if deleted)
if git ls-files --error-unmatch "$f" >/dev/null 2>&1 || [ -f "$f" ]; then
FILES="$FILES $f"
fi
done
# Check for any uncommitted changes using porcelain status
# This catches: staged, unstaged, untracked, deleted, renamed, and conflicts
if [ -n "$FILES" ]; then
# shellcheck disable=SC2086
if [ -n "$(git status --porcelain -- $FILES 2>/dev/null)" ]; then
echo "❌ Error: Uncommitted changes detected" >&2
echo "" >&2
echo "Before pushing, ensure all changes are committed. This includes:" >&2
echo " • bd JSONL updates (run 'bd sync')" >&2
echo " • any other modified files (run 'git status' to review)" >&2
echo "" >&2
# Check if bd is available and offer auto-sync
if command -v bd >/dev/null 2>&1; then
# Check if we're in an interactive terminal
if [ -t 0 ]; then
echo "Would you like to run 'bd sync' now to commit and push these changes? [y/N]" >&2
read -r response
case "$response" in
[yY][eE][sS]|[yY])
echo "" >&2
echo "Running: bd sync" >&2
if bd sync; then
echo "" >&2
echo "✓ Sync complete. Continuing with push..." >&2
exit 0
else
echo "" >&2
echo "❌ Sync failed. Push aborted." >&2
exit 1
fi
;;
*)
echo "" >&2
echo "Push aborted. Run 'bd sync' manually when ready:" >&2
echo "" >&2
echo " bd sync" >&2
echo " git push" >&2
echo "" >&2
exit 1
;;
esac
else
# Non-interactive: just show the message
echo "Run 'bd sync' to commit these changes:" >&2
echo "" >&2
echo " bd sync" >&2
echo "" >&2
exit 1
fi
else
# bd not available, fall back to manual git commands
echo "Please commit the updated JSONL before pushing:" >&2
echo "" >&2
# shellcheck disable=SC2086
echo " git add $FILES" >&2
echo ' git commit -m "Update bd JSONL"' >&2
echo " git push" >&2
echo "" >&2
exit 1
fi
fi
fi
exit 0
exec bd hooks run pre-push "$@"