refactor(cli): v0.3 cross-cutting cleanup

Cross-cutting findings surfaced by the branch-completion review.

Perf bug:
- Factory.Client closure was not memoized. Factory.ResolveKB internally
  calls f.Client() to resolve --kb name → id, then the command's RunE
  calls f.Client() again. Two SDK clients, two keyring reads, two
  AuthRetryTransport allocations per name-resolved invocation, with
  *independent* token state (a refresh in one was invisible to the
  other). Switched to sync.Once like Secrets already does.

Silent bug bait:
- cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the
  empty case; code returned CodeInputInvalidArgument. Aligned doc to
  code (present-but-empty is a bad value, not a missing flag).

Agent contract gaps:
- Five user-facing subcommands lacked SetAgentHelp: auth login /
  logout / list / status and chat. Added concise strings with error-
  code call-outs so agents can branch without parsing human strings.

Helper extraction (≥3 callers):
- text.KnowledgeDisplayName(fileName, title, id) — byte-identical
  formatter that was in both cmd/doc/list.go and cmd/search/docs.go.
  Takes fields directly so internal/text stays SDK-free.
- cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the
  `Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK
  call sites. Sed-driven migration; off-pattern shapes in chat.go
  (used streamErr) and cmdutil/kb.go (in-package) hand-edited.
  Contract test gains a comment update: post-migration the dominant
  pattern is WrapHTTP which the AST scanner skips entirely (only
  NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs()
  bridge still covers the dynamic codes those paths can yield.

UX consistency:
- cmd/doc/list.go --page-size help now reads "Items per page
  (1..1000)" matching cmd/session/list.go. The bounds validation
  already enforced 1..1000; the help text was the last drift.

Comment-discipline sweep:
- Deleted the WHAT-only "*Options captures `weknora ...` flag state"
  docstring across 23 files (context, kb, auth, doc, session, search,
  chat, doctor, link). Where the line carried a real WHY clause
  (kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and
  dropped only the leading WHAT phrase.
- Stripped third-party project-name attribution from inline comments
  and one user-visible flag-help string across ~40 files in cli/cmd
  and cli/internal (plus 4 test-file comments). Removed phrases like
  "Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style",
  "gcloud `--project`", "Stripe pattern", and the embedded GitHub
  URLs pointing at those projects. Behavioral descriptions and the
  WHY behind each comment are preserved; only the upstream-name
  attribution is gone. Inspiration / north-star references belong in
  cli/AGENTS.md (the design doc) and commit messages, not scattered
  through every file.

  Triggered by an audit round that surfaced several false / fragile
  parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no
  --name flag; "matches gcloud `--project` id-or-name" — gcloud's
  --project accepts ID only). Rather than fix them one by one, the
  whole category of in-comment external-project references was
  stripped uniformly.
This commit is contained in:
nullkey
2026-05-12 23:42:20 +08:00
committed by lyingbug
parent 73a88b4f0a
commit 5adcedf170
58 changed files with 274 additions and 314 deletions
+10 -11
View File
@@ -14,7 +14,6 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// ChunksOptions is the runtime configuration of a chunks search.
type ChunksOptions struct {
Query string
KB string // raw --kb (UUID or name)
@@ -34,18 +33,19 @@ type ChunksService interface {
}
// NewCmdChunks builds `weknora search chunks "<query>" --kb <id-or-name>`.
// Mirrors gh `search code`'s "subject as positional" shape (the previous
// top-level `weknora search` is its legacy alias — see search.go).
// Uses a positional query argument with the KB selected via flag.
//
// The `--kb` flag accepts either a KB UUID (passed through) or a name
// (resolved via ListKnowledgeBases). Mirrors gcloud `--project`'s
// id-or-name auto-detection.
// The `--kb` flag accepts either a KB UUID (passed through unchanged) or a
// name (resolved via ListKnowledgeBases — see cmdutil.ResolveKBFlag).
func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
opts := &ChunksOptions{}
cmd := &cobra.Command{
Use: `chunks "<query>"`,
Short: "Hybrid (vector + keyword) chunk retrieval against a knowledge base",
Args: cobra.ExactArgs(1),
Example: ` weknora search chunks "what is RAG?" --kb engineering
weknora search chunks "embedding model" --kb kb_abc --limit 20
weknora search chunks "k8s" --kb engineering --no-keyword # vector-only`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Query = strings.TrimSpace(args[0])
if err := opts.validate(); err != nil {
@@ -110,13 +110,12 @@ func runChunks(ctx context.Context, opts *ChunksOptions, svc ChunksService) erro
}
results, err := svc.HybridSearch(ctx, opts.KBID, params)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "hybrid search")
return cmdutil.WrapHTTP(err, "hybrid search")
}
// match_count is the server's *primary-match* cap — after that, the
// service appends parent / nearby / relation chunks as context
// enrichment, so the wire response can exceed Limit. CLIs like gh /
// kubectl / aws treat their `--limit`-style flag as a hard return-count
// cap; honor that contract by trimming on the client. Recall isn't
// enrichment, so the wire response can exceed Limit. Treat --limit as
// 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 {
+2 -3
View File
@@ -46,8 +46,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
// JSON envelope must surface match_type so machine consumers / agents can
// reason about retrieval channels without re-implementing the wire format.
// (Human renderer keeps default minimal — diagnostic info opt-in via --json,
// matching gh / kubectl / Algolia / Vespa terse-default conventions.)
// (Human renderer keeps default minimal — diagnostic info opt-in via --json.)
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
@@ -75,7 +74,7 @@ func TestRunSearch_EmptyResults(t *testing.T) {
// Server returns primary matches plus parent/related/nearby enrichment chunks,
// so the wire response can exceed Limit. CLI must trim to honor the user's
// hard-limit contract (gh / kubectl / aws idiom).
// hard-limit contract.
func TestRunSearch_LimitHardCap(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
+5 -17
View File
@@ -22,7 +22,6 @@ import (
// 1000 (per the doc/list bound this branch already added).
const docsPageSize = 200
// DocsSearchOptions captures `weknora search docs` flag state.
type DocsSearchOptions struct {
Query string
KB string // raw --kb (UUID or name)
@@ -47,7 +46,9 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: `docs "<query>"`,
Short: "Find documents in a knowledge base by name (client-side substring match)",
Args: cobra.ExactArgs(1),
Example: ` weknora search docs "Q3 forecast" --kb finance
weknora search docs "spec" --kb engineering --limit 5`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Query = strings.TrimSpace(args[0])
if opts.Query == "" {
@@ -82,7 +83,7 @@ func runDocsSearch(ctx context.Context, opts *DocsSearchOptions, svc DocsSearchS
for page := 1; ; page++ {
items, total, err := svc.ListKnowledge(ctx, opts.KBID, page, docsPageSize, "")
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list documents")
return cmdutil.WrapHTTP(err, "list documents")
}
for _, k := range items {
if matchKnowledge(k, needle) {
@@ -109,7 +110,7 @@ done:
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "ID\tFILE\tTYPE\tUPDATED")
for _, k := range matches {
name := text.Truncate(50, displayDocName(k))
name := text.Truncate(50, text.KnowledgeDisplayName(k.FileName, k.Title, k.ID))
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", k.ID, name, k.FileType, k.UpdatedAt.Format("2006-01-02"))
}
return tw.Flush()
@@ -121,19 +122,6 @@ func matchKnowledge(k sdk.Knowledge, needle string) bool {
return text.ContainsFold(needle, k.Title, k.FileName)
}
// displayDocName picks a human-friendly name. Order matches `weknora doc
// list` (FileName for uploads → Title for URL/text entries → ID fallback)
// so a Knowledge renders the same in both commands.
func displayDocName(k sdk.Knowledge) string {
if k.FileName != "" {
return k.FileName
}
if k.Title != "" {
return k.Title
}
return k.ID
}
// sortKnowledgeByRecency sorts in place by UpdatedAt desc.
func sortKnowledgeByRecency(items []sdk.Knowledge) {
sort.Slice(items, func(i, j int) bool {
+2 -2
View File
@@ -78,7 +78,7 @@ func TestDocsSearch_PaginatesUntilTotal(t *testing.T) {
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when no match on page 1")
}
func TestDocsSearch_StopsAtTopK(t *testing.T) {
func TestDocsSearch_StopsAtLimit(t *testing.T) {
_, _ = iostreams.SetForTest(t)
page1 := make([]sdk.Knowledge, 50)
for i := range page1 {
@@ -86,7 +86,7 @@ func TestDocsSearch_StopsAtTopK(t *testing.T) {
}
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3}, svc))
// Must not request page 2 because top-k was hit mid-page.
// Must not request page 2 because limit was hit mid-page.
assert.Equal(t, []int{1}, svc.calls)
}
+6 -5
View File
@@ -17,7 +17,6 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// KBSearchOptions captures `weknora search kb` flag state.
type KBSearchOptions struct {
Query string
Limit int
@@ -33,14 +32,16 @@ type KBSearchService interface {
// NewCmdKB builds `weknora search kb "<query>"` — substring + case-insensitive
// match across KB names and descriptions visible to the active context.
// Mirrors gh `search repos`. Results are sorted by name length (shortest
// first; usually the closest hit) for deterministic output.
// Results are sorted by name length (shortest first; usually the closest
// hit) for deterministic output.
func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
opts := &KBSearchOptions{}
cmd := &cobra.Command{
Use: `kb "<query>"`,
Short: "Find knowledge bases by name or description (client-side substring match)",
Args: cobra.ExactArgs(1),
Example: ` weknora search kb "marketing"
weknora search kb "team" --limit 5 --json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Query = strings.TrimSpace(args[0])
if opts.Query == "" {
@@ -62,7 +63,7 @@ func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
func runKBSearch(ctx context.Context, opts *KBSearchOptions, svc KBSearchService) error {
items, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list knowledge bases")
return cmdutil.WrapHTTP(err, "list knowledge bases")
}
matches := filterKBs(items, opts.Query)
if opts.Limit > 0 && len(matches) > opts.Limit {
+1 -1
View File
@@ -74,7 +74,7 @@ func TestKBSearch_SortByNameLength(t *testing.T) {
assert.Less(t, iMid, iLong)
}
func TestKBSearch_TopKHardCap(t *testing.T) {
func TestKBSearch_LimitHardCap(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
{ID: "a", Name: "match-a"}, {ID: "b", Name: "match-b"},
+3 -4
View File
@@ -1,6 +1,5 @@
// Package search implements the `weknora search` command tree:
// chunks / kb / docs / sessions. Verb-noun shape borrowed from
// gh search (gh search repos / code / commits / issues / prs).
// chunks / kb / docs / sessions.
package search
import (
@@ -11,12 +10,12 @@ import (
)
// NewCmdSearch builds the `weknora search` parent. Pure dispatcher to the
// four subcommands; no positional/legacy form.
// four subcommands — users must pick a verb (chunks / kb / docs / sessions).
func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "search",
Short: "Search across chunks, knowledge bases, documents, or sessions",
Long: `Verb-noun search tree (gh search idiom):
Long: `Verb-noun search tree:
search chunks "<q>" --kb X hybrid retrieval (RAG search)
search kb "<q>" find KBs by name / description
+4 -3
View File
@@ -19,7 +19,6 @@ import (
const sessionsPageSize = 200
// SessionsSearchOptions captures `weknora search sessions` flag state.
type SessionsSearchOptions struct {
Query string
Limit int
@@ -40,7 +39,9 @@ func NewCmdSessions(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: `sessions "<query>"`,
Short: "Find chat sessions by title or description (client-side substring match)",
Args: cobra.ExactArgs(1),
Example: ` weknora search sessions "onboarding"
weknora search sessions "Q3 review" --limit 3 --json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Query = strings.TrimSpace(args[0])
if opts.Query == "" {
@@ -66,7 +67,7 @@ func runSessionsSearch(ctx context.Context, opts *SessionsSearchOptions, svc Ses
for page := 1; ; page++ {
items, total, err := svc.GetSessionsByTenant(ctx, page, sessionsPageSize)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list sessions")
return cmdutil.WrapHTTP(err, "list sessions")
}
for _, s := range items {
if matchSession(s, needle) {