Files
Enterprise-Knowledge-Base/cli/internal/cmdutil/factory.go
T
nullkey 8bcbf5a154 refactor(cli): align command surface with mainstream conventions
Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe /
flyctl / terraform / vercel / netlify / lark) drove five alignment
fixes — each replaces a weknora-only design choice that mainstream CLIs
do not share. No backwards-compat shims; the CLI has no v0.1 users yet.

1. Single --kb flag (was --kb-id + --kb mutually exclusive)

   Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs
   "by name". Single flag (gh -R, gcloud --project) or positional
   (kubectl, stripe, terraform). Closest analog — gcloud --project —
   collapses identifier types onto one flag.

   Now: every command exposes one --kb flag; client-side prefix
   detection (cmdutil.IsKBID looks for "kb_") routes id-form values
   through directly and name-form values through ListKnowledgeBases.
   Mirrors gcloud --project's id-or-name auto-detection.

   Touched: search, chat, doc list / upload / delete, link.
   Factory.ResolveKB chain trimmed from 5 levels to 4.

2. link supersedes init

   Survey: only vercel and netlify ship both `init` AND `link` as
   siblings, and they keep them semantically distinct. weknora's pair
   wrote the same .weknora/project.yaml file with the same meaning,
   differentiated only by interactivity — that's a flag concern, not
   a command concern.

   Now: cmd/init/ deleted. cmd/link absorbs the interactive flow:
     - link --kb <id-or-name>  → non-interactive write
     - link on a TTY            → interactive prompt (lists KBs)
     - link non-TTY without --kb → CodeKBIDRequired
   Always overwrites silently (matches vercel link / netlify link /
   kubectl apply rather than git init's refuse-if-exists).

   Dead code purged: --force flag, CodeProjectAlreadyLinked error code.

3. whoami dropped

   Survey: 7/7 mainstream CLIs ship exactly one identity command —
   never both a status and a whoami. gh / gcloud / stripe pick status
   (config + live API); aws / kubectl / flyctl pick whoami (live API).

   weknora's auth status was already a superset of whoami (host +
   context + user + email + tenant_id + tenant_name vs user_id +
   tenant_id), so dropping whoami preserves all functionality and
   aligns with the gh / gcloud / stripe form.

4. kb get alias dropped

   `view` was already primary (gh repo view / gh pr view convention);
   `get` was kept as a cobra alias for v0.0/v0.1 callers. With no
   v0.0/v0.1 users to break, the alias is just noise on the command
   surface. Acceptance contract envelope cases renamed kb_get.* →
   kb_view.*; goldens renamed in lockstep.

