feat(cli): agent-first WeKnora CLI
The `weknora` command-line client for the WeKnora RAG server. Full command surface: kb / doc / chunk / session / message / agent / model / search / chat / auth / profile / link / api / mcp / skills / config / doctor / schema / exit-codes. Agent-first wire contract: JSON envelope by default, typed error codes mapped to stable exit codes, error.retry_argv / retryable / partial-failure status, global --dry-run preview, the exit-10 confirmation protocol for writes, and control/ANSI/Bidi input hygiene. Stateless env-credential auth (WEKNORA_API_KEY / WEKNORA_TOKEN + WEKNORA_HOST) for headless/CI/agent use. A curated read-only MCP tool surface (`mcp serve`) and embedded Agent Skills (`skills install`). Extensive unit + contract-golden tests and CI.
This commit is contained in:
@@ -31,6 +31,12 @@ type AgentHelp struct {
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
}
|
||||
|
||||
// agentHelpAnnotation stores the marshaled AgentHelp on the command so the
|
||||
// `weknora schema` command can introspect any command's contract without
|
||||
// invoking its help func (and toggling WEKNORA_AGENT_HELP). Shares the
|
||||
// annotations map with SetRisk (distinct keys).
|
||||
const agentHelpAnnotation = "weknora.agent_help"
|
||||
|
||||
// SetAgentHelp attaches agent-targeted help metadata to a command.
|
||||
//
|
||||
// Routing:
|
||||
@@ -39,7 +45,17 @@ type AgentHelp struct {
|
||||
// - Otherwise (human help path): if cmd has risk annotations from SetRisk,
|
||||
// prepend "Risk: <action> (<level>)" line; then render the normal human
|
||||
// help via origHelp; then append the "AI agents:" Warnings block.
|
||||
//
|
||||
// The AgentHelp is also recorded as a JSON annotation so `weknora schema` can
|
||||
// surface it as a first-class, discoverable command (not only via the
|
||||
// WEKNORA_AGENT_HELP env toggle on --help).
|
||||
func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
|
||||
if b, err := json.Marshal(ah); err == nil {
|
||||
if cmd.Annotations == nil {
|
||||
cmd.Annotations = make(map[string]string)
|
||||
}
|
||||
cmd.Annotations[agentHelpAnnotation] = string(b)
|
||||
}
|
||||
origHelp := cmd.HelpFunc()
|
||||
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
|
||||
if os.Getenv("WEKNORA_AGENT_HELP") == "1" {
|
||||
@@ -64,6 +80,22 @@ func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
|
||||
})
|
||||
}
|
||||
|
||||
// AgentHelpFor returns the AgentHelp registered on cmd via SetAgentHelp.
|
||||
// ok is false when the command carries none (e.g. cobra-generated subtrees).
|
||||
func AgentHelpFor(cmd *cobra.Command) (ah AgentHelp, ok bool) {
|
||||
if cmd.Annotations == nil {
|
||||
return ah, false
|
||||
}
|
||||
raw, present := cmd.Annotations[agentHelpAnnotation]
|
||||
if !present {
|
||||
return ah, false
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &ah); err != nil {
|
||||
return ah, false
|
||||
}
|
||||
return ah, true
|
||||
}
|
||||
|
||||
func emitAgentHelp(w io.Writer, ah AgentHelp) {
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
|
||||
@@ -70,6 +70,39 @@ func TestRunBatch_PartialFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunBatch_StatusExitTriState verifies the batch tri-state exit mapping:
|
||||
// all-success → exit 0 (nil summaryErr), partial → exit 1, all-fail → exit 1
|
||||
// (operation.failed fall-through). Pairs with the envelope-status tri-state in
|
||||
// output.TestWriteBatchEnvelope_StatusTriState.
|
||||
func TestRunBatch_StatusExitTriState(t *testing.T) {
|
||||
failIf := func(fails map[string]bool) func(context.Context, string) error {
|
||||
return func(_ context.Context, id string) error {
|
||||
if fails[id] {
|
||||
return errors.New("boom")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
ids []string
|
||||
fails map[string]bool
|
||||
wantExit int
|
||||
}{
|
||||
{"all_success", []string{"a", "b"}, nil, 0},
|
||||
{"partial", []string{"a", "b"}, map[string]bool{"b": true}, 1},
|
||||
{"all_fail", []string{"a", "b"}, map[string]bool{"a": true, "b": true}, 1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, summaryErr := RunBatch(context.Background(), tc.ids, failIf(tc.fails))
|
||||
if got := ExitCode(summaryErr); got != tc.wantExit {
|
||||
t.Errorf("ExitCode = %d, want %d (summaryErr=%v)", got, tc.wantExit, summaryErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunBatch_ContextCancellation verifies that once the context is cancelled,
|
||||
// remaining ids are marked with the context error without calling op.
|
||||
func TestRunBatch_ContextCancellation(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// unsafeRune reports whether r is a control / formatting character that has no
|
||||
// place in a CLI-supplied value: C0 control codes (except the ordinary
|
||||
// whitespace \t \n \r), DEL, Unicode Bidi overrides/isolates, and zero-width
|
||||
// characters.
|
||||
//
|
||||
// These are rejected because CLI arguments are untrusted — in an agent-first
|
||||
// CLI they frequently originate from an AI agent or upstream content. A
|
||||
// smuggled ANSI escape (ESC, U+001B) or Bidi override stored in a resource
|
||||
// name would execute in, or visually mislead, a human's terminal the moment
|
||||
// the value is rendered by a later `list` / `view`. Blocking at the input
|
||||
// boundary mirrors the input-hygiene stance of other agent-first CLIs.
|
||||
func unsafeRune(r rune) bool {
|
||||
switch {
|
||||
case r == '\t' || r == '\n' || r == '\r':
|
||||
return false // ordinary whitespace is allowed (multi-line --text etc.)
|
||||
case r < 0x20 || r == 0x7f:
|
||||
return true // C0 controls (includes ESC U+001B) and DEL
|
||||
case r >= 0x202a && r <= 0x202e:
|
||||
return true // LRE RLE PDF LRO RLO — Bidi overrides
|
||||
case r >= 0x2066 && r <= 0x2069:
|
||||
return true // LRI RLI FSI PDI — Bidi isolates
|
||||
case r == 0x200b || r == 0x200c || r == 0x200d || r == 0xfeff:
|
||||
return true // zero-width space / non-joiner / joiner / BOM
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CheckSafeText returns an input.invalid_argument error if value contains a
|
||||
// control / Bidi / zero-width character (see unsafeRune). label names the
|
||||
// offending input so an agent can fix the right argument. Returns nil for
|
||||
// ordinary text (including multi-line content with \t \n \r).
|
||||
func CheckSafeText(value, label string) error {
|
||||
for i, r := range value {
|
||||
if unsafeRune(r) {
|
||||
return &Error{
|
||||
Code: CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf(
|
||||
"%s contains a disallowed control character (U+%04X at byte %d); strip control / ANSI-escape / Bidi / zero-width characters",
|
||||
label, r, i,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckSafeArgs is the command-boundary input gate, hooked into the root
|
||||
// PersistentPreRunE so every command inherits it without per-command wiring.
|
||||
// It enforces two independent rules, each in its own helper so the rule is
|
||||
// discoverable:
|
||||
//
|
||||
// - checkNonEmptyArgs: every positional argument must be non-empty.
|
||||
// - CheckSafeText: no positional argument or explicitly-set flag value may
|
||||
// carry control / ANSI / Bidi / zero-width characters.
|
||||
//
|
||||
// Default (unchanged) flag values are not scanned — only what the caller
|
||||
// actually supplied.
|
||||
func CheckSafeArgs(args []string, flags *pflag.FlagSet) error {
|
||||
if err := checkNonEmptyArgs(args); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, a := range args {
|
||||
if err := CheckSafeText(a, fmt.Sprintf("argument %d", i+1)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if flags == nil {
|
||||
return nil
|
||||
}
|
||||
var ferr error
|
||||
flags.Visit(func(f *pflag.Flag) {
|
||||
if ferr == nil {
|
||||
ferr = CheckSafeText(f.Value.String(), "--"+f.Name)
|
||||
}
|
||||
})
|
||||
return ferr
|
||||
}
|
||||
|
||||
// checkNonEmptyArgs rejects empty / whitespace-only positional arguments before
|
||||
// any command logic runs — including the dry-run and exit-10 confirmation gates.
|
||||
// Every positional in this CLI is an id, name, query, or path; none is
|
||||
// meaningfully empty. The common agent trigger is capturing an id from a failed
|
||||
// prior step (KB=$(weknora kb create … --jq .data.id) when the create failed →
|
||||
// ""), which otherwise reaches the server as an empty path segment: GET/DELETE
|
||||
// /resource/ falls through to the LIST route, the array response fails to
|
||||
// unmarshal into a single-object struct, and the failure is mis-reported as
|
||||
// network.error ("check base URL"). Worse, an empty-id delete reaches the
|
||||
// confirmation gate with a malformed `weknora kb delete -y` retry_argv.
|
||||
// Caught here as a clear input.invalid_argument (exit 5) instead.
|
||||
//
|
||||
// This is intentionally a global invariant (no command exempts itself); flag
|
||||
// VALUES are not covered, so `--description ""` still legitimately clears a field.
|
||||
func checkNonEmptyArgs(args []string) error {
|
||||
for i, a := range args {
|
||||
if strings.TrimSpace(a) == "" {
|
||||
return &Error{
|
||||
Code: CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("argument %d is empty", i+1),
|
||||
Hint: "an empty id / name / query is never valid — verify the value you captured (e.g. from a prior --jq) is non-empty",
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func TestCheckSafeText(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
value string
|
||||
wantErr bool
|
||||
}{
|
||||
{"plain ascii", "my-knowledge-base", false},
|
||||
{"unicode letters", "测试知识库 café", false},
|
||||
{"emoji", "docs 🔥", false},
|
||||
{"multiline content allowed", "line1\nline2\twith tab\r\n", false},
|
||||
{"ansi escape rejected", "inject\x1b[31mRED", true},
|
||||
{"bell rejected", "name\x07bell", true},
|
||||
{"null byte rejected", "a\x00b", true},
|
||||
{"DEL rejected", "a\x7fb", true},
|
||||
{"bidi override rejected", "abc\u202ervd", true},
|
||||
{"zero-width rejected", "ab\u200bc", true},
|
||||
{"BOM rejected", "\ufeffname", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := CheckSafeText(tc.value, "name")
|
||||
if tc.wantErr && err == nil {
|
||||
t.Errorf("expected rejection for %q, got nil", tc.value)
|
||||
}
|
||||
if !tc.wantErr && err != nil {
|
||||
t.Errorf("expected %q to be allowed, got %v", tc.value, err)
|
||||
}
|
||||
if tc.wantErr {
|
||||
var typed *Error
|
||||
if !errors.As(err, &typed) || typed.Code != CodeInputInvalidArgument {
|
||||
t.Errorf("want *Error with CodeInputInvalidArgument, got %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckSafeArgs_PositionalAndFlags(t *testing.T) {
|
||||
fs := pflag.NewFlagSet("t", pflag.ContinueOnError)
|
||||
name := fs.String("name", "", "")
|
||||
_ = fs.Parse([]string{"--name", "clean-name"})
|
||||
|
||||
// Clean positional + clean flag → ok.
|
||||
if err := CheckSafeArgs([]string{"good-arg"}, fs); err != nil {
|
||||
t.Errorf("clean args should pass, got %v", err)
|
||||
}
|
||||
|
||||
// Dirty positional arg → rejected, names the argument.
|
||||
if err := CheckSafeArgs([]string{"bad\x1b[0marg"}, fs); err == nil {
|
||||
t.Error("control char in positional arg must be rejected")
|
||||
}
|
||||
|
||||
// Dirty flag value → rejected.
|
||||
*name = "x" // touch to avoid unused
|
||||
fs2 := pflag.NewFlagSet("t2", pflag.ContinueOnError)
|
||||
fs2.String("title", "", "")
|
||||
_ = fs2.Parse([]string{"--title", "evil\x07"})
|
||||
if err := CheckSafeArgs(nil, fs2); err == nil {
|
||||
t.Error("control char in flag value must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckSafeArgs_RejectsEmptyPositional pins that empty / whitespace-only
|
||||
// positional args are rejected as input.invalid_argument before any command
|
||||
// logic — the common agent failure of capturing an id from a failed prior step
|
||||
// (KB=$(... --jq .data.id) → "") must surface clearly, not reach the server as
|
||||
// an empty path segment (mis-classified network.error) or a malformed
|
||||
// `delete -y` confirmation. Empty FLAG values stay allowed (--description ""
|
||||
// legitimately clears a field).
|
||||
func TestCheckSafeArgs_RejectsEmptyPositional(t *testing.T) {
|
||||
for _, arg := range []string{"", " ", "\t", "\n"} {
|
||||
err := CheckSafeArgs([]string{arg}, nil)
|
||||
var ce *Error
|
||||
if !errors.As(err, &ce) || ce.Code != CodeInputInvalidArgument {
|
||||
t.Errorf("empty positional %q must be rejected as input.invalid_argument, got %v", arg, err)
|
||||
}
|
||||
}
|
||||
// A non-empty positional alongside an empty one still trips on the empty.
|
||||
if err := CheckSafeArgs([]string{"ok", ""}, nil); err == nil {
|
||||
t.Error("a later empty positional must be rejected")
|
||||
}
|
||||
// Empty flag value is NOT rejected (clearing a field is valid).
|
||||
fs := pflag.NewFlagSet("t", pflag.ContinueOnError)
|
||||
fs.String("description", "", "")
|
||||
_ = fs.Parse([]string{"--description", ""})
|
||||
if err := CheckSafeArgs([]string{"id1"}, fs); err != nil {
|
||||
t.Errorf("empty flag value must stay allowed, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckSafeArgs_UnchangedFlagsNotScanned pins that default (unset) flag
|
||||
// values are not scanned — only what the caller supplied.
|
||||
func TestCheckSafeArgs_UnchangedFlagsNotScanned(t *testing.T) {
|
||||
fs := pflag.NewFlagSet("t", pflag.ContinueOnError)
|
||||
// A default that (hypothetically) contains a control char must not trip
|
||||
// the check when the user never set the flag.
|
||||
fs.String("weird", "default\x1bvalue", "")
|
||||
_ = fs.Parse(nil)
|
||||
if err := CheckSafeArgs(nil, fs); err != nil {
|
||||
t.Errorf("unset flag default must not be scanned, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,33 @@ import (
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
)
|
||||
|
||||
// BuildRetryArgv assembles the directly-executable retry argv for a
|
||||
// confirmation-gated command: head (e.g. []string{"weknora","kb","update",id})
|
||||
// followed by each *changed* flag named in allow (as "--name", "value") in
|
||||
// pflag's visit order, plus a trailing "-y". Flags not in allow — multi-value
|
||||
// or file-based ones where a precise single argv is impractical — are skipped;
|
||||
// the human reconstructs those. Replaces the per-command build*RetryCmd helpers.
|
||||
func BuildRetryArgv(c *cobra.Command, head []string, allow ...string) []string {
|
||||
allowed := make(map[string]struct{}, len(allow))
|
||||
for _, a := range allow {
|
||||
allowed[a] = struct{}{}
|
||||
}
|
||||
parts := append([]string{}, head...)
|
||||
c.Flags().Visit(func(f *pflag.Flag) {
|
||||
if _, ok := allowed[f.Name]; ok {
|
||||
parts = append(parts, "--"+f.Name, f.Value.String())
|
||||
}
|
||||
})
|
||||
return append(parts, "-y")
|
||||
}
|
||||
|
||||
// confirmCaveat returns the trailing safety note shown after the interactive
|
||||
// prompt, tailored to the verb. Deletes/removals are irreversible; edits
|
||||
// overwrite prior values but are recoverable if you know the old value.
|
||||
@@ -38,9 +61,10 @@ func titleFirst(s string) string {
|
||||
//
|
||||
// Pass n = total count of items about to be deleted.
|
||||
// action is the namespaced action verb (e.g. "doc.delete") for the risk envelope.
|
||||
// retryCmd is the directly-executable retry argv (e.g. "weknora doc delete a b -y");
|
||||
// pass "" when no clean retry argv is available.
|
||||
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, verb, what string, n int, action, retryCmd string) error {
|
||||
// retryArgv is the directly-executable retry argv array
|
||||
// (e.g. []string{"weknora","doc","delete","a","b","-y"}); pass nil when no
|
||||
// clean retry argv is available.
|
||||
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, verb, what string, n int, action string, retryArgv []string) error {
|
||||
if yes {
|
||||
return nil
|
||||
}
|
||||
@@ -49,7 +73,7 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, verb, what st
|
||||
CodeInputConfirmationRequired,
|
||||
fmt.Sprintf("%s %d %s(s) requires explicit confirmation: re-run with -y/--yes", verb, n, what),
|
||||
).
|
||||
WithRetryCommand(retryCmd).
|
||||
WithRetryArgv(retryArgv).
|
||||
WithRisk("destructive", action)
|
||||
}
|
||||
ok, err := p.Confirm(fmt.Sprintf("%s %d %s(s)? %s", titleFirst(verb), n, what, confirmCaveat(verb)), false)
|
||||
@@ -81,9 +105,33 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, verb, what st
|
||||
//
|
||||
// `yes` should be sourced from the persistent global -y/--yes flag.
|
||||
// action is the namespaced action verb (e.g. "kb.delete") for the risk envelope.
|
||||
// retryCmd is the directly-executable retry argv (e.g. "weknora kb delete kb_x -y");
|
||||
// pass "" when no clean retry argv is available.
|
||||
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, verb, what, id, action, retryCmd string) error {
|
||||
// retryArgv is the directly-executable retry argv array
|
||||
// (e.g. []string{"weknora","kb","delete","kb_x","-y"}); pass nil when no
|
||||
// clean retry argv is available.
|
||||
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, verb, what, id, action string, retryArgv []string) error {
|
||||
return confirmGated(p, yes, jsonOut, verb, what, id, action, RiskDestructive, retryArgv)
|
||||
}
|
||||
|
||||
// ConfirmWrite guards a reversible metadata write (kb / agent / doc update).
|
||||
// Same confirmation gate as ConfirmDestructive — a labeling-accuracy variant,
|
||||
// NOT a weaker gate — but tags the risk envelope at the "write" level so an
|
||||
// agent can distinguish a recoverable edit from an irreversible delete.
|
||||
func ConfirmWrite(p prompt.Prompter, yes, jsonOut bool, verb, what, id, action string, retryArgv []string) error {
|
||||
return confirmGated(p, yes, jsonOut, verb, what, id, action, RiskWrite, retryArgv)
|
||||
}
|
||||
|
||||
// confirmGated is the shared single-resource confirmation gate behind
|
||||
// ConfirmDestructive / ConfirmWrite. `level` is the risk.level reported on the
|
||||
// exit-10 envelope (RiskDestructive for irreversible ops, RiskWrite for
|
||||
// recoverable edits). Behavior matrix:
|
||||
//
|
||||
// yes=true → proceed (explicit user opt-in via -y/--yes)
|
||||
// non-TTY OR jsonOut → CodeInputConfirmationRequired (exit 10) + risk{level,action};
|
||||
// no UI to prompt, agent/CI must re-invoke with -y after
|
||||
// the human explicitly approves
|
||||
// TTY + interactive → prompt; user-yes proceeds, user-no returns CodeUserAborted
|
||||
// prompter error → CodeInputMissingFlag (rare; stdin closed mid-prompt)
|
||||
func confirmGated(p prompt.Prompter, yes, jsonOut bool, verb, what, id, action, level string, retryArgv []string) error {
|
||||
if yes {
|
||||
return nil
|
||||
}
|
||||
@@ -92,16 +140,16 @@ func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, verb, what, id, ac
|
||||
CodeInputConfirmationRequired,
|
||||
fmt.Sprintf("%s %s %s requires explicit confirmation: re-run with -y/--yes", verb, what, id),
|
||||
).
|
||||
WithRetryCommand(retryCmd).
|
||||
WithRisk("destructive", action)
|
||||
WithRetryArgv(retryArgv).
|
||||
WithRisk(level, action)
|
||||
}
|
||||
ok, err := p.Confirm(fmt.Sprintf("%s %s %s? %s", titleFirst(verb), what, id, confirmCaveat(verb)), false)
|
||||
if err != nil {
|
||||
return Wrapf(CodeInputMissingFlag, err, "confirm delete")
|
||||
return Wrapf(CodeInputMissingFlag, err, "confirm %s", verb)
|
||||
}
|
||||
if !ok {
|
||||
fmt.Fprintln(iostreams.IO.Err, "Aborted.")
|
||||
return NewError(CodeUserAborted, "delete aborted")
|
||||
return NewError(CodeUserAborted, fmt.Sprintf("%s aborted", verb))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
// The confirmation message verb must match the actual operation: an `edit`
|
||||
// must not be described as `delete`. Regression for the hardcoded-"delete"
|
||||
// confirmation message that mislabeled kb/agent edits.
|
||||
// confirmation message that mislabeled kb/agent updates.
|
||||
func TestConfirmDestructive_VerbMatchesOperation(t *testing.T) {
|
||||
iostreams.SetForTest(t) // non-TTY buffers ⇒ the jsonOut/non-TTY branch
|
||||
|
||||
@@ -25,7 +25,7 @@ func TestConfirmDestructive_VerbMatchesOperation(t *testing.T) {
|
||||
{"remove", "current profile", "prod", "remove current profile prod requires", "delete"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
err := cmdutil.ConfirmDestructive(&testutil.ConfirmPrompter{}, false, true, tc.verb, tc.what, tc.id, tc.what+"."+tc.verb, "")
|
||||
err := cmdutil.ConfirmDestructive(&testutil.ConfirmPrompter{}, false, true, tc.verb, tc.what, tc.id, tc.what+"."+tc.verb, nil)
|
||||
if err == nil {
|
||||
t.Fatalf("verb %q: expected confirmation_required error", tc.verb)
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func TestConfirmDestructive_VerbMatchesOperation(t *testing.T) {
|
||||
// The batch flavor must likewise honor the verb.
|
||||
func TestConfirmDestructiveBatch_VerbMatchesOperation(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, true, "delete", "document", 3, "doc.delete", "")
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, true, "delete", "document", 3, "doc.delete", nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected confirmation_required error")
|
||||
}
|
||||
|
||||
@@ -43,8 +43,8 @@ func AddDryRunFlag(cmd *cobra.Command, dest *bool) {
|
||||
}
|
||||
|
||||
// EmitDryRun writes the dry-run envelope to w via FormatOptions.Emit, so the
|
||||
// envelope inherits the standard _notice injection, TTY indent, --jq filter,
|
||||
// and profile fields like every other success envelope. fopts may be nil for
|
||||
// envelope inherits the standard TTY indent, --jq filter, and profile fields
|
||||
// like every other success envelope. fopts may be nil for
|
||||
// callers that have no resolved FormatOptions (tests, error paths); a JSON-mode
|
||||
// default is used in that case.
|
||||
//
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
func TestAddDryRunFlag_RegistersFlag(t *testing.T) {
|
||||
@@ -78,27 +77,6 @@ func TestEmitDryRun_ApiPlanShape(t *testing.T) {
|
||||
assert.Equal(t, "foo", body["name"])
|
||||
}
|
||||
|
||||
func TestEmitDryRun_InjectsNotice(t *testing.T) {
|
||||
// Regression: dry-run envelope must carry the same _notice channel as
|
||||
// every other success envelope. PendingNotice is the system-level hook
|
||||
// used for deprecation / version_skew / security signals.
|
||||
output.PendingNotice = func() map[string]any {
|
||||
return map[string]any{"deprecation": "use weknora kb create-v2"}
|
||||
}
|
||||
t.Cleanup(func() { output.PendingNotice = nil })
|
||||
|
||||
var buf bytes.Buffer
|
||||
err := EmitDryRun(&buf, &FormatOptions{Mode: FormatJSON},
|
||||
DryRunPlan{Action: "kb.create", Args: map[string]any{"name": "x"}})
|
||||
require.NoError(t, err)
|
||||
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
notice, ok := got["_notice"].(map[string]any)
|
||||
require.True(t, ok, "expected _notice field on dry-run envelope; got %v", got)
|
||||
assert.Equal(t, "use weknora kb create-v2", notice["deprecation"])
|
||||
}
|
||||
|
||||
func TestEmitDryRun_HonorsTTYIndent(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
err := EmitDryRun(&buf, &FormatOptions{Mode: FormatJSON, TTY: true},
|
||||
|
||||
@@ -77,6 +77,13 @@ const (
|
||||
// contexts so the user-visible exit follows Unix signal convention.
|
||||
CodeOperationCancelled ErrorCode = "operation.cancelled"
|
||||
|
||||
// CodeInternalError is the catch-all for an error that reached the top
|
||||
// without a typed code (a bug, or an unmapped dependency error). Maps to
|
||||
// exit 1 via the fall-through bucket. Documented so the type is never a
|
||||
// surprise on the wire; a recurring internal.error is a classification gap
|
||||
// worth fixing at the source.
|
||||
CodeInternalError ErrorCode = "internal.error"
|
||||
|
||||
// local.* - config / file / keychain on the user's machine
|
||||
CodeLocalConfigCorrupt ErrorCode = "local.config_corrupt"
|
||||
CodeLocalKeychainDenied ErrorCode = "local.keychain_denied"
|
||||
@@ -117,8 +124,8 @@ type Error struct {
|
||||
// own output (e.g. bulk operations reporting partial-success data on
|
||||
// stdout) but still need to surface a non-zero exit code.
|
||||
Silent bool
|
||||
RetryCommand string // Directly-executable argv, distinct from prose Hint
|
||||
RetryAfterSeconds int // HTTP Retry-After header semantics (transport-level retry hint)
|
||||
RetryArgv []string // Directly-executable argv array, distinct from prose Hint
|
||||
RetryAfterSeconds int // HTTP Retry-After header semantics (transport-level retry hint)
|
||||
Detail any // Structured detail for envelope.error.detail (e.g. unknown-subcommand available[])
|
||||
Risk *RiskInfo
|
||||
}
|
||||
@@ -148,11 +155,11 @@ func (e *Error) WithHint(hint string) *Error {
|
||||
return e
|
||||
}
|
||||
|
||||
// WithRetryCommand sets the directly-executable retry argv string so agents
|
||||
// don't have to regex-extract argv from the prose Hint.
|
||||
// Empty string for codes without a canonical retry command.
|
||||
func (e *Error) WithRetryCommand(cmd string) *Error {
|
||||
e.RetryCommand = cmd
|
||||
// WithRetryArgv sets the directly-executable retry argv array so agents can
|
||||
// exec it directly instead of regex-extracting argv from the prose Hint.
|
||||
// Empty for codes without a canonical retry command.
|
||||
func (e *Error) WithRetryArgv(argv []string) *Error {
|
||||
e.RetryArgv = argv
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -194,8 +201,8 @@ func AsError(err error) *Error {
|
||||
|
||||
// ErrorToDetail converts a typed cmdutil.Error (or fallback) into
|
||||
// output.ErrDetail for embedding in success-envelope batch items or
|
||||
// MCP CallToolResult StructuredContent. Hint / RetryCommand fall back
|
||||
// to defaultHint / defaultRetryCommand when typed value is empty.
|
||||
// MCP CallToolResult StructuredContent. Hint / RetryArgv fall back
|
||||
// to defaultHint / defaultRetryArgv when typed value is empty.
|
||||
// Returns nil when err is nil.
|
||||
func ErrorToDetail(err error) *output.ErrDetail {
|
||||
if err == nil {
|
||||
@@ -206,9 +213,9 @@ func ErrorToDetail(err error) *output.ErrDetail {
|
||||
if hint == "" {
|
||||
hint = defaultHint(typed.Code)
|
||||
}
|
||||
retry := typed.RetryCommand
|
||||
if retry == "" {
|
||||
retry = defaultRetryCommand(typed.Code)
|
||||
retry := typed.RetryArgv
|
||||
if len(retry) == 0 {
|
||||
retry = defaultRetryArgv(typed.Code)
|
||||
}
|
||||
// Build message without the code prefix — the envelope's separate
|
||||
// "type" field already carries the code, so repeating it in "message"
|
||||
@@ -222,7 +229,7 @@ func ErrorToDetail(err error) *output.ErrDetail {
|
||||
Type: string(typed.Code),
|
||||
Message: msg,
|
||||
Hint: hint,
|
||||
RetryCommand: retry,
|
||||
RetryArgv: retry,
|
||||
RetryAfterSeconds: typed.RetryAfterSeconds,
|
||||
Detail: typed.Detail,
|
||||
}
|
||||
@@ -439,6 +446,8 @@ func AllCodes() []ErrorCode {
|
||||
CodeSSEStreamAborted, CodeSessionCreateFailed,
|
||||
// operation
|
||||
CodeOperationTimeout, CodeOperationFailed, CodeOperationCancelled,
|
||||
// internal catch-all
|
||||
CodeInternalError,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -10,22 +11,22 @@ func TestErrorToDetail_NilSafe(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestError_WithRetryCommand(t *testing.T) {
|
||||
func TestError_WithRetryArgv(t *testing.T) {
|
||||
err := NewError(CodeAuthUnauthenticated, "session expired").
|
||||
WithHint("run `weknora auth login`").
|
||||
WithRetryCommand("weknora auth login")
|
||||
WithRetryArgv([]string{"weknora", "auth", "login"})
|
||||
|
||||
if err.RetryCommand != "weknora auth login" {
|
||||
t.Errorf("RetryCommand not set; got %q", err.RetryCommand)
|
||||
if !reflect.DeepEqual(err.RetryArgv, []string{"weknora", "auth", "login"}) {
|
||||
t.Errorf("RetryArgv not set; got %v", err.RetryArgv)
|
||||
}
|
||||
if err.Hint != "run `weknora auth login`" {
|
||||
t.Errorf("Hint changed unexpectedly; got %q", err.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestError_RetryCommand_EmptyByDefault(t *testing.T) {
|
||||
func TestError_RetryArgv_EmptyByDefault(t *testing.T) {
|
||||
err := NewError(CodeResourceAlreadyExists, "kb name exists")
|
||||
if err.RetryCommand != "" {
|
||||
t.Errorf("RetryCommand should default empty; got %q", err.RetryCommand)
|
||||
if len(err.RetryArgv) != 0 {
|
||||
t.Errorf("RetryArgv should default empty; got %v", err.RetryArgv)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
@@ -93,7 +94,7 @@ func ExitCode(err error) int {
|
||||
|
||||
// PrintError writes err to w (typically stderr) in dual mode:
|
||||
// - text: code: msg\nhint: ...\nretry: ...
|
||||
// - json/ndjson: {ok:false, error:{...}, _notice?:...}
|
||||
// - json/ndjson: {ok:false, error:{...}}
|
||||
//
|
||||
// Mode is read from globalFormatMode (set by root PersistentPreRunE).
|
||||
func PrintError(w io.Writer, err error) {
|
||||
@@ -126,12 +127,12 @@ func printErrorProse(w io.Writer, err error) {
|
||||
if hint != "" {
|
||||
fmt.Fprintf(w, "hint: %s\n", hint)
|
||||
}
|
||||
retry := typed.RetryCommand
|
||||
if retry == "" {
|
||||
retry = defaultRetryCommand(typed.Code)
|
||||
retry := typed.RetryArgv
|
||||
if len(retry) == 0 {
|
||||
retry = defaultRetryArgv(typed.Code)
|
||||
}
|
||||
if retry != "" {
|
||||
fmt.Fprintf(w, "retry: %s\n", retry)
|
||||
if len(retry) > 0 {
|
||||
fmt.Fprintf(w, "retry: %s\n", strings.Join(retry, " "))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -198,30 +199,58 @@ func defaultHint(code ErrorCode) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// defaultRetryCommand returns canonical retry argv for known codes.
|
||||
// Empty string for codes without a stable canonical retry.
|
||||
// defaultRetryArgv returns canonical retry argv for known codes.
|
||||
// nil for codes without a stable canonical retry.
|
||||
// Symmetric counterpart to defaultHint.
|
||||
func defaultRetryCommand(code ErrorCode) string {
|
||||
func defaultRetryArgv(code ErrorCode) []string {
|
||||
switch code {
|
||||
case CodeAuthUnauthenticated, CodeAuthBadCredential, CodeAuthTokenExpired:
|
||||
return "weknora auth login"
|
||||
return []string{"weknora", "auth", "login"}
|
||||
case CodeKBIDRequired:
|
||||
return "weknora link"
|
||||
return []string{"weknora", "link"}
|
||||
case CodeNetworkError, CodeServerTimeout:
|
||||
return "weknora doctor"
|
||||
return []string{"weknora", "doctor"}
|
||||
case CodeProjectLinkCorrupt:
|
||||
return "weknora link" // re-bind the project to a KB
|
||||
return []string{"weknora", "link"} // re-bind the project to a KB
|
||||
case CodeLocalConfigCorrupt:
|
||||
// Recovery is two steps (delete config + re-login); the prose hint
|
||||
// already spells it out, so the retry argv stays empty.
|
||||
return ""
|
||||
// already spells it out, so the retry argv stays nil.
|
||||
return nil
|
||||
}
|
||||
return ""
|
||||
return nil
|
||||
}
|
||||
|
||||
// DefaultHint and DefaultRetryCommand are exported wrappers so that
|
||||
// cross-package callers (MCP handlers, batch envelope helpers) can
|
||||
// resolve hint/retry without duplicating the typed-code → string table.
|
||||
// Avoids drift between cmdutil and copies elsewhere.
|
||||
func DefaultHint(code ErrorCode) string { return defaultHint(code) }
|
||||
func DefaultRetryCommand(code ErrorCode) string { return defaultRetryCommand(code) }
|
||||
// boolPtr returns a pointer to b. Used by retryableForCode so the *bool can
|
||||
// distinguish true / false / unknown(nil) on the wire.
|
||||
func boolPtr(b bool) *bool { return &b }
|
||||
|
||||
// retryableForCode classifies whether re-running the SAME command may succeed.
|
||||
// Pointer-to-true for transient failures, pointer-to-false for deterministic
|
||||
// ones, nil (omitted) when genuinely unknown — notably CodeInternalError and
|
||||
// any unlisted code (do NOT default to false).
|
||||
func retryableForCode(code ErrorCode) *bool {
|
||||
switch code {
|
||||
// Transient — retrying the same command may succeed.
|
||||
case CodeServerRateLimited, CodeServerTimeout, CodeNetworkError,
|
||||
CodeOperationTimeout, CodeSSEStreamAborted:
|
||||
return boolPtr(true)
|
||||
// CodeServerError (generic 500) is deliberately NOT here: a 500 may be a
|
||||
// transient server hiccup OR a deterministic server-side bug / mislabeled
|
||||
// bad request, so blindly retrying risks a loop. Left unlisted → nil
|
||||
// (unknown), so the agent decides rather than reading an optimistic true.
|
||||
// Deterministic — same command will fail the same way.
|
||||
case CodeAuthUnauthenticated, CodeAuthTokenExpired, CodeAuthBadCredential,
|
||||
CodeAuthForbidden, CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch,
|
||||
CodeInputInvalidArgument, CodeInputMissingFlag,
|
||||
CodeInputConfirmationRequired, CodeInputUnknownSubcommand,
|
||||
CodeResourceNotFound, CodeResourceAlreadyExists, CodeResourceLocked,
|
||||
CodeOperationFailed, CodeOperationCancelled, CodeUserAborted,
|
||||
CodeUploadFileNotFound, CodeKBIDRequired, CodeKBNotFound,
|
||||
CodeProjectLinkCorrupt, CodeLocalConfigCorrupt, CodeLocalKeychainDenied,
|
||||
CodeLocalFileIO, CodeLocalProfileNotFound, CodeSessionCreateFailed,
|
||||
CodeServerIncompatibleVersion:
|
||||
return boolPtr(false)
|
||||
}
|
||||
// CodeInternalError and any unlisted code: genuinely unknown → omit.
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ func TestPrintError_JSONMode_WritesEnvelope(t *testing.T) {
|
||||
|
||||
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
|
||||
WithHint("re-run with -y/--yes").
|
||||
WithRetryCommand("weknora kb delete kb_x -y")
|
||||
WithRetryArgv([]string{"weknora", "kb", "delete", "kb_x", "-y"})
|
||||
|
||||
var buf bytes.Buffer
|
||||
PrintError(&buf, err)
|
||||
@@ -78,8 +78,8 @@ func TestPrintError_JSONMode_WritesEnvelope(t *testing.T) {
|
||||
if !strings.Contains(got, `"type":"input.confirmation_required"`) {
|
||||
t.Errorf("expected typed code; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"retry_command":"weknora kb delete kb_x -y"`) {
|
||||
t.Errorf("expected retry_command; got %q", got)
|
||||
if !strings.Contains(got, `"retry_argv":["weknora","kb","delete","kb_x","-y"]`) {
|
||||
t.Errorf("expected retry_argv; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ func TestPrintError_TextMode_WritesProse(t *testing.T) {
|
||||
|
||||
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
|
||||
WithHint("re-run with -y/--yes").
|
||||
WithRetryCommand("weknora kb delete kb_x -y")
|
||||
WithRetryArgv([]string{"weknora", "kb", "delete", "kb_x", "-y"})
|
||||
|
||||
var buf bytes.Buffer
|
||||
PrintError(&buf, err)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -113,6 +114,13 @@ func New() *Factory {
|
||||
// credentials are available so the user gets the right hint to run
|
||||
// `weknora auth login`.
|
||||
func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
// Env-credential injection: WEKNORA_TOKEN (bearer) or WEKNORA_API_KEY, with
|
||||
// WEKNORA_HOST (or the active profile's host), builds an ephemeral client
|
||||
// that bypasses config.yaml + the keyring — the stateless headless / CI /
|
||||
// agent path (no disk writes, no `auth login`).
|
||||
if c, handled, err := buildClientFromEnv(f); handled {
|
||||
return c, err
|
||||
}
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -130,7 +138,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
return nil, NewError(CodeInputInvalidArgument,
|
||||
fmt.Sprintf("profile %q not configured", profileName)).
|
||||
WithHint("list available profiles with `weknora profile list`").
|
||||
WithRetryCommand("weknora profile list")
|
||||
WithRetryArgv([]string{"weknora", "profile", "list"})
|
||||
}
|
||||
// ProfileOverride is empty: config.CurrentProfile points at a missing entry.
|
||||
// That's a genuinely corrupt config file.
|
||||
@@ -187,6 +195,58 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
return sdk.NewClient(prof.Host, opts...), nil
|
||||
}
|
||||
|
||||
// EnvCredential reports whether stateless env credentials are in effect and
|
||||
// which kind. Used by `auth status` / `config view` so their host / profile
|
||||
// output reflects that the env credential (and WEKNORA_HOST) — not the config
|
||||
// profile — is what actually authenticated the client. Mirrors buildClientFromEnv's
|
||||
// precedence (WEKNORA_TOKEN wins over WEKNORA_API_KEY).
|
||||
func EnvCredential() (active bool, kind string) {
|
||||
if strings.TrimSpace(os.Getenv("WEKNORA_TOKEN")) != "" {
|
||||
return true, "WEKNORA_TOKEN"
|
||||
}
|
||||
if strings.TrimSpace(os.Getenv("WEKNORA_API_KEY")) != "" {
|
||||
return true, "WEKNORA_API_KEY"
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// buildClientFromEnv builds an ephemeral SDK client from WEKNORA_TOKEN (bearer
|
||||
// JWT) or WEKNORA_API_KEY when either is set, bypassing config.yaml + the
|
||||
// keyring entirely — the stateless path for headless / CI / agent use. Returns
|
||||
// handled=false (fall through to the profile path) when neither var is set.
|
||||
//
|
||||
// Host resolution: WEKNORA_HOST, else the active profile's host (so env creds
|
||||
// can target an already-configured host without re-specifying it). When a token
|
||||
// is supplied, no 401→refresh transport is attached — env creds are ephemeral,
|
||||
// so a 401 propagates for the caller to supply a fresh token. WEKNORA_TOKEN
|
||||
// wins over WEKNORA_API_KEY if both are set.
|
||||
func buildClientFromEnv(f *Factory) (client *sdk.Client, handled bool, err error) {
|
||||
token := strings.TrimSpace(os.Getenv("WEKNORA_TOKEN"))
|
||||
apiKey := strings.TrimSpace(os.Getenv("WEKNORA_API_KEY"))
|
||||
if token == "" && apiKey == "" {
|
||||
return nil, false, nil
|
||||
}
|
||||
host := strings.TrimSpace(os.Getenv("WEKNORA_HOST"))
|
||||
if host == "" {
|
||||
// Best-effort fallback to the active profile's host; ignore config
|
||||
// errors so env creds + WEKNORA_HOST stay usable with no config at all.
|
||||
if cfg, cerr := f.Config(); cerr == nil && cfg != nil {
|
||||
if prof, ok := cfg.Profiles[cfg.CurrentProfile]; ok {
|
||||
host = prof.Host
|
||||
}
|
||||
}
|
||||
}
|
||||
if host == "" {
|
||||
return nil, true, NewError(CodeInputInvalidArgument,
|
||||
"WEKNORA_TOKEN / WEKNORA_API_KEY is set but no host is available").
|
||||
WithHint("set WEKNORA_HOST (e.g. https://kb.example.com) or configure a profile host")
|
||||
}
|
||||
if token != "" {
|
||||
return sdk.NewClient(host, sdk.WithBearerToken(token)), true, nil
|
||||
}
|
||||
return sdk.NewClient(host, sdk.WithAPIKey(apiKey)), true, nil
|
||||
}
|
||||
|
||||
// AddKBFlag registers the standard `--kb` flag that ResolveKB reads. Use this
|
||||
// instead of duplicating the flag declaration in every command that scopes to
|
||||
// a knowledge base — one source of truth for flag name and help text.
|
||||
@@ -212,22 +272,7 @@ func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) {
|
||||
}
|
||||
return ResolveKBNameToID(cmd.Context(), c, v)
|
||||
}
|
||||
if v := os.Getenv("WEKNORA_KB_ID"); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
cwd, err := os.Getwd()
|
||||
if err == nil {
|
||||
if path, found, derr := projectlink.Discover(cwd); derr == nil && found {
|
||||
p, lerr := projectlink.Load(path)
|
||||
if lerr != nil {
|
||||
return "", Wrapf(CodeProjectLinkCorrupt, lerr, "read project link")
|
||||
}
|
||||
if p.KBID != "" {
|
||||
return p.KBID, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", NewError(CodeKBIDRequired, "kb is required")
|
||||
return f.resolveKBFromEnvOrLink()
|
||||
}
|
||||
|
||||
// ResolveKBLocal mirrors ResolveKB but never calls the SDK. When --kb is a
|
||||
@@ -239,6 +284,14 @@ func (f *Factory) ResolveKBLocal(cmd *cobra.Command) (string, error) {
|
||||
if v, _ := cmd.Flags().GetString("kb"); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
return f.resolveKBFromEnvOrLink()
|
||||
}
|
||||
|
||||
// resolveKBFromEnvOrLink is the shared fallback tail of ResolveKB /
|
||||
// ResolveKBLocal (which differ only in how they treat the --kb flag): it reads
|
||||
// WEKNORA_KB_ID, then the walk-up .weknora/project.yaml link, and returns
|
||||
// CodeKBIDRequired when neither is set. Never calls the SDK.
|
||||
func (f *Factory) resolveKBFromEnvOrLink() (string, error) {
|
||||
if v := os.Getenv("WEKNORA_KB_ID"); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
|
||||
@@ -415,3 +415,56 @@ func TestResolveKB_Chain(t *testing.T) {
|
||||
assert.Equal(t, CodeKBIDRequired, typed.Code)
|
||||
})
|
||||
}
|
||||
|
||||
// TestBuildClientFromEnv covers the stateless env-credential path: WEKNORA_TOKEN
|
||||
// / WEKNORA_API_KEY build an ephemeral client with no config/keyring access.
|
||||
func TestBuildClientFromEnv(t *testing.T) {
|
||||
emptyCfg := &Factory{Config: func() (*config.Config, error) { return &config.Config{}, nil }}
|
||||
|
||||
t.Run("no env vars falls through to profile path", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_TOKEN", "")
|
||||
t.Setenv("WEKNORA_API_KEY", "")
|
||||
c, handled, err := buildClientFromEnv(emptyCfg)
|
||||
assert.False(t, handled, "no env creds must fall through")
|
||||
assert.Nil(t, c)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("api key + WEKNORA_HOST builds a client", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_TOKEN", "")
|
||||
t.Setenv("WEKNORA_API_KEY", "sk-test")
|
||||
t.Setenv("WEKNORA_HOST", "https://kb.example.com")
|
||||
c, handled, err := buildClientFromEnv(emptyCfg)
|
||||
assert.True(t, handled)
|
||||
require.NoError(t, err)
|
||||
assert.NotNil(t, c)
|
||||
})
|
||||
|
||||
t.Run("token set but no host is a typed input error", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_API_KEY", "")
|
||||
t.Setenv("WEKNORA_TOKEN", "jwt-token")
|
||||
t.Setenv("WEKNORA_HOST", "")
|
||||
c, handled, err := buildClientFromEnv(emptyCfg)
|
||||
assert.True(t, handled, "env creds set → handled even on host error")
|
||||
assert.Nil(t, c)
|
||||
var ce *Error
|
||||
require.ErrorAs(t, err, &ce)
|
||||
assert.Equal(t, CodeInputInvalidArgument, ce.Code)
|
||||
})
|
||||
|
||||
t.Run("host falls back to the active profile when WEKNORA_HOST unset", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_API_KEY", "")
|
||||
t.Setenv("WEKNORA_TOKEN", "jwt-token")
|
||||
t.Setenv("WEKNORA_HOST", "")
|
||||
f := &Factory{Config: func() (*config.Config, error) {
|
||||
return &config.Config{
|
||||
CurrentProfile: "p",
|
||||
Profiles: map[string]config.Profile{"p": {Host: "https://prof.example.com"}},
|
||||
}, nil
|
||||
}}
|
||||
c, handled, err := buildClientFromEnv(f)
|
||||
assert.True(t, handled)
|
||||
require.NoError(t, err, "should use the active profile's host")
|
||||
assert.NotNil(t, c)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ func (o *FormatOptions) WantsJSON() bool {
|
||||
// path) or as bare NDJSON lines (FormatNDJSON path). meta is optional
|
||||
// (pass nil for mutation commands without batch counts).
|
||||
//
|
||||
// FormatJSON path: envelope is {ok:true, data:..., meta?:..., _notice?:...}.
|
||||
// FormatJSON path: envelope is {ok:true, data:..., meta?:..., profile?:...}.
|
||||
// Indent is determined by o.TTY (populated by ResolveDefault).
|
||||
// When o.JQ is set, jq evaluates against the full envelope JSON, so users
|
||||
// project with ".data[]", ".meta.count", etc.
|
||||
@@ -149,13 +149,23 @@ func mapJQError(err error) error {
|
||||
// - For human-readable rendering, pass --format text explicitly
|
||||
func (o *FormatOptions) ResolveDefault(tty bool) {
|
||||
o.TTY = tty
|
||||
// Apply WEKNORA_FORMAT before the hard default so the documented
|
||||
// precedence holds: explicit --format (already set on o.Mode by
|
||||
// CheckFormatFlag) > WEKNORA_FORMAT > DefaultFormatMode. FromEnv is a
|
||||
// no-op when --format was passed. Folded in here because nearly every
|
||||
// command calls ResolveDefault but only a couple called FromEnv, so the
|
||||
// env var was silently ignored on success output across the CLI.
|
||||
o.FromEnv()
|
||||
if o.Mode == "" {
|
||||
o.Mode = DefaultFormatMode
|
||||
}
|
||||
}
|
||||
|
||||
// FromEnv reads WEKNORA_FORMAT and applies it when Mode hasn't been set
|
||||
// by --format. Call between CheckFormatFlag and ResolveDefault.
|
||||
// by --format. ResolveDefault now calls this, so commands get the env var
|
||||
// applied automatically; explicit callers (e.g. the root PersistentPreRunE,
|
||||
// which resolves the error-envelope mode before any command RunE) remain
|
||||
// valid and idempotent.
|
||||
//
|
||||
// Invalid env values are silently ignored (the user's --format on a
|
||||
// later invocation will still take precedence).
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestEmit_WrapsInEnvelope(t *testing.T) {
|
||||
func TestEmit_WithMeta(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
meta := &output.Meta{Count: 2, HasMore: true}
|
||||
meta := &output.Meta{Count: output.IntPtr(2), HasMore: true}
|
||||
if err := fopts.Emit(&buf, []string{"a", "b"}, meta); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
@@ -236,3 +236,38 @@ func TestFromEnv_InvalidValueIgnored(t *testing.T) {
|
||||
t.Errorf("invalid env should be ignored; got %v", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveDefault_AppliesEnv pins that ResolveDefault honours
|
||||
// WEKNORA_FORMAT. Regression: commands call CheckFormatFlag + ResolveDefault
|
||||
// but (nearly) none called FromEnv, so the documented env var was silently
|
||||
// ignored on success output across the whole CLI until ResolveDefault folded
|
||||
// it in. This is the path every command's RunE actually takes.
|
||||
func TestResolveDefault_AppliesEnv(t *testing.T) {
|
||||
t.Setenv("WEKNORA_FORMAT", "text")
|
||||
o := &FormatOptions{} // no --format → Mode empty, as after CheckFormatFlag
|
||||
o.ResolveDefault(false)
|
||||
if o.Mode != FormatText {
|
||||
t.Errorf("WEKNORA_FORMAT=text must drive ResolveDefault to text; got %v", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveDefault_FlagBeatsEnv pins precedence: an explicit --format
|
||||
// (Mode already set) wins over WEKNORA_FORMAT.
|
||||
func TestResolveDefault_FlagBeatsEnv(t *testing.T) {
|
||||
t.Setenv("WEKNORA_FORMAT", "text")
|
||||
o := &FormatOptions{Mode: FormatJSON} // --format json supplied
|
||||
o.ResolveDefault(false)
|
||||
if o.Mode != FormatJSON {
|
||||
t.Errorf("explicit --format json must beat WEKNORA_FORMAT=text; got %v", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveDefault_NoEnvNoFlag_UsesDefault pins the fallback.
|
||||
func TestResolveDefault_NoEnvNoFlag_UsesDefault(t *testing.T) {
|
||||
t.Setenv("WEKNORA_FORMAT", "")
|
||||
o := &FormatOptions{}
|
||||
o.ResolveDefault(false)
|
||||
if o.Mode != DefaultFormatMode {
|
||||
t.Errorf("no flag + no env must fall back to default %v; got %v", DefaultFormatMode, o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,79 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
// rfc3339Example is the canonical hint shown when a time-flag value isn't RFC3339.
|
||||
const rfc3339Example = "2006-01-02T15:04:05Z"
|
||||
|
||||
// ParseTimeFlag parses an RFC3339 time-flag value. An empty value is treated as
|
||||
// unset and returns (nil, nil) — callers use nil to mean "no bound". A
|
||||
// malformed value returns a CodeInputInvalidArgument error naming the label;
|
||||
// on success it returns the parsed time. label is used verbatim in the message
|
||||
// (e.g. "--start-time" for a CLI flag, "start_time" for an MCP tool field).
|
||||
//
|
||||
// One place owns the RFC3339 time-flag shape — the parse, error code, and
|
||||
// wording consistency sibling of ValidateEnum.
|
||||
func ParseTimeFlag(label, value string) (*time.Time, error) {
|
||||
if value == "" {
|
||||
return nil, nil
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339, value)
|
||||
if err != nil {
|
||||
return nil, &Error{
|
||||
Code: CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("%s must be RFC3339 (e.g. %s), got %q",
|
||||
label, rfc3339Example, value),
|
||||
}
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
// ValidateEnum checks a closed-set flag value, case-insensitively. An empty
|
||||
// value is treated as unset and returns "" with no error (callers use the empty
|
||||
// case to mean "no filter" / "server default"). A non-empty value that matches
|
||||
// no allowed entry returns CodeInputInvalidArgument naming the flag and the
|
||||
// valid set; on a match it returns the canonical spelling from allowed (so the
|
||||
// server, which may be case-sensitive, receives a normalized value).
|
||||
//
|
||||
// This is the one place the "validate a flag against a closed enum" shape
|
||||
// lives — keeping the membership test, error code, and message wording
|
||||
// consistent across every such flag instead of hand-rolling each.
|
||||
func ValidateEnum(flagName, value string, allowed []string) (string, error) {
|
||||
if value == "" {
|
||||
return "", nil
|
||||
}
|
||||
for _, a := range allowed {
|
||||
if strings.EqualFold(value, a) {
|
||||
return a, nil
|
||||
}
|
||||
}
|
||||
return "", &Error{
|
||||
Code: CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("--%s must be one of: %s - got %q",
|
||||
flagName, strings.Join(allowed, " | "), value),
|
||||
}
|
||||
}
|
||||
|
||||
// EnumStrings converts a slice of a ~string enum type (e.g. the SDK's
|
||||
// AllModelTypes / AllMessageSearchModes enumerators) to plain strings for
|
||||
// ValidateEnum and flag-help wording. Sourcing the closed set from the SDK
|
||||
// this way keeps the CLI from drifting from the server vocabulary.
|
||||
func EnumStrings[T ~string](xs []T) []string {
|
||||
out := make([]string, len(xs))
|
||||
for i, x := range xs {
|
||||
out[i] = string(x)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// OpenInput returns a reader for path. If path == "-", returns stdin
|
||||
// (iostreams.IO.In). Otherwise opens the file. Caller is responsible
|
||||
// for closing if needed — for typical "-input <file>"/"--input -" CLI
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseTimeFlag(t *testing.T) {
|
||||
// Empty → unset (nil, nil).
|
||||
if got, err := ParseTimeFlag("--before", ""); err != nil || got != nil {
|
||||
t.Errorf(`empty: got (%v, %v), want (nil, nil)`, got, err)
|
||||
}
|
||||
|
||||
// Valid RFC3339 → parsed time.
|
||||
want, _ := time.Parse(time.RFC3339, "2026-06-01T00:00:00Z")
|
||||
got, err := ParseTimeFlag("--before", "2026-06-01T00:00:00Z")
|
||||
if err != nil || got == nil || !got.Equal(want) {
|
||||
t.Errorf("valid: got (%v, %v)", got, err)
|
||||
}
|
||||
|
||||
// Malformed → CodeInputInvalidArgument naming the label.
|
||||
_, err = ParseTimeFlag("start_time", "2026-06-01")
|
||||
var typed *Error
|
||||
if !errors.As(err, &typed) || typed.Code != CodeInputInvalidArgument {
|
||||
t.Fatalf("malformed: expected CodeInputInvalidArgument, got %v", err)
|
||||
}
|
||||
if !strings.Contains(typed.Message, "start_time") || !strings.Contains(typed.Message, "RFC3339") {
|
||||
t.Errorf("message %q missing label/RFC3339 hint", typed.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateEnum(t *testing.T) {
|
||||
allowed := []string{"keyword", "vector", "hybrid"}
|
||||
|
||||
// Empty value is "unset" — allowed, returns "".
|
||||
if got, err := ValidateEnum("mode", "", allowed); err != nil || got != "" {
|
||||
t.Errorf(`empty: got (%q, %v), want ("", nil)`, got, err)
|
||||
}
|
||||
|
||||
// Exact and case-insensitive matches return the canonical spelling.
|
||||
for _, in := range []string{"hybrid", "Hybrid", "HYBRID"} {
|
||||
got, err := ValidateEnum("mode", in, allowed)
|
||||
if err != nil || got != "hybrid" {
|
||||
t.Errorf(`%q: got (%q, %v), want ("hybrid", nil)`, in, got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Canonical spelling comes from `allowed`, not the input casing.
|
||||
if got, _ := ValidateEnum("type", "embedding", []string{"Embedding", "Rerank"}); got != "Embedding" {
|
||||
t.Errorf(`canonical: got %q, want "Embedding"`, got)
|
||||
}
|
||||
|
||||
// Unknown value → CodeInputInvalidArgument naming the flag + valid set.
|
||||
_, err := ValidateEnum("mode", "hybird", allowed)
|
||||
var typed *Error
|
||||
if !errors.As(err, &typed) || typed.Code != CodeInputInvalidArgument {
|
||||
t.Fatalf("unknown: expected CodeInputInvalidArgument, got %v", err)
|
||||
}
|
||||
for _, want := range []string{"--mode", "keyword | vector | hybrid", `"hybird"`} {
|
||||
if !strings.Contains(typed.Message, want) {
|
||||
t.Errorf("message %q missing %q", typed.Message, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// ModelLister is the narrow SDK surface ResolveModelRef needs. *sdk.Client
|
||||
// satisfies it.
|
||||
type ModelLister interface {
|
||||
ListModels(ctx context.Context) ([]sdk.Model, error)
|
||||
}
|
||||
|
||||
// ResolveModelRef returns ref unchanged when it is already a model id (UUID);
|
||||
// otherwise it resolves ref as a model NAME among models of wantType (pass ""
|
||||
// to match any type) and returns that model's id. Mirrors the id-or-name policy
|
||||
// of --kb so model-referencing flags accept either.
|
||||
//
|
||||
// Errors with resource.not_found when nothing matches, and
|
||||
// input.invalid_argument when the name is ambiguous (so the caller passes an id
|
||||
// instead). The empty ref is returned as-is for callers to treat as "unset".
|
||||
func ResolveModelRef(ctx context.Context, lister ModelLister, ref, wantType string) (string, error) {
|
||||
if ref == "" || IsKBID(ref) { // IsKBID is a generic UUID check
|
||||
return ref, nil
|
||||
}
|
||||
models, err := lister.ListModels(ctx)
|
||||
if err != nil {
|
||||
return "", WrapHTTP(err, "list models to resolve %q", ref)
|
||||
}
|
||||
var matches []sdk.Model
|
||||
for _, m := range models {
|
||||
if m.Name == ref && (wantType == "" || string(m.Type) == wantType) {
|
||||
matches = append(matches, m)
|
||||
}
|
||||
}
|
||||
switch len(matches) {
|
||||
case 1:
|
||||
return matches[0].ID, nil
|
||||
case 0:
|
||||
msg := fmt.Sprintf("no model named %q", ref)
|
||||
if wantType != "" {
|
||||
msg = fmt.Sprintf("no %s model named %q", wantType, ref)
|
||||
}
|
||||
return "", NewError(CodeResourceNotFound, msg).
|
||||
WithHint("discover models with `weknora model list`")
|
||||
default:
|
||||
return "", NewError(CodeInputInvalidArgument,
|
||||
fmt.Sprintf("%q matches %d models — pass the model id instead", ref, len(matches))).
|
||||
WithHint("`weknora model list` shows the ids")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type fakeModelLister struct {
|
||||
models []sdk.Model
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeModelLister) ListModels(_ context.Context) ([]sdk.Model, error) {
|
||||
return f.models, f.err
|
||||
}
|
||||
|
||||
func TestResolveModelRef(t *testing.T) {
|
||||
lister := &fakeModelLister{models: []sdk.Model{
|
||||
{ID: "11111111-1111-1111-1111-111111111111", Name: "qwen2", Type: sdk.ModelTypeKnowledgeQA},
|
||||
{ID: "22222222-2222-2222-2222-222222222222", Name: "nomic", Type: sdk.ModelTypeEmbedding},
|
||||
{ID: "33333333-3333-3333-3333-333333333333", Name: "dup", Type: sdk.ModelTypeEmbedding},
|
||||
{ID: "44444444-4444-4444-4444-444444444444", Name: "dup", Type: sdk.ModelTypeKnowledgeQA},
|
||||
}}
|
||||
|
||||
// A UUID passes through untouched without hitting the lister.
|
||||
got, err := ResolveModelRef(context.Background(), &fakeModelLister{err: errors.New("must not call")},
|
||||
"99999999-9999-9999-9999-999999999999", "Embedding")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "99999999-9999-9999-9999-999999999999", got)
|
||||
|
||||
// Empty passes through (caller treats as unset).
|
||||
got, err = ResolveModelRef(context.Background(), lister, "", "")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", got)
|
||||
|
||||
// Name + type → id.
|
||||
got, err = ResolveModelRef(context.Background(), lister, "qwen2", "KnowledgeQA")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "11111111-1111-1111-1111-111111111111", got)
|
||||
|
||||
// Type filter disambiguates same-named models across types.
|
||||
got, err = ResolveModelRef(context.Background(), lister, "dup", "Embedding")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "33333333-3333-3333-3333-333333333333", got)
|
||||
|
||||
// No match → resource.not_found.
|
||||
_, err = ResolveModelRef(context.Background(), lister, "missing", "Embedding")
|
||||
var ce *Error
|
||||
require.ErrorAs(t, err, &ce)
|
||||
assert.Equal(t, CodeResourceNotFound, ce.Code)
|
||||
|
||||
// Ambiguous (same name, no type filter) → input.invalid_argument.
|
||||
_, err = ResolveModelRef(context.Background(), lister, "dup", "")
|
||||
require.ErrorAs(t, err, &ce)
|
||||
assert.Equal(t, CodeInputInvalidArgument, ce.Code)
|
||||
}
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
// keyring namespace.
|
||||
//
|
||||
// Crucially this also rejects shell metacharacters (space, `;`, `&`, `|`,
|
||||
// `$`, quotes, backticks, etc.), so the profile name remains safe to
|
||||
// interpolate into envelope.error.retry_command — an agent that exec's
|
||||
// `sh -c <retry_command>` cannot be tricked via a maliciously-named profile.
|
||||
// `$`, quotes, backticks, etc.), so the profile name remains safe to embed
|
||||
// in envelope.error.retry_argv — even an agent that joins the argv and exec's
|
||||
// `sh -c <joined>` cannot be tricked via a maliciously-named profile.
|
||||
func ValidateProfileName(name string) error {
|
||||
if name == "" {
|
||||
return &Error{
|
||||
|
||||
@@ -37,9 +37,9 @@ func TestValidateProfileName_RejectsEmpty(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestValidateProfileName_RejectsShellMetachars is the security-critical
|
||||
// case: anything that could break retry_command shell interpolation must be
|
||||
// case: anything that could break retry_argv shell interpolation must be
|
||||
// rejected at the entry point. If this test ever loosens, an agent that
|
||||
// exec()s retry_command becomes injectable via a malicious profile name.
|
||||
// joins-and-exec()s retry_argv becomes injectable via a malicious profile name.
|
||||
func TestValidateProfileName_RejectsShellMetachars(t *testing.T) {
|
||||
cases := []string{
|
||||
"evil; rm -rf /",
|
||||
|
||||
@@ -1,30 +1,51 @@
|
||||
// Package-level note:
|
||||
//
|
||||
// SetRisk attaches risk metadata to a destructive cobra command via cobra
|
||||
// SetRisk / SetWriteRisk attach risk metadata to a cobra command via cobra
|
||||
// annotations. The SetAgentHelp wrapper in agenthelp.go reads these
|
||||
// annotations and prepends a "Risk: <action> (<level>)" line at the top
|
||||
// of human help output.
|
||||
// of human help output. Destructive ops use SetRisk ("destructive");
|
||||
// reversible update commands use SetWriteRisk ("write"). "read" is reserved.
|
||||
//
|
||||
// envelope.error.risk.action is emitted separately by the
|
||||
// ConfirmDestructive callsite argument and does NOT read these annotations.
|
||||
// ConfirmDestructive / ConfirmWrite callsite argument and does NOT read
|
||||
// these annotations.
|
||||
package cmdutil
|
||||
|
||||
import "github.com/spf13/cobra"
|
||||
|
||||
// RiskDestructive is the only level value currently emitted. The annotation
|
||||
// key reserves "read" / "write" for future use.
|
||||
const RiskDestructive = "destructive"
|
||||
// Risk levels emitted in the annotation / envelope:
|
||||
// - RiskDestructive: irreversible ops (delete, kb init clobber).
|
||||
// - RiskWrite: reversible metadata edits (kb / agent / doc update).
|
||||
//
|
||||
// "read" remains reserved (read-only commands carry no risk annotation).
|
||||
const (
|
||||
RiskDestructive = "destructive"
|
||||
RiskWrite = "write"
|
||||
)
|
||||
|
||||
// SetRisk writes risk metadata to a cobra command's annotations.
|
||||
// SetRisk writes destructive risk metadata to a cobra command's annotations.
|
||||
// Idempotent: re-calling with the same action overwrites cleanly.
|
||||
//
|
||||
// nil-map guard: cobra.Command.Annotations is `map[string]string` and
|
||||
// defaults to nil. Writing to a nil map panics, so we allocate first.
|
||||
func SetRisk(cmd *cobra.Command, action string) {
|
||||
setRisk(cmd, RiskDestructive, action)
|
||||
}
|
||||
|
||||
// SetWriteRisk mirrors SetRisk but tags the command at the "write" level —
|
||||
// used by update commands (kb / agent / doc update), which are reversible
|
||||
// metadata edits rather than irreversible destructive ops. They remain
|
||||
// confirmation-gated; only the level label differs.
|
||||
func SetWriteRisk(cmd *cobra.Command, action string) {
|
||||
setRisk(cmd, RiskWrite, action)
|
||||
}
|
||||
|
||||
// setRisk is the shared writer behind SetRisk / SetWriteRisk.
|
||||
func setRisk(cmd *cobra.Command, level, action string) {
|
||||
if cmd.Annotations == nil {
|
||||
cmd.Annotations = make(map[string]string)
|
||||
}
|
||||
cmd.Annotations["risk.level"] = RiskDestructive
|
||||
cmd.Annotations["risk.level"] = level
|
||||
cmd.Annotations["risk.action"] = action
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package cmdutil
|
||||
|
||||
import "sort"
|
||||
|
||||
// levenshtein returns the rune-aware edit distance between a and b. Operates
|
||||
// on runes (not bytes) so multi-byte names compare correctly.
|
||||
func levenshtein(a, b string) int {
|
||||
ra, rb := []rune(a), []rune(b)
|
||||
la, lb := len(ra), len(rb)
|
||||
if la == 0 {
|
||||
return lb
|
||||
}
|
||||
if lb == 0 {
|
||||
return la
|
||||
}
|
||||
prev := make([]int, lb+1)
|
||||
curr := make([]int, lb+1)
|
||||
for j := 0; j <= lb; j++ {
|
||||
prev[j] = j
|
||||
}
|
||||
for i := 1; i <= la; i++ {
|
||||
curr[0] = i
|
||||
for j := 1; j <= lb; j++ {
|
||||
cost := 1
|
||||
if ra[i-1] == rb[j-1] {
|
||||
cost = 0
|
||||
}
|
||||
del := prev[j] + 1
|
||||
ins := curr[j-1] + 1
|
||||
sub := prev[j-1] + cost
|
||||
m := del
|
||||
if ins < m {
|
||||
m = ins
|
||||
}
|
||||
if sub < m {
|
||||
m = sub
|
||||
}
|
||||
curr[j] = m
|
||||
}
|
||||
prev, curr = curr, prev
|
||||
}
|
||||
return prev[lb]
|
||||
}
|
||||
|
||||
// SuggestOne returns the single candidate closest to target by edit distance
|
||||
// when it is a plausible typo (distance ≤ 2), or "" when none qualifies. Ties
|
||||
// are broken lexicographically so the result is deterministic regardless of
|
||||
// candidate ordering (Go randomizes map-range, so callers passing map keys
|
||||
// would otherwise get flaky "did you mean" output). Use when a single
|
||||
// "did you mean: X?" is wanted (e.g. profile lookup); SuggestClosest returns
|
||||
// the ranked list instead.
|
||||
func SuggestOne(target string, candidates []string) string {
|
||||
if target == "" {
|
||||
return ""
|
||||
}
|
||||
sorted := append([]string(nil), candidates...)
|
||||
sort.Strings(sorted)
|
||||
best := ""
|
||||
bestD := 3
|
||||
for _, c := range sorted {
|
||||
if d := levenshtein(target, c); d < bestD {
|
||||
bestD = d
|
||||
best = c
|
||||
}
|
||||
}
|
||||
if bestD > 2 {
|
||||
return ""
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// SuggestClosest returns the candidates nearest to target by edit distance,
|
||||
// closest first, limited to genuinely-plausible typos. Used to turn an
|
||||
// "unknown subcommand"/"unknown name" error into an actionable "did you
|
||||
// mean: X?" instead of dumping the whole list. Returns nil when nothing is
|
||||
// close enough.
|
||||
//
|
||||
// Threshold scales with the target length (max(2, len/3)) so short names
|
||||
// need an exact-ish match while longer names tolerate more slips. At most 3
|
||||
// suggestions are returned.
|
||||
func SuggestClosest(target string, candidates []string) []string {
|
||||
if target == "" {
|
||||
return nil
|
||||
}
|
||||
threshold := len([]rune(target)) / 3
|
||||
if threshold < 2 {
|
||||
threshold = 2
|
||||
}
|
||||
type scored struct {
|
||||
name string
|
||||
dist int
|
||||
}
|
||||
var matches []scored
|
||||
for _, c := range candidates {
|
||||
d := levenshtein(target, c)
|
||||
if d <= threshold {
|
||||
matches = append(matches, scored{c, d})
|
||||
}
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
return nil
|
||||
}
|
||||
sort.SliceStable(matches, func(i, j int) bool {
|
||||
if matches[i].dist != matches[j].dist {
|
||||
return matches[i].dist < matches[j].dist
|
||||
}
|
||||
return matches[i].name < matches[j].name
|
||||
})
|
||||
var out []string
|
||||
for i, m := range matches {
|
||||
if i >= 3 {
|
||||
break
|
||||
}
|
||||
out = append(out, m.name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLevenshtein(t *testing.T) {
|
||||
cases := []struct {
|
||||
a, b string
|
||||
want int
|
||||
}{
|
||||
{"", "", 0},
|
||||
{"abc", "", 3},
|
||||
{"", "abc", 3},
|
||||
{"list", "list", 0},
|
||||
{"list", "listt", 1},
|
||||
{"list", "lst", 1},
|
||||
{"limit", "limti", 2},
|
||||
{"café", "cafe", 1}, // rune-aware: é vs e is one edit
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := levenshtein(tc.a, tc.b); got != tc.want {
|
||||
t.Errorf("levenshtein(%q,%q) = %d, want %d", tc.a, tc.b, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuggestClosest(t *testing.T) {
|
||||
subs := []string{"create", "delete", "edit", "list", "pin", "status", "unpin", "view"}
|
||||
cases := []struct {
|
||||
target string
|
||||
want []string
|
||||
}{
|
||||
{"lst", []string{"list"}}, // 1 edit
|
||||
{"listt", []string{"list"}}, // 1 edit
|
||||
{"vieww", []string{"view"}}, // 1 edit
|
||||
{"creat", []string{"create"}}, // 1 edit
|
||||
{"xyzzy", nil}, // nothing close
|
||||
{"", nil}, // empty
|
||||
{"pinn", []string{"pin"}}, // 1 edit (pin), unpin is 2
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := SuggestClosest(tc.target, subs)
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("SuggestClosest(%q) = %v, want %v", tc.target, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSuggestClosest_RanksByDistance pins closest-first ordering when
|
||||
// candidates are at different distances.
|
||||
func TestSuggestClosest_RanksByDistance(t *testing.T) {
|
||||
// "creat" → "create" is 1 edit (append e); "delete" is far. create first.
|
||||
got := SuggestClosest("creat", []string{"delete", "create"})
|
||||
if len(got) == 0 || got[0] != "create" {
|
||||
t.Errorf("closest to 'creat' should be 'create' first; got %v", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user