beads/cmd/bd/create_form.go
Julian Knutsen 5126de8c1a
perf(bd): no git subprocesses on read-only commands (in-process repo discovery, lazy actor, backup probe) (#7400)
* perf(git): locate the repository in-process instead of running git rev-parse

Every bd invocation resolved the process-wide git context (beads directory
discovery reads it) with `git rev-parse --git-dir --git-common-dir
--show-toplevel`: one git subprocess per bd call before any work. Tools that
call bd hundreds of times (gascity's doctor issues ~250 bd calls per run)
paid it on every call.

On Linux, initGitContext now first runs discoverGitInProcess, which mirrors
Git's discovery walk (physical cwd, .git as directory or gitfile, bare-dir
check, filesystem-boundary stop) and produces byte-for-byte what rev-parse
prints for ordinary repositories (top and subdirectories), linked worktrees
(absolute or relative gitfile, symlinked targets), submodules (core.worktree
pointing back at the gitfile's directory), nested repositories and no
repository. Both answers feed one shared normalization
(gitContextFromRevParse), so downstream values are unchanged.

It declines, and git runs exactly as before, whenever it cannot prove the
answer: GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR / GIT_CEILING_DIRECTORIES /
GIT_DISCOVERY_ACROSS_FILESYSTEM / GIT_OBJECT_DIRECTORY / GIT_CONFIG_PARAMETERS
/ GIT_CONFIG_COUNT in the environment; a symlinked .git, an invalid gitfile
or git directory, a cwd inside a git directory; repository config with
core.worktree (other than the submodule shape), core.bare, extensions,
include directives, a format version above 1 or unmodeled syntax; any path
not owned by the effective uid (safe.directory is git's to evaluate), or
root under sudo. darwin and windows keep the subprocess (case folding and
ownership semantics).

Tests compare discoverGitFrom with real `git rev-parse` output across those
layouts, pin every decline case, and check the resulting cached context
equals the subprocess-derived one.

Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(cli): resolve the git user.name actor fallback only when needed

PersistentPreRunE assigned `actor = getActorWithGit()` for every command,
which, with no --actor / BEADS_ACTOR / BD_ACTOR / config actor, runs
`git config user.name`: the second git subprocess of every bd call, paid
by read-only commands that never consult the actor.

The pre-run now calls deferActorGitFallback, which marks an empty actor as
pending; currentActor (and getActorWithGit, getActor) resolve it on first
use with the unchanged priority order and store it in the global and the
CommandContext copy, as the eager assignment did. Command code reads the
actor through currentActor() instead of the raw global (a mechanical
rewrite of every read site the compiler reported; writes, the flag binding
and the pre-run config binding keep the raw variable). setActor cancels a
pending fallback. The telemetry span's bd.actor attribute is still set, but
only for a recording span, so a noop span does not force the lookup.

With the in-process repository discovery from the previous commit, a
read-only `bd list` / `bd show` now starts no git process at startup, in
the main checkout and in a linked worktree; a write asks git for user.name
once (bd create previously asked once, now still once) and records the same
value. Measured on 50 sequential `bd list` calls: 100 -> 0 git execs
(embedded and proxied-server workspaces, main checkout and worktree).

TestEmbeddedReadOnlyCommandsSpawnNoGit counts git execs through a PATH shim;
TestDeferredActorGitFallback pins the deferral semantics.

Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(git): decline in-process discovery on any config line git might read differently

Review follow-ups to the in-process repository discovery.

- The repository config scanner was looser than git: a config starting with
  a UTF-8 BOM followed by `[core] worktree = /other` made git report /other
  while discovery returned the cwd repository, and `[ core ]` or `!!! = x`
  (which git refuses) were accepted. scanGitConfig (gitconfig_linux.go) now
  skips a leading BOM exactly as git does and accepts only a narrow grammar:
  blank/comment lines, `[section]` / `[section "sub"]` headers at column 0,
  and `key` / `key = value` lines inside a section, with values free of
  backslashes and unbalanced quotes. Any other line declines to git.
- Walk from getcwd(2) (syscall.Getwd), as git does, instead of os.Getwd,
  which trusts $PWD when it names the same inode (bind-mount aliases).
- Resolve relative gitfile and commondir targets without filepath.Join's
  lexical Clean, so "link/.." resolves physically like git's realpath.
- A mount-boundary stop reports its own reason in the not-a-repository
  error.
- Tests: every decline case (BOM + core.worktree, malformed headers and
  keys, keys before a section, escapes, continuations, bare repositories,
  a commondir inside .git, ...) now also checks that what startup derives
  equals git's answer; BOM and CRLF/comment configs are equivalence cases;
  the no-repository case must be answered in-process instead of skipping;
  a $PWD alias test pins the getcwd walk.
- The exec-count test drops every GIT_* variable except the config-file
  selectors, so a runner exporting GIT_CONFIG_PARAMETERS & co. cannot make
  it fail spuriously.
- Comment the two places that touch the raw actor before the deferral.

Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(backup): decide embedded auto-backup's git-remote probe without git

In an embedded workspace whose backup.enabled is unset, maybeAutoBackup
asks isBackupAutoEnabled -> primeHasGitRemote after every command, reads
included. That built a RepoContext (`git -C .beads rev-parse
--git-common-dir`) and ran `git remote`: two git processes per read even
after the startup calls were gone. The throttle cannot short-circuit it:
without a remote no backup ever runs, so there is no backup state to
throttle on.

Both probes are now answered in-process when provable, and the subprocess
remains the fallback, so the decision and every warning/notice downstream
of it are unchanged:

- internal/beads getGitCommonDirForPath uses git.CommonDirInProcess (the
  discovery walk from the given directory, git's spelling).
- primeHasGitRemote uses git.HasRemoteInProcess in the same directory
  primeGitCmd would run git in (primeGitDir, factored out). It answers only
  when every config file `git remote` reads -- system (GIT_CONFIG_SYSTEM, or
  /etc/gitconfig and <prefix>/etc/gitconfig of the git on PATH), global
  (GIT_CONFIG_GLOBAL, or XDG and ~/.gitconfig) and the repository's own --
  is absent or within scanGitConfig's grammar and include-free, no
  GIT_CONFIG_PARAMETERS/COUNT/GIT_CONFIG or discovery override is set, and
  no legacy .git/remotes or .git/branches entries exist. A remote seen only
  in a system-config candidate declines. Remote names outside
  [A-Za-z0-9._-] decline.

Tests compare HasRemoteInProcess with `git remote` (no remote, local,
worktree, submodule, remote.pushDefault only, global remote, no repo) and
pin the declines (global include, malformed global, command-line config);
CommonDirInProcess is compared with `git -C dir rev-parse
--git-common-dir`. TestEmbeddedReadOnlyCommandsSpawnNoGit now runs with
backup.enabled at its default, with and without a git remote, and still
expects zero git processes for list/show.

Agent-Signature: claude-code-claude-opus-5-5-medium on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 20:08:24 +00:00

407 lines
12 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"os"
"strconv"
"strings"
"charm.land/huh/v2"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
// createFormRawInput holds the raw string values from the form UI.
// This struct encapsulates all form fields before parsing/conversion.
type createFormRawInput struct {
Title string
Description string
IssueType string
Priority string // String from select, e.g., "0", "1", "2"
Assignee string
Labels string // Comma-separated
Design string
Acceptance string
ExternalRef string
Deps string // Comma-separated, format: "type:id" or "id"
}
// createFormValues holds the parsed values from the create-form input.
// This struct is used to pass form data to the issue creation logic,
// allowing the creation logic to be tested independently of the form UI.
type createFormValues struct {
Title string
Description string
IssueType string
Priority int
Assignee string
Labels []string
Design string
AcceptanceCriteria string
ExternalRef string
Dependencies []string
ParentID string // Parent issue ID for hierarchical child creation
}
// parseCreateFormInput parses raw form input into a createFormValues struct.
// It handles comma-separated labels and dependencies, and converts priority strings.
func parseCreateFormInput(raw *createFormRawInput) *createFormValues {
// Parse priority
priority, err := strconv.Atoi(raw.Priority)
if err != nil {
priority = 2 // Default to medium if parsing fails
}
// Parse labels
var labels []string
if raw.Labels != "" {
for _, l := range strings.Split(raw.Labels, ",") {
l = strings.TrimSpace(l)
if l != "" {
labels = append(labels, l)
}
}
}
// Parse dependencies
var deps []string
if raw.Deps != "" {
for _, d := range strings.Split(raw.Deps, ",") {
d = strings.TrimSpace(d)
if d != "" {
deps = append(deps, d)
}
}
}
return &createFormValues{
Title: raw.Title,
Description: raw.Description,
IssueType: raw.IssueType,
Priority: priority,
Assignee: raw.Assignee,
Labels: labels,
Design: raw.Design,
AcceptanceCriteria: raw.Acceptance,
ExternalRef: raw.ExternalRef,
Dependencies: deps,
}
}
// CreateIssueFromFormValues creates an issue from the given form values.
// It returns the created issue and any error that occurred.
// This function handles parent-child relationships, labels, dependencies,
// and source_repo inheritance.
func CreateIssueFromFormValues(ctx context.Context, s storage.DoltStorage, fv *createFormValues, actor string) (*types.Issue, error) {
// If parent is specified, validate it exists and generate child ID
var explicitID string
var inheritedLabels []string
if fv.ParentID != "" {
_, err := s.GetIssue(ctx, fv.ParentID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nil, fmt.Errorf("parent issue %s not found", fv.ParentID)
}
return nil, fmt.Errorf("failed to check parent issue: %w", err)
}
childID, err := s.GetNextChildID(ctx, fv.ParentID)
if err != nil {
return nil, fmt.Errorf("failed to generate child ID: %w", err)
}
explicitID = childID
ctx = storage.WithReservedChildCounter(ctx, fv.ParentID, childID)
// Inherit parent labels (GH#2100), matching bd create --parent behavior
inheritedLabels, _ = s.GetLabels(ctx, fv.ParentID)
}
var externalRefPtr *string
if fv.ExternalRef != "" {
externalRefPtr = &fv.ExternalRef
}
labels := mergeCreateLabels(fv.Labels, inheritedLabels)
issue := &types.Issue{
Title: fv.Title,
Description: fv.Description,
Design: fv.Design,
AcceptanceCriteria: fv.AcceptanceCriteria,
Status: types.StatusOpen,
Priority: fv.Priority,
IssueType: types.IssueType(fv.IssueType).Normalize(),
Assignee: fv.Assignee,
ExternalRef: externalRefPtr,
CreatedBy: getActorWithGit(), // GH#748: track who created the issue
Labels: labels,
}
if explicitID != "" {
issue.ID = explicitID
}
// If a discovered-from dependency is present, inherit source_repo from
// the referenced parent issue.
if dfParent := discoveredFromParent(fv.Dependencies); dfParent != "" {
parentIssue, err := s.GetIssue(ctx, dfParent)
if err == nil && parentIssue != nil && parentIssue.SourceRepo != "" {
issue.SourceRepo = parentIssue.SourceRepo
}
}
// Parse dependency specs before creating anything. The form keeps its
// historical lenient parsing (warn and skip malformed entries), but the
// edges that do parse commit atomically with the create below.
var depSpecs []domain.DependencySpec
for _, depSpec := range fv.Dependencies {
depSpec = strings.TrimSpace(depSpec)
if depSpec == "" {
continue
}
var depType types.DependencyType
var dependsOnID string
if strings.Contains(depSpec, ":") {
parts := strings.SplitN(depSpec, ":", 2)
depType = types.DependencyType(strings.TrimSpace(parts[0]))
dependsOnID = strings.TrimSpace(parts[1])
} else {
depType = types.DepBlocks
dependsOnID = depSpec
}
if !depType.IsValid() {
fmt.Fprintf(os.Stderr, "Warning: invalid dependency type '%s' (valid: blocks, related, parent-child, discovered-from)\n", depType)
continue
}
depSpecs = append(depSpecs, domain.DependencySpec{Type: depType, TargetID: dependsOnID})
}
// The issue and its edges (parent-child per GH#1983, plus form deps)
// commit in one transaction; a failed edge rolls back the create instead
// of leaving a dep-less issue behind (same contract as bd create).
edges := createDepEdges{parentID: fv.ParentID, specs: depSpecs}
if err := createIssueWithDeps(ctx, s, issue, actor, edges); err != nil {
return nil, fmt.Errorf("failed to create issue: %w", err)
}
if edges.empty() {
// Bare create: preserve the embedded-mode follow-up Dolt commit.
// The deps path commits inside its transaction instead.
shouldCommit, err := shouldCommitCreatePostWrites(issue, false)
if err != nil {
return nil, fmt.Errorf("dolt auto-commit: %w", err)
}
if shouldCommit {
commitMsg := fmt.Sprintf("bd: create %s", issue.ID)
if err := s.Commit(ctx, commitMsg); err != nil && !isDoltNothingToCommit(err) {
WarnError("failed to commit post-create metadata: %v", err)
}
}
}
return issue, nil
}
var createFormCmd = &cobra.Command{
Use: "create-form",
GroupID: "issues",
Short: "Create a new issue using an interactive form",
Long: `Create a new issue using an interactive terminal form.
This command provides a user-friendly form interface for creating issues,
with fields for title, description, type, priority, labels, and more.
Use --parent to create a sub-issue under an existing parent issue.
The child will get an auto-generated hierarchical ID (e.g., parent-id.1).
The form uses keyboard navigation:
- Tab/Shift+Tab: Move between fields
- Enter: Submit the form (on the last field or submit button)
- Ctrl+C: Cancel and exit
- Arrow keys: Navigate within select fields`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("create-form is not supported in proxied-server mode")
}
CheckReadonly("create-form")
evt := metrics.NewCommandEvent("create-form")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
return runCreateForm(cmd)
},
}
func runCreateForm(cmd *cobra.Command) error {
parentID, _ := cmd.Flags().GetString("parent")
// Raw form input - will be populated by the form
raw := &createFormRawInput{}
// Issue type options
typeOptions := []huh.Option[string]{
huh.NewOption("Task", "task"),
huh.NewOption("Bug", "bug"),
huh.NewOption("Feature", "feature"),
huh.NewOption("Epic", "epic"),
huh.NewOption("Chore", "chore"),
}
// Priority options
priorityOptions := []huh.Option[string]{
huh.NewOption("P0 - Critical", "0"),
huh.NewOption("P1 - High", "1"),
huh.NewOption("P2 - Medium (default)", "2"),
huh.NewOption("P3 - Low", "3"),
huh.NewOption("P4 - Backlog", "4"),
}
// Build the form
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().
Title("Title").
Description("Brief summary of the issue (required)").
Placeholder("e.g., Fix authentication bug in login handler").
Value(&raw.Title).
Validate(func(s string) error {
if strings.TrimSpace(s) == "" {
return fmt.Errorf("title is required")
}
if len(s) > 500 {
return fmt.Errorf("title must be 500 characters or less")
}
return nil
}),
huh.NewText().
Title("Description").
Description("Detailed context about the issue").
Placeholder("Explain why this issue exists and what needs to be done...").
CharLimit(5000).
Value(&raw.Description),
huh.NewSelect[string]().
Title("Type").
Description("Categorize the kind of work").
Options(typeOptions...).
Value(&raw.IssueType),
huh.NewSelect[string]().
Title("Priority").
Description("Set urgency level").
Options(priorityOptions...).
Value(&raw.Priority),
),
huh.NewGroup(
huh.NewInput().
Title("Assignee").
Description("Who should work on this? (optional)").
Placeholder("username or email").
Value(&raw.Assignee),
huh.NewInput().
Title("Labels").
Description("Comma-separated tags (optional)").
Placeholder("e.g., urgent, backend, needs-review").
Value(&raw.Labels),
huh.NewInput().
Title("External Reference").
Description("Link to external tracker (optional)").
Placeholder("e.g., gh-123, jira-ABC-456").
Value(&raw.ExternalRef),
),
huh.NewGroup(
huh.NewText().
Title("Design Notes").
Description("Technical approach or design details (optional)").
Placeholder("Describe the implementation approach...").
CharLimit(5000).
Value(&raw.Design),
huh.NewText().
Title("Acceptance Criteria").
Description("How do we know this is done? (optional)").
Placeholder("List the criteria for completion...").
CharLimit(5000).
Value(&raw.Acceptance),
),
huh.NewGroup(
huh.NewInput().
Title("Dependencies").
Description("Format: type:id or just id (optional)").
Placeholder("e.g., discovered-from:bd-20, blocks:bd-15").
Value(&raw.Deps),
huh.NewConfirm().
Title("Create this issue?").
Affirmative("Create").
Negative("Cancel"),
),
).WithTheme(huh.ThemeFunc(huh.ThemeDracula))
err := form.Run()
if err != nil {
if err == huh.ErrUserAborted {
fmt.Fprintln(os.Stderr, "Issue creation canceled.")
return nil
}
return HandleError("form error: %v", err)
}
fv := parseCreateFormInput(raw)
fv.ParentID = parentID
issue, err := CreateIssueFromFormValues(rootCtx, store, fv, currentActor())
if err != nil {
return HandleError("%v", err)
}
if jsonOutput {
return outputJSON(issue)
}
printCreatedIssue(issue)
return nil
}
func printCreatedIssue(issue *types.Issue) {
fmt.Printf("\n%s Created issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(issue.ID, issue.Title))
fmt.Printf(" Type: %s\n", issue.IssueType)
fmt.Printf(" Priority: P%d\n", issue.Priority)
fmt.Printf(" Status: %s\n", issue.Status)
if issue.Assignee != "" {
fmt.Printf(" Assignee: %s\n", issue.Assignee)
}
if issue.Description != "" {
desc := issue.Description
if len(desc) > 100 {
desc = desc[:97] + "..."
}
fmt.Printf(" Description: %s\n", desc)
}
}
func init() {
// Note: --json flag is defined as a persistent flag in main.go
createFormCmd.Flags().String("parent", "", "Parent issue ID for creating a hierarchical child (e.g., 'bd-a3f8e9')")
rootCmd.AddCommand(createFormCmd)
}