refactor(cli): symmetric envelope infrastructure (supersedes e623e820)
Re-introduce the agent-first symmetric envelope deleted in commite623e820(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 frome623e820are 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:
+130
-22
@@ -4,6 +4,8 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -13,24 +15,65 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/cmd/auth"
|
||||
chatcmd "github.com/Tencent/WeKnora/cli/cmd/chat"
|
||||
chunkcmd "github.com/Tencent/WeKnora/cli/cmd/chunk"
|
||||
contextcmd "github.com/Tencent/WeKnora/cli/cmd/context"
|
||||
"github.com/Tencent/WeKnora/cli/cmd/doc"
|
||||
"github.com/Tencent/WeKnora/cli/cmd/doctor"
|
||||
"github.com/Tencent/WeKnora/cli/cmd/kb"
|
||||
linkcmd "github.com/Tencent/WeKnora/cli/cmd/link"
|
||||
mcpcmd "github.com/Tencent/WeKnora/cli/cmd/mcp"
|
||||
profilecmd "github.com/Tencent/WeKnora/cli/cmd/profile"
|
||||
"github.com/Tencent/WeKnora/cli/cmd/search"
|
||||
sessioncmd "github.com/Tencent/WeKnora/cli/cmd/session"
|
||||
"github.com/Tencent/WeKnora/cli/internal/build"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
// resolveFormatEarly scans raw argv for --format before cobra's command
|
||||
// dispatch. This ensures globalFormatMode is set before any cobra-side
|
||||
// validator fires (unknown flag, arg count, etc.), so PrintError routes
|
||||
// those errors through the JSON envelope when --format json is in effect.
|
||||
//
|
||||
// Call order: resolveFormatEarly → cobra Execute → PersistentPreRunE (which
|
||||
// re-runs CheckFormatFlag and calls SetFormatMode again with the same value).
|
||||
func resolveFormatEarly(args []string) {
|
||||
var mode string
|
||||
for i, a := range args {
|
||||
if a == "--format" && i+1 < len(args) {
|
||||
mode = strings.ToLower(args[i+1])
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(a, "--format=") {
|
||||
mode = strings.ToLower(strings.TrimPrefix(a, "--format="))
|
||||
break
|
||||
}
|
||||
}
|
||||
if mode == "" {
|
||||
if v := os.Getenv("WEKNORA_FORMAT"); v != "" {
|
||||
mode = strings.ToLower(v)
|
||||
}
|
||||
}
|
||||
switch mode {
|
||||
case "json", "ndjson", "human":
|
||||
cmdutil.SetFormatMode(mode)
|
||||
case "":
|
||||
// nothing to set; leave globalFormatMode at its zero value
|
||||
default:
|
||||
// Invalid format value: promote to json so the subsequent
|
||||
// rejection error (from CheckFormatFlag) still emits as an envelope
|
||||
// rather than prose. The real validation error will still fire.
|
||||
cmdutil.SetFormatMode("json")
|
||||
}
|
||||
}
|
||||
|
||||
// Execute is the entry point invoked by main(). Returns the process exit code.
|
||||
// The passed context is wired to OS signals (SIGINT / SIGTERM) by main so
|
||||
// commands that respect cmd.Context() can run their cancellation cleanup.
|
||||
func Execute(ctx context.Context) int {
|
||||
// Resolve --format early so cobra-side errors (unknown flag, arg-count
|
||||
// violations) still route through PrintError's JSON envelope path when
|
||||
// --format json is in effect. PersistentPreRunE will call SetFormatMode
|
||||
// again after full flag parse - idempotent when the value matches.
|
||||
resolveFormatEarly(os.Args[1:])
|
||||
root := NewRootCmd(cmdutil.New())
|
||||
if err := root.ExecuteContext(ctx); err != nil {
|
||||
// Errors go to stderr. Stdout stays
|
||||
@@ -78,7 +121,7 @@ var cobraFlagErrorPrefixes = []string{
|
||||
"requires at least", // MinimumNArgs
|
||||
"requires at most", // MaximumNArgs
|
||||
"unknown flag",
|
||||
"invalid argument", // pflag type-coercion failure (e.g. --limit=foo)
|
||||
"invalid argument \"", // pflag type-coercion: `invalid argument "foo" for "--flag" flag`
|
||||
}
|
||||
|
||||
// NewRootCmd builds the cobra tree. Splitting it from Execute() lets tests
|
||||
@@ -104,11 +147,24 @@ a curated read-only MCP tool surface for AI agents.`,
|
||||
// (build commit + date).
|
||||
Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
|
||||
PersistentPreRunE: func(c *cobra.Command, args []string) error {
|
||||
// Propagate the global --context flag into the Factory for this
|
||||
// invocation only - single-shot override, no disk write.
|
||||
if v, _ := c.Flags().GetString("context"); v != "" {
|
||||
f.ContextOverride = v
|
||||
// Propagate the global --profile flag (or WEKNORA_PROFILE env) into
|
||||
// the Factory for this invocation only - single-shot override, no disk write.
|
||||
// Flag takes precedence over env; env takes precedence over config file.
|
||||
if v, _ := c.Flags().GetString("profile"); v != "" {
|
||||
f.ProfileOverride = v
|
||||
} else if v := os.Getenv("WEKNORA_PROFILE"); v != "" {
|
||||
f.ProfileOverride = v
|
||||
}
|
||||
// Pin --format mode for cmdutil.PrintError envelope vs prose decision.
|
||||
// Safe on commands that don't register --format: CheckFormatFlag returns
|
||||
// {Mode:""}, ResolveDefault falls back to TTY detection.
|
||||
if fopts, err := cmdutil.CheckFormatFlag(c); err == nil && fopts != nil {
|
||||
fopts.FromEnv()
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cmdutil.SetFormatMode(string(fopts.Mode))
|
||||
}
|
||||
// Record the resolved profile for envelope.profile and NDJSON init.profile.
|
||||
cmdutil.SetProfile(f.ActiveProfile())
|
||||
// Resolve --log-level / WEKNORA_LOG_LEVEL and apply to the SDK
|
||||
// debug logger before any SDK call is made. Returns a typed error
|
||||
// when --log-level was passed explicitly with an invalid value
|
||||
@@ -131,7 +187,7 @@ a curated read-only MCP tool surface for AI agents.`,
|
||||
cmd.AddCommand(search.NewCmdSearch(f))
|
||||
cmd.AddCommand(doctor.NewCmd(f))
|
||||
cmd.AddCommand(kb.NewCmd(f))
|
||||
cmd.AddCommand(contextcmd.NewCmd(f))
|
||||
cmd.AddCommand(profilecmd.NewCmd(f))
|
||||
cmd.AddCommand(linkcmd.NewCmd(f))
|
||||
cmd.AddCommand(linkcmd.NewCmdUnlink())
|
||||
cmd.AddCommand(doc.NewCmd(f))
|
||||
@@ -141,6 +197,7 @@ a curated read-only MCP tool surface for AI agents.`,
|
||||
cmd.AddCommand(agentcmd.NewCmd(f))
|
||||
cmd.AddCommand(chunkcmd.NewCmdChunk(f))
|
||||
cmd.AddCommand(mcpcmd.NewCmd(f))
|
||||
installUnknownSubcommandGuard(cmd)
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -150,17 +207,20 @@ a curated read-only MCP tool surface for AI agents.`,
|
||||
func addGlobalFlags(cmd *cobra.Command) {
|
||||
pf := cmd.PersistentFlags()
|
||||
pf.BoolP("yes", "y", false, "Skip confirmation prompts on destructive operations")
|
||||
pf.String("context", "", "Override the active context for this invocation (no disk write)")
|
||||
pf.String("profile", "", "Override the active profile for this invocation (no disk write)")
|
||||
// --log-level is registered as a persistent (global) flag because the SDK
|
||||
// debug logger is initialised once at factory time before any command runs,
|
||||
// so the flag must be visible on all subcommands. Unlike --format (which
|
||||
// only some commands honour and is registered per-command, Method D),
|
||||
// --log-level applies uniformly to all SDK calls.
|
||||
cmdutil.AddLogLevelFlag(cmd)
|
||||
// NOTE: --format is registered per-command (cmdutil.AddFormatFlag in each
|
||||
// command's NewCmd). Only commands that actually honor --format register
|
||||
// it; cobra rejects --format on others with "unknown flag" rather than
|
||||
// silently ignoring it.
|
||||
// --format and --jq are persistent globals so unknown-subcommand paths
|
||||
// (e.g. `weknora fooo --format json`) reach the typed-envelope guard
|
||||
// instead of being rejected as "unknown flag" exit 2 by cobra. Commands
|
||||
// that don't produce JSON output (e.g. `completion bash`) ignore the flag
|
||||
// rather than error — the unified agent contract is worth the trade.
|
||||
pf.String("format", "", "Output format: human | json | ndjson (default: json)")
|
||||
pf.StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --format json|ndjson)")
|
||||
}
|
||||
|
||||
// versionFields enumerates the fields surfaced for `--format json` discovery on
|
||||
@@ -182,15 +242,11 @@ func newVersionCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
v, commit, date := build.Info()
|
||||
if fopts.WantsJSON() {
|
||||
return format.WriteJSONFiltered(
|
||||
c.OutOrStdout(),
|
||||
map[string]string{
|
||||
"version": v,
|
||||
"commit": commit,
|
||||
"date": date,
|
||||
},
|
||||
nil, fopts.JQ,
|
||||
)
|
||||
return fopts.Emit(c.OutOrStdout(), map[string]string{
|
||||
"version": v,
|
||||
"commit": commit,
|
||||
"date": date,
|
||||
}, nil)
|
||||
}
|
||||
fmt.Fprintf(c.OutOrStdout(), "weknora %s (commit %s, built %s)\n", v, commit, date)
|
||||
return nil
|
||||
@@ -199,3 +255,55 @@ func newVersionCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmdutil.AddFormatFlag(cmd, versionFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// installUnknownSubcommandGuard recursively attaches a RunE that emits a typed
|
||||
// envelope error when a parent command is invoked with no matching subcommand
|
||||
// (e.g. `weknora kb bogus`). Without this, cobra falls back to a free-form
|
||||
// "unknown command" string error via legacyArgs validation.
|
||||
//
|
||||
// cobra's legacyArgs (args.go) fires at Find() time when Args == nil:
|
||||
// for root commands it rejects any unrecognised positional before RunE runs.
|
||||
// Setting cobra.ArbitraryArgs bypasses that check so our RunE receives the
|
||||
// unknown arg and can emit the typed envelope instead.
|
||||
func installUnknownSubcommandGuard(cmd *cobra.Command) {
|
||||
if cmd.HasSubCommands() && cmd.Run == nil && cmd.RunE == nil {
|
||||
cmd.RunE = unknownSubcommandRunE
|
||||
cmd.Args = cobra.ArbitraryArgs
|
||||
}
|
||||
for _, c := range cmd.Commands() {
|
||||
installUnknownSubcommandGuard(c)
|
||||
}
|
||||
}
|
||||
|
||||
func unknownSubcommandRunE(cmd *cobra.Command, args []string) error {
|
||||
// Group command invoked with no subcommand (e.g. `weknora kb`):
|
||||
// show help rather than emit a confusing `unknown ""` error.
|
||||
if len(args) == 0 {
|
||||
return cmd.Help()
|
||||
}
|
||||
unknown := args[0]
|
||||
available := availableSubcommandNames(cmd)
|
||||
return cmdutil.NewError(
|
||||
cmdutil.CodeInputUnknownSubcommand,
|
||||
fmt.Sprintf("unknown subcommand %q for %q", unknown, cmd.CommandPath()),
|
||||
).
|
||||
WithHint(fmt.Sprintf("available subcommands: %s", strings.Join(available, ", "))).
|
||||
WithRetryCommand(cmd.CommandPath() + " --help").
|
||||
WithDetail(map[string]any{
|
||||
"unknown": unknown,
|
||||
"command_path": cmd.CommandPath(),
|
||||
"available": available,
|
||||
})
|
||||
}
|
||||
|
||||
func availableSubcommandNames(cmd *cobra.Command) []string {
|
||||
var names []string
|
||||
for _, c := range cmd.Commands() {
|
||||
if c.Hidden || c.Name() == "help" || c.Name() == "completion" {
|
||||
continue
|
||||
}
|
||||
names = append(names, c.Name())
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user