beads/internal/utils/id_parser_test.go
gascity-eddie[bot] 3a79fbad4c
test(resolver): pin leading-prefix partial-ID matching for gcy-g4o (follow-up to #4376) (#7605)
* fix(resolver): use last-segment prefix match to prevent wisp substring collision

When two beads share overlapping hash fragments (e.g. gcy-oqf and
gcy-wisp-goqfo), the previous strings.Contains check incorrectly matched
"goqfo" as containing "oqf" and silently returned the wrong bead.

The fix changes the fuzzy match from substring containment to a
last-dash-segment prefix comparison:
  lastSegment("wisp-goqfo") = "goqfo" → HasPrefix("goqfo","oqf") = false
  lastSegment("wisp-t3st")  = "t3st"  → HasPrefix("t3st","t3st") = true

This preserves the intended use case (resolving wisps by their trailing
segment, e.g. "t3st" → "bd-wisp-t3st") while eliminating false
substring hits.

Also adds BD_NO_FUZZY env var: when set, partial resolution is skipped
and only the exact-ID fast path runs. This lets callers opt out of all
fuzzy matching when they need strict lookups (e.g. to avoid cache-lag
ambiguity).

Fixes: gcy-g4o (fuzzy short-ID resolver silently redirects to wrong bead)

* test(resolver): pin prefix-only semantics for plain-hash partial match

* fix(resolver): restore leading-prefix ID matching, pin gcy-g4o cases

#4939 already made partial matching leading-prefix only (strings.HasPrefix
in place of strings.Contains at both call sites), which is what fixed the
gcy-g4o collision: gcy-oqf can no longer resolve to gcy-wisp-goqfo through
the substring "oqf".

The last-dash-segment matcher added on top of that compared only the text
after each id's last dash, so inputs naming no issue resolved to unrelated
beads: hr-8wnq to a local bd-8wnq2 (which also pre-empts its hr- prefix
route), gcy-wisp-g4o to gcy-g4oab, and a trailing dash to any hash. The
first loop also began claiming wisps as abbreviations, so an exact bare
wisp hash turned ambiguous beside a longer sibling. Restore main's matcher
and remove hashSegmentPrefixMatch and lastDashSegment.

Drop BD_NO_FUZZY and its test. The gate returned before prefix
normalization, so documented exact forms such as a bare hash failed, and
it skipped the ErrAbbreviatedIDNotAllowed sentinel that callers branch on.
Exact-only resolution already exists as ResolvePartialIDExact; a
user-facing strict mode is left as a follow-up.

Keep the gcy-g4o regression tests, reworked so they reach the partial
matcher:
- TestResolvePartialID_WispSubstringCollision stores only the wisp, so
  gcy-oqf and oqf must miss instead of hitting the exact fast path.
- TestResolvePartialID_WispLastSegment adds a longer wisp sibling, so the
  wisp fallback's exact branch is what resolves t3st.

Add Docker-free and routed coverage:
- TestResolvePartialID_FakeStore_QualifiedInputsNeverResolveToAnotherBead:
  hr-8wnq, gcy-wisp-g4o, bd-wisp-t3, abc, bd-ol-, aap- and - stay
  not-found on both resolvers, each beside a control abbreviation that
  resolves.
- TestResolvePartialIDMatchesLeadingPrefixOnly,
  TestResolvePartialIDSilentOnExactWispHash and
  TestResolvePartialIDNotifiesOnWispHashAbbreviation replace the
  helper-level tests.
- TestRoutedResolutionLooksPastLocalNearMiss: hr-8wnq reaches its hr-
  route despite a local bd-8wnq2, on the read and mutation paths.

With the last-segment matcher swapped back in, the table test (7 of 8
cases), the routed test, TestResolvePartialIDSilentOnExactWispHash and
TestResolvePartialID_WispLastSegment fail. With strings.Contains, the
table test (4 cases), TestResolvePartialIDMatchesLeadingPrefixOnly,
TestResolvePartialIDSilentOnExactWispHash and
TestResolvePartialID_WispSubstringCollision fail.

