feat(cli): scaffold weknora CLI module foundation (PR-1)

Empty cli/ Go module with Factory + Options skeleton that all v0.x commands
plug into.

Foundation packages (10 internal/):
- cmdutil: Factory(3 closure: Config/Client/Prompter) + Options + Errors
  with namespaced ErrorCode + typed predicates (IsAuthError / IsNotFound /
  IsTransient / IsAuthExpired) + Exporter + AddJSONFlags + ExitCode/PrintError
- iostreams: package singleton with TTY detection; ColorEnabled honors
  NO_COLOR / TERM=dumb on demand
- agent: mode + detect + annotations (Stripe pkg/useragent pattern;
  CLAUDECODE / CURSOR_AGENT / CODEX_* / AIDER_* / CONTINUE_* /
  OPENCODE_* / GEMINICODER env detection)
- build: ldflags-injected version/commit/date
- safepaths: separator-aware path-traversal protection
- config: yaml.v3 schema + atomic save 0600 (XDG-style)
- format: success/failure envelope (code/hint/request_id/risk/retryable/
  console_url) with typed RiskLevel
- prompt: Prompter interface + AgentPrompter (rejects in agent mode)
- secrets: file 0600 store with weknora:<context>:<key> namespace
- testutil: XDGTempDir(t) test helper

Smoke command: weknora version (-/--json). Build/test/vet matrix in
.github/workflows/cli.yml across linux x macos x windows x Go 1.24.

