beads/internal/workapi/list.go
Julian Knutsen ec55baa425
fix(http): bd show --current, recompute-blocked and search over http through issueops entries (S6e/S25/S26) (#7528)
* fix(show): --current through issueops.FindCurrentIssue over the Querier role; no swallowed refusal (S6e)

Over http `bd show --current` printed the WRONG issue, exit 0.
resolveCurrentIssueID asked the raw SearchIssues method for the actor's
in_progress and then hooked work; the http backend refuses that method, the
refusal was taken for "nothing found", and the command fell back to the
last-touched issue. The proxied route had its own copy of the lookup, read
inside its unit of work, with the same swallow.

One library entry now: issueops.FindCurrentIssue(ctx, Querier, actor). It
asks the Querier role (queryIssues over http, which every deployed server
publishes) for `status=<s> AND assignee="<actor>"`, limit 1 — exactly the
raw filter, answered in the store's default order, so the same row comes
first on every backend — in_progress, then hooked. A failed read is an
error; "" (two reads that answered and found nothing) is the only miss. The
actor is a quoted, escaped query value; the query language reads
`assignee=none`/`null` as "unassigned", so such an actor (or an empty one)
is not asked about.

Both CLI routes call it with their route's Querier (store.Querier() or the
proxied provider's) through one cmd/bd helper; what stays in the CLI is the
actor and the last-touched fallback (a workspace file). The proxied route
resolves --current before it opens its unit of work, and its duplicate
in-transaction lookup is deleted.

Tests: issueops unit tests (order, failure is an error on either read,
quoting, unaskable actors, each expression evaluates to exactly the raw
filter); cmd/bd fallback tests; served e2e TestE2E_ShowCurrentOverHTTP
(in-progress beats a later-touched issue, hooked when nothing is in
progress, last-touched only when neither). Against the old code the e2e
fails with exactly the reported bug.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recompute-blocked): one library entry, storage.RecomputeBlocked; a no-op on a remote backend (S25)

`bd recompute-blocked` refused over http ("storage backend does not support
is_blocked recompute"), and gc's BdStore.RecomputeBlocked issues it.

is_blocked is server-derived. Every write a remote client makes is committed
by the server's own store, which keeps the flag under
issueops.BlockedStateInvariant's local-write clause (targeted, inside the
write's transaction; a Postgres-family server has no full recompute at all
and runs a no-op readiness strategy for the same reason). A client cannot
leave the flag stale and holds no copy of it. The invariant's merge clause
(a recompute skipped after a pull, bd-6dnrw.37; a migration that over-set
it, beads#7037) happens to the SERVER's database, and its repair is this
command in the server's workspace.

So the decision is in the library, not the CLI: storage.RecomputeBlocked
(internal/storage/blocked_recomputer.go) is the one entry every backend goes
through. A local store (storage.BlockedRecomputer) recomputes its column; a
store implementing storage.ServerMaintainedBlockedState — the http client,
whose BlockedStateMaintainedByServer answers true — recomputes nothing and
reports MaintainedBy "server". No wire operation: a whole-column rewrite any
bearer of a workspace credential could trigger, for state no client can have
caused, is not one to publish. The proxied route keeps its pinned-connection
plumbing around the same versioncontrolops body the stores run.

--json keeps rows_corrected (gc requires the member; wh-bridge-sync reads the
exit code) as 0 and adds maintained_by: "server"; the text says where the
repair runs.

Tests: storage unit tests (local repair runs, server-maintained wins even
over a local repair and runs none, neither refuses); served e2e
TestE2E_RecomputeBlockedOverHTTP (exit 0, JSON shape, text, ready set
unchanged). With the server-maintained branch disabled the e2e fails with
the old refusal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(search): every bd search route through Reader.List with issueops.SearchListRequest; listIssues `q` behind issues.list.search (S26)

`bd search` called the raw SearchIssues method with its text, which the http
backend refuses ("partial-id search is not available over HTTP"), and its
direct and proxied routes each mapped the flags onto a storage filter by
hand. No served operation could carry search's meaning (title OR id contains
the text, case-insensitively; an id-shaped text also matches exact id, id
prefix and external ref): TitleSearch is title-only and the query language
has no title-or-id predicate.

The library entry is issueops.Reader.List:
- issueops.ListRequest gains Query, SearchIssues' free-text argument as a
  member. Both Reader bodies (workapi/storereader and the uow reader) pass it
  to SearchIssuesWithCounts where they passed "". It narrows and lifts no
  default exclusion; the ready arm refuses it (readyScopeFields).
