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

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

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

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

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

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

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

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

  Triggered by an audit round that surfaced several false / fragile
  parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no
  --name flag; "matches gcloud `--project` id-or-name" — gcloud's
  --project accepts ID only). Rather than fix them one by one, the
  whole category of in-comment external-project references was
  stripped uniformly.
This commit is contained in:
nullkey
2026-05-12 23:42:20 +08:00
committed by lyingbug
parent 73a88b4f0a
commit 5adcedf170
58 changed files with 274 additions and 314 deletions
+2 -3
View File
@@ -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.
//
-2
View File
@@ -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
+16 -3
View File
@@ -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.
+11 -8
View File
@@ -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()
}
+19 -9
View File
@@ -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
+5 -5
View File
@@ -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
+3 -3
View File
@@ -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 {