refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup

Sweep every CLI output path through the v0.7 envelope contract.

FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.

~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.

Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
  pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
  failures*}; Successes/Failures *int so explicit zero survives
  omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
  cmdutil.ClassifyContextErr collapse the three previously-duplicated
  multi-delete pipelines (doc / chunk / session) into one call site
  pattern. doc upload --recursive uses the same helpers with a per-
  file resultFn. Summary error sets Silent:true so the stderr
  envelope path doesn't duplicate the stdout batch detail (exit 1
  preserved via Code → ExitCode).

ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).

MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.

weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
  (stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
  envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
  envelope so --paginate never emits bare JSON to stdout.

Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
This commit is contained in:
nullkey
2026-05-21 18:41:56 +08:00
committed by lyingbug
parent 733bb3aaa1
commit ad150c7126
96 changed files with 2354 additions and 864 deletions
+2 -2
View File
@@ -124,8 +124,8 @@ func aggregateFailedCount(ctx context.Context, svc CheckService, kbID string) (i
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 fopts.Emit(w, res, nil)
case cmdutil.FormatHuman, "":
return writeCheckText(w, res)
default:
return fmt.Errorf("unsupported --format %q for kb check", fopts.Mode)
+7 -3
View File
@@ -95,10 +95,14 @@ func TestEmitCheck_JSON(t *testing.T) {
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 {
var env struct {
OK bool `json:"ok"`
Data CheckResult `json:"data"`
}
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
t.Fatalf("not JSON: %v\n%s", err, buf.String())
}
got := env.Data
if got.ID != "kb_x" || got.KnowledgeCount != 5 || got.FailedCount != 3 {
t.Errorf("got %+v", got)
}
@@ -112,7 +116,7 @@ func TestEmitCheck_TextHuman(t *testing.T) {
IsProcessing: true, ProcessingCount: 1,
FailedCount: 2,
}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
if err := emitCheck(res, fopts, &buf); err != nil {
t.Fatalf("emitCheck: %v", err)
}
+1 -1
View File
@@ -103,7 +103,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, created)
return fopts.Emit(iostreams.IO.Out, created, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)
return nil
+17 -11
View File
@@ -2,6 +2,7 @@ package kb
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
@@ -39,7 +40,7 @@ func TestCreate_Success_Human(t *testing.T) {
Description: "team docs",
EmbeddingModel: "model_x",
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
// Body sent to SDK matches flags.
require.NotNil(t, svc.got)
@@ -59,7 +60,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, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NotNil(t, svc.got)
assert.Equal(t, "", svc.got.EmbeddingModelID, "embedding-model unset ⇒ empty in request")
@@ -68,7 +69,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
func TestCreate_NameRequired(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@@ -80,7 +81,7 @@ func TestCreate_NameRequired(t *testing.T) {
func TestCreate_NameWhitespaceOnly(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@@ -91,7 +92,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"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@@ -102,7 +103,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"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@@ -117,16 +118,21 @@ func TestCreate_JSONOutput(t *testing.T) {
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb_99"`), "expected bare KnowledgeBase object; got %q", got)
var env struct {
OK bool `json:"ok"`
Data sdk.KnowledgeBase `json:"data"`
}
require.NoError(t, json.Unmarshal([]byte(got), &env), "expected valid JSON envelope, got %q", got)
assert.True(t, env.OK, "envelope.ok must be true")
assert.Equal(t, "kb_99", env.Data.ID, "envelope.data.id must be kb_99")
assert.Contains(t, got, `"name":"Eng"`)
assert.NotContains(t, got, `"ok":`)
}
func TestCreate_StorageProvider_InjectsRequest(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_s", Name: "n"}}
opts := &CreateOptions{Name: "n", StorageProvider: "Local"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NotNil(t, svc.got.StorageProviderConfig)
assert.Equal(t, "local", svc.got.StorageProviderConfig.Provider, "value should be lowercased + trimmed before send")
@@ -136,7 +142,7 @@ func TestCreate_StorageProvider_InvalidValueReturnsFlagError(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)
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
require.Error(t, err)
assert.Equal(t, 2, cmdutil.ExitCode(err), "invalid --storage-provider must exit 2 (flag validation)")
@@ -148,7 +154,7 @@ func TestCreate_StorageProvider_OmittedWhenEmpty(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_n", Name: "n"}}
opts := &CreateOptions{Name: "n"} // no --storage-provider
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
assert.Nil(t, svc.got.StorageProviderConfig, "empty flag must omit StorageProviderConfig (let server pick default)")
}
+13 -2
View File
@@ -67,11 +67,22 @@ exactly to guard against unintended deletes.`,
},
}
cmdutil.AddFormatFlag(cmd, kbDeleteFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "permanently delete a knowledge base and all its contents",
RequiredFlags: []string{"<kb-id> (positional)"},
Examples: []string{
"weknora kb delete kb_abc -y",
"weknora kb delete kb_abc -y --format json",
},
Warnings: []string{
"kb delete is irreversible; whole KB + docs + chunks gone. Never auto-add -y; surface the exit-10 prompt to the user and only retry after explicit approval.",
},
})
return cmd
}
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 {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "knowledge base", id, "kb.delete", "weknora kb delete "+id+" -y"); err != nil {
return err
}
@@ -80,7 +91,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOp
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted knowledge base %s\n", id)
return nil
+38 -10
View File
@@ -2,8 +2,8 @@ package kb
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -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, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_force"))
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_missing")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_nontty")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_nontty")
require.Error(t, err)
var typed *cmdutil.Error
@@ -80,9 +80,14 @@ func TestDelete_JSONOutput(t *testing.T) {
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)
assert.Contains(t, got, `"deleted":true`)
assert.NotContains(t, got, `"ok":`)
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
require.NoError(t, json.Unmarshal([]byte(got), &env), "expected valid JSON envelope, got %q", got)
assert.True(t, env.OK, "envelope.ok must be true")
assert.Equal(t, "kb_json", env.Data["id"], "envelope.data.id must be kb_json")
assert.Equal(t, true, env.Data["deleted"], "envelope.data.deleted must be true")
}
// The remaining tests cover the interactive confirm path which only fires
@@ -92,7 +97,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: true}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_yes"))
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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 +108,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: false}
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_no")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_no")
require.Error(t, err)
var typed *cmdutil.Error
@@ -118,7 +123,7 @@ func TestDelete_ConfirmPrompterError(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Err: prompt.ErrAgentNoPrompt}
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_err")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_err")
require.Error(t, err)
var typed *cmdutil.Error
@@ -159,3 +164,26 @@ func TestDelete_JSONOut_WithYes_Proceeds(t *testing.T) {
assert.True(t, svc.called)
assert.Contains(t, out.String(), `"deleted":true`)
}
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.
iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
opts := &DeleteOptions{Yes: false}
err := runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, p, "kb_x")
require.Error(t, err, "expected confirmation_required error")
ce := cmdutil.AsError(err)
require.NotNil(t, ce, "expected *cmdutil.Error; got %T %v", err, err)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
assert.False(t, svc.called, "SDK must not be called without confirmation")
assert.False(t, p.Asked, "--format json must not prompt even on test setup")
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")
}
+48 -3
View File
@@ -3,8 +3,10 @@ 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"
@@ -31,6 +33,7 @@ type EditOptions struct {
// clear the description.
Name *string
Description *string
Yes bool // sourced from global -y/--yes persistent flag
}
// EditService is the narrow SDK surface this command depends on. GetKnowledgeBase
@@ -53,7 +56,11 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
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.`,
server-side.
AI agents: this is a high-risk write. Without -y/--yes the CLI exits 10
with input.confirmation_required. Never auto-pass -y; surface the prompt
to the user first.`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -61,6 +68,7 @@ server-side.`,
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Yes, _ = c.Flags().GetBool("yes")
if c.Flag("name").Changed {
opts.Name = &name
}
@@ -71,15 +79,52 @@ server-side.`,
if err != nil {
return err
}
return runEdit(c.Context(), opts, fopts, cli, args[0])
id := args[0]
// 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(), "knowledge base", id, "kb.edit", retryCmd); err != nil {
return err
}
return runEdit(c.Context(), opts, fopts, cli, id)
},
}
cmd.Flags().StringVar(&name, "name", "", "New name (omit to leave unchanged)")
cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)")
cmdutil.AddFormatFlag(cmd, kbEditFields...)
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",
},
Warnings: []string{
"kb edit can change KB ownership / model config. Surface the exit-10 prompt to the user — only proceed after explicit approval.",
},
})
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{
@@ -112,7 +157,7 @@ func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOption
return cmdutil.WrapHTTP(err, "edit knowledge base %s", id)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, updated)
return fopts.Emit(iostreams.IO.Out, updated, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Updated knowledge base %s\n", id)
return nil
+52 -5
View File
@@ -5,11 +5,13 @@ import (
"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"
)
@@ -43,7 +45,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc")
err := runEdit(context.Background(), &EditOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -64,7 +66,7 @@ func TestEdit_OnlyName_PreservesCurrentDescription(t *testing.T) {
}
opts := &EditOptions{}
opts.Name = stringPtr("new")
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
assert.Equal(t, "kb_abc", svc.gotID)
require.NotNil(t, svc.gotReq)
@@ -83,7 +85,7 @@ func TestEdit_OnlyDescription_PreservesCurrentName(t *testing.T) {
}
opts := &EditOptions{}
opts.Description = stringPtr("new desc")
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
require.NotNil(t, svc.gotReq)
assert.Equal(t, "new desc", svc.gotReq.Description)
@@ -96,7 +98,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, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
assert.Equal(t, "renamed", svc.gotReq.Name)
assert.Equal(t, "new desc", svc.gotReq.Description)
}
@@ -108,7 +110,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, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing")
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -116,3 +118,48 @@ func TestEdit_NotFound(t *testing.T) {
}
func stringPtr(s string) *string { return &s }
// withRootHarnessKB wraps `weknora kb edit ...` 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.
func withRootHarnessKB(edit *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "Output format: human | json | ndjson")
pf.StringP("jq", "q", "", "")
kb := &cobra.Command{Use: "kb"}
kb.AddCommand(edit)
root.AddCommand(kb)
root.SetArgs(append([]string{"kb", "edit"}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
return root
}
// TestKBEdit_RequiresConfirmation asserts that without -y (non-TTY / JSON
// mode), kb edit returns input.confirmation_required (exit 10).
func TestKBEdit_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
svc := &fakeEditSvc{
current: &sdk.KnowledgeBase{ID: "kb_abc", Name: "old"},
resp: &sdk.KnowledgeBase{ID: "kb_abc", Name: "new"},
}
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
_ = svc // gate fires before SDK call
root := withRootHarnessKB(NewCmdEdit(f), "kb_abc", "--name", "new", "--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))
// retry command must include -y
assert.Contains(t, ce.RetryCommand, "-y")
assert.Contains(t, ce.RetryCommand, "kb_abc")
}
+11 -6
View File
@@ -11,6 +11,7 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
)
@@ -64,21 +65,21 @@ 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 (0 = no cap, 1..10000 = explicit)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
cmdutil.AddFormatFlag(cmd, kbListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List knowledge bases in the current tenant. Agents should use --format json to consume a stable {data, total, page, page_size} response.",
UsedFor: "List knowledge bases in the current tenant. --format json emits the v0.7 envelope {ok, data:[...], meta:{count}, profile}.",
Examples: []string{"weknora kb list --format json"},
Output: "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",
})
return cmd
}
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
if opts.Limit < 0 || opts.Limit > 10000 {
if opts.Limit < 1 || opts.Limit > 10000 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--limit must be in 0..10000 (0 = no cap), got %d", opts.Limit),
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
}
}
items, err := svc.ListKnowledgeBases(ctx)
@@ -104,12 +105,16 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
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.
if opts.Limit > 0 && len(items) > opts.Limit {
items = items[:opts.Limit]
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, items)
meta := &output.Meta{Count: len(items)}
return fopts.Emit(iostreams.IO.Out, items, meta)
}
if len(items) == 0 {
+35 -21
View File
@@ -25,7 +25,7 @@ func (f *fakeListSvc) ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBa
func TestList_Empty_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no knowledge bases)") {
@@ -36,12 +36,21 @@ func TestList_Empty_Human(t *testing.T) {
func TestList_Empty_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
t.Fatalf("runList: %v", err)
}
got := strings.TrimSpace(out.String())
if got != "[]" {
t.Errorf("empty JSON should be bare `[]`, got %q", got)
var env struct {
OK bool `json:"ok"`
Data []sdk.KnowledgeBase `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v\n%s", err, out.String())
}
if !env.OK {
t.Error("envelope.ok must be true")
}
if len(env.Data) != 0 {
t.Errorf("expected empty data, got %d items", len(env.Data))
}
}
@@ -52,7 +61,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
@@ -69,9 +78,9 @@ func TestList_JSON_JQProjection(t *testing.T) {
items := []sdk.KnowledgeBase{
{ID: "kb1", Name: "Marketing", Description: "MKT desc", UpdatedAt: now},
}
// --jq is the canonical projection mechanism in v0.6+.
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".[] | {id, name}"}
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
// --jq projects from the envelope; .data[] | ... extracts from the array inside envelope.
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data[] | {id, name}"}
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
var item map[string]any
@@ -93,8 +102,9 @@ func TestList_JSON_JQ(t *testing.T) {
{ID: "kb1", Name: "Marketing", UpdatedAt: now},
{ID: "kb2", Name: "Engineering", UpdatedAt: now.Add(-time.Hour)},
}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ". | length"}
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
// .data | length counts the items inside the envelope's data array.
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data | length"}
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
if got := strings.TrimSpace(out.String()); got != "2" {
@@ -110,7 +120,7 @@ func TestList_PinnedFilter(t *testing.T) {
{ID: "kb2", Name: "Engineering", IsPinned: false, UpdatedAt: now.Add(-time.Hour)},
{ID: "kb3", Name: "Finance", IsPinned: true, UpdatedAt: now.Add(-2 * time.Hour)},
}
if err := runList(context.Background(), &ListOptions{Pinned: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
@@ -127,7 +137,7 @@ func TestList_PinnedFilter_NoPinned_HumanMessage(t *testing.T) {
items := []sdk.KnowledgeBase{
{ID: "kb1", Name: "Marketing", IsPinned: false, UpdatedAt: time.Now()},
}
if err := runList(context.Background(), &ListOptions{Pinned: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no pinned knowledge bases)") {
@@ -162,22 +172,26 @@ func TestList_Limit_CapsResults(t *testing.T) {
}
}
func TestList_Limit_Zero_NoCap(t *testing.T) {
out, _ := iostreams.SetForTest(t)
func TestList_Limit_Zero_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{items: makeKBs(7)}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runList(context.Background(), &ListOptions{Limit: 0}, fopts, svc); err != nil {
t.Fatalf("runList: %v", err)
err := runList(context.Background(), &ListOptions{Limit: 0}, fopts, svc)
if err == nil {
t.Fatal("expected error for --limit 0")
}
got := strings.Count(out.String(), `"id":"kb_`)
if got != 7 {
t.Errorf("--limit 0 must not cap; got %d, want 7", got)
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T: %v", err, err)
}
if typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("expected CodeInputInvalidArgument, got %v", typed.Code)
}
}
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeKBs(3)})
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: makeKBs(3)})
if err == nil {
t.Fatal("expected error for negative --limit")
}
+2 -2
View File
@@ -79,7 +79,7 @@ func runPin(ctx context.Context, opts *PinOptions, fopts *cmdutil.FormatOptions,
// both fresh-toggle and no-op paths. Human path prints a confirming
// line; agents observe via the unchanged is_pinned field.
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, current)
return fopts.Emit(iostreams.IO.Out, current, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ %s is already %s\n", id, state)
return nil
@@ -90,7 +90,7 @@ func runPin(ctx context.Context, opts *PinOptions, fopts *cmdutil.FormatOptions,
return cmdutil.WrapHTTP(err, "%s knowledge base %s", verb, id)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, updated)
return fopts.Emit(iostreams.IO.Out, updated, nil)
}
state := "pinned"
if !updated.IsPinned {
+6 -6
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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", false))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", false))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing", true)
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, 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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true)
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+2 -2
View File
@@ -95,8 +95,8 @@ func runStatus(ctx context.Context, svc StatusService, id string) (*StatusResult
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 fopts.Emit(w, res, nil)
case cmdutil.FormatHuman, "":
return writeStatusText(w, res)
default:
return fmt.Errorf("unsupported --format %q for kb status", fopts.Mode)
+7 -3
View File
@@ -65,10 +65,14 @@ func TestEmitStatus_JSON(t *testing.T) {
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 {
var env struct {
OK bool `json:"ok"`
Data StatusResult `json:"data"`
}
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
t.Fatalf("not JSON: %v\n%s", err, buf.String())
}
got := env.Data
if got.ID != "kb_x" || got.KnowledgeCount != 5 {
t.Errorf("got %+v", got)
}
@@ -77,7 +81,7 @@ func TestEmitStatus_JSON(t *testing.T) {
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}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
if err := emitStatus(res, fopts, &buf); err != nil {
t.Fatalf("emitStatus: %v", err)
}
+1 -1
View File
@@ -62,7 +62,7 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
return cmdutil.WrapHTTP(err, "get knowledge base %q", id)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, kb)
return fopts.Emit(iostreams.IO.Out, kb, nil)
}
// Human: KEY: VALUE. Nested config structs (chunking_config, vlm_config,
// etc.) are intentionally omitted from the human render — those are for
+22 -14
View File
@@ -2,6 +2,7 @@ package kb
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
@@ -26,7 +27,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
t.Fatalf("runGet: %v", err)
}
got := out.String()
@@ -44,18 +45,25 @@ func TestGet_OK_JSON(t *testing.T) {
t.Fatalf("runGet: %v", err)
}
got := out.String()
if !strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb1"`) {
t.Errorf("expected bare object starting with id, got %q", got)
var env struct {
OK bool `json:"ok"`
Data sdk.KnowledgeBase `json:"data"`
}
if strings.Contains(got, `"ok":true`) {
t.Errorf("bare output must not carry envelope keys, got %q", got)
if err := json.Unmarshal([]byte(got), &env); err != nil {
t.Fatalf("parse: %v\n%s", err, got)
}
if !env.OK {
t.Errorf("envelope.ok must be true, got %q", got)
}
if env.Data.ID != "kb1" {
t.Errorf("expected id=kb1 in envelope.data, got %q", env.Data.ID)
}
}
func TestGet_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeGetSvc{err: errors.New("HTTP error 404: not found")}
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "missing")
if err == nil {
t.Fatal("expected error")
}
@@ -69,7 +77,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
if !strings.Contains(out.String(), "PINNED:") {
@@ -80,7 +88,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
for _, l := range strings.Split(out.String(), "\n") {
@@ -93,7 +101,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_t"); err != nil {
t.Fatalf("runView: %v", err)
}
if !strings.Contains(out.String(), "TEMPORARY:") {
@@ -104,7 +112,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -116,7 +124,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -128,7 +136,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_p"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_p"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -140,7 +148,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_idle"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_idle"); err != nil {
t.Fatalf("runView: %v", err)
}
for _, l := range strings.Split(out.String(), "\n") {
@@ -157,7 +165,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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()