- issueops.SearchListRequest(query) is search's scope as a request: Query,
  every status (AllFlag), every kind of row (the four Include*), and the
  store's default order (SortBy priority), so --limit keeps the rows a raw
  read kept.
- CLI: ONE runSearch for the direct, proxied and remote routes. One builder
  (searchListRequest) maps the flags onto SearchListRequest; the route only
  picks the reader (store.IssueReader() or the proxied provider's).
  --sort/--reverse reorder the page as before. search_proxied_server.go and
  its hand-built filter are deleted, and search leaves the forbidigo
  filter-writing exemption.
- Server: GET /v0/beads/issues decodes `q` into ListRequest.Query and calls
  the same Reader role, behind the new issues.list.search behavior token
  (spec parameter cites it; additive, no wire_revision bump; apigen and the
  wire-shape digest regenerated).
- Client: the encoder maps Query to `q`; httpReader.List refuses a request
  carrying Query BEFORE dialing, with ErrUnsupported{Capability:
  issues.list.search}, unless the handshake advertises it — never a round
  trip an old server would 400, never the unsearched listing passed off as
  the search. CapListSearch mirrors the server token. Flags listIssues
  publishes nothing for are put on the request so the encoder refuses them
  rather than widening the search.

Tests: Reader contract case RunReaderListQueryMatchesTheTitleOrTheID (also
pins SearchListRequest's scope) on all four legs — dolt, embedded dolt, uow,
served http (label-scoped, so the served leg runs it as written); handler
test that `q` reaches the seam as the search text, not TitleSearch; client
tests for `q` and the pre-dial refusal (zero dials); round-trip and
vocabulary gates; TestSearchRoutesAgree runs the same twelve flag sets on
the direct, proxied and remote routes and requires identical answers
(remote is bd serve over the proxied database, so ids and order too); served
e2e TestE2E_SearchOverHTTP. The remote legs skip with the
SearchIssuesWithCounts refusal until S6c's externaldeps reader passthrough is
underneath (loud refusal, never an empty or wrong answer); with S6c
cherry-picked all three routes agree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* build: resync BUILD srcs and the embedded storage shard manifest for S6e/S25/S26

gazelle picks up cmd/bd/show_current.go, cmd/bd/search_remote.go, the three
backend/http e2e files and internal/httpclient/list_search_test.go; the
embedded storage shard manifest gains
TestEmbeddedReaderListQueryMatchesTheTitleOrTheID
(scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration
--write).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: gofmt list_show_filter_modes.go (trailing blank line)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(backend/http/corpus): drop the show --current and recompute-blocked marks S6e and S25 retire

With S26 folded in, `bd show --current` resolves through
issueops.FindCurrentIssue over the Querier role and `bd recompute-blocked`
goes through storage.RecomputeBlocked (a no-op on a remote backend), so
gc-show-current and gc-recompute-blocked lose their pending marks.
mc-search stays pending, relabelled S6c+SRV-1: bd search now asks listIssues
with q behind issues.list.search, which the reference server profile does
not advertise, so the client refuses before dialing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(cmd/bd): split the bd search route agreement into the embedded and proxied lanes

TestSearchRoutesAgree skipped unless BEADS_TEST_EMBEDDED_DOLT=1, then ran
its proxied and remote legs only under BEADS_TEST_PROXIED_SERVER=1, and
its name matched neither lane's discovery (TestEmbedded* in
*_embedded_test.go, TestProxiedServer*/TestServerMode*). No CI lane ran
it, which main's #7468 guard (TestProxiedGatedTestsRunInTheProxiedLane)
now fails on.

Split it:
- TestEmbeddedSearchRoutesAgree (search_routes_embedded_test.go): the
  direct route, embedded lane.
- TestProxiedServerSearchRoutesAgree (search_routes_proxied_test.go): the
  proxied route and the remote route (bd serve over the proxied
  workspace), gated only on BEADS_TEST_PROXIED_SERVER. The remote route
  must still answer the proxied one row for row, ids and order included,
  and refuse the flag listIssues cannot carry.

Neither lane can run the other's workspace, so the shared helper
(search_routes_parity_test.go: the seed, the twelve flag sets, and
checkSearchRoute) holds every route to one expected answer per flag set;
agreeing with it is agreeing with each other. The remote leg's "needs
S6c" skip is gone: S6c is on main, so a refusal now fails.

Both manifests regenerated incrementally (embedded 100-shard block, shard
71; proxied 34-shard block, shard 23). Bazel: bd_embedded_part2_test
(--config=embedded) and bd_proxied_test (--config=doltserver-proxied)
pass and run the new tests; //scripts:go_test_sources_test passes.
Swapping the title-sort expectation fails both routes of the proxied
test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(search): keep an infra type's durable rows, expand --type aliases, fail the S26 e2e on refusal (bd-1ejjv6)

Review fixes for #7528, attempt 1: the three majors and three minors of
the synthesis.

`bd search --type <infra type>` dropped the type's durable rows (a
promoted wisp, an issue retyped after it was created), exit 0. The shared
listing (workapi.BuildListFilter) narrowed an infra --type to its
ephemeral rows unconditionally, so SearchListRequest's IncludeEphemeral
did not bring back what raw SearchIssues used to return. The narrowing
now applies only without IncludeEphemeral, in BuildListFilter and in the
count lockstep (applyCountIncludeInfra), and the http parent-walk
recognizer reads an infra type's Ephemeral back as the include_ephemeral
intent. This also fixes `bd list --type <infra type> --include-ephemeral`
and GET /v0/beads/issues, which shipped the narrowing in v1.3.1. Pinned by
workapi tests and by template, gate, wisp and promoted-message rows in the
Reader conformance Query case (new ReaderFixture.PromoteWisp) on the
dolt, embedded, uow and served backends; the issueops Reader/Counter docs
and the openapi descriptions say the same.

