feat(cli): --log-level + kb/agent status & check + cross-cutting refactor

Operability surface and the bulk of the jopts→fopts migration:

* --log-level error|warn|info|debug + WEKNORA_LOG_LEVEL env, wired to
  the SDK via client.SetDebugLevel. Invalid --log-level returns FlagError
  (exit 2).
* kb status <kb-id> / kb check <kb-id> verb split (1 HTTP vs 1+N for
  failed_count aggregation).
* agent status <agent-id> / agent check <agent-id> verb split
  (probes kb_scope_all_reachable via 1+N HTTP).
* kb create <name> positional (matches agent create).
* Positional id help strings namespaced (<kb-id> / <agent-id>).
* All auth / context / link / doctor / kb / agent CRUD commands migrated
  to the FormatOptions API.
* root.go Execute(ctx) takes a context so signal-cancellation propagates
  via cmd.Context() into long-running commands.
* Pagination termination uses len(accum) >= total (not page*pageSize)
  so server-capped page sizes do not truncate aggregations.
This commit is contained in:
nullkey
2026-05-18 01:38:16 +08:00
committed by lyingbug
parent 7eeb3bec5d
commit 0e081aec5c
64 changed files with 1581 additions and 393 deletions
+8 -7
View File
@@ -16,7 +16,7 @@ type AddOptions struct {
User string
}
// contextAddFields enumerates the fields surfaced for `--json` discovery on
// contextAddFields enumerates the fields surfaced for `--format json` discovery on
// `context add`. The result describes the newly-registered context.
var contextAddFields = []string{
"name", "host", "user", "current",
@@ -52,21 +52,22 @@ adds leave the current context untouched.`,
weknora context add prod --host https://prod.example.com --user alice@example.com`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
return runAdd(opts, jopts, args[0])
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
return runAdd(opts, fopts, args[0])
},
}
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)")
cmdutil.AddJSONFlags(cmd, contextAddFields)
cmdutil.AddFormatFlag(cmd, contextAddFields...)
_ = cmd.MarkFlagRequired("host")
return cmd
}
func runAdd(opts *AddOptions, jopts *cmdutil.JSONOptions, name string) error {
func runAdd(opts *AddOptions, fopts *cmdutil.FormatOptions, name string) error {
if err := validateName(name); err != nil {
return err
}
@@ -98,8 +99,8 @@ func runAdd(opts *AddOptions, jopts *cmdutil.JSONOptions, name string) error {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst})
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst})
}
if wasFirst {
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
+5 -5
View File
@@ -14,7 +14,7 @@ func TestAdd_HappyPath(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
out, _ := iostreams.SetForTest(t)
if err := runAdd(&AddOptions{Host: "https://my.example.com", User: "alice@example.com"}, nil, "staging"); err != nil {
if err := runAdd(&AddOptions{Host: "https://my.example.com", User: "alice@example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging"); err != nil {
t.Fatalf("runAdd: %v", err)
}
@@ -53,7 +53,7 @@ func TestAdd_DuplicateName(t *testing.T) {
t.Fatalf("Save: %v", err)
}
err := runAdd(&AddOptions{Host: "https://new.example.com"}, nil, "staging")
err := runAdd(&AddOptions{Host: "https://new.example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging")
if err == nil {
t.Fatal("expected error on duplicate name")
}
@@ -82,7 +82,7 @@ func TestAdd_BadHost(t *testing.T) {
"http://", // missing host
}
for _, h := range bad {
err := runAdd(&AddOptions{Host: h}, nil, "staging")
err := runAdd(&AddOptions{Host: h}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging")
if err == nil {
t.Errorf("host=%q: expected error", h)
continue
@@ -110,7 +110,7 @@ func TestAdd_SecondContextDoesNotChangeCurrent(t *testing.T) {
t.Fatalf("Save: %v", err)
}
if err := runAdd(&AddOptions{Host: "https://stg.example.com"}, nil, "staging"); err != nil {
if err := runAdd(&AddOptions{Host: "https://stg.example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging"); err != nil {
t.Fatalf("runAdd: %v", err)
}
got, _ := config.Load()
@@ -123,7 +123,7 @@ func TestAdd_JSON(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
out, _ := iostreams.SetForTest(t)
if err := runAdd(&AddOptions{Host: "https://my.example.com"}, &cmdutil.JSONOptions{}, "staging"); err != nil {
if err := runAdd(&AddOptions{Host: "https://my.example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, "staging"); err != nil {
t.Fatalf("runAdd: %v", err)
}
var got map[string]any
+8 -7
View File
@@ -15,7 +15,7 @@ import (
type ListOptions struct{}
// contextListFields enumerates the fields surfaced for `--json` discovery on
// contextListFields enumerates the fields surfaced for `--format json` discovery on
// `context list`. Each entry is a per-context summary row.
var contextListFields = []string{
"name", "host", "user", "current",
@@ -43,18 +43,19 @@ run "weknora auth list" for that. "context list" is the catalog of *where*
the CLI can talk to; "auth list" is the catalog of *how*.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
return runList(jopts)
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
return runList(fopts)
},
}
cmdutil.AddJSONFlags(cmd, contextListFields)
cmdutil.AddFormatFlag(cmd, contextListFields...)
return cmd
}
func runList(jopts *cmdutil.JSONOptions) error {
func runList(fopts *cmdutil.FormatOptions) error {
cfg, err := config.Load()
if err != nil {
return err
@@ -70,8 +71,8 @@ func runList(jopts *cmdutil.JSONOptions) error {
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, entries)
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, entries)
}
if len(entries) == 0 {
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` (or `weknora context add`) to create one.")
+3 -3
View File
@@ -14,7 +14,7 @@ func TestList_Empty(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
out, _ := iostreams.SetForTest(t)
if err := runList(nil); err != nil {
if err := runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "No contexts") {
@@ -38,7 +38,7 @@ func TestList_MultipleSorted(t *testing.T) {
t.Fatalf("Save: %v", err)
}
if err := runList(nil); err != nil {
if err := runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
@@ -75,7 +75,7 @@ func TestList_JSON(t *testing.T) {
t.Fatalf("Save: %v", err)
}
if err := runList(&cmdutil.JSONOptions{}); err != nil {
if err := runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
t.Fatalf("runList: %v", err)
}
+9 -8
View File
@@ -16,7 +16,7 @@ type RemoveOptions struct {
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
}
// contextRemoveFields enumerates the fields surfaced for `--json` discovery on
// contextRemoveFields enumerates the fields surfaced for `--format json` discovery on
// `context remove`. The result reports the disposition of the removed entry.
var contextRemoveFields = []string{
"name", "removed", "was_current",
@@ -46,28 +46,29 @@ Removing the current context also clears CurrentContext - subsequent commands
will error until you select another with ` + "`weknora context use <name>`" + ` or pick
one up via the global ` + "`--context`" + ` flag. Because that change is observable in
every later command, removing the current context requires explicit -y/--yes
in scripted / --json invocations (exit code 10; see cli/README.md).`,
in scripted / --format json invocations (exit code 10; see cli/README.md).`,
Example: ` weknora context remove staging # remove non-current → no prompt
weknora context remove production -y # remove current → confirm`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Yes, _ = c.Flags().GetBool("yes")
store, err := f.Secrets()
if err != nil {
return err
}
return runRemove(opts, jopts, args[0], store, f.Prompter())
return runRemove(opts, fopts, args[0], store, f.Prompter())
},
}
cmdutil.AddJSONFlags(cmd, contextRemoveFields)
cmdutil.AddFormatFlag(cmd, contextRemoveFields...)
return cmd
}
func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, store secrets.Store, p prompt.Prompter) error {
func runRemove(opts *RemoveOptions, fopts *cmdutil.FormatOptions, name string, store secrets.Store, p prompt.Prompter) error {
cfg, err := config.Load()
if err != nil {
return err
@@ -78,7 +79,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
}
wasCurrent := name == cfg.CurrentContext
jsonOut := jopts.Enabled()
jsonOut := fopts.WantsJSON()
// Confirmation only fires for removing the current context - non-current
// remove uses the same low-friction policy as `auth logout`.
if wasCurrent {
@@ -100,7 +101,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
result := removeResult{Name: name, Removed: true, WasCurrent: wasCurrent}
if jsonOut {
return jopts.Emit(iostreams.IO.Out, result)
return fopts.Emit(iostreams.IO.Out, result)
}
if wasCurrent {
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared - run `weknora context use <name>` to pick another)\n", name)
+5 -5
View File
@@ -50,7 +50,7 @@ func TestRemove_NonCurrent_NoPromptNeeded(t *testing.T) {
store := seedStore(t, "staging", "api_key")
p := &testutil.ConfirmPrompter{}
if err := runRemove(&RemoveOptions{}, nil, "staging", store, p); err != nil {
if err := runRemove(&RemoveOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging", store, p); err != nil {
t.Fatalf("runRemove: %v", err)
}
if p.Asked {
@@ -82,7 +82,7 @@ func TestRemove_NotFound_WithDidYouMean(t *testing.T) {
t.Fatalf("Save: %v", err)
}
err := runRemove(&RemoveOptions{}, nil, "prodution", secrets.NewMemStore(), &testutil.ConfirmPrompter{})
err := runRemove(&RemoveOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "prodution", secrets.NewMemStore(), &testutil.ConfirmPrompter{})
if err == nil {
t.Fatal("expected not-found error")
}
@@ -114,7 +114,7 @@ func TestRemove_Current_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
}
store := seedStore(t, "production", "access")
err := runRemove(&RemoveOptions{}, nil, "production", store, &testutil.ConfirmPrompter{})
err := runRemove(&RemoveOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "production", store, &testutil.ConfirmPrompter{})
if err == nil {
t.Fatal("expected confirmation-required error")
}
@@ -153,7 +153,7 @@ func TestRemove_Current_WithYes_ClearsCurrent(t *testing.T) {
}
store := seedStore(t, "production", "access")
if err := runRemove(&RemoveOptions{Yes: true}, nil, "production", store, &testutil.ConfirmPrompter{}); err != nil {
if err := runRemove(&RemoveOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "production", store, &testutil.ConfirmPrompter{}); err != nil {
t.Fatalf("runRemove: %v", err)
}
got, _ := config.Load()
@@ -182,7 +182,7 @@ func TestRemove_Current_TTY_PromptNo(t *testing.T) {
}
p := &testutil.ConfirmPrompter{Answer: false}
err := runRemove(&RemoveOptions{}, nil, "production", secrets.NewMemStore(), p)
err := runRemove(&RemoveOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "production", secrets.NewMemStore(), p)
if err == nil {
t.Fatal("expected user-aborted error")
}
+9 -8
View File
@@ -11,7 +11,7 @@ import (
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// contextUseFields enumerates fields surfaced for `--json` discovery on
// contextUseFields enumerates fields surfaced for `--format json` discovery on
// `context use`.
var contextUseFields = []string{"current_context", "previous_context"}
@@ -31,17 +31,18 @@ you to. Context selection is a user preference; one-shot overrides should use
the global --context flag instead, which writes nothing to disk.`,
Example: ` weknora context use staging # persist switch
weknora --context staging kb list # one-shot override (no disk write)
weknora context use staging --json # {current_context, previous_context}`,
weknora context use staging --format json # {current_context, previous_context}`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
return runUse(args[0], jopts)
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
return runUse(args[0], fopts)
},
}
cmdutil.AddJSONFlags(cmd, contextUseFields)
cmdutil.AddFormatFlag(cmd, contextUseFields...)
return cmd
}
@@ -50,7 +51,7 @@ type useResult struct {
PreviousContext string `json:"previous_context,omitempty"`
}
func runUse(name string, jopts *cmdutil.JSONOptions) error {
func runUse(name string, fopts *cmdutil.FormatOptions) error {
cfg, err := config.Load()
if err != nil {
return err
@@ -64,8 +65,8 @@ func runUse(name string, jopts *cmdutil.JSONOptions) error {
return err
}
result := useResult{CurrentContext: name, PreviousContext: prev}
if jopts.Enabled() {
return jopts.Emit(iostreams.IO.Out, result)
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, result)
}
if prev != "" && prev != name {
fmt.Fprintf(iostreams.IO.Out, "✓ Switched context to %s (was %s)\n", name, prev)
+5 -5
View File
@@ -24,7 +24,7 @@ func TestUse_OK(t *testing.T) {
t.Fatalf("Save initial config: %v", err)
}
if err := runUse("production", nil); err != nil {
if err := runUse("production", &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runUse: %v", err)
}
@@ -52,7 +52,7 @@ func TestUse_NotFound_WithDidYouMean(t *testing.T) {
t.Fatalf("Save: %v", err)
}
err := runUse("prodution", nil) // typo: missing 'c'
err := runUse("prodution", &cmdutil.FormatOptions{Mode: cmdutil.FormatText}) // typo: missing 'c'
if err == nil {
t.Fatal("expected error")
}
@@ -84,7 +84,7 @@ func TestUse_NotFound_DeterministicTieBreak(t *testing.T) {
}
// "prox" is distance 1 from prod / prom (both win); lex tie-break → prod.
for i := 0; i < 5; i++ {
err := runUse("prox", nil)
err := runUse("prox", &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err == nil {
t.Fatalf("iter %d: expected error", i)
}
@@ -99,7 +99,7 @@ func TestUse_NotFound_EmptyContexts(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t)
err := runUse("anything", nil)
err := runUse("anything", &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err == nil {
t.Fatal("expected error")
}
@@ -118,7 +118,7 @@ func TestUse_CaseSensitive(t *testing.T) {
}}
_ = config.Save(cfg)
err := runUse("production", nil) // lowercase - must NOT match "Production"
err := runUse("production", &cmdutil.FormatOptions{Mode: cmdutil.FormatText}) // lowercase - must NOT match "Production"
if err == nil {
t.Fatal("expected case-sensitive miss")
}