beads/cmd/bd/edit.go
Julian Knutsen b4c76a676b
fix(gate): ordinary commands wait for maintenance operations, fairly; init waits up to 60s (#7225)
* fix(gate): ordinary commands wait out maintenance, with writer fairness

Ordinary bd commands take the workspace (and physical-root) gate SHARED and
never waited for it, so while another process held it EXCLUSIVELY — bd init
(~8s), backup restore, migrate, bootstrap — they failed at once with "a
maintenance operation is running". In shared-server mode every project
shares one physical-root gate, so another project's bd init broke every bd
command on the machine for its duration.

Ordinary commands now wait:
- up to 15s by default; BEADS_GATE_WAIT_TIMEOUT (Go duration or bare
  seconds, same convention as BEADS_INIT_GATE_TIMEOUT) overrides it, and 0
  restores fail-fast;
- one "waiting for another bd process ..." notice after 2s (shared with bd
  init's notice);
- Ctrl-C aborts the wait. A canceled wait used to fall through to the
  shared fail-open path ("continuing ungated"); it is now a hard error;
- past the bound, the same error naming the holder, the wait, and the knob.

Git hooks stay fail-fast: `bd hooks run` and the bd export/import children
the hooks spawn run with BD_GIT_HOOK=1, treat failure as a warning, and must
not stall a commit or checkout for 15s.

Writer fairness (internal/workspacegate). flock/LockFileEx give no queueing,
and acquisition is non-blocking polling, so a steady stream of overlapping
shared holders could keep a waiting exclusive acquirer (bd init) out past
its bound. A per-gate intent lock (<gate>.intent) fixes that: a waiting
exclusive acquirer whose first try is busy takes the intent lock
exclusively while it polls, and waiting shared acquirers probe it before
every attempt and wait while it is held. The exclusive waiter then waits
only for in-flight holders to drain. The intent is an OS lock, so a crashed
waiter's intent dies with it; its advisory sidecar is ignored when the lock
is free, and intent-lock errors other than "busy" degrade to the old
behavior. Fail-fast acquisitions (Wait <= 0) ignore the queue entirely, so
hooks and BEADS_GATE_WAIT_TIMEOUT=0 behave exactly as before. The intent
lock is taken only while acquiring its gate, directly before it in
AcquireAll's sorted order, so it adds no lock-order cycles.

Nested bd (bd orphans running bd close, hooks fired by git that bd runs)
would deadlock against the queue: the child queues behind an exclusive
waiter that is waiting for the child's parent. A bd process holding its
gates shared exports BEADS_GATE_SHARED_HOLDER_PID; a child whose recorded
ancestor is alive skips the queue (it cannot help the waiter anyway).

Tests: workspacegate fairness (a continuous shared stream no longer starves
an exclusive waiter; verified to fail without the queue), intent lifecycle,
stale intent from a SIGKILLed process, cancellation while queued,
InheritedSharedHold. cmd/bd: holder released after ~3s lets a command
through with one notice; past-bound error text; fail-fast modes (0, hooks);
Ctrl-C is not fail-open; a new command queues behind a waiting bd init
while a child of a shared holder does not; env parsing.
TestSharedServerConcurrent runs a late bd init of a new project during the
client workloads, so both directions are exercised against a real server.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(gate): a queued exclusive waiter may delay shared commands, never fail them

Review follow-up (B1). A doomed exclusive waiter — bd init or restore
blocked behind a long-lived shared holder such as `bd list --watch`,
`bd events tail --follow`, an open `bd edit` editor, or a beads.OpenGated
embedder — held the writer-fairness intent lock for its whole budget, so
every NEW ordinary command deferred to it and failed with "queued for
exclusive access" even though nothing held the gate exclusively. Before
the fairness change those commands ran normally.

Two bounds fix it while keeping the fairness win:
- An exclusive waiter drops the intent lock after maxIntentHold (10s)
  without getting the gate and keeps polling unqueued. In-flight ordinary
  commands drain far faster than that.
- The final attempt of a waiting shared acquisition tries the gate even
  while intent is held, so a shared acquisition fails only when the gate
  itself is held exclusively.

With the final attempt ignoring intent, AcquireAll's 1ns floor for an
exhausted budget is dead code (a Wait-0 attempt behaves the same), so it is
back to 0. queuedDetail drops an intent sidecar left by a dead process (on
Windows its removal can fail while another process is reading it).

Tests: the doomed-waiter scenario (both bounds; each fails with its bound
removed), intent lock order across a two-gate set in both directions, an
exhausted AcquireAll budget, two exclusive waiters handing off the intent,
and BEADS_GATE_SHARED_HOLDER_PID inherited through a real subprocess.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(gate): 30s shared wait, 60s init wait, accurate errors, hook pinning

Review follow-ups for the shared gate wait (S1-S5 and nits), on top of the
workspacegate fix that keeps a queued exclusive waiter from failing
ordinary commands.

- Ordinary commands wait up to 30s by default (was 15s). Queued
  maintenance operations run one after another (two inits fanned out
  across shared-server projects hold the gate back to back, 10-15s each
  under load) and a waiting command waits for all of them. Documented in
  configuration.md and CHANGELOG, including BEADS_GATE_WAIT_TIMEOUT=0 for
  scripts that relied on fail-fast.
- bd init waits up to 60s by default (was 30s). Safe only now that a
  waiting init stops queueing others after 10s.
- Error text: a shared acquisition now fails only when the gate is held
  exclusively, so "running" is accurate; in shared-server mode it says
  "the shared server (possibly from another project)", and the detail
  still names the holder when known.
- hooks.go: the hookSubprocessEnv / bd import comments listed BD_GIT_HOOK's
  consumers without the gate wait, which now reads it to stay fail-fast.
  TestHookSubprocessEnvKeepsGateFailFast pins that hook subprocesses carry
  it and therefore never wait on the gate.
- bd edit's $EDITOR (which can outlive bd by hours) no longer inherits
  BEADS_GATE_SHARED_HOLDER_PID.
- Test hygiene: the cmd/bd test binary never advertises the marker
  (in-process command tests run beside tests that spawn bd) and clears any
  inherited one in TestMain; the notice-delay test runs in 1s, not 3s.
- TestSharedServerConcurrent's late init keeps a 30s bound so the 60s
  default cannot mask a fairness regression.

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-05 00:03:48 -07:00

195 lines
5.5 KiB
Go

package main
import (
"fmt"
"os"
"os/exec"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/ui"
)
var editCmd = &cobra.Command{
Use: "edit [id]",
GroupID: "issues",
Short: "Edit an issue field in $EDITOR",
Long: `Edit an issue field using your configured $EDITOR.
By default, edits the description. Use flags to edit other fields.
Examples:
bd edit bd-42 # Edit description
bd edit bd-42 --title # Edit title
bd edit bd-42 --design # Edit design notes
bd edit bd-42 --notes # Edit notes
bd edit bd-42 --acceptance # Edit acceptance criteria`,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("edit")
evt := metrics.NewCommandEvent("edit")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if usesProxiedServer() {
return runEditProxiedServer(cmd, rootCtx, args)
}
id := args[0]
ctx := rootCtx
// Resolve ID with prefix routing (supports cross-rig edits like `bd edit xe-5ls`)
result, err := resolveAndGetIssueForMutation(ctx, store, id)
if err != nil {
return HandleErrorRespectJSON("resolving %s: %v", id, err)
}
defer result.Close()
id = result.ResolvedID
issueStore := result.Store
fieldToEdit := "description"
if cmd.Flags().Changed("title") {
fieldToEdit = "title"
} else if cmd.Flags().Changed("design") {
fieldToEdit = "design"
} else if cmd.Flags().Changed("notes") {
fieldToEdit = "notes"
} else if cmd.Flags().Changed("acceptance") {
fieldToEdit = "acceptance_criteria"
}
editor := os.Getenv("EDITOR")
if editor == "" {
editor = os.Getenv("VISUAL")
}
if editor == "" {
for _, defaultEditor := range []string{"vim", "vi", "nano", "emacs"} {
if _, err := exec.LookPath(defaultEditor); err == nil {
editor = defaultEditor
break
}
}
}
if editor == "" {
return HandleErrorRespectJSON("no editor found. Set $EDITOR or $VISUAL environment variable")
}
issue := result.Issue
var currentValue string
switch fieldToEdit {
case "title":
currentValue = issue.Title
case "description":
currentValue = issue.Description
case "design":
currentValue = issue.Design
case "notes":
currentValue = issue.Notes
case "acceptance_criteria":
currentValue = issue.AcceptanceCriteria
}
tmpFile, err := os.CreateTemp("", fmt.Sprintf("bd-edit-%s-*.txt", fieldToEdit))
if err != nil {
return HandleErrorRespectJSON("creating temp file: %v", err)
}
tmpPath := tmpFile.Name()
editSaved := false
defer func() {
if editSaved {
_ = os.Remove(tmpPath)
}
}()
if _, err := tmpFile.WriteString(currentValue); err != nil {
_ = tmpFile.Close()
return HandleErrorRespectJSON("writing to temp file: %v", err)
}
_ = tmpFile.Close()
editorParts := strings.Fields(editor)
editorArgs := append(editorParts[1:], tmpPath)
editorCmd := exec.Command(editorParts[0], editorArgs...) //nolint:gosec // G204: editor from trusted $EDITOR/$VISUAL env or known defaults
editorCmd.Env = envWithoutSharedHoldMarker()
editorCmd.Stdin = os.Stdin
editorCmd.Stdout = os.Stdout
editorCmd.Stderr = os.Stderr
if err := editorCmd.Run(); err != nil {
return HandleErrorRespectJSON("running editor: %v", err)
}
// #nosec G304 -- tmpPath was created earlier in this function
editedContent, err := os.ReadFile(tmpPath)
if err != nil {
return HandleErrorRespectJSON("reading edited file: %v", err)
}
newValue := strings.TrimSpace(string(editedContent))
if newValue == currentValue {
editSaved = true
fmt.Println("No changes made")
return nil
}
if fieldToEdit == "title" && newValue == "" {
return HandleErrorRespectJSON("title cannot be empty")
}
updates := map[string]interface{}{
fieldToEdit: newValue,
}
err = issueStore.UpdateIssue(ctx, id, updates, actor)
if err != nil {
if accessor, ok := storage.UnwrapStore(issueStore).(storage.RawDBAccessor); ok {
if pingErr := accessor.DB().PingContext(ctx); pingErr != nil {
accessor.DB().SetConnMaxIdleTime(0)
_ = accessor.DB().PingContext(ctx)
}
}
err = issueStore.UpdateIssue(ctx, id, updates, actor)
}
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{
Command: "edit",
IssueIDs: []string{id},
}); err != nil {
fmt.Fprintf(os.Stderr, "Your edits are preserved in: %s\n", tmpPath)
return HandleErrorRespectJSON("failed to commit: %v", err)
}
displayTitle := issue.Title
if fieldToEdit == "title" {
displayTitle = newValue
}
fieldName := strings.ReplaceAll(fieldToEdit, "_", " ")
fmt.Printf("%s Updated %s for issue: %s\n", ui.RenderPass("✓"), fieldName, formatFeedbackID(id, displayTitle))
return nil
},
}
func init() {
editCmd.Flags().Bool("title", false, "Edit the title")
editCmd.Flags().Bool("description", false, "Edit the description (default)")
editCmd.Flags().Bool("design", false, "Edit the design notes")
editCmd.Flags().Bool("notes", false, "Edit the notes")
editCmd.Flags().Bool("acceptance", false, "Edit the acceptance criteria")
editCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(editCmd)
}