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>
This commit is contained in:
Julian Knutsen 2026-10-13 04:12:54 +00:00 • committed by GitHub
commit ec55baa425
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
66 changed files with 1898 additions and 737 deletions

View file

@ -217,6 +217,7 @@
100 71 TestEmbeddedCloseJSONReportsMoleculeAutoClose
100 71 TestEmbeddedInitRoleRoutingExplicitDefault
100 71 TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget
100 71 TestEmbeddedSearchRoutesAgree
100 72 TestEmbeddedContributorCreateMultiple
100 72 TestEmbeddedCreateWithGitRemote

View file

@ -380,6 +380,7 @@
40 24 TestEmbeddedIgnoredSeriesConvergesWithFreshInitShape
40 24 TestEmbeddedIssueOperationsCreateWithDependenciesSettlesInTheCreatingTransaction
40 24 TestEmbeddedMigrateSelfHealsAfterMidPassFault_4566
40 24 TestEmbeddedReaderListQueryMatchesTheTitleOrTheID
40 24 TestEmbeddedReaderListWispTypeNarrowsTheAdmittedPlaneRatherThanAdmittingIt
40 24 TestIgnoredCursorHealResumeRespectsOperatorOverride
40 24 TestLargeBatchApplyStatementCountsClassic40_Embedded

View file

@ -197,6 +197,7 @@
34 23 TestProxiedServerIfRevisionGuardUpdate
34 23 TestProxiedServerListWatchCountsTheOffsetIntoMaxRows
34 23 TestProxiedServerMolBurn
34 23 TestProxiedServerSearchRoutesAgree
34 23 TestProxiedServerServeUpdate
34 23 TestProxiedServerUpdateConcurrentClaim
34 23 TestProxiedServerUpdateWisp

View file

@ -467,7 +467,11 @@ linters:
# tests: false` means forbidigo never analyzes a test file at all, so that
# entry asserts nothing either way and scoping it would be the churn this
# comment just refused to write.
- path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|info|label|orphans|purge|search|todo|wisp|human)(_proxied_server)?\.go$'
#
# `search` LEFT this list when all three of its routes moved onto
# issueops.Reader.List with issueops.SearchListRequest (cmd/bd/search.go);
# it builds no filter any more.
- path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|info|label|orphans|purge|todo|wisp|human)(_proxied_server)?\.go$'
text: 'do not write a filter here'
linters:
- forbidigo

View file

@ -32,6 +32,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
description and metadata are unchanged, and omitting the flag (or passing
`0`) is byte-identical to today's output. JSON output is untouched;
`--include-comments` still streams every comment there.
- `GET /v0/beads/issues` accepts `q`, `bd search`'s free text, behind the
new `issues.list.search` capability token (additive; no wire_revision
bump). `issueops.ListRequest` gains `Query`, with `SearchIssues`' meaning
(title or id contains the text, case-insensitively), on every Reader
implementation, and `issueops.SearchListRequest` is search's scope as a
request. Every `bd search` route (direct, `--proxied-server` and the HTTP
backend) now asks `Reader.List` with it through one flag mapping; against
a server that does not advertise the token the HTTP client refuses before
dialing with a typed capability error. Two things a script can see follow
from that mapping: `bd search --type` expands aliases (`feat`, `mol`,
`dec`, ...) and validates the type as `bd list` does, so an unknown type
now exits 1 where it used to answer an empty result, and `bd search
--json` rows carry `comments_omitted` (additive) as `bd list --json` rows
do.
- `bd create --graph` now plans its batch through `issueops.BatchApplier`
instead of the old `buildDomainGraphPlan` path, so a graph create gets the
same atomic multi-row semantics as `bd batch apply`. A `waits-for` edge's
@ -494,6 +508,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
rollout) still stores P0, with no error on either side.
Out-of-tree storage backends must now honor `DefaultPriority`; see the
BREAKING (out-of-tree storage backends) entry under `### Changed`.
- `bd show --current` over the HTTP backend no longer prints the wrong issue.
Its in-progress/hooked lookup used the raw `SearchIssues` method, which
the HTTP backend refuses; the refusal was swallowed and the command fell
back to the last-touched issue, exit 0. The lookup now reads through the
`issueops.Querier` role, and a failed read is an error on every route
(including `--proxied-server`), never a fallback. A miss (nothing in
progress or hooked, or no actor) is another matter: `--proxied-server` now
falls back to the last-touched issue as the direct route always has, where
it used to fail with `no current issue found`.
- `bd list --type <infra type> --include-ephemeral` (and `GET
/v0/beads/issues` with the same parameters) now include that type's durable
rows — a promoted wisp, an issue retyped after it was created — beside its
wisps, as `--include-ephemeral` promises; the type used to narrow the read
to its wisps alone. `bd count --include-infra --include-ephemeral` and the
count endpoint count the same rows. An infra `--type` without
`--include-ephemeral` still reads only the wisps, and `bd search --type
<infra type>`, now served by the same listing, still finds that type's
wisps and durable rows alike.
- `bd recompute-blocked` on a workspace connected to `bd serve` is a no-op
that exits 0 instead of refusing: the server maintains `is_blocked` on
every write and the column lives in its database. `--json` reports
`{"rows_corrected": 0, "maintained_by": "server"}`.
- **The http store's `GetIssue` answers a miss with `storage.ErrNotFound`,
like the local stores.** It used to answer a missing (or empty) id with
`(nil, nil)`, which every caller written against the backend contract

View file

@ -251,6 +251,15 @@ credential would cross the network unencrypted) — pass `--allow-plaintext` to
override, or use `https://`. Switching a workspace that already selects a
different backend needs `--force`.
`bd search`, `bd show --current` and `bd recompute-blocked` work over HTTP
too, each in its own way. `bd search` asks the server's listing with its text (`q`, behind the `issues.list.search` capability) and
refuses before dialing against a server that does not advertise it.
`bd show --current` finds the actor's in-progress or hooked issue through the
server's boolean query. `bd recompute-blocked` is a no-op that exits 0: the
server maintains `is_blocked` on every write, and repairing a stale flag is
done in the server's own workspace (`--json` reports
`{"rows_corrected": 0, "maintained_by": "server"}`).
An embedding program that links beads as a library rather than running
`cmd/bd` registers this backend itself through the public
[`backend/http`](backend/http) package (`bdhttp.Register`), and can open a

View file

@ -113,6 +113,10 @@ type ReaderFixture struct {
AddDependency func(context.Context, *types.Dependency, string) error
// AddComment puts one comment on a durable issue.
AddComment func(ctx context.Context, issueID, author, text string) error
// PromoteWisp moves a seeded wisp into the durable plane, as `bd promote`
// does. It is the only way to seed a DURABLE row of an infra type: creating
// one routes it to the wisps plane on every backend.
PromoteWisp func(ctx context.Context, id, actor string) error
}
// RunReaderReadyDefaultTypeExclusionsYieldToAnExplicitType pins
@ -786,6 +790,112 @@ func RunReaderListReadyFlagRefusesAFilterItCannotCarry(t *testing.T, ctx context
assertReaderPageIDs(t, "List --id without --ready", page, []string{one})
}
// RunReaderListQueryMatchesTheTitleOrTheID pins ListRequest.Query: `bd
// search`'s text, which matches a row whose title OR id contains it, case
// insensitively, and which narrows without lifting a default exclusion — and
// issueops.SearchListRequest, the request every `bd search` route sends, which
// does lift them.
//
// EVERY KIND OF ROW the search scope promises is seeded with the text, because
// a scope that silently loses one kind answers every other row correctly: a
// template, a gate, a wisp of an infra type, and a DURABLE row of that type —
// a promoted wisp, which a type filter that narrows an infra type to its
// ephemeral rows drops with no error. Each must come back under the bare scope
// and under its own type.
//
// It scopes itself with a label rather than an id set, so the served leg runs
// it as written: listIssues publishes no id parameter.
func RunReaderListQueryMatchesTheTitleOrTheID(t *testing.T, ctx context.Context, fixture ReaderFixture) {
t.Helper()
if fixture.PromoteWisp == nil {
t.Fatal("fixture has no PromoteWisp: a durable row of an infra type cannot be seeded, and it is the row a narrowed type filter drops")
}
scope := readerLabel(fixture, "lsquery")
needle := strings.ToLower(fixture.IssuePrefix) + "qneedle"
titleHit := readerID(fixture, "lsquery", "title")
idHit := readerID(fixture, "lsquery", "idhit")
closedHit := readerID(fixture, "lsquery", "closed")
miss := readerID(fixture, "lsquery", "miss")
template := readerID(fixture, "lsquery", "template")
gate := readerID(fixture, "lsquery", "gate")
wispMessage := readerID(fixture, "lsquery", "wispmsg")
promotedMessage := readerID(fixture, "lsquery", "promotedmsg")
// The title carries the needle in UPPER case and the request asks in lower,
// so a case-sensitive match finds nothing.
titleIssue := readerIssue(titleHit, types.TypeTask, scope)
titleIssue.Title = "fix the " + strings.ToUpper(needle) + " path"
// The id-hit's title says nothing about it: only its id can match.
idIssue := readerIssue(idHit, types.TypeTask, scope)
idIssue.Title = "unrelated words"
closedIssue := readerIssue(closedHit, types.TypeTask, scope)
closedIssue.Title = "old " + needle
closedIssue.Status = types.StatusClosed
missIssue := readerIssue(miss, types.TypeTask, scope)
missIssue.Title = "nothing to see"
templateIssue := readerIssue(template, types.TypeTask, scope)
templateIssue.Title = needle + " template"
templateIssue.IsTemplate = true
gateIssue := readerIssue(gate, types.TypeGate, scope)
gateIssue.Title = needle + " gate"
for _, issue := range []*types.Issue{titleIssue, idIssue, closedIssue, missIssue, templateIssue, gateIssue} {
seedReaderIssue(t, ctx, fixture, issue)
}
// Two rows of the same infra type, one per plane. `message` is built in,
// so the type is valid on every backend without configuration.
for _, id := range []string{wispMessage, promotedMessage} {
message := readerIssue(id, types.TypeMessage, scope)
message.Title = needle + " message"
message.Ephemeral = true
seedReaderWisp(t, ctx, fixture, message)
}
if err := fixture.PromoteWisp(ctx, promotedMessage, "seed"); err != nil {
t.Fatalf("promote wisp %s: %v", promotedMessage, err)
}
searchType := func(issueType types.IssueType) publicops.ListRequest {
req := searchScoped(needle, scope)
req.IssueType = string(issueType)
return req
}
for _, tc := range []struct {
name string
req publicops.ListRequest
want []string
}{
{"a title match, case-insensitively, under the default exclusions", publicops.ListRequest{Labels: []string{scope}, Query: needle}, []string{titleHit}},
{"AllFlag takes the closed match back", publicops.ListRequest{Labels: []string{scope}, Query: needle, AllFlag: true}, []string{titleHit, closedHit}},
{"an id match whose title does not contain the text", publicops.ListRequest{Labels: []string{scope}, Query: idHit, AllFlag: true}, []string{idHit}},
{"text nothing contains", publicops.ListRequest{Labels: []string{scope}, Query: needle + "-absent", AllFlag: true}, nil},
{"no text narrows nothing", publicops.ListRequest{Labels: []string{scope}}, []string{titleHit, idHit, miss}},
{"SearchListRequest, `bd search`'s scope, takes every status and every kind of row back", searchScoped(needle, scope), []string{titleHit, closedHit, template, gate, wispMessage, promotedMessage}},
{"SearchListRequest under an infra type keeps both planes' rows of it", searchType(types.TypeMessage), []string{wispMessage, promotedMessage}},
{"SearchListRequest under the gate type", searchType(types.TypeGate), []string{gate}},
{"SearchListRequest under a plain type keeps its templates", searchType(types.TypeTask), []string{titleHit, closedHit, template}},
// Outside the search scope an infra type alone reads only its
// ephemeral rows, which is where creating one puts it; IncludeEphemeral
// is what lifts that narrowing to the durable rows as well.
{"an infra type alone reads only its ephemeral rows", publicops.ListRequest{Labels: []string{scope}, Query: needle, IssueType: string(types.TypeMessage)}, []string{wispMessage}},
{"IncludeEphemeral lifts that narrowing", publicops.ListRequest{Labels: []string{scope}, Query: needle, IssueType: string(types.TypeMessage), IncludeEphemeral: true}, []string{wispMessage, promotedMessage}},
} {
page, err := fixture.Reader.List(ctx, tc.req)
if err != nil {
t.Errorf("List %s: %v", tc.name, err)
continue
}
assertReaderPageIDSet(t, "List "+tc.name, page, tc.want)
}
}
// searchScoped is the library's search request narrowed to one case's label,
// the request every `bd search` route sends.
func searchScoped(query, label string) publicops.ListRequest {
req := publicops.SearchListRequest(query)
req.Labels = []string{label}
return req
}
// RunReaderListEmptyPageIsWellFormed pins the page shape when nothing matches
// (reader.go:376-381). Items is never nil for a successful call, so no caller
// has to tell null from empty to learn that nothing matched, and an empty page

View file

