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:
@@ -13,10 +13,8 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
)
|
||||
|
||||
// DeleteOptions captures `weknora doc delete` flags. Yes is sourced from the
|
||||
// global -y/--yes persistent flag (gh-style; see cli/cmd/root.go).
|
||||
type DeleteOptions struct {
|
||||
Yes bool
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go)
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
}
|
||||
@@ -33,8 +31,8 @@ type deleteResult struct {
|
||||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
|
||||
// NewCmdDelete builds `weknora doc delete`. Mirrors `gh repo delete --yes`
|
||||
// confirmation pattern via the global -y/--yes persistent flag.
|
||||
// NewCmdDelete builds `weknora doc delete`. Confirmation routed through
|
||||
// the global -y/--yes persistent flag.
|
||||
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &DeleteOptions{}
|
||||
cmd := &cobra.Command{
|
||||
@@ -81,7 +79,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr
|
||||
}
|
||||
|
||||
if err := svc.DeleteKnowledge(ctx, id); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete document %s", id)
|
||||
return cmdutil.WrapHTTP(err, "delete document %s", id)
|
||||
}
|
||||
|
||||
if opts.JSONOut {
|
||||
|
||||
@@ -129,9 +129,9 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestDelete_NoYes_NonTTY_RequiresConfirmation: when stdout isn't a TTY
|
||||
// (typical agent pipe / CI), the lark-cli skill protocol requires explicit
|
||||
// -y/--yes. The CLI exits 10 with input.confirmation_required, never
|
||||
// silently proceeds. See cli/AGENTS.md "Exit codes".
|
||||
// (typical agent pipe / CI), the destructive-write protocol requires
|
||||
// explicit -y/--yes. The CLI exits 10 with input.confirmation_required,
|
||||
// never silently proceeds. See cli/AGENTS.md "Exit codes".
|
||||
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
// DownloadOptions captures `weknora doc download` flag state.
|
||||
type DownloadOptions struct {
|
||||
Output string // --output / -O: target path, "-" for stdout, "" for server-suggested filename
|
||||
Clobber bool // --clobber: allow overwrite of an existing file
|
||||
@@ -28,11 +27,9 @@ type DownloadService interface {
|
||||
OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error)
|
||||
}
|
||||
|
||||
// NewCmdDownload builds `weknora doc download <id>`. Borrows shape from
|
||||
// `gh release download` — positional id, output flag, `-` sentinel for
|
||||
// stdout. Flag names match gh canon verified against the gh manual:
|
||||
// `-O, --output <file>` for destination, `--clobber` for overwrite
|
||||
// control.
|
||||
// NewCmdDownload builds `weknora doc download <id>`. Positional id, output
|
||||
// flag, `-` sentinel for stdout. Flags: `-O, --output <file>` for
|
||||
// destination, `--clobber` for overwrite control.
|
||||
func NewCmdDownload(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &DownloadOptions{}
|
||||
cmd := &cobra.Command{
|
||||
@@ -67,7 +64,7 @@ Existing files are NOT overwritten unless --clobber is passed.`,
|
||||
func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService, id string) error {
|
||||
suggested, body, err := svc.OpenKnowledgeFile(ctx, id)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "download %s", id)
|
||||
return cmdutil.WrapHTTP(err, "download %s", id)
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
|
||||
+3
-16
@@ -17,7 +17,6 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// ListOptions captures `weknora doc list` flags.
|
||||
type ListOptions struct {
|
||||
Page int
|
||||
PageSize int
|
||||
@@ -77,7 +76,7 @@ backend storage order is not guaranteed and varies between deployments.`,
|
||||
// value into the command's flag set.
|
||||
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)")
|
||||
cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)")
|
||||
cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page")
|
||||
cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page (1..1000)")
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
agent.SetAgentHelp(cmd, "Lists docs in the resolved KB. Returns data: {items, page, page_size, total, kb_id}; pass --kb when not running inside a project.")
|
||||
return cmd
|
||||
@@ -98,7 +97,7 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService, kbID strin
|
||||
}
|
||||
items, total, err := svc.ListKnowledge(ctx, kbID, opts.Page, opts.PageSize, "")
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list documents")
|
||||
return cmdutil.WrapHTTP(err, "list documents")
|
||||
}
|
||||
if items == nil {
|
||||
items = []sdk.Knowledge{} // ensure JSON [] not null
|
||||
@@ -130,25 +129,13 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService, kbID strin
|
||||
fmt.Fprintln(tw, "ID\tNAME\tSTATUS\tSIZE\tUPDATED")
|
||||
now := time.Now()
|
||||
for _, k := range items {
|
||||
name := text.Truncate(40, displayName(k))
|
||||
name := text.Truncate(40, text.KnowledgeDisplayName(k.FileName, k.Title, k.ID))
|
||||
updated := text.FuzzyAgo(now, k.UpdatedAt)
|
||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", k.ID, name, k.ParseStatus, formatSize(k.FileSize), updated)
|
||||
}
|
||||
return tw.Flush()
|
||||
}
|
||||
|
||||
// displayName picks the most informative human label for a knowledge entry.
|
||||
// File-uploads use FileName; URL / text entries fall back to Title.
|
||||
func displayName(k sdk.Knowledge) string {
|
||||
if k.FileName != "" {
|
||||
return k.FileName
|
||||
}
|
||||
if k.Title != "" {
|
||||
return k.Title
|
||||
}
|
||||
return k.ID
|
||||
}
|
||||
|
||||
// formatSize renders a byte count as a short human string (KB / MB).
|
||||
// Kept tiny on purpose — go-humanize would pull a transitive dep just for one
|
||||
// column. A "-" placeholder hides zero-size entries (URL / text).
|
||||
|
||||
@@ -19,7 +19,6 @@ import (
|
||||
// and "wechat" (mini-program). The server uses this only for analytics.
|
||||
const uploadChannel = "api"
|
||||
|
||||
// UploadOptions captures `weknora doc upload` flags.
|
||||
type UploadOptions struct {
|
||||
Name string
|
||||
Recursive bool // --recursive: positional arg is a directory; walk + upload each match
|
||||
@@ -132,7 +131,7 @@ func runUpload(ctx context.Context, opts *UploadOptions, svc UploadService, kbID
|
||||
|
||||
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, nil /*metadata*/, nil /*enableMultimodel*/, opts.Name, uploadChannel)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "upload %s", path)
|
||||
return cmdutil.WrapHTTP(err, "upload %s", path)
|
||||
}
|
||||
|
||||
if opts.JSONOut {
|
||||
|
||||
Reference in New Issue
Block a user