refactor(cli): resource-command refactors — --kb resolver, MCP session_ask, session stop (BREAKING)
Unify the --kb resolver (accepts name or UUID) across kb/doc/chunk/session/ search/chat/link; `agent create` attaches knowledge bases via --attach-kb (no longer --kb). Rename the MCP tool agent_invoke → session_ask and drop dead MCP error codes. Add `session stop` (StopSession), completing the start / continue-stream / stop triad. Across these commands, bring the agent contract up to par: --dry-run previews on mutations (incl. kb pin/unpin, session stop), agent-help blobs on the read/health surface, accurate destructive-confirmation verbs, and search has_more truncation signalling so an agent can tell its results were capped.
This commit is contained in:
@@ -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{"<query> (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)
|
||||
|
||||
@@ -137,6 +137,23 @@ func TestRunSearch_NilService(t *testing.T) {
|
||||
assert.Contains(t, err.Error(), "server.error")
|
||||
}
|
||||
|
||||
// TestNewCmdChunks_RequiresKB asserts that running `search chunks "<query>"`
|
||||
// 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{
|
||||
|
||||
+13
-2
@@ -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{"<query> (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 {
|
||||
|
||||
@@ -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")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user