* fix(utils): refuse a bare jq/JS sentinel as an issue ID
`jq -r` prints the literal string "null" when a selector misses, and JS
tooling prints "undefined". Both are a valid partial-ID shape, so
ResolvePartialID accepted them and resolved them through its leading-prefix
abbreviation branch: any issue whose hash began with the token became the
target, and the write reported success naming an issue the caller never
mentioned.
Reproduced on stock beads at a07794015, embedded Dolt, scratch workspace,
no orchestrator:
bd init --prefix bd
bd create --id bd-null3t0 "decoy: must not be touched"
bd update null --status closed
✓ Updated issue: bd-null3t0 — decoy: must not be touched (exit 0)
HasPrefix), so this needs a hash that begins with the token — the same case
The guard sits in ResolvePartialID rather than in a command because
internal/utils/id_parser.go is the only ID-resolution entry point in the
repository: 52 non-test call sites across 29 files, plus 2 through the
ResolvePartialIDs wrapper, and the four cmd/bd/*_proxied_server.go twins
resolve through the same function. One guard covers the direct, embedded and
proxied-server paths uniformly.
The riskiest thing this does is add a refusal to the resolver every command
shares. An ID that merely contains a token (bd-null, null3t0,
undefined-behavior) is unaffected, abbreviation matching is otherwise
unchanged, and the empty string already failed — it now says why.
Case folding is deliberate: NULL is what SQL-shaped tooling prints.
Whitespace is trimmed for the comparison only, never for resolution.
The tests use a nil store so the ordering is observable: reaching the
"storage is nil" error proves the guard did not fire. Mutation-tested — with
the guard reverted all eight refused inputs fail and the seven accepted
inputs still pass.
Fixes #6214
Refs #5393
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Cherub Kumar
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SDrKFyrfKTKM5J9yFbW7uA
* fix(utils): refuse none/nil too, and list the new test in the Bazel srcs
Maintainer review fixes for #6215, review iteration 1. Both lanes and the
scorecard returned approve with no required changes; this commit takes the two
actionable minors, both of which land inside the PR's own change.
Taken:
- Behavioral Correctness (minor). `bd update None --status closed` still reached
the leading-prefix abbreviation branch: strings.ToLower("None") is "none" and
every character passes looksLikePartialIDHash, so it could silently write to
whichever issue's hash begins "none" and exit 0. `nil` is the same class. That
is the identical silent-wrong-write harm this PR exists to prevent, and the
remedy lands in the switch the PR just added, so "none" and "nil" join the
same case arm and the refused-inputs table.
The error text is generalized with them: "none" is Python and "nil" is
Go/Ruby, so the previous jq/JS-only wording would have mis-described the two
new tokens.
- Change Impact / Blast Radius (minor). The PR adds two TestX functions that
`go list` selects for internal/utils but that Bazel's utils_test target could
not compile or run -- exactly what tools/bazel/equivalence.py reports as
`missing`. Gazelle's verdict, not a hand-guess: `make bazel-sync` produced
exactly `+ "id_parser_sentinel_test.go",` for internal/utils/BUILD.bazel. It
also rewrote 13 other BUILD.bazel files (pre-existing base drift), which is out
of scope here, so that output was reverted and only this PR's row re-applied at
gazelle's chosen slot. utils_test is 10 entries, sorted, no duplicates, all on
disk.
Note the review predicted the regen would also add `+ "//internal/debug",` to
this file's go_library deps "once rebased on main". It did not at this base,
because the import that needs it is not present here -- that dep is
base-owned drift and is already tracked separately.
Over-refusal is guarded, not assumed: the pre-existing accepted-inputs test
(nullos, null3t0) and the whole ResolvePartialID suite -- cross-prefix,
allowed-prefixes, wisp, title-false-positive -- all still pass.
Validation: gofmt clean, go build ./... and CGO_ENABLED=1 go vet ./internal/utils/
clean; 42 PASS / 0 FAIL / 0 SKIP over -run "Sentinel|ResolvePartialID". The new
rows are mutation-proved: dropping "none" from the case arm reds
TestResolvePartialIDRefusesSentinelTokens, and restoring returns rc=0.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Cherub Kumar <5449665+ckumar1@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
368 lines
13 KiB
Go
368 lines
13 KiB
Go
// Package utils provides utility functions for issue ID parsing and resolution.
|
|
package utils
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/steveyegge/beads/internal/debug"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
// ErrAmbiguousID is the sentinel wrapped into the error ResolvePartialID
|
|
// returns when a partial ID matches more than one issue. Callers use
|
|
// errors.Is(err, ErrAmbiguousID) to distinguish "ambiguous" from
|
|
// "not found" and surface the candidate list instead of a generic failure.
|
|
var ErrAmbiguousID = errors.New("ambiguous issue ID")
|
|
|
|
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)
|
|
GetConfig(ctx context.Context, key string) (string, error)
|
|
}
|
|
|
|
// parseIssueID ensures an issue ID has the configured prefix.
|
|
// If the input already has the prefix (e.g., "bd-a3f8e9"), returns it as-is.
|
|
// If the input lacks the prefix (e.g., "a3f8e9"), adds the configured prefix.
|
|
// Works with hierarchical IDs too: "a3f8e9.1.2" → "bd-a3f8e9.1.2"
|
|
func parseIssueID(input string, prefix string) string {
|
|
if prefix == "" {
|
|
prefix = "bd-"
|
|
}
|
|
|
|
if strings.HasPrefix(input, prefix) {
|
|
return input
|
|
}
|
|
|
|
return prefix + input
|
|
}
|
|
|
|
// ResolvePartialID resolves a potentially partial issue ID to a full ID.
|
|
// Supports:
|
|
// - Full IDs: "bd-a3f8e9" or "a3f8e9" → "bd-a3f8e9"
|
|
// - Without hyphen: "bda3f8e9" or "wya3f8e9" → "bd-a3f8e9"
|
|
// - Partial IDs: "a3f8" → "bd-a3f8e9" (if unique match)
|
|
// - Hierarchical: "a3f8e9.1" → "bd-a3f8e9.1"
|
|
//
|
|
// Returns an error if:
|
|
// - The input is a bare tooling sentinel ("", "null", "undefined", "none", "nil")
|
|
// - No issue found matching the ID
|
|
// - Multiple issues match (ambiguous prefix)
|
|
func ResolvePartialID(ctx context.Context, store PartialIDResolverStore, input string) (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)) {
|
|
case "":
|
|
return "", fmt.Errorf("refusing an empty string as an issue ID")
|
|
case "null", "undefined", "none", "nil":
|
|
return "", fmt.Errorf("refusing %q as an issue ID: that is what tooling prints for a missing value (jq/JS null and undefined, Python None, Go/Ruby nil), so the caller's selector matched nothing", input)
|
|
}
|
|
|
|
if store == nil {
|
|
return "", fmt.Errorf("cannot resolve issue ID %q: storage is nil", input)
|
|
}
|
|
|
|
// Fast path: Use SearchIssues with exact ID filter (GH#942).
|
|
// This uses the same query path as "bd list --id", ensuring consistency.
|
|
// Previously we used GetIssue which could fail in cases where SearchIssues
|
|
// with filter.IDs succeeded, likely due to subtle query differences.
|
|
exactFilter := types.IssueFilter{IDs: []string{input}}
|
|
if issues, err := store.SearchIssues(ctx, "", exactFilter); err == nil && len(issues) > 0 {
|
|
return issues[0].ID, nil
|
|
}
|
|
|
|
// Get the configured prefix
|
|
prefix, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil || prefix == "" {
|
|
prefix = "bd"
|
|
}
|
|
|
|
// Ensure prefix has hyphen for ID format
|
|
prefixWithHyphen := prefix
|
|
if !strings.HasSuffix(prefix, "-") {
|
|
prefixWithHyphen = prefix + "-"
|
|
}
|
|
|
|
// Build known prefixes from config for deterministic multi-hyphen prefix handling.
|
|
// This avoids relying solely on looksLikePrefixedID heuristics when the repo
|
|
// explicitly declares which prefixes are valid.
|
|
knownPrefixes := []string{strings.TrimSuffix(prefix, "-")}
|
|
if allowed, aErr := store.GetConfig(ctx, "allowed_prefixes"); aErr == nil && allowed != "" {
|
|
for _, p := range strings.Split(allowed, ",") {
|
|
p = strings.TrimSpace(p)
|
|
p = strings.TrimSuffix(p, "-")
|
|
if p != "" {
|
|
knownPrefixes = append(knownPrefixes, p)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Normalize input:
|
|
// 1. If it has the full prefix with hyphen (bd-a3f8e9), use as-is
|
|
// 2. If it starts with any known/allowed prefix, use as-is (config-aware cross-prefix)
|
|
// 3. If it has ANY prefix (heuristic fallback), use as-is for cross-prefix lookup
|
|
// 4. Otherwise, add prefix with hyphen (handles both bare hashes and prefix-without-hyphen cases)
|
|
|
|
var normalizedID string
|
|
|
|
if strings.HasPrefix(input, prefixWithHyphen) {
|
|
// Already has configured prefix with hyphen: "bd-a3f8e9"
|
|
normalizedID = input
|
|
} else if hasKnownPrefix(input, knownPrefixes) {
|
|
// Starts with a known/allowed prefix (e.g., "hacker-news-ko4" when allowed_prefixes includes "hacker-news")
|
|
normalizedID = input
|
|
} else if looksLikePrefixedID(input) {
|
|
// Has a different prefix (e.g., "aap-4ar" when configured prefix is "hq-")
|
|
// Don't prepend configured prefix - use as-is for cross-prefix lookup (GH#1513)
|
|
normalizedID = input
|
|
} else {
|
|
// Bare hash or prefix without hyphen: "a3f8e9", "07b8c8", "bda3f8e9" → all get prefix with hyphen added
|
|
normalizedID = prefixWithHyphen + input
|
|
}
|
|
|
|
// Try exact match on normalized ID using SearchIssues (GH#942)
|
|
normalizedFilter := types.IssueFilter{IDs: []string{normalizedID}}
|
|
if issues, err := store.SearchIssues(ctx, "", normalizedFilter); err == nil && len(issues) > 0 {
|
|
return issues[0].ID, nil
|
|
}
|
|
|
|
// If exact match failed, try substring search.
|
|
// Use the hash part as a search query to leverage SQL-level filtering
|
|
// (id LIKE %hash%) instead of loading ALL issues into memory.
|
|
// On large databases (23k+ issues over MySQL wire protocol), loading all
|
|
// issues took 60+ seconds; with SQL filtering it's near-instant.
|
|
hashPart := strings.TrimPrefix(normalizedID, prefixWithHyphen)
|
|
searchPart, ok := partialIDSearchPart(hashPart)
|
|
if !ok {
|
|
return "", fmt.Errorf("no issue found matching %q", input)
|
|
}
|
|
|
|
// Narrow projection: this loop only reads the .ID field, so use the
|
|
// SearchIssueIDs path instead of SearchIssues. Avoids hydrating all
|
|
// 45+ issue columns (including big TEXT fields like description, design,
|
|
// notes, metadata, payload) only to discard them.
|
|
filter := types.IssueFilter{}
|
|
ids, err := store.SearchIssueIDs(ctx, searchPart, filter)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to search issues: %w", err)
|
|
}
|
|
|
|
var matches []string
|
|
var exactMatch string
|
|
|
|
for _, id := range ids {
|
|
// Check for exact full ID match first (case: user typed full ID with different prefix)
|
|
if id == input {
|
|
exactMatch = id
|
|
break
|
|
}
|
|
|
|
// Extract hash from each issue using config-aware prefix extraction.
|
|
// This correctly handles multi-hyphen prefixes (e.g., "hacker-news-ko4"
|
|
// yields hash "ko4", not "news-ko4" from naive first-hyphen split).
|
|
var issueHash string
|
|
if p := ExtractIssuePrefixKnown(id, knownPrefixes); p != "" && strings.HasPrefix(id, p+"-") {
|
|
issueHash = id[len(p)+1:]
|
|
} else {
|
|
issueHash = id
|
|
}
|
|
|
|
// Check for exact hash match (excluding hierarchical children)
|
|
if issueHash == hashPart {
|
|
exactMatch = id
|
|
// Don't break - keep searching in case there's a full ID match
|
|
} else if strings.HasPrefix(issueHash, hashPart) {
|
|
// 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)
|
|
}
|
|
}
|
|
|
|
// Prefer exact match over substring matches
|
|
if exactMatch != "" {
|
|
return exactMatch, nil
|
|
}
|
|
|
|
// Fallback: explicitly search wisps table for partial ID resolution.
|
|
// DoltStore.SearchIssues merges wisps when Ephemeral is nil, but
|
|
// transaction-level SearchIssues does not. This ensures wisps are
|
|
// always resolvable by partial ID.
|
|
if len(matches) == 0 {
|
|
ephTrue := true
|
|
wispFilter := types.IssueFilter{Ephemeral: &ephTrue}
|
|
if wispIDs, wispErr := store.SearchIssueIDs(ctx, searchPart, wispFilter); wispErr == nil {
|
|
for _, wID := range wispIDs {
|
|
if wID == input {
|
|
return wID, nil
|
|
}
|
|
var wHash string
|
|
if p := ExtractIssuePrefixKnown(wID, knownPrefixes); p != "" && strings.HasPrefix(wID, p+"-") {
|
|
wHash = wID[len(p)+1:]
|
|
} else {
|
|
wHash = wID
|
|
}
|
|
// Wisp IDs are shaped "<prefix>-wisp-<hash>", so wHash here is
|
|
// the composite "wisp-<hash>". Strip the literal "wisp-" infix
|
|
// before comparing so bare-hash lookups (e.g. "t3st") resolve
|
|
// against the isolated hash, not the full "wisp-t3st" string.
|
|
wispHash := strings.TrimPrefix(wHash, "wisp-")
|
|
if wHash == hashPart || wispHash == hashPart {
|
|
exactMatch = wID
|
|
} else if strings.HasPrefix(wispHash, hashPart) {
|
|
matches = append(matches, wID)
|
|
}
|
|
}
|
|
if exactMatch != "" {
|
|
return exactMatch, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
if len(matches) == 0 {
|
|
return "", fmt.Errorf("no issue found matching %q", input)
|
|
}
|
|
|
|
// Sort so the ambiguity error lists IDs deterministically. SearchIssues return
|
|
// order is not a contract for ambiguous matches, so sorting by ID pins the same
|
|
// message for every storage implementation.
|
|
sort.Strings(matches)
|
|
|
|
if len(matches) > 1 {
|
|
return "", fmt.Errorf("%w: %q matches %d issues: %v\nUse more characters to disambiguate", ErrAmbiguousID, input, len(matches), matches)
|
|
}
|
|
|
|
// Sole leading-prefix match. Every other return from this function is an
|
|
// exact match (or a prefix-normalized exact match), so this is the one path
|
|
// that hands back an issue the caller did not name.
|
|
resolved := matches[0]
|
|
if shouldNotifyPartialResolution(input, resolved, debug.IsQuiet(), os.Getenv("BD_NO_PARTIAL_ID_NOTICE")) {
|
|
emitPartialResolutionNotice(input, resolved)
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
// shouldNotifyPartialResolution is the testable predicate behind the
|
|
// partial-resolution notice. It takes the quiet flag and the suppression env
|
|
// value as parameters so tests can cover every combination, the same shape as
|
|
// shouldWarnImplicitBlocksDefault in cmd/bd/dep.go.
|
|
//
|
|
// Deliberately NOT gated on stderr being a terminal, which is where it departs
|
|
// from that precedent. The implicit-blocks warning tells an interactive
|
|
// operator about a default they chose; this one tells a caller that the issue
|
|
// it is about to act on is not the issue it named, and the callers most exposed
|
|
// to that — scripts, hooks and agents — are exactly the non-TTY ones. Gating on
|
|
// a TTY would silence it precisely where it is most needed.
|
|
func shouldNotifyPartialResolution(input, resolved string, quiet bool, noNotifyEnv string) bool {
|
|
if resolved == "" || resolved == input {
|
|
return false
|
|
}
|
|
// --quiet is documented as "Suppress non-essential output (errors only)",
|
|
// matching how the other non-error stderr notices behave.
|
|
if quiet {
|
|
return false
|
|
}
|
|
// Explicit opt-out, following the BD_NO_DEP_TYPE_WARNING precedent.
|
|
if noNotifyEnv != "" {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// emitPartialResolutionNotice writes the notice. Split from the gate so the
|
|
// message text can be asserted under a captured stderr.
|
|
//
|
|
// stderr, never stdout: --json payloads and piped stdout stay byte-for-byte
|
|
// unchanged, so this cannot break a parsing caller.
|
|
func emitPartialResolutionNotice(input, resolved string) {
|
|
fmt.Fprintf(os.Stderr, "note: %q is not an exact issue ID; resolved to %s (silence with --quiet or BD_NO_PARTIAL_ID_NOTICE=1)\n", input, resolved) //nolint:gosec // G705: stderr, not a browser context
|
|
}
|
|
|
|
func partialIDSearchPart(hashPart string) (string, bool) {
|
|
if !looksLikePartialIDHash(hashPart) {
|
|
return "", false
|
|
}
|
|
searchPart := hashPart
|
|
if idx := strings.LastIndex(hashPart, "-"); idx >= 0 && idx < len(hashPart)-1 {
|
|
suffix := hashPart[idx+1:]
|
|
if looksLikePartialIDHash(suffix) {
|
|
searchPart = suffix
|
|
}
|
|
}
|
|
return searchPart, true
|
|
}
|
|
|
|
func looksLikePartialIDHash(input string) bool {
|
|
if input == "" || strings.Contains(input, " ") {
|
|
return false
|
|
}
|
|
for _, c := range input {
|
|
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' || c == '.') {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// ResolvePartialIDs resolves multiple potentially partial issue IDs.
|
|
// Returns the resolved IDs and any errors encountered.
|
|
func ResolvePartialIDs(ctx context.Context, store PartialIDResolverStore, inputs []string) ([]string, error) {
|
|
var resolved []string
|
|
for _, input := range inputs {
|
|
fullID, err := ResolvePartialID(ctx, store, input)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
resolved = append(resolved, fullID)
|
|
}
|
|
return resolved, nil
|
|
}
|
|
|
|
// looksLikePrefixedID checks if input appears to already have a prefix.
|
|
// A prefixed ID has the format "prefix-hash" where prefix is 1-8 lowercase
|
|
// letters/numbers and hash is alphanumeric (potentially with dots for hierarchical IDs).
|
|
// Examples: "aap-4ar", "bd-a3f8e9", "myproject-abc.1"
|
|
func looksLikePrefixedID(input string) bool {
|
|
idx := strings.Index(input, "-")
|
|
if idx <= 0 || idx > 8 {
|
|
// No hyphen, hyphen at start, or prefix too long
|
|
return false
|
|
}
|
|
|
|
prefix := input[:idx]
|
|
suffix := input[idx+1:]
|
|
|
|
// Prefix must be non-empty lowercase alphanumeric
|
|
for _, c := range prefix {
|
|
if !((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
|
|
return false
|
|
}
|
|
}
|
|
|
|
// Suffix must be non-empty and start with alphanumeric
|
|
if len(suffix) == 0 {
|
|
return false
|
|
}
|
|
first := rune(suffix[0])
|
|
if !((first >= 'a' && first <= 'z') || (first >= '0' && first <= '9')) {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// hasKnownPrefix checks if input starts with any of the known prefixes followed
|
|
// by a hyphen. Used to detect already-prefixed input before falling back to the
|
|
// looksLikePrefixedID heuristic.
|
|
func hasKnownPrefix(input string, knownPrefixes []string) bool {
|
|
for _, p := range knownPrefixes {
|
|
if p != "" && strings.HasPrefix(input, p+"-") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|