beads/cmd/bd/comments.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

340 lines
10 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/uimd"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/issueops"
)
// validateCommentsArgs runs as cobra's Args validation for the parent
// "comments" command, which executes before PersistentPreRunE opens the
// store (or runs migrations) and before RunE's usesProxiedServer() dispatch.
// The parent command only lists comments for a single issue, so any trailing
// positional arg is a mistake — most commonly the swapped-order add,
// `bd comments <id> add <text>`, which otherwise falls through, reads only
// args[0], and silently drops the rest with exit 0 (GH#4642). Validating
// here (rather than inside RunE, local-store-only) rejects the malformed
// invocation identically for the direct and proxied-server paths, before
// either one can open a store, run a migration, or hit the remote-migrate
// gate for an invocation that is guaranteed to fail.
func validateCommentsArgs(cmd *cobra.Command, args []string) error {
if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
return err
}
if len(args) <= 1 {
return nil
}
issueID := args[0]
if args[1] == "add" {
return HandleErrorRespectJSON(`"bd comments <issue-id> add ..." is not valid — the subcommand must come first.
To add a comment, run:
bd comments add <issue-id> <text>
Example:
bd comments add %s "your comment"
See: bd comments --help`, issueID)
}
return HandleErrorRespectJSON(`"bd comments" takes a single issue id and lists its comments.
To list comments:
bd comments <issue-id>
To add a comment:
bd comments add <issue-id> <text>
See: bd comments --help`)
}
var commentsCmd = &cobra.Command{
Use: "comments [issue-id]",
GroupID: "issues",
Short: "View or manage comments on an issue",
Long: `View or manage comments on an issue.
Examples:
# List all comments on an issue (issue id is required — there is no "comments list")
bd comments bd-123
# List comments in JSON format
bd comments bd-123 --json
# Add a comment
bd comments add bd-123 "This is a comment"
# Add a comment from a file
bd comments add bd-123 -f notes.txt`,
Args: validateCommentsArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("comments")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if usesProxiedServer() {
return runCommentsProxiedServer(cmd, rootCtx, args)
}
localTime, _ := cmd.Flags().GetBool("local-time")
issueID := args[0]
if err := ensureStoreActive(); err != nil {
return HandleErrorRespectJSON("getting comments: %v", err)
}
ctx := rootCtx
result, err := resolveAndGetIssueWithRouting(ctx, store, issueID)
if err != nil {
if result != nil {
result.Close()
}
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
}
if result == nil || result.Issue == nil {
if result != nil {
result.Close()
}
return HandleErrorRespectJSON("issue %s not found", issueID)
}
defer result.Close()
issueID = result.ResolvedID
comments, err := result.Store.GetIssueComments(ctx, issueID)
if err != nil {
return HandleErrorRespectJSON("getting comments: %v", err)
}
if comments == nil {
comments = make([]*types.Comment, 0)
}
if jsonOutput {
return outputJSON(comments)
}
if len(comments) == 0 {
fmt.Printf("No comments on %s\n", issueID)
return nil
}
fmt.Printf("\nComments on %s:\n\n", issueID)
for _, comment := range comments {
ts := comment.CreatedAt
if localTime {
ts = ts.Local()
}
fmt.Printf("[%s] at %s\n", comment.Author, ts.Format("2006-01-02 15:04"))
rendered := uimd.RenderMarkdown(comment.Text)
for _, line := range strings.Split(strings.TrimRight(rendered, "\n"), "\n") {
fmt.Printf(" %s\n", line)
}
fmt.Println()
}
return nil
},
}
var commentsMisplacedListCmd = &cobra.Command{
Use: "list",
Short: "Invalid — use bd comments <issue-id> to list comments",
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
return HandleErrorRespectJSON(`"bd comments list" is not valid.
To list comments on an issue, run:
bd comments <issue-id>
Example:
bd comments bd-123
See: bd comments --help`)
},
}
// validateCommentsAddArgs runs as cobra's Args validation for "comments add",
// the plural twin of "comment"'s validateCommentArgs. It exists for the same
// reason: an id argument that IS a reserved word (see
// commentReservedIDWords) must never reach either dispatch branch (local or
// proxied) or fuzzy resolution, where it could silently land on an unrelated
// issue instead of erroring. Unlike validateCommentArgs, there is no
// singular/plural confusion to special-case here — "comments add" is already
// the plural form — so this only runs the word-agnostic generic check.
func validateCommentsAddArgs(cmd *cobra.Command, args []string) error {
if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
return err
}
return checkCommentIDNotReservedWord(args[0])
}
var commentsAddCmd = &cobra.Command{
Use: "add [issue-id] [text...]",
Short: "Add a comment to an issue",
Long: `Add a comment to an issue.
Examples:
# Add a comment
bd comments add bd-123 "Working on this now"
# Add a comment from a file
bd comments add bd-123 -f notes.txt`,
Args: validateCommentsAddArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("comment add")
evt := metrics.NewCommandEvent("comments-add")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
issueID := args[0]
commentText, err := requireTextFromSources("comment text", "use positional args or -f to read from file",
cmdTextSources(cmd, args[1:]))
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
author, _ := cmd.Flags().GetString("author")
if author == "" {
author = getActorWithGit()
}
// Dispatched after the text is resolved so both backends read the
// same sources and report the same conflicts.
if usesProxiedServer() {
return runCommentsAddProxiedServer(rootCtx, issueID, author, commentText)
}
if err := ensureStoreActive(); err != nil {
return HandleErrorRespectJSON("adding comment: %v", err)
}
ctx := rootCtx
result, err := resolveAndGetIssueForMutationExact(ctx, store, issueID)
if err != nil {
if result != nil {
result.Close()
}
if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) {
// The issue does exist — id just isn't its full form — so
// "resolving %s: %v"'s generic wording (and the "no issue
// found matching" text underneath a plain not-found) would be
// false here. Say what actually happened instead, matching
// "bd comment"'s truthful message.
return HandleErrorRespectJSON("id abbreviations are not accepted on comment writes; use the full id from `bd show %s`", issueID)
}
return HandleErrorRespectJSON("resolving %s: %v", issueID, err)
}
if result == nil || result.Issue == nil {
if result != nil {
result.Close()
}
return HandleErrorRespectJSON("issue %s not found", issueID)
}
defer result.Close()
issueID = result.ResolvedID
comment, err := addCommentDirect(ctx, result.Store, issueID, author, commentText)
if err != nil {
return HandleErrorRespectJSON("adding comment: %v", err)
}
if err := commitPendingIfEmbedded(ctx, result.Store, currentActor(), doltAutoCommitParams{
Command: "comments add",
IssueIDs: []string{issueID},
}); err != nil {
return HandleErrorRespectJSON("failed to commit: %v", err)
}
if jsonOutput {
return outputJSON(comment)
}
fmt.Printf("Comment added to %s\n", issueID)
return nil
},
}
// addCommentDirect appends one comment through the Commenter role and returns
// the stored comment. It is the direct-route sibling of addCommentProxied and
// builds the SAME request, so the two front doors ask the storage layer one
// question.
//
// The role is reached through the STORE's own accessor, never a constructor:
// that accessor is where the store's decorator stack — hooks, telemetry — adds
// its layer, so a comment written here fires the same hook a comment written
// through the provider does. The store is the caller's rather than the global
// one, because a prefix-routed write has to reach the role through the store
// that actually holds the issue.
//
// The RESOLVE stays with the caller. On this route it is fuzzy, prefix-routed
// and cross-repo, none of which belongs on a contract an unattended client also
// calls, and the caller has already produced the canonical id. The role runs
// the issue-then-wisp fallback itself, so the comment lands on the plane the id
// actually names.
//
// The auto-commit policy is applied HERE rather than by each caller. The role
// creates its Dolt version commit inside the storage layer, so
// `--dolt-auto-commit batch` can only defer it by saying so on the context —
// the reason issueOpsContext exists — and a caller that forgets writes exactly
// the per-write commit batch mode is there to avoid. Both comment commands come
// through this function, so the policy is stated once.
func addCommentDirect(ctx context.Context, st storage.DoltStorage, issueID, author, text string) (*types.Comment, error) {
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return nil, err
}
commenter, err := st.Commenter()
if err != nil {
return nil, err
}
result, err := commenter.AddComment(opsCtx, issueops.AddCommentRequest{
Author: author,
IssueID: issueID,
Text: text,
})
if err != nil {
return nil, err
}
return result.Comment, nil
}
func init() {
commentsCmd.AddCommand(commentsMisplacedListCmd)
commentsCmd.AddCommand(commentsAddCmd)
commentsCmd.Flags().Bool("local-time", false, "Show timestamps in local time instead of UTC")
commentsAddCmd.Flags().StringP("file", "f", "", "Read comment text from file")
commentsAddCmd.Flags().StringP("author", "a", "", "Add author to comment")
// Issue ID completions
commentsCmd.ValidArgsFunction = issueIDCompletion
commentsAddCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(commentsCmd)
}
func isUnknownOperationError(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), "unknown operation")
}