refactor(cli): command-surface rename — session ask / doc fetch / doc create / doc delete --all

Three command renames consolidate the v0.7 verb table:

- `weknora agent invoke` → `weknora session ask --agent <id>`.
  Server route POST /sessions/{session_id}/agent-qa is session-
  anchored, so the verb moves with it. `weknora agent` subtree keeps
  CRUD only (list / view / create / edit / delete / status / check).
  SDK call (AgentQAStreamWithRequest) preserved verbatim; only the
  command surface + flag layout move.

- `weknora doc upload` split into three commands:
  - `weknora doc upload <file>`  — local file (only).
  - `weknora doc fetch <url>`    — server-side remote fetch (was
    `upload --from-url`). URL-only flags (--title / --file-type /
    --tag-id) move with the verb.
  - `weknora doc create --text`  — direct text knowledge entry via
    server CreateManualKnowledge.

- `weknora kb empty <id>` → `weknora doc delete --all --kb=<id>`.
  Atomic server ClearKnowledgeBaseContents (no list-then-delete
  race). Same exit-10 -y/--yes guard as other destructive verbs;
  unified through the extended ConfirmDestructive helper.

Parent commands (agent, kb, doc, chunk, session, auth, profile,
search) lose their explicit Args:NoArgs + Run:cmd.Help so the
unknown-subcommand guard fires correctly — `weknora agent invoke
ag_x q` now emits the typed input.unknown_subcommand envelope with
detail.available[] instead of cobra's free-form exit-2 prose.

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3.4 / §10.7
This commit is contained in:
nullkey
2026-05-21 18:42:27 +08:00
committed by lyingbug
parent ad150c7126
commit a2e368b1e8
20 changed files with 1866 additions and 1377 deletions
+120
View File
@@ -0,0 +1,120 @@
// Package doc — create.go implements `weknora doc create --text "..."`.
// Allows creating a knowledge entry directly from inline text content without
// uploading a file or fetching a remote URL.
package doc
import (
"cmp"
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// docCreateFields enumerates the fields surfaced for `--format json` discovery
// on `doc create`.
var docCreateFields = []string{
"id", "knowledge_base_id", "tag_id", "type", "title", "description",
"source", "channel", "parse_status", "summary_status", "enable_status",
"created_at", "updated_at", "error_message",
}
// CreateOptions holds CLI flag values for `doc create`.
type CreateOptions struct {
Text string // --text (required): document text content (Markdown)
Name string // --name: document title
TagID string // --tag-id: associate with a tag
Channel string // --channel: ingestion-channel tag (default "api")
}
// CreateService is the narrow SDK surface for `doc create`.
// *sdk.Client satisfies it.
type CreateService interface {
CreateManualKnowledge(
ctx context.Context,
kbID string,
req *sdk.CreateManualKnowledgeRequest,
) (*sdk.Knowledge, error)
}
// NewCmdCreate builds `weknora doc create --text "..."`.
func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts := &CreateOptions{}
cmd := &cobra.Command{
Use: "create",
Short: "Create a knowledge entry from inline text content",
Long: `Create a new knowledge entry by passing Markdown content directly via --text.
Useful for short snippets, agent-generated content, or structured notes that
don't require a file upload or remote URL. KB resolution follows the standard
4-level chain: --kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error.
--text <content> Document text in Markdown format (required).
--name <title> Display title stored with the entry.
--tag-id <id> Associate the new entry with a tag.
--channel <name> Override the ingestion-channel tag (default "api").`,
Example: ` weknora doc create --text "# Meeting Notes\n\nAction items: ..."
weknora doc create --text "$(cat notes.md)" --name "Sprint Notes" --kb my-kb
weknora doc create --text "API usage guide" --name "API Guide" --tag-id tag_abc`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
kbID, err := f.ResolveKB(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runCreate(c.Context(), opts, fopts, cli, kbID)
},
}
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)")
cmd.Flags().StringVar(&opts.Text, "text", "", "Document text content in Markdown format (required)")
cmd.Flags().StringVar(&opts.Name, "name", "", "Document title")
cmd.Flags().StringVar(&opts.TagID, "tag-id", "", "Tag id to associate with the new entry")
cmd.Flags().StringVar(&opts.Channel, "channel", "", "Ingestion-channel tag recorded server-side (default \"api\")")
_ = cmd.MarkFlagRequired("text")
cmdutil.AddFormatFlag(cmd, docCreateFields...)
return cmd
}
// runCreate creates a manual knowledge entry via SDK CreateManualKnowledge.
func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOptions, svc CreateService, kbID string) error {
// Guard against empty text: cobra's MarkFlagRequired enforces this for
// normal CLI invocations; this check protects tests that call runCreate
// directly and any future callers that bypass cobra.
if opts.Text == "" {
return cmdutil.NewFlagError(fmt.Errorf("--text is required"))
}
req := &sdk.CreateManualKnowledgeRequest{
Title: opts.Name,
Content: opts.Text,
TagID: opts.TagID,
Channel: cmp.Or(opts.Channel, uploadChannel),
}
k, err := svc.CreateManualKnowledge(ctx, kbID, req)
if err != nil {
return cmdutil.WrapHTTP(err, "create document")
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, k, nil)
}
displayed := opts.Name
if displayed == "" {
displayed = k.Title
}
if displayed == "" {
displayed = k.ID
}
fmt.Fprintf(iostreams.IO.Out, "✓ Created %q (id: %s)\n", displayed, k.ID)
return nil
}
+140
View File
@@ -0,0 +1,140 @@
package doc
import (
"context"
"encoding/json"
"errors"
"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 call arguments and returns canned responses.
type fakeCreateSvc struct {
resp *sdk.Knowledge
err error
got struct {
kbID string
req *sdk.CreateManualKnowledgeRequest
}
}
func (f *fakeCreateSvc) CreateManualKnowledge(
_ context.Context,
kbID string,
req *sdk.CreateManualKnowledgeRequest,
) (*sdk.Knowledge, error) {
f.got.kbID = kbID
f.got.req = req
return f.resp, f.err
}
func TestCreate_Success_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_1", Title: "Sprint Notes"}}
opts := &CreateOptions{Text: "# Sprint Notes\n\nAction items: ...", Name: "Sprint Notes"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, "# Sprint Notes\n\nAction items: ...", svc.got.req.Content)
assert.Equal(t, "Sprint Notes", svc.got.req.Title)
assert.Contains(t, out.String(), "Created")
assert.Contains(t, out.String(), "doc_manual_1")
}
func TestCreate_Success_NoName_FallsBackToTitle(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_2", Title: "Server Title"}}
opts := &CreateOptions{Text: "Some content"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
// When --name is omitted the display falls back to k.Title from the server response.
assert.Contains(t, out.String(), "Server Title")
}
func TestCreate_Success_NoName_NoTitle_FallsBackToID(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_3"}}
opts := &CreateOptions{Text: "Some content"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Contains(t, out.String(), "doc_manual_3")
}
func TestCreate_TagID_Forwarded(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_t"}}
opts := &CreateOptions{Text: "content", TagID: "tag_42"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "tag_42", svc.got.req.TagID)
}
func TestCreate_Channel_Override(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_ch"}}
opts := &CreateOptions{Text: "content", Channel: "browser_extension"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "browser_extension", svc.got.req.Channel)
}
func TestCreate_Channel_DefaultIsAPI(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_ch"}}
opts := &CreateOptions{Text: "content"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, uploadChannel, svc.got.req.Channel)
}
func TestCreate_JSON_Envelope(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_json", Title: "My Note"}}
opts := &CreateOptions{Text: "# My Note", Name: "My Note"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
require.NoError(t, runCreate(context.Background(), opts, fopts, svc, "kb_xxx"))
got := out.String()
var env struct {
OK bool `json:"ok"`
Data sdk.Knowledge `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, "doc_manual_json", env.Data.ID, "envelope.data.id must match")
}
func TestCreate_ServerError_Wraps(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal server error")}
err := runCreate(context.Background(),
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeServerError, typed.Code)
}
func TestCreate_HTTPError_400_Wraps(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{err: errors.New("HTTP error 400: bad request")}
err := runCreate(context.Background(),
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
func TestCreate_EmptyText_RejectsBeforeSDK(t *testing.T) {
_, _ = iostreams.SetForTest(t)
// The SDK should never be called when --text is empty (runCreate has a
// defensive guard; cobra's MarkFlagRequired catches it earlier in RunE).
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "should-not-reach"}}
err := runCreate(context.Background(),
&CreateOptions{Text: ""}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
require.Error(t, err)
// Verify the SDK was NOT called.
assert.Nil(t, svc.got.req, "SDK must not be called when --text is empty")
}
+94 -62
View File
@@ -3,10 +3,12 @@ package doc
import (
"context"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
sdk "github.com/Tencent/WeKnora/client"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
@@ -17,7 +19,9 @@ import (
var docDeleteFields = []string{"id", "deleted"}
type DeleteOptions struct {
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go)
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go)
All bool // delete all docs in --kb
KB string // required when --all
}
// DeleteService is the narrow SDK surface this command depends on.
@@ -26,33 +30,26 @@ type DeleteService interface {
DeleteKnowledge(ctx context.Context, id string) error
}
// AllService is the narrow SDK surface for --all mode.
// *sdk.Client satisfies it.
type AllService interface {
ClearKnowledgeBaseContents(ctx context.Context, kbID string) (*sdk.ClearKnowledgeBaseContentsResponse, error)
}
// deleteResult is the typed payload emitted under data on success (single-id).
type deleteResult struct {
ID string `json:"id"`
Deleted bool `json:"deleted"`
}
// MultiDeleteResult is the payload for multi-id deletes.
// ok: ids successfully deleted; failed: ids that could not be deleted.
type MultiDeleteResult struct {
OK []string `json:"ok"`
Failed []FailedItem `json:"failed,omitempty"`
}
// FailedItem records an id that failed to delete along with its error message.
type FailedItem struct {
ID string `json:"id"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
}
// NewCmdDelete builds `weknora doc delete`. Single-id keeps the simpler
// code path (one confirm prompt, exit 0/1); multi-id uses keep-going
// semantics (one -y confirms all, failures collected, exit 1 if any fail).
// semantics (one -y confirms all, failures collected, exit 1 if any fail);
// --all --kb=<id> atomically clears every document in a knowledge base.
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
opts := &DeleteOptions{}
cmd := &cobra.Command{
Use: "delete <doc-id> [<doc-id>...]",
Use: "delete <doc-id> [<doc-id>...] | --all --kb=<kb-id>",
Short: "Delete one or more documents from a knowledge base",
Long: `Permanently deletes one or more documents. Prompts for confirmation by
default when stdout is a TTY and JSON output is not set; pass -y/--yes
@@ -65,15 +62,23 @@ Multi-id:
• TTY prompt shows total: "Delete N document(s)? This cannot be undone."
• Exit 0 if all succeed; exit 1 if any failed.
All-in-KB (--all --kb=<kb-id>):
• Atomically clears every document in the named knowledge base.
• The KB record itself (name, config) is preserved.
• Mutually exclusive with positional doc ids.
• Exit 0 on success; exit 10 without -y in non-interactive/JSON mode.
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
and writes input.confirmation_required to stderr. NEVER auto-pass -y
without the user's explicit go-ahead.`,
Example: ` weknora doc delete doc_abc # interactive confirm
weknora doc delete doc_abc -y # no prompt
weknora doc delete doc_abc -y --format json # bare {id, deleted:true} JSON
weknora doc delete doc_a doc_b doc_c -y # delete 3, keep-going
weknora doc delete doc_a doc_b --format json # multi-id JSON output`,
Args: cobra.MinimumNArgs(1),
Example: ` weknora doc delete doc_abc # interactive confirm
weknora doc delete doc_abc -y # no prompt
weknora doc delete doc_abc -y --format json # bare {id, deleted:true} JSON
weknora doc delete doc_a doc_b doc_c -y # delete 3, keep-going
weknora doc delete doc_a doc_b --format json # multi-id JSON output
weknora doc delete --all --kb=kb_x -y # clear all docs in kb_x
weknora doc delete --all --kb=kb_x -y --format json # agent-friendly`,
Args: cobra.ArbitraryArgs,
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
@@ -85,28 +90,65 @@ without the user's explicit go-ahead.`,
if err != nil {
return err
}
if opts.All {
if opts.KB == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--all requires --kb=<id>").
WithHint("specify --kb=<kb-id> to scope the delete-all operation").
WithRetryCommand("weknora doc delete --all --kb=<kb-id> -y")
}
if len(args) > 0 {
return cmdutil.NewFlagError(fmt.Errorf("--all is exclusive with positional doc ids"))
}
return runDeleteAll(c.Context(), opts, fopts, cli, f.Prompter())
}
if len(args) == 0 {
return cmdutil.NewFlagError(fmt.Errorf("doc id(s) required (or use --all --kb=<id>)"))
}
// Single-id uses the simpler code path (bare {id, deleted}).
if len(args) == 1 {
return runDelete(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
}
res, runErr := runMultiDelete(c.Context(), opts, fopts, cli, f.Prompter(), args)
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "document", len(args), "doc.delete", "weknora doc delete "+strings.Join(args, " ")+" -y"); err != nil {
return err
}
outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error {
if err := cli.DeleteKnowledge(ctx, id); err != nil {
return cmdutil.WrapHTTP(err, "delete document %s", id)
}
return nil
})
// Only emit when the operation actually ran. Pre-flight errors
// (e.g. confirmation_required) must leave stdout empty per the
// wire contract in README.md.
if len(res.OK) > 0 || len(res.Failed) > 0 {
if emitErr := emitMultiDelete(res, fopts, iostreams.IO.Out); emitErr != nil {
if len(outcomes) > 0 {
if emitErr := cmdutil.EmitBatch(outcomes, fopts, iostreams.IO.Out, cmdutil.DeletedAtNow); emitErr != nil {
return emitErr
}
}
return runErr
},
}
cmd.Flags().BoolVar(&opts.All, "all", false, "delete all documents in the KB specified by --kb")
cmd.Flags().StringVar(&opts.KB, "kb", "", "knowledge base ID (required with --all)")
cmdutil.AddFormatFlag(cmd, docDeleteFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "permanently delete one or more documents from a knowledge base",
RequiredFlags: []string{"<doc-id>... (positional) | --all --kb=<id>"},
Examples: []string{
"weknora doc delete doc_abc -y",
"weknora doc delete doc_a doc_b doc_c -y",
"weknora doc delete --all --kb=kb_x -y --format json",
},
Warnings: []string{
"doc delete is irreversible. --all --kb=<id> atomically clears every document in the KB; that is especially destructive. 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(), "document", id); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "document", id, "doc.delete", "weknora doc delete "+id+" -y"); err != nil {
return err
}
@@ -115,46 +157,36 @@ 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 document %s\n", id)
return nil
}
// runMultiDelete iterates ids sequentially, keep-going on error: a single
// failure does not abort the run, so the caller sees the full outcome.
func runMultiDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, ids []string) (*MultiDeleteResult, error) {
if err := cmdutil.ConfirmDestructiveBatch(p, opts.Yes, fopts.WantsJSON(), "document", len(ids)); err != nil {
return &MultiDeleteResult{}, err
// runDeleteAll atomically clears every document in opts.KB via a single
// ClearKnowledgeBaseContents call. Non-TTY/JSON mode without -y returns
// CodeInputConfirmationRequired (exit 10) with risk metadata so agents can
// surface the risk to the user before re-invoking with -y.
func runDeleteAll(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc AllService, p prompt.Prompter) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "all docs in KB", opts.KB, "doc.delete_all", fmt.Sprintf("weknora doc delete --all --kb=%s -y", opts.KB)); err != nil {
return err
}
res := &MultiDeleteResult{}
for _, id := range ids {
if err := svc.DeleteKnowledge(ctx, id); err != nil {
res.Failed = append(res.Failed, FailedItem{ID: id, Message: err.Error()})
continue
}
res.OK = append(res.OK, id)
}
if len(res.Failed) > 0 {
return res, cmdutil.NewError(cmdutil.CodeOperationFailed, fmt.Sprintf("%d/%d delete(s) failed", len(res.Failed), len(ids)))
}
return res, nil
}
// emitMultiDelete renders per --format. Mirrors emitWaitResult / emitStatus.
func emitMultiDelete(res *MultiDeleteResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res)
case cmdutil.FormatText, "":
for _, id := range res.OK {
fmt.Fprintf(w, "OK %s\n", id)
}
for _, f := range res.Failed {
fmt.Fprintf(w, "FAIL %s: %s\n", f.ID, f.Message)
}
return nil
default:
return fmt.Errorf("unsupported --format %q for doc delete", fopts.Mode)
resp, err := svc.ClearKnowledgeBaseContents(ctx, opts.KB)
if err != nil {
return cmdutil.WrapHTTP(err, "clear KB %s", opts.KB)
}
deleted := 0
if resp != nil {
deleted = resp.DeletedCount
}
if !fopts.WantsJSON() {
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted %d document(s) from KB %s\n", deleted, opts.KB)
return nil
}
return fopts.Emit(iostreams.IO.Out, map[string]any{
"kb_id": opts.KB,
"deleted_count": deleted,
}, nil)
}
+297 -74
View File
@@ -5,17 +5,39 @@ import (
"context"
"encoding/json"
"errors"
"strings"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/Tencent/WeKnora/client"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/testutil"
)
// fakeAllSvc implements AllService for --all mode tests.
type fakeAllSvc struct {
err error
gotID string
called bool
resp *sdk.ClearKnowledgeBaseContentsResponse
}
func (f *fakeAllSvc) ClearKnowledgeBaseContents(_ context.Context, kbID string) (*sdk.ClearKnowledgeBaseContentsResponse, error) {
f.called = true
f.gotID = kbID
if f.err != nil {
return nil, f.err
}
if f.resp == nil {
return &sdk.ClearKnowledgeBaseContentsResponse{DeletedCount: 0}, nil
}
return f.resp, nil
}
// fakeDeleteSvc captures calls and returns canned errors.
// errFor maps id → error for per-id failure injection (used in multi-id tests).
type fakeDeleteSvc struct {
@@ -54,7 +76,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
opts := &DeleteOptions{Yes: 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, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc"))
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc"))
assert.Equal(t, "doc_abc", svc.got)
assert.Equal(t, 1, svc.calls)
@@ -69,15 +91,20 @@ func TestDelete_Success_JSON(t *testing.T) {
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc"))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"doc_abc"`), "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, "doc_abc", env.Data["id"], "envelope.data.id must be doc_abc")
assert.Equal(t, true, env.Data["deleted"], "envelope.data.deleted must be 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{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "doc_missing")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "doc_missing")
require.Error(t, err)
var typed *cmdutil.Error
@@ -88,7 +115,7 @@ func TestDelete_NotFound_404(t *testing.T) {
func TestDelete_HTTPError_500(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{err: errors.New("HTTP error 500: internal")}
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "doc_x")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "doc_x")
require.Error(t, err)
var typed *cmdutil.Error
@@ -102,7 +129,7 @@ func TestDelete_HTTPError_500(t *testing.T) {
func TestDelete_ConfirmYes(t *testing.T) {
out, _ := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc")
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc")
require.NoError(t, err)
assert.Equal(t, 1, svc.calls, "user said yes ⇒ delete proceeds")
assert.Contains(t, out.String(), "✓")
@@ -111,7 +138,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
func TestDelete_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc")
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc")
require.Error(t, err)
assert.Equal(t, 0, svc.calls, "user said no ⇒ SDK must NOT be called")
@@ -127,7 +154,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
func TestDelete_AgentPrompterErrors(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
require.Error(t, err)
assert.Equal(t, 0, svc.calls)
@@ -143,7 +170,7 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -153,46 +180,56 @@ func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
}
// ---------------------------------------------------------------------------
// Multi-id tests (runMultiDelete, keep-going semantics)
// Multi-id tests (cmdutil.RunBatch, keep-going semantics)
// ---------------------------------------------------------------------------
func TestRunMultiDelete_AllSucceed(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
res, err := runMultiDelete(
outcomes, err := cmdutil.RunBatch(
context.Background(),
&DeleteOptions{Yes: true},
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON},
svc,
&testutil.ConfirmPrompter{Answer: true},
[]string{"a", "b", "c"},
func(ctx context.Context, id string) error {
if err := svc.DeleteKnowledge(ctx, id); err != nil {
return cmdutil.WrapHTTP(err, "delete document %s", id)
}
return nil
},
)
require.NoError(t, err)
assert.Equal(t, []string{"a", "b", "c"}, res.OK)
assert.Empty(t, res.Failed)
require.Len(t, outcomes, 3)
for _, oc := range outcomes {
assert.Nil(t, oc.Err, "expected no error for id %s", oc.ID)
}
assert.Equal(t, "a", outcomes[0].ID)
assert.Equal(t, "b", outcomes[1].ID)
assert.Equal(t, "c", outcomes[2].ID)
assert.Equal(t, 3, svc.calls)
}
func TestRunMultiDelete_KeepGoingOnError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{errFor: map[string]error{"doc_b": errors.New("not found")}}
res, err := runMultiDelete(
outcomes, err := cmdutil.RunBatch(
context.Background(),
&DeleteOptions{Yes: true},
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON},
svc,
&testutil.ConfirmPrompter{Answer: true},
[]string{"doc_a", "doc_b", "doc_c"},
func(ctx context.Context, id string) error {
if err := svc.DeleteKnowledge(ctx, id); err != nil {
return cmdutil.WrapHTTP(err, "delete document %s", id)
}
return nil
},
)
require.Error(t, err, "partial failure must return non-nil error (exit 1)")
assert.Equal(t, 3, svc.calls, "all ids must be attempted (keep-going)")
require.Len(t, res.OK, 2)
require.Len(t, res.Failed, 1)
assert.Equal(t, "doc_b", res.Failed[0].ID)
assert.Equal(t, "not found", res.Failed[0].Message)
// OK list must contain only successful ids
assert.Contains(t, res.OK, "doc_a")
assert.Contains(t, res.OK, "doc_c")
require.Len(t, outcomes, 3)
// order preserved: doc_a ok, doc_b fail, doc_c ok
assert.Equal(t, "doc_a", outcomes[0].ID)
assert.Nil(t, outcomes[0].Err)
assert.Equal(t, "doc_b", outcomes[1].ID)
assert.NotNil(t, outcomes[1].Err)
assert.Equal(t, "doc_c", outcomes[2].ID)
assert.Nil(t, outcomes[2].Err)
}
func TestRunMultiDelete_AllFail(t *testing.T) {
@@ -201,30 +238,27 @@ func TestRunMultiDelete_AllFail(t *testing.T) {
"x": errors.New("HTTP error 404: not found"),
"y": errors.New("HTTP error 403: forbidden"),
}}
res, err := runMultiDelete(
outcomes, err := cmdutil.RunBatch(
context.Background(),
&DeleteOptions{Yes: true},
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON},
svc,
&testutil.ConfirmPrompter{Answer: true},
[]string{"x", "y"},
func(ctx context.Context, id string) error {
if err := svc.DeleteKnowledge(ctx, id); err != nil {
return cmdutil.WrapHTTP(err, "delete document %s", id)
}
return nil
},
)
require.Error(t, err)
assert.Empty(t, res.OK)
assert.Len(t, res.Failed, 2)
require.Len(t, outcomes, 2)
assert.NotNil(t, outcomes[0].Err)
assert.NotNil(t, outcomes[1].Err)
}
func TestRunMultiDelete_ConfirmBatch_NonTTY_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t) // non-TTY
svc := &fakeDeleteSvc{}
_, err := runMultiDelete(
context.Background(),
&DeleteOptions{Yes: false},
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON},
svc,
&testutil.ConfirmPrompter{Answer: false},
[]string{"a", "b"},
)
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "document", 2, "doc.delete", "")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -235,14 +269,8 @@ func TestRunMultiDelete_ConfirmBatch_NonTTY_RequiresConfirmation(t *testing.T) {
func TestRunMultiDelete_ConfirmBatch_TTY_UserAborts(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
_, err := runMultiDelete(
context.Background(),
&DeleteOptions{Yes: false},
&cmdutil.FormatOptions{Mode: cmdutil.FormatText},
svc,
&testutil.ConfirmPrompter{Answer: false},
[]string{"a", "b", "c"},
)
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "document", 3, "doc.delete", "")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -252,43 +280,83 @@ func TestRunMultiDelete_ConfirmBatch_TTY_UserAborts(t *testing.T) {
}
// ---------------------------------------------------------------------------
// Emit tests
// Emit tests — JSON path now emits batch envelope (§4.5)
// ---------------------------------------------------------------------------
// batchEnvelope is a minimal struct for parsing the batch envelope shape.
type batchEnvelope struct {
OK bool `json:"ok"`
Data []batchItem `json:"data"`
Meta batchMeta `json:"meta"`
}
type batchItem struct {
ID string `json:"id"`
OK bool `json:"ok"`
Result json.RawMessage `json:"result,omitempty"`
Error *batchItemError `json:"error,omitempty"`
}
type batchItemError struct {
Type string `json:"type"`
Message string `json:"message"`
}
type batchMeta struct {
Count int `json:"count"`
Successes int `json:"successes"`
Failures int `json:"failures"`
}
func TestEmitMultiDelete_JSON(t *testing.T) {
var buf bytes.Buffer
res := &MultiDeleteResult{
OK: []string{"a", "b"},
Failed: []FailedItem{{ID: "c", Message: "x"}},
outcomes := []cmdutil.BatchOutcome{
{ID: "a", Err: nil},
{ID: "b", Err: nil},
{ID: "c", Err: errors.New("x")},
}
err := emitMultiDelete(res, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &buf)
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &buf, cmdutil.DeletedAtNow)
require.NoError(t, err)
var got MultiDeleteResult
var got batchEnvelope
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
assert.Equal(t, []string{"a", "b"}, got.OK)
require.Len(t, got.Failed, 1)
assert.Equal(t, "c", got.Failed[0].ID)
// top-level: partial failure → ok:false
assert.False(t, got.OK)
assert.Equal(t, 3, got.Meta.Count)
assert.Equal(t, 2, got.Meta.Successes)
assert.Equal(t, 1, got.Meta.Failures)
require.Len(t, got.Data, 3)
assert.Equal(t, "a", got.Data[0].ID)
assert.True(t, got.Data[0].OK)
assert.Equal(t, "b", got.Data[1].ID)
assert.True(t, got.Data[1].OK)
assert.Equal(t, "c", got.Data[2].ID)
assert.False(t, got.Data[2].OK)
assert.NotNil(t, got.Data[2].Error)
}
func TestEmitMultiDelete_Text(t *testing.T) {
var buf bytes.Buffer
res := &MultiDeleteResult{
OK: []string{"a"},
Failed: []FailedItem{{ID: "b", Message: "boom"}},
outcomes := []cmdutil.BatchOutcome{
{ID: "a", Err: nil},
{ID: "b", Err: errors.New("boom")},
}
err := emitMultiDelete(res, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &buf)
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &buf, nil)
require.NoError(t, err)
out := buf.String()
assert.Contains(t, out, "OK a")
assert.Contains(t, out, "FAIL b: boom")
assert.Contains(t, out, "FAIL b:")
assert.Contains(t, out, "boom")
}
func TestEmitMultiDelete_TextEmpty(t *testing.T) {
var buf bytes.Buffer
res := &MultiDeleteResult{OK: []string{"x", "y"}}
err := emitMultiDelete(res, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &buf)
outcomes := []cmdutil.BatchOutcome{
{ID: "x", Err: nil},
{ID: "y", Err: nil},
}
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &buf, nil)
require.NoError(t, err)
out := buf.String()
@@ -298,9 +366,164 @@ func TestEmitMultiDelete_TextEmpty(t *testing.T) {
}
func TestEmitMultiDelete_UnsupportedFormat(t *testing.T) {
// EmitBatch defers unsupported format handling to WriteBatchEnvelope; for
// non-JSON formats it falls through to human text. Verify it does not error.
var buf bytes.Buffer
res := &MultiDeleteResult{}
err := emitMultiDelete(res, &cmdutil.FormatOptions{Mode: "yaml"}, &buf)
require.Error(t, err)
assert.Contains(t, err.Error(), "yaml")
outcomes := []cmdutil.BatchOutcome{}
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: "yaml"}, &buf, nil)
// EmitBatch itself does not error on unknown mode (it uses WantsJSON gate)
require.NoError(t, err)
}
// ---------------------------------------------------------------------------
// Batch envelope shape test — Task 2.6
// ---------------------------------------------------------------------------
// TestDocDelete_MultiID_PartialFailure_BatchEnvelope verifies that when a
// multi-id delete has a partial failure, stdout carries the §4.5 batch
// envelope shape: ok:false, data:[BatchItem...], meta:{count, successes,
// failures}. Order follows original argv order.
func TestDocDelete_MultiID_PartialFailure_BatchEnvelope(t *testing.T) {
// id1 succeeds, id2 fails, id3 succeeds.
svc := &fakeDeleteSvc{errFor: map[string]error{
"id2": errors.New("HTTP error 404: not found"),
}}
outcomes, runErr := cmdutil.RunBatch(
context.Background(),
[]string{"id1", "id2", "id3"},
func(ctx context.Context, id string) error {
if err := svc.DeleteKnowledge(ctx, id); err != nil {
return cmdutil.WrapHTTP(err, "delete document %s", id)
}
return nil
},
)
require.Error(t, runErr, "partial failure must return non-nil error")
require.Len(t, outcomes, 3)
var buf bytes.Buffer
require.NoError(t, cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, TTY: false}, &buf, cmdutil.DeletedAtNow))
var env batchEnvelope
require.NoError(t, json.Unmarshal(buf.Bytes(), &env))
// top-level ok:false (partial failure)
assert.False(t, env.OK)
// meta counts
assert.Equal(t, 3, env.Meta.Count)
assert.Equal(t, 2, env.Meta.Successes)
assert.Equal(t, 1, env.Meta.Failures)
// items in argv order
require.Len(t, env.Data, 3)
assert.Equal(t, "id1", env.Data[0].ID)
assert.True(t, env.Data[0].OK)
assert.Nil(t, env.Data[0].Error)
assert.Equal(t, "id2", env.Data[1].ID)
assert.False(t, env.Data[1].OK)
require.NotNil(t, env.Data[1].Error)
assert.Equal(t, "resource.not_found", env.Data[1].Error.Type)
assert.Equal(t, "id3", env.Data[2].ID)
assert.True(t, env.Data[2].OK)
assert.Nil(t, env.Data[2].Error)
}
// ---------------------------------------------------------------------------
// --all mode tests (runDeleteAll)
// ---------------------------------------------------------------------------
// TestDocDelete_All_MissingKB_ReturnsFlagError: --all without --kb must exit 2.
func TestDocDelete_All_MissingKB_ReturnsFlagError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeAllSvc{}
// Simulate the RunE guard: --all without --kb returns FlagError before
// runDeleteAll is ever called.
err := cmdutil.NewFlagError(fmt.Errorf("--all requires --kb=<id>"))
require.Error(t, err)
var flagErr *cmdutil.FlagError
require.ErrorAs(t, err, &flagErr)
assert.Equal(t, 2, cmdutil.ExitCode(err))
assert.False(t, svc.called)
}
// TestDocDelete_All_WithoutYes_JSONMode_ReturnsExit10 verifies the
// CodeInputConfirmationRequired (exit 10) path with risk metadata in JSON/non-TTY.
func TestDocDelete_All_WithoutYes_JSONMode_ReturnsExit10(t *testing.T) {
_, _ = iostreams.SetForTest(t) // non-TTY
svc := &fakeAllSvc{}
opts := &DeleteOptions{All: true, KB: "kb_x", Yes: false}
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, &testutil.ConfirmPrompter{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
assert.Equal(t, 10, cmdutil.ExitCode(err))
require.NotNil(t, typed.Risk)
assert.Equal(t, "destructive", typed.Risk.Level)
assert.Equal(t, "doc.delete_all", typed.Risk.Action)
assert.False(t, svc.called)
}
// TestDocDelete_All_WithYes_CallsClearKB verifies that with -y the call is made
// and the JSON envelope contains kb_id + deleted_count.
func TestDocDelete_All_WithYes_CallsClearKB(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeAllSvc{resp: &sdk.ClearKnowledgeBaseContentsResponse{DeletedCount: 17}}
opts := &DeleteOptions{All: true, KB: "kb_x", Yes: true}
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, &testutil.ConfirmPrompter{})
require.NoError(t, err)
assert.True(t, svc.called)
assert.Equal(t, "kb_x", svc.gotID)
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "expected valid JSON envelope, got %q", out.String())
assert.True(t, env.OK)
assert.Equal(t, "kb_x", env.Data["kb_id"])
assert.Equal(t, float64(17), env.Data["deleted_count"])
}
// TestDocDelete_All_WithYes_TextMode verifies the text output path.
func TestDocDelete_All_WithYes_TextMode(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeAllSvc{resp: &sdk.ClearKnowledgeBaseContentsResponse{DeletedCount: 5}}
opts := &DeleteOptions{All: true, KB: "kb_y", Yes: true}
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{})
require.NoError(t, err)
assert.True(t, svc.called)
body := out.String()
assert.Contains(t, body, "5")
assert.Contains(t, body, "kb_y")
}
// TestDocDelete_All_TTY_UserAborts: interactive TTY + user says no → CodeUserAborted.
func TestDocDelete_All_TTY_UserAborts(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeAllSvc{}
opts := &DeleteOptions{All: true, KB: "kb_z", Yes: false}
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeUserAborted, typed.Code)
assert.False(t, svc.called)
assert.Contains(t, errBuf.String(), "Aborted")
}
// TestDocDelete_All_ServiceError propagates SDK errors via WrapHTTP.
func TestDocDelete_All_ServiceError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeAllSvc{err: errors.New("HTTP error 404: not found")}
opts := &DeleteOptions{All: true, KB: "kb_missing", Yes: true}
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
}
+9 -8
View File
@@ -1,6 +1,7 @@
// Package doc implements the `weknora doc` subtree (list / view / upload /
// download / delete). Upload also supports --recursive / --glob for bulk
// ingestion.
// fetch / create / download / delete / wait). Upload supports --recursive /
// --glob for bulk ingestion from local files. Fetch ingests a remote URL.
// Create adds a knowledge entry from inline text content.
//
// "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
@@ -19,14 +20,14 @@ 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(NewCmdView(f))
cmd.AddCommand(NewCmdUpload(f))
cmd.AddCommand(NewCmdDownload(f))
cmd.AddCommand(NewCmdCreate(f))
cmd.AddCommand(NewCmdDelete(f))
cmd.AddCommand(NewCmdDownload(f))
cmd.AddCommand(NewCmdFetch(f))
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdUpload(f))
cmd.AddCommand(NewCmdView(f))
cmd.AddCommand(NewCmdWait(f))
return cmd
}
+140
View File
@@ -0,0 +1,140 @@
// Package doc — fetch.go implements `weknora doc fetch <url>`.
package doc
import (
"cmp"
"context"
"errors"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// docFetchFields enumerates the fields surfaced for `--format json` discovery
// on `doc fetch`.
var docFetchFields = []string{
"id", "knowledge_base_id", "tag_id", "type", "title", "description",
"source", "channel", "parse_status", "summary_status", "enable_status",
"embedding_model_id", "file_name", "file_type", "file_size", "file_hash",
"file_path", "storage_size",
"created_at", "updated_at", "processed_at", "error_message",
}
// FetchOptions holds CLI flag values for `doc fetch`.
type FetchOptions struct {
URL string
Name string // --name: FileName hint for file-vs-crawl mode detection
Title string // --title: display title for the new entry
FileType string // --file-type: extension hint for extension-less URLs
TagID string // --tag-id: associate the new entry with a tag
Channel string // --channel: ingestion-channel tag (default "api")
EnableMultimodel *bool // tri-state: nil = server default
}
// FetchService is the narrow SDK surface for `doc fetch`.
// *sdk.Client satisfies it.
type FetchService interface {
CreateKnowledgeFromURL(
ctx context.Context,
kbID string,
req sdk.CreateKnowledgeFromURLRequest,
) (*sdk.Knowledge, error)
}
// NewCmdFetch builds `weknora doc fetch <url>`.
func NewCmdFetch(f *cmdutil.Factory) *cobra.Command {
opts := &FetchOptions{}
cmd := &cobra.Command{
Use: "fetch <url>",
Short: "Fetch a remote document into a knowledge base",
Long: `Server fetches the document at the given URL and ingests it into the resolved
knowledge base. KB resolution follows the standard 4-level chain:
--kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error.
When the URL has a known file extension (.pdf, .docx, .md, .txt) the server
automatically switches from web-page-crawl mode to file-download mode. Pass
--file-type or --name with a recognisable extension to force file-download mode
for extension-less URLs.
Server-side ingestion knobs:
--name <name> Override the recorded file name; also used as the
file-type hint when the extension is recognisable.
--title <title> Set the display title stored with the entry.
--file-type <ext> Explicit file-type hint (e.g. "pdf") for URLs
without an extension.
--tag-id <id> Associate the new entry with a tag.
--enable-multimodel Toggle multimodal extraction (image-in-PDF → text).
Unset ⇒ server default; pass true or false to override.
--channel <name> Override the ingestion-channel tag (default "api").`,
Example: ` weknora doc fetch https://example.com/whitepaper.pdf
weknora doc fetch https://example.com/no-ext --file-type pdf --title "Whitepaper"
weknora doc fetch https://example.com/article.html --name "Q3 Article" --tag-id tag_abc
weknora doc fetch https://example.com/report.pdf --kb my-kb --enable-multimodel`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.URL = args[0]
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
// Tri-state --enable-multimodel: nil = unset (server default).
if c.Flags().Changed("enable-multimodel") {
raw, _ := c.Flags().GetString("enable-multimodel")
v, perr := parseTriBool(raw)
if perr != nil {
return perr
}
opts.EnableMultimodel = &v
}
if err := cmdutil.ValidateHTTPURL("<url>", opts.URL); err != nil {
return err
}
kbID, err := f.ResolveKB(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runFetch(c.Context(), opts, fopts, cli, kbID)
},
}
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)")
cmd.Flags().StringVar(&opts.Name, "name", "", "File name hint (also used as file-type hint when extension is recognisable)")
cmd.Flags().StringVar(&opts.Title, "title", "", "Display title for the new entry")
cmd.Flags().StringVar(&opts.FileType, "file-type", "", "File-type hint such as \"pdf\" when the URL has no extension")
cmd.Flags().StringVar(&opts.TagID, "tag-id", "", "Tag id to associate with the new entry")
cmd.Flags().StringVar(&opts.Channel, "channel", "", "Ingestion-channel tag recorded server-side (default \"api\")")
cmd.Flags().String("enable-multimodel", "", "Toggle multimodal extraction (true|false); unset ⇒ server default")
cmd.Flags().Lookup("enable-multimodel").NoOptDefVal = "true"
cmdutil.AddFormatFlag(cmd, docFetchFields...)
return cmd
}
// runFetch ingests a remote URL via SDK CreateKnowledgeFromURL.
func runFetch(ctx context.Context, opts *FetchOptions, fopts *cmdutil.FormatOptions, svc FetchService, kbID string) error {
req := sdk.CreateKnowledgeFromURLRequest{
URL: opts.URL,
FileName: opts.Name,
FileType: opts.FileType,
EnableMultimodel: opts.EnableMultimodel,
Title: opts.Title,
TagID: opts.TagID,
Channel: cmp.Or(opts.Channel, uploadChannel),
}
k, err := svc.CreateKnowledgeFromURL(ctx, kbID, req)
if err != nil {
if errors.Is(err, sdk.ErrDuplicateURL) {
return cmdutil.Wrapf(cmdutil.CodeResourceAlreadyExists, err,
"URL already ingested into this knowledge base")
}
return cmdutil.WrapHTTP(err, "fetch document from %s", opts.URL)
}
return renderUploadSuccess(k, fopts, "Ingested", opts.Name, opts.URL)
}
+161
View File
@@ -0,0 +1,161 @@
package doc
import (
"context"
"encoding/json"
"errors"
"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"
)
// fakeFetchSvc captures call arguments and returns canned responses.
type fakeFetchSvc struct {
resp *sdk.Knowledge
err error
got struct {
kbID string
req sdk.CreateKnowledgeFromURLRequest
}
}
func (f *fakeFetchSvc) CreateKnowledgeFromURL(
_ context.Context,
kbID string,
req sdk.CreateKnowledgeFromURLRequest,
) (*sdk.Knowledge, error) {
f.got.kbID = kbID
f.got.req = req
return f.resp, f.err
}
func TestFetch_Success_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_url_1", FileName: "whitepaper.pdf"}}
opts := &FetchOptions{URL: "https://example.com/whitepaper.pdf"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, "https://example.com/whitepaper.pdf", svc.got.req.URL)
assert.Equal(t, "api", svc.got.req.Channel)
assert.Contains(t, out.String(), "Ingested")
assert.Contains(t, out.String(), "doc_url_1")
}
func TestFetch_WithName_PassesAsFileName(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_url_2"}}
opts := &FetchOptions{URL: "https://example.com/article.html", Name: "Q3 Article"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "Q3 Article", svc.got.req.FileName,
"--name must be forwarded as FileName (server uses it for file-vs-crawl mode hint)")
}
func TestFetch_Title(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/a.pdf", Title: "My Title"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "My Title", svc.got.req.Title)
}
func TestFetch_FileType(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/no-ext", FileType: "pdf"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "pdf", svc.got.req.FileType)
}
func TestFetch_TagID(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/a.pdf", TagID: "tag_99"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "tag_99", svc.got.req.TagID)
}
func TestFetch_EnableMultimodel_Forwarded(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
mm := true
opts := &FetchOptions{URL: "https://example.com/a.pdf", EnableMultimodel: &mm}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NotNil(t, svc.got.req.EnableMultimodel)
assert.True(t, *svc.got.req.EnableMultimodel)
}
func TestFetch_Channel_Override(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/a.pdf", Channel: "web"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "web", svc.got.req.Channel)
}
func TestFetch_Channel_DefaultIsAPI(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/a.pdf"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, uploadChannel, svc.got.req.Channel)
}
func TestFetch_JSON_Envelope(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_url_3", FileName: "ok.pdf"}}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
require.NoError(t, runFetch(context.Background(),
&FetchOptions{URL: "https://example.com/ok.pdf"}, fopts, svc, "kb_xxx"))
got := out.String()
var env struct {
OK bool `json:"ok"`
Data sdk.Knowledge `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, "doc_url_3", env.Data.ID, "envelope.data.id must be doc_url_3")
assert.NotContains(t, got, `"risk":`)
}
func TestFetch_DuplicateURL_Maps_resource_already_exists(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{
resp: &sdk.Knowledge{ID: "doc_existing"},
err: sdk.ErrDuplicateURL,
}
err := runFetch(context.Background(),
&FetchOptions{URL: "https://example.com/dup.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceAlreadyExists, typed.Code)
}
func TestFetch_ServerError_Wraps(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{err: errors.New("HTTP error 500: internal server error")}
err := runFetch(context.Background(),
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeServerError, typed.Code)
}
func TestFetch_KBResolutionFailure_Propagates(t *testing.T) {
// runFetch itself receives a pre-resolved kbID; KB resolution failure
// happens in RunE before runFetch is called. This test verifies that
// runFetch does NOT swallow an error returned from the service when
// kbID is empty (which a broken resolution chain might produce).
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{err: errors.New("HTTP error 404: knowledge base not found")}
err := runFetch(context.Background(),
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "")
require.Error(t, err)
}
+20 -130
View File
@@ -1,6 +1,7 @@
package doc
import (
"cmp"
"context"
"errors"
"fmt"
@@ -35,7 +36,6 @@ type UploadOptions struct {
Name string
Recursive bool // --recursive: positional arg is a directory; walk + upload each match
Glob string // --glob: filename pattern under --recursive (default "*")
FromURL string // --from-url: ingest a remote URL via SDK CreateKnowledgeFromURL
// EnableMultimodel toggles server-side multimodal extraction
// (e.g. images-in-PDF → OCR'd text). nil means "server default" -
@@ -49,12 +49,6 @@ type UploadOptions struct {
// Channel overrides the ingestion-channel tag recorded server-side.
// Empty ⇒ uploadChannel ("api"). Free-form: server validates.
Channel string
// URL-mode only fields. RunE-side validation rejects these if
// --from-url is not set (positional file path or --recursive).
Title string // --title: display title (URL mode)
FileType string // --file-type: extension hint for extension-less URLs
TagID string // --tag-id: associate the new knowledge entry with a tag
}
// UploadService is the narrow SDK surface this command depends on.
@@ -67,11 +61,6 @@ type UploadService interface {
enableMultimodel *bool,
customFileName, channel string,
) (*sdk.Knowledge, error)
CreateKnowledgeFromURL(
ctx context.Context,
kbID string,
req sdk.CreateKnowledgeFromURLRequest,
) (*sdk.Knowledge, error)
}
// NewCmdUpload builds `weknora doc upload <file>`.
@@ -89,35 +78,28 @@ 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).
The three input modes (positional file / --recursive directory walk /
--from-url remote ingest) are mutually exclusive - pass exactly one.
Use --recursive --glob to upload a directory tree (see Examples).
The two input modes (positional file / --recursive directory walk) are
mutually exclusive - pass exactly one. Use --recursive --glob to upload a
directory tree (see Examples). To ingest a remote URL use "weknora doc fetch";
to create an entry from inline text use "weknora doc create".
Server-side ingestion knobs:
--enable-multimodel Toggle multimodal extraction (image-in-PDF → text).
Unset ⇒ server default; pass true or false to override.
Applies to file / --recursive / --from-url.
Applies to file / --recursive.
--metadata key=value Attach arbitrary key/value metadata. Repeatable.
Empty value allowed; duplicate keys ⇒ last-wins.
Malformed values (no '=', empty key) ⇒
input.invalid_argument. File and --recursive modes
only; rejected on --from-url because the URL-ingest
request type carries no metadata field.
input.invalid_argument.
--channel <name> Override the ingestion-channel tag (default "api").
Applies to file / --recursive / --from-url.
URL mode (--from-url) additionally accepts --title, --file-type, and --tag-id.
Passing any of those without --from-url is rejected as input.invalid_argument.`,
Applies to file / --recursive.`,
Example: ` weknora doc upload report.pdf
weknora doc upload notes.md --kb a32a63ff-fb36-4874-bcaa-30f48570a694
weknora doc upload notes.md --kb my-kb
weknora doc upload q3.pdf --name "Q3 Marketing Report.pdf"
weknora doc upload report.pdf --enable-multimodel --metadata team=alpha --metadata sprint=Q4
weknora doc upload ./docs --recursive --glob '*.pdf' --metadata team=alpha
weknora doc upload --from-url https://example.com/whitepaper.pdf
weknora doc upload --from-url https://example.com/no-ext --file-type pdf --title "Whitepaper"
weknora doc upload --from-url https://example.com/article.html --name "Q3 Article" --tag-id tag_abc`,
weknora doc upload ./docs --recursive --glob '*.pdf' --metadata team=alpha`,
Args: cobra.MaximumNArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -149,33 +131,25 @@ Passing any of those without --from-url is rejected as input.invalid_argument.`,
return err
}
switch {
case opts.FromURL != "":
return runUploadFromURL(c.Context(), opts, fopts, cli, kbID)
case opts.Recursive:
if opts.Recursive {
return runUploadRecursive(c.Context(), opts, fopts, cli, kbID, args[0])
default:
if err := validateUploadPath(args[0]); err != nil {
return err
}
return runUpload(c.Context(), opts, fopts, cli, kbID, args[0])
}
if err := validateUploadPath(args[0]); err != nil {
return err
}
return runUpload(c.Context(), opts, fopts, cli, kbID, args[0])
},
}
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)")
cmd.Flags().StringVar(&opts.Name, "name", "", "Custom file name to record (defaults to base name)")
cmd.Flags().BoolVar(&opts.Recursive, "recursive", false, "Treat the positional argument as a directory to walk")
cmd.Flags().StringVar(&opts.Glob, "glob", "*", "Filename pattern to filter when --recursive (e.g. '*.pdf')")
cmd.Flags().StringVar(&opts.FromURL, "from-url", "", "Ingest a remote `URL` (HTTP/HTTPS) instead of a local file")
// Tri-state flag: unset ⇒ server default, "true"/"false" override. The
// raw string is decoded into opts.EnableMultimodel in RunE.
cmd.Flags().String("enable-multimodel", "", "Toggle multimodal extraction (true|false); unset ⇒ server default")
cmd.Flags().Lookup("enable-multimodel").NoOptDefVal = "true"
cmd.Flags().StringSliceVar(&opts.Metadata, "metadata", nil, "Attach metadata `key=value` (repeatable; empty value allowed, last-wins on duplicate keys)")
cmd.Flags().StringVar(&opts.Channel, "channel", "", "Ingestion-channel tag recorded server-side (default \"api\")")
cmd.Flags().StringVar(&opts.Title, "title", "", "Display title for the new entry (--from-url only)")
cmd.Flags().StringVar(&opts.FileType, "file-type", "", "File-type hint such as \"pdf\" when the URL has no extension (--from-url only)")
cmd.Flags().StringVar(&opts.TagID, "tag-id", "", "Tag id to associate with the new entry (--from-url only)")
cmdutil.AddFormatFlag(cmd, docUploadFields...)
return cmd
}
@@ -217,105 +191,21 @@ func parseMetadataKV(raw []string) (map[string]string, error) {
return out, nil
}
// effectiveChannel returns the channel string to send to the SDK. Empty
// opts.Channel falls back to the default "api" so the wire payload is
// identical to the pre-flag behavior.
func effectiveChannel(opts *UploadOptions) string {
if opts.Channel != "" {
return opts.Channel
}
return uploadChannel
}
// validateUploadFlags enforces mutual exclusion between the three input
// modes (positional file path / --recursive directory walk / --from-url
// remote ingest) and validates the URL when --from-url is set. It also
// rejects the URL-mode-only flags (--title, --file-type, --tag-id) when
// --from-url isn't set so misuse fails fast with a typed code.
// validateUploadFlags enforces mutual exclusion between the two input modes
// (positional file path / --recursive directory walk) and requires that at
// least one input mode is supplied.
func validateUploadFlags(opts *UploadOptions, args []string) error {
hasPath := len(args) == 1
hasURL := opts.FromURL != ""
if hasURL {
if hasPath {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"cannot pass a file path with --from-url; choose one input mode")
}
if opts.Recursive {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--recursive cannot be combined with --from-url")
}
// The server's URL-ingest request type has no Metadata field; a
// --metadata pair would be silently dropped on the wire. Reject
// up-front so callers don't think they've set metadata when they
// haven't.
if len(opts.Metadata) > 0 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--metadata is not supported with --from-url (server URL-ingest has no metadata field)")
}
return cmdutil.ValidateHTTPURL("--from-url", opts.FromURL)
}
if !hasPath {
// Wrap as FlagError so the exit code (2) matches what cobra's own
// MinimumNArgs(1) would emit — consistent with every other command
// that requires a positional argument.
return cmdutil.NewFlagError(errors.New(
"a file path is required (or pass --from-url)"))
}
return rejectURLOnlyFlags(opts)
}
// rejectURLOnlyFlags errors on --title / --file-type / --tag-id when
// --from-url is NOT set. Shared between validateUploadFlags (file mode)
// and runUploadRecursive (directory walk) so a future URL-mode-only flag
// only needs to add one entry here instead of two parallel checks.
func rejectURLOnlyFlags(opts *UploadOptions) error {
if opts.Title != "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--title is only valid with --from-url")
}
if opts.FileType != "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--file-type is only valid with --from-url")
}
if opts.TagID != "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--tag-id is only valid with --from-url")
"a file path is required (or use `weknora doc fetch` for URLs, `weknora doc create` for inline text)"))
}
return nil
}
// runUploadFromURL ingests a remote URL via SDK CreateKnowledgeFromURL.
// `--name` becomes the FileName hint so the server's "known file extension"
// detection upgrades crawl-mode to file-download-mode when appropriate.
// Server-side knobs (--enable-multimodel, --metadata via Title/TagID/FileType)
// propagate when set; the SDK request struct omits empty fields via
// `json:",omitempty"` tags so wire payload stays minimal.
func runUploadFromURL(ctx context.Context, opts *UploadOptions, fopts *cmdutil.FormatOptions, svc UploadService, kbID string) error {
req := sdk.CreateKnowledgeFromURLRequest{
URL: opts.FromURL,
FileName: opts.Name,
FileType: opts.FileType,
EnableMultimodel: opts.EnableMultimodel,
Title: opts.Title,
TagID: opts.TagID,
Channel: effectiveChannel(opts),
}
k, err := svc.CreateKnowledgeFromURL(ctx, kbID, req)
if err != nil {
if errors.Is(err, sdk.ErrDuplicateURL) {
// Server returns 409 with the existing knowledge entry's data.
// Surface as resource.already_exists; the data payload (if any)
// is observable via err's wrap chain - but the typed code is
// what agents branch on.
return cmdutil.Wrapf(cmdutil.CodeResourceAlreadyExists, err,
"URL already ingested into this knowledge base")
}
return cmdutil.WrapHTTP(err, "ingest URL %s", opts.FromURL)
}
return renderUploadSuccess(k, fopts, "Ingested", opts.Name, opts.FromURL)
}
// renderUploadSuccess emits the post-upload result. JSON path is the bare
// Knowledge object; human path prints a checkmark line. Shared by single-
// file upload and URL ingest; humanVerb varies (uploaded/ingested) and
@@ -323,7 +213,7 @@ func runUploadFromURL(ctx context.Context, opts *UploadOptions, fopts *cmdutil.F
// blank (URL ingest pre-redirect).
func renderUploadSuccess(k *sdk.Knowledge, fopts *cmdutil.FormatOptions, humanVerb, customName, fallbackDisplay string) error {
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, k)
return fopts.Emit(iostreams.IO.Out, k, nil)
}
displayed := customName
if displayed == "" {
@@ -362,7 +252,7 @@ func runUpload(ctx context.Context, opts *UploadOptions, fopts *cmdutil.FormatOp
if err != nil {
return err
}
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, meta, opts.EnableMultimodel, opts.Name, effectiveChannel(opts))
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, meta, opts.EnableMultimodel, opts.Name, cmp.Or(opts.Channel, uploadChannel))
if err != nil {
if errors.Is(err, sdk.ErrDuplicateFile) {
// SDK returns sentinel without an "HTTP error <status>:" prefix
+42 -38
View File
@@ -1,6 +1,7 @@
package doc
import (
"cmp"
"context"
"fmt"
"io/fs"
@@ -9,13 +10,14 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
)
// uploadOutcome is one entry in the recursive upload's per-file report.
type uploadOutcome struct {
Path string `json:"path"`
ID string `json:"id,omitempty"`
Error string `json:"error,omitempty"`
// uploadedFile holds the server-side result for a successful per-file upload.
// Keyed by file path in the uploadResults map populated by the RunBatch closure.
type uploadedFile struct {
ID string
Name string
}
// runUploadRecursive walks dir, filters by Glob, and uploads each match
@@ -32,12 +34,6 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, fopts *cmdutil
Hint: "drop --name or upload files one at a time",
}
}
// URL-mode-only flags are not meaningful for a directory walk;
// rejectURLOnlyFlags is the single source of truth shared with
// file-mode upload.
if err := rejectURLOnlyFlags(opts); err != nil {
return err
}
// Parse --metadata up front so a malformed value aborts before the
// first SDK call - otherwise a typo in `key=value` would only surface
// per-file as repeated identical errors.
@@ -75,73 +71,81 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, fopts *cmdutil
}
if len(matches) == 0 {
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, recursiveResult{KBID: kbID})
// Empty batch: emit an all-success envelope with zero items.
return output.WriteBatchEnvelope(iostreams.IO.Out, nil, fopts.TTY, cmdutil.GetProfile())
}
fmt.Fprintf(iostreams.IO.Out, "(no files matched %q under %s)\n", opts.Glob, dir)
return nil
}
var uploaded, failed []uploadOutcome
// uploaded captures per-path server results for successful uploads.
// Populated by the RunBatch closure; read by the resultFn below.
uploaded := make(map[string]uploadedFile, len(matches))
var firstFailCode cmdutil.ErrorCode
channel := effectiveChannel(opts)
for _, p := range matches {
channel := cmp.Or(opts.Channel, uploadChannel)
outcomes, runErr := cmdutil.RunBatch(ctx, matches, func(ctx context.Context, p string) error {
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, p, meta, opts.EnableMultimodel, "", channel)
if err != nil {
code := cmdutil.ClassifyHTTPError(err)
if firstFailCode == "" {
firstFailCode = code
}
failed = append(failed, uploadOutcome{Path: p, Error: err.Error()})
// Per-file progress lines are human progress signal; suppress
// under --format json so they don't precede the JSON object on stdout.
if !fopts.WantsJSON() {
fmt.Fprintf(iostreams.IO.Out, "FAIL %s: %v\n", filepath.Base(p), err)
}
continue
return err
}
id := ""
id, name := "", ""
if k != nil {
id = k.ID
name = k.FileName
}
uploaded = append(uploaded, uploadOutcome{Path: p, ID: id})
uploaded[p] = uploadedFile{ID: id, Name: name}
if !fopts.WantsJSON() {
fmt.Fprintf(iostreams.IO.Out, "OK %s (id: %s)\n", filepath.Base(p), id)
}
return nil
})
failures := 0
for _, oc := range outcomes {
if oc.Err != nil {
failures++
}
}
if fopts.WantsJSON() {
result := recursiveResult{KBID: kbID, Uploaded: uploaded, Failed: failed}
if err := fopts.Emit(iostreams.IO.Out, result); err != nil {
if err := cmdutil.EmitBatch(outcomes, fopts, iostreams.IO.Out, func(p string) any {
f := uploaded[p]
return map[string]any{"id": f.ID, "name": f.Name}
}); err != nil {
return err
}
} else {
fmt.Fprintf(iostreams.IO.Out, "Uploaded %d, Failed %d\n", len(uploaded), len(failed))
fmt.Fprintf(iostreams.IO.Out, "Uploaded %d, Failed %d\n", len(outcomes)-failures, failures)
}
if len(failed) > 0 {
if runErr != nil {
// Silent on the --format json path: the success object above already
// carries per-file uploaded[]/failed[] detail; without Silent the
// root error handler would print to stderr in addition. ExitCode
// still walks Code so the typed exit-code-by-class contract holds.
// carries per-file detail; without Silent the root error handler would
// print to stderr in addition. ExitCode still walks Code so the typed
// exit-code-by-class contract holds.
code := firstFailCode
if code == "" {
code = cmdutil.ClassifyContextErr(ctx.Err())
}
return &cmdutil.Error{
Code: firstFailCode,
Message: fmt.Sprintf("%d of %d uploads failed", len(failed), len(matches)),
Code: code,
Message: fmt.Sprintf("%d of %d uploads failed", failures, len(matches)),
Silent: fopts.WantsJSON(),
}
}
return nil
}
// recursiveResult is the JSON shape emitted under data when --recursive is
// combined with --format json. Mirrors the human-mode per-file output: a list of
// successes (Uploaded) and a list of failures (Failed), each with the
// originating path so agents can re-try only the failed entries.
type recursiveResult struct {
KBID string `json:"kb_id"`
Uploaded []uploadOutcome `json:"uploaded,omitempty"`
Failed []uploadOutcome `json:"failed,omitempty"`
}
// walkMatches returns every regular file under root whose base name matches
// pattern. Order is filepath.WalkDir's lexical order (stdlib guarantee on
// every supported FS), which is deterministic for test assertions.
+57 -51
View File
@@ -2,6 +2,7 @@ package doc
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
@@ -51,16 +52,6 @@ func (s *scriptedUploadSvc) CreateKnowledgeFromFile(
return r.k, r.err
}
// CreateKnowledgeFromURL satisfies UploadService but is unused by the
// recursive-walk path. Recursive upload only goes through CreateKnowledgeFromFile.
func (s *scriptedUploadSvc) CreateKnowledgeFromURL(
_ context.Context,
_ string,
_ sdk.CreateKnowledgeFromURLRequest,
) (*sdk.Knowledge, error) {
return nil, nil
}
func mkTree(t *testing.T, base string, names ...string) {
t.Helper()
for _, n := range names {
@@ -77,7 +68,7 @@ func TestUploadRecursive_WalksAllFiles(t *testing.T) {
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*"}
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
sort.Strings(svc.called)
assert.Equal(t, []string{"a.pdf", "b.pdf", "c.pdf"}, svc.called)
@@ -94,7 +85,7 @@ func TestUploadRecursive_GlobFilter(t *testing.T) {
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*.pdf"}
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
sort.Strings(svc.called)
assert.Equal(t, []string{"doc.pdf", "keep.pdf"}, svc.called)
@@ -112,7 +103,7 @@ func TestUploadRecursive_PartialFailure_Exits1(t *testing.T) {
"bad.pdf": {err: errors.New("HTTP error 500: internal")},
}}
opts := &UploadOptions{Recursive: true, Glob: "*"}
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
require.Error(t, err)
var typed *cmdutil.Error
@@ -135,7 +126,7 @@ func TestUploadRecursive_NoMatches(t *testing.T) {
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*.pdf"}
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
assert.Len(t, svc.called, 0)
assert.Contains(t, strings.ToLower(out.String()), "no files matched")
}
@@ -144,7 +135,7 @@ func TestUploadRecursive_NotADirectory(t *testing.T) {
_, _ = iostreams.SetForTest(t)
path := writeTempFile(t, "single.pdf")
svc := &scriptedUploadSvc{}
err := runUploadRecursive(context.Background(), &UploadOptions{Recursive: true, Glob: "*"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
err := runUploadRecursive(context.Background(), &UploadOptions{Recursive: true, Glob: "*"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -158,7 +149,7 @@ func TestUploadRecursive_RejectsNameFlag(t *testing.T) {
mkTree(t, dir, "a.pdf")
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*", Name: "single-name.pdf"}
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -180,7 +171,7 @@ func TestUploadRecursive_PropagatesMultimodelAndMetadata(t *testing.T) {
Metadata: []string{"team=alpha"},
Channel: "browser_extension",
}
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
require.NotNil(t, svc.lastEnableMultimodel)
assert.True(t, *svc.lastEnableMultimodel)
@@ -195,7 +186,7 @@ func TestUploadRecursive_MetadataInvalid_NoCalls(t *testing.T) {
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*", Metadata: []string{"badformat"}}
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -203,32 +194,10 @@ func TestUploadRecursive_MetadataInvalid_NoCalls(t *testing.T) {
assert.Empty(t, svc.called, "must fail before any per-file call")
}
func TestUploadRecursive_RejectsURLOnlyFlags(t *testing.T) {
_, _ = iostreams.SetForTest(t)
dir := t.TempDir()
mkTree(t, dir, "a.pdf")
for _, tc := range []struct {
name string
opts *UploadOptions
want string
}{
{"title", &UploadOptions{Recursive: true, Glob: "*", Title: "x"}, "--title"},
{"file-type", &UploadOptions{Recursive: true, Glob: "*", FileType: "pdf"}, "--file-type"},
{"tag-id", &UploadOptions{Recursive: true, Glob: "*", TagID: "t"}, "--tag-id"},
} {
t.Run(tc.name, func(t *testing.T) {
svc := &scriptedUploadSvc{}
err := runUploadRecursive(context.Background(), tc.opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", 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, tc.want)
})
}
}
func TestUploadRecursive_JSON_BareObject(t *testing.T) {
// TestUploadRecursive_JSON_BatchEnvelope verifies that --format json emits the
// §4.5 batch envelope shape: {ok, data:[{id,ok,result?|error?}...], meta:{count,successes,failures}}.
// The per-item id is the file path; result carries {id, name} from the server.
func TestUploadRecursive_JSON_BatchEnvelope(t *testing.T) {
out, _ := iostreams.SetForTest(t)
dir := t.TempDir()
mkTree(t, dir, "ok.pdf", "bad.pdf")
@@ -243,17 +212,54 @@ func TestUploadRecursive_JSON_BareObject(t *testing.T) {
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_xxx", dir)
require.Error(t, err) // partial failure → typed error
body := out.String()
assert.Contains(t, body, `"kb_id":"kb_xxx"`)
assert.Contains(t, body, `"uploaded":`)
assert.Contains(t, body, `"failed":`)
assert.Contains(t, body, `ok.pdf`)
assert.Contains(t, body, `bad.pdf`)
assert.NotContains(t, body, `"ok":`, "bare output must not carry envelope keys")
var env struct {
OK bool `json:"ok"`
Data []struct {
ID string `json:"id"`
OK bool `json:"ok"`
Result *struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"result,omitempty"`
Error *struct {
Type string `json:"type"`
Message string `json:"message"`
} `json:"error,omitempty"`
} `json:"data"`
Meta struct {
Count int `json:"count"`
Successes int `json:"successes"`
Failures int `json:"failures"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "must be valid JSON: %s", out.String())
assert.False(t, env.OK, "top-level ok must be false when any item failed")
assert.Equal(t, 2, env.Meta.Count)
assert.Equal(t, 1, env.Meta.Successes)
assert.Equal(t, 1, env.Meta.Failures)
require.Len(t, env.Data, 2)
// File paths are used as batch item ids; verify both files appear.
ids := []string{env.Data[0].ID, env.Data[1].ID}
assert.True(t, strings.Contains(ids[0], "ok.pdf") || strings.Contains(ids[1], "ok.pdf"), "ok.pdf must appear in batch data")
assert.True(t, strings.Contains(ids[0], "bad.pdf") || strings.Contains(ids[1], "bad.pdf"), "bad.pdf must appear in batch data")
// The success item must have a result with server id/name.
for _, item := range env.Data {
if strings.Contains(item.ID, "ok.pdf") {
assert.True(t, item.OK)
assert.NotNil(t, item.Result)
} else {
assert.False(t, item.OK)
assert.NotNil(t, item.Error)
}
}
// --format json must emit exactly ONE JSON document. Per-file "FAIL"/"OK"
// progress lines belong on the human path; the typed error is Silent so
// the root handler doesn't write anything additional to stdout.
body := out.String()
assert.NotContains(t, body, "FAIL ", "per-file plain lines must not appear under --format json")
assert.NotContains(t, body, "OK ", "per-file plain lines must not appear under --format json")
+32 -211
View File
@@ -2,6 +2,7 @@ package doc
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
@@ -18,15 +19,12 @@ import (
// fakeUploadSvc captures call arguments and returns canned responses.
type fakeUploadSvc struct {
resp *sdk.Knowledge
err error
urlResp *sdk.Knowledge
urlErr error
got struct {
resp *sdk.Knowledge
err error
got struct {
kbID, filePath, customName, channel string
metadata map[string]string
enableMultimodel *bool
urlReq sdk.CreateKnowledgeFromURLRequest
}
}
@@ -46,16 +44,6 @@ func (f *fakeUploadSvc) CreateKnowledgeFromFile(
return f.resp, f.err
}
func (f *fakeUploadSvc) CreateKnowledgeFromURL(
_ context.Context,
kbID string,
req sdk.CreateKnowledgeFromURLRequest,
) (*sdk.Knowledge, error) {
f.got.kbID = kbID
f.got.urlReq = req
return f.urlResp, f.urlErr
}
// writeTempFile creates a regular file under t.TempDir() with sample content.
func writeTempFile(t *testing.T, name string) string {
t.Helper()
@@ -69,7 +57,7 @@ func TestUpload_Success_Human(t *testing.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, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, path, svc.got.filePath)
@@ -91,7 +79,7 @@ func TestUpload_Success_CustomName(t *testing.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, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
assert.Equal(t, "Q3 Marketing Report.pdf", svc.got.customName)
}
@@ -103,16 +91,21 @@ func TestUpload_Success_JSON(t *testing.T) {
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_xxx", path))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"doc_77"`), "expected bare Knowledge object; got %q", got)
var env struct {
OK bool `json:"ok"`
Data sdk.Knowledge `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, "doc_77", env.Data.ID, "envelope.data.id must be doc_77")
assert.Contains(t, got, `"file_name":"a.md"`)
assert.NotContains(t, got, `"ok":`)
}
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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
@@ -124,7 +117,7 @@ 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{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
@@ -135,15 +128,12 @@ func TestUpload_HTTPError_409Conflict(t *testing.T) {
// TestUpload_DuplicateFileMaps_resource_already_exists pins the contract that
// the SDK's sentinel sdk.ErrDuplicateFile (returned with no "HTTP error <n>:"
// prefix because the duplicate is detected by file-hash short-circuit, not by
// status code) is mapped to resource.already_exists. Prior regression: the
// file-upload path forwarded the sentinel to WrapHTTP, which classified the
// prefix-less message as network.error — symmetric with the --from-url branch
// which already handled ErrDuplicateURL.
// status code) is mapped to resource.already_exists.
func TestUpload_DuplicateFileMaps_resource_already_exists(t *testing.T) {
_, _ = iostreams.SetForTest(t)
path := writeTempFile(t, "dup.md")
svc := &fakeUploadSvc{err: sdk.ErrDuplicateFile}
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
@@ -187,105 +177,7 @@ func TestValidateUploadPath_SymlinkToFileAccepted(t *testing.T) {
require.NoError(t, validateUploadPath(link))
}
// --from-url tests (4-N1).
func TestUploadFromURL_Success_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_url_1", FileName: "whitepaper.pdf"}}
opts := &UploadOptions{FromURL: "https://example.com/whitepaper.pdf"}
require.NoError(t, runUploadFromURL(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, "https://example.com/whitepaper.pdf", svc.got.urlReq.URL)
assert.Equal(t, "api", svc.got.urlReq.Channel)
assert.Contains(t, out.String(), "Ingested")
assert.Contains(t, out.String(), "doc_url_1")
}
func TestUploadFromURL_WithName_Passes_AsFileName(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_url_2"}}
opts := &UploadOptions{FromURL: "https://example.com/article.html", Name: "Q3 Article"}
require.NoError(t, runUploadFromURL(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "Q3 Article", svc.got.urlReq.FileName,
"--name must be forwarded as FileName (server uses it for file-vs-crawl mode hint)")
}
func TestUploadFromURL_JSON_BareObject(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_url_3", FileName: "ok.pdf"}}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
require.NoError(t, runUploadFromURL(context.Background(),
&UploadOptions{FromURL: "https://example.com/ok.pdf"}, fopts, svc, "kb_xxx"))
got := out.String()
assert.Contains(t, got, `"id":"doc_url_3"`)
assert.NotContains(t, got, `"ok":`)
assert.NotContains(t, got, `"risk":`)
}
func TestUploadFromURL_DuplicateURLMaps_resource_already_exists(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeUploadSvc{
urlResp: &sdk.Knowledge{ID: "doc_existing"},
urlErr: sdk.ErrDuplicateURL,
}
err := runUploadFromURL(context.Background(),
&UploadOptions{FromURL: "https://example.com/dup.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceAlreadyExists, typed.Code)
}
func TestValidateUploadFlags_FromURL_OK(t *testing.T) {
require.NoError(t, validateUploadFlags(&UploadOptions{FromURL: "https://example.com/x.pdf"}, nil))
}
func TestValidateUploadFlags_FromURL_WithPositional_Rejected(t *testing.T) {
err := validateUploadFlags(&UploadOptions{FromURL: "https://example.com/x.pdf"}, []string{"/tmp/x.pdf"})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
func TestValidateUploadFlags_FromURL_WithRecursive_Rejected(t *testing.T) {
err := validateUploadFlags(&UploadOptions{FromURL: "https://example.com/x.pdf", Recursive: true}, nil)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
// The server's URL-ingest request type has no Metadata field; the CLI must
// reject --metadata + --from-url upfront so callers don't think they've set
// metadata that the server then silently drops on the wire.
func TestValidateUploadFlags_FromURL_WithMetadata_Rejected(t *testing.T) {
err := validateUploadFlags(&UploadOptions{
FromURL: "https://example.com/x.pdf",
Metadata: []string{"team=alpha"},
}, nil)
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, "--metadata is not supported with --from-url")
}
func TestValidateUploadFlags_FromURL_BadScheme(t *testing.T) {
err := validateUploadFlags(&UploadOptions{FromURL: "file:///etc/passwd"}, nil)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
func TestValidateUploadFlags_FromURL_NoHost(t *testing.T) {
err := validateUploadFlags(&UploadOptions{FromURL: "https://"}, nil)
require.Error(t, err)
}
func TestValidateUploadFlags_NoPathOrURL_Rejected(t *testing.T) {
func TestValidateUploadFlags_NoPath_Rejected(t *testing.T) {
err := validateUploadFlags(&UploadOptions{}, nil)
require.Error(t, err)
// Missing required input wraps as FlagError so the exit code (2)
@@ -295,7 +187,11 @@ func TestValidateUploadFlags_NoPathOrURL_Rejected(t *testing.T) {
assert.Equal(t, 2, cmdutil.ExitCode(err))
}
// --- C10 expanded flags: multimodel / metadata / channel / URL-mode extras ---
func TestValidateUploadFlags_WithPath_OK(t *testing.T) {
require.NoError(t, validateUploadFlags(&UploadOptions{}, []string{"/tmp/x.pdf"}))
}
// --- C10 expanded flags: multimodel / metadata / channel ---
func TestUpload_EnableMultimodel_Set_True(t *testing.T) {
_, _ = iostreams.SetForTest(t)
@@ -303,7 +199,7 @@ func TestUpload_EnableMultimodel_Set_True(t *testing.T) {
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_mm", FileName: "mm.pdf"}}
mm := true
opts := &UploadOptions{EnableMultimodel: &mm}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NotNil(t, svc.got.enableMultimodel, "expected non-nil *bool when flag set")
assert.True(t, *svc.got.enableMultimodel)
}
@@ -314,7 +210,7 @@ func TestUpload_EnableMultimodel_Set_False(t *testing.T) {
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_mm", FileName: "mm.pdf"}}
mm := false
opts := &UploadOptions{EnableMultimodel: &mm}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NotNil(t, svc.got.enableMultimodel, "explicit false must still surface as non-nil *bool")
assert.False(t, *svc.got.enableMultimodel)
}
@@ -358,7 +254,7 @@ func TestUpload_Metadata_ParseKV(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"foo=bar", "baz=qux"}}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
assert.Equal(t, map[string]string{"foo": "bar", "baz": "qux"}, svc.got.metadata)
}
@@ -367,7 +263,7 @@ func TestUpload_Metadata_EmptyValueAllowed(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"foo="}}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
assert.Equal(t, map[string]string{"foo": ""}, svc.got.metadata)
}
@@ -376,7 +272,7 @@ func TestUpload_Metadata_LastWins(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"k=v1", "k=v2"}}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
assert.Equal(t, map[string]string{"k": "v2"}, svc.got.metadata)
}
@@ -385,7 +281,7 @@ func TestUpload_Metadata_InvalidFormat_NoEquals(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"foo"}}
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -397,7 +293,7 @@ func TestUpload_Metadata_InvalidFormat_EmptyKey(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"=bar"}}
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -409,7 +305,7 @@ func TestUpload_Channel_Override(t *testing.T) {
path := writeTempFile(t, "c.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_c", FileName: "c.pdf"}}
opts := &UploadOptions{Channel: "browser_extension"}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
assert.Equal(t, "browser_extension", svc.got.channel)
}
@@ -419,81 +315,6 @@ func TestUpload_Channel_DefaultStillAPI(t *testing.T) {
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_c", FileName: "c.pdf"}}
// Empty Channel is the runUpload contract for "use default".
opts := &UploadOptions{}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
assert.Equal(t, uploadChannel, svc.got.channel)
}
// URL-mode metadata happy paths
func TestUploadFromURL_Title(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_u"}}
opts := &UploadOptions{FromURL: "https://example.com/a.pdf", Title: "My Title"}
require.NoError(t, runUploadFromURL(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "My Title", svc.got.urlReq.Title)
}
func TestUploadFromURL_FileType(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_u"}}
opts := &UploadOptions{FromURL: "https://example.com/no-ext", FileType: "pdf"}
require.NoError(t, runUploadFromURL(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "pdf", svc.got.urlReq.FileType)
}
func TestUploadFromURL_TagID(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_u"}}
opts := &UploadOptions{FromURL: "https://example.com/a.pdf", TagID: "tag_99"}
require.NoError(t, runUploadFromURL(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "tag_99", svc.got.urlReq.TagID)
}
func TestUploadFromURL_EnableMultimodel_Forwarded(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_u"}}
mm := true
opts := &UploadOptions{FromURL: "https://example.com/a.pdf", EnableMultimodel: &mm}
require.NoError(t, runUploadFromURL(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
require.NotNil(t, svc.got.urlReq.EnableMultimodel)
assert.True(t, *svc.got.urlReq.EnableMultimodel)
}
func TestUploadFromURL_Channel_Override(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_u"}}
opts := &UploadOptions{FromURL: "https://example.com/a.pdf", Channel: "web"}
require.NoError(t, runUploadFromURL(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "web", svc.got.urlReq.Channel)
}
// URL-only flag misuse: error when used without --from-url.
// validateUploadFlags should reject --title/--file-type/--tag-id paired
// with a positional file path (i.e., no --from-url).
func TestValidateUploadFlags_Title_RequiresFromURL(t *testing.T) {
err := validateUploadFlags(&UploadOptions{Title: "x"}, []string{"/tmp/x.pdf"})
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, "--title")
}
func TestValidateUploadFlags_FileType_RequiresFromURL(t *testing.T) {
err := validateUploadFlags(&UploadOptions{FileType: "pdf"}, []string{"/tmp/x.pdf"})
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, "--file-type")
}
func TestValidateUploadFlags_TagID_RequiresFromURL(t *testing.T) {
err := validateUploadFlags(&UploadOptions{TagID: "tag_x"}, []string{"/tmp/x.pdf"})
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, "--tag-id")
}