refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup

Sweep every CLI output path through the v0.7 envelope contract.

FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.

~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.

Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
  pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
  failures*}; Successes/Failures *int so explicit zero survives
  omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
  cmdutil.ClassifyContextErr collapse the three previously-duplicated
  multi-delete pipelines (doc / chunk / session) into one call site
  pattern. doc upload --recursive uses the same helpers with a per-
  file resultFn. Summary error sets Silent:true so the stderr
  envelope path doesn't duplicate the stdout batch detail (exit 1
  preserved via Code → ExitCode).

ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).

MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.

weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
  (stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
  envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
  envelope so --paginate never emits bare JSON to stdout.

Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
This commit is contained in:
nullkey
2026-05-21 18:41:56 +08:00
committed by lyingbug
parent 733bb3aaa1
commit ad150c7126
96 changed files with 2354 additions and 864 deletions
+2 -7
View File
@@ -101,17 +101,12 @@ func MergeAgentConfig(base *sdk.AgentConfig, ov AgentConfigFlags) *sdk.AgentConf
return &out
}
// skeletonCommentVersion is embedded in the skeleton header so users
// regenerating an outdated template after a schema bump can spot the
// version mismatch.
const skeletonCommentVersion = "v0.6 / 34 fields"
// GenerateAgentSkeleton writes a commented YAML template with every
// AgentConfig field at its zero value to w. Used by
// `agent create --generate-skeleton` so users get a ready-to-edit
// starting point without authoring the 34-field schema from memory.
// starting point without authoring the full schema from memory.
func GenerateAgentSkeleton(w io.Writer) error {
const skeleton = `# WeKnora AgentConfig skeleton (` + skeletonCommentVersion + `)
const skeleton = `# WeKnora AgentConfig YAML skeleton
# Edit this file and pass it to:
# weknora agent create "My Agent" --model <id> --config-file <this-file>
# Hot-path flags on the create command override values set here.
+128
View File
@@ -0,0 +1,128 @@
// Package cmdutil — batch.go provides reusable plumbing for multi-target
// mutations that emit the §4.5 batch envelope.
//
// Three pieces:
// - BatchOutcome: per-target structured outcome (preserves argv order).
// - RunBatch: drives a slice of targets through a closure, collecting
// outcomes. Stops on context cancellation; keep-going on per-item err.
// - EmitBatch: renders the outcomes — JSON/NDJSON via output.WriteBatchEnvelope,
// text via per-item "OK <id>" / "FAIL <id>: <msg>".
package cmdutil
import (
"context"
"errors"
"fmt"
"io"
"time"
"github.com/Tencent/WeKnora/cli/internal/output"
)
// BatchOutcome is one per-target result preserving argv order. Err==nil ⇒ success.
type BatchOutcome struct {
ID string
Err error
}
// RunBatch invokes op(ctx, id) for each id and collects outcomes in order.
// Per-item errors do not abort the run; context cancellation does (the
// remainder of the slice is marked with the context error).
//
// Returns (outcomes, summaryErr). summaryErr is a typed *Error with
// CodeOperationFailed when any per-item op failed, nil otherwise. Callers
// emit the outcomes before returning summaryErr so partial-success data
// reaches stdout.
func RunBatch(ctx context.Context, ids []string, op func(context.Context, string) error) ([]BatchOutcome, error) {
outcomes := make([]BatchOutcome, 0, len(ids))
failed := 0
for _, id := range ids {
select {
case <-ctx.Done():
outcomes = append(outcomes, BatchOutcome{ID: id, Err: ctx.Err()})
failed++
continue
default:
}
err := op(ctx, id)
outcomes = append(outcomes, BatchOutcome{ID: id, Err: err})
if err != nil {
failed++
}
}
if failed > 0 {
return outcomes, &Error{
Code: CodeOperationFailed,
Message: fmt.Sprintf("%d/%d operation(s) failed", failed, len(ids)),
// Silent suppresses the stderr error envelope because the caller
// already emitted the batch envelope to stdout (§4.5). The exit code
// still propagates via Error.Code → ExitCode (falls through to 1).
Silent: true,
}
}
return outcomes, nil
}
// EmitBatch writes the per-item outcomes per --format. JSON/NDJSON emit
// the §4.5 batch envelope; human/text mode emits per-line "OK <id>" /
// "FAIL <id>: <msg>".
//
// resultFn builds the per-item Result map for successes; nil ⇒ omit.
// A typical resultFn returns map[string]any{"deleted_at": time.Now()....}.
//
// Callers wanting a stable per-item timestamp pass time.Now() via
// resultFn so tests can pin the clock with SetDeletedAtClock.
func EmitBatch(outcomes []BatchOutcome, fopts *FormatOptions, w io.Writer, resultFn func(id string) any) error {
if fopts.WantsJSON() {
items := make([]output.BatchItem, len(outcomes))
for i, o := range outcomes {
items[i] = output.BatchItem{ID: o.ID, OK: o.Err == nil}
if o.Err != nil {
items[i].Error = ErrorToDetail(o.Err)
} else if resultFn != nil {
items[i].Result = resultFn(o.ID)
}
}
return output.WriteBatchEnvelope(w, items, fopts.TTY, globalProfile)
}
for _, o := range outcomes {
if o.Err == nil {
fmt.Fprintf(w, "OK %s\n", o.ID)
continue
}
fmt.Fprintf(w, "FAIL %s: %s\n", o.ID, o.Err)
}
return nil
}
// deletedAtClock is the clock source for DeletedAtNow. Overridable in tests
// to make per-item timestamps deterministic.
var deletedAtClock = time.Now
// DeletedAtNow is the canonical resultFn for delete batches that report
// {deleted_at: <RFC3339>} per success. Tests can freeze the clock via
// SetDeletedAtClock(func() time.Time { return fixed }).
func DeletedAtNow(id string) any {
return map[string]any{"deleted_at": deletedAtClock().Format(time.RFC3339)}
}
// SetDeletedAtClock overrides the time source used by DeletedAtNow. Returns
// a cleanup func that restores time.Now. For test use only.
func SetDeletedAtClock(clock func() time.Time) func() {
deletedAtClock = clock
return func() { deletedAtClock = time.Now }
}
// ClassifyContextErr maps a context error to the appropriate operation code.
// Falls back to CodeOperationFailed when err is nil or not a context signal.
func ClassifyContextErr(err error) ErrorCode {
switch {
case errors.Is(err, context.Canceled):
return CodeOperationCancelled
case errors.Is(err, context.DeadlineExceeded):
return CodeOperationTimeout
default:
return CodeOperationFailed
}
}
+193
View File
@@ -0,0 +1,193 @@
package cmdutil
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
)
// TestRunBatch_AllSuccess verifies that 3 ids all succeed: outcomes are
// ordered and summaryErr is nil.
func TestRunBatch_AllSuccess(t *testing.T) {
ids := []string{"a", "b", "c"}
op := func(_ context.Context, id string) error { return nil }
outcomes, err := RunBatch(context.Background(), ids, op)
if err != nil {
t.Fatalf("expected nil summaryErr; got %v", err)
}
if len(outcomes) != 3 {
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
}
for i, o := range outcomes {
if o.ID != ids[i] {
t.Errorf("outcomes[%d].ID = %q, want %q", i, o.ID, ids[i])
}
if o.Err != nil {
t.Errorf("outcomes[%d].Err = %v, want nil", i, o.Err)
}
}
}
// TestRunBatch_PartialFailure verifies that one failing id yields summaryErr
// with CodeOperationFailed while successful outcomes are preserved.
func TestRunBatch_PartialFailure(t *testing.T) {
ids := []string{"ok1", "fail", "ok2"}
errFail := errors.New("something went wrong")
op := func(_ context.Context, id string) error {
if id == "fail" {
return errFail
}
return nil
}
outcomes, summaryErr := RunBatch(context.Background(), ids, op)
if summaryErr == nil {
t.Fatal("expected non-nil summaryErr")
}
typedErr := AsError(summaryErr)
if typedErr == nil {
t.Fatalf("summaryErr is not *Error; got %T %v", summaryErr, summaryErr)
}
if typedErr.Code != CodeOperationFailed {
t.Errorf("summaryErr.Code = %q, want %q", typedErr.Code, CodeOperationFailed)
}
if !strings.Contains(typedErr.Message, "1/3") {
t.Errorf("summaryErr.Message = %q, expected 1/3 ratio", typedErr.Message)
}
if len(outcomes) != 3 {
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
}
if outcomes[1].Err != errFail {
t.Errorf("outcomes[1].Err = %v, want %v", outcomes[1].Err, errFail)
}
if outcomes[0].Err != nil || outcomes[2].Err != nil {
t.Error("expected outcomes[0] and outcomes[2] to have nil Err")
}
}
// TestRunBatch_ContextCancellation verifies that once the context is cancelled,
// remaining ids are marked with the context error without calling op.
func TestRunBatch_ContextCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ids := []string{"first", "second", "third"}
opCalled := 0
op := func(ctx context.Context, id string) error {
opCalled++
if id == "first" {
cancel() // cancel after the first item
}
return nil
}
outcomes, summaryErr := RunBatch(ctx, ids, op)
// summaryErr must be non-nil (cancelled items counted as failed)
if summaryErr == nil {
t.Fatal("expected non-nil summaryErr due to cancellation")
}
if len(outcomes) != 3 {
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
}
// "second" and "third" should have ctx.Err() as their error
for _, id := range []string{"second", "third"} {
var found *BatchOutcome
for i := range outcomes {
if outcomes[i].ID == id {
found = &outcomes[i]
break
}
}
if found == nil {
t.Fatalf("missing outcome for id %q", id)
}
if !errors.Is(found.Err, context.Canceled) {
t.Errorf("outcome[%s].Err = %v, want context.Canceled", id, found.Err)
}
}
}
// TestEmitBatch_JSON_Envelope verifies that the JSON path emits a valid §4.5
// batch envelope with correct ok/error/result fields.
func TestEmitBatch_JSON_Envelope(t *testing.T) {
outcomes := []BatchOutcome{
{ID: "x", Err: nil},
{ID: "y", Err: NewError(CodeResourceNotFound, "not found")},
}
fopts := &FormatOptions{Mode: FormatJSON, TTY: false}
var buf bytes.Buffer
err := EmitBatch(outcomes, fopts, &buf, func(id string) any {
return map[string]any{"deleted_at": "2026-01-01T00:00:00Z"}
})
if err != nil {
t.Fatalf("EmitBatch error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"ok":true`) {
t.Errorf("expected ok:true in envelope; got %q", got)
}
if !strings.Contains(got, `"id":"x"`) {
t.Errorf("expected id:x; got %q", got)
}
if !strings.Contains(got, `"id":"y"`) {
t.Errorf("expected id:y; got %q", got)
}
if !strings.Contains(got, `"deleted_at":"2026-01-01T00:00:00Z"`) {
t.Errorf("expected result.deleted_at for x; got %q", got)
}
if !strings.Contains(got, `"type":"resource.not_found"`) {
t.Errorf("expected error.type for y; got %q", got)
}
// meta.failures should be 1
if !strings.Contains(got, `"failures":1`) {
t.Errorf("expected meta.failures:1; got %q", got)
}
}
// TestDeletedAtNow_FixedClock verifies that SetDeletedAtClock overrides the
// timestamp used by DeletedAtNow, making per-item values deterministic in tests.
func TestDeletedAtNow_FixedClock(t *testing.T) {
fixed := time.Date(2026, 5, 20, 0, 0, 0, 0, time.UTC)
defer SetDeletedAtClock(func() time.Time { return fixed })()
got := DeletedAtNow("irrelevant")
m, ok := got.(map[string]any)
if !ok {
t.Fatalf("DeletedAtNow returned %T, want map[string]any", got)
}
want := fixed.Format(time.RFC3339)
if m["deleted_at"] != want {
t.Errorf("deleted_at = %q, want %q", m["deleted_at"], want)
}
}
// TestEmitBatch_Text_PerLine verifies that the human/text path emits
// "OK <id>" / "FAIL <id>: <msg>" per line.
func TestEmitBatch_Text_PerLine(t *testing.T) {
outcomes := []BatchOutcome{
{ID: "x", Err: nil},
{ID: "y", Err: fmt.Errorf("boom")},
}
fopts := &FormatOptions{Mode: FormatHuman}
var buf bytes.Buffer
err := EmitBatch(outcomes, fopts, &buf, nil)
if err != nil {
t.Fatalf("EmitBatch error: %v", err)
}
got := buf.String()
if !strings.Contains(got, "OK x\n") {
t.Errorf("expected 'OK x' line; got %q", got)
}
if !strings.Contains(got, "FAIL y: boom\n") {
t.Errorf("expected 'FAIL y: boom' line; got %q", got)
}
}
+14 -4
View File
@@ -13,7 +13,10 @@ import (
// — one -y confirms all items in the batch.
//
// Pass n = total count of items about to be deleted.
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string, n int) error {
// 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 {
if yes {
return nil
}
@@ -21,7 +24,9 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string,
return NewError(
CodeInputConfirmationRequired,
fmt.Sprintf("delete %d %s(s) requires explicit confirmation: re-run with -y/--yes", n, what),
)
).
WithRetryCommand(retryCmd).
WithRisk("destructive", action)
}
ok, err := p.Confirm(fmt.Sprintf("Delete %d %s(s)? This cannot be undone.", n, what), false)
if err != nil {
@@ -51,7 +56,10 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string,
// proceed. See cli/README.md "Exit codes".
//
// `yes` should be sourced from the persistent global -y/--yes flag.
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error {
// 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 {
if yes {
return nil
}
@@ -59,7 +67,9 @@ func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) e
return NewError(
CodeInputConfirmationRequired,
fmt.Sprintf("delete %s %s requires explicit confirmation: re-run with -y/--yes", what, id),
)
).
WithRetryCommand(retryCmd).
WithRisk("destructive", action)
}
ok, err := p.Confirm(fmt.Sprintf("Delete %s %s? This cannot be undone.", what, id), false)
if err != nil {
+77 -56
View File
@@ -4,41 +4,40 @@ import (
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/output"
)
// Typed format modes. Defined as constants to keep mode comparisons
// type-safe and prevent string drift across call sites.
// FormatMode is the resolved --format value (typed enum).
type FormatMode string
const (
FormatText = "text"
FormatJSON = "json"
FormatNDJSON = "ndjson"
FormatHuman FormatMode = "human"
FormatJSON FormatMode = "json"
FormatNDJSON FormatMode = "ndjson"
)
// FormatOptions captures the resolved --format + --jq state for a command.
// Mode is one of FormatText / FormatJSON / FormatNDJSON, or "" before
// Mode is one of FormatHuman / FormatJSON / FormatNDJSON, or "" before
// ResolveDefault has been called.
type FormatOptions struct {
Mode string
Mode FormatMode
JQ string
TTY bool // ResolveDefault populates; Emit reads for indent decision
}
// AddFormatFlag registers --format and --jq on cmd. Optional fieldHints are
// appended to cmd.Long as a documentation aid for --jq projection
// (e.g., `weknora kb list --format json --jq '.[] | {id, name}'`).
//
// Uses cmd.Flags() (local) rather than a root persistent flag — only
// commands that actually honor --format register it, so cobra rejects
// --format on others with "unknown flag" rather than silently ignoring it.
// AddFormatFlag attaches the --jq projection field hints (in cmd.Long) for
// commands that honor --format. The flags themselves are registered as
// persistent globals at the root, so this helper no longer re-registers
// them — it only appends documentation. Callers that don't need field
// hints can skip this call entirely.
func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
cmd.Flags().String("format", "", "Output format: text | json | ndjson (default: text in TTY, json in pipe)")
cmd.Flags().StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --format json|ndjson)")
if len(fieldHints) > 0 {
sorted := append([]string(nil), fieldHints...)
sort.Strings(sorted)
@@ -55,7 +54,7 @@ func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
// CheckFormatFlag resolves --format + --jq from cmd. Returns:
// - (*FormatOptions{Mode:""}, nil) flag not set; caller should call ResolveDefault
// - (*FormatOptions{Mode:v,JQ:q}, nil) valid values
// - (nil, *FlagError) invalid --format, or --jq with explicit --format text
// - (nil, *FlagError) invalid --format, or --jq with explicit --format human
//
// --jq with --format unset is accepted: ResolveDefault below will promote
// the mode to FormatJSON so the filter has somewhere to apply.
@@ -64,19 +63,21 @@ func CheckFormatFlag(cmd *cobra.Command) (*FormatOptions, error) {
if f := cmd.Flags().Lookup("format"); f != nil {
v := f.Value.String()
switch v {
case "", FormatText, FormatJSON, FormatNDJSON:
fopts.Mode = v
case "":
// unset; caller calls ResolveDefault
case "human", "json", "ndjson":
fopts.Mode = FormatMode(v)
default:
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be text | json | ndjson", v))
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be human | json | ndjson", v))
}
}
if f := cmd.Flags().Lookup("jq"); f != nil {
fopts.JQ = f.Value.String()
}
// --jq only meaningful for JSON-shaped output. Reject the explicit
// `--format text --jq ...` combination; the `--jq` with --format unset
// `--format human --jq ...` combination; the `--jq` with --format unset
// case is handled by ResolveDefault.
if fopts.JQ != "" && fopts.Mode == FormatText {
if fopts.JQ != "" && fopts.Mode == FormatHuman {
return nil, NewFlagError(errors.New("--jq requires --format json|ndjson"))
}
return fopts, nil
@@ -88,48 +89,68 @@ func (o *FormatOptions) WantsJSON() bool {
return o.Mode == FormatJSON || o.Mode == FormatNDJSON
}
// Emit serializes v according to the resolved Mode + JQ. For ndjson, slice
// values are split element-per-line (per ndjson.org); for json, v is
// emitted as-is. When JQ is set, the jq expression runs against the
// marshaled JSON and each result becomes a line. Text mode is the caller's
// job — Emit returns an error so a missed dispatch surfaces loudly.
func (o *FormatOptions) Emit(w io.Writer, v any) error {
// Emit serializes data wrapped in the success envelope (FormatJSON
// path) or as bare NDJSON lines (FormatNDJSON path). meta is optional
// (pass nil for mutation commands without batch counts).
//
// FormatJSON path: envelope is {ok:true, data:..., meta?:..., _notice?:...}.
// Indent is determined by o.TTY (populated by ResolveDefault).
// When o.JQ is set, jq evaluates against the full envelope JSON, so users
// project with ".data[]", ".meta.count", etc.
//
// FormatNDJSON path: emits one bare JSON object per line (no envelope).
// Matches spec §5 NDJSON event-passthrough semantics.
//
// FormatHuman path returns an error so a missed dispatch surfaces loudly.
func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
switch o.Mode {
case FormatJSON:
return format.WriteJSONFiltered(w, v, nil, o.JQ)
case FormatNDJSON:
// jq output is naturally line-per-result → already valid NDJSON.
// Without jq, split arrays per ndjson.org (one object per line).
if o.JQ != "" {
return format.WriteJSONFiltered(w, v, nil, o.JQ)
env := output.Envelope{
OK: true,
Data: data,
Meta: meta,
Notice: output.GetNotice(),
Profile: globalProfile,
}
return format.WriteJSONFiltered(w, env, nil, o.JQ)
}
return format.WriteNDJSON(w, v)
case FormatText:
return fmt.Errorf("FormatOptions.Emit: cannot emit text mode as JSON; caller must render text separately")
return output.WriteEnvelope(w, data, meta, o.TTY, globalProfile)
case FormatNDJSON:
if o.JQ != "" {
return format.WriteJSONFiltered(w, data, nil, o.JQ)
}
return format.WriteNDJSON(w, data)
case FormatHuman:
return fmt.Errorf("FormatOptions.Emit: cannot emit human mode as JSON; caller must render human-readable separately")
default:
return fmt.Errorf("FormatOptions.Emit: unknown mode %q", o.Mode)
}
}
// ResolveDefault fills in Mode using TTY detection when the user didn't pass
// --format explicitly. Pass iostreams.IO.IsStdoutTTY() as isTTY.
// No-op if Mode is already set.
//
// `--jq` without an explicit `--format` forces JSON regardless of TTY:
// the filter has no meaning in text mode, so silently dropping it would
// surprise the user. The `--jq` + `--format text` combination is caught
// up-front by CheckFormatFlag.
func (o *FormatOptions) ResolveDefault(isTTY bool) {
if o.Mode != "" {
return
}
if o.JQ != "" {
o.Mode = FormatJSON
return
}
if isTTY {
o.Mode = FormatText
} else {
// 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)
// - For human-readable rendering, pass --format human explicitly
func (o *FormatOptions) ResolveDefault(tty bool) {
o.TTY = tty
if o.Mode == "" {
o.Mode = FormatJSON
}
}
// FromEnv reads WEKNORA_FORMAT and applies it when Mode hasn't been set
// by --format. Call between CheckFormatFlag and ResolveDefault.
//
// Invalid env values are silently ignored (the user's --format on a
// later invocation will still take precedence).
func (o *FormatOptions) FromEnv() {
if o.Mode != "" {
return
}
v := os.Getenv("WEKNORA_FORMAT")
switch v {
case "human", "json", "ndjson":
o.Mode = FormatMode(v)
}
}
@@ -0,0 +1,88 @@
package cmdutil_test
import (
"bytes"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/output"
)
func TestEmit_WrapsInEnvelope(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
data := []map[string]string{{"id": "kb_x"}, {"id": "kb_y"}}
if err := fopts.Emit(&buf, data, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"ok":true`) {
t.Errorf("expected envelope ok:true; got %q", got)
}
if !strings.Contains(got, `"data":[`) {
t.Errorf("expected data array; got %q", got)
}
}
func TestEmit_WithMeta(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
meta := &output.Meta{Count: 2, HasMore: true}
if err := fopts.Emit(&buf, []string{"a", "b"}, meta); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"count":2`) {
t.Errorf("expected meta.count; got %q", got)
}
if !strings.Contains(got, `"has_more":true`) {
t.Errorf("expected meta.has_more; got %q", got)
}
}
func TestEmit_NDJSON_NoEnvelope(t *testing.T) {
// NDJSON path is event-passthrough; no envelope wrapping per spec §5.
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
data := []map[string]string{{"id": "a"}, {"id": "b"}}
if err := fopts.Emit(&buf, data, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if strings.Contains(got, `"ok":true`) {
t.Errorf("NDJSON path should not wrap in envelope; got %q", got)
}
// Expect 2 lines, one per item
lines := strings.Split(strings.TrimRight(got, "\n"), "\n")
if len(lines) != 2 {
t.Errorf("expected 2 NDJSON lines; got %d: %q", len(lines), got)
}
}
func TestEmit_TTYIndents(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, TTY: true}
if err := fopts.Emit(&buf, map[string]string{"id": "x"}, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, "\n \"") {
t.Errorf("expected indented multi-line output (TTY=true); got %q", got)
}
}
func TestEmit_PopulatesProfile(t *testing.T) {
cmdutil.SetProfile("staging")
t.Cleanup(func() { cmdutil.SetProfile("") })
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := fopts.Emit(&buf, map[string]string{"id": "x"}, nil); err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := buf.String()
if !strings.Contains(got, `"profile":"staging"`) {
t.Errorf("expected profile:staging in envelope; got %q", got)
}
}
+125 -31
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/spf13/cobra"
@@ -13,20 +14,26 @@ func TestCheckFormatFlags(t *testing.T) {
cases := []struct {
name string
args []string
wantMode string // "text" | "json" | "ndjson" | "" (unset)
wantMode FormatMode // FormatHuman | FormatJSON | FormatNDJSON | "" (unset)
wantErr bool
}{
// Unset → Mode is "" (caller resolves TTY default via ResolveDefault).
// Unset → Mode is "" (caller resolves default via ResolveDefault).
{"default", []string{}, "", false},
{"explicit text", []string{"--format", "text"}, "text", false},
{"json", []string{"--format", "json"}, "json", false},
{"ndjson", []string{"--format", "ndjson"}, "ndjson", false},
{"explicit human", []string{"--format", "human"}, FormatHuman, false},
{"json", []string{"--format", "json"}, FormatJSON, false},
{"ndjson", []string{"--format", "ndjson"}, FormatNDJSON, false},
{"invalid value", []string{"--format", "yaml"}, "", true},
// v0.7 BREAKING: "text" is no longer a valid --format value.
{"text rejected", []string{"--format", "text"}, "", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := &cobra.Command{}
AddFormatFlag(cmd)
// --format / --jq are persistent root flags in production; register
// them on this bare cmd so the test can exercise CheckFormatFlag in
// isolation.
cmd.PersistentFlags().String("format", "", "")
cmd.PersistentFlags().String("jq", "", "")
cmd.SetArgs(tc.args)
cmd.RunE = func(c *cobra.Command, _ []string) error {
opts, err := CheckFormatFlag(c)
@@ -45,9 +52,9 @@ func TestCheckFormatFlags(t *testing.T) {
func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
var buf bytes.Buffer
fopts := &FormatOptions{Mode: "ndjson"}
fopts := &FormatOptions{Mode: FormatNDJSON}
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
if err := fopts.Emit(&buf, arr); err != nil {
if err := fopts.Emit(&buf, arr, nil); err != nil {
t.Fatalf("Emit: %v", err)
}
want := `{"id":"a"}` + "\n" + `{"id":"b"}` + "\n"
@@ -58,45 +65,68 @@ func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
func TestFormatOptions_JSONEmitsArray(t *testing.T) {
var buf bytes.Buffer
fopts := &FormatOptions{Mode: "json"}
fopts := &FormatOptions{Mode: FormatJSON}
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
if err := fopts.Emit(&buf, arr); err != nil {
if err := fopts.Emit(&buf, arr, nil); err != nil {
t.Fatalf("Emit: %v", err)
}
// Expect a single JSON array, e.g. [{"id":"a"},{"id":"b"}]
var got []map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("not valid JSON: %v\n%s", err, buf.String())
// v0.7: JSON path wraps in success envelope {ok:true, data:[...]}.
// Unmarshal the envelope and check data array length.
var env struct {
OK bool `json:"ok"`
Data []map[string]string `json:"data"`
}
if len(got) != 2 {
t.Errorf("got %d items, want 2", len(got))
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
t.Fatalf("not valid envelope JSON: %v\n%s", err, buf.String())
}
if !env.OK {
t.Errorf("expected ok:true in envelope")
}
if len(env.Data) != 2 {
t.Errorf("got %d items, want 2", len(env.Data))
}
}
func TestFormatOptions_TextModeReturnsError(t *testing.T) {
fopts := &FormatOptions{Mode: "text"}
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"})
func TestFormatOptions_HumanModeReturnsError(t *testing.T) {
fopts := &FormatOptions{Mode: FormatHuman}
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"}, nil)
if err == nil {
t.Error("expected error for text mode, got nil")
t.Error("expected error for human mode, got nil")
}
}
// TestResolveDefault_AlwaysJSON verifies v0.7 semantics: default is FormatJSON
// regardless of whether stdout is a TTY (BREAKING change from v0.6).
func TestResolveDefault_AlwaysJSON(t *testing.T) {
for _, isTTY := range []bool{true, false} {
o := &FormatOptions{}
o.ResolveDefault(isTTY)
if o.Mode != FormatJSON {
t.Errorf("isTTY=%v: expected default FormatJSON, got %v", isTTY, o.Mode)
}
if o.TTY != isTTY {
t.Errorf("isTTY=%v: TTY field not propagated", isTTY)
}
}
}
func TestResolveDefault(t *testing.T) {
cases := []struct {
name string
mode string // pre-set Mode
mode FormatMode // pre-set Mode
jq string
isTTY bool
wantMode string
wantMode FormatMode
}{
{"empty isTTY", "", "", true, "text"},
{"empty no-tty", "", "", false, "json"},
{"already set keeps value tty", "ndjson", "", true, "ndjson"},
{"already set keeps value no-tty", "json", "", false, "json"},
// v0.7: empty Mode always resolves to FormatJSON regardless of TTY.
{"empty isTTY", "", "", true, FormatJSON},
{"empty no-tty", "", "", false, FormatJSON},
{"already set keeps value tty", FormatNDJSON, "", true, FormatNDJSON},
{"already set keeps value no-tty", FormatJSON, "", false, FormatJSON},
// --jq with unset --format promotes to JSON regardless of TTY so the
// filter has somewhere to apply (silent text drop would surprise users).
{"jq forces json on TTY", "", ".[]", true, "json"},
{"jq with explicit ndjson preserved", "ndjson", ".[]", true, "ndjson"},
// filter has somewhere to apply (silent human drop would surprise users).
{"jq forces json on TTY", "", ".[]", true, FormatJSON},
{"jq with explicit ndjson preserved", FormatNDJSON, ".[]", true, FormatNDJSON},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -117,12 +147,18 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
args []string
}{
{"invalid format value", []string{"--format", "yaml"}},
{"jq with explicit text mode", []string{"--format", "text", "--jq", ".id"}},
// v0.7: "text" is rejected; "human" is the valid human-readable value.
{"text rejected as invalid", []string{"--format", "text"}},
{"jq with explicit human mode", []string{"--format", "human", "--jq", ".id"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := &cobra.Command{}
AddFormatFlag(cmd)
// --format / --jq are persistent root flags in production; register
// them on this bare cmd so the test can exercise CheckFormatFlag in
// isolation.
cmd.PersistentFlags().String("format", "", "")
cmd.PersistentFlags().String("jq", "", "")
cmd.SetArgs(tc.args)
var got error
cmd.RunE = func(c *cobra.Command, _ []string) error {
@@ -144,3 +180,61 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
})
}
}
func TestCheckFormatFlag_InvalidValueRejected(t *testing.T) {
for _, v := range []string{"text", "yaml", "xml", "table"} {
v := v
t.Run(v, func(t *testing.T) {
cmd := &cobra.Command{}
cmd.Flags().String("format", "", "")
_ = cmd.Flags().Set("format", v)
_, err := CheckFormatFlag(cmd)
if err == nil {
t.Fatalf("expected error for --format %q", v)
}
if !strings.Contains(err.Error(), "human | json | ndjson") {
t.Errorf("expected enum hint for --format %q; got %v", v, err)
}
})
}
}
func TestCheckFormatFlag_HumanAccepted(t *testing.T) {
cmd := &cobra.Command{}
cmd.Flags().String("format", "", "")
_ = cmd.Flags().Set("format", "human")
o, err := CheckFormatFlag(cmd)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if o.Mode != FormatHuman {
t.Errorf("got %v, want FormatHuman", o.Mode)
}
}
func TestFromEnv_AppliesWEKNORA_FORMAT(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "ndjson")
o := &FormatOptions{}
o.FromEnv()
if o.Mode != FormatNDJSON {
t.Errorf("expected FormatNDJSON from env; got %v", o.Mode)
}
}
func TestFromEnv_PrecedenceFlagOverridesEnv(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "ndjson")
o := &FormatOptions{Mode: FormatJSON}
o.FromEnv()
if o.Mode != FormatJSON {
t.Errorf("flag should win over env; got %v", o.Mode)
}
}
func TestFromEnv_InvalidValueIgnored(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "yaml")
o := &FormatOptions{}
o.FromEnv()
if o.Mode != "" {
t.Errorf("invalid env should be ignored; got %v", o.Mode)
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ func AddLogLevelFlag(cmd *cobra.Command) {
//
// Invalid env values fall through to the next priority (no error — env is
// best-effort). The stderr writer is retained in the signature for symmetry
// with ApplyLogLevel callers but is unused in v0.6.
// with ApplyLogLevel callers but is unused at the OS level.
func ResolveLogLevel(cmd *cobra.Command, _ io.Writer) (string, bool) {
// Priority 1: explicit --log-level flag.
if cmd != nil {