Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(cli): add kb create/delete and doc list/upload/delete commands
nullkey8a0674186e24
diff --git a/cli/cmd/doc/delete.go b/cli/cmd/doc/delete.gonew file mode 100644index 000000000..0e36fce83--- /dev/null+++ b/cli/cmd/doc/delete.go@@ -0,0 +1,75 @@+package doc++import (+ "context"+ "fmt"++ "github.com/spf13/cobra"++ "github.com/Tencent/WeKnora/cli/internal/agent"+ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/format"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ "github.com/Tencent/WeKnora/cli/internal/prompt"+)++// DeleteOptions captures `weknora doc delete` flags.+type DeleteOptions struct {+ Force bool+ JSONOut bool+}++// DeleteService is the narrow SDK surface this command depends on.+// *sdk.Client satisfies it.+type DeleteService interface {+ DeleteKnowledge(ctx context.Context, id string) error+}++// deleteResult is the typed payload emitted under data on success.+type deleteResult struct {+ ID string `json:"id"`+ Deleted bool `json:"deleted"`+}++// NewCmdDelete builds `weknora doc delete`.+func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {+ opts := &DeleteOptions{}+ cmd := &cobra.Command{+ Use: "delete <id>",+ Short: "Delete a document from a knowledge base",+ Long: `Permanently deletes one document. Prompts for confirmation by default+when stdout is a TTY and --json is not set; pass --force to skip the prompt+(required in agent / CI / piped contexts).`,+ Example: ` weknora doc delete doc_abc # interactive confirm+ weknora doc delete doc_abc --force # no prompt+ weknora doc delete doc_abc --force --json # envelope output`,+ Args: cobra.ExactArgs(1),+ RunE: func(c *cobra.Command, args []string) error {+ cli, err := f.Client()+ if err != nil {+ return err+ }+ return runDelete(c.Context(), opts, cli, f.Prompter(), args[0])+ },+ }+ cmd.Flags().BoolVar(&opts.Force, "force", false, "Skip confirmation prompt")+ cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")+ agent.SetAgentHelp(cmd, "Destructively deletes one document by id. ALWAYS pass --force in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")+ return cmd+}++func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p prompt.Prompter, id string) error {+ if err := cmdutil.ConfirmDestructive(p, opts.Force, opts.JSONOut, "document", id); err != nil {+ return err+ }++ if err := svc.DeleteKnowledge(ctx, id); err != nil {+ return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete document %s", id)+ }++ if opts.JSONOut {+ return format.WriteEnvelope(iostreams.IO.Out, format.Success(deleteResult{ID: id, Deleted: true}, nil))+ }+ fmt.Fprintf(iostreams.IO.Out, "✓ Deleted document %s\n", id)+ return nil+}diff --git a/cli/cmd/doc/delete_test.go b/cli/cmd/doc/delete_test.gonew file mode 100644index 000000000..d47a3a13f--- /dev/null+++ b/cli/cmd/doc/delete_test.go@@ -0,0 +1,142 @@+package doc++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+)++// fakeDeleteSvc captures the id passed and returns a canned error.+type fakeDeleteSvc struct {+ err error+ got string+ calls int+}++func (f *fakeDeleteSvc) DeleteKnowledge(_ context.Context, id string) error {+ f.calls+++ f.got = id+ return f.err+}++// scriptedConfirm satisfies prompt.Prompter and returns predetermined answers.+type scriptedConfirm struct{ confirmReturn bool }++func (s scriptedConfirm) Input(string, string) (string, error) { return "", nil }+func (s scriptedConfirm) Password(string) (string, error) { return "", nil }+func (s scriptedConfirm) Confirm(string, bool) (bool, error) { return s.confirmReturn, nil }++// errPrompter returns an error from Confirm — simulates a non-TTY agent+// prompter.+type errPrompter struct{}++func (errPrompter) Input(string, string) (string, error) { return "", nil }+func (errPrompter) Password(string) (string, error) { return "", nil }+func (errPrompter) Confirm(string, bool) (bool, error) {+ return false, errors.New("no tty")+}++func TestDelete_Success_WithForce(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{}+ opts := &DeleteOptions{Force: true}+ // Force=true short-circuits the confirm path; the prompter must not be+ // consulted, so any value works.+ require.NoError(t, runDelete(context.Background(), opts, svc, scriptedConfirm{confirmReturn: false}, "doc_abc"))++ assert.Equal(t, "doc_abc", svc.got)+ assert.Equal(t, 1, svc.calls)+ assert.Contains(t, out.String(), "✓")+ assert.Contains(t, out.String(), "doc_abc")+}++func TestDelete_Success_JSON(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{}+ opts := &DeleteOptions{Force: true, JSONOut: true}+ require.NoError(t, runDelete(context.Background(), opts, svc, scriptedConfirm{confirmReturn: true}, "doc_abc"))++ got := out.String()+ assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)+ assert.Contains(t, got, `"id":"doc_abc"`)+ assert.Contains(t, got, `"deleted":true`)+}++func TestDelete_NotFound_404(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}+ err := runDelete(context.Background(), &DeleteOptions{Force: true}, svc, scriptedConfirm{}, "doc_missing")+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)+}++func TestDelete_HTTPError_500(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{err: errors.New("HTTP error 500: internal")}+ err := runDelete(context.Background(), &DeleteOptions{Force: true}, svc, scriptedConfirm{}, "doc_x")+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeServerError, typed.Code)+}++func TestDelete_ConfirmYes(t *testing.T) {+ out, _ := iostreams.SetForTestWithTTY(t)+ svc := &fakeDeleteSvc{}+ err := runDelete(context.Background(), &DeleteOptions{Force: false}, svc, scriptedConfirm{confirmReturn: true}, "doc_abc")+ require.NoError(t, err)+ assert.Equal(t, 1, svc.calls, "user said yes ⇒ delete proceeds")+ assert.Contains(t, out.String(), "✓")+}++func TestDelete_ConfirmNo(t *testing.T) {+ _, errBuf := iostreams.SetForTestWithTTY(t)+ svc := &fakeDeleteSvc{}+ err := runDelete(context.Background(), &DeleteOptions{Force: false}, svc, scriptedConfirm{confirmReturn: false}, "doc_abc")+ require.Error(t, err)+ assert.Equal(t, 0, svc.calls, "user said no ⇒ SDK must NOT be called")++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeUserAborted, typed.Code)+ assert.Contains(t, errBuf.String(), "Aborted.")+}++// TestDelete_AgentPrompterErrors covers the path where the prompter itself+// returns an error (e.g. AgentPrompter, broken stdin). runDelete maps this to+// CodeInputMissingFlag so the user sees "pass --force" in the hint.+func TestDelete_AgentPrompterErrors(t *testing.T) {+ _, _ = iostreams.SetForTestWithTTY(t)+ svc := &fakeDeleteSvc{}+ err := runDelete(context.Background(), &DeleteOptions{Force: false}, svc, errPrompter{}, "doc_abc")+ require.Error(t, err)+ assert.Equal(t, 0, svc.calls)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code)+}++// TestDelete_NoForce_NonTTY_Proceeds: when stdout isn't a TTY (typical agent+// pipe / CI), the confirm guard is skipped. This documents the existing+// contract — destructive ops in a pipe rely on the caller having chosen to+// pipe (intent expressed by the redirection) and on agents passing --force+// explicitly. Mirrors `weknora kb delete`.+func TestDelete_NoForce_NonTTY_Proceeds(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{}+ err := runDelete(context.Background(), &DeleteOptions{Force: false}, svc, errPrompter{}, "doc_abc")+ require.NoError(t, err, "non-TTY non-json invocation should proceed without prompting")+ assert.Equal(t, 1, svc.calls)+}diff --git a/cli/cmd/doc/doc.go b/cli/cmd/doc/doc.gonew file mode 100644index 000000000..2ab4cba53--- /dev/null+++ b/cli/cmd/doc/doc.go@@ -0,0 +1,27 @@+// Package doc implements the `weknora doc` subtree (list / upload / delete).+//+// "Doc" is the CLI noun; the underlying SDK type is `Knowledge`. The renaming+// is deliberate: end-users think of a knowledge entry as the document they+// uploaded, not as an abstract knowledge unit. Mapping happens in this package+// only — the SDK surface and server API keep the original spelling.+package doc++import (+ "github.com/spf13/cobra"++ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+)++// NewCmd builds the `weknora doc` parent command.+func NewCmd(f *cmdutil.Factory) *cobra.Command {+ cmd := &cobra.Command{+ Use: "doc",+ Short: "Manage documents in a knowledge base",+ Args: cobra.NoArgs,+ Run: func(c *cobra.Command, _ []string) { _ = c.Help() },+ }+ cmd.AddCommand(NewCmdList(f))+ cmd.AddCommand(NewCmdUpload(f))+ cmd.AddCommand(NewCmdDelete(f))+ return cmd+}diff --git a/cli/cmd/doc/list.go b/cli/cmd/doc/list.gonew file mode 100644index 000000000..6c3020199--- /dev/null+++ b/cli/cmd/doc/list.go@@ -0,0 +1,161 @@+package doc++import (+ "context"+ "fmt"+ "sort"+ "text/tabwriter"+ "time"++ "github.com/spf13/cobra"++ "github.com/Tencent/WeKnora/cli/internal/agent"+ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/format"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ "github.com/Tencent/WeKnora/cli/internal/text"+ sdk "github.com/Tencent/WeKnora/client"+)++// ListOptions captures `weknora doc list` flags.+type ListOptions struct {+ Page int+ PageSize int+ JSONOut bool+}++// ListService is the narrow SDK surface this command depends on.+// *sdk.Client satisfies it.+type ListService interface {+ ListKnowledge(ctx context.Context, kbID string, page, pageSize int, tagID string) ([]sdk.Knowledge, int64, error)+}++// listResult is the typed payload emitted under data on success.+//+// Items is non-nil even when empty (json:"[]" not "null") so agents can iterate+// without nil-checks. Page metadata is duplicated here (and not in _meta) to+// keep the payload self-describing for downstream consumers that strip _meta.+type listResult struct {+ Items []sdk.Knowledge `json:"items"`+ Page int `json:"page"`+ PageSize int `json:"page_size"`+ Total int64 `json:"total"`+ KBID string `json:"kb_id"`+}++// NewCmdList builds `weknora doc list`.+func NewCmdList(f *cmdutil.Factory) *cobra.Command {+ opts := &ListOptions{}+ cmd := &cobra.Command{+ Use: "list",+ Short: "List documents in a knowledge base",+ Long: `Lists documents (uploaded files / web pages / inline text) in the+resolved knowledge base. KB id resolution follows the standard 5-level chain:+--kb-id flag > --kb name > WEKNORA_KB_ID env > .weknora/project.yaml > error.++Default sort is updated_at desc so the most recent uploads surface first;+backend storage order is not guaranteed and varies between deployments.`,+ Example: ` weknora doc list # uses project link / env+ weknora doc list --kb-id kb_abc # explicit+ weknora doc list --page 2 --json # paginated envelope output`,+ Args: cobra.NoArgs,+ RunE: func(c *cobra.Command, _ []string) error {+ kbID, err := f.ResolveKB(c)+ if err != nil {+ return err+ }+ cli, err := f.Client()+ if err != nil {+ return err+ }+ return runList(c.Context(), opts, cli, kbID)+ },+ }+ // --kb-id / --kb are read by Factory.ResolveKB; declare them here so+ // Cobra parses the values into the command's flag set.+ cmd.Flags().String("kb-id", "", "Knowledge base id (overrides env / project link)")+ cmd.Flags().String("kb", "", "Knowledge base name (resolved to id)")+ cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)")+ cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page")+ cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")+ cmd.MarkFlagsMutuallyExclusive("kb-id", "kb")+ agent.SetAgentHelp(cmd, "Lists docs in the resolved KB. Returns data: {items, page, page_size, total, kb_id}; pass --kb-id when not running inside a project.")+ return cmd+}++func runList(ctx context.Context, opts *ListOptions, svc ListService, kbID string) error {+ items, total, err := svc.ListKnowledge(ctx, kbID, opts.Page, opts.PageSize, "")+ if err != nil {+ return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list documents")+ }+ if items == nil {+ items = []sdk.Knowledge{} // ensure JSON [] not null+ }+ // Default sort: updated_at desc. Server return order is not guaranteed,+ // so client-side sort makes output deterministic regardless of backend+ // storage choices. Mirrors `weknora kb list`.+ sort.Slice(items, func(i, j int) bool {+ return items[i].UpdatedAt.After(items[j].UpdatedAt)+ })++ r := listResult{+ Items: items,+ Page: opts.Page,+ PageSize: opts.PageSize,+ Total: total,+ KBID: kbID,+ }+ if opts.JSONOut {+ return format.WriteEnvelope(iostreams.IO.Out, format.Success(r, &format.Meta{KBID: kbID}))+ }++ if len(items) == 0 {+ fmt.Fprintln(iostreams.IO.Out, "(no documents)")+ return nil+ }++ tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)+ fmt.Fprintln(tw, "ID\tNAME\tSTATUS\tSIZE\tUPDATED")+ now := time.Now()+ for _, k := range items {+ name := text.Truncate(40, displayName(k))+ updated := text.FuzzyAgo(now, k.UpdatedAt)+ fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", k.ID, name, k.ParseStatus, formatSize(k.FileSize), updated)+ }+ return tw.Flush()+}++// displayName picks the most informative human label for a knowledge entry.+// File-uploads use FileName; URL / text entries fall back to Title.+func displayName(k sdk.Knowledge) string {+ if k.FileName != "" {+ return k.FileName+ }+ if k.Title != "" {+ return k.Title+ }+ return k.ID+}++// formatSize renders a byte count as a short human string (KB / MB).+// Kept tiny on purpose — go-humanize would pull a transitive dep just for one+// column. A "-" placeholder hides zero-size entries (URL / text).+func formatSize(bytes int64) string {+ if bytes <= 0 {+ return "-"+ }+ const (+ kb = 1 << 10+ mb = 1 << 20+ gb = 1 << 30+ )+ switch {+ case bytes >= gb:+ return fmt.Sprintf("%.1fGB", float64(bytes)/float64(gb))+ case bytes >= mb:+ return fmt.Sprintf("%.1fMB", float64(bytes)/float64(mb))+ case bytes >= kb:+ return fmt.Sprintf("%.1fKB", float64(bytes)/float64(kb))+ }+ return fmt.Sprintf("%dB", bytes)+}diff --git a/cli/cmd/doc/list_test.go b/cli/cmd/doc/list_test.gonew file mode 100644index 000000000..e9aebe64c--- /dev/null+++ b/cli/cmd/doc/list_test.go@@ -0,0 +1,219 @@+package doc++import (+ "context"+ "errors"+ "os"+ "strings"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/config"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ sdk "github.com/Tencent/WeKnora/client"+)++// fakeListSvc captures the request args and returns canned responses.+type fakeListSvc struct {+ items []sdk.Knowledge+ total int64+ err error+ got struct {+ kbID string+ page int+ pageSize int+ tagID string+ }+}++func (f *fakeListSvc) ListKnowledge(_ context.Context, kbID string, page, pageSize int, tagID string) ([]sdk.Knowledge, int64, error) {+ f.got.kbID, f.got.page, f.got.pageSize, f.got.tagID = kbID, page, pageSize, tagID+ return f.items, f.total, f.err+}++// chdirIsolated parks cwd in a fresh tempdir so Factory.ResolveKB doesn't pick+// up a stray .weknora/project.yaml from the repo. Also clears WEKNORA_KB_ID+// for the duration of the test.+func chdirIsolated(t *testing.T) {+ t.Helper()+ prev, err := os.Getwd()+ require.NoError(t, err)+ require.NoError(t, os.Chdir(t.TempDir()))+ t.Cleanup(func() { _ = os.Chdir(prev) })+ t.Setenv("WEKNORA_KB_ID", "")+}++func TestList_Success_Human(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ now := time.Now()+ items := []sdk.Knowledge{+ {ID: "doc1", FileName: "alpha.pdf", FileSize: 2048, ParseStatus: "completed", UpdatedAt: now.Add(-1 * time.Hour)},+ {ID: "doc2", FileName: "beta.md", FileSize: 0, ParseStatus: "pending", UpdatedAt: now.Add(-2 * 24 * time.Hour)},+ }+ svc := &fakeListSvc{items: items, total: 2}+ opts := &ListOptions{Page: 1, PageSize: 20}+ require.NoError(t, runList(context.Background(), opts, svc, "kb_xxx"))++ assert.Equal(t, "kb_xxx", svc.got.kbID)+ assert.Equal(t, 1, svc.got.page)+ assert.Equal(t, 20, svc.got.pageSize)+ assert.Equal(t, "", svc.got.tagID, "doc list does not filter by tag")++ got := out.String()+ for _, want := range []string{"ID", "NAME", "STATUS", "SIZE", "UPDATED", "doc1", "alpha.pdf", "completed", "2.0KB", "doc2", "beta.md", "pending"} {+ if !strings.Contains(got, want) {+ t.Errorf("output missing %q in:\n%s", want, got)+ }+ }+}++func TestList_Success_JSON(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeListSvc{items: []sdk.Knowledge{{ID: "doc1", FileName: "a.pdf"}}, total: 1}+ opts := &ListOptions{Page: 1, PageSize: 20, JSONOut: true}+ require.NoError(t, runList(context.Background(), opts, svc, "kb_xxx"))++ got := out.String()+ assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)+ assert.Contains(t, got, `"items":[`)+ assert.Contains(t, got, `"id":"doc1"`)+ assert.Contains(t, got, `"page":1`)+ assert.Contains(t, got, `"page_size":20`)+ assert.Contains(t, got, `"total":1`)+ assert.Contains(t, got, `"kb_id":"kb_xxx"`)+}++func TestList_Empty_Human(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeListSvc{items: nil, total: 0}+ opts := &ListOptions{Page: 1, PageSize: 20}+ require.NoError(t, runList(context.Background(), opts, svc, "kb_xxx"))+ assert.Contains(t, out.String(), "(no documents)")+}++func TestList_Empty_JSON(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeListSvc{items: nil, total: 0}+ opts := &ListOptions{Page: 1, PageSize: 20, JSONOut: true}+ require.NoError(t, runList(context.Background(), opts, svc, "kb_xxx"))++ got := out.String()+ assert.Contains(t, got, `"items":[]`, "items must serialize as [] not null")+ assert.NotContains(t, got, `"items":null`)+}++func TestList_HTTPError_500(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeListSvc{err: errors.New("HTTP error 500: internal")}+ opts := &ListOptions{Page: 1, PageSize: 20}+ err := runList(context.Background(), opts, svc, "kb_xxx")+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeServerError, typed.Code)+}++// TestList_KBIDRequired drives the cobra layer to verify Factory.ResolveKB's+// "no source supplied" path bubbles up as CodeKBIDRequired. Isolates cwd so+// no project.yaml sneaks in, and clears WEKNORA_KB_ID.+func TestList_KBIDRequired(t *testing.T) {+ chdirIsolated(t)+ _, _ = iostreams.SetForTest(t)++ cfg := &config.Config{+ CurrentContext: "default",+ Contexts: map[string]config.Context{"default": {Host: "https://example"}},+ }+ f := &cmdutil.Factory{+ Config: func() (*config.Config, error) { return cfg, nil },+ Client: func() (*sdk.Client, error) { return nil, errors.New("client should not be called when kb id is missing") },+ }+ cmd := NewCmdList(f)+ cmd.SetContext(context.Background())+ cmd.SetArgs([]string{}) // no --kb-id, no --kb+ cmd.SilenceErrors = true+ cmd.SilenceUsage = true+ err := cmd.Execute()+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)+}++// TestList_KBIDFlagWiredToResolveKB confirms that a --kb-id passed at the+// cobra layer reaches Factory.ResolveKB and skips the Client() call.+func TestList_KBIDFlagWiredToResolveKB(t *testing.T) {+ chdirIsolated(t)+ _, _ = iostreams.SetForTest(t)++ cfg := &config.Config{+ CurrentContext: "default",+ Contexts: map[string]config.Context{"default": {Host: "https://example"}},+ }+ f := &cmdutil.Factory{+ Config: func() (*config.Config, error) { return cfg, nil },+ Client: func() (*sdk.Client, error) {+ return nil, errors.New("forced-after-resolvekb")+ },+ }+ // With --kb-id supplied, ResolveKB short-circuits without consulting the+ // client. The RunE then asks for the client to run the actual list — that+ // call triggers the forced error. Surfacing "forced-after-resolvekb"+ // (rather than CodeKBIDRequired) is the proof point that --kb-id was+ // honored.+ cmd := NewCmdList(f)+ cmd.SetContext(context.Background())+ cmd.SetArgs([]string{"--kb-id", "kb_explicit"})+ cmd.SilenceErrors = true+ cmd.SilenceUsage = true+ err := cmd.Execute()+ require.Error(t, err, "expected client construction error")+ assert.Contains(t, err.Error(), "forced-after-resolvekb",+ "should surface the Client closure error, not a kb-id-required error")+}++// pinning the sort order: most-recent-first regardless of input order.+func TestList_SortByUpdatedDesc(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ now := time.Now()+ // Server returns oldest first; CLI must reorder.+ items := []sdk.Knowledge{+ {ID: "old", FileName: "old.pdf", UpdatedAt: now.Add(-10 * 24 * time.Hour)},+ {ID: "new", FileName: "new.pdf", UpdatedAt: now.Add(-1 * time.Hour)},+ }+ svc := &fakeListSvc{items: items, total: 2}+ require.NoError(t, runList(context.Background(), &ListOptions{Page: 1, PageSize: 20}, svc, "kb_xxx"))++ got := out.String()+ newIdx := strings.Index(got, "new.pdf")+ oldIdx := strings.Index(got, "old.pdf")+ require.GreaterOrEqual(t, newIdx, 0)+ require.GreaterOrEqual(t, oldIdx, 0)+ assert.Less(t, newIdx, oldIdx, "most-recent should render first")+}++// TestFormatSize sanity-checks the byte-count formatter without exporting it.+func TestFormatSize(t *testing.T) {+ cases := []struct {+ in int64+ want string+ }{+ {0, "-"},+ {-1, "-"},+ {900, "900B"},+ {2048, "2.0KB"},+ {5 * 1024 * 1024, "5.0MB"},+ }+ for _, c := range cases {+ if got := formatSize(c.in); got != c.want {+ t.Errorf("formatSize(%d) = %q, want %q", c.in, got, c.want)+ }+ }+}+diff --git a/cli/cmd/doc/upload.go b/cli/cmd/doc/upload.gonew file mode 100644index 000000000..82e985377--- /dev/null+++ b/cli/cmd/doc/upload.go@@ -0,0 +1,124 @@+package doc++import (+ "context"+ "fmt"+ "os"++ "github.com/spf13/cobra"++ "github.com/Tencent/WeKnora/cli/internal/agent"+ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/format"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ sdk "github.com/Tencent/WeKnora/client"+)++// uploadChannel is the ingestion-channel tag the server records for CLI uploads.+// Distinct from "web" (browser UI), "browser_extension" (one-click capture),+// and "wechat" (mini-program). The server uses this only for analytics.+const uploadChannel = "api"++// UploadOptions captures `weknora doc upload` flags.+type UploadOptions struct {+ Name string+ JSONOut bool+}++// UploadService is the narrow SDK surface this command depends on.+// *sdk.Client satisfies it.+type UploadService interface {+ CreateKnowledgeFromFile(+ ctx context.Context,+ kbID, filePath string,+ metadata map[string]string,+ enableMultimodel *bool,+ customFileName, channel string,+ ) (*sdk.Knowledge, error)+}++// NewCmdUpload builds `weknora doc upload <file>`.+func NewCmdUpload(f *cmdutil.Factory) *cobra.Command {+ opts := &UploadOptions{}+ cmd := &cobra.Command{+ Use: "upload <file>",+ Short: "Upload a local file to the knowledge base",+ Long: `Uploads a file (PDF / DOCX / Markdown / TXT / etc.) to the resolved+knowledge base. KB id resolution follows the standard 5-level chain:+--kb-id flag > --kb name > WEKNORA_KB_ID env > .weknora/project.yaml > error.++Pass --name to override the recorded file name (useful when the local file+has a generic name like "report.pdf" but you want to surface it as e.g.+"Q3 Marketing Report.pdf" in the UI).++v0.2 ships single-file upload only; --recursive / --glob and progress UI are+planned for v0.3.`,+ Example: ` weknora doc upload report.pdf+ weknora doc upload notes.md --kb-id kb_abc+ weknora doc upload q3.pdf --name "Q3 Marketing Report.pdf"`,+ Args: cobra.ExactArgs(1),+ RunE: func(c *cobra.Command, args []string) error {+ path := args[0]+ if err := validateUploadPath(path); err != nil {+ return err+ }+ kbID, err := f.ResolveKB(c)+ if err != nil {+ return err+ }+ cli, err := f.Client()+ if err != nil {+ return err+ }+ return runUpload(c.Context(), opts, cli, kbID, path)+ },+ }+ cmd.Flags().String("kb-id", "", "Knowledge base id (overrides env / project link)")+ cmd.Flags().String("kb", "", "Knowledge base name (resolved to id)")+ cmd.Flags().StringVar(&opts.Name, "name", "", "Custom file name to record (defaults to base name)")+ cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")+ cmd.MarkFlagsMutuallyExclusive("kb-id", "kb")+ agent.SetAgentHelp(cmd, "Uploads one local file to the resolved KB. Refuses non-regular files (dir / symlink). Returns data: Knowledge object with id, parse_status. Pass --kb-id outside a linked project.")+ return cmd+}++// validateUploadPath checks that path exists and refers to a regular file.+// Symlinks and directories are rejected up-front so users get a typed error+// instead of an opaque SDK failure mid-upload. os.Stat (not Lstat) is used+// here so a symlink to a regular file is accepted — that matches what+// `cp` / `git add` do, and the SDK opens the file via os.Open which follows+// symlinks anyway.+func validateUploadPath(path string) error {+ info, err := os.Stat(path)+ if err != nil {+ if os.IsNotExist(err) {+ return cmdutil.Wrapf(cmdutil.CodeUploadFileNotFound, err, "file not found: %s", path)+ }+ return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "stat %s", path)+ }+ if !info.Mode().IsRegular() {+ return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,+ fmt.Sprintf("not a regular file: %s (directories and devices are not supported)", path))+ }+ return nil+}++func runUpload(ctx context.Context, opts *UploadOptions, svc UploadService, kbID, path string) error {+ k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, nil /*metadata*/, nil /*enableMultimodel*/, opts.Name, uploadChannel)+ if err != nil {+ return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "upload %s", path)+ }++ if opts.JSONOut {+ return format.WriteEnvelope(iostreams.IO.Out, format.Success(k, &format.Meta{KBID: kbID}))+ }+ displayed := opts.Name+ if displayed == "" {+ displayed = k.FileName+ }+ if displayed == "" {+ displayed = path+ }+ fmt.Fprintf(iostreams.IO.Out, "✓ Uploaded %q (id: %s)\n", displayed, k.ID)+ return nil+}diff --git a/cli/cmd/doc/upload_test.go b/cli/cmd/doc/upload_test.gonew file mode 100644index 000000000..b7ebb055a--- /dev/null+++ b/cli/cmd/doc/upload_test.go@@ -0,0 +1,157 @@+package doc++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ sdk "github.com/Tencent/WeKnora/client"+)++// fakeUploadSvc captures call arguments and returns canned responses.+type fakeUploadSvc struct {+ resp *sdk.Knowledge+ err error+ got struct {+ kbID, filePath, customName, channel string+ metadata map[string]string+ enableMultimodel *bool+ }+}++func (f *fakeUploadSvc) CreateKnowledgeFromFile(+ _ context.Context,+ kbID, filePath string,+ metadata map[string]string,+ enableMultimodel *bool,+ customFileName, channel string,+) (*sdk.Knowledge, error) {+ f.got.kbID = kbID+ f.got.filePath = filePath+ f.got.metadata = metadata+ f.got.enableMultimodel = enableMultimodel+ f.got.customName = customFileName+ f.got.channel = channel+ return f.resp, f.err+}++// writeTempFile creates a regular file under t.TempDir() with sample content.+func writeTempFile(t *testing.T, name string) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), name)+ require.NoError(t, os.WriteFile(path, []byte("hello world"), 0o644))+ return path+}++func TestUpload_Success_Human(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ path := writeTempFile(t, "report.pdf")+ svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_99", FileName: "report.pdf"}}+ opts := &UploadOptions{}+ require.NoError(t, runUpload(context.Background(), opts, svc, "kb_xxx", path))++ assert.Equal(t, "kb_xxx", svc.got.kbID)+ assert.Equal(t, path, svc.got.filePath)+ assert.Equal(t, "", svc.got.customName, "no --name ⇒ empty (server uses base name)")+ assert.Equal(t, uploadChannel, svc.got.channel)+ assert.Nil(t, svc.got.metadata)+ assert.Nil(t, svc.got.enableMultimodel)++ got := out.String()+ for _, want := range []string{"✓", "Uploaded", "report.pdf", "doc_99"} {+ if !strings.Contains(got, want) {+ t.Errorf("output missing %q in:\n%s", want, got)+ }+ }+}++func TestUpload_Success_CustomName(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ path := writeTempFile(t, "q3.pdf")+ svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_88", FileName: "q3.pdf"}}+ opts := &UploadOptions{Name: "Q3 Marketing Report.pdf"}+ require.NoError(t, runUpload(context.Background(), opts, svc, "kb_xxx", path))+ assert.Equal(t, "Q3 Marketing Report.pdf", svc.got.customName)+}++func TestUpload_Success_JSON(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ path := writeTempFile(t, "a.md")+ svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_77", FileName: "a.md"}}+ opts := &UploadOptions{JSONOut: true}+ require.NoError(t, runUpload(context.Background(), opts, svc, "kb_xxx", path))++ got := out.String()+ assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)+ assert.Contains(t, got, `"id":"doc_77"`)+ assert.Contains(t, got, `"file_name":"a.md"`)+ assert.Contains(t, got, `"kb_id":"kb_xxx"`, "_meta.kb_id should carry the resolved kb id")+}++func TestUpload_HTTPError_500(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ path := writeTempFile(t, "x.txt")+ svc := &fakeUploadSvc{err: errors.New("HTTP error 500: internal")}+ err := runUpload(context.Background(), &UploadOptions{}, svc, "kb_xxx", path)+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeServerError, typed.Code)+}++func TestUpload_HTTPError_409Conflict(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ path := writeTempFile(t, "dup.pdf")+ svc := &fakeUploadSvc{err: errors.New("HTTP error 409: file exists")}+ err := runUpload(context.Background(), &UploadOptions{}, svc, "kb_xxx", path)+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeResourceAlreadyExists, typed.Code)+}++func TestValidateUploadPath_NotFound(t *testing.T) {+ missing := filepath.Join(t.TempDir(), "does-not-exist.pdf")+ err := validateUploadPath(missing)+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeUploadFileNotFound, typed.Code)+}++func TestValidateUploadPath_DirectoryRejected(t *testing.T) {+ dir := t.TempDir() // already exists, is a dir+ err := validateUploadPath(dir)+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)+ assert.Contains(t, typed.Message, "not a regular file")+}++func TestValidateUploadPath_RegularFileAccepted(t *testing.T) {+ path := writeTempFile(t, "ok.txt")+ require.NoError(t, validateUploadPath(path))+}++func TestValidateUploadPath_SymlinkToFileAccepted(t *testing.T) {+ target := writeTempFile(t, "target.txt")+ link := filepath.Join(t.TempDir(), "link.txt")+ if err := os.Symlink(target, link); err != nil {+ t.Skipf("symlink not supported on this platform: %v", err)+ }+ // os.Stat (not Lstat) should follow the symlink and report regular file.+ require.NoError(t, validateUploadPath(link))+}diff --git a/cli/cmd/kb/create.go b/cli/cmd/kb/create.gonew file mode 100644index 000000000..3a428001d--- /dev/null+++ b/cli/cmd/kb/create.go@@ -0,0 +1,81 @@+package kb++import (+ "context"+ "fmt"+ "strings"++ "github.com/spf13/cobra"++ "github.com/Tencent/WeKnora/cli/internal/agent"+ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/format"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ sdk "github.com/Tencent/WeKnora/client"+)++// CreateOptions captures `weknora kb create` flags.+type CreateOptions struct {+ Name string+ Description string+ EmbeddingModel string+ JSONOut bool+}++// CreateService is the narrow SDK surface this command depends on.+// *sdk.Client satisfies it via duck typing (ADR-4).+type CreateService interface {+ CreateKnowledgeBase(ctx context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error)+}++// NewCmdCreate builds `weknora kb create`.+func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {+ opts := &CreateOptions{}+ cmd := &cobra.Command{+ Use: "create --name <name>",+ Short: "Create a new knowledge base",+ Args: cobra.NoArgs,+ RunE: func(c *cobra.Command, _ []string) error {+ cli, err := f.Client()+ if err != nil {+ return err+ }+ return runCreate(c.Context(), opts, cli)+ },+ }+ cmd.Flags().StringVar(&opts.Name, "name", "", "Knowledge base name (required)")+ cmd.Flags().StringVar(&opts.Description, "description", "", "Knowledge base description (optional)")+ cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)")+ cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")+ agent.SetAgentHelp(cmd, "Creates a knowledge base under the active context. --name is required; --description and --embedding-model are optional. Returns data: full KnowledgeBase object including the new id.")+ return cmd+}++func runCreate(ctx context.Context, opts *CreateOptions, svc CreateService) error {+ // Validate locally before any HTTP — keeps `input.invalid_argument`+ // distinct from a server-side 400.+ if strings.TrimSpace(opts.Name) == "" {+ return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--name is required")+ }++ req := &sdk.KnowledgeBase{+ Name: opts.Name,+ Description: opts.Description,+ }+ if opts.EmbeddingModel != "" {+ req.EmbeddingModelID = opts.EmbeddingModel+ }++ created, err := svc.CreateKnowledgeBase(ctx, req)+ if err != nil {+ return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "create knowledge base")+ }++ if opts.JSONOut {+ return format.WriteEnvelope(iostreams.IO.Out, format.Success(created, &format.Meta{+ KBID: created.ID,+ }))+ }+ fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)+ return nil+}diff --git a/cli/cmd/kb/create_test.go b/cli/cmd/kb/create_test.gonew file mode 100644index 000000000..58a5b301b--- /dev/null+++ b/cli/cmd/kb/create_test.go@@ -0,0 +1,124 @@+package kb++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ sdk "github.com/Tencent/WeKnora/client"+)++// fakeCreateSvc captures the request and returns canned responses.+type fakeCreateSvc struct {+ resp *sdk.KnowledgeBase+ err error+ got *sdk.KnowledgeBase+}++func (f *fakeCreateSvc) CreateKnowledgeBase(_ context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error) {+ f.got = kb+ return f.resp, f.err+}++func TestCreate_Success_Human(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{+ ID: "kb_new",+ Name: "Marketing",+ Description: "team docs",+ EmbeddingModelID: "model_x",+ }}+ opts := &CreateOptions{+ Name: "Marketing",+ Description: "team docs",+ EmbeddingModel: "model_x",+ }+ require.NoError(t, runCreate(context.Background(), opts, svc))++ // Body sent to SDK matches flags.+ require.NotNil(t, svc.got)+ assert.Equal(t, "Marketing", svc.got.Name)+ assert.Equal(t, "team docs", svc.got.Description)+ assert.Equal(t, "model_x", svc.got.EmbeddingModelID)++ got := out.String()+ for _, want := range []string{"✓", "Created", "Marketing", "kb_new"} {+ if !strings.Contains(got, want) {+ t.Errorf("output missing %q in:\n%s", want, got)+ }+ }+}++func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_x", Name: "n"}}+ opts := &CreateOptions{Name: "n"}+ require.NoError(t, runCreate(context.Background(), opts, svc))++ require.NotNil(t, svc.got)+ assert.Equal(t, "", svc.got.EmbeddingModelID, "embedding-model unset ⇒ empty in request")+}++func TestCreate_NameRequired(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeCreateSvc{}+ err := runCreate(context.Background(), &CreateOptions{}, svc)+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)+ assert.Nil(t, svc.got, "service must not be called when name is missing")+}++func TestCreate_NameWhitespaceOnly(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeCreateSvc{}+ err := runCreate(context.Background(), &CreateOptions{Name: " "}, svc)+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)+}++func TestCreate_HTTPError_500(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal")}+ err := runCreate(context.Background(), &CreateOptions{Name: "x"}, svc)+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeServerError, typed.Code)+}++func TestCreate_HTTPError_409Conflict(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeCreateSvc{err: errors.New("HTTP error 409: name exists")}+ err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, svc)+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeResourceAlreadyExists, typed.Code)+}++func TestCreate_JSONOutput(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_99", Name: "Eng"}}+ opts := &CreateOptions{Name: "Eng", JSONOut: true}+ require.NoError(t, runCreate(context.Background(), opts, svc))++ got := out.String()+ assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)+ assert.Contains(t, got, `"id":"kb_99"`)+ assert.Contains(t, got, `"name":"Eng"`)+ assert.Contains(t, got, `"kb_id":"kb_99"`, "_meta.kb_id should carry the new id")+}diff --git a/cli/cmd/kb/delete.go b/cli/cmd/kb/delete.gonew file mode 100644index 000000000..5ed7235a5--- /dev/null+++ b/cli/cmd/kb/delete.go@@ -0,0 +1,78 @@+package kb++import (+ "context"+ "fmt"++ "github.com/spf13/cobra"++ "github.com/Tencent/WeKnora/cli/internal/agent"+ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/format"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ "github.com/Tencent/WeKnora/cli/internal/prompt"+)++// DeleteOptions captures `weknora kb delete` flags.+type DeleteOptions struct {+ Force bool+ JSONOut bool+}++// DeleteService is the narrow SDK surface this command depends on.+// *sdk.Client satisfies it.+type DeleteService interface {+ DeleteKnowledgeBase(ctx context.Context, id string) error+}++// deleteResult is the typed payload emitted under data on success.+type deleteResult struct {+ ID string `json:"id"`+ Deleted bool `json:"deleted"`+}++// NewCmdDelete builds `weknora kb delete`.+func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {+ opts := &DeleteOptions{}+ cmd := &cobra.Command{+ Use: "delete <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.+Pass --force to skip the prompt (required in agent / CI / piped contexts).`,+ Example: ` weknora kb delete kb_abc # interactive confirm+ weknora kb delete kb_abc --force # no prompt+ weknora kb delete kb_abc --force --json # envelope output`,+ Args: cobra.ExactArgs(1),+ RunE: func(c *cobra.Command, args []string) error {+ cli, err := f.Client()+ if err != nil {+ return err+ }+ return runDelete(c.Context(), opts, cli, f.Prompter(), args[0])+ },+ }+ cmd.Flags().BoolVar(&opts.Force, "force", false, "Skip confirmation prompt")+ cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")+ agent.SetAgentHelp(cmd, "Destructively deletes a knowledge base by id. ALWAYS pass --force in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")+ return cmd+}++func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p prompt.Prompter, id string) error {+ if err := cmdutil.ConfirmDestructive(p, opts.Force, opts.JSONOut, "knowledge base", id); err != nil {+ return err+ }++ if err := svc.DeleteKnowledgeBase(ctx, id); err != nil {+ return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete knowledge base %s", id)+ }++ if opts.JSONOut {+ return format.WriteEnvelope(iostreams.IO.Out, format.Success(deleteResult{ID: id, Deleted: true}, &format.Meta{+ KBID: id,+ }))+ }+ fmt.Fprintf(iostreams.IO.Out, "✓ Deleted knowledge base %s\n", id)+ return nil+}diff --git a/cli/cmd/kb/delete_test.go b/cli/cmd/kb/delete_test.gonew file mode 100644index 000000000..4da8489f1--- /dev/null+++ b/cli/cmd/kb/delete_test.go@@ -0,0 +1,151 @@+package kb++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/cli/internal/cmdutil"+ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ "github.com/Tencent/WeKnora/cli/internal/prompt"+)++// fakeDeleteSvc records what id was deleted.+type fakeDeleteSvc struct {+ err error+ gotID string+ called bool+}++func (f *fakeDeleteSvc) DeleteKnowledgeBase(_ context.Context, id string) error {+ f.called = true+ f.gotID = id+ return f.err+}++// confirmPrompter scripts a Confirm answer; Input/Password are unused here.+type confirmPrompter struct {+ answer bool+ err error+ asked bool+}++func (c *confirmPrompter) Input(string, string) (string, error) { return "", prompt.ErrAgentNoPrompt }+func (c *confirmPrompter) Password(string) (string, error) { return "", prompt.ErrAgentNoPrompt }+func (c *confirmPrompter) Confirm(string, bool) (bool, error) {+ c.asked = true+ return c.answer, c.err+}++func TestDelete_Success_WithForce(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{}+ p := &confirmPrompter{}+ opts := &DeleteOptions{Force: true}+ require.NoError(t, runDelete(context.Background(), opts, svc, p, "kb_force"))++ assert.True(t, svc.called)+ assert.Equal(t, "kb_force", svc.gotID)+ assert.False(t, p.asked, "--force must skip the confirm prompt")+ assert.Contains(t, out.String(), "✓ Deleted")+ assert.Contains(t, out.String(), "kb_force")+}++func TestDelete_NotFound(t *testing.T) {+ _, _ = iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}+ p := &confirmPrompter{}+ err := runDelete(context.Background(), &DeleteOptions{Force: true}, svc, p, "kb_missing")+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)+}++func TestDelete_NonTTY_NoPrompt_NoForce(t *testing.T) {+ // SetForTest uses bytes.Buffer for Out — IsStdoutTTY() = false. Confirm+ // path must be skipped entirely, so DeleteKnowledgeBase should run.+ out, _ := iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{}+ p := &confirmPrompter{}+ require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, svc, p, "kb_nontty"))++ assert.True(t, svc.called, "non-TTY must skip prompt and proceed")+ assert.False(t, p.asked, "non-TTY ⇒ Confirm is never invoked")+ assert.Contains(t, out.String(), "kb_nontty")+}++func TestDelete_JSONOutput(t *testing.T) {+ out, _ := iostreams.SetForTest(t)+ svc := &fakeDeleteSvc{}+ p := &confirmPrompter{}+ opts := &DeleteOptions{Force: true, JSONOut: true}+ require.NoError(t, runDelete(context.Background(), opts, svc, p, "kb_json"))++ got := out.String()+ assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)+ assert.Contains(t, got, `"id":"kb_json"`)+ assert.Contains(t, got, `"deleted":true`)+ assert.Contains(t, got, `"kb_id":"kb_json"`)+}++// The remaining tests cover the interactive confirm path which only fires+// under IsStdoutTTY() && !JSONOut — exercised via SetForTestWithTTY.++func TestDelete_ConfirmYes(t *testing.T) {+ _, _ = iostreams.SetForTestWithTTY(t)+ svc := &fakeDeleteSvc{}+ p := &confirmPrompter{answer: true}+ require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, svc, p, "kb_yes"))++ assert.True(t, p.asked, "confirm prompt should fire on TTY without --force")+ assert.True(t, svc.called, "answer=yes ⇒ delete proceeds")+ assert.Equal(t, "kb_yes", svc.gotID)+}++func TestDelete_ConfirmNo(t *testing.T) {+ _, errBuf := iostreams.SetForTestWithTTY(t)+ svc := &fakeDeleteSvc{}+ p := &confirmPrompter{answer: false}+ err := runDelete(context.Background(), &DeleteOptions{}, svc, p, "kb_no")+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeUserAborted, typed.Code)+ assert.True(t, p.asked)+ assert.False(t, svc.called, "answer=no ⇒ delete must NOT run")+ assert.Contains(t, errBuf.String(), "Aborted")+}++func TestDelete_ConfirmPrompterError(t *testing.T) {+ _, _ = iostreams.SetForTestWithTTY(t)+ svc := &fakeDeleteSvc{}+ p := &confirmPrompter{err: prompt.ErrAgentNoPrompt}+ err := runDelete(context.Background(), &DeleteOptions{}, svc, p, "kb_err")+ require.Error(t, err)++ var typed *cmdutil.Error+ require.ErrorAs(t, err, &typed)+ assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code,+ "prompter error should surface as missing-flag (pass --force)")+ assert.False(t, svc.called)+}++func TestDelete_JSONOut_SkipsPrompt(t *testing.T) {+ // Even on a TTY, --json indicates a scripted caller; don't prompt.+ out, _ := iostreams.SetForTestWithTTY(t)+ svc := &fakeDeleteSvc{}+ p := &confirmPrompter{}+ opts := &DeleteOptions{JSONOut: true}+ require.NoError(t, runDelete(context.Background(), opts, svc, p, "kb_jtty"))++ assert.False(t, p.asked, "--json must skip the prompt even on TTY")+ assert.True(t, svc.called)+ assert.Contains(t, out.String(), `"deleted":true`)+}diff --git a/cli/cmd/kb/kb.go b/cli/cmd/kb/kb.goindex 5a3c60402..c1f19ee2e 100644--- a/cli/cmd/kb/kb.go+++ b/cli/cmd/kb/kb.go@@ -17,5 +17,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {}cmd.AddCommand(NewCmdList(f))cmd.AddCommand(NewCmdGet(f))+ cmd.AddCommand(NewCmdCreate(f))+ cmd.AddCommand(NewCmdDelete(f))return cmd}diff --git a/cli/cmd/root.go b/cli/cmd/root.goindex 222874281..c35fb8c15 100644--- a/cli/cmd/root.go+++ b/cli/cmd/root.go@@ -14,6 +14,7 @@ import ("github.com/Tencent/WeKnora/cli/cmd/auth"contextcmd "github.com/Tencent/WeKnora/cli/cmd/context"+ "github.com/Tencent/WeKnora/cli/cmd/doc""github.com/Tencent/WeKnora/cli/cmd/doctor"initcmd "github.com/Tencent/WeKnora/cli/cmd/init""github.com/Tencent/WeKnora/cli/cmd/kb"@@ -178,6 +179,7 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,cmd.AddCommand(contextcmd.NewCmd(f))cmd.AddCommand(initcmd.NewCmd(f))cmd.AddCommand(linkcmd.NewCmd(f))+ cmd.AddCommand(doc.NewCmd(f))return cmd}diff --git a/cli/internal/cmdutil/confirm.go b/cli/internal/cmdutil/confirm.gonew file mode 100644index 000000000..4ac5032d3--- /dev/null+++ b/cli/internal/cmdutil/confirm.go@@ -0,0 +1,35 @@+package cmdutil++import (+ "fmt"++ "github.com/Tencent/WeKnora/cli/internal/iostreams"+ "github.com/Tencent/WeKnora/cli/internal/prompt"+)++// ConfirmDestructive prompts the user to confirm a destructive operation+// (e.g. delete). Returns nil if the operation should proceed, or a typed+// error otherwise:+// - CodeInputMissingFlag when the prompter rejects (non-TTY / agent mode):+// the caller forgot --force.+// - CodeUserAborted when the user explicitly answers no — also writes+// "Aborted." to stderr so the rejection is visible above the envelope.+//+// Skipped entirely when force is true, or when stdout is non-TTY, or when+// the caller is going to emit a JSON envelope (jsonOut=true) — envelope+// mode is by definition scripted, so a confirmation prompt would deadlock+// the consumer.+func ConfirmDestructive(p prompt.Prompter, force, jsonOut bool, what, id string) error {+ if force || !iostreams.IO.IsStdoutTTY() || jsonOut {+ return nil+ }+ ok, err := p.Confirm(fmt.Sprintf("Delete %s %s? This cannot be undone.", what, id), false)+ if err != nil {+ return Wrapf(CodeInputMissingFlag, err, "confirm delete")+ }+ if !ok {+ fmt.Fprintln(iostreams.IO.Err, "Aborted.")+ return NewError(CodeUserAborted, "delete aborted")+ }+ return nil+}diff --git a/cli/internal/iostreams/iostreams.go b/cli/internal/iostreams/iostreams.goindex 4dd583fee..7e0f45a53 100644--- a/cli/internal/iostreams/iostreams.go+++ b/cli/internal/iostreams/iostreams.go@@ -66,3 +66,22 @@ func SetForTest(t *testing.T) (out, errBuf *bytes.Buffer) {t.Cleanup(func() { IO = saved })return out, errBuf}++// SetForTestWithTTY is like SetForTest but reports IsStdoutTTY/IsStderrTTY+// = true so tests can exercise interactive code paths (confirm prompts,+// color, fancy renderers). Not safe under t.Parallel().+func SetForTestWithTTY(t *testing.T) (out, errBuf *bytes.Buffer) {+ t.Helper()+ saved := IO+ out = &bytes.Buffer{}+ errBuf = &bytes.Buffer{}+ IO = &IOStreams{+ In: bytes.NewReader(nil),+ Out: out,+ Err: errBuf,+ stdoutTTY: true,+ stderrTTY: true,+ }+ t.Cleanup(func() { IO = saved })+ return out, errBuf+}