feat(cli): --dry-run + risk metadata + validation parity on 19 mutations
Two intertwined agent safety nets that share the same files:
1. --dry-run flag for offline preview of mutation commands
2. Risk: metadata + SetRisk helper for destructive command surfaces
Coverage (19 mutation commands with --dry-run):
kb.create/edit/delete agent.create/edit/delete
doc.create/upload/fetch/delete doc.delete_all (special variant)
session.delete chunk.delete profile.add/remove
auth.refresh/logout link unlink
api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2)
Envelope additions (omitempty in non-dry-run paths):
meta.dry_run: bool true when --dry-run was used
meta.plan: map {action, args} per the per-command taxonomy
Risk: metadata
--------------
cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with
risk.level=destructive + risk.action=<action> on the 9 destructive
commands. The SetAgentHelp wrapper prepends a "Risk: <action>
(destructive)" line in the default text help path so agents see a clear
warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays
unchanged — structured agent-help already carries warnings[].
Validation parity with the live path
------------------------------------
Every pure-local validation (flag presence, mutual exclusion, enum
bounds, URL/regex format, ResolveKBLocal for KB resolution that does not
require an SDK call) runs BEFORE the dry-run gate. This matches the
industry-standard "preview shows what live would do" contract:
--dry-run accepts exactly the same invocations the live path accepts and
rejects exactly the same invocations the live path rejects, modulo the
side-effecting work itself.
The side-effecting work (SDK calls, file writes, keyring writes, server-
side name → id resolution) is what --dry-run actually gates. Each
mutation file pairs its RunE validation block with a regression test
under *_dry_run_test.go / dryrun_validation_test.go so future refactors
don't reintroduce the gap.
Helper surface
--------------
- HandleDryRun(cmd, dryRun, plan) extracts the early-return so the
19 RunE call sites stay 3 lines each.
- EmitDryRun routes through FormatOptions.Emit, inheriting _notice /
TTY indent / --jq filtering for free.
- ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run
paths use it so the plan reports the raw --kb value (UUID or name)
without a name → id lookup.
Streaming commands (chat, session ask, session continue-stream) are
deliberately excluded: a buffered plan makes no sense for an event
stream.
Lock semantics in the dry-run path:
- destructive + --dry-run: exit 0, no exit-10 confirmation prompt
- --dry-run + -y: byte-identical envelope to --dry-run alone
- --dry-run + --jq: filter applies to the preview envelope normally
This commit is contained in:
@@ -36,8 +36,9 @@ type AgentHelp struct {
|
||||
// Routing:
|
||||
// - WEKNORA_AGENT_HELP=1: emit the AgentHelp JSON blob to stdout and
|
||||
// return — agents get clean parseable JSON, no trailing prose.
|
||||
// - Otherwise: render the normal human help, then append an
|
||||
// "AI agents:" block when Warnings is non-empty.
|
||||
// - 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.
|
||||
func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
|
||||
origHelp := cmd.HelpFunc()
|
||||
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
|
||||
@@ -45,6 +46,12 @@ func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
|
||||
emitAgentHelp(c.OutOrStdout(), ah)
|
||||
return
|
||||
}
|
||||
// Prepend Risk: line in the default (human) branch only; the
|
||||
// JSON branch above already carries warnings[]. Skip silently if
|
||||
// the command has no risk annotations.
|
||||
if level, action, ok := GetRisk(c); ok {
|
||||
fmt.Fprintf(c.OutOrStdout(), "Risk: %s (%s)\n\n", action, level)
|
||||
}
|
||||
origHelp(c, args)
|
||||
if len(ah.Warnings) > 0 {
|
||||
w := c.OutOrStdout()
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
// Package-level note:
|
||||
//
|
||||
// AddDryRunFlag + EmitDryRun + DryRunPlan + HandleDryRun support the
|
||||
// --dry-run contract for mutation commands:
|
||||
// - Each mutation cobra command registers --dry-run via AddDryRunFlag.
|
||||
// - RunE early-exits (BEFORE ConfirmDestructive / Factory.Client() /
|
||||
// ResolveKB) when opts.DryRun is true, calling EmitDryRun with a
|
||||
// DryRunPlan describing the would-be action.
|
||||
// - The api command additionally rejects --dry-run on GET (FlagError).
|
||||
//
|
||||
// Side-effect suppression: the dry-run path must NOT call the SDK, write
|
||||
// the keyring, write .weknora/project.yaml, or write download files.
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
// DryRunPlan describes the would-be action for envelope meta.plan.
|
||||
// Field tags use omitempty for api-extra fields so mutation commands
|
||||
// emit only {action, args} and api commands emit {action, method, path, body}.
|
||||
type DryRunPlan struct {
|
||||
Action string `json:"action"`
|
||||
Args map[string]any `json:"args,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Body any `json:"body,omitempty"`
|
||||
}
|
||||
|
||||
// AddDryRunFlag registers --dry-run on a cobra command, binding to a bool
|
||||
// pointer. A bool is sufficient because the CLI is single-tenant and
|
||||
// self-hosted — there is no client/server distinction to encode.
|
||||
func AddDryRunFlag(cmd *cobra.Command, dest *bool) {
|
||||
cmd.Flags().BoolVar(dest, "dry-run", false,
|
||||
"Preview the action without executing (offline; no SDK calls, no file IO)")
|
||||
}
|
||||
|
||||
// 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
|
||||
// callers that have no resolved FormatOptions (tests, error paths); a JSON-mode
|
||||
// default is used in that case.
|
||||
//
|
||||
// The envelope shape is {ok:true, meta:{dry_run:true, plan:{...}}, ...}; data
|
||||
// is intentionally omitted (omitempty on Envelope.Data) since dry-run produced
|
||||
// no real data.
|
||||
//
|
||||
// Caller must ensure NO side effects occurred before this point: no SDK call,
|
||||
// no file write, no keyring touch.
|
||||
func EmitDryRun(w io.Writer, fopts *FormatOptions, plan DryRunPlan) error {
|
||||
planMap, err := planToMap(plan)
|
||||
if err != nil {
|
||||
return fmt.Errorf("dry-run: encode plan: %w", err)
|
||||
}
|
||||
meta := &output.Meta{
|
||||
DryRun: true,
|
||||
Plan: planMap,
|
||||
}
|
||||
if fopts == nil {
|
||||
fopts = &FormatOptions{Mode: FormatJSON}
|
||||
}
|
||||
// NDJSON mode is meaningless for a single dry-run envelope (the contract
|
||||
// emits exactly one object). Fall back to JSON envelope shape so meta.plan
|
||||
// is surfaced; this matches what every other mutation emit does.
|
||||
if fopts.Mode == FormatNDJSON {
|
||||
jsonOpts := *fopts
|
||||
jsonOpts.Mode = FormatJSON
|
||||
return jsonOpts.Emit(w, nil, meta)
|
||||
}
|
||||
return fopts.Emit(w, nil, meta)
|
||||
}
|
||||
|
||||
// HandleDryRun bundles the dry-run preamble for mutation command RunE:
|
||||
// FormatOptions resolution + envelope emit. Returns (handled, err) — when
|
||||
// handled is true, RunE should return err immediately without doing any
|
||||
// SDK / Factory.Client() / ResolveKB / ConfirmDestructive work.
|
||||
//
|
||||
// Pattern:
|
||||
//
|
||||
// if handled, err := cmdutil.HandleDryRun(cmd, opts.DryRun, cmdutil.DryRunPlan{
|
||||
// Action: "kb.create",
|
||||
// Args: map[string]any{"name": opts.Name},
|
||||
// }); handled {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// The helper invokes ONLY local config reads (CheckFormatFlag,
|
||||
// IsStdoutTTY) — no SDK calls, no keyring writes, no file IO. Safe to
|
||||
// call before any other RunE logic.
|
||||
//
|
||||
// The helper re-resolves FormatOptions internally so callsites stay
|
||||
// single-statement; this is intentionally redundant with the outer
|
||||
// CheckFormatFlag the non-dry-run success path still needs. The duplication
|
||||
// is cheap (local flag read) and is the price of consolidating the dry-run
|
||||
// preamble into one helper.
|
||||
func HandleDryRun(cmd *cobra.Command, dryRun bool, plan DryRunPlan) (handled bool, err error) {
|
||||
if !dryRun {
|
||||
return false, nil
|
||||
}
|
||||
fopts, err := CheckFormatFlag(cmd)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
return true, EmitDryRun(iostreams.IO.Out, fopts, plan)
|
||||
}
|
||||
|
||||
// planToMap converts a DryRunPlan to map[string]any so it can populate
|
||||
// output.Meta.Plan (which is open-typed). Goes through json to honor the
|
||||
// omitempty tags so api-only fields don't leak into mutation envelopes.
|
||||
func planToMap(plan DryRunPlan) (map[string]any, error) {
|
||||
b, err := json.Marshal(plan)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"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) {
|
||||
cmd := &cobra.Command{Use: "create"}
|
||||
var dryRun bool
|
||||
AddDryRunFlag(cmd, &dryRun)
|
||||
flag := cmd.Flags().Lookup("dry-run")
|
||||
require.NotNil(t, flag, "expected --dry-run flag registered")
|
||||
assert.Equal(t, "false", flag.DefValue, "default should be false")
|
||||
}
|
||||
|
||||
func TestEmitDryRun_EmitsEnvelopeWithPlan(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
plan := DryRunPlan{
|
||||
Action: "kb.create",
|
||||
Args: map[string]any{
|
||||
"name": "foo",
|
||||
"description": "bar",
|
||||
},
|
||||
}
|
||||
err := EmitDryRun(&buf, &FormatOptions{Mode: FormatJSON}, plan)
|
||||
require.NoError(t, err)
|
||||
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
|
||||
assert.Equal(t, true, got["ok"])
|
||||
assert.NotContains(t, got, "data", "data should be omitempty when nil")
|
||||
|
||||
meta, ok := got["meta"].(map[string]any)
|
||||
require.True(t, ok, "expected meta object")
|
||||
assert.Equal(t, true, meta["dry_run"])
|
||||
|
||||
planOut, ok := meta["plan"].(map[string]any)
|
||||
require.True(t, ok, "expected meta.plan object")
|
||||
assert.Equal(t, "kb.create", planOut["action"])
|
||||
|
||||
args, ok := planOut["args"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "foo", args["name"])
|
||||
assert.Equal(t, "bar", args["description"])
|
||||
}
|
||||
|
||||
func TestEmitDryRun_ApiPlanShape(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
plan := DryRunPlan{
|
||||
Action: "api.post",
|
||||
Method: "POST",
|
||||
Path: "/api/v1/knowledge-bases",
|
||||
Body: map[string]any{"name": "foo"},
|
||||
}
|
||||
err := EmitDryRun(&buf, &FormatOptions{Mode: FormatJSON}, plan)
|
||||
require.NoError(t, err)
|
||||
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
|
||||
planOut := got["meta"].(map[string]any)["plan"].(map[string]any)
|
||||
assert.Equal(t, "api.post", planOut["action"])
|
||||
assert.Equal(t, "POST", planOut["method"])
|
||||
assert.Equal(t, "/api/v1/knowledge-bases", planOut["path"])
|
||||
|
||||
body, ok := planOut["body"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
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},
|
||||
DryRunPlan{Action: "kb.create"})
|
||||
require.NoError(t, err)
|
||||
got := buf.String()
|
||||
assert.Contains(t, got, "\n \"", "TTY=true should produce indented JSON; got %q", got)
|
||||
}
|
||||
|
||||
func TestEmitDryRun_HonorsJQ(t *testing.T) {
|
||||
// jq runs against the full envelope, so the user can project any
|
||||
// envelope field (.meta.dry_run, .meta.plan.action, etc.). Routing
|
||||
// through FormatOptions.Emit is what makes this work.
|
||||
var buf bytes.Buffer
|
||||
err := EmitDryRun(&buf, &FormatOptions{Mode: FormatJSON, JQ: ".meta.plan"},
|
||||
DryRunPlan{Action: "kb.create", Args: map[string]any{"name": "foo"}})
|
||||
require.NoError(t, err)
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
assert.Equal(t, "kb.create", got["action"])
|
||||
args, ok := got["args"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "foo", args["name"])
|
||||
// Sanity: jq output should NOT carry the surrounding envelope fields.
|
||||
assert.NotContains(t, got, "ok")
|
||||
assert.NotContains(t, got, "meta")
|
||||
}
|
||||
|
||||
func TestEmitDryRun_NilFormatOptionsDefaultsJSON(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
err := EmitDryRun(&buf, nil, DryRunPlan{Action: "kb.create"})
|
||||
require.NoError(t, err)
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
assert.Equal(t, true, got["ok"])
|
||||
meta, ok := got["meta"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, true, meta["dry_run"])
|
||||
}
|
||||
|
||||
func TestEmitDryRun_NDJSONFallsBackToJSON(t *testing.T) {
|
||||
// NDJSON mode is meaningless for a single dry-run envelope; the helper
|
||||
// should fall back to JSON envelope shape so meta.plan is surfaced.
|
||||
var buf bytes.Buffer
|
||||
err := EmitDryRun(&buf, &FormatOptions{Mode: FormatNDJSON},
|
||||
DryRunPlan{Action: "kb.create"})
|
||||
require.NoError(t, err)
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
assert.Equal(t, true, got["ok"])
|
||||
meta, ok := got["meta"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, true, meta["dry_run"])
|
||||
}
|
||||
|
||||
func TestHandleDryRun_NotDryRun_SkipsAndReturnsHandledFalse(t *testing.T) {
|
||||
// dryRun=false short-circuits before any flag read / IO touch; helper
|
||||
// returns (false, nil) so RunE proceeds to the live SDK path.
|
||||
cmd := &cobra.Command{Use: "x"}
|
||||
var dryRun bool
|
||||
AddDryRunFlag(cmd, &dryRun)
|
||||
handled, err := HandleDryRun(cmd, false, DryRunPlan{Action: "kb.create"})
|
||||
assert.False(t, handled, "handled must be false when dryRun=false")
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestHandleDryRun_DryRun_EmitsEnvelopeAndReturnsHandledTrue(t *testing.T) {
|
||||
// dryRun=true → helper resolves FormatOptions, emits the envelope to
|
||||
// iostreams.IO.Out, and returns (true, nil). RunE returns the error
|
||||
// immediately without touching SDK.
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
cmd := &cobra.Command{Use: "x"}
|
||||
var dryRun bool
|
||||
AddDryRunFlag(cmd, &dryRun)
|
||||
// --format is a persistent root flag in production; for the unit test
|
||||
// we register it locally so CheckFormatFlag has something to read.
|
||||
cmd.Flags().String("format", "", "")
|
||||
cmd.Flags().String("jq", "", "")
|
||||
require.NoError(t, cmd.Flags().Set("format", "json"))
|
||||
|
||||
handled, err := HandleDryRun(cmd, true, DryRunPlan{
|
||||
Action: "kb.create",
|
||||
Args: map[string]any{"name": "foo"},
|
||||
})
|
||||
assert.True(t, handled, "handled must be true when dryRun=true")
|
||||
require.NoError(t, err)
|
||||
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &got))
|
||||
assert.Equal(t, true, got["ok"])
|
||||
meta, ok := got["meta"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, true, meta["dry_run"])
|
||||
plan, ok := meta["plan"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "kb.create", plan["action"])
|
||||
}
|
||||
|
||||
func TestHandleDryRun_InvalidFormat_ReturnsHandledTrueWithError(t *testing.T) {
|
||||
// Invalid --format must propagate as (true, FlagError) so the caller
|
||||
// returns immediately; otherwise a broken --format would silently fall
|
||||
// through to the live SDK path.
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
cmd := &cobra.Command{Use: "x"}
|
||||
var dryRun bool
|
||||
AddDryRunFlag(cmd, &dryRun)
|
||||
cmd.Flags().String("format", "", "")
|
||||
require.NoError(t, cmd.Flags().Set("format", "garbage"))
|
||||
|
||||
handled, err := HandleDryRun(cmd, true, DryRunPlan{Action: "kb.create"})
|
||||
assert.True(t, handled, "handled must be true even on flag error so RunE stops")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestEmitDryRun_PopulatesProfile(t *testing.T) {
|
||||
SetProfile("staging")
|
||||
t.Cleanup(func() { SetProfile("") })
|
||||
|
||||
var buf bytes.Buffer
|
||||
err := EmitDryRun(&buf, &FormatOptions{Mode: FormatJSON}, DryRunPlan{Action: "kb.create"})
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, buf.String(), `"profile":"staging"`, "expected profile field; got %q", buf.String())
|
||||
}
|
||||
@@ -230,6 +230,33 @@ func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) {
|
||||
return "", NewError(CodeKBIDRequired, "kb is required")
|
||||
}
|
||||
|
||||
// ResolveKBLocal mirrors ResolveKB but never calls the SDK. When --kb is a
|
||||
// name (not a UUID) it returns the raw value as-is instead of looking up the
|
||||
// id server-side. Intended for dry-run paths where SDK side effects must be
|
||||
// avoided; the dry-run plan reports the user-supplied identifier verbatim,
|
||||
// and the live execution path resolves the name → id at call time.
|
||||
func (f *Factory) ResolveKBLocal(cmd *cobra.Command) (string, error) {
|
||||
if v, _ := cmd.Flags().GetString("kb"); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
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")
|
||||
}
|
||||
|
||||
// ApplyLogLevel resolves --log-level / WEKNORA_LOG_LEVEL (in priority order)
|
||||
// and applies the result to the SDK's debug logger. Intended to be called
|
||||
// from the root command's PersistentPreRunE so the resolved level is in
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// Package-level note:
|
||||
//
|
||||
// SetRisk attaches risk metadata to a destructive 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.
|
||||
//
|
||||
// envelope.error.risk.action is emitted separately by the
|
||||
// ConfirmDestructive 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"
|
||||
|
||||
// SetRisk writes 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) {
|
||||
if cmd.Annotations == nil {
|
||||
cmd.Annotations = make(map[string]string)
|
||||
}
|
||||
cmd.Annotations["risk.level"] = RiskDestructive
|
||||
cmd.Annotations["risk.action"] = action
|
||||
}
|
||||
|
||||
// GetRisk reads risk metadata. Returns (level, action, ok). ok=false when
|
||||
// either the annotations map is nil or risk.action key is missing.
|
||||
//
|
||||
// Reading from a nil map is safe in Go (returns zero value); we still
|
||||
// check map-existence explicitly for clarity.
|
||||
func GetRisk(cmd *cobra.Command) (level, action string, ok bool) {
|
||||
if cmd.Annotations == nil {
|
||||
return "", "", false
|
||||
}
|
||||
action, ok = cmd.Annotations["risk.action"]
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
level = cmd.Annotations["risk.level"]
|
||||
return level, action, true
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSetAgentHelp_PrependsRiskWhenAnnotated(t *testing.T) {
|
||||
cmd := &cobra.Command{
|
||||
Use: "delete",
|
||||
Short: "Delete a knowledge base.",
|
||||
Long: "Delete a knowledge base.\n\nThis is irreversible.",
|
||||
}
|
||||
SetRisk(cmd, "kb.delete")
|
||||
SetAgentHelp(cmd, AgentHelp{
|
||||
UsedFor: "remove a KB and all its docs/chunks",
|
||||
Warnings: []string{"never auto -y"},
|
||||
})
|
||||
|
||||
var buf bytes.Buffer
|
||||
cmd.SetOut(&buf)
|
||||
cmd.SetErr(&buf)
|
||||
t.Setenv("WEKNORA_AGENT_HELP", "")
|
||||
|
||||
cmd.HelpFunc()(cmd, []string{})
|
||||
|
||||
out := buf.String()
|
||||
assert.True(t, strings.HasPrefix(out, "Risk: kb.delete (destructive)\n\n"),
|
||||
"expected Risk: line at top; got:\n%s", out)
|
||||
assert.Contains(t, out, "AI agents:", "expected AI agents block still present")
|
||||
assert.Contains(t, out, "- never auto -y", "expected Warnings preserved")
|
||||
}
|
||||
|
||||
func TestSetAgentHelp_NoRiskWhenUnannotated(t *testing.T) {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List knowledge bases.",
|
||||
Long: "List knowledge bases.",
|
||||
}
|
||||
// NO SetRisk call — cmd.Annotations stays nil
|
||||
SetAgentHelp(cmd, AgentHelp{UsedFor: "list KBs"})
|
||||
|
||||
var buf bytes.Buffer
|
||||
cmd.SetOut(&buf)
|
||||
cmd.SetErr(&buf)
|
||||
t.Setenv("WEKNORA_AGENT_HELP", "")
|
||||
|
||||
cmd.HelpFunc()(cmd, []string{})
|
||||
|
||||
out := buf.String()
|
||||
assert.False(t, strings.HasPrefix(out, "Risk:"),
|
||||
"expected NO Risk: line when not SetRisk'd; got:\n%s", out)
|
||||
}
|
||||
|
||||
func TestSetAgentHelp_JSONPathUnaffectedByRisk(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "delete"}
|
||||
SetRisk(cmd, "kb.delete")
|
||||
SetAgentHelp(cmd, AgentHelp{UsedFor: "x", Warnings: []string{"w1"}})
|
||||
|
||||
var buf bytes.Buffer
|
||||
cmd.SetOut(&buf)
|
||||
cmd.SetErr(&buf)
|
||||
t.Setenv("WEKNORA_AGENT_HELP", "1")
|
||||
|
||||
cmd.HelpFunc()(cmd, []string{})
|
||||
|
||||
out := buf.String()
|
||||
assert.False(t, strings.HasPrefix(out, "Risk:"),
|
||||
"JSON path should NOT contain Risk: prefix; got:\n%s", out)
|
||||
assert.Contains(t, out, `"used_for": "x"`, "expected JSON body emitted")
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSetRisk_WritesAnnotations(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "delete"}
|
||||
SetRisk(cmd, "kb.delete")
|
||||
assert.Equal(t, "destructive", cmd.Annotations["risk.level"])
|
||||
assert.Equal(t, "kb.delete", cmd.Annotations["risk.action"])
|
||||
}
|
||||
|
||||
func TestSetRisk_NilMapGuard(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "delete"}
|
||||
// cmd.Annotations is nil by default
|
||||
assert.Nil(t, cmd.Annotations)
|
||||
SetRisk(cmd, "agent.delete")
|
||||
// Should not panic; should initialize map
|
||||
assert.NotNil(t, cmd.Annotations)
|
||||
assert.Equal(t, "agent.delete", cmd.Annotations["risk.action"])
|
||||
}
|
||||
|
||||
func TestGetRisk_ReturnsWritten(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "delete"}
|
||||
SetRisk(cmd, "doc.delete")
|
||||
level, action, ok := GetRisk(cmd)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "destructive", level)
|
||||
assert.Equal(t, "doc.delete", action)
|
||||
}
|
||||
|
||||
func TestGetRisk_NotFound(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "list"}
|
||||
level, action, ok := GetRisk(cmd)
|
||||
assert.False(t, ok)
|
||||
assert.Empty(t, level)
|
||||
assert.Empty(t, action)
|
||||
}
|
||||
|
||||
func TestGetRisk_NilAnnotationsMap(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "list"}
|
||||
// Annotations is nil — should not panic, return ok=false
|
||||
assert.Nil(t, cmd.Annotations)
|
||||
_, _, ok := GetRisk(cmd)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestRiskDestructive_Const(t *testing.T) {
|
||||
assert.Equal(t, "destructive", RiskDestructive)
|
||||
}
|
||||
Reference in New Issue
Block a user