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>
This commit is contained in:
Julian Knutsen 2026-10-08 20:08:24 +00:00 • committed by GitHub
commit 5126de8c1a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
92 changed files with 1801 additions and 233 deletions

View file

@ -306,6 +306,7 @@
50 17 TestEmbeddedCompact
50 17 TestEmbeddedGateConcurrent
50 17 TestEmbeddedListComments
50 17 TestEmbeddedReadOnlyCommandsSpawnNoGit
50 18 TestEmbeddedContext
50 18 TestEmbeddedContributorCreate

View file

@ -114,6 +114,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Every `bd` invocation used to start two git subprocesses before doing any
work: `git rev-parse` to locate the repository and `git config user.name`
to resolve the actor. On Linux the repository is now located in-process
(ordinary repositories, linked worktrees, submodules, no repository),
producing exactly what `git rev-parse` printed and still running git for
anything it does not model (`GIT_DIR` and related overrides,
`core.worktree`/`core.bare`, repository extensions, includes, foreign
ownership subject to `safe.directory`). The `git config user.name` actor
fallback is resolved only when a command actually needs an actor, so
read-only commands such as `bd list` and `bd show` start no git process
for it. The actor's value and priority order are unchanged. In an embedded
workspace with `backup.enabled` unset, the per-command auto-backup check
("is there a git remote?") is likewise answered from the git config files
when they are plain (no includes, no command-line config), instead of
running `git -C .beads rev-parse --git-common-dir` and `git remote`.
- `bd create --graph` now stores a plan whose path from a node's parent to
the node runs through a `waits-for` edge; the graph-only preflight that
walked every ready-work edge used to refuse it. The plan now goes through

View file

@ -1147,6 +1147,7 @@ go_test(
"sql_test.go",
"stale_embedded_test.go",
"stale_test.go",
"startup_git_exec_embedded_test.go",
"state_embedded_test.go",
"state_proxied_integration_test.go",
"state_test.go",

View file

@ -246,3 +246,57 @@ func TestGetActorWithGit_PriorityOrder(t *testing.T) {
t.Errorf("Expected BD_ACTOR to be used as fallback, got %q", result)
}
}
// TestDeferredActorGitFallback pins the lazy actor: PersistentPreRunE defers
// the git config user.name fallback, and the first reader resolves it to
// exactly what the former eager getActorWithGit assignment produced.
func TestDeferredActorGitFallback(t *testing.T) {
origActor, origPending := actor, actorGitFallbackPending
var origCtxActor string
if cmdCtx != nil {
origCtxActor = cmdCtx.Actor
}
t.Cleanup(func() {
actor, actorGitFallbackPending = origActor, origPending
if cmdCtx != nil {
cmdCtx.Actor = origCtxActor
}
})
t.Setenv("BEADS_ACTOR", "")
t.Setenv("BD_ACTOR", "")
actor = "explicit"
deferActorGitFallback()
if actorGitFallbackPending {
t.Fatal("a configured actor must not defer a git lookup")
}
if got := currentActor(); got != "explicit" {
t.Fatalf("currentActor() = %q, want %q", got, "explicit")
}
actor = ""
want := resolveActorWithGit()
deferActorGitFallback()
if !actorGitFallbackPending || actor != "" {
t.Fatalf("deferral resolved eagerly: pending=%v actor=%q", actorGitFallbackPending, actor)
}
if got := currentActor(); got != want {
t.Fatalf("currentActor() = %q, want eager resolution %q", got, want)
}
if actorGitFallbackPending || actor != want {
t.Fatalf("after first use: pending=%v actor=%q, want resolved %q", actorGitFallbackPending, actor, want)
}
actor = ""
deferActorGitFallback()
if got := getActorWithGit(); got != want || actorGitFallbackPending || actor != want {
t.Fatalf("getActorWithGit() = %q (pending=%v actor=%q), want %q resolved into the global", got, actorGitFallbackPending, actor, want)
}
actor = ""
deferActorGitFallback()
setActor("assigned")
if got := currentActor(); got != "assigned" {
t.Fatalf("setActor must cancel a deferred fallback: currentActor() = %q", got)
}
}

View file

