feat(cli): --log-level + kb/agent status & check + cross-cutting refactor

Operability surface and the bulk of the jopts→fopts migration:

* --log-level error|warn|info|debug + WEKNORA_LOG_LEVEL env, wired to
  the SDK via client.SetDebugLevel. Invalid --log-level returns FlagError
  (exit 2).
* kb status <kb-id> / kb check <kb-id> verb split (1 HTTP vs 1+N for
  failed_count aggregation).
* agent status <agent-id> / agent check <agent-id> verb split
  (probes kb_scope_all_reachable via 1+N HTTP).
* kb create <name> positional (matches agent create).
* Positional id help strings namespaced (<kb-id> / <agent-id>).
* All auth / context / link / doctor / kb / agent CRUD commands migrated
  to the FormatOptions API.
* root.go Execute(ctx) takes a context so signal-cancellation propagates
  via cmd.Context() into long-running commands.
* Pagination termination uses len(accum) >= total (not page*pageSize)
  so server-capped page sizes do not truncate aggregations.
This commit is contained in:
nullkey
2026-05-18 01:38:16 +08:00
committed by lyingbug
parent 7eeb3bec5d
commit 0e081aec5c
64 changed files with 1581 additions and 393 deletions
+149
View File
@@ -0,0 +1,149 @@
package kb
import (
"context"
"fmt"
"io"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// CheckResult is the deep-verification response for `kb check <id>`.
// Superset of StatusResult: includes all status fields plus FailedCount
// aggregated by paging the doc list. Verb split with `kb status`:
// status reads existing state cheaply, check actively verifies.
type CheckResult struct {
ID string `json:"id"`
Reachable bool `json:"reachable"`
KnowledgeCount int64 `json:"knowledge_count,omitempty"`
ChunkCount int64 `json:"chunk_count,omitempty"`
IsProcessing bool `json:"is_processing,omitempty"`
ProcessingCount int64 `json:"processing_count,omitempty"`
FailedCount int64 `json:"failed_count"` // always populated (no omitempty)
}
// CheckService is the narrow SDK surface needed for kb check.
type CheckService interface {
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
ListKnowledgeWithFilter(ctx context.Context, kbID string, page, pageSize int, filter sdk.KnowledgeListFilter) ([]sdk.Knowledge, int64, error)
}
var kbCheckFields = []string{
"id", "reachable", "knowledge_count", "chunk_count",
"is_processing", "processing_count", "failed_count",
}
// NewCmdCheck builds `weknora kb check <id>`.
func NewCmdCheck(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "check <kb-id>",
Short: "Verify a knowledge base end-to-end (status + failed-doc aggregation)",
Long: `Active verification of a knowledge base.
Performs 1 + N HTTP calls:
1 GET /kb/{id} — reachable + counts + processing state
N page-walk doc list with parse_status=failed — failed_count
Use 'weknora kb status <id>' for a fast read-only health snapshot
(1 HTTP call, no failed_count). Use 'kb check' when you need
verification including failed-doc aggregation.`,
Example: ` weknora kb check kb_abc
weknora kb check kb_abc --format json`,
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
}
res, err := runCheck(c.Context(), cli, args[0])
if err != nil {
return err
}
return emitCheck(res, fopts, iostreams.IO.Out)
},
}
cmdutil.AddFormatFlag(cmd, kbCheckFields...)
return cmd
}
// runCheck is the testable core: status fields + failed-doc aggregation.
// Never returns an error for "kb not reachable" (Reachable=false carries
// the signal).
func runCheck(ctx context.Context, svc CheckService, id string) (*CheckResult, error) {
kb, err := svc.GetKnowledgeBase(ctx, id)
if err != nil {
return &CheckResult{ID: id, Reachable: false}, nil
}
res := &CheckResult{
ID: kb.ID,
Reachable: true,
KnowledgeCount: kb.KnowledgeCount,
ChunkCount: kb.ChunkCount,
IsProcessing: kb.IsProcessing,
ProcessingCount: kb.ProcessingCount,
}
failed, err := aggregateFailedCount(ctx, svc, id)
if err != nil {
return res, fmt.Errorf("aggregate failed_count: %w", err)
}
res.FailedCount = failed
return res, nil
}
// aggregateFailedCount pages the doc list with parse_status=failed and
// returns the total count. Termination uses accumulated total (not
// page*pageSize) so server-capped page sizes don't truncate.
func aggregateFailedCount(ctx context.Context, svc CheckService, kbID string) (int64, error) {
const pageSize = 100
var total int64
page := 1
for {
docs, totalAvailable, err := svc.ListKnowledgeWithFilter(ctx, kbID, page, pageSize, sdk.KnowledgeListFilter{ParseStatus: "failed"})
if err != nil {
return total, err
}
total += int64(len(docs))
if total >= totalAvailable || len(docs) == 0 {
break
}
page++
}
return total, nil
}
// emitCheck renders res. Same dispatch as emitStatus.
func emitCheck(res *CheckResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res)
case cmdutil.FormatText, "":
return writeCheckText(w, res)
default:
return fmt.Errorf("unsupported --format %q for kb check", fopts.Mode)
}
}
func writeCheckText(w io.Writer, res *CheckResult) error {
fmt.Fprintf(w, "ID: %s\n", res.ID)
fmt.Fprintf(w, "Reachable: %v\n", res.Reachable)
if !res.Reachable {
return nil
}
fmt.Fprintf(w, "Knowledge: %d\n", res.KnowledgeCount)
fmt.Fprintf(w, "Chunks: %d\n", res.ChunkCount)
fmt.Fprintf(w, "Processing: %v (%d active)\n", res.IsProcessing, res.ProcessingCount)
fmt.Fprintf(w, "Failed: %d\n", res.FailedCount)
return nil
}
// compile-time check: SDK client satisfies CheckService.
var _ CheckService = (*sdk.Client)(nil)
+128
View File
@@ -0,0 +1,128 @@
package kb
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeCheckSvc struct {
kb *sdk.KnowledgeBase
getErr error
failedDocs []sdk.Knowledge // returned by ListKnowledgeWithFilter when ParseStatus=failed
listErr error
}
func (f *fakeCheckSvc) GetKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
if f.getErr != nil {
return nil, f.getErr
}
return f.kb, nil
}
func (f *fakeCheckSvc) ListKnowledgeWithFilter(_ context.Context, _ string, page, pageSize int, _ sdk.KnowledgeListFilter) ([]sdk.Knowledge, int64, error) {
if f.listErr != nil {
return nil, 0, f.listErr
}
// Single-page fake: return all docs at once (page 1), empty thereafter.
if page == 1 {
return f.failedDocs, int64(len(f.failedDocs)), nil
}
return nil, int64(len(f.failedDocs)), nil
}
func TestRunCheck_AggregatesFailed(t *testing.T) {
svc := &fakeCheckSvc{
kb: &sdk.KnowledgeBase{ID: "kb_x", KnowledgeCount: 5, ChunkCount: 20},
failedDocs: []sdk.Knowledge{
{ID: "d1", ParseStatus: "failed"},
{ID: "d2", ParseStatus: "failed"},
},
}
res, err := runCheck(context.Background(), svc, "kb_x")
if err != nil {
t.Fatalf("runCheck: %v", err)
}
if res.FailedCount != 2 {
t.Errorf("FailedCount=%d, want 2", res.FailedCount)
}
if !res.Reachable {
t.Error("Reachable=false, want true")
}
if res.KnowledgeCount != 5 || res.ChunkCount != 20 {
t.Errorf("got %+v", res)
}
}
func TestRunCheck_Unreachable(t *testing.T) {
svc := &fakeCheckSvc{getErr: fmt.Errorf("404 not found")}
res, err := runCheck(context.Background(), svc, "kb_x")
if err != nil {
t.Fatalf("runCheck should not return err on unreachable; got %v", err)
}
if res.Reachable {
t.Error("Reachable=true, want false")
}
if res.ID != "kb_x" {
t.Errorf("ID=%q, want kb_x (echoed even when unreachable)", res.ID)
}
}
func TestRunCheck_NoFailedDocs(t *testing.T) {
svc := &fakeCheckSvc{
kb: &sdk.KnowledgeBase{ID: "kb_y", KnowledgeCount: 10},
failedDocs: nil,
}
res, err := runCheck(context.Background(), svc, "kb_y")
if err != nil {
t.Fatalf("runCheck: %v", err)
}
if res.FailedCount != 0 {
t.Errorf("FailedCount=%d, want 0", res.FailedCount)
}
}
func TestEmitCheck_JSON(t *testing.T) {
var buf bytes.Buffer
res := &CheckResult{ID: "kb_x", Reachable: true, KnowledgeCount: 5, FailedCount: 3}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := emitCheck(res, fopts, &buf); err != nil {
t.Fatalf("emitCheck: %v", err)
}
var got CheckResult
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("not JSON: %v\n%s", err, buf.String())
}
if got.ID != "kb_x" || got.KnowledgeCount != 5 || got.FailedCount != 3 {
t.Errorf("got %+v", got)
}
}
func TestEmitCheck_TextHuman(t *testing.T) {
var buf bytes.Buffer
res := &CheckResult{
ID: "kb_x", Reachable: true,
KnowledgeCount: 5, ChunkCount: 20,
IsProcessing: true, ProcessingCount: 1,
FailedCount: 2,
}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
if err := emitCheck(res, fopts, &buf); err != nil {
t.Fatalf("emitCheck: %v", err)
}
for _, want := range []string{"kb_x", "5", "20", "true", "2"} {
if !strings.Contains(buf.String(), want) {
t.Errorf("output missing %q:\n%s", want, buf.String())
}
}
// "Failed:" line must always appear for check
if !strings.Contains(buf.String(), "Failed:") {
t.Errorf("output missing 'Failed:' line:\n%s", buf.String())
}
}
+16 -15
View File
@@ -11,8 +11,8 @@ 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.
// kbDeleteFields enumerates the fields surfaced for `--format json` discovery
// on `kb delete`. The result payload is a small {id, deleted} object.
var kbDeleteFields = []string{"id", "deleted"}
type DeleteOptions struct {
@@ -37,40 +37,41 @@ type deleteResult struct {
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
opts := &DeleteOptions{}
cmd := &cobra.Command{
Use: "delete <id>",
Use: "delete <kb-id>",
Short: "Delete a knowledge base",
Long: `Permanently deletes a knowledge base and all its contents.
Prompts for confirmation by default when stdout is a TTY and --json is not set.
Prompts for confirmation by default when stdout is a TTY and JSON output is not set.
Pass -y/--yes (global flag) to skip the prompt (required in agent / CI / piped contexts).
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
and writes input.confirmation_required to stderr. NEVER auto-pass -y
without the user's explicit go-ahead - the exit-10 protocol exists
without the user's explicit go-ahead — the exit-10 protocol exists
exactly to guard against unintended deletes.`,
Example: ` weknora kb delete kb_abc # interactive confirm
weknora kb delete kb_abc -y # no prompt
weknora kb delete kb_abc -y --json # bare {id, deleted:true} JSON`,
Example: ` weknora kb delete kb_abc # interactive confirm
weknora kb delete kb_abc -y # no prompt
weknora kb delete kb_abc -y --format json # bare {id, deleted:true} JSON`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Yes, _ = c.Flags().GetBool("yes")
cli, err := f.Client()
if err != nil {
return err
}
return runDelete(c.Context(), opts, jopts, cli, f.Prompter(), args[0])
return runDelete(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
},
}
cmdutil.AddJSONFlags(cmd, kbDeleteFields)
cmdutil.AddFormatFlag(cmd, kbDeleteFields...)
return cmd
}
func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOptions, svc DeleteService, p prompt.Prompter, id string) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "knowledge base", id); err != nil {
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(), "knowledge base", id); err != nil {
return err
}
@@ -78,8 +79,8 @@ func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOpti
return cmdutil.WrapHTTP(err, "delete knowledge base %s", id)
}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
}
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted knowledge base %s\n", id)
return nil
+13 -13
View File
@@ -33,7 +33,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
opts := &DeleteOptions{Yes: true}
require.NoError(t, runDelete(context.Background(), opts, nil, svc, p, "kb_force"))
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_force"))
assert.True(t, svc.called)
assert.Equal(t, "kb_force", svc.gotID)
@@ -46,7 +46,7 @@ func TestDelete_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
p := &testutil.ConfirmPrompter{}
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, nil, svc, p, "kb_missing")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_missing")
require.Error(t, err)
var typed *cmdutil.Error
@@ -61,7 +61,7 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_nontty")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_nontty")
require.Error(t, err)
var typed *cmdutil.Error
@@ -77,7 +77,7 @@ func TestDelete_JSONOutput(t *testing.T) {
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
opts := &DeleteOptions{Yes: true}
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_json"))
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, p, "kb_json"))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb_json"`), "expected bare object; got %q", got)
@@ -92,7 +92,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: true}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_yes"))
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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")
@@ -103,7 +103,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: false}
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_no")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_no")
require.Error(t, err)
var typed *cmdutil.Error
@@ -118,7 +118,7 @@ func TestDelete_ConfirmPrompterError(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Err: prompt.ErrAgentNoPrompt}
err := runDelete(context.Background(), &DeleteOptions{}, nil, svc, p, "kb_err")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_err")
require.Error(t, err)
var typed *cmdutil.Error
@@ -129,31 +129,31 @@ func TestDelete_ConfirmPrompterError(t *testing.T) {
}
func TestDelete_JSONOut_NoYes_RequiresConfirmation(t *testing.T) {
// Even on a TTY, --json indicates a scripted caller; cannot prompt.
// Even on a TTY, --format json indicates a scripted caller; cannot prompt.
// Exit-10 protocol must fire when -y is absent.
iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
opts := &DeleteOptions{}
err := runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_jtty")
err := runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, p, "kb_jtty")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
assert.False(t, p.Asked, "--json must skip the prompt even on TTY")
assert.False(t, svc.called, "--json without -y must not call DeleteKnowledgeBase")
assert.False(t, p.Asked, "--format json must skip the prompt even on TTY")
assert.False(t, svc.called, "--format json without -y must not call DeleteKnowledgeBase")
assert.Equal(t, 10, cmdutil.ExitCode(err))
}
func TestDelete_JSONOut_WithYes_Proceeds(t *testing.T) {
// --json + -y is the agent happy-path: scripted caller with explicit
// --format json + -y is the agent happy-path: scripted caller with explicit
// approval. Must call SDK and emit the bare result object.
out, _ := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
opts := &DeleteOptions{Yes: true}
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_jtty"))
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, p, "kb_jtty"))
assert.False(t, p.Asked, "-y must skip the prompt")
assert.True(t, svc.called)
+9 -8
View File
@@ -11,7 +11,7 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// kbEditFields enumerates the fields surfaced for `--json` discovery on
// kbEditFields enumerates the fields surfaced for `--format json` discovery on
// `kb edit`. The result is the updated KnowledgeBase; mirrors the kb
// top-level json tags.
var kbEditFields = []string{
@@ -49,17 +49,18 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
opts := &EditOptions{}
var name, desc string
cmd := &cobra.Command{
Use: "edit <id>",
Use: "edit <kb-id>",
Short: "Edit 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.`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
if c.Flag("name").Changed {
opts.Name = &name
}
@@ -70,16 +71,16 @@ server-side.`,
if err != nil {
return err
}
return runEdit(c.Context(), opts, jopts, cli, args[0])
return runEdit(c.Context(), opts, fopts, 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)")
cmdutil.AddJSONFlags(cmd, kbEditFields)
cmdutil.AddFormatFlag(cmd, kbEditFields...)
return cmd
}
func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions, svc EditService, id string) error {
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,
@@ -110,8 +111,8 @@ func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions,
if err != nil {
return cmdutil.WrapHTTP(err, "edit knowledge base %s", id)
}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, updated)
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, updated)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Updated knowledge base %s\n", id)
return nil
+5 -5
View File
@@ -43,7 +43,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{}, nil, svc, "kb_abc")
err := runEdit(context.Background(), &EditOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -64,7 +64,7 @@ func TestEdit_OnlyName_PreservesCurrentDescription(t *testing.T) {
}
opts := &EditOptions{}
opts.Name = stringPtr("new")
require.NoError(t, runEdit(context.Background(), opts, nil, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
assert.Equal(t, "kb_abc", svc.gotID)
require.NotNil(t, svc.gotReq)
@@ -83,7 +83,7 @@ func TestEdit_OnlyDescription_PreservesCurrentName(t *testing.T) {
}
opts := &EditOptions{}
opts.Description = stringPtr("new desc")
require.NoError(t, runEdit(context.Background(), opts, nil, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
require.NotNil(t, svc.gotReq)
assert.Equal(t, "new desc", svc.gotReq.Description)
@@ -96,7 +96,7 @@ func TestEdit_BothFlags(t *testing.T) {
opts := &EditOptions{}
opts.Name = stringPtr("renamed")
opts.Description = stringPtr("new desc")
require.NoError(t, runEdit(context.Background(), opts, nil, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
assert.Equal(t, "renamed", svc.gotReq.Name)
assert.Equal(t, "new desc", svc.gotReq.Description)
}
@@ -108,7 +108,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, nil, svc, "kb_missing")
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+11 -10
View File
@@ -12,7 +12,7 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// kbEmptyFields enumerates the fields surfaced for `--json` discovery on
// kbEmptyFields enumerates the fields surfaced for `--format json` discovery on
// `kb empty`. The result payload is {id, deleted_count}.
var kbEmptyFields = []string{"id", "deleted_count"}
@@ -37,7 +37,7 @@ type emptyResult struct {
func NewCmdEmpty(f *cmdutil.Factory) *cobra.Command {
opts := &EmptyOptions{}
cmd := &cobra.Command{
Use: "empty <id>",
Use: "empty <kb-id>",
Short: "Delete every document in a knowledge base (preserves the KB)",
Long: `Removes all documents and chunks from a knowledge base while keeping the
KB record (its name, description, and config) intact. The delete is async;
@@ -46,27 +46,28 @@ the server reports the count of items enqueued for removal.
Prompts for confirmation by default; pass -y/--yes to skip in agent / CI /
piped contexts. Without -y the CLI exits 10 in non-interactive mode.`,
Example: ` weknora kb empty kb_abc # interactive confirm
weknora kb empty kb_abc -y --json # agent-friendly`,
weknora kb empty kb_abc -y --format json # agent-friendly`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Yes, _ = c.Flags().GetBool("yes")
cli, err := f.Client()
if err != nil {
return err
}
return runEmpty(c.Context(), opts, jopts, cli, f.Prompter(), args[0])
return runEmpty(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
},
}
cmdutil.AddJSONFlags(cmd, kbEmptyFields)
cmdutil.AddFormatFlag(cmd, kbEmptyFields...)
return cmd
}
func runEmpty(ctx context.Context, opts *EmptyOptions, jopts *cmdutil.JSONOptions, svc EmptyService, p prompt.Prompter, id string) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "all contents of knowledge base", id); err != nil {
func runEmpty(ctx context.Context, opts *EmptyOptions, fopts *cmdutil.FormatOptions, svc EmptyService, p prompt.Prompter, id string) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "all contents of knowledge base", id); err != nil {
return err
}
@@ -79,8 +80,8 @@ func runEmpty(ctx context.Context, opts *EmptyOptions, jopts *cmdutil.JSONOption
deleted = resp.DeletedCount
}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, emptyResult{ID: id, DeletedCount: deleted})
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, emptyResult{ID: id, DeletedCount: deleted})
}
fmt.Fprintf(iostreams.IO.Out, "✓ Emptied knowledge base %s (%d document(s) cleared)\n", id, deleted)
return nil
+4 -4
View File
@@ -37,7 +37,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}, nil, svc, &testutil.ConfirmPrompter{}, "kb_abc"))
require.NoError(t, runEmpty(context.Background(), &EmptyOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "kb_abc"))
assert.True(t, svc.called)
assert.Equal(t, "kb_abc", svc.gotID)
body := out.String()
@@ -48,7 +48,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{}, nil, svc, &testutil.ConfirmPrompter{}, "kb_abc")
err := runEmpty(context.Background(), &EmptyOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "kb_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -61,7 +61,7 @@ func TestEmpty_TTY_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeEmptySvc{}
p := &testutil.ConfirmPrompter{Answer: false}
err := runEmpty(context.Background(), &EmptyOptions{}, nil, svc, p, "kb_abc")
err := runEmpty(context.Background(), &EmptyOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -73,7 +73,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}, nil, svc, &testutil.ConfirmPrompter{}, "kb_missing")
err := runEmpty(context.Background(), &EmptyOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "kb_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+2
View File
@@ -25,5 +25,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd.AddCommand(NewCmdPin(f))
cmd.AddCommand(NewCmdUnpin(f))
cmd.AddCommand(NewCmdEmpty(f))
cmd.AddCommand(NewCmdStatus(f))
cmd.AddCommand(NewCmdCheck(f))
return cmd
}
+11 -10
View File
@@ -11,7 +11,7 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// kbPinFields enumerates the fields surfaced for `--json` discovery on
// kbPinFields enumerates the fields surfaced for `--format 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"}
@@ -39,27 +39,28 @@ func NewCmdUnpin(f *cmdutil.Factory) *cobra.Command {
func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.Command {
opts := &PinOptions{}
cmd := &cobra.Command{
Use: use + " <id>",
Use: use + " <kb-id>",
Short: short,
Long: short + ". Idempotent: reads the current pin state and toggles only if different, so re-running on a KB already in the target state is a no-op.",
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []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 runPin(c.Context(), opts, jopts, cli, args[0], want)
return runPin(c.Context(), opts, fopts, cli, args[0], want)
},
}
cmdutil.AddJSONFlags(cmd, kbPinFields)
cmdutil.AddFormatFlag(cmd, kbPinFields...)
return cmd
}
func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, svc PinService, id string, want bool) error {
func runPin(ctx context.Context, opts *PinOptions, fopts *cmdutil.FormatOptions, svc PinService, id string, want bool) error {
verb := "pin"
if !want {
verb = "unpin"
@@ -77,8 +78,8 @@ func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, s
// emit the current resource so callers see the canonical shape on
// both fresh-toggle and no-op paths. Human path prints a confirming
// line; agents observe via the unchanged is_pinned field.
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, current)
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, current)
}
fmt.Fprintf(iostreams.IO.Out, "✓ %s is already %s\n", id, state)
return nil
@@ -88,8 +89,8 @@ func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, s
if err != nil {
return cmdutil.WrapHTTP(err, "%s knowledge base %s", verb, id)
}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, updated)
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, updated)
}
state := "pinned"
if !updated.IsPinned {
+7 -7
View File
@@ -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{}, nil, svc, "kb_abc", true))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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{}, nil, svc, "kb_abc", true))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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{}, nil, svc, "kb_abc", false))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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{}, nil, svc, "kb_abc", false))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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{}, nil, svc, "kb_missing", true)
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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{}, nil, svc, "kb_abc", true)
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.JSONOptions{}, svc, "kb_abc", true))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_abc", true))
body := out.String()
assert.Contains(t, body, `"is_pinned":true`)
assert.Contains(t, body, `"id":"kb_abc"`)
+119
View File
@@ -0,0 +1,119 @@
package kb
import (
"context"
"fmt"
"io"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// StatusResult is the health-oriented response for `kb status <id>`.
// Shallow read only: 1 HTTP call, no failed-doc aggregation.
// For deep verification including failed_count, use `kb check <id>`.
type StatusResult struct {
ID string `json:"id"`
Reachable bool `json:"reachable"`
KnowledgeCount int64 `json:"knowledge_count,omitempty"`
ChunkCount int64 `json:"chunk_count,omitempty"`
IsProcessing bool `json:"is_processing,omitempty"`
ProcessingCount int64 `json:"processing_count,omitempty"`
}
// StatusService is the narrow SDK surface needed for kb status.
type StatusService interface {
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
}
var kbStatusFields = []string{
"id", "reachable", "knowledge_count", "chunk_count",
"is_processing", "processing_count",
}
// NewCmdStatus builds `weknora kb status <id>`.
func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "status <kb-id>",
Short: "Show health status of a knowledge base (shallow, 1 HTTP)",
Long: `Show health-oriented fields for a KB.
1 HTTP call:
reachable / knowledge_count / chunk_count / is_processing / processing_count
For deep verification including failed_count, use 'weknora kb check <id>'
(1 + N HTTP, pages the doc list with parse_status=failed).
For full metadata (config / pinned / tenant), use 'weknora kb view <id>'.`,
Example: ` weknora kb status kb_abc
weknora kb status kb_abc --format json`,
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
}
res, err := runStatus(c.Context(), cli, args[0])
if err != nil {
return err
}
return emitStatus(res, fopts, iostreams.IO.Out)
},
}
cmdutil.AddFormatFlag(cmd, kbStatusFields...)
return cmd
}
// runStatus is the testable core: fetch KB metadata and return a StatusResult.
// Never returns an error for "kb not reachable" (Reachable=false carries
// that signal).
func runStatus(ctx context.Context, svc StatusService, id string) (*StatusResult, error) {
kb, err := svc.GetKnowledgeBase(ctx, id)
if err != nil {
return &StatusResult{ID: id, Reachable: false}, nil
}
return &StatusResult{
ID: kb.ID,
Reachable: true,
KnowledgeCount: kb.KnowledgeCount,
ChunkCount: kb.ChunkCount,
IsProcessing: kb.IsProcessing,
ProcessingCount: kb.ProcessingCount,
}, nil
}
// emitStatus renders res using --format options. Mirrors emitWaitResult
// pattern from cli/cmd/doc/wait.go for consistency.
func emitStatus(res *StatusResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res)
case cmdutil.FormatText, "":
return writeStatusText(w, res)
default:
return fmt.Errorf("unsupported --format %q for kb status", fopts.Mode)
}
}
func writeStatusText(w io.Writer, res *StatusResult) error {
fmt.Fprintf(w, "ID: %s\n", res.ID)
fmt.Fprintf(w, "Reachable: %v\n", res.Reachable)
if !res.Reachable {
return nil
}
fmt.Fprintf(w, "Knowledge: %d\n", res.KnowledgeCount)
fmt.Fprintf(w, "Chunks: %d\n", res.ChunkCount)
fmt.Fprintf(w, "Processing: %v (%d active)\n", res.IsProcessing, res.ProcessingCount)
return nil
}
// compile-time check: SDK client satisfies StatusService.
var _ StatusService = (*sdk.Client)(nil)
+89
View File
@@ -0,0 +1,89 @@
package kb
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeStatusSvc struct {
kb *sdk.KnowledgeBase
getErr error
}
func (f *fakeStatusSvc) GetKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
if f.getErr != nil {
return nil, f.getErr
}
return f.kb, nil
}
func TestRunStatus_ShallowFields(t *testing.T) {
svc := &fakeStatusSvc{kb: &sdk.KnowledgeBase{
ID: "kb_x",
KnowledgeCount: 42,
ChunkCount: 100,
IsProcessing: true,
ProcessingCount: 3,
}}
res, err := runStatus(context.Background(), svc, "kb_x")
if err != nil {
t.Fatalf("runStatus: %v", err)
}
if !res.Reachable {
t.Error("Reachable=false, want true")
}
if res.KnowledgeCount != 42 || res.ChunkCount != 100 || res.ProcessingCount != 3 || !res.IsProcessing {
t.Errorf("got %+v", res)
}
}
func TestRunStatus_Unreachable(t *testing.T) {
svc := &fakeStatusSvc{getErr: fmt.Errorf("404 not found")}
res, err := runStatus(context.Background(), svc, "kb_x")
if err != nil {
t.Fatalf("runStatus should not return err on unreachable; got %v", err)
}
if res.Reachable {
t.Error("Reachable=true, want false")
}
if res.ID != "kb_x" {
t.Errorf("ID=%q, want kb_x (echoed even when unreachable)", res.ID)
}
}
func TestEmitStatus_JSON(t *testing.T) {
var buf bytes.Buffer
res := &StatusResult{ID: "kb_x", Reachable: true, KnowledgeCount: 5}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := emitStatus(res, fopts, &buf); err != nil {
t.Fatalf("emitStatus: %v", err)
}
var got StatusResult
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("not JSON: %v\n%s", err, buf.String())
}
if got.ID != "kb_x" || got.KnowledgeCount != 5 {
t.Errorf("got %+v", got)
}
}
func TestEmitStatus_TextHuman(t *testing.T) {
var buf bytes.Buffer
res := &StatusResult{ID: "kb_x", Reachable: true, KnowledgeCount: 5, ChunkCount: 20, IsProcessing: true, ProcessingCount: 1}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
if err := emitStatus(res, fopts, &buf); err != nil {
t.Fatalf("emitStatus: %v", err)
}
for _, want := range []string{"kb_x", "5", "20", "true"} {
if !strings.Contains(buf.String(), want) {
t.Errorf("output missing %q:\n%s", want, buf.String())
}
}
}
+10 -9
View File
@@ -12,7 +12,7 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// kbViewFields enumerates the fields surfaced for `--json` discovery on
// kbViewFields enumerates the fields surfaced for `--format json` discovery on
// `kb view`. Lists the KnowledgeBase top-level json tags; nested config
// structs are omitted (use --jq for those).
var kbViewFields = []string{
@@ -35,37 +35,38 @@ type ViewService interface {
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
opts := &ViewOptions{}
cmd := &cobra.Command{
Use: "view <id>",
Use: "view <kb-id>",
Short: "Show a knowledge base by ID",
Long: `Fetch a knowledge base's full configuration: chunking settings, embedding / summary model IDs, knowledge_count, chunk_count.`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []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 runView(c.Context(), opts, jopts, cli, args[0])
return runView(c.Context(), opts, fopts, cli, args[0])
},
}
cmdutil.AddJSONFlags(cmd, kbViewFields)
cmdutil.AddFormatFlag(cmd, kbViewFields...)
return cmd
}
func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions, svc ViewService, id string) error {
func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOptions, svc ViewService, id string) error {
kb, err := svc.GetKnowledgeBase(ctx, id)
if err != nil {
return cmdutil.WrapHTTP(err, "get knowledge base %q", id)
}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, kb)
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, kb)
}
// Human: KEY: VALUE. Nested config structs (chunking_config, vlm_config,
// etc.) are intentionally omitted from the human render — those are for
// `--json | jq '.chunking_config'` workflows.
// `--format json | jq '.chunking_config'` workflows.
w := iostreams.IO.Out
fmt.Fprintf(w, "ID: %s\n", kb.ID)
fmt.Fprintf(w, "NAME: %s\n", kb.Name)
+11 -11
View File
@@ -26,7 +26,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{}, nil, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runGet: %v", err)
}
got := out.String()
@@ -40,7 +40,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{}, &cmdutil.JSONOptions{}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb1"); err != nil {
t.Fatalf("runGet: %v", err)
}
got := out.String()
@@ -55,7 +55,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{}, nil, svc, "missing")
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
if err == nil {
t.Fatal("expected error")
}
@@ -69,7 +69,7 @@ func TestGet_NotFound(t *testing.T) {
func TestView_Pinned_RendersPinnedLine(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Pinned", IsPinned: true}}
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
if !strings.Contains(out.String(), "PINNED:") {
@@ -80,7 +80,7 @@ func TestView_Pinned_RendersPinnedLine(t *testing.T) {
func TestView_NotPinned_OmitsPinnedLine(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Plain", IsPinned: false}}
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
for _, l := range strings.Split(out.String(), "\n") {
@@ -93,7 +93,7 @@ func TestView_NotPinned_OmitsPinnedLine(t *testing.T) {
func TestView_Temporary_RendersTempLine(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_t", Name: "Tmp", IsTemporary: true}}
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_t"); err != nil {
t.Fatalf("runView: %v", err)
}
if !strings.Contains(out.String(), "TEMPORARY:") {
@@ -104,7 +104,7 @@ func TestView_Temporary_RendersTempLine(t *testing.T) {
func TestView_SummaryModel(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "X", SummaryModelID: "summary-model-x"}}
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -116,7 +116,7 @@ func TestView_SummaryModel(t *testing.T) {
func TestView_TypeAndSource(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "X", Type: "general", Description: "d"}}
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -128,7 +128,7 @@ func TestView_TypeAndSource(t *testing.T) {
func TestView_Processing(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_p", Name: "Busy", IsProcessing: true, ProcessingCount: 3}}
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb_p"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_p"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -140,7 +140,7 @@ func TestView_Processing(t *testing.T) {
func TestView_NotProcessing_OmitsProcessingLine(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_idle", Name: "Idle", IsProcessing: false}}
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb_idle"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_idle"); err != nil {
t.Fatalf("runView: %v", err)
}
for _, l := range strings.Split(out.String(), "\n") {
@@ -157,7 +157,7 @@ func TestView_CreatedAt_AlwaysRendered(t *testing.T) {
CreatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),
UpdatedAt: time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC),
}}
if err := runView(context.Background(), &ViewOptions{}, nil, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()