diff --git a/.github/scripts/embedded-cmd-test-shards.txt b/.github/scripts/embedded-cmd-test-shards.txt index b1c7b0e8c..7a1c26452 100644 --- a/.github/scripts/embedded-cmd-test-shards.txt +++ b/.github/scripts/embedded-cmd-test-shards.txt @@ -306,6 +306,7 @@ 50 17 TestEmbeddedCompact 50 17 TestEmbeddedGateConcurrent 50 17 TestEmbeddedListComments +50 17 TestEmbeddedReadOnlyCommandsSpawnNoGit 50 18 TestEmbeddedContext 50 18 TestEmbeddedContributorCreate diff --git a/CHANGELOG.md b/CHANGELOG.md index 09d65701d..9831b832c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 8f5ea468f..5964f512a 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -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", diff --git a/cmd/bd/actor_test.go b/cmd/bd/actor_test.go index d7efa7fc3..5ef83b505 100644 --- a/cmd/bd/actor_test.go +++ b/cmd/bd/actor_test.go @@ -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) + } +} diff --git a/cmd/bd/ado.go b/cmd/bd/ado.go index 08206992b..5e54257bc 100644 --- a/cmd/bd/ado.go +++ b/cmd/bd/ado.go @@ -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)) diff --git a/cmd/bd/assign.go b/cmd/bd/assign.go index ba3a72e97..83b145f33 100644 --- a/cmd/bd/assign.go +++ b/cmd/bd/assign.go @@ -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 { diff --git a/cmd/bd/audit.go b/cmd/bd/audit.go index 127e3f236..fd33d0536 100644 --- a/cmd/bd/audit.go +++ b/cmd/bd/audit.go @@ -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, diff --git a/cmd/bd/close.go b/cmd/bd/close.go index b99abe219..5a28910a2 100644 --- a/cmd/bd/close.go +++ b/cmd/bd/close.go @@ -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 { diff --git a/cmd/bd/close_direct.go b/cmd/bd/close_direct.go index d7ac30cb1..47890945e 100644 --- a/cmd/bd/close_direct.go +++ b/cmd/bd/close_direct.go @@ -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, diff --git a/cmd/bd/close_if_revision.go b/cmd/bd/close_if_revision.go index ac5bfda1a..b544714e5 100644 --- a/cmd/bd/close_if_revision.go +++ b/cmd/bd/close_if_revision.go @@ -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 { diff --git a/cmd/bd/close_proxied_server.go b/cmd/bd/close_proxied_server.go index 94a614e3a..e7a791d4f 100644 --- a/cmd/bd/close_proxied_server.go +++ b/cmd/bd/close_proxied_server.go @@ -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) } diff --git a/cmd/bd/comment.go b/cmd/bd/comment.go index 15f577e7c..76cf3342a 100644 --- a/cmd/bd/comment.go +++ b/cmd/bd/comment.go @@ -183,7 +183,7 @@ To list comments on an issue, use the plural form: bd comments `, 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 { diff --git a/cmd/bd/comments.go b/cmd/bd/comments.go index c789ef498..256e6151f 100644 --- a/cmd/bd/comments.go +++ b/cmd/bd/comments.go @@ -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 { diff --git a/cmd/bd/context.go b/cmd/bd/context.go index 6b4807e47..bd772896b 100644 --- a/cmd/bd/context.go +++ b/cmd/bd/context.go @@ -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. diff --git a/cmd/bd/cook.go b/cmd/bd/cook.go index d76422c97..6e94309b0 100644 --- a/cmd/bd/cook.go +++ b/cmd/bd/cook.go @@ -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) } } diff --git a/cmd/bd/create.go b/cmd/bd/create.go index e65c9ab82..38692d287 100644 --- a/cmd/bd/create.go +++ b/cmd/bd/create.go @@ -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 { diff --git a/cmd/bd/create_form.go b/cmd/bd/create_form.go index d52f88dce..42d455796 100644 --- a/cmd/bd/create_form.go +++ b/cmd/bd/create_form.go @@ -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) } diff --git a/cmd/bd/defer.go b/cmd/bd/defer.go index 4158253bb..0a22b18be 100644 --- a/cmd/bd/defer.go +++ b/cmd/bd/defer.go @@ -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 } diff --git a/cmd/bd/defer_proxied_server.go b/cmd/bd/defer_proxied_server.go index 280df6ace..0e1a47847 100644 --- a/cmd/bd/defer_proxied_server.go +++ b/cmd/bd/defer_proxied_server.go @@ -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 { diff --git a/cmd/bd/delete.go b/cmd/bd/delete.go index d48de774a..c767f3958 100644 --- a/cmd/bd/delete.go +++ b/cmd/bd/delete.go @@ -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, diff --git a/cmd/bd/delete_proxied_server.go b/cmd/bd/delete_proxied_server.go index 9cd6b0491..3fff3137d 100644 --- a/cmd/bd/delete_proxied_server.go +++ b/cmd/bd/delete_proxied_server.go @@ -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, diff --git a/cmd/bd/dep.go b/cmd/bd/dep.go index ef502d810..e77e1e1c8 100644 --- a/cmd/bd/dep.go +++ b/cmd/bd/dep.go @@ -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 { diff --git a/cmd/bd/dep_proxied_server.go b/cmd/bd/dep_proxied_server.go index 28e50f79f..aee6b0306 100644 --- a/cmd/bd/dep_proxied_server.go +++ b/cmd/bd/dep_proxied_server.go @@ -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, }) diff --git a/cmd/bd/duplicates.go b/cmd/bd/duplicates.go index 32c6417c0..f11e4ea35 100644 --- a/cmd/bd/duplicates.go +++ b/cmd/bd/duplicates.go @@ -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 } diff --git a/cmd/bd/edit.go b/cmd/bd/edit.go index 5fe2bed53..5e04128d0 100644 --- a/cmd/bd/edit.go +++ b/cmd/bd/edit.go @@ -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 { diff --git a/cmd/bd/gate.go b/cmd/bd/gate.go index 3aa97289e..98985e062 100644 --- a/cmd/bd/gate.go +++ b/cmd/bd/gate.go @@ -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) diff --git a/cmd/bd/gate_discover.go b/cmd/bd/gate_discover.go index f66c3d4fa..b1842e1de 100644 --- a/cmd/bd/gate_discover.go +++ b/cmd/bd/gate_discover.go @@ -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 diff --git a/cmd/bd/gate_proxied_server.go b/cmd/bd/gate_proxied_server.go index 8597a749b..f83e66186 100644 --- a/cmd/bd/gate_proxied_server.go +++ b/cmd/bd/gate_proxied_server.go @@ -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) diff --git a/cmd/bd/gc_proxied_server.go b/cmd/bd/gc_proxied_server.go index ed4818373..f5fbdb7df 100644 --- a/cmd/bd/gc_proxied_server.go +++ b/cmd/bd/gc_proxied_server.go @@ -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 } diff --git a/cmd/bd/github.go b/cmd/bd/github.go index 77ee4e8e8..bedc3ef4b 100644 --- a/cmd/bd/github.go +++ b/cmd/bd/github.go @@ -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) } diff --git a/cmd/bd/gitlab.go b/cmd/bd/gitlab.go index 6657dcb3b..6bc94e0d0 100644 --- a/cmd/bd/gitlab.go +++ b/cmd/bd/gitlab.go @@ -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) } } diff --git a/cmd/bd/graph_apply.go b/cmd/bd/graph_apply.go index 00faeb197..9a52f1415 100644 --- a/cmd/bd/graph_apply.go +++ b/cmd/bd/graph_apply.go @@ -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 } diff --git a/cmd/bd/heartbeat.go b/cmd/bd/heartbeat.go index 281db80c2..6790047a7 100644 --- a/cmd/bd/heartbeat.go +++ b/cmd/bd/heartbeat.go @@ -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)) diff --git a/cmd/bd/heartbeat_proxied_server.go b/cmd/bd/heartbeat_proxied_server.go index 80de4a033..c09772f52 100644 --- a/cmd/bd/heartbeat_proxied_server.go +++ b/cmd/bd/heartbeat_proxied_server.go @@ -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 diff --git a/cmd/bd/human.go b/cmd/bd/human.go index c87faa2d6..19fb98907 100644 --- a/cmd/bd/human.go +++ b/cmd/bd/human.go @@ -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) } diff --git a/cmd/bd/human_proxied_server.go b/cmd/bd/human_proxied_server.go index 10c948add..924ed2632 100644 --- a/cmd/bd/human_proxied_server.go +++ b/cmd/bd/human_proxied_server.go @@ -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) diff --git a/cmd/bd/jira.go b/cmd/bd/jira.go index 099359b2a..b03574fe9 100644 --- a/cmd/bd/jira.go +++ b/cmd/bd/jira.go @@ -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) } diff --git a/cmd/bd/label.go b/cmd/bd/label.go index 46fcfd177..5f5a768db 100644 --- a/cmd/bd/label.go +++ b/cmd/bd/label.go @@ -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 diff --git a/cmd/bd/label_proxied_server.go b/cmd/bd/label_proxied_server.go index 9d5b955a1..0bf9215f0 100644 --- a/cmd/bd/label_proxied_server.go +++ b/cmd/bd/label_proxied_server.go @@ -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) diff --git a/cmd/bd/linear.go b/cmd/bd/linear.go index 8e24cb777..f6ba42990 100644 --- a/cmd/bd/linear.go +++ b/cmd/bd/linear.go @@ -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 diff --git a/cmd/bd/link.go b/cmd/bd/link.go index 772a88d91..a05be924b 100644 --- a/cmd/bd/link.go +++ b/cmd/bd/link.go @@ -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 { diff --git a/cmd/bd/link_proxied_server.go b/cmd/bd/link_proxied_server.go index aa7fac1b9..aef888968 100644 --- a/cmd/bd/link_proxied_server.go +++ b/cmd/bd/link_proxied_server.go @@ -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 diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 9fd38b3b9..901d461ee 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -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 diff --git a/cmd/bd/markdown.go b/cmd/bd/markdown.go index 2c002ad74..b902ad7a4 100644 --- a/cmd/bd/markdown.go +++ b/cmd/bd/markdown.go @@ -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" } diff --git a/cmd/bd/merge_slot.go b/cmd/bd/merge_slot.go index 927327472..cfd715394 100644 --- a/cmd/bd/merge_slot.go +++ b/cmd/bd/merge_slot.go @@ -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) } diff --git a/cmd/bd/migrate_issues.go b/cmd/bd/migrate_issues.go index 382d7ac3b..192afcaf9 100644 --- a/cmd/bd/migrate_issues.go +++ b/cmd/bd/migrate_issues.go @@ -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) } } diff --git a/cmd/bd/mol_bond.go b/cmd/bd/mol_bond.go index 3ea600de9..4f8a5f2c2 100644 --- a/cmd/bd/mol_bond.go +++ b/cmd/bd/mol_bond.go @@ -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) diff --git a/cmd/bd/mol_burn.go b/cmd/bd/mol_burn.go index 3062ff794..48293d832 100644 --- a/cmd/bd/mol_burn.go +++ b/cmd/bd/mol_burn.go @@ -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) } diff --git a/cmd/bd/mol_current.go b/cmd/bd/mol_current.go index f3d92d33f..6769f01ef 100644 --- a/cmd/bd/mol_current.go +++ b/cmd/bd/mol_current.go @@ -73,7 +73,7 @@ Use --limit or --range to view specific steps: agent := forAgent if agent == "" { - agent = actor + agent = currentActor() } if usesProxiedServer() { diff --git a/cmd/bd/mol_progress.go b/cmd/bd/mol_progress.go index ba35c2b61..df77f9359 100644 --- a/cmd/bd/mol_progress.go +++ b/cmd/bd/mol_progress.go @@ -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{}{}) diff --git a/cmd/bd/mol_proxied_server.go b/cmd/bd/mol_proxied_server.go index 6136499dc..04f16955e 100644 --- a/cmd/bd/mol_proxied_server.go +++ b/cmd/bd/mol_proxied_server.go @@ -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) } diff --git a/cmd/bd/mol_squash.go b/cmd/bd/mol_squash.go index 223e31955..39363cbdd 100644 --- a/cmd/bd/mol_squash.go +++ b/cmd/bd/mol_squash.go @@ -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) } diff --git a/cmd/bd/mutate_proxied_server.go b/cmd/bd/mutate_proxied_server.go index 7008e9a41..fa72c238e 100644 --- a/cmd/bd/mutate_proxied_server.go +++ b/cmd/bd/mutate_proxied_server.go @@ -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}}}, }) diff --git a/cmd/bd/note.go b/cmd/bd/note.go index b0c8eeeab..9ee62cb9e 100644 --- a/cmd/bd/note.go +++ b/cmd/bd/note.go @@ -173,10 +173,10 @@ To read notes on an issue, use: bd show `, 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 { diff --git a/cmd/bd/notion.go b/cmd/bd/notion.go index 664cd31f6..3ec42b336 100644 --- a/cmd/bd/notion.go +++ b/cmd/bd/notion.go @@ -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) diff --git a/cmd/bd/pour.go b/cmd/bd/pour.go index 91aa946eb..7260365ee 100644 --- a/cmd/bd/pour.go +++ b/cmd/bd/pour.go @@ -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) } diff --git a/cmd/bd/prime.go b/cmd/bd/prime.go index adec80396..f314fcb4a 100644 --- a/cmd/bd/prime.go +++ b/cmd/bd/prime.go @@ -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 diff --git a/cmd/bd/priority.go b/cmd/bd/priority.go index 481afecec..66a633e71 100644 --- a/cmd/bd/priority.go +++ b/cmd/bd/priority.go @@ -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 { diff --git a/cmd/bd/promote.go b/cmd/bd/promote.go index b1238abbf..44a42eea0 100644 --- a/cmd/bd/promote.go +++ b/cmd/bd/promote.go @@ -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) } diff --git a/cmd/bd/promote_proxied_server.go b/cmd/bd/promote_proxied_server.go index edadce2d5..38f6fb547 100644 --- a/cmd/bd/promote_proxied_server.go +++ b/cmd/bd/promote_proxied_server.go @@ -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 diff --git a/cmd/bd/purge.go b/cmd/bd/purge.go index 0337db793..cead0ae98 100644 --- a/cmd/bd/purge.go +++ b/cmd/bd/purge.go @@ -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, diff --git a/cmd/bd/quick.go b/cmd/bd/quick.go index a0cdbf550..e9ab99c03 100644 --- a/cmd/bd/quick.go +++ b/cmd/bd/quick.go @@ -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) } diff --git a/cmd/bd/quick_proxied_server.go b/cmd/bd/quick_proxied_server.go index 3035863bb..46ab79c62 100644 --- a/cmd/bd/quick_proxied_server.go +++ b/cmd/bd/quick_proxied_server.go @@ -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 } diff --git a/cmd/bd/ready.go b/cmd/bd/ready.go index babcefa35..7e7e8aacf 100644 --- a/cmd/bd/ready.go +++ b/cmd/bd/ready.go @@ -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 { diff --git a/cmd/bd/ready_input.go b/cmd/bd/ready_input.go index 0643ae3bd..e55a830c4 100644 --- a/cmd/bd/ready_input.go +++ b/cmd/bd/ready_input.go @@ -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 diff --git a/cmd/bd/reclaim.go b/cmd/bd/reclaim.go index 34b40d98b..2a5262d99 100644 --- a/cmd/bd/reclaim.go +++ b/cmd/bd/reclaim.go @@ -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 { diff --git a/cmd/bd/relate.go b/cmd/bd/relate.go index 987ccdff9..f87f644d4 100644 --- a/cmd/bd/relate.go +++ b/cmd/bd/relate.go @@ -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) } diff --git a/cmd/bd/relate_proxied_server.go b/cmd/bd/relate_proxied_server.go index 601b1a30d..34a6d688f 100644 --- a/cmd/bd/relate_proxied_server.go +++ b/cmd/bd/relate_proxied_server.go @@ -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) } diff --git a/cmd/bd/rename_prefix.go b/cmd/bd/rename_prefix.go index 0ff1c8c91..68936732b 100644 --- a/cmd/bd/rename_prefix.go +++ b/cmd/bd/rename_prefix.go @@ -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) } } diff --git a/cmd/bd/reopen.go b/cmd/bd/reopen.go index 6bdb3f7cd..6a6635e23 100644 --- a/cmd/bd/reopen.go +++ b/cmd/bd/reopen.go @@ -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 { diff --git a/cmd/bd/reopen_proxied_server.go b/cmd/bd/reopen_proxied_server.go index a9fadd638..e61f85a22 100644 --- a/cmd/bd/reopen_proxied_server.go +++ b/cmd/bd/reopen_proxied_server.go @@ -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 diff --git a/cmd/bd/ship.go b/cmd/bd/ship.go index a8c0908ed..9e56be5bd 100644 --- a/cmd/bd/ship.go +++ b/cmd/bd/ship.go @@ -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) } diff --git a/cmd/bd/startup_git_exec_embedded_test.go b/cmd/bd/startup_git_exec_embedded_test.go new file mode 100644 index 000000000..a74194207 --- /dev/null +++ b/cmd/bd/startup_git_exec_embedded_test.go @@ -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")) + } +} diff --git a/cmd/bd/state.go b/cmd/bd/state.go index a3ad36623..b689b0f28 100644 --- a/cmd/bd/state.go +++ b/cmd/bd/state.go @@ -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}, diff --git a/cmd/bd/status.go b/cmd/bd/status.go index 855f67679..f5deaac38 100644 --- a/cmd/bd/status.go +++ b/cmd/bd/status.go @@ -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 { diff --git a/cmd/bd/swarm.go b/cmd/bd/swarm.go index 996eefc40..9d066a023 100644 --- a/cmd/bd/swarm.go +++ b/cmd/bd/swarm.go @@ -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) } diff --git a/cmd/bd/sync_push_pull.go b/cmd/bd/sync_push_pull.go index 63a2263ff..0e6b289da 100644 --- a/cmd/bd/sync_push_pull.go +++ b/cmd/bd/sync_push_pull.go @@ -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) } diff --git a/cmd/bd/tag.go b/cmd/bd/tag.go index 096b5f66c..02e4db5de 100644 --- a/cmd/bd/tag.go +++ b/cmd/bd/tag.go @@ -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 { diff --git a/cmd/bd/unclaim.go b/cmd/bd/unclaim.go index f900e1750..3dd59a8fe 100644 --- a/cmd/bd/unclaim.go +++ b/cmd/bd/unclaim.go @@ -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) } } diff --git a/cmd/bd/unclaim_proxied_server.go b/cmd/bd/unclaim_proxied_server.go index 85b56acc2..9269beb88 100644 --- a/cmd/bd/unclaim_proxied_server.go +++ b/cmd/bd/unclaim_proxied_server.go @@ -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 } diff --git a/cmd/bd/undefer.go b/cmd/bd/undefer.go index 08e251c6a..b89907be8 100644 --- a/cmd/bd/undefer.go +++ b/cmd/bd/undefer.go @@ -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 } diff --git a/cmd/bd/update.go b/cmd/bd/update.go index 1510b8c78..09e8edb64 100644 --- a/cmd/bd/update.go +++ b/cmd/bd/update.go @@ -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 { diff --git a/cmd/bd/update_proxied_server.go b/cmd/bd/update_proxied_server.go index fee3e9225..5d74583b2 100644 --- a/cmd/bd/update_proxied_server.go +++ b/cmd/bd/update_proxied_server.go @@ -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()} diff --git a/cmd/bd/wisp.go b/cmd/bd/wisp.go index 329b1734f..a1b7ac27e 100644 --- a/cmd/bd/wisp.go +++ b/cmd/bd/wisp.go @@ -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, diff --git a/cmd/bd/wisp_proxied_server.go b/cmd/bd/wisp_proxied_server.go index edc727ea8..fd43df23b 100644 --- a/cmd/bd/wisp_proxied_server.go +++ b/cmd/bd/wisp_proxied_server.go @@ -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 } diff --git a/internal/beads/context.go b/internal/beads/context.go index 63c63394c..7db3b0ee8 100644 --- a/internal/beads/context.go +++ b/internal/beads/context.go @@ -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) diff --git a/internal/git/BUILD.bazel b/internal/git/BUILD.bazel index 4d259cd16..e36e0ec55 100644 --- a/internal/git/BUILD.bazel +++ b/internal/git/BUILD.bazel @@ -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", ], diff --git a/internal/git/discover_linux.go b/internal/git/discover_linux.go new file mode 100644 index 000000000..4f88fd903 --- /dev/null +++ b/internal/git/discover_linux.go @@ -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 /.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 /.git being a gitfile ("gitdir: "), 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..* 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 /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..* 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 +} diff --git a/internal/git/discover_linux_test.go b/internal/git/discover_linux_test.go new file mode 100644 index 000000000..04d111f25 --- /dev/null +++ b/internal/git/discover_linux_test.go @@ -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) + } + }) + } +} diff --git a/internal/git/discover_other.go b/internal/git/discover_other.go new file mode 100644 index 000000000..231616c9b --- /dev/null +++ b/internal/git/discover_other.go @@ -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 +} diff --git a/internal/git/gitconfig_linux.go b/internal/git/gitconfig_linux.go new file mode 100644 index 000000000..ea786b373 --- /dev/null +++ b/internal/git/gitconfig_linux.go @@ -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 +} diff --git a/internal/git/gitdir.go b/internal/git/gitdir.go index 31019d7b4..133ed8203 100644 --- a/internal/git/gitdir.go +++ b/internal/git/gitdir.go @@ -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)