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:
@@ -104,7 +104,7 @@ func MergeAgentConfig(base *sdk.AgentConfig, ov AgentConfigFlags) *sdk.AgentConf
|
||||
// skeletonCommentVersion is embedded in the skeleton header so users
|
||||
// regenerating an outdated template after a schema bump can spot the
|
||||
// version mismatch.
|
||||
const skeletonCommentVersion = "v0.5 / 34 fields"
|
||||
const skeletonCommentVersion = "v0.6 / 34 fields"
|
||||
|
||||
// GenerateAgentSkeleton writes a commented YAML template with every
|
||||
// AgentConfig field at its zero value to w. Used by
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
@@ -211,6 +212,28 @@ func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) {
|
||||
return "", NewError(CodeKBIDRequired, "kb is required")
|
||||
}
|
||||
|
||||
// ApplyLogLevel resolves --log-level / WEKNORA_LOG_LEVEL (in priority order)
|
||||
// and applies the result to the SDK's debug logger. Intended to be called
|
||||
// from the root command's PersistentPreRunE so the resolved level is in
|
||||
// effect before any SDK call.
|
||||
//
|
||||
// Returns a typed error if the user passed an explicit --log-level with
|
||||
// an invalid value — matches the strictness of --format validation
|
||||
// (env values stay silent-fallthrough; flag values are strict).
|
||||
func (f *Factory) ApplyLogLevel(cmd *cobra.Command, stderr io.Writer) error {
|
||||
if cmd != nil {
|
||||
if fl := cmd.Flags().Lookup("log-level"); fl != nil && fl.Changed {
|
||||
if !IsValidLogLevel(fl.Value.String()) {
|
||||
return NewFlagError(fmt.Errorf(
|
||||
"invalid --log-level %q: must be error | warn | info | debug", fl.Value.String()))
|
||||
}
|
||||
}
|
||||
}
|
||||
level, _ := ResolveLogLevel(cmd, stderr)
|
||||
sdk.SetDebugLevel(level)
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadSecret fetches a named secret for the given context from the keyring.
|
||||
// Returns ("", nil) when the secret is absent (ErrNotFound); a real keyring
|
||||
// access failure surfaces as CodeLocalKeychainDenied. Used by buildClient
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// validLogLevels is the canonical set of accepted log levels
|
||||
// (debug|info|warn|error). Map gives O(1) validation.
|
||||
var validLogLevels = map[string]bool{
|
||||
"error": true,
|
||||
"warn": true,
|
||||
"info": true,
|
||||
"debug": true,
|
||||
}
|
||||
|
||||
// IsValidLogLevel reports whether v is one of the accepted log levels.
|
||||
// Exported so factory-level validation can give a strict error on an
|
||||
// explicit --log-level invalid value (env values stay silent-fallthrough).
|
||||
func IsValidLogLevel(v string) bool { return validLogLevels[v] }
|
||||
|
||||
// LogLevelDefault is the resolved level when nothing is configured: only
|
||||
// emit error-level logs (minimal noise for non-debug usage).
|
||||
const LogLevelDefault = "error"
|
||||
|
||||
// AddLogLevelFlag registers --log-level as a persistent flag on cmd
|
||||
// (typically the root command). Unlike --format (per-command, Method D),
|
||||
// --log-level is uniformly applied across all SDK calls so it lives on root.
|
||||
func AddLogLevelFlag(cmd *cobra.Command) {
|
||||
cmd.PersistentFlags().String("log-level", "", "Log verbosity: error | warn | info | debug (env: WEKNORA_LOG_LEVEL)")
|
||||
}
|
||||
|
||||
// ResolveLogLevel resolves the effective log level using priority (high → low):
|
||||
// 1. --log-level flag (if explicitly set, even from a parent command's persistent flagset)
|
||||
// 2. WEKNORA_LOG_LEVEL env (if set to a valid value)
|
||||
// 3. Default "error"
|
||||
//
|
||||
// Invalid env values fall through to the next priority (no error — env is
|
||||
// best-effort). The stderr writer is retained in the signature for symmetry
|
||||
// with ApplyLogLevel callers but is unused in v0.6.
|
||||
func ResolveLogLevel(cmd *cobra.Command, _ io.Writer) (string, bool) {
|
||||
// Priority 1: explicit --log-level flag.
|
||||
if cmd != nil {
|
||||
if f := cmd.Flags().Lookup("log-level"); f != nil && f.Changed {
|
||||
v := f.Value.String()
|
||||
if validLogLevels[v] {
|
||||
return v, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 2: WEKNORA_LOG_LEVEL env (silently skip invalid values).
|
||||
if v := os.Getenv("WEKNORA_LOG_LEVEL"); v != "" && validLogLevels[v] {
|
||||
return v, false
|
||||
}
|
||||
|
||||
// Priority 3: default.
|
||||
return LogLevelDefault, false
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestResolveLogLevel(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
flagVal string // "" means flag not set
|
||||
envVal string // WEKNORA_LOG_LEVEL
|
||||
wantLvl string
|
||||
wantWarn bool
|
||||
}{
|
||||
{"default", "", "", "error", false},
|
||||
{"flag wins over env", "debug", "info", "debug", false},
|
||||
{"env when no flag", "", "info", "info", false},
|
||||
{"invalid env falls through to default", "", "trace", "error", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_LOG_LEVEL", tc.envVal)
|
||||
|
||||
cmd := &cobra.Command{}
|
||||
AddLogLevelFlag(cmd)
|
||||
if tc.flagVal != "" {
|
||||
if err := cmd.ParseFlags([]string{"--log-level", tc.flagVal}); err != nil {
|
||||
t.Fatalf("ParseFlags: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var stderr bytes.Buffer
|
||||
got, warn := ResolveLogLevel(cmd, &stderr)
|
||||
if got != tc.wantLvl {
|
||||
t.Errorf("level=%q want %q", got, tc.wantLvl)
|
||||
}
|
||||
if warn != tc.wantWarn {
|
||||
t.Errorf("warn=%v want %v", warn, tc.wantWarn)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddLogLevelFlag_RegistersPersistent(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
AddLogLevelFlag(cmd)
|
||||
if f := cmd.PersistentFlags().Lookup("log-level"); f == nil {
|
||||
t.Error("--log-level must be registered as a persistent flag (global across all subcommands)")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user