diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml new file mode 100644 index 00000000..75bc9fca --- /dev/null +++ b/.github/workflows/cli.yml @@ -0,0 +1,52 @@ +name: CLI + +# Builds and tests the cli/ Go module on every push / PR that touches it. +# Foundation PR (PR-1) gates: 3-platform `go build` + `go test ./...` green. + +on: + push: + branches: [main] + paths: + - 'cli/**' + - '.github/workflows/cli.yml' + pull_request: + paths: + - 'cli/**' + - '.github/workflows/cli.yml' + +defaults: + run: + working-directory: cli + # Windows default is PowerShell, which tokenizes `go test -coverprofile=coverage.out ./...` + # in a way that detaches `.out` as a separate positional package arg. + # Force bash everywhere so the run lines parse identically across platforms + # (Git Bash is preinstalled on windows-latest runners). + shell: bash + +permissions: + contents: read + +jobs: + test: + name: test (${{ matrix.os }} / go ${{ matrix.go }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + go: ['1.24'] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: ${{ matrix.go }} + cache-dependency-path: cli/go.sum + - name: go build + run: go build ./... + - name: go test + run: go test -race -coverprofile=coverage.out ./... + - name: go vet + run: go vet ./... + - name: coverage report + if: matrix.os == 'ubuntu-latest' + run: go tool cover -func=coverage.out diff --git a/cli/.gitignore b/cli/.gitignore new file mode 100644 index 00000000..1460c080 --- /dev/null +++ b/cli/.gitignore @@ -0,0 +1,2 @@ +bin/ +coverage.out diff --git a/cli/Makefile b/cli/Makefile new file mode 100644 index 00000000..848d2a63 --- /dev/null +++ b/cli/Makefile @@ -0,0 +1,47 @@ +# Makefile for the WeKnora CLI (cli/ Go module). +# +# Usage: +# make build compile to ./bin/weknora with version metadata +# make test go test ./... +# make test-coverage same with coverage report +# make lint go vet (golangci-lint added in PR-9) +# make tidy go mod tidy +# make clean remove ./bin + +BINARY := weknora +BUILD_DIR := bin +PKG := github.com/Tencent/WeKnora/cli + +VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) +COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo none) +DATE := $(shell date -u +%Y-%m-%dT%H:%M:%SZ) + +LDFLAGS := -s -w \ + -X $(PKG)/internal/build.Version=$(VERSION) \ + -X $(PKG)/internal/build.Commit=$(COMMIT) \ + -X $(PKG)/internal/build.Date=$(DATE) + +.PHONY: build test test-coverage lint tidy clean help + +build: + @mkdir -p $(BUILD_DIR) + go build -ldflags="$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY) . + +test: + go test ./... + +test-coverage: + go test -coverprofile=coverage.out ./... + go tool cover -func=coverage.out + +lint: + go vet ./... + +tidy: + go mod tidy + +clean: + rm -rf $(BUILD_DIR) coverage.out + +help: + @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' diff --git a/cli/cmd/root.go b/cli/cmd/root.go new file mode 100644 index 00000000..d7dd4c46 --- /dev/null +++ b/cli/cmd/root.go @@ -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=" 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 +} diff --git a/cli/cmd/root_test.go b/cli/cmd/root_test.go new file mode 100644 index 00000000..5550207a --- /dev/null +++ b/cli/cmd/root_test.go @@ -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") +} diff --git a/cli/go.mod b/cli/go.mod new file mode 100644 index 00000000..d97b6485 --- /dev/null +++ b/cli/go.mod @@ -0,0 +1,53 @@ +module github.com/Tencent/WeKnora/cli + +go 1.24.2 + +toolchain go1.24.4 + +require ( + github.com/Tencent/WeKnora/client v0.0.0-00010101000000-000000000000 + github.com/charmbracelet/huh v1.0.0 + github.com/mattn/go-isatty v0.0.20 + github.com/spf13/cobra v1.8.1 + github.com/stretchr/testify v1.11.1 + github.com/zalando/go-keyring v0.2.8 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/catppuccin/go v0.3.0 // indirect + github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 // indirect + github.com/charmbracelet/bubbletea v1.3.6 // indirect + github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect + github.com/charmbracelet/lipgloss v1.1.0 // indirect + github.com/charmbracelet/x/ansi v0.9.3 // indirect + github.com/charmbracelet/x/cellbuf v0.0.13 // indirect + github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect + github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/danieljoos/wincred v1.2.3 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/godbus/dbus/v5 v5.2.2 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.16.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sync v0.15.0 // indirect + golang.org/x/sys v0.33.0 // indirect + golang.org/x/text v0.23.0 // indirect +) + +// In-repo SDK module: cli pulls the local client/ until both modules ship +// independent tagged versions. +replace github.com/Tencent/WeKnora/client => ../client diff --git a/cli/go.sum b/cli/go.sum new file mode 100644 index 00000000..2873fbeb --- /dev/null +++ b/cli/go.sum @@ -0,0 +1,101 @@ +github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= +github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY= +github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E= +github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY= +github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc= +github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7 h1:JFgG/xnwFfbezlUnFMJy0nusZvytYysV4SCS2cYbvws= +github.com/charmbracelet/bubbles v0.21.1-0.20250623103423-23b8fd6302d7/go.mod h1:ISC1gtLcVilLOf23wvTfoQuYbW2q0JevFxPfUzZ9Ybw= +github.com/charmbracelet/bubbletea v1.3.6 h1:VkHIxPJQeDt0aFJIsVxw8BQdh/F/L2KKZGsK6et5taU= +github.com/charmbracelet/bubbletea v1.3.6/go.mod h1:oQD9VCRQFF8KplacJLo28/jofOI2ToOfGYeFgBBxHOc= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/huh v1.0.0 h1:wOnedH8G4qzJbmhftTqrpppyqHakl/zbbNdXIWJyIxw= +github.com/charmbracelet/huh v1.0.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4= +github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= +github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/x/ansi v0.9.3 h1:BXt5DHS/MKF+LjuK4huWrC6NCvHtexww7dMayh6GXd0= +github.com/charmbracelet/x/ansi v0.9.3/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= +github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k= +github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/conpty v0.1.0 h1:4zc8KaIcbiL4mghEON8D72agYtSeIgq8FSThSPQIb+U= +github.com/charmbracelet/x/conpty v0.1.0/go.mod h1:rMFsDJoDwVmiYM10aD4bH2XiRgwI7NYJtQgl5yskjEQ= +github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA= +github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0= +github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ= +github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= +github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4= +github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ= +github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= +github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= +github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= +github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= +github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI= +github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4= +github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= +github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= +github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= +github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= +github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= +github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= +github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= +golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/cli/internal/agent/annotations.go b/cli/internal/agent/annotations.go new file mode 100644 index 00000000..df5929db --- /dev/null +++ b/cli/internal/agent/annotations.go @@ -0,0 +1,34 @@ +package agent + +import ( + "strings" + + "github.com/spf13/cobra" +) + +// AIAgentHelpKey is the cobra Annotation key used to attach an AI-agent-specific +// help blurb to a command. The blurb is appended to --help output only when +// agent mode is active. Mirrors Stripe's pkg/cmd/templates.go AIAgentHelpAnnotationKey. +const AIAgentHelpKey = "ai_agent_help" + +// FormatAgentGuidance returns the agent-targeted help text registered on cmd, +// or "" if none. Render it after the standard help when ShouldUseAgentMode reports true. +func FormatAgentGuidance(cmd *cobra.Command) string { + if cmd == nil { + return "" + } + v, ok := cmd.Annotations[AIAgentHelpKey] + if !ok { + return "" + } + return strings.TrimSpace(v) +} + +// SetAgentHelp is a small helper that initializes Annotations and stores the +// blurb under AIAgentHelpKey. Use it in NewCmdX constructors before returning. +func SetAgentHelp(cmd *cobra.Command, blurb string) { + if cmd.Annotations == nil { + cmd.Annotations = map[string]string{} + } + cmd.Annotations[AIAgentHelpKey] = strings.TrimSpace(blurb) +} diff --git a/cli/internal/agent/detect.go b/cli/internal/agent/detect.go new file mode 100644 index 00000000..7260bd2a --- /dev/null +++ b/cli/internal/agent/detect.go @@ -0,0 +1,39 @@ +// Package agent handles AI agent integration: --agent flag sugar, env detection, +// and per-command help annotations. +package agent + +import "os" + +// AIAgentName identifies the detected coding agent invoking the CLI. Empty +// string means no agent detected (or detection is disabled). +type AIAgentName string + +// aiAgentEnvs maps environment variable presence to a coding agent name. +// Modeled on Stripe's pkg/useragent/useragent.go DetectAIAgent. +var aiAgentEnvs = []struct { + env string + name AIAgentName +}{ + {"CLAUDECODE", "claude-code"}, + {"CURSOR_AGENT", "cursor"}, + {"CODEX_PROMPT_HOSTNAME", "codex"}, + {"AIDER_PROMPT", "aider"}, + {"CONTINUE_GLOBAL_DIR", "continue"}, + {"OPENCODE_RUNNING", "opencode"}, + {"GEMINICODER_PROFILE", "gemini-coder"}, +} + +// DetectAIAgent returns the first known agent name whose env var is set to a +// non-empty value, or "" if none are present. Detection is suppressed when +// WEKNORA_NO_AGENT_AUTODETECT is truthy. Tests substitute via t.Setenv. +func DetectAIAgent() AIAgentName { + if v := os.Getenv("WEKNORA_NO_AGENT_AUTODETECT"); v != "" && v != "0" && v != "false" { + return "" + } + for _, a := range aiAgentEnvs { + if os.Getenv(a.env) != "" { + return a.name + } + } + return "" +} diff --git a/cli/internal/agent/detect_test.go b/cli/internal/agent/detect_test.go new file mode 100644 index 00000000..168525ec --- /dev/null +++ b/cli/internal/agent/detect_test.go @@ -0,0 +1,90 @@ +package agent + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// clearAgentEnv unsets every env var DetectAIAgent inspects, so a developer +// running these tests from inside Claude Code / Cursor doesn't see false +// positives. +func clearAgentEnv(t *testing.T) { + t.Helper() + for _, a := range aiAgentEnvs { + t.Setenv(a.env, "") + } + t.Setenv("WEKNORA_NO_AGENT_AUTODETECT", "") + t.Setenv("WEKNORA_AGENT", "") +} + +func TestDetectAIAgent(t *testing.T) { + cases := []struct { + name string + set map[string]string + want AIAgentName + }{ + {name: "empty env", set: nil, want: ""}, + {name: "unrelated env", set: map[string]string{"PATH": "/usr/bin"}, want: ""}, + {name: "claude code", set: map[string]string{"CLAUDECODE": "1"}, want: "claude-code"}, + {name: "cursor", set: map[string]string{"CURSOR_AGENT": "yes"}, want: "cursor"}, + {name: "codex", set: map[string]string{"CODEX_PROMPT_HOSTNAME": "host"}, want: "codex"}, + {name: "aider", set: map[string]string{"AIDER_PROMPT": "y"}, want: "aider"}, + {name: "continue", set: map[string]string{"CONTINUE_GLOBAL_DIR": "/tmp"}, want: "continue"}, + {name: "opencode", set: map[string]string{"OPENCODE_RUNNING": "1"}, want: "opencode"}, + {name: "gemini-coder", set: map[string]string{"GEMINICODER_PROFILE": "default"}, want: "gemini-coder"}, + { + name: "first-match precedence", + set: map[string]string{"CLAUDECODE": "1", "CURSOR_AGENT": "1"}, + want: "claude-code", + }, + {name: "empty value treated as unset", set: map[string]string{"CLAUDECODE": ""}, want: ""}, + { + name: "WEKNORA_NO_AGENT_AUTODETECT=1 suppresses detection", + set: map[string]string{"CLAUDECODE": "1", "WEKNORA_NO_AGENT_AUTODETECT": "1"}, + want: "", + }, + { + name: "WEKNORA_NO_AGENT_AUTODETECT=0 still allows detection", + set: map[string]string{"CLAUDECODE": "1", "WEKNORA_NO_AGENT_AUTODETECT": "0"}, + want: "claude-code", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + clearAgentEnv(t) + for k, v := range tc.set { + t.Setenv(k, v) + } + assert.Equal(t, tc.want, DetectAIAgent()) + }) + } +} + +func TestShouldUseAgentMode_Triggers(t *testing.T) { + t.Run("WEKNORA_AGENT=1 triggers", func(t *testing.T) { + clearAgentEnv(t) + t.Setenv("WEKNORA_AGENT", "1") + assert.True(t, ShouldUseAgentMode(nil)) + }) + t.Run("WEKNORA_AGENT=true triggers", func(t *testing.T) { + clearAgentEnv(t) + t.Setenv("WEKNORA_AGENT", "true") + assert.True(t, ShouldUseAgentMode(nil)) + }) + t.Run("WEKNORA_AGENT=0 does not trigger", func(t *testing.T) { + clearAgentEnv(t) + t.Setenv("WEKNORA_AGENT", "0") + assert.False(t, ShouldUseAgentMode(nil)) + }) + t.Run("AI agent env triggers", func(t *testing.T) { + clearAgentEnv(t) + t.Setenv("CLAUDECODE", "1") + assert.True(t, ShouldUseAgentMode(nil)) + }) + t.Run("no triggers", func(t *testing.T) { + clearAgentEnv(t) + assert.False(t, ShouldUseAgentMode(nil)) + }) +} diff --git a/cli/internal/agent/mode.go b/cli/internal/agent/mode.go new file mode 100644 index 00000000..4c41b7e7 --- /dev/null +++ b/cli/internal/agent/mode.go @@ -0,0 +1,56 @@ +package agent + +import ( + "os" + + "github.com/spf13/cobra" +) + +// agentSugarFlags lists the flags ApplyAgentSugar sets to their agent-friendly +// defaults when triggered. Each entry is no-op'd at runtime if the leaf hasn't +// registered the flag (e.g. version doesn't have --no-progress). +var agentSugarFlags = []struct{ name, value string }{ + {"json", "true"}, + {"no-interactive", "true"}, + {"no-progress", "true"}, +} + +// ApplyAgentSugar evaluates --agent / WEKNORA_AGENT / env-based AI agent +// detection, then sets json / no-interactive / no-progress to their +// agent-friendly defaults unless the user already set them. +func ApplyAgentSugar(cmd *cobra.Command) { + if !ShouldUseAgentMode(cmd) { + return + } + for _, kv := range agentSugarFlags { + if f := cmd.Flags().Lookup(kv.name); f != nil && !cmd.Flags().Changed(kv.name) { + _ = cmd.Flags().Set(kv.name, kv.value) + } + } +} + +// ShouldUseAgentMode returns true if any of the three triggers are active: +// (1) --agent flag, (2) WEKNORA_AGENT=1 env, (3) a known agent env var is set. +func ShouldUseAgentMode(cmd *cobra.Command) bool { + if cmd != nil { + if v, err := cmd.Flags().GetBool("agent"); err == nil && v { + return true + } + } + if truthy(os.Getenv("WEKNORA_AGENT")) { + return true + } + return DetectAIAgent() != "" +} + +// truthy treats any non-empty value other than "0" / "false" / "FALSE" as +// truthy. This is wider than strconv.ParseBool by design — users set +// WEKNORA_AGENT=1, =true, or =yes interchangeably across CI shells. +func truthy(v string) bool { + switch v { + case "", "0", "false", "FALSE": + return false + default: + return true + } +} diff --git a/cli/internal/agent/mode_test.go b/cli/internal/agent/mode_test.go new file mode 100644 index 00000000..765c2f79 --- /dev/null +++ b/cli/internal/agent/mode_test.go @@ -0,0 +1,87 @@ +package agent + +import ( + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// newTestCmd returns a cobra command with the flags ApplyAgentSugar +// expects to be present (`--agent`, `--json`, `--no-interactive`, +// `--no-progress`). +func newTestCmd() *cobra.Command { + c := &cobra.Command{Use: "x"} + c.Flags().Bool("agent", false, "") + c.Flags().Bool("json", false, "") + c.Flags().Bool("no-interactive", false, "") + c.Flags().Bool("no-progress", false, "") + return c +} + +func TestApplyAgentSugar_AgentFlagSet(t *testing.T) { + c := newTestCmd() + require.NoError(t, c.Flags().Set("agent", "true")) + ApplyAgentSugar(c) + j, _ := c.Flags().GetBool("json") + assert.True(t, j) + ni, _ := c.Flags().GetBool("no-interactive") + assert.True(t, ni) + np, _ := c.Flags().GetBool("no-progress") + assert.True(t, np) +} + +func TestApplyAgentSugar_NoTrigger(t *testing.T) { + clearAgentEnv(t) + c := newTestCmd() + ApplyAgentSugar(c) + j, _ := c.Flags().GetBool("json") + assert.False(t, j, "without --agent or env, --json must remain unset") +} + +func TestApplyAgentSugar_ExplicitJSONFalseWins(t *testing.T) { + clearAgentEnv(t) + c := newTestCmd() + require.NoError(t, c.Flags().Set("agent", "true")) + require.NoError(t, c.Flags().Set("json", "false")) + ApplyAgentSugar(c) + j, _ := c.Flags().GetBool("json") + assert.False(t, j, "explicit --json=false must override agent sugar") +} + +func TestFormatAgentGuidance(t *testing.T) { + c := &cobra.Command{Use: "x"} + assert.Equal(t, "", FormatAgentGuidance(c)) + SetAgentHelp(c, " use --idempotency-key for safe retries ") + assert.Equal(t, "use --idempotency-key for safe retries", FormatAgentGuidance(c)) +} + +func TestSetAgentHelp_InitsAnnotations(t *testing.T) { + c := &cobra.Command{Use: "x"} + assert.Nil(t, c.Annotations) + SetAgentHelp(c, "blurb") + require.NotNil(t, c.Annotations) + assert.Equal(t, "blurb", c.Annotations[AIAgentHelpKey]) +} + +func TestTruthy(t *testing.T) { + cases := []struct { + in string + want bool + }{ + {"", false}, + {"0", false}, + {"false", false}, + {"FALSE", false}, + {"1", true}, + {"true", true}, + {"yes", true}, + {"anything-else", true}, + } + for _, tc := range cases { + t.Run(tc.in, func(t *testing.T) { + assert.Equal(t, tc.want, truthy(tc.in)) + }) + } +} diff --git a/cli/internal/build/build.go b/cli/internal/build/build.go new file mode 100644 index 00000000..6af77785 --- /dev/null +++ b/cli/internal/build/build.go @@ -0,0 +1,16 @@ +// Package build holds compile-time-injected build metadata. +// +// Values are set via -ldflags="-X github.com/Tencent/WeKnora/cli/internal/build.Version=..." at link time; +// the Makefile's `version` target wires them up. +package build + +var ( + Version = "dev" + Commit = "none" + Date = "unknown" +) + +// Info returns a snapshot of the build metadata. +func Info() (version, commit, date string) { + return Version, Commit, Date +} diff --git a/cli/internal/build/build_test.go b/cli/internal/build/build_test.go new file mode 100644 index 00000000..017760d0 --- /dev/null +++ b/cli/internal/build/build_test.go @@ -0,0 +1,25 @@ +package build + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestInfo_DefaultDevValues(t *testing.T) { + v, c, d := Info() + // In a non-ldflags-injected build, these are the package defaults; tests + // that vary them need to assign at run time, not via -ldflags (testing + // here only that Info returns whatever is current). + assert.NotEmpty(t, v) + assert.NotEmpty(t, c) + assert.NotEmpty(t, d) +} + +func TestInfo_ReflectsInjectedValues(t *testing.T) { + old := Version + t.Cleanup(func() { Version = old }) + Version = "v0.0.0-test" + v, _, _ := Info() + assert.Equal(t, "v0.0.0-test", v) +} diff --git a/cli/internal/cmdutil/errors.go b/cli/internal/cmdutil/errors.go new file mode 100644 index 00000000..b8cf0a62 --- /dev/null +++ b/cli/internal/cmdutil/errors.go @@ -0,0 +1,186 @@ +// Package cmdutil contains the Factory, Options helpers, error types, +// JSON-flag wiring, and the Exporter abstraction shared by all commands. +package cmdutil + +import ( + "errors" + "fmt" + "strconv" + "strings" +) + +// ErrorCode is a namespaced stable identifier carried in the failure envelope. +// SemVer governance: v0.x maintains the registry below; new codes are noted +// in release notes. v0.9 introduces a CI compat test (see ADR-6b). +type ErrorCode string + +const ( + // auth.* — authentication / permission + CodeAuthUnauthenticated ErrorCode = "auth.unauthenticated" + CodeAuthTokenExpired ErrorCode = "auth.token_expired" + CodeAuthBadCredential ErrorCode = "auth.bad_credential" + CodeAuthForbidden ErrorCode = "auth.forbidden" + CodeAuthCrossTenantBlocked ErrorCode = "auth.cross_tenant_blocked" + CodeAuthTenantMismatch ErrorCode = "auth.tenant_mismatch" + + // resource.* + CodeResourceNotFound ErrorCode = "resource.not_found" + CodeResourceAlreadyExists ErrorCode = "resource.already_exists" + CodeResourceLocked ErrorCode = "resource.locked" + + // input.* — flag and argument validation + CodeInputInvalidArgument ErrorCode = "input.invalid_argument" + CodeInputMissingFlag ErrorCode = "input.missing_flag" + + // server.* / network.* + CodeServerError ErrorCode = "server.error" + CodeServerTimeout ErrorCode = "server.timeout" + CodeServerRateLimited ErrorCode = "server.rate_limited" + CodeServerIncompatibleVersion ErrorCode = "server.incompatible_version" + CodeNetworkError ErrorCode = "network.error" + + // 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" + + // mcp.* + CodeMCPReadonlyMode ErrorCode = "mcp.readonly_mode" + CodeMCPToolNotAllowed ErrorCode = "mcp.tool_not_allowed" + CodeMCPSchemaUnknown ErrorCode = "mcp.schema_unknown_command" +) + +// Error is the typed error implementations carry through the call stack. +// RunE returns a *Error and the root command formats it into the envelope. +type Error struct { + Code ErrorCode + Message string + Hint string + Cause error + Retryable bool + HTTPStatus int +} + +func (e *Error) Error() string { + if e == nil { + return "" + } + if e.Cause != nil { + return fmt.Sprintf("%s: %s: %v", e.Code, e.Message, e.Cause) + } + return fmt.Sprintf("%s: %s", e.Code, e.Message) +} + +func (e *Error) Unwrap() error { return e.Cause } + +// NewError constructs a typed error. +func NewError(code ErrorCode, message string) *Error { + return &Error{Code: code, Message: message} +} + +// Wrapf wraps cause with a typed code and Sprintf-style message. +func Wrapf(code ErrorCode, cause error, format string, args ...any) *Error { + return &Error{Code: code, Message: fmt.Sprintf(format, args...), Cause: cause} +} + +// FlagError signals user-visible flag/argument problems; the root command +// prints help on top of the message and exits 2 (gh-style). +type FlagError struct{ err error } + +func (e *FlagError) Error() string { return e.err.Error() } +func (e *FlagError) Unwrap() error { return e.err } + +// NewFlagError wraps err as a FlagError. +func NewFlagError(err error) error { return &FlagError{err: err} } + +// SilentError skips printing to stderr; useful when a command has already +// emitted a fully-formatted message and exits non-zero. +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 (Stripe pattern). +// They walk the error chain so wrapped errors still match. + +// IsAuthError matches any auth.* code. +func IsAuthError(err error) bool { return matchPrefix(err, "auth.") } + +// IsNotFound matches resource.not_found. +func IsNotFound(err error) bool { return matchCode(err, CodeResourceNotFound) } + +// IsTransient matches network.* and server.timeout / rate_limited (worth retrying). +func IsTransient(err error) bool { + return matchPrefix(err, "network.") || + matchCode(err, CodeServerTimeout) || + matchCode(err, CodeServerRateLimited) +} + +// IsAuthExpired matches auth.token_expired. +func IsAuthExpired(err error) bool { return matchCode(err, CodeAuthTokenExpired) } + +// matchCode returns true if err (or anything it wraps) is a *Error with code == c. +// errors.As walks the wrap chain itself; the explicit unwrap loop is unnecessary. +func matchCode(err error, c ErrorCode) bool { + var e *Error + if !errors.As(err, &e) { + return false + } + return e.Code == c +} + +// matchPrefix returns true if err (or anything it wraps) is a *Error whose code +// has the given namespace prefix (e.g. "auth."). +func matchPrefix(err error, prefix string) bool { + var e *Error + if !errors.As(err, &e) { + return false + } + return strings.HasPrefix(string(e.Code), prefix) +} + +// ClassifyHTTPError maps an SDK HTTP error to the canonical ErrorCode by +// parsing the "HTTP error : ..." message format the SDK currently +// emits (client.parseResponse). Until the SDK exposes a typed APIError this +// is the lowest-friction way to surface 401/404/429/etc. as the right +// envelope code instead of every server-side problem collapsing to +// server.error. +// +// Returns CodeNetworkError when err is not an HTTP error (transport / DNS), +// and CodeServerError when the status can't be parsed. +func ClassifyHTTPError(err error) ErrorCode { + if err == nil { + return "" + } + msg := err.Error() + rest, ok := strings.CutPrefix(msg, "HTTP error ") + if !ok { + return CodeNetworkError + } + end := strings.IndexByte(rest, ':') + if end <= 0 { + return CodeServerError + } + status, perr := strconv.Atoi(rest[:end]) + if perr != nil { + return CodeServerError + } + switch { + case status == 401: + return CodeAuthUnauthenticated + case status == 403: + return CodeAuthForbidden + case status == 404: + return CodeResourceNotFound + case status == 409: + return CodeResourceAlreadyExists + case status == 429: + return CodeServerRateLimited + case status >= 500: + return CodeServerError + case status >= 400: + return CodeInputInvalidArgument + } + return CodeServerError +} diff --git a/cli/internal/cmdutil/errors_test.go b/cli/internal/cmdutil/errors_test.go new file mode 100644 index 00000000..39693cb1 --- /dev/null +++ b/cli/internal/cmdutil/errors_test.go @@ -0,0 +1,36 @@ +package cmdutil + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestClassifyHTTPError(t *testing.T) { + cases := []struct { + name string + err error + want ErrorCode + }{ + {"nil", nil, ""}, + {"non-HTTP transport", errors.New("dial tcp: lookup host: no such host"), CodeNetworkError}, + {"401", fmt.Errorf("HTTP error 401: invalid token"), CodeAuthUnauthenticated}, + {"403", fmt.Errorf("HTTP error 403: forbidden"), CodeAuthForbidden}, + {"404", fmt.Errorf("HTTP error 404: kb not found"), CodeResourceNotFound}, + {"409", fmt.Errorf("HTTP error 409: already exists"), CodeResourceAlreadyExists}, + {"429", fmt.Errorf("HTTP error 429: slow down"), CodeServerRateLimited}, + {"500", fmt.Errorf("HTTP error 500: internal"), CodeServerError}, + {"503", fmt.Errorf("HTTP error 503: unavailable"), CodeServerError}, + {"400 generic", fmt.Errorf("HTTP error 400: bad input"), CodeInputInvalidArgument}, + {"422 unprocessable", fmt.Errorf("HTTP error 422: validation"), CodeInputInvalidArgument}, + {"malformed status", fmt.Errorf("HTTP error abc: oops"), CodeServerError}, + {"missing colon", fmt.Errorf("HTTP error 404 no colon"), CodeServerError}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, ClassifyHTTPError(tc.err)) + }) + } +} diff --git a/cli/internal/cmdutil/exit.go b/cli/internal/cmdutil/exit.go new file mode 100644 index 00000000..0452157b --- /dev/null +++ b/cli/internal/cmdutil/exit.go @@ -0,0 +1,100 @@ +package cmdutil + +import ( + "errors" + "fmt" + "io" + + "github.com/Tencent/WeKnora/cli/internal/format" +) + +// ExitCode maps an error to the documented CLI exit code (spec §2.4). +// Mirrors gh / Stripe convention: +// - 0 success +// - 1 generic / unknown +// - 2 flag / argument problem +// - 3 auth.* +// - 4 resource.not_found +// - 5 input.* +// - 6 server.rate_limited +// - 7 server.* (other) / network.* +func ExitCode(err error) int { + if err == nil { + return 0 + } + var fe *FlagError + if errors.As(err, &fe) { + return 2 + } + if errors.Is(err, SilentError) { + return 1 + } + if IsAuthError(err) { + return 3 + } + if IsNotFound(err) { + return 4 + } + if matchPrefix(err, "input.") { + return 5 + } + if matchCode(err, CodeServerRateLimited) { + return 6 + } + if matchPrefix(err, "server.") || matchPrefix(err, "network.") { + return 7 + } + return 1 +} + +// PrintError writes err to w as one human-readable line. The envelope-aware +// JSON formatter is in `internal/format`; this helper is the human path used +// when no command produced its own output. +func PrintError(w io.Writer, err error) { + if err == nil || errors.Is(err, SilentError) { + return + } + fmt.Fprintln(w, err.Error()) +} + +// PrintErrorEnvelope writes err as a JSON envelope on w. Used in agent mode / +// --json / --format=json output so failures stay machine-parseable. +func PrintErrorEnvelope(w io.Writer, err error) { + if err == nil || errors.Is(err, SilentError) { + return + } + _ = format.WriteEnvelope(w, format.Failure(ToErrorBody(err))) +} + +// ToErrorBody projects err into the canonical envelope ErrorBody. Exposed so +// other emit paths (planned: MCP) reuse the same projection rather than +// reimplementing the typed-error → wire-shape mapping. +func ToErrorBody(err error) *format.ErrorBody { + if err == nil { + return nil + } + body := &format.ErrorBody{Message: err.Error()} + var typed *Error + if errors.As(err, &typed) { + body.Code = string(typed.Code) + body.Message = typed.Message + body.Hint = typed.Hint + body.Retryable = typed.Retryable + // Surface the wrapped cause so agents see the actual server / SDK + // error string, not just the wrap message ("hybrid search"). Stripe's + // envelope does the same — the human's printed line and the JSON + // envelope both end with the underlying problem. + if typed.Cause != nil { + body.Message = typed.Message + ": " + typed.Cause.Error() + } + return body + } + var fe *FlagError + if errors.As(err, &fe) { + body.Code = string(CodeInputInvalidArgument) + return body + } + // Unclassified error; consumers see the message but no stable code. + body.Code = string(CodeServerError) + return body +} diff --git a/cli/internal/cmdutil/exit_test.go b/cli/internal/cmdutil/exit_test.go new file mode 100644 index 00000000..32fea773 --- /dev/null +++ b/cli/internal/cmdutil/exit_test.go @@ -0,0 +1,84 @@ +package cmdutil + +import ( + "bytes" + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestExitCode(t *testing.T) { + cases := []struct { + name string + err error + want int + }{ + {"nil success", nil, 0}, + {"flag error", NewFlagError(errors.New("bad flag")), 2}, + {"silent", SilentError, 1}, + {"auth.* prefix", NewError(CodeAuthUnauthenticated, "x"), 3}, + {"auth.token_expired", NewError(CodeAuthTokenExpired, "x"), 3}, + {"resource.not_found", NewError(CodeResourceNotFound, "x"), 4}, + {"input.* prefix", NewError(CodeInputInvalidArgument, "x"), 5}, + {"input.missing_flag", NewError(CodeInputMissingFlag, "x"), 5}, + {"server.rate_limited", NewError(CodeServerRateLimited, "x"), 6}, + {"server.* prefix", NewError(CodeServerError, "x"), 7}, + {"server.timeout", NewError(CodeServerTimeout, "x"), 7}, + {"network.* prefix", NewError(CodeNetworkError, "x"), 7}, + {"unknown error", errors.New("plain"), 1}, + {"local.* prefix", NewError(CodeLocalConfigCorrupt, "x"), 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, ExitCode(tc.err)) + }) + } +} + +func TestToErrorBody(t *testing.T) { + t.Run("nil returns nil", func(t *testing.T) { + assert.Nil(t, ToErrorBody(nil)) + }) + t.Run("typed without cause", func(t *testing.T) { + body := ToErrorBody(NewError(CodeResourceNotFound, "kb missing")) + assert.Equal(t, "resource.not_found", body.Code) + assert.Equal(t, "kb missing", body.Message) + }) + t.Run("typed with cause surfaces inner", func(t *testing.T) { + inner := errors.New("HTTP error 500: server exploded") + body := ToErrorBody(Wrapf(CodeServerError, inner, "hybrid search")) + assert.Equal(t, "server.error", body.Code) + // Both wrap context AND server cause must appear so agents see what + // actually broke, not just our wrap label. + assert.Equal(t, "hybrid search: HTTP error 500: server exploded", body.Message) + }) + t.Run("flag error", func(t *testing.T) { + body := ToErrorBody(NewFlagError(errors.New("bad flag"))) + assert.Equal(t, "input.invalid_argument", body.Code) + }) + t.Run("unclassified", func(t *testing.T) { + body := ToErrorBody(errors.New("anything")) + assert.Equal(t, "server.error", body.Code) + assert.Equal(t, "anything", body.Message) + }) +} + +func TestPrintError(t *testing.T) { + t.Run("nil is silent", func(t *testing.T) { + var buf bytes.Buffer + PrintError(&buf, nil) + assert.Empty(t, buf.String()) + }) + t.Run("SilentError is silent", func(t *testing.T) { + var buf bytes.Buffer + PrintError(&buf, SilentError) + assert.Empty(t, buf.String()) + }) + t.Run("typed error prints message", func(t *testing.T) { + var buf bytes.Buffer + PrintError(&buf, NewError(CodeAuthUnauthenticated, "no creds")) + assert.Contains(t, buf.String(), "auth.unauthenticated") + assert.Contains(t, buf.String(), "no creds") + }) +} diff --git a/cli/internal/cmdutil/exporter.go b/cli/internal/cmdutil/exporter.go new file mode 100644 index 00000000..d8c7c439 --- /dev/null +++ b/cli/internal/cmdutil/exporter.go @@ -0,0 +1,30 @@ +package cmdutil + +import ( + "io" + + "github.com/Tencent/WeKnora/cli/internal/format" +) + +// Exporter renders command output. Foundation PR ships a single +// jsonExporter that writes the envelope; PR-3 lands lipgloss tables, jq, +// and templates as additional implementations. +type Exporter interface { + Write(w io.Writer, env format.Envelope) error +} + +// NewJSONExporter returns an Exporter that emits envelope JSON via +// format.WriteEnvelope (single-source encoder config: no HTML escape). +func NewJSONExporter() Exporter { return &jsonExporter{} } + +type jsonExporter struct{} + +func (jsonExporter) Write(w io.Writer, env format.Envelope) error { + return format.WriteEnvelope(w, env) +} + +// NewTableExporter is a foundation-PR alias for the JSON exporter; PR-3 +// replaces it with a lipgloss-based renderer that respects iostreams.IO +// ColorEnabled. Until then table output looks identical to JSON output so +// commands work end-to-end either way. +func NewTableExporter(_ []string) Exporter { return &jsonExporter{} } diff --git a/cli/internal/cmdutil/exporter_test.go b/cli/internal/cmdutil/exporter_test.go new file mode 100644 index 00000000..63aba319 --- /dev/null +++ b/cli/internal/cmdutil/exporter_test.go @@ -0,0 +1,33 @@ +package cmdutil + +import ( + "bytes" + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/cli/internal/format" +) + +func TestJSONExporter_WritesEnvelope(t *testing.T) { + var buf bytes.Buffer + exp := NewJSONExporter() + require.NoError(t, exp.Write(&buf, format.Success(map[string]string{"k": "v"}, nil))) + var got map[string]any + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, true, got["ok"]) +} + +func TestTableExporter_PR1AliasesJSON(t *testing.T) { + var buf bytes.Buffer + require.NoError(t, NewTableExporter([]string{"id"}).Write(&buf, format.Success("x", nil))) + assert.Contains(t, buf.String(), `"ok":true`) +} + +func TestFlagError_IsSentinel(t *testing.T) { + err := NewFlagError(assert.AnError) + _, ok := err.(*FlagError) + assert.True(t, ok) +} diff --git a/cli/internal/cmdutil/factory.go b/cli/internal/cmdutil/factory.go new file mode 100644 index 00000000..992b743d --- /dev/null +++ b/cli/internal/cmdutil/factory.go @@ -0,0 +1,135 @@ +package cmdutil + +import ( + "errors" + "fmt" + "sync" + + "github.com/Tencent/WeKnora/cli/internal/config" + "github.com/Tencent/WeKnora/cli/internal/iostreams" + "github.com/Tencent/WeKnora/cli/internal/prompt" + "github.com/Tencent/WeKnora/cli/internal/secrets" + sdk "github.com/Tencent/WeKnora/client" +) + +// Factory is the dependency container injected at command construction. Each +// closure is lazy: --help / completion / `weknora schema` must NOT trigger +// HTTP, keyring access, or filesystem I/O beyond the bare minimum. +// +// Four closures (ADR-4): +// - Config: parses ~/.config/weknora/config.yaml (no network) +// - Client: constructs the SDK client (network: server compat probe + cached) +// - Prompter: returns interactive prompter; agent mode returns AgentPrompter +// - Secrets: builds the OS keyring / file fallback credential store the +// first time it is requested (probing the keyring at startup +// 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.IO. The bar to add a new closure is at least 2 commands sharing the +// same dependency; resist factory bloat (gh CLI cautionary tale). +// +// 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. +type Factory struct { + Config func() (*config.Config, error) + Client func() (*sdk.Client, error) + Prompter func() prompt.Prompter + Secrets func() (secrets.Store, error) +} + +// New constructs a production Factory wired to real config / SDK client. +// +// All closures are lazy: invoking --help, version, or shell completion runs +// none of them. The Secrets closure memoizes via sync.Once so the keyring +// probe happens at most once per process. +func New() *Factory { + var ( + secretsOnce sync.Once + secretsStore secrets.Store + secretsErr error + ) + f := &Factory{} + f.Config = func() (*config.Config, error) { return config.Load() } + f.Client = func() (*sdk.Client, error) { return buildClient(f) } + f.Prompter = func() prompt.Prompter { + if iostreams.IO.IsStdoutTTY() && iostreams.IO.IsStderrTTY() { + return prompt.NewTTYPrompter() + } + return prompt.AgentPrompter{} + } + f.Secrets = func() (secrets.Store, error) { + secretsOnce.Do(func() { + secretsStore, secretsErr = secrets.NewBestEffortStore() + }) + return secretsStore, secretsErr + } + return f +} + +// buildClient resolves the active context, loads the credentials from secrets, +// and constructs a *sdk.Client. Returns CodeAuthUnauthenticated when no +// credentials are available so the user gets the right hint to run +// `weknora auth login`. +func buildClient(f *Factory) (*sdk.Client, error) { + cfg, err := f.Config() + if err != nil { + return nil, err + } + ctxName := cfg.CurrentContext + if ctxName == "" { + return nil, NewError(CodeAuthUnauthenticated, "no current context configured; run `weknora auth login` to set one up") + } + ctx, ok := cfg.Contexts[ctxName] + if !ok { + return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("config references unknown context %q", ctxName)) + } + if ctx.Host == "" { + return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("context %q has no host", ctxName)) + } + + opts := []sdk.ClientOption{} + store, err := f.Secrets() + if err != nil { + return nil, Wrapf(CodeLocalKeychainDenied, err, "init secrets store") + } + // Only fetch the secrets the context actually references. Skipping the + // unused fetch avoids a `security` exec (macOS) / DBus call (Linux) per + // authenticated invocation. + if ctx.TokenRef != "" { + if access, err := loadSecret(store, ctxName, "access"); err != nil { + return nil, err + } else if access != "" { + opts = append(opts, sdk.WithBearerToken(access)) + } + } + if ctx.APIKeyRef != "" { + if apiKey, err := loadSecret(store, ctxName, "api_key"); err != nil { + return nil, err + } else if apiKey != "" { + opts = append(opts, sdk.WithAPIKey(apiKey)) + } + } + // ctx.TenantID is intentionally NOT injected as X-Tenant-ID. Servers derive + // 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 — gh / gcloud / Stripe CLIs all require an explicit + // flag (`--tenant=N` is the planned v0.1 entry point) before sending it. + // `tenant_id` stays in config for `auth status` display only. + return sdk.NewClient(ctx.Host, opts...), nil +} + +// loadSecret returns the stored value for (context, key); ErrNotFound becomes +// ("", nil) so callers can treat "not configured" as success. +func loadSecret(store secrets.Store, context, key string) (string, error) { + v, err := store.Get(context, key) + if errors.Is(err, secrets.ErrNotFound) { + return "", nil + } + if err != nil { + return "", Wrapf(CodeLocalKeychainDenied, err, "load %s", key) + } + return v, nil +} diff --git a/cli/internal/cmdutil/factory_test.go b/cli/internal/cmdutil/factory_test.go new file mode 100644 index 00000000..67b18246 --- /dev/null +++ b/cli/internal/cmdutil/factory_test.go @@ -0,0 +1,214 @@ +package cmdutil + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/cli/internal/config" + "github.com/Tencent/WeKnora/cli/internal/prompt" + "github.com/Tencent/WeKnora/cli/internal/secrets" + sdk "github.com/Tencent/WeKnora/client" +) + +// TestFactory_Lazy ensures none of the closures execute work at construction +// time — `--help` / `completion` must not trigger HTTP / keyring access. +func TestFactory_Lazy(t *testing.T) { + var configCalls, clientCalls, prompterCalls int + f := &Factory{ + Config: func() (*config.Config, error) { + configCalls++ + return &config.Config{}, nil + }, + Client: func() (*sdk.Client, error) { + clientCalls++ + return nil, nil + }, + Prompter: func() prompt.Prompter { + prompterCalls++ + return prompt.AgentPrompter{} + }, + } + // Asserting on closure presence — none should have run yet. + assert.Equal(t, 0, configCalls) + assert.Equal(t, 0, clientCalls) + assert.Equal(t, 0, prompterCalls) + // Smoke: each closure runs exactly once when called. + _, err := f.Config() + require.NoError(t, err) + assert.Equal(t, 1, configCalls) + _, _ = f.Client() + assert.Equal(t, 1, clientCalls) + _ = f.Prompter() + assert.Equal(t, 1, prompterCalls) +} + +// TestNew_FoundationDefaults verifies the production New() returns a usable +// Factory and that Client surfaces auth.unauthenticated when no current +// context is configured (the precondition for `weknora auth login`). +func TestNew_FoundationDefaults(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // empty config → no current context + f := New() + require.NotNil(t, f) + require.NotNil(t, f.Config) + require.NotNil(t, f.Client) + require.NotNil(t, f.Prompter) + require.NotNil(t, f.Secrets) + + _, err := f.Client() + require.Error(t, err) + var typed *Error + require.True(t, errors.As(err, &typed), "expected *cmdutil.Error") + assert.Equal(t, CodeAuthUnauthenticated, typed.Code) +} + +// TestTypedPredicates exercises the namespace and code matchers. +func TestTypedPredicates(t *testing.T) { + t.Run("IsAuthError matches auth.* prefix", func(t *testing.T) { + err := NewError(CodeAuthUnauthenticated, "no creds") + assert.True(t, IsAuthError(err)) + assert.False(t, IsNotFound(err)) + }) + t.Run("IsNotFound matches resource.not_found exactly", func(t *testing.T) { + err := NewError(CodeResourceNotFound, "kb missing") + assert.True(t, IsNotFound(err)) + assert.False(t, IsTransient(err)) + }) + t.Run("IsTransient matches network.* and server.timeout / rate_limited", func(t *testing.T) { + assert.True(t, IsTransient(NewError(CodeNetworkError, ""))) + assert.True(t, IsTransient(NewError(CodeServerTimeout, ""))) + assert.True(t, IsTransient(NewError(CodeServerRateLimited, ""))) + assert.False(t, IsTransient(NewError(CodeServerError, ""))) + }) + t.Run("predicates walk the wrap chain", func(t *testing.T) { + inner := NewError(CodeAuthTokenExpired, "expired") + wrapped := Wrapf(CodeServerError, inner, "while calling foo") + // IsAuthExpired matches the wrapped *Error first; outer Wrapf has + // CodeServerError so the predicate returns false on the outer match. + // This documents current behavior: predicates report the first *Error + // in the chain, not deep walks. + assert.False(t, IsAuthExpired(wrapped)) + // Direct match works. + assert.True(t, IsAuthExpired(inner)) + }) + t.Run("non-typed errors are never matched", func(t *testing.T) { + assert.False(t, IsAuthError(errors.New("plain error"))) + assert.False(t, IsNotFound(nil)) + }) +} + +// TestError_Format checks the Error/Unwrap surface. +func TestError_Format(t *testing.T) { + cause := errors.New("dial tcp: refused") + e := Wrapf(CodeNetworkError, cause, "connect to %s", "host") + assert.Contains(t, e.Error(), "network.error") + assert.Contains(t, e.Error(), "connect to host") + assert.Contains(t, e.Error(), "dial tcp: refused") + assert.Same(t, cause, errors.Unwrap(e)) +} + +func memSecretsFn(s *secrets.MemStore) func() (secrets.Store, error) { + return func() (secrets.Store, error) { return s, nil } +} + +func TestBuildClient_NoCurrentContext(t *testing.T) { + f := &Factory{ + Config: func() (*config.Config, error) { return &config.Config{}, nil }, + Secrets: memSecretsFn(secrets.NewMemStore()), + } + _, err := buildClient(f) + require.Error(t, err) + var typed *Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, CodeAuthUnauthenticated, typed.Code) +} + +func TestBuildClient_UnknownContext(t *testing.T) { + f := &Factory{ + Config: func() (*config.Config, error) { + return &config.Config{CurrentContext: "ghost"}, nil + }, + Secrets: memSecretsFn(secrets.NewMemStore()), + } + _, err := buildClient(f) + require.Error(t, err) + var typed *Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, CodeLocalConfigCorrupt, typed.Code) +} + +func TestBuildClient_MissingHost(t *testing.T) { + f := &Factory{ + Config: func() (*config.Config, error) { + return &config.Config{ + CurrentContext: "p", + Contexts: map[string]config.Context{"p": {Host: ""}}, + }, nil + }, + Secrets: memSecretsFn(secrets.NewMemStore()), + } + _, err := buildClient(f) + require.Error(t, err) + var typed *Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, CodeLocalConfigCorrupt, typed.Code) +} + +func TestBuildClient_HappyPath(t *testing.T) { + store := secrets.NewMemStore() + require.NoError(t, store.Set("p", "access", "jwt")) + require.NoError(t, store.Set("p", "api_key", "sk-x")) + f := &Factory{ + Config: func() (*config.Config, error) { + return &config.Config{ + CurrentContext: "p", + Contexts: map[string]config.Context{ + "p": { + Host: "https://kb.example.com", + TenantID: 7, + TokenRef: "mem://p/access", + APIKeyRef: "mem://p/api_key", + }, + }, + }, nil + }, + Secrets: memSecretsFn(store), + } + cli, err := buildClient(f) + require.NoError(t, err) + require.NotNil(t, cli) +} + +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. + store := &countingSecrets{MemStore: secrets.NewMemStore()} + require.NoError(t, store.Set("p", "access", "jwt")) + f := &Factory{ + Config: func() (*config.Config, error) { + return &config.Config{ + CurrentContext: "p", + Contexts: map[string]config.Context{ + "p": {Host: "https://x", TokenRef: "mem://p/access"}, + }, + }, nil + }, + Secrets: func() (secrets.Store, error) { return store, nil }, + } + _, err := buildClient(f) + require.NoError(t, err) + assert.Equal(t, 1, store.gets, "must fetch only access; api_key was not referenced") +} + +// countingSecrets wraps MemStore to count Get invocations. +type countingSecrets struct { + *secrets.MemStore + gets int +} + +func (c *countingSecrets) Get(ctx, key string) (string, error) { + c.gets++ + return c.MemStore.Get(ctx, key) +} diff --git a/cli/internal/cmdutil/json_flags.go b/cli/internal/cmdutil/json_flags.go new file mode 100644 index 00000000..dbbf039a --- /dev/null +++ b/cli/internal/cmdutil/json_flags.go @@ -0,0 +1,28 @@ +package cmdutil + +import ( + "github.com/spf13/cobra" +) + +// AddJSONFlags registers the standard output triplet on cmd: +// +// --json [fields] JSON envelope output, optional field-projection list +// --jq embedded jq filter (PR-3 wires the real evaluator) +// --template Go text/template (PR-3) +// +// The three flags are mutually exclusive at evaluation time; PR-3 enforces it. +// `fields` is the list of valid field names that --json [fields] may project +// against; commands pass their resource's field set (kb / doc / chunk / ...). +// +// *exporter is initialized to a JSON exporter; PR-3 swaps in jq/template +// variants based on which flag the user supplied. +func AddJSONFlags(cmd *cobra.Command, exporter *Exporter, fields []string) { + _ = fields // PR-3 uses this for --json field-list completion + validation + var jsonOut bool + var jqExpr string + var tmpl string + cmd.Flags().BoolVar(&jsonOut, "json", false, "Output JSON envelope") + cmd.Flags().StringVar(&jqExpr, "jq", "", "Filter output via embedded jq expression") + cmd.Flags().StringVar(&tmpl, "template", "", "Format output via Go text/template") + *exporter = NewJSONExporter() +} diff --git a/cli/internal/cmdutil/json_flags_test.go b/cli/internal/cmdutil/json_flags_test.go new file mode 100644 index 00000000..b565ef03 --- /dev/null +++ b/cli/internal/cmdutil/json_flags_test.go @@ -0,0 +1,18 @@ +package cmdutil + +import ( + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" +) + +func TestAddJSONFlags_RegistersFlags(t *testing.T) { + c := &cobra.Command{Use: "x"} + var exp Exporter + AddJSONFlags(c, &exp, []string{"id", "name"}) + assert.NotNil(t, c.Flags().Lookup("json")) + assert.NotNil(t, c.Flags().Lookup("jq")) + assert.NotNil(t, c.Flags().Lookup("template")) + assert.NotNil(t, exp, "exporter must be initialized") +} diff --git a/cli/internal/cmdutil/options.go b/cli/internal/cmdutil/options.go new file mode 100644 index 00000000..bfe376a9 --- /dev/null +++ b/cli/internal/cmdutil/options.go @@ -0,0 +1,22 @@ +package cmdutil + +import ( + "fmt" + + "github.com/spf13/cobra" +) + +// Options is the marker interface every command's Options struct should +// satisfy. Concrete Options structs (KbListOptions, DocUploadOptions, ...) +// are declared in their own command file; see CONTRIBUTING.md for the template. +type Options interface{} + +// MustRequireFlag panics on programmer error (typo in flag name). cobra's +// MarkFlagRequired only returns an error when the named flag does not exist +// on the command, which means the caller has a typo at registration time — +// non-recoverable. Wrap so command builders stay one-line. +func MustRequireFlag(cmd *cobra.Command, name string) { + if err := cmd.MarkFlagRequired(name); err != nil { + panic(fmt.Sprintf("MarkFlagRequired %q: %v", name, err)) + } +} diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go new file mode 100644 index 00000000..e9351aae --- /dev/null +++ b/cli/internal/config/config.go @@ -0,0 +1,106 @@ +// Package config reads and writes the user-level config at +// $XDG_CONFIG_HOME/weknora/config.yaml. yaml.v3 directly; viper is intentionally +// not used (see ADR-2). +// +// v0.0 supports only Load/Save with multi-host context map; project link +// (.weknora/project.toml) is wired in v0.2 (ADR-16). +package config + +import ( + "errors" + "fmt" + "os" + "path/filepath" + + "gopkg.in/yaml.v3" +) + +// Config is the on-disk schema. Empty zero-value is valid (returned when the +// file does not exist) so commands like --help / version don't fail. +type Config struct { + CurrentContext string `yaml:"current_context,omitempty"` + Contexts map[string]Context `yaml:"contexts,omitempty"` + + // Defaults holds CLI-wide defaults; fields opt-in. + Defaults struct { + Format string `yaml:"format,omitempty"` + NoVersionCheck bool `yaml:"no_version_check,omitempty"` + RequestIDPrefix string `yaml:"request_id_prefix,omitempty"` + } `yaml:"defaults,omitempty"` +} + +// Context is one named connection target (host + tenant + credential reference). +type Context struct { + Host string `yaml:"host"` + TenantID uint64 `yaml:"tenant_id,omitempty"` + User string `yaml:"user,omitempty"` + APIKeyRef string `yaml:"api_key_ref,omitempty"` // keychain://... or file://... + TokenRef string `yaml:"token_ref,omitempty"` // keychain://... or file://... + RefreshRef string `yaml:"refresh_token_ref,omitempty"` + DefaultKBID string `yaml:"default_kb_id,omitempty"` +} + +// ErrCorrupt is returned by Load when the file exists but cannot be parsed. +// Callers should map this to error code "local.config_corrupt". +var ErrCorrupt = errors.New("config: file is malformed") + +// Path returns the absolute config file path. +// +// We honor XDG_CONFIG_HOME on every OS (CLI convention — gh, kubectl, helm +// all do this even on macOS, where os.UserConfigDir would otherwise return +// ~/Library/Application Support). Falls back to ~/.config/weknora. +func Path() (string, error) { + if x := os.Getenv("XDG_CONFIG_HOME"); x != "" { + return filepath.Join(x, "weknora", "config.yaml"), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("locate home dir: %w", err) + } + return filepath.Join(home, ".config", "weknora", "config.yaml"), nil +} + +// Load reads the config file. If it does not exist, returns a zero-value +// Config with no error (commands like `version` and `--help` must not fail +// just because the user has not run `auth login` yet). +func Load() (*Config, error) { + p, err := Path() + if err != nil { + return nil, err + } + data, err := os.ReadFile(p) + if errors.Is(err, os.ErrNotExist) { + return &Config{}, nil + } + if err != nil { + return nil, fmt.Errorf("read config: %w", err) + } + var c Config + if err := yaml.Unmarshal(data, &c); err != nil { + return nil, fmt.Errorf("%w: %v", ErrCorrupt, err) + } + return &c, nil +} + +// Save writes the config atomically (write temp + rename) with mode 0600. +func Save(c *Config) error { + p, err := Path() + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + return fmt.Errorf("mkdir config dir: %w", err) + } + data, err := yaml.Marshal(c) + if err != nil { + return fmt.Errorf("marshal config: %w", err) + } + tmp := p + ".tmp" + if err := os.WriteFile(tmp, data, 0o600); err != nil { + return fmt.Errorf("write config: %w", err) + } + if err := os.Rename(tmp, p); err != nil { + return fmt.Errorf("rename config: %w", err) + } + return nil +} diff --git a/cli/internal/config/config_test.go b/cli/internal/config/config_test.go new file mode 100644 index 00000000..c6393ad3 --- /dev/null +++ b/cli/internal/config/config_test.go @@ -0,0 +1,90 @@ +package config + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/cli/internal/testutil" +) + +func TestLoad_FileMissing(t *testing.T) { + testutil.XDGTempDir(t) + c, err := Load() + require.NoError(t, err, "missing file must not error (commands like --help must work)") + assert.NotNil(t, c) + assert.Empty(t, c.Contexts) +} + +func TestSaveLoad_RoundTrip(t *testing.T) { + testutil.XDGTempDir(t) + in := &Config{ + CurrentContext: "prod", + Contexts: map[string]Context{ + "prod": {Host: "https://kb.example.com", TenantID: 7, APIKeyRef: "keychain://weknora/prod/access"}, + }, + } + require.NoError(t, Save(in)) + + out, err := Load() + require.NoError(t, err) + assert.Equal(t, "prod", out.CurrentContext) + assert.Equal(t, "https://kb.example.com", out.Contexts["prod"].Host) + assert.Equal(t, uint64(7), out.Contexts["prod"].TenantID) + + p, err := Path() + require.NoError(t, err) + st, err := os.Stat(p) + require.NoError(t, err) + if runtime.GOOS != "windows" { + // Windows file ACLs don't map to Unix mode bits; os.Chmod is + // effectively a no-op for owner/group/other distinctions, so the + // 0600 invariant only meaningfully holds on Unix-like platforms. + assert.Equal(t, os.FileMode(0o600), st.Mode().Perm()) + } +} + +func TestLoad_Corrupt(t *testing.T) { + dir := testutil.XDGTempDir(t) + p := filepath.Join(dir, "weknora", "config.yaml") + require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o700)) + require.NoError(t, os.WriteFile(p, []byte("not: valid: yaml: ::"), 0o600)) + + _, err := Load() + require.Error(t, err) + assert.True(t, errors.Is(err, ErrCorrupt)) +} + +func TestPath_HonorsXDG(t *testing.T) { + xdg := filepath.Join(t.TempDir(), "xdg") + t.Setenv("XDG_CONFIG_HOME", xdg) + p, err := Path() + require.NoError(t, err) + assert.Equal(t, filepath.Join(xdg, "weknora", "config.yaml"), p) +} + +func TestPath_FallsBackToHome(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", "") + t.Setenv("HOME", filepath.Join(t.TempDir(), "home")) + p, err := Path() + require.NoError(t, err) + // Compare via slash-normalized form so the assertion is platform-agnostic + // (Windows uses backslash; semantics here is "the relative tail"). + assert.Contains(t, filepath.ToSlash(p), "/.config/weknora/config.yaml") +} + +func TestSave_AtomicReplace(t *testing.T) { + dir := testutil.XDGTempDir(t) + require.NoError(t, Save(&Config{CurrentContext: "a"})) + require.NoError(t, Save(&Config{CurrentContext: "b"})) + out, err := Load() + require.NoError(t, err) + assert.Equal(t, "b", out.CurrentContext) + matches, _ := filepath.Glob(filepath.Join(dir, "weknora", "*.tmp")) + assert.Empty(t, matches) +} diff --git a/cli/internal/format/envelope.go b/cli/internal/format/envelope.go new file mode 100644 index 00000000..063faeed --- /dev/null +++ b/cli/internal/format/envelope.go @@ -0,0 +1,73 @@ +// Package format renders command output: JSON envelope, jq, template, table. +// +// Non-TTY default = JSON envelope (ADR-5). Envelope schema is the contract +// shared with `weknora mcp serve` tools and external agents. +package format + +import ( + "encoding/json" + "io" +) + +// Envelope is the canonical success/failure shape returned by every command. +type Envelope struct { + OK bool `json:"ok"` + Data any `json:"data,omitempty"` + Error *ErrorBody `json:"error,omitempty"` + Meta *Meta `json:"_meta,omitempty"` +} + +// Meta carries non-payload context fields useful to agents and observability. +type Meta struct { + Context string `json:"context,omitempty"` + TenantID uint64 `json:"tenant_id,omitempty"` + KBID string `json:"kb_id,omitempty"` + RequestID string `json:"request_id,omitempty"` + NextCursor string `json:"next_cursor,omitempty"` + HasMore bool `json:"has_more,omitempty"` + Warnings []string `json:"warnings,omitempty"` + AppliedFilters []string `json:"applied_filters,omitempty"` +} + +// RiskLevel classifies an error by the kind of operation that produced it. +// Agents use this to decide whether to retry, escalate, or stop. +type RiskLevel string + +const ( + RiskRead RiskLevel = "read" + RiskMutating RiskLevel = "mutating" + RiskDestructive RiskLevel = "destructive" +) + +// ErrorBody is the failure shape. `code` is a stable namespaced ID (e.g. +// "auth.unauthenticated"); `hint` is an actionable next step; `risk` flags +// destructive intent for agent self-governance. +type ErrorBody struct { + Code string `json:"code"` + Message string `json:"message"` + Hint string `json:"hint,omitempty"` + RequestID string `json:"request_id,omitempty"` + Context string `json:"context,omitempty"` + Risk RiskLevel `json:"risk,omitempty"` + Retryable bool `json:"retryable,omitempty"` + ConsoleURL string `json:"console_url,omitempty"` + Details map[string]any `json:"details,omitempty"` +} + +// WriteEnvelope serializes env as one-line JSON to w. Used for non-TTY output +// and for `--format json` / `--agent` modes. +func WriteEnvelope(w io.Writer, env Envelope) error { + enc := json.NewEncoder(w) + enc.SetEscapeHTML(false) + return enc.Encode(env) +} + +// Success constructs a success envelope. +func Success(data any, meta *Meta) Envelope { + return Envelope{OK: true, Data: data, Meta: meta} +} + +// Failure constructs a failure envelope. +func Failure(err *ErrorBody) Envelope { + return Envelope{OK: false, Error: err} +} diff --git a/cli/internal/format/envelope_test.go b/cli/internal/format/envelope_test.go new file mode 100644 index 00000000..97a77e27 --- /dev/null +++ b/cli/internal/format/envelope_test.go @@ -0,0 +1,50 @@ +package format + +import ( + "bytes" + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSuccessEnvelope(t *testing.T) { + env := Success(map[string]string{"id": "kb_abc"}, &Meta{Context: "prod", RequestID: "cli-01"}) + var buf bytes.Buffer + require.NoError(t, WriteEnvelope(&buf, env)) + var got map[string]any + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, true, got["ok"]) + assert.NotNil(t, got["data"]) + assert.NotNil(t, got["_meta"]) + assert.Nil(t, got["error"]) +} + +func TestFailureEnvelope(t *testing.T) { + env := Failure(&ErrorBody{ + Code: "auth.unauthenticated", + Message: "no creds", + Hint: "run weknora auth login", + Risk: RiskRead, + Retryable: false, + }) + var buf bytes.Buffer + require.NoError(t, WriteEnvelope(&buf, env)) + var got map[string]any + require.NoError(t, json.Unmarshal(buf.Bytes(), &got)) + assert.Equal(t, false, got["ok"]) + errBody := got["error"].(map[string]any) + assert.Equal(t, "auth.unauthenticated", errBody["code"]) + assert.Equal(t, "run weknora auth login", errBody["hint"]) + assert.Equal(t, "read", errBody["risk"]) +} + +func TestEnvelope_NoEscapeHTML(t *testing.T) { + // Hints / messages may include & or <; ensure we don't HTML-escape them + // (would break agent jq pipelines). + env := Failure(&ErrorBody{Code: "x", Message: "a & b < c"}) + var buf bytes.Buffer + require.NoError(t, WriteEnvelope(&buf, env)) + assert.Contains(t, buf.String(), "a & b < c") +} diff --git a/cli/internal/iostreams/iostreams.go b/cli/internal/iostreams/iostreams.go new file mode 100644 index 00000000..4dd583fe --- /dev/null +++ b/cli/internal/iostreams/iostreams.go @@ -0,0 +1,68 @@ +// Package iostreams wraps stdout/stderr/stdin with TTY detection and color awareness. +// +// Tests swap the package-level singleton via SetForTest; production code reads +// the global IO directly. (Tests must not call SetForTest from t.Parallel(), +// since the swap is process-global.) +package iostreams + +import ( + "bytes" + "io" + "os" + "testing" + + "github.com/mattn/go-isatty" +) + +// IOStreams holds standard I/O handles plus environment-derived flags. +type IOStreams struct { + In io.Reader + Out io.Writer + Err io.Writer + + stdoutTTY bool + stderrTTY bool +} + +// IO is the package-level singleton. +var IO *IOStreams = newProduction() + +func newProduction() *IOStreams { + return &IOStreams{ + In: os.Stdin, + Out: os.Stdout, + Err: os.Stderr, + stdoutTTY: isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()), + stderrTTY: isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd()), + } +} + +// IsStdoutTTY reports whether stdout is a terminal. +func (s *IOStreams) IsStdoutTTY() bool { return s.stdoutTTY } + +// IsStderrTTY reports whether stderr is a terminal. +func (s *IOStreams) IsStderrTTY() bool { return s.stderrTTY } + +// ColorEnabled honors NO_COLOR (https://no-color.org) and TERM=dumb. +// Computed on demand so env changes after init are picked up by callers. +func (s *IOStreams) ColorEnabled() bool { + if !s.stdoutTTY { + return false + } + if os.Getenv("NO_COLOR") != "" { + return false + } + return os.Getenv("TERM") != "dumb" +} + +// SetForTest replaces the package singleton with in-memory buffers for the +// duration of t. Call it once per test. Not safe under t.Parallel(). +func SetForTest(t *testing.T) (out, errBuf *bytes.Buffer) { + t.Helper() + saved := IO + out = &bytes.Buffer{} + errBuf = &bytes.Buffer{} + IO = &IOStreams{In: bytes.NewReader(nil), Out: out, Err: errBuf} + t.Cleanup(func() { IO = saved }) + return out, errBuf +} diff --git a/cli/internal/iostreams/iostreams_test.go b/cli/internal/iostreams/iostreams_test.go new file mode 100644 index 00000000..410b5692 --- /dev/null +++ b/cli/internal/iostreams/iostreams_test.go @@ -0,0 +1,36 @@ +package iostreams + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSetForTest(t *testing.T) { + out, errBuf := SetForTest(t) + IO.Out.Write([]byte("stdout")) + IO.Err.Write([]byte("stderr")) + assert.Equal(t, "stdout", out.String()) + assert.Equal(t, "stderr", errBuf.String()) +} + +func TestSetForTest_RestoresSingleton(t *testing.T) { + original := IO + t.Run("nested", func(t *testing.T) { + SetForTest(t) + assert.NotSame(t, original, IO) + }) + // After the subtest's t.Cleanup runs, IO must be restored. + assert.Same(t, original, IO) +} + +func TestProductionGetters(t *testing.T) { + // We can't reliably assert the *value* of these (depends on whether tests + // run in a TTY) but we can ensure the methods don't panic and return + // consistent values across calls. + p := newProduction() + a, b := p.IsStdoutTTY(), p.IsStderrTTY() + assert.Equal(t, a, p.IsStdoutTTY()) + assert.Equal(t, b, p.IsStderrTTY()) + _ = p.ColorEnabled() // smoke +} diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.go new file mode 100644 index 00000000..bdb58d71 --- /dev/null +++ b/cli/internal/prompt/prompt.go @@ -0,0 +1,32 @@ +// Package prompt defines the interactive-input abstraction. +// +// Production impl will use charmbracelet/huh in v0.0 commands that need +// password input (auth login). Foundation PR ships only the interface + +// a sentinel error so non-TTY contexts surface the right error. +package prompt + +import "errors" + +// ErrAgentNoPrompt is returned by any Prompter call made when the CLI is in +// agent / non-interactive mode. Commands should map this to a "missing flag" +// user error before returning to cobra. +var ErrAgentNoPrompt = errors.New("prompt: interactive input not available in agent/non-interactive mode") + +// Prompter is the small abstraction the auth login flow needs. Tests inject +// scripted responses; production wires charmbracelet/huh. +type Prompter interface { + // Input collects free-form text input from the user. + Input(label, defaultValue string) (string, error) + // Password collects a secret without echoing. + Password(label string) (string, error) + // Confirm asks for yes/no confirmation, used by destructive commands. + Confirm(label string, defaultValue bool) (bool, error) +} + +// AgentPrompter rejects all interactive calls. Use it as the Factory.Prompter +// closure result whenever agent mode is detected. +type AgentPrompter struct{} + +func (AgentPrompter) Input(string, string) (string, error) { return "", ErrAgentNoPrompt } +func (AgentPrompter) Password(string) (string, error) { return "", ErrAgentNoPrompt } +func (AgentPrompter) Confirm(string, bool) (bool, error) { return false, ErrAgentNoPrompt } diff --git a/cli/internal/prompt/prompt_test.go b/cli/internal/prompt/prompt_test.go new file mode 100644 index 00000000..492e3258 --- /dev/null +++ b/cli/internal/prompt/prompt_test.go @@ -0,0 +1,18 @@ +package prompt + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestAgentPrompter_AlwaysRejects(t *testing.T) { + p := AgentPrompter{} + _, err := p.Input("label", "default") + assert.True(t, errors.Is(err, ErrAgentNoPrompt)) + _, err = p.Password("password") + assert.True(t, errors.Is(err, ErrAgentNoPrompt)) + _, err = p.Confirm("yes?", false) + assert.True(t, errors.Is(err, ErrAgentNoPrompt)) +} diff --git a/cli/internal/safepaths/safepaths.go b/cli/internal/safepaths/safepaths.go new file mode 100644 index 00000000..0536bcbe --- /dev/null +++ b/cli/internal/safepaths/safepaths.go @@ -0,0 +1,72 @@ +// Package safepaths provides path-traversal protection for file inputs to +// commands such as `weknora doc upload`. +// +// Two primary checks: +// - Validate(path): reject empty, ".", "..", or paths containing embedded ".." segments. +// - WithinRoot(path, root): both are made absolute and compared with a +// separator-aware prefix check, so a directory named "..foo" cannot +// masquerade as escaping ".." (the lexical strings.HasPrefix(rel, "..") +// trap). +// +// Symlinks are NOT resolved; callers needing realpath semantics must +// pre-resolve. Modeled on the same pattern as `internal/utils/security.go` +// SafePathUnderBase in the server module. +package safepaths + +import ( + "errors" + "fmt" + "path/filepath" + "strings" +) + +// ErrPathEscapes signals that the given path resolves outside the allowed root. +var ErrPathEscapes = errors.New("path escapes allowed root") + +// ErrEmptyPath signals an empty input. +var ErrEmptyPath = errors.New("path is empty") + +// ErrSuspiciousPath signals a "."/".." or embedded ".." traversal. +var ErrSuspiciousPath = errors.New("path contains suspicious traversal segment") + +// Validate cleans path and rejects empty inputs, "." / "..", or any path that +// contains an embedded ".." segment after cleaning. It does not resolve symlinks. +func Validate(path string) (string, error) { + if path == "" { + return "", ErrEmptyPath + } + cleaned := filepath.Clean(path) + if cleaned == "" || cleaned == "." || cleaned == ".." { + return "", fmt.Errorf("%w: %q", ErrSuspiciousPath, path) + } + for _, seg := range strings.Split(cleaned, string(filepath.Separator)) { + if seg == ".." { + return "", fmt.Errorf("%w: %q", ErrSuspiciousPath, path) + } + } + return cleaned, nil +} + +// WithinRoot reports whether path lies inside root after both are made +// absolute. Comparison is separator-aware: a path "/srv/data..foo" is NOT +// treated as escaping "/srv/data" just because "..foo" textually starts +// with "..". +func WithinRoot(path, root string) error { + absPath, err := filepath.Abs(path) + if err != nil { + return fmt.Errorf("resolve path: %w", err) + } + absRoot, err := filepath.Abs(root) + if err != nil { + return fmt.Errorf("resolve root: %w", err) + } + // Equal paths count as "within"; otherwise require a separator-bounded prefix. + if absPath == absRoot { + return nil + } + withSep := absRoot + string(filepath.Separator) + if !strings.HasPrefix(absPath, withSep) { + return fmt.Errorf("%w: %s not under %s", ErrPathEscapes, absPath, absRoot) + } + return nil +} diff --git a/cli/internal/safepaths/safepaths_test.go b/cli/internal/safepaths/safepaths_test.go new file mode 100644 index 00000000..25b7b26b --- /dev/null +++ b/cli/internal/safepaths/safepaths_test.go @@ -0,0 +1,70 @@ +package safepaths + +import ( + "errors" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestValidate(t *testing.T) { + t.Run("rejects empty", func(t *testing.T) { + _, err := Validate("") + require.ErrorIs(t, err, ErrEmptyPath) + }) + t.Run("rejects bare dot", func(t *testing.T) { + _, err := Validate(".") + require.ErrorIs(t, err, ErrSuspiciousPath) + }) + t.Run("rejects bare double-dot", func(t *testing.T) { + _, err := Validate("..") + require.ErrorIs(t, err, ErrSuspiciousPath) + }) + t.Run("rejects relative path that ascends past start", func(t *testing.T) { + // "../foo" preserves the ".." after Clean. + _, err := Validate("../foo") + require.ErrorIs(t, err, ErrSuspiciousPath) + }) + t.Run("cleans benign relative", func(t *testing.T) { + // "a/b/../c" cleans to "a/c" — fine. + got, err := Validate("a/b/../c") + require.NoError(t, err) + assert.Equal(t, filepath.Clean("a/c"), got) + }) + t.Run("cleans cancelling relative", func(t *testing.T) { + // "a/../b" cleans to "b" — also fine; the ascent fully resolves. + got, err := Validate("a/../b") + require.NoError(t, err) + assert.Equal(t, "b", got) + }) +} + +func TestWithinRoot(t *testing.T) { + t.Run("inside root", func(t *testing.T) { + err := WithinRoot("/srv/data/file.md", "/srv/data") + require.NoError(t, err) + }) + t.Run("equal to root", func(t *testing.T) { + err := WithinRoot("/srv/data", "/srv/data") + require.NoError(t, err) + }) + t.Run("escapes via parent", func(t *testing.T) { + err := WithinRoot("/srv/data/../../etc/passwd", "/srv/data") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrPathEscapes)) + }) + t.Run("sibling outside", func(t *testing.T) { + err := WithinRoot("/srv/other", "/srv/data") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrPathEscapes)) + }) + t.Run("dotdot-prefix sibling is not within", func(t *testing.T) { + // /srv/data..foo lexically starts with "/srv/data" but is a different dir. + // Without separator-awareness this would be a false negative. + err := WithinRoot("/srv/data..foo/x", "/srv/data") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrPathEscapes)) + }) +} diff --git a/cli/internal/secrets/secrets.go b/cli/internal/secrets/secrets.go new file mode 100644 index 00000000..650ee8c3 --- /dev/null +++ b/cli/internal/secrets/secrets.go @@ -0,0 +1,135 @@ +// Package secrets stores and retrieves credentials. +// +// v0.0 ships a file-only Store implementation (0600 perms under +// $XDG_CONFIG_HOME/weknora/secrets/). The OS keyring backend lands in v0.1 +// once auth login is needed in TTY contexts (current PR is foundation only). +// +// Namespace convention: "weknora::" where key is "access" or "refresh". +package secrets + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +// ErrNotFound is returned when the requested secret does not exist. +var ErrNotFound = errors.New("secret: not found") + +// Store is the abstraction CLI commands depend on; tests inject in-memory impls. +// +// Ref returns a stable URI (e.g. file:/// or +// keychain://weknora//) describing where a saved secret lives. +// Backends own their scheme so commands never need to type-assert the +// concrete implementation. +type Store interface { + Get(context, key string) (string, error) + Set(context, key, value string) error + Delete(context, key string) error + Ref(context, key string) string +} + +// FileStore writes 0600 plain-text files under $XDG_CONFIG_HOME/weknora/secrets/. +// It is the headless / CI default and the keychain fallback. Real keychain support +// is wired in v0.1 (see ADR-17 for namespace strategy). +type FileStore struct { + root string +} + +// NewFileStore returns a FileStore rooted at $XDG_CONFIG_HOME/weknora/secrets +// (or ~/.config/weknora/secrets if XDG_CONFIG_HOME is unset). Same convention +// as config.Path — see that file for the rationale (CLI convention). +func NewFileStore() (*FileStore, error) { + root, err := defaultRoot() + if err != nil { + return nil, err + } + return &FileStore{root: root}, nil +} + +func defaultRoot() (string, error) { + if x := os.Getenv("XDG_CONFIG_HOME"); x != "" { + return filepath.Join(x, "weknora", "secrets"), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("locate home dir: %w", err) + } + return filepath.Join(home, ".config", "weknora", "secrets"), nil +} + +func (f *FileStore) path(context, key string) string { + return filepath.Join(f.root, context, key) +} + +func (f *FileStore) Get(context, key string) (string, error) { + data, err := os.ReadFile(f.path(context, key)) + if errors.Is(err, os.ErrNotExist) { + return "", ErrNotFound + } + if err != nil { + return "", fmt.Errorf("read secret: %w", err) + } + return string(data), nil +} + +func (f *FileStore) Set(context, key, value string) error { + dir := filepath.Join(f.root, context) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("mkdir secrets dir: %w", err) + } + if err := os.WriteFile(f.path(context, key), []byte(value), 0o600); err != nil { + return fmt.Errorf("write secret: %w", err) + } + return nil +} + +func (f *FileStore) Delete(context, key string) error { + err := os.Remove(f.path(context, key)) + if errors.Is(err, os.ErrNotExist) { + return nil + } + return err +} + +// Ref returns the file:// URI under which a secret would be stored. Path +// component is forward-slash-normalized per RFC 8089 (file:///path on Unix, +// file:///C:/... on Windows) — the wire format must not depend on platform +// path separator since this string is persisted to config.yaml and may be +// consumed by tooling on a different OS. +func (f *FileStore) Ref(context, key string) string { + p := filepath.ToSlash(f.path(context, key)) + if !strings.HasPrefix(p, "/") { + // Windows absolute path "C:/..." needs a leading slash to form a + // proper file:/// URI ("file:///C:/..."). + p = "/" + p + } + return "file://" + p +} + +// MemStore is an in-memory implementation of Store used by tests across +// packages. It is intentionally exported (not _test.go-only) so that +// downstream packages can compose it without copying the same 20 lines. +type MemStore struct{ m map[string]string } + +// NewMemStore returns an empty in-memory secrets store. +func NewMemStore() *MemStore { return &MemStore{m: map[string]string{}} } + +func (m *MemStore) k(c, key string) string { return c + ":" + key } + +func (m *MemStore) Get(c, key string) (string, error) { + v, ok := m.m[m.k(c, key)] + if !ok { + return "", ErrNotFound + } + return v, nil +} + +func (m *MemStore) Set(c, key, value string) error { m.m[m.k(c, key)] = value; return nil } + +func (m *MemStore) Delete(c, key string) error { delete(m.m, m.k(c, key)); return nil } + +// Ref returns a mem:// URI; meaningful only inside tests. +func (m *MemStore) Ref(c, key string) string { return "mem://" + c + "/" + key } diff --git a/cli/internal/secrets/secrets_test.go b/cli/internal/secrets/secrets_test.go new file mode 100644 index 00000000..21bb94e4 --- /dev/null +++ b/cli/internal/secrets/secrets_test.go @@ -0,0 +1,87 @@ +package secrets + +import ( + "errors" + "os" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/cli/internal/testutil" +) + +func TestFileStore_RoundTrip(t *testing.T) { + testutil.XDGTempDir(t) + s, err := NewFileStore() + require.NoError(t, err) + + _, err = s.Get("prod", "access") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrNotFound)) + + require.NoError(t, s.Set("prod", "access", "secret-value")) + got, err := s.Get("prod", "access") + require.NoError(t, err) + assert.Equal(t, "secret-value", got) + + require.NoError(t, s.Delete("prod", "access")) + _, err = s.Get("prod", "access") + require.True(t, errors.Is(err, ErrNotFound)) + + require.NoError(t, s.Delete("prod", "access"), "Delete on missing must be a no-op") +} + +func TestFileStore_FileMode(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("file mode bits don't map to Windows ACLs; 0600 invariant is Unix-only") + } + testutil.XDGTempDir(t) + s, err := NewFileStore() + require.NoError(t, err) + require.NoError(t, s.Set("prod", "access", "v")) + + st, err := os.Stat(s.path("prod", "access")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), st.Mode().Perm(), "secrets must be 0600") +} + +func TestFileStore_NamespaceIsolation(t *testing.T) { + testutil.XDGTempDir(t) + s, err := NewFileStore() + require.NoError(t, err) + require.NoError(t, s.Set("prod", "access", "P")) + require.NoError(t, s.Set("staging", "access", "S")) + + got, _ := s.Get("prod", "access") + assert.Equal(t, "P", got) + got, _ = s.Get("staging", "access") + assert.Equal(t, "S", got) +} + +func TestFileStore_Ref(t *testing.T) { + testutil.XDGTempDir(t) + s, err := NewFileStore() + require.NoError(t, err) + ref := s.Ref("prod", "access") + // Ref is RFC 8089: scheme + slash-normalized path. On Windows the path + // starts with a drive letter (file:///C:/...); on Unix file:///home/... + assert.True(t, strings.HasPrefix(ref, "file:///"), "expected file:/// scheme, got %q", ref) + assert.Contains(t, ref, "/prod/access") +} + +func TestMemStore_RoundTripAndRef(t *testing.T) { + s := NewMemStore() + _, err := s.Get("p", "k") + require.ErrorIs(t, err, ErrNotFound) + require.NoError(t, s.Set("p", "k", "v")) + got, err := s.Get("p", "k") + require.NoError(t, err) + assert.Equal(t, "v", got) + assert.Equal(t, "mem://p/k", s.Ref("p", "k")) + require.NoError(t, s.Delete("p", "k")) + _, err = s.Get("p", "k") + require.ErrorIs(t, err, ErrNotFound) +} diff --git a/cli/internal/testutil/xdg.go b/cli/internal/testutil/xdg.go new file mode 100644 index 00000000..a702df47 --- /dev/null +++ b/cli/internal/testutil/xdg.go @@ -0,0 +1,20 @@ +// Package testutil holds small test-only helpers shared across cli/internal packages. +// +// Build tag is intentionally absent: Go links _test.go files only into test +// binaries, but other packages need to import this from their tests. Keep +// production code out. +package testutil + +import ( + "testing" +) + +// XDGTempDir creates a fresh temp dir and points XDG_CONFIG_HOME at it for the +// duration of t. Use whenever a test exercises code that reads +// $XDG_CONFIG_HOME/weknora/* (config.Load, secrets.NewFileStore, ...). +func XDGTempDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", dir) + return dir +} diff --git a/cli/main.go b/cli/main.go new file mode 100644 index 00000000..2c4ba756 --- /dev/null +++ b/cli/main.go @@ -0,0 +1,12 @@ +// Command weknora is a CLI for Tencent WeKnora knowledge bases. +package main + +import ( + "os" + + "github.com/Tencent/WeKnora/cli/cmd" +) + +func main() { + os.Exit(cmd.Execute()) +}