refactor(cli): symmetric envelope infrastructure (supersedes e623e820)

Re-introduce the agent-first symmetric envelope deleted in commit
e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are
primary consumers, the bare-JSON shape can't carry protocol channels
(_notice / risk / meta / request_id / profile) that agents need.
Errors-on-stderr and typed exit codes from e623e820 are preserved;
the envelope wraps the success/error payloads on top.

- cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope /
  Meta / ErrDetail / RiskDetail structs; WriteEnvelope +
  WriteErrorEnvelope writers; PendingNotice plumbing for the open-map
  _notice channel (reserved infra; producer wiring planned for v0.8).
- cli/internal/output/envelope_test.go (new): 7 tests covering
  success / error / TTY indent / Notice / Risk shapes.
- cmdutil.Error extended with RetryCommand (directly-executable
  argv distinct from prose Hint), RetryAfterSeconds (HTTP
  Retry-After), *RiskInfo (nested level+action; ErrInternalServer-
  vs-NotFound distinction), Detail (open structured payload),
  Silent (suppress stderr emit while preserving Code for ExitCode).
- ErrorToDetail single source of envelope.error construction; reused
  by stderr PrintError, MCP StructuredContent, and batch per-item
  error path.
- WithHint / WithRetryCommand / WithRetryAfter / WithDetail /
  WithRisk builders. IsCancelled helper. AsError unwrap helper.
- defaultHint covers ~21 codes; defaultRetryCommand symmetric
  counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand
  exported wrappers for cross-package callers.
- ClassifyHTTPError tightened: rescues HTTP 500 with structured
  server-side code 1003 (ErrNotFound) into resource.not_found.
  Server's generic 1007 (ErrInternalServer) bucket stays as
  server.error — including it would mis-route validation failures
  (e.g. SQLSTATE 22001) as not-found.
- PrintError dual-mode: text/human → prose with code:msg / hint /
  retry lines; json/ndjson → envelope on stderr. Mode pinned by
  root PersistentPreRunE via SetFormatMode. resolveFormatEarly()
  scans argv before cobra dispatch so cobra-side validators
  (unknown flag, arg-count) still surface as envelope when
  --format json is in effect. Silent typed errors short-circuit
  the stderr emit. FlagError mapped to input.invalid_argument for
  the envelope (exit code stays 2 via FlagError class).
- Unknown-subcommand guard installed recursively at the root:
  parents with subcommands but no Run/RunE get a typed RunE that
  emits input.unknown_subcommand envelope with
  detail.{unknown, command_path, available[]} and
  retry_command "<parent> --help". cobra.ArbitraryArgs bypasses
  legacyArgs validation so the guard receives unmatched argv.
- cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for
  chain debugging; ErrorToDetail strips the code prefix from
  envelope.message since the separate type field carries it
  (prevents the doubled-prefix "code: code: ..." that agents would
  see).

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
This commit is contained in:
nullkey
2026-05-21 18:40:06 +08:00
committed by lyingbug
parent 7d1fe6f11b
commit 733bb3aaa1
11 changed files with 852 additions and 55 deletions
+158 -10
View File
@@ -3,10 +3,14 @@
package cmdutil
import (
"context"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/Tencent/WeKnora/cli/internal/output"
)
// ErrorCode is a namespaced stable identifier emitted on stderr in the
@@ -37,6 +41,11 @@ const (
// surface the error to the user and only retry with -y after explicit
// human approval; never auto-retry.
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
// CodeInputUnknownSubcommand marks an invocation that reached a parent
// command path but the first positional argument did not match any
// registered subcommand. Detail includes an `available` list so agents
// can surface valid choices without re-invoking; retry with `<path> --help`.
CodeInputUnknownSubcommand ErrorCode = "input.unknown_subcommand"
// server.* / network.*
CodeServerError ErrorCode = "server.error"
@@ -72,7 +81,7 @@ const (
CodeLocalKeychainDenied ErrorCode = "local.keychain_denied"
CodeLocalFileIO ErrorCode = "local.file_io"
CodeLocalUnimplemented ErrorCode = "local.unimplemented"
CodeLocalContextNotFound ErrorCode = "local.context_not_found"
CodeLocalProfileNotFound ErrorCode = "local.profile_not_found"
// KB-resolution chain and project-link codes.
CodeKBIDRequired ErrorCode = "local.kb_id_required"
CodeKBNotFound ErrorCode = "local.kb_not_found"
@@ -103,17 +112,26 @@ const (
// `code: message[: cause]\nhint: ...` form. Exit code is derived by
// ExitCode().
type Error struct {
Code ErrorCode
Message string
Hint string
Cause error
Retryable bool
HTTPStatus int
Code ErrorCode
Message string
Hint string
Cause error
// Silent suppresses PrintError's stderr output while preserving the
// typed Code for ExitCode. Set by commands that already wrote their
// own output (e.g. bulk operations reporting partial-success data on
// stdout) but still need to surface a non-zero exit code.
Silent bool
Silent bool
RetryCommand string // Directly-executable argv, 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
}
// RiskInfo tags an error with destructive-write metadata that surfaces
// in the wire envelope's error.risk field.
type RiskInfo struct {
Level string
Action string
}
func (e *Error) Error() string {
@@ -128,6 +146,101 @@ func (e *Error) Error() string {
func (e *Error) Unwrap() error { return e.Cause }
// WithHint sets a prose-style actionable hint.
func (e *Error) WithHint(hint string) *Error {
e.Hint = hint
return e
}
// WithRetryCommand sets the directly-executable retry argv string.
// Agent 端不用 regex 从 prose hint 提 argv。
// Empty string for codes without a canonical retry command.
func (e *Error) WithRetryCommand(cmd string) *Error {
e.RetryCommand = cmd
return e
}
// WithRetryAfter sets the retry_after_seconds hint (from HTTP Retry-After header).
func (e *Error) WithRetryAfter(s int) *Error {
e.RetryAfterSeconds = s
return e
}
// WithDetail attaches structured error.detail (e.g. unknown-subcommand available[]).
func (e *Error) WithDetail(d any) *Error {
e.Detail = d
return e
}
// WithRisk tags a high-risk write (destructive deletes etc.) for the agent protocol.
func (e *Error) WithRisk(level, action string) *Error {
e.Risk = &RiskInfo{Level: level, Action: action}
return e
}
// AsError unwraps to *Error if the chain contains one. Returns nil if not found.
func AsError(err error) *Error {
var typed *Error
if errors.As(err, &typed) {
return typed
}
return nil
}
// 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.
// Returns nil when err is nil.
func ErrorToDetail(err error) *output.ErrDetail {
if err == nil {
return nil
}
if typed := AsError(err); typed != nil {
hint := typed.Hint
if hint == "" {
hint = defaultHint(typed.Code)
}
retry := typed.RetryCommand
if retry == "" {
retry = defaultRetryCommand(typed.Code)
}
// Build message without the code prefix — the envelope's separate
// "type" field already carries the code, so repeating it in "message"
// causes agents that render "{type}: {message}" to produce a doubled
// prefix (e.g. "resource.not_found: resource.not_found: ...").
msg := typed.Message
if typed.Cause != nil {
msg = fmt.Sprintf("%s: %v", typed.Message, typed.Cause)
}
detail := &output.ErrDetail{
Type: string(typed.Code),
Message: msg,
Hint: hint,
RetryCommand: retry,
RetryAfterSeconds: typed.RetryAfterSeconds,
Detail: typed.Detail,
}
if typed.Risk != nil {
detail.Risk = &output.RiskDetail{Level: typed.Risk.Level, Action: typed.Risk.Action}
}
return detail
}
// Cobra parse / arg-count errors flow through cmdutil.NewFlagError —
// surface them as input.invalid_argument so the wire envelope carries a
// useful typed code instead of the unclassified "internal.error" bucket.
// ExitCode separately maps FlagError → 2.
var fe *FlagError
if errors.As(err, &fe) {
return &output.ErrDetail{
Type: string(CodeInputInvalidArgument),
Message: err.Error(),
Hint: defaultHint(CodeInputInvalidArgument),
}
}
return &output.ErrDetail{Type: "internal.error", Message: err.Error()}
}
// NewError constructs a typed error.
func NewError(code ErrorCode, message string) *Error {
return &Error{Code: code, Message: message}
@@ -207,6 +320,15 @@ func matchPrefix(err error, prefix string) bool {
return strings.HasPrefix(string(e.Code), prefix)
}
// serverNotFoundRE matches the WeKnora server's structured error-envelope body
// for the typed "not found" code (1003 = ErrNotFound). Server's 1007 is the
// generic ErrInternalServer bucket — including it would mis-classify every
// validation / DB failure (e.g. SQLSTATE 22001 "value too long") as
// resource.not_found, sending agents down the wrong recovery path.
// Matching the structured "code":1003 anchor avoids the free-substring false
// positive (e.g. a stack trace containing "config file not found").
var serverNotFoundRE = regexp.MustCompile(`"code":1003\b`)
// ClassifyHTTPStatus maps an HTTP status code to the canonical ErrorCode.
// Single source of truth so error codes stay aligned whether the failure
// was detected by the SDK (string-formatted error) or by the CLI directly
@@ -257,7 +379,18 @@ func ClassifyHTTPError(err error) ErrorCode {
if perr != nil {
return CodeServerError
}
return ClassifyHTTPStatus(status)
base := ClassifyHTTPStatus(status)
// Server-side 500-misclassification rescue: some servers return HTTP 500
// for logical "not found" cases (e.g. code 1007 "knowledge base not found",
// code 1003 "Knowledge not found") instead of 404. Match the server's known
// error-code envelope precisely to avoid false-positive rescues on generic
// 500 bodies that happen to contain "not found" (e.g. "config file not found
// in stack trace"). The free-substring match would over-match.
body := rest[end+1:]
if base == CodeServerError && serverNotFoundRE.MatchString(body) {
return CodeResourceNotFound
}
return base
}
// AllCodes returns the registered error code set.
@@ -273,12 +406,13 @@ func AllCodes() []ErrorCode {
CodeResourceNotFound, CodeResourceAlreadyExists, CodeResourceLocked,
// input
CodeInputInvalidArgument, CodeInputMissingFlag, CodeInputConfirmationRequired,
CodeInputUnknownSubcommand,
// server / network
CodeServerError, CodeServerTimeout, CodeServerRateLimited,
CodeServerIncompatibleVersion, CodeNetworkError,
// local
CodeLocalConfigCorrupt, CodeLocalKeychainDenied, CodeLocalFileIO,
CodeLocalUnimplemented, CodeLocalContextNotFound,
CodeLocalUnimplemented, CodeLocalProfileNotFound,
CodeKBIDRequired, CodeKBNotFound,
CodeProjectLinkCorrupt,
CodeUserAborted, CodeUploadFileNotFound,
@@ -308,3 +442,17 @@ func ClassifyHTTPErrorOutputs() []ErrorCode {
CodeNetworkError, // non-HTTP error
}
}
// IsCancelled reports whether err is a context cancellation, either via
// the context itself or via wrapped CancelError / context.Canceled /
// context.DeadlineExceeded. Used by streaming commands to distinguish
// SIGINT-driven shutdown from real errors.
func IsCancelled(ctx context.Context, err error) bool {
if errors.Is(err, context.Canceled) {
return true
}
if ctx.Err() == context.Canceled {
return true
}
return false
}
+31
View File
@@ -0,0 +1,31 @@
package cmdutil
import (
"testing"
)
func TestErrorToDetail_NilSafe(t *testing.T) {
if got := ErrorToDetail(nil); got != nil {
t.Errorf("ErrorToDetail(nil) should return nil; got %v", got)
}
}
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")
if err.RetryCommand != "weknora auth login --host https://kb.example.com" {
t.Errorf("RetryCommand not set; got %q", err.RetryCommand)
}
if err.Hint != "run `weknora auth login`" {
t.Errorf("Hint changed unexpectedly; got %q", err.Hint)
}
}
func TestError_RetryCommand_EmptyByDefault(t *testing.T) {
err := NewError(CodeResourceAlreadyExists, "kb name exists")
if err.RetryCommand != "" {
t.Errorf("RetryCommand should default empty; got %q", err.RetryCommand)
}
}
+69
View File
@@ -34,3 +34,72 @@ func TestClassifyHTTPError(t *testing.T) {
})
}
}
func TestClassifyHTTPError_500NotFoundRescue(t *testing.T) {
// Server's 1003 = ErrNotFound is the only typed "not found" code we
// rescue. 1007 = ErrInternalServer is the catch-all bucket — its
// presence around a "not found"-shaped message reflects a server-side
// classification gap, not an authoritative not-found signal, so we
// must NOT silently re-route it.
err := fmt.Errorf("HTTP error 500: %s", `{"error":{"code":1003,"message":"Knowledge not found"},"success":false}`)
if got := ClassifyHTTPError(err); got != CodeResourceNotFound {
t.Errorf("expected resource.not_found rescue for code 1003; got %v", got)
}
}
// TestClassifyHTTPError_500GenericCode_StaysServerError pins the round-9
// finding: code 1007 is server's generic ErrInternalServer bucket
// (validation errors, DB failures, etc.), NOT a not-found signal. Even
// when its message text contains "not found", rescuing it would mis-route
// e.g. a 10k-char KB name (SQLSTATE 22001) as resource.not_found.
func TestClassifyHTTPError_500GenericCode_StaysServerError(t *testing.T) {
cases := []struct {
name string
body string
}{
{
name: "code 1007 with 'not found' in message",
body: `HTTP error 500: {"error":{"code":1007,"message":"knowledge base not found"},"success":false}`,
},
{
name: "code 1007 with SQLSTATE",
body: `HTTP error 500: {"error":{"code":1007,"message":"value too long for type character varying(255) (SQLSTATE 22001)"},"success":false}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := fmt.Errorf("%s", tc.body)
if got := ClassifyHTTPError(err); got != CodeServerError {
t.Errorf("expected server.error for generic code 1007; got %v", got)
}
})
}
}
func TestClassifyHTTPError_500Generic_StaysServerError(t *testing.T) {
cases := []struct {
name string
body string
}{
{
name: "generic 500",
body: "HTTP error 500: internal server error",
},
{
name: "config file not found in stack trace",
body: "HTTP error 500: panic: config file not found in /etc/app/config.yaml",
},
{
name: "not found substring without server code",
body: `HTTP error 500: {"message":"something not found","other":true}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := fmt.Errorf("%s", tc.body)
if got := ClassifyHTTPError(err); got != CodeServerError {
t.Errorf("expected server.error for generic 500; got %v", got)
}
})
}
}
+89 -7
View File
@@ -4,15 +4,42 @@ import (
"errors"
"fmt"
"io"
"github.com/Tencent/WeKnora/cli/internal/output"
)
// globalFormatMode tracks the resolved --format value for the current invocation.
// Set by cmd/root.go in PersistentPreRunE; used by PrintError to choose text vs envelope.
var globalFormatMode string
// SetFormatMode records the resolved --format mode for the current invocation.
// Called by cmd/root.go PersistentPreRunE after FormatOptions.ResolveDefault.
func SetFormatMode(mode string) {
globalFormatMode = mode
}
// globalProfile tracks the resolved profile name for the current invocation.
// Set by cmd/root.go in PersistentPreRunE via SetProfile; read by Emit and
// init events to populate envelope.profile / NDJSON init.profile.
var globalProfile string
// SetProfile records the resolved profile name for the current invocation.
// Called by cmd/root.go PersistentPreRunE after SetFormatMode.
func SetProfile(name string) { globalProfile = name }
// GetProfile returns the profile name recorded for the current invocation.
// Empty string when nothing is configured (omitempty fields suppress the field).
func GetProfile() string { return globalProfile }
// ExitCode maps an error to the documented CLI exit code.
// - 0 success
// - 1 generic / unknown typed error - fallback bucket: resource.already_exists,
// resource.locked, local.*, mcp.*, operation.failed, server.session_create_failed
// (workflow-level, see special case below), and any code outside the named
// buckets below
// - 2 flag / argument problem (cobra parse / unknown subcommand)
// - 2 cobra-parse problem (unrecognised flag, arg-count violation) —
// typed input.unknown_subcommand from the guard maps to exit 5
// (input.* bucket); only ungated cobra prose lands here
// - 3 auth.*
// - 4 resource.not_found
// - 5 input.* (other than confirmation_required)
@@ -64,14 +91,31 @@ func ExitCode(err error) int {
return 1
}
// PrintError writes err to w (typically stderr) as `code: message\nhint:
// ...`. Typed *Error values surface their Hint as a second line so users
// see the actionable next-step. Falls through to defaultHint when the
// caller didn't set one.
// PrintError writes err to w (typically stderr) in dual mode:
// - text/human: code: msg\nhint: ...\nretry: ...
// - json/ndjson: {ok:false, error:{...}, _notice?:...}
//
// Mode is read from globalFormatMode (set by root PersistentPreRunE).
func PrintError(w io.Writer, err error) {
if err == nil || errors.Is(err, SilentError) {
return
}
// Typed *Error with Silent=true suppresses stderr emit while preserving
// the Code for ExitCode. Used by batch paths that already wrote per-item
// detail to stdout (cmdutil.RunBatch) — emitting a summary envelope on
// stderr would duplicate the failure signal.
if typed := AsError(err); typed != nil && typed.Silent {
return
}
if globalFormatMode == "json" || globalFormatMode == "ndjson" {
printErrorEnvelope(w, err)
return
}
printErrorProse(w, err)
}
func printErrorProse(w io.Writer, err error) {
fmt.Fprintln(w, err.Error())
var typed *Error
if errors.As(err, &typed) {
@@ -82,9 +126,20 @@ func PrintError(w io.Writer, err error) {
if hint != "" {
fmt.Fprintf(w, "hint: %s\n", hint)
}
retry := typed.RetryCommand
if retry == "" {
retry = defaultRetryCommand(typed.Code)
}
if retry != "" {
fmt.Fprintf(w, "retry: %s\n", retry)
}
}
}
func printErrorEnvelope(w io.Writer, err error) {
_ = output.WriteErrorEnvelope(w, ErrorToDetail(err), false)
}
// defaultHint returns a canonical actionable hint for known error codes
// when the call site didn't set one. `auth.unauthenticated` always points
// at `weknora auth login` - covers the broad surface (auth status / kb
@@ -98,9 +153,9 @@ func defaultHint(code ErrorCode) string {
case CodeAuthTokenExpired:
return "your session expired; run `weknora auth login` to re-authenticate"
case CodeAuthForbidden:
return "active context lacks permission for this resource"
return "active profile lacks permission for this resource"
case CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch:
return "verify tenant context with `weknora auth status`"
return "verify tenant profile with `weknora auth status`"
case CodeNetworkError:
return "check base URL reachability with `weknora doctor`"
case CodeServerIncompatibleVersion:
@@ -142,3 +197,30 @@ func defaultHint(code ErrorCode) string {
}
return ""
}
// defaultRetryCommand returns canonical retry argv for known codes.
// Empty string for codes without a stable canonical retry.
// Symmetric counterpart to defaultHint.
func defaultRetryCommand(code ErrorCode) string {
switch code {
case CodeAuthUnauthenticated, CodeAuthBadCredential, CodeAuthTokenExpired:
return "weknora auth login"
case CodeKBIDRequired:
return "weknora link"
case CodeNetworkError, CodeServerTimeout:
return "weknora doctor"
case CodeProjectLinkCorrupt:
return "weknora link" // 重新绑定
case CodeLocalConfigCorrupt:
// 删 config + 重 login 是两步;prose hint 已说明,retry argv 留空
return ""
}
return ""
}
// 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) }
+63
View File
@@ -3,6 +3,7 @@ package cmdutil
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -58,3 +59,65 @@ func TestPrintError(t *testing.T) {
assert.Contains(t, buf.String(), "no creds")
})
}
func TestPrintError_JSONMode_WritesEnvelope(t *testing.T) {
t.Cleanup(func() { SetFormatMode("") })
SetFormatMode("json")
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
WithHint("re-run with -y/--yes").
WithRetryCommand("weknora kb delete kb_x -y")
var buf bytes.Buffer
PrintError(&buf, err)
got := buf.String()
if !strings.Contains(got, `"ok":false`) {
t.Errorf("expected envelope ok:false; got %q", got)
}
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)
}
}
func TestPrintError_JSONMode_IncludesRetryAfter(t *testing.T) {
t.Cleanup(func() { SetFormatMode("") })
SetFormatMode("json")
err := NewError(CodeServerRateLimited, "rate limited").
WithRetryAfter(30)
var buf bytes.Buffer
PrintError(&buf, err)
got := buf.String()
if !strings.Contains(got, `"retry_after_seconds":30`) {
t.Errorf("expected retry_after_seconds:30; got %q", got)
}
}
func TestPrintError_TextMode_WritesProse(t *testing.T) {
t.Cleanup(func() { SetFormatMode("") })
SetFormatMode("human")
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
WithHint("re-run with -y/--yes").
WithRetryCommand("weknora kb delete kb_x -y")
var buf bytes.Buffer
PrintError(&buf, err)
got := buf.String()
if !strings.Contains(got, "input.confirmation_required: kb delete kb_x requires confirmation") {
t.Errorf("expected prose code:message line; got %q", got)
}
if !strings.Contains(got, "hint: re-run with -y/--yes") {
t.Errorf("expected hint line; got %q", got)
}
if !strings.Contains(got, "retry: weknora kb delete kb_x -y") {
t.Errorf("expected retry line; got %q", got)
}
}