5. api refactored to gh shape (-X/--method, default GET, auto-POST)

   gh CLI's signature is `gh api <endpoint> [--method M]` — single
   positional path, method as a flag, default GET, auto-promoted to
   POST when a body is supplied. weknora's previous `api <method>
   <path>` inverted this and forced the method to be passed even for
   GET — a needless deviation from our declared north star.

   Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol
   on the DELETE escape-hatch is preserved; -X DELETE still hits
   ConfirmDestructive when -y absent.

Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate
divergence from gh / lark — borrowed from `flutter doctor` / `brew
doctor` because RAG deployments routinely break on misconfigured
embeddings / storage / credentials and a 4-status structured envelope
is the cleanest surface for it.

Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages
removed). Acceptance contract envelope cases for whoami removed,
kb_get → kb_view renamed, search args / mock path updated for the
kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests
rewritten for the single-flag shape. api_test driver updated for the
positional-path / -X-method shape.
2026-05-12 13:20:42 +08:00

200 lines
7.0 KiB
Go

package cmdutil
import (
"errors"
"fmt"
"os"
"sync"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/projectlink"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
)
// Factory is the dependency container injected at command construction. Each
// closure is lazy: --help / completion / `weknora version` must NOT trigger
// HTTP, keyring access, or filesystem I/O beyond the bare minimum.
//
// Four closures (ADR-4):
// - Config: parses ~/.config/weknora/config.yaml (no network)
// - Client: constructs the SDK client; only Secrets is sync.Once-cached,
// so callers should hold the returned *sdk.Client across
// multiple SDK calls within one invocation
// - Prompter: returns interactive prompter; agent mode returns AgentPrompter
// - Secrets: builds the OS keyring / file fallback credential store the
// first time it is requested (probing the keyring at startup
// would fork+exec on macOS and DBus-touch on Linux,
// defeating the lazy contract above).
//
// 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).
//
// 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
// real SDK satisfy them implicitly via duck typing.
type Factory struct {
Config func() (*config.Config, error)
Client func() (*sdk.Client, error)
Prompter func() prompt.Prompter
Secrets func() (secrets.Store, error)
// ContextOverride, if non-empty, replaces config.CurrentContext for this
// invocation only — set by the global --context flag in PersistentPreRun.
// Buildable Config() / Client() honor it without writing to disk; matches
// spec §1.2 "weknora --context foo kb list = single-shot override".
ContextOverride string
}
// 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.
func New() *Factory {
var (
secretsOnce sync.Once
secretsStore secrets.Store
secretsErr error
)
f := &Factory{}
f.Config = func() (*config.Config, error) {
cfg, err := config.Load()
if err != nil {
// Map raw fs / parse errors to typed codes so envelopes don't
// surface bare `server.error` for what's actually a local IO /
// corrupt-config problem.
if errors.Is(err, config.ErrCorrupt) {
return nil, Wrapf(CodeLocalConfigCorrupt, err, "config malformed")
}
return nil, Wrapf(CodeLocalFileIO, err, "load config")
}
if f.ContextOverride != "" {
cfg.CurrentContext = f.ContextOverride
}
return cfg, nil
}
f.Client = func() (*sdk.Client, error) { return buildClient(f) }
f.Prompter = func() prompt.Prompter {
if iostreams.IO.IsStdoutTTY() && iostreams.IO.IsStderrTTY() {
return prompt.NewTTYPrompter()
}
return prompt.AgentPrompter{}
}
f.Secrets = func() (secrets.Store, error) {
secretsOnce.Do(func() {
secretsStore, secretsErr = secrets.NewBestEffortStore()
})
return secretsStore, secretsErr
}
return f
}
// buildClient resolves the active context, loads the credentials from secrets,
// and constructs a *sdk.Client. Returns CodeAuthUnauthenticated when no
// credentials are available so the user gets the right hint to run
// `weknora auth login`.
func buildClient(f *Factory) (*sdk.Client, error) {
cfg, err := f.Config()
if err != nil {
return nil, err
}
ctxName := cfg.CurrentContext
if ctxName == "" {
return nil, NewError(CodeAuthUnauthenticated, "no current context configured; run `weknora auth login` to set one up")
}
ctx, ok := cfg.Contexts[ctxName]
if !ok {
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("config references unknown context %q", ctxName))
}
if ctx.Host == "" {
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("context %q has no host", ctxName))
}
opts := []sdk.ClientOption{}
store, err := f.Secrets()
if err != nil {
return nil, Wrapf(CodeLocalKeychainDenied, err, "init secrets store")
}
// Only fetch the secrets the context actually references. Skipping the
// unused fetch avoids a `security` exec (macOS) / DBus call (Linux) per
// authenticated invocation.
if ctx.TokenRef != "" {
if access, err := loadSecret(store, ctxName, "access"); err != nil {
return nil, err
} else if access != "" {
opts = append(opts, sdk.WithBearerToken(access))
}
}
if ctx.APIKeyRef != "" {
if apiKey, err := loadSecret(store, ctxName, "api_key"); err != nil {
return nil, err
} else if apiKey != "" {
opts = append(opts, sdk.WithAPIKey(apiKey))
}
}
// ctx.TenantID is intentionally NOT injected as X-Tenant-ID. Servers derive
// 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.
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)
// 2. WEKNORA_KB_ID env (always an explicit id)
// 3. .weknora/project.yaml (walk-up from cwd)
// 4. error: kb required
func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) {
if v, _ := cmd.Flags().GetString("kb"); v != "" {
if IsKBID(v) {
return v, nil
}
c, err := f.Client()
if err != nil {
return "", err
}
return ResolveKBNameToID(cmd.Context(), c, v)
}
if v := os.Getenv("WEKNORA_KB_ID"); v != "" {
return v, nil
}
cwd, err := os.Getwd()
if err == nil {
if path, found, derr := projectlink.Discover(cwd); derr == nil && found {
p, lerr := projectlink.Load(path)
if lerr != nil {
return "", Wrapf(CodeProjectLinkCorrupt, lerr, "read project link")
}
if p.KBID != "" {
return p.KBID, nil
}
}
}
return "", NewError(CodeKBIDRequired, "kb is required")
}
// loadSecret returns the stored value for (context, key); ErrNotFound becomes
// ("", nil) so callers can treat "not configured" as success.
func loadSecret(store secrets.Store, context, key string) (string, error) {
v, err := store.Get(context, key)
if errors.Is(err, secrets.ErrNotFound) {
return "", nil
}
if err != nil {
return "", Wrapf(CodeLocalKeychainDenied, err, "load %s", key)
}
return v, nil
}