* perf(git): locate the repository in-process instead of running git rev-parse Every bd invocation resolved the process-wide git context (beads directory discovery reads it) with `git rev-parse --git-dir --git-common-dir --show-toplevel`: one git subprocess per bd call before any work. Tools that call bd hundreds of times (gascity's doctor issues ~250 bd calls per run) paid it on every call. On Linux, initGitContext now first runs discoverGitInProcess, which mirrors Git's discovery walk (physical cwd, .git as directory or gitfile, bare-dir check, filesystem-boundary stop) and produces byte-for-byte what rev-parse prints for ordinary repositories (top and subdirectories), linked worktrees (absolute or relative gitfile, symlinked targets), submodules (core.worktree pointing back at the gitfile's directory), nested repositories and no repository. Both answers feed one shared normalization (gitContextFromRevParse), so downstream values are unchanged. It declines, and git runs exactly as before, whenever it cannot prove the answer: GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR / GIT_CEILING_DIRECTORIES / GIT_DISCOVERY_ACROSS_FILESYSTEM / GIT_OBJECT_DIRECTORY / GIT_CONFIG_PARAMETERS / GIT_CONFIG_COUNT in the environment; a symlinked .git, an invalid gitfile or git directory, a cwd inside a git directory; repository config with core.worktree (other than the submodule shape), core.bare, extensions, include directives, a format version above 1 or unmodeled syntax; any path not owned by the effective uid (safe.directory is git's to evaluate), or root under sudo. darwin and windows keep the subprocess (case folding and ownership semantics). Tests compare discoverGitFrom with real `git rev-parse` output across those layouts, pin every decline case, and check the resulting cached context equals the subprocess-derived one. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(cli): resolve the git user.name actor fallback only when needed PersistentPreRunE assigned `actor = getActorWithGit()` for every command, which, with no --actor / BEADS_ACTOR / BD_ACTOR / config actor, runs `git config user.name`: the second git subprocess of every bd call, paid by read-only commands that never consult the actor. The pre-run now calls deferActorGitFallback, which marks an empty actor as pending; currentActor (and getActorWithGit, getActor) resolve it on first use with the unchanged priority order and store it in the global and the CommandContext copy, as the eager assignment did. Command code reads the actor through currentActor() instead of the raw global (a mechanical rewrite of every read site the compiler reported; writes, the flag binding and the pre-run config binding keep the raw variable). setActor cancels a pending fallback. The telemetry span's bd.actor attribute is still set, but only for a recording span, so a noop span does not force the lookup. With the in-process repository discovery from the previous commit, a read-only `bd list` / `bd show` now starts no git process at startup, in the main checkout and in a linked worktree; a write asks git for user.name once (bd create previously asked once, now still once) and records the same value. Measured on 50 sequential `bd list` calls: 100 -> 0 git execs (embedded and proxied-server workspaces, main checkout and worktree). TestEmbeddedReadOnlyCommandsSpawnNoGit counts git execs through a PATH shim; TestDeferredActorGitFallback pins the deferral semantics. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(git): decline in-process discovery on any config line git might read differently Review follow-ups to the in-process repository discovery. - The repository config scanner was looser than git: a config starting with a UTF-8 BOM followed by `[core] worktree = /other` made git report /other while discovery returned the cwd repository, and `[ core ]` or `!!! = x` (which git refuses) were accepted. scanGitConfig (gitconfig_linux.go) now skips a leading BOM exactly as git does and accepts only a narrow grammar: blank/comment lines, `[section]` / `[section "sub"]` headers at column 0, and `key` / `key = value` lines inside a section, with values free of backslashes and unbalanced quotes. Any other line declines to git. - Walk from getcwd(2) (syscall.Getwd), as git does, instead of os.Getwd, which trusts $PWD when it names the same inode (bind-mount aliases). - Resolve relative gitfile and commondir targets without filepath.Join's lexical Clean, so "link/.." resolves physically like git's realpath. - A mount-boundary stop reports its own reason in the not-a-repository error. - Tests: every decline case (BOM + core.worktree, malformed headers and keys, keys before a section, escapes, continuations, bare repositories, a commondir inside .git, ...) now also checks that what startup derives equals git's answer; BOM and CRLF/comment configs are equivalence cases; the no-repository case must be answered in-process instead of skipping; a $PWD alias test pins the getcwd walk. - The exec-count test drops every GIT_* variable except the config-file selectors, so a runner exporting GIT_CONFIG_PARAMETERS & co. cannot make it fail spuriously. - Comment the two places that touch the raw actor before the deferral. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(backup): decide embedded auto-backup's git-remote probe without git In an embedded workspace whose backup.enabled is unset, maybeAutoBackup asks isBackupAutoEnabled -> primeHasGitRemote after every command, reads included. That built a RepoContext (`git -C .beads rev-parse --git-common-dir`) and ran `git remote`: two git processes per read even after the startup calls were gone. The throttle cannot short-circuit it: without a remote no backup ever runs, so there is no backup state to throttle on. Both probes are now answered in-process when provable, and the subprocess remains the fallback, so the decision and every warning/notice downstream of it are unchanged: - internal/beads getGitCommonDirForPath uses git.CommonDirInProcess (the discovery walk from the given directory, git's spelling). - primeHasGitRemote uses git.HasRemoteInProcess in the same directory primeGitCmd would run git in (primeGitDir, factored out). It answers only when every config file `git remote` reads -- system (GIT_CONFIG_SYSTEM, or /etc/gitconfig and <prefix>/etc/gitconfig of the git on PATH), global (GIT_CONFIG_GLOBAL, or XDG and ~/.gitconfig) and the repository's own -- is absent or within scanGitConfig's grammar and include-free, no GIT_CONFIG_PARAMETERS/COUNT/GIT_CONFIG or discovery override is set, and no legacy .git/remotes or .git/branches entries exist. A remote seen only in a system-config candidate declines. Remote names outside [A-Za-z0-9._-] decline. Tests compare HasRemoteInProcess with `git remote` (no remote, local, worktree, submodule, remote.pushDefault only, global remote, no repo) and pin the declines (global include, malformed global, command-line config); CommonDirInProcess is compared with `git -C dir rev-parse --git-common-dir`. TestEmbeddedReadOnlyCommandsSpawnNoGit now runs with backup.enabled at its default, with and without a git remote, and still expects zero git processes for list/show. Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
393 lines
9.4 KiB
Go
393 lines
9.4 KiB
Go
// Package main provides the CommandContext struct that consolidates runtime state.
|
|
// This addresses the code smell of 20+ global variables in main.go by grouping
|
|
// related state into a single struct for better testability and clearer ownership.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/steveyegge/beads/internal/hooks"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
)
|
|
|
|
// CommandContext holds all runtime state for command execution.
|
|
// This consolidates the previously scattered global variables for:
|
|
// - Better testability (can inject mock contexts)
|
|
// - Clearer state ownership (all state in one place)
|
|
// - Reduced global count (20+ globals → 1 context)
|
|
// - Thread safety (mutexes grouped with the data they protect)
|
|
type CommandContext struct {
|
|
// Configuration (derived from flags and config)
|
|
DBPath string
|
|
Actor string
|
|
JSONOutput bool
|
|
SandboxMode bool
|
|
ReadonlyMode bool
|
|
LockTimeout time.Duration
|
|
Verbose bool
|
|
Quiet bool
|
|
|
|
ServerMode bool
|
|
ProxiedServerMode bool
|
|
|
|
// Runtime state
|
|
Store storage.DoltStorage
|
|
RootCtx context.Context
|
|
RootCancel context.CancelFunc
|
|
HookRunner *hooks.Runner
|
|
|
|
// Version tracking
|
|
VersionUpgradeDetected bool
|
|
PreviousVersion string
|
|
UpgradeAcknowledged bool
|
|
|
|
// Profiling
|
|
ProfileFile *os.File
|
|
TraceFile *os.File
|
|
}
|
|
|
|
// cmdCtx is the global CommandContext instance.
|
|
// Commands access state through this single point instead of scattered globals.
|
|
var cmdCtx *CommandContext
|
|
|
|
// testModeUseGlobals when true forces accessor functions to use legacy globals.
|
|
// This ensures backward compatibility with tests that manipulate globals directly.
|
|
var testModeUseGlobals bool
|
|
|
|
// initCommandContext creates and initializes a new CommandContext.
|
|
// Called from PersistentPreRun to set up runtime state.
|
|
func initCommandContext() {
|
|
cmdCtx = &CommandContext{}
|
|
}
|
|
|
|
// GetCommandContext returns the current CommandContext.
|
|
// Returns nil if called before initialization (e.g., during init() or help).
|
|
func GetCommandContext() *CommandContext {
|
|
return cmdCtx
|
|
}
|
|
|
|
// resetCommandContext clears the CommandContext for testing.
|
|
// This ensures tests that manipulate globals directly work correctly.
|
|
// Only call this in tests, never in production code.
|
|
func resetCommandContext() {
|
|
cmdCtx = nil
|
|
}
|
|
|
|
// enableTestModeGlobals forces accessor functions to use legacy globals.
|
|
// This ensures backward compatibility with tests that manipulate globals directly.
|
|
func enableTestModeGlobals() {
|
|
testModeUseGlobals = true
|
|
cmdCtx = nil
|
|
}
|
|
|
|
// shouldUseGlobals returns true if accessor functions should use globals.
|
|
func shouldUseGlobals() bool {
|
|
return testModeUseGlobals || cmdCtx == nil
|
|
}
|
|
|
|
// The following accessor functions provide backward-compatible access
|
|
// to the CommandContext fields. Commands can use these during the
|
|
// migration period, and they can be gradually replaced with direct
|
|
// cmdCtx access as files are updated.
|
|
|
|
// getStore returns the current storage backend.
|
|
// This is the primary way commands should access storage.
|
|
func getStore() storage.DoltStorage {
|
|
if shouldUseGlobals() {
|
|
return store // fallback to legacy global during transition
|
|
}
|
|
return cmdCtx.Store
|
|
}
|
|
|
|
// setStore updates the storage backend in the CommandContext.
|
|
func setStore(s storage.DoltStorage) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.Store = s
|
|
}
|
|
store = s // keep legacy global in sync during transition
|
|
}
|
|
|
|
// getActor returns the current actor name for audit trail.
|
|
func getActor() string {
|
|
if shouldUseGlobals() {
|
|
return currentActor()
|
|
}
|
|
// cmdCtx.Actor is a copy of the global taken by syncCommandContext or
|
|
// setActor. While the two agree, the global is authoritative and may
|
|
// still carry a deferred git fallback (see deferActorGitFallback).
|
|
if cmdCtx.Actor == actor {
|
|
return currentActor()
|
|
}
|
|
return cmdCtx.Actor
|
|
}
|
|
|
|
// setActor updates the actor name in the CommandContext.
|
|
func setActor(a string) {
|
|
actorMu.Lock()
|
|
defer actorMu.Unlock()
|
|
if cmdCtx != nil {
|
|
cmdCtx.Actor = a
|
|
}
|
|
actor = a
|
|
actorGitFallbackPending = false
|
|
}
|
|
|
|
// isJSONOutput returns true if JSON output mode is enabled.
|
|
func isJSONOutput() bool {
|
|
if shouldUseGlobals() {
|
|
return jsonOutput
|
|
}
|
|
return cmdCtx.JSONOutput
|
|
}
|
|
|
|
// setJSONOutput updates the JSON output flag.
|
|
func setJSONOutput(j bool) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.JSONOutput = j
|
|
}
|
|
jsonOutput = j
|
|
}
|
|
|
|
// getDBPath returns the database path.
|
|
func getDBPath() string {
|
|
if shouldUseGlobals() {
|
|
return dbPath
|
|
}
|
|
return cmdCtx.DBPath
|
|
}
|
|
|
|
// setDBPath updates the database path.
|
|
func setDBPath(p string) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.DBPath = p
|
|
}
|
|
dbPath = p
|
|
}
|
|
|
|
// getRootContext returns the signal-aware root context.
|
|
// Returns context.Background() if the root context is nil (e.g., before CLI initialization).
|
|
func getRootContext() context.Context {
|
|
var ctx context.Context
|
|
if shouldUseGlobals() {
|
|
ctx = rootCtx
|
|
} else {
|
|
ctx = cmdCtx.RootCtx
|
|
}
|
|
if ctx == nil {
|
|
return context.Background()
|
|
}
|
|
return ctx
|
|
}
|
|
|
|
// setRootContext updates the root context and cancel function.
|
|
func setRootContext(ctx context.Context, cancel context.CancelFunc) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.RootCtx = ctx
|
|
cmdCtx.RootCancel = cancel
|
|
}
|
|
rootCtx = ctx
|
|
rootCancel = cancel
|
|
}
|
|
|
|
// getHookRunner returns the hook runner instance.
|
|
func getHookRunner() *hooks.Runner {
|
|
if shouldUseGlobals() {
|
|
return hookRunner
|
|
}
|
|
return cmdCtx.HookRunner
|
|
}
|
|
|
|
// setHookRunner updates the hook runner.
|
|
func setHookRunner(h *hooks.Runner) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.HookRunner = h
|
|
}
|
|
hookRunner = h
|
|
}
|
|
|
|
// isReadonlyMode returns true if read-only mode is enabled.
|
|
func isReadonlyMode() bool {
|
|
if shouldUseGlobals() {
|
|
return readonlyMode
|
|
}
|
|
return cmdCtx.ReadonlyMode
|
|
}
|
|
|
|
// getLockTimeout returns the SQLite lock timeout.
|
|
func getLockTimeout() time.Duration {
|
|
if shouldUseGlobals() {
|
|
return lockTimeout
|
|
}
|
|
return cmdCtx.LockTimeout
|
|
}
|
|
|
|
// lockStore acquires the store mutex for thread-safe access.
|
|
func lockStore() {
|
|
storeMutex.Lock()
|
|
}
|
|
|
|
// unlockStore releases the store mutex.
|
|
func unlockStore() {
|
|
storeMutex.Unlock()
|
|
}
|
|
|
|
// isStoreActive returns true if the store is currently available.
|
|
func isStoreActive() bool {
|
|
return storeActive
|
|
}
|
|
|
|
// setStoreActive updates the store active flag.
|
|
func setStoreActive(active bool) {
|
|
storeActive = active
|
|
}
|
|
|
|
// isVerbose returns true if verbose mode is enabled.
|
|
func isVerbose() bool {
|
|
if shouldUseGlobals() {
|
|
return verboseFlag
|
|
}
|
|
return cmdCtx.Verbose
|
|
}
|
|
|
|
// isQuiet returns true if quiet mode is enabled.
|
|
func isQuiet() bool {
|
|
if shouldUseGlobals() {
|
|
return quietFlag
|
|
}
|
|
return cmdCtx.Quiet
|
|
}
|
|
|
|
// isSandboxMode returns true if sandbox mode is enabled.
|
|
func isSandboxMode() bool {
|
|
if shouldUseGlobals() {
|
|
return sandboxMode
|
|
}
|
|
return cmdCtx.SandboxMode
|
|
}
|
|
|
|
// setSandboxMode updates the sandbox mode flag.
|
|
func setSandboxMode(sm bool) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.SandboxMode = sm
|
|
}
|
|
sandboxMode = sm
|
|
}
|
|
|
|
// isVersionUpgradeDetected returns true if a version upgrade was detected.
|
|
func isVersionUpgradeDetected() bool {
|
|
if shouldUseGlobals() {
|
|
return versionUpgradeDetected
|
|
}
|
|
return cmdCtx.VersionUpgradeDetected
|
|
}
|
|
|
|
// setVersionUpgradeDetected updates the version upgrade detected flag.
|
|
func setVersionUpgradeDetected(detected bool) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.VersionUpgradeDetected = detected
|
|
}
|
|
versionUpgradeDetected = detected
|
|
}
|
|
|
|
// getPreviousVersion returns the previous bd version.
|
|
func getPreviousVersion() string {
|
|
if shouldUseGlobals() {
|
|
return previousVersion
|
|
}
|
|
return cmdCtx.PreviousVersion
|
|
}
|
|
|
|
// setPreviousVersion updates the previous version.
|
|
func setPreviousVersion(v string) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.PreviousVersion = v
|
|
}
|
|
previousVersion = v
|
|
}
|
|
|
|
// isUpgradeAcknowledged returns true if the upgrade notification was shown.
|
|
func isUpgradeAcknowledged() bool {
|
|
if shouldUseGlobals() {
|
|
return upgradeAcknowledged
|
|
}
|
|
return cmdCtx.UpgradeAcknowledged
|
|
}
|
|
|
|
// setUpgradeAcknowledged updates the upgrade acknowledged flag.
|
|
func setUpgradeAcknowledged(ack bool) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.UpgradeAcknowledged = ack
|
|
}
|
|
upgradeAcknowledged = ack
|
|
}
|
|
|
|
// getProfileFile returns the CPU profile file handle.
|
|
func getProfileFile() *os.File {
|
|
if shouldUseGlobals() {
|
|
return profileFile
|
|
}
|
|
return cmdCtx.ProfileFile
|
|
}
|
|
|
|
// setProfileFile updates the CPU profile file handle.
|
|
func setProfileFile(f *os.File) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.ProfileFile = f
|
|
}
|
|
profileFile = f
|
|
}
|
|
|
|
// getTraceFile returns the trace file handle.
|
|
func getTraceFile() *os.File {
|
|
if shouldUseGlobals() {
|
|
return traceFile
|
|
}
|
|
return cmdCtx.TraceFile
|
|
}
|
|
|
|
// setTraceFile updates the trace file handle.
|
|
func setTraceFile(f *os.File) {
|
|
if cmdCtx != nil {
|
|
cmdCtx.TraceFile = f
|
|
}
|
|
traceFile = f
|
|
}
|
|
|
|
// syncCommandContext copies all legacy global values to the CommandContext.
|
|
// This is called after initialization is complete to ensure cmdCtx has all values.
|
|
func syncCommandContext() {
|
|
if shouldUseGlobals() {
|
|
return
|
|
}
|
|
|
|
// Configuration
|
|
cmdCtx.DBPath = dbPath
|
|
cmdCtx.Actor = actor
|
|
cmdCtx.JSONOutput = jsonOutput
|
|
cmdCtx.SandboxMode = sandboxMode
|
|
cmdCtx.ReadonlyMode = readonlyMode
|
|
cmdCtx.LockTimeout = lockTimeout
|
|
cmdCtx.Verbose = verboseFlag
|
|
cmdCtx.Quiet = quietFlag
|
|
|
|
// Storage mode
|
|
cmdCtx.ServerMode = serverMode
|
|
cmdCtx.ProxiedServerMode = proxiedServerMode
|
|
|
|
// Runtime state
|
|
cmdCtx.Store = store
|
|
cmdCtx.RootCtx = rootCtx
|
|
cmdCtx.RootCancel = rootCancel
|
|
cmdCtx.HookRunner = hookRunner
|
|
|
|
// Version tracking
|
|
cmdCtx.VersionUpgradeDetected = versionUpgradeDetected
|
|
cmdCtx.PreviousVersion = previousVersion
|
|
cmdCtx.UpgradeAcknowledged = upgradeAcknowledged
|
|
|
|
// Profiling
|
|
cmdCtx.ProfileFile = profileFile
|
|
cmdCtx.TraceFile = traceFile
|
|
}
|