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
+4 -7
View File
@@ -13,10 +13,8 @@ import (
"github.com/Tencent/WeKnora/cli/internal/prompt"
)
// DeleteOptions captures `weknora session delete` flag state. Yes is
// sourced from the global -y/--yes persistent flag (gh-style).
type DeleteOptions struct {
Yes bool
Yes bool // sourced from the global -y/--yes persistent flag
JSONOut bool
DryRun bool
}
@@ -32,9 +30,8 @@ type deleteResult struct {
Deleted bool `json:"deleted"`
}
// NewCmdDelete builds `weknora session delete`. Mirrors `gh issue delete`:
// destructive write gated by -y/--yes (exit-10 protocol in scripted /
// --json invocations).
// NewCmdDelete builds `weknora session delete`. Destructive write gated
// by -y/--yes (exit-10 protocol in scripted / --json invocations).
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
opts := &DeleteOptions{}
cmd := &cobra.Command{
@@ -83,7 +80,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr
}
if err := svc.DeleteSession(ctx, id); err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete session %s", id)
return cmdutil.WrapHTTP(err, "delete session %s", id)
}
if opts.JSONOut {
+5 -7
View File
@@ -22,7 +22,6 @@ const (
maxPageSize = 1000
)
// ListOptions captures `weknora session list` flags.
type ListOptions struct {
Page int
PageSize int
@@ -40,8 +39,7 @@ type listResult struct {
}
// NewCmdList builds `weknora session list`. Paginated; defaults to page=1
// page_size=30. Mirrors `gh issue list` shape (no cursor — server is
// page-based today).
// page_size=30. No cursor — server is page-based today.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{Page: defaultPage, PageSize: defaultPageSize}
cmd := &cobra.Command{
@@ -79,7 +77,7 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
items, total, err := svc.GetSessionsByTenant(ctx, opts.Page, opts.PageSize)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list sessions")
return cmdutil.WrapHTTP(err, "list sessions")
}
if items == nil {
items = []sdk.Session{} // JSON [] not null
@@ -107,9 +105,9 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
return tw.Flush()
}
// fuzzyTime renders a server-provided timestamp string in `gh`-style "2d
// ago" form. Returns the raw input if parsing fails — better to surface
// the unknown format than to silently render "-".
// fuzzyTime renders a server-provided timestamp string in "2d ago" form.
// Returns the raw input if parsing fails — better to surface the unknown
// format than to silently render "-".
func fuzzyTime(now time.Time, ts string) string {
if ts == "" {
return "-"
+1 -1
View File
@@ -1,5 +1,5 @@
// Package sessioncmd holds `weknora session` command tree (list / view /
// delete). Mirrors `gh issue list/view/delete` for chat history.
// delete) for chat history.
//
// Package name `sessioncmd` (not `session`) so callers can `import sdk
// "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without
+5 -6
View File
@@ -14,7 +14,6 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// ViewOptions captures `weknora session view` flags.
type ViewOptions struct {
JSONOut bool
}
@@ -24,10 +23,10 @@ type ViewService interface {
GetSession(ctx context.Context, id string) (*sdk.Session, error)
}
// NewCmdView builds `weknora session view <id>`. Mirrors `gh issue view`.
// The server endpoint returns metadata only (title/description/timestamps);
// message content lives under a separate session_messages endpoint that the
// SDK doesn't currently wrap, which is why there's no --full flag.
// NewCmdView builds `weknora session view <id>`. The server endpoint
// returns metadata only (title/description/timestamps); message content
// lives under a separate session_messages endpoint that the SDK doesn't
// currently wrap, which is why there's no --full flag.
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
opts := &ViewOptions{}
cmd := &cobra.Command{
@@ -50,7 +49,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error {
s, err := svc.GetSession(ctx, id)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "get session %q", id)
return cmdutil.WrapHTTP(err, "get session %q", id)
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(s, nil))