feat(cli): agent-first WeKnora CLI
The `weknora` command-line client for the WeKnora RAG server. Full command surface: kb / doc / chunk / session / message / agent / model / search / chat / auth / profile / link / api / mcp / skills / config / doctor / schema / exit-codes. Agent-first wire contract: JSON envelope by default, typed error codes mapped to stable exit codes, error.retry_argv / retryable / partial-failure status, global --dry-run preview, the exit-10 confirmation protocol for writes, and control/ANSI/Bidi input hygiene. Stateless env-credential auth (WEKNORA_API_KEY / WEKNORA_TOKEN + WEKNORA_HOST) for headless/CI/agent use. A curated read-only MCP tool surface (`mcp serve`) and embedded Agent Skills (`skills install`). Extensive unit + contract-golden tests and CI.
This commit is contained in:
+23
-12
@@ -26,12 +26,17 @@ var docCreateFields = []string{
|
||||
// CreateOptions holds CLI flag values for `doc create`.
|
||||
type CreateOptions struct {
|
||||
Text string // --text (required): document text content (Markdown)
|
||||
Name string // --name: document title
|
||||
Title string // --title: document title (preferred; matches `doc update --title`)
|
||||
Name string // --name: deprecated alias for --title
|
||||
TagID string // --tag-id: associate with a tag
|
||||
Channel string // --channel: ingestion-channel tag (default "api")
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// title returns the resolved document title, preferring --title over the
|
||||
// deprecated --name alias.
|
||||
func (o *CreateOptions) title() string { return cmp.Or(o.Title, o.Name) }
|
||||
|
||||
// CreateService is the narrow SDK surface for `doc create`.
|
||||
// *sdk.Client satisfies it.
|
||||
type CreateService interface {
|
||||
@@ -54,12 +59,12 @@ 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.
|
||||
--title <title> Display title stored with the entry (matches doc update --title).
|
||||
--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`,
|
||||
weknora doc create --text "$(cat notes.md)" --title "Sprint Notes" --kb my-kb
|
||||
weknora doc create --text "API usage guide" --title "API Guide" --tag-id tag_abc`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
@@ -78,9 +83,9 @@ don't require a file upload or remote URL. KB resolution follows the standard
|
||||
if handled, err := cmdutil.HandleDryRun(c, true, cmdutil.DryRunPlan{
|
||||
Action: "doc.create",
|
||||
Args: map[string]any{
|
||||
"text": opts.Text,
|
||||
"name": opts.Name,
|
||||
"kb": kbID,
|
||||
"text": opts.Text,
|
||||
"title": opts.title(),
|
||||
"kb": kbID,
|
||||
},
|
||||
}); handled {
|
||||
return err
|
||||
@@ -100,7 +105,9 @@ don't require a file upload or remote URL. KB resolution follows the standard
|
||||
}
|
||||
cmdutil.AddKBFlag(cmd)
|
||||
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.Title, "title", "", "Document title")
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Document title (deprecated: use --title)")
|
||||
_ = cmd.Flags().MarkDeprecated("name", "use --title instead")
|
||||
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")
|
||||
@@ -108,8 +115,12 @@ don't require a file upload or remote URL. KB resolution follows the standard
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Create a knowledge entry from inline Markdown text. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
|
||||
RequiredFlags: []string{"--text"},
|
||||
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, title, parse_status",
|
||||
RequiredFlags: []string{"--text", "--kb (or WEKNORA_KB_ID / project link)"},
|
||||
Examples: []string{
|
||||
`weknora doc create --kb kb_eng --text "# Runbook\n\nRestart steps: ..."`,
|
||||
`weknora doc create --kb kb_eng --text "$(cat notes.md)" --title "Sprint Notes"`,
|
||||
},
|
||||
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, title, parse_status",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
@@ -123,7 +134,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
|
||||
return cmdutil.NewFlagError(fmt.Errorf("--text is required"))
|
||||
}
|
||||
req := &sdk.CreateManualKnowledgeRequest{
|
||||
Title: opts.Name,
|
||||
Title: opts.title(),
|
||||
Content: opts.Text,
|
||||
TagID: opts.TagID,
|
||||
Channel: cmp.Or(opts.Channel, uploadChannel),
|
||||
@@ -135,7 +146,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, k, nil)
|
||||
}
|
||||
displayed := opts.Name
|
||||
displayed := opts.title()
|
||||
if displayed == "" {
|
||||
displayed = k.Title
|
||||
}
|
||||
|
||||
@@ -35,6 +35,24 @@ func (f *fakeCreateSvc) CreateManualKnowledge(
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
// TestCreate_TitlePreferredOverName: --title is the canonical flag; the
|
||||
// deprecated --name remains a working alias but --title wins when both are set.
|
||||
func TestCreate_TitlePreferredOverName(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "d1"}}
|
||||
require.NoError(t, runCreate(context.Background(),
|
||||
&CreateOptions{Text: "x", Title: "FromTitle", Name: "FromName"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"))
|
||||
assert.Equal(t, "FromTitle", svc.got.req.Title)
|
||||
|
||||
// --name alone still works (back-compat for the deprecated alias).
|
||||
svc2 := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "d2"}}
|
||||
require.NoError(t, runCreate(context.Background(),
|
||||
&CreateOptions{Text: "x", Name: "OnlyName"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc2, "kb1"))
|
||||
assert.Equal(t, "OnlyName", svc2.got.req.Title)
|
||||
}
|
||||
|
||||
func TestCreate_Success_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_1", Title: "Sprint Notes"}}
|
||||
|
||||
@@ -3,7 +3,6 @@ package doc
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
@@ -95,7 +94,7 @@ without the user's explicit go-ahead.`,
|
||||
if opts.KB == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--all requires --kb=<id>").
|
||||
WithHint("specify --kb=<uuid-or-name> to scope the delete-all operation").
|
||||
WithRetryCommand("weknora doc delete --all --kb=<kb-id> -y")
|
||||
WithRetryArgv([]string{"weknora", "doc", "delete", "--all", "--kb=<kb-id>", "-y"})
|
||||
}
|
||||
if len(args) > 0 {
|
||||
return cmdutil.NewFlagError(fmt.Errorf("--all is exclusive with positional doc ids"))
|
||||
@@ -138,7 +137,9 @@ without the user's explicit go-ahead.`,
|
||||
if len(args) == 1 {
|
||||
return runDelete(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
|
||||
}
|
||||
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "document", len(args), "doc.delete", "weknora doc delete "+strings.Join(args, " ")+" -y"); err != nil {
|
||||
batchRetry := append([]string{"weknora", "doc", "delete"}, args...)
|
||||
batchRetry = append(batchRetry, "-y")
|
||||
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "document", len(args), "doc.delete", batchRetry); err != nil {
|
||||
return err
|
||||
}
|
||||
outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error {
|
||||
@@ -171,6 +172,7 @@ without the user's explicit go-ahead.`,
|
||||
"weknora doc delete doc_a doc_b doc_c -y",
|
||||
"weknora doc delete --all --kb=kb_x -y --format json",
|
||||
},
|
||||
Output: "envelope.data shape depends on the form: a single doc id -> {id, deleted:true}; multiple doc ids -> batch envelope (top-level status success|partial|error, ok=(failures==0), data per-item [{id, ok, error?}], meta.successes/failures — read data[].ok per id, ok:true overall does not survive a partial failure / exit 1); --all --kb -> {kb_id, deleted_count}.",
|
||||
Warnings: []string{
|
||||
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
|
||||
"doc delete is irreversible; loses the document + its chunks + embeddings.",
|
||||
@@ -181,7 +183,7 @@ without the user's explicit go-ahead.`,
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "document", id, "doc.delete", "weknora doc delete "+id+" -y"); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "document", id, "doc.delete", []string{"weknora", "doc", "delete", id, "-y"}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -201,7 +203,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOp
|
||||
// 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(), "delete", "all docs in KB", opts.KB, "doc.delete_all", fmt.Sprintf("weknora doc delete --all --kb=%s -y", opts.KB)); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "all docs in KB", opts.KB, "doc.delete_all", []string{"weknora", "doc", "delete", "--all", "--kb=" + opts.KB, "-y"}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -262,7 +262,7 @@ func TestRunMultiDelete_ConfirmBatch_NonTTY_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t) // non-TTY
|
||||
svc := &fakeDeleteSvc{}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "delete", "document", 2, "doc.delete", "")
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "delete", "document", 2, "doc.delete", nil)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -274,7 +274,7 @@ func TestRunMultiDelete_ConfirmBatch_TTY_UserAborts(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "delete", "document", 3, "doc.delete", "")
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "delete", "document", 3, "doc.delete", nil)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
@@ -26,6 +26,8 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.AddCommand(NewCmdDownload(f))
|
||||
cmd.AddCommand(NewCmdFetch(f))
|
||||
cmd.AddCommand(NewCmdList(f))
|
||||
cmd.AddCommand(NewCmdReparse(f))
|
||||
cmd.AddCommand(NewCmdUpdate(f))
|
||||
cmd.AddCommand(NewCmdUpload(f))
|
||||
cmd.AddCommand(NewCmdView(f))
|
||||
cmd.AddCommand(NewCmdWait(f))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package doc — dryrun_validation_test.go asserts that --dry-run on
|
||||
// doc subcommands rejects identically to the live path (industry standard:
|
||||
// gh / kubectl / lark all validate before previewing). Before the surrounding
|
||||
// fix, validation lived in runX() and was reached only after HandleDryRun
|
||||
// doc subcommands rejects identically to the live path (validation must run
|
||||
// before previewing). Before the surrounding fix, validation lived in runX()
|
||||
// and was reached only after HandleDryRun
|
||||
// short-circuited, so --dry-run silently emitted plan envelopes for inputs
|
||||
// the live path would reject — agents got false-positive previews.
|
||||
package doc
|
||||
|
||||
@@ -136,8 +136,11 @@ Server-side ingestion knobs:
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Ingest a remote URL into the resolved knowledge base. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
|
||||
RequiredFlags: []string{"<url> (positional)"},
|
||||
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, source, parse_status",
|
||||
RequiredFlags: []string{"<url> (positional)", "--kb (or WEKNORA_KB_ID / project link)"},
|
||||
Examples: []string{
|
||||
`weknora doc fetch https://example.com/whitepaper.pdf --kb kb_eng`,
|
||||
},
|
||||
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, source, parse_status",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
+44
-37
@@ -3,9 +3,7 @@ package doc
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
@@ -48,10 +46,6 @@ type ListOptions struct {
|
||||
EndTime string // raw RFC3339; parsed into filter.EndTime
|
||||
}
|
||||
|
||||
// rfc3339Example is the canonical RFC3339 hint surfaced when --start-time /
|
||||
// --end-time fail to parse. Picked to match Go's reference time docs.
|
||||
const rfc3339Example = "2006-01-02T15:04:05Z"
|
||||
|
||||
// docListStatusValues mirrors internal/types/knowledge.go ParseStatus*
|
||||
// constants - these are the values the server accepts on the
|
||||
// ?parse_status= query. Kept in sync manually since the SDK doesn't
|
||||
@@ -88,6 +82,14 @@ backend storage order is not guaranteed and varies between deployments.`,
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
// Validate static input (--page-size / --limit / --status) before
|
||||
// resolving the KB or building the client so a bad value returns
|
||||
// input.invalid_argument (exit 5) instead of an auth error (exit 3)
|
||||
// when the profile is unconfigured — an agent must see the real,
|
||||
// fixable problem.
|
||||
if err := validateListOpts(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
kbID, err := f.ResolveKB(c)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -101,7 +103,7 @@ backend storage order is not guaranteed and varies between deployments.`,
|
||||
}
|
||||
cmdutil.AddKBFlag(cmd)
|
||||
cmd.Flags().IntVar(&opts.PageSize, "page-size", 50, "Items per server batch (1..1000)")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return — client-side cap; meta.has_more/total_count report the full size (1..10000)")
|
||||
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
|
||||
cmd.Flags().StringVar(&opts.Status, "status", "", "Filter by parse status: pending | processing | completed | failed")
|
||||
cmd.Flags().StringVar(&opts.Keyword, "keyword", "", "Server-side substring match against title / file_name (case-sensitive)")
|
||||
@@ -114,12 +116,15 @@ backend storage order is not guaranteed and varies between deployments.`,
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "List documents in the resolved knowledge base. Results come with meta.count; use --limit to cap, --all-pages to walk every server page, --status/--keyword to filter server-side.",
|
||||
Examples: []string{"weknora doc list --format json", "weknora doc list --all-pages --limit 200 --format json"},
|
||||
Output: "envelope.data is an array of Knowledge objects with id, title, file_name, parse_status; meta.count is the total returned",
|
||||
Output: "envelope.data is an array of Knowledge objects with id, title, file_name, parse_status; meta.count is the total returned; meta.total_count is the server-side total before client-side --limit truncation",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService, kbID string) error {
|
||||
// validateListOpts checks --page-size / --limit / --status. Called from RunE
|
||||
// before the KB/client are resolved (so bad input surfaces as exit 5, not an
|
||||
// auth error) and again at the top of runList for direct callers; idempotent.
|
||||
func validateListOpts(opts *ListOptions) error {
|
||||
if opts.PageSize < 1 || opts.PageSize > 1000 {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
@@ -132,12 +137,19 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
|
||||
}
|
||||
}
|
||||
if opts.Status != "" && !validDocListStatus(opts.Status) {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("--status must be one of: %s - got %q",
|
||||
strings.Join(docListStatusValues, " | "), opts.Status),
|
||||
}
|
||||
// Validate + normalize --status via the shared enum helper (same exit-5
|
||||
// path and case-insensitive normalization as every other enum flag).
|
||||
status, err := cmdutil.ValidateEnum("status", opts.Status, docListStatusValues)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.Status = status
|
||||
return nil
|
||||
}
|
||||
|
||||
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService, kbID string) error {
|
||||
if err := validateListOpts(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
filter := sdk.KnowledgeListFilter{
|
||||
ParseStatus: opts.Status,
|
||||
@@ -146,26 +158,25 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
Source: opts.Source,
|
||||
TagID: opts.TagID,
|
||||
}
|
||||
if opts.StartTime != "" {
|
||||
t, err := time.Parse(time.RFC3339, opts.StartTime)
|
||||
if err != nil {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
|
||||
fmt.Sprintf("--start-time must be RFC3339 (e.g. %s), got %q", rfc3339Example, opts.StartTime))
|
||||
}
|
||||
filter.StartTime = t
|
||||
start, err := cmdutil.ParseTimeFlag("--start-time", opts.StartTime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.EndTime != "" {
|
||||
t, err := time.Parse(time.RFC3339, opts.EndTime)
|
||||
if err != nil {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
|
||||
fmt.Sprintf("--end-time must be RFC3339 (e.g. %s), got %q", rfc3339Example, opts.EndTime))
|
||||
}
|
||||
filter.EndTime = t
|
||||
if start != nil {
|
||||
filter.StartTime = *start
|
||||
}
|
||||
end, err := cmdutil.ParseTimeFlag("--end-time", opts.EndTime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if end != nil {
|
||||
filter.EndTime = *end
|
||||
}
|
||||
|
||||
// Pagination is always 1-indexed internally. --all-pages walks; the
|
||||
// non-walking path returns the first page only.
|
||||
var items []sdk.Knowledge
|
||||
var serverTotal int64
|
||||
if opts.AllPages {
|
||||
accum := make([]sdk.Knowledge, 0)
|
||||
for page := 1; ; page++ {
|
||||
@@ -173,6 +184,7 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list documents")
|
||||
}
|
||||
serverTotal = total
|
||||
accum = append(accum, chunk...)
|
||||
if opts.Limit > 0 && len(accum) >= opts.Limit {
|
||||
accum = accum[:opts.Limit]
|
||||
@@ -184,10 +196,11 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
}
|
||||
items = accum
|
||||
} else {
|
||||
chunk, _, err := svc.ListKnowledgeWithFilter(ctx, kbID, 1, opts.PageSize, filter)
|
||||
chunk, total, err := svc.ListKnowledgeWithFilter(ctx, kbID, 1, opts.PageSize, filter)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "list documents")
|
||||
}
|
||||
serverTotal = total
|
||||
items = chunk
|
||||
}
|
||||
if items == nil {
|
||||
@@ -208,7 +221,7 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
meta := &output.Meta{Count: len(items), HasMore: truncated}
|
||||
meta := &output.Meta{Count: output.IntPtr(len(items)), HasMore: truncated, TotalCount: output.IntPtr(int(serverTotal))}
|
||||
return fopts.Emit(iostreams.IO.Out, items, meta)
|
||||
}
|
||||
|
||||
@@ -228,12 +241,6 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
return tw.Flush()
|
||||
}
|
||||
|
||||
// validDocListStatus reports whether s matches one of the server-accepted
|
||||
// parse_status enum values surfaced via --status.
|
||||
func validDocListStatus(s string) bool {
|
||||
return slices.Contains(docListStatusValues, s)
|
||||
}
|
||||
|
||||
// formatSize renders a byte count as a short human string (KB / MB).
|
||||
// Kept tiny on purpose - go-humanize would pull a transitive dep just for one
|
||||
// column. A "-" placeholder hides zero-size entries (URL / text).
|
||||
|
||||
@@ -431,6 +431,45 @@ func TestList_EndTime_InvalidFormat_Rejected(t *testing.T) {
|
||||
assert.Contains(t, typed.Message, "--end-time")
|
||||
}
|
||||
|
||||
// TestList_JSON_TotalCount_SinglePage asserts that meta.total_count is populated
|
||||
// from the server total when doing a single-page fetch.
|
||||
func TestList_JSON_TotalCount_SinglePage(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{
|
||||
items: []sdk.Knowledge{{ID: "doc1", FileName: "a.pdf"}},
|
||||
total: 99,
|
||||
}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_xxx"))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"total_count":99`, "single-page fetch must surface server total in meta.total_count")
|
||||
}
|
||||
|
||||
// TestList_JSON_TotalCount_AllPages asserts meta.total_count is populated
|
||||
// from the server total when walking all pages.
|
||||
func TestList_JSON_TotalCount_AllPages(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &pagedDocSvc{all: makeDocs(45)}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 10000, AllPages: true}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_xxx"))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"total_count":45`, "--all-pages fetch must surface server total in meta.total_count")
|
||||
}
|
||||
|
||||
// TestList_JSON_TotalCount_Zero_Present asserts that when server returns total=0
|
||||
// on an empty list, meta.total_count (and meta.count) still serialize as 0. The
|
||||
// *int + omitempty pattern omits only nil, so the agent contract stays stable:
|
||||
// an empty result reports 0, not a missing key.
|
||||
func TestList_JSON_TotalCount_Zero_Present(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{items: nil, total: 0}
|
||||
opts := &ListOptions{PageSize: 20, Limit: 30}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_xxx"))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"total_count":0`, "zero server total must serialize as 0 on empty list")
|
||||
assert.Contains(t, body, `"count":0`, "empty list must report count:0, not omit it")
|
||||
}
|
||||
|
||||
// TestList_AllFiltersCombined drives every new filter flag at once to confirm
|
||||
// they all land on the same filter struct (AND combine on the server).
|
||||
func TestList_AllFiltersCombined(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package doc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// docReparseFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `doc reparse`. The result is the Knowledge object; the caller mainly wants
|
||||
// the id and the reset parse_status.
|
||||
var docReparseFields = []string{"id", "parse_status", "file_name", "title"}
|
||||
|
||||
// ReparseOptions captures `doc reparse` flag state.
|
||||
type ReparseOptions struct {
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// ReparseService is the narrow SDK surface this command depends on.
|
||||
type ReparseService interface {
|
||||
ReparseKnowledge(ctx context.Context, id string) (*sdk.Knowledge, error)
|
||||
}
|
||||
|
||||
// NewCmdReparse builds `weknora doc reparse <doc-id>`.
|
||||
func NewCmdReparse(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &ReparseOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "reparse <doc-id>",
|
||||
Short: "Re-run parsing on a document",
|
||||
Long: `Re-trigger server-side parsing of a document — the recovery path when a
|
||||
document's parse_status is failed, or after its source changed. The document
|
||||
keeps its id; parsing restarts asynchronously, so follow with
|
||||
'weknora doc wait <doc-id>' to block until it reaches a terminal status.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
|
||||
Action: "doc.reparse",
|
||||
Args: map[string]any{"doc": args[0]},
|
||||
}); handled {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runReparse(c.Context(), opts, fopts, cli, args[0])
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, docReparseFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "re-run parsing on a document (recovery after parse_status=failed, or a changed source)",
|
||||
RequiredFlags: []string{"<doc-id> (positional)"},
|
||||
Examples: []string{
|
||||
"weknora doc reparse doc_abc",
|
||||
"weknora doc reparse doc_abc --format json",
|
||||
},
|
||||
Output: "envelope.data is the Knowledge object with parse_status reset to the re-processing state; poll `weknora doc wait <doc-id>` for completion",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runReparse(ctx context.Context, opts *ReparseOptions, fopts *cmdutil.FormatOptions, svc ReparseService, id string) error {
|
||||
k, err := svc.ReparseKnowledge(ctx, id)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "reparse document %s", id)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, k, nil)
|
||||
}
|
||||
// fileName → title, with no id fallback (empty means "skip the suffix").
|
||||
name := text.KnowledgeDisplayName(k.FileName, k.Title, "")
|
||||
w := iostreams.IO.Out
|
||||
fmt.Fprintf(w, "✓ reparse triggered for %s", id)
|
||||
if name != "" {
|
||||
fmt.Fprintf(w, " (%s)", name)
|
||||
}
|
||||
fmt.Fprintln(w)
|
||||
if k.ParseStatus != "" {
|
||||
fmt.Fprintf(w, " parse_status: %s\n", k.ParseStatus)
|
||||
}
|
||||
fmt.Fprintf(w, " next: weknora doc wait %s\n", id)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
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"
|
||||
)
|
||||
|
||||
type fakeReparseSvc struct {
|
||||
k *sdk.Knowledge
|
||||
err error
|
||||
called bool
|
||||
}
|
||||
|
||||
func (f *fakeReparseSvc) ReparseKnowledge(_ context.Context, id string) (*sdk.Knowledge, error) {
|
||||
f.called = true
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
k := *f.k
|
||||
k.ID = id
|
||||
return &k, nil
|
||||
}
|
||||
|
||||
func TestDocReparse_Text(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeReparseSvc{k: &sdk.Knowledge{FileName: "runbook.md", ParseStatus: "processing"}}
|
||||
require.NoError(t, runReparse(context.Background(), &ReparseOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc"))
|
||||
assert.True(t, svc.called)
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "doc_abc")
|
||||
assert.Contains(t, got, "runbook.md")
|
||||
assert.Contains(t, got, "processing")
|
||||
assert.Contains(t, got, "doc wait doc_abc")
|
||||
}
|
||||
|
||||
func TestDocReparse_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeReparseSvc{k: &sdk.Knowledge{ParseStatus: "processing"}}
|
||||
require.NoError(t, runReparse(context.Background(), &ReparseOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "doc_abc"))
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data sdk.Knowledge `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "got %q", out.String())
|
||||
assert.True(t, env.OK)
|
||||
assert.Equal(t, "doc_abc", env.Data.ID)
|
||||
assert.Equal(t, "processing", env.Data.ParseStatus)
|
||||
}
|
||||
|
||||
func TestDocReparse_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeReparseSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runReparse(context.Background(), &ReparseOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsNotFound(err))
|
||||
}
|
||||
|
||||
// TestDocReparse_DryRun_NoServerCall: --dry-run must emit a doc.reparse plan
|
||||
// (exit 0) without reaching the server, honoring the mutation-preview contract.
|
||||
func TestDocReparse_DryRun_NoServerCall(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
root := withRootHarnessDoc(NewCmdReparse(docDryRunFactory(t)), "doc_x", "--dry-run", "--format", "json")
|
||||
require.NoError(t, root.Execute(), "dry-run must succeed without a client")
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Meta struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
Plan map[string]any `json:"plan"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "got %q", out.String())
|
||||
assert.True(t, env.OK)
|
||||
assert.True(t, env.Meta.DryRun)
|
||||
assert.Equal(t, "doc.reparse", env.Meta.Plan["action"])
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package doc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// docUpdateFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `doc update`. The result is the updated Knowledge object.
|
||||
var docUpdateFields = []string{"id", "title", "description", "file_name", "parse_status"}
|
||||
|
||||
// UpdateOptions captures `doc update` flag state. Title/Description are *string
|
||||
// so an unset flag is distinguishable from "set to empty" — only fields the
|
||||
// user passed are changed; the rest are preserved via fetch-then-update.
|
||||
type UpdateOptions struct {
|
||||
Title *string
|
||||
Description *string
|
||||
Yes bool // sourced from global -y/--yes persistent flag
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// UpdateService is the narrow SDK surface this command depends on. The server's
|
||||
// UpdateKnowledge endpoint persists only title and description (other fields on
|
||||
// the PUT body are ignored), so this command edits just those two; GetKnowledge
|
||||
// supplies the fetch half of the fetch-then-update flow.
|
||||
type UpdateService interface {
|
||||
GetKnowledge(ctx context.Context, id string) (*sdk.Knowledge, error)
|
||||
UpdateKnowledge(ctx context.Context, k *sdk.Knowledge) error
|
||||
}
|
||||
|
||||
// NewCmdUpdate builds `weknora doc update <doc-id>`. At least one of
|
||||
// --title / --description must be provided.
|
||||
func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &UpdateOptions{}
|
||||
var title, desc string
|
||||
cmd := &cobra.Command{
|
||||
Use: "update <doc-id>",
|
||||
Short: "Update a document's title or description",
|
||||
Long: `Update a document's title and/or description. At least one of --title /
|
||||
--description must be supplied; the document's content, file, and parse state are
|
||||
untouched (only the title and description are editable — re-upload to change the
|
||||
content).
|
||||
|
||||
AI agents: this is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
with input.confirmation_required. Never auto-pass -y; surface the prompt
|
||||
to the user first.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
if c.Flag("title").Changed {
|
||||
opts.Title = &title
|
||||
}
|
||||
if c.Flag("description").Changed {
|
||||
opts.Description = &desc
|
||||
}
|
||||
id := args[0]
|
||||
// Validate "at least one mutation flag" before the dry-run gate so
|
||||
// --dry-run rejects identically to the live path.
|
||||
if opts.Title == nil && opts.Description == nil {
|
||||
return errNoUpdateFlag()
|
||||
}
|
||||
planArgs := map[string]any{"doc": id}
|
||||
if opts.Title != nil {
|
||||
planArgs["title"] = *opts.Title
|
||||
}
|
||||
if opts.Description != nil {
|
||||
planArgs["description"] = *opts.Description
|
||||
}
|
||||
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
|
||||
Action: "doc.update",
|
||||
Args: planArgs,
|
||||
}); handled {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Build a retry command from the flags the user actually passed so
|
||||
// agents can re-invoke with -y after explicit human approval.
|
||||
retryCmd := cmdutil.BuildRetryArgv(c, []string{"weknora", "doc", "update", id}, "title", "description", "format")
|
||||
if err := cmdutil.ConfirmWrite(f.Prompter(), opts.Yes, fopts.WantsJSON(), "update", "document", id, "doc.update", retryCmd); err != nil {
|
||||
return err
|
||||
}
|
||||
return runUpdate(c.Context(), opts, fopts, cli, id)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&title, "title", "", "New title (omit to leave unchanged)")
|
||||
cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)")
|
||||
cmdutil.AddFormatFlag(cmd, docUpdateFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetWriteRisk(cmd, "doc.update")
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "update a document's title or description (content is not editable — re-upload for that)",
|
||||
RequiredFlags: []string{"<doc-id> (positional)", "--title or --description (at least one)"},
|
||||
Examples: []string{
|
||||
`weknora doc update doc_abc --title "Q3 Runbook" -y`,
|
||||
`weknora doc update doc_abc --description "archived" --format json -y`,
|
||||
},
|
||||
Output: "envelope.data is the Knowledge object with the new title/description",
|
||||
Warnings: []string{
|
||||
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func errNoUpdateFlag() error {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputMissingFlag,
|
||||
Message: "doc update requires at least one of --title or --description",
|
||||
Hint: "pass --title <title> and/or --description <desc>",
|
||||
}
|
||||
}
|
||||
|
||||
func runUpdate(ctx context.Context, opts *UpdateOptions, fopts *cmdutil.FormatOptions, svc UpdateService, id string) error {
|
||||
if opts.Title == nil && opts.Description == nil {
|
||||
return errNoUpdateFlag()
|
||||
}
|
||||
// Fetch-then-update: load the current record, overlay only the fields the
|
||||
// user set, and PUT the whole object. TOCTOU note: a concurrent writer could
|
||||
// change the record between the Get and Put (same window as kb update).
|
||||
current, err := svc.GetKnowledge(ctx, id)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "fetch document %s", id)
|
||||
}
|
||||
if opts.Title != nil {
|
||||
current.Title = *opts.Title
|
||||
}
|
||||
if opts.Description != nil {
|
||||
current.Description = *opts.Description
|
||||
}
|
||||
if err := svc.UpdateKnowledge(ctx, current); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "update document %s", id)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, current, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Updated document %s\n", id)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
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"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type fakeUpdateSvc struct {
|
||||
current *sdk.Knowledge
|
||||
getErr error
|
||||
updateErr error
|
||||
got *sdk.Knowledge // captured object passed to UpdateKnowledge
|
||||
}
|
||||
|
||||
func (f *fakeUpdateSvc) GetKnowledge(_ context.Context, id string) (*sdk.Knowledge, error) {
|
||||
if f.getErr != nil {
|
||||
return nil, f.getErr
|
||||
}
|
||||
c := *f.current
|
||||
c.ID = id
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (f *fakeUpdateSvc) UpdateKnowledge(_ context.Context, k *sdk.Knowledge) error {
|
||||
f.got = k
|
||||
return f.updateErr
|
||||
}
|
||||
|
||||
func strptr(s string) *string { return &s }
|
||||
|
||||
func TestDocUpdate_Title_FetchThenUpdate(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeUpdateSvc{current: &sdk.Knowledge{Title: "Old", Description: "keep", FileName: "f.md"}}
|
||||
require.NoError(t, runUpdate(context.Background(),
|
||||
&UpdateOptions{Title: strptr("New")}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "doc_abc"))
|
||||
// Only title changed; description preserved from the fetched record.
|
||||
require.NotNil(t, svc.got)
|
||||
assert.Equal(t, "New", svc.got.Title)
|
||||
assert.Equal(t, "keep", svc.got.Description)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data sdk.Knowledge `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "got %q", out.String())
|
||||
assert.True(t, env.OK)
|
||||
assert.Equal(t, "doc_abc", env.Data.ID)
|
||||
assert.Equal(t, "New", env.Data.Title)
|
||||
}
|
||||
|
||||
func TestDocUpdate_DescriptionOnly_PreservesTitle(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeUpdateSvc{current: &sdk.Knowledge{Title: "Keep", Description: "old"}}
|
||||
require.NoError(t, runUpdate(context.Background(),
|
||||
&UpdateOptions{Description: strptr("fresh")}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc"))
|
||||
assert.Equal(t, "Keep", svc.got.Title)
|
||||
assert.Equal(t, "fresh", svc.got.Description)
|
||||
}
|
||||
|
||||
func TestDocUpdate_NoFlags_MissingFlag(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeUpdateSvc{current: &sdk.Knowledge{}}
|
||||
err := runUpdate(context.Background(), &UpdateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc")
|
||||
var typed *cmdutil.Error
|
||||
require.True(t, errors.As(err, &typed))
|
||||
assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code)
|
||||
assert.Nil(t, svc.got, "must not call UpdateKnowledge when no flag is set")
|
||||
}
|
||||
|
||||
func TestDocUpdate_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeUpdateSvc{getErr: errors.New("HTTP error 404: not found")}
|
||||
err := runUpdate(context.Background(),
|
||||
&UpdateOptions{Title: strptr("x")}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsNotFound(err))
|
||||
}
|
||||
|
||||
// TestDocUpdate_DryRun_NoServerCall: --dry-run emits a doc.update plan (exit 0)
|
||||
// without reaching the server.
|
||||
func TestDocUpdate_DryRun_NoServerCall(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
root := withRootHarnessDoc(NewCmdUpdate(docDryRunFactory(t)), "doc_x", "--title", "T", "--dry-run", "--format", "json")
|
||||
require.NoError(t, root.Execute(), "dry-run must succeed without a client")
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Meta struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
Plan map[string]any `json:"plan"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "got %q", out.String())
|
||||
assert.True(t, env.Meta.DryRun)
|
||||
assert.Equal(t, "doc.update", env.Meta.Plan["action"])
|
||||
}
|
||||
|
||||
// TestDocUpdate_RequiresConfirmation asserts that without -y (non-TTY / JSON
|
||||
// mode), doc update returns input.confirmation_required (exit 10) — parity with
|
||||
// kb/agent update gating (AGENTS.md §3.1: all three updates are confirmation-gated).
|
||||
func TestDocUpdate_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t) // non-TTY
|
||||
f := &cmdutil.Factory{
|
||||
Client: func() (*sdk.Client, error) { return nil, nil },
|
||||
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
|
||||
}
|
||||
root := withRootHarnessDoc(NewCmdUpdate(f), "doc_abc", "--title", "New", "--format", "json")
|
||||
err := root.Execute()
|
||||
require.Error(t, err)
|
||||
var ce *cmdutil.Error
|
||||
require.ErrorAs(t, err, &ce)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err))
|
||||
// retry argv must include -y and the target id
|
||||
assert.Contains(t, ce.RetryArgv, "-y")
|
||||
assert.Contains(t, ce.RetryArgv, "doc_abc")
|
||||
}
|
||||
|
||||
// TestDocUpdate_DryRun_RejectsNoFlag: --dry-run rejects the no-mutation-flag
|
||||
// invocation identically to the live path (validation before the dry-run gate).
|
||||
func TestDocUpdate_DryRun_RejectsNoFlag(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
root := withRootHarnessDoc(NewCmdUpdate(docDryRunFactory(t)), "doc_x", "--dry-run", "--format", "json")
|
||||
err := root.Execute()
|
||||
require.Error(t, err, "dry-run must reject identically to live path")
|
||||
var typed *cmdutil.Error
|
||||
require.True(t, errors.As(err, &typed))
|
||||
assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code)
|
||||
}
|
||||
@@ -191,8 +191,12 @@ Server-side ingestion knobs:
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Upload a local file to the resolved knowledge base. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
|
||||
RequiredFlags: []string{"<file> (positional)"},
|
||||
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, file_name, parse_status",
|
||||
RequiredFlags: []string{"<file> (positional)", "--kb (or WEKNORA_KB_ID / project link)"},
|
||||
Examples: []string{
|
||||
`weknora doc upload report.pdf --kb kb_eng`,
|
||||
`weknora doc upload report.pdf --kb kb_eng --jq .data.id # then: doc wait <id>`,
|
||||
},
|
||||
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, file_name, parse_status",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user