`bd search --type` handed the raw string to the Reader: an alias (feat,
mol, mr, ...) answered nothing and an unknown type an empty result. It is
now expanded with utils.NormalizeIssueType as `bd list` does, and an
unknown type exits 1. The help text and the CHANGELOG say so, and the
CHANGELOG also records the additive comments_omitted field in
`bd search --json` rows.

TestE2E_SearchOverHTTP skipped on the very SearchIssuesWithCounts refusal
it exists to catch; it now fails. The route agreement seeds "kinded"
template, gate, wisp and promoted-message rows and pins the alias, the
unknown-type refusal and the infra rows on the direct, proxied and remote
routes.

Minors: the CHANGELOG states the proxied `bd show --current` miss
fallback; the CommentsOmitted contract names `bd search --json`; the
storage.RecomputeBlocked and `bd recompute-blocked` comments name the
deliberate --proxied-server bypass.

Validation: go vet and gofmt on every changed package; make api-check;
workapi, issueops, httpclient/encode, types and storage unit tests; the
Reader conformance on dolt, embedded, uow and served; the embedded and
proxied route agreements (remote included), the embedded search tests,
TestProxiedServerSearch, TestProxiedServerRecomputeBlocked, the http e2e
search/show/recompute tests; docs flag, freshness and docsync checks; and
a hand-run bd search/list/count against a scratch workspace.

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>
2026-10-13 04:12:54 +00:00

544 lines
18 KiB
Go

