fix(comments): reject swapped-order comments <id> add instead of silent no-op (#4642) (#4787)

* fix(comments): reject swapped-order `comments <id> add` instead of no-op

`bd comments <issue-id> add <text>` (issue id before the `add` subcommand)
fell through to the parent `comments` command, which reads only args[0] as
the issue id and silently drops the rest — listing existing comments and
exiting 0 without ever writing the intended comment (GH#4642). In scripted
or agent pipelines this reads as a successful add and is only caught by
re-listing.

The parent command only lists comments for a single issue, so any trailing
positional arg is a mistake. Reject it with a clear error; the common
swapped-`add` case gets a targeted hint pointing at `bd comments add <id>
<text>`.

Adds embedded regression tests covering the swapped-order add (must exit
non-zero and store nothing) and a generic stray trailing arg.

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

* fix(comments): move swapped-order rejection into a pre-open Args validator (PR #4787 review follow-up)

The 2026-07-24 maintainer review found two blockers with the RunE-only
check: (1) it runs after PersistentPreRunE, so the malformed invocation
this PR exists to catch could still trigger migration work, hit the
remote-migrate gate, or die with "no database found" before the helpful
hint ever printed — the embedded tests use an already-initialized store,
so they couldn't see this; and (2) merge-base drift means current main
dispatches proxied mode to a real runCommentsProxiedServer (added after
this PR branched) that reads only args[0] and ignores trailing `add
<text>`, so the RunE-only check never runs for that path.

One fix for both, per the review: moved the swapped-order/stray-trailing-arg
rejection into validateCommentsArgs, wired as commentsCmd.Args. Cobra runs
Args validation before PersistentPreRunE and before RunE's
usesProxiedServer() branch, so the rejection now fires identically for
every backend, before any store open, migration, or proxied dispatch.

Added two regression tests: TestCLI_CommentsSwappedAddRejectedBeforeStoreOpen
runs in a directory with no .beads/ at all to prove the store is never
touched, and TestCLI_CommentsSwappedAddRejectedInProxiedServerMode forces
proxiedServerMode to cover the proxied path without needing a real proxied
server. The existing embedded regression tests (comments_swapped_add_rejected,
comments_extra_arg_rejected) still pass unchanged.

Agent-Signature: claude-fable-5-medium on behalf of maphew

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: matt wilkie <maphew@gmail.com>
This commit is contained in:
Harry Miller 2026-07-26 13:41:08 -07:00 • committed by GitHub
commit e2dd121f4f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 134 additions and 1 deletions

View file

@ -1189,6 +1189,62 @@ func TestCLI_CommentsListMisplacedSyntax(t *testing.T) {
}
}
// TestCLI_CommentsSwappedAddRejectedBeforeStoreOpen is a regression test for
// GH#4642's should-fix: the swapped-order rejection (`bd comments <id> add
// <text>`) must fire from commentsCmd's Args validator, before
// PersistentPreRunE ever opens a store or runs a migration, and before
// RunE's usesProxiedServer() dispatch — not from a check inside RunE that
// only the local-store branch reaches. Using a directory with no .beads/ at
// all proves the store was never touched: the old RunE-only check needed an
// already-initialized store (PersistentPreRunE would have failed first with
// "no beads database found"), so this would fail with the wrong error before
// the fix.
func TestCLI_CommentsSwappedAddRejectedBeforeStoreOpen(t *testing.T) {
noBeadsCwd := t.TempDir()
if _, err := os.Stat(filepath.Join(noBeadsCwd, ".beads")); err == nil {
t.Fatalf("test setup: %s unexpectedly has a .beads dir", noBeadsCwd)
}
stdout, stderr, err := runBDInProcessAllowError(t, noBeadsCwd, "comments", "bd-123", "add", "should not be stored")
if err == nil {
t.Fatalf("expected non-zero exit for swapped-order add, got success:\nstdout: %s", stdout)
}
combined := stdout + stderr
if strings.Contains(combined, "no beads database found") {
t.Fatalf("Args validation did not run before store open: got the pre-fix error.\nOutput:\n%s", combined)
}
if !strings.Contains(combined, "bd comments add") {
t.Errorf("expected hint pointing to `bd comments add`, got:\n%s", combined)
}
}
// TestCLI_CommentsSwappedAddRejectedInProxiedServerMode is the proxied-server
// counterpart: forcing proxiedServerMode simulates the dispatch that GH#4642's
// merge-base drift routes around a RunE-only check (main added
// runCommentsProxiedServer after this fix branched, consuming only args[0]
// and ignoring trailing `add <text>`). Because validateCommentsArgs runs in
// Args — before RunE ever branches on usesProxiedServer() — the rejection
// fires identically regardless of backend, without needing a real proxied
// server.
func TestCLI_CommentsSwappedAddRejectedInProxiedServerMode(t *testing.T) {
origProxied := proxiedServerMode
t.Cleanup(func() { proxiedServerMode = origProxied })
proxiedServerMode = true
tmpDir := setupCLITestDB(t)
stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "bd-123", "add", "should not be stored")
if err == nil {
t.Fatalf("expected non-zero exit for swapped-order add in proxied-server mode, got success:\nstdout: %s", stdout)
}
combined := stdout + stderr
if strings.Contains(combined, "not supported in proxied-server mode") {
t.Fatalf("Args validation did not run before the proxied dispatch: got RunE's proxied-mode stub error instead.\nOutput:\n%s", combined)
}
if !strings.Contains(combined, "bd comments add") {
t.Errorf("expected hint pointing to `bd comments add`, got:\n%s", combined)
}
}
// TestCLI_CommentsAddShortID tests that 'comments add' accepts short IDs (issue #1070)
// Most bd commands accept short IDs (e.g., "5wbm") but comments add previously required
// full IDs (e.g., "mike.vibe-coding-5wbm"). This test ensures short IDs work.

View file

@ -11,6 +11,48 @@ import (
"github.com/steveyegge/beads/internal/uimd"
)
// validateCommentsArgs runs as cobra's Args validation for the parent
// "comments" command, which executes before PersistentPreRunE opens the
// store (or runs migrations) and before RunE's usesProxiedServer() dispatch.
// The parent command only lists comments for a single issue, so any trailing
// positional arg is a mistake — most commonly the swapped-order add,
// `bd comments <id> add <text>`, which otherwise falls through, reads only
// args[0], and silently drops the rest with exit 0 (GH#4642). Validating
// here (rather than inside RunE, local-store-only) rejects the malformed
// invocation identically for the direct and proxied-server paths, before
// either one can open a store, run a migration, or hit the remote-migrate
// gate for an invocation that is guaranteed to fail.
func validateCommentsArgs(cmd *cobra.Command, args []string) error {
if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {
return err
}
if len(args) <= 1 {
return nil
}
issueID := args[0]
if args[1] == "add" {
return HandleErrorRespectJSON(`"bd comments <issue-id> add ..." is not valid — the subcommand must come first.
To add a comment, run:
bd comments add <issue-id> <text>
Example:
bd comments add %s "your comment"
See: bd comments --help`, issueID)
}
return HandleErrorRespectJSON(`"bd comments" takes a single issue id and lists its comments.
To list comments:
bd comments <issue-id>
To add a comment:
bd comments add <issue-id> <text>
See: bd comments --help`)
}
var commentsCmd = &cobra.Command{
Use: "comments [issue-id]",
GroupID: "issues",
@ -29,7 +71,7 @@ Examples:
# Add a comment from a file
bd comments add bd-123 -f notes.txt`,
Args: cobra.MinimumNArgs(1),
Args: validateCommentsArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {

View file

@ -92,6 +92,41 @@ func TestEmbeddedCommentsCLI(t *testing.T) {
}
})
// Swapped-order add (`bd comments <id> add <text>`) must be rejected, not
// silently dropped with exit 0 (GH#4642).
t.Run("comments_swapped_add_rejected", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Swapped add target", "--type", "task")
cmd := exec.Command(bd, "comments", issue.ID, "add", "should not be stored")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected non-zero exit for swapped-order add, got success:\n%s", out)
}
if !strings.Contains(string(out), "bd comments add") {
t.Errorf("expected hint pointing to `bd comments add`, got:\n%s", out)
}
// The stray "add"/text must NOT have been written as a comment.
list := bdComments(t, bd, dir, issue.ID)
if strings.Contains(list, "should not be stored") {
t.Errorf("swapped-order add silently stored a comment:\n%s", list)
}
})
// Any other stray trailing arg on the list form is also rejected.
t.Run("comments_extra_arg_rejected", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Extra arg target", "--type", "task")
cmd := exec.Command(bd, "comments", issue.ID, "stray")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected non-zero exit for stray trailing arg, got success:\n%s", out)
}
})
// ===== comments list =====
t.Run("comments_list", func(t *testing.T) {