feat(cli): v0.9 contract harmonization
Make the agent-facing contract uniform across the whole surface: - cobra parse errors (unknown flag, arg-count) emit the JSON envelope by default, not bare prose — via a single DefaultFormatMode shared by the early resolver and ResolveDefault. - a malformed --jq is input.invalid_argument (exit 5), not internal.error. - destructive-confirmation messages name the real operation (edit/remove, not a hardcoded "delete"). - `doc wait` emits one envelope (Silent failure, no contradictory stderr); completed marshals as [] not null. - WEKNORA_AGENT_HELP covers every leaf command, enforced by a coverage drift guard; a sibling guard enforces --dry-run on every mutation. - `search docs`/`search chunks` resolve --kb through the same flag→env→project-link chain as `doc list`/`chat` (no longer a hard --kb requirement); a linked dir or WEKNORA_KB_ID now works without --kb, and an unresolved KB is local.kb_id_required (exit 1). The destructive `doc delete --all` keeps its explicit-only rule. - exit-code and batch/wait ok-semantics documented in the shared skill, README, and AGENTS.md.
This commit is contained in:
@@ -2,11 +2,35 @@ package cmdutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
)
|
||||
|
||||
// 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.
|
||||
func confirmCaveat(verb string) string {
|
||||
switch verb {
|
||||
case "edit":
|
||||
return "This overwrites the current values."
|
||||
default: // delete / remove — irreversible
|
||||
return "This cannot be undone."
|
||||
}
|
||||
}
|
||||
|
||||
// titleFirst upper-cases the first rune so the interactive prompt reads as a
|
||||
// sentence ("Delete …?" / "Edit …?") without pulling in golang.org/x/text.
|
||||
func titleFirst(s string) string {
|
||||
if s == "" {
|
||||
return s
|
||||
}
|
||||
r, size := utf8.DecodeRuneInString(s)
|
||||
return string(unicode.ToUpper(r)) + s[size:]
|
||||
}
|
||||
|
||||
// ConfirmDestructiveBatch is the multi-id flavor of ConfirmDestructive: same
|
||||
// behavior matrix (yes / non-TTY / TTY-prompt / user-no) but the prompt text
|
||||
// reflects the count, not a single id. Used by `doc delete <id> [<id>...]`
|
||||
@@ -16,19 +40,19 @@ import (
|
||||
// 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, what string, n int, action, retryCmd string) error {
|
||||
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, verb, what string, n int, action, retryCmd string) error {
|
||||
if yes {
|
||||
return nil
|
||||
}
|
||||
if !iostreams.IO.IsStdoutTTY() || jsonOut {
|
||||
return NewError(
|
||||
CodeInputConfirmationRequired,
|
||||
fmt.Sprintf("delete %d %s(s) requires explicit confirmation: re-run with -y/--yes", n, what),
|
||||
fmt.Sprintf("%s %d %s(s) requires explicit confirmation: re-run with -y/--yes", verb, n, what),
|
||||
).
|
||||
WithRetryCommand(retryCmd).
|
||||
WithRisk("destructive", action)
|
||||
}
|
||||
ok, err := p.Confirm(fmt.Sprintf("Delete %d %s(s)? This cannot be undone.", n, what), false)
|
||||
ok, err := p.Confirm(fmt.Sprintf("%s %d %s(s)? %s", titleFirst(verb), n, what, confirmCaveat(verb)), false)
|
||||
if err != nil {
|
||||
return Wrapf(CodeInputMissingFlag, err, "confirm batch delete")
|
||||
}
|
||||
@@ -59,19 +83,19 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string,
|
||||
// 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, what, id, action, retryCmd string) error {
|
||||
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, verb, what, id, action, retryCmd string) error {
|
||||
if yes {
|
||||
return nil
|
||||
}
|
||||
if !iostreams.IO.IsStdoutTTY() || jsonOut {
|
||||
return NewError(
|
||||
CodeInputConfirmationRequired,
|
||||
fmt.Sprintf("delete %s %s requires explicit confirmation: re-run with -y/--yes", what, id),
|
||||
fmt.Sprintf("%s %s %s requires explicit confirmation: re-run with -y/--yes", verb, what, id),
|
||||
).
|
||||
WithRetryCommand(retryCmd).
|
||||
WithRisk("destructive", action)
|
||||
}
|
||||
ok, err := p.Confirm(fmt.Sprintf("Delete %s %s? This cannot be undone.", what, id), false)
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package cmdutil_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
)
|
||||
|
||||
// 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.
|
||||
func TestConfirmDestructive_VerbMatchesOperation(t *testing.T) {
|
||||
iostreams.SetForTest(t) // non-TTY buffers ⇒ the jsonOut/non-TTY branch
|
||||
|
||||
cases := []struct {
|
||||
verb, what, id string
|
||||
wantPrefix string
|
||||
wantNotContains string
|
||||
}{
|
||||
{"edit", "knowledge base", "kb_x", "edit knowledge base kb_x requires", "delete"},
|
||||
{"delete", "knowledge base", "kb_x", "delete knowledge base kb_x requires", ""},
|
||||
{"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, "")
|
||||
if err == nil {
|
||||
t.Fatalf("verb %q: expected confirmation_required error", tc.verb)
|
||||
}
|
||||
msg := err.Error()
|
||||
if !strings.Contains(msg, tc.wantPrefix) {
|
||||
t.Errorf("verb %q: message %q does not contain %q", tc.verb, msg, tc.wantPrefix)
|
||||
}
|
||||
if tc.wantNotContains != "" && strings.Contains(msg, tc.wantNotContains) {
|
||||
t.Errorf("verb %q: message %q must not contain %q", tc.verb, msg, tc.wantNotContains)
|
||||
}
|
||||
if typed := cmdutil.AsError(err); typed == nil || typed.Code != cmdutil.CodeInputConfirmationRequired {
|
||||
t.Errorf("verb %q: expected CodeInputConfirmationRequired, got %v", tc.verb, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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", "")
|
||||
if err == nil {
|
||||
t.Fatal("expected confirmation_required error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "delete 3 document(s) requires") {
|
||||
t.Errorf("unexpected batch message: %q", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -100,11 +100,6 @@ const (
|
||||
// from network.error (pre-stream transport failure) so users see the
|
||||
// stream specifically aborted, not a connection that never opened.
|
||||
CodeSSEStreamAborted ErrorCode = "local.sse_stream_aborted"
|
||||
|
||||
// mcp.*
|
||||
CodeMCPReadonlyMode ErrorCode = "mcp.readonly_mode"
|
||||
CodeMCPToolNotAllowed ErrorCode = "mcp.tool_not_allowed"
|
||||
CodeMCPSchemaUnknown ErrorCode = "mcp.schema_unknown_command"
|
||||
)
|
||||
|
||||
// Error is the typed error implementations carry through the call stack.
|
||||
@@ -178,6 +173,15 @@ func (e *Error) WithRisk(level, action string) *Error {
|
||||
return e
|
||||
}
|
||||
|
||||
// WithSilent suppresses PrintError's stderr envelope while preserving the Code
|
||||
// for ExitCode. Use when the command already emitted a structured outcome
|
||||
// envelope to stdout (e.g. batch / wait partitions) and a second error envelope
|
||||
// on stderr would contradict it. Mirrors RunBatch's Silent behavior.
|
||||
func (e *Error) WithSilent() *Error {
|
||||
e.Silent = true
|
||||
return e
|
||||
}
|
||||
|
||||
// AsError unwraps to *Error if the chain contains one. Returns nil if not found.
|
||||
func AsError(err error) *Error {
|
||||
var typed *Error
|
||||
@@ -419,8 +423,6 @@ func AllCodes() []ErrorCode {
|
||||
CodeSSEStreamAborted, CodeSessionCreateFailed,
|
||||
// operation
|
||||
CodeOperationTimeout, CodeOperationFailed, CodeOperationCancelled,
|
||||
// mcp
|
||||
CodeMCPReadonlyMode, CodeMCPToolNotAllowed, CodeMCPSchemaUnknown,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,9 @@ func TestErrorToDetail_NilSafe(t *testing.T) {
|
||||
func TestError_WithRetryCommand(t *testing.T) {
|
||||
err := NewError(CodeAuthUnauthenticated, "session expired").
|
||||
WithHint("run `weknora auth login`").
|
||||
WithRetryCommand("weknora auth login --host https://kb.example.com")
|
||||
WithRetryCommand("weknora auth login")
|
||||
|
||||
if err.RetryCommand != "weknora auth login --host https://kb.example.com" {
|
||||
if err.RetryCommand != "weknora auth login" {
|
||||
t.Errorf("RetryCommand not set; got %q", err.RetryCommand)
|
||||
}
|
||||
if err.Hint != "run `weknora auth login`" {
|
||||
|
||||
@@ -23,6 +23,12 @@ const (
|
||||
FormatNDJSON FormatMode = "ndjson"
|
||||
)
|
||||
|
||||
// DefaultFormatMode is the mode used when neither --format nor WEKNORA_FORMAT
|
||||
// is set. Single source of truth shared by FormatOptions.ResolveDefault and
|
||||
// cmd.resolveFormatEarly (the early cobra-parse-error path) so the two cannot
|
||||
// drift on what "no flag" defaults to.
|
||||
const DefaultFormatMode = FormatJSON
|
||||
|
||||
// FormatOptions captures the resolved --format + --jq state for a command.
|
||||
// Mode is one of FormatText / FormatJSON / FormatNDJSON, or "" before
|
||||
// ResolveDefault has been called.
|
||||
@@ -106,12 +112,12 @@ func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
|
||||
switch o.Mode {
|
||||
case FormatJSON:
|
||||
if o.JQ != "" {
|
||||
return format.WriteJSONFiltered(w, output.NewEnvelope(data, meta, globalProfile), nil, o.JQ)
|
||||
return mapJQError(format.WriteJSONFiltered(w, output.NewEnvelope(data, meta, globalProfile), nil, o.JQ))
|
||||
}
|
||||
return output.WriteEnvelope(w, data, meta, o.TTY, globalProfile)
|
||||
case FormatNDJSON:
|
||||
if o.JQ != "" {
|
||||
return format.WriteJSONFiltered(w, data, nil, o.JQ)
|
||||
return mapJQError(format.WriteJSONFiltered(w, data, nil, o.JQ))
|
||||
}
|
||||
return format.WriteNDJSON(w, data)
|
||||
case FormatText:
|
||||
@@ -121,6 +127,22 @@ func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
|
||||
}
|
||||
}
|
||||
|
||||
// mapJQError converts a failure rooted in the user-supplied --jq expression
|
||||
// (format.JQError) into a typed input.invalid_argument error (exit 5) so agents
|
||||
// fix the expression instead of treating a bad --jq as a CLI bug. Non-jq errors
|
||||
// (e.g. an internal serialization fault) pass through unchanged.
|
||||
func mapJQError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var jqe *format.JQError
|
||||
if errors.As(err, &jqe) {
|
||||
return NewError(CodeInputInvalidArgument, jqe.Error()).
|
||||
WithHint("invalid --jq expression; see https://jqlang.github.io/jq/manual/")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// ResolveDefault fills in Mode when the caller has not explicitly set it:
|
||||
// - Mode defaults to FormatJSON
|
||||
// - TTY only affects the indent decision (auto-indent in TTY; compact in pipe)
|
||||
@@ -128,7 +150,7 @@ func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
|
||||
func (o *FormatOptions) ResolveDefault(tty bool) {
|
||||
o.TTY = tty
|
||||
if o.Mode == "" {
|
||||
o.Mode = FormatJSON
|
||||
o.Mode = DefaultFormatMode
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,17 +46,27 @@ func filterObjectKeys(objRaw json.RawMessage, fields []string) (json.RawMessage,
|
||||
return json.Marshal(dst)
|
||||
}
|
||||
|
||||
// JQError marks a failure attributable to the user-supplied --jq expression
|
||||
// (parse or evaluation), as opposed to an internal serialization fault. The
|
||||
// cmdutil layer (which can't be imported here without a cycle) maps it to
|
||||
// input.invalid_argument so agents fix the expression rather than treating a
|
||||
// bad --jq as a CLI bug (internal.error / exit 1).
|
||||
type JQError struct{ Err error }
|
||||
|
||||
func (e *JQError) Error() string { return e.Err.Error() }
|
||||
func (e *JQError) Unwrap() error { return e.Err }
|
||||
|
||||
// writeJQ evaluates expr against raw and writes each result line by line to w.
|
||||
// String results render without quotes (so `--jq '.name'` yields shell-friendly
|
||||
// bare strings); non-string results use encoding/json.
|
||||
//
|
||||
// Returns input.invalid_argument-shaped errors via plain errors.New + fmt;
|
||||
// the caller is responsible for wrapping with cmdutil.NewError if it wants
|
||||
// the typed code.
|
||||
// Expression-attributable failures (parse / eval) are wrapped in *JQError so
|
||||
// the caller can map them to a typed input.invalid_argument code. A failure to
|
||||
// parse `raw` itself is internal (our own envelope JSON) and stays plain.
|
||||
func writeJQ(w io.Writer, raw []byte, expr string) error {
|
||||
query, err := gojq.Parse(expr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jq parse: %w", err)
|
||||
return &JQError{Err: fmt.Errorf("jq parse: %w", err)}
|
||||
}
|
||||
var input any
|
||||
if err := json.Unmarshal(raw, &input); err != nil {
|
||||
@@ -69,7 +79,7 @@ func writeJQ(w io.Writer, raw []byte, expr string) error {
|
||||
return nil
|
||||
}
|
||||
if e, ok := v.(error); ok {
|
||||
return fmt.Errorf("jq eval: %w", e)
|
||||
return &JQError{Err: fmt.Errorf("jq eval: %w", e)}
|
||||
}
|
||||
if s, ok := v.(string); ok {
|
||||
if _, err := fmt.Fprintln(w, s); err != nil {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package format_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
// A malformed --jq expression must surface as *format.JQError so the cmdutil
|
||||
// layer can map it to a typed input.invalid_argument (exit 5) instead of the
|
||||
// unclassified internal.error bucket (exit 1). Regression for the bad-jq
|
||||
// misclassification.
|
||||
func TestWriteJSONFiltered_BadJQExpr_IsJQError(t *testing.T) {
|
||||
for _, expr := range []string{".data[", "this is not jq"} {
|
||||
buf := &bytes.Buffer{}
|
||||
err := format.WriteJSONFiltered(buf, map[string]any{"data": []any{}}, nil, expr)
|
||||
if err == nil {
|
||||
t.Fatalf("expr %q: expected error, got nil", expr)
|
||||
}
|
||||
var jqe *format.JQError
|
||||
if !errors.As(err, &jqe) {
|
||||
t.Errorf("expr %q: expected *format.JQError, got %T: %v", expr, err, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A jq eval failure (valid parse, runtime error) is also expression-attributable
|
||||
// and must be a *JQError.
|
||||
func TestWriteJSONFiltered_JQEvalError_IsJQError(t *testing.T) {
|
||||
buf := &bytes.Buffer{}
|
||||
// ".foo.bar" against a non-object .foo raises an eval error.
|
||||
err := format.WriteJSONFiltered(buf, map[string]any{"foo": 5}, nil, ".foo.bar")
|
||||
if err == nil {
|
||||
t.Fatal("expected eval error, got nil")
|
||||
}
|
||||
var jqe *format.JQError
|
||||
if !errors.As(err, &jqe) {
|
||||
t.Errorf("expected *format.JQError, got %T: %v", err, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A valid expression must NOT error.
|
||||
func TestWriteJSONFiltered_ValidJQ_NoError(t *testing.T) {
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteJSONFiltered(buf, map[string]any{"data": []any{"a", "b"}}, nil, ".data[]"); err != nil {
|
||||
t.Fatalf("valid jq errored: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -83,8 +83,13 @@ func TestSkillsReferenceLiveCommandsAndFlags(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", path, err)
|
||||
}
|
||||
// Normalize CRLF → LF before parsing: Windows CI checks out *.md with
|
||||
// CRLF (git autocrlf), and the \n-anchored codeFence regex would never
|
||||
// match ```weknora\r\n, resolving zero commands. Keep the tokenizer
|
||||
// OS-independent rather than depend on checkout line endings.
|
||||
content := strings.ReplaceAll(string(raw), "\r\n", "\n")
|
||||
rel, _ := filepath.Rel(skillsRoot(t), path)
|
||||
for _, block := range codeFence.FindAllStringSubmatch(string(raw), -1) {
|
||||
for _, block := range codeFence.FindAllStringSubmatch(content, -1) {
|
||||
for _, line := range strings.Split(block[1], "\n") {
|
||||
idx := strings.Index(line, "weknora ")
|
||||
if idx < 0 {
|
||||
|
||||
Reference in New Issue
Block a user