2026-05-06 06:22:36 +00:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
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
2026-05-21 10:40:06 +00:00
|
|
|
"encoding/json"
|
2026-05-06 06:22:36 +00:00
|
|
|
"errors"
|
|
|
|
|
"strings"
|
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func TestRoot_Help(t *testing.T) {
|
|
|
|
|
var out bytes.Buffer
|
2026-05-08 08:13:58 +00:00
|
|
|
root := NewRootCmd(cmdutil.New())
|
2026-05-06 06:22:36 +00:00
|
|
|
root.SetArgs([]string{"--help"})
|
|
|
|
|
root.SetOut(&out)
|
|
|
|
|
require.NoError(t, root.Execute())
|
|
|
|
|
got := out.String()
|
|
|
|
|
assert.Contains(t, got, "weknora")
|
|
|
|
|
assert.Contains(t, got, "version")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestVersion_JSON(t *testing.T) {
|
|
|
|
|
var out bytes.Buffer
|
2026-05-08 08:13:58 +00:00
|
|
|
root := NewRootCmd(cmdutil.New())
|
2026-05-17 17:38:16 +00:00
|
|
|
root.SetArgs([]string{"version", "--format", "json"})
|
2026-05-06 06:22:36 +00:00
|
|
|
root.SetOut(&out)
|
|
|
|
|
require.NoError(t, root.Execute())
|
|
|
|
|
got := out.String()
|
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
2026-05-21 10:40:06 +00:00
|
|
|
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":`)
|
2026-05-06 06:22:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Smoke test for cmdutil.ExitCode wiring; full coverage lives in
|
|
|
|
|
// cli/internal/cmdutil/exit_test.go.
|
|
|
|
|
func TestExecute_ExitCodeSurface(t *testing.T) {
|
|
|
|
|
assert.Equal(t, 0, cmdutil.ExitCode(nil))
|
|
|
|
|
assert.Equal(t, 1, cmdutil.ExitCode(assert.AnError))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestMapCobraError_PinnedPrefixes guards against silent breakage if cobra
|
|
|
|
|
// changes the message format of unknown-command / required-flag / arg-count
|
|
|
|
|
// errors. Cobra v1.10 emits these via fmt.Errorf in args.go and command.go;
|
|
|
|
|
// if a future bump alters the wording, this test fails loudly so we update
|
|
|
|
|
// cobraFlagErrorPrefixes (or migrate to typed sentinels if cobra ever
|
|
|
|
|
// provides them).
|
|
|
|
|
func TestMapCobraError_PinnedPrefixes(t *testing.T) {
|
|
|
|
|
t.Run("unknown command", func(t *testing.T) {
|
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
2026-05-21 10:40:06 +00:00
|
|
|
// 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.
|
2026-05-08 08:13:58 +00:00
|
|
|
root := NewRootCmd(cmdutil.New())
|
2026-05-06 06:22:36 +00:00
|
|
|
root.SetArgs([]string{"bogus"})
|
|
|
|
|
root.SetErr(&bytes.Buffer{})
|
|
|
|
|
root.SetOut(&bytes.Buffer{})
|
|
|
|
|
err := root.Execute()
|
|
|
|
|
require.Error(t, err)
|
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
2026-05-21 10:40:06 +00:00
|
|
|
typed := cmdutil.AsError(err)
|
|
|
|
|
require.NotNil(t, typed, "expected typed *cmdutil.Error; got %T: %v", err, err)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeInputUnknownSubcommand, typed.Code)
|
2026-05-06 06:22:36 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
t.Run("required flag(s)", func(t *testing.T) {
|
refactor(cli): drop aiclient package; align AGENTS.md with mainstream
Survey of 10 mainstream CLIs (gh, lark, stripe, vercel, supabase, aws,
azure, gcloud, openai/codex, github-copilot-cli) showed env-gated
per-command --help blurbs are a Stripe-only pattern; gh uses env detect
for telemetry only, and lark relies on installed agent Skills + MCP.
Our cmd/mcp/serve already covers the dominant 2025/26 path, so
internal/aiclient/ (136 LOC + 38 callsites) is net maintenance burden
without precedent.
- Drop internal/aiclient/ entirely (annotations + detect + tests)
- Remove 38 SetAgentHelp callsites + agentAwareHelpFunc / SetHelpFunc
wiring in cmd/root.go
- Migrate 4 command-level rules to standard Long help (visible to all,
not env-gated): doc upload mode mutex, kb edit at-least-one,
kb pin idempotent, search chunks channel mutex
- Rewrite AGENTS.md as a developer guide (gh-style 6 H2 / 167 lines):
audience preamble + Build / Architecture / Command Structure /
Testing / Code Style / Error Handling. Drops sections absent in
surveyed projects (Commit & PR Conventions, Who Uses This CLI)
- Clean 14 internal doc refs (ADR-N, spec §X, v0.X) in source comments
and docs that pointed at docs/superpowers/ — that directory is
local-only / uncommitted, so refs are dead for outside readers
- Drop forward-looking "once v0.2 ships" from README
2026-05-14 18:16:45 +00:00
|
|
|
// Self-contained probe - the pin must hold even before resource commands
|
2026-05-06 06:22:36 +00:00
|
|
|
// register their own required flags. RunE is required: without it cobra
|
|
|
|
|
// treats the command as a parent and skips ValidateRequiredFlags.
|
|
|
|
|
probe := &cobra.Command{Use: "probe", RunE: func(*cobra.Command, []string) error { return nil }}
|
|
|
|
|
probe.Flags().String("host", "", "")
|
|
|
|
|
require.NoError(t, probe.MarkFlagRequired("host"))
|
|
|
|
|
probe.SetErr(&bytes.Buffer{})
|
|
|
|
|
probe.SetOut(&bytes.Buffer{})
|
|
|
|
|
err := probe.Execute()
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.True(t, strings.HasPrefix(err.Error(), "required flag(s)"),
|
|
|
|
|
"cobra required-flag prefix changed; update cobraFlagErrorPrefixes. got: %q", err.Error())
|
|
|
|
|
})
|
|
|
|
|
|
refactor(cli): drop aiclient package; align AGENTS.md with mainstream
Survey of 10 mainstream CLIs (gh, lark, stripe, vercel, supabase, aws,
azure, gcloud, openai/codex, github-copilot-cli) showed env-gated
per-command --help blurbs are a Stripe-only pattern; gh uses env detect
for telemetry only, and lark relies on installed agent Skills + MCP.
Our cmd/mcp/serve already covers the dominant 2025/26 path, so
internal/aiclient/ (136 LOC + 38 callsites) is net maintenance burden
without precedent.
- Drop internal/aiclient/ entirely (annotations + detect + tests)
- Remove 38 SetAgentHelp callsites + agentAwareHelpFunc / SetHelpFunc
wiring in cmd/root.go
- Migrate 4 command-level rules to standard Long help (visible to all,
not env-gated): doc upload mode mutex, kb edit at-least-one,
kb pin idempotent, search chunks channel mutex
- Rewrite AGENTS.md as a developer guide (gh-style 6 H2 / 167 lines):
audience preamble + Build / Architecture / Command Structure /
Testing / Code Style / Error Handling. Drops sections absent in
surveyed projects (Commit & PR Conventions, Who Uses This CLI)
- Clean 14 internal doc refs (ADR-N, spec §X, v0.X) in source comments
and docs that pointed at docs/superpowers/ — that directory is
local-only / uncommitted, so refs are dead for outside readers
- Drop forward-looking "once v0.2 ships" from README
2026-05-14 18:16:45 +00:00
|
|
|
t.Run("accepts N arg(s) - ExactArgs", func(t *testing.T) {
|
2026-05-06 06:22:36 +00:00
|
|
|
probe := &cobra.Command{
|
|
|
|
|
Use: "probe",
|
|
|
|
|
Args: cobra.ExactArgs(1),
|
|
|
|
|
RunE: func(*cobra.Command, []string) error { return nil },
|
|
|
|
|
}
|
|
|
|
|
probe.SetArgs([]string{}) // no args, but ExactArgs(1) wants 1
|
|
|
|
|
probe.SetErr(&bytes.Buffer{})
|
|
|
|
|
probe.SetOut(&bytes.Buffer{})
|
|
|
|
|
err := probe.Execute()
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.True(t, strings.HasPrefix(err.Error(), "accepts "),
|
|
|
|
|
"cobra ExactArgs prefix changed; update cobraFlagErrorPrefixes. got: %q", err.Error())
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestMapCobraError(t *testing.T) {
|
|
|
|
|
t.Run("nil passes through", func(t *testing.T) {
|
2026-05-08 08:42:17 +00:00
|
|
|
assert.Nil(t, MapCobraError(nil))
|
2026-05-06 06:22:36 +00:00
|
|
|
})
|
|
|
|
|
t.Run("non-matching error passes through", func(t *testing.T) {
|
2026-05-08 08:42:17 +00:00
|
|
|
err := MapCobraError(assert.AnError)
|
2026-05-06 06:22:36 +00:00
|
|
|
assert.Equal(t, assert.AnError, err)
|
|
|
|
|
})
|
|
|
|
|
t.Run("unknown command wraps as FlagError", func(t *testing.T) {
|
2026-05-08 08:42:17 +00:00
|
|
|
err := MapCobraError(errors.New(`unknown command "bogus" for "weknora"`))
|
2026-05-06 06:22:36 +00:00
|
|
|
var fe *cmdutil.FlagError
|
|
|
|
|
assert.True(t, errors.As(err, &fe))
|
|
|
|
|
})
|
|
|
|
|
t.Run("required flag wraps as FlagError", func(t *testing.T) {
|
2026-05-08 08:42:17 +00:00
|
|
|
err := MapCobraError(errors.New(`required flag(s) "host" not set`))
|
2026-05-06 06:22:36 +00:00
|
|
|
var fe *cmdutil.FlagError
|
|
|
|
|
assert.True(t, errors.As(err, &fe))
|
|
|
|
|
})
|
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
2026-05-21 10:40:06 +00:00
|
|
|
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")
|
|
|
|
|
})
|
2026-05-06 06:22:36 +00:00
|
|
|
}
|
|
|
|
|
|
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
2026-05-21 10:40:06 +00:00
|
|
|
// 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) {
|
2026-05-08 08:42:17 +00:00
|
|
|
cases := []struct {
|
|
|
|
|
name string
|
|
|
|
|
args []string
|
|
|
|
|
want string
|
|
|
|
|
}{
|
|
|
|
|
{"no flag", []string{"version"}, ""},
|
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
2026-05-21 10:40:06 +00:00
|
|
|
{"global before subcmd", []string{"--profile", "staging", "version"}, "staging"},
|
|
|
|
|
{"--profile=value form", []string{"--profile=prod", "version"}, "prod"},
|
2026-05-08 08:42:17 +00:00
|
|
|
}
|
|
|
|
|
for _, tc := range cases {
|
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
|
f := cmdutil.New()
|
|
|
|
|
root := NewRootCmd(f)
|
|
|
|
|
root.SetArgs(tc.args)
|
|
|
|
|
root.SetOut(&bytes.Buffer{})
|
|
|
|
|
root.SetErr(&bytes.Buffer{})
|
|
|
|
|
require.NoError(t, root.Execute())
|
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
2026-05-21 10:40:06 +00:00
|
|
|
assert.Equal(t, tc.want, f.ProfileOverride)
|
2026-05-08 08:42:17 +00:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-05-29 12:06:53 +00:00
|
|
|
|
|
|
|
|
// resolveFormatEarly must default to the JSON envelope when no --format/env is
|
|
|
|
|
// given, so cobra-side errors (unknown flag, arg-count) — which fire before
|
|
|
|
|
// PersistentPreRunE runs ResolveDefault — emit a machine-readable envelope on
|
|
|
|
|
// stderr, not bare prose. Regression for the success-path-defaults-to-json /
|
|
|
|
|
// error-path-defaults-to-prose asymmetry.
|
|
|
|
|
func TestResolveFormatEarly_DefaultsToEnvelope(t *testing.T) {
|
|
|
|
|
cases := []struct {
|
|
|
|
|
name string
|
|
|
|
|
args []string
|
|
|
|
|
want bool // true ⇒ expect JSON envelope
|
|
|
|
|
}{
|
|
|
|
|
{"no format flag (default)", []string{"kb", "view"}, true},
|
|
|
|
|
{"explicit --format json", []string{"kb", "view", "--format", "json"}, true},
|
|
|
|
|
{"explicit --format text", []string{"kb", "view", "--format", "text"}, false},
|
|
|
|
|
}
|
|
|
|
|
for _, tc := range cases {
|
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
|
|
|
resolveFormatEarly(tc.args)
|
|
|
|
|
err := MapCobraError(errors.New("accepts 1 arg(s), received 0"))
|
|
|
|
|
var buf bytes.Buffer
|
|
|
|
|
cmdutil.PrintError(&buf, err)
|
|
|
|
|
isEnvelope := strings.HasPrefix(strings.TrimSpace(buf.String()), "{")
|
|
|
|
|
assert.Equal(t, tc.want, isEnvelope,
|
|
|
|
|
"args=%v: got %q", tc.args, buf.String())
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|