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

948 lines
26 KiB
Go

package main
import (
"encoding/json"
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/ado"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/github"
"github.com/steveyegge/beads/internal/gitlab"
"github.com/steveyegge/beads/internal/jira"
"github.com/steveyegge/beads/internal/linear"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/notion"
"github.com/steveyegge/beads/internal/tracker"
)
// trackerPushPullFlags holds shared flags for push/pull subcommands.
type trackerPushPullFlags struct {
dryRun bool
}
// --- ADO push/pull ---
var adoPushCmd = &cobra.Command{
Use: "push [bead-ids...]",
Short: "Push specific beads to Azure DevOps",
Long: `Push one or more beads issues to Azure DevOps.
Accepts bead IDs as positional arguments.
Equivalent to: bd ado sync --push-only --issues <ids>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runADOPush,
}
var adoPullCmd = &cobra.Command{
Use: "pull [refs...]",
Short: "Pull specific items from Azure DevOps",
Long: `Pull one or more items from Azure DevOps.
Accepts bead IDs or external references as positional arguments.
Equivalent to: bd ado sync --pull-only --issues <refs>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runADOPull,
}
// --- Jira push/pull ---
var jiraPushCmd = &cobra.Command{
Use: "push [bead-ids...]",
Short: "Push specific beads to Jira",
Long: `Push one or more beads issues to Jira.
Accepts bead IDs as positional arguments.
Equivalent to: bd jira sync --push --issues <ids>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runJiraPush,
}
var jiraPullCmd = &cobra.Command{
Use: "pull [refs...]",
Short: "Pull specific items from Jira",
Long: `Pull one or more items from Jira.
Accepts bead IDs or external references as positional arguments.
Equivalent to: bd jira sync --pull --issues <refs>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runJiraPull,
}
// --- Linear push/pull ---
var linearPushCmd = &cobra.Command{
Use: "push [bead-ids...]",
Short: "Push specific beads to Linear",
Long: `Push one or more beads issues to Linear.
Accepts bead IDs as positional arguments.
Equivalent to: bd linear sync --push --issues <ids>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runLinearPush,
}
var linearPullCmd = &cobra.Command{
Use: "pull [refs...]",
Short: "Pull specific items from Linear",
Long: `Pull one or more items from Linear.
Accepts bead IDs or external references as positional arguments.
Equivalent to: bd linear sync --pull --issues <refs>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runLinearPull,
}
// --- GitHub push/pull ---
var githubPushCmd = &cobra.Command{
Use: "push [bead-ids...]",
Short: "Push specific beads to GitHub",
Long: `Push one or more beads issues to GitHub.
Accepts bead IDs as positional arguments.
Equivalent to: bd github sync --push-only --issues <ids>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runGitHubPush,
}
var githubPullCmd = &cobra.Command{
Use: "pull [refs...]",
Short: "Pull specific items from GitHub",
Long: `Pull one or more items from GitHub.
Accepts bead IDs or external references as positional arguments.
Equivalent to: bd github sync --pull-only --issues <refs>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runGitHubPull,
}
// --- GitLab push/pull ---
var gitlabPushCmd = &cobra.Command{
Use: "push [bead-ids...]",
Short: "Push specific beads to GitLab",
Long: `Push one or more beads issues to GitLab.
Accepts bead IDs as positional arguments.
Equivalent to: bd gitlab sync --push-only --issues <ids>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runGitLabPush,
}
var gitlabPullCmd = &cobra.Command{
Use: "pull [refs...]",
Short: "Pull specific items from GitLab",
Long: `Pull one or more items from GitLab.
Accepts bead IDs or external references as positional arguments.
Equivalent to: bd gitlab sync --pull-only --issues <refs>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runGitLabPull,
}
// --- Notion push/pull ---
var notionPushCmd = &cobra.Command{
Use: "push [bead-ids...]",
Short: "Push specific beads to Notion",
Long: `Push one or more beads issues to Notion.
Accepts bead IDs as positional arguments.
Equivalent to: bd notion sync --push --issues <ids>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runNotionPush,
}
var notionPullCmd = &cobra.Command{
Use: "pull [refs...]",
Short: "Pull specific items from Notion",
Long: `Pull one or more items from Notion.
Accepts bead IDs or external references as positional arguments.
Equivalent to: bd notion sync --pull --issues <refs>`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runNotionPull,
}
func init() {
// ADO push/pull
adoPushCmd.Flags().Bool("dry-run", false, "Preview push without making changes")
adoPullCmd.Flags().Bool("dry-run", false, "Preview pull without making changes")
adoCmd.AddCommand(adoPushCmd)
adoCmd.AddCommand(adoPullCmd)
// Jira push/pull
jiraPushCmd.Flags().Bool("dry-run", false, "Preview push without making changes")
jiraPullCmd.Flags().Bool("dry-run", false, "Preview pull without making changes")
jiraCmd.AddCommand(jiraPushCmd)
jiraCmd.AddCommand(jiraPullCmd)
// Linear push/pull
linearPushCmd.Flags().Bool("dry-run", false, "Preview push without making changes")
linearPullCmd.Flags().Bool("dry-run", false, "Preview pull without making changes")
linearPullCmd.Flags().Bool("relations", false, "Import Linear relations as bd dependencies when pulling")
linearCmd.AddCommand(linearPushCmd)
linearCmd.AddCommand(linearPullCmd)
// GitHub push/pull
githubPushCmd.Flags().Bool("dry-run", false, "Preview push without making changes")
githubPullCmd.Flags().Bool("dry-run", false, "Preview pull without making changes")
githubCmd.AddCommand(githubPushCmd)
githubCmd.AddCommand(githubPullCmd)
// GitLab push/pull
gitlabPushCmd.Flags().Bool("dry-run", false, "Preview push without making changes")
gitlabPullCmd.Flags().Bool("dry-run", false, "Preview pull without making changes")
gitlabCmd.AddCommand(gitlabPushCmd)
gitlabCmd.AddCommand(gitlabPullCmd)
// Notion push/pull
notionPushCmd.Flags().Bool("dry-run", false, "Preview push without making changes")
notionPullCmd.Flags().Bool("dry-run", false, "Preview pull without making changes")
notionCmd.AddCommand(notionPushCmd)
notionCmd.AddCommand(notionPullCmd)
}
// outputSyncResult writes sync results as JSON or human-readable text.
func outputSyncResult(result *tracker.SyncResult, dryRun bool) {
if jsonOutput {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(result)
return
}
if dryRun {
fmt.Println("Dry run mode - no changes will be made")
}
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 dryRun {
fmt.Println("\nRun without --dry-run to apply changes")
}
}
// --- ADO implementations ---
func runADOPush(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("ado-push")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return fmt.Errorf("at least one bead ID is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("ado push")
}
cfg := getADOConfig()
if err := validateADOConfig(cfg); err != nil {
return err
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("database not available: %w", err)
}
ctx := cmd.Context()
at := &ado.Tracker{}
if err := at.Init(ctx, store); err != nil {
return fmt.Errorf("initializing Azure DevOps tracker: %w", err)
}
engine := tracker.NewEngine(at, store, currentActor())
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
result, err := engine.Sync(ctx, tracker.SyncOptions{
Push: true,
Pull: false,
DryRun: dryRun,
IssueIDs: args,
})
if err != nil {
return err
}
outputSyncResult(result, dryRun)
return nil
}
func runADOPull(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("ado-pull")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return fmt.Errorf("at least one bead ID or external reference is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("ado pull")
}
cfg := getADOConfig()
if err := validateADOConfig(cfg); err != nil {
return err
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("database not available: %w", err)
}
ctx := cmd.Context()
at := &ado.Tracker{}
if err := at.Init(ctx, store); err != nil {
return fmt.Errorf("initializing Azure DevOps tracker: %w", err)
}
engine := tracker.NewEngine(at, store, currentActor())
engine.PullHooks = buildADOPullHooks(ctx, at, false, false, new(int), engine.OnWarning)
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
result, err := engine.Sync(ctx, tracker.SyncOptions{
Pull: true,
Push: false,
DryRun: dryRun,
IssueIDs: args,
})
if err != nil {
return err
}
outputSyncResult(result, dryRun)
return nil
}
// --- Jira implementations ---
func runJiraPush(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("jira-push")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return HandleError("at least one bead ID is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("jira push")
}
trackerStore, err := trackerStoreForCommand(rootCtx)
if err != nil {
return HandleError("database not available: %v", err)
}
if err := validateJiraConfigForStore(trackerStore); err != nil {
return HandleError("%v", err)
}
ctx := rootCtx
jt := &jira.Tracker{}
if err := jt.Init(ctx, trackerStore); err != nil {
return HandleError("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)
result, err := engine.Sync(ctx, tracker.SyncOptions{
Push: true,
Pull: false,
DryRun: dryRun,
IssueIDs: args,
})
if err != nil {
return HandleError("sync failed: %v", err)
}
outputSyncResult(result, dryRun)
return nil
}
func runJiraPull(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("jira-pull")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return HandleError("at least one bead ID or external reference is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("jira pull")
}
trackerStore, err := trackerStoreForCommand(rootCtx)
if err != nil {
return HandleError("database not available: %v", err)
}
if err := validateJiraConfigForStore(trackerStore); err != nil {
return HandleError("%v", err)
}
ctx := rootCtx
jt := &jira.Tracker{}
if err := jt.Init(ctx, trackerStore); err != nil {
return HandleError("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) }
result, err := engine.Sync(ctx, tracker.SyncOptions{
Pull: true,
Push: false,
DryRun: dryRun,
IssueIDs: args,
})
if err != nil {
return HandleError("sync failed: %v", err)
}
outputSyncResult(result, dryRun)
return nil
}
// --- Linear implementations ---
func runLinearPush(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("linear-push")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return HandleError("at least one bead ID is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("linear push")
}
if lockDir := beads.FindBeadsDir(); lockDir != "" {
syncLock, err := linear.AcquireSyncLock(lockDir, true)
if err != nil {
return HandleError("acquiring sync lock: %v", err)
}
defer func() {
if err := syncLock.Release(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to release sync lock: %v\n", err)
}
}()
}
trackerStore, err := trackerStoreForCommand(rootCtx)
if err != nil {
return HandleError("database not available: %v", err)
}
if err := validateLinearConfigForStore(trackerStore, nil); err != nil {
return HandleError("%v", err)
}
ctx := rootCtx
teamIDs := getLinearTeamIDsForStore(ctx, trackerStore, nil)
if len(teamIDs) > 1 {
return HandleError("linear push does not support multiple configured teams\nUse: bd linear sync --push --team <TEAM_ID>")
}
lt := &linear.Tracker{}
lt.SetTeamIDs(teamIDs)
if err := lt.Init(ctx, trackerStore); err != nil {
return HandleError("initializing Linear tracker: %v", err)
}
if err := lt.ValidatePushStateMappings(ctx); err != nil {
return HandleError("%v", err)
}
engine := tracker.NewEngine(lt, 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 = buildLinearPushHooksForStore(ctx, trackerStore, lt, len(args) > 0)
result, err := engine.Sync(ctx, tracker.SyncOptions{
Push: true,
Pull: false,
DryRun: dryRun,
ExcludeEphemeral: true,
IssueIDs: args,
})
if err != nil {
return HandleError("sync failed: %v", err)
}
outputSyncResult(result, dryRun)
return nil
}
func runLinearPull(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("linear-pull")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return HandleError("at least one bead ID or external reference is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
relations, _ := cmd.Flags().GetBool("relations")
if !dryRun {
CheckReadonly("linear pull")
}
if lockDir := beads.FindBeadsDir(); lockDir != "" {
syncLock, err := linear.AcquireSyncLock(lockDir, true)
if err != nil {
return HandleError("acquiring sync lock: %v", err)
}
defer func() {
if err := syncLock.Release(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to release sync lock: %v\n", err)
}
}()
}
trackerStore, err := trackerStoreForCommand(rootCtx)
if err != nil {
return HandleError("database not available: %v", err)
}
if err := validateLinearConfigForStore(trackerStore, nil); err != nil {
return HandleError("%v", err)
}
ctx := rootCtx
teamIDs := getLinearTeamIDsForStore(ctx, trackerStore, nil)
lt := &linear.Tracker{}
lt.SetTeamIDs(teamIDs)
if err := lt.Init(ctx, trackerStore); err != nil {
return HandleError("initializing Linear tracker: %v", err)
}
engine := tracker.NewEngine(lt, trackerStore, currentActor())
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
engine.PullHooks = buildLinearPullHooksForStore(ctx, trackerStore, linearPullHookOptions{
DryRun: dryRun,
Actor: currentActor(),
})
result, err := engine.Sync(ctx, tracker.SyncOptions{
Pull: true,
Push: false,
DryRun: dryRun,
IssueIDs: args,
DependencySources: linearPullDependencySources(relations),
})
if err != nil {
return HandleError("sync failed: %v", err)
}
outputSyncResult(result, dryRun)
return nil
}
// --- GitHub implementations ---
func runGitHubPush(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("github-push")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return fmt.Errorf("at least one bead ID is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("github push")
}
config := getGitHubConfig()
if err := validateGitHubConfig(config); err != nil {
return err
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("database not available: %w", err)
}
ctx := cmd.Context()
gt := &github.Tracker{}
if err := gt.Init(ctx, store); err != nil {
return fmt.Errorf("initializing GitHub tracker: %w", err)
}
engine := tracker.NewEngine(gt, store, currentActor())
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
engine.PushHooks = buildGitHubPushHooks(gt)
opts := tracker.SyncOptions{
Push: true,
Pull: false,
DryRun: dryRun,
IssueIDs: args,
}
result, err := engine.Sync(ctx, opts)
if err != nil {
return err
}
// Relationship push pass, matching `bd github sync`: converge beads
// epic/child links and "blocks" dependencies among the requested issues
// into GitHub sub-issues and issue dependencies.
warnLink := func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
linksPushed := pushGitHubDependencyLinks(ctx, gt, store, opts, dryRun, os.Stdout, warnLink)
// Under --dry-run PushLinks counts planned links in Created, so this line
// would affirm writes that never happened; the `bd github sync` twin gates
// it the same way.
if linksPushed > 0 && !dryRun && !jsonOutput {
fmt.Printf("✓ Synced %d relationship links\n", linksPushed)
}
outputSyncResult(result, dryRun)
return nil
}
func runGitHubPull(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("github-pull")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return fmt.Errorf("at least one bead ID or external reference is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("github pull")
}
config := getGitHubConfig()
if err := validateGitHubConfig(config); err != nil {
return err
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("database not available: %w", err)
}
ctx := cmd.Context()
gt := &github.Tracker{}
if err := gt.Init(ctx, store); err != nil {
return fmt.Errorf("initializing GitHub tracker: %w", err)
}
engine := tracker.NewEngine(gt, store, currentActor())
engine.PullHooks = buildGitHubPullHooks(ctx)
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
result, err := engine.Sync(ctx, tracker.SyncOptions{
Pull: true,
Push: false,
DryRun: dryRun,
IssueIDs: args,
})
if err != nil {
return err
}
outputSyncResult(result, dryRun)
return nil
}
// --- GitLab implementations ---
func runGitLabPush(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("gitlab-push")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return fmt.Errorf("at least one bead ID is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("gitlab push")
}
config := getGitLabConfig()
if err := validateGitLabConfig(config); err != nil {
return err
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("database not available: %w", err)
}
ctx := cmd.Context()
gt := &gitlab.Tracker{}
if err := gt.Init(ctx, store); err != nil {
return fmt.Errorf("initializing GitLab tracker: %w", err)
}
out := cmd.OutOrStdout()
engine := tracker.NewEngine(gt, store, currentActor())
engine.OnMessage = func(msg string) {
if !jsonOutput {
fmt.Fprintln(out, " "+msg)
}
}
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
engine.PushHooks = buildGitLabPushHooks()
if dryRun && !jsonOutput {
fmt.Fprintln(out, "Dry run mode - no changes will be made")
fmt.Fprintln(out)
}
opts := tracker.SyncOptions{
Push: true,
Pull: false,
DryRun: dryRun,
IssueIDs: args,
}
result, err := engine.Sync(ctx, opts)
if err != nil {
return err
}
// Dependency-link push parity with `bd gitlab sync`: converge beads
// dependencies among the requested issues into GitLab issue links (and
// repair epic-child milestones). Without this, `bd gitlab push <ids>`
// would sync content but silently omit dependency links. Output is
// rendered here (rather than via outputSyncResult) so the link pass runs
// before the summary and the --json payload carries the link counts,
// matching bd gitlab sync.
var linkWarnings []string
warnLink := func(msg string) {
linkWarnings = append(linkWarnings, msg)
fmt.Fprintf(os.Stderr, "Warning: %s\n", msg)
}
linksPushed, linksLicenseSkipped, milestonesUpdated := pushGitLabDependencyLinks(ctx, gt, store, opts, dryRun, out, warnLink)
if jsonOutput {
return outputJSON(gitlabSyncResult{
DryRun: dryRun,
Pushed: result.Stats.Pushed,
Created: result.Stats.Created,
Updated: result.Stats.Updated,
Skipped: result.Stats.Skipped,
Conflicts: result.Stats.Conflicts,
Errors: result.Stats.Errors,
LinksPushed: linksPushed,
LinksLicenseSkipped: linksLicenseSkipped,
MilestonesUpdated: milestonesUpdated,
Warnings: append(result.Warnings, linkWarnings...),
})
}
if dryRun {
fmt.Fprintln(out)
fmt.Fprintln(out, "Run without --dry-run to apply changes")
return nil
}
if result.Stats.Pushed > 0 {
fmt.Fprintf(out, "✓ Pushed %d issues\n", result.Stats.Pushed)
}
if linksPushed > 0 {
fmt.Fprintf(out, "✓ Synced %d dependency links\n", linksPushed)
}
if result.Stats.Conflicts > 0 {
fmt.Fprintf(out, "→ Resolved %d conflicts\n", result.Stats.Conflicts)
}
return nil
}
func runGitLabPull(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("gitlab-pull")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return fmt.Errorf("at least one bead ID or external reference is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("gitlab pull")
}
config := getGitLabConfig()
if err := validateGitLabConfig(config); err != nil {
return err
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("database not available: %w", err)
}
ctx := cmd.Context()
gt := &gitlab.Tracker{}
if err := gt.Init(ctx, store); err != nil {
return fmt.Errorf("initializing GitLab tracker: %w", err)
}
engine := tracker.NewEngine(gt, store, currentActor())
engine.PullHooks = buildGitLabPullHooks(ctx)
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
result, err := engine.Sync(ctx, tracker.SyncOptions{
Pull: true,
Push: false,
DryRun: dryRun,
IssueIDs: args,
})
if err != nil {
return err
}
outputSyncResult(result, dryRun)
return nil
}
// --- Notion implementations ---
func runNotionPush(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("notion-push")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return fmt.Errorf("at least one bead ID is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("notion push")
}
cfg := getNotionConfig()
auth, err := resolveNotionAuth(cmd.Context())
if err != nil {
return err
}
if err := validateNotionConfig(cfg, auth); err != nil {
return err
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("database not available: %w", err)
}
ctx := cmd.Context()
nt := &notion.Tracker{}
if err := nt.Init(ctx, store); err != nil {
return fmt.Errorf("initializing Notion tracker: %w", err)
}
engine := tracker.NewEngine(nt, store, currentActor())
unsupportedStats := newNotionUnsupportedPushStats()
engine.PushHooks = buildNotionPushHooks(ctx, nt, unsupportedStats)
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
result, syncErr := engine.Sync(ctx, tracker.SyncOptions{
Push: true,
Pull: false,
DryRun: dryRun,
ExcludeEphemeral: true,
IssueIDs: args,
})
if syncErr != nil {
return syncErr
}
outputSyncResult(result, dryRun)
return nil
}
func runNotionPull(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("notion-pull")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if len(args) == 0 {
return fmt.Errorf("at least one bead ID or external reference is required")
}
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("notion pull")
}
cfg := getNotionConfig()
auth, err := resolveNotionAuth(cmd.Context())
if err != nil {
return err
}
if err := validateNotionConfig(cfg, auth); err != nil {
return err
}
if err := ensureStoreActive(); err != nil {
return fmt.Errorf("database not available: %w", err)
}
ctx := cmd.Context()
nt := &notion.Tracker{}
if err := nt.Init(ctx, store); err != nil {
return fmt.Errorf("initializing Notion tracker: %w", err)
}
engine := tracker.NewEngine(nt, store, currentActor())
engine.PullHooks = buildNotionPullHooks(ctx)
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
engine.OnWarning = func(msg string) { fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }
result, syncErr := engine.Sync(ctx, tracker.SyncOptions{
Pull: true,
Push: false,
DryRun: dryRun,
IssueIDs: args,
})
if syncErr != nil {
return syncErr
}
outputSyncResult(result, dryRun)
return nil
}