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
+130 -22
View File
@@ -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
}
+36 -14
View File
@@ -2,6 +2,7 @@ package cmd
import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"
@@ -31,10 +32,14 @@ func TestVersion_JSON(t *testing.T) {
root.SetOut(&out)
require.NoError(t, root.Execute())
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{`), "expected bare JSON object, got: %q", got)
assert.Contains(t, got, `"version":"`)
assert.NotContains(t, got, `"ok":`)
assert.NotContains(t, got, `"data":`)
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "expected valid JSON envelope, got: %q", got)
assert.True(t, env.OK, "envelope.ok must be true")
assert.NotNil(t, env.Data, "envelope.data must be present")
assert.Contains(t, got, `"version":`)
}
// Smoke test for cmdutil.ExitCode wiring; full coverage lives in
@@ -52,14 +57,19 @@ func TestExecute_ExitCodeSurface(t *testing.T) {
// provides them).
func TestMapCobraError_PinnedPrefixes(t *testing.T) {
t.Run("unknown command", func(t *testing.T) {
// With installUnknownSubcommandGuard in place, unknown root-level
// subcommands now return a typed *cmdutil.Error (CodeInputUnknownSubcommand)
// rather than cobra's legacy "unknown command" text. The cobraFlagErrorPrefixes
// fallback remains for any path that bypasses the guard.
root := NewRootCmd(cmdutil.New())
root.SetArgs([]string{"bogus"})
root.SetErr(&bytes.Buffer{})
root.SetOut(&bytes.Buffer{})
err := root.Execute()
require.Error(t, err)
assert.True(t, strings.HasPrefix(err.Error(), "unknown command "),
"cobra unknown-command prefix changed; update cobraFlagErrorPrefixes. got: %q", err.Error())
typed := cmdutil.AsError(err)
require.NotNil(t, typed, "expected typed *cmdutil.Error; got %T: %v", err, err)
assert.Equal(t, cmdutil.CodeInputUnknownSubcommand, typed.Code)
})
t.Run("required flag(s)", func(t *testing.T) {
@@ -111,21 +121,33 @@ func TestMapCobraError(t *testing.T) {
var fe *cmdutil.FlagError
assert.True(t, errors.As(err, &fe))
})
t.Run("pflag invalid argument wraps as FlagError", func(t *testing.T) {
// pflag emits: `invalid argument "foo" for "--limit" flag`
err := MapCobraError(errors.New(`invalid argument "foo" for "--limit" flag: strconv.ParseInt: parsing "foo": invalid syntax`))
var fe *cmdutil.FlagError
assert.True(t, errors.As(err, &fe), "pflag-shaped invalid argument should become FlagError")
})
t.Run("domain invalid argument does not wrap", func(t *testing.T) {
// Domain code writing fmt.Errorf("invalid argument: ...") must NOT become FlagError.
err := MapCobraError(errors.New("invalid argument: kb id cannot be empty"))
var fe *cmdutil.FlagError
assert.False(t, errors.As(err, &fe), "domain-shaped invalid argument must not become FlagError")
})
}
// TestRoot_ContextFlagPropagation guards the cobra → Factory wiring of the
// global --context flag. Without this, a future refactor that disconnects
// PersistentPreRun from f.ContextOverride would only fail e2e - the
// per-package TestFactory_ContextOverride only proves the Factory side.
func TestRoot_ContextFlagPropagation(t *testing.T) {
// TestRoot_ProfileFlagPropagation guards the cobra → Factory wiring of the
// global --profile flag. Without this, a future refactor that disconnects
// PersistentPreRun from f.ProfileOverride would only fail e2e - the
// per-package TestFactory_ProfileOverride only proves the Factory side.
func TestRoot_ProfileFlagPropagation(t *testing.T) {
cases := []struct {
name string
args []string
want string
}{
{"no flag", []string{"version"}, ""},
{"global before subcmd", []string{"--context", "staging", "version"}, "staging"},
{"--context=value form", []string{"--context=prod", "version"}, "prod"},
{"global before subcmd", []string{"--profile", "staging", "version"}, "staging"},
{"--profile=value form", []string{"--profile=prod", "version"}, "prod"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -135,7 +157,7 @@ func TestRoot_ContextFlagPropagation(t *testing.T) {
root.SetOut(&bytes.Buffer{})
root.SetErr(&bytes.Buffer{})
require.NoError(t, root.Execute())
assert.Equal(t, tc.want, f.ContextOverride)
assert.Equal(t, tc.want, f.ProfileOverride)
})
}
}
+54
View File
@@ -0,0 +1,54 @@
package cmd
import (
"bytes"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// TestAgentInvoke_NowReturnsUnknownSubcommand verifies the deleted v0.6
// command emits a typed envelope rather than cobra's free-form exit-2 prose.
func TestAgentInvoke_NowReturnsUnknownSubcommand(t *testing.T) {
root := NewRootCmd(cmdutil.New())
root.SetArgs([]string{"agent", "invoke", "ag_x", "q"})
root.SetOut(&bytes.Buffer{})
root.SetErr(&bytes.Buffer{})
err := root.Execute()
ce := cmdutil.AsError(err)
if ce == nil || ce.Code != cmdutil.CodeInputUnknownSubcommand {
t.Errorf("expected CodeInputUnknownSubcommand, got %v", err)
}
}
func TestUnknownSubcommand_EmitsTypedEnvelope(t *testing.T) {
t.Cleanup(func() { cmdutil.SetFormatMode("") })
root := NewRootCmd(cmdutil.New())
var stderr bytes.Buffer
root.SetErr(&stderr)
root.SetArgs([]string{"fooo"})
err := root.Execute()
if err == nil {
t.Fatal("expected unknown-subcommand error, got nil")
}
// Force JSON mode for PrintError regardless of how PersistentPreRunE
// resolved it during the test invocation (no TTY in test buffer).
cmdutil.SetFormatMode("json")
mapped := MapCobraError(err)
cmdutil.PrintError(&stderr, mapped)
got := stderr.String()
if !strings.Contains(got, `"type":"input.unknown_subcommand"`) {
t.Errorf("expected typed code; got %q", got)
}
if !strings.Contains(got, `"available":[`) {
t.Errorf("expected detail.available[]; got %q", got)
}
if !strings.Contains(got, `"retry_command":"weknora --help"`) {
t.Errorf("expected retry_command; got %q", got)
}
}