Factory.Client returns CodeLocalUnimplemented until PR-3 wires the SDK
adapter; PR-1 commands (version) don't need it.
This commit is contained in:
nullkey
2026-05-06 14:22:36 +08:00
committed by lyingbug
parent 6019c4b661
commit a39805aa89
39 changed files with 2708 additions and 0 deletions
+206
View File
@@ -0,0 +1,206 @@
// Package cmd holds the cobra command tree. main.go calls Execute().
//
// Foundation PR registers only the root command and `version`; resource
// commands (auth, kb, doc, ...) land in PR-4 and later.
package cmd
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/build"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// Execute is the entry point invoked by main(). Returns the process exit code.
func Execute() int {
root := newRootCmd(cmdutil.New())
// ExecuteC returns the actually-invoked leaf (or root when invocation
// failed before dispatch); we use it to honor the leaf's --json and
// inherited --format without walking the tree ourselves.
cmd, err := root.ExecuteC()
if err == nil {
return 0
}
err = mapCobraError(err)
if agent.ShouldUseAgentMode(cmd) || wantsJSONOutput(cmd) {
cmdutil.PrintErrorEnvelope(iostreams.IO.Out, err)
} else {
cmdutil.PrintError(iostreams.IO.Err, err)
}
return cmdutil.ExitCode(err)
}
// wantsJSONOutput reports whether cmd was invoked with --json, so error
// output matches the success format. Persistent flags inherit automatically
// via cmd.Flags().
//
// Falls back to scanning os.Args when cobra never reached the leaf — e.g.
// 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 {
if v, err := cmd.Flags().GetBool("json"); err == nil && v {
return true
}
return argsRequestJSON(os.Args[1:])
}
// argsRequestJSON scans a flag-only slice for --json in the forms pflag
// accepts. Used as a fallback when cobra short-circuits before flag parsing
// (unknown command / unknown flag at root). Mirrors only the subset of pflag
// bool parsing relevant here — `--json=false` is treated as not-JSON,
// matching pflag.
func argsRequestJSON(args []string) bool {
for _, a := range args {
switch {
case a == "--json":
return true
case strings.HasPrefix(a, "--json="):
if isPflagTruthy(strings.TrimPrefix(a, "--json=")) {
return true
}
}
}
return false
}
// isPflagTruthy mirrors pflag's bool parsing for "--flag=<v>" tokens.
// pflag accepts 1/t/T/TRUE/true/True as truthy.
func isPflagTruthy(v string) bool {
switch v {
case "1", "t", "T", "TRUE", "true", "True":
return true
}
return false
}
// 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.
//
// 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 {
if err == nil {
return nil
}
msg := err.Error()
for _, prefix := range cobraFlagErrorPrefixes {
if strings.HasPrefix(msg, prefix) {
return cmdutil.NewFlagError(err)
}
}
return err
}
// cobraFlagErrorPrefixes lists the text prefixes cobra uses for invocation
// problems we want to surface as exit 2. Pinned per cobra v1.10.
var cobraFlagErrorPrefixes = []string{
"unknown command ",
"required flag(s)",
"accepts ", // ExactArgs / RangeArgs / etc. — `accepts N arg(s), received M`
"requires at least", // MinimumNArgs
"requires at most", // MaximumNArgs
"unknown flag",
"invalid argument", // pflag type-coercion failure (e.g. --top-k=foo)
}
// newRootCmd builds the cobra tree. Splitting it from Execute() lets tests
// drive the tree directly with their own factory.
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",
SilenceUsage: true,
SilenceErrors: true,
// Version makes cobra auto-register a `--version` global flag that
// prints this string. Mainstream CLIs (gh / kubectl / aws / gcloud)
// all accept both `--version` and a `version` subcommand; the
// subcommand still owns the richer `--json` envelope output.
Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
PersistentPreRun: func(c *cobra.Command, args []string) {
agent.ApplyAgentSugar(c)
},
}
// Match `weknora version` line format so both forms output the same.
cmd.SetVersionTemplate("weknora {{.Version}}\n")
addGlobalFlags(cmd)
cmd.SetHelpFunc(agentAwareHelpFunc(cmd.HelpFunc()))
// Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps
// them to exit 2 (gh-style). "unknown command" errors are detected by
// message prefix in Execute() since cobra emits them as plain errors.
cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error {
return cmdutil.NewFlagError(err)
})
cmd.AddCommand(newVersionCmd(f))
return cmd
}
// 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.
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")
}
// agentAwareHelpFunc wraps cobra's default help to append the AI agent guidance
// (Annotations[agent.AIAgentHelpKey]) only when agent mode is active.
// Stripe pkg/cmd/templates.go pattern.
func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command, []string) {
return func(c *cobra.Command, args []string) {
orig(c, args)
if !agent.ShouldUseAgentMode(c) {
return
}
extra := agent.FormatAgentGuidance(c)
if extra == "" {
return
}
w := c.OutOrStdout()
fmt.Fprintln(w)
fmt.Fprintln(w, "AI Agent guidance:")
fmt.Fprintln(w, " "+extra)
}
}
// newVersionCmd is the only leaf command shipped in the foundation PR. It
// doubles as the smoke test that proves Factory + iostreams + cobra wiring works.
func newVersionCmd(f *cmdutil.Factory) *cobra.Command {
var jsonOut bool
cmd := &cobra.Command{
Use: "version",
Short: "Show CLI build metadata",
RunE: func(c *cobra.Command, args []string) error {
v, commit, date := build.Info()
if jsonOut {
return cmdutil.NewJSONExporter().Write(c.OutOrStdout(), format.Success(map[string]string{
"version": v,
"commit": commit,
"date": date,
}, nil))
}
fmt.Fprintf(c.OutOrStdout(), "weknora %s (commit %s, built %s)\n", v, commit, date)
return nil
},
}
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output JSON envelope")
return cmd
}
+145
View File
@@ -0,0 +1,145 @@
package cmd
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
func TestRoot_Help(t *testing.T) {
var out bytes.Buffer
root := newRootCmd(cmdutil.New())
root.SetArgs([]string{"--help"})
root.SetOut(&out)
require.NoError(t, root.Execute())
got := out.String()
assert.Contains(t, got, "weknora")
assert.Contains(t, got, "version")
}
func TestVersion_JSON(t *testing.T) {
var out bytes.Buffer
root := newRootCmd(cmdutil.New())
root.SetArgs([]string{"version", "--json"})
root.SetOut(&out)
require.NoError(t, root.Execute())
got := out.String()
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "got: %q", got)
assert.Contains(t, got, "version")
}
// Smoke test for cmdutil.ExitCode wiring; full coverage lives in
// cli/internal/cmdutil/exit_test.go.
func TestExecute_ExitCodeSurface(t *testing.T) {
assert.Equal(t, 0, cmdutil.ExitCode(nil))
assert.Equal(t, 1, cmdutil.ExitCode(assert.AnError))
}
// TestMapCobraError_PinnedPrefixes guards against silent breakage if cobra
// changes the message format of unknown-command / required-flag / arg-count
// errors. Cobra v1.10 emits these via fmt.Errorf in args.go and command.go;
// if a future bump alters the wording, this test fails loudly so we update
// cobraFlagErrorPrefixes (or migrate to typed sentinels if cobra ever
// provides them).
func TestMapCobraError_PinnedPrefixes(t *testing.T) {
t.Run("unknown command", func(t *testing.T) {
root := newRootCmd(cmdutil.New())
root.SetArgs([]string{"bogus"})
root.SetErr(&bytes.Buffer{})
root.SetOut(&bytes.Buffer{})
err := root.Execute()
require.Error(t, err)
assert.True(t, strings.HasPrefix(err.Error(), "unknown command "),
"cobra unknown-command prefix changed; update cobraFlagErrorPrefixes. got: %q", err.Error())
})
t.Run("required flag(s)", func(t *testing.T) {
// Self-contained probe — the pin must hold even before resource commands
// register their own required flags. RunE is required: without it cobra
// treats the command as a parent and skips ValidateRequiredFlags.
probe := &cobra.Command{Use: "probe", RunE: func(*cobra.Command, []string) error { return nil }}
probe.Flags().String("host", "", "")
require.NoError(t, probe.MarkFlagRequired("host"))
probe.SetErr(&bytes.Buffer{})
probe.SetOut(&bytes.Buffer{})
err := probe.Execute()
require.Error(t, err)
assert.True(t, strings.HasPrefix(err.Error(), "required flag(s)"),
"cobra required-flag prefix changed; update cobraFlagErrorPrefixes. got: %q", err.Error())
})
t.Run("accepts N arg(s) — ExactArgs", func(t *testing.T) {
probe := &cobra.Command{
Use: "probe",
Args: cobra.ExactArgs(1),
RunE: func(*cobra.Command, []string) error { return nil },
}
probe.SetArgs([]string{}) // no args, but ExactArgs(1) wants 1
probe.SetErr(&bytes.Buffer{})
probe.SetOut(&bytes.Buffer{})
err := probe.Execute()
require.Error(t, err)
assert.True(t, strings.HasPrefix(err.Error(), "accepts "),
"cobra ExactArgs prefix changed; update cobraFlagErrorPrefixes. got: %q", err.Error())
})
}
func TestMapCobraError(t *testing.T) {
t.Run("nil passes through", func(t *testing.T) {
assert.Nil(t, mapCobraError(nil))
})
t.Run("non-matching error passes through", func(t *testing.T) {
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"`))
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`))
var fe *cmdutil.FlagError
assert.True(t, errors.As(err, &fe))
})
}
func TestArgsRequestJSON(t *testing.T) {
cases := []struct {
name string
args []string
want bool
}{
{"empty", nil, false},
{"--json bare", []string{"version", "--json"}, true},
{"--json=true", []string{"version", "--json=true"}, true},
{"--json=1", []string{"version", "--json=1"}, true},
{"--json=TRUE", []string{"version", "--json=TRUE"}, true},
{"--json=false", []string{"version", "--json=false"}, false},
{"unrelated", []string{"bogus", "--kb", "x"}, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.want, argsRequestJSON(tc.args))
})
}
}
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
// 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")
require.NoError(t, c.Flags().Set("json", "true"))
assert.True(t, wantsJSONOutput(c), "--json=true honored")
}