diff --git a/cli/acceptance/testdata/wire/doctor.error_network.json b/cli/acceptance/testdata/wire/doctor.error_network.json index 57d7b920..6bf123f1 100644 --- a/cli/acceptance/testdata/wire/doctor.error_network.json +++ b/cli/acceptance/testdata/wire/doctor.error_network.json @@ -1 +1 @@ -{"ok":true,"data":{"summary":{"all_passed":false,"passed":1,"failed":1,"skipped":2},"checks":[{"name":"base_url_reachable","status":"fail","details":"server returned 500","hint":"verify the host configured for the active profile (run `weknora auth login --host=...`) and network reachability"},{"name":"auth_credential","status":"skip","details":"prereq failed: base_url_reachable"},{"name":"server_version","status":"skip","details":"prereq failed: auth_credential"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}} +{"ok":true,"data":{"summary":{"all_passed":false,"passed":1,"failed":1,"skipped":2},"checks":[{"name":"base_url_reachable","status":"fail","details":"server returned 500","hint":"verify the host configured for the active profile (run `weknora profile list` / `weknora profile add --host=...`) and network reachability"},{"name":"auth_credential","status":"skip","details":"prereq failed: base_url_reachable"},{"name":"server_version","status":"skip","details":"prereq failed: auth_credential"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}} diff --git a/cli/cmd/agent/check.go b/cli/cmd/agent/check.go index 7a25e7f9..7c708d17 100644 --- a/cli/cmd/agent/check.go +++ b/cli/cmd/agent/check.go @@ -68,6 +68,12 @@ the agent's downstream dependencies are all reachable.`, }, } cmdutil.AddFormatFlag(cmd, agentCheckFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "verify a custom agent end-to-end: status plus kb_scope reachability", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora agent check agent_abc"}, + Output: "envelope.data is {id, reachable, ...} with kb_scope reachability folded in", + }) return cmd } diff --git a/cli/cmd/agent/create.go b/cli/cmd/agent/create.go index d0cfdc13..8b485e2c 100644 --- a/cli/cmd/agent/create.go +++ b/cli/cmd/agent/create.go @@ -59,7 +59,7 @@ type createFlagSet struct { } const agentCreateExample = ` weknora agent create "Support Bot" --model - weknora agent create "Code Reviewer" --model --system-prompt-file ./prompt.md --kb kb_eng --kb kb_arch + weknora agent create "Code Reviewer" --model --system-prompt-file ./prompt.md --attach-kb kb_eng --attach-kb kb_arch weknora agent create "From Template" --model --from ag_existing weknora agent create --generate-skeleton > my-agent.yaml weknora agent create "Tuned" --model --config-file ./my-agent.yaml` @@ -76,7 +76,7 @@ Precedence when both a config file and hot-path flags are supplied: hot-path flag > config-file value > server default --from copies an existing agent (SDK CopyAgent) then applies any -hot-path overrides via UpdateAgent. --kb on --from REPLACES the copied +hot-path overrides via UpdateAgent. --attach-kb on --from REPLACES the copied agent's KB list (not merge) — matches surgical-flag semantics. AI agents: writes a new resource server-side. Failure surfaces as a @@ -112,7 +112,7 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { opts.flags.rerankModelSet = cmd.Flags().Changed("rerank-model") opts.flags.temperatureSet = cmd.Flags().Changed("temperature") opts.flags.kbSelectionModeSet = cmd.Flags().Changed("kb-selection-mode") - opts.flags.kbsSet = cmd.Flags().Changed("kb") + opts.flags.kbsSet = cmd.Flags().Changed("attach-kb") // --temperature is bounded 0.0..2.0. Reject out-of-range // early with a typed input.invalid_argument so users don't @@ -174,7 +174,7 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { cmd.Flags().StringVar(&systemPromptFile, "system-prompt-file", "", "Read system prompt from FILE, or '-' for stdin") cmd.MarkFlagsMutuallyExclusive("system-prompt", "system-prompt-file") cmd.Flags().StringVar(&opts.AgentMode, "agent-mode", "", "Agent operating mode: quick-answer | smart-reasoning") - cmd.Flags().StringSliceVar(&opts.KBs, "kb", nil, "Attach knowledge base id (repeatable)") + cmd.Flags().StringSliceVar(&opts.KBs, "attach-kb", nil, "Attach a knowledge base id (repeatable); aligns with 'agent edit --add-kb'") cmd.Flags().StringVar(&opts.KBSelectionMode, "kb-selection-mode", "", "KB selection mode: all | selected | none") cmd.Flags().StringVar(&opts.RerankModel, "rerank-model", "", "Rerank model id") cmd.Flags().Float64Var(&opts.Temperature, "temperature", 0.0, "Generation temperature (0.0..2.0)") @@ -186,6 +186,11 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { cmdutil.AddFormatFlag(cmd, agentViewFields...) cmdutil.AddDryRunFlag(cmd, &opts.DryRun) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Create a new custom agent. --model is required; --attach-kb takes KB ids (repeatable, not names). Emits the created Agent object.", + RequiredFlags: []string{" (positional)", "--model"}, + Output: "envelope.data is the created Agent object with id, name, config", + }) return cmd } @@ -230,7 +235,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp base = *copied.Config } - // --kb on --from REPLACES the copied KB list; when --kb + // --attach-kb on --from REPLACES the copied KB list; when --attach-kb // is not set, KnowledgeBasesSet stays false inside applyCreateOverrides // and the copy's KB list passes through unchanged. cfg := applyCreateOverrides(&base, opts) @@ -266,7 +271,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp } // applyCreateOverrides merges hot-path flag overrides into the base config, -// then applies the "--kb implies --kb-selection-mode=selected" fallback. +// then applies the "--attach-kb implies --kb-selection-mode=selected" fallback. // Shared by the --from path (base=copied agent's config) and the plain // create path (base=zero or --config-file). Keeping both paths on one // helper prevents silent divergence when future flags are added. @@ -282,7 +287,7 @@ func applyCreateOverrides(base *sdk.AgentConfig, opts *CreateOptions) *sdk.Agent } cfg := cmdutil.MergeAgentConfig(base, overrides) - // --kb without explicit --kb-selection-mode implies "selected". + // --attach-kb without explicit --kb-selection-mode implies "selected". if opts.flags.kbsSet && !opts.flags.kbSelectionModeSet && cfg.KBSelectionMode == "" { cfg.KBSelectionMode = "selected" } diff --git a/cli/cmd/agent/create_test.go b/cli/cmd/agent/create_test.go index 17dd6753..1f38c73a 100644 --- a/cli/cmd/agent/create_test.go +++ b/cli/cmd/agent/create_test.go @@ -132,7 +132,7 @@ func TestCreate_RepeatedKB_ImpliesSelectedMode(t *testing.T) { } require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)) assert.Equal(t, []string{"kb_a", "kb_b"}, svc.createReq.Config.KnowledgeBases) - assert.Equal(t, "selected", svc.createReq.Config.KBSelectionMode, "passing --kb implies selected mode") + assert.Equal(t, "selected", svc.createReq.Config.KBSelectionMode, "passing --attach-kb implies selected mode") } func TestCreate_SystemPromptFile_ReaderRead(t *testing.T) { @@ -176,14 +176,14 @@ func TestCreate_From_PreservesSourceFieldsNotOverridden(t *testing.T) { require.NotNil(t, svc.updateReq.Config) assert.Equal(t, "Source prompt", svc.updateReq.Config.SystemPrompt, "source SystemPrompt must round-trip") assert.Equal(t, "smart-reasoning", svc.updateReq.Config.AgentMode, "source AgentMode must round-trip") - assert.Equal(t, []string{"kb_src_a", "kb_src_b"}, svc.updateReq.Config.KnowledgeBases, "source KB list must round-trip when --kb not passed") + assert.Equal(t, []string{"kb_src_a", "kb_src_b"}, svc.updateReq.Config.KnowledgeBases, "source KB list must round-trip when --attach-kb not passed") assert.InDelta(t, 0.9, svc.updateReq.Config.Temperature, 0.001, "Temperature overridden") } func TestCreate_From_KBReplacesSourceList(t *testing.T) { - // --kb on --from REPLACES the copied agent's KB list (instead of + // --attach-kb on --from REPLACES the copied agent's KB list (instead of // merging with it). The override semantic matches a from-scratch - // `agent create --kb a --kb b`: whatever was on the source agent is + // `agent create --attach-kb a --attach-kb b`: whatever was on the source agent is // discarded for KBs the caller explicitly listed. _, _ = iostreams.SetForTest(t) svc := &fakeCreateSvc{ @@ -200,8 +200,8 @@ func TestCreate_From_KBReplacesSourceList(t *testing.T) { } require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)) require.NotNil(t, svc.updateReq.Config) - assert.Equal(t, []string{"kb_new"}, svc.updateReq.Config.KnowledgeBases, "--kb replaces source KB list") - assert.Equal(t, "selected", svc.updateReq.Config.KBSelectionMode, "--kb on --from implies selected mode") + assert.Equal(t, []string{"kb_new"}, svc.updateReq.Config.KnowledgeBases, "--attach-kb replaces source KB list") + assert.Equal(t, "selected", svc.updateReq.Config.KBSelectionMode, "--attach-kb on --from implies selected mode") } func TestCreate_Temperature_Bounds(t *testing.T) { @@ -235,3 +235,20 @@ var errBadHTTP404 = &simpleErr{msg: "HTTP error 404: not found"} type simpleErr struct{ msg string } func (e *simpleErr) Error() string { return e.msg } + +// --------------------------------------------------------------------------- +// --attach-kb (renamed from --kb) +// --------------------------------------------------------------------------- + +// TestCreate_AttachKBFlagExists asserts that `--attach-kb` is a registered flag +// on `agent create` and that the old `--kb` flag no longer exists. +func TestCreate_AttachKBFlagExists(t *testing.T) { + cmd := NewCmdCreate(nil) + // --attach-kb must exist + f := cmd.Flags().Lookup("attach-kb") + require.NotNil(t, f, "--attach-kb flag must be registered on 'agent create'") + // bare --kb must NOT exist (renamed) + old := cmd.Flags().Lookup("kb") + assert.Nil(t, old, "old --kb flag must not exist on 'agent create' (renamed to --attach-kb)") +} + diff --git a/cli/cmd/agent/delete.go b/cli/cmd/agent/delete.go index 4660c804..4f6f7cb2 100644 --- a/cli/cmd/agent/delete.go +++ b/cli/cmd/agent/delete.go @@ -106,7 +106,7 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command { } func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error { - if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "agent", opts.AgentID, "agent.delete", "weknora agent delete "+opts.AgentID+" -y"); err != nil { + if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "agent", opts.AgentID, "agent.delete", "weknora agent delete "+opts.AgentID+" -y"); err != nil { return err } if err := svc.DeleteAgent(ctx, opts.AgentID); err != nil { diff --git a/cli/cmd/agent/edit.go b/cli/cmd/agent/edit.go index 346ec835..323a24b1 100644 --- a/cli/cmd/agent/edit.go +++ b/cli/cmd/agent/edit.go @@ -209,7 +209,7 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command { yes, _ := cmd.Flags().GetBool("yes") // Build the retry command from the flags the user actually passed. retryCmd := buildAgentEditRetryCmd(cmd, opts.AgentID) - if err := cmdutil.ConfirmDestructive(f.Prompter(), yes, fopts.WantsJSON(), "agent", opts.AgentID, "agent.edit", retryCmd); err != nil { + if err := cmdutil.ConfirmDestructive(f.Prompter(), yes, fopts.WantsJSON(), "edit", "agent", opts.AgentID, "agent.edit", retryCmd); err != nil { return err } cli, err := f.Client() diff --git a/cli/cmd/agent/list.go b/cli/cmd/agent/list.go index 48c67573..19cbb649 100644 --- a/cli/cmd/agent/list.go +++ b/cli/cmd/agent/list.go @@ -60,6 +60,11 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)") cmdutil.AddFormatFlag(cmd, agentListFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "List custom agents visible to the active tenant. The SDK returns all agents in one call (no server-side pagination); meta.count reflects the full tenant set, --limit caps client-side.", + Examples: []string{"weknora agent list --format json", "weknora agent list --limit 10 --format json"}, + Output: "envelope.data is an array of Agent objects with id, name, is_builtin; meta.count is the total returned", + }) return cmd } diff --git a/cli/cmd/agent/status.go b/cli/cmd/agent/status.go index bdf38ee0..a76cdf24 100644 --- a/cli/cmd/agent/status.go +++ b/cli/cmd/agent/status.go @@ -65,6 +65,12 @@ For downstream KB reachability verification use 'weknora agent check ' }, } cmdutil.AddFormatFlag(cmd, agentStatusFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "shallow health probe of a custom agent: reachability without kb_scope verification", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora agent status agent_abc"}, + Output: "envelope.data is {id, reachable, ...}; use `agent check` for deep kb_scope verification", + }) return cmd } diff --git a/cli/cmd/agent/view.go b/cli/cmd/agent/view.go index d5a7b5bd..7edf2c56 100644 --- a/cli/cmd/agent/view.go +++ b/cli/cmd/agent/view.go @@ -64,6 +64,12 @@ Use --jq to project specific fields or reach into nested config.`, }, } cmdutil.AddFormatFlag(cmd, agentViewFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "fetch one custom agent's full configuration by id", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora agent view agent_abc"}, + Output: "envelope.data is the custom agent (id, name, description, is_builtin, and a nested config object holding model/kb_scope/...)", + }) return cmd } diff --git a/cli/cmd/api/api.go b/cli/cmd/api/api.go index f22535d3..d45336f5 100644 --- a/cli/cmd/api/api.go +++ b/cli/cmd/api/api.go @@ -114,7 +114,7 @@ Examples: // Escape-hatch DELETE through `weknora api` is just as destructive // as `weknora kb delete` - exit-10 protocol must apply (cli/README.md). if method == http.MethodDelete { - if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "endpoint", args[0], "api.delete", "weknora api -X DELETE "+args[0]+" -y"); err != nil { + if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "endpoint", args[0], "api.delete", "weknora api -X DELETE "+args[0]+" -y"); err != nil { return err } } @@ -141,7 +141,7 @@ Examples: }, Output: "raw server response body or envelope on error", Warnings: []string{ - "Note: -X DELETE/PUT/PATCH on existing resources may trigger exit 10 / input.confirmation_required at runtime; -X GET/POST are unguarded.", + "Only -X DELETE is confirmation-gated (exit 10 / input.confirmation_required unless -y); -X GET/POST/PUT/PATCH and other methods are unguarded — you own the safety of writes made through this escape hatch.", "Raw HTTP passthrough; agents should prefer typed subcommands (kb/doc/session/...) when available.", }, }) diff --git a/cli/cmd/chunk/delete.go b/cli/cmd/chunk/delete.go index ee2a211e..e1d333c7 100644 --- a/cli/cmd/chunk/delete.go +++ b/cli/cmd/chunk/delete.go @@ -101,7 +101,7 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command { opts.ChunkID = args[0] return runDelete(c.Context(), opts, fopts, cli, f.Prompter()) } - if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "chunk", len(args), "chunk.delete", "weknora chunk delete "+strings.Join(args, " ")+" --doc "+opts.DocID+" -y"); err != nil { + if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "chunk", len(args), "chunk.delete", "weknora chunk delete "+strings.Join(args, " ")+" --doc "+opts.DocID+" -y"); err != nil { return err } outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error { @@ -143,7 +143,7 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command { } func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error { - if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "chunk", opts.ChunkID, "chunk.delete", "weknora chunk delete "+opts.ChunkID+" --doc "+opts.DocID+" -y"); err != nil { + if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "chunk", opts.ChunkID, "chunk.delete", "weknora chunk delete "+opts.ChunkID+" --doc "+opts.DocID+" -y"); err != nil { return err } if err := svc.DeleteChunk(ctx, opts.DocID, opts.ChunkID); err != nil { diff --git a/cli/cmd/chunk/delete_test.go b/cli/cmd/chunk/delete_test.go index cce4fb76..8f246e8f 100644 --- a/cli/cmd/chunk/delete_test.go +++ b/cli/cmd/chunk/delete_test.go @@ -178,7 +178,7 @@ func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) { _, _ = iostreams.SetForTest(t) svc := &fakeMultiChunkDeleteSvc{} fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText} - err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "chunk", 2, "chunk.delete", "") + err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "delete", "chunk", 2, "chunk.delete", "") require.Error(t, err) var typed *cmdutil.Error require.ErrorAs(t, err, &typed) diff --git a/cli/cmd/chunk/list.go b/cli/cmd/chunk/list.go index a0e3076d..ee811085 100644 --- a/cli/cmd/chunk/list.go +++ b/cli/cmd/chunk/list.go @@ -104,6 +104,12 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd.Flags().IntVar(&opts.PageSize, "page-size", defaultPageSize, "Items per server batch (1..1000)") cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)") cmdutil.AddFormatFlag(cmd, chunkListFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "List chunks of a specific document in stored order (admin/debug). Results come with meta.count; use --limit (1..1000) and --all-pages to paginate. Prefer 'search chunks' for RAG retrieval.", + RequiredFlags: []string{"--doc"}, + Examples: []string{"weknora chunk list --doc doc_abc --format json", "weknora chunk list --doc doc_abc --all-pages --format json"}, + Output: "envelope.data is an array of Chunk objects with id, chunk_index, content, is_enabled; meta.count is the total returned", + }) return cmd } diff --git a/cli/cmd/chunk/view.go b/cli/cmd/chunk/view.go index 9c11d1da..e27212ef 100644 --- a/cli/cmd/chunk/view.go +++ b/cli/cmd/chunk/view.go @@ -81,6 +81,12 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command { }, } cmdutil.AddFormatFlag(cmd, chunkViewFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "fetch one chunk's fields and content by id (scope-less; no --doc needed)", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora chunk view chunk_abc"}, + Output: "envelope.data is the chunk object (id, content, knowledge_id, ...)", + }) return cmd } diff --git a/cli/cmd/doc/create.go b/cli/cmd/doc/create.go index aecffbc4..b6f5eda9 100644 --- a/cli/cmd/doc/create.go +++ b/cli/cmd/doc/create.go @@ -106,6 +106,11 @@ don't require a file upload or remote URL. KB resolution follows the standard _ = cmd.MarkFlagRequired("text") cmdutil.AddFormatFlag(cmd, docCreateFields...) 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", + }) return cmd } diff --git a/cli/cmd/doc/create_test.go b/cli/cmd/doc/create_test.go index 6579a17e..6c7e5ad2 100644 --- a/cli/cmd/doc/create_test.go +++ b/cli/cmd/doc/create_test.go @@ -1,6 +1,7 @@ package doc import ( + "bytes" "context" "encoding/json" "errors" @@ -138,3 +139,21 @@ func TestCreate_EmptyText_RejectsBeforeSDK(t *testing.T) { // Verify the SDK was NOT called. assert.Nil(t, svc.got.req, "SDK must not be called when --text is empty") } + +// TestCreate_AgentHelp_EmitsUsedFor verifies that when WEKNORA_AGENT_HELP=1 +// the `doc create --help` path emits a JSON blob containing "used_for". +// This is the representative test for 3.2; the mechanism is covered by +// internal/cmdutil/agenthelp_test.go — we test the wiring here. +func TestCreate_AgentHelp_EmitsUsedFor(t *testing.T) { + t.Setenv("WEKNORA_AGENT_HELP", "1") + _, _ = iostreams.SetForTest(t) + + f := &cmdutil.Factory{} + cmd := NewCmdCreate(f) + + var buf bytes.Buffer + cmd.SetOut(&buf) + cmd.HelpFunc()(cmd, nil) + + assert.Contains(t, buf.String(), `"used_for"`) +} diff --git a/cli/cmd/doc/delete.go b/cli/cmd/doc/delete.go index eb91aad7..86216589 100644 --- a/cli/cmd/doc/delete.go +++ b/cli/cmd/doc/delete.go @@ -94,7 +94,7 @@ without the user's explicit go-ahead.`, if opts.All { if opts.KB == "" { return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--all requires --kb="). - WithHint("specify --kb= to scope the delete-all operation"). + WithHint("specify --kb= to scope the delete-all operation"). WithRetryCommand("weknora doc delete --all --kb= -y") } if len(args) > 0 { @@ -122,13 +122,23 @@ without the user's explicit go-ahead.`, } if opts.All { + // Resolve KB name → id before the destructive SDK call. + // Must use cmdutil.ResolveKBFlag (id-or-name, lists KBs and + // matches by name) rather than Factory.ResolveKB, which walks + // the project link — a destructive "empty the KB" must never + // inherit an implicit linked KB. + kbID, err := cmdutil.ResolveKBFlag(c.Context(), cli, opts.KB) + if err != nil { + return err + } + opts.KB = kbID return runDeleteAll(c.Context(), opts, fopts, cli, f.Prompter()) } // 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]) } - if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "document", len(args), "doc.delete", "weknora doc delete "+strings.Join(args, " ")+" -y"); err != nil { + 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 { return err } outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error { @@ -149,13 +159,13 @@ without the user's explicit go-ahead.`, }, } 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)") + cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name (required with --all)") cmdutil.AddFormatFlag(cmd, docDeleteFields...) cmdutil.AddDryRunFlag(cmd, &opts.DryRun) cmdutil.SetRisk(cmd, "doc.delete") cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ UsedFor: "permanently delete one or more documents from a knowledge base", - RequiredFlags: []string{"... (positional) | --all --kb="}, + RequiredFlags: []string{"... (positional) | --all --kb="}, Examples: []string{ "weknora doc delete doc_abc -y", "weknora doc delete doc_a doc_b doc_c -y", @@ -171,7 +181,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(), "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", "weknora doc delete "+id+" -y"); err != nil { return err } @@ -191,7 +201,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(), "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", fmt.Sprintf("weknora doc delete --all --kb=%s -y", opts.KB)); err != nil { return err } diff --git a/cli/cmd/doc/delete_test.go b/cli/cmd/doc/delete_test.go index e9ac72d7..402b267a 100644 --- a/cli/cmd/doc/delete_test.go +++ b/cli/cmd/doc/delete_test.go @@ -6,6 +6,8 @@ import ( "encoding/json" "errors" "fmt" + "net/http" + "net/http/httptest" "testing" "github.com/stretchr/testify/assert" @@ -14,7 +16,9 @@ import ( sdk "github.com/Tencent/WeKnora/client" "github.com/Tencent/WeKnora/cli/internal/cmdutil" + "github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/iostreams" + "github.com/Tencent/WeKnora/cli/internal/prompt" "github.com/Tencent/WeKnora/cli/internal/testutil" ) @@ -258,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(), "document", 2, "doc.delete", "") + err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "delete", "document", 2, "doc.delete", "") require.Error(t, err) var typed *cmdutil.Error require.ErrorAs(t, err, &typed) @@ -270,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(), "document", 3, "doc.delete", "") + err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "delete", "document", 3, "doc.delete", "") require.Error(t, err) var typed *cmdutil.Error require.ErrorAs(t, err, &typed) @@ -527,3 +531,54 @@ func TestDocDelete_All_ServiceError(t *testing.T) { require.ErrorAs(t, err, &typed) assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code) } + +// --------------------------------------------------------------------------- +// KB name resolution tests (--all --kb resolves name → id) +// --------------------------------------------------------------------------- + +// TestDocDelete_All_ResolvesKBNameToID verifies that `doc delete --all --kb eng -y` +// resolves the KB name "eng" to its canonical id "kb_eng" before calling +// ClearKnowledgeBaseContents. Uses an httptest.Server to fake both the +// ListKnowledgeBases and ClearKnowledgeBaseContents endpoints so the real +// *sdk.Client can be injected through the factory (mirrors link_test.go pattern). +func TestDocDelete_All_ResolvesKBNameToID(t *testing.T) { + _, _ = iostreams.SetForTest(t) + + var clearCalledWith string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/knowledge-bases": + _ = json.NewEncoder(w).Encode(sdk.KnowledgeBaseListResponse{ + Success: true, + Data: []sdk.KnowledgeBase{{ID: "kb_eng", Name: "eng"}}, + }) + case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/knowledge-bases/kb_eng/knowledge": + clearCalledWith = "kb_eng" + _ = json.NewEncoder(w).Encode(map[string]any{ + "success": true, + "data": map[string]any{"deleted_count": 3}, + }) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + + cli := sdk.NewClient(srv.URL) + f := &cmdutil.Factory{ + Config: func() (*config.Config, error) { + return &config.Config{ + CurrentProfile: "default", + Profiles: map[string]config.Profile{"default": {Host: srv.URL}}, + }, nil + }, + Client: func() (*sdk.Client, error) { return cli, nil }, + Prompter: func() prompt.Prompter { return &testutil.ConfirmPrompter{Answer: true} }, + } + root := withRootHarnessDoc(NewCmdDelete(f), "--all", "--kb", "eng", "-y") + err := root.Execute() + require.NoError(t, err, "doc delete --all --kb eng -y should succeed") + assert.Equal(t, "kb_eng", clearCalledWith, + "ClearKnowledgeBaseContents must be called with resolved id 'kb_eng', not raw name 'eng'") +} diff --git a/cli/cmd/doc/download.go b/cli/cmd/doc/download.go index 3eea2a0d..ba627578 100644 --- a/cli/cmd/doc/download.go +++ b/cli/cmd/doc/download.go @@ -14,6 +14,18 @@ import ( "github.com/Tencent/WeKnora/cli/internal/iostreams" ) +// downloadFields enumerates the fields surfaced for `--format json` discovery on +// `doc download`. Matches the downloadResult struct. +var downloadFields = []string{"path", "bytes", "filename"} + +// downloadResult is the typed payload emitted as the success envelope when +// --format json is requested and output is going to a file (not stdout). +type downloadResult struct { + Path string `json:"path"` + Bytes int64 `json:"bytes"` + Filename string `json:"filename"` +} + type DownloadOptions struct { Output string // --output / -O: target path, "-" for stdout, "" for server-suggested filename Clobber bool // --clobber: allow overwrite of an existing file @@ -40,26 +52,43 @@ Default behavior (no --output): writes to the cwd under the filename the server suggests via Content-Disposition. If the server doesn't suggest one, the command errors and asks for --output FILE explicitly. -Existing files are NOT overwritten unless --clobber is passed.`, +Existing files are NOT overwritten unless --clobber is passed. + +With --format json, on success emits a JSON envelope whose data has +path, bytes, and filename fields. When output is stdout (--output -), +the JSON envelope is suppressed because the raw bytes already occupy +stdout.`, Example: ` weknora doc download doc_abc # writes ./ weknora doc download doc_abc -O report.pdf weknora doc download doc_abc --output - # stream to stdout (binary safe) - weknora doc download doc_abc -O report.pdf --clobber`, + weknora doc download doc_abc -O report.pdf --clobber + weknora doc download doc_abc -O report.pdf --format json # JSON envelope`, Args: cobra.ExactArgs(1), RunE: func(c *cobra.Command, args []string) error { + fopts, err := cmdutil.CheckFormatFlag(c) + if err != nil { + return err + } + fopts.ResolveDefault(iostreams.IO.IsStdoutTTY()) cli, err := f.Client() if err != nil { return err } - return runDownload(c.Context(), opts, cli, args[0]) + return runDownload(c.Context(), opts, fopts, cli, args[0]) }, } cmd.Flags().StringVarP(&opts.Output, "output", "O", "", `Output path; "-" for stdout. Defaults to the server-suggested filename.`) cmd.Flags().BoolVar(&opts.Clobber, "clobber", false, "Overwrite the output file if it already exists") + cmdutil.AddFormatFlag(cmd, downloadFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Download a document's bytes by id. Writes a file (or stdout with --output -).", + RequiredFlags: []string{" (positional)"}, + Output: "with --format json (file output): envelope.data has path, bytes, filename; suppressed with --output - (raw bytes to stdout)", + }) return cmd } -func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService, id string) error { +func runDownload(ctx context.Context, opts *DownloadOptions, fopts *cmdutil.FormatOptions, svc DownloadService, id string) error { suggested, body, err := svc.OpenKnowledgeFile(ctx, id) if err != nil { return cmdutil.WrapHTTP(err, "download %s", id) @@ -71,13 +100,15 @@ func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService return err } if dest == "-" { + // Raw bytes go to stdout — suppress any JSON envelope regardless of + // --format json because both can't occupy stdout simultaneously. _, err := io.Copy(iostreams.IO.Out, body) return err } if err := refuseIfExists(dest, opts.Clobber); err != nil { return err } - return streamToFile(body, dest) + return streamToFile(body, dest, fopts) } // resolveDownloadDest returns the final destination ("-" for stdout, an @@ -133,20 +164,32 @@ func refuseIfExists(path string, clobber bool) error { // streamToFile copies body into a newly-created file at path. On any // streaming error the partial file is removed so callers don't see a // truncated artifact at the user-visible path. -func streamToFile(body io.Reader, path string) error { +// +// On success: if fopts.WantsJSON(), emits a downloadResult envelope to +// stdout instead of the "✓ Saved" text. +func streamToFile(body io.Reader, path string, fopts *cmdutil.FormatOptions) error { f, err := os.Create(path) if err != nil { return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "create %s", path) } - if _, err := io.Copy(f, body); err != nil { + n, copyErr := io.Copy(f, body) + if copyErr != nil { _ = f.Close() _ = os.Remove(path) - return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write %s", path) + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, copyErr, "write %s", path) } if err := f.Close(); err != nil { _ = os.Remove(path) return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "close %s", path) } + + if fopts.WantsJSON() { + return fopts.Emit(iostreams.IO.Out, downloadResult{ + Path: path, + Bytes: n, + Filename: filepath.Base(path), + }, nil) + } fmt.Fprintf(iostreams.IO.Err, "✓ Saved %s\n", path) return nil } diff --git a/cli/cmd/doc/download_test.go b/cli/cmd/doc/download_test.go index 6a2d1f54..e8627366 100644 --- a/cli/cmd/doc/download_test.go +++ b/cli/cmd/doc/download_test.go @@ -2,6 +2,7 @@ package doc import ( "context" + "encoding/json" "errors" "io" "os" @@ -34,6 +35,10 @@ func (f *fakeDownloadSvc) OpenKnowledgeFile(_ context.Context, id string) (strin return f.filename, io.NopCloser(strings.NewReader(f.content)), nil } +// textFopts returns a text-mode FormatOptions for tests that don't care +// about JSON output. +func textFopts() *cmdutil.FormatOptions { return &cmdutil.FormatOptions{Mode: cmdutil.FormatText} } + func TestDownload_DefaultUsesServerFilename(t *testing.T) { _, _ = iostreams.SetForTest(t) tmp := t.TempDir() @@ -42,7 +47,7 @@ func TestDownload_DefaultUsesServerFilename(t *testing.T) { defer os.Chdir(prevWD) svc := &fakeDownloadSvc{content: "PDF-1.4 bytes", filename: "report.pdf"} - require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc")) + require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, textFopts(), svc, "doc_abc")) got, err := os.ReadFile(filepath.Join(tmp, "report.pdf")) require.NoError(t, err) @@ -53,7 +58,7 @@ func TestDownload_OutFile(t *testing.T) { _, _ = iostreams.SetForTest(t) dest := filepath.Join(t.TempDir(), "out.bin") svc := &fakeDownloadSvc{content: "hello", filename: "ignored.txt"} - require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest}, svc, "doc_abc")) + require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest}, textFopts(), svc, "doc_abc")) got, err := os.ReadFile(dest) require.NoError(t, err) @@ -63,14 +68,14 @@ func TestDownload_OutFile(t *testing.T) { func TestDownload_OutDash_Stdout(t *testing.T) { out, _ := iostreams.SetForTest(t) svc := &fakeDownloadSvc{content: "binary payload", filename: "report.pdf"} - require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: "-"}, svc, "doc_abc")) + require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: "-"}, textFopts(), svc, "doc_abc")) assert.Equal(t, "binary payload", out.String()) } func TestDownload_NoFilenameFromServer_DefaultPath_Errors(t *testing.T) { _, _ = iostreams.SetForTest(t) svc := &fakeDownloadSvc{content: "x", filename: ""} - err := runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc") + err := runDownload(context.Background(), &DownloadOptions{}, textFopts(), svc, "doc_abc") require.Error(t, err) var typed *cmdutil.Error require.ErrorAs(t, err, &typed) @@ -81,7 +86,7 @@ func TestDownload_NoFilenameFromServer_DefaultPath_Errors(t *testing.T) { func TestDownload_NotFound(t *testing.T) { _, _ = iostreams.SetForTest(t) svc := &fakeDownloadSvc{err: errors.New("HTTP error 404: not found")} - err := runDownload(context.Background(), &DownloadOptions{Output: filepath.Join(t.TempDir(), "x")}, svc, "doc_missing") + err := runDownload(context.Background(), &DownloadOptions{Output: filepath.Join(t.TempDir(), "x")}, textFopts(), svc, "doc_missing") require.Error(t, err) var typed *cmdutil.Error require.ErrorAs(t, err, &typed) @@ -94,7 +99,7 @@ func TestDownload_RefusesOverwrite(t *testing.T) { require.NoError(t, os.WriteFile(dest, []byte("OLD"), 0o644)) svc := &fakeDownloadSvc{content: "NEW", filename: ""} - err := runDownload(context.Background(), &DownloadOptions{Output: dest}, svc, "doc_abc") + err := runDownload(context.Background(), &DownloadOptions{Output: dest}, textFopts(), svc, "doc_abc") require.Error(t, err) var typed *cmdutil.Error require.ErrorAs(t, err, &typed) @@ -116,7 +121,7 @@ func TestDownload_RejectsServerPathTraversal(t *testing.T) { // The server sends "../../etc/shadow" - we accept only "shadow" and // write to cwd. svc := &fakeDownloadSvc{content: "exfil", filename: "../../etc/shadow"} - require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc")) + require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, textFopts(), svc, "doc_abc")) // File must land inside cwd; parent dirs untouched. got, err := os.ReadFile(filepath.Join(tmp, "shadow")) @@ -145,7 +150,52 @@ func TestDownload_ForceOverwrites(t *testing.T) { require.NoError(t, os.WriteFile(dest, []byte("OLD"), 0o644)) svc := &fakeDownloadSvc{content: "NEW", filename: ""} - require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest, Clobber: true}, svc, "doc_abc")) + require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest, Clobber: true}, textFopts(), svc, "doc_abc")) got, _ := os.ReadFile(dest) assert.Equal(t, "NEW", string(got)) } + +// TestDownload_JSONEnvelope verifies that --format json emits a success +// envelope with path/bytes/filename when downloading to a temp file. +func TestDownload_JSONEnvelope(t *testing.T) { + out, _ := iostreams.SetForTest(t) + dest := filepath.Join(t.TempDir(), "report.pdf") + svc := &fakeDownloadSvc{content: "PDF bytes here", filename: "report.pdf"} + fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON} + + require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest}, fopts, svc, "doc_abc")) + + // File content must still be written correctly. + got, err := os.ReadFile(dest) + require.NoError(t, err) + assert.Equal(t, "PDF bytes here", string(got)) + + // stdout must contain the JSON envelope. + var env struct { + OK bool `json:"ok"` + Data struct { + Path string `json:"path"` + Bytes int64 `json:"bytes"` + Filename string `json:"filename"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal([]byte(out.String()), &env), "expected valid JSON envelope, got %q", out.String()) + assert.True(t, env.OK) + assert.Equal(t, dest, env.Data.Path) + assert.Equal(t, int64(len("PDF bytes here")), env.Data.Bytes) + assert.Equal(t, "report.pdf", env.Data.Filename) +} + +// TestDownload_JSONEnvelope_SuppressedOnStdout verifies that when output is +// stdout (--output -), the JSON envelope is NOT emitted even with --format json +// because raw bytes already occupy stdout. +func TestDownload_JSONEnvelope_SuppressedOnStdout(t *testing.T) { + out, _ := iostreams.SetForTest(t) + svc := &fakeDownloadSvc{content: "binary payload", filename: "report.pdf"} + fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON} + + require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: "-"}, fopts, svc, "doc_abc")) + + // stdout must contain only the raw bytes, not a JSON envelope. + assert.Equal(t, "binary payload", out.String()) +} diff --git a/cli/cmd/doc/fetch.go b/cli/cmd/doc/fetch.go index 28ede79d..0ef5ae8c 100644 --- a/cli/cmd/doc/fetch.go +++ b/cli/cmd/doc/fetch.go @@ -134,6 +134,11 @@ Server-side ingestion knobs: cmd.Flags().Lookup("enable-multimodel").NoOptDefVal = "true" cmdutil.AddFormatFlag(cmd, docFetchFields...) 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{" (positional)"}, + Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, source, parse_status", + }) return cmd } diff --git a/cli/cmd/doc/list.go b/cli/cmd/doc/list.go index 167bec83..327bd0d0 100644 --- a/cli/cmd/doc/list.go +++ b/cli/cmd/doc/list.go @@ -111,6 +111,11 @@ backend storage order is not guaranteed and varies between deployments.`, cmd.Flags().StringVar(&opts.StartTime, "start-time", "", "Include docs with updated_at >= this RFC3339 timestamp (e.g. 2006-01-02T15:04:05Z)") cmd.Flags().StringVar(&opts.EndTime, "end-time", "", "Include docs with updated_at <= this RFC3339 timestamp (e.g. 2006-01-02T15:04:05Z)") cmdutil.AddFormatFlag(cmd, docListFields...) + 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", + }) return cmd } diff --git a/cli/cmd/doc/upload.go b/cli/cmd/doc/upload.go index 448e7825..822dea82 100644 --- a/cli/cmd/doc/upload.go +++ b/cli/cmd/doc/upload.go @@ -188,6 +188,11 @@ Server-side ingestion knobs: cmd.Flags().StringVar(&opts.Channel, "channel", "", "Ingestion-channel tag recorded server-side (default \"api\")") cmdutil.AddFormatFlag(cmd, docUploadFields...) 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{" (positional)"}, + Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, file_name, parse_status", + }) return cmd } diff --git a/cli/cmd/doc/view.go b/cli/cmd/doc/view.go index d9fa15dc..9f3a9d32 100644 --- a/cli/cmd/doc/view.go +++ b/cli/cmd/doc/view.go @@ -52,6 +52,12 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command { }, } cmdutil.AddFormatFlag(cmd, docViewFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "fetch one document's metadata by id", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora doc view doc_abc", "weknora doc view doc_abc --jq .data.parse_status"}, + Output: "envelope.data is the document object (id, file_name, parse_status, ...)", + }) return cmd } diff --git a/cli/cmd/doc/wait.go b/cli/cmd/doc/wait.go index 92460da4..0933984d 100644 --- a/cli/cmd/doc/wait.go +++ b/cli/cmd/doc/wait.go @@ -74,13 +74,19 @@ For fail-fast semantics, use shell composition: return err } + // The partition (completed/failed/timeout) is already on stdout via + // emitWaitResult. On aggregate failure we still need a non-zero exit, + // but the error is Silent so PrintError does NOT write a second, + // contradictory {ok:false} envelope to stderr — the agent reads the + // failure detail from the stdout partition + the exit code (1/124). + // Same contract as cmdutil.RunBatch. switch res.ExitCode() { case 0: return nil case 1: - return cmdutil.NewError(cmdutil.CodeOperationFailed, fmt.Sprintf("%d doc(s) failed", len(res.Failed))) + return cmdutil.NewError(cmdutil.CodeOperationFailed, fmt.Sprintf("%d doc(s) failed", len(res.Failed))).WithSilent() case 124: - return cmdutil.NewError(cmdutil.CodeOperationTimeout, fmt.Sprintf("wait timed out (%d doc(s) still pending)", len(res.Timeout))) + return cmdutil.NewError(cmdutil.CodeOperationTimeout, fmt.Sprintf("wait timed out (%d doc(s) still pending)", len(res.Timeout))).WithSilent() } return nil }, @@ -88,6 +94,19 @@ For fail-fast semantics, use shell composition: cmd.Flags().DurationVar(&opts.Timeout, "timeout", 10*time.Minute, "Max wait time before exiting 124") cmd.Flags().DurationVar(&opts.Interval, "interval", 2*time.Second, "Initial poll interval; exponential backoff capped at 15s + jitter") cmdutil.AddFormatFlag(cmd) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "block until one or more documents reach a terminal parse state (completed or failed), or --timeout elapses", + RequiredFlags: []string{"... (one or more positionals)"}, + Examples: []string{ + "weknora doc wait doc_abc", + "weknora doc wait doc_a doc_b --timeout 5m", + }, + Output: "envelope.data is {completed:[], failed:[{id,message}], timeout:[]}", + Warnings: []string{ + "exit code carries the aggregate result: 0 all completed, 1 any failed, 124 timeout", + "ok:true means the wait ran to a terminal state — NOT that every doc succeeded; branch on the exit code or inspect data.failed", + }, + }) return cmd } @@ -146,7 +165,9 @@ func waitForDocs(ctx context.Context, ids []string, svc WaitService, opts WaitOp ctx, cancel := context.WithTimeout(ctx, opts.Timeout) defer cancel() - result := &WaitResult{} + // Completed is non-omitempty (always present in the partition), so start it + // as an empty slice rather than nil — agents see `"completed":[]`, not null. + result := &WaitResult{Completed: []string{}} var mu sync.Mutex addCompleted := func(id string) { mu.Lock() diff --git a/cli/cmd/doc/wait_test.go b/cli/cmd/doc/wait_test.go index ed00167c..b0cf8b4d 100644 --- a/cli/cmd/doc/wait_test.go +++ b/cli/cmd/doc/wait_test.go @@ -291,3 +291,23 @@ func TestWaitResult_ExitCode(t *testing.T) { }) } } + +// On aggregate failure, doc wait emits the partition envelope to stdout; the +// returned error must be Silent so PrintError does NOT write a second, +// contradictory {ok:false} envelope to stderr. Regression for the dual-envelope +// contract violation (stdout ok:true + stderr ok:false for one invocation). +func TestDocWait_FailureError_IsSilent(t *testing.T) { + // Mirror RunBatch's contract: the failure carries CodeOperationFailed for + // the exit code, but Silent=true suppresses the stderr envelope. + err := cmdutil.NewError(cmdutil.CodeOperationFailed, "1 doc(s) failed").WithSilent() + typed := cmdutil.AsError(err) + if typed == nil { + t.Fatal("expected typed *Error") + } + if !typed.Silent { + t.Error("doc wait failure error must be Silent to avoid a contradictory stderr envelope") + } + if cmdutil.ExitCode(err) != 1 { + t.Errorf("exit code = %d, want 1", cmdutil.ExitCode(err)) + } +} diff --git a/cli/cmd/doctor/doctor.go b/cli/cmd/doctor/doctor.go index 4f0d0d94..75a4c27f 100644 --- a/cli/cmd/doctor/doctor.go +++ b/cli/cmd/doctor/doctor.go @@ -125,6 +125,15 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache (located at $XDG_CACHE_HOME/weknora/server-info.yaml); force re-probe") cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage (credential_storage check still runs)") cmdutil.AddFormatFlag(cmd, doctorFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "run self-checks: base-url reachability, auth credential, server version, credential storage", + Examples: []string{ + "weknora doctor", + "weknora doctor --offline", + "weknora doctor --no-cache --format json", + }, + Output: "envelope.data is {summary:{all_passed,passed,failed,skipped}, checks:[{name,status,detail}]}", + }) return cmd } @@ -164,7 +173,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string) t0 := time.Now() if err := svc.PingBaseURL(ctx); err != nil { checks[0].Status = StatusFail - checks[0].Hint = "verify the host configured for the active profile (run `weknora auth login --host=...`) and network reachability" + checks[0].Hint = "verify the host configured for the active profile (run `weknora profile list` / `weknora profile add --host=...`) and network reachability" checks[0].Details = err.Error() } else { checks[0].Status = StatusOK diff --git a/cli/cmd/doctor/doctor_test.go b/cli/cmd/doctor/doctor_test.go index 71de862b..b1db3196 100644 --- a/cli/cmd/doctor/doctor_test.go +++ b/cli/cmd/doctor/doctor_test.go @@ -98,8 +98,8 @@ func TestDoctor_BaseURLFails_DownstreamSkip(t *testing.T) { if r.Checks[0].Status != StatusFail { t.Errorf("base_url_reachable status = %q, want fail", r.Checks[0].Status) } - if !strings.Contains(r.Checks[0].Hint, "auth login") { - t.Errorf("base_url fail hint should reference `auth login`, got %q", r.Checks[0].Hint) + if !strings.Contains(r.Checks[0].Hint, "profile") { + t.Errorf("base_url fail hint should reference the active profile's host config, got %q", r.Checks[0].Hint) } if r.Checks[1].Status != StatusSkip { t.Errorf("auth_credential status = %q, want skip", r.Checks[1].Status) diff --git a/cli/cmd/kb/check.go b/cli/cmd/kb/check.go index a382824d..a88a8946 100644 --- a/cli/cmd/kb/check.go +++ b/cli/cmd/kb/check.go @@ -72,6 +72,12 @@ verification including failed-doc aggregation.`, }, } cmdutil.AddFormatFlag(cmd, kbCheckFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "verify a knowledge base end-to-end: status plus failed-doc aggregation", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora kb check kb_abc"}, + Output: "envelope.data is {id, reachable, failed_count, ...}; deeper than `kb status`", + }) return cmd } diff --git a/cli/cmd/kb/create.go b/cli/cmd/kb/create.go index def0290c..6521d84d 100644 --- a/cli/cmd/kb/create.go +++ b/cli/cmd/kb/create.go @@ -92,6 +92,11 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { "Storage provider for documents in this KB: "+strings.Join(storageProviderValues, " | ")+" (optional; server default when unset)") cmdutil.AddFormatFlag(cmd, kbCreateFields...) cmdutil.AddDryRunFlag(cmd, &opts.DryRun) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Create a new knowledge base with the given name. Emits the created KB object with its id.", + RequiredFlags: []string{" (positional)"}, + Output: "envelope.data is the created KnowledgeBase object with id, name, type, embedding_model_id", + }) return cmd } diff --git a/cli/cmd/kb/delete.go b/cli/cmd/kb/delete.go index 6e682b56..89ca2e5f 100644 --- a/cli/cmd/kb/delete.go +++ b/cli/cmd/kb/delete.go @@ -94,7 +94,7 @@ exactly to guard against unintended deletes.`, } func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error { - if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "knowledge base", id, "kb.delete", "weknora kb delete "+id+" -y"); err != nil { + if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "knowledge base", id, "kb.delete", "weknora kb delete "+id+" -y"); err != nil { return err } diff --git a/cli/cmd/kb/edit.go b/cli/cmd/kb/edit.go index 923b515c..876e846b 100644 --- a/cli/cmd/kb/edit.go +++ b/cli/cmd/kb/edit.go @@ -109,7 +109,7 @@ to the user first.`, // Build a retry command from the flags the user actually passed so // agents can re-invoke with -y after explicit human approval. retryCmd := buildKBEditRetryCmd(c, id) - if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "knowledge base", id, "kb.edit", retryCmd); err != nil { + if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "edit", "knowledge base", id, "kb.edit", retryCmd); err != nil { return err } return runEdit(c.Context(), opts, fopts, cli, id) diff --git a/cli/cmd/kb/pin.go b/cli/cmd/kb/pin.go index 23d9a9e6..89cbfc89 100644 --- a/cli/cmd/kb/pin.go +++ b/cli/cmd/kb/pin.go @@ -16,7 +16,9 @@ import ( // relevant fields here are the id and the new pin state. var kbPinFields = []string{"id", "is_pinned"} -type PinOptions struct{} +type PinOptions struct { + DryRun bool +} // PinService is the narrow SDK surface this command depends on. The CLI // reads current state before toggling so `pin`/`unpin` are idempotent - @@ -49,6 +51,16 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C return err } fopts.ResolveDefault(iostreams.IO.IsStdoutTTY()) + action := "kb.pin" + if !want { + action = "kb.unpin" + } + if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{ + Action: action, + Args: map[string]any{"kb": args[0]}, + }); handled { + return err + } cli, err := f.Client() if err != nil { return err @@ -57,6 +69,13 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C }, } cmdutil.AddFormatFlag(cmd, kbPinFields...) + cmdutil.AddDryRunFlag(cmd, &opts.DryRun) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: use + " a knowledge base (idempotent: a no-op if it is already in the target state)", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora " + use + " kb_abc"}, + Output: "envelope.data is the KnowledgeBase with is_pinned reflecting the new state", + }) return cmd } diff --git a/cli/cmd/kb/pin_test.go b/cli/cmd/kb/pin_test.go index d8a193db..f640ddf6 100644 --- a/cli/cmd/kb/pin_test.go +++ b/cli/cmd/kb/pin_test.go @@ -2,9 +2,11 @@ package kb import ( "context" + "encoding/json" "errors" "testing" + "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -104,3 +106,33 @@ func TestPin_JSON(t *testing.T) { assert.Contains(t, body, `"is_pinned":true`) assert.Contains(t, body, `"id":"kb_abc"`) } + +// TestPin_DryRun_NoServerCall: --dry-run must emit a kb.pin plan (exit 0) +// without reaching the server, so pin/unpin honor the same mutation-preview +// contract as create/edit/delete. Regression for pin/unpin lacking --dry-run. +func TestPin_DryRun_NoServerCall(t *testing.T) { + for _, tc := range []struct { + name, want string + cmd func(*cmdutil.Factory) *cobra.Command + }{ + {"pin", "kb.pin", NewCmdPin}, + {"unpin", "kb.unpin", NewCmdUnpin}, + } { + t.Run(tc.name, func(t *testing.T) { + out, _ := iostreams.SetForTest(t) + root := withRootHarness(tc.cmd(kbDryRunFactory(t)), "kb_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, tc.want, env.Meta.Plan["action"]) + }) + } +} diff --git a/cli/cmd/kb/status.go b/cli/cmd/kb/status.go index 9de9ce62..760e470d 100644 --- a/cli/cmd/kb/status.go +++ b/cli/cmd/kb/status.go @@ -69,6 +69,12 @@ For full metadata (config / pinned / tenant), use 'weknora kb view '.`, }, } cmdutil.AddFormatFlag(cmd, kbStatusFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "shallow health probe of a knowledge base (one HTTP call): reachability, no failed-doc aggregation", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora kb status kb_abc"}, + Output: "envelope.data is {id, reachable, ...}; use `kb check` for deep failed-doc aggregation", + }) return cmd } diff --git a/cli/cmd/kb/view.go b/cli/cmd/kb/view.go index c1351a7f..f2075ea0 100644 --- a/cli/cmd/kb/view.go +++ b/cli/cmd/kb/view.go @@ -53,6 +53,15 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command { }, } cmdutil.AddFormatFlag(cmd, kbViewFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "fetch one knowledge base's full configuration by id", + RequiredFlags: []string{" (positional)"}, + Examples: []string{ + "weknora kb view kb_abc", + "weknora kb view kb_abc --jq .data.embedding_model_id", + }, + Output: "envelope.data is the KnowledgeBase object (id, name, type, embedding/summary model ids, chunk_count, ...)", + }) return cmd } diff --git a/cli/cmd/link/link.go b/cli/cmd/link/link.go index a4ac4d85..98f78bde 100644 --- a/cli/cmd/link/link.go +++ b/cli/cmd/link/link.go @@ -87,6 +87,11 @@ user explicitly asked to bind this directory; don't run it as a side effect.`, cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name; omit on a TTY for interactive prompt") cmdutil.AddFormatFlag(cmd, linkFields...) cmdutil.AddDryRunFlag(cmd, &opts.DryRun) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Bind the current directory to a knowledge base by writing .weknora/project.yaml. Requires --kb (non-interactive); only run when the user explicitly asks to link this directory.", + RequiredFlags: []string{"--kb (required when no TTY)"}, + Output: "envelope.data has kb_id, kb_name, project_link_path", + }) return cmd } diff --git a/cli/cmd/link/unlink.go b/cli/cmd/link/unlink.go index b614bab0..4c8f9d57 100644 --- a/cli/cmd/link/unlink.go +++ b/cli/cmd/link/unlink.go @@ -76,6 +76,10 @@ is present anywhere in the parent chain.`, } cmdutil.AddFormatFlag(cmd, unlinkFields...) cmdutil.AddDryRunFlag(cmd, &opts.DryRun) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Remove the .weknora/project.yaml KB binding from the current directory tree. No flags required; walks up from cwd to find the link.", + Output: "envelope.data has project_link_path of the removed file", + }) return cmd } diff --git a/cli/cmd/search/chunks.go b/cli/cmd/search/chunks.go index fe74d929..22a42f43 100644 --- a/cli/cmd/search/chunks.go +++ b/cli/cmd/search/chunks.go @@ -84,6 +84,12 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command { } bindChunksFlags(cmd, opts) _ = cmd.MarkFlagRequired("kb") + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Hybrid (vector + keyword) chunk retrieval against a knowledge base. Results come with meta.count; use --limit to cap (default 8, tuned for RAG context). Pass --no-vector or --no-keyword to disable one channel.", + RequiredFlags: []string{" (positional)", "--kb"}, + Examples: []string{`weknora search chunks "what is RAG?" --kb engineering --format json`}, + Output: "envelope.data is an array of SearchResult objects with id, content, score, knowledge_id; meta.count is the returned count; meta.has_more=true if more matched than --limit", + }) return cmd } @@ -138,7 +144,8 @@ func runChunks(ctx context.Context, opts *ChunksOptions, fopts *cmdutil.FormatOp // a hard return-count cap by trimming on the client. Recall isn't // affected because the server's internal retrieval pool is already // max(MatchCount*5, 50). - if opts.Limit > 0 && len(results) > opts.Limit { + truncated := opts.Limit > 0 && len(results) > opts.Limit + if truncated { results = results[:opts.Limit] } @@ -146,7 +153,7 @@ func runChunks(ctx context.Context, opts *ChunksOptions, fopts *cmdutil.FormatOp if results == nil { results = []*sdk.SearchResult{} } - meta := &output.Meta{Count: len(results)} + meta := &output.Meta{Count: len(results), HasMore: truncated} return fopts.Emit(iostreams.IO.Out, results, meta) } return renderChunkResults(results, opts.KBID) diff --git a/cli/cmd/search/chunks_test.go b/cli/cmd/search/chunks_test.go index c9209177..cf5c01ed 100644 --- a/cli/cmd/search/chunks_test.go +++ b/cli/cmd/search/chunks_test.go @@ -137,6 +137,23 @@ func TestRunSearch_NilService(t *testing.T) { assert.Contains(t, err.Error(), "server.error") } +// TestNewCmdChunks_RequiresKB asserts that running `search chunks ""` +// without --kb returns an error containing `required flag(s) "kb"`. +// This locks the behavior so a later refactor cannot silently introduce a +// project-link fallback for this destructive-free read path. +func TestNewCmdChunks_RequiresKB(t *testing.T) { + iostreams.SetForTest(t) + cmd := NewCmdChunks(&cmdutil.Factory{ + Client: func() (*sdk.Client, error) { return nil, nil }, + }) + cmd.SetArgs([]string{"some query"}) // query but no --kb + cmd.SilenceErrors = true + cmd.SilenceUsage = true + err := cmd.Execute() + require.Error(t, err) + assert.Contains(t, err.Error(), `required flag(s) "kb"`) +} + func TestNewCmdChunks_RequiresQuery(t *testing.T) { iostreams.SetForTest(t) cmd := NewCmdChunks(&cmdutil.Factory{ diff --git a/cli/cmd/search/docs.go b/cli/cmd/search/docs.go index 121912d8..f7b49948 100644 --- a/cli/cmd/search/docs.go +++ b/cli/cmd/search/docs.go @@ -115,6 +115,12 @@ reached or the KB is exhausted. Pass --all-pages=false to stop after one page.`, cmd.Flags().BoolVar(&opts.AllPages, "all-pages", true, "Walk every server page until exhausted or --limit hit") cmdutil.AddFormatFlag(cmd, docsFields...) _ = cmd.MarkFlagRequired("kb") + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Find documents in a knowledge base by keyword (server-side LIKE filter on title/file_name). Results come with meta.count; use --limit to cap and --all-pages=false to stop after one page.", + RequiredFlags: []string{" (positional)", "--kb"}, + Examples: []string{`weknora search docs "spec" --kb engineering --format json`}, + Output: "envelope.data is an array of Knowledge objects with id, title, file_name, parse_status; meta.count is the returned count; meta.has_more=true if more matched than --limit", + }) return cmd } @@ -139,7 +145,8 @@ func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, fopts *cmdutil. } for _, k := range items { matches = append(matches, k) - if opts.Limit > 0 && len(matches) >= opts.Limit { + // Collect one past --limit so has_more is accurate; trimmed below. + if opts.Limit > 0 && len(matches) > opts.Limit { goto done } } @@ -152,12 +159,16 @@ func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, fopts *cmdutil. } done: sortKnowledgeByRecency(matches) + truncated := opts.Limit > 0 && len(matches) > opts.Limit + if truncated { + matches = matches[:opts.Limit] + } if fopts.WantsJSON() { if matches == nil { matches = []sdk.Knowledge{} } - meta := &output.Meta{Count: len(matches)} + meta := &output.Meta{Count: len(matches), HasMore: truncated} return fopts.Emit(iostreams.IO.Out, matches, meta) } if len(matches) == 0 { diff --git a/cli/cmd/search/docs_test.go b/cli/cmd/search/docs_test.go index 234eb623..78e49f5b 100644 --- a/cli/cmd/search/docs_test.go +++ b/cli/cmd/search/docs_test.go @@ -193,3 +193,47 @@ func mustTime(t *testing.T, s string) time.Time { require.NoError(t, err) return v } + +// TestDocsSearch_HasMore asserts the meta.has_more truncation signal: true when +// more matches than --limit exist (over-fetch detects it, data trimmed to +// --limit), absent/false when the full result set fits. Mirrors the list +// commands' contract so an agent can tell its search was capped. +func TestDocsSearch_HasMore(t *testing.T) { + page := make([]sdk.Knowledge, 10) + for i := range page { + page[i] = sdk.Knowledge{ID: "match", Title: "needle"} + } + type meta struct { + Count int `json:"count"` + HasMore bool `json:"has_more"` + } + parse := func(t *testing.T, s string) meta { + var env struct { + Meta meta `json:"meta"` + } + require.NoError(t, json.Unmarshal([]byte(s), &env), "got %q", s) + return env.Meta + } + + t.Run("truncated -> has_more true, data trimmed", func(t *testing.T) { + out, _ := iostreams.SetForTest(t) + svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page}, total: 10} + require.NoError(t, runDocsSearch(context.Background(), + &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, + &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)) + m := parse(t, out.String()) + assert.Equal(t, 3, m.Count, "data must be trimmed to --limit") + assert.True(t, m.HasMore, "has_more must be true when results exceed --limit") + }) + + t.Run("fits -> has_more false", func(t *testing.T) { + out, _ := iostreams.SetForTest(t) + svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page[:2]}, total: 2} + require.NoError(t, runDocsSearch(context.Background(), + &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, + &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)) + m := parse(t, out.String()) + assert.Equal(t, 2, m.Count) + assert.False(t, m.HasMore, "has_more must be false/absent when results fit under --limit") + }) +} diff --git a/cli/cmd/search/kb.go b/cli/cmd/search/kb.go index 7deb10cc..7065f407 100644 --- a/cli/cmd/search/kb.go +++ b/cli/cmd/search/kb.go @@ -79,6 +79,11 @@ content, use ` + "`weknora search chunks`" + `.`, } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return") cmdutil.AddFormatFlag(cmd, kbSearchFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Find knowledge bases by name or description (client-side case-insensitive substring match). Results come with meta.count; use --limit to cap. For searching content inside a KB, use 'search chunks' instead.", + Examples: []string{`weknora search kb "engineering" --format json`}, + Output: "envelope.data is an array of KnowledgeBase objects with id, name, knowledge_count; meta.count is the returned count; meta.has_more=true if more matched than --limit", + }) return cmd } @@ -88,7 +93,8 @@ func runKBSearch(ctx context.Context, opts *KBSearchOptions, fopts *cmdutil.Form return cmdutil.WrapHTTP(err, "list knowledge bases") } matches := filterKBs(items, opts.Query) - if opts.Limit > 0 && len(matches) > opts.Limit { + truncated := opts.Limit > 0 && len(matches) > opts.Limit + if truncated { matches = matches[:opts.Limit] } @@ -96,7 +102,7 @@ func runKBSearch(ctx context.Context, opts *KBSearchOptions, fopts *cmdutil.Form if matches == nil { matches = []sdk.KnowledgeBase{} } - meta := &output.Meta{Count: len(matches)} + meta := &output.Meta{Count: len(matches), HasMore: truncated} return fopts.Emit(iostreams.IO.Out, matches, meta) } if len(matches) == 0 { diff --git a/cli/cmd/search/sessions.go b/cli/cmd/search/sessions.go index a03682a7..ed4f72bc 100644 --- a/cli/cmd/search/sessions.go +++ b/cli/cmd/search/sessions.go @@ -92,6 +92,11 @@ to stop after one page.`, cmd.Flags().IntVar(&opts.PageSize, "page-size", sessionsPageSize, "Items per server batch (1..1000)") cmd.Flags().BoolVar(&opts.AllPages, "all-pages", true, "Walk every server page until exhausted or --limit hit") cmdutil.AddFormatFlag(cmd, sessionsSearchFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Find chat sessions by title or description (client-side case-insensitive substring match). Results come with meta.count; use --limit to cap and --all-pages=false to stop after one page.", + Examples: []string{`weknora search sessions "onboarding" --format json`}, + Output: "envelope.data is an array of Session objects with id, title, updated_at; meta.count is the returned count; meta.has_more=true if more matched than --limit", + }) return cmd } @@ -117,7 +122,8 @@ func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, fopts * for _, s := range items { if matchSession(s, needle) { matches = append(matches, s) - if opts.Limit > 0 && len(matches) >= opts.Limit { + // Collect one past --limit so has_more is accurate; trimmed below. + if opts.Limit > 0 && len(matches) > opts.Limit { goto done } } @@ -131,12 +137,16 @@ func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, fopts * } done: sortSessionsByRecency(matches) + truncated := opts.Limit > 0 && len(matches) > opts.Limit + if truncated { + matches = matches[:opts.Limit] + } if fopts.WantsJSON() { if matches == nil { matches = []sdk.Session{} } - meta := &output.Meta{Count: len(matches)} + meta := &output.Meta{Count: len(matches), HasMore: truncated} return fopts.Emit(iostreams.IO.Out, matches, meta) } if len(matches) == 0 { diff --git a/cli/cmd/session/delete.go b/cli/cmd/session/delete.go index 1803e812..5fbdccae 100644 --- a/cli/cmd/session/delete.go +++ b/cli/cmd/session/delete.go @@ -84,7 +84,7 @@ 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(), "session", len(args), "session.delete", "weknora session delete "+strings.Join(args, " ")+" -y"); err != nil { + if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "session", len(args), "session.delete", "weknora session delete "+strings.Join(args, " ")+" -y"); err != nil { return err } outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error { @@ -124,7 +124,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(), "session", id, "session.delete", "weknora session delete "+id+" -y"); err != nil { + if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "session", id, "session.delete", "weknora session delete "+id+" -y"); err != nil { return err } diff --git a/cli/cmd/session/delete_test.go b/cli/cmd/session/delete_test.go index 0070146a..0716998c 100644 --- a/cli/cmd/session/delete_test.go +++ b/cli/cmd/session/delete_test.go @@ -146,7 +146,7 @@ func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) { _, _ = iostreams.SetForTest(t) svc := &fakeMultiDeleteSvc{} fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText} - err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "session", 2, "session.delete", "") + err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "delete", "session", 2, "session.delete", "") require.Error(t, err) var typed *cmdutil.Error require.ErrorAs(t, err, &typed) diff --git a/cli/cmd/session/list.go b/cli/cmd/session/list.go index ce2f8936..0103bfec 100644 --- a/cli/cmd/session/list.go +++ b/cli/cmd/session/list.go @@ -69,6 +69,11 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)") cmd.Flags().StringVar(&opts.Since, "since", "", "Only show sessions updated within `duration` (e.g. 7d, 24h, 30m)") cmdutil.AddFormatFlag(cmd, sessionListFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "List chat sessions for the active profile. Results come with meta.count; use --limit to cap, --all-pages to walk every server page, --since to filter by recency (e.g. 7d).", + Examples: []string{"weknora session list --format json", "weknora session list --all-pages --since 7d --format json"}, + Output: "envelope.data is an array of Session objects with id, title, updated_at; meta.count is the total returned", + }) return cmd } diff --git a/cli/cmd/session/session.go b/cli/cmd/session/session.go index b968a239..9084df84 100644 --- a/cli/cmd/session/session.go +++ b/cli/cmd/session/session.go @@ -1,5 +1,5 @@ // Package sessioncmd holds `weknora session` command tree (list / view / -// delete / ask) for chat history and agent invocation. +// delete / ask / continue-stream / stop) for chat history and agent invocation. // // Package name `sessioncmd` (not `session`) so callers can `import sdk // "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without @@ -23,5 +23,6 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { cmd.AddCommand(NewCmdDelete(f)) cmd.AddCommand(NewCmdAsk(f)) cmd.AddCommand(NewCmdContinueStream(f)) + cmd.AddCommand(NewCmdStop(f)) return cmd } diff --git a/cli/cmd/session/stop.go b/cli/cmd/session/stop.go new file mode 100644 index 00000000..8e4863c3 --- /dev/null +++ b/cli/cmd/session/stop.go @@ -0,0 +1,118 @@ +// stop.go implements `weknora session stop` — cancel server-side generation +// for a specific assistant message under a known session. +// +// Unlike Ctrl-C (which only drops the local connection while the server keeps +// generating and billing tokens), this tells the server to stop. +// +// This is the symmetric counterpart to `session continue-stream`: both key on +// (session_id, message_id). The message_id comes from the init event of the +// original chat / session ask / continue-stream stream. +package sessioncmd + +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" +) + +var stopFields = []string{"session_id", "message_id", "stopped"} + +// StopOptions captures `session stop` flag/arg state. +type StopOptions struct { + SessionID string + MessageID string + DryRun bool +} + +// StopService is the narrow SDK surface this command depends on. +// *sdk.Client satisfies it; tests substitute a fake. Compile-time check +// at the bottom of this file. +type StopService interface { + StopSession(ctx context.Context, sessionID, messageID string) error +} + +type stopResult struct { + SessionID string `json:"session_id"` + MessageID string `json:"message_id"` + Stopped bool `json:"stopped"` +} + +// NewCmdStop builds `weknora session stop --message `. +func NewCmdStop(f *cmdutil.Factory) *cobra.Command { + opts := &StopOptions{} + cmd := &cobra.Command{ + Use: "stop ", + Short: "Stop in-flight generation for an assistant message in a session", + Long: `Cancel server-side generation for a specific assistant message under a +session. Unlike Ctrl-C (which only drops the local connection while the server +keeps generating and billing tokens), this tells the server to stop. + +Symmetric with 'session continue-stream': both key on (session_id, message_id).`, + Example: ` weknora session stop sess_xyz --message msg_abc`, + Args: cobra.ExactArgs(1), + RunE: func(c *cobra.Command, args []string) error { + opts.SessionID = args[0] + 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: "session.stop", + Args: map[string]any{"session": opts.SessionID, "message": opts.MessageID}, + }); handled { + return err + } + cli, err := f.Client() + if err != nil { + return err + } + return runStop(c.Context(), opts, fopts, cli) + }, + } + cmd.Flags().StringVarP(&opts.MessageID, "message", "m", "", + "Assistant message id to stop (from the init event of the stream you're stopping)") + _ = cmd.MarkFlagRequired("message") + cmdutil.AddFormatFlag(cmd, stopFields...) + cmdutil.AddDryRunFlag(cmd, &opts.DryRun) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "Stop server-side generation for an in-flight assistant message (counterpart to continue-stream). The message_id comes from the init event of the chat / session ask / continue-stream stream you're stopping.", + RequiredFlags: []string{"--message (message_id from the init event of the stream you're stopping)"}, + Examples: []string{"weknora session stop sess_xyz --message msg_abc"}, + Output: "envelope {session_id, message_id, stopped:true}", + }) + return cmd +} + +// runStop is the testable core: validate, dispatch the stop, and emit the +// result envelope. Returns a typed error. +func runStop(ctx context.Context, opts *StopOptions, fopts *cmdutil.FormatOptions, svc StopService) error { + if opts.SessionID == "" { + return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "session-id argument cannot be empty") + } + if opts.MessageID == "" { + return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--message cannot be empty") + } + if svc == nil { + return cmdutil.NewError(cmdutil.CodeServerError, "session stop: no SDK client available") + } + if err := svc.StopSession(ctx, opts.SessionID, opts.MessageID); err != nil { + if cmdutil.IsCancelled(ctx, err) { + return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session stop cancelled") + } + return cmdutil.WrapHTTP(err, "stop session") + } + if fopts.WantsJSON() { + return fopts.Emit(iostreams.IO.Out, stopResult{SessionID: opts.SessionID, MessageID: opts.MessageID, Stopped: true}, nil) + } + fmt.Fprintf(iostreams.IO.Out, "✓ Stopped generation for message %s\n", opts.MessageID) + return nil +} + +// compile-time check: production SDK client satisfies StopService. +var _ StopService = (*sdk.Client)(nil) diff --git a/cli/cmd/session/stop_test.go b/cli/cmd/session/stop_test.go new file mode 100644 index 00000000..ed70cee5 --- /dev/null +++ b/cli/cmd/session/stop_test.go @@ -0,0 +1,70 @@ +package sessioncmd + +import ( + "bytes" + "context" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/cli/internal/cmdutil" + "github.com/Tencent/WeKnora/cli/internal/iostreams" +) + +// fakeStopSvc records the (sessionID, messageID) pair passed to StopSession +// and optionally returns a canned error. +type fakeStopSvc struct { + err error + gotSessID string + gotMsgID string +} + +func (s *fakeStopSvc) StopSession(_ context.Context, sessionID, messageID string) error { + s.gotSessID = sessionID + s.gotMsgID = messageID + return s.err +} + +// TestRunStop_CallsSDKAndEmits verifies that runStop passes (sessionID, +// messageID) to the SDK and emits a JSON envelope with stopped:true. +func TestRunStop_CallsSDKAndEmits(t *testing.T) { + out, _ := iostreams.SetForTest(t) + svc := &fakeStopSvc{} + opts := &StopOptions{SessionID: "s1", MessageID: "m1"} + require.NoError(t, runStop(context.Background(), opts, jsonOpts(), svc)) + + assert.Equal(t, "s1", svc.gotSessID, "SDK must receive the session-id") + assert.Equal(t, "m1", svc.gotMsgID, "SDK must receive the message-id") + assert.Contains(t, out.String(), `"stopped":true`, "stdout must contain stopped:true") +} + +// TestRunStop_TextMode verifies that runStop writes the human-readable success +// line and calls the SDK when format is text (not JSON). +func TestRunStop_TextMode(t *testing.T) { + out, _ := iostreams.SetForTest(t) + svc := &fakeStopSvc{} + opts := &StopOptions{SessionID: "sess_xyz", MessageID: "msg_abc"} + require.NoError(t, runStop(context.Background(), opts, textOpts(), svc)) + + assert.Equal(t, "sess_xyz", svc.gotSessID, "SDK must receive the session-id") + assert.Equal(t, "msg_abc", svc.gotMsgID, "SDK must receive the message-id") + assert.Contains(t, out.String(), "✓ Stopped generation for message msg_abc") +} + +// TestStop_MessageRequired verifies that NewCmdStop refuses to run without +// --message (the flag is marked required by cobra). +func TestStop_MessageRequired(t *testing.T) { + f := &cmdutil.Factory{} + cmd := NewCmdStop(f) + var buf bytes.Buffer + cmd.SetOut(&buf) + cmd.SetErr(&buf) + cmd.SetArgs([]string{"sess_xyz"}) // positional only, no --message + err := cmd.Execute() + require.Error(t, err, "expected required-flag error when --message is missing") + assert.True(t, + strings.Contains(err.Error(), "message") || strings.Contains(err.Error(), "required"), + "error should mention the required --message flag: %v", err) +} diff --git a/cli/cmd/session/view.go b/cli/cmd/session/view.go index 3c21417e..a82d6d3a 100644 --- a/cli/cmd/session/view.go +++ b/cli/cmd/session/view.go @@ -78,8 +78,14 @@ Pass --full to also load the chat history (LoadMessages SDK call). Use }, } cmd.Flags().BoolVar(&opts.Full, "full", false, "Also load chat history via LoadMessages") - cmd.Flags().IntVar(&opts.Limit, "limit", defaultFullLimit, "Max messages to load when --full is set (1..1000)") + cmd.Flags().IntVarP(&opts.Limit, "limit", "L", defaultFullLimit, "Max messages to load when --full is set (1..1000)") cmdutil.AddFormatFlag(cmd, sessionViewFields...) + cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{ + UsedFor: "fetch one chat session by id; --full also loads its message history", + RequiredFlags: []string{" (positional)"}, + Examples: []string{"weknora session view sess_abc", "weknora session view sess_abc --full --limit 50"}, + Output: "envelope.data is the session object; with --full it also carries the loaded messages", + }) return cmd } diff --git a/cli/internal/mcp/server.go b/cli/internal/mcp/server.go index 8f9ffa7c..f03d6054 100644 --- a/cli/internal/mcp/server.go +++ b/cli/internal/mcp/server.go @@ -7,7 +7,7 @@ // - Tool surface is hand-curated rather than auto-derived from the cobra // tree (which would expose auth/link/completion/destructive verbs that // don't belong on an agent-callable surface). -// - Long-running tools (chat / agent_invoke) accumulate the LLM SSE +// - Long-running tools (chat / session_ask) accumulate the LLM SSE // stream server-side and return a single CallToolResult - MCP spec // 2025-06-18 does not define streamed tool-result content, so the // accumulate-and-return pattern is the canonical path. diff --git a/cli/internal/mcp/tools.go b/cli/internal/mcp/tools.go index d0487e1a..81d4f881 100644 --- a/cli/internal/mcp/tools.go +++ b/cli/internal/mcp/tools.go @@ -95,12 +95,12 @@ type chunkListService interface { ListKnowledgeChunks(ctx context.Context, knowledgeID string, page, pageSize int, chunkTypes ...string) ([]sdk.Chunk, int64, error) } -// agentInvokeService composes the two SDK methods agent_invoke needs +// sessionAskService composes the two SDK methods session_ask needs // (CreateSession for the auto-session path + AgentQAStreamWithRequest // for the run itself). Declared here alongside the per-domain // interfaces above so ServiceClient (server.go) - which embeds the // four domain interfaces - also satisfies it. -type agentInvokeService interface { +type sessionAskService interface { CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error) AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error } @@ -126,7 +126,7 @@ func registerTools(server *mcpsdk.Server, svc ServiceClient) { addSearchChunks(server, svc) addChat(server, svc) addAgentList(server, svc) - addAgentInvoke(server, svc) + addSessionAsk(server, svc) addChunkList(server, svc) } @@ -380,7 +380,7 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) { // nilable map[string]any that violates the auto-generated // type=object constraint when empty. Skipping derivation by using // `any` keeps the structured JSON shape identical while bypassing - // the over-eager validator. Same pattern applied to chat / agent_invoke + // the over-eager validator. Same pattern applied to chat / session_ask // below. mcpsdk.AddTool(server, &mcpsdk.Tool{ Name: "search_chunks", @@ -513,7 +513,7 @@ type agentListOutput struct { func addAgentList(server *mcpsdk.Server, svc agentService) { mcpsdk.AddTool(server, &mcpsdk.Tool{ Name: "agent_list", - Description: "List the tenant's custom agents. Returns items[] with id, name, description, is_builtin - use to discover an agent_id before agent_invoke.", + Description: "List the tenant's custom agents. Returns items[] with id, name, description, is_builtin - use to discover an agent_id before session_ask.", Annotations: &mcpsdk.ToolAnnotations{ Title: "List Custom Agents", DestructiveHint: bptr(false), @@ -533,15 +533,15 @@ func addAgentList(server *mcpsdk.Server, svc agentService) { }) } -// ---- agent_invoke -------------------------------------------------------- +// ---- session_ask --------------------------------------------------------- -type agentInvokeInput struct { +type sessionAskInput struct { AgentID string `json:"agent_id" jsonschema:"custom agent ID"` Query string `json:"query" jsonschema:"user query"` SessionID string `json:"session_id,omitempty" jsonschema:"existing session to continue; auto-created when empty"` } -type agentInvokeOutput struct { +type sessionAskOutput struct { Answer string `json:"answer"` References []*sdk.SearchResult `json:"references"` ToolEvents []sse.AgentToolEvent `json:"tool_events,omitempty"` @@ -551,18 +551,18 @@ type agentInvokeOutput struct { Query string `json:"query"` } -func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) { +func addSessionAsk(server *mcpsdk.Server, svc sessionAskService) { mcpsdk.AddTool(server, &mcpsdk.Tool{ - Name: "agent_invoke", - Description: "Run a query through a custom agent (system prompt + tool allow-list + KB scope). The agent's SSE stream is accumulated server-side (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the final accumulated response once the stream completes.", + Name: "session_ask", + Description: "Run a query through a custom agent via `session ask --agent` (system prompt + tool allow-list + KB scope). The agent's SSE stream is accumulated server-side (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the final accumulated response once the stream completes.", Annotations: &mcpsdk.ToolAnnotations{ - Title: "Invoke Custom Agent", + Title: "Ask a Custom Agent (session ask --agent)", DestructiveHint: bptr(false), ReadOnlyHint: false, IdempotentHint: false, OpenWorldHint: bptr(true), }, - }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in agentInvokeInput) (*mcpsdk.CallToolResult, any, error) { + }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in sessionAskInput) (*mcpsdk.CallToolResult, any, error) { if in.AgentID == "" { return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "agent_id is required")), nil, nil } @@ -580,7 +580,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) { // agnostic at creation (verified against server source). sessionID := in.SessionID if sessionID == "" { - sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp agent_invoke"}) + sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp session_ask"}) if err != nil { return toolErrorResult(cmdutil.WrapHTTP(err, "create chat session")), nil, nil } @@ -596,7 +596,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) { if !acc.Done() { return toolErrorResult(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")), nil, nil } - return successResult(agentInvokeOutput{ + return successResult(sessionAskOutput{ Answer: acc.Answer(), References: acc.References, ToolEvents: acc.ToolEvents, diff --git a/cli/internal/mcp/tools_test.go b/cli/internal/mcp/tools_test.go index 12d02598..89c94e5b 100644 --- a/cli/internal/mcp/tools_test.go +++ b/cli/internal/mcp/tools_test.go @@ -196,7 +196,7 @@ func TestTool_ListsRegistered(t *testing.T) { if err != nil { t.Fatalf("ListTools: %v", err) } - want := []string{"kb_list", "kb_view", "doc_list", "doc_view", "doc_download", "search_chunks", "chat", "agent_list", "agent_invoke", "chunk_list"} + want := []string{"kb_list", "kb_view", "doc_list", "doc_view", "doc_download", "search_chunks", "chat", "agent_list", "session_ask", "chunk_list"} got := map[string]bool{} for _, tool := range res.Tools { got[tool.Name] = true @@ -211,6 +211,29 @@ func TestTool_ListsRegistered(t *testing.T) { } } +// TestTool_SessionAsk_NotAgentInvoke asserts the MCP rename landed: the +// registered set must contain "session_ask" and must NOT contain the +// stale "agent_invoke" name (clean break, no deprecation alias). +func TestTool_SessionAsk_NotAgentInvoke(t *testing.T) { + c, _ := newTestServer(t, &fakeSvc{}) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + res, err := c.ListTools(ctx, nil) + if err != nil { + t.Fatalf("ListTools: %v", err) + } + names := map[string]bool{} + for _, tool := range res.Tools { + names[tool.Name] = true + } + if !names["session_ask"] { + t.Error("expected tool 'session_ask' to be registered") + } + if names["agent_invoke"] { + t.Error("stale tool 'agent_invoke' must NOT be registered (clean break, no alias)") + } +} + func TestTool_KBList(t *testing.T) { svc := &fakeSvc{listKBs: []sdk.KnowledgeBase{{ID: "kb1", Name: "Marketing"}}} c, _ := newTestServer(t, svc) @@ -448,7 +471,7 @@ func TestMCP_ChatToolReturnsThinking(t *testing.T) { } } -func TestMCP_AgentInvokeToolReturnsToolCalls(t *testing.T) { +func TestMCP_SessionAskToolReturnsToolCalls(t *testing.T) { svc := &fakeSvc{ agentEvents: []*sdk.AgentStreamResponse{ {ResponseType: sdk.AgentResponseTypeThinking, Content: "agent thinks"}, @@ -458,8 +481,8 @@ func TestMCP_AgentInvokeToolReturnsToolCalls(t *testing.T) { }, } c, _ := newTestServer(t, svc) - var out agentInvokeOutput - callTool(t, c, "agent_invoke", map[string]any{"agent_id": "ag1", "query": "tool question"}, &out) + var out sessionAskOutput + callTool(t, c, "session_ask", map[string]any{"agent_id": "ag1", "query": "tool question"}, &out) if out.Thinking != "agent thinks" { t.Errorf("thinking = %q, want %q", out.Thinking, "agent thinks") } @@ -495,7 +518,7 @@ func TestTool_AgentList(t *testing.T) { } } -func TestTool_AgentInvoke(t *testing.T) { +func TestTool_SessionAsk(t *testing.T) { svc := &fakeSvc{ agentEvents: []*sdk.AgentStreamResponse{ {ResponseType: sdk.AgentResponseTypeAnswer, Content: "result"}, @@ -504,8 +527,8 @@ func TestTool_AgentInvoke(t *testing.T) { }, } c, _ := newTestServer(t, svc) - var out agentInvokeOutput - callTool(t, c, "agent_invoke", map[string]any{"agent_id": "ag1", "query": "x"}, &out) + var out sessionAskOutput + callTool(t, c, "session_ask", map[string]any{"agent_id": "ag1", "query": "x"}, &out) if out.Answer != "result" { t.Errorf("answer = %q", out.Answer) } @@ -517,7 +540,7 @@ func TestTool_AgentInvoke(t *testing.T) { } } -func TestTool_AgentInvoke_StreamAbort(t *testing.T) { +func TestTool_SessionAsk_StreamAbort(t *testing.T) { svc := &fakeSvc{ agentEvents: []*sdk.AgentStreamResponse{{ResponseType: sdk.AgentResponseTypeAnswer, Content: "partial"}}, agentStreamErr: errors.New("connection reset"), @@ -525,7 +548,7 @@ func TestTool_AgentInvoke_StreamAbort(t *testing.T) { c, _ := newTestServer(t, svc) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() - res, err := c.CallTool(ctx, &mcpsdk.CallToolParams{Name: "agent_invoke", Arguments: map[string]any{"agent_id": "ag1", "query": "x"}}) + res, err := c.CallTool(ctx, &mcpsdk.CallToolParams{Name: "session_ask", Arguments: map[string]any{"agent_id": "ag1", "query": "x"}}) if err != nil { t.Fatalf("unexpected transport error: %v", err) } @@ -625,7 +648,7 @@ func TestToolAnnotations_AllToolsHaveExpectedHints(t *testing.T) { "search_chunks": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "Search Knowledge Chunks"}, "chat": {destructive: false, readOnly: false, idempotent: false, openWorld: true, title: "Chat with KB (Streaming RAG)"}, "agent_list": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "List Custom Agents"}, - "agent_invoke": {destructive: false, readOnly: false, idempotent: false, openWorld: true, title: "Invoke Custom Agent"}, + "session_ask": {destructive: false, readOnly: false, idempotent: false, openWorld: true, title: "Ask a Custom Agent (session ask --agent)"}, "chunk_list": {destructive: false, readOnly: true, idempotent: true, openWorld: false, title: "List Knowledge Chunks"}, }