* 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>
318 lines
14 KiB
Go
318 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
"github.com/steveyegge/beads/internal/workapi"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// readyInput is everything `bd ready` parsed off the command line: the
|
|
// frontend-independent query knobs (issueops.ReadyRequest, the request the
|
|
// reader role takes and the filter is built from), the filter itself, and the
|
|
// mode and presentation choices that never leave the CLI.
|
|
type readyInput struct {
|
|
issueops.ReadyRequest
|
|
|
|
filter types.WorkFilter
|
|
|
|
// dirLabels is the directory-label default (GH#541) this listing applied,
|
|
// or nil when it did not apply one. It is the gatherer's DECISION rather
|
|
// than the configured value: the question is answerable only BEFORE the
|
|
// default has been written onto the filter. See readyRoleRequest.
|
|
dirLabels []string
|
|
|
|
claim bool
|
|
gated bool
|
|
molID string
|
|
explain bool
|
|
prettyFormat bool
|
|
plainFormat bool
|
|
jsonOut bool
|
|
}
|
|
|
|
// gatherReadyInput parses `bd ready`'s flags and builds the work filter. Both
|
|
// routes call it - the direct one in ready.go and the proxied one in
|
|
// ready_proxied_server.go - so there is one definition of what the command
|
|
// accepts. Usage errors are reported through HandleErrorRespectJSON, which is
|
|
// what a --json caller has always gotten from the direct route; the proxied
|
|
// route printed five of them as plain stderr text before the two builders were
|
|
// collapsed, so TestGatherReadyInputUsageErrorsRespectJSON pins the unified
|
|
// behavior that replaced them.
|
|
//
|
|
// resolveCap resolves --max-rows / BEADS_MAX_ROWS and is passed in rather than
|
|
// called directly because only the direct route has a cap to enforce: the
|
|
// proxied route rejects a live one in its own RunE and ignores it for --claim,
|
|
// and resolving a second time here would repeat resolveMaxRowsEnvOnly's
|
|
// malformed-value warning. It runs where the direct route's inline builder ran
|
|
// it, ahead of the metadata and sort checks, so a doubly-invalid command line
|
|
// still reports the cap first and a malformed BEADS_MAX_ROWS still warns even
|
|
// when a later check aborts the command.
|
|
func gatherReadyInput(cmd *cobra.Command, resolveCap func(*cobra.Command) (int, string, error)) (readyInput, error) {
|
|
in := readyInput{}
|
|
|
|
in.claim, _ = cmd.Flags().GetBool("claim")
|
|
in.gated, _ = cmd.Flags().GetBool("gated")
|
|
in.molID, _ = cmd.Flags().GetString("mol")
|
|
in.explain, _ = cmd.Flags().GetBool("explain")
|
|
in.Brief, _ = cmd.Flags().GetBool("brief")
|
|
in.prettyFormat, _ = cmd.Flags().GetBool("pretty")
|
|
in.plainFormat, _ = cmd.Flags().GetBool("plain")
|
|
if flat, _ := cmd.Flags().GetBool("flat"); flat {
|
|
in.plainFormat = true
|
|
}
|
|
in.jsonOut = jsonOutput
|
|
|
|
limit, _ := cmd.Flags().GetInt("limit")
|
|
in.Limit = &limit
|
|
// A negative --offset is not a page request, so it never reaches the
|
|
// filter. Rejecting it belongs to the proxied RunE, the only route that
|
|
// pages at all: the direct route rejects --offset > 0 outright and has
|
|
// always ignored a negative value rather than failing on it.
|
|
if offset, _ := cmd.Flags().GetInt("offset"); offset > 0 {
|
|
in.Offset = offset
|
|
}
|
|
in.Assignee, _ = cmd.Flags().GetString("assignee")
|
|
in.Unassigned, _ = cmd.Flags().GetBool("unassigned")
|
|
in.Sort, _ = cmd.Flags().GetString("sort")
|
|
in.Labels, _ = cmd.Flags().GetStringSlice("label")
|
|
in.LabelsAny, _ = cmd.Flags().GetStringSlice("label-any")
|
|
in.ExcludeLabels, _ = cmd.Flags().GetStringSlice("exclude-label")
|
|
in.LabelPattern, _ = cmd.Flags().GetString("label-pattern")
|
|
in.LabelRegex, _ = cmd.Flags().GetString("label-regex")
|
|
in.IssueType, _ = cmd.Flags().GetString("type")
|
|
in.ParentID, _ = cmd.Flags().GetString("parent")
|
|
in.IncludeDeferred, _ = cmd.Flags().GetBool("include-deferred")
|
|
in.IncludeEphemeral, _ = cmd.Flags().GetBool("include-ephemeral")
|
|
in.ExcludeTypes, _ = cmd.Flags().GetStringSlice("exclude-type")
|
|
|
|
if molTypeStr, _ := cmd.Flags().GetString("mol-type"); molTypeStr != "" {
|
|
mt := types.MolType(molTypeStr)
|
|
if !mt.IsValid() {
|
|
return in, HandleErrorRespectJSON("invalid mol-type %q (must be %s)", molTypeStr, types.ValidMolTypeNames())
|
|
}
|
|
in.MolType = &mt
|
|
}
|
|
|
|
if in.claim && in.Assignee != "" {
|
|
return in, HandleErrorRespectJSON("--claim cannot be combined with --assignee")
|
|
}
|
|
if in.claim && in.gated {
|
|
return in, HandleErrorRespectJSON("--claim cannot be combined with --gated")
|
|
}
|
|
if in.claim && in.molID != "" {
|
|
return in, HandleErrorRespectJSON("--claim cannot be combined with --mol")
|
|
}
|
|
if in.claim && in.explain {
|
|
return in, HandleErrorRespectJSON("--claim cannot be combined with --explain")
|
|
}
|
|
if err := briefModeConflict(in.Brief, in.claim, in.gated, in.explain, in.molID, in.jsonOut); err != nil {
|
|
return in, err
|
|
}
|
|
if in.Offset > 0 && in.claim {
|
|
return in, HandleErrorRespectJSON("--offset cannot be combined with --claim")
|
|
}
|
|
if in.Offset > 0 && in.gated {
|
|
return in, HandleErrorRespectJSON("--offset cannot be combined with --gated")
|
|
}
|
|
if in.Offset > 0 && in.molID != "" {
|
|
return in, HandleErrorRespectJSON("--offset cannot be combined with --mol")
|
|
}
|
|
if in.Offset > 0 && in.explain {
|
|
return in, HandleErrorRespectJSON("--offset cannot be combined with --explain")
|
|
}
|
|
|
|
var maxRows int
|
|
var maxRowsSource string
|
|
if resolveCap != nil {
|
|
var err error
|
|
if maxRows, maxRowsSource, err = resolveCap(cmd); err != nil {
|
|
return in, err
|
|
}
|
|
}
|
|
|
|
// Use Changed() to properly handle P0 (priority=0)
|
|
if cmd.Flags().Changed("priority") {
|
|
priority, _ := cmd.Flags().GetInt("priority")
|
|
in.Priority = &priority
|
|
}
|
|
|
|
// Metadata filters (GH#1406)
|
|
metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field")
|
|
if len(metadataFieldFlags) > 0 {
|
|
in.MetadataFields = make(map[string]string, len(metadataFieldFlags))
|
|
for _, mf := range metadataFieldFlags {
|
|
k, v, ok := strings.Cut(mf, "=")
|
|
if !ok || k == "" {
|
|
return in, HandleErrorRespectJSON("invalid --metadata-field: expected key=value, got %q", mf)
|
|
}
|
|
if err := storage.ValidateMetadataKey(k); err != nil {
|
|
return in, HandleErrorRespectJSON("invalid --metadata-field key: %v", err)
|
|
}
|
|
in.MetadataFields[k] = v
|
|
}
|
|
}
|
|
if k, _ := cmd.Flags().GetString("has-metadata-key"); k != "" {
|
|
if err := storage.ValidateMetadataKey(k); err != nil {
|
|
return in, HandleErrorRespectJSON("invalid --has-metadata-key: %v", err)
|
|
}
|
|
in.HasMetadataKey = k
|
|
}
|
|
|
|
// `bd ready` builds the filter rather than calling IssueReader(): its
|
|
// routes hand this filter to --claim, --gated, --explain and --mol, none
|
|
// of which the Reader role expresses, and they stamp the --max-rows cap
|
|
// onto it below. Routing only the plain listing through the role would
|
|
// fork the command in two.
|
|
//
|
|
// CONSTRUCTION is shared with the role and always was: this is the same
|
|
// builder, over the same issueops.ReadyRequest, that both Reader
|
|
// implementations call, pinned by the builder's golden file.
|
|
//
|
|
// EXECUTION is shared on the proxied route, which runs the same
|
|
// workapi.FinishPage the role's two implementations run. It is NOT shared
|
|
// on the direct route, and that is a real and remaining difference: the
|
|
// role answers "did the limit hide anything" by fetching one row past the
|
|
// page, while `bd ready --json` answers the strictly larger question "how
|
|
// many were hidden" with a second counting query and reports the total in
|
|
// its pagination meta. That total is the CLI's published output, so the
|
|
// two epilogues cannot be collapsed without changing one surface's answer.
|
|
// See issueops.Reader's doc comment.
|
|
filter, err := workapi.BuildReadyFilter(in.ReadyRequest)
|
|
if err != nil {
|
|
return in, HandleErrorRespectJSON("%v", err)
|
|
}
|
|
// The cap is deliberately NOT a field on ReadyRequest: it is a local
|
|
// defense against a runaway query on this machine, not a property of the
|
|
// question being asked, and a server has no business honoring a client's.
|
|
filter.MaxRows = maxRows
|
|
filter.MaxRowsSource = maxRowsSource
|
|
|
|
// Directory-aware label scoping (GH#541). It is applied to the built
|
|
// filter rather than passed in as a parameter for two reasons: it is
|
|
// derived from the client's cwd, which a server process does not share,
|
|
// and `bd ready` has always put the configured label on the filter
|
|
// verbatim. Routing it through issueops.ReadyRequest would run it through
|
|
// NormalizeLabels, so a directory.labels value with stray whitespace
|
|
// would start matching a different label than it does today.
|
|
//
|
|
// The emptiness test reads the filter's label sets, which BuildReadyFilter
|
|
// has already normalized: `--label " "` is no label at all and must not
|
|
// suppress the default.
|
|
if len(filter.Labels) == 0 && len(filter.LabelsAny) == 0 {
|
|
if dirLabels := config.GetDirectoryLabels(); len(dirLabels) > 0 {
|
|
filter.LabelsAny = dirLabels
|
|
// Recorded rather than recomputed downstream: the line above has
|
|
// just made the filter's label sets non-empty, so re-running the
|
|
// emptiness test would read its own output.
|
|
in.dirLabels = dirLabels
|
|
}
|
|
}
|
|
in.filter = filter
|
|
|
|
return in, nil
|
|
}
|
|
|
|
// readyRoleRequest is the request `bd ready` hands the two roles that take a
|
|
// whole ready question rather than a filter: ReadyClaimer, which claims one
|
|
// row out of it, and ReadyCounter, which sizes it. Both routes of both
|
|
// operations build it here, so a claim, a count and the listing beside them
|
|
// ask ONE question no matter which door they came through.
|
|
//
|
|
// The two things the filter carries that the request does not:
|
|
//
|
|
// - The --max-rows cap. It never applied to either role. A claim consumes
|
|
// one row however large the pool it scanned (ClaimReadyIssueInTx clears
|
|
// MaxRows, MaxRowsSource and Limit before it scans, because a cap sized
|
|
// for bulk reads must not make a single-row claim report an empty front),
|
|
// and a count materializes no rows at all.
|
|
//
|
|
// - The directory-label default (GH#541). The listing puts it on the built
|
|
// filter verbatim; here it goes on the request, where it is normalized
|
|
// along with every other label. That differs only for a directory.labels
|
|
// value carrying stray whitespace.
|
|
//
|
|
// IT IS READ OFF readyInput.dirLabels, NEVER RECOMPUTED FROM in.filter.
|
|
// The gatherer has already written the default INTO that filter, so
|
|
// re-running its emptiness test here sees a non-empty label set and skips.
|
|
// That is what made `bd ready --claim` in a scoped directory claim from
|
|
// the WHOLE ready front while `bd ready` beside it listed only the
|
|
// configured scope — the one thing ReadyClaimer's contract says a claim
|
|
// must never do (issueops/readyclaimer.go:9-14).
|
|
//
|
|
// Limit and Offset are ErrValidation on BOTH roles, so they are cleared here
|
|
// once. Neither was ever live for the claim; for the count they are exactly
|
|
// what has to go — the page is the thing being sized.
|
|
func readyRoleRequest(in readyInput) issueops.ReadyRequest {
|
|
req := in.ReadyRequest
|
|
req.Limit, req.Offset = nil, 0
|
|
if len(in.dirLabels) > 0 {
|
|
req.LabelsAny = in.dirLabels
|
|
}
|
|
return req
|
|
}
|
|
|
|
// claimNextRequest is `bd ready --claim`'s request to the ReadyClaimer role:
|
|
// the shared ready question above, plus the claimant.
|
|
func claimNextRequest(in readyInput) issueops.ClaimNextRequest {
|
|
return issueops.ClaimNextRequest{Actor: currentActor(), Filter: readyRoleRequest(in)}
|
|
}
|
|
|
|
// briefModeConflict reports the usage error for a --brief combination that no
|
|
// route can honor, and nil when there is none.
|
|
//
|
|
// THE PROJECTION IS REFUSED WHEREVER IT CANNOT BE HONORED, rather than accepted
|
|
// and dropped. types.WorkFilter.Lite reaches the driver through one query, the
|
|
// counts mega-query behind GetReadyWorkWithCounts, and `bd ready` only runs
|
|
// that query for --json. Everything else reaches a different one: the text
|
|
// routes call the bare GetReadyWork, and --gated, --mol and --explain answer
|
|
// with shapes of their own. A flag those routes take and ignore is exactly the
|
|
// silent no-op this feature exists to close, so each combination says so.
|
|
//
|
|
// --claim is refused for a stronger reason than the rest: it cannot be served
|
|
// on ANY route. ClaimNext refetches its winning row whole and returns
|
|
// ErrValidation for a projected request (issueops.ValidateClaimNextRequest).
|
|
// Refusing here keeps the message about the two flags the user typed, and
|
|
// leaves readyRoleRequest free to carry Brief for the COUNT, which needs it.
|
|
//
|
|
// IT IS ONE BODY WITH TWO CALLERS, and that is the point. readyCmd's RunE
|
|
// dispatches --gated, --mol and --explain before gathering, so a copy of these
|
|
// checks written into each of those branches would guard the direct route only,
|
|
// with nothing driving it: the gatherer's tests reach the proxied route alone,
|
|
// and deleting one of the copies would re-open the silent no-op while every
|
|
// test stayed green. RunE calls this once, above the dispatch, and the gatherer
|
|
// calls it for every other arrival.
|
|
func briefModeConflict(brief, claim, gated, explain bool, molID string, jsonOut bool) error {
|
|
if !brief {
|
|
return nil
|
|
}
|
|
switch {
|
|
case claim:
|
|
return HandleErrorRespectJSON("--claim cannot be combined with --brief")
|
|
case gated:
|
|
return HandleErrorRespectJSON("--gated cannot be combined with --brief")
|
|
case molID != "":
|
|
return HandleErrorRespectJSON("--mol cannot be combined with --brief")
|
|
case explain:
|
|
return HandleErrorRespectJSON("--explain cannot be combined with --brief")
|
|
case !jsonOut:
|
|
return HandleErrorRespectJSON("--brief requires --json; the text renderings print none of the fields it omits")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// briefModeConflictFromFlags is readyCmd's entry to the check above, reading the
|
|
// mode flags off the command because it runs before gatherReadyInput has.
|
|
func briefModeConflictFromFlags(cmd *cobra.Command) error {
|
|
brief, _ := cmd.Flags().GetBool("brief")
|
|
claim, _ := cmd.Flags().GetBool("claim")
|
|
gated, _ := cmd.Flags().GetBool("gated")
|
|
explain, _ := cmd.Flags().GetBool("explain")
|
|
molID, _ := cmd.Flags().GetString("mol")
|
|
return briefModeConflict(brief, claim, gated, explain, molID, jsonOutput)
|
|
}
|