Co-authored-by: Saren <saren@dumstruck.com>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Saren <saren@dumstruck.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 11:25:14 +00:00

1078 lines
29 KiB
Go

//go:build cgo
package utils_test
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"testing"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/testutil"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
func newTestStore(t *testing.T) *dolt.DoltStore {
t.Helper()
testutil.RequireDoltBinary(t)
if utils.DoltTestServerPort == 0 {
t.Skip("Test Dolt server not running, skipping test")
}
ctx := context.Background()
dbName := uniqueTestDBName(t)
store, err := dolt.New(ctx, &dolt.Config{
Path: t.TempDir(),
Database: dbName,
ServerPort: utils.DoltTestServerPort,
CreateIfMissing: true, // test creates fresh database
})
if err != nil {
t.Fatalf("Failed to create dolt store: %v", err)
}
if err := store.SetConfig(ctx, "issue_prefix", "bd"); err != nil {
store.Close()
t.Fatalf("Failed to set issue_prefix: %v", err)
}
t.Cleanup(func() { store.Close() })
return store
}
func uniqueTestDBName(t *testing.T) string {
t.Helper()
buf := make([]byte, 6)
if _, err := rand.Read(buf); err != nil {
t.Fatalf("failed to generate random bytes: %v", err)
}
return fmt.Sprintf("testdb_%s", hex.EncodeToString(buf))
}
func TestResolvePartialID(t *testing.T) {
ctx := context.Background()
store := newTestStore(t)
// Create test issues with sequential IDs (current implementation)
// When hash IDs (bd-165) are implemented, these can be hash-based
issue1 := &types.Issue{
ID: "bd-1",
Title: "Test Issue 1",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
issue2 := &types.Issue{
ID: "bd-2",
Title: "Test Issue 2",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
issue3 := &types.Issue{
ID: "bd-10",
Title: "Test Issue 3",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
// Test hierarchical IDs - parent and child
parentIssue := &types.Issue{
ID: "offlinebrew-3d0",
Title: "Parent Epic",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeEpic,
}
childIssue := &types.Issue{
ID: "offlinebrew-3d0.1",
Title: "Child Task",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
// Test substring matching rejection (GH#4234)
// This issue's hash "j0kt8" contains "kt8" as substring
substringIssue := &types.Issue{
ID: "hq-wisp-j0kt8",
Title: "Inspect resource conditions",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
// Test leading-prefix abbreviation still resolves (documented UX, e.g.
// "a3f8" -> "a3f8e9..."), not just exact hash matches.
prefixIssue := &types.Issue{
ID: "bd-a3f8e9",
Title: "Prefix resolution target",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
if err := store.CreateIssue(ctx, issue1, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, issue2, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, issue3, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, parentIssue, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, childIssue, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, substringIssue, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, prefixIssue, "test"); err != nil {
t.Fatal(err)
}
// Set config for prefix
if err := store.SetConfig(ctx, "issue_prefix", "bd-"); err != nil {
t.Fatal(err)
}
// Allow hq prefix for cross-prefix lookup test
if err := store.SetConfig(ctx, "allowed_prefixes", "hq"); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
input string
expected string
shouldError bool
errorMsg string
}{
{
name: "exact match with prefix",
input: "bd-1",
expected: "bd-1",
},
{
name: "exact match without prefix",
input: "1",
expected: "bd-1",
},
{
name: "exact match with prefix (two digits)",
input: "bd-10",
expected: "bd-10",
},
{
name: "exact match without prefix (two digits)",
input: "10",
expected: "bd-10",
},
{
name: "nonexistent issue",
input: "bd-999",
shouldError: true,
errorMsg: "no issue found",
},
{
name: "partial match - unique substring",
input: "bd-1",
expected: "bd-1",
},
{
name: "ambiguous partial match",
input: "bd-1",
expected: "bd-1", // Will match exactly, not ambiguously
},
{
name: "exact match parent ID with hierarchical child - gh-316",
input: "offlinebrew-3d0",
expected: "offlinebrew-3d0", // Should match exactly, not be ambiguous with offlinebrew-3d0.1
},
{
name: "exact match parent without prefix - gh-316",
input: "3d0",
expected: "offlinebrew-3d0", // Should still prefer exact hash match
},
{
name: "substring match should error - GH#4234",
input: "hq-kt8",
shouldError: true,
errorMsg: "no issue found",
// hq-wisp-j0kt8 exists but "kt8" is only a substring of "j0kt8", not exact
},
{
name: "substring match without prefix should error - GH#4234",
input: "kt8",
shouldError: true,
errorMsg: "no issue found",
// hq-wisp-j0kt8 exists but "kt8" is only a substring of "j0kt8", not exact
},
{
name: "exact match with full ID containing substring",
input: "hq-wisp-j0kt8",
expected: "hq-wisp-j0kt8",
},
{
name: "leading-prefix abbreviation still resolves",
input: "a3f8",
expected: "bd-a3f8e9", // "a3f8" is a leading prefix of "a3f8e9", not just a substring
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := utils.ResolvePartialID(ctx, store, tt.input)
if tt.shouldError {
if err == nil {
t.Errorf("utils.ResolvePartialID(%q) expected error containing %q, got nil", tt.input, tt.errorMsg)
} else if tt.errorMsg != "" && !contains(err.Error(), tt.errorMsg) {
t.Errorf("utils.ResolvePartialID(%q) error = %q; want error containing %q", tt.input, err.Error(), tt.errorMsg)
}
} else {
if err != nil {
t.Errorf("utils.ResolvePartialID(%q) unexpected error: %v", tt.input, err)
}
if result != tt.expected {
t.Errorf("utils.ResolvePartialID(%q) = %q; want %q", tt.input, result, tt.expected)
}
}
})
}
}
func TestResolvePartialIDs(t *testing.T) {
ctx := context.Background()
store := newTestStore(t)
// Create test issues
issue1 := &types.Issue{
ID: "bd-1",
Title: "Test Issue 1",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
issue2 := &types.Issue{
ID: "bd-2",
Title: "Test Issue 2",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
if err := store.CreateIssue(ctx, issue1, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, issue2, "test"); err != nil {
t.Fatal(err)
}
if err := store.SetConfig(ctx, "issue_prefix", "bd-"); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
inputs []string
expected []string
shouldError bool
}{
{
name: "resolve multiple IDs without prefix",
inputs: []string{"1", "2"},
expected: []string{"bd-1", "bd-2"},
},
{
name: "resolve mixed full and partial IDs",
inputs: []string{"bd-1", "2"},
expected: []string{"bd-1", "bd-2"},
},
{
name: "error on nonexistent ID",
inputs: []string{"1", "999"},
shouldError: true,
},
{
name: "empty input list",
inputs: []string{},
expected: []string{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := utils.ResolvePartialIDs(ctx, store, tt.inputs)
if tt.shouldError {
if err == nil {
t.Errorf("utils.ResolvePartialIDs(%v) expected error, got nil", tt.inputs)
}
} else {
if err != nil {
t.Errorf("utils.ResolvePartialIDs(%v) unexpected error: %v", tt.inputs, err)
}
if len(result) != len(tt.expected) {
t.Errorf("utils.ResolvePartialIDs(%v) returned %d results; want %d", tt.inputs, len(result), len(tt.expected))
}
for i := range result {
if result[i] != tt.expected[i] {
t.Errorf("utils.ResolvePartialIDs(%v)[%d] = %q; want %q", tt.inputs, i, result[i], tt.expected[i])
}
}
}
})
}
}
func TestResolvePartialID_NoConfig(t *testing.T) {
ctx := context.Background()
store := newTestStore(t)
// Create test issue without setting config (test default prefix)
issue1 := &types.Issue{
ID: "bd-1",
Title: "Test Issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
if err := store.CreateIssue(ctx, issue1, "test"); err != nil {
t.Fatal(err)
}
// Don't set config - should use default "bd" prefix
result, err := utils.ResolvePartialID(ctx, store, "1")
if err != nil {
t.Fatalf("ResolvePartialID failed with default config: %v", err)
}
if result != "bd-1" {
t.Errorf("utils.ResolvePartialID(\"1\") with default config = %q; want \"bd-1\"", result)
}
}
func TestResolvePartialID_NilStorage(t *testing.T) {
ctx := context.Background()
// Test that nil storage returns an error instead of panicking
_, err := utils.ResolvePartialID(ctx, nil, "bd-123")
if err == nil {
t.Fatal("ResolvePartialID with nil storage should return error, got nil")
}
expectedMsg := "storage is nil"
if !contains(err.Error(), expectedMsg) {
t.Errorf("ResolvePartialID error = %q; want error containing %q", err.Error(), expectedMsg)
}
}
func TestExtractIssuePrefix(t *testing.T) {
tests := []struct {
name string
issueID string
expected string
}{
{
name: "standard format",
issueID: "bd-a3f8e9",
expected: "bd",
},
{
name: "custom prefix",
issueID: "ticket-123",
expected: "ticket",
},
{
name: "hierarchical ID",
issueID: "bd-a3f8e9.1.2",
expected: "bd",
},
{
name: "no hyphen",
issueID: "invalid",
expected: "",
},
{
name: "empty string",
issueID: "",
expected: "",
},
{
name: "only prefix",
issueID: "bd-",
expected: "bd",
},
{
name: "multi-part prefix with numeric suffix",
issueID: "alpha-beta-1",
expected: "alpha-beta", // Last hyphen before numeric suffix
},
{
name: "multi-part non-numeric suffix (word-like)",
issueID: "vc-baseline-test",
expected: "vc", // Word-like suffix (4+ chars, no digit) uses first hyphen (bd-fasa fix)
},
{
name: "beads-vscode style prefix",
issueID: "beads-vscode-1",
expected: "beads-vscode", // Last hyphen before numeric suffix
},
{
name: "web-app style prefix",
issueID: "web-app-123",
expected: "web-app", // Should extract "web-app", not "web-"
},
{
name: "three-part prefix with hash",
issueID: "my-cool-app-a3f8e9",
expected: "my-cool-app", // Hash suffix should use last hyphen logic
},
{
name: "four-part prefix with 4-char hash",
issueID: "super-long-project-name-1a2b",
expected: "super-long-project-name", // 4-char hash
},
{
name: "prefix with 5-char hash",
issueID: "my-app-1a2b3",
expected: "my-app", // 5-char hash
},
{
name: "prefix with 6-char hash",
issueID: "web-app-a1b2c3",
expected: "web-app", // 6-char hash
},
{
name: "uppercase hash",
issueID: "my-app-A3F8E9",
expected: "my-app", // Uppercase hash should work
},
{
name: "mixed case hash",
issueID: "proj-AbCd12",
expected: "proj", // Mixed case hash should work
},
{
name: "3-char hash with hyphenated prefix",
issueID: "document-intelligence-0sa",
expected: "document-intelligence", // 3-char hash (base36) should use last hyphen
},
{
name: "3-char hash with multi-part prefix",
issueID: "my-cool-app-1x7",
expected: "my-cool-app", // 3-char base36 hash
},
{
name: "3-char all-letters suffix (now treated as hash, GH #446)",
issueID: "test-proj-abc",
expected: "test-proj", // 3-char all-letter now accepted as hash (GH #446)
},
// GH#405: multi-hyphen prefixes with hash suffixes
{
name: "hacker-news prefix with hash (GH#405)",
issueID: "hacker-news-ko4",
expected: "hacker-news", // Not "hacker" - 3-char hash uses last hyphen
},
{
name: "hacker-news prefix with numeric suffix (GH#405)",
issueID: "hacker-news-42",
expected: "hacker-news", // Numeric suffix uses last hyphen
},
{
name: "me-py-toolkit prefix with hash (GH#405)",
issueID: "me-py-toolkit-a1b",
expected: "me-py-toolkit", // 3-part prefix, 3-char hash
},
{
name: "me-py-toolkit prefix with 4-char hash (GH#405)",
issueID: "me-py-toolkit-1a2b",
expected: "me-py-toolkit", // 3-part prefix, 4-char hash with digits
},
{
name: "me-py-toolkit prefix with numeric suffix (GH#405)",
issueID: "me-py-toolkit-7",
expected: "me-py-toolkit", // 3-part prefix, numeric suffix
},
{
name: "three-hyphen prefix with 3-char all-letter hash",
issueID: "my-cool-web-app-bat",
expected: "my-cool-web-app", // 4-part prefix, 3-char all-letter hash
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := utils.ExtractIssuePrefix(tt.issueID)
if result != tt.expected {
t.Errorf("utils.ExtractIssuePrefix(%q) = %q; want %q", tt.issueID, result, tt.expected)
}
})
}
}
func TestExtractIssuePrefixKnown(t *testing.T) {
tests := []struct {
name string
issueID string
knownPrefixes []string
expected string
}{
{
name: "known prefix matches multi-dash",
issueID: "me-py-toolkit-abcd",
knownPrefixes: []string{"me-py-toolkit"},
expected: "me-py-toolkit",
},
{
name: "overlapping prefixes: longest wins",
issueID: "hq-cv-test",
knownPrefixes: []string{"hq", "hq-cv"},
expected: "hq-cv",
},
{
name: "overlapping prefixes reversed order: longest still wins",
issueID: "hq-cv-test",
knownPrefixes: []string{"hq-cv", "hq"},
expected: "hq-cv",
},
{
name: "no known prefix: falls back to heuristic",
issueID: "vc-baseline-test",
knownPrefixes: []string{"bd"},
expected: "vc", // heuristic: word-like suffix falls back to first hyphen
},
{
name: "known prefix with trailing hyphen is normalized",
issueID: "hacker-news-ko4",
knownPrefixes: []string{"hacker-news-"},
expected: "hacker-news",
},
{
name: "known prefix with whitespace is normalized",
issueID: "hacker-news-ko4",
knownPrefixes: []string{" hacker-news "},
expected: "hacker-news",
},
{
name: "empty known prefixes: falls back to heuristic",
issueID: "bd-a3f8e9",
knownPrefixes: nil,
expected: "bd", // heuristic result
},
{
name: "simple known prefix",
issueID: "bd-a3f8e9",
knownPrefixes: []string{"bd"},
expected: "bd",
},
{
name: "known prefix among several",
issueID: "hacker-news-ko4",
knownPrefixes: []string{"bd", "gt", "hacker-news"},
expected: "hacker-news",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := utils.ExtractIssuePrefixKnown(tt.issueID, tt.knownPrefixes)
if result != tt.expected {
t.Errorf("utils.ExtractIssuePrefixKnown(%q, %v) = %q; want %q",
tt.issueID, tt.knownPrefixes, result, tt.expected)
}
})
}
}
func TestExtractIssueNumber(t *testing.T) {
tests := []struct {
name string
issueID string
expected int
}{
{
name: "simple number",
issueID: "bd-123",
expected: 123,
},
{
name: "hash ID (no number)",
issueID: "bd-a3f8e9",
expected: 0,
},
{
name: "hierarchical with number",
issueID: "bd-42.1.2",
expected: 42,
},
{
name: "no hyphen",
issueID: "invalid",
expected: 0,
},
{
name: "empty string",
issueID: "",
expected: 0,
},
{
name: "zero",
issueID: "bd-0",
expected: 0,
},
{
name: "large number",
issueID: "bd-999999",
expected: 999999,
},
{
name: "number with text after",
issueID: "bd-123abc",
expected: 123,
},
{
name: "hyphenated prefix with number",
issueID: "alpha-beta-7",
expected: 7,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := utils.ExtractIssueNumber(tt.issueID)
if result != tt.expected {
t.Errorf("utils.ExtractIssueNumber(%q) = %d; want %d", tt.issueID, result, tt.expected)
}
})
}
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(s) > len(substr) &&
(s[:len(substr)] == substr || s[len(s)-len(substr):] == substr ||
findSubstring(s, substr)))
}
func findSubstring(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
// TestResolvePartialID_CrossPrefix tests resolution of IDs with different prefixes
// than the configured prefix. This is the GH#1513 fix for multi-repo scenarios
// where issues from different rigs (with different prefixes) are hydrated into
// a single database.
func TestResolvePartialID_CrossPrefix(t *testing.T) {
ctx := context.Background()
store := newTestStore(t)
// Create issues with different prefixes (simulating multi-repo hydration)
hqIssue := &types.Issue{
ID: "hq-abc12",
Title: "HQ Issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
aapIssue := &types.Issue{
ID: "aap-4ar",
Title: "AAP Issue from different rig",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
crIssue := &types.Issue{
ID: "cr-xyz99",
Title: "CR Issue from another rig",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
if err := store.CreateIssue(ctx, hqIssue, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, aapIssue, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, crIssue, "test"); err != nil {
t.Fatal(err)
}
// Set config prefix to "hq" (the "town" prefix)
if err := store.SetConfig(ctx, "issue_prefix", "hq"); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
input string
expected string
shouldError bool
}{
{
name: "configured prefix - full ID",
input: "hq-abc12",
expected: "hq-abc12",
},
{
name: "configured prefix - short ID",
input: "abc12",
expected: "hq-abc12",
},
{
name: "different prefix - full ID (GH#1513)",
input: "aap-4ar",
expected: "aap-4ar",
},
{
name: "different prefix - another rig (GH#1513)",
input: "cr-xyz99",
expected: "cr-xyz99",
},
{
name: "different prefix - short ID falls back to substring match",
input: "4ar",
expected: "aap-4ar",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := utils.ResolvePartialID(ctx, store, tt.input)
if tt.shouldError {
if err == nil {
t.Errorf("utils.ResolvePartialID(%q) expected error, got nil", tt.input)
}
} else {
if err != nil {
t.Errorf("utils.ResolvePartialID(%q) unexpected error: %v", tt.input, err)
}
if result != tt.expected {
t.Errorf("utils.ResolvePartialID(%q) = %q; want %q", tt.input, result, tt.expected)
}
}
})
}
}
// TestResolvePartialID_AllowedPrefixes verifies that config-aware prefix detection
// in ResolvePartialID correctly handles multi-hyphen prefixes when allowed_prefixes
// is set. This exercises both the normalization path (hasKnownPrefix) and the
// hash extraction path (ExtractIssuePrefixKnown).
func TestResolvePartialID_AllowedPrefixes(t *testing.T) {
ctx := context.Background()
store := newTestStore(t)
// Create issues with multi-hyphen prefixes
hackerNews := &types.Issue{
ID: "hacker-news-ko4",
Title: "Hacker News item",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
pyToolkit := &types.Issue{
ID: "me-py-toolkit-a1b",
Title: "Python toolkit issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
hqCvIssue := &types.Issue{
ID: "hq-cv-7x2",
Title: "HQ CV issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
if err := store.CreateIssue(ctx, hackerNews, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, pyToolkit, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, hqCvIssue, "test"); err != nil {
t.Fatal(err)
}
// Configure primary prefix and allowed prefixes
if err := store.SetConfig(ctx, "issue_prefix", "hq"); err != nil {
t.Fatal(err)
}
if err := store.SetConfig(ctx, "allowed_prefixes", "hacker-news, me-py-toolkit, hq-cv"); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
input string
expected string
}{
{
name: "short hash resolves multi-dash prefix (ko4 -> hacker-news-ko4)",
input: "ko4",
expected: "hacker-news-ko4",
},
{
name: "short hash resolves multi-dash prefix (a1b -> me-py-toolkit-a1b)",
input: "a1b",
expected: "me-py-toolkit-a1b",
},
{
name: "full multi-dash ID is not mangled (hacker-news-ko4)",
input: "hacker-news-ko4",
expected: "hacker-news-ko4",
},
{
name: "full allowed-prefix ID resolves as-is (me-py-toolkit-a1b)",
input: "me-py-toolkit-a1b",
expected: "me-py-toolkit-a1b",
},
{
name: "overlapping prefix: hq-cv-7x2 not mangled to hq-hq-cv-7x2",
input: "hq-cv-7x2",
expected: "hq-cv-7x2",
},
{
name: "short hash with overlapping prefix (7x2 -> hq-cv-7x2)",
input: "7x2",
expected: "hq-cv-7x2",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := utils.ResolvePartialID(ctx, store, tt.input)
if err != nil {
t.Errorf("utils.ResolvePartialID(%q) unexpected error: %v", tt.input, err)
}
if result != tt.expected {
t.Errorf("utils.ResolvePartialID(%q) = %q; want %q", tt.input, result, tt.expected)
}
})
}
}
// TestResolvePartialID_Wisp verifies that wisps (ephemeral issues) are resolvable
// by partial ID. This exercises the explicit wisp fallback in ResolvePartialID.
func TestResolvePartialID_Wisp(t *testing.T) {
ctx := context.Background()
store := newTestStore(t)
// Create a wisp (ephemeral issue) with a wisp-prefixed ID
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
}{
{
name: "full wisp ID",
input: "bd-wisp-t3st",
expected: "bd-wisp-t3st",
},
{
name: "partial hash",
input: "t3st",
expected: "bd-wisp-t3st",
},
{
name: "wisp prefix with hash",
input: "wisp-t3st",
expected: "bd-wisp-t3st",
},
{
name: "partial hash prefix resolves",
input: "t3s",
expected: "bd-wisp-t3st", // "t3s" is a leading prefix of the wisp's bare hash "t3st"
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := utils.ResolvePartialID(ctx, store, tt.input)
if err != nil {
t.Errorf("utils.ResolvePartialID(%q) unexpected error: %v", tt.input, err)
}
if result != tt.expected {
t.Errorf("utils.ResolvePartialID(%q) = %q; want %q", tt.input, result, tt.expected)
}
})
}
}
// TestResolvePartialID_TitleFalsePositive verifies that when the search query
// matches an issue's title but NOT its ID, the in-memory filter correctly
// rejects it. This is important because the optimization passes hashPart as
// the search query (matching title/description/ID) instead of loading all issues.
func TestResolvePartialID_TitleFalsePositive(t *testing.T) {
ctx := context.Background()
store := newTestStore(t)
// Issue whose title contains "abc12" but ID does NOT
decoy := &types.Issue{
ID: "bd-xyz99",
Title: "See abc12 for reference",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
// Issue whose ID actually contains "abc12"
target := &types.Issue{
ID: "bd-abc12",
Title: "Real issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
}
if err := store.CreateIssue(ctx, decoy, "test"); err != nil {
t.Fatal(err)
}
if err := store.CreateIssue(ctx, target, "test"); err != nil {
t.Fatal(err)
}
if err := store.SetConfig(ctx, "issue_prefix", "bd-"); err != nil {
t.Fatal(err)
}
// Search for "abc12" — should find bd-abc12, NOT bd-xyz99
result, err := utils.ResolvePartialID(ctx, store, "abc12")
if err != nil {
t.Fatalf("utils.ResolvePartialID(%q) unexpected error: %v", "abc12", err)
}
if result != "bd-abc12" {
t.Errorf("utils.ResolvePartialID(%q) = %q; want %q (title match should be rejected)", "abc12", result, "bd-abc12")
}
}
// TestResolvePartialID_WispSubstringCollision is a regression test for gcy-g4o:
// a real bead (gcy-oqf) and an ephemeral wisp (gcy-wisp-goqfo) coexist, and a
// lookup of gcy-oqf that missed the exact-ID fast path fell through to partial
// matching, where the wisp's hash "wisp-goqfo" contains the substring "oqf".
// Partial matching has been leading-prefix only since #4939 (strings.HasPrefix
// replaced strings.Contains at both call sites), and neither "wisp-goqfo" nor
// the stripped "goqfo" starts with "oqf". With only the wisp stored, nothing
// short-circuits the partial path, so both forms of the id must come back not
// found. Once the real bead exists, the exact-ID fast path returns it before
// partial matching runs.
func TestResolvePartialID_WispSubstringCollision(t *testing.T) {
ctx := context.Background()
store := newTestStore(t)
real := &types.Issue{
ID: "gcy-oqf",
Title: "Real bug bead",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeBug,
}
wisp := &types.Issue{
ID: "gcy-wisp-goqfo",
Title: "Order wisp",
Status: types.StatusClosed,
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", "gcy"); err != nil {
t.Fatal(err)
}
// The wisp alone must not answer for gcy-oqf: this is the lookup gcy-g4o
// silently resolved to the wisp.
for _, input := range []string{"gcy-oqf", "oqf"} {
if got, err := utils.ResolvePartialID(ctx, store, input); err == nil {
t.Errorf("utils.ResolvePartialID(%q) = %q; want not found (wisp substring collision)", input, got)
}
}
if err := store.CreateIssue(ctx, real, "test"); err != nil {
t.Fatal(err)
}
// The real bead must still resolve to itself. This lookup is answered by
// the exact-ID fast path, so it passes under any partial matcher; the
// wisp-only loop above is the substring-collision assertion.
result, err := utils.ResolvePartialID(ctx, store, "gcy-oqf")
if err != nil {
t.Fatalf("utils.ResolvePartialID(%q) unexpected error: %v", "gcy-oqf", err)
}
if result != "gcy-oqf" {
t.Errorf("utils.ResolvePartialID(%q) = %q; want %q (the exact ID must resolve to itself)", "gcy-oqf", result, "gcy-oqf")
}
}
// TestResolvePartialID_WispLastSegment verifies that a bare wisp hash resolves
// to its wisp ("t3st" finds "bd-wisp-t3st") through the wisp fallback's exact
// branch, even beside a longer wisp hash it abbreviates. The Dolt store merges
// wisps into the unfiltered search, so a matcher that let the first loop claim
// "wisp-t3st" as an abbreviation of "t3st" would make this lookup ambiguous
// with bd-wisp-t3stzz instead of exact.
func TestResolvePartialID_WispLastSegment(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,
}
sibling := &types.Issue{
ID: "bd-wisp-t3stzz",
Title: "Sibling 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.CreateIssue(ctx, sibling, "test"); err != nil {
t.Fatal(err)
}
if err := store.SetConfig(ctx, "issue_prefix", "bd"); err != nil {
t.Fatal(err)
}
// "t3st" is exactly the hash of bd-wisp-t3st and must resolve to it.
result, err := utils.ResolvePartialID(ctx, store, "t3st")
if err != nil {
t.Fatalf("utils.ResolvePartialID(%q) unexpected error: %v", "t3st", err)
}
if result != "bd-wisp-t3st" {
t.Errorf("utils.ResolvePartialID(%q) = %q; want %q", "t3st", result, "bd-wisp-t3st")
}
}