refactor(cli): drop aiclient package; align AGENTS.md with mainstream

Survey of 10 mainstream CLIs (gh, lark, stripe, vercel, supabase, aws,
azure, gcloud, openai/codex, github-copilot-cli) showed env-gated
per-command --help blurbs are a Stripe-only pattern; gh uses env detect
for telemetry only, and lark relies on installed agent Skills + MCP.
Our cmd/mcp/serve already covers the dominant 2025/26 path, so
internal/aiclient/ (136 LOC + 38 callsites) is net maintenance burden
without precedent.

- Drop internal/aiclient/ entirely (annotations + detect + tests)
- Remove 38 SetAgentHelp callsites + agentAwareHelpFunc / SetHelpFunc
  wiring in cmd/root.go
- Migrate 4 command-level rules to standard Long help (visible to all,
  not env-gated): doc upload mode mutex, kb edit at-least-one,
  kb pin idempotent, search chunks channel mutex
- Rewrite AGENTS.md as a developer guide (gh-style 6 H2 / 167 lines):
  audience preamble + Build / Architecture / Command Structure /
  Testing / Code Style / Error Handling. Drops sections absent in
  surveyed projects (Commit & PR Conventions, Who Uses This CLI)
- Clean 14 internal doc refs (ADR-N, spec §X, v0.X) in source comments
  and docs that pointed at docs/superpowers/ — that directory is
  local-only / uncommitted, so refs are dead for outside readers
