* feat(http): serve list/show counts/dep tree/ping, close+reopen under a session, one-lookup not-found (S6b/S6c/S6d) S6c. The external-dependency decorator rebuilt its role views from the legacy DoltStorage seam (storereader over itself, IsBlocked, GetDependencyTree, ClaimReadyIssue), which a remote store only partly serves: `bd list`/`bd children` refused on the SearchIssuesWithCounts stub, `bd show --json` printed zero counts, the default `bd dep tree` refused, `bd ready --claim` and `bd close` of an externally blocked issue reached unsupported paths. For a storage.RemoteBackendStore each view now passes the inner role through and lays the policy over it in role terms (externaldeps/remote_roles.go): ready reads and the ready claim exclude the workspace-wide blocked set over a widened window; per-issue checks (claim, close, batch close, list annotations, tree leaves) read only the named issues' edges through EdgeReader instead of every edge in the workspace. A server advertising policy.external_dependencies (MC's does) gets a plain passthrough. `bd ping` uses a new storage.Pinger, which the http store answers with its authenticated context read. S6d. A store reporting storage.CallerAttributionLimitedStore (http) cannot carry a Provenance label or a patch's closed_by_session. The library still refuses both; the CLI omits them where nothing is lost: `bd reopen`'s fixed "bd: reopen <id>" label (the server labels the same entry), and the closed_by_session of `bd update -s closed` (attribution only, usually the ambient CLAUDE_SESSION_ID; an explicit --session prints a notice; `bd close` still records it). See cmd/bd/remote_backend.go. S6b. utils.ExactIDLookupStore: the resolver stops at exact lookups for a store with no substring search, so a missing prefixed id is a not-found (beadserrors.ErrNotFound, "no issue found matching") after one getIssue. The general resolver no longer repeats an identical normalized probe. The http SearchIssueIDs answers D11's partial-id refusal, which now unwraps to ErrNotFound. Contributor auto-routing for a remote workspace reads local config only, so the not-found fallback pays no settings round trip. `bd update <absent> --claim` (gc's hook claim) answers a gc-classifiable not-found in at most two requests. Served e2e (backend/http/e2e_remote_roles_test.go): every gc list shape and `bd children` against embedded, `show --json` count parity, default dep tree parity, external blocking still enforced, close/reopen under CLAUDE_SESSION_ID, missing-id request counts, absent-id claim against the current server and the MC handshake mask, policy passthrough under the MC mask, ping. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(externaldeps): role-level remote reader and claimer cases bd ready and bd update --claim reach the policy through the legacy seam and the lifecycle guard, so the remote Reader.Ready exclusion and the remote Claimer guard (what bd serve and library callers reach) are pinned at the role level with a fake remote store. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(http): bd serve advertises policy.external_dependencies; clients pass through bd serve composes every ready, claim, claim-next, close, blocking and tree role through the external-dependency policy, but never said so. Every client therefore ran the policy a second time, with the CLIENT machine's external-project config, and claim-next became a non-atomic read-then-claim loop on the client. The server now advertises the token exactly when the roles it serves were composed through the policy: httpapi.Config.ExternalDependencyPolicy, which bd serve derives from its actual chain (externaldeps.Applied for the store arm, externaldeps.AppliedToProvider for the provider arm). A server handed raw roles still withholds it, so the token stays truthful. Against a server that advertises it, every remote role view hands the request to the server's own role untouched: no client validation, no edge reads, claim-next is the server's one atomic call, and the ready count is the server's countReadyWork (new remoteReadyCounter). The client-side policy remains only for servers that do not advertise the token. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(create): default created_by to the request's actor in the create role created_by was stamped in two front doors and never in the library: the CLI (creationActorStamp, with a remote-workspace special case) and the three httpapi create handlers. A library caller of Lifecycle.Create or BatchCreator with an empty CreatedBy stored "" locally and the actor over http. PreparePublicCreateRequest, which every create shape prepares through (Lifecycle.Create, BatchCreator items, batch-apply create items), now defaults an empty CreatedBy to request.Actor; an explicit value is kept. The handlers no longer stamp, `bd create` and the state event create pass only the actor, and creationActorStamp/isRemoteBackendWorkspace are gone. The CLI sites that still create through the raw CreateIssue seam (swarm, todo, gate, the create form) keep stamping currentActor(): that seam is shared with import, where defaulting would re-attribute imported rows, and the http store refuses it anyway, so the remote special case was never reachable there. Conformance: the lifecycle-create, batch-creator and batch-apply contracts now pin created_by == actor for an item that names none, on every leg. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(httpclient): GetIssue answers a miss with storage.ErrNotFound, like the local stores The http store's raw GetIssue answered a missing id with (nil, nil), where DoltStore and the embedded store return a wrapped storage.ErrNotFound. A caller written against the backend contract read the http miss as a hit: `bd create --graph` refused every explicit-id plan over http (patched in cmd/bd on feat/http-mc-corpus; that workaround is reverted there). GetIssue now returns the miss (and the empty id) as storage.ErrNotFound, spelled as issueops.GetIssueInTx spells it. GetLabels, which reads through GetIssue, keeps the local read's "no labels" answer for a missing id; the `bd list --parent` walk reads the typed miss as "parent issue not found". The served bridge test now holds the local reference store and the http store to the same miss: ErrNotFound with the same text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(createbatchequiv): re-record the apply golden for the created_by default c2866ea7fe made the create role default an empty CreatedBy to the request's actor, so every create item of the apply scenario's batch (actor "apply-writer") now stores created_by "apply-writer" instead of "". TestCreateBatchFastPathsMatchPerRow_*/apply compared the stored rows to a digest recorded before that change and failed on exactly the three tables the column reaches: issues and wisps (the row) and events (the update event's old-value snapshot). Fast and per-row bodies still agree; the batch-apply conformance contract pins the same value. Bisected with bazel: passes at be92efe40f's integ twin 696f7acc8e, fails from the created_by commit on. Only apply.json's three digests move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: gofmt ledger.go and the externaldeps remote-roles test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cmd/bd): bd create reads routing settings local-only on a remote backend too determineAutoRoutedRepoPath skipped a remote backend's settings document (routing targets are local paths that one shared document cannot name for every client), but getRoutingConfigValue, which `bd create` and migrate-personal read routing.* and contributor.* through, still asked it. The same workspace could route a create one way and a lookup another, and every create paid a settings round trip per key. Both now go through routingSettingsStore: nil for a remote backend, so routing comes from config.yaml / the environment only there, and a local store is still consulted. A unit test holds both reads to the rule with a store that counts settings reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cmd/bd): say so when update -s closed drops an ambient CLAUDE_SESSION_ID Over http `bd update -s closed` cannot carry closed_by_session, so the CLI drops it rather than refusing the close. An explicit --session printed a notice; the ambient CLAUDE_SESSION_ID every agent under Claude Code exports was dropped without a word, a silent data difference from a local backend (the served corpus's mc-update-meta-status-closed). The drop is now named on stderr in both cases, once per command, pointing at `bd close`, whose wire operation records the session. The served e2e asserts the notice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend/http): hold bd list --limit 2 to each side's own unlimited order TestE2E_ListWithGCFiltersMatchesEmbedded compared the --limit 2 rows of the served and embedded workspaces as sets. The seed has four P2 rows, so the limit cuts a priority tie whose created_at order differs between two workspaces seeded seconds apart: a test-only flake, the order itself being total. Each side's two rows must now be, in order, the first two of that same side's --limit 0 listing; the unlimited listings are still compared across sides by the shape loop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: unit-tier pins for the created_by default, the policy token and the GetIssue miss Three review mutations were caught only by a heavier tier (the uow conformance legs, the served httpclient tier) or by one package's test alone. Each now has a unit test where its rule lives: - issueops: PreparePublicCreateRequest defaults an empty CreatedBy to the actor and keeps an explicit one, without mutating the caller's request. - externaldeps: the policy layer AppliedToProvider finds becomes the handshake's policy.external_dependencies through httpapi.Listen, the composition bd serve performs, and a raw provider's handshake lacks it. - httpclient (no embedded engine): GetIssue over the real wire client against a stub server answers a 404 not_found, and the empty id without dialing, as storage.ErrNotFound spelled like the local stores. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(changelog): S6b/c/d entries match the code The S6 entry still said `bd create` suppresses created_by on a remote workspace and that the external-dependency policy runs client-side. Since S6b/c/d, created_by defaults to the actor in the library on every backend, and every bd serve composed through the policy advertises policy.external_dependencies, so clients pass those operations through; the client-side policy (now in role terms) runs only against a server that does not advertise it. New entries: the advertised policy token, bd ping over http, the created_by library default, closed_by_session dropped by an http `bd update -s closed` (with a notice, typed or ambient), reopen without a Provenance label over http, local-only routing.* / contributor.* on a remote backend, GetIssue's miss as storage.ErrNotFound, and list/children/show counts/dep tree over http. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(externaldeps): keep S6's list --ready, --claim-next refusal and lost-race error on the S6c composition The re-adopted S6 head (#7288) carries the review fixup's remote role composition; S6c replaces it with its own (rolesAreRemote, the widened ready window, the policy passthrough). Two behaviours S6 shipped and its reviews pinned would otherwise go: - bd close --claim-next against a server that does not apply the policy is refused whole, before anything is read or closed, with "the served batch close cannot carry a next claim, so nothing was closed; close without --claim-next, then run `bd ready --claim`". S6c passed the batch to the http closer, whose W-CloseBatchRequest.ClaimNext refusal drops the remedy, so TestE2E_BDOverHTTP's two refuseClaimNext steps went red. A request invalid on every backend is still ErrValidation first, and a server that applies the policy still gets the request untouched. - remoteReadyClaimer.ClaimNext reports a page on which every candidate was lost to another actor as "claim ready: lost N races ...", not as the empty answer that means there is no work. - `bd list --ready` (List with ReadyFlag) is answered by the policy store's own reader over the served ready reads, as S6 does. S6c passed it to the served listing, which cannot carry ReadyFlag (httpclient ledger row E-ListRequest.ReadyFlag), so it exited 1 over http with or without external refs; TestE2E_BDOverHTTP and TestServedRolesKeepTheExternalDependencyPolicy were red on it. TestRemoteReaderAnswersAReadyListingWithoutTheWireFlag pins it, with the fake's served List refusing ReadyFlag as the wire does. S6's composition tests now run against S6c as remote_roles_composition_test.go. Their fake serves Ready the way a server does (the S6 composition read ready work through the legacy policy reader instead), and two call logs gain that Ready. TestRemoteBatchCloserRefusesANextClaim, TestRemoteBatchCloserValidatesANextClaimFirst and TestRemoteReadyClaimerReportsLostRaces were red on S6c before this change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(externaldeps): unassigned claim-next and fail-closed close reads Review fixes for the S6c composition against a server that does not advertise policy.external_dependencies: the two majors of review attempt 1, plus the minors on the same code. - ReadyClaimer: the composed claim-next reads only open, unassigned ready rows (Unassigned=true, Assignee cleared), the candidates the local ClaimReadyIssueInTx selects. A row another actor holds, or one already assigned to the caller, is no longer taken or counted as a lost race. Each pass reads 25 candidates past the blocked rows, as httpclient's composed claim does, and a full window lost end to end is read once more: claimed rows leave the unassigned set. Only a claim that tried candidates and won none is an error. - BatchCloser: an externally blocked item travels to the server only when its status read finds it closed or not found (liveRefusal). Any other read error is that item's outcome, so a transient or auth failure no longer forwards a refused close to a server that will not refuse it. - TreeWalker: a failed capability probe renders the external leaves over the walked tree instead of failing a walk the server already answered. appendTreeExternalReferences skips an id the tree holds, so an enforcing server's own leaves are not doubled. - remoteEdges names each anchor once and skips an empty one, which the http EdgeReader refuses with ErrValidation. The composition fakes now honor Unassigned/Assignee as workapi.BuildReadyFilter does, model a rival claim landing first and a failing GetIssue, and refuse an empty edge anchor as httpclient does. New: TestRemoteReadyClaimerTakesOnlyUnassignedWork, TestRemoteReadyClaimerWalksAContendedFront, TestRemoteBatchCloserAnswersAFailedReadWithIt, TestRemoteEdgesNamesEachAnchorOnce, and the probe-failure cases of TestRemoteTreeWalkerAddsExternalLeaves. Each is red with its fix reverted. From review attempt 2, three nearby cleanups: - TestServedRolesKeepTheExternalDependencyPolicy seeds open rows held by another actor and by the claimant ahead of the free work, then claims with and without an assignee filter. The unassigned-only claim is now pinned over a real served server, not only through the fakes: red with the pre-fixup remote_roles.go, with filter.Unassigned dropped, and (the filtered claim) with an explicit assignee honored. - The capabilities description in openapi.v0.yaml (and the regenerated types.gen.go comment) no longer calls the whole list build-level: policy.external_dependencies depends on how the server composed its roles, as the paragraph above it says. - createbatchequiv's golden note names issueops.PreparePublicCreateRequest instead of a commit id that is not on this branch. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend/http): count a not_found read as reaching the remote in #7469's credential doors main's #7469 added TestExplicitCredentialIgnoresTheEnvPlaintextGrant. Its OpenWith and Open doors read bd-1 from plaintextRemote, which answers every issue read not_found, and the granted leg needs that read to return a nil error. That held while the http client answered a miss with (nil, nil). This branch's "fix(httpclient): GetIssue answers a miss with storage.ErrNotFound, like the local stores" makes the same read return storage.ErrNotFound. So on main plus this branch both doors fail at per_open_credential_test.go:392 ("with Target.AllowInsecureCredential: not found: issue bd-1") under plain go test. The merge is textually clean, so only a build of the merge shows it. The two store doors now count storage.ErrNotFound as success, since that answer came off the wire. The assertions are unchanged. The refused leg still needs the "refusing to send a credential" error and no request on the transport. The granted leg still needs exactly one request carrying "Bearer explicit-token": a granted read that never reaches the wire still fails at :408. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
533 lines
21 KiB
Go
533 lines
21 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/beadserrors"
|
|
"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)
|
|
}
|
|
|
|
// ExactIDLookupStore is an optional PartialIDResolverStore capability: a store
|
|
// that can look an issue up only by its EXACT id and has no substring id
|
|
// search at all (the http backend: the v0 wire publishes none, design D11).
|
|
//
|
|
// For such a store the resolver stops at the exact lookups. An input already
|
|
// shaped like a prefixed id normalizes to itself, so the first exact probe is
|
|
// the whole answer and a miss is a not-found after ONE lookup. A bare hash
|
|
// still reads the prefix vocabulary to build its prefixed spelling. A miss
|
|
// wraps beadserrors.ErrNotFound — never the substring search's refusal, which
|
|
// would report a missing id as a backend fault.
|
|
//
|
|
// The assertion is made on the store the caller passes, so a decorated chain
|
|
// must hand over the store that actually implements it (cmd/bd's routed
|
|
// resolution unwraps for this).
|
|
type ExactIDLookupStore interface {
|
|
ExactIDLookupOnly() bool
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
if exact, ok := store.(ExactIDLookupStore); ok && exact.ExactIDLookupOnly() {
|
|
return resolveExactIDOnly(ctx, store, 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). An input
|
|
// that normalized to itself was already asked exactly that above.
|
|
if normalizedID != input {
|
|
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
|
|
}
|
|
|
|
// resolveExactIDOnly is resolvePartialID for an ExactIDLookupStore: the exact
|
|
// lookups only, with the same input normalization, and a not-found that says
|
|
// why no abbreviation was tried.
|
|
func resolveExactIDOnly(ctx context.Context, store PartialIDResolverStore, input string) (string, error) {
|
|
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{input}})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(issues) > 0 {
|
|
return issues[0].ID, nil
|
|
}
|
|
if !looksLikePrefixedID(input) {
|
|
// A bare hash, or a configured prefix without its hyphen: only the
|
|
// prefixed spelling can name an issue, and building it needs the
|
|
// workspace's prefix vocabulary.
|
|
prefix, allowed := exactOnlyPrefixConfig(ctx, store)
|
|
if prefix == "" {
|
|
prefix = "bd"
|
|
}
|
|
prefixWithHyphen := prefix
|
|
if !strings.HasSuffix(prefix, "-") {
|
|
prefixWithHyphen = prefix + "-"
|
|
}
|
|
knownPrefixes := []string{strings.TrimSuffix(prefix, "-")}
|
|
if allowed != "" {
|
|
for _, p := range strings.Split(allowed, ",") {
|
|
if p = strings.TrimSuffix(strings.TrimSpace(p), "-"); p != "" {
|
|
knownPrefixes = append(knownPrefixes, p)
|
|
}
|
|
}
|
|
}
|
|
if !strings.HasPrefix(input, prefixWithHyphen) && !hasKnownPrefix(input, knownPrefixes) {
|
|
issues, err = store.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{prefixWithHyphen + input}})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(issues) > 0 {
|
|
return issues[0].ID, nil
|
|
}
|
|
}
|
|
}
|
|
return "", &exactIDNotFoundError{input: input}
|
|
}
|
|
|
|
// exactIDNotFoundError is resolveExactIDOnly's miss. Its text keeps the general
|
|
// resolver's "no issue found matching" lead, which every not-found matcher
|
|
// downstream reads (bd's isNotFoundErr, gc's isBdNotFound), and it wraps
|
|
// beadserrors.ErrNotFound for errors.Is callers.
|
|
type exactIDNotFoundError struct{ input string }
|
|
|
|
func (e *exactIDNotFoundError) Error() string {
|
|
return fmt.Sprintf("no issue found matching %q (this backend resolves exact ids only; partial-id search is not available)", e.input)
|
|
}
|
|
|
|
func (e *exactIDNotFoundError) Unwrap() error { return beadserrors.ErrNotFound }
|
|
|
|
// exactOnlyPrefixConfig reads issue_prefix and allowed_prefixes, in one
|
|
// settings read when the store can enumerate them (a remote store pays a round
|
|
// trip per read) and with two point reads otherwise. A failed read is an unset
|
|
// key, as it is on the general path.
|
|
func exactOnlyPrefixConfig(ctx context.Context, store PartialIDResolverStore) (prefix, allowed string) {
|
|
if all, ok := store.(interface {
|
|
GetAllConfig(ctx context.Context) (map[string]string, error)
|
|
}); ok {
|
|
if values, err := all.GetAllConfig(ctx); err == nil {
|
|
return values["issue_prefix"], values["allowed_prefixes"]
|
|
}
|
|
}
|
|
if v, err := store.GetConfig(ctx, "issue_prefix"); err == nil {
|
|
prefix = v
|
|
}
|
|
if v, err := store.GetConfig(ctx, "allowed_prefixes"); err == nil {
|
|
allowed = v
|
|
}
|
|
return prefix, allowed
|
|
}
|
|
|
|
// 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
|
|
}
|