fix(close): support per-id reasons (#4194)

* fix(close): support per-id reasons

Why: upstream GH#3279 reports repeated --reason values applying incorrectly across multi-ID close, while GH#3268 needs a ready zero-dependency regression guard to prevent queue drift.

_codex-gpt-5.5-medium on behalf of matt wilkie_

* docs: refresh close CLI references

_codex-gpt-5.5-medium on behalf of CI Bot_

* fix(close): preserve empty reason compatibility

Ignore empty --reason occurrences so explicit empty strings continue to fall back to the default close reason and do not conflict with --reason-file. Clarify that repeated reasons map to IDs by positional index.

_codex-gpt-5.5-medium on behalf of matt wilkie_
This commit is contained in:
matt wilkie 2026-05-27 20:41:07 -07:00 • committed by GitHub
commit a180c63066
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 324 additions and 51 deletions

View file

@ -24,7 +24,12 @@ var closeCmd = &cobra.Command{
Long: `Close one or more issues.
If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation).`,
create, update, show, or close operation).
When closing multiple issues, provide one --reason for all IDs or repeat
--reason once per ID. Reasons map positionally: the first --reason applies
to the first ID, the second --reason to the second ID, regardless of where
the flags appear in the command line.`,
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
CheckReadonly("close")
@ -37,49 +42,14 @@ create, update, show, or close operation).`,
}
args = []string{lastTouched}
}
reason, _ := cmd.Flags().GetString("reason")
if reason == "" {
// Check --resolution alias (Jira CLI convention)
reason, _ = cmd.Flags().GetString("resolution")
}
if reason == "" {
// Check -m alias (git commit convention)
reason, _ = cmd.Flags().GetString("message")
}
if reason == "" {
// Check --comment alias (desire-path from hq-ftpg)
reason, _ = cmd.Flags().GetString("comment")
}
// --reason-file <path> (with - for stdin) mirrors `bd create --body-file`,
// so agents can pass structured close templates without shell-escaping hell (#3512).
if fileReason, ok, err := resolveReasonFile(cmd, reason); err != nil {
reasons, updatedArgs, err := resolveCloseReasons(cmd, args)
if err != nil {
FatalErrorRespectJSON("%v", err)
} else if ok {
reason = fileReason
}
args = updatedArgs
// Desire-path: "bd done <id> <message>" treats last positional arg as reason
// when no reason flag was explicitly provided (hq-pe8ce)
if reason == "" && cmd.CalledAs() == "done" && len(args) >= 2 {
reason = args[len(args)-1]
args = args[:len(args)-1]
}
if reason == "" {
reason = "Closed"
}
// Validate close reason if configured
closeValidation := config.GetString("validation.on-close")
if closeValidation == "error" || closeValidation == "warn" {
if err := validation.ValidateCloseReason(reason); err != nil {
if closeValidation == "error" {
FatalErrorRespectJSON("%v", err)
}
// warn mode: print warning but proceed
fmt.Fprintf(os.Stderr, "%s %v\n", ui.RenderWarn("⚠"), err)
}
if err := validateCloseReasons(reasons); err != nil {
FatalErrorRespectJSON("%v", err)
}
force, _ := cmd.Flags().GetBool("force")
@ -129,6 +99,7 @@ create, update, show, or close operation).`,
for i, id := range resolvedIDs {
result := results[i]
activeStore := result.Store
reason := reasonForCloseIndex(reasons, i)
// Get issue for checks (nil issue is handled by validateIssueClosable)
issue := result.Issue
@ -321,7 +292,7 @@ create, update, show, or close operation).`,
}
func init() {
closeCmd.Flags().StringP("reason", "r", "", "Reason for closing")
registerCloseReasonFlag(closeCmd)
closeCmd.Flags().String("resolution", "", "Alias for --reason (Jira CLI convention)")
_ = closeCmd.Flags().MarkHidden("resolution") // Hidden alias for agent/CLI ergonomics
closeCmd.Flags().StringP("message", "m", "", "Alias for --reason (git commit convention)")
@ -339,6 +310,120 @@ func init() {
rootCmd.AddCommand(closeCmd)
}
type closeReasonFlagValue struct {
values []string
}
func registerCloseReasonFlag(cmd *cobra.Command) {
cmd.Flags().VarP(&closeReasonFlagValue{}, "reason", "r", "Reason for closing")
}
func (v *closeReasonFlagValue) Set(s string) error {
v.values = append(v.values, s)
return nil
}
func (v *closeReasonFlagValue) String() string {
if len(v.values) == 0 {
return ""
}
return v.values[len(v.values)-1]
}
func (v *closeReasonFlagValue) Type() string {
return "string"
}
func (v *closeReasonFlagValue) Values() []string {
out := make([]string, len(v.values))
copy(out, v.values)
return out
}
func resolveCloseReasons(cmd *cobra.Command, args []string) ([]string, []string, error) {
reasons, err := collectCloseReasonFlags(cmd)
if err != nil {
return nil, args, err
}
if fileReason, ok, err := resolveReasonFile(cmd, len(reasons) > 0); err != nil {
return nil, args, err
} else if ok {
reasons = []string{fileReason}
}
// Desire-path: "bd done <id> <message>" treats last positional arg as reason
// when no reason flag was explicitly provided (hq-pe8ce)
if len(reasons) == 0 && cmd.CalledAs() == "done" && len(args) >= 2 {
reasons = []string{args[len(args)-1]}
args = args[:len(args)-1]
}
if len(reasons) == 0 {
reasons = []string{"Closed"}
}
if len(reasons) > 1 && len(reasons) != len(args) {
return nil, args, fmt.Errorf("got %d close reasons for %d issue IDs; provide exactly one shared reason or one reason per issue", len(reasons), len(args))
}
return reasons, args, nil
}
func collectCloseReasonFlags(cmd *cobra.Command) ([]string, error) {
if flag := cmd.Flags().Lookup("reason"); flag != nil {
if v, ok := flag.Value.(interface{ Values() []string }); ok {
if reasons := nonEmptyCloseReasons(v.Values()); len(reasons) > 0 {
return reasons, nil
}
}
}
for _, name := range []string{"resolution", "message", "comment"} {
reason, err := cmd.Flags().GetString(name)
if err != nil {
return nil, err
}
if reason != "" {
return []string{reason}, nil
}
}
return nil, nil
}
func nonEmptyCloseReasons(reasons []string) []string {
out := make([]string, 0, len(reasons))
for _, reason := range reasons {
if reason != "" {
out = append(out, reason)
}
}
return out
}
func reasonForCloseIndex(reasons []string, i int) string {
if len(reasons) == 1 {
return reasons[0]
}
return reasons[i]
}
func validateCloseReasons(reasons []string) error {
closeValidation := config.GetString("validation.on-close")
if closeValidation != "error" && closeValidation != "warn" {
return nil
}
for _, reason := range reasons {
if err := validation.ValidateCloseReason(reason); err != nil {
if closeValidation == "error" {
return err
}
// warn mode: print warning but proceed
fmt.Fprintf(os.Stderr, "%s %v\n", ui.RenderWarn("⚠"), err)
}
}
return nil
}
// isMachineCheckableGate returns true if the issue is a gate with a machine-checkable await type.
func isMachineCheckableGate(issue *types.Issue) bool {
if issue == nil || issue.IssueType != "gate" {
@ -471,11 +556,11 @@ func shouldAutoCloseCompletedRoot(root *types.Issue) bool {
// Returns an error on conflict with an existing reason, file read failure, or empty content.
// Mirrors the --body-file pattern from `bd create` so agents can pass structured close
// templates without shell-escaping hell.
func resolveReasonFile(cmd *cobra.Command, existingReason string) (string, bool, error) {
func resolveReasonFile(cmd *cobra.Command, hasExistingReason bool) (string, bool, error) {
if !cmd.Flags().Changed("reason-file") {
return "", false, nil
}
if existingReason != "" {
if hasExistingReason {
return "", false, fmt.Errorf("cannot specify both --reason-file and --reason/--resolution/--message/--comment")
}
path, _ := cmd.Flags().GetString("reason-file")

View file

@ -178,6 +178,22 @@ func TestEmbeddedClose(t *testing.T) {
}
})
t.Run("close_multiple_ids_with_per_id_reasons", func(t *testing.T) {
issue1 := bdCreate(t, bd, dir, "Multi close reason 1", "--type", "task")
issue2 := bdCreate(t, bd, dir, "Multi close reason 2", "--type", "task")
bdClose(t, bd, dir, issue1.ID, "--reason", "fixed A", issue2.ID, "--reason", "fixed B")
got1 := bdShow(t, bd, dir, issue1.ID)
got2 := bdShow(t, bd, dir, issue2.ID)
if got1.CloseReason != "fixed A" {
t.Errorf("issue1 close_reason = %q, want %q", got1.CloseReason, "fixed A")
}
if got2.CloseReason != "fixed B" {
t.Errorf("issue2 close_reason = %q, want %q", got2.CloseReason, "fixed B")
}
})
t.Run("close_already_closed", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Double close", "--type", "task")
bdClose(t, bd, dir, issue.ID)

View file

@ -3,6 +3,7 @@ package main
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
@ -17,7 +18,7 @@ func newCloseLikeCmd() *cobra.Command {
Use: "close",
Run: func(cmd *cobra.Command, args []string) {},
}
cmd.Flags().StringP("reason", "r", "", "Reason for closing")
registerCloseReasonFlag(cmd)
cmd.Flags().String("resolution", "", "")
cmd.Flags().StringP("message", "m", "", "")
cmd.Flags().String("comment", "", "")
@ -38,7 +39,7 @@ func TestCloseResolveReasonFile_FileWithContent(t *testing.T) {
t.Fatalf("parse flags: %v", err)
}
got, ok, err := resolveReasonFile(cmd, "")
got, ok, err := resolveReasonFile(cmd, false)
if err != nil {
t.Fatalf("resolveReasonFile: %v", err)
}
@ -70,7 +71,7 @@ func TestCloseResolveReasonFile_StdinDash(t *testing.T) {
t.Fatalf("parse flags: %v", err)
}
got, ok, err := resolveReasonFile(cmd, "")
got, ok, err := resolveReasonFile(cmd, false)
if err != nil {
t.Fatalf("resolveReasonFile: %v", err)
}
@ -89,7 +90,7 @@ func TestCloseResolveReasonFile_FileNotFound(t *testing.T) {
t.Fatalf("parse flags: %v", err)
}
_, ok, err := resolveReasonFile(cmd, "")
_, ok, err := resolveReasonFile(cmd, false)
if err == nil {
t.Fatal("expected error for missing file, got nil")
}
@ -116,7 +117,7 @@ func TestCloseResolveReasonFile_ConflictWithReason(t *testing.T) {
// Caller has already collected the inline reason from the various aliases,
// so we pass it in directly to mirror how close.go invokes the helper.
_, ok, err := resolveReasonFile(cmd, "from flag")
_, ok, err := resolveReasonFile(cmd, true)
if err == nil {
t.Fatal("expected conflict error, got nil")
}
@ -140,7 +141,7 @@ func TestCloseResolveReasonFile_EmptyFile(t *testing.T) {
t.Fatalf("parse flags: %v", err)
}
_, ok, err := resolveReasonFile(cmd, "")
_, ok, err := resolveReasonFile(cmd, false)
if err == nil {
t.Fatal("expected error for whitespace-only file, got nil")
}
@ -158,7 +159,7 @@ func TestCloseResolveReasonFile_FlagNotSet(t *testing.T) {
t.Fatalf("parse flags: %v", err)
}
got, ok, err := resolveReasonFile(cmd, "inline")
got, ok, err := resolveReasonFile(cmd, true)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -169,3 +170,123 @@ func TestCloseResolveReasonFile_FlagNotSet(t *testing.T) {
t.Errorf("expected empty content, got %q", got)
}
}
func TestCloseResolveReasons_PerIDReasons(t *testing.T) {
cmd := newCloseLikeCmd()
cmd.SetArgs([]string{"issue-a", "--reason", "reason A", "issue-b", "--reason", "reason B"})
var gotReasons, gotArgs []string
cmd.Run = func(cmd *cobra.Command, args []string) {
var err error
gotReasons, gotArgs, err = resolveCloseReasons(cmd, args)
if err != nil {
t.Fatalf("resolveCloseReasons: %v", err)
}
}
if err := cmd.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !slices.Equal(gotArgs, []string{"issue-a", "issue-b"}) {
t.Fatalf("args = %v, want [issue-a issue-b]", gotArgs)
}
if !slices.Equal(gotReasons, []string{"reason A", "reason B"}) {
t.Fatalf("reasons = %v, want per-ID reasons", gotReasons)
}
}
func TestCloseResolveReasons_SharedReasonForMultipleIDs(t *testing.T) {
cmd := newCloseLikeCmd()
cmd.SetArgs([]string{"issue-a", "issue-b", "--reason", "same reason"})
var gotReasons, gotArgs []string
cmd.Run = func(cmd *cobra.Command, args []string) {
var err error
gotReasons, gotArgs, err = resolveCloseReasons(cmd, args)
if err != nil {
t.Fatalf("resolveCloseReasons: %v", err)
}
}
if err := cmd.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !slices.Equal(gotArgs, []string{"issue-a", "issue-b"}) {
t.Fatalf("args = %v, want [issue-a issue-b]", gotArgs)
}
if !slices.Equal(gotReasons, []string{"same reason"}) {
t.Fatalf("reasons = %v, want one shared reason", gotReasons)
}
}
func TestCloseResolveReasons_EmptyReasonFallsBackToDefault(t *testing.T) {
cmd := newCloseLikeCmd()
cmd.SetArgs([]string{"issue-a", "--reason", ""})
var gotReasons, gotArgs []string
cmd.Run = func(cmd *cobra.Command, args []string) {
var err error
gotReasons, gotArgs, err = resolveCloseReasons(cmd, args)
if err != nil {
t.Fatalf("resolveCloseReasons: %v", err)
}
}
if err := cmd.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !slices.Equal(gotArgs, []string{"issue-a"}) {
t.Fatalf("args = %v, want [issue-a]", gotArgs)
}
if !slices.Equal(gotReasons, []string{"Closed"}) {
t.Fatalf("reasons = %v, want default reason", gotReasons)
}
}
func TestCloseResolveReasons_EmptyReasonDoesNotConflictWithReasonFile(t *testing.T) {
tmp := t.TempDir()
path := filepath.Join(tmp, "reason.md")
if err := os.WriteFile(path, []byte("from file"), 0644); err != nil {
t.Fatalf("write fixture: %v", err)
}
cmd := newCloseLikeCmd()
cmd.SetArgs([]string{"issue-a", "--reason", "", "--reason-file", path})
var gotReasons, gotArgs []string
cmd.Run = func(cmd *cobra.Command, args []string) {
var err error
gotReasons, gotArgs, err = resolveCloseReasons(cmd, args)
if err != nil {
t.Fatalf("resolveCloseReasons: %v", err)
}
}
if err := cmd.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !slices.Equal(gotArgs, []string{"issue-a"}) {
t.Fatalf("args = %v, want [issue-a]", gotArgs)
}
if !slices.Equal(gotReasons, []string{"from file"}) {
t.Fatalf("reasons = %v, want file reason", gotReasons)
}
}
func TestCloseResolveReasons_RejectsMismatchedPerIDReasons(t *testing.T) {
cmd := newCloseLikeCmd()
cmd.SetArgs([]string{"issue-a", "--reason", "reason A", "issue-b", "--reason", "reason B", "issue-c"})
cmd.Run = func(cmd *cobra.Command, args []string) {
_, _, err := resolveCloseReasons(cmd, args)
if err == nil {
t.Fatal("expected mismatch error, got nil")
}
if !strings.Contains(err.Error(), "2 close reasons for 3 issue IDs") {
t.Fatalf("unexpected error: %v", err)
}
}
if err := cmd.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
}

View file

@ -28,6 +28,32 @@ func TestEmbeddedReady(t *testing.T) {
// ===== Default =====
t.Run("ready_includes_open_issue_with_zero_dependencies", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "GH3268 zero dependency ready issue", "--type", "task", "--label", "gh3268-zero-deps")
cmd := exec.Command(bd, "ready", "--json", "--label", "gh3268-zero-deps")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd ready --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
}
var ready []types.IssueWithCounts
if err := json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &ready); err != nil {
t.Fatalf("parse ready JSON: %v\n%s", err, stdout.String())
}
if len(ready) != 1 {
t.Fatalf("ready count = %d, want 1: %s", len(ready), stdout.String())
}
if ready[0].ID != issue.ID {
t.Fatalf("ready ID = %s, want %s", ready[0].ID, issue.ID)
}
if ready[0].DependencyCount != 0 {
t.Fatalf("dependency_count = %d, want 0", ready[0].DependencyCount)
}
})
t.Run("ready_default", func(t *testing.T) {
cmd := exec.Command(bd, "ready")
cmd.Dir = dir

View file

@ -346,6 +346,11 @@ Close one or more issues.
If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation).
When closing multiple issues, provide one --reason for all IDs or repeat
--reason once per ID. Reasons map positionally: the first --reason applies
to the first ID, the second --reason to the second ID, regardless of where
the flags appear in the command line.
```
bd close [id...] [flags]
```

View file

@ -15,6 +15,11 @@ Close one or more issues.
If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation).
When closing multiple issues, provide one --reason for all IDs or repeat
--reason once per ID. Reasons map positionally: the first --reason applies
to the first ID, the second --reason to the second ID, regardless of where
the flags appear in the command line.
```
bd close [id...] [flags]
```

View file

@ -2569,6 +2569,11 @@ Close one or more issues.
If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation).
When closing multiple issues, provide one --reason for all IDs or repeat
--reason once per ID. Reasons map positionally: the first --reason applies
to the first ID, the second --reason to the second ID, regardless of where
the flags appear in the command line.
```
bd close [id...] [flags]
```

View file

@ -15,6 +15,11 @@ Close one or more issues.
If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation).
When closing multiple issues, provide one --reason for all IDs or repeat
--reason once per ID. Reasons map positionally: the first --reason applies
to the first ID, the second --reason to the second ID, regardless of where
the flags appear in the command line.
```
bd close [id...] [flags]
```

View file

@ -15,6 +15,11 @@ Close one or more issues.
If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation).
When closing multiple issues, provide one --reason for all IDs or repeat
--reason once per ID. Reasons map positionally: the first --reason applies
to the first ID, the second --reason to the second ID, regardless of where
the flags appear in the command line.
```
bd close [id...] [flags]
```