feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
This commit is contained in:
+24
-8
@@ -14,11 +14,23 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// kbCreateFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb create`. The result is the full KnowledgeBase struct; these mirror its
|
||||
// top-level json tags. Nested config objects are intentionally omitted —
|
||||
// users wanting them can drop --json (no filter) or use --jq.
|
||||
var kbCreateFields = []string{
|
||||
"id", "name", "type", "description",
|
||||
"is_temporary", "is_pinned",
|
||||
"embedding_model_id", "summary_model_id",
|
||||
"knowledge_count", "chunk_count",
|
||||
"is_processing", "processing_count",
|
||||
"created_at", "updated_at",
|
||||
}
|
||||
|
||||
type CreateOptions struct {
|
||||
Name string
|
||||
Description string
|
||||
EmbeddingModel string
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
@@ -36,26 +48,30 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
|
||||
Short: "Create a new knowledge base",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runCreate(c.Context(), opts, nil) // service unused on dry-run
|
||||
return runCreate(c.Context(), opts, jopts, nil) // service unused on dry-run
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runCreate(c.Context(), opts, cli)
|
||||
return runCreate(c.Context(), opts, jopts, cli)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Knowledge base name (required)")
|
||||
cmd.Flags().StringVar(&opts.Description, "description", "", "Knowledge base description (optional)")
|
||||
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)")
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, kbCreateFields)
|
||||
agent.SetAgentHelp(cmd, "Creates a knowledge base under the active context. --name is required; --description and --embedding-model are optional. Returns data: full KnowledgeBase object including the new id.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runCreate(ctx context.Context, opts *CreateOptions, svc CreateService) error {
|
||||
func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOptions, svc CreateService) error {
|
||||
// Validate locally before any HTTP — keeps `input.invalid_argument`
|
||||
// distinct from a server-side 400.
|
||||
if strings.TrimSpace(opts.Name) == "" {
|
||||
@@ -71,7 +87,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, svc CreateService) erro
|
||||
}
|
||||
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(opts.JSONOut, req, nil,
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(), req, nil,
|
||||
&format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("create knowledge base %q", opts.Name)})
|
||||
}
|
||||
|
||||
@@ -80,9 +96,9 @@ func runCreate(ctx context.Context, opts *CreateOptions, svc CreateService) erro
|
||||
return cmdutil.WrapHTTP(err, "create knowledge base")
|
||||
}
|
||||
|
||||
if opts.JSONOut {
|
||||
if jopts.Enabled() {
|
||||
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("created knowledge base %s", created.ID)}
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(created, &format.Meta{KBID: created.ID}, risk))
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(created, &format.Meta{KBID: created.ID}, risk), jopts.Fields, jopts.JQ)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)
|
||||
return nil
|
||||
|
||||
@@ -39,7 +39,7 @@ func TestCreate_Success_Human(t *testing.T) {
|
||||
Description: "team docs",
|
||||
EmbeddingModel: "model_x",
|
||||
}
|
||||
require.NoError(t, runCreate(context.Background(), opts, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, nil, svc))
|
||||
|
||||
// Body sent to SDK matches flags.
|
||||
require.NotNil(t, svc.got)
|
||||
@@ -59,7 +59,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_x", Name: "n"}}
|
||||
opts := &CreateOptions{Name: "n"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, nil, svc))
|
||||
|
||||
require.NotNil(t, svc.got)
|
||||
assert.Equal(t, "", svc.got.EmbeddingModelID, "embedding-model unset ⇒ empty in request")
|
||||
@@ -68,7 +68,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
|
||||
func TestCreate_NameRequired(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
err := runCreate(context.Background(), &CreateOptions{}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{}, nil, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -80,7 +80,7 @@ func TestCreate_NameRequired(t *testing.T) {
|
||||
func TestCreate_NameWhitespaceOnly(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: " "}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: " "}, nil, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -91,7 +91,7 @@ func TestCreate_NameWhitespaceOnly(t *testing.T) {
|
||||
func TestCreate_HTTPError_500(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal")}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, nil, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -102,7 +102,7 @@ func TestCreate_HTTPError_500(t *testing.T) {
|
||||
func TestCreate_HTTPError_409Conflict(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{err: errors.New("HTTP error 409: name exists")}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, nil, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -113,8 +113,8 @@ func TestCreate_HTTPError_409Conflict(t *testing.T) {
|
||||
func TestCreate_JSONOutput(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_99", Name: "Eng"}}
|
||||
opts := &CreateOptions{Name: "Eng", JSONOut: true}
|
||||
require.NoError(t, runCreate(context.Background(), opts, svc))
|
||||
opts := &CreateOptions{Name: "Eng"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
|
||||
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)
|
||||
|
||||
+18
-11
@@ -13,10 +13,13 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
)
|
||||
|
||||
// kbDeleteFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb delete`. The result payload is a small {id, deleted} object.
|
||||
var kbDeleteFields = []string{"id", "deleted"}
|
||||
|
||||
type DeleteOptions struct {
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go addGlobalFlags)
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go addGlobalFlags)
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// DeleteService is the narrow SDK surface this command depends on.
|
||||
@@ -53,31 +56,35 @@ guard against unintended deletes.`,
|
||||
weknora kb delete kb_abc -y --json # envelope output`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runDelete(c.Context(), opts, nil, f.Prompter(), args[0])
|
||||
return runDelete(c.Context(), opts, jopts, nil, f.Prompter(), args[0])
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runDelete(c.Context(), opts, cli, f.Prompter(), args[0])
|
||||
return runDelete(c.Context(), opts, jopts, cli, f.Prompter(), args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, kbDeleteFields)
|
||||
agent.SetAgentHelp(cmd, "Destructively deletes a knowledge base by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p prompt.Prompter, id string) error {
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOptions, svc DeleteService, p prompt.Prompter, id string) error {
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(opts.JSONOut,
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(),
|
||||
deleteResult{ID: id, Deleted: false}, &format.Meta{KBID: id},
|
||||
&format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("delete knowledge base %s", id)})
|
||||
}
|
||||
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "knowledge base", id); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "knowledge base", id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -85,9 +92,9 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr
|
||||
return cmdutil.WrapHTTP(err, "delete knowledge base %s", id)
|
||||
}
|
||||
|
||||
if opts.JSONOut {
|
||||
if jopts.Enabled() {
|
||||
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("deleted knowledge base %s", id)}
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(deleteResult{ID: id, Deleted: true}, &format.Meta{KBID: id}, risk))
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(deleteResult{ID: id, Deleted: true}, &format.Meta{KBID: id}, risk), jopts.Fields, jopts.JQ)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted knowledge base %s\n", id)
|
||||
return nil
|
||||
|
||||
+12
-12
@@ -46,7 +46,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, svc, p, "kb_force"))
|
||||
require.NoError(t, runDelete(context.Background(), opts, nil, svc, p, "kb_force"))
|
||||
|
||||
assert.True(t, svc.called)
|
||||
assert.Equal(t, "kb_force", svc.gotID)
|
||||
@@ -59,7 +59,7 @@ func TestDelete_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
|
||||
p := &confirmPrompter{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, svc, p, "kb_missing")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, p, "kb_missing")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -74,7 +74,7 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, svc, p, "kb_nontty")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_nontty")
|
||||
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -89,8 +89,8 @@ func TestDelete_JSONOutput(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: true, JSONOut: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, svc, p, "kb_json"))
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_json"))
|
||||
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)
|
||||
@@ -106,7 +106,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{answer: true}
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, svc, p, "kb_yes"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_yes"))
|
||||
|
||||
assert.True(t, p.asked, "confirm prompt should fire on TTY without --force")
|
||||
assert.True(t, svc.called, "answer=yes ⇒ delete proceeds")
|
||||
@@ -117,7 +117,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{answer: false}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, svc, p, "kb_no")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_no")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -132,7 +132,7 @@ func TestDelete_ConfirmPrompterError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{err: prompt.ErrAgentNoPrompt}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, svc, p, "kb_err")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_err")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
@@ -148,8 +148,8 @@ func TestDelete_JSONOut_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
opts := &DeleteOptions{JSONOut: true}
|
||||
err := runDelete(context.Background(), opts, svc, p, "kb_jtty")
|
||||
opts := &DeleteOptions{}
|
||||
err := runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_jtty")
|
||||
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -166,8 +166,8 @@ func TestDelete_JSONOut_WithYes_Proceeds(t *testing.T) {
|
||||
out, _ := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &confirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: true, JSONOut: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, svc, p, "kb_jtty"))
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_jtty"))
|
||||
|
||||
assert.False(t, p.asked, "-y must skip the prompt")
|
||||
assert.True(t, svc.called)
|
||||
|
||||
+23
-8
@@ -13,6 +13,18 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// kbEditFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb edit`. The result is the updated KnowledgeBase; mirrors the kb
|
||||
// top-level json tags.
|
||||
var kbEditFields = []string{
|
||||
"id", "name", "type", "description",
|
||||
"is_temporary", "is_pinned",
|
||||
"embedding_model_id", "summary_model_id",
|
||||
"knowledge_count", "chunk_count",
|
||||
"is_processing", "processing_count",
|
||||
"created_at", "updated_at",
|
||||
}
|
||||
|
||||
type EditOptions struct {
|
||||
// Name/Description are *string so we can distinguish "unset" from "set to
|
||||
// empty". An unset field is omitted from the SDK request — only fields the
|
||||
@@ -21,7 +33,6 @@ type EditOptions struct {
|
||||
// clear the description.
|
||||
Name *string
|
||||
Description *string
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
@@ -45,6 +56,10 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
Short: "Edit a knowledge base's name or description",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Flag("name").Changed {
|
||||
opts.Name = &name
|
||||
}
|
||||
@@ -53,23 +68,23 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
}
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runEdit(c.Context(), opts, nil, args[0])
|
||||
return runEdit(c.Context(), opts, jopts, nil, args[0])
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runEdit(c.Context(), opts, cli, args[0])
|
||||
return runEdit(c.Context(), opts, jopts, cli, args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&name, "name", "", "New name (omit to leave unchanged)")
|
||||
cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)")
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, kbEditFields)
|
||||
agent.SetAgentHelp(cmd, "Edits a knowledge base. At least one of --name/--description is required. Fields not passed are preserved server-side. Returns the updated KnowledgeBase.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runEdit(ctx context.Context, opts *EditOptions, svc EditService, id string) error {
|
||||
func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions, svc EditService, id string) error {
|
||||
if opts.Name == nil && opts.Description == nil {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputMissingFlag,
|
||||
@@ -89,7 +104,7 @@ func runEdit(ctx context.Context, opts *EditOptions, svc EditService, id string)
|
||||
if opts.Description != nil {
|
||||
preview.Description = *opts.Description
|
||||
}
|
||||
return cmdutil.EmitDryRun(opts.JSONOut, preview, &format.Meta{KBID: id}, risk)
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(), preview, &format.Meta{KBID: id}, risk)
|
||||
}
|
||||
|
||||
// Fetch current state so we can fill in fields the user didn't touch.
|
||||
@@ -114,8 +129,8 @@ func runEdit(ctx context.Context, opts *EditOptions, svc EditService, id string)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "edit knowledge base %s", id)
|
||||
}
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk))
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk), jopts.Fields, jopts.JQ)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Updated knowledge base %s\n", id)
|
||||
return nil
|
||||
|
||||
@@ -44,7 +44,7 @@ func (f *fakeEditSvc) UpdateKnowledgeBase(_ context.Context, id string, req *sdk
|
||||
func TestEdit_RequiresAtLeastOneFlag(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{}
|
||||
err := runEdit(context.Background(), &EditOptions{}, svc, "kb_abc")
|
||||
err := runEdit(context.Background(), &EditOptions{}, nil, svc, "kb_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -65,7 +65,7 @@ func TestEdit_OnlyName_PreservesCurrentDescription(t *testing.T) {
|
||||
}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("new")
|
||||
require.NoError(t, runEdit(context.Background(), opts, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, nil, svc, "kb_abc"))
|
||||
|
||||
assert.Equal(t, "kb_abc", svc.gotID)
|
||||
require.NotNil(t, svc.gotReq)
|
||||
@@ -84,7 +84,7 @@ func TestEdit_OnlyDescription_PreservesCurrentName(t *testing.T) {
|
||||
}
|
||||
opts := &EditOptions{}
|
||||
opts.Description = stringPtr("new desc")
|
||||
require.NoError(t, runEdit(context.Background(), opts, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, nil, svc, "kb_abc"))
|
||||
|
||||
require.NotNil(t, svc.gotReq)
|
||||
assert.Equal(t, "new desc", svc.gotReq.Description)
|
||||
@@ -97,16 +97,16 @@ func TestEdit_BothFlags(t *testing.T) {
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("renamed")
|
||||
opts.Description = stringPtr("new desc")
|
||||
require.NoError(t, runEdit(context.Background(), opts, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, nil, svc, "kb_abc"))
|
||||
assert.Equal(t, "renamed", svc.gotReq.Name)
|
||||
assert.Equal(t, "new desc", svc.gotReq.Description)
|
||||
}
|
||||
|
||||
func TestEdit_DryRun_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
opts := &EditOptions{DryRun: true, JSONOut: true}
|
||||
opts := &EditOptions{DryRun: true}
|
||||
opts.Name = stringPtr("preview")
|
||||
require.NoError(t, runEdit(context.Background(), opts, nil, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, nil, "kb_abc"))
|
||||
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
|
||||
@@ -121,7 +121,7 @@ func TestEdit_NotFound(t *testing.T) {
|
||||
svc := &fakeEditSvc{currentErr: errors.New("HTTP error 404: not found")}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("x")
|
||||
err := runEdit(context.Background(), opts, svc, "kb_missing")
|
||||
err := runEdit(context.Background(), opts, nil, svc, "kb_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
+19
-12
@@ -14,10 +14,13 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// kbEmptyFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb empty`. The result payload is {id, deleted_count}.
|
||||
var kbEmptyFields = []string{"id", "deleted_count"}
|
||||
|
||||
type EmptyOptions struct {
|
||||
Yes bool
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
Yes bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
type EmptyService interface {
|
||||
@@ -49,31 +52,35 @@ piped contexts. Without -y the CLI exits 10 in non-interactive mode.`,
|
||||
weknora kb empty kb_abc -y --json # agent-friendly`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runEmpty(c.Context(), opts, nil, f.Prompter(), args[0])
|
||||
return runEmpty(c.Context(), opts, jopts, nil, f.Prompter(), args[0])
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runEmpty(c.Context(), opts, cli, f.Prompter(), args[0])
|
||||
return runEmpty(c.Context(), opts, jopts, cli, f.Prompter(), args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, kbEmptyFields)
|
||||
agent.SetAgentHelp(cmd, "Destructively empties a knowledge base (deletes all documents, preserves the KB record + config). ALWAYS pass -y/--yes in agent mode (non-TTY ⇒ confirm fails). Returns data: {id, deleted_count}. Async — items may still be processing server-side after the call returns.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runEmpty(ctx context.Context, opts *EmptyOptions, svc EmptyService, p prompt.Prompter, id string) error {
|
||||
func runEmpty(ctx context.Context, opts *EmptyOptions, jopts *cmdutil.JSONOptions, svc EmptyService, p prompt.Prompter, id string) error {
|
||||
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("empty knowledge base %s", id)}
|
||||
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(opts.JSONOut, emptyResult{ID: id}, &format.Meta{KBID: id}, risk)
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(), emptyResult{ID: id}, &format.Meta{KBID: id}, risk)
|
||||
}
|
||||
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "all contents of knowledge base", id); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "all contents of knowledge base", id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -86,10 +93,10 @@ func runEmpty(ctx context.Context, opts *EmptyOptions, svc EmptyService, p promp
|
||||
deleted = resp.DeletedCount
|
||||
}
|
||||
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(
|
||||
emptyResult{ID: id, DeletedCount: deleted}, &format.Meta{KBID: id}, risk,
|
||||
))
|
||||
), jopts.Fields, jopts.JQ)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Emptied knowledge base %s (%d document(s) cleared)\n", id, deleted)
|
||||
return nil
|
||||
|
||||
@@ -38,7 +38,7 @@ func (f *fakeEmptySvc) ClearKnowledgeBaseContents(_ context.Context, id string)
|
||||
func TestEmpty_WithYes(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeEmptySvc{resp: &sdk.ClearKnowledgeBaseContentsResponse{DeletedCount: 42}}
|
||||
require.NoError(t, runEmpty(context.Background(), &EmptyOptions{Yes: true}, svc, &testutil.ConfirmPrompter{}, "kb_abc"))
|
||||
require.NoError(t, runEmpty(context.Background(), &EmptyOptions{Yes: true}, nil, svc, &testutil.ConfirmPrompter{}, "kb_abc"))
|
||||
assert.True(t, svc.called)
|
||||
assert.Equal(t, "kb_abc", svc.gotID)
|
||||
body := out.String()
|
||||
@@ -49,7 +49,7 @@ func TestEmpty_WithYes(t *testing.T) {
|
||||
func TestEmpty_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeEmptySvc{}
|
||||
err := runEmpty(context.Background(), &EmptyOptions{}, svc, &testutil.ConfirmPrompter{}, "kb_abc")
|
||||
err := runEmpty(context.Background(), &EmptyOptions{}, nil, svc, &testutil.ConfirmPrompter{}, "kb_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -62,7 +62,7 @@ func TestEmpty_TTY_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeEmptySvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runEmpty(context.Background(), &EmptyOptions{}, svc, p, "kb_abc")
|
||||
err := runEmpty(context.Background(), &EmptyOptions{}, nil, svc, p, "kb_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -74,7 +74,7 @@ func TestEmpty_TTY_ConfirmNo(t *testing.T) {
|
||||
func TestEmpty_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEmptySvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runEmpty(context.Background(), &EmptyOptions{Yes: true}, svc, &testutil.ConfirmPrompter{}, "kb_missing")
|
||||
err := runEmpty(context.Background(), &EmptyOptions{Yes: true}, nil, svc, &testutil.ConfirmPrompter{}, "kb_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -84,7 +84,7 @@ func TestEmpty_NotFound(t *testing.T) {
|
||||
func TestEmpty_DryRun_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeEmptySvc{}
|
||||
require.NoError(t, runEmpty(context.Background(), &EmptyOptions{DryRun: true, JSONOut: true}, svc, &testutil.ConfirmPrompter{}, "kb_dry"))
|
||||
require.NoError(t, runEmpty(context.Background(), &EmptyOptions{DryRun: true}, &cmdutil.JSONOptions{}, svc, &testutil.ConfirmPrompter{}, "kb_dry"))
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
|
||||
assert.Contains(t, body, `"dry_run":true`)
|
||||
|
||||
+25
-9
@@ -17,8 +17,17 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type ListOptions struct {
|
||||
JSONOut bool
|
||||
// kbListFields enumerates the fields surfaced for `--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 envelope.
|
||||
var kbListFields = []string{
|
||||
"id", "name", "type", "description",
|
||||
"is_temporary", "is_pinned",
|
||||
"embedding_model_id", "summary_model_id",
|
||||
"knowledge_count", "chunk_count",
|
||||
"is_processing", "processing_count",
|
||||
"created_at", "updated_at",
|
||||
}
|
||||
|
||||
// ListService is the narrow SDK surface this command depends on.
|
||||
@@ -33,25 +42,28 @@ type listResult struct {
|
||||
|
||||
// NewCmdList builds `weknora kb list`.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &ListOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List knowledge bases visible to the active context",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runList(c.Context(), opts, cli)
|
||||
return runList(c.Context(), jopts, cli)
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
agent.SetAgentHelp(cmd, "Lists all knowledge bases. Returns data.items: [{id, name, ...}]; empty array when none.")
|
||||
cmdutil.AddJSONFlags(cmd, kbListFields)
|
||||
agent.SetAgentHelp(cmd, "Lists all knowledge bases. Returns data.items: [{id, name, ...}]; empty array when none. Use `--json` (bare) for the field list, `--json id,name` to project, or `--jq` for arbitrary reshape.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
|
||||
func runList(ctx context.Context, jopts *cmdutil.JSONOptions, svc ListService) error {
|
||||
items, err := svc.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list knowledge bases")
|
||||
@@ -66,8 +78,12 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
|
||||
return items[i].UpdatedAt.After(items[j].UpdatedAt)
|
||||
})
|
||||
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.Success(listResult{Items: items}, nil))
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(
|
||||
iostreams.IO.Out,
|
||||
format.Success(listResult{Items: items}, nil),
|
||||
jopts.Fields, jopts.JQ,
|
||||
)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
+53
-3
@@ -2,10 +2,12 @@ package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
@@ -21,7 +23,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{}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
if err := runList(context.Background(), nil, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no knowledge bases)") {
|
||||
@@ -31,7 +33,8 @@ func TestList_Empty_Human(t *testing.T) {
|
||||
|
||||
func TestList_Empty_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{JSONOut: true}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
jopts := &cmdutil.JSONOptions{}
|
||||
if err := runList(context.Background(), jopts, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -50,7 +53,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{}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), nil, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -60,3 +63,50 @@ func TestList_NonEmpty_Human_RenderColumns(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_JSON_FieldFilter(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(), jopts, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, out.String())
|
||||
}
|
||||
if len(env.Data.Items) != 1 {
|
||||
t.Fatalf("expected 1 item, got %d", len(env.Data.Items))
|
||||
}
|
||||
item := env.Data.Items[0]
|
||||
if item["id"] != "kb1" || item["name"] != "Marketing" {
|
||||
t.Errorf("kept fields wrong: %+v", item)
|
||||
}
|
||||
if _, has := item["description"]; has {
|
||||
t.Errorf("description should be dropped, got: %+v", item)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_JSON_JQ(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
now := time.Now()
|
||||
items := []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "Marketing", UpdatedAt: now},
|
||||
{ID: "kb2", Name: "Engineering", UpdatedAt: now.Add(-time.Hour)},
|
||||
}
|
||||
jopts := &cmdutil.JSONOptions{JQ: ".data.items | length"}
|
||||
if err := runList(context.Background(), jopts, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(out.String()); got != "2" {
|
||||
t.Errorf("expected '2', got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
+19
-11
@@ -13,9 +13,13 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// kbPinFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb pin` / `kb unpin`. The toggle result is the KnowledgeBase; the user-
|
||||
// relevant fields here are the id and the new pin state.
|
||||
var kbPinFields = []string{"id", "is_pinned"}
|
||||
|
||||
type PinOptions struct {
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// PinService is the narrow SDK surface this command depends on. The CLI
|
||||
@@ -43,23 +47,27 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C
|
||||
Short: short,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runPin(c.Context(), opts, nil, args[0], want)
|
||||
return runPin(c.Context(), opts, jopts, nil, args[0], want)
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runPin(c.Context(), opts, cli, args[0], want)
|
||||
return runPin(c.Context(), opts, jopts, cli, args[0], want)
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, kbPinFields)
|
||||
agent.SetAgentHelp(cmd, fmt.Sprintf("Idempotent %s: reads current pin state, toggles only if different. No-op when already in the requested state.", use))
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, want bool) error {
|
||||
func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, svc PinService, id string, want bool) error {
|
||||
verb := "pin"
|
||||
if !want {
|
||||
verb = "unpin"
|
||||
@@ -70,7 +78,7 @@ func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, wa
|
||||
// Dry-run can't introspect state without a network call by design (see
|
||||
// kb/delete.go for the same convention). Report what *would* run if
|
||||
// state diverged; agents can disambiguate via a subsequent `kb view`.
|
||||
return cmdutil.EmitDryRun(opts.JSONOut, struct {
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(), struct {
|
||||
ID string `json:"id"`
|
||||
Want bool `json:"want_pinned"`
|
||||
}{id, want}, &format.Meta{KBID: id}, risk)
|
||||
@@ -88,9 +96,9 @@ func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, wa
|
||||
// No-op path: tell agents what happened. The risk-write classification
|
||||
// was the *requested* operation, not what occurred — surface it via a
|
||||
// _meta.warning so audit logs don't count a write that wasn't made.
|
||||
if opts.JSONOut {
|
||||
if jopts.Enabled() {
|
||||
meta := &format.Meta{KBID: id, Warnings: []string{fmt.Sprintf("already %s — no server call made", state)}}
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.Success(current, meta))
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.Success(current, meta), jopts.Fields, jopts.JQ)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ %s is already %s\n", id, state)
|
||||
return nil
|
||||
@@ -100,8 +108,8 @@ func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, wa
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "%s knowledge base %s", verb, id)
|
||||
}
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk))
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk), jopts.Fields, jopts.JQ)
|
||||
}
|
||||
state := "pinned"
|
||||
if !updated.IsPinned {
|
||||
|
||||
@@ -44,7 +44,7 @@ func (f *fakePinSvc) TogglePinKnowledgeBase(_ context.Context, id string) (*sdk.
|
||||
func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, svc, "kb_abc", true))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, nil, svc, "kb_abc", true))
|
||||
assert.True(t, svc.toggleCalled, "must call toggle when current state differs")
|
||||
assert.Contains(t, out.String(), "kb_abc")
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
|
||||
func TestPin_AlreadyPinned_NoOp(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, svc, "kb_abc", true))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, nil, svc, "kb_abc", true))
|
||||
assert.False(t, svc.toggleCalled, "already pinned ⇒ must not call toggle")
|
||||
assert.Contains(t, out.String(), "already pinned")
|
||||
}
|
||||
@@ -60,14 +60,14 @@ func TestPin_AlreadyPinned_NoOp(t *testing.T) {
|
||||
func TestUnpin_PinnedToUnpinned_CallsToggle(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, svc, "kb_abc", false))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, nil, svc, "kb_abc", false))
|
||||
assert.True(t, svc.toggleCalled)
|
||||
}
|
||||
|
||||
func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, svc, "kb_abc", false))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, nil, svc, "kb_abc", false))
|
||||
assert.False(t, svc.toggleCalled, "already unpinned ⇒ must not call toggle")
|
||||
assert.Contains(t, out.String(), "already unpinned")
|
||||
}
|
||||
@@ -75,7 +75,7 @@ func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
|
||||
func TestPin_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{getErr: errors.New("HTTP error 404: not found")}
|
||||
err := runPin(context.Background(), &PinOptions{}, svc, "kb_missing", true)
|
||||
err := runPin(context.Background(), &PinOptions{}, nil, svc, "kb_missing", true)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -89,7 +89,7 @@ func TestPin_ToggleError(t *testing.T) {
|
||||
current: sdk.KnowledgeBase{IsPinned: false},
|
||||
toggleErr: errors.New("HTTP error 500: internal"),
|
||||
}
|
||||
err := runPin(context.Background(), &PinOptions{}, svc, "kb_abc", true)
|
||||
err := runPin(context.Background(), &PinOptions{}, nil, svc, "kb_abc", true)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -99,7 +99,7 @@ func TestPin_ToggleError(t *testing.T) {
|
||||
func TestPin_DryRun_StateDiffers(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{DryRun: true, JSONOut: true}, svc, "kb_abc", true))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{DryRun: true}, &cmdutil.JSONOptions{}, svc, "kb_abc", true))
|
||||
assert.False(t, svc.toggleCalled, "dry-run must not call toggle")
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"dry_run":true`)
|
||||
@@ -109,7 +109,7 @@ func TestPin_DryRun_StateDiffers(t *testing.T) {
|
||||
func TestPin_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{JSONOut: true}, svc, "kb_abc", true))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.JSONOptions{}, svc, "kb_abc", true))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"is_pinned":true`)
|
||||
assert.Contains(t, body, `"id":"kb_abc"`)
|
||||
|
||||
+21
-7
@@ -14,10 +14,20 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type ViewOptions struct {
|
||||
JSONOut bool
|
||||
// kbViewFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `kb view`. Lists the KnowledgeBase top-level json tags; nested config
|
||||
// structs are omitted (use --jq for those).
|
||||
var kbViewFields = []string{
|
||||
"id", "name", "type", "description",
|
||||
"is_temporary", "is_pinned",
|
||||
"embedding_model_id", "summary_model_id",
|
||||
"knowledge_count", "chunk_count",
|
||||
"is_processing", "processing_count",
|
||||
"created_at", "updated_at",
|
||||
}
|
||||
|
||||
type ViewOptions struct{}
|
||||
|
||||
// ViewService is the narrow SDK surface this command depends on.
|
||||
type ViewService interface {
|
||||
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
|
||||
@@ -31,25 +41,29 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
|
||||
Short: "Show a knowledge base by ID",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runView(c.Context(), opts, cli, args[0])
|
||||
return runView(c.Context(), opts, jopts, cli, args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, kbViewFields)
|
||||
agent.SetAgentHelp(cmd, "Returns details of one knowledge base by ID (config + counts).")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error {
|
||||
func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions, svc ViewService, id string) error {
|
||||
kb, err := svc.GetKnowledgeBase(ctx, id)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "get knowledge base %q", id)
|
||||
}
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.Success(kb, nil))
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.Success(kb, nil), jopts.Fields, jopts.JQ)
|
||||
}
|
||||
// Human: KEY: VALUE
|
||||
w := iostreams.IO.Out
|
||||
|
||||
@@ -25,7 +25,7 @@ func TestGet_OK_Human(t *testing.T) {
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{
|
||||
ID: "kb1", Name: "Marketing", KnowledgeCount: 12, ChunkCount: 245,
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runGet: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -39,7 +39,7 @@ func TestGet_OK_Human(t *testing.T) {
|
||||
func TestGet_OK_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Marketing"}}
|
||||
if err := runView(context.Background(), &ViewOptions{JSONOut: true}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.JSONOptions{}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runGet: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -54,7 +54,7 @@ func TestGet_OK_JSON(t *testing.T) {
|
||||
func TestGet_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runView(context.Background(), &ViewOptions{}, svc, "missing")
|
||||
err := runView(context.Background(), &ViewOptions{}, nil, svc, "missing")
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user