refactor(cli): drop --dry-run + introduce bare-JSON output path

Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):

1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
   (gh, aws, stripe, lark): none expose --dry-run. The mainstream that
   does (kubectl/git/helm/ansible) operates on declarative manifests
   or local state where the preview is materially different from the
   executed action. WeKnora's CLI just echoed the same parameters
   that would have gone on the wire — the preview added no real
   signal over `--help` + reading the call site. Removes:
   - root --dry-run persistent flag + cmdutil/dryrun.go
   - DryRun fields + EmitDryRun calls in 12 write commands
   - format.Envelope.DryRun field
   - 8 corresponding *_test.go cases
   - --dry-run mention from README.md and CHANGELOG.md
   - "dry_run":false from 16 golden envelopes

2. Migrate every --json output to bare data:
   - New format.WriteJSON / WriteJSONFiltered helpers
     (cli/internal/format/bare.go) share filterArrayItems /
     filterObjectKeys / writeJQ with the (still-live for now) envelope
     filter helpers.
   - Read commands (kb/doc/session list+view, search chunks/docs/
     sessions/kb, auth list/status, agent list/view, context list,
     doctor) emit bare arrays / objects on stdout.
   - Write commands (kb create/edit/delete/pin/empty, doc upload/
     upload_recursive/delete, session delete, auth login/logout/
     refresh/token, link/unlink, context add/use/remove, agent
     invoke, chat, api, version) emit bare result objects. Risk
     classification dropped — the resource + exit code already
     convey the action.

Per-command shape changes:
   list / search       → []T   (was {ok, data:{items:[…]}})
   view                → T     (was {ok, data:T, _meta:…})
   create / edit       → T
   delete / pin / etc. → {id, …action result…}
   doctor              → {summary, checks}
   api                 → {status, headers, body}

