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:
@@ -21,7 +21,7 @@ type Refresher interface {
|
||||
// retry the original request).
|
||||
//
|
||||
// Single canonical implementation shared by `weknora auth refresh` and the
|
||||
// AuthRetryTransport's refresh closure — both used to inline the same
|
||||
// AuthRetryTransport's refresh closure - both used to inline the same
|
||||
// six-step sequence with subtly diverging error wording.
|
||||
func RefreshAndPersist(ctx context.Context, store secrets.Store, refresher Refresher, ctxName string) (string, error) {
|
||||
refresh, err := store.Get(ctxName, "refresh")
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
// - 401 on /api/v1/auth/login or /api/v1/auth/refresh: pass through
|
||||
// (otherwise a stale refresh token causes infinite recursion).
|
||||
// - 401 with no initial token configured (api-key contexts): pass through
|
||||
// — api-key credentials have no refresh semantic.
|
||||
// - api-key credentials have no refresh semantic.
|
||||
// - 401 with non-replayable request body (req.GetBody == nil): pass
|
||||
// through. The SDK always uses bytes.Buffer bodies; this is a safety
|
||||
// net for hand-built requests.
|
||||
@@ -31,7 +31,7 @@ import (
|
||||
// the updated currentToken and replay without re-refreshing (singleflight).
|
||||
//
|
||||
// The transport intentionally shadows the SDK's bearerToken (set via
|
||||
// WithBearerToken). After a refresh, the SDK is unaware of the new token —
|
||||
// WithBearerToken). After a refresh, the SDK is unaware of the new token -
|
||||
// the transport's per-request override is the single source of truth for
|
||||
// the Authorization header. Tokens persisted to the secrets store happen
|
||||
// inside refreshFn (see cmdutil.RefreshAndPersist).
|
||||
@@ -49,7 +49,7 @@ type AuthRetryTransport struct {
|
||||
//
|
||||
// Pass an empty initialToken to indicate "no bearer credential configured"
|
||||
// (e.g. an api-key context). In that mode the transport never invokes
|
||||
// refreshFn — a 401 is propagated as-is.
|
||||
// refreshFn - a 401 is propagated as-is.
|
||||
func NewAuthRetryTransport(base http.RoundTripper, initialToken string, refreshFn func(context.Context) (string, error)) *AuthRetryTransport {
|
||||
if base == nil {
|
||||
base = http.DefaultTransport
|
||||
|
||||
@@ -172,7 +172,7 @@ func TestAuthRetry_SkipAuthEndpoints(t *testing.T) {
|
||||
func TestAuthRetry_NoTokenConfigured_DoesNotInjectAuthz(t *testing.T) {
|
||||
// API-key contexts construct the transport with an empty initial token;
|
||||
// authretry should pass through 401s untouched (no refresh callback exists
|
||||
// for api-key — they're rejected at the auth-refresh layer).
|
||||
// for api-key - they're rejected at the auth-refresh layer).
|
||||
base := &stubTransport{t: t, resps: []*http.Response{resp(401, "")}}
|
||||
refreshed := false
|
||||
rt := NewAuthRetryTransport(base, "", func(context.Context) (string, error) {
|
||||
@@ -192,7 +192,7 @@ func TestAuthRetry_NoTokenConfigured_DoesNotInjectAuthz(t *testing.T) {
|
||||
func TestAuthRetry_ConcurrentRefresh_SingleFlight(t *testing.T) {
|
||||
// 4 parallel 401s should trigger exactly 1 refresh; all 4 then retry with
|
||||
// the new token. Use a server that 401s first request from each unique
|
||||
// path then 200s on retry — except we use one shared transport with
|
||||
// path then 200s on retry - except we use one shared transport with
|
||||
// scripted responses, ordering matters. To keep determinism, build a
|
||||
// transport that always returns 401 on first call per request, 200 on
|
||||
// second, and gate the refresh callback.
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
//
|
||||
// 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".
|
||||
// proceed. See cli/README.md "Exit codes".
|
||||
//
|
||||
// `yes` should be sourced from the persistent global -y/--yes flag.
|
||||
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error {
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
type ErrorCode string
|
||||
|
||||
const (
|
||||
// auth.* — authentication / permission
|
||||
// auth.* - authentication / permission
|
||||
CodeAuthUnauthenticated ErrorCode = "auth.unauthenticated"
|
||||
CodeAuthTokenExpired ErrorCode = "auth.token_expired"
|
||||
CodeAuthBadCredential ErrorCode = "auth.bad_credential"
|
||||
@@ -28,12 +28,12 @@ const (
|
||||
CodeResourceAlreadyExists ErrorCode = "resource.already_exists"
|
||||
CodeResourceLocked ErrorCode = "resource.locked"
|
||||
|
||||
// input.* — flag and argument validation
|
||||
// input.* - flag and argument validation
|
||||
CodeInputInvalidArgument ErrorCode = "input.invalid_argument"
|
||||
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 (see cli/AGENTS.md). Agents must surface the
|
||||
// Mapped to exit code 10 (see cli/README.md). Agents must surface the
|
||||
// error to the user and only retry with -y after explicit human
|
||||
// approval; never auto-retry.
|
||||
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
|
||||
@@ -49,13 +49,13 @@ const (
|
||||
// server.error so agents can retry with their own --session.
|
||||
CodeSessionCreateFailed ErrorCode = "server.session_create_failed"
|
||||
|
||||
// local.* — config / file / keychain on the user's machine
|
||||
// local.* - config / file / keychain on the user's machine
|
||||
CodeLocalConfigCorrupt ErrorCode = "local.config_corrupt"
|
||||
CodeLocalKeychainDenied ErrorCode = "local.keychain_denied"
|
||||
CodeLocalFileIO ErrorCode = "local.file_io"
|
||||
CodeLocalUnimplemented ErrorCode = "local.unimplemented"
|
||||
CodeLocalContextNotFound ErrorCode = "local.context_not_found"
|
||||
// v0.2 KB-resolution chain (spec §1.3) and project-link (spec §2.4) codes.
|
||||
// KB-resolution chain and project-link codes.
|
||||
CodeKBIDRequired ErrorCode = "local.kb_id_required"
|
||||
CodeKBNotFound ErrorCode = "local.kb_not_found"
|
||||
CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
|
||||
@@ -124,7 +124,7 @@ func Wrapf(code ErrorCode, cause error, format string, args ...any) *Error {
|
||||
// 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.
|
||||
// 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
|
||||
@@ -150,7 +150,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.
|
||||
// Typed predicates - use these instead of comparing ErrorCode strings.
|
||||
// They walk the error chain so wrapped errors still match.
|
||||
|
||||
// IsAuthError matches any auth.* code.
|
||||
@@ -285,6 +285,6 @@ func ClassifyHTTPErrorOutputs() []ErrorCode {
|
||||
CodeServerRateLimited, // 429
|
||||
CodeServerError, // 5xx / parse-failure / default
|
||||
CodeInputInvalidArgument, // 4xx (else)
|
||||
CodeNetworkError, // 非 HTTP error
|
||||
CodeNetworkError, // non-HTTP error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ func TestAllCodes_NonEmpty(t *testing.T) {
|
||||
if len(codes) == 0 {
|
||||
t.Fatal("AllCodes() should return registered codes")
|
||||
}
|
||||
// Sentinel: 至少包含这几个 v0.0 已知 code
|
||||
// Sentinel: contains the baseline error codes the registry must always carry.
|
||||
want := map[cmdutil.ErrorCode]bool{
|
||||
cmdutil.CodeAuthUnauthenticated: false,
|
||||
cmdutil.CodeResourceNotFound: false,
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"io"
|
||||
)
|
||||
|
||||
// ExitCode maps an error to the documented CLI exit code (spec §2.4 + ADR-3).
|
||||
// ExitCode maps an error to the documented CLI exit code.
|
||||
// - 0 success
|
||||
// - 1 generic / unknown typed error — fallback for: resource.already_exists,
|
||||
// - 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,
|
||||
@@ -19,8 +19,8 @@ import (
|
||||
// - 5 input.* (other than confirmation_required)
|
||||
// - 6 server.rate_limited
|
||||
// - 7 server.* (other than rate_limited/session_create_failed) / network.*
|
||||
// - 10 input.confirmation_required — high-risk write needs explicit -y
|
||||
// (see cli/AGENTS.md)
|
||||
// - 10 input.confirmation_required - high-risk write needs explicit -y
|
||||
// (see cli/README.md)
|
||||
// - 130 SIGINT (handled by Go runtime, not this function)
|
||||
func ExitCode(err error) int {
|
||||
if err == nil {
|
||||
@@ -77,7 +77,7 @@ func PrintError(w io.Writer, err error) {
|
||||
|
||||
// defaultHint returns a canonical actionable hint for known error codes
|
||||
// when the call site didn't set one. `auth.unauthenticated` always points
|
||||
// at `weknora auth login` — covers the broad surface (auth status / kb
|
||||
// at `weknora auth login` - covers the broad surface (auth status / kb
|
||||
// list / kb view / search) without per-command hint plumbing.
|
||||
//
|
||||
// Empty string for codes without a stable canonical hint.
|
||||
@@ -104,7 +104,7 @@ func defaultHint(code ErrorCode) string {
|
||||
case CodeInputInvalidArgument, CodeInputMissingFlag:
|
||||
return "see `weknora <command> --help` for valid usage"
|
||||
case CodeInputConfirmationRequired:
|
||||
return "high-risk write — re-run with -y/--yes after the user explicitly approves"
|
||||
return "high-risk write - re-run with -y/--yes after the user explicitly approves"
|
||||
case CodeLocalKeychainDenied:
|
||||
return "verify keyring access; falls back to file storage"
|
||||
case CodeLocalConfigCorrupt:
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
// 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):
|
||||
// Four closures:
|
||||
// - 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
|
||||
@@ -33,13 +33,13 @@ import (
|
||||
// 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 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.
|
||||
//
|
||||
// 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.
|
||||
// service interfaces 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)
|
||||
@@ -47,9 +47,8 @@ type Factory struct {
|
||||
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".
|
||||
// invocation only - set by the global --context flag in PersistentPreRun.
|
||||
// Buildable Config() / Client() honor it without writing to disk.
|
||||
ContextOverride string
|
||||
}
|
||||
|
||||
@@ -59,7 +58,7 @@ type Factory struct {
|
||||
// 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
|
||||
// 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 {
|
||||
@@ -157,7 +156,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
// 401-retry transport: on the first 401 from a non-/auth/* endpoint, the
|
||||
// transport reads the stored refresh token, calls /api/v1/auth/refresh,
|
||||
// persists the new pair, and replays the original request with the new
|
||||
// bearer. API-key contexts skip this (no refresh semantic) — a 401 from
|
||||
// bearer. API-key contexts skip this (no refresh semantic) - a 401 from
|
||||
// them propagates as auth.unauthenticated for the caller to handle.
|
||||
if ctx.TokenRef != "" && ctx.RefreshRef != "" {
|
||||
refreshFn := func(rctx context.Context) (string, error) {
|
||||
@@ -171,9 +170,8 @@ 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 — 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.
|
||||
// breaks that contract - explicit cross-tenant flags would be required
|
||||
// before sending it. `tenant_id` stays in config for `auth status` display only.
|
||||
return sdk.NewClient(ctx.Host, opts...), nil
|
||||
}
|
||||
|
||||
@@ -231,7 +229,7 @@ func LoadSecret(store secrets.Store, context, key string) (string, error) {
|
||||
|
||||
// refreshAccessToken is the closure target injected into AuthRetryTransport's
|
||||
// refreshFn. A fresh SDK Client is built here rather than reusing the one
|
||||
// being constructed — that one is itself wrapped by the transport, which
|
||||
// being constructed - that one is itself wrapped by the transport, which
|
||||
// would recurse on refresh. The refresh endpoint is unauthenticated apart
|
||||
// from the refresh token in the body, so no credential options are needed.
|
||||
func refreshAccessToken(ctx context.Context, store secrets.Store, host, ctxName string) (string, error) {
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
)
|
||||
|
||||
// TestFactory_Lazy ensures none of the closures execute work at construction
|
||||
// time — `--help` / `completion` must not trigger HTTP / keyring access.
|
||||
// time - `--help` / `completion` must not trigger HTTP / keyring access.
|
||||
func TestFactory_Lazy(t *testing.T) {
|
||||
var configCalls, clientCalls, prompterCalls int
|
||||
f := &Factory{
|
||||
@@ -39,7 +39,7 @@ func TestFactory_Lazy(t *testing.T) {
|
||||
return prompt.AgentPrompter{}
|
||||
},
|
||||
}
|
||||
// Asserting on closure presence — none should have run yet.
|
||||
// Asserting on closure presence - none should have run yet.
|
||||
assert.Equal(t, 0, configCalls)
|
||||
assert.Equal(t, 0, clientCalls)
|
||||
assert.Equal(t, 0, prompterCalls)
|
||||
@@ -74,7 +74,7 @@ func TestNew_FoundationDefaults(t *testing.T) {
|
||||
|
||||
// TestFactory_ContextOverride verifies the global --context flag mechanism:
|
||||
// f.ContextOverride replaces config.CurrentContext for this invocation only,
|
||||
// without writing to disk. Spec §1.2.
|
||||
// without writing to disk.
|
||||
func TestFactory_ContextOverride(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", dir)
|
||||
@@ -234,7 +234,7 @@ func TestBuildClient_HappyPath(t *testing.T) {
|
||||
|
||||
func TestBuildClient_SkipsUnreferencedSecrets(t *testing.T) {
|
||||
// If the context doesn't list APIKeyRef, buildClient must not call
|
||||
// Get(api_key) — a perf invariant: avoid keychain trips for unused creds.
|
||||
// Get(api_key) - a perf invariant: avoid keychain trips for unused creds.
|
||||
store := &countingSecrets{MemStore: secrets.NewMemStore()}
|
||||
require.NoError(t, store.Set("p", "access", "jwt"))
|
||||
f := &Factory{
|
||||
@@ -310,7 +310,7 @@ func TestResolveKB_Chain(t *testing.T) {
|
||||
t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose")
|
||||
dir := t.TempDir()
|
||||
resolveKBChdir(t, dir)
|
||||
// Drop a project link too — must be ignored.
|
||||
// Drop a project link too - must be ignored.
|
||||
require.NoError(t, projectlink.Save(filepath.Join(dir, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"}))
|
||||
|
||||
clientCalls := 0
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
// NormalizeHost validates and canonicalizes a `--host` value. Trailing
|
||||
// slashes are trimmed. Every failure path returns CodeInputInvalidArgument —
|
||||
// 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).
|
||||
//
|
||||
@@ -30,7 +30,7 @@ func NormalizeHost(host string) (string, error) {
|
||||
// ValidateHTTPURL applies the same http/https URL rules NormalizeHost uses,
|
||||
// but parameterized by flagLabel so error messages name the caller's flag
|
||||
// (e.g. "--host", "--from-url"). Returns CodeInputInvalidArgument on any
|
||||
// failure. Empty `value` is not pre-checked here — callers that distinguish
|
||||
// failure. Empty `value` is not pre-checked here - callers that distinguish
|
||||
// "missing" from "malformed" should test for empty before calling.
|
||||
func ValidateHTTPURL(flagLabel, value string) error {
|
||||
u, err := url.Parse(value)
|
||||
|
||||
@@ -118,7 +118,7 @@ func TestAddJSONFlags_JQWithoutJSON(t *testing.T) {
|
||||
if err.Error() != want {
|
||||
t.Errorf("wrong message.\nwant: %q\ngot: %q", want, err.Error())
|
||||
}
|
||||
// Must NOT be a FlagError — gh emits this as a plain error so exit
|
||||
// Must NOT be a FlagError - gh emits this as a plain error so exit
|
||||
// code stays 1, not 2.
|
||||
var fe *cmdutil.FlagError
|
||||
if errors.As(err, &fe) {
|
||||
|
||||
@@ -38,7 +38,7 @@ func ResolveKBFlag(ctx context.Context, lister KBLister, raw string) (string, er
|
||||
}
|
||||
|
||||
// ResolveKBNameToID looks up a knowledge base by name and returns its ID.
|
||||
// Used by `link` and `Factory.ResolveKB` — a single lookup so the match
|
||||
// Used by `link` and `Factory.ResolveKB` - a single lookup so the match
|
||||
// policy (currently exact case-sensitive) lives in one place.
|
||||
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
|
||||
kbs, err := lister.ListKnowledgeBases(ctx)
|
||||
|
||||
Reference in New Issue
Block a user