package workapi
import (
"context"
"fmt"
"strings"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/issueops"
)
// DefaultListLimit is the default number of rows a list query returns when the
// caller does not ask for a specific limit. Every frontend registers its limit
// knob from this constant so the surfaces cannot drift apart; 0 still means
// unlimited.
const DefaultListLimit = 50
// PageLimit is the number of rows a list request asks to RECEIVE.
func PageLimit(in issueops.ListRequest) int {
return LimitOr(in.Limit, DefaultListLimit)
}
// SQLLimit is the row limit pushed into the query, which can differ from the
// page limit: `--sort id` needs natural-numeric comparison (bd-9 < bd-10) that
// SQL cannot express without a schema-side sort column, so that ordering
// fetches the whole result set and trims in Go afterwards.
//
// This lives beside the builder rather than in a caller because it is the
// second half of one decision — the first half is what the filter carries —
// and splitting a decision across a library and its callers is how the two
// halves drift.
func SQLLimit(in issueops.ListRequest) int {
if in.SortBy == "id" {
return 0
}
return PageLimit(in)
}
// ListConfig is the store-derived configuration BuildListFilter needs: the
// workspace's custom statuses and types, plus its infra-type set.
type ListConfig struct {
CustomStatuses []types.CustomStatus
CustomTypes []string
InfraSet map[string]bool
}
func (c ListConfig) CustomStatusNames() []string {
out := make([]string, len(c.CustomStatuses))
for i, s := range c.CustomStatuses {
out[i] = s.Name
}
return out
}
func (c ListConfig) InfraTypes() []string {
if len(c.InfraSet) == 0 {
return domain.DefaultInfraTypes()
}
out := make([]string, 0, len(c.InfraSet))
for t := range c.InfraSet {
out = append(out, t)
}
return out
}
func (c ListConfig) IsInfra(t string) bool {
if len(c.InfraSet) == 0 {
return domain.IsInfraType(types.IssueType(t))
}
return c.InfraSet[t]
}
// ConfigSource reads the workspace configuration BuildListFilter depends on.
// It is the seam between the filter logic and however a given frontend reaches
// storage (a direct store handle, a unit of work, ...).
type ConfigSource interface {
GetCustomStatuses(ctx context.Context) ([]types.CustomStatus, error)
GetCustomTypes(ctx context.Context) ([]string, error)
GetInfraTypes(ctx context.Context) (map[string]bool, error)
}
type storeConfigSource struct{ store storage.DoltStorage }
// NewStoreConfigSource reads list configuration straight from a store handle.
func NewStoreConfigSource(store storage.DoltStorage) ConfigSource {
return storeConfigSource{store: store}
}
func (d storeConfigSource) GetCustomStatuses(ctx context.Context) ([]types.CustomStatus, error) {
return d.store.GetCustomStatusesDetailed(ctx)
}
func (d storeConfigSource) GetCustomTypes(ctx context.Context) ([]string, error) {
return d.store.GetCustomTypes(ctx)
}
func (d storeConfigSource) GetInfraTypes(ctx context.Context) (map[string]bool, error) {
return d.store.GetInfraTypes(ctx), nil
}
// UnitOfWork is the slice of an open unit of work this package reads through.
//
// It is declared here, structurally, rather than imported from
// internal/storage/uow: that package's provider implements the Reader role and
// therefore imports this one, so naming its interface here would close an
// import cycle. uow.UnitOfWork satisfies it without an adapter, which is what
// keeps the seam honest — this is the same object, described by what the
// queries need from it.
type UnitOfWork interface {
ConfigUseCase() domain.ConfigUseCase
IssueUseCase() domain.IssueUseCase
DependencyUseCase() domain.DependencyUseCase
LabelUseCase() domain.LabelUseCase
CommentUseCase() domain.CommentUseCase
}
type uowConfigSource struct{ uw UnitOfWork }
// NewUOWConfigSource reads list configuration through an open unit of work.
func NewUOWConfigSource(uw UnitOfWork) ConfigSource {
return uowConfigSource{uw: uw}
}
func (p uowConfigSource) GetCustomStatuses(ctx context.Context) ([]types.CustomStatus, error) {
return p.uw.ConfigUseCase().GetCustomStatuses(ctx)
}
func (p uowConfigSource) GetCustomTypes(ctx context.Context) ([]string, error) {
return p.uw.ConfigUseCase().GetCustomTypes(ctx)
}
func (p uowConfigSource) GetInfraTypes(ctx context.Context) (map[string]bool, error) {
return p.uw.ConfigUseCase().GetInfraTypes(ctx)
}
// LoadListConfig materializes the list configuration from a ConfigSource,
// falling back to the workspace YAML for custom types the store does not know.
func LoadListConfig(ctx context.Context, src ConfigSource) (ListConfig, error) {
var cfg ListConfig
statuses, err := src.GetCustomStatuses(ctx)
if err != nil {
return cfg, fmt.Errorf("load custom statuses: %w", err)
}
cfg.CustomStatuses = statuses
ct, err := src.GetCustomTypes(ctx)
if err != nil {
return cfg, fmt.Errorf("load custom types: %w", err)
}
if len(ct) > 0 {
cfg.CustomTypes = ct
} else {
cfg.CustomTypes = config.GetCustomTypesFromYAML()
}
infraSet, err := src.GetInfraTypes(ctx)
if err != nil {
return cfg, fmt.Errorf("load infra types: %w", err)
}
if len(infraSet) > 0 {
cfg.InfraSet = infraSet
}
return cfg, nil
}
// LoadStoreListConfig loads the list configuration from a store handle. A nil
// store (no workspace open) still yields the YAML custom types.
func LoadStoreListConfig(ctx context.Context, store storage.DoltStorage) (ListConfig, error) {
if store == nil {
return ListConfig{CustomTypes: config.GetCustomTypesFromYAML()}, nil
}
return LoadListConfig(ctx, NewStoreConfigSource(store))
}
// LoadUOWListConfig loads the list configuration through an open unit of work.
func LoadUOWListConfig(ctx context.Context, uw UnitOfWork) (ListConfig, error) {
return LoadListConfig(ctx, NewUOWConfigSource(uw))
}
// BuildListFilter turns list parameters into the storage-level filter. It is
// the single definition of what `bd list` means: the closed/done/frozen status
// exclusions, the pinned and template defaults, and the gate, infra-type, and
// wisp suppression that make the default listing show durable work only.
func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter, error) {
// The --ready arm reaches its query through ReadyFilterFromIssueFilter,
// which carries only part of what this filter can express. A request that
// asks --ready to honor something the projection drops is refused here,
// at the one point every frontend and every implementation of
// issueops.Reader passes through, rather than answered with the wider set.
// The drop set and the refusal text live beside the promise they enforce,
// in issueops.
if err := issueops.ValidateReadyFlagScope(in); err != nil {
return types.IssueFilter{}, err
}
filter := types.IssueFilter{
Limit: SQLLimit(in),
// The offset is carried for the callers that consume this filter as a
// VALUE and run their own query — `bd list --watch` and the proxied
// hierarchical --parent walk — where the seam beneath them renders it.
// Both implementations of issueops.Reader take it back off
// (WithRowsBeforeThePage) and skip in the shared page epilogue instead;
// FinishPageAt says why the role cannot leave it here.
Offset: in.Offset,
SortBy: in.SortBy,
SortDesc: in.Reverse,
AfterCreatedAt: in.AfterCreatedAt,
AfterID: in.AfterID,
AfterPriority: in.AfterPriority,
// The defensive cap travels ON the request, so this builder is the
// only writer of the filter's two cap fields. `bd list` used to stamp
// them onto the filter after the builder returned, which is the
// "build it, then reach in and change it" half-step the role exists to
// make unreachable — and it left the cap invisible to every
// implementation of Reader.List.
MaxRows: in.MaxRows,
MaxRowsSource: in.MaxRowsSource,
}
// The status selector is parsed once here; every consumer below — the
// "all" short-circuit, the default exclusions, the pinned default —
// works from the same parts so their readings cannot drift.
statusParts := splitStatusSelector(in.Status)
statusAll := len(statusParts) == 1 && statusParts[0] == "all"
// --ready defaults to open (the blocker-aware query's historical pin),
// but an explicit --status is an intersection, not an override. Dropping
// the selector used to answer `bd list --status X --ready` with the
// unfiltered ready set (GH#5832). `--status all` is the no-filter
// spelling, so the open default still applies there.
if in.ReadyFlag && (len(statusParts) == 0 || statusAll) {
s := types.StatusOpen
filter.Status = &s
} else if len(statusParts) > 0 && !statusAll {
if err := applyStatusParts(&filter, statusParts, cfg.CustomStatusNames()); err != nil {
return filter, err
}
}
if len(statusParts) == 0 && !in.AllFlag && !in.ReadyFlag && !in.PinnedFlag {
excludeStatuses := []types.Status{types.StatusClosed, types.StatusPinned}
for _, cs := range cfg.CustomStatuses {
if cs.Category == types.CategoryDone || cs.Category == types.CategoryFrozen {
excludeStatuses = append(excludeStatuses, types.Status(cs.Name))
}
}
filter.ExcludeStatus = excludeStatuses
}
if in.Priority != nil {
p := *in.Priority
filter.Priority = &p
}
if in.Assignee != "" {
a := in.Assignee
filter.Assignee = &a
}
if in.IssueType != "" {
t := types.IssueType(in.IssueType)
if !t.IsValidWithCustom(cfg.CustomTypes) {
validTypes := "bug, feature, task, epic, chore, decision"
if len(cfg.CustomTypes) > 0 {
validTypes += ", " + strings.Join(cfg.CustomTypes, ", ")
}
return filter, fmt.Errorf("invalid issue type %q (valid: %s)", in.IssueType, validTypes)
}
filter.IssueType = &t
}
if len(in.Labels) > 0 {
filter.Labels = in.Labels
}
if len(in.LabelsAny) > 0 {
filter.LabelsAny = in.LabelsAny
}
if len(in.ExcludeLabels) > 0 {
filter.ExcludeLabels = in.ExcludeLabels
}
if in.LabelPattern != "" {
filter.LabelPattern = in.LabelPattern
}
if in.LabelRegex != "" {
filter.LabelRegex = in.LabelRegex
}
if in.TitleSearch != "" {
filter.TitleSearch = in.TitleSearch
}
if in.IDFilter != "" {
ids := utils.NormalizeLabels(strings.Split(in.IDFilter, ","))
if len(ids) > 0 {
filter.IDs = ids
}
}
if in.SpecPrefix != "" {
filter.SpecIDPrefix = in.SpecPrefix
}
if in.TitleContains != "" {
filter.TitleContains = in.TitleContains
}
if in.DescContains != "" {
filter.DescriptionContains = in.DescContains
}
if in.NotesContains != "" {
filter.NotesContains = in.NotesContains
}
if in.ExternalContains != "" {
filter.ExternalRefContains = in.ExternalContains
}
if in.ExternalRef != "" {
filter.ExternalRef = &in.ExternalRef
}
filter.CreatedAfter = in.CreatedAfter
filter.CreatedBefore = in.CreatedBefore
filter.UpdatedAfter = in.UpdatedAfter
filter.UpdatedBefore = in.UpdatedBefore
filter.ClosedAfter = in.ClosedAfter
filter.ClosedBefore = in.ClosedBefore
if in.EmptyDesc {
filter.EmptyDescription = true
}
if in.NoAssignee {
filter.NoAssignee = true
}
if in.NoLabels {
filter.NoLabels = true
}
if in.SkipLabels {
filter.SkipLabels = true
}
if in.SkipCounts {
filter.SkipCounts = true
}
if in.Brief {
filter.Lite = true
}
if in.PriorityMin != nil {
p := *in.PriorityMin
filter.PriorityMin = &p
}
if in.PriorityMax != nil {
p := *in.PriorityMax
filter.PriorityMax = &p
}
if in.PinnedFlag {
pinned := true
filter.Pinned = &pinned
} else if in.NoPinnedFlag || (!statusSelectsPinned(statusParts, !in.ReadyFlag) && !in.AllFlag) {
pinned := false
filter.Pinned = &pinned
}
applyTypeSuppressions(in, cfg, &filter)
for _, raw := range in.ExcludeTypes {
for _, t := range strings.Split(raw, ",") {
t = strings.TrimSpace(t)
if t != "" {
filter.ExcludeTypes = append(filter.ExcludeTypes, types.IssueType(utils.NormalizeIssueType(t)))
}
}
}
if in.ParentID != "" {
pid := in.ParentID
filter.ParentID = &pid
}
if in.NoParent {
filter.NoParent = true
}
if in.MolType != nil {
filter.MolType = in.MolType
}
if in.WispType != nil {
filter.WispType = in.WispType
}
if in.DeferredFlag {
filter.Deferred = true
}
filter.DeferAfter = in.DeferAfter
filter.DeferBefore = in.DeferBefore
filter.DueAfter = in.DueAfter
filter.DueBefore = in.DueBefore
if in.OverdueFlag {
filter.Overdue = true
}
if len(in.MetadataFields) > 0 {
filter.MetadataFields = in.MetadataFields
}
if in.HasMetadataKey != "" {
filter.HasMetadataKey = in.HasMetadataKey
}
if err := ValidateMetadataFilters(in.MetadataFields, in.HasMetadataKey); err != nil {
return filter, err
}
return filter, nil
}
// applyTypeSuppressions applies every default suppression that hides a bead on
// account of WHAT IT IS, so that a "show everything" frontend has exactly one
// thing to skip. Two kinds live here: the type-level exclusions that make the
// default listing show durable work only (templates, gates, infra types), and
// the plane decision — whether the wisps TABLE is read at all, and for a named
// infra type whether only its ephemeral rows are.
//
// IncludeAllTypes lifts them ALL by skipping this function entirely, which is
// what makes it future-proof: a suppression added here is automatically lifted
// for frontends like `bd human list` without touching them.
func applyTypeSuppressions(in issueops.ListRequest, cfg ListConfig, filter *types.IssueFilter) {
if in.IncludeAllTypes {
return
}
if !in.IncludeTemplates {
isTemplate := false
filter.IsTemplate = &isTemplate
}
if !in.IncludeGates && in.IssueType != "gate" {
filter.ExcludeTypes = append(filter.ExcludeTypes, "gate")
}
if !in.IncludeInfra && !cfg.IsInfra(in.IssueType) {
for _, t := range cfg.InfraTypes() {
filter.ExcludeTypes = append(filter.ExcludeTypes, types.IssueType(t))
}
}
// The plane bit. Three requests admit the wisp table: an explicit
// IncludeEphemeral, IncludeInfra (which admits the plane AND drops the
// infra-type exclusions above), and naming an infra type (which narrows to
// its ephemeral rows, below). Everything else is the durable listing.
// IncludeAllTypes is a fourth, via the early return above — it is the union
// of these flags, so it must decide the plane too, not only the type
// exclusions.
if !in.IncludeEphemeral && !in.IncludeInfra && (in.IssueType == "" || !cfg.IsInfra(in.IssueType)) {
filter.SkipWisps = true
}
// Naming an infra type narrows the read to its EPHEMERAL rows alone, which
// is where creating one puts it. IncludeEphemeral lifts that narrowing,
// because it promises the durable answer PLUS the plane, never the plane
// instead: an infra-typed row can still be durable — a promoted wisp, an
// issue retyped after it was created, or one written before its type
// joined types.infra — and while the narrowing held, `bd search --type
// message` (whose scope sets the flag) dropped exactly those rows with exit
// 0. IncludeInfra alone keeps the narrowing, and BuildCountFilter's
// IncludeInfra arm mirrors both halves (GH#4387).
if cfg.IsInfra(in.IssueType) && !in.IncludeEphemeral {
ephemeral := true
filter.Ephemeral = &ephemeral
}
}
// splitStatusSelector splits a --status selector into its trimmed
// comma-separated parts. An empty selector yields nil. This is the only
// reading of the selector syntax; everything downstream works on the parts.
func splitStatusSelector(status string) []string {
if status == "" {
return nil
}
parts := strings.Split(status, ",")
for i := range parts {
parts[i] = strings.TrimSpace(parts[i])
}
return parts
}
// statusSelectsPinned reports whether a status selector asks for
// pinned-carrying beads: the pinned or hooked status, or — when the selector
// actually applies to the query — the "all" selector, which promises every
// status. The pinned default is not forced off for a filter that asks for
// those beads. allApplies is false under --ready: `--status all` (and the
// omitted selector) still pin open, so "all" must not lift the pinned
// default there. Explicit selectors are honored under --ready (GH#5832);
// pinned and hooked still return true regardless of allApplies.
func statusSelectsPinned(parts []string, allApplies bool) bool {
for _, part := range parts {
switch part {
case "pinned", "hooked":
return true
case "all":
if allApplies {
return true
}
}
}
return false
}
// ValidStatusList renders the status names a filter accepts, for error text.
func ValidStatusList(customStatusNames []string) string {
validList := "open, in_progress, blocked, deferred, closed, pinned, hooked"
if len(customStatusNames) > 0 {
validList += ", " + strings.Join(customStatusNames, ", ")
}
return validList
}
// ApplyStatusFilter parses a status selector - one status, or a
// comma-separated OR set - onto the filter.
func ApplyStatusFilter(filter *types.IssueFilter, status string, customStatusNames []string) error {
parts := splitStatusSelector(status)
if len(parts) == 0 {
return fmt.Errorf("invalid status %q (valid: %s)", status, ValidStatusList(customStatusNames))
}
return applyStatusParts(filter, parts, customStatusNames)
}
func applyStatusParts(filter *types.IssueFilter, parts []string, customStatusNames []string) error {
if len(parts) == 1 {
s := types.Status(parts[0])
if !s.IsValidWithCustom(customStatusNames) {
return fmt.Errorf("invalid status %q (valid: %s)", parts[0], ValidStatusList(customStatusNames))
}
filter.Status = &s
return nil
}
for _, part := range parts {
s := types.Status(part)
if !s.IsValidWithCustom(customStatusNames) {
// "all" is a real selector on its own (every status), so failing
// it as merely "invalid" would contradict the flag help. A custom
// status literally named "all" passes validation above instead.
if part == "all" {
return fmt.Errorf(`status "all" cannot be combined with other statuses`)
}
return fmt.Errorf("invalid status %q in multi-status filter (valid: %s)", part, ValidStatusList(customStatusNames))
}
filter.Statuses = append(filter.Statuses, s)
}
return nil
}