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
+13 -7
View File
@@ -15,7 +15,7 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// kbListFields enumerates the fields surfaced for `--json` discovery on
// kbListFields enumerates the fields surfaced for `--format json` discovery on
// `kb list`. Nested config structs (chunking / image / FAQ / VLM / storage
// / extract) are intentionally omitted - users wanting those can use `--jq`
// against the full object.
@@ -51,24 +51,30 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
Long: `List knowledge bases visible to the active context, sorted by most recently updated. Pass --pinned to restrict to pinned KBs.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
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 runList(c.Context(), opts, jopts, cli)
return runList(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().BoolVar(&opts.Pinned, "pinned", false, "Only show pinned knowledge bases")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
cmdutil.AddJSONFlags(cmd, kbListFields)
cmdutil.AddFormatFlag(cmd, kbListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List knowledge bases in the current tenant. Agents should use --format json to consume a stable {data, total, page, page_size} response.",
Examples: []string{"weknora kb list --format json"},
Output: "array of KnowledgeBase objects with id, name, is_pinned, type, embedding_model_id",
})
return cmd
}
func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions, svc ListService) error {
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
if opts.Limit < 0 || opts.Limit > 10000 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
@@ -102,8 +108,8 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
items = items[:opts.Limit]
}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, items)
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, items)
}
if len(items) == 0 {
+19 -22
View File
@@ -25,7 +25,7 @@ func (f *fakeListSvc) ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBa
func TestList_Empty_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{}, nil, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no knowledge bases)") {
@@ -35,8 +35,8 @@ func TestList_Empty_Human(t *testing.T) {
func TestList_Empty_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
jopts := &cmdutil.JSONOptions{}
if err := runList(context.Background(), &ListOptions{}, jopts, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
t.Fatalf("runList: %v", err)
}
got := strings.TrimSpace(out.String())
@@ -52,7 +52,7 @@ func TestList_NonEmpty_Human_RenderColumns(t *testing.T) {
{ID: "kb1", Name: "Marketing", KnowledgeCount: 5, UpdatedAt: now.Add(-3 * time.Hour)},
{ID: "kb2", Name: "Engineering", KnowledgeCount: 1, UpdatedAt: now.Add(-2 * 24 * time.Hour)},
}
if err := runList(context.Background(), &ListOptions{}, nil, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
@@ -63,24 +63,21 @@ func TestList_NonEmpty_Human_RenderColumns(t *testing.T) {
}
}
func TestList_JSON_FieldFilter(t *testing.T) {
func TestList_JSON_JQProjection(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.KnowledgeBase{
{ID: "kb1", Name: "Marketing", Description: "MKT desc", UpdatedAt: now},
}
jopts := &cmdutil.JSONOptions{Fields: []string{"id", "name"}}
if err := runList(context.Background(), &ListOptions{}, jopts, &fakeListSvc{items: items}); err != nil {
// --jq is the canonical projection mechanism in v0.6+.
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".[] | {id, name}"}
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
var got []map[string]any
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
var item map[string]any
if err := json.Unmarshal(out.Bytes(), &item); err != nil {
t.Fatalf("parse: %v\n%s", err, out.String())
}
if len(got) != 1 {
t.Fatalf("expected 1 item, got %d", len(got))
}
item := got[0]
if item["id"] != "kb1" || item["name"] != "Marketing" {
t.Errorf("kept fields wrong: %+v", item)
}
@@ -96,8 +93,8 @@ func TestList_JSON_JQ(t *testing.T) {
{ID: "kb1", Name: "Marketing", UpdatedAt: now},
{ID: "kb2", Name: "Engineering", UpdatedAt: now.Add(-time.Hour)},
}
jopts := &cmdutil.JSONOptions{JQ: ". | length"}
if err := runList(context.Background(), &ListOptions{}, jopts, &fakeListSvc{items: items}); err != nil {
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ". | length"}
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
if got := strings.TrimSpace(out.String()); got != "2" {
@@ -113,7 +110,7 @@ func TestList_PinnedFilter(t *testing.T) {
{ID: "kb2", Name: "Engineering", IsPinned: false, UpdatedAt: now.Add(-time.Hour)},
{ID: "kb3", Name: "Finance", IsPinned: true, UpdatedAt: now.Add(-2 * time.Hour)},
}
if err := runList(context.Background(), &ListOptions{Pinned: true}, nil, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Pinned: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
@@ -130,7 +127,7 @@ func TestList_PinnedFilter_NoPinned_HumanMessage(t *testing.T) {
items := []sdk.KnowledgeBase{
{ID: "kb1", Name: "Marketing", IsPinned: false, UpdatedAt: time.Now()},
}
if err := runList(context.Background(), &ListOptions{Pinned: true}, nil, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Pinned: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no pinned knowledge bases)") {
@@ -155,8 +152,8 @@ func makeKBs(n int) []sdk.KnowledgeBase {
func TestList_Limit_CapsResults(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{items: makeKBs(20)}
jopts := &cmdutil.JSONOptions{}
if err := runList(context.Background(), &ListOptions{Limit: 5}, jopts, svc); err != nil {
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runList(context.Background(), &ListOptions{Limit: 5}, fopts, svc); err != nil {
t.Fatalf("runList: %v", err)
}
got := strings.Count(out.String(), `"id":"kb_`)
@@ -168,8 +165,8 @@ func TestList_Limit_CapsResults(t *testing.T) {
func TestList_Limit_Zero_NoCap(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{items: makeKBs(7)}
jopts := &cmdutil.JSONOptions{}
if err := runList(context.Background(), &ListOptions{Limit: 0}, jopts, svc); err != nil {
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runList(context.Background(), &ListOptions{Limit: 0}, fopts, svc); err != nil {
t.Fatalf("runList: %v", err)
}
got := strings.Count(out.String(), `"id":"kb_`)
@@ -180,7 +177,7 @@ func TestList_Limit_Zero_NoCap(t *testing.T) {
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(), &ListOptions{Limit: -1}, nil, &fakeListSvc{items: makeKBs(3)})
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeKBs(3)})
if err == nil {
t.Fatal("expected error for negative --limit")
}