@ -540,7 +540,7 @@ func runADOSync(cmd *cobra.Command, _ []string) error {
}
// Create the sync engine
engine := tracker.NewEngine(at, store, actor)
engine := tracker.NewEngine(at, store, currentActor())
var warnings []string
if !jsonOutput {
engine.OnMessage = func(msg string) { _, _ = fmt.Fprintln(out, " "+msg) }
@ -641,7 +641,7 @@ func runADOSync(cmd *cobra.Command, _ []string) error {
continue
}
reason := fmt.Sprintf("ADO work item %s deleted", idStr)
if cerr := store.CloseIssue(ctx, localID, reason, actor, ""); cerr != nil {
if cerr := store.CloseIssue(ctx, localID, reason, currentActor(), ""); cerr != nil {
msg := fmt.Sprintf("Failed to close %s for deleted ADO #%s: %v", localID, idStr, cerr)
warnings = append(warnings, msg)
if !jsonOutput {
@ -915,7 +915,7 @@ func buildADOPullHooks(ctx context.Context, at *ado.Tracker, bootstrapMatch, noC
"external_ref": ref,
"source_system": "ado:" + extIssue.ID,
}
if err := store.UpdateIssue(ctx, result.BeadsID, updates, actor); err == nil {
if err := store.UpdateIssue(ctx, result.BeadsID, updates, currentActor()); err == nil {
*matchCount++
if warn != nil {
warn(fmt.Sprintf("Bootstrap matched ADO #%s → %s (%s)", extIssue.ID, result.BeadsID, result.MatchType))

View file

@ -85,7 +85,7 @@ Examples:
// lost race reports precondition_failed from the guarded write below
// instead of this policy refusal — see ifRevisionAlreadyStale's doc.
if !ifRevisionAlreadyStale(result.Issue, ifRevision) {
if err := validateIssueReassignable(id, result.Issue, actor, assignee,
if err := validateIssueReassignable(id, result.Issue, currentActor(), assignee,
storeClaimPoolAliases(ctx, issueStore), force); err != nil {
return HandleErrorRespectJSON("%s", err)
}
@ -104,7 +104,7 @@ Examples:
return HandleErrorRespectJSON("%v", err)
}
mutationResult, err := runCommandUpdateMutation(opsCtx, ops, commandUpdateMutation{
actor: actor,
actor: currentActor(),
issueID: result.ResolvedID,
patch: issueops.IssuePatch{
Assignee: issueops.Field[string]{Set: true, Value: assignee},
@ -121,7 +121,7 @@ Examples:
return HandleErrorRespectJSON("updating %s: %v", id, err)
}
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
Command: "assign",
IssueIDs: []string{result.ResolvedID},
}); err != nil {

View file

@ -77,8 +77,8 @@ var auditRecordCmd = &cobra.Command{
if err := json.Unmarshal(b, &e); err != nil {
return HandleError("invalid JSON on stdin: %v", err)
}
if actor != "" {
e.Actor = actor
if currentActor() != "" {
e.Actor = currentActor()
}
} else {
if auditRecordKind == "" {
@ -86,7 +86,7 @@ var auditRecordCmd = &cobra.Command{
}
e = audit.Entry{
Kind: auditRecordKind,
Actor: actor,
Actor: currentActor(),
IssueID: auditRecordIssueID,
Model: auditRecordModel,
Prompt: auditRecordPrompt,
@ -137,7 +137,7 @@ var auditLabelCmd = &cobra.Command{
}
e := audit.Entry{
Kind: "label",
Actor: actor,
Actor: currentActor(),
ParentID: parentID,
Label: auditLabelValue,
Reason: auditLabelReason,

View file

@ -227,7 +227,7 @@ the flags appear in the command line.`,
// suppressed real-close side effects (no audit, no closed→closed on the
// step). Register the store when it actually closed the root so the
// pending-commit sweep persists it — closedCount==0 would not commit.
if molID := autoCloseCompletedMolecule(ctx, activeStore, id, actor, session); molID != "" {
if molID := autoCloseCompletedMolecule(ctx, activeStore, id, currentActor(), session); molID != "" {
mutatedStores[activeStore] = append(mutatedStores[activeStore], molID)
}
} else {
@ -238,13 +238,13 @@ the flags appear in the command line.`,
if issue != nil {
oldStatus = string(issue.Status)
}
audit.LogFieldChange(id, "status", oldStatus, "closed", actor, reason)
audit.LogFieldChange(id, "status", oldStatus, "closed", currentActor(), reason)
closedCount++
// Auto-close parent molecule if all steps are now complete.
// Runs against the same store the step was closed in.
autoCloseCompletedMolecule(ctx, activeStore, id, actor, session)
autoCloseCompletedMolecule(ctx, activeStore, id, currentActor(), session)
}
// First id this command settled as closed — a real close or an
@ -313,7 +313,7 @@ the flags appear in the command line.`,
if continueFlag && len(resolvedIDs) == 1 && closedForCommand {
autoClaim := !noAuto
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(postCloseStore), resolvedIDs[0], autoClaim, actor)
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(postCloseStore), resolvedIDs[0], autoClaim, currentActor())
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not advance to next step: %v\n", err)
} else if result != nil {
@ -400,7 +400,7 @@ the flags appear in the command line.`,
if s == nil {
continue
}
if err := commitPendingIfEmbedded(ctx, s, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, s, currentActor(), doltAutoCommitParams{
Command: "close",
IssueIDs: ids,
}); err != nil {

View file

@ -81,7 +81,7 @@ func closeDirectCheckOne(id string, issue *types.Issue, st storage.DoltStorage,
// guard remains the authority on whether the close is a no-op, so a
// concurrent close still converges. Mirrored in closeProxiedCheckOne.
if issue == nil || issue.Status != types.StatusClosed {
if err := validateIssueClosable(id, issue, actor, force); err != nil {
if err := validateIssueClosable(id, issue, currentActor(), force); err != nil {
return err.Error()
}
}
@ -135,7 +135,7 @@ func closeDirectBatches(items []closeDirectItem) []closeDirectBatch {
// hands out ONE claim however many stores the ids spanned.
func closeDirectRequest(batch closeDirectBatch, session string, force bool, claimStore storage.DoltStorage, claimNext *issueops.ReadyRequest) issueops.CloseBatchRequest {
request := issueops.CloseBatchRequest{
Actor: actor,
Actor: currentActor(),
Items: make([]issueops.BatchCloseItem, 0, len(batch.items)),
Session: session,
Force: force,

View file

@ -50,7 +50,7 @@ func runCloseDirectIfRevision(ctx context.Context, id, reason string, force bool
preCloseStatus := string(result.Issue.Status)
closeResult, closeErr := ops.Close(opsCtx, issueops.CloseRequest{
Actor: actor,
Actor: currentActor(),
IssueID: result.ResolvedID,
Reason: reason,
Session: session,
@ -79,11 +79,11 @@ func runCloseDirectIfRevision(ctx context.Context, id, reason string, force bool
// entirely (mc-zndi7.75) and would otherwise leave a molecule's root
// stranded open forever.
mutatedIDs := []string{result.ResolvedID}
if molID := autoCloseCompletedMolecule(ctx, result.Store, result.ResolvedID, actor, session); molID != "" {
if molID := autoCloseCompletedMolecule(ctx, result.Store, result.ResolvedID, currentActor(), session); molID != "" {
mutatedIDs = append(mutatedIDs, molID)
}
if err := commitPendingIfEmbedded(ctx, result.Store, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, result.Store, currentActor(), doltAutoCommitParams{
Command: "close",
IssueIDs: mutatedIDs,
}); err != nil {
@ -116,7 +116,7 @@ func runCloseProxiedIfRevision(ctx context.Context, id, reason string, force boo
}
closeResult, closeErr := ops.Close(ctx, issueops.CloseRequest{
Actor: actor,
Actor: currentActor(),
IssueID: id,
Reason: reason,
Session: session,
@ -165,7 +165,7 @@ func runCloseIfRevisionProxiedPostClose(ctx context.Context, id, session string)
}
autoClosedMol, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (*types.Issue, string, error) {
var warnings []string
mol := autoCloseProxiedCompletedMolecule(ctx, uw, id, actor, session, &warnings)
mol := autoCloseProxiedCompletedMolecule(ctx, uw, id, currentActor(), session, &warnings)
for _, w := range warnings {
fmt.Fprintf(os.Stderr, "Warning: %s\n", w)
}
@ -209,7 +209,7 @@ func reportClosedIfRevisionResult(id, reason, preCloseStatus string, closeResult
closedIssue.Dependencies = nil
}
if closeResult.Changed {
audit.LogFieldChange(id, "status", preCloseStatus, "closed", actor, reason)
audit.LogFieldChange(id, "status", preCloseStatus, "closed", currentActor(), reason)
}
if jsonOutput {
if closedIssue != nil {

View file

@ -140,7 +140,7 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
return HandleErrorRespectJSON("%v", cerr)
}
result, err = closer.CloseBatch(ctx, issueops.CloseBatchRequest{
Actor: actor,
Actor: currentActor(),
Items: pre.items,
Session: in.session,
Force: in.force,
@ -166,7 +166,7 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
for i, o := range outcomes {
if o.closed {
audit.LogFieldChange(o.id, "status", o.auditOld, "closed", actor, o.auditReason)
audit.LogFieldChange(o.id, "status", o.auditOld, "closed", currentActor(), o.auditReason)
}
if !in.jsonOut {
fmt.Printf("%s Closed %s: %s\n", ui.RenderPass("✓"), formatFeedbackID(o.after.ID, o.after.Title), closeReasons[i])
@ -300,7 +300,7 @@ func closeProxiedCheckOne(ctx context.Context, uw uow.UnitOfWork, id string, in
// always been. Both close paths must agree here — diverging is the defect
// class #5217 closed.
if current.Status != types.StatusClosed {
if err := validateIssueClosable(id, current, actor, in.force); err != nil {
if err := validateIssueClosable(id, current, currentActor(), in.force); err != nil {
return err.Error(), nil
}
}
@ -483,7 +483,7 @@ func closeProxiedRunPostClose(ctx context.Context, args []string, in closeProxie
var wrote []string
for _, o := range outcomes {
mol := autoCloseProxiedCompletedMolecule(ctx, uw, o.id, actor, in.session, &out.warnings)
mol := autoCloseProxiedCompletedMolecule(ctx, uw, o.id, currentActor(), in.session, &out.warnings)
if mol != nil {
out.autoClosedMol = mol
wrote = append(wrote, "auto-close "+mol.ID)
@ -529,7 +529,7 @@ func closeProxiedSuggestNext(ctx context.Context, uw uow.UnitOfWork, closedID st
}
func closeProxiedContinue(ctx context.Context, uw uow.UnitOfWork, closedID string, autoClaim bool) (*ContinueResult, string) {
result, err := AdvanceToNextStep(ctx, newUOWMolWriter(uw), closedID, autoClaim, actor)
result, err := AdvanceToNextStep(ctx, newUOWMolWriter(uw), closedID, autoClaim, currentActor())
if err != nil {
return nil, fmt.Sprintf("could not advance to next step: %v", err)
}

View file

@ -183,7 +183,7 @@ To list comments on an issue, use the plural form: bd comments <id>`,
if err != nil {
return HandleErrorRespectJSON("adding comment: %v", err)
}
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
Command: "comment",
IssueIDs: []string{result.ResolvedID},
}); err != nil {

View file

@ -258,7 +258,7 @@ Examples:
if err != nil {
return HandleErrorRespectJSON("adding comment: %v", err)
}
if err := commitPendingIfEmbedded(ctx, result.Store, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, result.Store, currentActor(), doltAutoCommitParams{
Command: "comments add",
IssueIDs: []string{issueID},
}); err != nil {

View file

@ -112,17 +112,26 @@ func setStore(s storage.DoltStorage) {
// getActor returns the current actor name for audit trail.
func getActor() string {
if shouldUseGlobals() {
return actor
return currentActor()
}
// cmdCtx.Actor is a copy of the global taken by syncCommandContext or
// setActor. While the two agree, the global is authoritative and may
// still carry a deferred git fallback (see deferActorGitFallback).
if cmdCtx.Actor == actor {
return currentActor()
}
return cmdCtx.Actor
}
// setActor updates the actor name in the CommandContext.
func setActor(a string) {
actorMu.Lock()
defer actorMu.Unlock()
if cmdCtx != nil {
cmdCtx.Actor = a
}
actor = a
actorGitFallbackPending = false
}
// isJSONOutput returns true if JSON output mode is enabled.

View file

@ -1001,20 +1001,20 @@ func cookFormula(ctx context.Context, s storage.DoltStorage, f *formula.Formula,
}
// Create all issues
if err := tx.CreateIssues(ctx, issues, actor); err != nil {
if err := tx.CreateIssues(ctx, issues, currentActor()); err != nil {
return fmt.Errorf("failed to create issues: %w", err)
}
// Add labels
for _, l := range labels {
if err := tx.AddLabel(ctx, l.issueID, l.label, actor); err != nil {
if err := tx.AddLabel(ctx, l.issueID, l.label, currentActor()); err != nil {
return fmt.Errorf("failed to add label %s to %s: %w", l.label, l.issueID, err)
}
}
// Add dependencies
for _, dep := range deps {
if err := tx.AddDependency(ctx, dep, actor); err != nil {
if err := tx.AddDependency(ctx, dep, currentActor()); err != nil {
return fmt.Errorf("failed to create dependency: %w", err)
}
}

View file

@ -568,7 +568,7 @@ var createCmd = &cobra.Command{
// dry-run preview needs it too; asking the facade to inherit as well
// would append the parent's labels a second time.
result, err := ops.Create(opsCtx, issueops.CreateRequest{
Actor: actor,
Actor: currentActor(),
Issue: issue,
ParentID: parentID,
Dependencies: createDependencyRequests(depSpecs),
@ -610,7 +610,7 @@ var createCmd = &cobra.Command{
}
if repoPath != "." && targetStore != nil {
if err := commitPendingIfEmbedded(ctx, targetStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, targetStore, currentActor(), doltAutoCommitParams{
Command: "create",
IssueIDs: []string{created.ID},
}); err != nil {

View file

@ -371,7 +371,7 @@ func runCreateForm(cmd *cobra.Command) error {
fv := parseCreateFormInput(raw)
fv.ParentID = parentID
issue, err := CreateIssueFromFormValues(rootCtx, store, fv, actor)
issue, err := CreateIssueFromFormValues(rootCtx, store, fv, currentActor())
if err != nil {
return HandleError("%v", err)
}

View file

@ -123,7 +123,7 @@ Examples:
updates["notes"] = notes + reason
}
if err := store.UpdateIssue(ctx, fullID, updates, actor); err != nil {
if err := store.UpdateIssue(ctx, fullID, updates, currentActor()); err != nil {
fmt.Fprintf(os.Stderr, "Error deferring %s: %v\n", fullID, err)
continue
}

View file

@ -27,9 +27,9 @@ type deferProxiedResult struct {
func proxiedUpdateByID(ctx context.Context, uw uow.UnitOfWork, id string, isWisp bool, updates map[string]any) error {
if isWisp {
return uw.IssueUseCase().UpdateWisp(ctx, id, updates, actor)
return uw.IssueUseCase().UpdateWisp(ctx, id, updates, currentActor())
}
return uw.IssueUseCase().UpdateIssue(ctx, id, updates, actor)
return uw.IssueUseCase().UpdateIssue(ctx, id, updates, currentActor())
}
func proxiedGetByID(ctx context.Context, uw uow.UnitOfWork, id string, isWisp bool) *types.Issue {

View file

@ -163,7 +163,7 @@ Force: Delete and orphan dependents
// rewrite runs INSIDE the transaction that deletes, because it is the
// role's.
request := issueops.DeleteRequest{
Actor: actor,
Actor: currentActor(),
IDs: []string{issueID},
Force: force,
DryRun: dryRun || !force,
@ -378,7 +378,7 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
// --force is the confirmation as well as the orphan mode, so an unconfirmed
// run asks the role what it WOULD do; see the single-id path.
request := issueops.DeleteRequest{
Actor: actor,
Actor: currentActor(),
IDs: resolvedIDs,
Cascade: cascade,
Force: force,

View file

@ -102,7 +102,7 @@ func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
// --force is the confirmation as well as the orphan mode, exactly as on the
// direct route, so an unconfirmed run asks the role what it WOULD do.
request := issueops.DeleteRequest{
Actor: actor,
Actor: currentActor(),
IDs: in.ids,
Cascade: in.cascade,
Force: in.force,

View file

@ -37,7 +37,7 @@ func addDependencyEdgesDirect(ctx context.Context, st storage.DoltStorage, edges
return err
}
_, err = editor.AddDependencies(ctx, issueops.AddDependenciesRequest{
Actor: actor,
Actor: currentActor(),
Edges: edges,
SkipPerEdgeCycleCheck: skipPerEdgeCycleCheck,
})
@ -330,7 +330,7 @@ Examples:
warnIfCyclesExist(fromStore)
}
if err := commitPendingIfEmbedded(ctx, fromStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, fromStore, currentActor(), doltAutoCommitParams{
Command: "dep add",
IssueIDs: []string{fromID, toID},
}); err != nil {
@ -520,7 +520,7 @@ Examples:
warnIfCyclesExist(fromStore)
}
if err := commitPendingIfEmbedded(ctx, fromStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, fromStore, currentActor(), doltAutoCommitParams{
Command: "dep add",
IssueIDs: []string{fromID, toID},
}); err != nil {
@ -1270,7 +1270,7 @@ var depRemoveCmd = &cobra.Command{
return HandleErrorRespectJSON("%v", err)
}
result, err := editor.RemoveDependency(opsCtx, issueops.RemoveDependencyRequest{
Actor: actor,
Actor: currentActor(),
IssueID: fullFromID,
DependsOnID: fullToID,
})
@ -1278,7 +1278,7 @@ var depRemoveCmd = &cobra.Command{
return HandleErrorRespectJSON("%v", err)
}
if err := commitPendingIfEmbedded(ctx, fromStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, fromStore, currentActor(), doltAutoCommitParams{
Command: "dep remove",
IssueIDs: []string{fullFromID, fullToID},
}); err != nil {

View file

@ -76,7 +76,7 @@ func addDependencyEdgesProxied(ctx context.Context, edges []issueops.DependencyE
return err
}
_, err = editor.AddDependencies(ctx, issueops.AddDependenciesRequest{
Actor: actor,
Actor: currentActor(),
Edges: edges,
SkipPerEdgeCycleCheck: skipPerEdgeCycleCheck,
})
@ -370,7 +370,7 @@ func runDepRemoveProxiedServer(_ *cobra.Command, ctx context.Context, args []str
return HandleErrorRespectJSON("%v", err)
}
result, err := editor.RemoveDependency(ctx, issueops.RemoveDependencyRequest{
Actor: actor,
Actor: currentActor(),
IssueID: fromID,
DependsOnID: toID,
})

View file

@ -424,7 +424,7 @@ func performMerge(targetID string, sourceIDs []string) map[string]interface{} {
// Close the duplicate issue
reason := fmt.Sprintf("Duplicate of %s", targetID)
if err := store.CloseIssue(ctx, sourceID, reason, actor, ""); err != nil {
if err := store.CloseIssue(ctx, sourceID, reason, currentActor(), ""); err != nil {
errors = append(errors, fmt.Sprintf("failed to close %s: %v", sourceID, err))
continue
}

View file

@ -150,7 +150,7 @@ Examples:
fieldToEdit: newValue,
}
err = issueStore.UpdateIssue(ctx, id, updates, actor)
err = issueStore.UpdateIssue(ctx, id, updates, currentActor())
if err != nil {
if accessor, ok := storage.UnwrapStore(issueStore).(storage.RawDBAccessor); ok {
if pingErr := accessor.DB().PingContext(ctx); pingErr != nil {
@ -158,14 +158,14 @@ Examples:
_ = accessor.DB().PingContext(ctx)
}
}
err = issueStore.UpdateIssue(ctx, id, updates, actor)
err = issueStore.UpdateIssue(ctx, id, updates, currentActor())
}
if err != nil {
fmt.Fprintf(os.Stderr, "Your edits are preserved in: %s\n", tmpPath)
return HandleErrorRespectJSON("updating issue: %v", err)
}
editSaved = true
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
Command: "edit",
IssueIDs: []string{id},
}); err != nil {

View file

@ -275,7 +275,7 @@ This is used by 'bd done --phase-complete' to register for gate wake notificatio
updates := map[string]interface{}{
"waiters": newWaiters,
}
if err := store.UpdateIssue(ctx, gateID, updates, actor); err != nil {
if err := store.UpdateIssue(ctx, gateID, updates, currentActor()); err != nil {
return HandleError("updating gate: %v", err)
}
@ -355,7 +355,7 @@ Examples:
}
gate.Metadata = metadata
if err := store.CreateIssue(ctx, gate, actor); err != nil {
if err := store.CreateIssue(ctx, gate, currentActor()); err != nil {
return HandleErrorRespectJSON("creating gate: %v", err)
}
@ -364,7 +364,7 @@ Examples:
DependsOnID: gate.ID,
Type: types.DepBlocks,
}
if err := store.AddDependency(ctx, dep, actor); err != nil {
if err := store.AddDependency(ctx, dep, currentActor()); err != nil {
return HandleErrorRespectJSON("adding blocking dependency: %v", err)
}
@ -573,7 +573,7 @@ Use --reason to provide context for why the gate was resolved.`,
return HandleError("%s is not a gate issue (type=%s)", gateID, issue.IssueType)
}
if err := store.CloseIssue(ctx, gateID, reason, actor, ""); err != nil {
if err := store.CloseIssue(ctx, gateID, reason, currentActor(), ""); err != nil {
return HandleError("closing gate: %v", err)
}
@ -679,7 +679,7 @@ Examples:
return updateGateAwaitIDFunc(nil, gateID, runID)
}
recordSeen = func(gate *types.Issue) error {
if err := store.UpdateIssue(ctx, gate.ID, beadGateSeenUpdate(gate.AwaitID), actor); err != nil {
if err := store.UpdateIssue(ctx, gate.ID, beadGateSeenUpdate(gate.AwaitID), currentActor()); err != nil {
return err
}
commandDidWrite.Store(true)
@ -1575,7 +1575,7 @@ func beadGateRetargetUpdate(awaitID string, dropSeen bool) map[string]interface{
// closeGate closes a gate issue with the given reason
func closeGate(_ interface{}, gateID, reason string) error {
if err := store.CloseIssue(rootCtx, gateID, reason, actor, ""); err != nil {
if err := store.CloseIssue(rootCtx, gateID, reason, currentActor(), ""); err != nil {
return err
}
commandDidWrite.Store(true)

View file

@ -581,7 +581,7 @@ func updateGateAwaitID(_ interface{}, gateID, runID string) error {
updates := map[string]interface{}{
"await_id": runID,
}
if err := store.UpdateIssue(rootCtx, gateID, updates, actor); err != nil {
if err := store.UpdateIssue(rootCtx, gateID, updates, currentActor()); err != nil {
return err
}
return nil

View file

@ -140,7 +140,7 @@ func runGateCheckProxiedServer(cmd *cobra.Command, ctx context.Context) error {
}
for gateID, runID := range discovered {
if err := uw.IssueUseCase().UpdateIssue(ctx, gateID, map[string]any{"await_id": runID}, actor); err != nil {
if err := uw.IssueUseCase().UpdateIssue(ctx, gateID, map[string]any{"await_id": runID}, currentActor()); err != nil {
out.awaitErrs[gateID] = fmt.Errorf("failed to update gate with discovered run ID: %w", err)
continue
}
@ -168,7 +168,7 @@ func runGateCheckProxiedServer(cmd *cobra.Command, ctx context.Context) error {
if before != nil && before.Status == types.StatusClosed {
continue
}
res, closeErr := uw.IssueUseCase().CloseIssue(ctx, r.gate.ID, domain.CloseIssueParams{Reason: r.reason}, actor)
res, closeErr := uw.IssueUseCase().CloseIssue(ctx, r.gate.ID, domain.CloseIssueParams{Reason: r.reason}, currentActor())
if closeErr != nil {
out.closeErrs[r.gate.ID] = closeErr
continue
@ -192,7 +192,7 @@ func runGateCheckProxiedServer(cmd *cobra.Command, ctx context.Context) error {
}
for _, c := range applied.closed {
audit.LogFieldChange(c.after.ID, "status", c.oldStatus, "closed", actor, c.reason)
audit.LogFieldChange(c.after.ID, "status", c.oldStatus, "closed", currentActor(), c.reason)
}
if len(applied.closed) > 0 || len(applied.updated) > 0 {
commandDidWrite.Store(true)
@ -326,7 +326,7 @@ func runGateAddWaiterProxiedServer(_ *cobra.Command, ctx context.Context, args [
}
newWaiters := append(issue.Waiters, waiter)
if err := uw.IssueUseCase().UpdateIssue(ctx, gateID, map[string]any{"waiters": newWaiters}, actor); err != nil {
if err := uw.IssueUseCase().UpdateIssue(ctx, gateID, map[string]any{"waiters": newWaiters}, currentActor()); err != nil {
return out, "", fmt.Errorf("updating gate: %w", err)
}
if after, getErr := uw.IssueUseCase().GetIssue(ctx, gateID); getErr == nil {
@ -394,7 +394,7 @@ func runGateCreateProxiedServer(cmd *cobra.Command, ctx context.Context) error {
}
gate.Metadata = metadata
res, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{Issue: gate}, actor)
res, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{Issue: gate}, currentActor())
if err != nil {
return out, "", fmt.Errorf("creating gate: %w", err)
}
@ -404,7 +404,7 @@ func runGateCreateProxiedServer(cmd *cobra.Command, ctx context.Context) error {
DependsOnID: res.Issue.ID,
Type: types.DepBlocks,
}
if err := uw.DependencyUseCase().AddDependency(ctx, dep, actor); err != nil {
if err := uw.DependencyUseCase().AddDependency(ctx, dep, currentActor()); err != nil {
return out, "", fmt.Errorf("adding blocking dependency: %w", err)
}
@ -464,7 +464,7 @@ func runGateResolveProxiedServer(cmd *cobra.Command, ctx context.Context, args [
return out, "", fmt.Errorf("%s is not a gate issue (type=%s)", gateID, issue.IssueType)
}
res, err := uw.IssueUseCase().CloseIssue(ctx, gateID, domain.CloseIssueParams{Reason: reason}, actor)
res, err := uw.IssueUseCase().CloseIssue(ctx, gateID, domain.CloseIssueParams{Reason: reason}, currentActor())
if err != nil {
return out, "", fmt.Errorf("closing gate: %w", err)
}
@ -486,7 +486,7 @@ func runGateResolveProxiedServer(cmd *cobra.Command, ctx context.Context, args [
// double-resolve must not re-log it (same guard as the o.closed check in
// close_proxied_server.go).
if applied.closed && applied.after != nil {
audit.LogFieldChange(applied.after.ID, "status", applied.oldStatus, "closed", actor, reason)
audit.LogFieldChange(applied.after.ID, "status", applied.oldStatus, "closed", currentActor(), reason)
}
commandDidWrite.Store(true)

View file

@ -93,7 +93,7 @@ func runGCProxiedServer(ctx context.Context) error {
ids[i] = issue.ID
}
deleteResult, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeleteIssuesResult, string, error) {
res, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{IDs: ids}, actor)
res, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{IDs: ids}, currentActor())
if err != nil {
return domain.DeleteIssuesResult{}, "", err
}

View file

@ -419,7 +419,7 @@ func runGitHubSync(cmd *cobra.Command, args []string) error {
}
// Create the sync engine
engine := tracker.NewEngine(gt, store, actor)
engine := tracker.NewEngine(gt, store, currentActor())
engine.OnMessage = func(msg string) { _, _ = fmt.Fprintln(out, " "+msg) }
engine.OnWarning = func(msg string) { _, _ = fmt.Fprintf(os.Stderr, "Warning: %s\n", msg) }

View file

@ -511,7 +511,7 @@ func runGitLabSync(cmd *cobra.Command, args []string) error {
}
// Create the sync engine
engine := tracker.NewEngine(gt, store, actor)
engine := tracker.NewEngine(gt, store, currentActor())
if !jsonOutput {
engine.OnMessage = func(msg string) { _, _ = fmt.Fprintln(out, " "+msg) }
}

View file

@ -1167,7 +1167,7 @@ func graphApplyEdgeBatchMetadata(edge GraphApplyEdge, depType types.DependencyTy
}
func executeGraphApply(ctx context.Context, plan *GraphApplyPlan, opts GraphApplyOptions) (*GraphApplyResult, error) {
req, err := buildGraphApplyBatchRequest(plan, opts, actor, getOwner())
req, err := buildGraphApplyBatchRequest(plan, opts, currentActor(), getOwner())
if err != nil {
return nil, err
}

View file

@ -68,11 +68,11 @@ Examples:
defer result.Close()
issueStore := result.Store
if err := issueStore.HeartbeatIssue(ctx, result.ResolvedID, actor); err != nil {
if err := issueStore.HeartbeatIssue(ctx, result.ResolvedID, currentActor()); err != nil {
return HandleErrorRespectJSON("heartbeat %s: %v", result.ResolvedID, err)
}
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
Command: "heartbeat",
IssueIDs: []string{result.ResolvedID},
}); err != nil {
@ -94,7 +94,7 @@ func renderHeartbeatSuccess(id, title string) error {
return outputJSON(map[string]string{
"id": id,
"status": "heartbeat",
"owner": actor,
"owner": currentActor(),
})
}
fmt.Printf("%s Heartbeat %s (lease refreshed)\n", ui.RenderPass("✓"), formatFeedbackID(id, title))

View file

@ -41,7 +41,7 @@ func runHeartbeatProxiedServer(ctx context.Context, id string) error {
}
// Wisps resolve here too and are refused below: the repo verb
// classifies them ErrNotClaimable ("is ephemeral"), same as classic.
if herr := uw.IssueUseCase().Heartbeat(ctx, issue.ID, actor); herr != nil {
if herr := uw.IssueUseCase().Heartbeat(ctx, issue.ID, currentActor()); herr != nil {
return heartbeatProxiedOutcome{}, fmt.Errorf("heartbeat %s: %w", issue.ID, herr)
}
return heartbeatProxiedOutcome{id: issue.ID, title: issue.Title}, nil

View file

@ -307,12 +307,12 @@ Examples:
warnIfNotHumanLabeled(issue)
_, err = targetStore.AddIssueComment(ctx, resolvedID, actor, commentText)
_, err = targetStore.AddIssueComment(ctx, resolvedID, currentActor(), commentText)
if err != nil {
return HandleErrorRespectJSON("adding comment: %v", err)
}
if err := targetStore.CloseIssue(ctx, resolvedID, "Responded", actor, ""); err != nil {
if err := targetStore.CloseIssue(ctx, resolvedID, "Responded", currentActor(), ""); err != nil {
return HandleErrorRespectJSON("closing bead: %v", err)
}
@ -403,7 +403,7 @@ Examples:
warnIfNotHumanLabeled(issue)
if err := targetStore.CloseIssue(ctx, resolvedID, closeReason, actor, ""); err != nil {
if err := targetStore.CloseIssue(ctx, resolvedID, closeReason, currentActor(), ""); err != nil {
return HandleErrorRespectJSON("closing bead: %v", err)
}

View file

@ -122,9 +122,9 @@ func closeHumanProxied(ctx context.Context, id, comment, closeReason, commitVerb
if comment != "" {
var cerr error
if isWisp {
_, cerr = uw.CommentUseCase().AddCommentToWisp(ctx, issue.ID, actor, comment)
_, cerr = uw.CommentUseCase().AddCommentToWisp(ctx, issue.ID, currentActor(), comment)
} else {
_, cerr = uw.CommentUseCase().AddCommentToIssue(ctx, issue.ID, actor, comment)
_, cerr = uw.CommentUseCase().AddCommentToIssue(ctx, issue.ID, currentActor(), comment)
}
if cerr != nil {
return humanCloseResult{}, "", fmt.Errorf("adding comment: %w", cerr)
@ -133,9 +133,9 @@ func closeHumanProxied(ctx context.Context, id, comment, closeReason, commitVerb
params := domain.CloseIssueParams{Reason: closeReason}
if isWisp {
_, err = uw.IssueUseCase().CloseWisp(ctx, issue.ID, params, actor)
_, err = uw.IssueUseCase().CloseWisp(ctx, issue.ID, params, currentActor())
} else {
_, err = uw.IssueUseCase().CloseIssue(ctx, issue.ID, params, actor)
_, err = uw.IssueUseCase().CloseIssue(ctx, issue.ID, params, currentActor())
}
if err != nil {
return humanCloseResult{}, "", fmt.Errorf("closing bead: %w", err)

View file

@ -139,7 +139,7 @@ func runJiraSync(cmd *cobra.Command, args []string) error {
return HandleErrorRespectJSON("initializing Jira tracker: %v", err)
}
engine := tracker.NewEngine(jt, trackerStore, actor)
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) }

View file

@ -165,7 +165,7 @@ func applyLabelEdit(ctx context.Context, issueIDs []string, labels []string, ope
}
}
result, uerr := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: actor,
Actor: currentActor(),
IssueID: issueID,
Patch: patch,
})
@ -361,7 +361,7 @@ func removeLabelsByPrefix(ctx context.Context, issueIDs []string, prefix string,
outcomes := make([]labelEditOutcome, 0, len(targets))
for _, target := range targets {
result, uerr := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: actor,
Actor: currentActor(),
IssueID: target.issueID,
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{Remove: target.labels}},
})
@ -707,7 +707,7 @@ var labelPropagateCmd = &cobra.Command{
commitMsg := fmt.Sprintf("bd: propagate label '%s' from %s to %d children", label, parentID, len(children))
err = transactHonoringAutoCommit(ctx, store, commitMsg, func(tx storage.Transaction) error {
for _, child := range children {
if err := tx.AddLabel(ctx, child.ID, label, actor); err != nil {
if err := tx.AddLabel(ctx, child.ID, label, currentActor()); err != nil {
return fmt.Errorf("add label '%s' on %s: %w", label, child.ID, err)
}
}
@ -809,7 +809,7 @@ func runLabelRename(ctx context.Context, args []string, dryRun bool) error {
if usesProxiedServer() {
renamed, merged, err = runLabelRenameProxiedServer(ctx, oldLabel, newLabel)
} else {
renamed, merged, _, err = store.RenameLabel(ctx, oldLabel, newLabel, actor)
renamed, merged, _, err = store.RenameLabel(ctx, oldLabel, newLabel, currentActor())
}
// Recorded from renamed>0 BEFORE the error check: a rename can commit its
// SQL side and still return a non-nil err (e.g. the Dolt publication step

View file

@ -148,7 +148,7 @@ func runLabelRenameProxiedServer(ctx context.Context, oldLabel, newLabel string)
err = uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
var rerr error
renamed, merged, _, rerr = uw.LabelUseCase().RenameLabel(ctx, oldLabel, newLabel, actor) //nolint:forbidigo // bulk rename; no role serves it, and Patch.Labels would reintroduce the per-issue add/remove event divergence this delegation replaced
renamed, merged, _, rerr = uw.LabelUseCase().RenameLabel(ctx, oldLabel, newLabel, currentActor()) //nolint:forbidigo // bulk rename; no role serves it, and Patch.Labels would reintroduce the per-issue add/remove event divergence this delegation replaced
if rerr != nil {
return "", fmt.Errorf("rename label '%s' -> '%s': %w", oldLabel, newLabel, rerr)
}
@ -209,9 +209,9 @@ func runLabelPropagateProxiedServer(ctx context.Context, args []string) error {
for _, child := range children {
var e error
if child.Ephemeral {
e = uw.LabelUseCase().AddWispLabel(ctx, child.ID, label, actor) //nolint:forbidigo // atomic N-child fan-out; awaits a BatchApplier accessor
e = uw.LabelUseCase().AddWispLabel(ctx, child.ID, label, currentActor()) //nolint:forbidigo // atomic N-child fan-out; awaits a BatchApplier accessor
} else {
e = uw.LabelUseCase().AddLabel(ctx, child.ID, label, actor) //nolint:forbidigo // atomic N-child fan-out; awaits a BatchApplier accessor
e = uw.LabelUseCase().AddLabel(ctx, child.ID, label, currentActor()) //nolint:forbidigo // atomic N-child fan-out; awaits a BatchApplier accessor
}
if e != nil {
return "", fmt.Errorf("add label '%s' on %s: %w", label, child.ID, e)

View file

@ -338,14 +338,14 @@ func runLinearSync(cmd *cobra.Command, args []string) error {
}
}
engine := tracker.NewEngine(lt, trackerStore, actor)
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{
Milestones: milestones,
DryRun: dryRun,
Actor: actor,
Actor: currentActor(),
})
opts := tracker.SyncOptions{
@ -488,7 +488,7 @@ func buildLinearPullHooksForStore(ctx context.Context, st tracker.Store, opts li
hooks := &tracker.PullHooks{}
hookActor := opts.Actor
if hookActor == "" {
hookActor = actor
hookActor = currentActor()
}
var generateID func(context.Context, *types.Issue) error

View file

@ -77,13 +77,13 @@ Examples:
Type: dt,
}
if err := fromStore.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{EmitEvent: true}); err != nil {
if err := fromStore.AddDependencyWithOptions(ctx, dep, currentActor(), storage.DependencyAddOptions{EmitEvent: true}); err != nil {
return HandleErrorRespectJSON("%v", err)
}
warnIfCyclesExist(fromStore)
if err := commitPendingIfEmbedded(ctx, fromStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, fromStore, currentActor(), doltAutoCommitParams{
Command: "link",
IssueIDs: []string{fromID, toID},
}); err != nil {

View file

@ -35,7 +35,7 @@ func runLinkProxiedServer(cmd *cobra.Command, ctx context.Context, args []string
// Source-routed, like the direct twin's store.AddDependencyWithOptions:
// `bd link` takes whatever id the caller names, and a wisp source has no
// row in the issues plane for the edge to hang off.
if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actor, domain.BulkAddDepsOpts{}); err != nil {
if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, currentActor(), domain.BulkAddDepsOpts{}); err != nil {
return "", err
}
return fmt.Sprintf("bd: link %s %s", id1, id2), nil

View file

@ -840,6 +840,10 @@ func refreshBoundCommandConfig(cmd *cobra.Command) {
readonlyMode = config.GetBool("readonly")
}
if !root.PersistentFlags().Changed("actor") {
// Raw write, not setActor: every caller runs in PersistentPreRunE
// BEFORE deferActorGitFallback, which then decides from this value
// whether the git user.name fallback is pending. A call after it would
// need setActor (and the deferral re-run) to keep that decision true.
actor = resolveConfiguredActor()
}
if !root.PersistentFlags().Changed("dolt-auto-commit") {
@ -893,11 +897,74 @@ func resolveConfiguredActor() string {
return config.GetString("actor")
}
// actorGitFallbackPending records that PersistentPreRunE deferred the
// getActorWithGit fallback (git config user.name, then $USER) instead of
// resolving it eagerly. Most invocations — every read-only list/show/query a
// tool like gascity issues by the hundred — never consult the actor, and the
// eager lookup cost one `git config` subprocess per bd call. currentActor
// performs the deferred resolution on first use, so the resolved value and its
// priority order are unchanged; only the moment of the lookup moves.
//
// Guarded by actorMu together with the resolution it triggers. Plain writes to
// actor elsewhere stay unguarded, exactly as before this was introduced.
var (
actorMu sync.Mutex
actorGitFallbackPending bool
)
// deferActorGitFallback replaces the former eager `actor = getActorWithGit()`
// in PersistentPreRunE. A non-empty actor (--actor, BEADS_ACTOR, BD_ACTOR or
// config.yaml) is already the answer getActorWithGit would return, so only an
// empty actor needs the deferred fallback.
func deferActorGitFallback() {
actorMu.Lock()
defer actorMu.Unlock()
actorGitFallbackPending = actor == ""
}
// currentActor returns the actor for this invocation, resolving a fallback
// deferred by deferActorGitFallback on first use. Command code reads the actor
// through this instead of the raw global so that the git lookup happens only
// when an actor is actually needed.
func currentActor() string {
actorMu.Lock()
defer actorMu.Unlock()
resolvePendingActorLocked()
return actor
}
// resolvePendingActorLocked performs a deferred fallback. Caller holds actorMu.
func resolvePendingActorLocked() {
if !actorGitFallbackPending {
return
}
actorGitFallbackPending = false
deferred := actor
actor = resolveActorWithGit()
// Keep the CommandContext copy in step, as the eager assignment did
// before syncCommandContext copied it.
if cmdCtx != nil && cmdCtx.Actor == deferred {
cmdCtx.Actor = actor
}
}
// getActorWithGit returns the actor for audit trails with git config fallback.
// Priority: --actor flag > BEADS_ACTOR env > BD_ACTOR env (deprecated) > git config user.name > $USER > "unknown"
// This provides a sensible default for developers: their git identity is used unless
// explicitly overridden
// explicitly overridden.
//
// After PersistentPreRunE it returns the same value as currentActor (resolving
// a deferred fallback once, into the global, as the eager assignment did).
func getActorWithGit() string {
actorMu.Lock()
defer actorMu.Unlock()
resolvePendingActorLocked()
return resolveActorWithGit()
}
// resolveActorWithGit is getActorWithGit's resolution order, without the
// deferred-fallback bookkeeping. Caller holds actorMu or owns the global.
func resolveActorWithGit() string {
// If actor is already set (from --actor flag), use it
if actor != "" {
return actor
@ -1239,6 +1306,10 @@ var rootCmd = &cobra.Command{
WasSet bool
}{dbPath, true}
}
// Reads and writes the raw global on purpose: this runs before
// deferActorGitFallback, so no fallback is pending yet and the value
// is only the flag/env/config actor. currentActor() here would resolve
// git user.name eagerly, which is what the deferral exists to avoid.
if !cmd.Root().PersistentFlags().Changed("actor") && actor == "" {
actor = resolveConfiguredActor()
} else if cmd.Root().PersistentFlags().Changed("actor") {
@ -1674,11 +1745,14 @@ var rootCmd = &cobra.Command{
return HandleProxyCapabilityError(AssertProxyCapability(ProxyModeProxied, ProxyCapReadonly))
}
// Set actor for audit trail
actor = getActorWithGit()
// Attach actor to the command span now that we have it.
if commandSpan != nil {
commandSpan.SetAttributes(attribute.String("bd.actor", actor))
// Set actor for audit trail. The git config user.name fallback is
// resolved lazily by currentActor, so commands that never consult the
// actor (read-only queries) do not spawn a git subprocess for it.
deferActorGitFallback()
// Attach actor to the command span. Only a recording span (telemetry
// enabled) needs the value, so a noop span does not force the lookup.
if commandSpan != nil && commandSpan.IsRecording() {
commandSpan.SetAttributes(attribute.String("bd.actor", currentActor()))
}
// Check if this is a read-only command (GH#804) or an explicitly

View file

@ -425,8 +425,8 @@ func markdownBatchActor(in createInput) string {
if in.createdBy != "" {
return in.createdBy
}
if actor != "" {
return actor
if currentActor() != "" {
return currentActor()
}
return "bd"
}

View file

@ -126,7 +126,7 @@ func runMergeSlotCreate(cmd *cobra.Command, args []string) error {
}
}()
issue, err := store.MergeSlotCreate(rootCtx, actor)
issue, err := store.MergeSlotCreate(rootCtx, currentActor())
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
@ -222,13 +222,13 @@ func runMergeSlotAcquire(cmd *cobra.Command, args []string) error {
holder := mergeSlotHolder
if holder == "" {
holder = actor
holder = currentActor()
}
if holder == "" {
return HandleError("no holder specified; use --holder or set BEADS_ACTOR env var")
}
result, err := store.MergeSlotAcquire(rootCtx, holder, actor, mergeSlotAddWaiter)
result, err := store.MergeSlotAcquire(rootCtx, holder, currentActor(), mergeSlotAddWaiter)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
@ -305,7 +305,7 @@ func runMergeSlotRelease(cmd *cobra.Command, args []string) error {
}
}()
if err := store.MergeSlotRelease(rootCtx, mergeSlotHolder, actor); err != nil {
if err := store.MergeSlotRelease(rootCtx, mergeSlotHolder, currentActor()); err != nil {
return HandleErrorRespectJSON("%v", err)
}

View file

@ -600,7 +600,7 @@ func executeMigration(ctx context.Context, s storage.DoltStorage, migrationSet [
for _, id := range migrationSet {
if err := tx.UpdateIssue(ctx, id, map[string]interface{}{
"source_repo": to,
}, actor); err != nil {
}, currentActor()); err != nil {
return fmt.Errorf("failed to update issue %s: %w", id, err)
}
}

View file

@ -148,21 +148,21 @@ func runMolBond(cmd *cobra.Command, args []string) error {
var result *BondResult
switch {
case aIsProto && bIsProto:
result, err = bondProtoProto(ctx, store, issueA, issueB, in.bondType, in.customTitle, actor)
result, err = bondProtoProto(ctx, store, issueA, issueB, in.bondType, in.customTitle, currentActor())
case aIsProto && !bIsProto:
if cookedA {
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphA, issueA, issueB, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphA, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
} else {
result, err = bondProtoMol(ctx, store, issueA, issueB, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
result, err = bondProtoMol(ctx, store, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
}
case !aIsProto && bIsProto:
if cookedB {
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphB, issueB, issueA, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphB, issueB, issueA, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
} else {
result, err = bondMolProto(ctx, store, issueA, issueB, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
result, err = bondMolProto(ctx, store, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
}
default:
result, err = bondMolMol(ctx, store, issueA, issueB, in.bondType, actor)
result, err = bondMolMol(ctx, store, issueA, issueB, in.bondType, currentActor())
}
if err != nil {
return HandleErrorRespectJSON("bonding: %v", err)

View file

@ -190,7 +190,7 @@ func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, fo
// Batch delete all wisps in one call
if len(wispIDs) > 0 {
result, err := burnWisps(ctx, store, wispIDs, actor)
result, err := burnWisps(ctx, store, wispIDs, currentActor())
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Error burning wisps: %v\n", err)
@ -296,7 +296,7 @@ func burnWispMolecule(ctx context.Context, resolvedID string, dryRun, force bool
}
}
result, err := burnWisps(ctx, store, wispIDs, actor)
result, err := burnWisps(ctx, store, wispIDs, currentActor())
if err != nil {
return HandleErrorRespectJSON("burning wisp: %v", err)
}

View file

@ -73,7 +73,7 @@ Use --limit or --range to view specific steps:
agent := forAgent
if agent == "" {
agent = actor
agent = currentActor()
}
if usesProxiedServer() {

View file

@ -58,7 +58,7 @@ Example:
}
moleculeID = resolved
} else {
moleculeIDs := findInProgressMoleculeIDs(ctx, store, actor)
moleculeIDs := findInProgressMoleculeIDs(ctx, store, currentActor())
if len(moleculeIDs) == 0 {
if jsonOutput {
return outputJSON([]interface{}{})

View file

@ -124,7 +124,7 @@ func runPourProxiedServer(ctx context.Context, in pourInput) error {
spawnResult, err := cloneSubgraphInto(ctx, w, subgraph, CloneOptions{
Vars: vars,
Assignee: in.assignee,
Actor: actor,
Actor: currentActor(),
Prefix: types.IDPrefixMol,
})
if err != nil {
@ -138,7 +138,7 @@ func runPourProxiedServer(ctx context.Context, in pourInput) error {
return pourProxiedResult{}, "", fmt.Errorf("loading spawned mol: %w", err)
}
for _, attach := range attachments {
bondResult, err := bondProtoMolAttachInto(ctx, w, attach.subgraph, attach.issue, spawnedMol, in.attachType, vars, "", actor, false, true)
bondResult, err := bondProtoMolAttachInto(ctx, w, attach.subgraph, attach.issue, spawnedMol, in.attachType, vars, "", currentActor(), false, true)
if err != nil {
return pourProxiedResult{}, "", fmt.Errorf("attaching %s: %w", attach.id, err)
}
@ -278,7 +278,7 @@ func runMolProgressProxiedServer(ctx context.Context, args []string) error {
}
moleculeID = resolved
} else {
moleculeIDs := findInProgressMoleculeIDs(ctx, r, actor)
moleculeIDs := findInProgressMoleculeIDs(ctx, r, currentActor())
if len(moleculeIDs) == 0 {
if jsonOutput {
return outputJSON([]interface{}{})
@ -426,13 +426,13 @@ func runMolBondProxiedServer(ctx context.Context, in molBondInput) error {
var result *BondResult
switch {
case aIsProto && bIsProto:
result, err = bondProtoProtoInto(ctx, w, issueA, issueB, in.bondType, in.customTitle, actor)
result, err = bondProtoProtoInto(ctx, w, issueA, issueB, in.bondType, in.customTitle, currentActor())
case aIsProto && !bIsProto:
result, err = bondProtoMolAttachInto(ctx, w, subgraphA, issueA, issueB, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
result, err = bondProtoMolAttachInto(ctx, w, subgraphA, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
case !aIsProto && bIsProto:
result, err = bondProtoMolAttachInto(ctx, w, subgraphB, issueB, issueA, in.bondType, in.vars, in.childRef, actor, in.ephemeral, in.pour)
result, err = bondProtoMolAttachInto(ctx, w, subgraphB, issueB, issueA, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
default:
result, err = bondMolMolInto(ctx, w, issueA, issueB, in.bondType, actor)
result, err = bondMolMolInto(ctx, w, issueA, issueB, in.bondType, currentActor())
}
if err != nil {
return bondTxResult{}, "", fmt.Errorf("bonding: %w", err)
@ -501,7 +501,7 @@ func runMolSquashProxiedServer(ctx context.Context, in molSquashInput) error {
return &SquashResult{MoleculeID: moleculeID, SquashedCount: 0}, "", nil
}
result, err := squashMoleculeInto(ctx, w, subgraph.Root, wispChildren, in.keepChildren, in.summary, actor)
result, err := squashMoleculeInto(ctx, w, subgraph.Root, wispChildren, in.keepChildren, in.summary, currentActor())
if err != nil {
return nil, "", fmt.Errorf("squashing molecule: %w", err)
}
@ -638,7 +638,7 @@ func runMolBurnProxiedServer(ctx context.Context, args []string, dryRun, force b
if len(wispIDs) > 0 {
// The wisp half's direct twin is burnWisps -> `transact`.
result, err := uow.RunTxResult(explicitCommitPointContext(ctx), uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (*BurnResult, string, error) {
r, err := burnWispsInto(ctx, newUOWMolWriter(uw), wispIDs, actor)
r, err := burnWispsInto(ctx, newUOWMolWriter(uw), wispIDs, currentActor())
if err != nil {
return nil, "", err
}
@ -672,7 +672,7 @@ func runMolBurnProxiedServer(ctx context.Context, args []string, dryRun, force b
IDs: issueIDs,
Cascade: true,
UpdateTextReferences: true,
}, actor)
}, currentActor())
if err != nil {
return BurnResult{}, "", fmt.Errorf("burning %s: %w", id, err)
}

View file

@ -178,7 +178,7 @@ func runMolSquash(cmd *cobra.Command, args []string) error {
return nil
}
result, err := squashMolecule(ctx, store, subgraph.Root, wispChildren, in.keepChildren, in.summary, actor)
result, err := squashMolecule(ctx, store, subgraph.Root, wispChildren, in.keepChildren, in.summary, currentActor())
if err != nil {
return HandleErrorRespectJSON("squashing molecule: %v", err)
}

View file

@ -54,15 +54,15 @@ func proxiedUpdateIssueFields(ctx context.Context, id, commitMsg string, updates
// bd-98s5c: an unguarded assignee update (bd assign via the proxied
// server) must not silently overwrite another actor's live claim.
if newAssignee, ok := updates["assignee"].(string); ok {
if err := validateIssueReassignable(id, issue, actor, newAssignee,
if err := validateIssueReassignable(id, issue, currentActor(), newAssignee,
uowClaimPoolAliases(ctx, uw), force); err != nil {
return err
}
}
if isWisp {
return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, actor)
return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, currentActor())
}
return uw.IssueUseCase().UpdateIssue(ctx, issue.ID, updates, actor)
return uw.IssueUseCase().UpdateIssue(ctx, issue.ID, updates, currentActor())
})
}
@ -95,7 +95,7 @@ func proxiedAssign(ctx context.Context, id, assignee string, force bool, ifRevis
// from the guarded write below instead of this policy refusal — see
// ifRevisionAlreadyStale's doc.
if !ifRevisionAlreadyStale(current, ifRevision) {
if verr := validateIssueReassignable(id, current, actor, assignee,
if verr := validateIssueReassignable(id, current, currentActor(), assignee,
uowClaimPoolAliases(ctx, uw), force); verr != nil {
return struct{}{}, verr
}
@ -111,7 +111,7 @@ func proxiedAssign(ctx context.Context, id, assignee string, force bool, ifRevis
return nil, err
}
result, err := runCommandUpdateMutation(ctx, ops, commandUpdateMutation{
actor: actor,
actor: currentActor(),
issueID: id,
patch: issueops.IssuePatch{
Assignee: issueops.Field[string]{Set: true, Value: assignee},
@ -183,9 +183,9 @@ func runNoteProxiedServer(ctx context.Context, id, noteText string) error {
combined += noteText
updates := map[string]any{"notes": combined}
if isWisp {
return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, actor)
return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, currentActor())
}
return uw.IssueUseCase().UpdateIssue(ctx, issue.ID, updates, actor)
return uw.IssueUseCase().UpdateIssue(ctx, issue.ID, updates, currentActor())
})
if err != nil {
return HandleErrorRespectJSON("note %s: %v", id, err)
@ -245,7 +245,7 @@ func runTagProxiedServer(ctx context.Context, id, label string) error {
return HandleErrorRespectJSON("tag %s: %v", id, err)
}
result, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: actor,
Actor: currentActor(),
IssueID: details.ID,
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{Add: []string{label}}},
})

View file

@ -173,10 +173,10 @@ To read notes on an issue, use: bd show <id>`,
updates := map[string]interface{}{
issueops.OpAppendNotes: noteText,
}
if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, actor); err != nil {
if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, currentActor()); err != nil {
return HandleErrorRespectJSON("updating %s: %v", id, err)
}
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
Command: "note",
IssueIDs: []string{result.ResolvedID},
}); err != nil {

View file

@ -467,7 +467,7 @@ func runNotionSync(cmd *cobra.Command, _ []string) error {
return HandleError("initializing Notion tracker: %v", err)
}
engine := tracker.NewEngine(nt, store, actor)
engine := tracker.NewEngine(nt, store, currentActor())
engine.PullHooks = buildNotionPullHooks(ctx)
unsupportedStats := newNotionUnsupportedPushStats()
engine.PushHooks = buildNotionPushHooks(ctx, nt, unsupportedStats)

View file

@ -198,7 +198,7 @@ func runPour(cmd *cobra.Command, args []string) error {
return nil
}
result, err := spawnMolecule(ctx, store, subgraph, vars, in.assignee, actor, false, types.IDPrefixMol)
result, err := spawnMolecule(ctx, store, subgraph, vars, in.assignee, currentActor(), false, types.IDPrefixMol)
if err != nil {
return HandleError("pouring proto: %v", err)
}
@ -211,7 +211,7 @@ func runPour(cmd *cobra.Command, args []string) error {
}
for _, attach := range attachments {
bondResult, err := bondProtoMol(ctx, store, attach.issue, spawnedMol, in.attachType, vars, "", actor, false, true)
bondResult, err := bondProtoMol(ctx, store, attach.issue, spawnedMol, in.attachType, vars, "", currentActor(), false, true)
if err != nil {
return HandleError("attaching %s: %v", attach.id, err)
}

View file

@ -17,6 +17,7 @@ import (
"github.com/steveyegge/beads"
internalbeads "github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/memoryops"
)
@ -303,10 +304,16 @@ func primeWorkspaceDir() string {
// failure falls back to a cwd probe instead of propagating — so this no
// longer returns an error. If a future caller needs one, reintroduce it then.
func primeGitCmd(ctx context.Context, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Dir = primeGitDir()
return cmd
}
// primeGitDir is the directory primeGitCmd runs git in ("" for the process
// cwd): the -C target, else the cwd repository root from the RepoContext.
func primeGitDir() string {
if ws := primeWorkspaceDir(); ws != "" {
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Dir = ws
return cmd
return ws
}
rc, err := internalbeads.GetRepoContext()
if err != nil {
@ -317,9 +324,9 @@ func primeGitCmd(ctx context.Context, args ...string) *exec.Cmd {
// workspace, so probe it directly instead of giving up. The SEC-003
// boundary on BEADS_DIR stays enforced by the callers that consume
// BEADS_DIR itself; these probes only ask git about its own workspace.
return exec.CommandContext(ctx, "git", args...)
return ""
}
return rc.GitCmdCWD(ctx, args...)
return rc.CWDRepoRoot // GitCmdCWD's directory; "" leaves the process cwd
}
// outputHookJSON wraps content in the SessionStart hook JSON envelope shared
@ -422,8 +429,18 @@ var primeAgentProfile = func() config.AgentProfile {
// `git remote` in the workspace succeeds. primeGitCmd supplies that fallback,
// which keeps the -C behavior above intact. The SEC-003 boundary on BEADS_DIR
// remains enforced elsewhere.
//
// The probe runs on every command in an embedded workspace whose
// backup.enabled is unset (isBackupAutoEnabled), so it is answered from the
// config files when git.HasRemoteInProcess can prove the answer, and by
// `git remote` otherwise.
var primeHasGitRemote = func() bool {
cmd := primeGitCmd(context.Background(), "remote")
dir := primeGitDir()
if has, ok := git.HasRemoteInProcess(dir); ok {
return has
}
cmd := exec.CommandContext(context.Background(), "git", "remote")
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
return false

View file

@ -78,10 +78,10 @@ Examples:
updates := map[string]interface{}{
"priority": priority,
}
if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, actor); err != nil {
if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, currentActor()); err != nil {
return HandleErrorRespectJSON("updating %s: %v", id, err)
}
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
Command: "priority",
IssueIDs: []string{result.ResolvedID},
}); err != nil {

View file

@ -97,13 +97,13 @@ Examples:
return HandleErrorRespectJSON("%s is not a wisp (already persistent)", fullID)
}
if err := store.PromoteFromEphemeral(ctx, fullID, actor); err != nil {
if err := store.PromoteFromEphemeral(ctx, fullID, currentActor()); err != nil {
return HandleErrorRespectJSON("promoting %s: %v", fullID, err)
}
// Add promotion comment (issue is now in permanent table, AddComment routes correctly
// via GetIssue fallback)
if err := store.AddComment(ctx, fullID, actor, promotionComment(reason)); err != nil {
if err := store.AddComment(ctx, fullID, currentActor(), promotionComment(reason)); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to add promotion comment to %s: %v\n", fullID, err)
}

View file

@ -62,10 +62,10 @@ func runPromoteProxiedServer(ctx context.Context, id, reason string) error {
}
err = uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
if err := uw.IssueUseCase().PromoteWisp(ctx, fullID, actor); err != nil {
if err := uw.IssueUseCase().PromoteWisp(ctx, fullID, currentActor()); err != nil {
return "", err
}
if _, err := uw.CommentUseCase().AddCommentToIssue(ctx, fullID, actor, promotionComment(reason)); err != nil {
if _, err := uw.CommentUseCase().AddCommentToIssue(ctx, fullID, currentActor(), promotionComment(reason)); err != nil {
return "", fmt.Errorf("adding promotion comment: %w", err)
}
return fmt.Sprintf("bd: promote %s", fullID), nil

View file

@ -165,7 +165,7 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error {
}
request := issueops.SweepRequest{
Actor: actor,
Actor: currentActor(),
Tier: scope.tier,
IDPattern: pattern,
ProtectReferenced: scope.protectReferenced,

View file

@ -94,7 +94,7 @@ Example:
// The issue and its parent-child edge commit in one transaction; a
// failed edge rolls back the create instead of leaving a dep-less
// child behind (same contract as bd create).
if err := createIssueWithDeps(ctx, store, issue, actor, createDepEdges{parentID: parentID}); err != nil {
if err := createIssueWithDeps(ctx, store, issue, currentActor(), createDepEdges{parentID: parentID}); err != nil {
return HandleError("%v", err)
}

View file

@ -47,7 +47,7 @@ func runQuickProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
Labels: labels,
InheritLabelsFromParent: parentID != "",
}
result, err := uw.IssueUseCase().CreateIssue(ctx, params, actor)
result, err := uw.IssueUseCase().CreateIssue(ctx, params, currentActor())
if err != nil {
return nil, "", err
}

View file

@ -159,7 +159,7 @@ This is useful for agents executing molecules to see which steps can run next.`,
return nil
}
claimed := res.Claimed
if err := commitPendingIfEmbedded(ctx, activeStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, activeStore, currentActor(), doltAutoCommitParams{
Command: "ready",
IssueIDs: []string{claimed.ID},
}); err != nil {

View file

@ -260,7 +260,7 @@ func readyRoleRequest(in readyInput) issueops.ReadyRequest {
// 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: actor, Filter: readyRoleRequest(in)}
return issueops.ClaimNextRequest{Actor: currentActor(), Filter: readyRoleRequest(in)}
}
// briefModeConflict reports the usage error for a --brief combination that no

View file

@ -104,7 +104,7 @@ Examples:
}
ctx := rootCtx
reclaimed, err := store.ReclaimExpiredLeases(ctx, olderThan, filter, actor)
reclaimed, err := store.ReclaimExpiredLeases(ctx, olderThan, filter, currentActor())
if err != nil {
return HandleErrorRespectJSON("reclaim: %v", err)
}
@ -113,7 +113,7 @@ Examples:
for _, r := range reclaimed {
ids = append(ids, r.ID)
}
if err := commitPendingIfEmbedded(ctx, store, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, store, currentActor(), doltAutoCommitParams{
Command: "reclaim",
IssueIDs: ids,
}); err != nil {

View file

@ -111,7 +111,7 @@ func runRelate(cmd *cobra.Command, args []string) error {
}
// bd relate is an explicit dependency verb, so it records history like
// bd link / bd dep add (EmitEvent); only structural edge wiring stays silent.
if err := store.AddDependencyWithOptions(ctx, dep1, actor, storage.DependencyAddOptions{EmitEvent: true}); err != nil {
if err := store.AddDependencyWithOptions(ctx, dep1, currentActor(), storage.DependencyAddOptions{EmitEvent: true}); err != nil {
return fmt.Errorf("failed to add relates-to %s -> %s: %w", id1, id2, err)
}
// Add id2 -> id1 (bidirectional)
@ -120,7 +120,7 @@ func runRelate(cmd *cobra.Command, args []string) error {
DependsOnID: id1,
Type: types.DepRelatesTo,
}
if err := store.AddDependencyWithOptions(ctx, dep2, actor, storage.DependencyAddOptions{EmitEvent: true}); err != nil {
if err := store.AddDependencyWithOptions(ctx, dep2, currentActor(), storage.DependencyAddOptions{EmitEvent: true}); err != nil {
return fmt.Errorf("failed to add relates-to %s -> %s: %w", id2, id1, err)
}
@ -190,11 +190,11 @@ func runUnrelate(cmd *cobra.Command, args []string) error {
// bd unrelate is an explicit dependency verb, so it records history
// (EmitEvent) like bd dep remove; only structural teardown stays silent.
// Remove id1 -> id2
if err := store.RemoveDependencyWithOptions(ctx, id1, id2, actor, storage.DependencyRemoveOptions{EmitEvent: true}); err != nil {
if err := store.RemoveDependencyWithOptions(ctx, id1, id2, currentActor(), storage.DependencyRemoveOptions{EmitEvent: true}); err != nil {
return fmt.Errorf("failed to remove relates-to %s -> %s: %w", id1, id2, err)
}
// Remove id2 -> id1 (bidirectional)
if err := store.RemoveDependencyWithOptions(ctx, id2, id1, actor, storage.DependencyRemoveOptions{EmitEvent: true}); err != nil {
if err := store.RemoveDependencyWithOptions(ctx, id2, id1, currentActor(), storage.DependencyRemoveOptions{EmitEvent: true}); err != nil {
return fmt.Errorf("failed to remove relates-to %s -> %s: %w", id2, id1, err)
}

View file

@ -66,7 +66,7 @@ func runRelateProxiedServer(ctx context.Context, args []string) error {
}
// bd relate is an explicit dependency verb, so the bulk path's
// EmitEvent trail matches the direct route's history behavior.
if _, err := uw.DependencyUseCase().AddDependencies(ctx, deps, actor, domain.BulkAddDepsOpts{}); err != nil {
if _, err := uw.DependencyUseCase().AddDependencies(ctx, deps, currentActor(), domain.BulkAddDepsOpts{}); err != nil {
return "", err
}
return fmt.Sprintf("bd: relate %s %s", id1, id2), nil
@ -111,11 +111,11 @@ func runUnrelateProxiedServer(ctx context.Context, args []string) error {
return "", fmt.Errorf("issue not found: %s", id)
}
}
removed1, err := uw.DependencyUseCase().RemoveDependencyBySource(ctx, id1, id2, actor)
removed1, err := uw.DependencyUseCase().RemoveDependencyBySource(ctx, id1, id2, currentActor())
if err != nil {
return "", fmt.Errorf("failed to remove relates-to %s -> %s: %w", id1, id2, err)
}
removed2, err := uw.DependencyUseCase().RemoveDependencyBySource(ctx, id2, id1, actor)
removed2, err := uw.DependencyUseCase().RemoveDependencyBySource(ctx, id2, id1, currentActor())
if err != nil {
return "", fmt.Errorf("failed to remove relates-to %s -> %s: %w", id2, id1, err)
}

View file

@ -112,7 +112,7 @@ NOTE: This is a rare operation. Most users never need this command.`,
)
}
if err := repairPrefixes(ctx, store, actor, newPrefix, issues, prefixes, dryRun); err != nil {
if err := repairPrefixes(ctx, store, currentActor(), newPrefix, issues, prefixes, dryRun); err != nil {
return HandleError("failed to repair prefixes: %v", err)
}
if !dryRun {
@ -456,7 +456,7 @@ func renamePrefixInDB(ctx context.Context, oldPrefix, newPrefix string, issues [
continue
}
if err := renameIssueKeepingBeadGates(ctx, store, issue, newID, gates[oldID], actor); err != nil {
if err := renameIssueKeepingBeadGates(ctx, store, issue, newID, gates[oldID], currentActor()); err != nil {
return fmt.Errorf("failed to update issue %s: %w", oldID, err)
}
}

View file

@ -96,7 +96,7 @@ another actor won the race, so retrying the same guard is pointless).`,
continue
}
reopened, err := ops.Reopen(opsCtx, issueops.ReopenRequest{
Actor: actor,
Actor: currentActor(),
IssueID: fullID,
Reason: reason,
ExpectedVersion: ifRevision,
@ -150,7 +150,7 @@ another actor won the race, so retrying the same guard is pointless).`,
}
for s, ids := range mutatedStores {
if err := commitPendingIfEmbedded(ctx, s, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, s, currentActor(), doltAutoCommitParams{
Command: "reopen",
IssueIDs: ids,
}); err != nil {

View file

@ -66,7 +66,7 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
reopenedIssues := []*types.Issue{}
for _, target := range targets {
result, err := lifecycle.Reopen(ctx, issueops.ReopenRequest{
Actor: actor,
Actor: currentActor(),
IssueID: target.id,
Reason: reason,
ExpectedVersion: ifRevision,
@ -94,7 +94,7 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
continue
}
audit.LogFieldChange(target.id, "status", string(target.status), string(types.StatusOpen), actor, reason)
audit.LogFieldChange(target.id, "status", string(target.status), string(types.StatusOpen), currentActor(), reason)
if jsonOut {
if issue := result.Issue; issue != nil {
// `bd reopen` has never printed dependency records, on either

View file

@ -127,7 +127,7 @@ func runShip(cmd *cobra.Command, args []string) error {
return nil
}
if err := store.AddLabel(ctx, issue.ID, providesLabel, actor); err != nil {
if err := store.AddLabel(ctx, issue.ID, providesLabel, currentActor()); err != nil {
return HandleErrorRespectJSON("adding label: %v", err)
}

View file

@ -0,0 +1,176 @@
//go:build cgo && linux
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// gitExecRecorder puts a `git` shim first on PATH that logs each invocation's
// arguments and then runs the real git, so a test can count the git processes
// a bd subprocess spawns.
type gitExecRecorder struct {
shimDir, log string
}
func newGitExecRecorder(t *testing.T) *gitExecRecorder {
t.Helper()
realGit, err := exec.LookPath("git")
if err != nil {
t.Skipf("git not found: %v", err)
}
r := &gitExecRecorder{shimDir: t.TempDir()}
r.log = filepath.Join(r.shimDir, "git-calls.log")
script := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> '" + r.log + "'\nexec '" + realGit + "' \"$@\"\n"
if err := os.WriteFile(filepath.Join(r.shimDir, "git"), []byte(script), 0o755); err != nil { // #nosec G306 -- test shim must be executable
t.Fatal(err)
}
return r
}
// run runs bd in dir with the shim on PATH and returns stdout plus the git
// invocations it made.
func (r *gitExecRecorder) run(t *testing.T, bd, dir string, args ...string) (string, []string) {
t.Helper()
if err := os.Remove(r.log); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
cmd := exec.Command(bd, args...)
cmd.Dir = dir
// Drop every GIT_* variable but the config-file selectors: any of
// internal/git's discovery overrides (GIT_DIR, GIT_WORK_TREE,
// GIT_COMMON_DIR, GIT_CEILING_DIRECTORIES, GIT_DISCOVERY_ACROSS_FILESYSTEM,
// GIT_OBJECT_DIRECTORY, GIT_CONFIG_PARAMETERS, GIT_CONFIG_COUNT with its
// GIT_CONFIG_KEY_n/VALUE_n, ...) exported by the runner — a `git -c`
// wrapper, a hook context — would rightly send bd back to git rev-parse.
var env []string
for _, kv := range envWithout(envWithout(bdEnv(dir), "BD_ACTOR"), "PATH") {
name, _, _ := strings.Cut(kv, "=")
if strings.HasPrefix(name, "GIT_") && name != "GIT_CONFIG_GLOBAL" &&
name != "GIT_CONFIG_SYSTEM" && name != "GIT_CONFIG_NOSYSTEM" {
continue
}
env = append(env, kv)
}
// backup.enabled stays at its default, so embedded auto-backup asks
// whether a git remote exists after every command (isBackupAutoEnabled).
// Global and system git config are pinned (empty, none) so the answer
// does not depend on the host's ~/.gitconfig — an include there would
// rightly send that probe to `git remote`.
env = envWithout(envWithout(env, "BD_BACKUP_ENABLED"), "BEADS_BACKUP_ENABLED")
for _, name := range []string{"GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_CONFIG_NOSYSTEM"} {
env = envWithout(env, name)
}
emptyGlobal := filepath.Join(r.shimDir, "empty.gitconfig")
if err := os.WriteFile(emptyGlobal, nil, 0o600); err != nil {
t.Fatal(err)
}
cmd.Env = append(env, "GIT_CONFIG_GLOBAL="+emptyGlobal, "GIT_CONFIG_NOSYSTEM=1",
"PATH="+r.shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
out, err := cmd.Output()
if err != nil {
var stderr string
if exit, ok := err.(*exec.ExitError); ok {
stderr = string(exit.Stderr)
}
t.Fatalf("bd %s: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, out, stderr)
}
data, err := os.ReadFile(r.log)
if err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
var calls []string
for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
if line != "" {
calls = append(calls, line)
}
}
return string(out), calls
}
// TestEmbeddedReadOnlyCommandsSpawnNoGit pins the per-call cost tools that
// call bd by the hundred depend on: a read-only command resolves the
// repository in-process, never needs the actor, and decides embedded
// auto-backup (default backup.enabled, with and without a git remote) without
// git, so it runs no git at all — from the main checkout and from a linked
// worktree sharing its database. A write still resolves the actor from git
// config user.name, lazily and to the same value.
func TestEmbeddedReadOnlyCommandsSpawnNoGit(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "gx")
issue := bdCreate(t, bd, dir, "startup git probe")
worktree := filepath.Join(filepath.Dir(dir), filepath.Base(dir)+"-wt")
t.Cleanup(func() { _ = os.RemoveAll(worktree) })
noHooks := "core.hooksPath=" + t.TempDir() // keep bd's installed hooks out of fixture setup
for _, args := range [][]string{
{"-c", noHooks, "commit", "--allow-empty", "--no-verify", "-m", "base"},
{"-c", noHooks, "worktree", "add", "-q", worktree},
} {
cmd := gitCommand(args...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
}
}
rec := newGitExecRecorder(t)
reads := func(phase string) {
t.Helper()
for _, location := range []struct{ name, dir string }{
{"main checkout", dir},
{"linked worktree", worktree},
} {
for _, args := range [][]string{
{"list", "--json"},
{"show", issue.ID, "--json"},
} {
out, calls := rec.run(t, bd, location.dir, args...)
if !strings.Contains(out, issue.ID) {
t.Fatalf("%s, %s: bd %s did not find %s:\n%s", phase, location.name, args[0], issue.ID, out)
}
if len(calls) != 0 {
t.Errorf("%s, %s: bd %s spawned %d git process(es), want 0:\n%s",
phase, location.name, args[0], len(calls), strings.Join(calls, "\n"))
}
}
}
}
// No git remote: auto-backup stays off, decided without running git.
reads("no git remote")
// With a remote, auto-backup turns on (still decided in-process); the
// first read may run the backup itself, which needs no git either.
addRemote := gitCommand("remote", "add", "origin", "https://example.invalid/gitcalls.git")
addRemote.Dir, addRemote.Env = dir, bdEnv(dir)
if out, err := addRemote.CombinedOutput(); err != nil {
t.Fatalf("git remote add: %v\n%s", err, out)
}
reads("git remote configured")
// Positive control for the shim, and the deferred actor's value: a write
// asks git for user.name exactly once and records it as before.
out, calls := rec.run(t, bd, dir, "create", "--json", "lazy actor")
created := parseIssueJSON(t, []byte(out))
if created.CreatedBy != "Test" {
t.Errorf("created_by = %q, want git user.name %q", created.CreatedBy, "Test")
}
nameLookups := 0
for _, call := range calls {
if call == "config user.name" {
nameLookups++
}
}
if nameLookups != 1 {
t.Errorf("bd create ran `git config user.name` %d times, want 1; calls:\n%s", nameLookups, strings.Join(calls, "\n"))
}
}

View file

@ -226,7 +226,7 @@ func runSetState(ctx context.Context, issueID, dimension, newValue, reason strin
// could not write, so an event that disagreed with its subject's plane
// fails the command instead of silently landing in the wrong table.
created, err := lifecycle.Create(ctx, issueops.CreateRequest{
Actor: actor,
Actor: currentActor(),
Issue: &types.Issue{
Title: eventTitle,
Description: eventDesc,
@ -254,7 +254,7 @@ func runSetState(ctx context.Context, issueID, dimension, newValue, reason strin
// failed. The plane needs no branch: IssuePlaneOnly stays false and the
// role resolves it inside its own transaction.
if _, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: actor,
Actor: currentActor(),
IssueID: fullID,
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{
Add: []string{newLabel},

View file

@ -88,7 +88,7 @@ Examples:
// --no-blocked is not consulted here, and never was: an
// assignee-scoped summary computes both numbers by a route that has
// no fast path (issueops.StatsReporter.AssigneeStats).
result, err = reporter.AssigneeStats(rootCtx, issueops.AssigneeStatsRequest{Assignee: actor})
result, err = reporter.AssigneeStats(rootCtx, issueops.AssigneeStatsRequest{Assignee: currentActor()})
} else {
result, err = reporter.Stats(rootCtx, issueops.StatsRequest{SkipBlocked: noBlocked})
if err == nil && noBlocked && result.Summary.BlockedIssues != nil {

View file

@ -1001,10 +1001,10 @@ Examples:
Status: types.StatusOpen,
Priority: issue.Priority,
IssueType: types.TypeEpic,
CreatedBy: actor,
CreatedBy: currentActor(),
}
if err := store.CreateIssue(ctx, wrapperEpic, actor); err != nil {
if err := store.CreateIssue(ctx, wrapperEpic, currentActor()); err != nil {
return HandleErrorRespectJSON("failed to create wrapper epic: %v", err)
}
@ -1012,9 +1012,9 @@ Examples:
IssueID: issue.ID,
DependsOnID: wrapperEpic.ID,
Type: types.DepParentChild,
CreatedBy: actor,
CreatedBy: currentActor(),
}
if err := store.AddDependency(ctx, dep, actor); err != nil {
if err := store.AddDependency(ctx, dep, currentActor()); err != nil {
return HandleErrorRespectJSON("failed to link issue to epic: %v", err)
}
@ -1081,10 +1081,10 @@ Examples:
IssueType: "molecule",
MolType: types.MolTypeSwarm,
Assignee: coordinator,
CreatedBy: actor,
CreatedBy: currentActor(),
}
if err := store.CreateIssue(ctx, swarmMol, actor); err != nil {
if err := store.CreateIssue(ctx, swarmMol, currentActor()); err != nil {
return HandleErrorRespectJSON("failed to create swarm molecule: %v", err)
}
@ -1092,9 +1092,9 @@ Examples:
IssueID: swarmMol.ID,
DependsOnID: epicID,
Type: types.DepRelatesTo,
CreatedBy: actor,
CreatedBy: currentActor(),
}
if err := store.AddDependency(ctx, dep, actor); err != nil {
if err := store.AddDependency(ctx, dep, currentActor()); err != nil {
return HandleErrorRespectJSON("failed to link swarm to epic: %v", err)
}

View file

@ -272,7 +272,7 @@ func runADOPush(cmd *cobra.Command, args []string) error {
return fmt.Errorf("initializing Azure DevOps tracker: %w", err)
}
engine := tracker.NewEngine(at, store, actor)
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) }
@ -319,7 +319,7 @@ func runADOPull(cmd *cobra.Command, args []string) error {
return fmt.Errorf("initializing Azure DevOps tracker: %w", err)
}
engine := tracker.NewEngine(at, store, actor)
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) }
@ -369,7 +369,7 @@ func runJiraPush(cmd *cobra.Command, args []string) error {
return HandleError("initializing Jira tracker: %v", err)
}
engine := tracker.NewEngine(jt, trackerStore, actor)
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)
@ -417,7 +417,7 @@ func runJiraPull(cmd *cobra.Command, args []string) error {
return HandleError("initializing Jira tracker: %v", err)
}
engine := tracker.NewEngine(jt, trackerStore, actor)
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) }
@ -487,7 +487,7 @@ func runLinearPush(cmd *cobra.Command, args []string) error {
return HandleError("%v", err)
}
engine := tracker.NewEngine(lt, trackerStore, actor)
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)
@ -552,12 +552,12 @@ func runLinearPull(cmd *cobra.Command, args []string) error {
return HandleError("initializing Linear tracker: %v", err)
}
engine := tracker.NewEngine(lt, trackerStore, actor)
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: actor,
Actor: currentActor(),
})
result, err := engine.Sync(ctx, tracker.SyncOptions{
@ -606,7 +606,7 @@ func runGitHubPush(cmd *cobra.Command, args []string) error {
return fmt.Errorf("initializing GitHub tracker: %w", err)
}
engine := tracker.NewEngine(gt, store, actor)
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)
@ -668,7 +668,7 @@ func runGitHubPull(cmd *cobra.Command, args []string) error {
return fmt.Errorf("initializing GitHub tracker: %w", err)
}
engine := tracker.NewEngine(gt, store, actor)
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) }
@ -719,7 +719,7 @@ func runGitLabPush(cmd *cobra.Command, args []string) error {
}
out := cmd.OutOrStdout()
engine := tracker.NewEngine(gt, store, actor)
engine := tracker.NewEngine(gt, store, currentActor())
engine.OnMessage = func(msg string) {
if !jsonOutput {
fmt.Fprintln(out, " "+msg)
@ -821,7 +821,7 @@ func runGitLabPull(cmd *cobra.Command, args []string) error {
return fmt.Errorf("initializing GitLab tracker: %w", err)
}
engine := tracker.NewEngine(gt, store, actor)
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) }
@ -875,7 +875,7 @@ func runNotionPush(cmd *cobra.Command, args []string) error {
return fmt.Errorf("initializing Notion tracker: %w", err)
}
engine := tracker.NewEngine(nt, store, actor)
engine := tracker.NewEngine(nt, store, currentActor())
unsupportedStats := newNotionUnsupportedPushStats()
engine.PushHooks = buildNotionPushHooks(ctx, nt, unsupportedStats)
engine.OnMessage = func(msg string) { fmt.Println(" " + msg) }
@ -929,7 +929,7 @@ func runNotionPull(cmd *cobra.Command, args []string) error {
return fmt.Errorf("initializing Notion tracker: %w", err)
}
engine := tracker.NewEngine(nt, store, actor)
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) }

View file

@ -67,10 +67,10 @@ Examples:
return HandleErrorRespectJSON("%s", err)
}
if err := issueStore.AddLabel(ctx, result.ResolvedID, label, actor); err != nil {
if err := issueStore.AddLabel(ctx, result.ResolvedID, label, currentActor()); err != nil {
return HandleErrorRespectJSON("adding label to %s: %v", id, err)
}
if err := commitPendingIfEmbedded(ctx, issueStore, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
Command: "tag",
IssueIDs: []string{result.ResolvedID},
}); err != nil {

View file

@ -90,9 +90,9 @@ Examples:
var unclaimErr error
if conditional {
unclaimErr = issueStore.UnclaimIssueIfAssignee(ctx, fullID, actor, ifAssignee)
unclaimErr = issueStore.UnclaimIssueIfAssignee(ctx, fullID, currentActor(), ifAssignee)
} else {
unclaimErr = issueStore.UnclaimIssue(ctx, fullID, actor, force)
unclaimErr = issueStore.UnclaimIssue(ctx, fullID, currentActor(), force)
}
if unclaimErr != nil {
fmt.Fprintf(os.Stderr, "Error unclaiming %s: %v\n", fullID, unclaimErr)
@ -102,7 +102,7 @@ Examples:
}
if reason != "" {
if _, err := issueStore.AddIssueComment(ctx, fullID, actor, reason); err != nil {
if _, err := issueStore.AddIssueComment(ctx, fullID, currentActor(), reason); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to add reason comment: %v\n", err)
}
}

View file

@ -62,9 +62,9 @@ func runUnclaimProxiedServer(ctx context.Context, args []string, reason string,
var uerr error
if expectedAssignee != "" {
uerr = uw.IssueUseCase().UnclaimIfAssignee(ctx, fullID, actor, expectedAssignee)
uerr = uw.IssueUseCase().UnclaimIfAssignee(ctx, fullID, currentActor(), expectedAssignee)
} else {
uerr = uw.IssueUseCase().Unclaim(ctx, fullID, actor, force)
uerr = uw.IssueUseCase().Unclaim(ctx, fullID, currentActor(), force)
}
if uerr != nil {
r.errs = append(r.errs, fmt.Sprintf("Error unclaiming %s: %v", fullID, uerr))
@ -72,7 +72,7 @@ func runUnclaimProxiedServer(ctx context.Context, args []string, reason string,
}
if reason != "" {
if _, cerr := uw.CommentUseCase().AddCommentToIssue(ctx, fullID, actor, reason); cerr != nil {
if _, cerr := uw.CommentUseCase().AddCommentToIssue(ctx, fullID, currentActor(), reason); cerr != nil {
r.errs = append(r.errs, fmt.Sprintf("Warning: failed to add reason comment on %s: %v", fullID, cerr))
}
}
@ -129,7 +129,7 @@ func runReclaimProxiedServer(ctx context.Context, olderThan time.Duration, filte
}
reclaimed, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) ([]types.ReclaimedLease, string, error) {
out, rerr := uw.IssueUseCase().ReclaimExpiredLeases(ctx, olderThan, filter, actor)
out, rerr := uw.IssueUseCase().ReclaimExpiredLeases(ctx, olderThan, filter, currentActor())
if rerr != nil {
return nil, "", rerr
}

View file

@ -89,7 +89,7 @@ Examples:
updates["status"] = string(types.StatusOpen)
}
if err := store.UpdateIssue(ctx, fullID, updates, actor); err != nil {
if err := store.UpdateIssue(ctx, fullID, updates, currentActor()); err != nil {
fmt.Fprintf(os.Stderr, "Error undeferring %s: %v\n", fullID, err)
continue
}

View file

@ -511,7 +511,7 @@ pointless).`,
// the actor's own fresh claim. A policy refusal, so it exits 1,
// not 13.
if newAssignee, ok := updates["assignee"].(string); ok && ifAssignee == nil && !claimFlag && !ifRevisionAlreadyStale(issue, ifRevision) {
if err := validateIssueReassignable(id, issue, actor, newAssignee,
if err := validateIssueReassignable(id, issue, currentActor(), newAssignee,
storeClaimPoolAliases(ctx, issueStore), forceFlag); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
recordFailure(id, err.Error())
@ -552,7 +552,7 @@ pointless).`,
// through: `--force -s closed` is now a legitimate way to ask for
// the close-policy half alone.
updateResult, updateErr := runCommandUpdateMutation(opsCtx, ops, commandUpdateMutation{
actor: actor,
actor: currentActor(),
issueID: result.ResolvedID,
patch: patch,
claim: claimFlag,
@ -602,13 +602,13 @@ pointless).`,
}
// Audit log key field changes (survives Dolt GC flatten)
if patch.Status.Set {
audit.LogFieldChange(result.ResolvedID, "status", string(issue.Status), string(patch.Status.Value), actor, "")
audit.LogFieldChange(result.ResolvedID, "status", string(issue.Status), string(patch.Status.Value), currentActor(), "")
}
if patch.Assignee.Set {
audit.LogFieldChange(result.ResolvedID, "assignee", issue.Assignee, patch.Assignee.Value, actor, "")
audit.LogFieldChange(result.ResolvedID, "assignee", issue.Assignee, patch.Assignee.Value, currentActor(), "")
}
if patch.Priority.Set {
audit.LogFieldChange(result.ResolvedID, "priority", fmt.Sprintf("%d", issue.Priority), fmt.Sprintf("%d", patch.Priority.Value), actor, "")
audit.LogFieldChange(result.ResolvedID, "priority", fmt.Sprintf("%d", issue.Priority), fmt.Sprintf("%d", patch.Priority.Value), currentActor(), "")
}
// The operation's own post-state snapshot replaces the re-read.
@ -642,7 +642,7 @@ pointless).`,
if s == nil {
continue
}
if err := commitPendingIfEmbedded(ctx, s, actor, doltAutoCommitParams{
if err := commitPendingIfEmbedded(ctx, s, currentActor(), doltAutoCommitParams{
Command: "update",
IssueIDs: ids,
}); err != nil {

View file

@ -127,7 +127,7 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
expectedStatus = &expected
}
result, err := runCommandUpdateMutation(ctx, ops, commandUpdateMutation{
actor: actor,
actor: currentActor(),
issueID: id,
patch: patch,
claim: in.claim,
@ -226,7 +226,7 @@ func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*type
// mc-zndi7.74: also skipped when this pre-read is already stale against an
// active --if-revision guard — see ifRevisionAlreadyStale's doc.
if newAssignee, ok := in.fields["assignee"].(string); ok && in.ifAssignee == nil && !in.claim && !ifRevisionAlreadyStale(current, in.ifRevision) {
if err := validateIssueReassignable(id, current, actor, newAssignee,
if err := validateIssueReassignable(id, current, currentActor(), newAssignee,
proxiedClaimPoolAliases(ctx), in.force); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
return nil, &updateIDFailure{ID: id, Error: err.Error()}

View file

@ -280,7 +280,7 @@ func runWispCreateCore(cmd *cobra.Command, args []string) error {
result, err := spawnMoleculeWithOptions(ctx, store, subgraph, CloneOptions{
Vars: vars,
Actor: actor,
Actor: currentActor(),
Ephemeral: true,
Prefix: types.IDPrefixWisp,
RootOnly: rootOnly,

View file

@ -92,7 +92,7 @@ func runWispCreateProxiedServer(ctx context.Context, in wispCreateInput) error {
w := newUOWMolWriter(uw)
spawnResult, err := cloneSubgraphInto(ctx, w, subgraph, CloneOptions{
Vars: vars,
Actor: actor,
Actor: currentActor(),
Ephemeral: true,
Prefix: types.IDPrefixWisp,
RootOnly: in.rootOnly,
@ -189,7 +189,7 @@ func runWispGCProxiedServer(ctx context.Context, dryRun bool, ageThreshold time.
IDs: ids,
Cascade: false,
UpdateTextReferences: true,
}, actor)
}, currentActor())
if err != nil {
return domain.DeleteIssuesResult{}, "", err
}
@ -320,7 +320,7 @@ func runWispPurgeClosedProxiedServer(ctx context.Context, dryRun, force bool, ex
IDs: ids,
Cascade: false,
UpdateTextReferences: true,
}, actor)
}, currentActor())
if err != nil {
return domain.DeleteIssuesResult{}, "", err
}

View file

@ -314,13 +314,23 @@ func isExternalBeadsDir(beadsDir string) (bool, error) {
// getGitCommonDirForPath returns the shared git directory for a path.
// For worktrees, this returns the shared git directory (common to all worktrees).
//
// Every startup that builds a RepoContext asks this about the beads
// directory, so the answer comes from git.CommonDirInProcess when it can,
// with `git -C path rev-parse --git-common-dir` as the fallback.
func getGitCommonDirForPath(path string) (string, error) {
cmd := exec.Command("git", "-C", path, "rev-parse", "--git-common-dir")
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to get git common dir for %s: %w", path, err)
result, isRepo, ok := git.CommonDirInProcess(path)
switch {
case ok && !isRepo:
return "", fmt.Errorf("failed to get git common dir for %s: not a git repository", path)
case !ok:
cmd := exec.Command("git", "-C", path, "rev-parse", "--git-common-dir")
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to get git common dir for %s: %w", path, err)
}
result = strings.TrimSpace(string(output))
}
result := strings.TrimSpace(string(output))
if !filepath.IsAbs(result) {
absPath, err := filepath.Abs(path)

View file

@ -2,7 +2,12 @@ load("@rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "git",
srcs = ["gitdir.go"],
srcs = [
"discover_linux.go",
"discover_other.go",
"gitconfig_linux.go",
"gitdir.go",
],
importpath = "github.com/steveyegge/beads/internal/git",
visibility = ["//:__subpackages__"],
)
@ -10,6 +15,7 @@ go_library(
go_test(
name = "git_test",
srcs = [
"discover_linux_test.go",
"gitdir_test.go",
"jujutsu_test.go",
],

View file

@ -0,0 +1,559 @@
//go:build linux
package git
import (
"bytes"
"errors"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
)
// discoveryEnvOverrides are the environment variables that change how Git
// finds or validates a repository. When any is present, discovery is left to
// git itself. The list is deliberately broader than strictly necessary: a
// fallback costs one subprocess, a wrong answer costs a wrong workspace.
var discoveryEnvOverrides = []string{
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_COMMON_DIR",
"GIT_CEILING_DIRECTORIES",
"GIT_DISCOVERY_ACROSS_FILESYSTEM",
"GIT_OBJECT_DIRECTORY",
"GIT_CONFIG_PARAMETERS",
"GIT_CONFIG_COUNT",
"GIT_TEST_ASSUME_DIFFERENT_OWNER",
}
// discoverGitInProcess answers `git rev-parse --git-dir --git-common-dir
// --show-toplevel` for the process working directory without running git. ok
// is false whenever the layout is outside what it reproduces exactly; the
// caller then runs git.
func discoverGitInProcess() (revParseResult, bool) {
if discoveryEnvOverridden() {
return revParseResult{}, false
}
wd, err := processCwd()
if err != nil {
return revParseResult{}, false
}
return discoverGitFrom(wd)
}
// processCwd is getcwd(2), as Git uses. os.Getwd prefers $PWD whenever it
// names the same inode as ".", which under bind-mount aliases (same device
// and inode, different ancestors) would walk a different path than git.
func processCwd() (string, error) {
return syscall.Getwd()
}
// errNotGitRepositoryMountBoundary is the in-process counterpart of Git's
// "not a git repository (or any parent up to mount point ...)".
var errNotGitRepositoryMountBoundary = errors.New("no .git found in the working directory or any parent up to the filesystem boundary")
// discoverGitFrom mirrors setup_git_directory_gently's discovery walk (Git
// 2.x) from cwd. Git walks the physical directory (getcwd), checks each
// directory's .git as a gitfile or a git directory, then the directory itself
// as a bare repository, and stops at the first filesystem boundary.
func discoverGitFrom(cwd string) (revParseResult, bool) {
cwd, err := filepath.EvalSymlinks(cwd)
if err != nil || !filepath.IsAbs(cwd) {
return revParseResult{}, false
}
cwd = filepath.Clean(cwd)
cwdStat := statOf(cwd)
if cwdStat == nil {
return revParseResult{}, false
}
for dir := cwd; ; {
dotGit := filepath.Join(dir, ".git")
info, err := os.Lstat(dotGit)
switch {
case err == nil && info.Mode().IsDir():
return discoveredGitDir(cwd, dir, dotGit)
case err == nil && info.Mode().IsRegular():
return discoveredGitFile(dir, dotGit)
case err == nil:
// Symlinked .git, sockets, ...: let git decide.
return revParseResult{}, false
case !os.IsNotExist(err):
return revParseResult{}, false
}
// The directory itself may be a git directory (a bare repository, or
// somewhere inside a .git directory); git answers those differently.
if looksLikeGitDir(dir) {
return revParseResult{}, false
}
parent := filepath.Dir(dir)
if parent == dir {
return revParseResult{notRepo: true}, true
}
parentStat := statOf(parent)
if parentStat == nil {
return revParseResult{}, false
}
if parentStat.Dev != cwdStat.Dev {
// Git stops at a mount point unless
// GIT_DISCOVERY_ACROSS_FILESYSTEM is set (handled by the caller).
return revParseResult{notRepo: true, notRepoErr: errNotGitRepositoryMountBoundary}, true
}
dir = parent
}
}
// discoveredGitDir handles <top>/.git being a directory.
func discoveredGitDir(cwd, top, gitDir string) (revParseResult, bool) {
// A .git directory carrying a commondir file is unusual; leave it to git.
if exists(filepath.Join(gitDir, "commondir")) {
return revParseResult{}, false
}
if !isGitDirectory(gitDir, gitDir) {
// Git would keep walking upward past an invalid .git directory.
return revParseResult{}, false
}
if !ownedByCurrentUser(top) || !ownedByCurrentUser(gitDir) {
return revParseResult{}, false
}
if worktree, ok := repoConfigAllowsDiscovery(gitDir); !ok || worktree != "" {
return revParseResult{}, false
}
if cwd == top {
return revParseResult{gitDir: ".git", commonDir: ".git", topLevel: top}, true
}
// From a subdirectory Git prints the git directory absolute and the common
// directory relative to the working directory.
rel, err := filepath.Rel(top, cwd)
if err != nil || rel == "." || strings.HasPrefix(rel, "..") {
return revParseResult{}, false
}
depth := len(strings.Split(rel, string(filepath.Separator)))
return revParseResult{
gitDir: gitDir,
commonDir: strings.Repeat("../", depth) + ".git",
topLevel: top,
}, true
}
// discoveredGitFile handles <top>/.git being a gitfile ("gitdir: <path>"), as
// in linked worktrees and submodules.
func discoveredGitFile(top, gitFile string) (revParseResult, bool) {
data, err := os.ReadFile(gitFile) // #nosec G304 -- the .git file Git itself would read during discovery
if err != nil {
return revParseResult{}, false
}
content := strings.TrimRight(string(data), "\r\n")
target, found := strings.CutPrefix(content, "gitdir: ")
if !found || target == "" || strings.ContainsAny(target, "\n\r\x00") {
return revParseResult{}, false
}
if !filepath.IsAbs(target) {
// Not filepath.Join: its lexical Clean would fold "link/.." before
// symlinks resolve, where Git's realpath resolves them physically
// (as EvalSymlinks does for ".." after a resolved component).
target = top + string(filepath.Separator) + target
}
gitDir, err := filepath.EvalSymlinks(target)
if err != nil {
return revParseResult{}, false
}
commonDir := gitDir
if raw, err := os.ReadFile(filepath.Join(gitDir, "commondir")); err == nil {
common := strings.TrimRight(string(raw), "\r\n")
if common == "" || strings.ContainsAny(common, "\n\r\x00") {
return revParseResult{}, false
}
if !filepath.IsAbs(common) {
common = gitDir + string(filepath.Separator) + common // physical "..", as above
}
if commonDir, err = filepath.EvalSymlinks(common); err != nil {
return revParseResult{}, false
}
} else if !os.IsNotExist(err) {
return revParseResult{}, false
}
if !isGitDirectory(gitDir, commonDir) {
return revParseResult{}, false
}
if !ownedByCurrentUser(gitFile) || !ownedByCurrentUser(top) || !ownedByCurrentUser(gitDir) {
return revParseResult{}, false
}
worktree, ok := repoConfigAllowsDiscovery(commonDir)
if !ok {
return revParseResult{}, false
}
if worktree != "" && !submoduleWorktreeIs(gitDir, commonDir, worktree, top) {
return revParseResult{}, false
}
// Git prints both absolute from anywhere in the work tree.
return revParseResult{gitDir: gitDir, commonDir: commonDir, topLevel: top}, true
}
// isGitDirectory mirrors Git's is_git_directory: a valid HEAD in the git
// directory, objects/ and refs/ in the common directory.
func isGitDirectory(gitDir, commonDir string) bool {
if !validHeadRef(filepath.Join(gitDir, "HEAD")) {
return false
}
return isDir(filepath.Join(commonDir, "objects")) && isDir(filepath.Join(commonDir, "refs"))
}
// looksLikeGitDir is a cheap superset test for "git might treat dir as a git
// directory"; a hit only means discovery is handed to git.
func looksLikeGitDir(dir string) bool {
return exists(filepath.Join(dir, "HEAD")) &&
(exists(filepath.Join(dir, "objects")) || exists(filepath.Join(dir, "commondir")))
}
// validHeadRef accepts the HEAD forms Git's validate_headref does for the
// files it writes itself: "ref: refs/..." or a full object id. Symlinked HEAD
// (an ancient layout) is left to git.
func validHeadRef(path string) bool {
info, err := os.Lstat(path)
if err != nil || !info.Mode().IsRegular() {
return false
}
data, err := os.ReadFile(path) // #nosec G304 -- HEAD of the discovered git directory
if err != nil {
return false
}
if ref, ok := bytes.CutPrefix(data, []byte("ref:")); ok {
return bytes.HasPrefix(bytes.TrimLeft(ref, " \t"), []byte("refs/"))
}
line := strings.TrimRight(string(data), "\r\n")
if len(line) != 40 && len(line) != 64 {
return false
}
for _, c := range line {
if !strings.ContainsRune("0123456789abcdef", c) {
return false
}
}
return true
}
// submoduleWorktreeIs reports whether a gitfile repository's core.worktree
// names exactly the directory holding the gitfile. Git writes that for every
// submodule (core.worktree = ../../../sub in .git/modules/sub/config), and Git
// then resolves the work tree by chdir(gitdir) + chdir(core.worktree), which
// lands on top again. Only that plain shape is accepted: a separate git
// directory (no shared common directory) and a value of leading "../"
// segments followed by plain names, which resolves lexically from the
// already-physical git directory exactly as the chdirs do.
func submoduleWorktreeIs(gitDir, commonDir, worktree, top string) bool {
if gitDir != commonDir || filepath.IsAbs(worktree) {
return false
}
rest := filepath.ToSlash(filepath.Clean(worktree))
if rest != worktree && rest+"/" != worktree {
return false
}
for strings.HasPrefix(rest, "../") {
rest = rest[len("../"):]
}
for _, part := range strings.Split(rest, "/") {
if part == "" || part == "." || part == ".." {
return false
}
}
resolved, err := filepath.EvalSymlinks(filepath.Join(gitDir, worktree))
return err == nil && resolved == top
}
// repoConfigAllowsDiscovery reports whether the repository config leaves
// Git's answer to the plain discovery result, and returns core.worktree when
// it is set (the caller decides whether it is the submodule shape). Git
// consults only the repository's own config file here
// (read_repository_format), so global and system config cannot move the work
// tree. Anything else that could — core.bare, extensions (worktreeConfig,
// unknown ones Git rejects), a format version Git refuses, include
// directives, a repeated core.worktree, or any line scanGitConfig does not
// fully understand (where Git might honor or reject it) — sends discovery to
// git.
func repoConfigAllowsDiscovery(commonDir string) (worktree string, ok bool) {
ok = scanGitConfig(filepath.Join(commonDir, "config"), func(e gitConfigEntry) bool {
if strings.HasPrefix(e.section, "include") || e.section == "extensions" {
return false
}
if e.section != "core" || e.subsection != nil {
return true
}
switch e.key {
case "worktree":
if worktree != "" || !e.hasValue || e.value == "" || strings.ContainsAny(e.rawValue, "\"#;") {
return false
}
worktree = e.value
case "bare":
if !e.hasValue {
return false // a bare "bare" key means true
}
switch strings.ToLower(e.value) {
case "false", "no", "off", "0":
default:
return false
}
case "repositoryformatversion":
if v, err := strconv.Atoi(e.value); err != nil || v < 0 || v > 1 {
return false
}
}
return true
})
if !ok {
return "", false
}
return worktree, true
}
// ownedByCurrentUser mirrors Git's is_path_owned_by_current_uid (lstat, owner
// equals the effective uid). Git's sudo allowance (root with SUDO_UID) is left
// to git. A path owned by someone else engages safe.directory, which only git
// evaluates.
func ownedByCurrentUser(path string) bool {
euid := os.Geteuid()
if euid == 0 {
if _, set := os.LookupEnv("SUDO_UID"); set {
return false
}
}
info, err := os.Lstat(path)
if err != nil {
return false
}
st, ok := info.Sys().(*syscall.Stat_t)
return ok && int(st.Uid) == euid
}
// statOf returns path's stat data (following symlinks, as Git's
// get_device_or_die does), or nil.
func statOf(path string) *syscall.Stat_t {
info, err := os.Stat(path)
if err != nil {
return nil
}
st, _ := info.Sys().(*syscall.Stat_t)
return st
}
func exists(path string) bool {
_, err := os.Lstat(path)
return err == nil
}
func isDir(path string) bool {
info, err := os.Stat(path)
return err == nil && info.IsDir()
}
// CommonDirInProcess answers `git -C dir rev-parse --git-common-dir` without
// running git, in git's own spelling (relative to dir's physical location
// when git prints it relative). isRepo is false where git would fail with
// "not a git repository". ok is false whenever discoverGitInProcess would
// decline; the caller then runs git.
func CommonDirInProcess(dir string) (commonDir string, isRepo, ok bool) {
if discoveryEnvOverridden() {
return "", false, false
}
abs, err := filepath.Abs(dir)
if err != nil {
return "", false, false
}
raw, ok := discoverGitFrom(abs)
if !ok {
return "", false, false
}
if raw.notRepo {
return "", false, true
}
return raw.commonDir, true, true
}
// HasRemoteInProcess answers "does `git remote` in dir print anything" (dir
// "" is the process working directory) without running git, or ok=false.
//
// `git remote` lists every remote that any config scope defines a
// remote.<name>.* key for, and fails outside a repository. The answer is
// given only when every file git would read — system, global (XDG and
// ~/.gitconfig, or GIT_CONFIG_GLOBAL), and the repository's own config — is
// absent or within scanGitConfig's grammar and free of include directives,
// the repository is one discoverGitFrom answers for, and no environment
// variable adds config or redirects discovery. The system file's location is
// compiled into git; the candidates are /etc/gitconfig and <prefix>/etc/gitconfig
// for the git found on PATH (as invoked and with symlinks resolved), and a
// remote seen only in a system candidate declines rather than guess which one
// git reads.
func HasRemoteInProcess(dir string) (has, ok bool) {
if discoveryEnvOverridden() {
return false, false
}
if _, set := os.LookupEnv("GIT_CONFIG"); set {
return false, false
}
if dir == "" {
wd, err := processCwd()
if err != nil {
return false, false
}
dir = wd
}
abs, err := filepath.Abs(dir)
if err != nil {
return false, false
}
physical, err := filepath.EvalSymlinks(abs)
if err != nil {
return false, false
}
raw, ok := discoverGitFrom(physical)
if !ok {
return false, false
}
if raw.notRepo {
return false, true // `git remote` exits 128 outside a repository
}
commonDir := raw.commonDir
if !filepath.IsAbs(commonDir) {
commonDir = filepath.Join(physical, commonDir)
}
// Legacy remote definitions (.git/remotes/*, .git/branches/*) are not
// listed by `git remote`, but are not modeled either: decline if present.
for _, legacy := range []string{"remotes", "branches"} {
if entries, err := os.ReadDir(filepath.Join(commonDir, legacy)); err == nil && len(entries) > 0 {
return false, false
} else if err != nil && !os.IsNotExist(err) {
return false, false
}
}
system, ok := systemConfigCandidates()
if !ok {
return false, false
}
global, ok := globalConfigFiles()
if !ok {
return false, false
}
inSystem, inOther := false, false
for _, scope := range []struct {
files []string
system bool
}{{system, true}, {global, false}, {[]string{filepath.Join(commonDir, "config")}, false}} {
for _, file := range scope.files {
found, ok := configDefinesRemote(file)
if !ok {
return false, false
}
if found && scope.system {
inSystem = true
} else if found {
inOther = true
}
}
}
switch {
case inOther:
return true, true
case inSystem:
return false, false
default:
return false, true
}
}
// remoteName is the remote-name shape answered in-process; git ignores names
// starting with "/" and accepts many others this does not model.
var remoteName = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
// configDefinesRemote reports whether file defines a remote.<name>.* key.
func configDefinesRemote(file string) (found, ok bool) {
ok = scanGitConfig(file, func(e gitConfigEntry) bool {
if strings.HasPrefix(e.section, "include") {
return false
}
if e.section != "remote" || e.subsection == nil {
return true // remote.pushDefault and friends define no remote
}
if !remoteName.MatchString(*e.subsection) {
return false
}
found = true
return true
})
return found, ok
}
// globalConfigFiles mirrors git_global_config.
func globalConfigFiles() ([]string, bool) {
if global, set := os.LookupEnv("GIT_CONFIG_GLOBAL"); set {
if global == "" || !filepath.IsAbs(global) {
return nil, false
}
return []string{global}, true
}
home := os.Getenv("HOME")
if home == "" || !filepath.IsAbs(home) {
return nil, false
}
xdg := filepath.Join(home, ".config", "git", "config")
if x := os.Getenv("XDG_CONFIG_HOME"); x != "" {
if !filepath.IsAbs(x) {
return nil, false
}
xdg = filepath.Join(x, "git", "config")
}
return []string{xdg, filepath.Join(home, ".gitconfig")}, true
}
// systemConfigCandidates mirrors git_system_config, with the compiled-in
// ETC_GITCONFIG approximated as described on HasRemoteInProcess.
func systemConfigCandidates() ([]string, bool) {
if v, set := os.LookupEnv("GIT_CONFIG_NOSYSTEM"); set {
switch strings.ToLower(v) {
case "1", "true", "yes", "on":
return nil, true
case "", "0", "false", "no", "off":
default:
return nil, false
}
}
if system, set := os.LookupEnv("GIT_CONFIG_SYSTEM"); set {
if system == "" || !filepath.IsAbs(system) {
return nil, false
}
return []string{system}, true
}
bin, err := exec.LookPath("git")
if err != nil || !filepath.IsAbs(bin) {
return nil, false
}
candidates := []string{"/etc/gitconfig"}
paths := []string{bin}
if resolved, err := filepath.EvalSymlinks(bin); err == nil {
paths = append(paths, resolved)
}
for _, p := range paths {
if filepath.Base(filepath.Dir(p)) != "bin" {
return nil, false
}
if prefix := filepath.Dir(filepath.Dir(p)); prefix != "/usr" {
candidates = append(candidates, filepath.Join(prefix, "etc", "gitconfig"))
}
}
return candidates, true
}
func discoveryEnvOverridden() bool {
for _, name := range discoveryEnvOverrides {
if _, set := os.LookupEnv(name); set {
return true
}
}
return false
}

View file

@ -0,0 +1,471 @@
//go:build linux
package git
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// discoveryFixtureEnv is the environment fixture git runs under: the process
// environment minus every discovery override, with no system or user config.
func discoveryFixtureEnv(t *testing.T) []string {
t.Helper()
var env []string
for _, kv := range os.Environ() {
name, _, _ := strings.Cut(kv, "=")
if strings.HasPrefix(name, "GIT_") || name == "HOME" {
continue
}
env = append(env, kv)
}
return append(env, "HOME="+t.TempDir(), "GIT_CONFIG_NOSYSTEM=1",
"GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com",
"GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com")
}
func runFixtureGit(t *testing.T, env []string, dir string, args ...string) string {
t.Helper()
cmd := gitCommand(args...)
cmd.Dir, cmd.Env = dir, env
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %s in %s: %v\n%s", strings.Join(args, " "), dir, err, out)
}
return string(out)
}
// gitRevParse is the reference answer discoverGitFrom must reproduce.
func gitRevParse(t *testing.T, env []string, dir string) revParseResult {
t.Helper()
cmd := exec.Command("git", "rev-parse", "--git-dir", "--git-common-dir", "--show-toplevel")
cmd.Dir, cmd.Env = dir, env
out, err := cmd.Output()
if err != nil {
return revParseResult{notRepo: true}
}
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
if len(lines) != 3 {
t.Fatalf("git rev-parse in %s: unexpected output %q", dir, out)
}
return revParseResult{gitDir: lines[0], commonDir: lines[1], topLevel: lines[2]}
}
type discoveryFixture struct {
root, main, worktree, relWorktree, symWorktree, submodule, nested string
env []string
}
func newDiscoveryFixture(t *testing.T) discoveryFixture {
t.Helper()
root, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
env := discoveryFixtureEnv(t)
f := discoveryFixture{
root: root,
main: filepath.Join(root, "main"),
worktree: filepath.Join(root, "wt"),
relWorktree: filepath.Join(root, "wt-rel"),
symWorktree: filepath.Join(root, "wt-sym"),
env: env,
}
f.submodule = filepath.Join(f.main, "sub")
f.nested = filepath.Join(f.main, "a", "inner")
subSrc := filepath.Join(root, "subsrc")
for _, dir := range []string{f.main, subSrc, filepath.Join(f.main, "a", "b"), f.nested, filepath.Join(root, "norepo", "x")} {
if err := os.MkdirAll(dir, 0o750); err != nil {
t.Fatal(err)
}
}
for _, dir := range []string{f.main, subSrc} {
runFixtureGit(t, env, dir, "init", "-q")
runFixtureGit(t, env, dir, "commit", "-q", "--allow-empty", "-m", "base")
}
runFixtureGit(t, env, f.main, "worktree", "add", "-q", f.worktree)
runFixtureGit(t, env, f.main, "worktree", "add", "-q", f.relWorktree)
// A relative gitfile, as `git worktree add --relative-paths` (or a moved
// checkout) writes it.
if err := os.WriteFile(filepath.Join(f.relWorktree, ".git"), []byte("gitdir: ../main/.git/worktrees/wt-rel\n"), 0o600); err != nil {
t.Fatal(err)
}
// A gitfile naming its git directory through a symlink: Git prints the
// resolved path.
runFixtureGit(t, env, f.main, "worktree", "add", "-q", f.symWorktree)
if err := os.Symlink(filepath.Join(f.main, ".git"), filepath.Join(root, "gitlink")); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(f.symWorktree, ".git"), []byte("gitdir: "+filepath.Join(root, "gitlink", "worktrees", "wt-sym")+"\n"), 0o600); err != nil {
t.Fatal(err)
}
runFixtureGit(t, env, f.main, "-c", "protocol.file.allow=always", "submodule", "add", "-q", subSrc, "sub")
runFixtureGit(t, env, f.nested, "init", "-q")
for _, dir := range []string{filepath.Join(f.worktree, "w"), filepath.Join(f.submodule, "s"), filepath.Join(f.nested, "deep")} {
if err := os.MkdirAll(dir, 0o750); err != nil {
t.Fatal(err)
}
}
if err := os.Symlink(f.main, filepath.Join(root, "link")); err != nil {
t.Fatal(err)
}
return f
}
// resolvedLikeStartup is what bd's startup derives for dir: the in-process
// answer when discovery gives one, else git's.
func resolvedLikeStartup(dir string, env []string) (gitContext, bool) {
if raw, ok := discoverGitFrom(dir); ok {
return gitContextFromRevParse(dir, raw), true
}
return loadGitContext(dir, env), false
}
// assertSameAsGit checks the startup-derived context for dir against the git
// subprocess's: same failure, or the same paths.
func assertSameAsGit(t *testing.T, env []string, dir string) {
t.Helper()
got, _ := resolvedLikeStartup(dir, env)
want := loadGitContext(dir, env)
if (got.err != nil) != (want.err != nil) {
t.Fatalf("in %s: startup err %v, git err %v", dir, got.err, want.err)
}
if got.gitDirRaw != want.gitDirRaw || got.commonDir != want.commonDir ||
got.repoRoot != want.repoRoot || got.isWorktree != want.isWorktree {
t.Fatalf("in %s: startup %+v, git %+v", dir, got, want)
}
}
// repoWithRawConfig makes a repository and replaces its config file.
func repoWithRawConfig(t *testing.T, env []string, config string) string {
t.Helper()
dir := filepath.Join(t.TempDir(), "r")
runFixtureGit(t, env, t.TempDir(), "init", "-q", dir)
if err := os.WriteFile(filepath.Join(dir, ".git", "config"), []byte(config), 0o600); err != nil {
t.Fatal(err)
}
return dir
}
const plainRepoConfig = "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n"
// TestDiscoverGitFromMatchesRevParse is the equivalence contract: wherever
// in-process discovery answers, its answer is byte-for-byte what `git
// rev-parse --git-dir --git-common-dir --show-toplevel` prints there.
func TestDiscoverGitFromMatchesRevParse(t *testing.T) {
f := newDiscoveryFixture(t)
for _, tc := range []struct{ name, dir string }{
{"repo top", f.main},
{"repo subdir", filepath.Join(f.main, "a", "b")},
{"repo first-level subdir", filepath.Join(f.main, "a")},
{"linked worktree top", f.worktree},
{"linked worktree subdir", filepath.Join(f.worktree, "w")},
{"linked worktree with relative gitfile", f.relWorktree},
{"linked worktree with gitfile through a symlink", f.symWorktree},
{"submodule top", f.submodule},
{"submodule subdir", filepath.Join(f.submodule, "s")},
{"nested repo top", f.nested},
{"nested repo subdir", filepath.Join(f.nested, "deep")},
{"symlinked path to repo top", filepath.Join(f.root, "link")},
{"symlinked path to repo subdir", filepath.Join(f.root, "link", "a", "b")},
// No ancestor of a fresh temp directory is a repository, so this is
// answered in-process (by the walk reaching / or a mount boundary).
{"no repository", filepath.Join(f.root, "norepo", "x")},
{"config with a UTF-8 BOM", repoWithRawConfig(t, f.env, "\xef\xbb\xbf"+plainRepoConfig)},
{"config with CRLF and comments", repoWithRawConfig(t, f.env,
"# leading comment\r\n[core] ; header comment\r\n\tbare = false # trailing\r\n[remote \"origin\"]\r\n\turl = \"/x y\"\r\n")},
} {
t.Run(tc.name, func(t *testing.T) {
got, ok := discoverGitFrom(tc.dir)
if !ok {
t.Fatalf("discoverGitFrom(%s) declined; want an in-process answer", tc.dir)
}
if want := gitRevParse(t, f.env, tc.dir); got != want {
t.Fatalf("discoverGitFrom(%s) = %+v, git rev-parse = %+v", tc.dir, got, want)
}
assertSameAsGit(t, f.env, tc.dir)
})
}
}
// TestDiscoverGitFromDeclinesUnmodeledLayouts covers the layouts in-process
// discovery must hand to git rather than guess, and checks that what startup
// then derives (from git) is git's answer.
func TestDiscoverGitFromDeclinesUnmodeledLayouts(t *testing.T) {
f := newDiscoveryFixture(t)
repoWithConfig := func(t *testing.T, args ...string) string {
t.Helper()
dir := filepath.Join(t.TempDir(), "r")
runFixtureGit(t, f.env, t.TempDir(), "init", "-q", dir)
runFixtureGit(t, f.env, dir, append([]string{"config"}, args...)...)
return dir
}
mkdir := func(t *testing.T, parts ...string) string {
t.Helper()
dir := filepath.Join(parts...)
if err := os.MkdirAll(dir, 0o750); err != nil {
t.Fatal(err)
}
return dir
}
invalidGitfile := mkdir(t, t.TempDir(), "badfile")
if err := os.WriteFile(filepath.Join(invalidGitfile, ".git"), []byte("not a gitfile\n"), 0o600); err != nil {
t.Fatal(err)
}
symlinkedDotGit := mkdir(t, t.TempDir(), "symlinked")
if err := os.Symlink(filepath.Join(f.main, ".git"), filepath.Join(symlinkedDotGit, ".git")); err != nil {
t.Fatal(err)
}
bare := filepath.Join(t.TempDir(), "bare.git")
runFixtureGit(t, f.env, t.TempDir(), "init", "-q", "--bare", bare)
bareSub := mkdir(t, bare, "sub") // below a bare repository: the walk meets HEAD+objects
commondirInDotGit := repoWithConfig(t, "core.filemode", "true")
if err := os.WriteFile(filepath.Join(commondirInDotGit, ".git", "commondir"), []byte(".\n"), 0o600); err != nil {
t.Fatal(err)
}
for _, tc := range []struct{ name, dir string }{
{"core.worktree", repoWithConfig(t, "core.worktree", t.TempDir())},
{"core.bare", repoWithConfig(t, "core.bare", "true")},
{"extensions.worktreeConfig", repoWithConfig(t, "extensions.worktreeConfig", "true")},
{"include directive", repoWithConfig(t, "include.path", "/dev/null")},
// Git skips a leading BOM and honors the section after it.
{"BOM then core.worktree", repoWithRawConfig(t, f.env, "\xef\xbb\xbf[core]\n\tworktree = "+t.TempDir()+"\n")},
{"header with inner spaces", repoWithRawConfig(t, f.env, "[ core ]\n\tbare = false\n")},
{"header with leading whitespace", repoWithRawConfig(t, f.env, " [core]\n\tbare = false\n")},
{"malformed key line", repoWithRawConfig(t, f.env, plainRepoConfig+"!!! = x\n")},
{"key before any section", repoWithRawConfig(t, f.env, "bare = false\n"+plainRepoConfig)},
{"key on the header line", repoWithRawConfig(t, f.env, "[core] bare = false\n")},
{"escaped value", repoWithRawConfig(t, f.env, plainRepoConfig+"[alias]\n\tx = \"a\\tb\"\n")},
{"unterminated quote", repoWithRawConfig(t, f.env, plainRepoConfig+"[alias]\n\tx = \"a\n")},
{"continuation line", repoWithRawConfig(t, f.env, plainRepoConfig+"[alias]\n\tx = a \\\n b\n")},
{"dotted section", repoWithRawConfig(t, f.env, "[core.x]\n\ty = 1\n"+plainRepoConfig)},
{"inside the git directory", filepath.Join(f.main, ".git", "refs")},
{"bare repository", bare},
{"below a bare repository", bareSub},
{"commondir inside .git", commondirInDotGit},
{"invalid gitfile", invalidGitfile},
{"symlinked .git", symlinkedDotGit},
} {
t.Run(tc.name, func(t *testing.T) {
if got, ok := discoverGitFrom(tc.dir); ok {
t.Fatalf("discoverGitFrom(%s) = %+v; want it to defer to git", tc.dir, got)
}
assertSameAsGit(t, f.env, tc.dir)
})
}
}
// TestDiscoverGitInProcessUsesPhysicalCwd: Git walks from getcwd(2); a $PWD
// naming the same directory through another path (a symlink here; a bind
// mount alias in containers) must not change the walk.
func TestDiscoverGitInProcessUsesPhysicalCwd(t *testing.T) {
f := newDiscoveryFixture(t)
physical := filepath.Join(f.main, "a", "b")
alias := filepath.Join(f.root, "link", "a", "b")
t.Chdir(physical)
t.Setenv("PWD", alias)
if wd, err := os.Getwd(); err != nil || wd != alias {
t.Fatalf("os.Getwd() = %q, %v; this test needs it to report the $PWD alias %q", wd, err, alias)
}
if wd, err := processCwd(); err != nil || wd != physical {
t.Fatalf("processCwd() = %q, %v; want getcwd's %q", wd, err, physical)
}
for _, k := range discoveryEnvOverrides {
if _, set := os.LookupEnv(k); set {
t.Setenv(k, "")
if err := os.Unsetenv(k); err != nil {
t.Fatal(err)
}
}
}
got, ok := discoverGitInProcess()
if !ok {
t.Fatal("discoverGitInProcess declined")
}
if want := gitRevParse(t, f.env, physical); got != want {
t.Fatalf("discoverGitInProcess() = %+v, git rev-parse = %+v", got, want)
}
}
// TestDiscoverGitInProcessDefersToGitEnvOverrides: GIT_DIR and friends
// redefine discovery, so their presence (even empty) sends it to git.
func TestDiscoverGitInProcessDefersToGitEnvOverrides(t *testing.T) {
f := newDiscoveryFixture(t)
t.Chdir(f.main)
for _, name := range discoveryEnvOverrides {
t.Run(name, func(t *testing.T) {
t.Setenv(name, "")
if got, ok := discoverGitInProcess(); ok {
t.Fatalf("with %s set, discoverGitInProcess() = %+v; want it to defer to git", name, got)
}
})
}
}
// TestGitContextInProcessMatchesGitSubprocess checks the cached context end
// to end: what bd's startup now derives without git equals what it derived
// from the git subprocess, for each discovery layout.
func TestGitContextInProcessMatchesGitSubprocess(t *testing.T) {
f := newDiscoveryFixture(t)
for _, k := range discoveryEnvOverrides {
if _, set := os.LookupEnv(k); set {
t.Setenv(k, "")
if err := os.Unsetenv(k); err != nil {
t.Fatal(err)
}
}
}
for _, dir := range []string{
f.main, filepath.Join(f.main, "a", "b"), f.worktree, filepath.Join(f.worktree, "w"),
f.submodule, filepath.Join(f.nested, "deep"),
} {
t.Run(strings.TrimPrefix(dir, f.root), func(t *testing.T) {
t.Chdir(dir)
raw, ok := discoverGitInProcess()
if !ok {
t.Fatalf("discoverGitInProcess declined in %s", dir)
}
got := gitContextFromRevParse("", raw)
want := loadGitContext("", f.env)
if got.err != nil || want.err != nil {
t.Fatalf("errors: in-process %v, git %v", got.err, want.err)
}
if got.gitDirRaw != want.gitDirRaw || got.commonDir != want.commonDir ||
got.repoRoot != want.repoRoot || got.isWorktree != want.isWorktree {
t.Fatalf("in-process %+v, git %+v", got, want)
}
})
}
}
// isolateGitConfigEnv points git and the in-process readers at the same,
// controlled config files: no system config, an empty global file.
func isolateGitConfigEnv(t *testing.T) (global string) {
t.Helper()
for _, kv := range os.Environ() {
name, _, _ := strings.Cut(kv, "=")
if strings.HasPrefix(name, "GIT_") {
t.Setenv(name, "")
if err := os.Unsetenv(name); err != nil {
t.Fatal(err)
}
}
}
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "xdg"))
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
global = filepath.Join(home, "global.gitconfig")
if err := os.WriteFile(global, nil, 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("GIT_CONFIG_GLOBAL", global)
return global
}
func gitRemoteListsAny(t *testing.T, dir string) bool {
t.Helper()
cmd := exec.Command("git", "remote")
cmd.Dir = dir
out, err := cmd.Output()
return err == nil && strings.TrimSpace(string(out)) != ""
}
// TestHasRemoteInProcessMatchesGitRemote: wherever HasRemoteInProcess
// answers, it is what `git remote` (the auto-backup probe) reports.
func TestHasRemoteInProcessMatchesGitRemote(t *testing.T) {
f := newDiscoveryFixture(t)
global := isolateGitConfigEnv(t)
withRemote := filepath.Join(t.TempDir(), "with-remote")
runFixtureGit(t, f.env, t.TempDir(), "init", "-q", withRemote)
runFixtureGit(t, f.env, withRemote, "remote", "add", "origin", "https://example.invalid/r.git")
pushDefaultOnly := filepath.Join(t.TempDir(), "push-default")
runFixtureGit(t, f.env, t.TempDir(), "init", "-q", pushDefaultOnly)
runFixtureGit(t, f.env, pushDefaultOnly, "config", "remote.pushDefault", "origin")
runFixtureGit(t, f.env, f.main, "remote", "add", "up", "https://example.invalid/m.git")
setGlobal := func(t *testing.T, content string) {
t.Helper()
if err := os.WriteFile(global, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.WriteFile(global, nil, 0o600) })
}
for _, tc := range []struct {
name, dir, global string
wantDecline bool
}{
{name: "no remote", dir: f.nested},
{name: "local remote", dir: withRemote},
{name: "remote.pushDefault only", dir: pushDefaultOnly},
{name: "linked worktree sees the common config", dir: filepath.Join(f.worktree, "w")},
{name: "submodule (origin in its own config)"},
{name: "no repository", dir: filepath.Join(f.root, "norepo", "x")},
{name: "remote in global config", dir: f.nested, global: "[remote \"g\"]\n\turl = /g\n"},
{name: "include in global config", dir: f.nested, global: "[include]\n\tpath = /dev/null\n", wantDecline: true},
{name: "malformed global config", dir: f.nested, global: "[ user ]\n", wantDecline: true},
} {
t.Run(tc.name, func(t *testing.T) {
dir := tc.dir
if dir == "" {
dir = f.submodule
}
if tc.global != "" {
setGlobal(t, tc.global)
}
has, ok := HasRemoteInProcess(dir)
if ok == tc.wantDecline {
t.Fatalf("HasRemoteInProcess(%s) ok=%v, want ok=%v", dir, ok, !tc.wantDecline)
}
if want := gitRemoteListsAny(t, dir); ok && has != want {
t.Fatalf("HasRemoteInProcess(%s) = %v, git remote lists any = %v", dir, has, want)
}
})
}
t.Run("GIT_CONFIG_PARAMETERS declines", func(t *testing.T) {
t.Setenv("GIT_CONFIG_PARAMETERS", "'remote.x.url'='/x'")
if _, ok := HasRemoteInProcess(f.nested); ok {
t.Fatal("HasRemoteInProcess answered despite command-line config")
}
})
t.Run("process cwd", func(t *testing.T) {
t.Chdir(withRemote)
if has, ok := HasRemoteInProcess(""); !ok || !has {
t.Fatalf("HasRemoteInProcess(\"\") = %v, %v; want true, true", has, ok)
}
})
}
// TestCommonDirInProcessMatchesGit: the auto-backup RepoContext asks
// `git -C <.beads> rev-parse --git-common-dir`; the in-process answer has
// git's spelling.
func TestCommonDirInProcessMatchesGit(t *testing.T) {
f := newDiscoveryFixture(t)
isolateGitConfigEnv(t)
beadsDir := filepath.Join(f.main, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
for _, dir := range []string{
f.main, beadsDir, filepath.Join(f.main, "a", "b"), f.worktree, f.submodule,
filepath.Join(f.root, "link", "a"), filepath.Join(f.root, "norepo", "x"),
} {
t.Run(strings.TrimPrefix(dir, f.root), func(t *testing.T) {
got, isRepo, ok := CommonDirInProcess(dir)
if !ok {
t.Fatalf("CommonDirInProcess(%s) declined", dir)
}
cmd := exec.Command("git", "-C", dir, "rev-parse", "--git-common-dir")
out, err := cmd.Output()
if (err == nil) != isRepo {
t.Fatalf("CommonDirInProcess(%s) isRepo=%v, git err=%v", dir, isRepo, err)
}
if want := strings.TrimSpace(string(out)); isRepo && got != want {
t.Fatalf("CommonDirInProcess(%s) = %q, git = %q", dir, got, want)
}
})
}
}

View file

@ -0,0 +1,20 @@
//go:build !linux
package git
// discoverGitInProcess is linux-only: elsewhere path case-folding (darwin,
// windows) and ownership semantics (windows) make an exact in-process answer
// harder to prove, so discovery always runs git.
func discoverGitInProcess() (revParseResult, bool) {
return revParseResult{}, false
}
// CommonDirInProcess is linux-only; see discoverGitInProcess.
func CommonDirInProcess(string) (commonDir string, isRepo, ok bool) {
return "", false, false
}
// HasRemoteInProcess is linux-only; see discoverGitInProcess.
func HasRemoteInProcess(string) (has, ok bool) {
return false, false
}

View file

@ -0,0 +1,109 @@
//go:build linux
package git
import (
"bytes"
"os"
"regexp"
"strings"
)
// gitConfigEntry is one key line of a git config file, as scanGitConfig
// understood it.
type gitConfigEntry struct {
section string // lower-cased section name
subsection *string // nil for [section]; case preserved
key string // lower-cased variable name
hasValue bool // false for a bare "key" line (boolean true)
rawValue string // value text after '=', as written, comment included
value string // rawValue without its comment, trimmed and unquoted
}
var (
gitConfigHeader = regexp.MustCompile(`^\[([A-Za-z0-9-]+)(?: "([^"\\]*)")?\][ \t]*(?:[#;].*)?$`)
gitConfigKeyLine = regexp.MustCompile(`^[ \t]*([A-Za-z][A-Za-z0-9-]*)[ \t]*(?:=(.*)|(?:[#;].*)?)$`)
gitConfigCommentLn = regexp.MustCompile(`^[ \t]*(?:[#;].*)?$`)
)
// scanGitConfig reads a git config file with a deliberately narrow grammar
// and calls visit for each key line; it returns false (the caller then asks
// git) when the file is unreadable, a visit returns false, or ANY line falls
// outside that grammar — Git might honor such a line differently or refuse
// the file. A missing file is an empty config, as for Git.
//
// Understood: a UTF-8 BOM at the start of the file (Git skips it), CRLF line
// endings, blank and comment lines, "[section]" and `[section "sub"]`
// headers at the start of a line (optionally followed by a comment), and
// "key", "key = value" lines inside a section. Values containing a backslash
// or an odd number of double quotes (escapes, continuations, unterminated
// strings) are not understood.
func scanGitConfig(path string, visit func(gitConfigEntry) bool) bool {
data, err := os.ReadFile(path) // #nosec G304 -- a git config file Git itself would read
if os.IsNotExist(err) {
return true
}
if err != nil || bytes.IndexByte(data, 0) >= 0 {
return false
}
text := strings.TrimPrefix(string(data), "\xef\xbb\xbf")
section, haveSection := "", false
var subsection *string
for _, line := range strings.Split(text, "\n") {
line = strings.TrimSuffix(line, "\r")
if strings.ContainsRune(line, '\r') {
return false
}
if gitConfigCommentLn.MatchString(line) {
continue
}
if m := gitConfigHeader.FindStringSubmatch(line); m != nil {
section, haveSection = strings.ToLower(m[1]), true
subsection = nil
if strings.Contains(line[:strings.IndexByte(line, ']')], `"`) {
sub := m[2]
subsection = &sub
}
continue
}
m := gitConfigKeyLine.FindStringSubmatchIndex(line)
if m == nil || !haveSection {
return false
}
e := gitConfigEntry{section: section, subsection: subsection, key: strings.ToLower(line[m[2]:m[3]])}
if m[4] >= 0 {
e.hasValue = true
e.rawValue = line[m[4]:m[5]]
value, ok := parseGitConfigValue(e.rawValue)
if !ok {
return false
}
e.value = value
}
if !visit(e) {
return false
}
}
return true
}
// parseGitConfigValue strips a trailing comment, surrounding whitespace and
// balanced double quotes from a value it fully understands.
func parseGitConfigValue(raw string) (string, bool) {
if strings.ContainsRune(raw, '\\') || strings.Count(raw, `"`)%2 != 0 {
return "", false
}
var b strings.Builder
inQuote := false
for _, c := range raw {
switch {
case c == '"':
inQuote = !inQuote
continue
case !inQuote && (c == '#' || c == ';'):
return strings.TrimSpace(b.String()), true
}
b.WriteRune(c)
}
return strings.TrimSpace(b.String()), true
}

View file

@ -88,10 +88,36 @@ func canonicalPinPath(p string) string {
// initGitContext populates the gitContext with a single git call.
// This is called once per process via sync.Once.
//
// The process-wide context is the one every bd invocation resolves at startup
// (beads directory discovery), so it first tries discoverGitInProcess, which
// answers the common layouts — an ordinary repository, a linked worktree, a
// submodule, no repository at all — from the filesystem with the exact output
// `git rev-parse --git-dir --git-common-dir --show-toplevel` would print, and
// declines (falling back to that subprocess) for anything it cannot prove
// equivalent: GIT_DIR-style overrides, repository config that moves the work
// tree, ownership that would engage safe.directory, and so on.
func initGitContext() {
if raw, ok := discoverGitInProcess(); ok {
gitCtx = gitContextFromRevParse("", raw)
return
}
gitCtx = loadGitContext("", nil)
}
// revParseResult is the answer to `git rev-parse --git-dir --git-common-dir
// --show-toplevel`, in Git's own spelling, or notRepo when Git would report
// that the directory is not inside a repository.
type revParseResult struct {
gitDir, commonDir, topLevel string
notRepo bool
notRepoErr error // why, when notRepo; nil means errNotGitRepository
}
// errNotGitRepository stands in for git's exit status when in-process
// discovery establishes that there is no repository to find.
var errNotGitRepository = errors.New("no .git found in the working directory or any parent")
func loadGitContext(workDir string, env []string) gitContext {
var ctx gitContext
// Get all three values with a single git call
@ -116,10 +142,29 @@ func loadGitContext(workDir string, env []string) gitContext {
ctx.err = fmt.Errorf("unexpected git rev-parse output: got %d lines, expected 3", len(lines))
return ctx
}
return gitContextFromRevParse(workDir, revParseResult{
gitDir: strings.TrimSpace(lines[0]),
commonDir: strings.TrimSpace(lines[1]),
topLevel: strings.TrimSpace(lines[2]),
})
}
ctx.gitDirRaw = strings.TrimSpace(lines[0])
commonDirRaw := strings.TrimSpace(lines[1])
repoRootRaw := strings.TrimSpace(lines[2])
// gitContextFromRevParse derives the cached context from rev-parse output,
// whichever of git or discoverGitInProcess produced it, so both paths share
// one normalization.
func gitContextFromRevParse(workDir string, raw revParseResult) gitContext {
var ctx gitContext
if raw.notRepo {
reason := raw.notRepoErr
if reason == nil {
reason = errNotGitRepository
}
ctx.err = fmt.Errorf("not a git repository: %w", reason)
return ctx
}
ctx.gitDirRaw = raw.gitDir
commonDirRaw := raw.commonDir
repoRootRaw := raw.topLevel
// Convert commonDir to absolute for reliable comparison
absCommon, err := absoluteGitPath(workDir, commonDirRaw)