diff --git a/cli/acceptance/contract/errorcodes_test.go b/cli/acceptance/contract/errorcodes_test.go index f54577c8..12e98c4d 100644 --- a/cli/acceptance/contract/errorcodes_test.go +++ b/cli/acceptance/contract/errorcodes_test.go @@ -17,16 +17,22 @@ import ( // cmdutil.NewError(codeXxx, ...) and cmdutil.Wrapf(codeXxx, ...) and verifies // that codeXxx is registered in cmdutil.AllCodes(). // -// ClassifyHTTPError is dynamic: callers pass cmdutil.ClassifyHTTPError(err) -// as the first arg. We bridge that via cmdutil.ClassifyHTTPErrorOutputs(), -// which returns every code that the switch can return — those are added to -// the registered set so the AST scanner doesn't false-positive on them. +// ClassifyHTTPError is dynamic — callers don't pass a literal CodeXxx +// ident. Most SDK call sites go through cmdutil.WrapHTTP(err, ...) which +// the scanner skips entirely (it only inspects NewError / Wrapf selector +// names). A few sites still call ClassifyHTTPError directly to inspect +// or remap the code; those are call-expression args the scanner also +// skips. Either way, the codes those paths can yield are bridged via +// cmdutil.ClassifyHTTPErrorOutputs(), which enumerates every code the +// switch can return — added to the registered set so the AST scanner +// doesn't false-positive on them. // // Limitations (documented in spec §4.3): // - Only literal cmdutil.CodeXxx idents are detected; codes assigned to // a local variable then passed are NOT scanned (rare pattern). -// - cmdutil.ClassifyHTTPError(...) call expressions are skipped — bridge -// covers them. +// - cmdutil.WrapHTTP(...) and cmdutil.ClassifyHTTPError(...) call +// expressions are skipped — the ClassifyHTTPErrorOutputs bridge +// covers their dynamic codes. // - v0.x does not enforce a baseline diff (spec ADR-6b); v0.9 will. func TestAllReferencedCodesAreRegistered(t *testing.T) { registered := make(map[cmdutil.ErrorCode]struct{}) diff --git a/cli/cmd/api/api.go b/cli/cmd/api/api.go index 2d9c91b9..71e8b35a 100644 --- a/cli/cmd/api/api.go +++ b/cli/cmd/api/api.go @@ -1,11 +1,10 @@ // Package api implements the `weknora api` raw HTTP passthrough command. // -// Mirrors `gh api` ergonomics (verified against the gh manual): one -// positional (path) + `-X/--method` flag, default GET (auto-promoted to -// POST when a body is supplied via --data or --input). The two body- -// source flags are mutually exclusive. Default raw response body to -// stdout; --json wraps in CLI envelope. Reuses sdk.Client.Raw which -// already applies tenant + auth headers. +// Shape: one positional (path) + `-X/--method` flag, default GET (auto- +// promoted to POST when a body is supplied via --data or --input). The two +// body-source flags are mutually exclusive. Default raw response body to +// stdout; --json wraps in CLI envelope. Reuses sdk.Client.Raw which already +// applies tenant + auth headers. package api import ( @@ -26,7 +25,6 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// Options captures `weknora api` flag state. type Options struct { Method string Data string @@ -89,16 +87,16 @@ Examples: } cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied)") cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Request body as raw string (e.g. JSON)") - cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin); gh CLI parity") + cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Wrap response in JSON envelope (status/headers/body)") cmd.MarkFlagsMutuallyExclusive("data", "input") - agent.SetAgentHelp(cmd, "Raw HTTP passthrough to the WeKnora server. Use when no typed command exists for the endpoint. Headers (auth / tenant / request-id) are injected from the active context.") + agent.SetAgentHelp(cmd, "Raw HTTP passthrough to the WeKnora server. Use when no typed command exists for the endpoint. Headers (auth / tenant / request-id) are injected from the active context. Without --json the response body streams to stdout verbatim. With --json: data is {status, headers, body} where body is the parsed JSON if response is JSON, else the raw string. Non-2xx responses surface as a typed error (4xx → input.invalid_argument / auth.* / resource.not_found per ClassifyHTTPStatus; 5xx → server.error / network.error). DELETE through `weknora api` triggers exit-10 confirm just like `weknora kb delete`. Mutual exclusion: --data and --input cannot both be set (input.invalid_argument).") return cmd } // readInput reads opts.Input and returns its contents. "-" reads from -// opts.StdinReader (or iostreams.IO.In as the production default). -// Mirrors gh `api --input -` for piped JSON payloads. +// opts.StdinReader (or iostreams.IO.In as the production default) for +// piped JSON payloads. func readInput(opts *Options) ([]byte, error) { if opts.Input == "-" { r := opts.StdinReader @@ -118,7 +116,7 @@ func readInput(opts *Options) ([]byte, error) { return b, nil } -// resolveMethod implements gh's auto-method behavior: explicit -X wins; +// resolveMethod implements the auto-method behavior: explicit -X wins; // otherwise body presence promotes GET → POST. func resolveMethod(opts *Options) string { if opts.Method != "" { @@ -179,7 +177,7 @@ func runAPI(ctx context.Context, opts *Options, svc Service, method, path string if err != nil { // Transport / DNS failure (Raw never returns a typed HTTP error of its // own; non-2xx responses still surface as resp != nil, err == nil). - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "%s %s", method, path) + return cmdutil.WrapHTTP(err, "%s %s", method, path) } defer resp.Body.Close() diff --git a/cli/cmd/api/api_test.go b/cli/cmd/api/api_test.go index ddbd6ea2..7e16afe9 100644 --- a/cli/cmd/api/api_test.go +++ b/cli/cmd/api/api_test.go @@ -117,8 +117,7 @@ func TestAPI_PostWithData(t *testing.T) { } } -// TestAPI_InputFile verifies --input reads the request body from -// disk. gh CLI parity (verified against gh manual: `--input `). +// TestAPI_InputFile verifies --input reads the request body from disk. func TestAPI_InputFile(t *testing.T) { _, _ = iostreams.SetForTest(t) tmp := filepath.Join(t.TempDir(), "body.json") @@ -142,8 +141,8 @@ func TestAPI_InputFile(t *testing.T) { } } -// TestAPI_InputDash_Stdin verifies the gh-style "--input -" form: the -// payload comes from opts.StdinReader (production-default iostreams.IO.In). +// TestAPI_InputDash_Stdin verifies the "--input -" form: the payload comes +// from opts.StdinReader (production-default iostreams.IO.In). func TestAPI_InputDash_Stdin(t *testing.T) { _, _ = iostreams.SetForTest(t) var seenBody []byte diff --git a/cli/cmd/auth/list.go b/cli/cmd/auth/list.go index 8da60152..d5a74ea9 100644 --- a/cli/cmd/auth/list.go +++ b/cli/cmd/auth/list.go @@ -7,17 +7,16 @@ import ( "github.com/spf13/cobra" + "github.com/Tencent/WeKnora/cli/internal/agent" "github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/iostreams" ) -// ListOptions captures `weknora auth list` flag state. type ListOptions struct { JSONOut bool } -// listEntry is one row in the rendered list / one element of envelope.data. type listEntry struct { Name string `json:"name"` Host string `json:"host"` @@ -26,10 +25,9 @@ type listEntry struct { Current bool `json:"current"` } -// NewCmdList builds `weknora auth list`. Mirrors gh's per-host enumeration -// and lark `auth list`: render one row per registered context, marking the -// active one. Reads only ~/.config/weknora/config.yaml — no network, no -// keyring touch. +// NewCmdList builds `weknora auth list`. Per-host enumeration: render one +// row per registered context, marking the active one. Reads only +// ~/.config/weknora/config.yaml — no network, no keyring touch. func NewCmdList(f *cmdutil.Factory) *cobra.Command { opts := &ListOptions{} cmd := &cobra.Command{ @@ -41,6 +39,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { }, } cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") + agent.SetAgentHelp(cmd, "Lists configured auth contexts (name/host/user/mode/current). Read-only, no network, no keyring access. Use to confirm context names before --context or `auth login --name`.") return cmd } diff --git a/cli/cmd/auth/login.go b/cli/cmd/auth/login.go index 976647bb..dd15baeb 100644 --- a/cli/cmd/auth/login.go +++ b/cli/cmd/auth/login.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" + "github.com/Tencent/WeKnora/cli/internal/agent" "github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/format" @@ -19,10 +20,7 @@ import ( type LoginOptions struct { Host string // --host Context string // --name: context name to write into config.yaml - // (was --context in v0.0; renamed v0.1 to - // avoid shadowing the new global --context - // single-shot override flag) - WithToken bool // --with-token (read api key from stdin instead of prompting password) + WithToken bool // --with-token: read api key from stdin instead of prompting password APIKey string // populated by --with-token from stdin Email string Password string @@ -49,6 +47,7 @@ func NewCmdLogin(f *cmdutil.Factory, runF func(context.Context, *LoginOptions, * Credentials are persisted to the OS keyring when available; otherwise to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets. The named context becomes the current_context in ~/.config/weknora/config.yaml.`, + Args: cobra.NoArgs, RunE: func(c *cobra.Command, args []string) error { run := runF if run == nil { @@ -66,6 +65,7 @@ the current_context in ~/.config/weknora/config.yaml.`, cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") cmdutil.MustRequireFlag(cmd, "host") + agent.SetAgentHelp(cmd, "Authenticates and stores credentials. --with-token reads an API key from stdin (no password prompt, agent-safe). Otherwise email/password prompts fire — non-TTY callers must pipe `--with-token` or pre-set --name. Errors: auth.bad_credential on wrong password; input.invalid_argument on bad --host; input.missing_flag when --with-token has empty stdin.") return cmd } diff --git a/cli/cmd/auth/logout.go b/cli/cmd/auth/logout.go index 3ac4534a..cd21ba5a 100644 --- a/cli/cmd/auth/logout.go +++ b/cli/cmd/auth/logout.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" + "github.com/Tencent/WeKnora/cli/internal/agent" "github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/format" @@ -13,7 +14,6 @@ import ( "github.com/Tencent/WeKnora/cli/internal/secrets" ) -// LogoutOptions captures `weknora auth logout` flag state. type LogoutOptions struct { Name string // --name: target a specific context (default: current) All bool // --all: clear every context @@ -25,11 +25,9 @@ type logoutResult struct { Removed []string `json:"removed"` } -// NewCmdLogout builds `weknora auth logout`. Mirrors `gh auth logout` and -// `lark auth logout`: clears stored credentials (keyring + file fallback) and -// removes the context entry from config.yaml. No server-side revocation — -// matches gh's documented behavior ("does not revoke … users must do that -// manually"). +// NewCmdLogout builds `weknora auth logout`. Clears stored credentials +// (keyring + file fallback) and removes the context entry from config.yaml. +// No server-side revocation — local-only credential clear. func NewCmdLogout(f *cmdutil.Factory) *cobra.Command { opts := &LogoutOptions{} cmd := &cobra.Command{ @@ -53,6 +51,7 @@ accepted until it expires.`, cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") cmd.MarkFlagsMutuallyExclusive("name", "all") + agent.SetAgentHelp(cmd, "Clears local credentials only; the server-side token / api-key continues to be valid until expired or rotated. Returns data.removed: [...names]. Errors: auth.unauthenticated when no contexts configured.") return cmd } diff --git a/cli/cmd/auth/refresh.go b/cli/cmd/auth/refresh.go index b8f5bfec..c4884373 100644 --- a/cli/cmd/auth/refresh.go +++ b/cli/cmd/auth/refresh.go @@ -13,7 +13,6 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// RefreshOptions captures `weknora auth refresh` flag state. type RefreshOptions struct { Name string // --name: target context (defaults to current) JSONOut bool @@ -29,11 +28,7 @@ type refreshResult struct { // NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access // token by spending the stored refresh_token via POST /auth/refresh — -// the standard OAuth refresh-token grant. Note: `gh auth refresh` -// shares the name but has a different semantic (interactive OAuth- -// scope expansion via the browser); there's no direct gh parallel -// because gh's PAT/OAuth-app model doesn't have a short-lived -// access_token + refresh_token pair. +// the standard OAuth refresh-token grant. // // API-key contexts are rejected — they have no refresh semantic; // rotate the key via the server UI instead. diff --git a/cli/cmd/auth/status.go b/cli/cmd/auth/status.go index 48c2921d..7b6f470a 100644 --- a/cli/cmd/auth/status.go +++ b/cli/cmd/auth/status.go @@ -6,13 +6,13 @@ import ( "github.com/spf13/cobra" + "github.com/Tencent/WeKnora/cli/internal/agent" "github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/iostreams" sdk "github.com/Tencent/WeKnora/client" ) -// StatusOptions captures the (sparse) configuration of `weknora auth status`. type StatusOptions struct { JSONOut bool } @@ -37,6 +37,7 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "status", Short: "Show the active context, principal, and token state", + Args: cobra.NoArgs, RunE: func(c *cobra.Command, args []string) error { cli, err := f.Client() if err != nil { @@ -46,6 +47,7 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command { }, } cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") + agent.SetAgentHelp(cmd, "Live-checks the active credential by calling /auth/me. Returns {context, user_id, email, tenant_id, tenant_name}. Errors: auth.unauthenticated when token is invalid or missing (run `auth login` / `auth refresh`).") return cmd } @@ -55,7 +57,7 @@ func runStatus(ctx context.Context, opts *StatusOptions, f *cmdutil.Factory, svc } resp, err := svc.GetCurrentUser(ctx) if err != nil { - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "fetch current user") + return cmdutil.WrapHTTP(err, "fetch current user") } user := resp.Data.User tenant := resp.Data.Tenant diff --git a/cli/cmd/chat/chat.go b/cli/cmd/chat/chat.go index 056da3a2..e839ed29 100644 --- a/cli/cmd/chat/chat.go +++ b/cli/cmd/chat/chat.go @@ -28,6 +28,7 @@ import ( "github.com/spf13/cobra" + "github.com/Tencent/WeKnora/cli/internal/agent" "github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -35,7 +36,6 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// Options captures one `weknora chat` invocation. type Options struct { Query string KBID string @@ -102,6 +102,7 @@ Modes: cmd.Flags().StringVar(&opts.SessionID, "session-id", "", "Continue an existing chat session (skip auto-create)") cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Emit a single JSON envelope (implies --no-stream)") + agent.SetAgentHelp(cmd, "Streams an LLM answer over SSE. Agent / non-TTY callers should pass --json so the full {answer, references, session_id, assistant_message_id} envelope is emitted at completion (no partial chunks). Pass --session-id to thread follow-ups. Errors: server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.") return cmd } @@ -192,7 +193,7 @@ func runChat(ctx context.Context, opts *Options, svc chatService) error { } // Pre-stream HTTP / transport failure: route through the canonical // classifier so 401 / 404 / 5xx still surface their specific codes. - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(streamErr), streamErr, "knowledge qa stream") + return cmdutil.WrapHTTP(streamErr, "knowledge qa stream") } // SDK returned nil but we never saw a Done event — server closed the diff --git a/cli/cmd/context/add.go b/cli/cmd/context/add.go index 9b21e2b2..d8e2a375 100644 --- a/cli/cmd/context/add.go +++ b/cli/cmd/context/add.go @@ -13,7 +13,6 @@ import ( "github.com/Tencent/WeKnora/cli/internal/iostreams" ) -// AddOptions captures `weknora context add` flag state. type AddOptions struct { Host string User string @@ -31,11 +30,9 @@ type addResult struct { // NewCmdAdd builds `weknora context add`. Registers a *credentialless* // connection target — host + optional user only. Credentials for the new // context are attached separately with `weknora auth login --name `, -// reflecting gh's separation of "where" the CLI talks to (the host) and -// "how" it authenticates (the credential). kubectl's `config set-context` -// covers the same operation under a different surface convention. If you -// want one command for both, run `weknora auth login --name --host -// ` instead. +// separating "where" the CLI talks to (the host) and "how" it authenticates +// (the credential). If you want one command for both, run +// `weknora auth login --name --host ` instead. func NewCmdAdd(f *cmdutil.Factory) *cobra.Command { opts := &AddOptions{} cmd := &cobra.Command{ @@ -56,7 +53,7 @@ adds leave the current context untouched.`, }, } cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)") - cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in `context list` (optional, cosmetic only)") + cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") _ = cmd.MarkFlagRequired("host") agent.SetAgentHelp(cmd, "Adds a context. First context added auto-becomes current. Errors with resource.already_exists if name collides; input.invalid_argument if --host is not an absolute http(s) URL.") diff --git a/cli/cmd/context/context.go b/cli/cmd/context/context.go index 23c36004..11119965 100644 --- a/cli/cmd/context/context.go +++ b/cli/cmd/context/context.go @@ -1,9 +1,6 @@ // Package contextcmd holds `weknora context` command tree -// (list / add / remove / use). Uses the gh-style ` ` shape -// consistent with the rest of this CLI. kubectl exposes the same set -// of operations as flat hyphenated subcommands (`config get-contexts / -// set-context / delete-context / use-context`) — a different idiom we -// don't adopt because it would make `context` an outlier in our tree. +// (list / add / remove / use). Uses the ` ` shape +// consistent with the rest of this CLI. // // Package name `contextcmd` (not `context`) to avoid shadowing stdlib context. // The cobra Use: string is "context" — this is what users type. diff --git a/cli/cmd/context/list.go b/cli/cmd/context/list.go index 74f13542..52ab34e8 100644 --- a/cli/cmd/context/list.go +++ b/cli/cmd/context/list.go @@ -14,12 +14,10 @@ import ( "github.com/Tencent/WeKnora/cli/internal/iostreams" ) -// ListOptions captures `weknora context list` flag state. type ListOptions struct { JSONOut bool } -// listEntry is one row in the rendered table / one element of envelope.data. type listEntry struct { Name string `json:"name"` Host string `json:"host"` @@ -27,11 +25,8 @@ type listEntry struct { Current bool `json:"current"` } -// NewCmdList builds `weknora context list`. Same listing shape as gh -// `auth status` (per-host enumeration with an active marker). The kubectl -// equivalent is `config get-contexts` — same data, different surface -// convention (kubectl uses hyphenated subcommands; we use noun-verb). -// Reads only config.yaml — no network, no keyring touch. +// NewCmdList builds `weknora context list`. Per-host enumeration with an +// active marker. Reads only config.yaml — no network, no keyring touch. func NewCmdList(f *cmdutil.Factory) *cobra.Command { opts := &ListOptions{} cmd := &cobra.Command{ diff --git a/cli/cmd/context/remove.go b/cli/cmd/context/remove.go index eba5b3b9..8e87ff72 100644 --- a/cli/cmd/context/remove.go +++ b/cli/cmd/context/remove.go @@ -14,10 +14,8 @@ import ( "github.com/Tencent/WeKnora/cli/internal/secrets" ) -// RemoveOptions captures `weknora context remove` flag state. Yes is sourced -// from the global -y/--yes persistent flag (matches `kb delete`). type RemoveOptions struct { - Yes bool + Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`) JSONOut bool DryRun bool } @@ -30,12 +28,10 @@ type removeResult struct { } // NewCmdRemove builds `weknora context remove`. Drops the entry from -// config.yaml and best-effort clears keyring references. The kubectl -// equivalent is `config delete-context`; we use the noun-verb form -// instead. Removing a non-current context is low-friction (no prompt). -// Removing the *current* context triggers the lark-cli exit-10 -// confirmation protocol because subsequent commands will have no -// default connection target. +// config.yaml and best-effort clears keyring references. Removing a +// non-current context is low-friction (no prompt). Removing the *current* +// context triggers the destructive-write confirmation protocol (exit 10), +// because subsequent commands will have no default connection target. func NewCmdRemove(f *cmdutil.Factory) *cobra.Command { opts := &RemoveOptions{} cmd := &cobra.Command{ @@ -48,7 +44,7 @@ Removing the current context also clears CurrentContext — subsequent commands will error until you select another with ` + "`weknora context use `" + ` or pick one up via the global ` + "`--context`" + ` flag. Because that change is observable in every later command, removing the current context requires explicit -y/--yes -in scripted / --json invocations (exit-10 protocol; AGENTS.md).`, +in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`, Example: ` weknora context remove staging # remove non-current → no prompt weknora context remove production -y # remove current → confirm`, Args: cobra.ExactArgs(1), @@ -86,7 +82,7 @@ func runRemove(opts *RemoveOptions, name string, store secrets.Store, p prompt.P risk) } // Confirmation only fires for removing the current context — non-current - // remove matches `auth logout`'s low-friction policy. + // remove uses the same low-friction policy as `auth logout`. if wasCurrent { if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "current context", name); err != nil { return err @@ -133,7 +129,7 @@ func riskForRemove(name string, wasCurrent bool) *format.Risk { // clearContextSecrets mirrors auth/logout.go: best-effort delete every secret // slot the context references. Errors are swallowed so a missing keyring -// entry doesn't block remove (logout had the same policy from v0.2). +// entry doesn't block remove (logout has had the same policy since v0.2). func clearContextSecrets(store secrets.Store, c config.Context, name string) { if c.TokenRef != "" { _ = store.Delete(name, "access") diff --git a/cli/cmd/doc/delete.go b/cli/cmd/doc/delete.go index d9b25e13..7e1f756d 100644 --- a/cli/cmd/doc/delete.go +++ b/cli/cmd/doc/delete.go @@ -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 { diff --git a/cli/cmd/doc/delete_test.go b/cli/cmd/doc/delete_test.go index 140fdfac..de705098 100644 --- a/cli/cmd/doc/delete_test.go +++ b/cli/cmd/doc/delete_test.go @@ -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{} diff --git a/cli/cmd/doc/download.go b/cli/cmd/doc/download.go index 8be2e9fd..62582295 100644 --- a/cli/cmd/doc/download.go +++ b/cli/cmd/doc/download.go @@ -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 `. 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 ` for destination, `--clobber` for overwrite -// control. +// NewCmdDownload builds `weknora doc download `. Positional id, output +// flag, `-` sentinel for stdout. Flags: `-O, --output ` 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() diff --git a/cli/cmd/doc/list.go b/cli/cmd/doc/list.go index 2348ea83..df78858c 100644 --- a/cli/cmd/doc/list.go +++ b/cli/cmd/doc/list.go @@ -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). diff --git a/cli/cmd/doc/upload.go b/cli/cmd/doc/upload.go index cc7086a5..4c757cce 100644 --- a/cli/cmd/doc/upload.go +++ b/cli/cmd/doc/upload.go @@ -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 { diff --git a/cli/cmd/doctor/doctor.go b/cli/cmd/doctor/doctor.go index cfbb440d..30694c01 100644 --- a/cli/cmd/doctor/doctor.go +++ b/cli/cmd/doctor/doctor.go @@ -1,6 +1,6 @@ // Package doctor implements `weknora doctor` — 4-item self-check (spec §1.2). // -// Status semantics (4-tier, from larksuite/cli's pass/fail/warn/skip set): +// Status semantics (4-tier): // // ok — passed // warn — soft problem; non-blocking (e.g. server minor older than CLI, @@ -39,7 +39,6 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// Options captures the CLI flags for `weknora doctor`. type Options struct { NoCache bool Offline bool @@ -99,6 +98,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "doctor", Short: "Run 4 self-checks: base URL, auth, server version, credential storage", + Args: cobra.NoArgs, RunE: func(c *cobra.Command, _ []string) error { svc, err := buildServices(f) if err != nil { @@ -107,10 +107,10 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { cliVer, _, _ := build.Info() r := runChecks(c.Context(), opts, svc, cliVer) emit(opts, r) - // v0.2 exit-code policy: fail → exit 1 (gh / kubectl convention); - // warn / ok / skip → exit 0. SilentError suppresses both the human - // "error: ..." line and the error envelope printer, so the data - // envelope already written by emit() is the only stdout content. + // v0.2 exit-code policy: fail → exit 1; warn / ok / skip → exit 0. + // SilentError suppresses both the human "error: ..." line and the + // error envelope printer, so the data envelope already written by + // emit() is the only stdout content. if r.Summary.Failed > 0 { return cmdutil.SilentError } @@ -356,9 +356,9 @@ func emit(opts *Options, r Result) { // marker returns the human-mode prefix glyph for a check status. // -// Glyphs follow gh / kubectl convention. Agent / JSON consumers read the -// stable status string from data.checks[].status; the glyphs are presentation- -// only and never appear in --json output. +// Agent / JSON consumers read the stable status string from +// data.checks[].status; the glyphs are presentation-only and never appear +// in --json output. func marker(s Status) string { switch s { case StatusFail: diff --git a/cli/cmd/kb/create.go b/cli/cmd/kb/create.go index 2374c5ce..c7fe5366 100644 --- a/cli/cmd/kb/create.go +++ b/cli/cmd/kb/create.go @@ -14,7 +14,6 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// CreateOptions captures `weknora kb create` flags. type CreateOptions struct { Name string Description string @@ -78,7 +77,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, svc CreateService) erro created, err := svc.CreateKnowledgeBase(ctx, req) if err != nil { - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "create knowledge base") + return cmdutil.WrapHTTP(err, "create knowledge base") } if opts.JSONOut { diff --git a/cli/cmd/kb/delete.go b/cli/cmd/kb/delete.go index 117f9bc5..7e84f210 100644 --- a/cli/cmd/kb/delete.go +++ b/cli/cmd/kb/delete.go @@ -13,10 +13,8 @@ import ( "github.com/Tencent/WeKnora/cli/internal/prompt" ) -// DeleteOptions captures `weknora kb delete` flags. Yes is sourced from the -// global -y/--yes persistent flag (gh-style; see cli/cmd/root.go addGlobalFlags). type DeleteOptions struct { - Yes bool + Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go addGlobalFlags) JSONOut bool DryRun bool } @@ -33,10 +31,9 @@ type deleteResult struct { Deleted bool `json:"deleted"` } -// NewCmdDelete builds `weknora kb delete`. Mirrors `gh repo delete --yes` -// (https://cli.github.com/manual/gh_repo_delete) on the confirmation -// pattern — the global -y/--yes persistent flag is the single skip-prompt -// switch. +// NewCmdDelete builds `weknora kb delete`. The global -y/--yes persistent +// flag is the single skip-prompt switch for the destructive-write +// confirmation pattern. func NewCmdDelete(f *cmdutil.Factory) *cobra.Command { opts := &DeleteOptions{} cmd := &cobra.Command{ @@ -85,7 +82,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr } if err := svc.DeleteKnowledgeBase(ctx, id); err != nil { - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "delete knowledge base %s", id) + return cmdutil.WrapHTTP(err, "delete knowledge base %s", id) } if opts.JSONOut { diff --git a/cli/cmd/kb/delete_test.go b/cli/cmd/kb/delete_test.go index fde0b91d..6cf74ebc 100644 --- a/cli/cmd/kb/delete_test.go +++ b/cli/cmd/kb/delete_test.go @@ -69,8 +69,8 @@ func TestDelete_NotFound(t *testing.T) { func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) { // SetForTest uses bytes.Buffer for Out — IsStdoutTTY() = false. Without - // -y/--yes, exit-10 protocol fires (lark-cli skill protocol; AGENTS.md): - // the CLI must NOT silently proceed in scripted contexts. + // -y/--yes, exit-10 protocol fires (see AGENTS.md): the CLI must NOT + // silently proceed in scripted contexts. iostreams.SetForTest(t) svc := &fakeDeleteSvc{} p := &confirmPrompter{} @@ -82,7 +82,7 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) { assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code) assert.False(t, svc.called, "non-TTY without -y must not call DeleteKnowledgeBase") assert.False(t, p.asked, "non-TTY ⇒ Confirm is never invoked") - assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per lark-cli skill protocol") + assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per destructive-write protocol") } func TestDelete_JSONOutput(t *testing.T) { diff --git a/cli/cmd/kb/edit.go b/cli/cmd/kb/edit.go index 35500c9c..27b70859 100644 --- a/cli/cmd/kb/edit.go +++ b/cli/cmd/kb/edit.go @@ -13,26 +13,24 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// EditOptions captures `weknora kb edit` flags. Name/Description are *string -// so we can distinguish "unset" from "set to empty". An unset field is -// omitted from the SDK request — only fields the user passed are sent. The -// server PUT semantics are "replace everything in the request"; if we -// always sent both, an `--name` invocation would silently clear the -// description. type EditOptions struct { + // Name/Description are *string so we can distinguish "unset" from "set to + // empty". An unset field is omitted from the SDK request — only fields the + // user passed are sent. Server PUT semantics are "replace everything in the + // request"; if we always sent both, an `--name` invocation would silently + // clear the description. Name *string Description *string JSONOut bool DryRun bool } -// EditService is the narrow SDK surface this command depends on. type EditService interface { UpdateKnowledgeBase(ctx context.Context, id string, req *sdk.UpdateKnowledgeBaseRequest) (*sdk.KnowledgeBase, error) } -// NewCmdEdit builds `weknora kb edit `. Mirrors `gh repo edit`. At -// least one of --name / --description must be provided. +// NewCmdEdit builds `weknora kb edit `. At least one of --name / +// --description must be provided. func NewCmdEdit(f *cmdutil.Factory) *cobra.Command { opts := &EditOptions{} var name, desc string @@ -89,7 +87,7 @@ func runEdit(ctx context.Context, opts *EditOptions, svc EditService, id string) updated, err := svc.UpdateKnowledgeBase(ctx, id, req) if err != nil { - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "edit knowledge base %s", id) + return cmdutil.WrapHTTP(err, "edit knowledge base %s", id) } if opts.JSONOut { return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk)) diff --git a/cli/cmd/kb/empty.go b/cli/cmd/kb/empty.go index bc0a9b28..3a88825d 100644 --- a/cli/cmd/kb/empty.go +++ b/cli/cmd/kb/empty.go @@ -14,14 +14,12 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// EmptyOptions captures `weknora kb empty` flag state. type EmptyOptions struct { Yes bool JSONOut bool DryRun bool } -// EmptyService is the narrow SDK surface this command depends on. type EmptyService interface { ClearKnowledgeBaseContents(ctx context.Context, id string) (*sdk.ClearKnowledgeBaseContentsResponse, error) } @@ -32,10 +30,10 @@ type emptyResult struct { DeletedCount int `json:"deleted_count"` } -// NewCmdEmpty builds `weknora kb empty `. Wipes every -// document inside the knowledge base; the KB itself is preserved. The -// server runs the delete asynchronously and reports the count of documents -// that were enqueued for removal. +// NewCmdEmpty builds `weknora kb empty `. Wipes every document inside +// the knowledge base; the KB itself is preserved. The server runs the +// delete asynchronously and reports the count of documents that were +// enqueued for removal. func NewCmdEmpty(f *cmdutil.Factory) *cobra.Command { opts := &EmptyOptions{} cmd := &cobra.Command{ @@ -46,7 +44,7 @@ KB record (its name, description, and config) intact. The delete is async; the server reports the count of items enqueued for removal. Prompts for confirmation by default; pass -y/--yes to skip in agent / CI / -piped contexts. Without -y the CLI exits 10 (lark-cli skill protocol).`, +piped contexts. Without -y the CLI exits 10 in non-interactive mode.`, Example: ` weknora kb empty kb_abc # interactive confirm weknora kb empty kb_abc -y --json # agent-friendly`, Args: cobra.ExactArgs(1), @@ -81,7 +79,7 @@ func runEmpty(ctx context.Context, opts *EmptyOptions, svc EmptyService, p promp resp, err := svc.ClearKnowledgeBaseContents(ctx, id) if err != nil { - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "empty knowledge base %s", id) + return cmdutil.WrapHTTP(err, "empty knowledge base %s", id) } deleted := 0 if resp != nil { diff --git a/cli/cmd/kb/kb.go b/cli/cmd/kb/kb.go index 9fb0d0cc..caa6c589 100644 --- a/cli/cmd/kb/kb.go +++ b/cli/cmd/kb/kb.go @@ -1,7 +1,6 @@ // Package kb holds the `weknora kb` command tree: list / view / create / -// edit / delete / pin / unpin / clear-contents. `view` is the primary read -// verb (gh repo view convention); `get` survives as a cobra alias on the -// view subcommand for v0.0/v0.1 callers. +// edit / delete / pin / unpin / empty. Verb set follows common CRUD +// vocabulary (list/view/create/edit/delete) plus pin/unpin and empty. package kb import ( diff --git a/cli/cmd/kb/list.go b/cli/cmd/kb/list.go index 1ee57567..2a2762e6 100644 --- a/cli/cmd/kb/list.go +++ b/cli/cmd/kb/list.go @@ -17,7 +17,6 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// ListOptions captures `weknora kb list` flags. type ListOptions struct { JSONOut bool } @@ -55,7 +54,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { func runList(ctx context.Context, opts *ListOptions, svc ListService) 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") } if items == nil { items = []sdk.KnowledgeBase{} // ensure JSON [] not null diff --git a/cli/cmd/kb/pin.go b/cli/cmd/kb/pin.go index 9c0cf5c4..1d9eb17d 100644 --- a/cli/cmd/kb/pin.go +++ b/cli/cmd/kb/pin.go @@ -13,7 +13,6 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// PinOptions captures `weknora kb pin / unpin` flag state. type PinOptions struct { JSONOut bool DryRun bool @@ -79,7 +78,7 @@ func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, wa current, err := svc.GetKnowledgeBase(ctx, id) if err != nil { - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "get knowledge base %s", id) + return cmdutil.WrapHTTP(err, "get knowledge base %s", id) } if current.IsPinned == want { state := "pinned" @@ -99,7 +98,7 @@ func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, wa updated, err := svc.TogglePinKnowledgeBase(ctx, id) if err != nil { - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "%s knowledge base %s", verb, id) + return cmdutil.WrapHTTP(err, "%s knowledge base %s", verb, id) } if opts.JSONOut { return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk)) diff --git a/cli/cmd/kb/view.go b/cli/cmd/kb/view.go index 20da8314..e14e3f8d 100644 --- a/cli/cmd/kb/view.go +++ b/cli/cmd/kb/view.go @@ -14,7 +14,6 @@ import ( sdk "github.com/Tencent/WeKnora/client" ) -// ViewOptions captures `weknora kb view` flags. type ViewOptions struct { JSONOut bool } @@ -24,9 +23,7 @@ type ViewService interface { GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error) } -// NewCmdView builds `weknora kb view `. Mirrors `gh repo view` -// (https://cli.github.com/manual/gh_repo_view) — the established mainstream -// verb for single-resource reads. +// NewCmdView builds `weknora kb view `. func NewCmdView(f *cmdutil.Factory) *cobra.Command { opts := &ViewOptions{} cmd := &cobra.Command{ @@ -49,7 +46,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command { func runView(ctx context.Context, opts *ViewOptions, svc ViewService, id string) error { kb, err := svc.GetKnowledgeBase(ctx, id) if err != nil { - return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "get knowledge base %q", id) + return cmdutil.WrapHTTP(err, "get knowledge base %q", id) } if opts.JSONOut { return format.WriteEnvelope(iostreams.IO.Out, format.Success(kb, nil)) diff --git a/cli/cmd/link/link.go b/cli/cmd/link/link.go index b4fe89d0..1a0a9135 100644 --- a/cli/cmd/link/link.go +++ b/cli/cmd/link/link.go @@ -1,9 +1,8 @@ // Package linkcmd implements `weknora link` — binds the current working // directory to a knowledge base by writing .weknora/project.yaml. Always -// overwrites an existing link silently, mirroring `vercel link` / -// `netlify link` / `kubectl apply` rather than `git init`'s -// refuse-if-exists posture. The cobra Long: text covers the user-facing -// modes (--kb / TTY / non-TTY). +// overwrites an existing link silently rather than refusing when one is +// already present. The cobra Long: text covers the user-facing modes +// (--kb / TTY / non-TTY). package linkcmd import ( @@ -22,7 +21,6 @@ import ( "github.com/Tencent/WeKnora/cli/internal/projectlink" ) -// Options captures `weknora link` flags. type Options struct { Context string // --context: record a specific context instead of the active one KB string // --kb: KB UUID or name; empty triggers interactive prompt on TTY @@ -164,7 +162,7 @@ func resolveKB(ctx context.Context, opts *Options, f *cmdutil.Factory) (string, func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory) (string, string, error) { kbs, err := svc.ListKnowledgeBases(ctx) if err != nil { - return "", "", cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list knowledge bases") + return "", "", cmdutil.WrapHTTP(err, "list knowledge bases") } if len(kbs) == 0 { return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active context; create one first") diff --git a/cli/cmd/root.go b/cli/cmd/root.go index 2086cadb..4ef5daf0 100644 --- a/cli/cmd/root.go +++ b/cli/cmd/root.go @@ -144,9 +144,9 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`, SilenceUsage: true, SilenceErrors: true, // Version makes cobra auto-register a `--version` global flag that - // prints this string. Mainstream CLIs (gh / kubectl / aws / gcloud) - // all accept both `--version` and a `version` subcommand; the - // subcommand still owns the richer `--json` envelope output. + // prints this string. We accept both `--version` and a `version` + // subcommand; the subcommand still owns the richer `--json` envelope + // output. Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date), PersistentPreRun: func(c *cobra.Command, args []string) { // Propagate the global --context flag into the Factory for this @@ -161,8 +161,8 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`, addGlobalFlags(cmd) cmd.SetHelpFunc(agentAwareHelpFunc(cmd.HelpFunc())) // Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps - // them to exit 2 (gh-style). "unknown command" errors are detected by - // message prefix in Execute() since cobra emits them as plain errors. + // them to exit 2. "unknown command" errors are detected by message prefix + // in Execute() since cobra emits them as plain errors. cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error { return cmdutil.NewFlagError(err) }) @@ -193,8 +193,8 @@ func addGlobalFlags(cmd *cobra.Command) { // agentAwareHelpFunc wraps cobra's default help to append the AI agent guidance // (Annotations[agent.AIAgentHelpKey]) only when an AI coding agent env var is -// detected (CLAUDECODE / CURSOR_AGENT). Help-only render — no behavior switch. -// Stripe pkg/cmd/templates.go pattern, but reduced from mode-switch (v0.2 ADR-3). +// detected (CLAUDECODE / CURSOR_AGENT). Help-only render — no behavior switch +// (v0.2 ADR-3). func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command, []string) { return func(c *cobra.Command, args []string) { orig(c, args) @@ -219,6 +219,7 @@ func newVersionCmd(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "version", Short: "Show CLI build metadata", + Args: cobra.NoArgs, RunE: func(c *cobra.Command, args []string) error { v, commit, date := build.Info() if jsonOut { diff --git a/cli/cmd/search/chunks.go b/cli/cmd/search/chunks.go index 8684fc6e..828e93cf 100644 --- a/cli/cmd/search/chunks.go +++ b/cli/cmd/search/chunks.go @@ -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 "" --kb `. -// 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 ""`, 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 { diff --git a/cli/cmd/search/chunks_test.go b/cli/cmd/search/chunks_test.go index 7236e078..094f7025 100644 --- a/cli/cmd/search/chunks_test.go +++ b/cli/cmd/search/chunks_test.go @@ -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{ diff --git a/cli/cmd/search/docs.go b/cli/cmd/search/docs.go index 4a2241d2..acfd1683 100644 --- a/cli/cmd/search/docs.go +++ b/cli/cmd/search/docs.go @@ -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 ""`, 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 { diff --git a/cli/cmd/search/docs_test.go b/cli/cmd/search/docs_test.go index 2699ef27..0ac93211 100644 --- a/cli/cmd/search/docs_test.go +++ b/cli/cmd/search/docs_test.go @@ -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) } diff --git a/cli/cmd/search/kb.go b/cli/cmd/search/kb.go index bfd102cd..1d6ca2f3 100644 --- a/cli/cmd/search/kb.go +++ b/cli/cmd/search/kb.go @@ -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 ""` — 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 ""`, 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 { diff --git a/cli/cmd/search/kb_test.go b/cli/cmd/search/kb_test.go index 3b848edf..e0b2e9e2 100644 --- a/cli/cmd/search/kb_test.go +++ b/cli/cmd/search/kb_test.go @@ -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"}, diff --git a/cli/cmd/search/search.go b/cli/cmd/search/search.go index b2397c91..0dec82ea 100644 --- a/cli/cmd/search/search.go +++ b/cli/cmd/search/search.go @@ -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 "" --kb X hybrid retrieval (RAG search) search kb "" find KBs by name / description diff --git a/cli/cmd/search/sessions.go b/cli/cmd/search/sessions.go index ee4bb214..cf29f8fc 100644 --- a/cli/cmd/search/sessions.go +++ b/cli/cmd/search/sessions.go @@ -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 ""`, 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) { diff --git a/cli/cmd/session/delete.go b/cli/cmd/session/delete.go index a08df052..0ed32912 100644 --- a/cli/cmd/session/delete.go +++ b/cli/cmd/session/delete.go @@ -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 { diff --git a/cli/cmd/session/list.go b/cli/cmd/session/list.go index 00a5b3fd..79c5e281 100644 --- a/cli/cmd/session/list.go +++ b/cli/cmd/session/list.go @@ -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 "-" diff --git a/cli/cmd/session/session.go b/cli/cmd/session/session.go index 1a96f70e..43202c08 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). 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 diff --git a/cli/cmd/session/view.go b/cli/cmd/session/view.go index 4e13751a..53187388 100644 --- a/cli/cmd/session/view.go +++ b/cli/cmd/session/view.go @@ -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 `. 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 `. 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)) diff --git a/cli/internal/agent/annotations.go b/cli/internal/agent/annotations.go index 6ee350d2..4428ef0c 100644 --- a/cli/internal/agent/annotations.go +++ b/cli/internal/agent/annotations.go @@ -8,7 +8,7 @@ import ( // AIAgentHelpKey is the cobra Annotation key used to attach an AI-agent-specific // help blurb to a command. The blurb is appended to --help output only when -// agent mode is active. Mirrors Stripe's pkg/cmd/templates.go AIAgentHelpAnnotationKey. +// agent mode is active. const AIAgentHelpKey = "ai_agent_help" // FormatAgentGuidance returns the agent-targeted help text registered on cmd, diff --git a/cli/internal/agent/detect.go b/cli/internal/agent/detect.go index d36c697a..e7cc285c 100644 --- a/cli/internal/agent/detect.go +++ b/cli/internal/agent/detect.go @@ -2,15 +2,11 @@ // trigger AGENT-targeted help text) and per-command help annotations. // // v0.2 ADR-3: removed the omnibus `--agent` flag + ApplyAgentSugar -// mode-switch as over-design. Mainstream CLIs (gh / kubectl / aws / docker / -// flyctl) deliberately don't have a single mode-switch flag; per-command -// --json + TTY auto-detect cover 95% of cases. WeKnora now follows that -// convention. See cli/AGENTS.md for the full agent contract. +// mode-switch as over-design. Per-command --json + TTY auto-detect cover +// 95% of cases. See cli/AGENTS.md for the full agent contract. // // What remains here: a small env-detect for known coding agents, used purely -// to render the AGENT-targeted help section (no behavior change). Patterned -// after Stripe's DetectAIAgent (https://github.com/stripe/stripe-cli/tree/master/pkg/useragent), -// which Stripe uses only for User-Agent telemetry tagging. +// to render the AGENT-targeted help section (no behavior change). package agent import "os" @@ -20,12 +16,10 @@ import "os" type AIAgentName string // aiAgentEnvs maps environment variable presence to a coding agent name. -// Cropped to the entries the Stripe CLI also recognizes (verified against -// stripe-cli/pkg/useragent/useragent.go). The earlier 7-entry list (CODEX_*, -// AIDER_PROMPT, CONTINUE_GLOBAL_DIR, OPENCODE_RUNNING, GEMINICODER_PROFILE) -// did not have official agent docs backing those env names; removed in v0.2 -// to avoid maintaining an unverified hardcoded list. New entries should -// document the source URL. +// The earlier 7-entry list (CODEX_*, AIDER_PROMPT, CONTINUE_GLOBAL_DIR, +// OPENCODE_RUNNING, GEMINICODER_PROFILE) did not have official agent docs +// backing those env names; removed in v0.2 to avoid maintaining an +// unverified hardcoded list. New entries should document the source URL. var aiAgentEnvs = []struct { env string name AIAgentName diff --git a/cli/internal/cmdutil/confirm.go b/cli/internal/cmdutil/confirm.go index 317ea5e0..ee167229 100644 --- a/cli/internal/cmdutil/confirm.go +++ b/cli/internal/cmdutil/confirm.go @@ -20,10 +20,9 @@ import ( // prompter error → returns CodeInputMissingFlag (rare; stdin closed // mid-prompt) // -// The non-TTY branch is the lark-cli skill protocol: high-risk writes +// The non-TTY branch is the destructive-write protocol: high-risk writes // always require explicit confirmation in scripted contexts, never silent -// proceed. See cli/AGENTS.md "Exit codes" and -// https://github.com/larksuite/cli/blob/main/skills/lark-shared/SKILL.md. +// proceed. See cli/AGENTS.md "Exit codes". // // `yes` should be sourced from the persistent global -y/--yes flag. // diff --git a/cli/internal/cmdutil/dryrun.go b/cli/internal/cmdutil/dryrun.go index ae29b9db..b8a5052c 100644 --- a/cli/internal/cmdutil/dryrun.go +++ b/cli/internal/cmdutil/dryrun.go @@ -13,8 +13,6 @@ import ( // of its parents. Write commands check this and skip the SDK call, returning // an envelope with dry_run=true that describes the action that would have // run. Read commands ignore --dry-run (no side effect to preview). -// -// Pattern from lark-cli's `--dry-run` (cmd/api/api.go DryRun field). func IsDryRun(cmd *cobra.Command) bool { if cmd == nil { return false diff --git a/cli/internal/cmdutil/errors.go b/cli/internal/cmdutil/errors.go index fbb9302c..253ba15c 100644 --- a/cli/internal/cmdutil/errors.go +++ b/cli/internal/cmdutil/errors.go @@ -33,7 +33,7 @@ const ( CodeInputMissingFlag ErrorCode = "input.missing_flag" // CodeInputConfirmationRequired marks a high-risk write that has no // interactive UI (non-TTY or --json) and was invoked without -y/--yes. - // Mapped to exit code 10 (lark-cli skill protocol — see cli/AGENTS.md). + // Mapped to exit code 10 (see cli/AGENTS.md). // Agents must surface the envelope to the user and only retry with -y // after explicit human approval; never auto-retry. CodeInputConfirmationRequired ErrorCode = "input.confirmation_required" @@ -126,8 +126,21 @@ func Wrapf(code ErrorCode, cause error, format string, args ...any) *Error { return &Error{Code: code, Message: fmt.Sprintf(format, args...), Cause: cause} } +// WrapHTTP wraps a transport / response error with the typed code derived +// from its HTTP shape (404 → resource.not_found, 401 → auth.unauthenticated, +// non-HTTP → network.error, …). Shortcut for the universal pattern +// `Wrapf(ClassifyHTTPError(err), err, format, args...)` used by every SDK +// call site — single source for the wrap-and-classify policy. +// +// Use this for any error returned from a wire call. Stays paired with +// ClassifyHTTPErrorOutputs() in the acceptance/contract test, which +// enumerates the codes this helper can yield. +func WrapHTTP(cause error, format string, args ...any) *Error { + return Wrapf(ClassifyHTTPError(cause), cause, format, args...) +} + // FlagError signals user-visible flag/argument problems; the root command -// prints help on top of the message and exits 2 (gh-style). +// prints help on top of the message and exits 2. type FlagError struct{ err error } func (e *FlagError) Error() string { return e.err.Error() } @@ -143,7 +156,7 @@ var SilentError = errors.New("silent error (handled)") // CancelError marks a user-cancelled operation (Ctrl-C / "no" at confirm). var CancelError = errors.New("operation cancelled") -// Typed predicates — use these instead of comparing ErrorCode strings (Stripe pattern). +// Typed predicates — use these instead of comparing ErrorCode strings. // They walk the error chain so wrapped errors still match. // IsAuthError matches any auth.* code. diff --git a/cli/internal/cmdutil/exit.go b/cli/internal/cmdutil/exit.go index 3e753c72..2a2aa1e4 100644 --- a/cli/internal/cmdutil/exit.go +++ b/cli/internal/cmdutil/exit.go @@ -9,17 +9,20 @@ import ( ) // ExitCode maps an error to the documented CLI exit code (spec §2.4 + ADR-3). -// Mirrors gh / Stripe / lark-cli convention: // - 0 success -// - 1 generic / unknown typed error -// - 2 flag / argument problem +// - 1 generic / unknown typed error — fallback for: resource.already_exists, +// resource.locked, local.* (config_corrupt / keychain_denied / file_io / +// context_not_found / kb_id_required / kb_not_found / projectlink_corrupt / +// user_aborted / upload_file_not_found), mcp.*, server.session_create_failed, +// sse.stream_aborted, and any code outside the named buckets below +// - 2 flag / argument problem (cobra parse / unknown subcommand) // - 3 auth.* // - 4 resource.not_found // - 5 input.* (other than confirmation_required) // - 6 server.rate_limited -// - 7 server.* (other) / network.* +// - 7 server.* (other than rate_limited/session_create_failed) / network.* // - 10 input.confirmation_required — high-risk write needs explicit -y -// (lark-cli skill protocol; see cli/AGENTS.md) +// (see cli/AGENTS.md) // - 130 SIGINT (handled by Go runtime, not this function) func ExitCode(err error) int { if err == nil { @@ -120,9 +123,9 @@ func ToErrorBody(err error) *format.ErrorBody { } body.Retryable = typed.Retryable // Surface the wrapped cause so agents see the actual server / SDK - // error string, not just the wrap message ("hybrid search"). Stripe's - // envelope does the same — the human's printed line and the JSON - // envelope both end with the underlying problem. + // error string, not just the wrap message ("hybrid search"). The + // human's printed line and the JSON envelope both end with the + // underlying problem. if typed.Cause != nil { body.Message = typed.Message + ": " + typed.Cause.Error() } diff --git a/cli/internal/cmdutil/factory.go b/cli/internal/cmdutil/factory.go index cda1eb38..208d6b44 100644 --- a/cli/internal/cmdutil/factory.go +++ b/cli/internal/cmdutil/factory.go @@ -35,7 +35,7 @@ import ( // // IOStreams is intentionally NOT a Factory closure — it is the package singleton // iostreams.IO. The bar to add a new closure is at least 2 commands sharing the -// same dependency; resist factory bloat (gh CLI cautionary tale). +// same dependency; resist factory bloat. // // Client returns a *sdk.Client (the WeKnora SDK). Commands that want narrow // service interfaces (per ADR-4) declare them in their own files and let the @@ -56,13 +56,21 @@ type Factory struct { // New constructs a production Factory wired to real config / SDK client. // // All closures are lazy: invoking --help, version, or shell completion runs -// none of them. The Secrets closure memoizes via sync.Once so the keyring -// probe happens at most once per process. +// none of them. Client and Secrets closures memoize via sync.Once so the +// SDK client is built (and the keyring is probed) at most once per process, +// even when Factory.ResolveKB internally calls f.Client() before the +// command's RunE calls it again — without this, name-resolved --kb paths +// would build two clients with two AuthRetryTransports holding independent +// token state. func New() *Factory { var ( secretsOnce sync.Once secretsStore secrets.Store secretsErr error + + clientOnce sync.Once + client *sdk.Client + clientErr error ) f := &Factory{} f.Config = func() (*config.Config, error) { @@ -81,7 +89,10 @@ func New() *Factory { } return cfg, nil } - f.Client = func() (*sdk.Client, error) { return buildClient(f) } + f.Client = func() (*sdk.Client, error) { + clientOnce.Do(func() { client, clientErr = buildClient(f) }) + return client, clientErr + } f.Prompter = func() prompt.Prompter { if iostreams.IO.IsStdoutTTY() && iostreams.IO.IsStderrTTY() { return prompt.NewTTYPrompter() @@ -160,17 +171,16 @@ func buildClient(f *Factory) (*sdk.Client, error) { // tenant from the credential itself (JWT claim or API key prefix); the // header is only meaningful for explicit cross-tenant switching by users // with CanAccessAllTenants. Auto-mirroring the persisted tenant from config - // breaks that contract — gh / gcloud / Stripe CLIs all require an explicit - // flag (`--tenant=N` is the planned v0.1 entry point) before sending it. - // `tenant_id` stays in config for `auth status` display only. + // breaks that contract — explicit flags (`--tenant=N` is the planned v0.1 + // entry point) are required before sending it. `tenant_id` stays in config + // for `auth status` display only. return sdk.NewClient(ctx.Host, opts...), nil } // ResolveKB returns the active KB id for the running command, applying the // 4-level fallback chain (highest to lowest): // 1. --kb flag (kb_<...> id passed through; anything else resolved via -// ListKnowledgeBases as a name → id lookup; mirrors gcloud --project's -// id-or-name auto-detection) +// ListKnowledgeBases as a name → id lookup) // 2. WEKNORA_KB_ID env (always an explicit id) // 3. .weknora/project.yaml (walk-up from cwd) // 4. error: kb required diff --git a/cli/internal/cmdutil/host.go b/cli/internal/cmdutil/host.go index a212a26d..dd6f0f5f 100644 --- a/cli/internal/cmdutil/host.go +++ b/cli/internal/cmdutil/host.go @@ -6,12 +6,12 @@ import ( "strings" ) -// NormalizeHost validates and canonicalizes a `--host` / `--hostname` value. -// The returned string is trimmed of trailing slashes. Returns a typed -// CLI error (CodeInputMissingFlag for empty, CodeInputInvalidArgument for -// malformed) so callers can `return cmdutil.NormalizeHost(...)` directly. +// NormalizeHost validates and canonicalizes a `--host` value. Trailing +// slashes are trimmed. Every failure path returns CodeInputInvalidArgument — +// a present-but-empty flag is treated as a bad value, not as a missing flag +// (cobra's required-flag layer is what catches the absent case). // -// Rules (matches gh CLI's URL handling): +// Rules: // - non-empty // - scheme is http or https // - URL parses diff --git a/cli/internal/cmdutil/kb.go b/cli/internal/cmdutil/kb.go index 99983a4b..7c2377c9 100644 --- a/cli/internal/cmdutil/kb.go +++ b/cli/internal/cmdutil/kb.go @@ -14,8 +14,8 @@ import ( var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) // IsKBID reports whether s looks like a KB id. Used by Factory.ResolveKB and -// any caller that accepts a single id-or-name selector value — same pattern -// gcloud uses for --project (id vs name auto-detection). +// any caller that accepts a single id-or-name selector value (id vs name +// auto-detection). func IsKBID(s string) bool { return uuidPattern.MatchString(s) } // KBLister is the narrow SDK surface ResolveKBNameToID depends on. The @@ -43,7 +43,7 @@ func ResolveKBFlag(ctx context.Context, lister KBLister, raw string) (string, er func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) { kbs, err := lister.ListKnowledgeBases(ctx) if err != nil { - return "", Wrapf(ClassifyHTTPError(err), err, "list knowledge bases") + return "", WrapHTTP(err, "list knowledge bases") } for _, kb := range kbs { if kb.Name == name { diff --git a/cli/internal/compat/compat.go b/cli/internal/compat/compat.go index ae3aeef4..9d809aa9 100644 --- a/cli/internal/compat/compat.go +++ b/cli/internal/compat/compat.go @@ -61,7 +61,7 @@ func parseSemver(s string) (major, minor int, ok bool) { if s == "" || s == "(unknown)" { return 0, 0, false } - // 接受 "v" 前缀 (kubectl / gh 同款宽容):git describe + Tencent tag 都带 v + // 接受 "v" 前缀:git describe + Tencent tag 都带 v s = strings.TrimPrefix(s, "v") // 去掉 prerelease/build metadata if i := strings.IndexAny(s, "-+"); i >= 0 { diff --git a/cli/internal/compat/version_check.go b/cli/internal/compat/version_check.go index 958dbd20..b200a2d8 100644 --- a/cli/internal/compat/version_check.go +++ b/cli/internal/compat/version_check.go @@ -1,8 +1,7 @@ // Package compat probes server `/system/info` and decides client-server // version skew level. Used by `weknora doctor` 的 server_version 检查项。 // -// Mirrors gh internal/update/update.go cache pattern (24h TTL state file) -// and kubectl pkg/version/skew_warning.go three-tier compat semantics +// 24h TTL state file cache, three-tier compat semantics // (major-mismatch=hard / minor-mismatch=soft / equal=ok). package compat diff --git a/cli/internal/format/envelope.go b/cli/internal/format/envelope.go index d0c60ed2..588b3678 100644 --- a/cli/internal/format/envelope.go +++ b/cli/internal/format/envelope.go @@ -11,10 +11,9 @@ import ( // Envelope is the canonical success/failure shape returned by every command. // -// v0.2 ADR-3 added Notice / Risk / DryRun, borrowed from lark-cli's envelope -// (https://github.com/larksuite/cli/blob/main/internal/output/envelope.go). -// All three are absent on read-only commands; write commands populate Risk -// even on success so agents can record what action ran. +// v0.2 ADR-3 added Notice / Risk / DryRun. All three are absent on +// read-only commands; write commands populate Risk even on success so +// agents can record what action ran. type Envelope struct { OK bool `json:"ok"` Data any `json:"data,omitempty"` @@ -56,8 +55,7 @@ type VersionSkewNotice struct { // Risk classifies the operation the user is performing — not the error. // Agents inspect this on every envelope. When Level == RiskHighRiskWrite and // the operation requires confirmation (no -y), the CLI exits 10. See -// cli/AGENTS.md "Exit codes" and lark-cli's -// skills/lark-shared/SKILL.md. +// cli/AGENTS.md "Exit codes". type Risk struct { Level RiskLevel `json:"level"` Action string `json:"action,omitempty"` @@ -76,9 +74,7 @@ type Meta struct { } // RiskLevel classifies an operation. Agents use this to decide whether to -// retry, require explicit user approval, or stop. Values are aligned with -// lark-cli's risk taxonomy -// (https://github.com/larksuite/cli/blob/main/internal/output/envelope.go). +// retry, require explicit user approval, or stop. type RiskLevel string const ( diff --git a/cli/internal/text/displayname.go b/cli/internal/text/displayname.go new file mode 100644 index 00000000..6877ea00 --- /dev/null +++ b/cli/internal/text/displayname.go @@ -0,0 +1,20 @@ +package text + +// KnowledgeDisplayName picks the most informative human label for a +// knowledge entry. File-uploads use FileName; URL / text entries fall +// back to Title; the ID is the last-resort placeholder so a table cell +// is never empty. Single source for the ordering — `weknora doc list` +// and `weknora search docs` both call this so a Knowledge renders +// identically in either command. +// +// Takes the three fields directly rather than `sdk.Knowledge` so this +// package stays free of SDK imports. +func KnowledgeDisplayName(fileName, title, id string) string { + if fileName != "" { + return fileName + } + if title != "" { + return title + } + return id +} diff --git a/cli/internal/text/pluralize.go b/cli/internal/text/pluralize.go index 3cab2df8..13166211 100644 --- a/cli/internal/text/pluralize.go +++ b/cli/internal/text/pluralize.go @@ -1,11 +1,10 @@ -// Package text holds gh-style string helpers for human-readable CLI output. +// Package text holds string helpers for human-readable CLI output. // All functions are pure (no I/O, no time.Now), making them trivially testable. package text import "fmt" -// Pluralize returns " " or " s". Mirrors gh -// internal/text/text.go Pluralize signature — simple suffix "s" only; +// Pluralize returns " " or " s". Simple suffix "s" only; // irregular forms (person/people) are not supported (add PluralizeIrregular // when needed, per spec §2.1). func Pluralize(n int, thing string) string { diff --git a/cli/internal/text/truncate.go b/cli/internal/text/truncate.go index 1949c974..03afc749 100644 --- a/cli/internal/text/truncate.go +++ b/cli/internal/text/truncate.go @@ -5,8 +5,7 @@ import "github.com/mattn/go-runewidth" const ellipsis = "…" // Truncate cuts s to at most maxWidth display columns (CJK / emoji 占 2 列; -// ASCII 占 1 列), appending "…" if truncated. Mirrors gh -// internal/text/text.go Truncate semantics — display width, not rune count. +// ASCII 占 1 列), appending "…" if truncated. Display width, not rune count. // // Edge cases: // diff --git a/cli/internal/xdg/xdg.go b/cli/internal/xdg/xdg.go index b760927f..7f66dc15 100644 --- a/cli/internal/xdg/xdg.go +++ b/cli/internal/xdg/xdg.go @@ -21,9 +21,8 @@ import ( // under $HOME used when the env var is unset (".config" / ".cache" / etc.). // parts join under "weknora/" inside the chosen root. // -// Honors the XDG vars on every OS (CLI convention — gh / kubectl / helm all -// do this even on macOS, where os.UserConfigDir would otherwise return -// ~/Library/Application Support). +// Honors the XDG vars on every OS, even macOS — where os.UserConfigDir +// would otherwise return ~/Library/Application Support. func Path(envVar, fallbackDir string, parts ...string) (string, error) { if x := os.Getenv(envVar); x != "" { return filepath.Join(append([]string{x, "weknora"}, parts...)...), nil