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
+7 -8
View File
@@ -17,23 +17,22 @@ import (
// cmdutil.NewError(codeXxx, ...) and cmdutil.Wrapf(codeXxx, ...) and verifies
// that codeXxx is registered in cmdutil.AllCodes().
//
// ClassifyHTTPError is dynamic — callers don't pass a literal CodeXxx
// ClassifyHTTPError is dynamic - callers don't pass a literal CodeXxx
// ident. Most SDK call sites go through cmdutil.WrapHTTP(err, ...) which
// the scanner skips entirely (it only inspects NewError / Wrapf selector
// names). A few sites still call ClassifyHTTPError directly to inspect
// or remap the code; those are call-expression args the scanner also
// skips. Either way, the codes those paths can yield are bridged via
// cmdutil.ClassifyHTTPErrorOutputs(), which enumerates every code the
// switch can return — added to the registered set so the AST scanner
// switch can return - added to the registered set so the AST scanner
// doesn't false-positive on them.
//
// Limitations (documented in spec §4.3):
// Limitations:
// - Only literal cmdutil.CodeXxx idents are detected; codes assigned to
// a local variable then passed are NOT scanned (rare pattern).
// - cmdutil.WrapHTTP(...) and cmdutil.ClassifyHTTPError(...) call
// expressions are skipped — the ClassifyHTTPErrorOutputs bridge
// expressions are skipped - the ClassifyHTTPErrorOutputs bridge
// covers their dynamic codes.
// - v0.x does not enforce a baseline diff (spec ADR-6b); v0.9 will.
func TestAllReferencedCodesAreRegistered(t *testing.T) {
registered := make(map[cmdutil.ErrorCode]struct{})
for _, c := range cmdutil.AllCodes() {
@@ -117,7 +116,7 @@ func collectErrorCodes(fset *token.FileSet, f *ast.File, out map[cmdutil.ErrorCo
}
// First arg should be cmdutil.CodeXxx (SelectorExpr ident).
// If it's a function call (e.g. cmdutil.ClassifyHTTPError(err)), skip
// — bridge handles those.
// - bridge handles those.
arg0Sel, ok := call.Args[0].(*ast.SelectorExpr)
if !ok {
return true
@@ -128,7 +127,7 @@ func collectErrorCodes(fset *token.FileSet, f *ast.File, out map[cmdutil.ErrorCo
}
code, ok := identToErrorCode(arg0Sel.Sel.Name)
if !ok {
// Unknown ident name — record as bogus so the test fails with
// Unknown ident name - record as bogus so the test fails with
// a clear "code referenced but not registered" message.
code = cmdutil.ErrorCode("UNKNOWN_REF:" + arg0Sel.Sel.Name)
}
@@ -140,7 +139,7 @@ func collectErrorCodes(fset *token.FileSet, f *ast.File, out map[cmdutil.ErrorCo
// identToErrorCode maps an ident name like "CodeAuthUnauthenticated" to its
// underlying ErrorCode value via a simple switch. Avoids reflect.
// Keep in sync with cmdutil.AllCodes() — adding a new const here is the same
// Keep in sync with cmdutil.AllCodes() - adding a new const here is the same
// bookkeeping as adding it to AllCodes().
func identToErrorCode(name string) (cmdutil.ErrorCode, bool) {
switch name {
+5 -6
View File
@@ -38,13 +38,12 @@ func TestMain(m *testing.M) {
var update = flag.Bool("update", false, "update golden files")
// newTestFactory builds a Factory whose Client returns mockClient.
// Caller must NOT use t.Parallel() — see iostreams.SetForTest contract.
// Caller must NOT use t.Parallel() - see iostreams.SetForTest contract.
//
// WEKNORA_BASE_URL is set when mockServer is non-nil. v0.0 buildClient does
// not currently honor this env var (it reads from config.Host); commands that
// need the mock URL must rely on the mockClient injection above. The env
// is set anyway as a forward-affordance for any direct net/http callers
// added in PR-7+ (e.g. doctor's PingBaseURL HEAD /health).
// WEKNORA_BASE_URL is set when mockServer is non-nil. buildClient does not
// currently honor this env var (it reads from config.Host); commands that
// need the mock URL rely on the mockClient injection above. The env is set
// anyway for any direct net/http callers (e.g. doctor's HEAD /health).
func newTestFactory(t *testing.T, mockServer *httptest.Server, mockClient *sdk.Client) *cmdutil.Factory {
t.Helper()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+16 -16
View File
@@ -12,7 +12,7 @@
// line on stderr.
//
// Cases intentionally omitted (with reason):
// - doctor.success — non-offline path emits
// - doctor.success - non-offline path emits
// unstable timing
// ("reachable in 2ms").
// Unit tests in cli/cmd/doctor
@@ -20,12 +20,12 @@
// doctor.success_offline is
// the deterministic sibling
// kept here.
// - auth_login.success — requires stdin pipe
// - auth_login.success - requires stdin pipe
// (--with-token) + keyring-
// aware Secrets store; the
// helper does not yet expose
// a stdin hook.
// - auth_login.error_auth_unauthenticated — same setup as above.
// - auth_login.error_auth_unauthenticated - same setup as above.
//
// All cases use leaf-positioned --json (e.g. `version --json`). --json is a
// per-leaf flag, not a global persistent flag.
@@ -45,13 +45,13 @@ import (
)
// wireCase declares one row in the contract matrix. Optional fields:
// server — mock /api/v1/* endpoints; nil means no network.
// preConfig — seed config.yaml under the per-test XDG_CONFIG_HOME
// server - mock /api/v1/* endpoints; nil means no network.
// preConfig - seed config.yaml under the per-test XDG_CONFIG_HOME
// (set by newTestFactory); use for cases like
// `context use` that read local state without an
// SDK round-trip.
// wantErr — non-zero exit expected.
// wantStderrSubstring — stderr must contain this substring (typically the
// wantErr - non-zero exit expected.
// wantStderrSubstring - stderr must contain this substring (typically the
// typed error code, e.g. "auth.unauthenticated").
// Only meaningful when wantErr=true.
type wireCase struct {
@@ -66,13 +66,13 @@ type wireCase struct {
// wireCases enumerates every contract scenario whose stdout is golden-pinned.
// Order is illustrative, not load-bearing.
var wireCases = []wireCase{
// 1. version.success — pure local; no client touched.
// 1. version.success - pure local; no client touched.
{
name: "version.success",
args: []string{"version", "--json"},
},
// 2. doctor.success_offline — only credential_storage runs; the three
// 2. doctor.success_offline - only credential_storage runs; the three
// network checks are skipped. Stable details + summary.
{
name: "doctor.success_offline",
@@ -80,7 +80,7 @@ var wireCases = []wireCase{
server: doctorReachable, // ensures buildServices succeeds even if probed
},
// 3. doctor.error_network — base_url returns 500 → ping fail → cascade
// 3. doctor.error_network - base_url returns 500 → ping fail → cascade
// skip on auth_credential + server_version. credential_storage still
// runs (independent). Contract: any check=fail bumps summary.failed
// and RunE returns SilentError → exit 1 with the data object
@@ -92,7 +92,7 @@ var wireCases = []wireCase{
wantErr: true,
},
// 4-7. kb list / get — SDK paths /api/v1/knowledge-bases[/<id>]
// 4-7. kb list / get - SDK paths /api/v1/knowledge-bases[/<id>]
{
name: "kb_list.success",
args: []string{"kb", "list", "--json"},
@@ -123,7 +123,7 @@ var wireCases = []wireCase{
wantStderrSubstring: "resource.not_found",
},
// 8. context use — pure local I/O against config.yaml.
// 8. context use - pure local I/O against config.yaml.
{
name: "context_use.success",
args: []string{"context", "use", "production", "--json"},
@@ -140,9 +140,9 @@ var wireCases = []wireCase{
}
},
},
// (context_use.error_local_context_not_found dropped — see file header.)
// (context_use.error_local_context_not_found dropped - see file header.)
// 9-10. auth status — SDK /api/v1/auth/me, plus config inspection.
// 9-10. auth status - SDK /api/v1/auth/me, plus config inspection.
{
name: "auth_status.success",
args: []string{"auth", "status", "--json"},
@@ -156,7 +156,7 @@ var wireCases = []wireCase{
wantStderrSubstring: "auth.unauthenticated",
},
// 11-13. search chunks — verb-noun shape (gh search parity), positional query, --kb required.
// 11-13. search chunks - verb-noun shape (gh search parity), positional query, --kb required.
// --kb accepts either kb_<id> (passed through) or a name (resolved via
// list); UUID-format detection happens client-side, mirroring gcloud
// --project's id-or-name auto-detection.
@@ -185,7 +185,7 @@ var wireCases = []wireCase{
// TestWireGolden is the matrix-runner. Cases are sequential (the
// iostreams singleton swap inside helpers.runCmd is package-global;
// t.Parallel is contractually forbidden — see helpers_test.go).
// t.Parallel is contractually forbidden - see helpers_test.go).
func TestWireGolden(t *testing.T) {
for _, tc := range wireCases {
t.Run(tc.name, func(t *testing.T) {
+3 -5
View File
@@ -2,11 +2,9 @@
//
// Package acceptance is the cli/ subtree top-level home for cross-cutting
// contract / integration tests. Lives outside cli/internal/ so a future
// reviewer immediately sees "this is the contract surface — change with care".
// reviewer immediately sees "this is the contract surface - change with care".
//
// Sub-packages:
// contract/ — envelope JSON shape golden + error.code registry consistency
// e2e/ — real WeKnora server blackbox tests (testscript-style)
//
// Layout convention follows spec §4.5.
// contract/ - envelope JSON shape golden + error.code registry consistency
// e2e/ - real WeKnora server blackbox tests (testscript-style)
package acceptance
+4 -4
View File
@@ -31,7 +31,7 @@ import (
// TestRAGFullLoop walks the demo MVP path: link a context, create a KB,
// upload a doc, wait for indexing, search it, then chat against it. Each
// step parses the CLI's bare JSON to extract IDs for the next step —
// step parses the CLI's bare JSON to extract IDs for the next step -
// validating both functional behavior and wire-contract stability.
func TestRAGFullLoop(t *testing.T) {
host := mustEnv(t, "WEKNORA_E2E_HOST")
@@ -45,7 +45,7 @@ func TestRAGFullLoop(t *testing.T) {
env := append(os.Environ(),
"XDG_CONFIG_HOME="+xdg,
"XDG_CACHE_HOME="+filepath.Join(xdg, "cache"),
// SDK debug off — explicit so the CI run isn't noisy.
// SDK debug off - explicit so the CI run isn't noisy.
"WEKNORA_SDK_DEBUG=",
)
@@ -102,7 +102,7 @@ func TestRAGFullLoop(t *testing.T) {
}
t.Logf("chat answer (%d chars), %d references", len(chat.Answer), len(chat.References))
if len(chat.References) == 0 {
// Soft warning — some servers may not surface references for every
// Soft warning - some servers may not surface references for every
// question, but the demo flow is supposed to.
t.Logf("warning: chat returned 0 references (server may have a different config)")
}
@@ -189,7 +189,7 @@ matching (lexical) to balance recall and precision.
// waitDocReady polls `doc list` until the uploaded document's status indicates
// indexing is complete. WeKnora server uses a few status values across versions
// ("ready", "completed", "ok") — accept any non-pending/non-processing/non-failed
// ("ready", "completed", "ok") - accept any non-pending/non-processing/non-failed
// state so we don't break on a server-side rename. Failed status fails the test
// fast.
func waitDocReady(t *testing.T, bin string, env []string, kbID, docID string, timeout time.Duration) {