@ -568,6 +568,7 @@ var roleContractCases = []roleContract{
RunReaderListKeysetPositionResumesTheCreatedDescIDAscOrder,
RunReaderListReadyFlagAnswersTheBlockerAwareSet,
RunReaderListReadyFlagRefusesAFilterItCannotCarry,
RunReaderListQueryMatchesTheTitleOrTheID,
RunReaderListEmptyPageIsWellFormed,
RunReaderListMaxRowsIsHonored,
RunReaderListMaxRowsBoundaryIsLimitPlusOffset,

View file

@ -33,7 +33,10 @@ go_test(
"attach_test.go",
"e2e_cli_test.go",
"e2e_mol_test.go",
"e2e_recompute_blocked_test.go",
"e2e_remote_roles_test.go",
"e2e_search_test.go",
"e2e_show_current_test.go",
"open_test.go",
"per_open_credential_test.go",
"register_test.go",

View file

@ -157,7 +157,6 @@ shapes:
- id: gc-show-current
source: gc cmd_bd_show_watch.go bdWatchRunner (show --current --json)
args: [show, --current, --json]
pending: {slice: "S6e", reason: "NEW: resolveCurrentIssueID calls raw store.SearchIssues, the http refusal is swallowed, and it silently falls back to the last-touched issue (wrong issue, exit 0)"}
- id: gc-show-missing
source: gc BdStore.Get not-found classification (routing fallbacks)
args: [show, --json, e2e-nonexistent]
@ -326,7 +325,7 @@ shapes:
source: mc mol-bug-report-flow-v2 (bd search)
args: [search, "Routed", --json]
compare: ids
pending: {slice: "S24", reason: "NEW: bd search is refused over http ('partial-id search is not available over HTTP'); not in B3"}
pending: {slice: "S6c+SRV-1", reason: "S26 sends bd search as listIssues q behind issues.list.search, which the reference server does not advertise, so the client refuses before dialing; remove the mark when reference_server.json is upgraded"}
- id: mc-status
source: mc normalized_child_launch.py (bd status)
args: [status, --json]
@ -412,7 +411,6 @@ shapes:
source: gc bdstore_blocked_repair.go RecomputeBlocked
args: [recompute-blocked, --json]
compare: exit
pending: {slice: "S25", reason: "NEW: recompute-blocked refuses over http ('storage backend does not support is_blocked recompute'); gc BdStore.RecomputeBlocked issues it; not in B3"}
- id: gc-backup-status
source: gc checks_proxied_backup_coverage.go (backup status --json)
args: [backup, status, --json]

View file

@ -0,0 +1,46 @@
//go:build cgo
package bdhttp_test
import (
"encoding/json"
"strings"
"testing"
)
// TestE2E_RecomputeBlockedOverHTTP is S25. On a remote backend
// `bd recompute-blocked` is a no-op that exits 0: the server maintains
// is_blocked on every write and the column lives in its database. --json still
// carries rows_corrected (gc parses it) and says the server maintains the flag.
func TestE2E_RecomputeBlockedOverHTTP(t *testing.T) {
bd := connectE2EWorkspace(t, "worker")
// A blocked edge exists, so there is state the server derived; the client
// must not claim to have repaired or refused it.
blocked := createE2EIssue(t, bd, "blocked")
blocker := createE2EIssue(t, bd, "blocker")
mustRun(t, bd, "dep", "add", blocked, blocker, "--json")
r := mustRun(t, bd, "recompute-blocked", "--json")
var body struct {
RowsCorrected *int `json:"rows_corrected"`
MaintainedBy string `json:"maintained_by"`
}
if err := json.Unmarshal([]byte(strings.TrimSpace(r.stdout)), &body); err != nil {
t.Fatalf("parse recompute-blocked --json: %v\n%s", err, r.stdout)
}
if body.RowsCorrected == nil || *body.RowsCorrected != 0 || body.MaintainedBy != "server" {
t.Fatalf("recompute-blocked --json = %s, want rows_corrected 0 and maintained_by server", r.stdout)
}
text := mustRun(t, bd, "recompute-blocked")
if !strings.Contains(text.stdout, "maintained by the bd serve backend") {
t.Errorf("recompute-blocked text does not say the server maintains the flag: %s", text.stdout)
}
// The ready set still reflects the edge: nothing was rewritten.
ready := jsonIDSet(t, mustRun(t, bd, "ready", "--json").stdout)
if ready[blocked] || !ready[blocker] {
t.Errorf("bd ready after recompute-blocked = %v, want %s ready and %s blocked", ready, blocker, blocked)
}
}

View file

@ -0,0 +1,57 @@
//go:build cgo
package bdhttp_test
import (
"testing"
)
// TestE2E_SearchOverHTTP is S26. `bd search` called the raw SearchIssues
// method, which the http backend refuses ("partial-id search is not available
// over HTTP"); it now asks Reader.List with the text in ListRequest.Query,
// which travels as listIssues' `q` behind issues.list.search.
func TestE2E_SearchOverHTTP(t *testing.T) {
bd := connectE2EWorkspace(t, "worker")
routed := createE2EIssue(t, bd, "Routed pool work")
alsoRouted := createE2EIssue(t, bd, "re-routed later")
closedRouted := createE2EIssue(t, bd, "routed and done")
other := createE2EIssue(t, bd, "something else")
mustRun(t, bd, "close", closedRouted, "--json")
// A refusal of the raw SearchIssuesWithCounts seam is the S26 regression
// itself, not a missing dependency: S6c (the externaldeps reader
// passthrough) is underneath, so nothing on this route reaches that seam.
r := bd("search", "ROUTED", "--json")
if r.code != 0 {
t.Fatalf("bd search failed (exit %d): stdout=%s stderr=%s", r.code, r.stdout, r.stderr)
}
got := jsonIDSet(t, r.stdout)
// Case-insensitive, every status (search includes closed by default).
for _, id := range []string{routed, alsoRouted, closedRouted} {
if !got[id] {
t.Errorf("bd search ROUTED missed %s: %s", id, r.stdout)
}
}
if got[other] {
t.Errorf("bd search ROUTED matched %s, whose title does not contain it: %s", other, r.stdout)
}
// --status narrows, as on a local workspace.
open := jsonIDSet(t, mustRun(t, bd, "search", "routed", "--status", "open", "--json").stdout)
if open[closedRouted] || !open[routed] {
t.Errorf("bd search routed --status open = %v, want %s without %s", open, routed, closedRouted)
}
// An id matches even when the title does not contain it.
byID := jsonIDSet(t, mustRun(t, bd, "search", other, "--json").stdout)
if !byID[other] {
t.Errorf("bd search %s did not match the issue by its id: %v", other, byID)
}
// A flag listIssues publishes nothing for refuses rather than widening the
// search.
if r := bd("search", "routed", "--desc-contains", "pool", "--json"); r.code == 0 {
t.Errorf("bd search --desc-contains succeeded over http; the wire cannot carry it, so it must refuse: %s", r.stdout)
}
}

View file

@ -0,0 +1,88 @@
//go:build cgo
package bdhttp_test
import (
"strings"
"testing"
)
// connectE2EWorkspace starts an in-process server and returns a workspace
// `bd connect`ed to it, plus a runner that drives the built binary there as
// the given actor.
func connectE2EWorkspace(t *testing.T, actor string) func(args ...string) bdResult {
t.Helper()
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
addr := startE2EServer(t)
workspace := t.TempDir()
env := []string{"BEADS_ACTOR=" + actor}
if r := runBD(t, bin, workspace, env, "connect", "http://"+addr, "--expect-project-id", e2eProjectID, "--json"); r.code != 0 {
t.Fatalf("bd connect failed (exit %d): stdout=%s stderr=%s", r.code, r.stdout, r.stderr)
}
return func(args ...string) bdResult {
t.Helper()
return runBD(t, bin, workspace, env, args...)
}
}
func mustRun(t *testing.T, bd func(args ...string) bdResult, args ...string) bdResult {
t.Helper()
r := bd(args...)
if r.code != 0 {
t.Fatalf("bd %s failed (exit %d): stdout=%s stderr=%s", strings.Join(args, " "), r.code, r.stdout, r.stderr)
}
return r
}
func createE2EIssue(t *testing.T, bd func(args ...string) bdResult, title string) string {
t.Helper()
id := firstJSONField(t, mustRun(t, bd, "create", title, "--json").stdout, "id")
if id == "" {
t.Fatalf("bd create %q --json produced no id", title)
}
return id
}
// TestE2E_ShowCurrentOverHTTP is S6e. `bd show --current` used to read the
// actor's in-progress work through the raw SearchIssues method, which the http
// backend refuses; the refusal was swallowed and the command printed the
// LAST-TOUCHED issue instead, exit 0. It now reads through the Querier role
// (queryIssues), so the in-progress issue wins over a more recently touched
// one, and a hooked issue is found when nothing is in progress.
func TestE2E_ShowCurrentOverHTTP(t *testing.T) {
bd := connectE2EWorkspace(t, "worker")
current := createE2EIssue(t, bd, "the work in progress")
hooked := createE2EIssue(t, bd, "hooked work")
touched := createE2EIssue(t, bd, "touched last")
mustRun(t, bd, "update", current, "--status", "in_progress", "--assignee", "worker", "--json")
// Touch another issue AFTER claiming, so last-touched is not the current
// issue: the old swallowed refusal answered with exactly this one.
mustRun(t, bd, "update", touched, "--priority", "1", "--json")
showCurrent := func() string {
t.Helper()
r := mustRun(t, bd, "show", "--current", "--json")
return firstJSONField(t, r.stdout, "id")
}
if got := showCurrent(); got != current {
t.Fatalf("bd show --current = %s, want the in-progress %s (last touched was %s)", got, current, touched)
}
// Nothing in progress: the hooked issue assigned to the actor is current.
mustRun(t, bd, "update", current, "--status", "open", "--assignee", "", "--json")
mustRun(t, bd, "update", hooked, "--status", "hooked", "--assignee", "worker", "--json")
mustRun(t, bd, "update", touched, "--priority", "2", "--json")
if got := showCurrent(); got != hooked {
t.Fatalf("bd show --current = %s, want the hooked %s (last touched was %s)", got, hooked, touched)
}
// Neither: last-touched is the answer, and only now.
mustRun(t, bd, "update", hooked, "--status", "open", "--assignee", "", "--json")
mustRun(t, bd, "update", touched, "--priority", "3", "--json")
if got := showCurrent(); got != touched {
t.Fatalf("bd show --current = %s, want the last-touched %s when nothing is in progress or hooked", got, touched)
}
}

View file

@ -314,13 +314,13 @@ go_library(
"schema.go",
"schema_skew.go",
"search.go",
"search_proxied_server.go",
"send_metrics.go",
"serve.go",
"setup.go",
"ship.go",
"show.go",
"show_children.go",
"show_current.go",
"show_display.go",
"show_format.go",
"show_proxied_server.go",
@ -1112,6 +1112,9 @@ go_test(
"schema_test.go",
"search_embedded_test.go",
"search_proxied_integration_test.go",
"search_routes_embedded_test.go",
"search_routes_parity_test.go",
"search_routes_proxied_test.go",
"search_test.go",
"send_metrics_diagnostics_test.go",
"serve_batch_close_proxied_integration_test.go",

View file

@ -298,53 +298,3 @@ func gatherProxiedHierarchical(ctx context.Context, uw uow.UnitOfWork, parentID
out = append(out, descendants...)
return out, nil
}
type currentIssueSearcher interface {
SearchIssues(context.Context, string, types.IssueFilter) ([]*types.Issue, error)
}
// resolveCurrentIssueID determines the current active issue for the agent.
// Priority: in-progress assigned to actor > hooked > last touched.
func resolveCurrentIssueID(ctx context.Context) string {
return resolveCurrentIssueIDFrom(ctx, store, getActorWithGit, GetLastTouchedID)
}
func resolveCurrentIssueIDFrom(ctx context.Context, searcher currentIssueSearcher, currentActor func() string, fallback func() string) string {
if searcher == nil {
return fallback()
}
actor := currentActor()
if actor == "" {
return fallback()
}
for _, status := range []types.Status{types.StatusInProgress, types.StatusHooked} {
status := status
filter := types.IssueFilter{
Status: &status,
Assignee: &actor,
}
issues, err := searcher.SearchIssues(ctx, "", filter)
if err == nil && len(issues) > 0 {
return issues[0].ID
}
}
return fallback()
}
func resolveCurrentIssueIDProxied(ctx context.Context, uw uow.UnitOfWork) string {
currentActor := getActorWithGit()
if currentActor == "" {
return ""
}
for _, status := range []types.Status{types.StatusInProgress, types.StatusHooked} {
st := status
filter := types.IssueFilter{Status: &st, Assignee: &currentActor}
page, err := uw.IssueUseCase().SearchIssues(ctx, "", filter)
if err == nil && len(page.Items) > 0 {
return page.Items[0].ID
}
}
return ""
}

View file

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"github.com/spf13/cobra"
@ -27,6 +28,11 @@ It is idempotent: on a consistent database it changes nothing. Works in every
storage mode — embedded, server, and proxied-server (unlike 'bd doctor', which
is server-mode only).
On a workspace connected to a bd serve backend ('bd connect') it is a no-op
that exits 0: the server maintains is_blocked on every write, and the column
lives in the server's database, so the repair is run there, by the server's
operator. --json then reports {"rows_corrected": 0, "maintained_by": "server"}.
Examples:
bd recompute-blocked # Repair stale is_blocked flags
bd recompute-blocked --json # Machine-parseable {"rows_corrected": N}`,
@ -48,15 +54,23 @@ Examples:
return runRecomputeBlockedProxiedServer(ctx)
}
recomputer, ok := storage.UnwrapStore(store).(storage.BlockedRecomputer)
if !ok {
return HandleError("storage backend does not support is_blocked recompute")
}
changed, err := recomputer.RecomputeAllBlocked(ctx)
// One library entry for every store (storage.RecomputeBlocked): a
// local store recomputes its own column; a remote backend (`bd
// connect`) answers that its server maintains the column, and
// recomputes nothing. The --proxied-server route above bypasses it on
// purpose; runRecomputeBlockedProxiedServer says why.
result, err := storage.RecomputeBlocked(ctx, store)
if err != nil {
var unsup *storage.ErrUnsupported
if errors.As(err, &unsup) {
return HandleError("storage backend does not support is_blocked recompute")
}
return HandleError("recompute is_blocked: %v", err)
}
return renderRecomputeBlocked(changed)
if result.MaintainedBy == storage.BlockedMaintainedByServer {
return renderRecomputeBlockedServerMaintained()
}
return renderRecomputeBlocked(result.RowsCorrected)
},
}
@ -76,6 +90,25 @@ func renderRecomputeBlocked(changed int) error {
return nil
}
// renderRecomputeBlockedServerMaintained renders a remote backend's answer
// (storage.BlockedMaintainedByServer): nothing was recomputed here, because
// the server derives the column and it lives in the server's database — see
// storage.RecomputeBlocked for why that is a no-op rather than a wire
// operation.
//
// It still answers rows_corrected (0) because callers parse it (gc's
// BdStore.RecomputeBlocked requires the member, and wh-bridge-sync reads the
// exit code), and it carries `maintained_by: "server"` so a caller that cares
// can tell "nothing was stale" from "nothing was checked here".
func renderRecomputeBlockedServerMaintained() error {
if jsonOutput {
return outputJSON(map[string]interface{}{"rows_corrected": 0, "maintained_by": storage.BlockedMaintainedByServer})
}
fmt.Println("is_blocked is maintained by the bd serve backend on every write; nothing to recompute from this client.")
fmt.Println("To repair a stale flag on the server's database, run bd recompute-blocked in the server's workspace.")
return nil
}
func init() {
rootCmd.AddCommand(recomputeBlockedCmd)
}

View file

@ -1,9 +1,11 @@
package main
import (
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
@ -12,6 +14,7 @@ import (
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
var searchCmd = &cobra.Command{
@ -49,273 +52,184 @@ Examples:
c.CloseEventAndAdd(evt)
}
}()
if usesProxiedServer() {
return runSearchProxiedServer(cmd, rootCtx, args)
}
queryFlag, _ := cmd.Flags().GetString("query")
var query string
if len(args) > 0 {
query = strings.Join(args, " ")
} else if queryFlag != "" {
query = queryFlag
}
if query == "" {
if err := cmd.Help(); err != nil {
fmt.Fprintf(os.Stderr, "Error displaying help: %v\n", err)
}
return HandleError("search query is required")
}
// Get filter flags
status, _ := cmd.Flags().GetString("status")
assignee, _ := cmd.Flags().GetString("assignee")
issueType, _ := cmd.Flags().GetString("type")
limit, _ := cmd.Flags().GetInt("limit")
labels, _ := cmd.Flags().GetStringSlice("label")
labelsAny, _ := cmd.Flags().GetStringSlice("label-any")
longFormat, _ := cmd.Flags().GetBool("long")
sortBy, _ := cmd.Flags().GetString("sort")
reverse, _ := cmd.Flags().GetBool("reverse")
// Date range flags
createdAfter, _ := cmd.Flags().GetString("created-after")
createdBefore, _ := cmd.Flags().GetString("created-before")
updatedAfter, _ := cmd.Flags().GetString("updated-after")
updatedBefore, _ := cmd.Flags().GetString("updated-before")
closedAfter, _ := cmd.Flags().GetString("closed-after")
closedBefore, _ := cmd.Flags().GetString("closed-before")
// Priority range flags
priorityMinStr, _ := cmd.Flags().GetString("priority-min")
priorityMaxStr, _ := cmd.Flags().GetString("priority-max")
// Pattern matching flags
descContains, _ := cmd.Flags().GetString("desc-contains")
notesContains, _ := cmd.Flags().GetString("notes-contains")
externalContains, _ := cmd.Flags().GetString("external-contains")
// Empty/null check flags
emptyDesc, _ := cmd.Flags().GetBool("empty-description")
noAssignee, _ := cmd.Flags().GetBool("no-assignee")
noLabels, _ := cmd.Flags().GetBool("no-labels")
// Normalize labels
labels = utils.NormalizeLabels(labels)
labelsAny = utils.NormalizeLabels(labelsAny)
// Build filter
filter := types.IssueFilter{
Limit: limit,
}
if status != "" && status != "all" {
cfg, err := workapi.LoadStoreListConfig(rootCtx, store)
if err != nil {
return HandleError("loading status configuration: %v", err)
}
if err := workapi.ApplyStatusFilter(&filter, status, cfg.CustomStatusNames()); err != nil {
return HandleError("%v", err)
}
}
// Default (no --status) searches ALL statuses including closed
// (bd-t5yex): the dominant real-world query is "was this already
// found/filed/fixed?" — exactly where silently excluding closed
// issues produces a false "no". This reverses the hq-319 open-only
// default, which traded that correctness for scan scope; narrow
// explicitly (e.g. --status open) when performance matters.
if assignee != "" {
filter.Assignee = &assignee
}
if issueType != "" {
t := types.IssueType(issueType)
filter.IssueType = &t
}
if len(labels) > 0 {
filter.Labels = labels
}
if len(labelsAny) > 0 {
filter.LabelsAny = labelsAny
}
// Pattern matching
if descContains != "" {
filter.DescriptionContains = descContains
}
if notesContains != "" {
filter.NotesContains = notesContains
}
if externalContains != "" {
filter.ExternalRefContains = externalContains
}
// Empty/null checks
if emptyDesc {
filter.EmptyDescription = true
}
if noAssignee {
filter.NoAssignee = true
}
if noLabels {
filter.NoLabels = true
}
// Date ranges
if createdAfter != "" {
t, err := parseTimeFlag(createdAfter)
if err != nil {
return HandleError("parsing --created-after: %v", err)
}
filter.CreatedAfter = &t
}
if createdBefore != "" {
t, err := parseTimeFlag(createdBefore)
if err != nil {
return HandleError("parsing --created-before: %v", err)
}
filter.CreatedBefore = &t
}
if updatedAfter != "" {
t, err := parseTimeFlag(updatedAfter)
if err != nil {
return HandleError("parsing --updated-after: %v", err)
}
filter.UpdatedAfter = &t
}
if updatedBefore != "" {
t, err := parseTimeFlag(updatedBefore)
if err != nil {
return HandleError("parsing --updated-before: %v", err)
}
filter.UpdatedBefore = &t
}
if closedAfter != "" {
t, err := parseTimeFlag(closedAfter)
if err != nil {
return HandleError("parsing --closed-after: %v", err)
}
filter.ClosedAfter = &t
}
if closedBefore != "" {
t, err := parseTimeFlag(closedBefore)
if err != nil {
return HandleError("parsing --closed-before: %v", err)
}
filter.ClosedBefore = &t
}
if cmd.Flags().Changed("priority-min") {
priorityMin, err := validation.ValidatePriority(priorityMinStr)
if err != nil {
return HandleError("parsing --priority-min: %v", err)
}
filter.PriorityMin = &priorityMin
}
if cmd.Flags().Changed("priority-max") {
priorityMax, err := validation.ValidatePriority(priorityMaxStr)
if err != nil {
return HandleError("parsing --priority-max: %v", err)
}
filter.PriorityMax = &priorityMax
}
metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field")
if len(metadataFieldFlags) > 0 {
filter.MetadataFields = make(map[string]string, len(metadataFieldFlags))
for _, mf := range metadataFieldFlags {
k, v, ok := strings.Cut(mf, "=")
if !ok || k == "" {
return HandleError("invalid --metadata-field: expected key=value, got %q", mf)
}
if err := storage.ValidateMetadataKey(k); err != nil {
return HandleError("invalid --metadata-field key: %v", err)
}
filter.MetadataFields[k] = v
}
}
hasMetadataKey, _ := cmd.Flags().GetString("has-metadata-key")
if hasMetadataKey != "" {
if err := storage.ValidateMetadataKey(hasMetadataKey); err != nil {
return HandleError("invalid --has-metadata-key: %v", err)
}
filter.HasMetadataKey = hasMetadataKey
}
ctx := rootCtx
issues, err := store.SearchIssues(ctx, query, filter)
if err != nil {
return HandleError("%v", err)
}
// Apply sorting
workapi.SortIssues(issues, sortBy, reverse)
if jsonOutput {
// Get labels and dependency counts
issueIDs := make([]string, len(issues))
for i, issue := range issues {
issueIDs[i] = issue.ID
}
labelsMap, err := store.GetLabelsForIssues(ctx, issueIDs)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to get labels: %v\n", err)
labelsMap = make(map[string][]string)
}
depCounts, err := store.GetDependencyCounts(ctx, issueIDs)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to get dependency counts: %v\n", err)
depCounts = make(map[string]*types.DependencyCounts)
}
commentCounts, err := store.GetCommentCounts(ctx, issueIDs)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to get comment counts: %v\n", err)
commentCounts = make(map[string]int)
}
// Populate labels
for _, issue := range issues {
issue.Labels = labelsMap[issue.ID]
}
// Build response with counts
issuesWithCounts := make([]*types.IssueWithCounts, len(issues))
for i, issue := range issues {
counts := depCounts[issue.ID]
if counts == nil {
counts = &types.DependencyCounts{DependencyCount: 0, DependentCount: 0}
}
issuesWithCounts[i] = &types.IssueWithCounts{
Issue: issue,
DependencyCount: counts.DependencyCount,
DependentCount: counts.DependentCount,
CommentCount: commentCounts[issue.ID],
}
}
return outputJSON(issuesWithCounts)
}
// Load labels for display
issueIDs := make([]string, len(issues))
for i, issue := range issues {
issueIDs[i] = issue.ID
}
labelsMap, _ := store.GetLabelsForIssues(ctx, issueIDs)
for _, issue := range issues {
issue.Labels = labelsMap[issue.ID]
}
outputSearchResults(issues, query, longFormat)
return nil
return runSearch(cmd, args)
},
}
// runSearch is `bd search` on every route — the direct store, the proxied
// server and a remote backend — and every route asks the same library entry:
// issueops.Reader.List with issueops.SearchListRequest (plus the narrowing
// flags), whose ListRequest.Query is SearchIssues' free text. The route only
// decides WHICH reader answers: the store's, or the proxied provider's. A
// remote backend's reader sends the text as listIssues' `q`, which the
// server's handler hands to the same role, and refuses before dialing against
// a server that does not advertise issues.list.search.
//
// The page is the first --limit rows in the store's default order (the
// request's SortBy); --sort/--reverse reorder that page here, which is what
// this command has always done.
func runSearch(cmd *cobra.Command, args []string) error {
fail := HandleError
if usesProxiedServer() {
fail = HandleErrorRespectJSON
}
queryFlag, _ := cmd.Flags().GetString("query")
query := queryFlag
if len(args) > 0 {
query = strings.Join(args, " ")
}
if query == "" {
if err := cmd.Help(); err != nil {
fmt.Fprintf(os.Stderr, "Error displaying help: %v\n", err)
}
return fail("search query is required")
}
req, err := searchListRequest(cmd, query)
if err != nil {
return fail("%v", err)
}
reader, err := searchReader()
if err != nil {
return fail("%v", err)
}
page, err := reader.List(rootCtx, req)
if err != nil {
var unsup *storage.ErrUnsupported
if errors.As(err, &unsup) && unsup.Capability != "" {
return fail("bd search needs a bd serve that advertises %s: %v", unsup.Capability, err)
}
return fail("%v", err)
}
sortBy, _ := cmd.Flags().GetString("sort")
reverse, _ := cmd.Flags().GetBool("reverse")
if jsonOutput {
items := make([]*types.IssueWithCounts, 0, len(page.Items))
for _, row := range page.Items {
if row != nil && row.Issue != nil {
items = append(items, row)
}
}
workapi.SortIssuesWithCounts(items, sortBy, reverse)
return outputJSON(items)
}
issues, _ := listPageIssues(page)
workapi.SortIssues(issues, sortBy, reverse)
longFormat, _ := cmd.Flags().GetBool("long")
outputSearchResults(issues, query, longFormat)
return nil
}
// searchReader is the Reader this invocation's route answers through, taken
// from the route's own accessor so its decorators are in place.
func searchReader() (issueops.Reader, error) {
if usesProxiedServer() {
return proxiedIssueReader()
}
if store == nil {
return nil, errors.New("no storage available")
}
return store.IssueReader()
}
// searchListRequest maps `bd search`'s flags onto issueops.SearchListRequest.
// Flags a backend's Reader cannot carry (over http: --updated-*, --closed-*,
// --priority-min/max, the text-contains and empty/absent filters) are put on
// the request anyway, so that Reader refuses them rather than answering a
// wider search than was asked for.
func searchListRequest(cmd *cobra.Command, query string) (issueops.ListRequest, error) {
flags := cmd.Flags()
str := func(name string) string { v, _ := flags.GetString(name); return v }
boolean := func(name string) bool { v, _ := flags.GetBool(name); return v }
limit, _ := flags.GetInt("limit")
labels, _ := flags.GetStringSlice("label")
labelsAny, _ := flags.GetStringSlice("label-any")
req := issueops.SearchListRequest(query)
req.Limit = &limit
if status := str("status"); status != "all" {
req.Status = status
}
req.Assignee = str("assignee")
// Expanded before the Reader validates it, as `bd list` does
// (list_input.go): an alias (feat, mol, mr, ...) names its canonical type,
// and a name the workspace does not know is refused, never an empty answer.
req.IssueType = utils.NormalizeIssueType(str("type"))
req.Labels = utils.NormalizeLabels(labels)
req.LabelsAny = utils.NormalizeLabels(labelsAny)
req.DescContains = str("desc-contains")
req.NotesContains = str("notes-contains")
req.ExternalContains = str("external-contains")
req.EmptyDesc = boolean("empty-description")
req.NoAssignee = boolean("no-assignee")
req.NoLabels = boolean("no-labels")
for _, d := range []struct {
flag string
dst **time.Time
}{
{"created-after", &req.CreatedAfter},
{"created-before", &req.CreatedBefore},
{"updated-after", &req.UpdatedAfter},
{"updated-before", &req.UpdatedBefore},
{"closed-after", &req.ClosedAfter},
{"closed-before", &req.ClosedBefore},
} {
raw := str(d.flag)
if raw == "" {
continue
}
t, err := parseTimeFlag(raw)
if err != nil {
return req, fmt.Errorf("parsing --%s: %w", d.flag, err)
}
*d.dst = &t
}
for _, p := range []struct {
flag string
dst **int
}{
{"priority-min", &req.PriorityMin},
{"priority-max", &req.PriorityMax},
} {
if !flags.Changed(p.flag) {
continue
}
v, err := validation.ValidatePriority(str(p.flag))
if err != nil {
return req, fmt.Errorf("parsing --%s: %w", p.flag, err)
}
*p.dst = &v
}
if fields, _ := flags.GetStringArray("metadata-field"); len(fields) > 0 {
req.MetadataFields = make(map[string]string, len(fields))
for _, mf := range fields {
k, v, ok := strings.Cut(mf, "=")
if !ok || k == "" {
return req, fmt.Errorf("invalid --metadata-field: expected key=value, got %q", mf)
}
if err := storage.ValidateMetadataKey(k); err != nil {
return req, fmt.Errorf("invalid --metadata-field key: %w", err)
}
req.MetadataFields[k] = v
}
}
if key := str("has-metadata-key"); key != "" {
if err := storage.ValidateMetadataKey(key); err != nil {
return req, fmt.Errorf("invalid --has-metadata-key: %w", err)
}
req.HasMetadataKey = key
}
return req, nil
}
// outputSearchResults formats and displays search results
func outputSearchResults(issues []*types.Issue, query string, longFormat bool) {
if len(issues) == 0 {
@ -360,7 +274,7 @@ func init() {
searchCmd.Flags().String("query", "", "Search query (alternative to positional argument)")
searchCmd.Flags().StringP("status", "s", "", "Filter by stored status (comma-separated for OR; open, in_progress, blocked, deferred, closed, all). Default searches all statuses including closed. Note: dependency-blocked issues use 'bd blocked'")
searchCmd.Flags().StringP("assignee", "a", "", "Filter by assignee")
searchCmd.Flags().StringP("type", "t", "", "Filter by type (bug, feature, task, epic, chore, decision, merge-request, molecule, gate)")
searchCmd.Flags().StringP("type", "t", "", "Filter by type (bug, feature, task, epic, chore, decision, message, molecule, gate, spike, story, milestone); custom types require types.custom config, and an unknown type is an error. Aliases: feat/enhancement→feature, mol→molecule, dec/adr→decision, mr→merge-request")
searchCmd.Flags().StringSliceP("label", "l", []string{}, "Filter by labels (AND: must have ALL)")
searchCmd.Flags().StringSlice("label-any", []string{}, "Filter by labels (OR: must have AT LEAST ONE)")
searchCmd.Flags().IntP("limit", "n", 50, "Limit results (default: 50)")

View file

@ -1,225 +0,0 @@
package main
import (
"context"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/internal/validation"
"github.com/steveyegge/beads/internal/workapi"
)
func runSearchProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
queryFlag, _ := cmd.Flags().GetString("query")
var query string
if len(args) > 0 {
query = strings.Join(args, " ")
} else if queryFlag != "" {
query = queryFlag
}
if query == "" {
if err := cmd.Help(); err != nil {
fmt.Fprintf(os.Stderr, "Error displaying help: %v\n", err)
}
return HandleErrorRespectJSON("search query is required")
}
status, _ := cmd.Flags().GetString("status")
assignee, _ := cmd.Flags().GetString("assignee")
issueType, _ := cmd.Flags().GetString("type")
limit, _ := cmd.Flags().GetInt("limit")
labels, _ := cmd.Flags().GetStringSlice("label")
labelsAny, _ := cmd.Flags().GetStringSlice("label-any")
longFormat, _ := cmd.Flags().GetBool("long")
sortBy, _ := cmd.Flags().GetString("sort")
reverse, _ := cmd.Flags().GetBool("reverse")
createdAfter, _ := cmd.Flags().GetString("created-after")
createdBefore, _ := cmd.Flags().GetString("created-before")
updatedAfter, _ := cmd.Flags().GetString("updated-after")
updatedBefore, _ := cmd.Flags().GetString("updated-before")
closedAfter, _ := cmd.Flags().GetString("closed-after")
closedBefore, _ := cmd.Flags().GetString("closed-before")
priorityMinStr, _ := cmd.Flags().GetString("priority-min")
priorityMaxStr, _ := cmd.Flags().GetString("priority-max")
descContains, _ := cmd.Flags().GetString("desc-contains")
notesContains, _ := cmd.Flags().GetString("notes-contains")
externalContains, _ := cmd.Flags().GetString("external-contains")
emptyDesc, _ := cmd.Flags().GetBool("empty-description")
noAssignee, _ := cmd.Flags().GetBool("no-assignee")
noLabels, _ := cmd.Flags().GetBool("no-labels")
labels = utils.NormalizeLabels(labels)
labelsAny = utils.NormalizeLabels(labelsAny)
filter := types.IssueFilter{
Limit: limit,
}
// Default (no --status) searches all statuses including closed
// (bd-t5yex) — keep in lockstep with the embedded path in search.go.
if assignee != "" {
filter.Assignee = &assignee
}
if issueType != "" {
t := types.IssueType(issueType)
filter.IssueType = &t
}
if len(labels) > 0 {
filter.Labels = labels
}
if len(labelsAny) > 0 {
filter.LabelsAny = labelsAny
}
if descContains != "" {
filter.DescriptionContains = descContains
}
if notesContains != "" {
filter.NotesContains = notesContains
}
if externalContains != "" {
filter.ExternalRefContains = externalContains
}
if emptyDesc {
filter.EmptyDescription = true
}
if noAssignee {
filter.NoAssignee = true
}
if noLabels {
filter.NoLabels = true
}
if createdAfter != "" {
t, err := parseTimeFlag(createdAfter)
if err != nil {
return HandleErrorRespectJSON("parsing --created-after: %v", err)
}
filter.CreatedAfter = &t
}
if createdBefore != "" {
t, err := parseTimeFlag(createdBefore)
if err != nil {
return HandleErrorRespectJSON("parsing --created-before: %v", err)
}
filter.CreatedBefore = &t
}
if updatedAfter != "" {
t, err := parseTimeFlag(updatedAfter)
if err != nil {
return HandleErrorRespectJSON("parsing --updated-after: %v", err)
}
filter.UpdatedAfter = &t
}
if updatedBefore != "" {
t, err := parseTimeFlag(updatedBefore)
if err != nil {
return HandleErrorRespectJSON("parsing --updated-before: %v", err)
}
filter.UpdatedBefore = &t
}
if closedAfter != "" {
t, err := parseTimeFlag(closedAfter)
if err != nil {
return HandleErrorRespectJSON("parsing --closed-after: %v", err)
}
filter.ClosedAfter = &t
}
if closedBefore != "" {
t, err := parseTimeFlag(closedBefore)
if err != nil {
return HandleErrorRespectJSON("parsing --closed-before: %v", err)
}
filter.ClosedBefore = &t
}
if cmd.Flags().Changed("priority-min") {
priorityMin, err := validation.ValidatePriority(priorityMinStr)
if err != nil {
return HandleErrorRespectJSON("parsing --priority-min: %v", err)
}
filter.PriorityMin = &priorityMin
}
if cmd.Flags().Changed("priority-max") {
priorityMax, err := validation.ValidatePriority(priorityMaxStr)
if err != nil {
return HandleErrorRespectJSON("parsing --priority-max: %v", err)
}
filter.PriorityMax = &priorityMax
}
metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field")
if len(metadataFieldFlags) > 0 {
filter.MetadataFields = make(map[string]string, len(metadataFieldFlags))
for _, mf := range metadataFieldFlags {
k, v, ok := strings.Cut(mf, "=")
if !ok || k == "" {
return HandleErrorRespectJSON("invalid --metadata-field: expected key=value, got %q", mf)
}
if err := storage.ValidateMetadataKey(k); err != nil {
return HandleErrorRespectJSON("invalid --metadata-field key: %v", err)
}
filter.MetadataFields[k] = v
}
}
hasMetadataKey, _ := cmd.Flags().GetString("has-metadata-key")
if hasMetadataKey != "" {
if err := storage.ValidateMetadataKey(hasMetadataKey); err != nil {
return HandleErrorRespectJSON("invalid --has-metadata-key: %v", err)
}
filter.HasMetadataKey = hasMetadataKey
}
uw, err := openProxiedListUOW(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
defer uw.Close(ctx)
if status != "" && status != "all" {
cfg, err := workapi.LoadUOWListConfig(ctx, uw)
if err != nil {
return HandleErrorRespectJSON("loading status configuration: %v", err)
}
if err := workapi.ApplyStatusFilter(&filter, status, cfg.CustomStatusNames()); err != nil {
return HandleErrorRespectJSON("%v", err)
}
}
if jsonOutput {
page, err := uw.IssueUseCase().SearchIssuesWithCounts(ctx, query, filter)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
items := page.Items
workapi.SortIssuesWithCounts(items, sortBy, reverse)
if items == nil {
items = []*types.IssueWithCounts{}
}
return outputJSON(items)
}
page, err := uw.IssueUseCase().SearchIssues(ctx, query, filter)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
issues := page.Items
workapi.SortIssues(issues, sortBy, reverse)
outputSearchResults(issues, query, longFormat)
return nil
}

View file

@ -0,0 +1,30 @@
//go:build cgo
package main
import (
"os"
"testing"
)
// TestEmbeddedSearchRoutesAgree is the direct route of the `bd search` route
// agreement (search_routes_parity_test.go): an embedded workspace answers
// every flag set as searchRouteQueries expects.
// TestProxiedServerSearchRoutesAgree holds the proxied and remote routes to
// the same answers.
func TestEmbeddedSearchRoutesAgree(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "sp")
seedSearchRoutes(searchRouteOps{
create: func(title string, args []string) string {
return bdCreate(t, bd, dir, append([]string{title}, args...)...).ID
},
close: func(id string) { bdClose(t, bd, dir, id) },
markTemplate: func(id string) { markIssueTemplate(t, beadsDir, "sp", id) },
promote: func(id string) { bdPromote(t, bd, dir, id) },
})
checkSearchRoute(t, "direct", bd, dir, bdEnv(dir), false)
}

View file

@ -0,0 +1,232 @@
//go:build cgo
package main
import (
"encoding/json"
"os/exec"
"slices"
"strings"
"testing"
)
// The `bd search` route agreement. Every route (the direct store, the proxied
// server and a remote backend) builds ONE request (searchListRequest over
// issueops.SearchListRequest) and asks ONE library entry with it
// (issueops.Reader.List), so the same seed must answer the same flags the same
// way on all of them. A route that mapped a flag on its own, or reached a
// different read, would answer differently.
//
// The routes run in two lanes: TestEmbeddedSearchRoutesAgree (the direct
// route, embedded lane) and TestProxiedServerSearchRoutesAgree (the proxied
// and remote routes, proxied lane). Neither lane can run the other's
// workspace, so both hold their answers to the same expectation,
// searchRouteQueries' want, through checkSearchRoute. Agreeing with it on
// every route is agreeing with each other.
// searchRouteSeed is one row of the seed every route gets. Distinct priorities
// among the "routed" rows make a --limit cut the same rows on every route
// regardless of creation-time ties.
//
// The "kinded" rows are one of each kind of row a listing hides by default and
// search's scope takes back (issueops.SearchListRequest): a template, a gate,
// an infra-typed wisp and a durable row of the same infra type. They match a
// word of their own rather than "routed", so the ordered queries below still
// see one row per priority.
type searchRouteSeed struct {
title string
args []string
then searchRouteStep
}
// searchRouteStep is what a route does to a seed row once it has created it.
type searchRouteStep int
const (
srAsCreated searchRouteStep = iota
srClose
srMarkTemplate // no create flag makes a template, so this is raw SQL
srPromote // out of the ephemeral plane creating an infra type puts it in
)
var searchRouteSeeds = []searchRouteSeed{
{"Routed alpha task", []string{"--type", "task", "--priority", "0", "--assignee", "alice", "--label", "lane:a"}, srAsCreated},
{"Routed beta bug", []string{"--type", "bug", "--priority", "1", "--assignee", "bob", "--label", "lane:b"}, srAsCreated},
{"re-ROUTED gamma", []string{"--type", "feature", "--priority", "2", "--label", "lane:a"}, srAsCreated},
{"Routed and done", []string{"--type", "task", "--priority", "3"}, srClose},
{"unrelated delta", []string{"--type", "task", "--priority", "4", "--label", "lane:a"}, srAsCreated},
{"Kinded template", []string{"--type", "task"}, srMarkTemplate},
{"Kinded gate", []string{"--type", "gate"}, srAsCreated},
{"Kinded wisp message", []string{"--type", "message"}, srAsCreated},
{"Kinded promoted message", []string{"--type", "message"}, srPromote},
}
const (
srAlpha = "Routed alpha task|open"
srBeta = "Routed beta bug|open"
srGamma = "re-ROUTED gamma|open"
srDone = "Routed and done|closed"
skTemplate = "Kinded template|open"
skGate = "Kinded gate|open"
skWisp = "Kinded wisp message|open"
skPromoted = "Kinded promoted message|open"
)
// searchRouteQuery is one flag set. want is the seed's answer as title|status:
// in output order when ordered, otherwise as a set.
type searchRouteQuery struct {
name string
args []string
ordered bool // the flags fix the output order
wireCan bool // listIssues can carry every flag
want []string
}
var searchRouteQueries = []searchRouteQuery{
{"text", []string{"routed"}, false, true, []string{srAlpha, srBeta, srGamma, srDone}},
{"status open", []string{"routed", "--status", "open"}, false, true, []string{srAlpha, srBeta, srGamma}},
{"status all", []string{"routed", "--status", "all"}, false, true, []string{srAlpha, srBeta, srGamma, srDone}},
{"type", []string{"routed", "--type", "bug"}, false, true, []string{srBeta}},
{"label", []string{"routed", "--label", "lane:a"}, false, true, []string{srAlpha, srGamma}},
{"assignee", []string{"routed", "--assignee", "alice"}, false, true, []string{srAlpha}},
// The store's default order is priority first, so the cut keeps P0 and P1.
{"limit", []string{"routed", "--limit", "2"}, false, true, []string{srAlpha, srBeta}},
// The title sort is case-insensitive (workapi.SortIssues).
{"sort title", []string{"routed", "--sort", "title"}, true, true, []string{srGamma, srAlpha, srDone, srBeta}},
{"sort priority reverse", []string{"routed", "--sort", "priority", "--reverse"}, true, true, []string{srDone, srGamma, srBeta, srAlpha}},
{"query flag", []string{"--query", "gamma"}, false, true, []string{srGamma}},
{"no match", []string{"nothing-matches-this"}, false, true, nil},
{"priority-max", []string{"routed", "--priority-max", "1"}, false, false, []string{srAlpha, srBeta}},
// --type is expanded as `bd list` expands it before the Reader validates it.
{"type alias", []string{"routed", "--type", "feat"}, false, true, []string{srGamma}},
// Every kind of row comes back under no flag and under its own --type. An
// infra type is the one that also narrows a listing to its ephemeral rows;
// search's scope keeps the durable row of that type beside the wisp.
{"every kind of row", []string{"kinded"}, false, true, []string{skTemplate, skGate, skWisp, skPromoted}},
{"type message keeps both planes", []string{"kinded", "--type", "message"}, false, true, []string{skWisp, skPromoted}},
{"type gate", []string{"kinded", "--type", "gate"}, false, true, []string{skGate}},
{"type task keeps the template", []string{"kinded", "--type", "task"}, false, true, []string{skTemplate}},
}
// searchRouteRefusals are flag sets every route must refuse, naming the value
// it refused, rather than answer with an empty result.
var searchRouteRefusals = []struct {
name string
args []string
value string
}{
{"unknown type", []string{"routed", "--type", "no-such-type"}, "no-such-type"},
}
type searchRouteRow struct{ ID, Title, Status string }
// searchRouteOps is how one route writes the seed.
type searchRouteOps struct {
create func(title string, args []string) string
close func(id string)
markTemplate func(id string)
promote func(id string)
}
// seedSearchRoutes creates searchRouteSeeds through one route's writes.
func seedSearchRoutes(ops searchRouteOps) {
for _, s := range searchRouteSeeds {
id := ops.create(s.title, s.args)
switch s.then {
case srClose:
ops.close(id)
case srMarkTemplate:
ops.markTemplate(id)
case srPromote:
ops.promote(id)
}
}
}
// runSearchRoute runs `bd search --json args...` in dir and returns its
// stdout, stderr and exit code.
func runSearchRoute(t *testing.T, bd, dir string, env []string, args ...string) (string, string, int) {
t.Helper()
cmd := exec.Command(bd, append([]string{"search", "--json"}, args...)...)
cmd.Dir = dir
cmd.Env = env
stdout, stderr, err := runCommandBuffers(t, cmd)
code := 0
if err != nil {
ee, ok := err.(*exec.ExitError)
if !ok {
t.Fatalf("running bd search: %v", err)
}
code = ee.ExitCode()
}
return stdout.String(), stderr.String(), code
}
func decodeSearchRoute(t *testing.T, out string) []searchRouteRow {
t.Helper()
s := strings.TrimSpace(out)
start := strings.Index(s, "[")
if start < 0 {
return nil
}
var rows []searchRouteRow
if err := json.Unmarshal([]byte(s[start:]), &rows); err != nil {
t.Fatalf("parse search JSON: %v\n%s", err, s)
}
return rows
}
// searchRouteComparable projects rows onto what two databases with the same
// seed share (title and status, not ids); an unordered answer is a sorted set.
func searchRouteComparable(rows []searchRouteRow, ordered bool) []string {
out := make([]string, 0, len(rows))
for _, r := range rows {
out = append(out, r.Title+"|"+r.Status)
}
if !ordered {
slices.Sort(out)
}
return out
}
// checkSearchRoute runs every query on one route and holds each answer to its
// want. A query listIssues cannot carry (wireCan false) must refuse on a
// remote route rather than answer without the flag, and every refusal must
// refuse on every route. It returns the decoded answers by query name, for a
// route that is compared row for row with another one over the same database.
func checkSearchRoute(t *testing.T, route, bd, dir string, env []string, remote bool) map[string][]searchRouteRow {
t.Helper()
answers := map[string][]searchRouteRow{}
for _, q := range searchRouteQueries {
stdout, stderr, code := runSearchRoute(t, bd, dir, env, q.args...)
if remote && !q.wireCan {
if code == 0 {
t.Errorf("%s: %s bd search %v succeeded; listIssues cannot carry it, so it must refuse", q.name, route, q.args)
}
continue
}
if code != 0 {
t.Errorf("%s: %s bd search %v failed (exit %d): %s", q.name, route, q.args, code, stderr)
continue
}
rows := decodeSearchRoute(t, stdout)
answers[q.name] = rows
want := slices.Clone(q.want)
if !q.ordered {
slices.Sort(want)
}
if got := searchRouteComparable(rows, q.ordered); !slices.Equal(got, want) {
t.Errorf("%s: %s bd search %v answered %v, want %v", q.name, route, q.args, got, want)
}
}
for _, r := range searchRouteRefusals {
stdout, stderr, code := runSearchRoute(t, bd, dir, env, r.args...)
if code == 0 {
t.Errorf("%s: %s bd search %v succeeded with %s; it must refuse", r.name, route, r.args, strings.TrimSpace(stdout))
} else if !strings.Contains(stdout+stderr, r.value) {
t.Errorf("%s: %s bd search %v refused (exit %d) without naming %q:\n%s%s", r.name, route, r.args, code, r.value, stdout, stderr)
}
}
return answers
}

View file

@ -0,0 +1,66 @@
//go:build cgo
package main
import (
"os"
"os/exec"
"slices"
"testing"
)
// TestProxiedServerSearchRoutesAgree is the proxied and remote routes of the
// `bd search` route agreement (search_routes_parity_test.go). Both answer every
// flag set as searchRouteQueries expects, the answers
// TestEmbeddedSearchRoutesAgree holds the direct route to. The remote route is
// `bd serve` over the proxied workspace (bd serve needs a SQL server, so it
// cannot serve an embedded one), so it reads the SAME database as the proxied
// route and must answer it row for row, ids and order included.
func TestProxiedServerSearchRoutesAgree(t *testing.T) {
if os.Getenv("BEADS_TEST_PROXIED_SERVER") != "1" {
t.Skip("set BEADS_TEST_PROXIED_SERVER=1 to run proxied server integration tests")
}
bd := buildEmbeddedBD(t)
p := newSharedProxiedProject(t, bd, "sp")
seedSearchRoutes(searchRouteOps{
create: func(title string, args []string) string {
return bdProxiedCreate(t, bd, p.dir, append([]string{title}, args...)...).ID
},
close: func(id string) { bdProxiedClose(t, bd, p.dir, id) },
markTemplate: func(id string) {
res, err := openProxiedDB(t, p).Exec("UPDATE issues SET is_template = 1 WHERE id = ?", id)
if err != nil {
t.Fatalf("mark %s a template: %v", id, err)
}
if n, err := res.RowsAffected(); err != nil || n != 1 {
t.Fatalf("mark %s a template: %d rows affected (err %v), want 1", id, n, err)
}
},
promote: func(id string) {
if out, err := bdProxiedRun(t, bd, p.dir, "promote", id); err != nil {
t.Fatalf("bd promote %s: %v\n%s", id, err, out)
}
},
})
proxied := checkSearchRoute(t, "proxied", bd, p.dir, bdProxiedEnv(p.dir), false)
sp := startServe(t, bd, p.dir, bdProxiedEnv(p.dir))
remoteDir := t.TempDir()
connect := exec.Command(bd, "connect", "http://"+sp.addr, "--json")
connect.Dir = remoteDir
connect.Env = bdEnv(remoteDir)
if out, err := connect.CombinedOutput(); err != nil {
t.Fatalf("bd connect: %v\n%s", err, out)
}
remote := checkSearchRoute(t, "remote", bd, remoteDir, bdEnv(remoteDir), true)
for _, q := range searchRouteQueries {
got, gotOK := remote[q.name]
want, wantOK := proxied[q.name]
if !gotOK || !wantOK {
continue // refused or failed on a route: reported above
}
if !slices.Equal(got, want) {
t.Errorf("%s: remote answered %+v, proxied answered %+v", q.name, got, want)
}
}
}

View file

@ -81,7 +81,10 @@ var showCmd = &cobra.Command{
if len(args) > 0 {
return HandleErrorRespectJSON("--current cannot be combined with explicit issue IDs")
}
currentID := resolveCurrentIssueID(ctx)
currentID, err := resolveCurrentIssueID(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if currentID == "" {
return HandleErrorRespectJSON("no current issue found (no in-progress, hooked, or recently touched issues)")
}

52
cmd/bd/show_current.go Normal file
View file

@ -0,0 +1,52 @@
package main
import (
"context"
"fmt"
"github.com/steveyegge/beads/issueops"
)
// resolveCurrentIssueID determines the current active issue for the agent.
// Priority: in-progress assigned to actor > hooked > last touched.
//
// The lookup is the library's (issueops.FindCurrentIssue, over the Querier
// role every backend serves: queryIssues on a remote one), and both routes ask
// it: the direct route with store.Querier(), the proxied route with the
// provider's. What stays here is CLI policy: who the actor is, and the
// last-touched fallback, which is a file in this workspace.
//
// A failed read is an error. The fallback answers "nothing is in progress",
// and only reads that answered may say so: taking the http backend's refusal
// for a miss is what printed the wrong issue with exit 0.
func resolveCurrentIssueID(ctx context.Context) (string, error) {
var querier issueops.Querier
if usesProxiedServer() {
q, err := proxiedQuerier()
if err != nil {
return "", fmt.Errorf("finding the current issue: %w", err)
}
querier = q
} else if store != nil {
q, err := store.Querier()
if err != nil {
return "", fmt.Errorf("finding the current issue: %w", err)
}
querier = q
}
return resolveCurrentIssueIDFrom(ctx, querier, getActorWithGit, GetLastTouchedID)
}
func resolveCurrentIssueIDFrom(ctx context.Context, querier issueops.Querier, currentActor func() string, fallback func() string) (string, error) {
if querier == nil {
return fallback(), nil
}
id, err := issueops.FindCurrentIssue(ctx, querier, currentActor())
if err != nil {
return "", err
}
if id == "" {
return fallback(), nil
}
return id, nil
}

View file

@ -3,140 +3,66 @@ package main
import (
"context"
"errors"
"reflect"
"testing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
type currentIssueSearchCall struct {
query string
filter types.IssueFilter
type fixedQuerier struct {
ids []string
err error
n int
}
type currentIssueSearchResponse struct {
issues []*types.Issue
err error
func (q *fixedQuerier) Query(context.Context, issueops.QueryRequest) (issueops.IssuePage, error) {
q.n++
if q.err != nil {
return issueops.IssuePage{}, q.err
}
items := make([]*types.IssueWithCounts, 0, len(q.ids))
for _, id := range q.ids {
items = append(items, &types.IssueWithCounts{Issue: &types.Issue{ID: id}})
}
return issueops.IssuePage{Items: items}, nil
}
type currentIssueSearchRecorder struct {
responses []currentIssueSearchResponse
calls []currentIssueSearchCall
}
// The lookup itself is issueops.FindCurrentIssue's (issueops/current_test.go).
// What the CLI owns is the fallback: last-touched answers only a lookup that
// answered and found nothing, never a failed one.
func (r *currentIssueSearchRecorder) SearchIssues(_ context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) {
r.calls = append(r.calls, currentIssueSearchCall{query: query, filter: filter})
response := r.responses[len(r.calls)-1]
return response.issues, response.err
}
func TestResolveCurrentIssueIDFromInProgressShortCircuits(t *testing.T) {
searcher := &currentIssueSearchRecorder{
responses: []currentIssueSearchResponse{{
issues: []*types.Issue{{ID: "in-progress-first"}, {ID: "in-progress-second"}},
}},
}
actorCalls := 0
got := resolveCurrentIssueIDFrom(context.Background(), searcher, func() string {
actorCalls++
return "tester"
}, func() string {
t.Fatal("fallback called after in-progress result")
return ""
})
if got != "in-progress-first" {
t.Fatalf("resolveCurrentIssueIDFrom() = %q, want %q", got, "in-progress-first")
}
if actorCalls != 1 {
t.Fatalf("actor calls = %d, want 1", actorCalls)
}
assertCurrentIssueSearchCalls(t, searcher.calls, "tester", types.StatusInProgress)
}
func TestResolveCurrentIssueIDFromFindsHookedAfterInProgressMiss(t *testing.T) {
searcher := &currentIssueSearchRecorder{
responses: []currentIssueSearchResponse{
{err: errors.New("in-progress search failed")},
{issues: []*types.Issue{{ID: "hooked"}}},
},
}
got := resolveCurrentIssueIDFrom(context.Background(), searcher, func() string {
return "tester"
}, func() string {
t.Fatal("fallback called after hooked result")
return ""
})
if got != "hooked" {
t.Fatalf("resolveCurrentIssueIDFrom() = %q, want %q", got, "hooked")
}
assertCurrentIssueSearchCalls(t, searcher.calls, "tester", types.StatusInProgress, types.StatusHooked)
}
func TestResolveCurrentIssueIDFromFallsBackAfterTwoMisses(t *testing.T) {
searcher := &currentIssueSearchRecorder{
responses: []currentIssueSearchResponse{{}, {}},
}
fallbackCalls := 0
got := resolveCurrentIssueIDFrom(context.Background(), searcher, func() string {
return "tester"
}, func() string {
fallbackCalls++
return "last-touched"
})
if got != "last-touched" {
t.Fatalf("resolveCurrentIssueIDFrom() = %q, want %q", got, "last-touched")
}
if fallbackCalls != 1 {
t.Fatalf("fallback calls = %d, want 1", fallbackCalls)
}
assertCurrentIssueSearchCalls(t, searcher.calls, "tester", types.StatusInProgress, types.StatusHooked)
}
func TestResolveCurrentIssueIDFromNilSearcherUsesFallback(t *testing.T) {
actorCalls := 0
fallbackCalls := 0
got := resolveCurrentIssueIDFrom(context.Background(), nil, func() string {
actorCalls++
return "tester"
}, func() string {
fallbackCalls++
return "last-touched"
})
if got != "last-touched" {
t.Fatalf("resolveCurrentIssueIDFrom() = %q, want %q", got, "last-touched")
}
if actorCalls != 0 {
t.Fatalf("actor calls = %d, want 0", actorCalls)
}
if fallbackCalls != 1 {
t.Fatalf("fallback calls = %d, want 1", fallbackCalls)
func TestResolveCurrentIssueIDFromUsesTheLookupBeforeTheFallback(t *testing.T) {
got, err := resolveCurrentIssueIDFrom(context.Background(), &fixedQuerier{ids: []string{"in-progress"}},
func() string { return "tester" },
func() string { t.Fatal("fallback called after a found issue"); return "" })
if err != nil || got != "in-progress" {
t.Fatalf("got (%q, %v), want (in-progress, nil)", got, err)
}
}
func assertCurrentIssueSearchCalls(t *testing.T, got []currentIssueSearchCall, actor string, statuses ...types.Status) {
t.Helper()
func TestResolveCurrentIssueIDFromFallsBackOnlyOnAMiss(t *testing.T) {
got, err := resolveCurrentIssueIDFrom(context.Background(), &fixedQuerier{},
func() string { return "tester" }, func() string { return "last-touched" })
if err != nil || got != "last-touched" {
t.Fatalf("got (%q, %v), want (last-touched, nil)", got, err)
}
}
want := make([]currentIssueSearchCall, 0, len(statuses))
for _, status := range statuses {
status := status
want = append(want, currentIssueSearchCall{
query: "",
filter: types.IssueFilter{
Status: &status,
Assignee: &actor,
},
})
func TestResolveCurrentIssueIDFromNeverFallsBackOnAFailure(t *testing.T) {
refusal := errors.New("not supported over HTTP")
got, err := resolveCurrentIssueIDFrom(context.Background(), &fixedQuerier{err: refusal},
func() string { return "tester" },
func() string { t.Fatal("fallback called after a failed read"); return "" })
if !errors.Is(err, refusal) || got != "" {
t.Fatalf("got (%q, %v), want (\"\", an error wrapping the refusal)", got, err)
}
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("SearchIssues calls = %#v, want %#v", got, want)
func TestResolveCurrentIssueIDFromNilQuerierUsesFallback(t *testing.T) {
got, err := resolveCurrentIssueIDFrom(context.Background(), nil,
func() string { t.Fatal("actor resolved without a querier"); return "" },
func() string { return "last-touched" })
if err != nil || got != "last-touched" {
t.Fatalf("got (%q, %v), want (last-touched, nil)", got, err)
}
}

View file

@ -100,13 +100,14 @@ func runShowProxiedServer(cmd *cobra.Command, ctx context.Context, args []string
return err
}
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
// Resolved BEFORE the unit of work opens: --current reads through the
// provider's Querier role, which runs its own read.
if err := resolveShowProxiedIDs(ctx, in); err != nil {
return err
}
if err := resolveShowProxiedIDs(ctx, uw, in); err != nil {
uw.Close(ctx)
uw, err := proxiedOpenReadUOW(ctx)
if err != nil {
return err
}
@ -140,12 +141,15 @@ func runShowProxiedServer(cmd *cobra.Command, ctx context.Context, args []string
// resolveShowProxiedIDs turns --current into an explicit id and rejects an
// empty id list, the same checks the direct route makes before dispatching.
func resolveShowProxiedIDs(ctx context.Context, uw uow.UnitOfWork, in *showProxiedInput) error {
func resolveShowProxiedIDs(ctx context.Context, in *showProxiedInput) error {
if in.currentMode {
if len(in.ids) > 0 {
return HandleErrorRespectJSON("--current cannot be combined with explicit issue IDs")
}
currentID := resolveCurrentIssueIDProxied(ctx, uw)
currentID, err := resolveCurrentIssueID(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if currentID == "" {
return HandleErrorRespectJSON("no current issue found (no in-progress, hooked, or recently touched issues)")
}

View file

@ -1101,7 +1101,7 @@ type ContextResponse struct {
// OPTIONAL, and absent means only that this server does not disclose its filesystem layout — never that it has no workspace. A client MUST NOT require it, MUST NOT treat absence as an error, and has no use for the value beyond display: it is a path on the SERVER's filesystem, which the client cannot open. Identify the workspace by `project_id` and `database`, which are required.
BeadsDir *string `json:"beads_dir,omitempty"`
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`, `issues.advanceMolecule`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, and `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0, and `issues.close.autoCloseMolecule`, which announces that `POST /v0/beads/issues/{id}:close` and `POST /v0/beads/issues:batchClose` accept `auto_close_molecule` and answer `auto_closed_molecule` and `molecule_auto_close_refusal` rather than a `400` naming the member unknown. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external:<project>:<capability>` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`, `issues.advanceMolecule`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0, and `issues.close.autoCloseMolecule`, which announces that `POST /v0/beads/issues/{id}:close` and `POST /v0/beads/issues:batchClose` accept `auto_close_molecule` and answer `auto_closed_molecule` and `molecule_auto_close_refusal` rather than a `400` naming the member unknown, and `issues.list.search`, which announces that `GET /v0/beads/issues` accepts `q`, `bd search`'s free text (see that parameter), rather than silently answering `unknown_parameter`. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external:<project>:<capability>` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
//
// THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL, apart from the conditional `policy.external_dependencies` above, which depends on how this server composed its roles rather than on the build. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive.
Capabilities []string `json:"capabilities"`
@ -2396,6 +2396,8 @@ type ListIssuesParams struct {
// IncludeEphemeral Include the ephemeral tier — ephemeral rows and the non-synced rows stored beside them — merged into the same order as the durable ones, whichever order `sort` named.
//
// It admits a TIER and takes no TYPE exclusion off, so a row whose type this operation already hides stays hidden. That includes the configured infrastructure types: ephemeral `agent`, `role` and `message` rows need `include_infra` as well as, or instead of, this one. What `include_ephemeral` alone reaches is the ephemeral rows of the types a listing already shows.
//
// A `type` this workspace calls infra is the one NARROWING it lifts. Such a type on its own reads only that type's ephemeral rows, which is where creating one puts it; with `include_ephemeral` the type's durable rows (a promoted wisp, an issue retyped after it was created) are listed as well. `include_infra` alone keeps the narrowing.
IncludeEphemeral *bool `form:"include_ephemeral,omitempty" json:"include_ephemeral,omitempty"`
// CreatedBefore Only issues created strictly before this instant (RFC 3339).
@ -2410,6 +2412,11 @@ type ListIssuesParams struct {
// HasMetadataKey Only issues carrying this top-level metadata key.
HasMetadataKey *string `form:"has_metadata_key,omitempty" json:"has_metadata_key,omitempty"`
// Q `bd search`'s free text. A row matches when its title or its id contains the text, case-insensitively; a text shaped like an issue id also matches that exact id, an id prefix, and the external reference. It narrows the listing and lifts none of its default exclusions, so a caller that wants `bd search`'s every-status, every-kind answer also sends `all`, `include_templates`, `include_gates`, `include_infra` and `include_ephemeral`.
//
// Behind the `issues.list.search` behavior token: an older server answers `unknown_parameter` for this name. A client with the handshake's capabilities cached refuses a search locally against a server that does not advertise the token, rather than paying for that round trip.
Q *string `form:"q,omitempty" json:"q,omitempty"`
// Sort Which of the two served total orders this page is in. `created` is `(created_at DESC, id ASC)`; `priority` is `(priority ASC, created_at DESC, id ASC)` — `bd list`'s flagless ordering, and the order `bd list --sort priority` produces.
//
// THE DEFAULT IS `created` AND WILL NOT CHANGE. It is what this operation served before this parameter existed, so moving it would alter which rows a truncated page contains for every client written against that behavior, with no error to notice it by.
@ -2547,7 +2554,7 @@ type CountIssuesParams struct {
// Type One issue type, with `status`'s match-nothing-rather-than-fail treatment and NO shorthand alias expansion at all — unlike `GET /v0/beads/ready`'s `type`, which expands aliases.
//
// It has a SECOND effect under `include_infra`: a type this workspace calls infra routes the count to the ephemeral tier. See that parameter.
// It has a SECOND effect under `include_infra`: a type this workspace calls infra routes the count to the ephemeral tier, unless `include_ephemeral` is also set. See that parameter.
Type *string `form:"type,omitempty" json:"type,omitempty"`
// Assignee Only issues assigned to this actor. Sending it beside `no_assignee` is not refused: the two are handed to the filter as written and answer with the empty intersection, which is `0`.
@ -2616,6 +2623,8 @@ type CountIssuesParams struct {
// IncludeEphemeral Admit the EPHEMERAL PLANE — the wisps table — and nothing else. Exactly the first of `include_infra`'s four changes, with none of the other three: no type exclusion is taken off, so a row whose TYPE a default count already excludes stays excluded.
//
// It exists because there was no way to ask for that one thing. The write path routes on STORAGE CLASS, not type, so a `no_history` bead lives in the wisps table while remaining ordinary durable work. Reaching it needed `include_infra`, which also drops template rows of the named type — one silent undercount traded for another.
//
// Beside `include_infra` it also lifts the fourth change's routing of an infra `type`, so that type's durable rows are counted along with its ephemeral ones rather than instead of them.
IncludeEphemeral *bool `form:"include_ephemeral,omitempty" json:"include_ephemeral,omitempty"`
// HasMetadataKey Only issues carrying this top-level metadata key.
@ -2623,7 +2632,7 @@ type CountIssuesParams struct {
// IncludeInfra Count the cardinality of `bd list --include-infra --all` instead of the durable plane. IT CHANGES FOUR THINGS AT ONCE, and they are listed rather than summarized because a caller reading "include infra" would expect one:
//
// the ephemeral wisps tier is MERGED IN, picking up both wisps and the `no_history` beads that are durable work stored in that tier; template molecules are EXCLUDED, which a default count includes; gate beads are EXCLUDED unless `type=gate` asks for them by name; and a `type` this workspace calls infra ROUTES the count to the ephemeral tier instead of the durable one.
// the ephemeral wisps tier is MERGED IN, picking up both wisps and the `no_history` beads that are durable work stored in that tier; template molecules are EXCLUDED, which a default count includes; gate beads are EXCLUDED unless `type=gate` asks for them by name; and a `type` this workspace calls infra ROUTES the count to the ephemeral tier instead of the durable one — unless `include_ephemeral` is also set, which keeps the durable tier as well, as `GET /v0/beads/issues` does.
//
// The infra vocabulary is the WORKSPACE's, read from its configuration inside the role. A caller does not supply it and cannot — that config load is what this role exists to keep off both front doors.
//

View file

@ -375,6 +375,9 @@ func (s *Server) handleListIssues(w http.ResponseWriter, r *http.Request) {
MetadataFields: q.metadataFields("metadata_field"),
HasMetadataKey: q.str("has_metadata_key"),
// `bd search`'s text, behind issues.list.search (CapIssuesListSearch).
Query: q.str("q"),
Limit: q.limit(),
}

View file

@ -23,7 +23,10 @@ type recordingIssues struct {
mu sync.Mutex
ready []types.WorkFilter
search []types.IssueFilter
items []*types.IssueWithCounts
// queries is the free-text argument of each SearchIssuesWithCounts call,
// index-aligned with search.
queries []string
items []*types.IssueWithCounts
}
func (f *recordingIssues) GetReadyWorkWithCounts(_ context.Context, filter types.WorkFilter) (domain.SearchCountsPage, error) {
@ -33,9 +36,10 @@ func (f *recordingIssues) GetReadyWorkWithCounts(_ context.Context, filter types
return domain.SearchCountsPage{Items: f.items}, nil
}
func (f *recordingIssues) SearchIssuesWithCounts(_ context.Context, _ string, filter types.IssueFilter) (domain.SearchCountsPage, error) {
func (f *recordingIssues) SearchIssuesWithCounts(_ context.Context, query string, filter types.IssueFilter) (domain.SearchCountsPage, error) {
f.mu.Lock()
f.search = append(f.search, filter)
f.queries = append(f.queries, query)
f.mu.Unlock()
return domain.SearchCountsPage{Items: f.items}, nil
}
@ -52,6 +56,12 @@ func (f *recordingIssues) readyFilters() []types.WorkFilter {
return append([]types.WorkFilter(nil), f.ready...)
}
func (f *recordingIssues) searchQueries() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.queries...)
}
func (f *recordingIssues) searchFilters() []types.IssueFilter {
f.mu.Lock()
defer f.mu.Unlock()
@ -434,6 +444,33 @@ func TestListForwardsTheEphemeralPlaneParameter(t *testing.T) {
}
}
// TestListForwardsTheSearchText is the handler half of ListRequest.Query
// (issues.list.search): `q` reaches the storage seam as SearchIssues' free-text
// argument — not as TitleSearch, which matches titles only — and its absence
// sends no text at all.
func TestListForwardsTheSearchText(t *testing.T) {
for _, tc := range []struct {
name, path, want string
}{
{"absent sends no text", "/v0/beads/issues", ""},
{"q is the search text", "/v0/beads/issues?q=login+bug&all=true", "login bug"},
} {
t.Run(tc.name, func(t *testing.T) {
ts, rec := newReadServer(t, Config{})
if resp := ts.get(t, tc.path); resp.StatusCode != http.StatusOK {
t.Fatalf("GET %s: status = %d, want 200", tc.path, resp.StatusCode)
}
queries := rec.searchQueries()
if len(queries) != 1 || queries[0] != tc.want {
t.Fatalf("search texts = %q, want [%q]", queries, tc.want)
}
if f := rec.searchFilters()[0]; f.TitleSearch != "" || f.TitleContains != "" {
t.Errorf("q leaked into a title-only filter: TitleSearch=%q TitleContains=%q", f.TitleSearch, f.TitleContains)
}
})
}
}
// TestTheEphemeralPlaneParameterIsTheSkewSignal pins the version-skew half.
//
// A client that sends `include_ephemeral` to a server built before this

View file

@ -119,6 +119,19 @@ const CapIssuesListSort = "issues.list.sort"
// count.
const CapIssuesCountScope = "issues.count.scope"
// CapIssuesListSearch is the behavior capability that advertises GET
// /v0/beads/issues' `q` parameter (reads.go, spec `q` on OpListIssues):
// `bd search`'s free text, carried as issueops.ListRequest.Query. Like
// CapIssuesListSort it names a PARAMETER added to an existing operation, so it
// rides behaviorCapabilities, and it is the token the parameter's OpenAPI
// description cites for TestNewParameterOnExistingOperationHasABehaviorToken.
//
// The client (internal/httpclient) refuses a search locally against a server
// that does not advertise it, with ErrUnsupported naming the token, so a
// search is never sent to a server that would answer `unknown_parameter` and
// is never widened into an unsearched listing.
const CapIssuesListSearch = "issues.list.search"
// CapIssuesSweepWispsPlane is the behavior capability that advertises the
// `wisps-plane` value of SweepRequest.tier (sweep.go, spec SweepRequest.tier):
// a third, wider tier that clears the whole wisps table plus any durable bead
@ -986,7 +999,7 @@ var behaviorCapabilities = []string{
CapProjectEnforce, CapBatchApplyLarge, CapIssuesListSort, CapIssuesCountScope,
CapIssuesSweepWispsPlane, CapIssuesSweepLiveDependents, CapIssuesSweepLimit,
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority,
CapIssuesCloseAutoCloseMolecule,
CapIssuesCloseAutoCloseMolecule, CapIssuesListSearch,
}
// Capabilities lists what this build advertises in ContextResponse.capabilities:

View file

@ -638,7 +638,7 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
want = append(want, "project.enforce", "issues.batchApplyLarge", "issues.list.sort", "issues.count.scope",
"issues.sweep.wispsPlane", "issues.sweep.liveDependents", "issues.sweep.limit",
"issues.batchApply.depAddLineage", "issues.update.allowTemplate", "issues.create.defaultPriority",
"issues.close.autoCloseMolecule")
"issues.close.autoCloseMolecule", "issues.list.search")
slices.Sort(want)
if !slices.Equal(got, want) {
t.Errorf("capabilities = %v, want %v", got, want)

View file

@ -1260,6 +1260,14 @@ paths:
`message` rows need `include_infra` as well as, or instead of,
this one. What `include_ephemeral` alone reaches is the ephemeral
rows of the types a listing already shows.
A `type` this workspace calls infra is the one NARROWING it lifts.
Such a type on its own reads only that type's ephemeral rows, which
is where creating one puts it; with `include_ephemeral` the type's
durable rows (a promoted wisp, an issue retyped after it was
created) are listed as well. `include_infra` alone keeps the
narrowing.
schema:
type: boolean
default: false
@ -1291,6 +1299,25 @@ paths:
description: Only issues carrying this top-level metadata key.
schema:
type: string
- name: q
in: query
description: >-
`bd search`'s free text. A row matches when its title or its id
contains the text, case-insensitively; a text shaped like an issue
id also matches that exact id, an id prefix, and the external
reference. It narrows the listing and lifts none of its default
exclusions, so a caller that wants `bd search`'s every-status,
every-kind answer also sends `all`, `include_templates`,
`include_gates`, `include_infra` and `include_ephemeral`.
Behind the `issues.list.search` behavior token: an older server
answers `unknown_parameter` for this name. A client with the
handshake's capabilities cached refuses a search locally against a
server that does not advertise the token, rather than paying for
that round trip.
schema:
type: string
- name: sort
in: query
description: >-
@ -1871,8 +1898,8 @@ paths:
It has a SECOND effect under `include_infra`: a type this workspace
calls infra routes the count to the ephemeral tier. See that
parameter.
calls infra routes the count to the ephemeral tier, unless
`include_ephemeral` is also set. See that parameter.
schema:
type: string
- name: assignee
@ -2033,6 +2060,11 @@ paths:
lives in the wisps table while remaining ordinary durable work.
Reaching it needed `include_infra`, which also drops template rows of
the named type — one silent undercount traded for another.
Beside `include_infra` it also lifts the fourth change's routing of
an infra `type`, so that type's durable rows are counted along with
its ephemeral ones rather than instead of them.
schema:
type: boolean
default: false
@ -2055,7 +2087,9 @@ paths:
template molecules are EXCLUDED, which a default count includes;
gate beads are EXCLUDED unless `type=gate` asks for them by name;
and a `type` this workspace calls infra ROUTES the count to the
ephemeral tier instead of the durable one.
ephemeral tier instead of the durable one — unless
`include_ephemeral` is also set, which keeps the durable tier as
well, as `GET /v0/beads/issues` does.
The infra vocabulary is the WORKSPACE's, read from its configuration
@ -8195,7 +8229,7 @@ components:
`skipped.live_dependent` rather than silently answering
`unknown_parameter`, `issues.sweep.limit`, which announces
that it accepts `limit` and answers `remaining` rather than
silently answering `unknown_parameter`, and
silently answering `unknown_parameter`,
`issues.batchApply.depAddLineage`, which announces that a
`dep_add` item on `POST /v0/beads/issues:batchApply` accepts
`has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than
@ -8213,7 +8247,10 @@ components:
`POST /v0/beads/issues:batchClose` accept `auto_close_molecule`
and answer `auto_closed_molecule` and
`molecule_auto_close_refusal` rather than a `400` naming the
member unknown. One behavior token is
member unknown, and `issues.list.search`, which announces that
`GET /v0/beads/issues` accepts `q`, `bd search`'s free text (see
that parameter), rather than silently answering
`unknown_parameter`. One behavior token is
CONDITIONAL rather than build-level: `policy.external_dependencies`
announces that this server's ready, claim, claim-next, close,
blocking and dependency-tree operations already apply bd's

View file

@ -5855,6 +5855,14 @@
"style": "form",
"explode": true
},
{
"schema": "param:listIssues",
"member": "query:q",
"type": "string",
"required": false,
"style": "form",
"explode": true
},
{
"schema": "param:listIssues",
"member": "query:sort",

View file

@ -10,6 +10,7 @@ go_library(
"batchcloser.go",
"batchcreator.go",
"batchgetter.go",
"blocked_recomputer.go",
"bridge.go",
"ca.go",
"ca_permissions_other.go",
@ -116,6 +117,7 @@ go_test(
"insecure_credential_guard_test.go",
"lifecycle_create_test.go",
"lifecycle_update_test.go",
"list_search_test.go",
"list_sort_test.go",
"metadatacas_test.go",
"molecule_test.go",

View file

@ -0,0 +1,12 @@
package httpclient
import "github.com/steveyegge/beads/internal/storage"
// BlockedStateMaintainedByServer satisfies storage.ServerMaintainedBlockedState:
// the server derives and maintains is_blocked (issueops.BlockedStateInvariant's
// local-write clause runs on every write the server commits) and the column
// lives in the server's database, so storage.RecomputeBlocked answers
// storage.BlockedMaintainedByServer for this store and dials nothing.
func (s *Store) BlockedStateMaintainedByServer() bool { return true }
var _ storage.ServerMaintainedBlockedState = (*Store)(nil)

View file

@ -295,6 +295,7 @@ func ListParams(req issueops.ListRequest) (url.Values, error) {
b.list("exclude_label", req.ExcludeLabels)
b.str("parent", req.ParentID)
b.str("q", req.Query)
b.boolean("all", req.AllFlag)
b.boolean("include_templates", req.IncludeTemplates)

View file

@ -212,12 +212,21 @@ func recognizeIntents(f types.IssueFilter, cfg ListConfig) (walkIntents, error)
}
// The same rule for the plane, and it has TWO suppressors rather than one:
// `--include-infra` admits the wisp plane as well as the infra types, and an
// infra `--type` routes to the plane on its own. Either one leaves SkipWisps
// false whatever the ephemeral flag was, so under either of them the pair is
// the same question as the infra intent alone — `--all --no-pinned` and
// `--status all` again — and inventing the second parameter would be a
// distinction the re-derivation cannot see.
if intents.IncludeInfra || cfg.IsInfra(issueType) {
// infra `--type` admits it on its own. Either one leaves SkipWisps false
// whatever the ephemeral flag was, so SkipWisps cannot carry the intent
// under either of them.
//
// Under `--include-infra` alone the pair is the same question as the infra
// intent — `--all --no-pinned` and `--status all` again — and inventing the
// second parameter would be a distinction the re-derivation cannot see. An
// infra `--type` is different: it also narrows the read to that type's
// ephemeral rows, and the ephemeral flag LIFTS that narrowing (so durable
// rows of the type come back too), so there the plane intent leaves its
// trace in Ephemeral instead — present without the flag, absent with it.
switch {
case cfg.IsInfra(issueType):
intents.IncludeEphemeral = f.Ephemeral == nil
case intents.IncludeInfra:
intents.IncludeEphemeral = false
}

View file

@ -127,6 +127,30 @@ func TestTheParentWalkInvertsTheDerivedDefaults(t *testing.T) {
in: textListing(issueops.ListRequest{IncludeEphemeral: true, IncludeInfra: true}),
want: url.Values{"parent": {"bd-root"}, "include_infra": {"true"}},
},
{
// An infra --type admits the plane on its own too, AND narrows the
// read to that type's ephemeral rows, so a bare one is no plane
// intent at all: the server re-derives the narrowing from the type.
name: "an infra --type alone does not invent an ephemeral intent",
in: textListing(issueops.ListRequest{IssueType: "message"}),
want: url.Values{"parent": {"bd-root"}, "type": {"message"}},
},
{
// With an infra --type the ephemeral flag is NOT redundant: it lifts
// the type's ephemeral-only narrowing, so the durable rows of that
// type (a promoted wisp, a retyped issue) come back too. Dropping the
// parameter here would ask the server the narrower question.
name: "--include-ephemeral with an infra --type keeps the plane intent",
in: textListing(issueops.ListRequest{IncludeEphemeral: true, IssueType: "message"}),
want: url.Values{"parent": {"bd-root"}, "type": {"message"}, "include_ephemeral": {"true"}},
},
{
// --include-infra is redundant beside an infra --type whatever the
// ephemeral flag says, so the pair still reads as the flag alone.
name: "--include-ephemeral --include-infra with an infra --type is the same question as --include-ephemeral",
in: textListing(issueops.ListRequest{IncludeEphemeral: true, IncludeInfra: true, IssueType: "message"}),
want: url.Values{"parent": {"bd-root"}, "type": {"message"}, "include_ephemeral": {"true"}},
},
{
name: "an explicit status travels verbatim under its own parameter",
in: textListing(issueops.ListRequest{Status: "in_progress"}),
@ -446,6 +470,8 @@ func TestTheParentWalkRoundTripsThroughTheServerDecoder(t *testing.T) {
{"--include-ephemeral alone", textListing(issueops.ListRequest{IncludeEphemeral: true})},
{"--include-ephemeral --include-infra", textListing(issueops.ListRequest{IncludeEphemeral: true, IncludeInfra: true})},
{"--include-ephemeral with an infra --type", textListing(issueops.ListRequest{IncludeEphemeral: true, IssueType: "agent"})},
{"--include-ephemeral --include-infra with an infra --type", textListing(issueops.ListRequest{IncludeEphemeral: true, IncludeInfra: true, IssueType: "agent"})},
{"--include-infra with an infra --type", textListing(issueops.ListRequest{IncludeInfra: true, IssueType: "agent"})},
{"--include-templates alone", textListing(issueops.ListRequest{IncludeTemplates: true})},
{"an explicit status", textListing(issueops.ListRequest{Status: "in_progress"})},
{"a multi-status filter", textListing(issueops.ListRequest{Status: "open,in_progress"})},

View file

@ -182,6 +182,7 @@ func roundTripCases() []roundTripCase {
ExcludeLabels: []string{"delta", "epsilon"},
ParentID: "bd-epic1",
Query: "login bug",
AllFlag: true,
IncludeTemplates: true,

View file

@ -329,6 +329,10 @@ func listTable() Table {
refused("TitleSearch", "E-ListRequest.TitleSearch"),
refused("SpecPrefix", "E-ListRequest.SpecPrefix"),
refused("IDFilter", "E-ListRequest.IDFilter"),
// Behind issues.list.search: httpReader.List refuses a request
// carrying it, before dialing, unless the handshake advertises the
// token (role_reader.go refuseUnservedSearch).
param("Query", "q"),
param("Labels", "label"),
param("LabelsAny", "label_any"),
param("ExcludeLabels", "exclude_label"),

View file

@ -0,0 +1,67 @@
package httpclient
import (
"errors"
"slices"
"testing"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/issueops"
)
func listRoleWithSnapshot(t *testing.T, w *countingWire, snap *apigen.ContextResponse) issueops.Reader {
t.Helper()
reader, err := New(testTarget(t), w, snap).IssueReader()
if err != nil {
t.Fatalf("IssueReader(): %v", err)
}
return reader
}
// TestListQueryRidesQBehindTheSearchCapability is S26's client half: a
// ListRequest carrying Query reaches listIssues as `q` once the handshake
// advertises issues.list.search.
func TestListQueryRidesQBehindTheSearchCapability(t *testing.T) {
served := &apigen.ContextResponse{Capabilities: []string{"issues.list", wire.CapListSearch}}
w := newCountingWire(`{"items":[],"has_more":false}`)
limit := 10
if _, err := listRoleWithSnapshot(t, w, served).List(t.Context(), issueops.ListRequest{Query: "login bug", Limit: &limit}); err != nil {
t.Fatalf("List: %v", err)
}
if got := w.query(t)["q"]; !slices.Equal(got, []string{"login bug"}) {
t.Errorf("query[q] = %v, want [login bug] (full query: %v)", got, w.query(t))
}
}
// TestListQueryRefusesLocallyWhenTheServerLacksTheSearchCapability is the skew
// side: against a server that does not advertise issues.list.search (the
// deployed reference server, for one), a search refuses BEFORE dialing with
// the typed capability error. Sending it would cost a guaranteed 400
// unknown_parameter; dropping `q` would answer the unsearched listing as the
// search.
func TestListQueryRefusesLocallyWhenTheServerLacksTheSearchCapability(t *testing.T) {
masked := &apigen.ContextResponse{Capabilities: []string{"issues.list", wire.CapListSort}}
w := newCountingWire(`{"items":[],"has_more":false}`)
_, err := listRoleWithSnapshot(t, w, masked).List(t.Context(), issueops.ListRequest{Query: "login bug"})
var unsup *storage.ErrUnsupported
if !errors.As(err, &unsup) {
t.Fatalf("List error = %v, want *storage.ErrUnsupported", err)
}
if unsup.Capability != wire.CapListSearch || unsup.Op != "Reader.List" {
t.Errorf("refusal = {Op: %q, Capability: %q}, want {Reader.List, %s}", unsup.Op, unsup.Capability, wire.CapListSearch)
}
if len(w.dialed) != 0 {
t.Errorf("dialed %d times, want 0: a pre-dial refusal must never reach the wire", len(w.dialed))
}
// A listing without Query is unaffected by the missing token.
limit := 10
if _, err := listRoleWithSnapshot(t, w, masked).List(t.Context(), issueops.ListRequest{Limit: &limit}); err != nil {
t.Fatalf("List without Query against the same server: %v", err)
}
if q := w.query(t); q.Has("q") {
t.Errorf("a listing without Query sent q: %v", q)
}
}

View file

@ -5,6 +5,7 @@ package httpclient
import (
"context"
"net/http"
"slices"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
@ -62,6 +63,9 @@ func (r httpReader) Ready(ctx context.Context, req issueops.ReadyRequest) (issue
// List serves listIssues, through the pager in list_walk.go.
func (r httpReader) List(ctx context.Context, req issueops.ListRequest) (issueops.IssuePage, error) {
if err := r.refuseUnservedSearch(ctx, req); err != nil {
return issueops.IssuePage{}, err
}
params, err := encode.ListParams(req)
if err != nil {
return issueops.IssuePage{}, r.store.inexpressible("Reader.List", err)
@ -69,6 +73,30 @@ func (r httpReader) List(ctx context.Context, req issueops.ListRequest) (issueop
return r.store.walkIssues(ctx, params, req)
}
// refuseUnservedSearch is the pre-dial gate for ListRequest.Query, which rides
// listIssues' `q` only on a server advertising issues.list.search. An older
// server answers `q` with 400 unknown_parameter, so a search against it is
// refused HERE, with the typed capability error naming the token: never a
// round trip that is refused anyway, and never the unsearched listing passed
// off as the search.
//
// listIssues is a baseline operation, so dispatch preflights nothing for it;
// this is the one handshake a search costs, and a request without Query never
// asks for it.
func (r httpReader) refuseUnservedSearch(ctx context.Context, req issueops.ListRequest) error {
if req.Query == "" {
return nil
}
snap, err := r.store.snapshot(ctx)
if err != nil {
return err
}
if snap != nil && slices.Contains(snap.Capabilities, wire.CapListSearch) {
return nil
}
return r.store.unsupportedCapability("Reader.List", wire.CapListSearch)
}
// Get serves getIssue, including the two landed include parameters that retired
// ledger row L4.
//

View file

@ -54,6 +54,7 @@ func servedReaderFixture(t *testing.T, name string) conformance.ReaderFixture {
CreateWisp: c.seedIssue,
AddDependency: c.seedDependency,
AddComment: c.seedComment,
PromoteWisp: c.seedPromotion,
}
}
@ -181,6 +182,13 @@ func TestServedReaderListEmptyPageIsWellFormed(t *testing.T) {
conformance.RunReaderListEmptyPageIsWellFormed(t, t.Context(), servedReaderFixture(t, "rdr"))
}
// TestServedReaderListQueryMatchesTheTitleOrTheID runs the search-text case as
// written: it scopes itself with a label, and Query rides listIssues' `q`
// parameter behind issues.list.search, which this in-process server serves.
func TestServedReaderListQueryMatchesTheTitleOrTheID(t *testing.T) {
conformance.RunReaderListQueryMatchesTheTitleOrTheID(t, t.Context(), servedReaderFixture(t, "rdr"))
}
func TestServedReaderListMaxRowsIsHonored(t *testing.T) {
skipKnownDivergence(t, "E-ListRequest.IDFilter", readParkBead,
"the case scopes itself with IDFilter; the cap it pins is honored over this wire and exercised by "+

View file

@ -312,6 +312,10 @@ func (c *servedComposition) seedComment(ctx context.Context, issueID, author, te
return err
}
func (c *servedComposition) seedPromotion(ctx context.Context, id, actor string) error {
return c.reference.PromoteFromEphemeral(ctx, id, actor)
}
// queryScalar is the composition's raw-row hook: a single-row query against the
// REFERENCE store, which is where the rows a contract seeded actually live.
//

View file

@ -154,6 +154,15 @@ const CapListSort = "issues.list.sort"
// parity gate compares this client's whole vocabulary with the server's.
const CapCountScope = "issues.count.scope"
// CapListSearch is the behavior capability announcing that listIssues honors
// `q`, `bd search`'s free text (issueops.ListRequest.Query), spelled exactly
// as httpapi's CapIssuesListSearch. The Reader's List reads it off the
// handshake snapshot and refuses a request that carries Query LOCALLY, with a
// typed capability error naming this token, when the server does not
// advertise it — so a search never dials a server that would answer
// `unknown_parameter`, and is never widened into the unsearched listing.
const CapListSearch = "issues.list.search"
// CapBatchApplyLarge is the behavior capability announcing that issues.batchApply
// accepts a batch larger than the compiled-in floor (100 items), up to the
// raised ceiling (1000), spelled exactly as httpapi's constant of the same name
@ -382,7 +391,7 @@ var behaviorCapabilities = []string{
CapProjectEnforce, CapBatchApplyLarge, CapListSort, CapCountScope,
CapSweepWispsPlane, CapSweepLiveDependents, CapSweepLimit,
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority,
CapCloseAutoCloseMolecule,
CapCloseAutoCloseMolecule, CapListSearch,
}
// CapabilityFor reports the capability token gating op, and whether op is on

View file

@ -148,6 +148,9 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
if CapListSort != httpapi.CapIssuesListSort {
t.Errorf("CapListSort = %q, server says %q", CapListSort, httpapi.CapIssuesListSort)
}
if CapListSearch != httpapi.CapIssuesListSearch {
t.Errorf("CapListSearch = %q, server says %q", CapListSearch, httpapi.CapIssuesListSearch)
}
if CapCountScope != httpapi.CapIssuesCountScope {
t.Errorf("CapCountScope = %q, server says %q", CapCountScope, httpapi.CapIssuesCountScope)
}
@ -201,11 +204,11 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
httpapi.CapProjectEnforce, httpapi.CapBatchApplyLarge, httpapi.CapIssuesListSort, httpapi.CapIssuesCountScope,
httpapi.CapIssuesSweepWispsPlane, httpapi.CapIssuesSweepLiveDependents, httpapi.CapIssuesSweepLimit,
httpapi.CapBatchApplyDepAddLineage, httpapi.CapIssuesUpdateAllowTemplate, httpapi.CapIssuesCreateDefaultPriority,
httpapi.CapIssuesCloseAutoCloseMolecule,
httpapi.CapIssuesCloseAutoCloseMolecule, httpapi.CapIssuesListSearch,
}) {
t.Errorf("behaviorCapabilities = %v, want the server's project.enforce, issues.batchApplyLarge, issues.list.sort, "+
"issues.count.scope, issues.sweep.wispsPlane, issues.sweep.liveDependents, issues.sweep.limit and "+
"issues.batchApply.depAddLineage, issues.update.allowTemplate, issues.create.defaultPriority and issues.close.autoCloseMolecule tokens", behaviorCapabilities)
"issues.count.scope, issues.sweep.wispsPlane, issues.sweep.liveDependents, issues.sweep.limit, "+
"issues.batchApply.depAddLineage, issues.update.allowTemplate, issues.create.defaultPriority, issues.close.autoCloseMolecule and issues.list.search tokens", behaviorCapabilities)
}
}

View file

@ -8,6 +8,7 @@ go_library(
"batch.go",
"batch_apply.go",
"batch_close_policy.go",
"blocked_recomputer.go",
"bulk_issues.go",
"child_counter_reservation.go",
"compaction.go",
@ -81,6 +82,7 @@ go_test(
srcs = [
"batch_apply_test.go",
"batch_close_policy_test.go",
"blocked_recomputer_test.go",
"contract_leg_registry_test.go",
"directory_size_test.go",
"hook_batch_applier_test.go",

View file

@ -0,0 +1,70 @@
package storage
import (
"context"
)
// BlockedMaintainedByServer is RecomputeBlockedResult.MaintainedBy for a
// backend whose blocked state lives in, and is maintained by, a remote server.
const BlockedMaintainedByServer = "server"
// RecomputeBlockedResult is what one is_blocked repair did.
type RecomputeBlockedResult struct {
// RowsCorrected is how many rows' persisted flag changed. A consistent
// store corrects none.
RowsCorrected int
// MaintainedBy is "" when THIS backend recomputed its own column, and
// BlockedMaintainedByServer when the column belongs to a remote server
// that maintains it, in which case nothing was recomputed here and
// RowsCorrected is 0. A caller that must tell "nothing was stale" from
// "nothing was checked here" reads it.
MaintainedBy string
}
// ServerMaintainedBlockedState is implemented by a store whose blocked state a
// remote server derives and keeps — today the http backend.
type ServerMaintainedBlockedState interface {
BlockedStateMaintainedByServer() bool
}
// RecomputeBlocked is the one library entry for the is_blocked repair
// (`bd recompute-blocked`), the named repair of
// issueops.BlockedStateInvariant's merge clause — the one way that
// invariant's persisted column can be stale. Every store goes through it. The
// `--proxied-server` route deliberately does not: it runs
// versioncontrolops.RecomputeAllBlockedOnConn (the guard, recompute, staging
// set and commit message a local store uses) on a pinned non-transactional
// connection, because the repair's DOLT_ADD/DOLT_COMMIT are stored procedures
// Dolt refuses inside an explicit transaction and its commit must stage
// `issues` alone (cmd/bd/recompute_blocked_proxied_server.go).
//
// A LOCAL store (BlockedRecomputer) recomputes its whole column from the
// dependency graph and commits the result, idempotently.
//
// A REMOTE store (ServerMaintainedBlockedState) recomputes nothing and answers
// BlockedMaintainedByServer. Every write its client makes is committed by the
// server's own store under the invariant's local-write clause, so the client
// cannot leave the column stale and holds no copy of it; the merge clause's
// staleness happens to the server's database, and its repair is this same
// entry run against that database, in the server's workspace. There is no
// wire operation for it: a whole-column rewrite any bearer of a workspace
// credential could trigger, for state no client can have caused, is not one
// to publish.
//
// It looks through the decorator chain, as the repair fires no hooks. Any
// other store refuses with *ErrUnsupported.
func RecomputeBlocked(ctx context.Context, s DoltStorage) (RecomputeBlockedResult, error) {
inner := UnwrapStore(s)
if remote, ok := inner.(ServerMaintainedBlockedState); ok && remote.BlockedStateMaintainedByServer() {
return RecomputeBlockedResult{MaintainedBy: BlockedMaintainedByServer}, nil
}
local, ok := inner.(BlockedRecomputer)
if !ok {
return RecomputeBlockedResult{}, &ErrUnsupported{Op: "RecomputeAllBlocked", Backend: "this storage"}
}
changed, err := local.RecomputeAllBlocked(ctx)
if err != nil {
return RecomputeBlockedResult{}, err
}
return RecomputeBlockedResult{RowsCorrected: changed}, nil
}

View file

@ -0,0 +1,61 @@
package storage
import (
"context"
"errors"
"testing"
)
type localRecomputeStore struct {
DoltStorage
changed int
err error
calls int
}
func (s *localRecomputeStore) RecomputeAllBlocked(context.Context) (int, error) {
s.calls++
return s.changed, s.err
}
type serverMaintainedStore struct {
localRecomputeStore
}
func (*serverMaintainedStore) BlockedStateMaintainedByServer() bool { return true }
type plainStore struct{ DoltStorage }
func TestRecomputeBlockedRunsTheLocalRepair(t *testing.T) {
s := &localRecomputeStore{changed: 3}
got, err := RecomputeBlocked(context.Background(), s)
if err != nil || got != (RecomputeBlockedResult{RowsCorrected: 3}) || s.calls != 1 {
t.Fatalf("RecomputeBlocked = (%+v, %v) after %d repairs, want ({3 \"\"}, nil) after 1", got, err, s.calls)
}
s.err = errors.New("dirty graph")
if _, err := RecomputeBlocked(context.Background(), s); !errors.Is(err, s.err) {
t.Fatalf("RecomputeBlocked error = %v, want the repair's own error", err)
}
}
// TestRecomputeBlockedAnswersServerMaintainedWithoutRepairing pins S25: a store
// whose server maintains the column recomputes nothing, even if it ALSO offers
// a local repair, and says who maintains it.
func TestRecomputeBlockedAnswersServerMaintainedWithoutRepairing(t *testing.T) {
s := &serverMaintainedStore{localRecomputeStore{changed: 7}}
got, err := RecomputeBlocked(context.Background(), s)
if err != nil || got != (RecomputeBlockedResult{MaintainedBy: BlockedMaintainedByServer}) {
t.Fatalf("RecomputeBlocked = (%+v, %v), want ({0 server}, nil)", got, err)
}
if s.calls != 0 {
t.Fatalf("the local repair ran %d times for a server-maintained store, want 0", s.calls)
}
}
func TestRecomputeBlockedRefusesAStoreWithNeither(t *testing.T) {
_, err := RecomputeBlocked(context.Background(), plainStore{})
var unsup *ErrUnsupported
if !errors.As(err, &unsup) {
t.Fatalf("RecomputeBlocked error = %v, want *ErrUnsupported", err)
}
}

View file

@ -134,6 +134,12 @@ func TestReaderListEmptyPageIsWellFormed(t *testing.T) {
conformance.RunReaderListEmptyPageIsWellFormed(t, ctx, fixture)
}
func TestReaderListQueryMatchesTheTitleOrTheID(t *testing.T) {
fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr")
defer cleanup()
conformance.RunReaderListQueryMatchesTheTitleOrTheID(t, ctx, fixture)
}
func TestReaderGetResolvesTheExactIDAcrossBothPlanes(t *testing.T) {
fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr")
defer cleanup()
@ -297,6 +303,7 @@ func newDoltReaderFixture(t *testing.T, prefix string) (conformance.ReaderFixtur
_, err := store.AddIssueComment(ctx, issueID, author, text)
return err
},
PromoteWisp: store.PromoteFromEphemeral,
}
return fixture, ctx, func() {
cancel()

View file

@ -133,6 +133,12 @@ func TestEmbeddedReaderListEmptyPageIsWellFormed(t *testing.T) {
conformance.RunReaderListEmptyPageIsWellFormed(t, ctx, newEmbeddedReaderFixture(t, "rdr"))
}
func TestEmbeddedReaderListQueryMatchesTheTitleOrTheID(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
conformance.RunReaderListQueryMatchesTheTitleOrTheID(t, ctx, newEmbeddedReaderFixture(t, "rdr"))
}
func TestEmbeddedReaderGetResolvesTheExactIDAcrossBothPlanes(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
@ -276,5 +282,6 @@ func newEmbeddedReaderFixture(t *testing.T, prefix string) conformance.ReaderFix
_, err := te.store.AddIssueComment(ctx, issueID, author, text)
return err
},
PromoteWisp: te.store.PromoteFromEphemeral,
}
}

View file

@ -122,7 +122,7 @@ func (r *issueReader) List(ctx context.Context, req publicops.ListRequest) (publ
if req.ReadyFlag {
page, err = uw.IssueUseCase().GetReadyWorkWithCounts(ctx, workapi.ReadyFilterFromIssueFilter(filter))
} else {
page, err = uw.IssueUseCase().SearchIssuesWithCounts(ctx, "", filter)
page, err = uw.IssueUseCase().SearchIssuesWithCounts(ctx, req.Query, filter)
}
if err != nil {
return publicops.IssuePage{}, err

View file

@ -92,6 +92,9 @@ func TestReaderContract(t *testing.T) {
t.Run("ListEmptyPageIsWellFormed", func(t *testing.T) {
conformance.RunReaderListEmptyPageIsWellFormed(t, ctx, fixture)
})
t.Run("ListQueryMatchesTheTitleOrTheID", func(t *testing.T) {
conformance.RunReaderListQueryMatchesTheTitleOrTheID(t, ctx, fixture)
})
t.Run("GetResolvesTheExactIDAcrossBothPlanes", func(t *testing.T) {
conformance.RunReaderGetResolvesTheExactIDAcrossBothPlanes(t, ctx, fixture)
})
@ -207,5 +210,10 @@ func newUOWReaderFixture(t *testing.T, provider UnitOfWorkProvider, prefix strin
return "bd: comment " + issueID, err
})
},
PromoteWisp: func(ctx context.Context, id, actor string) error {
return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) {
return "bd: promote " + id, uw.IssueUseCase().PromoteWisp(ctx, id, actor)
})
},
}
}

View file

@ -1230,7 +1230,8 @@ type IssueWithCounts struct {
// WHICH SURFACES SET IT, because this type is shared by more than the
// listing and an absent marker means different things on them. It is set
// by the page epilogue behind issueops.Reader.List — `bd list --json` on
// both routes, its --ready arm included, and GET /v0/beads/issues. It is
// both routes, its --ready arm included, `bd search --json` on every
// route, and GET /v0/beads/issues. It is
// NOT set by Reader.Ready (GET /v0/beads/ready) or by the claim response
// that returns this type, so on those an absent marker says nothing about
// whether a row's comments exist: read comment_count there. Extending the

View file

@ -160,7 +160,7 @@ func BuildCountFilter(in issueops.CountRequest, cfg ListConfig) (types.IssueFilt
}
if in.IncludeInfra {
applyCountIncludeInfra(&filter, in.IssueType, cfg)
applyCountIncludeInfra(&filter, in.IssueType, in.IncludeEphemeral, cfg)
} else if !in.IncludeEphemeral {
filter.SkipWisps = true
}
@ -178,12 +178,15 @@ func BuildCountFilter(in issueops.CountRequest, cfg ListConfig) (types.IssueFilt
// - template molecules are excluded (list's default);
// - gate beads are excluded unless requested via --type gate;
// - counting an infra type (agent/role/message, or the store-configured set)
// routes to the ephemeral wisps tier, like list's infra-type listing.
// routes to the ephemeral wisps tier, like list's infra-type listing —
// unless includeEphemeral is also set, which lifts that narrowing on both
// builders, so the durable rows of that type are counted as they are
// listed.
//
// A count without IncludeInfra never calls this. It keeps its historical
// durable-only semantics unless IncludeEphemeral admits the wisps tier: the
// first of the changes above, with none of the rest.
func applyCountIncludeInfra(filter *types.IssueFilter, issueType string, cfg ListConfig) {
func applyCountIncludeInfra(filter *types.IssueFilter, issueType string, includeEphemeral bool, cfg ListConfig) {
filter.SkipWisps = false
isTemplate := false
@ -193,7 +196,7 @@ func applyCountIncludeInfra(filter *types.IssueFilter, issueType string, cfg Lis
filter.ExcludeTypes = append(filter.ExcludeTypes, "gate")
}
if issueType != "" && cfg.IsInfra(issueType) {
if issueType != "" && cfg.IsInfra(issueType) && !includeEphemeral {
ephemeral := true
filter.Ephemeral = &ephemeral
}

View file

@ -16,57 +16,76 @@ import (
// dimensions are the wisps merge (SkipWisps), template exclusion (IsTemplate),
// the default gate exclusion (ExcludeTypes), and infra-type routing to the
// ephemeral tier (Ephemeral).
//
// Each type runs twice, the second time with --include-ephemeral on both
// sides. That flag lifts the infra-type routing on the list side (an
// infra-typed row can live in the durable table too, and the flag promises
// the durable answer plus the plane), so a count that kept routing would read
// only the wisp tier while the listing it mirrors reads both: the `message`
// arm is the one that fails if the two builders stop moving in lockstep.
func TestBuildCountFilterIncludeInfraMirrorsListFilter(t *testing.T) {
cfg := ListConfig{}
for _, issueType := range []string{"", "task", "gate", "message"} {
name := issueType
if name == "" {
name = "none"
for _, includeEphemeral := range []bool{false, true} {
for _, issueType := range []string{"", "task", "gate", "message"} {
name := issueType
if name == "" {
name = "none"
}
if includeEphemeral {
name += "_include_ephemeral"
}
t.Run("type_"+name, func(t *testing.T) {
assertCountMirrorsListIncludeInfra(t, cfg, issueType, includeEphemeral)
})
}
t.Run("type_"+name, func(t *testing.T) {
want, err := BuildListFilter(issueops.ListRequest{
AllFlag: true, IncludeInfra: true, IssueType: issueType,
}, cfg)
if err != nil {
t.Fatalf("BuildListFilter(%q): %v", issueType, err)
}
got, err := BuildCountFilter(issueops.CountRequest{
IncludeInfra: true, IssueType: issueType,
}, cfg)
if err != nil {
t.Fatalf("BuildCountFilter(%q): %v", issueType, err)
}
}
}
if got.SkipWisps != want.SkipWisps {
t.Errorf("SkipWisps = %v, list --include-infra --all uses %v", got.SkipWisps, want.SkipWisps)
}
if !reflect.DeepEqual(got.IsTemplate, want.IsTemplate) {
t.Errorf("IsTemplate = %v, list --include-infra --all uses %v", countPtrStr(got.IsTemplate), countPtrStr(want.IsTemplate))
}
if !reflect.DeepEqual(got.ExcludeTypes, want.ExcludeTypes) {
t.Errorf("ExcludeTypes = %v, list --include-infra --all uses %v", got.ExcludeTypes, want.ExcludeTypes)
}
if !reflect.DeepEqual(got.Ephemeral, want.Ephemeral) {
t.Errorf("Ephemeral = %v, list --include-infra --all uses %v", countPtrStr(got.Ephemeral), countPtrStr(want.Ephemeral))
}
if !reflect.DeepEqual(got.IssueType, want.IssueType) {
t.Errorf("IssueType = %v, list --include-infra --all uses %v", got.IssueType, want.IssueType)
}
// A count defaults to all statuses and all pinned states, which is
// exactly what list's --all flag selects.
if !reflect.DeepEqual(got.Status, want.Status) {
t.Errorf("Status = %v, list --include-infra --all uses %v", got.Status, want.Status)
}
if !reflect.DeepEqual(got.Statuses, want.Statuses) {
t.Errorf("Statuses = %v, list --include-infra --all uses %v", got.Statuses, want.Statuses)
}
if !reflect.DeepEqual(got.ExcludeStatus, want.ExcludeStatus) {
t.Errorf("ExcludeStatus = %v, list --include-infra --all uses %v", got.ExcludeStatus, want.ExcludeStatus)
}
if !reflect.DeepEqual(got.Pinned, want.Pinned) {
t.Errorf("Pinned = %v, list --include-infra --all uses %v", countPtrStr(got.Pinned), countPtrStr(want.Pinned))
}
})
// assertCountMirrorsListIncludeInfra compares one `bd count --include-infra`
// filter against the `bd list --include-infra --all` filter it mirrors.
func assertCountMirrorsListIncludeInfra(t *testing.T, cfg ListConfig, issueType string, includeEphemeral bool) {
t.Helper()
want, err := BuildListFilter(issueops.ListRequest{
AllFlag: true, IncludeInfra: true, IssueType: issueType, IncludeEphemeral: includeEphemeral,
}, cfg)
if err != nil {
t.Fatalf("BuildListFilter(%q): %v", issueType, err)
}
got, err := BuildCountFilter(issueops.CountRequest{
IncludeInfra: true, IssueType: issueType, IncludeEphemeral: includeEphemeral,
}, cfg)
if err != nil {
t.Fatalf("BuildCountFilter(%q): %v", issueType, err)
}
if got.SkipWisps != want.SkipWisps {
t.Errorf("SkipWisps = %v, list --include-infra --all uses %v", got.SkipWisps, want.SkipWisps)
}
if !reflect.DeepEqual(got.IsTemplate, want.IsTemplate) {
t.Errorf("IsTemplate = %v, list --include-infra --all uses %v", countPtrStr(got.IsTemplate), countPtrStr(want.IsTemplate))
}
if !reflect.DeepEqual(got.ExcludeTypes, want.ExcludeTypes) {
t.Errorf("ExcludeTypes = %v, list --include-infra --all uses %v", got.ExcludeTypes, want.ExcludeTypes)
}
if !reflect.DeepEqual(got.Ephemeral, want.Ephemeral) {
t.Errorf("Ephemeral = %v, list --include-infra --all uses %v", countPtrStr(got.Ephemeral), countPtrStr(want.Ephemeral))
}
if !reflect.DeepEqual(got.IssueType, want.IssueType) {
t.Errorf("IssueType = %v, list --include-infra --all uses %v", got.IssueType, want.IssueType)
}
// A count defaults to all statuses and all pinned states, which is
// exactly what list's --all flag selects.
if !reflect.DeepEqual(got.Status, want.Status) {
t.Errorf("Status = %v, list --include-infra --all uses %v", got.Status, want.Status)
}
if !reflect.DeepEqual(got.Statuses, want.Statuses) {
t.Errorf("Statuses = %v, list --include-infra --all uses %v", got.Statuses, want.Statuses)
}
if !reflect.DeepEqual(got.ExcludeStatus, want.ExcludeStatus) {
t.Errorf("ExcludeStatus = %v, list --include-infra --all uses %v", got.ExcludeStatus, want.ExcludeStatus)
}
if !reflect.DeepEqual(got.Pinned, want.Pinned) {
t.Errorf("Pinned = %v, list --include-infra --all uses %v", countPtrStr(got.Pinned), countPtrStr(want.Pinned))
}
}

View file

@ -367,11 +367,6 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter
}
}
if cfg.IsInfra(in.IssueType) {
ephemeral := true
filter.Ephemeral = &ephemeral
}
if in.ParentID != "" {
pid := in.ParentID
filter.ParentID = &pid
@ -415,7 +410,8 @@ func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter
// 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.
// 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
@ -442,14 +438,28 @@ func applyTypeSuppressions(in issueops.ListRequest, cfg ListConfig, filter *type
// 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 routed to
// the plane alone in BuildListFilter). 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.
// 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

View file

@ -60,6 +60,50 @@ func TestIncludeEphemeralIsThePlaneBitAndNothingElse(t *testing.T) {
}
}
// TestIncludeEphemeralLiftsTheInfraTypeNarrowing pins the other half of the
// "admits in addition, never narrows" promise, for the one request that DOES
// narrow: naming an infra type reads only that type's ephemeral rows
// (Ephemeral=true), which is where creating one puts it. An infra-typed row can
// still be durable — a promoted wisp, a retyped issue — so IncludeEphemeral has
// to lift the narrowing, or `bd search --type message` (whose scope sets the
// flag) drops those rows with exit 0, as it did while the narrowing held.
// IncludeInfra alone keeps it; IncludeAllTypes, the union of the flags, lifts
// it with them.
func TestIncludeEphemeralLiftsTheInfraTypeNarrowing(t *testing.T) {
searchScope := issueops.SearchListRequest("needle")
searchScope.IssueType = "message"
for _, tc := range []struct {
name string
req issueops.ListRequest
narrow bool
}{
{"an infra type alone narrows to its ephemeral rows", issueops.ListRequest{IssueType: "message"}, true},
{"IncludeInfra alone keeps the narrowing", issueops.ListRequest{IssueType: "message", IncludeInfra: true}, true},
{"IncludeEphemeral lifts it", issueops.ListRequest{IssueType: "message", IncludeEphemeral: true}, false},
{"IncludeEphemeral lifts it beside IncludeInfra", issueops.ListRequest{IssueType: "message", IncludeEphemeral: true, IncludeInfra: true}, false},
{"IncludeAllTypes lifts it", issueops.ListRequest{IssueType: "message", IncludeAllTypes: true}, false},
{"search's scope lifts it", searchScope, false},
{"a type that is not infra is never narrowed", issueops.ListRequest{IssueType: "task"}, false},
} {
t.Run(tc.name, func(t *testing.T) {
filter, err := BuildListFilter(tc.req, ListConfig{})
if err != nil {
t.Fatalf("BuildListFilter: %v", err)
}
switch {
case tc.narrow && (filter.Ephemeral == nil || !*filter.Ephemeral):
t.Errorf("Ephemeral = %v, want true: the infra type's own wisps are the only rows this request asked for", filter.Ephemeral)
case !tc.narrow && filter.Ephemeral != nil:
t.Errorf("Ephemeral = %v, want nil: the durable rows of the type are part of this answer", *filter.Ephemeral)
}
if tc.req.IssueType == "message" && filter.SkipWisps {
t.Error("SkipWisps is set, but naming an infra type always reads the wisp table")
}
})
}
}
// TestReadyProjectionCarriesTheEphemeralPlane pins the ReadyFlag arm's half of
// the same promise. The projection onto WorkFilter is where a list field is
// silently dropped, and a dropped IncludeEphemeral would answer `--ready

View file

@ -114,7 +114,7 @@ func (r *storeReader) List(ctx context.Context, req issueops.ListRequest) (issue
if req.ReadyFlag {
items, err = r.store.GetReadyWorkWithCounts(ctx, workapi.ReadyFilterFromIssueFilter(filter))
} else {
items, err = r.store.SearchIssuesWithCounts(ctx, "", filter)
items, err = r.store.SearchIssuesWithCounts(ctx, req.Query, filter)
}
if err != nil {
return issueops.IssuePage{}, err

View file

@ -13,6 +13,7 @@ go_library(
"claimer.go",
"commenter.go",
"counter.go",
"current.go",
"cycledetector.go",
"deleter.go",
"dependencyeditor.go",
@ -34,6 +35,7 @@ go_library(
"readycounter.go",
"relations.go",
"releaser.go",
"search.go",
"statsreporter.go",
"sweeper.go",
"template_errors.go",
@ -53,14 +55,17 @@ go_test(
name = "issueops_test",
srcs = [
"claimer_external_test.go",
"current_test.go",
"issueops_external_test.go",
"molecule_internal_test.go",
"molecule_test.go",
"search_test.go",
],
embed = [":issueops"],
deps = [
"//:beads",
"//internal/types",
"//internal/workapi",
],
)

View file

@ -167,7 +167,8 @@ type CountRequest struct {
// - template molecules are excluded, which a default count includes;
// - gate beads are excluded, unless IssueType asks for gates by name;
// - an IssueType the workspace calls infra routes the count to the
// ephemeral tier instead of the durable one.
// ephemeral tier instead of the durable one — unless IncludeEphemeral
// is also set, which lifts that routing, as it does for a listing.
//
// The infra vocabulary is the WORKSPACE's, read from configuration inside
// the implementation. A caller does not supply it and cannot: that is the
@ -198,6 +199,11 @@ type CountRequest struct {
// it; only IncludeInfra sets out to reconcile cardinality, and it pays for
// that with three changes beyond the plane.
//
// Beside IncludeInfra it does one thing more, the same thing it does to a
// listing: it lifts the fourth change's routing of an infra IssueType, so
// the durable rows of that type (a promoted wisp, a retyped issue) are
// counted along with its wisps rather than instead of them.
//
// Unset — and with IncludeInfra also unset — the count is durable-plane
// only: the historical answer, unchanged.
IncludeEphemeral bool

64
issueops/current.go Normal file
View file

@ -0,0 +1,64 @@
package issueops
import (
"context"
"fmt"
"strings"
"github.com/steveyegge/beads/internal/types"
)
// CurrentIssueStatuses is the order FindCurrentIssue looks in: the actor's
// in-progress work first, then work hooked to it.
var CurrentIssueStatuses = []types.Status{types.StatusInProgress, types.StatusHooked}
// FindCurrentIssue answers `bd show --current`'s question — which issue is
// this actor working on — through the Querier role, which every backend
// serves (a remote one as queryIssues). It returns the id of the first issue
// in the actor's in-progress work, else the first hooked to it, in the store's
// default order; "" when both reads answered and found nothing.
//
// A FAILED READ IS AN ERROR, never a miss. A caller falls back (to the
// last-touched issue, say) only on "", which only two reads that answered can
// produce. Treating a refusal as "nothing in progress" is what made the http
// backend print the wrong issue with exit 0.
//
// Each read is exactly the filter `status=<s>`, `assignee=<actor>` and nothing
// else, one row. The actor travels as a quoted query value. The query language
// reads `assignee=none` and `assignee=null` (any case) as "no assignee", so an
// actor by one of those names, or an empty actor, cannot be asked about and
// gets "".
func FindCurrentIssue(ctx context.Context, querier Querier, actor string) (string, error) {
if querier == nil || actor == "" || strings.EqualFold(actor, "none") || strings.EqualFold(actor, "null") {
return "", nil
}
for _, status := range CurrentIssueStatuses {
page, err := querier.Query(ctx, currentIssueQuery(status, actor))
if err != nil {
return "", fmt.Errorf("finding the current issue (%s, assigned to %s): %w", status, actor, err)
}
for _, row := range page.Items {
if row != nil && row.Issue != nil {
return row.ID, nil
}
}
}
return "", nil
}
// currentIssueQuery is the role request for one status. No display order:
// every backend answers in its default order, and a sort would change which
// row is "current".
func currentIssueQuery(status types.Status, actor string) QueryRequest {
one := 1
return QueryRequest{
Expression: fmt.Sprintf("status=%s AND assignee=%s", status, quoteQueryValue(actor)),
Limit: &one,
}
}
// quoteQueryValue renders v as a double-quoted query-language string, escaping
// the two characters the lexer gives meaning inside one.
func quoteQueryValue(v string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(v) + `"`
}

154
issueops/current_test.go Normal file
View file

@ -0,0 +1,154 @@
package issueops_test
import (
"context"
"errors"
"reflect"
"testing"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
type currentQueryResponse struct {
ids []string
err error
}
type currentQueryRecorder struct {
responses []currentQueryResponse
calls []issueops.QueryRequest
}
func (r *currentQueryRecorder) Query(_ context.Context, req issueops.QueryRequest) (issueops.IssuePage, error) {
r.calls = append(r.calls, req)
response := r.responses[len(r.calls)-1]
if response.err != nil {
return issueops.IssuePage{}, response.err
}
items := make([]*types.IssueWithCounts, 0, len(response.ids))
for _, id := range response.ids {
items = append(items, &types.IssueWithCounts{Issue: &types.Issue{ID: id}})
}
return issueops.IssuePage{Items: items}, nil
}
func wantCurrentQueries(quotedActor string, statuses ...types.Status) []issueops.QueryRequest {
one := 1
want := make([]issueops.QueryRequest, 0, len(statuses))
for _, status := range statuses {
want = append(want, issueops.QueryRequest{
Expression: "status=" + string(status) + " AND assignee=" + quotedActor,
Limit: &one,
})
}
return want
}
func TestFindCurrentIssueInProgressShortCircuits(t *testing.T) {
q := &currentQueryRecorder{responses: []currentQueryResponse{{ids: []string{"in-progress-first", "in-progress-second"}}}}
got, err := issueops.FindCurrentIssue(context.Background(), q, "tester")
if err != nil || got != "in-progress-first" {
t.Fatalf("FindCurrentIssue = (%q, %v), want (in-progress-first, nil)", got, err)
}
if want := wantCurrentQueries(`"tester"`, types.StatusInProgress); !reflect.DeepEqual(q.calls, want) {
t.Fatalf("Query calls = %#v, want %#v", q.calls, want)
}
}
func TestFindCurrentIssueFindsHookedAfterInProgressMiss(t *testing.T) {
q := &currentQueryRecorder{responses: []currentQueryResponse{{}, {ids: []string{"hooked"}}}}
got, err := issueops.FindCurrentIssue(context.Background(), q, "tester")
if err != nil || got != "hooked" {
t.Fatalf("FindCurrentIssue = (%q, %v), want (hooked, nil)", got, err)
}
if want := wantCurrentQueries(`"tester"`, types.StatusInProgress, types.StatusHooked); !reflect.DeepEqual(q.calls, want) {
t.Fatalf("Query calls = %#v, want %#v", q.calls, want)
}
}
func TestFindCurrentIssueAnswersEmptyAfterTwoMisses(t *testing.T) {
q := &currentQueryRecorder{responses: []currentQueryResponse{{}, {}}}
got, err := issueops.FindCurrentIssue(context.Background(), q, "tester")
if err != nil || got != "" {
t.Fatalf("FindCurrentIssue = (%q, %v), want (\"\", nil)", got, err)
}
}
// TestFindCurrentIssueNeverTakesAFailureForAMiss is S6e: a refused or failed
// read used to fall through to the next read and then to the last-touched
// issue, so `bd show --current` printed the WRONG issue, exit 0.
func TestFindCurrentIssueNeverTakesAFailureForAMiss(t *testing.T) {
refusal := errors.New("SearchIssues: not supported over HTTP")
for _, tc := range []struct {
name string
responses []currentQueryResponse
calls int
}{
{"in-progress read fails", []currentQueryResponse{{err: refusal}}, 1},
{"hooked read fails", []currentQueryResponse{{}, {err: refusal}}, 2},
} {
t.Run(tc.name, func(t *testing.T) {
q := &currentQueryRecorder{responses: tc.responses}
got, err := issueops.FindCurrentIssue(context.Background(), q, "tester")
if !errors.Is(err, refusal) || got != "" {
t.Fatalf("FindCurrentIssue = (%q, %v), want (\"\", an error wrapping %v)", got, err, refusal)
}
if len(q.calls) != tc.calls {
t.Fatalf("query calls = %d, want %d", len(q.calls), tc.calls)
}
})
}
}
// TestFindCurrentIssueQuotesTheActor pins that an actor is one quoted value,
// whatever it contains, so it can neither break the parse nor splice in a
// clause.
func TestFindCurrentIssueQuotesTheActor(t *testing.T) {
q := &currentQueryRecorder{responses: []currentQueryResponse{{ids: []string{"x"}}}}
if _, err := issueops.FindCurrentIssue(context.Background(), q, `gastown/polecats/ru"st\ AND status=closed`); err != nil {
t.Fatal(err)
}
if want := wantCurrentQueries(`"gastown/polecats/ru\"st\\ AND status=closed"`, types.StatusInProgress); !reflect.DeepEqual(q.calls, want) {
t.Fatalf("Query calls = %#v, want %#v", q.calls, want)
}
}
// TestFindCurrentIssueSkipsActorsItCannotAskAbout pins the actors the query
// language cannot express: `assignee=none`/`null` mean "no assignee", which
// would name some unassigned issue as this actor's.
func TestFindCurrentIssueSkipsActorsItCannotAskAbout(t *testing.T) {
for _, actor := range []string{"", "none", "NULL"} {
q := &currentQueryRecorder{}
got, err := issueops.FindCurrentIssue(context.Background(), q, actor)
if err != nil || got != "" || len(q.calls) != 0 {
t.Fatalf("actor %q: got (%q, %v) after %d queries, want (\"\", nil) after none", actor, got, err, len(q.calls))
}
}
}
// TestFindCurrentIssueQueryMeansTheRawFilter pins that each read evaluates to
// exactly `status=<s>`, `assignee=<actor>` — no predicate half, no default
// closed exclusion, no sort — so the store answers it with the same rows in
// the same default order the raw read did.
func TestFindCurrentIssueQueryMeansTheRawFilter(t *testing.T) {
for _, actor := range []string{"tester", "gastown/polecats/rust", `we"ird\name`, "has space"} {
q := &currentQueryRecorder{responses: []currentQueryResponse{{}, {}}}
if _, err := issueops.FindCurrentIssue(context.Background(), q, actor); err != nil {
t.Fatal(err)
}
for i, req := range q.calls {
plan, err := workapi.BuildQueryPlan(req)
if err != nil {
t.Fatalf("actor %q read %d: %v", actor, i, err)
}
f := plan.Filter
status := issueops.CurrentIssueStatuses[i]
if plan.RequiresPredicate() || f.Status == nil || *f.Status != status || f.Assignee == nil || *f.Assignee != actor ||
f.NoAssignee || len(f.ExcludeStatus) != 0 || f.Limit != 1 || f.SortBy != "" {
t.Fatalf("actor %q status %s: plan = %+v", actor, status, plan)
}
}
}
}

View file

@ -152,6 +152,17 @@ type ListRequest struct {
SpecPrefix string
// IDFilter is a comma-separated id set.
IDFilter string
// Query is `bd search`'s free text, with that command's meaning and not
// TitleSearch's: a row matches when its title contains the text or its id
// does, case-insensitively, and an id-shaped text also matches an exact
// id, an id prefix and the external ref. It is the `query` argument of the
// storage seam's SearchIssues, carried as a member so a backend that
// serves only roles can answer a search.
//
// It narrows; it lifts no default exclusion. A caller that wants search's
// "every status, every kind of row" answer asks for that with AllFlag and
// the Include* members, as for any other listing.
Query string
Labels []string
LabelsAny []string
@ -311,6 +322,14 @@ type ListRequest struct {
// field alone reaches is the ephemeral rows of the types a listing already
// shows.
//
// AN INFRA IssueType IS THE ONE NARROWING IT LIFTS. Naming a type the
// workspace calls infra reads only that type's EPHEMERAL rows, which is
// where creating one puts it; with this flag set the request reads the
// type's rows on both planes instead, because 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. That is the superset
// promise above applied to the narrowing; IncludeInfra alone keeps it.
//
// THE MERGED ANSWER IS ONE ORDER. Both planes are ordered together by
// SortBy as if they were a single table — not the durable rows followed by
// the ephemeral ones — so a Limit truncates the merged order rather than

View file

@ -64,6 +64,7 @@ type readyScopeField struct {
// that can never contain one — it is in the list below.
var readyScopeFields = []readyScopeField{
{"IDFilter", "--id", func(r ListRequest) bool { return r.IDFilter != "" }},
{"Query", "bd search", func(r ListRequest) bool { return r.Query != "" }},
{"TitleSearch", "--title", func(r ListRequest) bool { return r.TitleSearch != "" }},
{"SpecPrefix", "--spec", func(r ListRequest) bool { return r.SpecPrefix != "" }},

33
issueops/search.go Normal file
View file

@ -0,0 +1,33 @@
package issueops
// SearchListRequest is `bd search`'s request: the listing that answers the
// text query, with search's own scope. Every route of `bd search` — the direct
// store, the proxied server and a remote backend — asks issueops.Reader.List
// with this request (plus the caller's narrowing flags), so the three cannot
// answer the same search differently, and a remote backend serves it through
// the same role the server's listIssues handler calls.
//
// The scope is search's, not a listing's:
// - EVERY STATUS. Closed rows match unless the caller narrows with Status
// (bd-t5yex: "was this already filed or fixed?" must not answer no just
// because the answer is closed). AllFlag lifts the status exclusions and
// the pinned-flag predicate together.
// - EVERY KIND OF ROW. Templates, gates, the workspace's infrastructure types
// and the ephemeral plane all match; the four Include* members lift those
// exclusions.
// - THE STORE'S DEFAULT ORDER, priority then newest then id, so a Limit
// keeps the same rows a raw SearchIssues read kept. A display sort is the
// caller's to apply to the page afterwards.
//
// Limit is left nil (the listing default); a caller sets it.
func SearchListRequest(query string) ListRequest {
return ListRequest{
Query: query,
AllFlag: true,
IncludeTemplates: true,
IncludeGates: true,
IncludeInfra: true,
IncludeEphemeral: true,
SortBy: "priority",
}
}

22
issueops/search_test.go Normal file
View file

@ -0,0 +1,22 @@
package issueops_test
import (
"reflect"
"testing"
"github.com/steveyegge/beads/issueops"
)
// TestSearchListRequestIsSearchsScope pins the library's search scope: every
// status, every kind of row, the store's default order.
func TestSearchListRequestIsSearchsScope(t *testing.T) {
got := issueops.SearchListRequest("needle")
want := issueops.ListRequest{
Query: "needle", AllFlag: true,
IncludeTemplates: true, IncludeGates: true, IncludeInfra: true, IncludeEphemeral: true,
SortBy: "priority",
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("SearchListRequest = %+v, want %+v", got, want)
}
}