- Drop forward-looking "once v0.2 ships" from README
This commit is contained in:
nullkey
2026-05-15 02:16:45 +08:00
committed by lyingbug
parent a0dd989c81
commit f2e8e3f56c
111 changed files with 575 additions and 908 deletions
+1 -1
View File
@@ -21,7 +21,7 @@ const (
)
// modeFromRefs maps the per-context TokenRef / APIKeyRef presence to a
// canonical credential-mode token. Bearer wins when both are present —
// canonical credential-mode token. Bearer wins when both are present -
// matches the precedence in cmdutil.buildClient.
func modeFromRefs(apiKeyRef, tokenRef string) string {
switch {
+2 -3
View File
@@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -31,11 +30,12 @@ type listEntry struct {
// 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.
// ~/.config/weknora/config.yaml - no network, no keyring touch.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List configured authentication contexts",
Long: `Show every configured context (name, host, user, mode, current). Read-only; no network or keyring access.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
@@ -46,7 +46,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
},
}
cmdutil.AddJSONFlags(cmd, authListFields)
aiclient.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
}
+2 -2
View File
@@ -37,7 +37,7 @@ func TestList_HumanRender(t *testing.T) {
// Mode column.
assert.Contains(t, got, ModeBearer)
assert.Contains(t, got, ModeAPIKey)
// Sorted alphabetically — prod after staging? No: "prod" < "staging".
// Sorted alphabetically - prod after staging? No: "prod" < "staging".
assert.Less(t, strings.Index(got, "prod"), strings.Index(got, "staging"),
"contexts should render sorted by name")
}
@@ -72,7 +72,7 @@ func TestList_JSON_BareArray(t *testing.T) {
}
func TestModeFromRefs(t *testing.T) {
// Hand-edited config with neither ref set — surface "unknown" rather
// Hand-edited config with neither ref set - surface "unknown" rather
// than pretending the context is a valid login.
assert.Equal(t, ModeUnknown, modeFromRefs("", ""))
assert.Equal(t, ModeBearer, modeFromRefs("", "tok"))
+4 -6
View File
@@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -17,7 +16,7 @@ import (
)
// authLoginFields enumerates the fields surfaced for `--json` discovery on
// `auth login`. The post-login summary has no token values — they stay in the
// `auth login`. The post-login summary has no token values - they stay in the
// keyring; agents who need to verify the credential should re-run
// `auth status`.
var authLoginFields = []string{
@@ -97,7 +96,6 @@ 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")
cmdutil.AddJSONFlags(cmd, authLoginFields)
_ = cmd.MarkFlagRequired("host")
aiclient.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
}
@@ -126,7 +124,7 @@ func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOption
opts.APIKey = key
// Validate against the server before persisting so a typo'd /
// expired / wrong-host key fails fast (gh CLI parity). The probe
// is /auth/me — read-only, side-effect-free.
// is /auth/me - read-only, side-effect-free.
user, err := defaultAPIKeyValidator(ctx, opts.Host, key)
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key")
@@ -268,7 +266,7 @@ func validateHost(host string) error {
// warnOnFileFallback prints a one-shot stderr advisory when the secrets
// store fell back to the plaintext 0600 file backend (keychain unavailable
// — typical on headless CI, WSL without DBus, agent containers). Helps
// - typical on headless CI, WSL without DBus, agent containers). Helps
// users notice that credentials are NOT in the OS keychain before they're
// surprised by it later. doctor's credential_storage check carries the
// same info but agents that bypass doctor would otherwise miss it.
@@ -276,7 +274,7 @@ func warnOnFileFallback(store secrets.Store) {
if _, isFile := store.(*secrets.FileStore); !isFile {
return
}
fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable — credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.")
fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable - credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.")
fmt.Fprintln(iostreams.IO.Err, " install / unlock the keyring (or use `weknora doctor` to inspect) for OS-backed storage.")
}
+1 -1
View File
@@ -124,7 +124,7 @@ func stubAPIKeyValidator(fn apiKeyValidator) func() {
func TestRunLogin_WithToken_Empty(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
// Validator must NOT be called when stdin is empty — verify by setting
// Validator must NOT be called when stdin is empty - verify by setting
// a panic-on-call sentinel.
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
t.Fatal("validator should not be called on empty stdin")
+4 -6
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -30,7 +29,7 @@ type logoutResult struct {
// 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.
// No server-side revocation - local-only credential clear.
func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
opts := &LogoutOptions{}
cmd := &cobra.Command{
@@ -39,7 +38,7 @@ func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
Long: `Clear keyring + file-fallback secrets for one context (or all of
them with --all) and drop the context entry from ~/.config/weknora/config.yaml.
Note: this does NOT revoke the credential server-side — for API keys, you
Note: this does NOT revoke the credential server-side - for API keys, you
must rotate them in the server UI; for JWT, the token will continue to be
accepted until it expires.`,
Example: ` weknora auth logout # current context
@@ -58,7 +57,6 @@ accepted until it expires.`,
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context")
cmdutil.AddJSONFlags(cmd, authLogoutFields)
cmd.MarkFlagsMutuallyExclusive("name", "all")
aiclient.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
}
@@ -85,7 +83,7 @@ func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
delete(cfg.Contexts, name)
}
// If we removed the active context, pick a remaining one (deterministic by
// map order would be flaky — leave CurrentContext empty so the next
// map order would be flaky - leave CurrentContext empty so the next
// invocation surfaces a clear "no current context" error rather than
// silently switching).
if _, stillExists := cfg.Contexts[cfg.CurrentContext]; !stillExists {
@@ -128,7 +126,7 @@ func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error
// clearContextSecrets best-effort deletes every secret slot the context
// references. Errors are swallowed because a missing secret is a no-op
// (tested in keyring_test.go) — we don't want a stale ref to block logout.
// (tested in keyring_test.go) - we don't want a stale ref to block logout.
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
if c.TokenRef != "" {
_ = store.Delete(name, "access")
+1 -1
View File
@@ -14,7 +14,7 @@ import (
)
// newLogoutFactory builds a Factory whose Config closure mutates the supplied
// cfg in place — runLogout writes back via config.Save which touches disk, so
// cfg in place - runLogout writes back via config.Save which touches disk, so
// tests use t.Setenv("XDG_CONFIG_HOME", t.TempDir()) at the call site to
// isolate the on-disk file.
func newLogoutFactory(t *testing.T, cfg *config.Config, store secrets.Store) *cmdutil.Factory {
+8 -10
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
@@ -17,11 +16,11 @@ type RefreshOptions struct {
}
// authRefreshFields enumerates the fields surfaced for `--json` discovery
// on `auth refresh`. Token values are intentionally omitted — see refreshResult.
// on `auth refresh`. Token values are intentionally omitted - see refreshResult.
var authRefreshFields = []string{"context"}
// refreshResult is the typed payload emitted under data on success. Token
// values are intentionally NOT included — emitting them would leak secrets
// values are intentionally NOT included - emitting them would leak secrets
// into stdout / agent transcripts. Agents needing to verify the new token
// can re-run `weknora auth status` (live API check).
type refreshResult struct {
@@ -29,10 +28,10 @@ type refreshResult struct {
}
// NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access
// token by spending the stored refresh_token via POST /auth/refresh —
// token by spending the stored refresh_token via POST /auth/refresh -
// the standard OAuth refresh-token grant.
//
// API-key contexts are rejected — they have no refresh semantic;
// API-key contexts are rejected - they have no refresh semantic;
// rotate the key via the server UI instead.
func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
opts := &RefreshOptions{}
@@ -43,7 +42,7 @@ func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
exchanges it for a new access + refresh token pair via POST /api/v1/auth/refresh.
Both new tokens replace the existing entries in the OS keyring.
API-key contexts are rejected with input.invalid_argument — they have no
API-key contexts are rejected with input.invalid_argument - they have no
refresh semantic. Rotate the key in the server UI instead.`,
Example: ` weknora auth refresh # refresh the current context
weknora auth refresh --name staging # refresh a specific context`,
@@ -58,12 +57,11 @@ refresh semantic. Rotate the key in the server UI instead.`,
}
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)")
cmdutil.AddJSONFlags(cmd, authRefreshFields)
aiclient.SetAgentHelp(cmd, "Renews the access token using the stored refresh token. Errors with auth.token_expired when refresh itself is rejected — surface the hint to re-run auth login.")
return cmd
}
// defaultRefresher constructs a fresh, unauthenticated SDK client targeting
// host — the /auth/refresh endpoint reads the refresh token from the body,
// host - the /auth/refresh endpoint reads the refresh token from the body,
// so no bearer / api-key header is needed.
func defaultRefresher(host string) cmdutil.Refresher {
return sdk.NewClient(host)
@@ -92,9 +90,9 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, jopts *cmdutil.JSONOp
fmt.Sprintf("context %q has no host", name))
}
if c.RefreshRef == "" {
hint := "api-key contexts can't be refreshed — rotate the key in the server UI and run `weknora auth login --with-token`"
hint := "api-key contexts can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`"
if c.APIKeyRef == "" {
hint = "no refresh token stored — run `weknora auth login` to authenticate"
hint = "no refresh token stored - run `weknora auth login` to authenticate"
}
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
+2 -2
View File
@@ -140,7 +140,7 @@ func TestRefresh_NoRefreshTokenStored(t *testing.T) {
"prod": {Host: "https://kb", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"},
},
}
// MemStore is empty — RefreshRef points to a slot that doesn't exist.
// MemStore is empty - RefreshRef points to a slot that doesn't exist.
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
@@ -168,7 +168,7 @@ func TestRefresh_ServerRefused(t *testing.T) {
assert.Contains(t, typed.Hint, "auth login")
// stored access must NOT have been overwritten with empty
if v, _ := store.Get("prod", "access"); v == "" {
// Was never set in this test, that's fine — main thing is no panic.
// Was never set in this test, that's fine - main thing is no panic.
_ = v
}
}
+8 -3
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
@@ -37,7 +36,14 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "Show the active context, principal, and token state",
Args: cobra.NoArgs,
Long: `Live-check the active credential by calling /auth/me. Reports the user
and tenant the server resolves the credential to.
Exits with auth.unauthenticated when the token is invalid or missing - run
` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT contexts) to recover.
For JWT contexts the SDK transparently refreshes on 401, so this command
usually only surfaces a hard auth failure.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
@@ -51,7 +57,6 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
},
}
cmdutil.AddJSONFlags(cmd, authStatusFields)
aiclient.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
}
+1 -1
View File
@@ -90,7 +90,7 @@ func TestRunStatus_SDKError_Transport(t *testing.T) {
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
err := runStatus(context.Background(), nil, f, &fakeStatusService{err: assert.AnError})
require.Error(t, err)
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems —
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems -
// classify network.error so retry logic / exit code 7 / IsTransient apply.
assert.True(t, cmdutil.IsTransient(err), "expected transient/network classification, got %v", err)
}
+5 -7
View File
@@ -5,7 +5,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
@@ -27,7 +26,7 @@ type tokenResult struct {
// curl -H "Authorization: Bearer $WEKNORA_TOKEN" ... # JWT mode
// curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key mode
//
// The user is responsible for constructing the appropriate header —
// The user is responsible for constructing the appropriate header -
// `auth list` shows which mode each context uses.
//
// Default output: raw token on stdout, no trailing newline (clean $(...)).
@@ -60,7 +59,6 @@ to see which mode each context uses, and construct the matching HTTP header:
},
}
cmdutil.AddJSONFlags(cmd, authTokenFields)
aiclient.SetAgentHelp(cmd, "Prints the active context's credential to stdout for scripting. Default: raw secret, no trailing newline. With --json: bare {token, mode, context} object. Errors: auth.unauthenticated when no active context or no stored credential (run `auth login`); local.keychain_denied when the keyring rejects the read.")
return cmd
}
@@ -89,7 +87,7 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
}
// Resolve the stored credential. Prefer bearer (JWT) when both refs
// are present — JWT is the more capable mode and what `buildClient`
// are present - JWT is the more capable mode and what `buildClient`
// uses for the Authorization header (see factory.go buildClient).
var token, mode string
switch {
@@ -119,18 +117,18 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
return jopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Context: ctxName})
}
// No trailing newline — clean $(weknora auth token) substitution.
// No trailing newline - clean $(weknora auth token) substitution.
fmt.Fprint(iostreams.IO.Out, token)
// Defensive hint to stderr when stdout is an interactive terminal:
// the user likely didn't mean to display the secret on screen.
// stderr-only so scripts (always non-TTY) are unaffected. Mode-specific
// because api-key tokens are long-lived and rotation is the only
// recourse on leak — bearer tokens self-expire via refresh.
// recourse on leak - bearer tokens self-expire via refresh.
if iostreams.IO.IsStdoutTTY() {
fmt.Fprintln(iostreams.IO.Err)
fmt.Fprintln(iostreams.IO.Err, "hint: pipe to $(weknora auth token) to capture; this terminal scrollback now contains the secret")
if mode == ModeAPIKey {
fmt.Fprintln(iostreams.IO.Err, "note: api-key credentials are long-lived — rotate via your auth provider if exposed (no `auth refresh` path)")
fmt.Fprintln(iostreams.IO.Err, "note: api-key credentials are long-lived - rotate via your auth provider if exposed (no `auth refresh` path)")
}
}
return nil
+3 -3
View File
@@ -165,7 +165,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) {
},
}
store := secrets.NewMemStore()
// no Set — keyring is empty
// no Set - keyring is empty
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), nil)
if err == nil {
@@ -200,7 +200,7 @@ func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
// interactive terminal, it ALSO writes a stderr advisory ("you just put the
// secret in your scrollback") + a mode-specific rotation note for api-key
// credentials. The stdout half must stay clean under all modes so $(...)
// substitution is unaffected — tests assert both axes.
// substitution is unaffected - tests assert both axes.
func makeBearerCfg() (*config.Config, *secrets.MemStore) {
cfg := &config.Config{
@@ -278,7 +278,7 @@ func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
func TestAuthToken_TTY_JSONMode_NoStderrHint(t *testing.T) {
// --json output mode targets script/agent consumers even when stdout
// happens to be a TTY (e.g. an IDE running the CLI on the user's
// behalf). Hint would pollute their parsing — suppress.
// behalf). Hint would pollute their parsing - suppress.
cfg, store := makeBearerCfg()
_, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil {