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
+18 -20
View File
@@ -1,12 +1,12 @@
// Package doctor implements `weknora doctor` — 4-item self-check (spec §1.2).
// Package doctor implements `weknora doctor` - 4-item self-check.
//
// Status semantics (4-tier):
//
// ok — passed
// warn — soft problem; non-blocking (e.g. server minor older than CLI,
// ok - passed
// warn - soft problem; non-blocking (e.g. server minor older than CLI,
// keychain unavailable so falling back to file store)
// fail — failed; "hint" actionable
// skip — cascade-skipped (prereq failed) or --offline mode
// fail - failed; "hint" actionable
// skip - cascade-skipped (prereq failed) or --offline mode
//
// JSON output emits the Result object directly (bare data). Exit-code
// signal:
@@ -28,7 +28,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/build"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/compat"
@@ -66,7 +65,7 @@ type Check struct {
Hint string `json:"hint,omitempty"`
}
// Summary is the agent-friendly short-circuit payload (spec §1.2).
// Summary is the agent-friendly short-circuit payload.
//
// AllPassed is true only when there are zero warn/fail/skip rows; warn does
// not block exit-0 but it does flip AllPassed so agents reading just the
@@ -125,7 +124,6 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache (located at $XDG_CACHE_HOME/weknora/server-info.yaml); force re-probe")
cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage (credential_storage check still runs)")
cmdutil.AddJSONFlags(cmd, doctorFields)
aiclient.SetAgentHelp(cmd, "Returns 4 health checks as a bare JSON object {summary, checks}. AGENT short-circuit: read summary.all_passed; if false, inspect checks[].status (ok/warn/fail/skip). exit 1 only when any status=fail; warn does not affect exit.")
return cmd
}
@@ -133,7 +131,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
// offline-mode skip and prereq-failed skip. Returns true when the check has
// been completed (Status set on c) and the caller should NOT run its body.
//
// A prereq is considered "passing" if its Status is OK or Warn — warn signals
// A prereq is considered "passing" if its Status is OK or Warn - warn signals
// a soft problem that does not block downstream functionality. Only fail/skip
// cascades into a downstream skip.
func cascade(c *Check, offline bool, prereqs ...*Check) bool {
@@ -160,7 +158,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
{Name: "credential_storage"},
}
// 1. base_url_reachable — gated by offline only.
// 1. base_url_reachable - gated by offline only.
if !cascade(&checks[0], opts.Offline) {
t0 := time.Now()
if err := svc.PingBaseURL(ctx); err != nil {
@@ -173,7 +171,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
}
}
// 2. auth_credential — needs base_url.
// 2. auth_credential - needs base_url.
if !cascade(&checks[1], opts.Offline, &checks[0]) {
if _, err := svc.GetCurrentUser(ctx); err != nil {
checks[1].Status = StatusFail
@@ -184,7 +182,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
}
}
// 3. server_version — needs auth_credential.
// 3. server_version - needs auth_credential.
if !cascade(&checks[2], opts.Offline, &checks[1]) {
info, fromCache, err := loadOrProbeServerInfo(ctx, opts, svc)
if err != nil {
@@ -195,14 +193,14 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
}
}
// 4. credential_storage — independent of network; never gated by offline.
// 4. credential_storage - independent of network; never gated by offline.
fillCredentialStorageCheck(&checks[3])
return Result{Summary: summarize(checks), Checks: checks}
}
// fillVersionCheck applies compat.Compat to (server, cli) version pair and
// sets Status/Details/Hint on c. fromCache toggles the "cached" suffix —
// sets Status/Details/Hint on c. fromCache toggles the "cached" suffix -
// the loader knows authoritatively which branch it took, time-based
// derivation from ProbedAt is unreliable since SaveCache uses time.Now().
//
@@ -239,8 +237,8 @@ func fillVersionCheck(c *Check, info *compat.Info, cliVer string, fromCache bool
}
}
// credStoreFactory is the seam tests use to inject a fake-store outcome —
// keyring success, file-store fallback, or hard failure — without touching
// credStoreFactory is the seam tests use to inject a fake-store outcome -
// keyring success, file-store fallback, or hard failure - without touching
// the lazy-resolve buildServices contract (round-4 fix). Production stays
// at secrets.NewBestEffortStore.
var credStoreFactory = func() (secrets.Store, error) { return secrets.NewBestEffortStore() }
@@ -248,7 +246,7 @@ var credStoreFactory = func() (secrets.Store, error) { return secrets.NewBestEff
// SetCredStoreFactoryForTest overrides the credential-storage factory used by
// runChecks and returns a cleanup function that restores the previous value.
// Exported so out-of-package tests (notably cli/acceptance/contract) can
// pin the credential_storage outcome — otherwise the check probes the real
// pin the credential_storage outcome - otherwise the check probes the real
// OS keyring, which is present on macOS dev machines but not on Linux CI
// runners without libsecret, producing host-dependent test flakes.
//
@@ -269,7 +267,7 @@ func SetCredStoreFactoryForTest(fn func() (secrets.Store, error)) (restore func(
//
// keyring usable → StatusOK (preferred path)
// file fallback → StatusWarn (keyring unavailable, secrets still persist
// with 0600 file perms — agent containers / WSL hit this)
// with 0600 file perms - agent containers / WSL hit this)
// construction fails → StatusFail
//
// Detection of "fallback to file store" relies on the type returned by
@@ -378,7 +376,7 @@ func marker(s Status) string {
// server, not localhost.
//
// Critically: this does NOT pre-resolve f.Client(). doctor's package promise
// (top comment) is that credential_storage runs even when no auth is set up —
// (top comment) is that credential_storage runs even when no auth is set up -
// e.g. first-time `weknora doctor` to diagnose setup. Pre-resolving Client
// here would early-exit with auth.unauthenticated before any check runs,
// contradicting the docs. Instead, GetCurrentUser / GetSystemInfo lazily
@@ -443,7 +441,7 @@ func (s *realServices) GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResp
// GetSystemInfo lazily resolves the SDK client (same rationale as GetCurrentUser).
// In the cascade ordering, auth_credential gates server_version, so this only
// runs when auth_credential succeeded — but the lazy resolution keeps doctor
// runs when auth_credential succeeded - but the lazy resolution keeps doctor
// useful when only credential_storage is checkable (e.g., user not yet logged in).
func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) {
cli, err := s.f.Client()
+8 -8
View File
@@ -21,7 +21,7 @@ import (
// and would make CI flake on macOS vs Linux vs WSL). Restored in t.Cleanup.
//
// The hook intentionally lives at package scope (rather than as a runChecks
// parameter) so the production call site stays a zero-arg function — keeping
// parameter) so the production call site stays a zero-arg function - keeping
// the lazy-resolve buildServices contract unchanged (round-4 fix).
func withCredStoreFactory(t *testing.T, fn func() (secrets.Store, error)) {
t.Helper()
@@ -58,7 +58,7 @@ func TestDoctor_AllOK(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
out, _ := iostreams.SetForTest(t)
// Pin credential_storage to ok so this test doesn't probe the host OS
// keyring — macOS dev machines have Keychain, Linux CI without libsecret
// keyring - macOS dev machines have Keychain, Linux CI without libsecret
// would otherwise warn and break the AllPassed assertion.
withCredStoreFactory(t, func() (secrets.Store, error) {
return secrets.NewMemStore(), nil
@@ -107,7 +107,7 @@ func TestDoctor_BaseURLFails_DownstreamSkip(t *testing.T) {
if r.Checks[2].Status != StatusSkip {
t.Errorf("server_version status = %q, want skip", r.Checks[2].Status)
}
// credential_storage 与网络无关,应该独立运行(不受 base_url fail 影响)
// credential_storage is network-independent and runs regardless of base_url failures.
if r.Checks[3].Name != "credential_storage" {
t.Errorf("Checks[3] = %q, want credential_storage", r.Checks[3].Name)
}
@@ -245,7 +245,7 @@ func TestDoctor_NoCache_BypassesCache(t *testing.T) {
func TestDoctor_VersionSkewWarns(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t)
// Force keyring path to ok so credential_storage doesn't itself warn —
// Force keyring path to ok so credential_storage doesn't itself warn -
// we want this test to assert ONLY on server_version.
withCredStoreFactory(t, func() (secrets.Store, error) { return secrets.NewMemStore(), nil })
@@ -262,7 +262,7 @@ func TestDoctor_VersionSkewWarns(t *testing.T) {
if v.Status != StatusWarn {
t.Errorf("server_version status = %q, want warn (server older than CLI)", v.Status)
}
// compat.Compat hint contains "server is older" — that's the load-bearing
// compat.Compat hint contains "server is older" - that's the load-bearing
// substring agents may pattern-match. Not asserting full message text
// since compat.Compat owns the wording.
if !strings.Contains(v.Details, "older") {
@@ -318,7 +318,7 @@ func TestDoctor_HardErrorStillFails(t *testing.T) {
// TestDoctor_KeychainFallbackWarns covers credential_storage's third
// state: keyring unavailable, fell back to FileStore (agent containers,
// headless CI, WSL without DBus). The check should warn — secrets still
// headless CI, WSL without DBus). The check should warn - secrets still
// persist (0600 file perms) but the OS-backed path was unreachable.
func TestDoctor_KeychainFallbackWarns(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
@@ -355,7 +355,7 @@ func TestDoctor_KeychainFallbackWarns(t *testing.T) {
}
// TestDoctor_CredStoreFactoryError surfaces the constructor failure path as
// fail (not warn) — distinguishes "cannot persist credentials at all" from
// fail (not warn) - distinguishes "cannot persist credentials at all" from
// "downgraded to file store".
func TestDoctor_CredStoreFactoryError(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
@@ -487,7 +487,7 @@ func TestDoctor_RunE_FailReturnsSilentError(t *testing.T) {
}
}
// TestDoctor_RunE_WarnReturnsNil — soft skew path stays exit-0. Pairs with
// TestDoctor_RunE_WarnReturnsNil - soft skew path stays exit-0. Pairs with
// TestDoctor_RunE_FailReturnsSilentError: warn does NOT trigger SilentError.
func TestDoctor_RunE_WarnReturnsNil(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())