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:
@@ -101,8 +101,8 @@ func runAgentCheck(ctx context.Context, svc AgentCheckService, id string) (*Agen
|
||||
func emitAgentCheck(res *AgentCheckResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
return writeAgentCheckText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for agent check", fopts.Mode)
|
||||
|
||||
@@ -122,10 +122,14 @@ func TestEmitAgentCheck_JSON(t *testing.T) {
|
||||
if err := emitAgentCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
var got AgentCheckResult
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data AgentCheckResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
got := env.Data
|
||||
if got.ModelID != "m_x" {
|
||||
t.Errorf("ModelID=%q, want m_x", got.ModelID)
|
||||
}
|
||||
@@ -138,7 +142,7 @@ func TestEmitAgentCheck_TextHuman(t *testing.T) {
|
||||
trueP := true
|
||||
var buf bytes.Buffer
|
||||
res := &AgentCheckResult{ID: "ag_x", Reachable: true, ModelID: "m_x", KBScopeAllReachable: &trueP}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
if err := emitAgentCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
@@ -291,12 +291,12 @@ func openConfigFile(path string) (io.Reader, string, error) {
|
||||
return r, kind, nil
|
||||
}
|
||||
|
||||
// emitAgent writes the Agent to stdout per the v0.4 wire contract (bare
|
||||
// SDK shape for --format json, human KV otherwise). Shared by create and edit;
|
||||
// defined here for proximity to the create flow.
|
||||
// emitAgent writes the Agent to stdout (bare SDK shape for --format json,
|
||||
// human KV otherwise). Shared by create and edit; defined here for proximity
|
||||
// to the create flow.
|
||||
func emitAgent(fopts *cmdutil.FormatOptions, ag *sdk.Agent) error {
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, ag)
|
||||
return fopts.Emit(iostreams.IO.Out, ag, nil)
|
||||
}
|
||||
renderAgent(iostreams.IO.Out, ag)
|
||||
return nil
|
||||
|
||||
+13
-2
@@ -79,18 +79,29 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, agentDeleteFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "permanently delete a custom agent",
|
||||
RequiredFlags: []string{"<agent-id> (positional)"},
|
||||
Examples: []string{
|
||||
"weknora agent delete ag_abc -y",
|
||||
"weknora agent delete ag_abc -y --format json",
|
||||
},
|
||||
Warnings: []string{
|
||||
"agent delete removes the configured agent and its workflow. Never auto-add -y.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "agent", opts.AgentID); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "agent", opts.AgentID, "agent.delete", "weknora agent delete "+opts.AgentID+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := svc.DeleteAgent(ctx, opts.AgentID); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete agent %s", opts.AgentID)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.AgentID, Deleted: true})
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.AgentID, Deleted: true}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted agent %s\n", opts.AgentID)
|
||||
return nil
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestDelete_NonTTY_WithYes_Direct(t *testing.T) {
|
||||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc", Yes: true},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{},
|
||||
))
|
||||
assert.Equal(t, "ag_abc", svc.gotID)
|
||||
assert.Contains(t, out.String(), "ag_abc")
|
||||
@@ -56,7 +56,7 @@ func TestDelete_404_PropagatesNotFound(t *testing.T) {
|
||||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_missing", Yes: true},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{},
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
@@ -71,7 +71,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
|
||||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p,
|
||||
))
|
||||
assert.True(t, p.Asked)
|
||||
assert.Equal(t, "ag_abc", svc.gotID)
|
||||
@@ -84,7 +84,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
||||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p,
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
||||
+62
-8
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -82,15 +83,16 @@ invocation:
|
||||
|
||||
surgical flag > config-file value > zero value
|
||||
|
||||
AI agents: writes to a server resource. Failure surfaces as a typed
|
||||
code on stderr: resource.not_found (agent id or KB id), auth.forbidden,
|
||||
input.invalid_argument (no flags passed, bad file).`
|
||||
AI agents: this is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
with input.confirmation_required. Surface the prompt to the user and only
|
||||
retry with -y after explicit approval. Other failure codes: resource.not_found
|
||||
(agent id or KB id), auth.forbidden, input.invalid_argument (no flags, bad file).`
|
||||
|
||||
const agentEditExample = ` weknora agent edit ag_abc --name "Renamed"
|
||||
weknora agent edit ag_abc --description "" # clear description
|
||||
weknora agent edit ag_abc --add-kb kb_new --remove-kb kb_old
|
||||
weknora agent edit ag_abc --system-prompt-file ./prompt.md
|
||||
weknora agent edit ag_abc --config-file ./tuned.yaml --temperature 0.9`
|
||||
const agentEditExample = ` weknora agent edit ag_abc --name "Renamed" -y
|
||||
weknora agent edit ag_abc --description "" -y # clear description
|
||||
weknora agent edit ag_abc --add-kb kb_new --remove-kb kb_old -y
|
||||
weknora agent edit ag_abc --system-prompt-file ./prompt.md -y
|
||||
weknora agent edit ag_abc --config-file ./tuned.yaml --temperature 0.9 -y`
|
||||
|
||||
// NewCmdEdit builds `weknora agent edit <agent-id>`.
|
||||
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
@@ -147,6 +149,12 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
yes, _ := cmd.Flags().GetBool("yes")
|
||||
// Build the retry command from the flags the user actually passed.
|
||||
retryCmd := buildAgentEditRetryCmd(cmd, opts.AgentID)
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), yes, fopts.WantsJSON(), "agent", opts.AgentID, "agent.edit", retryCmd); err != nil {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -173,9 +181,55 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().StringVar(&configFile, "config-file", "", "Full AgentConfig YAML or JSON (REPLACES current config baseline; surgical flags then apply on top)")
|
||||
|
||||
cmdutil.AddFormatFlag(cmd, agentViewFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "surgically edit a custom agent's configuration",
|
||||
RequiredFlags: []string{"<agent-id> (positional)", "at least one edit flag (--name, --add-kb, etc.)"},
|
||||
Examples: []string{
|
||||
"weknora agent edit ag_abc --name \"Renamed\"",
|
||||
"weknora agent edit ag_abc --add-kb kb_new --remove-kb kb_old",
|
||||
"weknora agent edit ag_abc --config-file ./tuned.yaml",
|
||||
},
|
||||
Warnings: []string{
|
||||
"agent edit can change tool allowlist / KB scope. Surface the exit-10 prompt to the user — only proceed after explicit approval.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
// buildAgentEditRetryCmd constructs a directly-executable retry argv from the
|
||||
// flags the user actually set so agents can surface a precise re-run command.
|
||||
func buildAgentEditRetryCmd(cmd *cobra.Command, id string) string {
|
||||
var parts []string
|
||||
parts = append(parts, "weknora", "agent", "edit", id)
|
||||
cmd.Flags().Visit(func(f *pflag.Flag) {
|
||||
switch f.Name {
|
||||
case "name":
|
||||
parts = append(parts, "--name", f.Value.String())
|
||||
case "description":
|
||||
parts = append(parts, "--description", f.Value.String())
|
||||
case "model":
|
||||
parts = append(parts, "--model", f.Value.String())
|
||||
case "system-prompt":
|
||||
parts = append(parts, "--system-prompt", f.Value.String())
|
||||
case "agent-mode":
|
||||
parts = append(parts, "--agent-mode", f.Value.String())
|
||||
case "rerank-model":
|
||||
parts = append(parts, "--rerank-model", f.Value.String())
|
||||
case "temperature":
|
||||
parts = append(parts, "--temperature", f.Value.String())
|
||||
case "kb-selection-mode":
|
||||
parts = append(parts, "--kb-selection-mode", f.Value.String())
|
||||
case "format":
|
||||
parts = append(parts, "--format", f.Value.String())
|
||||
// --add-kb, --remove-kb, --system-prompt-file, --config-file are excluded
|
||||
// because they are multi-value or file-based; a precise argv is impractical.
|
||||
// The user must reconstruct those manually.
|
||||
}
|
||||
})
|
||||
parts = append(parts, "-y")
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// editHasAnyFlag reports whether opts carries at least one surgical update
|
||||
// signal. Required-flag validation lives in runEdit (not PreRunE) so unit
|
||||
// tests can invoke runEdit with a hand-built EditOptions directly.
|
||||
|
||||
@@ -7,11 +7,13 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
@@ -247,3 +249,42 @@ func TestEdit_SystemPromptFile(t *testing.T) {
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "new prompt", svc.updateReq.Config.SystemPrompt)
|
||||
}
|
||||
|
||||
// withRootHarnessAgent wraps `weknora agent edit ...` under a synthetic root
|
||||
// cmd that registers the global persistent flags (mirrors addGlobalFlags in
|
||||
// cmd/root.go).
|
||||
func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
|
||||
root := &cobra.Command{Use: "weknora"}
|
||||
pf := root.PersistentFlags()
|
||||
pf.BoolP("yes", "y", false, "")
|
||||
pf.String("format", "", "Output format: human | json | ndjson")
|
||||
pf.StringP("jq", "q", "", "")
|
||||
ag := &cobra.Command{Use: "agent"}
|
||||
ag.AddCommand(edit)
|
||||
root.AddCommand(ag)
|
||||
root.SetArgs(append([]string{"agent", "edit"}, args...))
|
||||
root.SetContext(context.Background())
|
||||
root.SilenceErrors = true
|
||||
root.SilenceUsage = true
|
||||
return root
|
||||
}
|
||||
|
||||
// TestAgentEdit_RequiresConfirmation asserts that without -y (non-TTY / JSON
|
||||
// mode), agent edit returns input.confirmation_required (exit 10).
|
||||
func TestAgentEdit_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t) // non-TTY
|
||||
f := &cmdutil.Factory{
|
||||
Client: func() (*sdk.Client, error) { return nil, nil },
|
||||
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
|
||||
}
|
||||
root := withRootHarnessAgent(NewCmdEdit(f), "ag_abc", "--name", "Renamed", "--format", "json")
|
||||
err := root.Execute()
|
||||
require.Error(t, err)
|
||||
var ce *cmdutil.Error
|
||||
require.ErrorAs(t, err, &ce)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per destructive-write protocol")
|
||||
// retry command must include -y and the agent id
|
||||
assert.Contains(t, ce.RetryCommand, "-y")
|
||||
assert.Contains(t, ce.RetryCommand, "ag_abc")
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
@@ -57,7 +58,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
return runList(c.Context(), opts, fopts, cli)
|
||||
},
|
||||
}
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
|
||||
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
|
||||
cmdutil.AddFormatFlag(cmd, agentListFields...)
|
||||
return cmd
|
||||
}
|
||||
@@ -66,10 +67,10 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
if opts == nil {
|
||||
opts = &ListOptions{}
|
||||
}
|
||||
if opts.Limit < 0 || opts.Limit > 10000 {
|
||||
if opts.Limit < 1 || opts.Limit > 10000 {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("--limit must be in 0..10000 (0 = no cap), got %d", opts.Limit),
|
||||
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
|
||||
}
|
||||
}
|
||||
items, err := svc.ListAgents(ctx)
|
||||
@@ -85,12 +86,16 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
||||
return items[i].UpdatedAt.After(items[j].UpdatedAt)
|
||||
})
|
||||
// --limit applies after sort so the cap returns the top-N most-recent.
|
||||
// The agent list SDK is unpaginated, so client-side truncation does not
|
||||
// imply server-side has_more — there is no cursor to continue with.
|
||||
// has_more is omitted; callers needing all agents should raise --limit.
|
||||
if opts.Limit > 0 && len(items) > opts.Limit {
|
||||
items = items[:opts.Limit]
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, items)
|
||||
meta := &output.Meta{Count: len(items)}
|
||||
return fopts.Emit(iostreams.IO.Out, items, meta)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
+37
-19
@@ -25,7 +25,7 @@ func (f *fakeListSvc) ListAgents(_ context.Context) ([]sdk.Agent, error) {
|
||||
|
||||
func TestList_Empty_Human(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no agents)") {
|
||||
@@ -35,11 +35,21 @@ func TestList_Empty_Human(t *testing.T) {
|
||||
|
||||
func TestList_Empty_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(out.String()); got != "[]" {
|
||||
t.Errorf("expected bare `[]`, got %q", got)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Agent `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse envelope: %v\n%s", err, out.String())
|
||||
}
|
||||
if !env.OK {
|
||||
t.Error("envelope.ok=false")
|
||||
}
|
||||
if len(env.Data) != 0 {
|
||||
t.Errorf("expected empty data, got %d items", len(env.Data))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +60,7 @@ func TestList_NonEmpty_Human_RendersColumns(t *testing.T) {
|
||||
{ID: "ag_a", Name: "Research", IsBuiltin: true, UpdatedAt: now.Add(-1 * time.Hour)},
|
||||
{ID: "ag_b", Name: "Triage", UpdatedAt: now.Add(-3 * 24 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -69,13 +79,17 @@ func TestList_NonEmpty_JSON_SortsByUpdatedAtDesc(t *testing.T) {
|
||||
{ID: "ag_new", Name: "new", UpdatedAt: now},
|
||||
{ID: "ag_mid", Name: "mid", UpdatedAt: now.Add(-1 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
var got []sdk.Agent
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Agent `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
got := env.Data
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("len = %d, want 3", len(got))
|
||||
}
|
||||
@@ -92,9 +106,9 @@ func TestList_JSON_JQProjection(t *testing.T) {
|
||||
items := []sdk.Agent{
|
||||
{ID: "ag_x", Name: "Foo", Description: "long description"},
|
||||
}
|
||||
// --jq is the canonical projection mechanism in v0.6+.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".[] | {id, name}"}
|
||||
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
// --jq projects from the envelope; .data[] | ... extracts from the array inside envelope.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data[] | {id, name}"}
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
var got map[string]any
|
||||
@@ -131,20 +145,24 @@ func TestList_Limit_CapsResults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_Limit_Zero_NoCap(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(7)}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
func TestList_Limit_Zero_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(), &ListOptions{Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(7)})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for --limit 0")
|
||||
}
|
||||
got := strings.Count(out.String(), `"id":"ag_`)
|
||||
if got != 7 {
|
||||
t.Errorf("--limit 0 must not cap; got %d, want 7", got)
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T: %v", err, err)
|
||||
}
|
||||
if typed.Code != cmdutil.CodeInputInvalidArgument {
|
||||
t.Errorf("expected CodeInputInvalidArgument, got %v", typed.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeAgents(2)})
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: makeAgents(2)})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for negative --limit")
|
||||
}
|
||||
|
||||
@@ -87,8 +87,8 @@ func runAgentStatus(ctx context.Context, svc AgentStatusService, id string) (*Ag
|
||||
func emitAgentStatus(res *AgentStatusResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
return writeAgentStatusText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for agent status", fopts.Mode)
|
||||
|
||||
@@ -80,10 +80,14 @@ func TestEmitAgentStatus_JSON(t *testing.T) {
|
||||
if err := emitAgentStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
var got AgentStatusResult
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data AgentStatusResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
got := env.Data
|
||||
if got.ModelID != "m_x" {
|
||||
t.Errorf("ModelID=%q, want m_x", got.ModelID)
|
||||
}
|
||||
@@ -92,7 +96,7 @@ func TestEmitAgentStatus_JSON(t *testing.T) {
|
||||
func TestEmitAgentStatus_TextHuman(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
res := &AgentStatusResult{ID: "ag_x", Reachable: true, ModelID: "m_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
if err := emitAgentStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ func runView(ctx context.Context, fopts *cmdutil.FormatOptions, svc ViewService,
|
||||
return cmdutil.WrapHTTP(err, "fetch agent %s", agentID)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, a)
|
||||
return fopts.Emit(iostreams.IO.Out, a, nil)
|
||||
}
|
||||
renderAgent(iostreams.IO.Out, a)
|
||||
return nil
|
||||
|
||||
@@ -41,7 +41,7 @@ func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
|
||||
WebSearchEnabled: true,
|
||||
},
|
||||
}}
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_abc"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_abc"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -126,7 +126,7 @@ func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}}
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_min"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_min"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -150,22 +150,26 @@ func TestView_JSON_BareObject(t *testing.T) {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "ag_json"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
var got sdk.Agent
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data sdk.Agent `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
got := env.Data
|
||||
if got.ID != "ag_json" || got.Name != "JSONy" {
|
||||
t.Errorf("bare object shape wrong: id=%s name=%s", got.ID, got.Name)
|
||||
t.Errorf("envelope.data shape wrong: id=%s name=%s", got.ID, got.Name)
|
||||
}
|
||||
if strings.Contains(out.String(), `"ok":`) || strings.Contains(out.String(), `"data":`) {
|
||||
t.Errorf("bare output must not carry envelope keys, got %q", out.String())
|
||||
if !env.OK {
|
||||
t.Errorf("envelope.ok must be true, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestView_404_MapsToResourceNotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{err: errors.New("HTTP error 404: agent not found")}
|
||||
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_missing")
|
||||
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_missing")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user