feat(cli): doc delete multi-id + api --paginate + paginate fixes + batch deletes

Batch-write surface and pagination consistency:

* weknora doc delete <doc-id> [<doc-id>...] — positional multi-id, default
  keep-going on failure. Single -y confirms entire batch.
* weknora session delete <session-id> [<session-id>...] — same shape.
* weknora chunk delete <chunk-id> [<chunk-id>...] --doc <doc-id> — multi-id
  with shared --doc parent.
* Multi-id partial-failure rolls up as operation.failed (exit 1), not
  server.error (exit 7) — failures are operation outcomes, not transient
  transport issues, and the retry-with-backoff hint for server.* would
  mislead callers.
* weknora api <path> --paginate — auto-walks offset pagination and merges
  pages into a single {data, total} JSON response.
* Paginate truncation fix across 6 list/follower call sites.
* All doc / search / chunk / session / kb list commands migrated to
  FormatOptions API.

Multi-id RunE only emits the {ok, failed} envelope when the operation
actually ran — pre-flight failures (e.g. confirmation_required) leave
stdout empty per the wire contract.

doc upload's missing-positional-or-flag check is wrapped as FlagError so
the exit code (2) matches the convention used by other commands that
require a positional argument directly.
This commit is contained in:
nullkey
2026-05-18 01:38:30 +08:00
committed by lyingbug
parent 0e081aec5c
commit 34bb0b5096
33 changed files with 1259 additions and 406 deletions
+8 -7
View File
@@ -12,7 +12,7 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// chunksFields enumerates the fields surfaced for `--json` discovery on
// chunksFields enumerates the fields surfaced for `--format json` discovery on
// `search chunks`. Filter applies to each SearchResult object in the bare
// array.
var chunksFields = []string{
@@ -64,10 +64,11 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
if opts.Limit < 1 || opts.Limit > 1000 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
}
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
@@ -77,7 +78,7 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
return err
}
opts.KBID = kbID
return runChunks(c.Context(), opts, jopts, cli)
return runChunks(c.Context(), opts, fopts, cli)
},
}
bindChunksFlags(cmd, opts)
@@ -94,7 +95,7 @@ func bindChunksFlags(cmd *cobra.Command, opts *ChunksOptions) {
cmd.Flags().Float64Var(&opts.KeywordThreshold, "keyword-threshold", 0, "Keyword retrieval score floor (per-channel, pre-fusion); 0 = no filter")
cmd.Flags().BoolVar(&opts.NoVector, "no-vector", false, "Disable the vector channel")
cmd.Flags().BoolVar(&opts.NoKeyword, "no-keyword", false, "Disable the keyword channel")
cmdutil.AddJSONFlags(cmd, chunksFields)
cmdutil.AddFormatFlag(cmd, chunksFields...)
}
// validate checks the option set before any SDK call. Limit bounds are
@@ -110,7 +111,7 @@ func (o *ChunksOptions) validate() error {
return nil
}
func runChunks(ctx context.Context, opts *ChunksOptions, jopts *cmdutil.JSONOptions, svc ChunksService) error {
func runChunks(ctx context.Context, opts *ChunksOptions, fopts *cmdutil.FormatOptions, svc ChunksService) error {
if err := opts.validate(); err != nil {
return err
}
@@ -140,11 +141,11 @@ func runChunks(ctx context.Context, opts *ChunksOptions, jopts *cmdutil.JSONOpti
results = results[:opts.Limit]
}
if jopts.Enabled() {
if fopts.WantsJSON() {
if results == nil {
results = []*sdk.SearchResult{}
}
return jopts.Emit(iostreams.IO.Out, results)
return fopts.Emit(iostreams.IO.Out, results)
}
return renderChunkResults(results, opts.KBID)
}
+12 -12
View File
@@ -34,7 +34,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
{Score: 0.81, Content: "second chunk", KnowledgeID: "doc-2", MatchType: sdk.MatchTypeKeyword},
}}
opts := &ChunksOptions{Query: "hello", KBID: "kb_abc", Limit: 5}
require.NoError(t, runChunks(context.Background(), opts, nil, svc))
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Equal(t, "kb_abc", svc.gotKB)
assert.Equal(t, "hello", svc.gotQ)
@@ -46,13 +46,13 @@ func TestRunSearch_HumanOutput(t *testing.T) {
// JSON output must surface match_type so machine consumers / agents can
// reason about retrieval channels without re-implementing the wire format.
// (Human renderer keeps default minimal - diagnostic info opt-in via --json.)
// (Human renderer keeps default minimal - diagnostic info opt-in via --format json.)
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
{Score: 0.9, Content: "x", MatchType: sdk.MatchTypeKeyword},
}}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Contains(t, out.String(), `"match_type":1`)
}
@@ -60,7 +60,7 @@ func TestRunSearch_JSONOutput(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: []*sdk.SearchResult{{Score: 0.9, Content: "x"}}}
opts := &ChunksOptions{Query: "q", KBID: "kb1", Limit: 1}
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), "["), "expected bare JSON array, got: %q", got)
assert.NotContains(t, got, `"ok":`)
@@ -70,7 +70,7 @@ func TestRunSearch_JSONOutput(t *testing.T) {
func TestRunSearch_EmptyResults(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: nil}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, nil, svc))
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "(no results)")
}
@@ -86,7 +86,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
{Score: 0, Content: "enrichment parent"}, // server-padded
{Score: 0, Content: "enrichment nearby"}, // server-padded
}}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, nil, svc))
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
assert.Contains(t, got, "3 result(s)")
assert.NotContains(t, got, "enrichment parent")
@@ -95,7 +95,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
func TestRunSearch_BothChannelsDisabled(t *testing.T) {
iostreams.SetForTest(t)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, nil, &fakeChunksSvc{})
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeChunksSvc{})
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
@@ -103,7 +103,7 @@ func TestRunSearch_BothChannelsDisabled(t *testing.T) {
func TestRunSearch_ServiceError_Transport(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeChunksSvc{err: assert.AnError}
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, nil, svc)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -114,7 +114,7 @@ func TestRunSearch_ServiceError_Transport(t *testing.T) {
func TestRunSearch_ServiceError_HTTPNotFound(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeChunksSvc{err: errors.New("HTTP error 404: knowledge base not found")}
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, nil, svc)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -128,7 +128,7 @@ func TestIndent(t *testing.T) {
func TestRunSearch_NilService(t *testing.T) {
iostreams.SetForTest(t)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, nil, nil)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "server.error")
}
@@ -164,7 +164,7 @@ func TestRunSearch_NoVectorPassedThrough(t *testing.T) {
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
Query: "q", KBID: "kb1", NoVector: true,
}, nil, svc))
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NotNil(t, got)
assert.True(t, got.DisableVectorMatch)
assert.False(t, got.DisableKeywordsMatch)
@@ -176,7 +176,7 @@ func TestRunSearch_NoKeywordPassedThrough(t *testing.T) {
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
Query: "q", KBID: "kb1", NoKeyword: true,
}, nil, svc))
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NotNil(t, got)
assert.True(t, got.DisableKeywordsMatch)
assert.False(t, got.DisableVectorMatch)
+12 -11
View File
@@ -21,10 +21,10 @@ import (
// single page even at conservative sizes. Server caps page_size at 1000.
const docsPageSize = 200
// docsMaxPageSize bounds the --page-size flag, matching session/doc list canon.
// docsMaxPageSize bounds the --page-size flag, matching the session/doc list cap.
const docsMaxPageSize = 1000
// docsFields enumerates the fields surfaced for `--json` discovery on
// docsFields enumerates the fields surfaced for `--format json` discovery on
// `search docs`. Mirrors sdk.Knowledge json tags.
var docsFields = []string{
"id", "tenant_id", "knowledge_base_id", "tag_id", "type", "title",
@@ -92,10 +92,11 @@ reached or the KB is exhausted (matching v0.4 behavior). Pass
if opts.Limit < 1 || opts.Limit > 1000 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
}
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
@@ -105,19 +106,19 @@ reached or the KB is exhausted (matching v0.4 behavior). Pass
return err
}
opts.KBID = kbID
return runDocsSearch(c.Context(), opts, jopts, cli)
return runDocsSearch(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name (required)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
cmd.Flags().IntVar(&opts.PageSize, "page-size", docsPageSize, "Items per server batch (1..1000)")
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", true, "Walk every server page until exhausted or --limit hit")
cmdutil.AddJSONFlags(cmd, docsFields)
cmdutil.AddFormatFlag(cmd, docsFields...)
_ = cmd.MarkFlagRequired("kb")
return cmd
}
func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, jopts *cmdutil.JSONOptions, svc DocsSearchService) error {
func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, fopts *cmdutil.FormatOptions, svc DocsSearchService) error {
if opts.PageSize < 1 || opts.PageSize > docsMaxPageSize {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--page-size must be in 1..%d, got %d", docsMaxPageSize, opts.PageSize))
@@ -129,8 +130,8 @@ func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, jopts *cmdutil.
// The server applies the keyword filter pre-pagination, so every item
// returned is already a match - no client-side filter needed.
// --all-pages=true (default) walks every server page; --all-pages=false
// stops after the first page. The server returns total; stop when
// page*pageSize >= total.
// stops after the first page. Termination counts records actually
// received so server-capped page_size doesn't truncate.
for page := 1; ; page++ {
items, total, err := svc.ListKnowledgeWithFilter(ctx, opts.KBID, page, opts.PageSize, filter)
if err != nil {
@@ -145,18 +146,18 @@ func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, jopts *cmdutil.
if !opts.AllPages {
break
}
if int64(page*opts.PageSize) >= total || len(items) == 0 {
if int64(len(matches)) >= total || len(items) == 0 {
break
}
}
done:
sortKnowledgeByRecency(matches)
if jopts.Enabled() {
if fopts.WantsJSON() {
if matches == nil {
matches = []sdk.Knowledge{}
}
return jopts.Emit(iostreams.IO.Out, matches)
return fopts.Emit(iostreams.IO.Out, matches)
}
if len(matches) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
+11 -11
View File
@@ -48,7 +48,7 @@ func TestDocsSearch_Substring(t *testing.T) {
},
total: 2,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Equal(t, "q3", svc.lastFilter.Keyword, "query must be threaded as filter.Keyword")
got := out.String()
assert.Contains(t, got, "d1")
@@ -62,7 +62,7 @@ func TestDocsSearch_MatchesFileName(t *testing.T) {
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "Untitled", FileName: "report.pdf"}}},
total: 1,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "d1")
}
@@ -81,7 +81,7 @@ func TestDocsSearch_PaginatesUntilTotal(t *testing.T) {
pages: map[int][]sdk.Knowledge{1: page1, 2: page2},
total: int64(docsPageSize) + 1,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: docsPageSize + 1, PageSize: docsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: docsPageSize + 1, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "found")
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when more items reported")
}
@@ -93,7 +93,7 @@ func TestDocsSearch_StopsAtLimit(t *testing.T) {
page1[i] = sdk.Knowledge{ID: "match", Title: "needle"}
}
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
// Must not request page 2 because limit was hit mid-page.
assert.Equal(t, []int{1}, svc.calls)
}
@@ -104,7 +104,7 @@ func TestDocsSearch_JSON(t *testing.T) {
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "match"}}},
total: 1,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "match", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "match", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), "["), "expected bare JSON array, got: %q", got)
assert.Contains(t, got, `"id":"d1"`)
@@ -114,7 +114,7 @@ func TestDocsSearch_JSON(t *testing.T) {
func TestDocsSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDocsSearchSvc{err: errors.New("HTTP error 404: kb not found")}
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, nil, svc)
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -136,7 +136,7 @@ func TestSearchDocs_AllPagesFlag_DefaultsTrue_WalksAllPages(t *testing.T) {
total: 3,
}
opts := &DocsSearchOptions{Query: "needle", KBID: "kb_abc", Limit: 100, PageSize: 2, AllPages: true}
require.NoError(t, runDocsSearch(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runDocsSearch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.GreaterOrEqual(t, len(svc.calls), 2, "must walk multi pages by default")
}
@@ -150,7 +150,7 @@ func TestSearchDocs_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
total: 100,
}
opts := &DocsSearchOptions{Query: "needle", KBID: "kb_abc", Limit: 100, PageSize: 2, AllPages: false}
require.NoError(t, runDocsSearch(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runDocsSearch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Len(t, svc.calls, 1, "must stop at first page when --all-pages=false")
}
@@ -161,7 +161,7 @@ func TestSearchDocs_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
func TestSearchDocs_KeywordPassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: {{ID: "d1"}}}, total: 1}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "my-query", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "my-query", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Equal(t, "my-query", svc.lastFilter.Keyword, "Query must be threaded as filter.Keyword on ListKnowledgeWithFilter")
// Other filter fields must be empty - search docs only forwards the keyword.
assert.Empty(t, svc.lastFilter.ParseStatus)
@@ -171,11 +171,11 @@ func TestSearchDocs_KeywordPassedToFilter(t *testing.T) {
}
// TestSearchDocs_PageSizeBound asserts the 1..1000 range guard mirrors the
// session/doc list canon. Out-of-range values must produce
// session/doc list cap. Out-of-range values must produce
// input.invalid_argument and never reach the SDK.
func TestSearchDocs_PageSizeBound(t *testing.T) {
for _, ps := range []int{0, -1, 1001} {
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "t", KBID: "k", Limit: 50, PageSize: ps}, &cmdutil.JSONOptions{}, &fakeDocsSearchSvc{})
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "t", KBID: "k", Limit: 50, PageSize: ps}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeDocsSearchSvc{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+9 -8
View File
@@ -15,7 +15,7 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// kbSearchFields enumerates the fields surfaced for `--json` discovery on
// kbSearchFields enumerates the fields surfaced for `--format json` discovery on
// `search kb`. Subset of KnowledgeBase suitable for list/filter results.
var kbSearchFields = []string{
"id", "name", "type", "description",
@@ -54,7 +54,7 @@ usually the closest hit) for deterministic output.
This is name-discovery only - for searching *inside* a knowledge base's
content, use ` + "`weknora search chunks`" + `.`,
Example: ` weknora search kb "marketing"
weknora search kb "team" --limit 5 --json`,
weknora search kb "team" --limit 5 --format json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Query = strings.TrimSpace(args[0])
@@ -64,23 +64,24 @@ content, use ` + "`weknora search chunks`" + `.`,
if opts.Limit < 1 || opts.Limit > 1000 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
}
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
return runKBSearch(c.Context(), opts, jopts, cli)
return runKBSearch(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
cmdutil.AddJSONFlags(cmd, kbSearchFields)
cmdutil.AddFormatFlag(cmd, kbSearchFields...)
return cmd
}
func runKBSearch(ctx context.Context, opts *KBSearchOptions, jopts *cmdutil.JSONOptions, svc KBSearchService) error {
func runKBSearch(ctx context.Context, opts *KBSearchOptions, fopts *cmdutil.FormatOptions, svc KBSearchService) error {
items, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return cmdutil.WrapHTTP(err, "list knowledge bases")
@@ -90,11 +91,11 @@ func runKBSearch(ctx context.Context, opts *KBSearchOptions, jopts *cmdutil.JSON
matches = matches[:opts.Limit]
}
if jopts.Enabled() {
if fopts.WantsJSON() {
if matches == nil {
matches = []sdk.KnowledgeBase{}
}
return jopts.Emit(iostreams.IO.Out, matches)
return fopts.Emit(iostreams.IO.Out, matches)
}
if len(matches) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
+8 -8
View File
@@ -30,7 +30,7 @@ func TestKBSearch_Substring(t *testing.T) {
{ID: "kb2", Name: "Engineering Docs", KnowledgeCount: 50},
{ID: "kb3", Name: "Marketing Q4 Plan", KnowledgeCount: 5},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, nil, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
assert.Contains(t, got, "kb1")
assert.Contains(t, got, "kb3")
@@ -42,7 +42,7 @@ func TestKBSearch_CaseInsensitive(t *testing.T) {
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
{ID: "kb1", Name: "ENGINEERING"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, nil, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "kb1")
}
@@ -51,7 +51,7 @@ func TestKBSearch_MatchesDescription(t *testing.T) {
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
{ID: "kb1", Name: "Engineering", Description: "all marketing docs are here"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, nil, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "kb1")
}
@@ -62,7 +62,7 @@ func TestKBSearch_SortByNameLength(t *testing.T) {
{ID: "kb_short", Name: "marketing"},
{ID: "kb_mid", Name: "marketing 2024"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, nil, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
// Order: shortest name first.
iShort := strings.Index(got, "kb_short")
@@ -78,7 +78,7 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
{ID: "a", Name: "match-a"}, {ID: "b", Name: "match-b"},
{ID: "c", Name: "match-c"}, {ID: "d", Name: "match-d"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, nil, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
count := 0
for _, id := range []string{"a", "b", "c", "d"} {
@@ -92,14 +92,14 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
func TestKBSearch_NoMatches(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{{Name: "foo"}}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, nil, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "(no matches)")
}
func TestKBSearch_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{{ID: "kb1", Name: "marketing"}}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), "["), "expected bare JSON array, got: %q", got)
@@ -110,7 +110,7 @@ func TestKBSearch_JSON(t *testing.T) {
func TestKBSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{err: errors.New("HTTP error 401: unauthenticated")}
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, nil, svc)
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+15 -10
View File
@@ -21,10 +21,10 @@ import (
// filter client-side. Tunable via --page-size in 1..1000.
const sessionsPageSize = 200
// sessionsMaxPageSize bounds the --page-size flag, matching session/doc list canon.
// sessionsMaxPageSize bounds the --page-size flag, matching the session/doc list cap.
const sessionsMaxPageSize = 1000
// sessionsSearchFields enumerates the fields surfaced for `--json` discovery
// sessionsSearchFields enumerates the fields surfaced for `--format json` discovery
// on `search sessions`. Mirrors sdk.Session json tags.
var sessionsSearchFields = []string{
"id", "tenant_id", "title", "description", "created_at", "updated_at",
@@ -64,7 +64,7 @@ By default, --all-pages=true walks every server page until --limit is
reached or the tenant's sessions are exhausted (matching v0.4 behavior).
Pass --all-pages=false to stop after one page.`,
Example: ` weknora search sessions "onboarding"
weknora search sessions "Q3 review" --limit 3 --json
weknora search sessions "Q3 review" --limit 3 --format json
weknora search sessions "Q3 review" --all-pages=false`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
@@ -75,31 +75,35 @@ Pass --all-pages=false to stop after one page.`,
if opts.Limit < 1 || opts.Limit > 1000 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
}
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
return runSessionsSearch(c.Context(), opts, jopts, cli)
return runSessionsSearch(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
cmd.Flags().IntVar(&opts.PageSize, "page-size", sessionsPageSize, "Items per server batch (1..1000)")
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", true, "Walk every server page until exhausted or --limit hit")
cmdutil.AddJSONFlags(cmd, sessionsSearchFields)
cmdutil.AddFormatFlag(cmd, sessionsSearchFields...)
return cmd
}
func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, jopts *cmdutil.JSONOptions, svc SessionsSearchService) error {
func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, fopts *cmdutil.FormatOptions, svc SessionsSearchService) error {
if opts.PageSize < 1 || opts.PageSize > sessionsMaxPageSize {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--page-size must be in 1..%d, got %d", sessionsMaxPageSize, opts.PageSize))
}
needle := strings.ToLower(opts.Query)
var matches []sdk.Session
var received int // count of server-returned items so far (separate from
// matches, which is client-filtered). Used for termination so a
// server-capped page_size doesn't cause early break.
// --all-pages=true (default) walks every server page; --all-pages=false
// stops after the first page.
@@ -108,6 +112,7 @@ func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, jopts *
if err != nil {
return cmdutil.WrapHTTP(err, "list sessions")
}
received += len(items)
for _, s := range items {
if matchSession(s, needle) {
matches = append(matches, s)
@@ -119,18 +124,18 @@ func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, jopts *
if !opts.AllPages {
break
}
if page*opts.PageSize >= total || len(items) == 0 {
if received >= total || len(items) == 0 {
break
}
}
done:
sortSessionsByRecency(matches)
if jopts.Enabled() {
if fopts.WantsJSON() {
if matches == nil {
matches = []sdk.Session{}
}
return jopts.Emit(iostreams.IO.Out, matches)
return fopts.Emit(iostreams.IO.Out, matches)
}
if len(matches) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
+9 -9
View File
@@ -39,7 +39,7 @@ func TestSessionsSearch_TitleAndDescription(t *testing.T) {
}},
total: 3,
}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
assert.Contains(t, got, "s1")
assert.Contains(t, got, "s2")
@@ -52,7 +52,7 @@ func TestSessionsSearch_NoMatches(t *testing.T) {
pages: map[int][]sdk.Session{1: {{Title: "foo"}}},
total: 1,
}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "(no matches)")
}
@@ -63,14 +63,14 @@ func TestSessionsSearch_PaginatesAndStopsAtLimit(t *testing.T) {
page1[i] = sdk.Session{ID: "m", Title: "needle"}
}
svc := &fakeSessionsSearchSvc{pages: map[int][]sdk.Session{1: page1}, total: 1000}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5, PageSize: sessionsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Equal(t, []int{1}, svc.calls, "stops paging when limit reached")
}
func TestSessionsSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeSessionsSearchSvc{err: errors.New("HTTP error 500: internal")}
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, nil, svc)
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -90,7 +90,7 @@ func TestSessionsSearch_RendersFuzzyTime(t *testing.T) {
}},
total: 1,
}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, nil, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
body := out.String()
assert.Contains(t, body, "hour", "must render relative time (e.g. 'about 2 hours ago'), not raw RFC3339")
assert.NotContains(t, body, "T0", "raw RFC3339 has 'T' between date and time; fuzzyTime output should not")
@@ -111,7 +111,7 @@ func TestSearchSessions_AllPagesFlag_DefaultsTrue_WalksAllPages(t *testing.T) {
total: 3,
}
opts := &SessionsSearchOptions{Query: "needle", Limit: 100, PageSize: 2, AllPages: true}
require.NoError(t, runSessionsSearch(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runSessionsSearch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.GreaterOrEqual(t, len(svc.calls), 2, "must walk multi pages by default")
}
@@ -125,16 +125,16 @@ func TestSearchSessions_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
total: 100,
}
opts := &SessionsSearchOptions{Query: "needle", Limit: 100, PageSize: 2, AllPages: false}
require.NoError(t, runSessionsSearch(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
require.NoError(t, runSessionsSearch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Len(t, svc.calls, 1, "must stop at first page when --all-pages=false")
}
// TestSearchSessions_PageSizeBound asserts the 1..1000 range guard mirrors
// the session/doc list canon. Out-of-range values must produce
// the session/doc list cap. Out-of-range values must produce
// input.invalid_argument and never reach the SDK.
func TestSearchSessions_PageSizeBound(t *testing.T) {
for _, ps := range []int{0, -1, 1001} {
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "t", Limit: 50, PageSize: ps}, &cmdutil.JSONOptions{}, &fakeSessionsSearchSvc{})
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "t", Limit: 50, PageSize: ps}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeSessionsSearchSvc{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)