feat(cli): agent-first WeKnora CLI

The `weknora` command-line client for the WeKnora RAG server. Full command
surface: kb / doc / chunk / session / message / agent / model / search / chat /
auth / profile / link / api / mcp / skills / config / doctor / schema /
exit-codes.

Agent-first wire contract: JSON envelope by default, typed error codes mapped to
stable exit codes, error.retry_argv / retryable / partial-failure status,
global --dry-run preview, the exit-10 confirmation protocol for writes, and
control/ANSI/Bidi input hygiene. Stateless env-credential auth
(WEKNORA_API_KEY / WEKNORA_TOKEN + WEKNORA_HOST) for headless/CI/agent use.
A curated read-only MCP tool surface (`mcp serve`) and embedded Agent Skills
(`skills install`). Extensive unit + contract-golden tests and CI.
This commit is contained in:
nullkey
2026-06-26 20:40:59 +08:00
committed by lyingbug
parent 445a4330fa
commit 6f8b825f5f
151 changed files with 7305 additions and 733 deletions
+88
View File
@@ -0,0 +1,88 @@
package kb
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// kbConfigFields enumerates the fields surfaced for `--format json` discovery on
// `kb config`. Mirrors client.InitializationConfig.
var kbConfigFields = []string{
"chat_model_id", "embedding_model_id", "rerank_model_id", "multimodal_id",
}
// ConfigService is the narrow SDK surface this command depends on.
type ConfigService interface {
GetInitializationConfig(ctx context.Context, kbID string) (*sdk.InitializationConfig, error)
}
// NewCmdConfig builds `weknora kb config <kb-id>` — read-only inspection of a
// knowledge base's model configuration (set it with `weknora kb init`).
func NewCmdConfig(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "config <kb-id>",
Short: "Show a knowledge base's model configuration",
Long: `Show the model configuration bound to a knowledge base: chat, embedding,
rerank, and multimodal model ids. An empty embedding_model_id means the KB is
not yet usable for retrieval — configure it with 'weknora kb init'.`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
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 runConfig(c.Context(), fopts, cli, args[0])
},
}
cmdutil.AddFormatFlag(cmd, kbConfigFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "show a KB's model config (chat/embedding/rerank/multimodal model ids). Empty embedding_model_id => not retrieval-ready; run `weknora kb init`.",
RequiredFlags: []string{"<kb-id> (positional)"},
Examples: []string{"weknora kb config kb_abc --jq .data.embedding_model_id"},
Output: "envelope.data is {chat_model_id, embedding_model_id, rerank_model_id, multimodal_id}",
})
return cmd
}
func runConfig(ctx context.Context, fopts *cmdutil.FormatOptions, svc ConfigService, kbID string) error {
cfg, err := svc.GetInitializationConfig(ctx, kbID)
if err != nil {
return cmdutil.WrapHTTP(err, "get config for knowledge base %q", kbID)
}
if cfg == nil {
cfg = &sdk.InitializationConfig{}
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, cfg, nil)
}
w := iostreams.IO.Out
fmt.Fprintf(w, "%-11s %s\n", "EMBEDDING:", orNone(cfg.EmbeddingModelID))
fmt.Fprintf(w, "%-11s %s\n", "CHAT:", orNone(cfg.ChatModelID))
fmt.Fprintf(w, "%-11s %s\n", "RERANK:", orNone(cfg.RerankModelID))
fmt.Fprintf(w, "%-11s %s\n", "MULTIMODAL:", orNone(cfg.MultimodalID))
if cfg.EmbeddingModelID == "" {
fmt.Fprintln(w, "\n(no embedding model set — run `weknora kb init <kb-id> --embedding-model <id>`)")
}
return nil
}
func orNone(s string) string {
if s == "" {
return "(unset)"
}
return s
}
// compile-time check: the production SDK client implements ConfigService.
var _ ConfigService = (*sdk.Client)(nil)
+50
View File
@@ -0,0 +1,50 @@
package kb
import (
"context"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeConfigSvc struct {
cfg *sdk.InitializationConfig
err error
}
func (f *fakeConfigSvc) GetInitializationConfig(_ context.Context, _ string) (*sdk.InitializationConfig, error) {
return f.cfg, f.err
}
func TestKBConfig_EmitsConfig(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeConfigSvc{cfg: &sdk.InitializationConfig{EmbeddingModelID: "model_emb", ChatModelID: "model_chat"}}
require.NoError(t, runConfig(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_abc"))
var env struct {
OK bool `json:"ok"`
Data sdk.InitializationConfig `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.True(t, env.OK)
assert.Equal(t, "model_emb", env.Data.EmbeddingModelID)
assert.Equal(t, "model_chat", env.Data.ChatModelID)
}
// TestKBConfig_NilConfig: a nil server config (KB not yet initialized) emits an
// empty object, not a crash.
func TestKBConfig_NilConfig(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeConfigSvc{cfg: nil}
require.NoError(t, runConfig(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_abc"))
var env struct {
Data sdk.InitializationConfig `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.Empty(t, env.Data.EmbeddingModelID)
}
+28 -19
View File
@@ -3,7 +3,6 @@ package kb
import (
"context"
"fmt"
"slices"
"strings"
"github.com/spf13/cobra"
@@ -36,7 +35,7 @@ type CreateOptions struct {
// storageProviderValues mirrors the server enum in
// internal/types/knowledgebase.go:StorageProviderConfig.Provider.
var storageProviderValues = []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3"}
var storageProviderValues = []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3", "obs"}
// CreateService is the narrow SDK surface this command depends on.
// *sdk.Client satisfies it via duck typing.
@@ -60,16 +59,16 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Name = args[0]
// Validate --storage-provider enum before the dry-run gate so
// --dry-run rejects identically to the live path. Same typed
// FlagError as runCreate (kept there for direct-call callers).
if opts.StorageProvider != "" {
v := strings.ToLower(strings.TrimSpace(opts.StorageProvider))
if !slices.Contains(storageProviderValues, v) {
return cmdutil.NewFlagError(fmt.Errorf(
"invalid --storage-provider %q: must be %s",
opts.StorageProvider, strings.Join(storageProviderValues, " | ")))
}
// --dry-run rejects identically to the live path. ValidateEnum
// returns input.invalid_argument (exit 5) and normalizes to the
// canonical lowercase form — consistent with every other enum flag
// (model --type, agent --agent-mode, message search --mode).
// runCreate re-validates for direct-call callers.
canonSP, err := cmdutil.ValidateEnum("storage-provider", opts.StorageProvider, storageProviderValues)
if err != nil {
return err
}
opts.StorageProvider = canonSP
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
Action: "kb.create",
Args: map[string]any{
@@ -83,11 +82,18 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
if err != nil {
return err
}
// --embedding-model accepts a model id or name (a UUID passes
// through; a name resolves among Embedding models). Configuring a
// KB's models fully is `weknora kb init`; this just pre-sets the
// embedding model at creation.
if opts.EmbeddingModel, err = cmdutil.ResolveModelRef(c.Context(), cli, opts.EmbeddingModel, "Embedding"); err != nil {
return err
}
return runCreate(c.Context(), opts, fopts, cli)
},
}
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().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model id or name (optional; configure models fully with `weknora kb init`)")
cmd.Flags().StringVar(&opts.StorageProvider, "storage-provider", "",
"Storage provider for documents in this KB: "+strings.Join(storageProviderValues, " | ")+" (optional; server default when unset)")
cmdutil.AddFormatFlag(cmd, kbCreateFields...)
@@ -95,7 +101,12 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Create a new knowledge base with the given name. Emits the created KB object with its id.",
RequiredFlags: []string{"<name> (positional)"},
Output: "envelope.data is the created KnowledgeBase object with id, name, type, embedding_model_id",
Examples: []string{
`weknora kb create "Eng Docs"`,
`weknora kb create "Eng Docs" --description "engineering knowledge base"`,
`weknora kb create "Eng Docs" --jq .data.id # capture id to chain into doc upload --kb`,
},
Output: "envelope.data is the created KnowledgeBase object with id, name, type, embedding_model_id",
})
return cmd
}
@@ -115,13 +126,11 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
req.EmbeddingModelID = opts.EmbeddingModel
}
if opts.StorageProvider != "" {
v := strings.ToLower(strings.TrimSpace(opts.StorageProvider))
if !slices.Contains(storageProviderValues, v) {
return cmdutil.NewFlagError(fmt.Errorf(
"invalid --storage-provider %q: must be %s",
opts.StorageProvider, strings.Join(storageProviderValues, " | ")))
canonSP, err := cmdutil.ValidateEnum("storage-provider", opts.StorageProvider, storageProviderValues)
if err != nil {
return err
}
req.StorageProviderConfig = &sdk.StorageProviderConfig{Provider: v}
req.StorageProviderConfig = &sdk.StorageProviderConfig{Provider: canonSP}
}
created, err := svc.CreateKnowledgeBase(ctx, req)
+3 -3
View File
@@ -93,7 +93,7 @@ func TestKBCreate_DryRun_RejectsInvalidStorageProvider(t *testing.T) {
err := root.Execute()
require.Error(t, err, "dry-run must reject invalid --storage-provider")
// runCreate emits a FlagError (exit 2) for this — make sure dry-run preserves
// that exact mapping.
assert.Equal(t, 2, cmdutil.ExitCode(err), "FlagError must map to exit 2")
// The enum check returns input.invalid_argument (exit 5) — make sure the
// dry-run path preserves that exact mapping (same as the live path).
assert.Equal(t, 5, cmdutil.ExitCode(err), "invalid --storage-provider must map to exit 5")
}
+10 -4
View File
@@ -138,16 +138,22 @@ func TestCreate_StorageProvider_InjectsRequest(t *testing.T) {
assert.Equal(t, "local", svc.got.StorageProviderConfig.Provider, "value should be lowercased + trimmed before send")
}
func TestCreate_StorageProvider_InvalidValueReturnsFlagError(t *testing.T) {
func TestCreate_StorageProvider_InvalidValueReturnsInputError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
opts := &CreateOptions{Name: "n", StorageProvider: "azure"}
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
assert.Equal(t, 2, cmdutil.ExitCode(err), "invalid --storage-provider must exit 2 (flag validation)")
assert.Contains(t, err.Error(), "invalid --storage-provider")
assert.Nil(t, svc.got, "SDK must not be called when flag validation fails")
// A bad enum *value* (cobra accepted the string; the app rejected it) is an
// app-level input error → exit 5, consistent with every other enum flag
// (model --type, agent --agent-mode, message search --mode).
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
assert.Equal(t, 5, cmdutil.ExitCode(err), "invalid --storage-provider must exit 5 (app-level input validation)")
assert.Contains(t, err.Error(), "--storage-provider")
assert.Nil(t, svc.got, "SDK must not be called when input validation fails")
}
func TestCreate_StorageProvider_OmittedWhenEmpty(t *testing.T) {
+1 -1
View File
@@ -94,7 +94,7 @@ exactly to guard against unintended deletes.`,
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "knowledge base", id, "kb.delete", "weknora kb delete "+id+" -y"); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "knowledge base", id, "kb.delete", []string{"weknora", "kb", "delete", id, "-y"}); err != nil {
return err
}
+3 -3
View File
@@ -167,8 +167,8 @@ func TestDelete_JSONOut_WithYes_Proceeds(t *testing.T) {
func TestKbDelete_NoYes_JSONMode_AttachesRiskAndRetry(t *testing.T) {
// Non-TTY + JSON mode without -y must return CodeInputConfirmationRequired
// with risk.action == "kb.delete" and retry_command == "weknora kb delete kb_x -y".
// Regression test for H1: ConfirmDestructive must attach risk + retry_command.
// with risk.action == "kb.delete" and retry_argv == [weknora kb delete kb_x -y].
// Regression test for H1: ConfirmDestructive must attach risk + retry_argv.
iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
@@ -185,5 +185,5 @@ func TestKbDelete_NoYes_JSONMode_AttachesRiskAndRetry(t *testing.T) {
require.NotNil(t, ce.Risk, "expected risk metadata on confirmation_required error")
assert.Equal(t, "kb.delete", ce.Risk.Action, "expected risk.action == kb.delete")
assert.Equal(t, "destructive", ce.Risk.Level, "expected risk.level == destructive")
assert.Equal(t, "weknora kb delete kb_x -y", ce.RetryCommand, "expected retry_command")
assert.Equal(t, []string{"weknora", "kb", "delete", "kb_x", "-y"}, ce.RetryArgv, "expected retry_argv")
}
+17 -39
View File
@@ -3,10 +3,8 @@ package kb
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -14,7 +12,7 @@ import (
)
// kbEditFields enumerates the fields surfaced for `--format json` discovery on
// `kb edit`. The result is the updated KnowledgeBase; mirrors the kb
// `kb update`. The result is the updated KnowledgeBase; mirrors the kb
// top-level json tags.
var kbEditFields = []string{
"id", "name", "type", "description",
@@ -47,14 +45,14 @@ type EditService interface {
UpdateKnowledgeBase(ctx context.Context, id string, req *sdk.UpdateKnowledgeBaseRequest) (*sdk.KnowledgeBase, error)
}
// NewCmdEdit builds `weknora kb edit <id>`. At least one of --name /
// NewCmdEdit builds `weknora kb update <id>`. At least one of --name /
// --description must be provided.
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
opts := &EditOptions{}
var name, desc string
cmd := &cobra.Command{
Use: "edit <kb-id>",
Short: "Edit a knowledge base's name or description",
Use: "update <kb-id>",
Short: "Update a knowledge base's name or description",
Long: `Update a knowledge base's name and/or description. At least one of
--name / --description must be supplied; fields you omit are preserved
server-side.
@@ -78,14 +76,13 @@ to the user first.`,
}
id := args[0]
// Validate pure-local "at least one mutation flag" before the
// dry-run gate so --dry-run rejects identically to the live path
// (industry standard: gh / kubectl / lark all validate before
// preview). Same typed Error as runEdit so live behavior is
// unchanged, just earlier.
// dry-run gate so --dry-run rejects identically to the live path.
// Same typed Error as runEdit so live behavior is unchanged, just
// earlier.
if opts.Name == nil && opts.Description == nil {
return &cmdutil.Error{
Code: cmdutil.CodeInputMissingFlag,
Message: "kb edit requires at least one of --name or --description",
Message: "kb update requires at least one of --name or --description",
Hint: "pass --name <name> and/or --description <desc>",
}
}
@@ -97,7 +94,7 @@ to the user first.`,
planArgs["description"] = *opts.Description
}
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
Action: "kb.edit",
Action: "kb.update",
Args: planArgs,
}); handled {
return err
@@ -108,8 +105,8 @@ to the user first.`,
}
// Build a retry command from the flags the user actually passed so
// agents can re-invoke with -y after explicit human approval.
retryCmd := buildKBEditRetryCmd(c, id)
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "edit", "knowledge base", id, "kb.edit", retryCmd); err != nil {
retryCmd := cmdutil.BuildRetryArgv(c, []string{"weknora", "kb", "update", id}, "name", "description", "format")
if err := cmdutil.ConfirmWrite(f.Prompter(), opts.Yes, fopts.WantsJSON(), "update", "knowledge base", id, "kb.update", retryCmd); err != nil {
return err
}
return runEdit(c.Context(), opts, fopts, cli, id)
@@ -119,46 +116,27 @@ to the user first.`,
cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)")
cmdutil.AddFormatFlag(cmd, kbEditFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetRisk(cmd, "kb.edit")
cmdutil.SetWriteRisk(cmd, "kb.update")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "update a knowledge base's name or description",
RequiredFlags: []string{"<kb-id> (positional)", "--name or --description (at least one)"},
Examples: []string{
"weknora kb edit kb_abc --name \"New Name\" -y",
"weknora kb edit kb_abc --description \"Updated desc\" --format json -y",
"weknora kb update kb_abc --name \"New Name\" -y",
"weknora kb update kb_abc --description \"Updated desc\" --format json -y",
},
Warnings: []string{
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
"kb edit overwrites fields; SDK uses fetch-then-update to avoid clobbering, but malformed input can still corrupt config.",
"kb update overwrites fields; SDK uses fetch-then-update to avoid clobbering, but malformed input can still corrupt config.",
},
})
return cmd
}
// buildKBEditRetryCmd constructs a directly-executable retry argv from the
// flags the user actually set so agents can surface a precise re-run command.
func buildKBEditRetryCmd(c *cobra.Command, id string) string {
var parts []string
parts = append(parts, "weknora", "kb", "edit", id)
c.Flags().Visit(func(f *pflag.Flag) {
switch f.Name {
case "name":
parts = append(parts, "--name", f.Value.String())
case "description":
parts = append(parts, "--description", f.Value.String())
case "format":
parts = append(parts, "--format", f.Value.String())
}
})
parts = append(parts, "-y")
return strings.Join(parts, " ")
}
func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOptions, svc EditService, id string) error {
if opts.Name == nil && opts.Description == nil {
return &cmdutil.Error{
Code: cmdutil.CodeInputMissingFlag,
Message: "kb edit requires at least one of --name or --description",
Message: "kb update requires at least one of --name or --description",
Hint: "pass --name <name> and/or --description <desc>",
}
}
@@ -183,7 +161,7 @@ func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOption
updated, err := svc.UpdateKnowledgeBase(ctx, id, req)
if err != nil {
return cmdutil.WrapHTTP(err, "edit knowledge base %s", id)
return cmdutil.WrapHTTP(err, "update knowledge base %s", id)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, updated, nil)
+1 -2
View File
@@ -15,8 +15,7 @@ import (
// "no mutation flag supplied" invocation the live path rejects. Before the
// fix the validation lived in runEdit() (the live-only callee) and was
// reached only after HandleDryRun early-exited, so --dry-run silently
// emitted a no-op plan envelope. Industry standard (gh / kubectl / lark)
// validates before previewing.
// emitted a no-op plan envelope. Validation must run before previewing.
func TestKBEdit_DryRun_RejectsNoMutationFlag(t *testing.T) {
iostreams.SetForTest(t)
f := kbDryRunFactory(t)
+6 -6
View File
@@ -119,7 +119,7 @@ func TestEdit_NotFound(t *testing.T) {
func stringPtr(s string) *string { return &s }
// withRootHarnessKB wraps `weknora kb edit ...` under a synthetic root cmd
// withRootHarnessKB wraps `weknora kb update ...` under a synthetic root cmd
// that registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go). Required because NewCmdEdit reads --yes and --format from the
// persistent flag set.
@@ -132,7 +132,7 @@ func withRootHarnessKB(edit *cobra.Command, args ...string) *cobra.Command {
kb := &cobra.Command{Use: "kb"}
kb.AddCommand(edit)
root.AddCommand(kb)
root.SetArgs(append([]string{"kb", "edit"}, args...))
root.SetArgs(append([]string{"kb", "update"}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
@@ -140,7 +140,7 @@ func withRootHarnessKB(edit *cobra.Command, args ...string) *cobra.Command {
}
// TestKBEdit_RequiresConfirmation asserts that without -y (non-TTY / JSON
// mode), kb edit returns input.confirmation_required (exit 10).
// mode), kb update returns input.confirmation_required (exit 10).
func TestKBEdit_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
svc := &fakeEditSvc{
@@ -159,7 +159,7 @@ func TestKBEdit_RequiresConfirmation(t *testing.T) {
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
assert.Equal(t, 10, cmdutil.ExitCode(err))
// retry command must include -y
assert.Contains(t, ce.RetryCommand, "-y")
assert.Contains(t, ce.RetryCommand, "kb_abc")
// retry argv must include -y
assert.Contains(t, ce.RetryArgv, "-y")
assert.Contains(t, ce.RetryArgv, "kb_abc")
}
+158
View File
@@ -0,0 +1,158 @@
package kb
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// kbInitFields enumerates the fields surfaced for `--format json` discovery on
// `kb init`. The result is the resulting InitializationConfig (read back).
var kbInitFields = []string{
"chat_model_id", "embedding_model_id", "rerank_model_id", "multimodal_id",
}
type InitOptions struct {
ChatModel string
EmbeddingModel string
Yes bool
DryRun bool
}
// InitService is the narrow SDK surface this command depends on. SetKBModelConfig
// points the KB at already-registered models; GetInitializationConfig re-reads
// the server's resulting state so the success envelope reflects what stuck.
type InitService interface {
SetKBModelConfig(ctx context.Context, kbID string, cfg *sdk.KBModelConfig) error
GetInitializationConfig(ctx context.Context, kbID string) (*sdk.InitializationConfig, error)
}
// NewCmdInit builds `weknora kb init <kb-id>` — bind models to a knowledge base
// so it becomes usable for retrieval and generation.
func NewCmdInit(f *cmdutil.Factory) *cobra.Command {
opts := &InitOptions{}
cmd := &cobra.Command{
Use: "init <kb-id>",
Short: "Configure a knowledge base's models (make it usable)",
Long: `Bind already-registered models to a knowledge base so it can embed, retrieve,
and generate. Both --chat-model (LLM, used for generation/summary) and
--embedding-model (used for retrieval) are required; register models first with
'weknora model create' and discover ids with 'weknora model list'.
High-risk write: changing a KB's embedding model affects how its content is
indexed and searched (and the server refuses once the KB has documents).
Without -y/--yes in a non-TTY / JSON context it exits 10
(input.confirmation_required) without applying the change.`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Yes, _ = c.Flags().GetBool("yes")
kbID := args[0]
// Validate required flags before the dry-run gate so --dry-run rejects
// identically to the live path.
if err := validateInitFlags(opts); err != nil {
return err
}
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
Action: "kb.init",
Args: map[string]any{"kb": kbID, "chat_model": opts.ChatModel, "embedding_model": opts.EmbeddingModel},
}); handled {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(),
"configure", "knowledge base", kbID, "kb.init",
cmdutil.BuildRetryArgv(c, []string{"weknora", "kb", "init", kbID}, "chat-model", "embedding-model", "format")); err != nil {
return err
}
// Resolve name-or-id for the model flags (a UUID passes through; a
// name is looked up among models of the expected type). Network read
// on the live path only — the dry-run above shows the raw refs.
if opts.ChatModel, err = cmdutil.ResolveModelRef(c.Context(), cli, opts.ChatModel, "KnowledgeQA"); err != nil {
return err
}
if opts.EmbeddingModel, err = cmdutil.ResolveModelRef(c.Context(), cli, opts.EmbeddingModel, "Embedding"); err != nil {
return err
}
return runInit(c.Context(), opts, fopts, cli, kbID)
},
}
cmd.Flags().StringVar(&opts.ChatModel, "chat-model", "", "Chat / LLM model id or name for generation & summary (required) — see `weknora model list`")
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model id or name for retrieval (required) — see `weknora model list`")
cmdutil.AddFormatFlag(cmd, kbInitFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetRisk(cmd, "kb.init")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "bind models to a KB so it becomes usable. --chat-model and --embedding-model are required and accept a model id or name; discover them with `weknora model list`.",
RequiredFlags: []string{"<kb-id> (positional)", "--chat-model", "--embedding-model"},
Examples: []string{
"weknora kb init kb_abc --chat-model model_llm --embedding-model model_emb -y",
},
Output: "envelope.data is the resulting {chat_model_id, embedding_model_id, rerank_model_id, multimodal_id}",
Warnings: []string{
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
"The server refuses to change the embedding model of a KB that already has documents.",
},
})
return cmd
}
func validateInitFlags(opts *InitOptions) error {
var missing []string
if strings.TrimSpace(opts.ChatModel) == "" {
missing = append(missing, "--chat-model")
}
if strings.TrimSpace(opts.EmbeddingModel) == "" {
missing = append(missing, "--embedding-model")
}
if len(missing) == 0 {
return nil
}
return &cmdutil.Error{
Code: cmdutil.CodeInputMissingFlag,
Message: "kb init requires " + strings.Join(missing, " and "),
Hint: "discover model ids with `weknora model list` (or register one with `weknora model create`), then pass --chat-model <id> --embedding-model <id>",
}
}
func runInit(ctx context.Context, opts *InitOptions, fopts *cmdutil.FormatOptions, svc InitService, kbID string) error {
if err := validateInitFlags(opts); err != nil {
return err
}
cfg := &sdk.KBModelConfig{
LLMModelID: opts.ChatModel,
EmbeddingModelID: opts.EmbeddingModel,
}
if err := svc.SetKBModelConfig(ctx, kbID, cfg); err != nil {
return cmdutil.WrapHTTP(err, "configure knowledge base %q", kbID)
}
// Re-read the server's resulting state so the envelope reflects what stuck.
result, err := svc.GetInitializationConfig(ctx, kbID)
if err != nil || result == nil {
// The write succeeded; surface what we applied if the read-back failed.
result = &sdk.InitializationConfig{ChatModelID: opts.ChatModel, EmbeddingModelID: opts.EmbeddingModel}
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, result, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Configured knowledge base %s (chat: %s, embedding: %s)\n",
kbID, result.ChatModelID, result.EmbeddingModelID)
return nil
}
// compile-time check: the production SDK client implements InitService.
var _ InitService = (*sdk.Client)(nil)
+134
View File
@@ -0,0 +1,134 @@
package kb
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeInitSvc struct {
gotKB string
gotCfg *sdk.KBModelConfig
result *sdk.InitializationConfig
setErr error
}
func (f *fakeInitSvc) SetKBModelConfig(_ context.Context, kbID string, cfg *sdk.KBModelConfig) error {
f.gotKB = kbID
f.gotCfg = cfg
return f.setErr
}
func (f *fakeInitSvc) GetInitializationConfig(_ context.Context, _ string) (*sdk.InitializationConfig, error) {
if f.result != nil {
return f.result, nil
}
if f.gotCfg == nil {
return &sdk.InitializationConfig{}, nil
}
return &sdk.InitializationConfig{
ChatModelID: f.gotCfg.LLMModelID,
EmbeddingModelID: f.gotCfg.EmbeddingModelID,
}, nil
}
func TestKBInit_AppliesAndEmitsResult(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeInitSvc{}
opts := &InitOptions{ChatModel: "model_llm", EmbeddingModel: "model_emb"}
require.NoError(t, runInit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_abc"))
assert.Equal(t, "kb_abc", svc.gotKB)
require.NotNil(t, svc.gotCfg)
assert.Equal(t, "model_llm", svc.gotCfg.LLMModelID)
assert.Equal(t, "model_emb", svc.gotCfg.EmbeddingModelID)
var env struct {
OK bool `json:"ok"`
Data sdk.InitializationConfig `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.True(t, env.OK)
assert.Equal(t, "model_emb", env.Data.EmbeddingModelID)
assert.Equal(t, "model_llm", env.Data.ChatModelID)
}
func TestKBInit_RequiresBothModels(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeInitSvc{}
// Missing both.
err := runInit(context.Background(), &InitOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc")
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputMissingFlag, ce.Code)
assert.Equal(t, "", svc.gotKB, "must not call SetKBModelConfig when flags are missing")
// Missing just embedding.
err = runInit(context.Background(), &InitOptions{ChatModel: "m"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc")
require.ErrorAs(t, err, &ce)
assert.Contains(t, ce.Message, "--embedding-model")
}
func TestKBInit_WriteSucceedsReadbackFails(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc2 := &readbackErrSvc{fakeInitSvc: &fakeInitSvc{}}
opts := &InitOptions{ChatModel: "model_llm", EmbeddingModel: "model_emb"}
require.NoError(t, runInit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc2, "kb_abc"))
var env struct {
Data sdk.InitializationConfig `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.Equal(t, "model_emb", env.Data.EmbeddingModelID, "falls back to applied config when read-back fails")
}
type readbackErrSvc struct{ *fakeInitSvc }
func (s *readbackErrSvc) GetInitializationConfig(_ context.Context, _ string) (*sdk.InitializationConfig, error) {
return nil, errors.New("read-back boom")
}
// withRootKB wraps a kb subcommand under a synthetic root with global flags,
// keyed off the sub's own name (unlike withRootHarnessKB which is hardcoded to
// `update`).
func withRootKB(sub *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
pf.StringP("jq", "q", "", "")
kb := &cobra.Command{Use: "kb"}
kb.AddCommand(sub)
root.AddCommand(kb)
root.SetArgs(append([]string{"kb", sub.Name()}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
return root
}
func TestKBInit_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t)
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootKB(NewCmdInit(f), "kb_abc", "--chat-model", "model_llm", "--embedding-model", "model_emb", "--format", "json")
err := root.Execute()
require.Error(t, err)
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
assert.Equal(t, 10, cmdutil.ExitCode(err))
assert.Contains(t, ce.RetryArgv, "-y")
assert.Contains(t, ce.RetryArgv, "model_emb")
}
+4 -2
View File
@@ -1,6 +1,6 @@
// Package kb holds the `weknora kb` command tree: list / view / create /
// edit / delete / pin / unpin. Verb set follows common CRUD vocabulary
// (list/view/create/edit/delete) plus pin/unpin. Bulk content deletion
// update / delete / pin / unpin. Verb set follows common CRUD vocabulary
// (list/view/create/update/delete) plus pin/unpin. Bulk content deletion
// is exposed via `weknora doc delete --all --kb=<id>`.
package kb
@@ -25,5 +25,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd.AddCommand(NewCmdUnpin(f))
cmd.AddCommand(NewCmdStatus(f))
cmd.AddCommand(NewCmdCheck(f))
cmd.AddCommand(NewCmdConfig(f))
cmd.AddCommand(NewCmdInit(f))
return cmd
}
+29 -9
View File
@@ -57,6 +57,12 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
// Validate static input before building the client so a bad --limit
// returns input.invalid_argument (exit 5) rather than an auth error
// (exit 3) when no profile is configured.
if err := validateListOpts(opts); err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
@@ -65,23 +71,33 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
},
}
cmd.Flags().BoolVar(&opts.Pinned, "pinned", false, "Only show pinned knowledge bases")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return — client-side cap; meta.has_more/total_count report the full size (1..10000)")
cmdutil.AddFormatFlag(cmd, kbListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List knowledge bases in the current tenant. --format json emits the v0.7 envelope {ok, data:[...], meta:{count}, profile}.",
UsedFor: "List knowledge bases in the current tenant. --format json emits the standard envelope {ok, data:[...], meta:{count}, profile}.",
Examples: []string{"weknora kb list --format json"},
Output: "envelope.data is an array of KnowledgeBase objects with id, name, is_pinned, type, embedding_model_id",
Output: "envelope.data is an array of KnowledgeBase objects with id, name, is_pinned, type, embedding_model_id; meta.total_count is the full tenant set and meta.has_more=true means --limit truncated it (raise --limit to get the rest)",
})
return cmd
}
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
// validateListOpts checks --limit. Called from RunE before the client is built
// (so a bad value surfaces as exit 5, not an auth error) and at runList's top
// for direct callers; idempotent.
func validateListOpts(opts *ListOptions) error {
if opts.Limit < 1 || opts.Limit > 10000 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
}
}
return nil
}
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
if err := validateListOpts(opts); err != nil {
return err
}
items, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return cmdutil.WrapHTTP(err, "list knowledge bases")
@@ -104,16 +120,20 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
sort.Slice(items, func(i, j int) bool {
return items[i].UpdatedAt.After(items[j].UpdatedAt)
})
// --limit applies after sort so the cap returns the top-N most-recent.
// The KB list SDK is unpaginated, so client-side truncation does not
// imply server-side has_more — there is no cursor to continue with.
// has_more is omitted; callers needing all KBs should raise --limit.
// The KB list SDK is unpaginated — it returns every KB in one call —
// so the CLI holds the true total and can tell the caller whether the
// client-side --limit dropped any. total_count is the full count;
// has_more flags that --limit truncated it (raise --limit to get the
// rest — there is no server cursor to continue with).
total := len(items)
truncated := false
if opts.Limit > 0 && len(items) > opts.Limit {
items = items[:opts.Limit]
truncated = true
}
if fopts.WantsJSON() {
meta := &output.Meta{Count: len(items)}
meta := &output.Meta{Count: output.IntPtr(len(items)), HasMore: truncated, TotalCount: output.IntPtr(total)}
return fopts.Emit(iostreams.IO.Out, items, meta)
}
+37
View File
@@ -172,6 +172,43 @@ func TestList_Limit_CapsResults(t *testing.T) {
}
}
// TestList_Truncation_SignalsHasMoreAndTotal pins that a client-side --limit
// truncation tells the agent it did NOT get everything: has_more=true and
// total_count=full set. Regression: kb list silently dropped items past
// --limit with no completeness signal, so an agent listing to find a KB by
// name could miss KBs beyond position 30 and never know.
func TestList_Truncation_SignalsHasMoreAndTotal(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{items: makeKBs(20)}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runList(context.Background(), &ListOptions{Limit: 5}, fopts, svc); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), `"has_more":true`) {
t.Errorf("truncated list must set has_more:true; got:\n%s", out.String())
}
if !strings.Contains(out.String(), `"total_count":20`) {
t.Errorf("truncated list must report total_count:20; got:\n%s", out.String())
}
}
// TestList_NoTruncation_OmitsHasMore pins that when --limit does NOT truncate,
// has_more is absent (omitempty) so the agent reads "complete".
func TestList_NoTruncation_OmitsHasMore(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{items: makeKBs(3)}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, svc); err != nil {
t.Fatalf("runList: %v", err)
}
if strings.Contains(out.String(), `"has_more"`) {
t.Errorf("non-truncated list must omit has_more; got:\n%s", out.String())
}
if !strings.Contains(out.String(), `"total_count":3`) {
t.Errorf("list must report total_count:3; got:\n%s", out.String())
}
}
func TestList_Limit_Zero_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{items: makeKBs(7)}
+23 -6
View File
@@ -21,10 +21,13 @@ type PinOptions struct {
}
// PinService is the narrow SDK surface this command depends on. The CLI
// reads current state before toggling so `pin`/`unpin` are idempotent -
// the server endpoint is only a non-idempotent toggle.
// reads current state before toggling so `pin`/`unpin` are idempotent — the
// server endpoint is only a toggle. Pin state is read from the LIST endpoint:
// the single-KB GET does not carry per-user pin state (pin is a per-user
// list-ordering preference, surfaced where the user sees it — in `kb list`),
// so the list is the canonical source.
type PinService interface {
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error)
TogglePinKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
}
@@ -73,7 +76,7 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: use + " a knowledge base (idempotent: a no-op if it is already in the target state)",
RequiredFlags: []string{"<kb-id> (positional)"},
Examples: []string{"weknora " + use + " kb_abc"},
Examples: []string{"weknora kb " + use + " kb_abc"},
Output: "envelope.data is the KnowledgeBase with is_pinned reflecting the new state",
})
return cmd
@@ -84,9 +87,23 @@ func runPin(ctx context.Context, opts *PinOptions, fopts *cmdutil.FormatOptions,
if !want {
verb = "unpin"
}
current, err := svc.GetKnowledgeBase(ctx, id)
// Read the current pin state from the list (the canonical per-user pin
// source); the single-KB GET doesn't carry it. This makes pin/unpin
// idempotent: we toggle only when the state actually needs to change.
kbs, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return cmdutil.WrapHTTP(err, "get knowledge base %s", id)
return cmdutil.WrapHTTP(err, "list knowledge bases")
}
var current *sdk.KnowledgeBase
for i := range kbs {
if kbs[i].ID == id {
current = &kbs[i]
break
}
}
if current == nil {
return cmdutil.NewError(cmdutil.CodeResourceNotFound,
fmt.Sprintf("knowledge base not found: %s", id))
}
if current.IsPinned == want {
state := "pinned"
+8 -4
View File
@@ -15,7 +15,9 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// fakePinSvc satisfies PinService: GetKnowledgeBase + TogglePinKnowledgeBase.
// fakePinSvc satisfies PinService: ListKnowledgeBases + TogglePinKnowledgeBase.
// The fake's `current` is returned as the single KB in the list (the list is
// the canonical pin-state source).
type fakePinSvc struct {
current sdk.KnowledgeBase
getErr error
@@ -23,13 +25,15 @@ type fakePinSvc struct {
toggleCalled bool
}
func (f *fakePinSvc) GetKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
func (f *fakePinSvc) ListKnowledgeBases(_ context.Context) ([]sdk.KnowledgeBase, error) {
if f.getErr != nil {
return nil, f.getErr
}
c := f.current
c.ID = id
return &c, nil
if c.ID == "" {
c.ID = "kb_abc" // tests address this id
}
return []sdk.KnowledgeBase{c}, nil
}
func (f *fakePinSvc) TogglePinKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
+15
View File
@@ -27,8 +27,11 @@ var kbViewFields = []string{
type ViewOptions struct{}
// ViewService is the narrow SDK surface this command depends on.
// ListKnowledgeBases is used only to enrich is_pinned (the single-KB GET
// doesn't carry per-user pin state — pin is a per-user list concept).
type ViewService interface {
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error)
}
// NewCmdView builds `weknora kb view <id>`.
@@ -70,6 +73,18 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
if err != nil {
return cmdutil.WrapHTTP(err, "get knowledge base %q", id)
}
// The single-KB GET doesn't stamp per-user pin state, so is_pinned would
// always read false here. Enrich it from the list (the canonical pin
// source) so the field is accurate. Best-effort: a list error leaves the
// (unstamped) value rather than failing the view.
if kbs, lerr := svc.ListKnowledgeBases(ctx); lerr == nil {
for i := range kbs {
if kbs[i].ID == id {
kb.IsPinned = kbs[i].IsPinned
break
}
}
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, kb, nil)
}
+9
View File
@@ -22,6 +22,15 @@ func (f *fakeGetSvc) GetKnowledgeBase(ctx context.Context, id string) (*sdk.Know
return f.kb, f.err
}
// ListKnowledgeBases backs is_pinned enrichment in runView. Returns the same
// KB so the enrichment finds it; nil/empty is fine (enrichment is best-effort).
func (f *fakeGetSvc) ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error) {
if f.kb == nil {
return nil, nil
}
return []sdk.KnowledgeBase{*f.kb}, nil
}
func TestGet_OK_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{