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

360 lines
11 KiB
Go

package main
import (
"context"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/jira"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/tracker"
"github.com/steveyegge/beads/internal/types"
)
var jiraCmd = &cobra.Command{
Use: "jira",
GroupID: "advanced",
Short: "Jira integration commands",
Long: `Synchronize issues between beads and Jira.
Configuration:
bd config set jira.url "https://company.atlassian.net"
bd config set jira.project "PROJ"
bd config set jira.projects "PROJ1,PROJ2" # Multiple projects
bd config set jira.api_token "YOUR_TOKEN"
bd config set jira.username "your_email@company.com" # For Jira Cloud
bd config set jira.push_prefix "hippo" # Only push hippo-* issues to Jira
bd config set jira.push_prefix "proj1,proj2" # Multiple prefixes (comma-separated)
Environment variables (alternative to config):
JIRA_API_TOKEN - Jira API token
JIRA_USERNAME - Jira username/email
JIRA_PROJECTS - Comma-separated project keys
Examples:
bd jira sync --pull # Import issues from Jira
bd jira sync --push # Export issues to Jira
bd jira sync # Bidirectional sync (pull then push)
bd jira sync --dry-run # Preview sync without changes
bd jira status # Show sync status`,
}
var jiraSyncCmd = &cobra.Command{
Use: "sync",
Short: "Synchronize issues with Jira",
Long: `Synchronize issues between beads and Jira.
Modes:
--pull Import issues from Jira into beads
--push Export issues from beads to Jira
(no flags) Bidirectional sync: pull then push, with conflict resolution
Conflict Resolution:
By default, newer timestamp wins. Override with:
--prefer-local Always prefer local beads version
--prefer-jira Always prefer Jira version
Examples:
bd jira sync --pull # Import from Jira
bd jira sync --push --create-only # Push new issues only
bd jira sync --dry-run # Preview without changes
bd jira sync --prefer-local # Bidirectional, local wins`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runJiraSync,
}
var jiraStatusCmd = &cobra.Command{
Use: "status",
Short: "Show Jira sync status",
Long: `Show the current Jira sync status, including:
- Last sync timestamp
- Configuration status
- Number of issues with Jira links
- Issues pending push (no external_ref)`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runJiraStatus,
}
func init() {
jiraSyncCmd.Flags().Bool("pull", false, "Pull issues from Jira")
jiraSyncCmd.Flags().Bool("push", false, "Push issues to Jira")
jiraSyncCmd.Flags().Bool("dry-run", false, "Preview sync without making changes")
jiraSyncCmd.Flags().Bool("prefer-local", false, "Prefer local version on conflicts")
jiraSyncCmd.Flags().Bool("prefer-jira", false, "Prefer Jira version on conflicts")
jiraSyncCmd.Flags().Bool("create-only", false, "Only create new issues, don't update existing")
jiraSyncCmd.Flags().String("state", "all", "Issue state to sync: open, closed, all")
jiraSyncCmd.Flags().StringSlice("project", nil, "Project key(s) to sync (overrides configured project/projects)")
registerSelectiveSyncFlags(jiraSyncCmd)
jiraCmd.AddCommand(jiraSyncCmd)
jiraCmd.AddCommand(jiraStatusCmd)
rootCmd.AddCommand(jiraCmd)
}
func runJiraSync(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("jira-sync")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
pull, _ := cmd.Flags().GetBool("pull")
push, _ := cmd.Flags().GetBool("push")
dryRun, _ := cmd.Flags().GetBool("dry-run")
preferLocal, _ := cmd.Flags().GetBool("prefer-local")
preferJira, _ := cmd.Flags().GetBool("prefer-jira")
createOnly, _ := cmd.Flags().GetBool("create-only")
state, _ := cmd.Flags().GetString("state")
if !dryRun {
CheckReadonly("jira sync")
}
if preferLocal && preferJira {
return HandleErrorRespectJSON("cannot use both --prefer-local and --prefer-jira")
}
trackerStore, err := trackerStoreForCommand(rootCtx)
if err != nil {
return HandleErrorRespectJSON("database not available: %v", err)
}
if err := validateJiraConfigForStore(trackerStore); err != nil {
return HandleErrorRespectJSON("%v", err)
}
ctx := rootCtx
jt := &jira.Tracker{}
cliProjects, _ := cmd.Flags().GetStringSlice("project")
if len(cliProjects) > 0 {
jt.SetProjectKeys(tracker.DeduplicateStrings(cliProjects))
}
if err := jt.Init(ctx, trackerStore); err != nil {
return HandleErrorRespectJSON("initializing Jira tracker: %v", err)
}
engine := tracker.NewEngine(jt, trackerStore, currentActor())
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
engine.PushHooks = buildJiraPushHooksForStore(ctx, trackerStore)
opts := tracker.SyncOptions{
Pull: pull,
Push: push,
DryRun: dryRun,
CreateOnly: createOnly,
State: state,
}
if err := applySelectiveSyncFlags(cmd, &opts, push); err != nil {
return HandleErrorRespectJSON("%v", err)
}
if preferLocal {
opts.ConflictResolution = tracker.ConflictLocal
} else if preferJira {
opts.ConflictResolution = tracker.ConflictExternal
} else {
opts.ConflictResolution = tracker.ConflictTimestamp
}
result, err := engine.Sync(ctx, opts)
if err != nil {
if jsonOutput {
if jerr := outputJSON(result); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleError("%v", err)
}
if jsonOutput {
return outputJSON(result)
}
if dryRun {
fmt.Println("\n✓ Dry run complete (no changes made)")
return nil
}
if result.Stats.Pulled > 0 {
fmt.Printf("✓ Pulled %d issues (%d created, %d updated)\n",
result.Stats.Pulled, result.Stats.Created, result.Stats.Updated)
}
if result.Stats.Pushed > 0 {
fmt.Printf("✓ Pushed %d issues\n", result.Stats.Pushed)
}
if result.Stats.Conflicts > 0 {
fmt.Printf("→ Resolved %d conflicts\n", result.Stats.Conflicts)
}
fmt.Println("\n✓ Jira sync complete")
if len(result.Warnings) > 0 {
fmt.Println("\nWarnings:")
for _, w := range result.Warnings {
fmt.Printf(" - %s\n", w)
}
}
return nil
}
// buildJiraPushHooks creates PushHooks for Jira-specific push behavior.
func buildJiraPushHooks(ctx context.Context) *tracker.PushHooks {
return buildJiraPushHooksForStore(ctx, tracker.NewStore(store))
}
func buildJiraPushHooksForStore(ctx context.Context, st tracker.Store) *tracker.PushHooks {
return &tracker.PushHooks{
ShouldPush: func(issue *types.Issue) bool {
pushPrefix, _ := st.GetConfig(ctx, "jira.push_prefix")
if pushPrefix == "" {
return true
}
for _, prefix := range strings.Split(pushPrefix, ",") {
prefix = strings.TrimSpace(prefix)
prefix = strings.TrimSuffix(prefix, "-")
if prefix != "" && strings.HasPrefix(issue.ID, prefix+"-") {
return true
}
}
return false
},
}
}
func runJiraStatus(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("jira-status")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
ctx := rootCtx
trackerStore, err := trackerStoreForCommand(rootCtx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
jiraURL, _ := trackerStore.GetConfig(ctx, "jira.url")
lastSync, _ := trackerStore.GetConfig(ctx, "jira.last_sync")
pluralProjects, _ := trackerStore.GetConfig(ctx, "jira.projects")
singularProject, _ := trackerStore.GetConfig(ctx, "jira.project")
projectKeys := tracker.ResolveProjectIDs(nil, pluralProjects, singularProject)
configured := jiraURL != "" && len(projectKeys) > 0
// jira sync is a round-trip path — opt out of BEADS_MAX_ROWS
// (designer §4.1) so a misconfigured env doesn't abort partway.
allIssues, err := trackerStore.SearchIssues(ctx, "", types.IssueFilter{
MaxRows: 0,
MaxRowsSource: "",
})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
withJiraRef := 0
pendingPush := 0
for _, issue := range allIssues {
if issue.ExternalRef != nil && jira.IsJiraExternalRef(*issue.ExternalRef, jiraURL) {
withJiraRef++
} else if issue.ExternalRef == nil {
pendingPush++
}
}
if jsonOutput {
primaryProject := ""
if len(projectKeys) > 0 {
primaryProject = projectKeys[0]
}
return outputJSON(map[string]interface{}{
"configured": configured,
"jira_url": jiraURL,
"jira_project": primaryProject,
"jira_projects": projectKeys,
"last_sync": lastSync,
"total_issues": len(allIssues),
"with_jira_ref": withJiraRef,
"pending_push": pendingPush,
})
}
fmt.Println("Jira Sync Status")
fmt.Println("================")
fmt.Println()
if !configured {
fmt.Println("Status: Not configured")
fmt.Println()
fmt.Println("To configure Jira integration:")
fmt.Println(" bd config set jira.url \"https://company.atlassian.net\"")
fmt.Println(" bd config set jira.project \"PROJ\"")
fmt.Println(" bd config set jira.projects \"PROJ1,PROJ2\" # multiple projects")
fmt.Println(" bd config set jira.api_token \"YOUR_TOKEN\"")
fmt.Println(" bd config set jira.username \"your@email.com\"")
return nil
}
fmt.Printf("Jira URL: %s\n", jiraURL)
if len(projectKeys) == 1 {
fmt.Printf("Project: %s\n", projectKeys[0])
} else {
fmt.Printf("Projects: %s (%d projects)\n", strings.Join(projectKeys, ", "), len(projectKeys))
}
if lastSync != "" {
fmt.Printf("Last Sync: %s\n", lastSync)
} else {
fmt.Println("Last Sync: Never")
}
fmt.Println()
fmt.Printf("Total Issues: %d\n", len(allIssues))
fmt.Printf("With Jira: %d\n", withJiraRef)
fmt.Printf("Local Only: %d\n", pendingPush)
if pendingPush > 0 {
fmt.Println()
fmt.Printf("Run 'bd jira sync --push' to push %d local issue(s) to Jira\n", pendingPush)
}
return nil
}
// validateJiraConfig checks that required Jira configuration is present.
func validateJiraConfig() error {
return validateJiraConfigForStore(tracker.NewStore(store))
}
func validateJiraConfigForStore(st tracker.Store) error {
ctx := rootCtx
if st == nil {
return fmt.Errorf("database not available")
}
jiraURL, _ := st.GetConfig(ctx, "jira.url")
if jiraURL == "" {
return fmt.Errorf("jira.url not configured\nRun: bd config set jira.url \"https://company.atlassian.net\"")
}
// Check for project configuration (singular or plural).
pluralProjects, _ := st.GetConfig(ctx, "jira.projects")
singularProject, _ := st.GetConfig(ctx, "jira.project")
projectKeys := tracker.ResolveProjectIDs(nil, pluralProjects, singularProject)
if len(projectKeys) == 0 {
return fmt.Errorf("no Jira project configured\nRun: bd config set jira.project \"PROJ\"\nOr: bd config set jira.projects \"PROJ1,PROJ2\"")
}
apiToken, _ := st.GetConfig(ctx, "jira.api_token")
if apiToken == "" && os.Getenv("JIRA_API_TOKEN") == "" {
return fmt.Errorf("Jira API token not configured\nRun: bd config set jira.api_token \"YOUR_TOKEN\"\nOr: export JIRA_API_TOKEN=YOUR_TOKEN")
}
return nil
}