diff --git a/CHANGELOG.md b/CHANGELOG.md index 754391433..d291eb727 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -166,6 +166,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 (default 24h) controls how often the pause is re-announced. Manual `bd backup` / `bd backup sync` are not capped. +- **`bd comment`/`bd comments add` refuse an abbreviated id and a reserved + word instead of silently resolving one to the wrong issue** + ([#5393](https://github.com/gastownhall/beads/pull/5393)). `bd comment list + `, a typo for `bd comments list`, used to parse as id="list" with no + guard on the id slot — and since no issue is ever literally named "list", + the default abbreviation-tolerant resolver would fuzzy-match it against + whatever existing bead or wisp id happened to start with "list" and write + the rest of the command line there as a comment. Confirmed in production: + 15+ automated sessions made this exact typo over two days and all landed on + the same unrelated wisp. `bd comment`'s id positional now (a) refuses the + four words a `bd comments ` typo is likely to produce — `list`, `add`, + `rm`, `delete` — before any id resolution is attempted, on both the + embedded and proxied-server paths, and (b) requires an EXACT id match + (`bd-a1b2c3d4`, not `a1b2`) rather than the abbreviation-tolerant matching + every other command keeps. The refusal message is truthful about which + case applies: a reserved word gets a hint toward `bd comments`; an + abbreviation of a REAL issue gets `id abbreviations are not accepted on + comment writes; use the full id from \`bd show \`` rather than the + generic (and in that case false) "no issue found matching" text a genuine + not-found gets. See [Working with + IDs](docs/core-concepts/hash-ids.md#working-with-ids) for the full + read/write distinction. The proxied-server comment path was investigated + separately and found to already be exact-id-only by construction (its + resolution never performed abbreviation matching in the first place) — a + regression test now locks that in rather than leaving it undocumented. + - **`bd doctor` no longer flags a `.local_version` that starts with `v`.** The canonical spelling of a Go module version — and the string a build stamped from a Go pseudo-version reports and writes into `.local_version` itself — diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index a08de0d9a..e6045c935 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -559,7 +559,10 @@ go_test( "command_telemetry_test.go", "comment_promote_embedded_test.go", "comment_proxied_integration_test.go", + "comment_reserved_word_test.go", + "comment_routed_exact_test.go", "comment_test.go", + "comments_add_test.go", "comments_cli_embedded_test.go", "comments_test.go", "compact_embedded_test.go", diff --git a/cmd/bd/cli_fast_test.go b/cmd/bd/cli_fast_test.go index 92d96cfcb..93f179d3a 100644 --- a/cmd/bd/cli_fast_test.go +++ b/cmd/bd/cli_fast_test.go @@ -1525,11 +1525,13 @@ func TestCLI_CommentsSwappedAddRejectedInProxiedServerMode(t *testing.T) { } } -// 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. -// -// Note: Short IDs work because the code calls utils.ResolvePartialID(). +// TestCLI_CommentsAddShortID tests that 'comments add' accepts a bare full +// hash without its issue prefix (e.g. "5wbm" for "mike.vibe-coding-5wbm", +// issue #1070) — full IDs used to be required. It does NOT test genuine +// abbreviation (a hash shorter than the real one): since PR #5393, comment +// writes require an exact id (see resolveAndGetIssueForMutationExact / +// utils.ResolvePartialIDExact) and PartialIDWithCommentsAdd below asserts +// that a real abbreviation is refused, not accepted. func TestCLI_CommentsAddShortID(t *testing.T) { t.Run("ShortIDWithCommentsAdd", func(t *testing.T) { @@ -1582,6 +1584,14 @@ func TestCLI_CommentsAddShortID(t *testing.T) { } }) + // PartialIDWithCommentsAdd used to assert that a genuinely abbreviated id + // (shorter than the full hash) succeeded on "comments add" — true when + // this test was written (issue #1070), but no longer the contract: PR + // #5393 review item M1 established that "comments add" must refuse an + // abbreviation exactly like "comment" (singular) does (see + // TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage), since the two + // are documented as guarded twins (CHANGELOG.md, hash-ids.md). This + // subtest now asserts the refusal instead of the old silent-accept. t.Run("PartialIDWithCommentsAdd", func(t *testing.T) { tmpDir := setupCLITestDB(t) @@ -1595,22 +1605,53 @@ func TestCLI_CommentsAddShortID(t *testing.T) { json.Unmarshal([]byte(jsonOut), &issue) fullID := issue["id"].(string) - // Extract short ID and use only first 4 characters (partial match) + // Derive the abbreviation as a strict, one-character-shorter leading + // prefix of the real hash — the same derivation + // comment_proxied_integration_test.go:247 already uses. The previous + // "truncate to 4 chars, only if longer than 4" logic never fired + // against a fresh test DB's fixture hashes (min_hash_length unset, + // hashes as short as 3 chars), so shortID stayed equal to the full + // hash and this subtest was dead-red in its own setup, never reaching + // the assertions below (PR #5393 review R2, bee-ghosttrack) — and + // mutation P-B (reverting comments.go's resolver back to the + // abbreviation-tolerant one) went uncaught as a result. parts := strings.Split(fullID, "-") - shortID := parts[len(parts)-1] - if len(shortID) > 4 { - shortID = shortID[:4] // Use only first 4 chars for partial match + hash := parts[len(parts)-1] + if len(hash) < 2 { + t.Fatalf("test setup: hash %q too short to abbreviate", hash) } + shortID := hash[:len(hash)-1] t.Logf("Full ID: %s, Partial ID: %s", fullID, shortID) - // Add comment using partial ID - stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", shortID, "Comment via partial ID") + // Sanity check: the same abbreviation still works on a READ path + // (show), proving this is a real, resolvable abbreviation and not an + // accident of the fixture — the refusal below is specific to writes. + showOut, showErr, err := runBDInProcessAllowError(t, tmpDir, "show", shortID, "--json") if err != nil { - t.Fatalf("comments add with partial ID failed: %v\nstdout: %s\nstderr: %s", err, stdout, stderr) + t.Fatalf("fixture sanity check failed: 'bd show %s' unexpectedly failed: %v\nstdout: %s\nstderr: %s", shortID, err, showOut, showErr) + } + if !strings.Contains(showOut, fullID) { + t.Fatalf("fixture sanity check failed: 'bd show %s' did not resolve to %s, got: %s", shortID, fullID, showOut) } - if !strings.Contains(stdout, "Comment added") { - t.Errorf("Expected 'Comment added' in output, got: %s", stdout) + // Add comment using partial ID — must now be refused, truthfully. + stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", shortID, "Comment via partial ID") + if err == nil { + t.Fatalf("expected non-zero exit for 'bd comments add %s ...' (abbreviation on a write path), got stdout=%q stderr=%q", shortID, stdout, stderr) + } + combined := stdout + stderr + if !strings.Contains(combined, "abbreviations are not accepted") { + t.Errorf("expected the truthful abbreviation-refusal message, got stdout=%q stderr=%q", stdout, stderr) + } + if strings.Contains(combined, "not found") { + t.Errorf("message must not claim the issue was not found — %s exists, only the abbreviation was refused; got stdout=%q stderr=%q", fullID, stdout, stderr) + } + + // Regression check: no comment silently landed on the real issue. + commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json") + trimmed := strings.TrimSpace(commentsOut) + if trimmed != "[]" && trimmed != "null" { + t.Fatalf("expected no comments on %s after rejected abbreviated 'comments add', got: %s", fullID, commentsOut) } }) @@ -1810,6 +1851,176 @@ func TestCLI_CommentTextStartingWithReservedWordStillWorks(t *testing.T) { } } +// TestCLI_CommentRmDeleteReservedWordsRejected covers the two reserved words +// TestCLI_CommentListMisplacedSyntax/TestCLI_CommentAddMisplacedSyntax do not: +// "rm" and "delete" carry no hand-written case in validateCommentArgs (unlike +// "list"/"add"), so they fall through to checkCommentIDNotReservedWord's +// generic message and, before this test, had no CLI-level (cobra-dispatch) +// coverage at all — steveyegge's PR #5393 review (item a) flagged that +// generic message as potentially misleading for these two specifically, since +// neither is an actual "bd comments" subcommand the way "list"/"add" are. +// This pins both halves: the command is rejected, AND — the part that +// actually matters — no comment silently lands on an unrelated real issue. +func TestCLI_CommentRmDeleteReservedWordsRejected(t *testing.T) { + t.Parallel() + + for _, word := range []string{"rm", "delete"} { + t.Run(word, func(t *testing.T) { + t.Parallel() + tmpDir := setupCLITestDB(t) + + out := runBDInProcess(t, tmpDir, "create", "Bystander issue for "+word+"-typo", "-p", "1", "--json") + jsonStart := strings.Index(out, "{") + if jsonStart < 0 { + t.Fatalf("No JSON found in create output: %s", out) + } + var issue map[string]interface{} + if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil { + t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out) + } + fullID := issue["id"].(string) + + stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", word, "accidental stray text") + if err == nil { + t.Fatalf("expected non-zero exit for 'bd comment %s ...', got stdout=%q stderr=%q", word, stdout, stderr) + } + combined := stdout + stderr + // Must be refused as an id/reserved word — but, unlike "list"/"add", + // must NOT claim it is a misplaced "bd comments" subcommand: there is + // no "bd comments rm" or "bd comments delete". + if !strings.Contains(combined, "not a valid issue id") { + t.Errorf("expected a not-a-valid-issue-id refusal, got stdout=%q stderr=%q", stdout, stderr) + } + if strings.Contains(combined, "misplaced") { + t.Errorf("message falsely implies %q is a misplaced \"bd comments\" subcommand (it isn't one), got stdout=%q stderr=%q", word, stdout, stderr) + } + + // The regression check: the bystander issue must have received NO + // comment. + commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json") + trimmed := strings.TrimSpace(commentsOut) + if trimmed != "[]" && trimmed != "null" { + t.Fatalf("expected no comments on bystander issue %s after rejected 'comment %s', got: %s", fullID, word, commentsOut) + } + }) + } +} + +// TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch closes PR #5393 +// review R2's "NEW MINOR — the guard's wiring is untested": comments_add_test.go +// unit-tests validateCommentsAddArgs directly, and that catches a gutted +// function body (mutation P-C), but nothing drove "bd comments add +// ..." through actual cobra dispatch — unwiring +// commentsAddCmd's Args field back to cobra.MinimumNArgs(1) left every +// existing test green (mutation P-D). This runs the real command line, the +// way a caller or an automated session actually invokes it, for every word in +// commentReservedIDWords (validateCommentsAddArgs has no singular/plural +// special-casing, unlike "comment"'s validateCommentArgs, so all four take +// the same generic-message path and are equally worth covering here). +func TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch(t *testing.T) { + t.Parallel() + + for _, word := range []string{"list", "add", "rm", "delete"} { + t.Run(word, func(t *testing.T) { + t.Parallel() + tmpDir := setupCLITestDB(t) + + out := runBDInProcess(t, tmpDir, "create", "Bystander issue for comments-add "+word+"-typo", "-p", "1", "--json") + jsonStart := strings.Index(out, "{") + if jsonStart < 0 { + t.Fatalf("No JSON found in create output: %s", out) + } + var issue map[string]interface{} + if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil { + t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out) + } + fullID := issue["id"].(string) + + stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comments", "add", word, "accidental stray text") + if err == nil { + t.Fatalf("expected non-zero exit for 'bd comments add %s ...', got stdout=%q stderr=%q", word, stdout, stderr) + } + combined := stdout + stderr + if !strings.Contains(combined, "not a valid issue id") { + t.Errorf("expected a not-a-valid-issue-id refusal, got stdout=%q stderr=%q", stdout, stderr) + } + + // The regression check: the bystander issue must have received NO + // comment — this is exactly what unwiring commentsAddCmd.Args back + // to cobra.MinimumNArgs(1) would silently allow through. + commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json") + trimmed := strings.TrimSpace(commentsOut) + if trimmed != "[]" && trimmed != "null" { + t.Fatalf("expected no comments on bystander issue %s after rejected 'comments add %s', got: %s", fullID, word, commentsOut) + } + }) + } +} + +// TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage is the CLI-level +// regression test for steveyegge's PR #5393 review item (c): a leading-prefix +// abbreviation of a REAL issue's id is refused on comment writes (exact-only +// policy, unchanged), but the refusal message must not claim the issue does +// not exist — it does, the abbreviation was just refused. Before this fix, +// resolveAndGetIssueForMutationExact surfaced ResolvePartialIDExact's plain +// "no issue found matching %q", which is false in exactly this case; every +// other command family (show/close/update) still accepts the same +// abbreviation, so a truthful, distinguishing message matters here more than +// most refusals. +func TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage(t *testing.T) { + t.Parallel() + + tmpDir := setupCLITestDB(t) + + out := runBDInProcess(t, tmpDir, "create", "Needs an exact id on comment", "-p", "1", "--json") + jsonStart := strings.Index(out, "{") + if jsonStart < 0 { + t.Fatalf("No JSON found in create output: %s", out) + } + var issue map[string]interface{} + if err := json.Unmarshal([]byte(out[jsonStart:]), &issue); err != nil { + t.Fatalf("Failed to parse create JSON: %v\nOutput: %s", err, out) + } + fullID := issue["id"].(string) + if len(fullID) < 4 { + t.Fatalf("test setup: generated id %q too short to abbreviate", fullID) + } + abbrev := fullID[:len(fullID)-1] + + // Sanity check: the same abbreviation still works on a READ path (show), + // proving this is a real, resolvable abbreviation and not an accident of + // the fixture — the gap this test guards is specific to comment WRITES. + showOut, showErr, err := runBDInProcessAllowError(t, tmpDir, "show", abbrev, "--json") + if err != nil { + t.Fatalf("fixture sanity check failed: 'bd show %s' unexpectedly failed: %v\nstdout: %s\nstderr: %s", abbrev, err, showOut, showErr) + } + if !strings.Contains(showOut, fullID) { + t.Fatalf("fixture sanity check failed: 'bd show %s' did not resolve to %s, got: %s", abbrev, fullID, showOut) + } + + stdout, stderr, err := runBDInProcessAllowError(t, tmpDir, "comment", abbrev, "should not be written") + if err == nil { + t.Fatalf("expected non-zero exit for 'bd comment %s ...' (abbreviation on a write path), got stdout=%q stderr=%q", abbrev, stdout, stderr) + } + combined := stdout + stderr + if !strings.Contains(combined, "abbreviations are not accepted") { + t.Errorf("expected the truthful abbreviation-refusal message, got stdout=%q stderr=%q", stdout, stderr) + } + if !strings.Contains(combined, "bd show") { + t.Errorf("expected the message to point at the full id via `bd show`, got stdout=%q stderr=%q", stdout, stderr) + } + if strings.Contains(combined, "not found") { + t.Errorf("message must not claim the issue was not found — %s exists, only the abbreviation was refused; got stdout=%q stderr=%q", fullID, stdout, stderr) + } + + // The regression check: no comment silently landed on the real issue. + commentsOut := runBDInProcess(t, tmpDir, "comments", fullID, "--json") + trimmed := strings.TrimSpace(commentsOut) + if trimmed != "[]" && trimmed != "null" { + t.Fatalf("expected no comments on %s after rejected abbreviated 'comment', got: %s", fullID, commentsOut) + } +} + // TestCLI_CreateRejectsFlagLikeTitles verifies that positional arguments starting // with - or -- are rejected as likely misinterpreted flags (bd-2c0). func TestCLI_CreateRejectsFlagLikeTitles(t *testing.T) { diff --git a/cmd/bd/close.go b/cmd/bd/close.go index d4ceda333..816314fff 100644 --- a/cmd/bd/close.go +++ b/cmd/bd/close.go @@ -843,7 +843,7 @@ func resolveCloseTargets(ctx context.Context, localStore storage.DoltStorage, id // Write-intent: a prefix-routed target opens writable so the close // commits on the target head (#4141). Contributor auto-routing below // stays read-only: it hydrates foreign projects that must not be mutated. - if r, err := resolveViaPrefixRoutingWithAccess(ctx, id, true); err == nil { + if r, err := resolveViaPrefixRoutingWithAccess(ctx, id, true, false); err == nil { results = append(results, r) continue } diff --git a/cmd/bd/comment.go b/cmd/bd/comment.go index ac1d9e737..15f577e7c 100644 --- a/cmd/bd/comment.go +++ b/cmd/bd/comment.go @@ -1,13 +1,60 @@ package main import ( + "errors" "fmt" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/internal/utils" ) +// commentReservedIDWords are "comments" subcommand names that must never be +// silently accepted as the positional of "bd comment" (singular). They +// exist so a typo'd plural form — "bd comment list ", meant to be +// "bd comments list" / "bd comments " — fails loudly instead of treating +// "list" as the id and the real id as comment text. +// +// This is not a hypothetical: 15+ automated sessions in one deployment made +// exactly this typo over two days, and because "list" happened to be a +// leading-prefix abbreviation of an unrelated wisp's hash ("list3t0"), each +// one silently wrote a garbage comment onto that wisp instead of erroring. +// The word list mirrors the real "comments" subcommand (add) plus the other +// verbs a "comments " typo is likely to produce. +var commentReservedIDWords = map[string]bool{ + "list": true, + "add": true, + "rm": true, + "delete": true, +} + +// checkCommentIDNotReservedWord rejects an id argument that is one of +// commentReservedIDWords, with a message pointing at the "bd comments" +// subcommand the caller most likely meant. Pure and side-effect free so it +// can run before either the direct or proxied-server RunE branch, and be +// unit tested without a store. +func checkCommentIDNotReservedWord(id string) error { + if !commentReservedIDWords[id] { + return nil + } + // "list" and "add" are genuinely misplaced "bd comments" subcommands, but + // "rm" and "delete" are not — there is no "bd comments rm"/"bd comments + // delete" (they read as bd's own delete command, or "dep rm"'s pattern, + // used in the wrong place). The message below must hold for all four, so + // it says "reserved word", never "misplaced bd comments subcommand". + return HandleErrorRespectJSON(`%q is not a valid issue id — bd reserves it as a command/subcommand word (a real id never collides with one), so it is refused as an id instead of silently resolved as one. + +To comment on an issue: + bd comment "text" + bd comments add "text" + +To list comments: + bd comments + +See: bd comment --help`, id) +} + // validateCommentArgs runs as cobra's Args validation for the singular // "comment" shorthand, before RunE's usesProxiedServer() dispatch and (on // the local/embedded path) before the id ever reaches ResolvePartialID's @@ -45,7 +92,15 @@ To add a comment: See: bd comment --help`) } - return nil + // The two cases above carry hand-written messages for the two typos that + // were actually reported, both real "bd comments" subcommands. The + // remaining reserved words ("rm", "delete") are not "bd comments" + // subcommands — they collide with words bd uses elsewhere ("bd delete", + // "dep rm") — so they get checkCommentIDNotReservedWord's word-agnostic + // generic message instead of a claim that would be false for them. + // Keeping the whole set in commentReservedIDWords also keeps the check + // unit-testable on its own. + return checkCommentIDNotReservedWord(args[0]) } var commentCmd = &cobra.Command{ @@ -96,11 +151,18 @@ To list comments on an issue, use the plural form: bd comments `, ctx := rootCtx - result, err := resolveAndGetIssueForMutation(ctx, store, id) + result, err := resolveAndGetIssueForMutationExact(ctx, store, id) if err != nil { if result != nil { result.Close() } + if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + // The issue does exist — id just isn't its full form — so + // "resolving %s: %v"'s generic wording (and the "no issue + // found matching" text underneath a plain not-found) would be + // false here. Say what actually happened instead. + return HandleErrorRespectJSON("id abbreviations are not accepted on comment writes; use the full id from `bd show %s`", id) + } return HandleErrorRespectJSON("resolving %s: %v", id, err) } if result == nil || result.Issue == nil { diff --git a/cmd/bd/comment_proxied_integration_test.go b/cmd/bd/comment_proxied_integration_test.go index 4885d8461..4875a5889 100644 --- a/cmd/bd/comment_proxied_integration_test.go +++ b/cmd/bd/comment_proxied_integration_test.go @@ -216,6 +216,75 @@ func TestProxiedServerComment(t *testing.T) { } }) + // TestProxiedServerComment/comment_write_never_resolves_abbreviated_id is + // the "document/test the gap explicitly" half of steveyegge's PR #5393 + // review item (b): "the proxied-server path is untouched by the + // exact-match fix... extend exact matching to that path, or document/test + // the gap explicitly." + // + // Investigation (not just this test) found there is no gap to extend + // matching to: resolveCommentTargetProxied (comments_proxied_server.go) + // resolves via workapi.GetIssueOrWisp with the RAW id, which bottoms out + // in issueSQLRepositoryImpl.Get's plain "WHERE id = ?" (SQL exact + // equality — internal/storage/domain/db/issue.go). Unlike the embedded + // path (resolveAndGetIssueWithRouting -> utils.ResolvePartialID), nothing + // in this call chain ever performed leading-prefix abbreviation matching + // — comment's proxied writes were exact-id-only before PR #5393 and + // remain so. This test locks that in as a regression guard: an + // abbreviation of a REAL issue's id must be refused (not silently + // resolved to it, and not silently resolved to an unrelated bystander + // issue) when running against a real proxied server, the same way it + // already is against the embedded store. + t.Run("comment_write_never_resolves_abbreviated_id", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "pa") + target := bdProxiedCreate(t, bd, p.dir, "Needs exact id on comment (proxied)") + bystander := bdProxiedCreate(t, bd, p.dir, "Bystander issue (proxied)") + + if len(target.ID) < 4 { + t.Fatalf("test setup: generated id %q too short to abbreviate", target.ID) + } + abbrev := target.ID[:len(target.ID)-1] + + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "comment", abbrev, "should not land anywhere") + if err == nil { + t.Fatalf("bd comment %s unexpectedly succeeded in proxied mode\nstdout:\n%s\nstderr:\n%s", abbrev, stdout, stderr) + } + // Asserted as the whole message, not strings.Contains(id): the proxied + // route resolves through one exact "WHERE id = ?", so it cannot tell an + // abbreviation of a real issue from an id that names nothing, and it + // deliberately keeps the same "not found" wording for both — where the + // embedded route says "id abbreviations are not accepted on comment + // writes" (comment.go). Giving the proxied plane the truthful wording + // would mean probing for abbreviation matches on a write path, which is + // the resolution behaviour this PR exists to remove. A Contains(id) + // assertion passes on either wording, so it would leave that asymmetry + // untested; pinning the exact text makes it a deliberate choice that + // breaks loudly if either side moves. + if got, want := strings.TrimSpace(stderr), "Error: issue "+abbrev+" not found"; got != want { + t.Errorf("abbreviated-ID stderr = %q, want %q", got, want) + } + if stdout != "" { + t.Errorf("abbreviated-ID stdout = %q, want empty", stdout) + } + + // The regression check: neither the abbreviation's real target nor an + // unrelated bystander received a comment. + for _, id := range []string{target.ID, bystander.ID} { + commentsOut, commentsErr, cErr := bdProxiedRunBuffers(t, bd, p.dir, "comments", "--json", id) + if cErr != nil { + t.Fatalf("bd comments --json %s failed: %v\nstdout:\n%s\nstderr:\n%s", id, cErr, commentsOut, commentsErr) + } + var comments []types.Comment + if err := json.Unmarshal([]byte(commentsOut), &comments); err != nil { + t.Fatalf("decode comments JSON for %s: %v\nraw: %q", id, err, commentsOut) + } + if len(comments) != 0 { + t.Fatalf("expected no comments on %s after rejected abbreviated 'comment', got: %v", id, comments) + } + } + }) + t.Run("wisp_comments_add_round_trip_and_physical_routing", func(t *testing.T) { t.Parallel() p := newSharedProxiedProject(t, bd, "wa") diff --git a/cmd/bd/comment_reserved_word_test.go b/cmd/bd/comment_reserved_word_test.go new file mode 100644 index 000000000..ed67ba2fc --- /dev/null +++ b/cmd/bd/comment_reserved_word_test.go @@ -0,0 +1,46 @@ +package main + +import ( + "strings" + "testing" +) + +// TestCheckCommentIDNotReservedWord covers a real incident: "bd comment list +// ", a typo for "bd comments list", must be rejected before any id +// resolution is attempted — not silently treat "list" as the id. +func TestCheckCommentIDNotReservedWord(t *testing.T) { + reserved := []string{"list", "add", "rm", "delete"} + for _, word := range reserved { + t.Run("rejects reserved word "+word, func(t *testing.T) { + var err error + stderr := captureStderr(t, func() { + err = checkCommentIDNotReservedWord(word) + }) + if err == nil { + t.Fatalf("checkCommentIDNotReservedWord(%q) = nil; want error", word) + } + if !strings.Contains(stderr, "bd comments") { + t.Errorf("checkCommentIDNotReservedWord(%q) printed %q; want a hint mentioning bd comments", word, stderr) + } + }) + } + + happyPath := []string{ + "bd-123", + "a3f8e9", + "ga-wisp-list3t0", // full id containing "list" as a substring must NOT be rejected + "listicle-42", // starts with "list" but is not the literal reserved word + "LIST", // reserved-word check is intentionally case-sensitive: real ids are lowercase hashes + } + for _, id := range happyPath { + t.Run("allows real id "+id, func(t *testing.T) { + var err error + captureStderr(t, func() { + err = checkCommentIDNotReservedWord(id) + }) + if err != nil { + t.Errorf("checkCommentIDNotReservedWord(%q) = %v; want nil (happy path must stay intact)", id, err) + } + }) + } +} diff --git a/cmd/bd/comment_routed_exact_test.go b/cmd/bd/comment_routed_exact_test.go new file mode 100644 index 000000000..e20b70dee --- /dev/null +++ b/cmd/bd/comment_routed_exact_test.go @@ -0,0 +1,127 @@ +//go:build cgo + +package main + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/utils" +) + +// TestResolveAndGetIssueForMutationExactSurfacesRoutedAbbreviationRefusal pins +// the error SELECTION in resolveAndGetIssueForMutationExact, the one part of +// the exact-match contract the rest of this PR's tests cannot reach: they all +// exercise the LOCAL tier, where the refusal is the function's own return +// value. A cross-rig or auto-routed tier mints the same sentinel, and the +// truthful message the comment write paths print (comment.go, comments.go) +// depends on errors.Is seeing it from there too. +// +// The setup is the shape the sentinel exists for: the local store genuinely +// knows nothing about the id, so its error is the plain "no issue found +// matching" — which is FALSE here, because prefix routing finds the +// abbreviation's real target in the other rig and refuses it there. +// +// Both directions are pinned, because either assertion alone passes for the +// wrong reason: an abbreviation of a routed issue must select the ROUTED +// refusal over the local not-found, and an id that names nothing anywhere +// must still come back as a plain not-found rather than claiming an +// abbreviation exists. +// +// NOTE: assigns the dbPath global and uses os.Chdir, so it cannot run in +// parallel (same constraint as TestCheckBeadGateCrossRigPrefixRoute). +func TestResolveAndGetIssueForMutationExactSurfacesRoutedAbbreviationRefusal(t *testing.T) { + ctx := context.Background() + townRoot := t.TempDir() + townBeadsDir := filepath.Join(townRoot, ".beads") + rigBeadsDir := filepath.Join(townRoot, "rig", ".beads") + if err := os.MkdirAll(townBeadsDir, 0o755); err != nil { + t.Fatalf("create town beads dir: %v", err) + } + if err := os.MkdirAll(rigBeadsDir, 0o755); err != nil { + t.Fatalf("create rig beads dir: %v", err) + } + + // The town store is the local store the comment write paths hold; it never + // holds the routed id, so it supplies the plain not-found this test is + // about discarding. + townDBPath := filepath.Join(townBeadsDir, "dolt") + townStore := newTestStoreIsolatedDB(t, townDBPath, "hq") + + const routedID = "gt-abcdefgh" + // One character short of routedID: not an exact id anywhere, but a valid + // leading-prefix abbreviation of a real issue in the routed rig. + const routedAbbrev = "gt-abcdefg" + // Routes to the same rig, but names nothing there in either form. + const absentRoutedID = "gt-zzzzzzzz" + + rigStore := newTestStoreIsolatedDB(t, filepath.Join(rigBeadsDir, "dolt"), "gt") + if err := rigStore.CreateIssue(ctx, &types.Issue{ + ID: routedID, + Title: "Routed comment target", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + }, "test"); err != nil { + t.Fatalf("create routed issue %s: %v", routedID, err) + } + // Prefix routing opens the target itself, so hand the database back first. + if err := rigStore.Close(); err != nil { + t.Fatalf("close rig store: %v", err) + } + + routesPath := filepath.Join(townBeadsDir, "routes.jsonl") + if err := os.WriteFile(routesPath, []byte(`{"prefix":"gt-","path":"rig"}`), 0o644); err != nil { + t.Fatalf("write routes.jsonl: %v", err) + } + + oldDBPath := dbPath + dbPath = townDBPath + t.Cleanup(func() { dbPath = oldDBPath }) + oldWD, err := os.Getwd() + if err != nil { + t.Fatalf("get working directory: %v", err) + } + if err := os.Chdir(townRoot); err != nil { + t.Fatalf("change to town root: %v", err) + } + t.Cleanup(func() { _ = os.Chdir(oldWD) }) + + // Direction 1: the routed tier's refusal must reach the caller, because + // the issue it refuses demonstrably exists. + result, err := resolveAndGetIssueForMutationExact(ctx, townStore, routedAbbrev) + if result != nil { + result.Close() + t.Fatalf("abbreviation %q of routed issue %s resolved instead of being refused", routedAbbrev, routedID) + } + if err == nil { + t.Fatalf("abbreviation %q of routed issue %s returned no error", routedAbbrev, routedID) + } + if !errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + t.Errorf("routed abbreviation %q error = %v, want one satisfying errors.Is(err, utils.ErrAbbreviatedIDNotAllowed)\n"+ + "the comment write paths key their truthful message off this sentinel, so a local not-found here prints "+ + "\"no issue found matching\" for an issue the routed rig holds", routedAbbrev, err) + } + + // Direction 2: an id that names nothing in either store must NOT be + // reported as an abbreviation refusal — the selection has to be driven by + // the routed error's own sentinel, not by having routed at all. + result, err = resolveAndGetIssueForMutationExact(ctx, townStore, absentRoutedID) + if result != nil { + result.Close() + t.Fatalf("absent routed id %q resolved unexpectedly", absentRoutedID) + } + if err == nil { + t.Fatalf("absent routed id %q returned no error", absentRoutedID) + } + if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + t.Errorf("absent routed id %q error = %v, want NOT an abbreviation refusal", absentRoutedID, err) + } + if !isNotFoundErr(err) { + t.Errorf("absent routed id %q error = %v, want a not-found error", absentRoutedID, err) + } +} diff --git a/cmd/bd/comments.go b/cmd/bd/comments.go index f0d02bb4e..c789ef498 100644 --- a/cmd/bd/comments.go +++ b/cmd/bd/comments.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "fmt" "strings" @@ -10,6 +11,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/uimd" + "github.com/steveyegge/beads/internal/utils" "github.com/steveyegge/beads/issueops" ) @@ -165,6 +167,21 @@ See: bd comments --help`) }, } +// validateCommentsAddArgs runs as cobra's Args validation for "comments add", +// the plural twin of "comment"'s validateCommentArgs. It exists for the same +// reason: an id argument that IS a reserved word (see +// commentReservedIDWords) must never reach either dispatch branch (local or +// proxied) or fuzzy resolution, where it could silently land on an unrelated +// issue instead of erroring. Unlike validateCommentArgs, there is no +// singular/plural confusion to special-case here — "comments add" is already +// the plural form — so this only runs the word-agnostic generic check. +func validateCommentsAddArgs(cmd *cobra.Command, args []string) error { + if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { + return err + } + return checkCommentIDNotReservedWord(args[0]) +} + var commentsAddCmd = &cobra.Command{ Use: "add [issue-id] [text...]", Short: "Add a comment to an issue", @@ -176,7 +193,7 @@ Examples: # Add a comment from a file bd comments add bd-123 -f notes.txt`, - Args: cobra.MinimumNArgs(1), + Args: validateCommentsAddArgs, SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { @@ -213,11 +230,19 @@ Examples: } ctx := rootCtx - result, err := resolveAndGetIssueForMutation(ctx, store, issueID) + result, err := resolveAndGetIssueForMutationExact(ctx, store, issueID) if err != nil { if result != nil { result.Close() } + if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + // The issue does exist — id just isn't its full form — so + // "resolving %s: %v"'s generic wording (and the "no issue + // found matching" text underneath a plain not-found) would be + // false here. Say what actually happened instead, matching + // "bd comment"'s truthful message. + return HandleErrorRespectJSON("id abbreviations are not accepted on comment writes; use the full id from `bd show %s`", issueID) + } return HandleErrorRespectJSON("resolving %s: %v", issueID, err) } if result == nil || result.Issue == nil { diff --git a/cmd/bd/comments_add_test.go b/cmd/bd/comments_add_test.go new file mode 100644 index 000000000..979ecbfb3 --- /dev/null +++ b/cmd/bd/comments_add_test.go @@ -0,0 +1,43 @@ +package main + +import "testing" + +// TestValidateCommentsAddArgs is a pure unit test for "comments add"'s Args +// guard — it calls the validator directly with no store, no Dolt, and no +// cobra dispatch, so it runs regardless of cgo/Docker availability. Mirrors +// TestValidateCommentArgs (the singular "comment" sibling in comment_test.go) +// for the plural form: PR #5393 review item M1 established that "comments +// add" must reject a reserved-word id exactly like "comment" does, since the +// two are documented as guarded twins (CHANGELOG.md, hash-ids.md). +func TestValidateCommentsAddArgs(t *testing.T) { + origJSONOutput := jsonOutput + jsonOutput = false + t.Cleanup(func() { jsonOutput = origJSONOutput }) + + cases := []struct { + name string + args []string + wantErr bool + }{ + {name: "bare list is rejected", args: []string{"list", "some text"}, wantErr: true}, + {name: "bare add is rejected", args: []string{"add", "some text"}, wantErr: true}, + {name: "bare rm is rejected", args: []string{"rm", "some text"}, wantErr: true}, + {name: "bare delete is rejected", args: []string{"delete", "some text"}, wantErr: true}, + {name: "real id with text starting with the word list is fine", args: []string{"test-abc123", "list", "of", "things", "to", "do"}, wantErr: false}, + {name: "real id with text starting with the word add is fine", args: []string{"test-abc123", "add", "one", "more", "item"}, wantErr: false}, + {name: "real id alone (text comes from --stdin/--file) is fine", args: []string{"test-abc123"}, wantErr: false}, + {name: "no args at all is rejected by the base MinimumNArgs check", args: []string{}, wantErr: true}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := validateCommentsAddArgs(commentsAddCmd, tc.args) + if tc.wantErr && err == nil { + t.Fatalf("validateCommentsAddArgs(%q): expected an error, got nil", tc.args) + } + if !tc.wantErr && err != nil { + t.Fatalf("validateCommentsAddArgs(%q): expected no error, got %v", tc.args, err) + } + }) + } +} diff --git a/cmd/bd/routed.go b/cmd/bd/routed.go index af08bfa19..ae0ca7757 100644 --- a/cmd/bd/routed.go +++ b/cmd/bd/routed.go @@ -78,7 +78,7 @@ func resolveAndGetIssueWithRoutingAccess(ctx context.Context, localStore storage // This handles cross-rig lookups where the ID's prefix maps to a different // database (e.g., hr-8wn.1 routes to the herald rig's database). if isNotFoundErr(err) { - if prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, writablePrefixRoute); prefixErr == nil { + if prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, writablePrefixRoute, false); prefixErr == nil { return prefixResult, nil } } @@ -87,7 +87,7 @@ func resolveAndGetIssueWithRoutingAccess(ctx context.Context, localStore storage // Auto-routed stores stay read-only even for write-intent callers (writablePrefixRoute): // this path hydrates foreign contributor projects, which must never be mutated. if isNotFoundErr(err) { - if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id); autoErr == nil { + if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id, false); autoErr == nil { return autoResult, nil } } @@ -117,16 +117,102 @@ func resolveAndGetFromStore(ctx context.Context, s storage.DoltStorage, id strin }, nil } +// resolveAndGetFromStoreExact is resolveAndGetFromStore's exact-match sibling: +// it requires utils.ResolvePartialIDExact instead of the default abbreviation- +// tolerant resolver, so a non-exact candidate (e.g. a reserved word that +// happens to be a leading-prefix abbreviation of some issue's hash) is +// reported as "not found" rather than silently resolved. +func resolveAndGetFromStoreExact(ctx context.Context, s storage.DoltStorage, id string, routed bool) (*RoutedResult, error) { + resolvedID, err := utils.ResolvePartialIDExact(ctx, s, id) + if err != nil { + return nil, err + } + + issue, err := s.GetIssue(ctx, resolvedID) + if err != nil { + return nil, err + } + + return &RoutedResult{ + Issue: issue, + Store: s, + Routed: routed, + ResolvedID: resolvedID, + }, nil +} + +// resolveAndGetIssueForMutationExact resolves an issue like +// resolveAndGetIssueForMutation, but requires an EXACT id match against each +// store it tries (no leading-prefix abbreviation matching) — see +// utils.ResolvePartialIDExact. Cross-rig prefix routing and contributor +// auto-routing are still attempted as fallbacks exactly as before if the +// local store doesn't have the issue at all; only the per-store resolution +// within each tier is tightened. Used by write paths where an id argument +// that doesn't exactly name a real issue must error out instead of silently +// mutating whatever it fuzzy-matches (`bd comment list `, a typo for +// `bd comments list`, was silently resolving "list" to a wisp whose hash +// happened to start with "list"). +func resolveAndGetIssueForMutationExact(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) { + result, err := resolveAndGetFromStoreExact(ctx, localStore, id, false) + if err == nil { + return result, nil + } + + // The routed tiers resolve with utils.ResolvePartialIDExact too, so each + // can mint utils.ErrAbbreviatedIDNotAllowed of its own — the abbreviation + // names a real issue in the routed rig rather than here — and both + // wrappers hand that error back unwrapped. Keep the first such refusal: + // the local error is only a plain not-found, and returning it would tell + // the caller no issue matches an id a routed store demonstrably holds, + // which is exactly the falsehood the sentinel exists to prevent. + var abbrevErr error + + if isNotFoundErr(err) { + prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, true, true) + if prefixErr == nil { + return prefixResult, nil + } + if errors.Is(prefixErr, utils.ErrAbbreviatedIDNotAllowed) { + abbrevErr = prefixErr + } + } + + if isNotFoundErr(err) { + autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id, true) + if autoErr == nil { + return autoResult, nil + } + if abbrevErr == nil && errors.Is(autoErr, utils.ErrAbbreviatedIDNotAllowed) { + abbrevErr = autoErr + } + } + + if abbrevErr != nil { + return nil, abbrevErr + } + + return nil, err +} + // resolveViaAutoRouting attempts to find an issue using contributor auto-routing. // This is the fallback when the local store doesn't have the issue (GH#2345). // Returns a RoutedResult if the issue is found in the auto-routed store. -func resolveViaAutoRouting(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) { +// +// exact selects utils.ResolvePartialIDExact over the default abbreviation- +// tolerant resolver for the auto-routed store lookup, mirroring the local-store +// distinction in resolveAndGetFromStore vs resolveAndGetFromStoreExact. +func resolveViaAutoRouting(ctx context.Context, localStore storage.DoltStorage, id string, exact bool) (*RoutedResult, error) { routedStore, routed, _, err := openRoutedReadStore(ctx, localStore) if err != nil || !routed { return nil, fmt.Errorf("no auto-routed store available") } - result, err := resolveAndGetFromStore(ctx, routedStore, id, true) + var result *RoutedResult + if exact { + result, err = resolveAndGetFromStoreExact(ctx, routedStore, id, true) + } else { + result, err = resolveAndGetFromStore(ctx, routedStore, id, true) + } if err != nil { _ = routedStore.Close() return nil, err @@ -152,14 +238,17 @@ type prefixRoute struct { // The read-only open guarantees a routed read cannot mutate the target; mutation // commands must route through resolveViaPrefixRoutingWithAccess with writable=true. func resolveViaPrefixRouting(ctx context.Context, id string) (*RoutedResult, error) { - return resolveViaPrefixRoutingWithAccess(ctx, id, false) + return resolveViaPrefixRoutingWithAccess(ctx, id, false, false) } // resolveViaPrefixRoutingWithAccess is the shared implementation that selects the // store-open mode. writable opens the routed target writable, behaving like running // the command inside that rig; false keeps the read-only open that guarantees a -// routed read cannot mutate the target (bd-6dnrw.32). -func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable bool) (*RoutedResult, error) { +// routed read cannot mutate the target (bd-6dnrw.32). exact selects +// utils.ResolvePartialIDExact over the default abbreviation-tolerant resolver for +// the routed store lookup, mirroring resolveAndGetFromStore vs +// resolveAndGetFromStoreExact. +func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable bool, exact bool) (*RoutedResult, error) { if strings.Index(id, "-") <= 0 { return nil, fmt.Errorf("no prefix in ID %q", id) } @@ -225,7 +314,12 @@ func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable return nil, fmt.Errorf("opening routed store for %s: %w", matchedRoute.Path, openErr) } - result, err := resolveAndGetFromStore(ctx, targetStore, id, true) + var result *RoutedResult + if exact { + result, err = resolveAndGetFromStoreExact(ctx, targetStore, id, true) + } else { + result, err = resolveAndGetFromStore(ctx, targetStore, id, true) + } if err != nil { _ = targetStore.Close() return nil, err @@ -326,7 +420,7 @@ func getIssueWithRouting(ctx context.Context, localStore storage.DoltStorage, id // If not found via prefix routing, try contributor auto-routing as fallback (GH#2345). if isNotFoundErr(err) { - if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id); autoErr == nil { + if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id, false); autoErr == nil { return autoResult, nil } } diff --git a/docs/core-concepts/hash-ids.md b/docs/core-concepts/hash-ids.md index 92b2267ff..8c8efd2e6 100644 --- a/docs/core-concepts/hash-ids.md +++ b/docs/core-concepts/hash-ids.md @@ -118,6 +118,31 @@ bd show bd-a1b2c3d4 bd list --full-ids ``` +### `bd comment` requires the full id + +Every command above resolves an abbreviation the same way — but `bd comment + "text"` (and its `bd comments add` twin) is the one deliberate exception: +it accepts only a full, exact id, never an abbreviation. This is a policy +trade for an agent fleet, not an oversight: an abbreviation that happens to be +a leading-prefix match for the wrong issue would silently write the comment +there instead of erroring, and a comment write has no confirmation step to +catch it before the message lands on the wrong issue. Reads and every other +mutation (`show`, `close`, `update`, …) keep accepting abbreviations as +documented above. + +```bash +bd show a1b2 # OK — abbreviation resolves for reads +bd close a1b2 # OK — abbreviation resolves for other writes +bd comment a1b2 "text" # refused — comment writes require the full id +bd comment bd-a1b2c3d4 "text" # OK — use the full id from `bd show` +``` + +A reserved word (`list`, `add`, `rm`, `delete`) as the id positional is +refused the same way, for a related reason: `bd comment list "text"` almost +always means the caller confused the singular shorthand with the plural `bd +comments list`/`bd comments add "text"`, not that an issue is literally +named `list`. + ## Migration from Sequential IDs If migrating from a system with sequential IDs: @@ -132,7 +157,9 @@ bd show bd-new --json | jq '.original_id' ## Best Practices -1. **Use short references** - `bd-a1b2` is usually unique enough +1. **Use short references** - `bd-a1b2` is usually unique enough, except on + `bd comment` writes, which require the full id (see + [Working with IDs](#working-with-ids) above) 2. **Use `--json` for scripts** - Parse full ID programmatically 3. **Reference by hash in commits** - `Fixed bd-a1b2` in commit messages 4. **Let hierarchies form naturally** - Create epics, add children as needed diff --git a/internal/utils/BUILD.bazel b/internal/utils/BUILD.bazel index 72a46213c..97d1a0e58 100644 --- a/internal/utils/BUILD.bazel +++ b/internal/utils/BUILD.bazel @@ -29,6 +29,8 @@ go_library( go_test( name = "utils_test", srcs = [ + "id_parser_exact_test.go", + "id_parser_fake_test.go", "id_parser_prefix_test.go", "id_parser_sentinel_test.go", "id_parser_test.go", diff --git a/internal/utils/id_parser.go b/internal/utils/id_parser.go index ec77d1a2e..70167c593 100644 --- a/internal/utils/id_parser.go +++ b/internal/utils/id_parser.go @@ -19,6 +19,20 @@ import ( // "not found" and surface the candidate list instead of a generic failure. var ErrAmbiguousID = errors.New("ambiguous issue ID") +// ErrAbbreviatedIDNotAllowed is the sentinel wrapped into the error +// ResolvePartialIDExact returns when the input does not exactly name an +// issue but WOULD have resolved via leading-prefix abbreviation matching — +// the behavior ResolvePartialID allows and exact-only callers refuse. +// +// Distinguishing this from "no such issue at all" matters because the two +// are not the same failure: an abbreviation that matches a real issue is +// proof the issue exists, so telling the caller "no issue found matching" +// (the message a genuine not-found gets) is false. Exact-only callers use +// errors.Is(err, ErrAbbreviatedIDNotAllowed) to give a truthful, actionable +// message instead ("id abbreviations are not accepted here; use the full +// id") — see bd comment's resolveAndGetIssueForMutationExact caller. +var ErrAbbreviatedIDNotAllowed = errors.New("id is a valid abbreviation, but exact-match resolution is required here") + type PartialIDResolverStore interface { SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) SearchIssueIDs(ctx context.Context, query string, filter types.IssueFilter) ([]string, error) @@ -53,6 +67,29 @@ func parseIssueID(input string, prefix string) string { // - No issue found matching the ID // - Multiple issues match (ambiguous prefix) func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input string) (string, error) { + return resolvePartialID(ctx, store, input, true) +} + +// ResolvePartialIDExact resolves an issue ID like ResolvePartialID, but never +// falls back to leading-prefix abbreviation matching (e.g. "a3f8" -> +// "a3f8e9...", or a wisp's stripped hash "list" -> "list3t0") — only a full +// exact ID or exact hash match (with or without a "wisp-" infix) succeeds. +// +// Intended for write paths where a mistyped or coincidentally-prefix-matching +// argument must return "not found" instead of silently mutating an unrelated +// issue (e.g. `bd comment list `, a typo for `bd comments list`, was +// silently fuzzy-resolving "list" to a wisp whose hash happened to start with +// "list" and writing the rest of the command line to it as a comment). +// +// When the input matches nothing exactly but WOULD have resolved via +// leading-prefix abbreviation, the returned error wraps +// ErrAbbreviatedIDNotAllowed rather than being indistinguishable from a +// genuine not-found — see that sentinel's doc comment. +func ResolvePartialIDExact(ctx context.Context, store PartialIDResolverStore, input string) (string, error) { + return resolvePartialID(ctx, store, input, false) +} + +func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input string, allowAbbrev bool) (string, error) { // Refuse before any lookup: these tokens are a valid partial-ID shape, so // they otherwise reach the leading-prefix abbreviation branch below. switch strings.ToLower(strings.TrimSpace(input)) { @@ -153,6 +190,10 @@ func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input s var matches []string var exactMatch string + // abbrevOnly collects candidates that matched ONLY via leading-prefix + // abbreviation while allowAbbrev is false — never resolved to, only used + // to make the final "not found" error truthful (see ErrAbbreviatedIDNotAllowed). + var abbrevOnly []string for _, id := range ids { // Check for exact full ID match first (case: user typed full ID with different prefix) @@ -179,7 +220,14 @@ func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input s // Leading-prefix abbreviation (documented UX, e.g. "a3f8" -> "a3f8e9..."). // HasPrefix rather than Contains: reject interior-substring matches // like "kt8" inside "j0kt8" (GH#4234). - matches = append(matches, id) + if allowAbbrev { + matches = append(matches, id) + } else { + // Exact-only callers must never silently resolve to this + // candidate, but its existence is what makes "no issue found + // matching" false below — track it instead of discarding it. + abbrevOnly = append(abbrevOnly, id) + } } } @@ -214,7 +262,11 @@ func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input s if wHash == hashPart || wispHash == hashPart { exactMatch = wID } else if strings.HasPrefix(wispHash, hashPart) { - matches = append(matches, wID) + if allowAbbrev { + matches = append(matches, wID) + } else { + abbrevOnly = append(abbrevOnly, wID) + } } } if exactMatch != "" { @@ -224,6 +276,16 @@ func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input s } if len(matches) == 0 { + if !allowAbbrev && len(abbrevOnly) > 0 { + // The input matched nothing exactly, but it IS a valid leading- + // prefix abbreviation of at least one real issue — telling the + // caller "no issue found" here would be false. Report the + // truthful reason instead so an exact-only caller (comment.go's + // resolveAndGetIssueForMutationExact) can surface an accurate, + // actionable message rather than claiming the issue is missing. + sort.Strings(abbrevOnly) + return "", fmt.Errorf("%w: %q (matches %v)", ErrAbbreviatedIDNotAllowed, input, abbrevOnly) + } return "", fmt.Errorf("no issue found matching %q", input) } diff --git a/internal/utils/id_parser_exact_test.go b/internal/utils/id_parser_exact_test.go new file mode 100644 index 000000000..e60d9e370 --- /dev/null +++ b/internal/utils/id_parser_exact_test.go @@ -0,0 +1,208 @@ +//go:build cgo + +package utils_test + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/utils" +) + +// TestResolvePartialIDExact_RejectsAbbreviationAcceptsExact reuses the same +// fixture shape as TestResolvePartialID (full/partial/hierarchical/substring +// issues) to show ResolvePartialIDExact keeps every exact-match case working +// identically to ResolvePartialID, while every leading-prefix-abbreviation +// case — which ResolvePartialID happily resolves — now errors instead of +// silently picking a candidate. +func TestResolvePartialIDExact_RejectsAbbreviationAcceptsExact(t *testing.T) { + ctx := context.Background() + store := newTestStore(t) + + prefixIssue := &types.Issue{ + ID: "bd-a3f8e9", + Title: "Prefix resolution target", + Status: types.StatusOpen, + Priority: 1, + IssueType: types.TypeTask, + } + plainIssue := &types.Issue{ + ID: "bd-1", + Title: "Plain issue", + Status: types.StatusOpen, + Priority: 1, + IssueType: types.TypeTask, + } + + if err := store.CreateIssue(ctx, prefixIssue, "test"); err != nil { + t.Fatal(err) + } + if err := store.CreateIssue(ctx, plainIssue, "test"); err != nil { + t.Fatal(err) + } + if err := store.SetConfig(ctx, "issue_prefix", "bd-"); err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + input string + expected string + shouldError bool + }{ + { + name: "exact match with prefix still resolves", + input: "bd-1", + expected: "bd-1", + }, + { + name: "exact match without prefix still resolves", + input: "1", + expected: "bd-1", + }, + { + name: "exact full hash still resolves", + input: "a3f8e9", + expected: "bd-a3f8e9", + }, + { + name: "leading-prefix abbreviation now errors (was silently accepted by ResolvePartialID)", + input: "a3f8", + shouldError: true, + }, + { + name: "nonexistent issue still errors", + input: "bd-999", + shouldError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := utils.ResolvePartialIDExact(ctx, store, tt.input) + if tt.shouldError { + if err == nil { + t.Fatalf("utils.ResolvePartialIDExact(%q) = %q, nil; want error", tt.input, result) + } + return + } + if err != nil { + t.Fatalf("utils.ResolvePartialIDExact(%q) unexpected error: %v", tt.input, err) + } + if result != tt.expected { + t.Errorf("utils.ResolvePartialIDExact(%q) = %q; want %q", tt.input, result, tt.expected) + } + }) + } +} + +// TestResolvePartialIDExact_Wisp is a direct regression test for the +// reported incident: a wisp's stripped hash ("t3st" from "bd-wisp-t3st") +// must still resolve exactly (that's a real, deliberate exact-match +// convenience — referencing a wisp without typing "wisp-"), but a +// leading-prefix abbreviation of that hash ("t3s", or the real incident's +// "list" against "list3t0") must now error instead of silently landing on +// the wisp. +func TestResolvePartialIDExact_Wisp(t *testing.T) { + ctx := context.Background() + store := newTestStore(t) + + wisp := &types.Issue{ + ID: "bd-wisp-t3st", + Title: "Test wisp", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: true, + } + if err := store.CreateIssue(ctx, wisp, "test"); err != nil { + t.Fatal(err) + } + if err := store.SetConfig(ctx, "issue_prefix", "bd"); err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + input string + expected string + shouldError bool + }{ + { + name: "full wisp ID still resolves exactly", + input: "bd-wisp-t3st", + expected: "bd-wisp-t3st", + }, + { + name: "wisp prefix with full hash still resolves exactly", + input: "wisp-t3st", + expected: "bd-wisp-t3st", + }, + { + name: "bare full hash still resolves exactly (wisp- infix stripped, but hash is complete)", + input: "t3st", + expected: "bd-wisp-t3st", + }, + { + name: "leading-prefix abbreviation of the wisp hash now errors", + input: "t3s", + shouldError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := utils.ResolvePartialIDExact(ctx, store, tt.input) + if tt.shouldError { + if err == nil { + t.Fatalf("utils.ResolvePartialIDExact(%q) = %q, nil; want error", tt.input, result) + } + return + } + if err != nil { + t.Fatalf("utils.ResolvePartialIDExact(%q) unexpected error: %v", tt.input, err) + } + if result != tt.expected { + t.Errorf("utils.ResolvePartialIDExact(%q) = %q; want %q", tt.input, result, tt.expected) + } + }) + } +} + +// TestResolvePartialIDExact_ReservedWordDoesNotCollideWithWisp is the exact +// shape of the real incident: a wisp whose hash happens to start with a +// word a caller might type by accident. Even without the CLI-level +// reserved-word guard, ResolvePartialIDExact alone must refuse to resolve +// "list" against a wisp hashed "list3t0". +func TestResolvePartialIDExact_ReservedWordDoesNotCollideWithWisp(t *testing.T) { + ctx := context.Background() + store := newTestStore(t) + + wisp := &types.Issue{ + ID: "bd-wisp-list3t0", + Title: "Unrelated wisp (order:dolt-health)", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: true, + } + if err := store.CreateIssue(ctx, wisp, "test"); err != nil { + t.Fatal(err) + } + if err := store.SetConfig(ctx, "issue_prefix", "bd"); err != nil { + t.Fatal(err) + } + + if result, err := utils.ResolvePartialIDExact(ctx, store, "list"); err == nil { + t.Fatalf(`utils.ResolvePartialIDExact("list") = %q, nil; want "not found" error, not a silent match onto %s`, result, wisp.ID) + } + + // Sanity check against the OLD behavior: ResolvePartialID (still the + // default for read paths) is documented to resolve this via the leading- + // prefix abbreviation branch — confirms the fixture actually reproduces + // the incident's collision instead of trivially not matching anything. + if result, err := utils.ResolvePartialID(ctx, store, "list"); err != nil || result != wisp.ID { + t.Fatalf("fixture sanity check failed: utils.ResolvePartialID(%q) = (%q, %v); want (%q, nil) — the incident's collision did not reproduce", "list", result, err, wisp.ID) + } +} diff --git a/internal/utils/id_parser_fake_test.go b/internal/utils/id_parser_fake_test.go new file mode 100644 index 000000000..22e7e209a --- /dev/null +++ b/internal/utils/id_parser_fake_test.go @@ -0,0 +1,233 @@ +package utils_test + +// Fake, in-memory implementation of utils.PartialIDResolverStore. Unlike the +// other tests in this package, this one needs no cgo, no Dolt binary, and no +// Docker test container — it exercises ResolvePartialID/ResolvePartialIDExact +// against a hand-rolled store, so it can actually run in any environment +// (including ones where the Docker-backed newTestStore tests in +// id_parser_test.go / id_parser_exact_test.go skip themselves). + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/utils" +) + +type fakeIssue struct { + id string + ephemeral bool +} + +// fakeResolverStore is a minimal PartialIDResolverStore backed by a plain +// slice, replicating just enough of the real store's query semantics for +// ResolvePartialID/ResolvePartialIDExact: exact-ID lookup (SearchIssues with +// filter.IDs) and substring "LIKE"-style search optionally scoped to +// ephemeral issues (SearchIssueIDs). +type fakeResolverStore struct { + issues []fakeIssue + config map[string]string +} + +func (f *fakeResolverStore) SearchIssues(_ context.Context, _ string, filter types.IssueFilter) ([]*types.Issue, error) { + var out []*types.Issue + for _, iss := range f.issues { + if len(filter.IDs) > 0 && !containsStr(filter.IDs, iss.id) { + continue + } + out = append(out, &types.Issue{ID: iss.id, Ephemeral: iss.ephemeral}) + } + return out, nil +} + +func (f *fakeResolverStore) SearchIssueIDs(_ context.Context, query string, filter types.IssueFilter) ([]string, error) { + var out []string + for _, iss := range f.issues { + if filter.Ephemeral != nil && iss.ephemeral != *filter.Ephemeral { + continue + } + if query != "" && !strings.Contains(iss.id, query) { + continue + } + out = append(out, iss.id) + } + return out, nil +} + +func (f *fakeResolverStore) GetConfig(_ context.Context, key string) (string, error) { + return f.config[key], nil +} + +func containsStr(haystack []string, needle string) bool { + for _, s := range haystack { + if s == needle { + return true + } + } + return false +} + +// TestResolvePartialIDExact_FakeStore_ReproducesReportedIncident is a +// Docker-free, always-runnable reproduction of a real incident: +// "bd comment list " (a typo for "bd comments list") resolved "list" +// against a wisp "hq-wisp-list3t0" via leading-prefix abbreviation and wrote +// the rest of the command line to it as a comment. It asserts three things +// in one place: (1) the fixture genuinely reproduces the old collision via +// ResolvePartialID, (2) ResolvePartialIDExact refuses the same input, and +// (3) ResolvePartialIDExact still resolves genuinely exact references +// (happy path untouched). +func TestResolvePartialIDExact_FakeStore_ReproducesReportedIncident(t *testing.T) { + ctx := context.Background() + store := &fakeResolverStore{ + issues: []fakeIssue{ + {id: "hq-wisp-list3t0", ephemeral: true}, + {id: "hq-165vq", ephemeral: false}, + }, + config: map[string]string{"issue_prefix": "hq"}, + } + + // Sanity check: confirm the fixture reproduces the OLD (still-default, + // still-correct-for-read-paths) fuzzy behavior before asserting the fix. + gotFuzzy, err := utils.ResolvePartialID(ctx, store, "list") + if err != nil || gotFuzzy != "hq-wisp-list3t0" { + t.Fatalf("fixture sanity check failed: ResolvePartialID(%q) = (%q, %v); want (%q, nil) — incident did not reproduce", + "list", gotFuzzy, err, "hq-wisp-list3t0") + } + + // The fix: the write-path resolver must refuse the same input instead of + // silently landing on the unrelated wisp. Asserting errors.Is (not just + // err != nil) pins the WISP branch's abbrevOnly tracking specifically: + // without it, "list" still fails (via the generic "no issue found" + // fallback), so a regression that silently drops the wisp-branch + // abbrevOnly candidate — reintroducing this exact incident's false + // not-found — would pass this test undetected. + if got, err := utils.ResolvePartialIDExact(ctx, store, "list"); err == nil { + t.Fatalf(`ResolvePartialIDExact("list") = (%q, nil); want a "not found" error, not a silent match onto hq-wisp-list3t0`, got) + } else if !errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + t.Fatalf(`ResolvePartialIDExact("list") error = %v; want errors.Is(err, ErrAbbreviatedIDNotAllowed) — "list" IS a valid leading-prefix abbreviation of hq-wisp-list3t0, so the error must say so truthfully, not fall back to a generic "no issue found"`, err) + } + + // Happy path: an id that genuinely, exactly names an issue must still + // resolve under the exact-only resolver. + if got, err := utils.ResolvePartialIDExact(ctx, store, "hq-165vq"); err != nil || got != "hq-165vq" { + t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil)", "hq-165vq", got, err, "hq-165vq") + } + if got, err := utils.ResolvePartialIDExact(ctx, store, "165vq"); err != nil || got != "hq-165vq" { + t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil) — bare full hash must still resolve exactly", "165vq", got, err, "hq-165vq") + } + if got, err := utils.ResolvePartialIDExact(ctx, store, "hq-wisp-list3t0"); err != nil || got != "hq-wisp-list3t0" { + t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil) — full wisp id must still resolve exactly", "hq-wisp-list3t0", got, err, "hq-wisp-list3t0") + } +} + +// TestResolvePartialIDExact_AbbreviationRefusalIsDistinguishableFromNotFound +// is a Docker-free regression test for the follow-up steveyegge's PR #5393 +// review flagged (item c): an abbreviation that DOES match a real issue must +// error differently from an input that matches nothing at all, because "no +// issue found matching %q" is false in the first case — the issue exists, +// only the abbreviation was refused. Exact-only callers (bd comment) use +// errors.Is(err, ErrAbbreviatedIDNotAllowed) to tell the two apart and give a +// truthful, actionable message instead of claiming the issue is missing. +func TestResolvePartialIDExact_AbbreviationRefusalIsDistinguishableFromNotFound(t *testing.T) { + ctx := context.Background() + store := &fakeResolverStore{ + issues: []fakeIssue{ + {id: "hq-a3f8e9", ephemeral: false}, + }, + config: map[string]string{"issue_prefix": "hq"}, + } + + // A real, valid leading-prefix abbreviation of an existing issue: must + // wrap ErrAbbreviatedIDNotAllowed, not a plain "not found". + got, err := utils.ResolvePartialIDExact(ctx, store, "a3f8") + if err == nil { + t.Fatalf(`ResolvePartialIDExact("a3f8") = (%q, nil); want an ErrAbbreviatedIDNotAllowed error — "a3f8" is a real abbreviation of hq-a3f8e9`, got) + } + if !errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + t.Errorf(`ResolvePartialIDExact("a3f8") error = %q; want it to wrap ErrAbbreviatedIDNotAllowed (errors.Is)`, err) + } + if strings.Contains(err.Error(), "no issue found matching") { + t.Errorf(`ResolvePartialIDExact("a3f8") error = %q; must NOT claim "no issue found" — hq-a3f8e9 exists`, err) + } + + // An input that matches nothing at all, not even via abbreviation: must + // stay a plain not-found, and must NOT wrap ErrAbbreviatedIDNotAllowed — + // proves the two failure modes are genuinely distinguishable, not just + // differently worded copies of the same check. + got, err = utils.ResolvePartialIDExact(ctx, store, "zzzzzz") + if err == nil { + t.Fatalf(`ResolvePartialIDExact("zzzzzz") = (%q, nil); want a not-found error`, got) + } + if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + t.Errorf(`ResolvePartialIDExact("zzzzzz") error = %q; want a plain not-found, not ErrAbbreviatedIDNotAllowed — nothing matches "zzzzzz" even via abbreviation`, err) + } + if !strings.Contains(err.Error(), "no issue found matching") { + t.Errorf(`ResolvePartialIDExact("zzzzzz") error = %q; want the genuine "no issue found matching" wording`, err) + } + + // Sanity: the exact id still resolves under the same store/config, + // confirming the fixture didn't accidentally break the happy path. + if got, err := utils.ResolvePartialIDExact(ctx, store, "hq-a3f8e9"); err != nil || got != "hq-a3f8e9" { + t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil)", "hq-a3f8e9", got, err, "hq-a3f8e9") + } +} + +// TestResolvePartialIDExact_RefusesSentinelTokens pins where #6215's bare- +// sentinel guard has to live once this PR splits the resolver in two. +// +// #6215 (base) refuses "null"/"undefined"/"none"/"nil"/"" before any lookup, +// and put that guard in ResolvePartialID because it was then the only +// ID-resolution entry point in the repository. This PR adds a second one, +// ResolvePartialIDExact, so the guard belongs in the shared resolvePartialID +// body — which is what keeps #6215's own stated guarantee ("bd update null, +// bd comment null and every other command that resolves an ID now fail before +// any lookup") true for the comment write paths this PR routes through the +// exact-only resolver. +// +// Nothing else covers that: #6215's id_parser_sentinel_test.go exercises only +// ResolvePartialID, so leaving the guard in the exported wrapper alone keeps +// every one of its assertions green while a sentinel reaching the exact path +// degrades into an ErrAbbreviatedIDNotAllowed that names an unrelated decoy +// issue — telling the caller to "use the full id" for a token that is really +// just their selector having matched nothing. +func TestResolvePartialIDExact_RefusesSentinelTokens(t *testing.T) { + ctx := context.Background() + // hq-null3t0 is #6215's own decoy shape: a real issue whose hash begins + // with "null", so an unguarded sentinel is a live abbreviation match here + // rather than a plain not-found. + store := &fakeResolverStore{ + issues: []fakeIssue{ + {id: "hq-null3t0", ephemeral: false}, + {id: "hq-165vq", ephemeral: false}, + }, + config: map[string]string{"issue_prefix": "hq"}, + } + + for _, input := range []string{"null", "NULL", " null ", "undefined", "none", "nil", "", " "} { + got, err := utils.ResolvePartialIDExact(ctx, store, input) + if err == nil { + t.Errorf("ResolvePartialIDExact(%q) = (%q, nil); want #6215's sentinel refusal", input, got) + continue + } + if !strings.Contains(err.Error(), "refusing") { + t.Errorf("ResolvePartialIDExact(%q) error = %q; want #6215's sentinel refusal (guard did not fire on the exact path)", input, err) + } + if errors.Is(err, utils.ErrAbbreviatedIDNotAllowed) { + t.Errorf("ResolvePartialIDExact(%q) error = %q; a tooling sentinel must be refused as such, not reported as a refused abbreviation of hq-null3t0", input, err) + } + if strings.Contains(err.Error(), "hq-null3t0") { + t.Errorf("ResolvePartialIDExact(%q) error = %q; must not name the decoy issue", input, err) + } + } + + // Over-refusal guard, the twin of #6215's accepted-inputs test: an id that + // merely CONTAINS a sentinel token must still resolve exactly. + for _, input := range []string{"hq-null3t0", "null3t0"} { + if got, err := utils.ResolvePartialIDExact(ctx, store, input); err != nil || got != "hq-null3t0" { + t.Errorf("ResolvePartialIDExact(%q) = (%q, %v); want (%q, nil) — the guard must match the whole token, not a prefix", input, got, err, "hq-null3t0") + } + } +}