_meta dropped on the read path:
   pagination (page/page_size/total/has_more) — agents iterate with
   --all-pages or accept --limit (gh CLI parity);
   kb_id / context echo — caller already knows what it asked for.

Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
This commit is contained in:
nullkey
2026-05-14 23:28:14 +08:00
committed by lyingbug
parent bdc589e1c0
commit cc8254f862
95 changed files with 579 additions and 911 deletions
+1 -12
View File
@@ -31,7 +31,6 @@ type CreateOptions struct {
Name string
Description string
EmbeddingModel string
DryRun bool
}
// CreateService is the narrow SDK surface this command depends on.
@@ -52,10 +51,6 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
if err != nil {
return err
}
opts.DryRun = cmdutil.IsDryRun(c)
if opts.DryRun {
return runCreate(c.Context(), opts, jopts, nil) // service unused on dry-run
}
cli, err := f.Client()
if err != nil {
return err
@@ -86,19 +81,13 @@ func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOpti
req.EmbeddingModelID = opts.EmbeddingModel
}
if opts.DryRun {
return cmdutil.EmitDryRun(jopts.Enabled(), req, nil,
&format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("create knowledge base %q", opts.Name)})
}
created, err := svc.CreateKnowledgeBase(ctx, req)
if err != nil {
return cmdutil.WrapHTTP(err, "create knowledge base")
}
if jopts.Enabled() {
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("created knowledge base %s", created.ID)}
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(created, &format.Meta{KBID: created.ID}, risk), jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, created, jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)
return nil
+2 -3
View File
@@ -117,8 +117,7 @@ func TestCreate_JSONOutput(t *testing.T) {
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
got := out.String()
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)
assert.Contains(t, got, `"id":"kb_99"`)
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb_99"`), "expected bare KnowledgeBase object; got %q", got)
assert.Contains(t, got, `"name":"Eng"`)
assert.Contains(t, got, `"kb_id":"kb_99"`, "_meta.kb_id should carry the new id")
assert.NotContains(t, got, `"ok":`)
}
+2 -14
View File
@@ -18,8 +18,7 @@ import (
var kbDeleteFields = []string{"id", "deleted"}
type DeleteOptions struct {
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go addGlobalFlags)
DryRun bool
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go addGlobalFlags)
}
// DeleteService is the narrow SDK surface this command depends on.
@@ -61,10 +60,6 @@ guard against unintended deletes.`,
return err
}
opts.Yes, _ = c.Flags().GetBool("yes")
opts.DryRun = cmdutil.IsDryRun(c)
if opts.DryRun {
return runDelete(c.Context(), opts, jopts, nil, f.Prompter(), args[0])
}
cli, err := f.Client()
if err != nil {
return err
@@ -78,12 +73,6 @@ guard against unintended deletes.`,
}
func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOptions, svc DeleteService, p prompt.Prompter, id string) error {
if opts.DryRun {
return cmdutil.EmitDryRun(jopts.Enabled(),
deleteResult{ID: id, Deleted: false}, &format.Meta{KBID: id},
&format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("delete knowledge base %s", id)})
}
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "knowledge base", id); err != nil {
return err
}
@@ -93,8 +82,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOpti
}
if jopts.Enabled() {
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("deleted knowledge base %s", id)}
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(deleteResult{ID: id, Deleted: true}, &format.Meta{KBID: id}, risk), jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted knowledge base %s\n", id)
return nil
+2 -3
View File
@@ -93,10 +93,9 @@ func TestDelete_JSONOutput(t *testing.T) {
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, p, "kb_json"))
got := out.String()
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)
assert.Contains(t, got, `"id":"kb_json"`)
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb_json"`), "expected bare object; got %q", got)
assert.Contains(t, got, `"deleted":true`)
assert.Contains(t, got, `"kb_id":"kb_json"`)
assert.NotContains(t, got, `"ok":`)
}
// The remaining tests cover the interactive confirm path which only fires
+1 -20
View File
@@ -33,7 +33,6 @@ type EditOptions struct {
// clear the description.
Name *string
Description *string
DryRun bool
}
// EditService is the narrow SDK surface this command depends on. GetKnowledgeBase
@@ -66,10 +65,6 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
if c.Flag("description").Changed {
opts.Description = &desc
}
opts.DryRun = cmdutil.IsDryRun(c)
if opts.DryRun {
return runEdit(c.Context(), opts, jopts, nil, args[0])
}
cli, err := f.Client()
if err != nil {
return err
@@ -93,20 +88,6 @@ func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions,
}
}
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("edit knowledge base %s", id)}
if opts.DryRun {
// Dry-run renders only the user-set fields so the preview reflects
// intent; the real-run fetch path fills in the rest from the server.
preview := &sdk.UpdateKnowledgeBaseRequest{}
if opts.Name != nil {
preview.Name = *opts.Name
}
if opts.Description != nil {
preview.Description = *opts.Description
}
return cmdutil.EmitDryRun(jopts.Enabled(), preview, &format.Meta{KBID: id}, risk)
}
// Fetch current state so we can fill in fields the user didn't touch.
// TOCTOU note: another writer could change Name/Description between
// our Get and Put; matches the same race window kb pin / unpin have.
@@ -130,7 +111,7 @@ func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions,
return cmdutil.WrapHTTP(err, "edit knowledge base %s", id)
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk), jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, updated, jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Updated knowledge base %s\n", id)
return nil
-13
View File
@@ -3,7 +3,6 @@ package kb
import (
"context"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -102,18 +101,6 @@ func TestEdit_BothFlags(t *testing.T) {
assert.Equal(t, "new desc", svc.gotReq.Description)
}
func TestEdit_DryRun_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
opts := &EditOptions{DryRun: true}
opts.Name = stringPtr("preview")
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.JSONOptions{}, nil, "kb_abc"))
body := out.String()
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
assert.Contains(t, body, `"dry_run":true`)
assert.Contains(t, body, `"write"`)
}
func TestEdit_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
// 404 must come from the GetKnowledgeBase pre-fetch in the fetch-then-
+3 -15
View File
@@ -19,8 +19,7 @@ import (
var kbEmptyFields = []string{"id", "deleted_count"}
type EmptyOptions struct {
Yes bool
DryRun bool
Yes bool
}
type EmptyService interface {
@@ -57,10 +56,6 @@ piped contexts. Without -y the CLI exits 10 in non-interactive mode.`,
return err
}
opts.Yes, _ = c.Flags().GetBool("yes")
opts.DryRun = cmdutil.IsDryRun(c)
if opts.DryRun {
return runEmpty(c.Context(), opts, jopts, nil, f.Prompter(), args[0])
}
cli, err := f.Client()
if err != nil {
return err
@@ -74,12 +69,6 @@ piped contexts. Without -y the CLI exits 10 in non-interactive mode.`,
}
func runEmpty(ctx context.Context, opts *EmptyOptions, jopts *cmdutil.JSONOptions, svc EmptyService, p prompt.Prompter, id string) error {
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("empty knowledge base %s", id)}
if opts.DryRun {
return cmdutil.EmitDryRun(jopts.Enabled(), emptyResult{ID: id}, &format.Meta{KBID: id}, risk)
}
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "all contents of knowledge base", id); err != nil {
return err
}
@@ -94,9 +83,8 @@ func runEmpty(ctx context.Context, opts *EmptyOptions, jopts *cmdutil.JSONOption
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(
emptyResult{ID: id, DeletedCount: deleted}, &format.Meta{KBID: id}, risk,
), jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out,
emptyResult{ID: id, DeletedCount: deleted}, jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Emptied knowledge base %s (%d document(s) cleared)\n", id, deleted)
return nil
-11
View File
@@ -3,7 +3,6 @@ package kb
import (
"context"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -81,13 +80,3 @@ func TestEmpty_NotFound(t *testing.T) {
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
}
func TestEmpty_DryRun_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeEmptySvc{}
require.NoError(t, runEmpty(context.Background(), &EmptyOptions{DryRun: true}, &cmdutil.JSONOptions{}, svc, &testutil.ConfirmPrompter{}, "kb_dry"))
body := out.String()
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
assert.Contains(t, body, `"dry_run":true`)
assert.Contains(t, body, `"high-risk-write"`)
assert.False(t, svc.called)
}
+2 -11
View File
@@ -44,11 +44,6 @@ type ListService interface {
ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error)
}
// listResult is the typed payload emitted under data.items.
type listResult struct {
Items []sdk.KnowledgeBase `json:"items"`
}
// NewCmdList builds `weknora kb list`.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{}
@@ -71,7 +66,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd.Flags().BoolVar(&opts.Pinned, "pinned", false, "Only show pinned knowledge bases")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
cmdutil.AddJSONFlags(cmd, kbListFields)
aiclient.SetAgentHelp(cmd, "Lists all knowledge bases. Returns data.items: [{id, name, ...}]; empty array when none. --pinned restricts to pinned KBs (client-side filter). --limit caps the returned slice. Use `--json` (bare) for the field list, `--json id,name` to project, or `--jq` for arbitrary reshape.")
aiclient.SetAgentHelp(cmd, "Lists all knowledge bases as a bare JSON array of {id, name, ...} objects (empty `[]` when none). --pinned restricts to pinned KBs (client-side filter). --limit caps the returned slice. Use `--json` (bare) for full objects, `--json id,name` to project fields, or `--jq` for arbitrary reshape.")
return cmd
}
@@ -110,11 +105,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Success(listResult{Items: items}, nil),
jopts.Fields, jopts.JQ,
)
return format.WriteJSONFiltered(iostreams.IO.Out, items, jopts.Fields, jopts.JQ)
}
if len(items) == 0 {
+9 -17
View File
@@ -39,12 +39,9 @@ func TestList_Empty_JSON(t *testing.T) {
if err := runList(context.Background(), &ListOptions{}, jopts, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
if !strings.Contains(got, `"items":[]`) {
t.Errorf("empty JSON should contain items:[], got %q", got)
}
if strings.Contains(got, `"items":null`) {
t.Error("items must be [] not null")
got := strings.TrimSpace(out.String())
if got != "[]" {
t.Errorf("empty JSON should be bare `[]`, got %q", got)
}
}
@@ -76,19 +73,14 @@ func TestList_JSON_FieldFilter(t *testing.T) {
if err := runList(context.Background(), &ListOptions{}, jopts, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data struct {
Items []map[string]any `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
var got []map[string]any
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, out.String())
}
if len(env.Data.Items) != 1 {
t.Fatalf("expected 1 item, got %d", len(env.Data.Items))
if len(got) != 1 {
t.Fatalf("expected 1 item, got %d", len(got))
}
item := env.Data.Items[0]
item := got[0]
if item["id"] != "kb1" || item["name"] != "Marketing" {
t.Errorf("kept fields wrong: %+v", item)
}
@@ -104,7 +96,7 @@ func TestList_JSON_JQ(t *testing.T) {
{ID: "kb1", Name: "Marketing", UpdatedAt: now},
{ID: "kb2", Name: "Engineering", UpdatedAt: now.Add(-time.Hour)},
}
jopts := &cmdutil.JSONOptions{JQ: ".data.items | length"}
jopts := &cmdutil.JSONOptions{JQ: ". | length"}
if err := runList(context.Background(), &ListOptions{}, jopts, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
+7 -25
View File
@@ -18,9 +18,7 @@ import (
// relevant fields here are the id and the new pin state.
var kbPinFields = []string{"id", "is_pinned"}
type PinOptions struct {
DryRun bool
}
type PinOptions struct{}
// PinService is the narrow SDK surface this command depends on. The CLI
// reads current state before toggling so `pin`/`unpin` are idempotent —
@@ -51,10 +49,6 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C
if err != nil {
return err
}
opts.DryRun = cmdutil.IsDryRun(c)
if opts.DryRun {
return runPin(c.Context(), opts, jopts, nil, args[0], want)
}
cli, err := f.Client()
if err != nil {
return err
@@ -72,18 +66,6 @@ func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, s
if !want {
verb = "unpin"
}
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("%s knowledge base %s", verb, id)}
if opts.DryRun {
// Dry-run can't introspect state without a network call by design (see
// kb/delete.go for the same convention). Report what *would* run if
// state diverged; agents can disambiguate via a subsequent `kb view`.
return cmdutil.EmitDryRun(jopts.Enabled(), struct {
ID string `json:"id"`
Want bool `json:"want_pinned"`
}{id, want}, &format.Meta{KBID: id}, risk)
}
current, err := svc.GetKnowledgeBase(ctx, id)
if err != nil {
return cmdutil.WrapHTTP(err, "get knowledge base %s", id)
@@ -93,12 +75,12 @@ func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, s
if !want {
state = "unpinned"
}
// No-op path: tell agents what happened. The risk-write classification
// was the *requested* operation, not what occurred — surface it via a
// _meta.warning so audit logs don't count a write that wasn't made.
// No-op path: the resource is already in the requested state. We
// emit the current resource so callers see the canonical shape on
// both fresh-toggle and no-op paths. Human path prints a confirming
// line; agents observe via the unchanged is_pinned field.
if jopts.Enabled() {
meta := &format.Meta{KBID: id, Warnings: []string{fmt.Sprintf("already %s — no server call made", state)}}
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.Success(current, meta), jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, current, jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ %s is already %s\n", id, state)
return nil
@@ -109,7 +91,7 @@ func runPin(ctx context.Context, opts *PinOptions, jopts *cmdutil.JSONOptions, s
return cmdutil.WrapHTTP(err, "%s knowledge base %s", verb, id)
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk), jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, updated, jopts.Fields, jopts.JQ)
}
state := "pinned"
if !updated.IsPinned {
-10
View File
@@ -96,16 +96,6 @@ func TestPin_ToggleError(t *testing.T) {
assert.Equal(t, cmdutil.CodeServerError, typed.Code)
}
func TestPin_DryRun_StateDiffers(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
require.NoError(t, runPin(context.Background(), &PinOptions{DryRun: true}, &cmdutil.JSONOptions{}, svc, "kb_abc", true))
assert.False(t, svc.toggleCalled, "dry-run must not call toggle")
body := out.String()
assert.Contains(t, body, `"dry_run":true`)
assert.Contains(t, body, `"write"`)
}
func TestPin_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
+1 -1
View File
@@ -63,7 +63,7 @@ func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions,
return cmdutil.WrapHTTP(err, "get knowledge base %q", id)
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.Success(kb, nil), jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, kb, jopts.Fields, jopts.JQ)
}
// Human: KEY: VALUE
w := iostreams.IO.Out
+4 -4
View File
@@ -43,11 +43,11 @@ func TestGet_OK_JSON(t *testing.T) {
t.Fatalf("runGet: %v", err)
}
got := out.String()
if !strings.Contains(got, `"ok":true`) {
t.Errorf("expected ok:true in %q", got)
if !strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb1"`) {
t.Errorf("expected bare object starting with id, got %q", got)
}
if !strings.Contains(got, `"id":"kb1"`) {
t.Errorf("expected id field in %q", got)
if strings.Contains(got, `"ok":true`) {
t.Errorf("bare output must not carry envelope keys, got %q", got)
}
}