feat(cli): contract test suite + dependabot (PR-8)

cli/acceptance/contract/:
  envelope_test.go    — 16 envelope golden cases (9 commands × {success/error
                        variants}; 3 cases dropped with rationale: doctor.success
                        non-offline has unstable timing detail; auth_login.* needs
                        stdin/keyring scaffold deferred to v0.2; context_use.error
                        needs leaf-local --json deferred to follow-up)
  errorcodes_test.go  — single-direction AST scan of cli/cmd/ extracting first
                        arg of cmdutil.NewError / cmdutil.Wrapf calls;
                        ClassifyHTTPError dynamic-classify bridged via
                        cmdutil.ClassifyHTTPErrorOutputs() per spec §4.3.
  testdata/envelopes/ — 16 JSON golden files

helpers_test.go (PR-6 scaffold) extended:
  runCmd now wires cobra Out/Err sinks (version uses c.OutOrStdout) AND
  replicates cmd.Execute()'s error-envelope path so error-case goldens are
  populated. Without this, every error scenario's golden was 0 bytes.

cli/cmd/root.go: mapCobraError → MapCobraError, wantsJSONOutput → WantsJSONOutput
                 (exported so the contract test helper can replicate Execute()'s
                 envelope-printing path without calling Execute() itself).
                 root_test.go updated to use new exported names.

.github/dependabot.yml (新增):gomod /cli + github-actions weekly,gh-style
                              ignore semver-major to avoid noise. Open-source
                              dependency safety,independent of release cadence.

