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
+1 -1
View File
@@ -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,
+7 -13
View File
@@ -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
+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 {
+1 -1
View File
@@ -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 {
+1 -2
View File
@@ -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
+5 -9
View File
@@ -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 (
+20
View File
@@ -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
}
+2 -3
View File
@@ -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 "<n> <thing>" or "<n> <thing>s". Mirrors gh
// internal/text/text.go Pluralize signature — simple suffix "s" only;
// Pluralize returns "<n> <thing>" or "<n> <thing>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 {
+1 -2
View File
@@ -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:
//
+2 -3
View File
@@ -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