beads/cmd/bd/status.go
Julian Knutsen 5126de8c1a
perf(bd): no git subprocesses on read-only commands (in-process repo discovery, lazy actor, backup probe) (#7400)
* 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>
2026-10-08 20:08:24 +00:00

273 lines
11 KiB
Go

package main
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/issueops"
)
// StatusOutput represents the complete status output
type StatusOutput struct {
Summary *types.Statistics `json:"summary"`
BlockedCountSkipped bool `json:"blocked_count_skipped,omitempty"`
RecentActivity *RecentActivitySummary `json:"recent_activity,omitempty"`
}
// RecentActivitySummary represents activity from git history
type RecentActivitySummary struct {
HoursTracked int `json:"hours_tracked"`
CommitCount int `json:"commit_count"`
IssuesCreated int `json:"issues_created"`
IssuesClosed int `json:"issues_closed"`
IssuesUpdated int `json:"issues_updated"`
IssuesReopened int `json:"issues_reopened"`
TotalChanges int `json:"total_changes"`
}
var statusCmd = &cobra.Command{
Use: "status",
GroupID: "views",
Aliases: []string{"stats"},
Short: "Show issue database overview and statistics",
Long: `Show a quick snapshot of the issue database state and statistics.
This command provides a summary of issue counts by state (open, in_progress,
blocked, closed), ready work, extended statistics (pinned issues,
average lead time), and recent activity over the last 24 hours from git history.
Similar to how 'git status' shows working tree state, 'bd status' gives you
a quick overview of your issue database without needing multiple queries.
Use cases:
- Quick project health check
- Onboarding for new contributors
- Integration with shell prompts or CI/CD
- Daily standup reference
- Fast CI status checks that don't need blocked-count accuracy
Examples:
bd status # Show summary with activity
bd status --no-activity # Skip git activity (faster)
bd status --no-blocked # Skip slow blocked-count scan (faster)
bd stats --no-blocked --json # JSON output without blocked count
bd status --json # JSON format output
bd status --assigned # Show issues assigned to current user
bd stats # Alias for bd status`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("status")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
showAssigned, _ := cmd.Flags().GetBool("assigned")
noActivity, _ := cmd.Flags().GetBool("no-activity")
noBlocked, _ := cmd.Flags().GetBool("no-blocked")
jsonFormat, _ := cmd.Flags().GetBool("json")
if jsonFormat {
jsonOutput = true
}
reporter, err := openStatsReporter()
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
var result issueops.StatsResult
if showAssigned {
// --no-blocked is not consulted here, and never was: an
// assignee-scoped summary computes both numbers by a route that has
// no fast path (issueops.StatsReporter.AssigneeStats).
result, err = reporter.AssigneeStats(rootCtx, issueops.AssigneeStatsRequest{Assignee: currentActor()})
} else {
result, err = reporter.Stats(rootCtx, issueops.StatsRequest{SkipBlocked: noBlocked})
if err == nil && noBlocked && result.Summary.BlockedIssues != nil {
// Derived from the ANSWER rather than from the route: the two
// routes differ on it today (the unit-of-work seam publishes no
// no-blocked query), and a backend that gains one stops printing
// this without an edit here.
fmt.Fprintln(os.Stderr, "warning: this backend has no --no-blocked fast path; the full blocked-count query ran")
}
}
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
var recentActivity *RecentActivitySummary
if !noActivity {
recentActivity = getGitActivity(24)
}
return renderStatus(&result.Summary, recentActivity)
},
}
// openStatsReporter hands back the summary role for whichever route this
// invocation is on, each through its own capability accessor.
func openStatsReporter() (issueops.StatsReporter, error) {
if usesProxiedServer() {
return proxiedStatsReporter()
}
return store.StatsReporter()
}
// suppressedTypeSummary describes the counted rows that a default bd list will
// not show, so the totals above can be reconciled against a listing instead of
// looking like a phantom.
//
// THE REMEDY IT PRINTS NAMES TWO FLAGS, not one, because the default listing
// applies its TYPE and its STATUS suppressions independently. These counts
// come from the same scan as TotalIssues and are status-blind with it: a
// CLOSED gate is in GateIssues. `bd list --include-gates` would still not show
// that row, because the default ExcludeStatus of closed and pinned
// (internal/workapi/list.go) is lifted only by --all - which "replaces the
// status exclusions only" and lifts no type exclusion of its own, pinned as
// that phrase in backend/conformance/reader_contract.go. So the type flag on
// its own is a remedy that reproduces the number only in a workspace whose
// gates and protos all happen to still be open, and gates are closed as the
// work they guard completes. Naming both flags is what makes the printed
// remedy actually reconcile; a hint that does not is the same silent
// disagreement this line exists to remove, one level down.
//
// It names two of the three type-based suppressions a default listing applies.
// The third - the infra types, which applyTypeSuppressions
// (internal/workapi/list.go) adds to ExcludeTypes independently of the wisp
// plane bit - is NOT here, and not because a durable infra row is unreachable.
// It is reachable: the plane routing and the listing's exclusions both read the
// WORKSPACE-CONFIGURED types.infra set, and changing that set only invalidates
// a cache (internal/storage/dolt/config.go) - it never moves rows already
// written. So durable rows created while a type was not infra stay in the
// issues plane once it becomes one, and a type evicted from the set creates
// durable rows outright (pinned by the create contract in
// backend/conformance/issue_operations_contract.go). Counting them therefore
// needs that configured set, which ScanIssueCountsInTx - pure portable SQL with
// no config seam - cannot reach. Tracked separately rather than guessed at
// here with the built-in names, which would be wrong in exactly the workspaces
// where it matters.
func suppressedTypeSummary(stats *types.Statistics) string {
var parts []string
if stats.GateIssues > 0 {
parts = append(parts, fmt.Sprintf("%s (--include-gates --all)", pluralCount(stats.GateIssues, "gate", "gates")))
}
if stats.TemplateIssues > 0 {
parts = append(parts, fmt.Sprintf("%s (--include-templates --all)", pluralCount(stats.TemplateIssues, "template", "templates")))
}
return strings.Join(parts, ", ")
}
// pluralCount renders a count with the right one of two spellings. Both forms
// are passed in rather than derived by appending "s", so a caller with an
// irregular plural is not silently mis-served.
//
// It is not a fourth spelling of the three helpers already in package main:
// pluralIssue, pluralize and plural all DERIVE the "s" and so cannot render a
// caller-chosen pair. The tree's one two-form helper, pluralWord in
// internal/storage/issueops/lease.go, is unexported in a storage package, and
// exporting it so a CLI string could reach it would add exported surface to a
// storage role for a cosmetic. That file's own doc comment records the same
// trade from the other side - it carries whole words because the issueops
// plural() covers only the "s" case - so one two-form helper per package is
// the established shape here.
func pluralCount(n int, singular, plural string) string {
if n == 1 {
return fmt.Sprintf("%d %s", n, singular)
}
return fmt.Sprintf("%d %s", n, plural)
}
func renderStatus(stats *types.Statistics, recentActivity *RecentActivitySummary) error {
output := &StatusOutput{
Summary: stats,
BlockedCountSkipped: stats.BlockedIssues == nil,
RecentActivity: recentActivity,
}
if jsonOutput {
return outputJSON(output)
}
// Human-readable colorized output using semantic ui package
fmt.Printf("\n%s Issue Database Status\n\n", ui.RenderAccent("📊"))
fmt.Printf("Summary:\n")
fmt.Printf(" Total Issues: %d\n", stats.TotalIssues)
fmt.Printf(" Open: %s\n", ui.RenderPass(fmt.Sprintf("%d", stats.OpenIssues)))
fmt.Printf(" In Progress: %s\n", ui.RenderWarn(fmt.Sprintf("%d", stats.InProgressIssues)))
// Skip-state is derived from the data itself (nil BlockedIssues/ReadyIssues),
// not the --no-blocked flag: --assigned recomputes fully-populated stats even
// when --no-blocked was also passed, so the flag alone would misrender those
// as skipped.
if stats.BlockedIssues == nil {
fmt.Printf(" Blocked: %s\n", ui.MutedStyle.Render("(skipped)"))
} else if *stats.BlockedIssues > 0 {
fmt.Printf(" Blocked: %s\n", ui.RenderFail(fmt.Sprintf("%d", *stats.BlockedIssues)))
} else {
fmt.Printf(" Blocked: %d\n", *stats.BlockedIssues)
}
fmt.Printf(" Closed: %d\n", stats.ClosedIssues)
if stats.ReadyIssues == nil {
fmt.Printf(" Ready to Work: %s\n", ui.MutedStyle.Render("(skipped)"))
} else {
fmt.Printf(" Ready to Work: %s\n", ui.RenderPass(fmt.Sprintf("%d", *stats.ReadyIssues)))
}
if suppressed := suppressedTypeSummary(stats); suppressed != "" {
fmt.Printf(" Not shown by bd list: %s\n", suppressed)
}
// Extended statistics (only show if non-zero)
hasExtended := stats.PinnedIssues > 0 ||
stats.EpicsEligibleForClosure > 0 || stats.AverageLeadTime > 0
if hasExtended {
fmt.Printf("\nExtended:\n")
if stats.PinnedIssues > 0 {
fmt.Printf(" Pinned: %d\n", stats.PinnedIssues)
}
if stats.EpicsEligibleForClosure > 0 {
fmt.Printf(" Epics Ready to Close: %s\n", ui.RenderPass(fmt.Sprintf("%d", stats.EpicsEligibleForClosure)))
}
if stats.AverageLeadTime > 0 {
fmt.Printf(" Avg Lead Time: %.1f hours\n", stats.AverageLeadTime)
}
}
if recentActivity != nil {
fmt.Printf("\nRecent Activity (last %d hours):\n", recentActivity.HoursTracked)
fmt.Printf(" Commits: %d\n", recentActivity.CommitCount)
fmt.Printf(" Total Changes: %d\n", recentActivity.TotalChanges)
fmt.Printf(" Issues Created: %d\n", recentActivity.IssuesCreated)
fmt.Printf(" Issues Closed: %d\n", recentActivity.IssuesClosed)
fmt.Printf(" Issues Reopened: %d\n", recentActivity.IssuesReopened)
fmt.Printf(" Issues Updated: %d\n", recentActivity.IssuesUpdated)
}
fmt.Printf("\nFor more details, use 'bd list' to see individual issues.\n")
fmt.Println()
return nil
}
// getGitActivity returns recent activity statistics.
// Previously calculated from git log of issues.jsonl; now returns nil
// as activity tracking has moved to Dolt-native queries.
func getGitActivity(_ int) *RecentActivitySummary {
return nil
}
func init() {
statusCmd.Flags().Bool("all", false, "Show all issues (default behavior)")
statusCmd.Flags().Bool("assigned", false, "Show issues assigned to current user")
statusCmd.Flags().Bool("no-activity", false, "Skip git activity summary (faster)")
statusCmd.Flags().Bool("no-blocked", false, "Skip blocked-count computation (faster on large rigs; not supported in proxied-server mode)")
// Note: --json flag is defined as a persistent flag in main.go, not here
rootCmd.AddCommand(statusCmd)
}