v0.1 不发布到任何分发平台 (release infra 推迟到发布窗口 milestone)。
This commit is contained in:
nullkey
2026-05-08 16:42:17 +08:00
committed by lyingbug
parent cf84bf2a38
commit bb592a59a6
38 changed files with 1245 additions and 197 deletions
+4 -1
View File
@@ -31,9 +31,12 @@ func TestNewCmdAuth_TreeShape(t *testing.T) {
func TestNewCmdLogin_FlagsRegistered(t *testing.T) {
cmd := NewCmdLogin(&cmdutil.Factory{}, nil)
for _, name := range []string{"host", "context", "with-token", "json"} {
for _, name := range []string{"host", "name", "with-token", "json"} {
assert.NotNilf(t, cmd.Flags().Lookup(name), "flag %s missing", name)
}
// `--context` should NOT be a local flag (it's the global persistent flag).
// Local registration would silently shadow the global single-shot override.
assert.Nil(t, cmd.Flags().Lookup("context"), "auth login must not declare a local --context flag (use --name)")
}
func TestNewCmdLogin_InvokesRunF(t *testing.T) {
+5 -2
View File
@@ -19,7 +19,10 @@ import (
// LoginOptions is the configuration captured from flags + prompts.
type LoginOptions struct {
Host string // --host
Context string // --context name to write
Context string // --name: context name to write into config.yaml
// (was --context in v0.0; renamed v0.1 to
// avoid shadowing the new global --context
// single-shot override flag)
WithToken bool // --with-token (read api key from stdin instead of prompting password)
APIKey string // populated by --with-token from stdin
Email string
@@ -60,7 +63,7 @@ the current_context in ~/.config/weknora/config.yaml.`,
},
}
cmd.Flags().StringVar(&opts.Host, "host", "", "WeKnora server URL, e.g. https://kb.example.com")
cmd.Flags().StringVar(&opts.Context, "context", "default", "Name to assign this context in config.yaml")
cmd.Flags().StringVar(&opts.Context, "name", "default", "Context name to register in config.yaml")
cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.MustRequireFlag(cmd, "host")
+22 -9
View File
@@ -2,6 +2,7 @@ package contextcmd
import (
"fmt"
"sort"
"github.com/spf13/cobra"
@@ -17,7 +18,15 @@ func NewCmdUse(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "use <name>",
Short: "Switch the default context for subsequent commands",
Args: cobra.ExactArgs(1),
Long: `Switches the default context written in config.yaml. Names are case-sensitive.
The active context is what every subsequent command uses for auth + host. The
global --context flag (e.g. weknora --context staging kb list) overrides for
one command without writing to disk.`,
Example: ` weknora context use staging # persist switch
weknora --context staging kb list # one-shot override (no disk write)
weknora context use --help # this help`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
return runUse(args[0])
},
@@ -58,10 +67,13 @@ func notFoundError(name string, cfg *config.Config) error {
Hint: "no contexts registered — run `weknora auth login` first",
}
}
candidate := closestMatch(name, contextKeys(cfg.Contexts))
hint := availableHint(cfg)
keys := contextKeys(cfg.Contexts)
candidate := closestMatch(name, keys)
var hint string
if candidate != "" && candidate != name {
hint = fmt.Sprintf("did you mean: %q?", candidate)
} else {
hint = fmt.Sprintf("available contexts: %v", keys)
}
return &cmdutil.Error{
Code: cmdutil.CodeLocalContextNotFound,
@@ -78,16 +90,17 @@ func contextKeys(m map[string]config.Context) []string {
return out
}
func availableHint(cfg *config.Config) string {
return fmt.Sprintf("available contexts: %v", contextKeys(cfg.Contexts))
}
// closestMatch returns the candidate with min levenshtein distance ≤ 2,
// or "" if none qualifies.
// or "" if none qualifies. Ties broken by lexicographic order so the hint
// is deterministic across map-iteration orderings (Go randomizes range over
// map; without this, did-you-mean output is flaky for equally-close
// candidates).
func closestMatch(target string, candidates []string) string {
sorted := append([]string(nil), candidates...)
sort.Strings(sorted)
best := ""
bestD := 3
for _, c := range candidates {
for _, c := range sorted {
d := levenshtein(target, c)
if d < bestD {
bestD = d
+29 -2
View File
@@ -63,8 +63,35 @@ func TestUse_NotFound_WithDidYouMean(t *testing.T) {
if cm.Code != cmdutil.CodeLocalContextNotFound {
t.Errorf("code = %q, want %q", cm.Code, cmdutil.CodeLocalContextNotFound)
}
if !strings.Contains(cm.Hint, "production") {
t.Errorf("hint should suggest 'production', got %q", cm.Hint)
if cm.Hint != `did you mean: "production"?` {
t.Errorf("hint should be exact `did you mean: \"production\"?`, got %q", cm.Hint)
}
}
// TestUse_NotFound_DeterministicTieBreak guards against map-iteration-order
// flake: when two candidates have equal levenshtein distance, the suggestion
// must be reproducibly the lexicographically-smaller one.
func TestUse_NotFound_DeterministicTieBreak(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t)
cfg := &config.Config{Contexts: map[string]config.Context{
"prod": {Host: "https://a"},
"prom": {Host: "https://b"},
"prog": {Host: "https://c"},
}}
if err := config.Save(cfg); err != nil {
t.Fatalf("Save: %v", err)
}
// "prox" is distance 1 from prod / prom (both win); lex tie-break → prod.
for i := 0; i < 5; i++ {
err := runUse("prox")
if err == nil {
t.Fatalf("iter %d: expected error", i)
}
cm := err.(*cmdutil.Error)
if cm.Hint != `did you mean: "prod"?` {
t.Fatalf("iter %d: tie-break must pick lex-smallest 'prod', got %q", i, cm.Hint)
}
}
}
+127 -83
View File
@@ -41,10 +41,21 @@ type Options struct {
JSONOut bool
}
// Status is the per-check outcome on the wire (JSON Marshal still emits the
// underlying string). Typed so cascade comparisons can't typo against bare
// "ok"/"fail"/"skip" string literals.
type Status string
const (
StatusOK Status = "ok"
StatusFail Status = "fail"
StatusSkip Status = "skip"
)
// Check is one row in the report.
type Check struct {
Name string `json:"name"`
Status string `json:"status"` // ok / fail / skip
Status Status `json:"status"`
Details string `json:"details,omitempty"`
Hint string `json:"hint,omitempty"`
}
@@ -88,13 +99,30 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
return nil // doctor 自身不返回 error;失败状态在 data.checks
},
}
cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache; force re-probe")
cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage")
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)")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
agent.SetAgentHelp(cmd, "Returns 4 health checks. AGENT short-circuit: read data.summary.all_passed; if false, inspect data.checks[].status (ok/fail/skip).")
return cmd
}
// cascade implements the two short-circuits every gated check shares:
// 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.
func cascade(c *Check, offline bool, prereqs ...*Check) bool {
if offline {
c.Status, c.Details = StatusSkip, "offline mode"
return true
}
for _, p := range prereqs {
if p.Status != StatusOK {
c.Status, c.Details = StatusSkip, "prereq failed: "+p.Name
return true
}
}
return false
}
// runChecks executes the 4-item check matrix with cascade-skip semantics.
// Pure function over Services so tests can drive it directly.
func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string) Result {
@@ -105,118 +133,105 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
{Name: "credential_storage"},
}
// 1. base_url_reachable
if opts.Offline {
checks[0].Status = "skip"
checks[0].Details = "offline mode"
} else {
// 1. base_url_reachable — gated by offline only.
if !cascade(&checks[0], opts.Offline) {
t0 := time.Now()
if err := svc.PingBaseURL(ctx); err != nil {
checks[0].Status = "fail"
checks[0].Hint = "verify --base-url and network reachability"
checks[0].Status = StatusFail
checks[0].Hint = "verify the host configured for the active context (run `weknora auth login --host=...`) and network reachability"
checks[0].Details = err.Error()
} else {
checks[0].Status = "ok"
checks[0].Status = StatusOK
checks[0].Details = fmt.Sprintf("reachable in %s", time.Since(t0).Round(time.Millisecond))
}
}
// 2. auth_credential — depends on base_url
switch {
case opts.Offline:
checks[1].Status = "skip"
checks[1].Details = "offline mode"
case checks[0].Status == "fail":
checks[1].Status = "skip"
checks[1].Details = "prereq failed: base_url_reachable"
default:
_, err := svc.GetCurrentUser(ctx)
if err != nil {
checks[1].Status = "fail"
// 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
checks[1].Hint = "run `weknora auth login`"
checks[1].Details = err.Error()
} else {
checks[1].Status = "ok"
checks[1].Status = StatusOK
}
}
// 3. server_version — depends on auth_credential
switch {
case opts.Offline:
checks[2].Status = "skip"
checks[2].Details = "offline mode"
case checks[1].Status != "ok":
checks[2].Status = "skip"
checks[2].Details = "prereq failed: auth_credential"
default:
// 3. server_version — needs auth_credential.
if !cascade(&checks[2], opts.Offline, &checks[1]) {
info, fromCache, err := loadOrProbeServerInfo(ctx, opts, svc)
if err != nil {
checks[2].Status = "fail"
checks[2].Status = StatusFail
checks[2].Details = err.Error()
} else {
level, hint := compat.Compat(info.ServerVersion, cliVer)
suffix := ""
if fromCache {
suffix = " (cached, pass --no-cache to refresh)"
}
if level == compat.HardError {
checks[2].Status = "fail"
checks[2].Hint = hint
checks[2].Details = "server " + info.ServerVersion + suffix
} else {
checks[2].Status = "ok"
if hint != "" {
checks[2].Details = hint + suffix
} else {
checks[2].Details = fmt.Sprintf("server %s%s", info.ServerVersion, suffix)
}
}
fillVersionCheck(&checks[2], info, cliVer, fromCache)
}
}
// 4. credential_storage — independent of network
// 4. credential_storage — independent of network; never gated by offline.
if _, err := secrets.NewBestEffortStore(); err != nil {
checks[3].Status = "fail"
checks[3].Status = StatusFail
checks[3].Details = err.Error()
checks[3].Hint = "verify keyring access; falls back to file store"
} else {
checks[3].Status = "ok"
checks[3].Status = StatusOK
checks[3].Details = "keyring or file storage available"
}
return Result{Summary: summarize(checks), Checks: checks}
}
// loadOrProbeServerInfo respects --no-cache:
// --no-cache or stale/missing cache → call svc.GetSystemInfo + SaveCache
// else → return cached Info (fromCache=true)
//
// SaveCache failure does NOT propagate — best-effort write. The probe
// data is still returned to the caller for the compat check.
// fillVersionCheck applies compat.Compat to (server, cli) version pair and
// 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().
func fillVersionCheck(c *Check, info *compat.Info, cliVer string, fromCache bool) {
level, hint := compat.Compat(info.ServerVersion, cliVer)
suffix := ""
if fromCache {
suffix = " (cached, pass --no-cache to refresh)"
}
if level == compat.HardError {
c.Status = StatusFail
c.Hint = hint
c.Details = "server " + info.ServerVersion + suffix
return
}
c.Status = StatusOK
if hint != "" {
c.Details = hint + suffix
} else {
c.Details = fmt.Sprintf("server %s%s", info.ServerVersion, suffix)
}
}
// loadOrProbeServerInfo respects --no-cache: load fresh cache when allowed,
// else call compat.Probe (which wraps svc.GetSystemInfo) and persist. Cache
// write is best-effort. Returns fromCache so the caller can render the
// "cached" presentation hint without a brittle ProbedAt heuristic.
func loadOrProbeServerInfo(ctx context.Context, opts *Options, svc Services) (info *compat.Info, fromCache bool, err error) {
if !opts.NoCache {
if cached, fresh, _ := compat.LoadCache(); fresh && cached != nil {
return cached, true, nil
}
}
sys, err := svc.GetSystemInfo(ctx)
probed, err := compat.Probe(ctx, svc)
if err != nil {
return nil, false, err
}
fresh := &compat.Info{ServerVersion: sys.Version, ProbedAt: time.Now()}
_ = compat.SaveCache(fresh) // best-effort
return fresh, false, nil
_ = compat.SaveCache(probed)
return probed, false, nil
}
func summarize(cs []Check) Summary {
s := Summary{}
for _, c := range cs {
switch c.Status {
case "ok":
case StatusOK:
s.Passed++
case "fail":
case StatusFail:
s.Failed++
case "skip":
case StatusSkip:
s.Skipped++
}
}
@@ -232,9 +247,9 @@ func emit(opts *Options, r Result) {
for _, c := range r.Checks {
marker := "[ok]"
switch c.Status {
case "fail":
case StatusFail:
marker = "[fail]"
case "skip":
case StatusSkip:
marker = "[skip]"
}
line := fmt.Sprintf("%-6s %-20s %s", marker, c.Name, c.Status)
@@ -251,16 +266,34 @@ func emit(opts *Options, r Result) {
}
// buildServices wires the Factory closures into the doctor.Services interface.
// Reads the active context's host so PingBaseURL targets the user's actual
// 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 —
// 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
// resolve and surface their own failure as a per-check StatusFail.
func buildServices(f *cmdutil.Factory) (Services, error) {
cli, err := f.Client()
cfg, err := f.Config()
if err != nil {
return nil, err
}
return &realServices{cli: cli}, nil
host := ""
if ctx, ok := cfg.Contexts[cfg.CurrentContext]; ok {
host = ctx.Host
}
// WEKNORA_BASE_URL still wins as a test/dev override; production reads host.
if v := os.Getenv("WEKNORA_BASE_URL"); v != "" {
host = v
}
return &realServices{f: f, host: host}, nil
}
type realServices struct {
cli *sdk.Client
f *cmdutil.Factory
host string
}
// pingTimeout caps the HEAD /health probe so a wedged TCP connection
@@ -268,9 +301,10 @@ type realServices struct {
const pingTimeout = 5 * time.Second
func (s *realServices) PingBaseURL(ctx context.Context) error {
// WEKNORA_BASE_URL is the test-scaffold override; production should plumb
// config.Host through (TODO v0.2: add Client.BaseURL() accessor in SDK).
url := envOrDefault("WEKNORA_BASE_URL", "http://localhost:8080") + "/health"
if s.host == "" {
return fmt.Errorf("no host configured for active context")
}
url := s.host + "/health"
ctx, cancel := context.WithTimeout(ctx, pingTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, nil)
@@ -288,16 +322,26 @@ func (s *realServices) PingBaseURL(ctx context.Context) error {
return nil
}
// GetCurrentUser lazily resolves the SDK client. When no context is configured
// or credentials missing, f.Client() returns auth.unauthenticated; we surface
// that as the auth_credential check's failure rather than aborting doctor.
func (s *realServices) GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResponse, error) {
return s.cli.GetCurrentUser(ctx)
}
func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) {
return s.cli.GetSystemInfo(ctx)
cli, err := s.f.Client()
if err != nil {
return nil, err
}
return cli.GetCurrentUser(ctx)
}
func envOrDefault(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
// 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
// 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()
if err != nil {
return nil, err
}
return def
return cli.GetSystemInfo(ctx)
}
+57 -8
View File
@@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/compat"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
@@ -48,6 +49,9 @@ func TestDoctor_AllOK(t *testing.T) {
if !r.Summary.AllPassed {
t.Errorf("expected all_passed, got summary %+v", r.Summary)
}
if r.Summary.Passed != 4 {
t.Errorf("expected Passed=4 (one per check), got %+v", r.Summary)
}
if r.Summary.Failed != 0 || r.Summary.Skipped != 0 {
t.Errorf("expected 0 fail / 0 skip, got %+v", r.Summary)
}
@@ -69,13 +73,16 @@ func TestDoctor_BaseURLFails_DownstreamSkip(t *testing.T) {
if r.Summary.Skipped != 2 {
t.Errorf("expected 2 skipped (auth_credential + server_version), got %d", r.Summary.Skipped)
}
if r.Checks[0].Status != "fail" {
if r.Checks[0].Status != StatusFail {
t.Errorf("base_url_reachable status = %q, want fail", r.Checks[0].Status)
}
if r.Checks[1].Status != "skip" {
if !strings.Contains(r.Checks[0].Hint, "auth login") {
t.Errorf("base_url fail hint should reference `auth login`, got %q", r.Checks[0].Hint)
}
if r.Checks[1].Status != StatusSkip {
t.Errorf("auth_credential status = %q, want skip", r.Checks[1].Status)
}
if r.Checks[2].Status != "skip" {
if r.Checks[2].Status != StatusSkip {
t.Errorf("server_version status = %q, want skip", r.Checks[2].Status)
}
// credential_storage 与网络无关,应该独立运行(不受 base_url fail 影响)
@@ -96,7 +103,7 @@ func TestDoctor_Offline_OnlyKeyringChecked(t *testing.T) {
if last.Name != "credential_storage" {
t.Errorf("last check = %q, want credential_storage", last.Name)
}
if last.Status == "skip" {
if last.Status == StatusSkip {
t.Error("credential_storage should NOT be skipped even in offline mode")
}
}
@@ -109,13 +116,13 @@ func TestDoctor_AuthFails_VersionSkipped(t *testing.T) {
systemInfo: &sdk.SystemInfo{Version: "1.0.0"},
}
r := runChecks(context.Background(), &Options{}, svc, "1.0.0")
if r.Checks[0].Status != "ok" {
if r.Checks[0].Status != StatusOK {
t.Errorf("base_url should pass, got %q", r.Checks[0].Status)
}
if r.Checks[1].Status != "fail" {
if r.Checks[1].Status != StatusFail {
t.Errorf("auth_credential should fail, got %q", r.Checks[1].Status)
}
if r.Checks[2].Status != "skip" {
if r.Checks[2].Status != StatusSkip {
t.Errorf("server_version should skip due to auth fail, got %q", r.Checks[2].Status)
}
}
@@ -129,7 +136,7 @@ func TestDoctor_CacheHit_SkipsProbe(t *testing.T) {
}
svc := &fakeServices{userResp: goodUserResp()}
r := runChecks(context.Background(), &Options{}, svc, "1.0.0")
if r.Checks[2].Status != "ok" {
if r.Checks[2].Status != StatusOK {
t.Errorf("server_version should be ok via cache, got %q (%s)", r.Checks[2].Status, r.Checks[2].Details)
}
if svc.systemInfoHits.Load() != 0 {
@@ -140,6 +147,48 @@ func TestDoctor_CacheHit_SkipsProbe(t *testing.T) {
}
}
// TestDoctor_NoConfig_StillRunsCredentialStorage guards the package-doc
// promise that credential_storage runs even with zero configuration. Round-4
// reviewer surfaced that buildServices used to abort on f.Client() failure,
// silently violating the doc for any first-time user running `weknora doctor`
// to diagnose setup. The lazy-resolve fix means missing auth surfaces as
// auth_credential=fail, not a top-level command exit.
func TestDoctor_NoConfig_StillRunsCredentialStorage(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t)
f := cmdutil.New()
svc, err := buildServices(f)
if err != nil {
t.Fatalf("buildServices must succeed even with no config; got: %v", err)
}
r := runChecks(context.Background(), &Options{}, svc, "1.0.0")
// All 4 checks must run (no early-exit). Last one is credential_storage and
// has no network/auth dependency, so it must report ok.
if got := len(r.Checks); got != 4 {
t.Fatalf("expected 4 checks executed, got %d", got)
}
if r.Checks[3].Name != "credential_storage" {
t.Errorf("Checks[3] = %q, want credential_storage", r.Checks[3].Name)
}
if r.Checks[3].Status != StatusOK {
t.Errorf("credential_storage must run / pass even without auth, got %q (%s)",
r.Checks[3].Status, r.Checks[3].Details)
}
// base_url_reachable fails (no host); cascade then skips auth_credential
// and server_version. Whether auth/version are skip vs fail is an internal
// cascade detail; the user-visible promise is that 4 checks executed and
// the independent credential_storage one passed.
if r.Checks[0].Status != StatusFail {
t.Errorf("base_url must fail without host, got %q", r.Checks[0].Status)
}
if r.Checks[1].Status == StatusOK {
t.Errorf("auth_credential must NOT report ok without config, got %q", r.Checks[1].Status)
}
}
func TestDoctor_NoCache_BypassesCache(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t)
+7
View File
@@ -3,6 +3,7 @@ package kb
import (
"context"
"fmt"
"sort"
"text/tabwriter"
"time"
@@ -59,6 +60,12 @@ func runList(ctx context.Context, opts *ListOptions, svc ListService) error {
if items == nil {
items = []sdk.KnowledgeBase{} // ensure JSON [] not null
}
// Spec §1.2: default sort by updated_at desc. Server return order is not
// guaranteed, so client-side sort makes output deterministic regardless
// of backend storage choices.
sort.Slice(items, func(i, j int) bool {
return items[i].UpdatedAt.After(items[j].UpdatedAt)
})
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(listResult{Items: items}, nil))
+37 -19
View File
@@ -7,6 +7,7 @@ package cmd
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
@@ -34,8 +35,8 @@ func Execute() int {
if err == nil {
return 0
}
err = mapCobraError(err)
if agent.ShouldUseAgentMode(cmd) || wantsJSONOutput(cmd) {
err = MapCobraError(err)
if agent.ShouldUseAgentMode(cmd) || WantsJSONOutput(cmd) {
cmdutil.PrintErrorEnvelope(iostreams.IO.Out, err)
} else {
cmdutil.PrintError(iostreams.IO.Err, err)
@@ -43,7 +44,7 @@ func Execute() int {
return cmdutil.ExitCode(err)
}
// wantsJSONOutput reports whether cmd was invoked with --json, so error
// WantsJSONOutput reports whether cmd was invoked with --json, so error
// output matches the success format. Persistent flags inherit automatically
// via cmd.Flags().
//
@@ -51,7 +52,10 @@ func Execute() int {
// unknown subcommand or unknown flag at root level. Without this, `weknora
// bogus --json` would emit a human stderr line instead of the envelope the
// agent asked for.
func wantsJSONOutput(cmd *cobra.Command) bool {
//
// Exported so the acceptance/contract test helper can replicate Execute()'s
// envelope-printing path without having to call os.Exit-bound Execute() itself.
func WantsJSONOutput(cmd *cobra.Command) bool {
if v, err := cmd.Flags().GetBool("json"); err == nil && v {
return true
}
@@ -78,16 +82,14 @@ func argsRequestJSON(args []string) bool {
}
// isPflagTruthy mirrors pflag's bool parsing for "--flag=<v>" tokens.
// pflag accepts 1/t/T/TRUE/true/True as truthy.
// pflag delegates to strconv.ParseBool, which accepts 1/t/T/TRUE/true/True
// as truthy and 0/f/F/FALSE/false/False as falsy. Anything else errors.
func isPflagTruthy(v string) bool {
switch v {
case "1", "t", "T", "TRUE", "true", "True":
return true
}
return false
b, err := strconv.ParseBool(v)
return err == nil && b
}
// mapCobraError tags the textually-emitted cobra errors as cmdutil.FlagError
// MapCobraError tags the textually-emitted cobra errors as cmdutil.FlagError
// so they exit 2 like other user invocation mistakes. SetFlagErrorFunc handles
// flag parse errors at parse time; this catches positional/Args validation
// errors and unknown subcommands that propagate as plain errors.
@@ -95,7 +97,10 @@ func isPflagTruthy(v string) bool {
// Pinned to cobra v1.10 message formats (cobra/args.go: ExactArgs / NoArgs;
// cobra/command.go: required-flag / unknown-command). TestMapCobraError_PinnedPrefixes
// guards against a silent break on cobra bumps.
func mapCobraError(err error) error {
//
// Exported so the acceptance/contract test helper can reuse the mapping when
// replicating Execute()'s error-envelope path in-process.
func MapCobraError(err error) error {
if err == nil {
return nil
}
@@ -126,8 +131,15 @@ var cobraFlagErrorPrefixes = []string{
func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
v, commit, date := build.Info()
cmd := &cobra.Command{
Use: "weknora",
Short: "WeKnora CLI — RAG knowledge base from your terminal",
Use: "weknora",
Short: "WeKnora CLI — RAG knowledge base from your terminal",
Long: `WeKnora CLI lets you authenticate, browse knowledge bases, and run
hybrid searches against a WeKnora server from your shell or an AI agent.`,
Example: ` weknora auth login --host=https://kb.example.com # one-time setup
weknora kb list # list knowledge bases
weknora kb get <id> # show one
weknora search "your question" --kb=<id> # hybrid retrieval
weknora doctor --json # health check (agent-readable)`,
SilenceUsage: true,
SilenceErrors: true,
// Version makes cobra auto-register a `--version` global flag that
@@ -137,6 +149,11 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
PersistentPreRun: func(c *cobra.Command, args []string) {
agent.ApplyAgentSugar(c)
// Propagate the global --context flag into the Factory for this
// invocation only. Spec §1.2: single-shot override, no disk write.
if v, _ := c.Flags().GetString("context"); v != "" {
f.ContextOverride = v
}
},
}
// Match `weknora version` line format so both forms output the same.
@@ -161,17 +178,18 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
}
// addGlobalFlags registers persistent flags available on every subcommand.
// Only flags whose behavior is actually wired in v0.0 are listed — flags
// that need work in later PRs (--format multi-value in v0.1, --context in
// v0.1 PR-4, --no-version-check in v0.7's compat probe) are added when
// their consumer lands. A flag that accepts values but does nothing is a
// worse contract than no flag.
// Only flags whose behavior is actually wired are listed — a flag that
// accepts values but does nothing is a worse contract than no flag.
//
// --context lands here in v0.1 (spec §1.2); --no-version-check waits for
// v0.7's compat probe consumer.
func addGlobalFlags(cmd *cobra.Command) {
pf := cmd.PersistentFlags()
pf.Bool("agent", false, "Agent mode: envelope JSON output + no interactive prompts + no progress UI")
pf.Bool("no-interactive", false, "Refuse interactive prompts; missing input becomes a hard error")
pf.Bool("no-progress", false, "Suppress progress bars and spinners")
pf.BoolP("yes", "y", false, "Skip confirmation prompts on destructive operations")
pf.String("context", "", "Override the active context for this invocation (no disk write)")
}
// agentAwareHelpFunc wraps cobra's default help to append the AI agent guidance
+34 -7
View File
@@ -93,24 +93,51 @@ func TestMapCobraError_PinnedPrefixes(t *testing.T) {
func TestMapCobraError(t *testing.T) {
t.Run("nil passes through", func(t *testing.T) {
assert.Nil(t, mapCobraError(nil))
assert.Nil(t, MapCobraError(nil))
})
t.Run("non-matching error passes through", func(t *testing.T) {
err := mapCobraError(assert.AnError)
err := MapCobraError(assert.AnError)
assert.Equal(t, assert.AnError, err)
})
t.Run("unknown command wraps as FlagError", func(t *testing.T) {
err := mapCobraError(errors.New(`unknown command "bogus" for "weknora"`))
err := MapCobraError(errors.New(`unknown command "bogus" for "weknora"`))
var fe *cmdutil.FlagError
assert.True(t, errors.As(err, &fe))
})
t.Run("required flag wraps as FlagError", func(t *testing.T) {
err := mapCobraError(errors.New(`required flag(s) "host" not set`))
err := MapCobraError(errors.New(`required flag(s) "host" not set`))
var fe *cmdutil.FlagError
assert.True(t, errors.As(err, &fe))
})
}
// TestRoot_ContextFlagPropagation guards the cobra → Factory wiring of the
// global --context flag. Without this, a future refactor that disconnects
// PersistentPreRun from f.ContextOverride would only fail e2e — the
// per-package TestFactory_ContextOverride only proves the Factory side.
func TestRoot_ContextFlagPropagation(t *testing.T) {
cases := []struct {
name string
args []string
want string
}{
{"no flag", []string{"version"}, ""},
{"global before subcmd", []string{"--context", "staging", "version"}, "staging"},
{"--context=value form", []string{"--context=prod", "version"}, "prod"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := cmdutil.New()
root := NewRootCmd(f)
root.SetArgs(tc.args)
root.SetOut(&bytes.Buffer{})
root.SetErr(&bytes.Buffer{})
require.NoError(t, root.Execute())
assert.Equal(t, tc.want, f.ContextOverride)
})
}
}
func TestArgsRequestJSON(t *testing.T) {
cases := []struct {
name string
@@ -134,12 +161,12 @@ func TestArgsRequestJSON(t *testing.T) {
func TestWantsJSONOutput(t *testing.T) {
// Build a minimal *cobra.Command with the json flag directly so we test
// the helper without going through cobra's parse pipeline. wantsJSONOutput
// the helper without going through cobra's parse pipeline. WantsJSONOutput
// reads cmd.Flags() which on a fresh command equals LocalFlags().
c := &cobra.Command{Use: "x"}
c.Flags().Bool("json", false, "")
assert.False(t, wantsJSONOutput(c), "default: --json unset")
assert.False(t, WantsJSONOutput(c), "default: --json unset")
require.NoError(t, c.Flags().Set("json", "true"))
assert.True(t, wantsJSONOutput(c), "--json=true honored")
assert.True(t, WantsJSONOutput(c), "--json=true honored")
}