* Refuse reserved words and fuzzy id matches on bd comment writes
bd comment <id> [text...] treated its first argument as an id via the
same abbreviation-tolerant resolver used everywhere else, with no
protection against the id slot holding something that was never meant
to be an id. Two related failure modes came from that:
- "bd comment list <id>", a typo for "bd comments list" (or "bd
comments <id>"), silently ran with id="list" and text="<id>" instead
of erroring.
- If "list" (or any other stray first word) happened to be a
leading-prefix abbreviation of some unrelated issue's hash, the
resolver picked that issue and the comment landed there instead of
failing with "not found". This is exactly what happened in
production: 15+ automated sessions made the "bd comment list <id>"
typo over two days, and because "list" was a leading-prefix
abbreviation of an unrelated wisp's hash ("list3t0"), every one of
them wrote a garbage comment onto that wisp.
Fixes both, independently:
- checkCommentIDNotReservedWord rejects list/add/rm/delete as the id
argument before any resolution is attempted, mirroring the existing
"bd comments list" misplaced-subcommand guard.
- ResolvePartialIDExact (internal/utils) is an exact-match sibling of
ResolvePartialID: identical exact-ID and exact-hash matching
(including a wisp's hash with its "wisp-" infix stripped), but never
falls through to leading-prefix abbreviation matching. bd comment
now resolves through this via a new resolveAndGetIssueForMutationExact,
which keeps the existing cross-rig prefix-routing and contributor
auto-routing fallbacks intact (tightened to exact matching too) so
cross-repo comment writes by full id are unaffected.
Every other caller of the touched shared functions (ResolvePartialID,
resolveAndGetIssueForMutation, resolveViaPrefixRoutingWithAccess,
resolveViaAutoRouting) keeps its exact current behavior — the new exact
variants are additive, and existing call sites were updated to pass an
explicit "false" for the new parameter rather than changing behavior.
Testing: go build/go vet pass across the whole module. The new pure-Go
guard test and a hand-rolled in-memory PartialIDResolverStore test both
run and pass without Docker or a live Dolt server, and the latter
reproduces the original collision (ResolvePartialID) before asserting
the fix (ResolvePartialIDExact) in the same test, so the fixture is
proven to exercise the real failure mode rather than trivially passing.
The Dolt-container-backed table tests (mirroring the existing
TestResolvePartialID_Wisp / TestResolvePartialID suites) could not be
run locally (no Docker in this environment) — they compile and skip
cleanly the same way the pre-existing suite does, and will run for real
in CI.
* fix(ga-wpdum): address steveyegge's PR #5393 review items b/c/d
Review (2026-08-07, posted as a PR comment, not a formal GitHub review —
hence reviewDecision stayed empty) asked for four things before merge; (a)
rebase onto #5369 was already done (2026-09-07, see PR history). This
addresses the rest:
(c) MAJOR — comment writes require an exact id, but a REAL abbreviated id
was refused with "no issue found matching %q", which is false: the issue
exists, only the abbreviation was rejected. ResolvePartialIDExact now
distinguishes the two failure modes via a new sentinel,
ErrAbbreviatedIDNotAllowed, wrapped only when the input would have resolved
via leading-prefix abbreviation. bd comment's RunE checks errors.Is against
it and returns a truthful, actionable message pointing at `bd show <id>`
instead of claiming the issue is missing. Docs (hash-ids.md) and CHANGELOG
updated with the read/write carve-out this creates.
(b) MAJOR — investigated whether the proxied-server comment path needed the
same exact-match treatment. It doesn't: resolveCommentTargetProxied resolves
via workapi.GetIssueOrWisp with the raw id, which bottoms out in
issueSQLRepositoryImpl.Get's plain "WHERE id = ?" — SQL exact equality, with
no abbreviation-matching layer anywhere in that call chain (unlike the
embedded path's utils.ResolvePartialID). Comment writes over the proxied
server were already exact-id-only before this PR. Per the review's own
fallback ("extend exact matching to that path, or document/test the gap
explicitly"), added a regression test locking this in rather than leaving it
implicit.
(d) Added CLI-level (cobra-dispatch, in-process rootCmd.Execute) tests for:
- "rm"/"delete" reserved-word rejection, the two words the #5369-inherited
tests don't cover (only "list"/"add" have hand-written cases).
- The new (c) abbreviation-refusal message end-to-end, including a
same-abbreviation sanity check against `bd show` to prove it's a real,
resolvable abbreviation and not a fixture accident.
Plus a Docker-free fake-store test in internal/utils pinning
ErrAbbreviatedIDNotAllowed's distinguishability from a genuine not-found.
Fixed in the same pass, same class of defect as (c): checkCommentIDNotReservedWord's
message claimed every reserved word is a "misplaced bd comments subcommand" —
true for "list"/"add", false for "rm"/"delete" (no such subcommand exists;
bd has "delete" as a top-level command and "rm" as an alias elsewhere, e.g.
"dep rm"). Message now says "reserved word" generically, true for all four.
Testing: go vet (plain and -tags=integration) clean on cmd/bd and
internal/utils. go test ./internal/utils/... passes including the new
ErrAbbreviatedIDNotAllowed test. go test ./cmd/bd/. (non-integration tag)
passes including both reserved-word cases. The new CLI-level and
proxied-server integration tests need a Dolt test container (Docker) this
environment doesn't have — same limitation the original commit's own
Dolt-backed tests already disclosed; they compile clean under
-tags=integration and skip cleanly the same way the pre-existing suite does.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(ga-wpdum): address bee-ghosttrack's R1 review (M1 + the flagged MINOR)
R1 (aec6de4ad, REQUEST-CHANGES) found that CHANGELOG.md and hash-ids.md
claim `bd comments add` is guarded against abbreviated ids and reserved
words exactly like `bd comment`, but the code never extended the guard
to the plural form — `commentsAddCmd` had no Args validator and resolved
through the abbreviation-tolerant `resolveAndGetIssueForMutation`. Per
the reviewer's preferred fix (option ii), extend the guard instead of
softening the docs:
- Add `validateCommentsAddArgs` (mirrors `comment`'s `validateCommentArgs`
minus the singular/plural-confusion special cases) and wire it as
`commentsAddCmd.Args`, so a reserved-word id is refused before either
dispatch branch.
- Switch the embedded-path resolution from `resolveAndGetIssueForMutation`
to `resolveAndGetIssueForMutationExact`, with the same
`errors.Is(ErrAbbreviatedIDNotAllowed)` truthful-message mapping
`comment` already has. (The proxied path already resolved exactly —
it shares `addCommentProxied`/`resolveCommentTargetProxied` with
`comment` — so this closes the embedded-path gap only.)
- Update the one pre-existing test that asserted the old, now-removed
behavior (`PartialIDWithCommentsAdd` expected a genuine abbreviation to
succeed) to assert the refusal instead, and add a CLI-level regression
test mirroring `TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage`.
- Add `TestValidateCommentsAddArgs`, a pure Args-validator unit test
(no store/Docker needed) mirroring `TestValidateCommentArgs`.
Also treats the one MINOR the review flagged as an actual gap (not just
a suggestion): the wisp-branch abbrevOnly tracking in id_parser.go had no
test pinning it — P3 (making the wisp-branch abbrevOnly append a no-op)
went uncaught. Strengthened
TestResolvePartialIDExact_FakeStore_ReproducesReportedIncident's "list"
assertion from a bare `err != nil` to `errors.Is(err,
ErrAbbreviatedIDNotAllowed)`, which is exactly the incident's own shape
in the wisp branch.
CI (PR Core / wrapper timing) is failing on this branch, but independently
confirmed pre-existing and unrelated: `ci-pr-core.sh` runs `go test -race
./...` with no `-timeout` override, so cmd/bd (a large package under
-race) hits Go's default 10-minute per-package ceiling; same-hour green
runs on other PRs measured 11-13.5 min total job time, already at the
edge, and the actively-running test at the deadline
(TestWhereCommand_ReadsPrefixFromEmbeddedStore) is unrelated to this
diff. R1 independently measured the same thing (541.6s/387.0s on other
green runs vs. 600.9s here). Needs a green re-run, not a code fix.
Verified locally (no Docker in this environment, so the two integration-
tagged CLI tests above compile-check clean via `go vet -tags=integration,
gms_pure_go` but run as SKIP rather than PASS; will run for real in CI):
- go build ./...; go vet ./cmd/bd/ ./internal/utils/: clean
- go vet -tags=integration,gms_pure_go ./cmd/bd/: clean
- gofmt -l on all 4 changed/added files: clean
- go test ./internal/utils/... -run ResolvePartialID: PASS
- go test ./cmd/bd/. -run 'TestValidateCommentsAddArgs|TestValidateCommentArgs|TestCheckCommentIDNotReservedWord': PASS
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(ga-wpdum): address bee-ghosttrack's R2 review (dead-red fixture + cobra-dispatch wiring test)
R2 (a639234a0, CHANGES_REQUESTED): TestCLI_CommentsAddShortID/PartialIDWithCommentsAdd
was dead-red in its own setup — it only truncated the fixture hash to a
4-char abbreviation when len(hash) > 4, but fresh test DBs mint 3-char
hashes (min_hash_length unset), so shortID always equaled the full hash
and the t.Fatalf guard fired before any of the subtest's real assertions
ran. That meant mutation P-B (reverting comments.go's exact resolver back
to the abbreviation-tolerant one) went uncaught.
Fix: derive the abbreviation as a strict, one-character-shorter leading
prefix of the real hash (hash[:len(hash)-1]), the same derivation
comment_proxied_integration_test.go already uses — correct regardless of
fixture hash length, with a length>=2 guard instead of the old
always-true-in-practice one.
Also closes R2's recommended "NEW MINOR — the guard's wiring is
untested": comments_add_test.go drives validateCommentsAddArgs directly
(catches a gutted body, mutation P-C) but nothing exercised
commentsAddCmd's Args field through real cobra dispatch, so unwiring it
back to cobra.MinimumNArgs(1) left every test green (mutation P-D). Added
TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch, which runs
`bd comments add <reserved-word> ...` through actual rootCmd.Execute()
dispatch for all four reserved words and asserts the bystander issue
receives no comment.
Not touched, per R2: the carried-over m1 (cross-rig abbreviation error
message) — reviewer marked "Not a blocker" — and the CI race-default
timeout on cmd/bd, already diagnosed (R2 + prior PR comment) as
pre-existing infra flakiness needing a fresh run, not a code change.
Verified in this environment (no Docker/testcontainers available, same
disclosed limitation as prior rounds): gofmt clean; go vet -tags=integration
./cmd/bd/... clean (requires CGO_CPPFLAGS/CGO_LDFLAGS/PKG_CONFIG_PATH
pointed at the keg-only icu4c@78 install); go test -tags=integration
-run 'TestCLI_CommentsAddShortID|TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch'
./cmd/bd/ -v passes with all Dolt-backed subtests skipping cleanly
(Docker not available) rather than panicking — confirms both tests compile
and execute up to the container-availability skip. The actual fixture-hash
logic under test only runs where a Dolt container exists (CI); it has not
been exercised against a real container here.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* chore(bazel): enumerate the PR's 4 new test files in BUILD.bazel (adopt-pr rebase gate)
Base added cmd/bd/BUILD.bazel and internal/utils/BUILD.bazel enumerates
go_test srcs explicitly, so PR #5393's four new test files were unlisted.
Output of 'make bazel-sync' (gazelle + go_srcs.py + mod tidy), verbatim and
idempotent. Measured: the unrepaired //internal/utils:utils_test binary lists
0 of the PR's 5 TestResolvePartialIDExact* tests while still building green
(a fake green); repaired it lists 5/5.
* fix(review): surface a routed-tier abbreviation refusal on comment writes
Review-loop fixup for PR #5393 (iteration 1). The review approved with no
required changes; these are the non-gating minor plus one of the two nits,
taken because the minor is a user-visible false message on this PR's own
headline contract.
[minor] Contract & Interface Fidelity. resolveAndGetIssueForMutationExact
passes exact=true to all three tiers, so the cross-rig and auto-routed tiers
can mint utils.ErrAbbreviatedIDNotAllowed too -- and both wrappers propagate it
unwrapped (routed.go:303-305) -- but each routed error was bound inside an `if`
statement and discarded, and `return nil, err` returned the LOCAL error. The
consumers' errors.Is (comment.go:158, comments.go:238) was therefore
structurally unable to observe a routed-tier refusal, so `bd comment hr-8wn
"text"` printed `no issue found matching "hr-8wn"` for an issue a routed rig
demonstrably holds -- the exact falsehood the sentinel's own doc condemns, at
the caller that doc names (internal/utils/id_parser.go:33). Both tiers' errors
are now captured and the first abbreviation refusal is returned in preference to
the local not-found. The wrong write was already refused on every tier; only
the message contract was unmet.
The new pin cmd/bd/comment_routed_exact_test.go drives the real seam (local
town store + routed rig + routes.jsonl, mirroring
TestCheckBeadGateCrossRigPrefixRoute) in both directions, because either
assertion alone passes for the wrong reason: an abbreviation of a routed issue
must select the ROUTED refusal, and an id absent everywhere must stay a plain
not-found. Proven non-vacuous by mutation -- dropping only the selection reds
direction 1 with `no issue found matching "gt-abcdefg"`, the original symptom
verbatim, while direction 2 still passes.
[nit] Test Evidence Quality. The proxied regression test asserted only
strings.Contains(stdout+stderr, id), which passes identically on the false and
the truthful message and so locked the local/proxied message asymmetry in where
the suite could not see it. It now asserts the whole message (verified
empirically: `Error: issue pa-2u not found`) and empty stdout, matching the
exact-message norm of the sibling missing-ID subtest. The asymmetry itself is
deliberate and stays: the proxied route resolves through one exact
`WHERE id = ?` and cannot distinguish an abbreviation of a real issue from an
absent id without adding back the abbreviation probing this PR exists to remove
from write paths.
[nit] Release Safety -- DECLINED, measured. The prescribed `### Changed` bullet
belongs at the top of the first `### Changed` block in `## [Unreleased]` (base
CHANGELOG.md:383), and main has since inserted its own bullet at exactly that
anchor (`@@ -384,0 +492,16`, the #6111 entry). Adding it would mint a second
CHANGELOG add/add conflict for the finalize base-refresh on top of the
`### Fixed` re-conflict already predicted by the rebase gate -- not worth it for
an optional nit whose own text says "No code change".
cmd/bd/BUILD.bazel gains one srcs row for the new test file (via make
bazel-sync, a no-op on a second run) so bazel.yml's "BUILD files in sync" gate
stays clean.
Validation: go build ./... rc 0; go vet ./cmd/bd/ ./internal/utils/ rc 0; gofmt
clean; git diff --check clean; cmd/bd selectors 11/11 PASS including base's own
TestMatchPrefixRoute (the GH#5048 longest-prefix union guard) and
TestResolveCloseTargets (the abbreviation-tolerant sibling path);
TestProxiedServerComment 3/3 under BEADS_TEST_PROXIED_SERVER=1.
* test(utils): pin #6215's sentinel guard to the shared resolver (#5393 base refresh)
Rebasing this PR onto current main (e7138e93af -> a1ac9f4dcb, 27 commits) hit
two conflicts. Both are recorded in .gc/reviews/<root>/base-refresh-repair.md;
this commit carries the one piece of the repair that is not simply a replayed
contributor hunk.
The substantive conflict was internal/utils/id_parser.go against ab88b20517
(#6215, "refuse a bare jq/JS sentinel ... as an issue ID", which itself says
Refs #5393). Both sides ADD at the same point -- the diff3 ancestor section is
empty -- so nothing base-owned is rewritten, and the only question is WHERE
#6215's guard lands now that this PR splits the resolver into ResolvePartialID
(abbreviation-tolerant) and ResolvePartialIDExact (exact-only) over a shared
resolvePartialID.
It belongs in the shared body. #6215 put it in ResolvePartialID only because
that was then the repository's single ID-resolution entry point ("One guard
covers the direct, embedded and proxied-server paths uniformly"); this PR adds
a second. Its changelog entry on main states the guarantee directly -- "bd
update null, bd comment null and every other command that resolves an ID now
fail before any lookup, because the guard sits in the shared resolver" -- and
bd comment is precisely what this PR routes through the exact-only path. The
relocation costs no patch delta: the guard re-anchors as unchanged context
after the PR's insertion, so the content-line diff of (old base..old head) vs
(new base..new head) is empty, and the PR's stat is 16 files +1212/-31 before
and after.
Nothing covered that choice, which is why this test exists. #6215's own
id_parser_sentinel_test.go exercises only ResolvePartialID, so the naive
textual resolution -- guard left in the exported wrapper -- keeps every one of
its assertions green while a sentinel reaching the exact path degrades into
`id is a valid abbreviation, but exact-match resolution is required here:
"null" (matches [hq-null3t0])`: it names an unrelated decoy issue and tells
the caller to use the full id, when in truth their selector matched nothing.
Mutation-proved in both directions: with the guard moved into the wrapper
alone, #6215's two tests still PASS and this test FAILs; with the guard deleted
outright, #6215's refusal test and this one both FAIL (so neither is vacuous).
The over-refusal arm mirrors #6215's accepted-inputs test through the exact
path, so hq-null3t0 and the bare hash null3t0 must still resolve.
No new file, so no BUILD.bazel srcs row is owed. 61 PASS / 0 FAIL / 0 SKIP for
-run 'Sentinel|ResolvePartialID' against a real Dolt container.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
430 lines
17 KiB
Go
430 lines
17 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")
|
|
|
|
// 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)
|
|
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) {
|
|
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 <id>`, 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)) {
|
|
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
|
|
// 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)
|
|
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).
|
|
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)
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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) {
|
|
if allowAbbrev {
|
|
matches = append(matches, wID)
|
|
} else {
|
|
abbrevOnly = append(abbrevOnly, wID)
|
|
}
|
|
}
|
|
}
|
|
if exactMatch != "" {
|
|
return exactMatch, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
// 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
|
|
}
|