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 -3
View File
@@ -68,9 +68,7 @@ func runList(jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(entries, &format.Meta{Context: cfg.CurrentContext}),
jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, entries, jopts.Fields, jopts.JQ)
}
if len(entries) == 0 {
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` to create one.")
+10 -18
View File
@@ -48,7 +48,7 @@ func TestList_Empty(t *testing.T) {
assert.Contains(t, out.String(), "No contexts configured")
}
func TestList_JSONEnvelope(t *testing.T) {
func TestList_JSON_BareArray(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cfg := &config.Config{
CurrentContext: "prod",
@@ -59,24 +59,16 @@ func TestList_JSONEnvelope(t *testing.T) {
}
require.NoError(t, runList(&cmdutil.JSONOptions{}, newListFactory(cfg)))
var env struct {
OK bool `json:"ok"`
Data []listEntry `json:"data"`
Meta struct {
Context string `json:"context"`
} `json:"_meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.True(t, env.OK)
assert.Equal(t, "prod", env.Meta.Context)
require.Len(t, env.Data, 2)
var got []listEntry
require.NoError(t, json.Unmarshal(out.Bytes(), &got))
require.Len(t, got, 2)
// Sorted: prod < staging.
assert.Equal(t, "prod", env.Data[0].Name)
assert.True(t, env.Data[0].Current)
assert.Equal(t, ModeBearer, env.Data[0].Mode)
assert.Equal(t, "staging", env.Data[1].Name)
assert.False(t, env.Data[1].Current)
assert.Equal(t, ModeAPIKey, env.Data[1].Mode)
assert.Equal(t, "prod", got[0].Name)
assert.True(t, got[0].Current)
assert.Equal(t, ModeBearer, got[0].Mode)
assert.Equal(t, "staging", got[1].Name)
assert.False(t, got[1].Current)
assert.Equal(t, ModeAPIKey, got[1].Mode)
}
func TestModeFromRefs(t *testing.T) {
+1 -6
View File
@@ -211,12 +211,7 @@ func saveContextRef(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.F
result.User = user.Email
result.TenantID = user.TenantID
}
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(result, &format.Meta{
Context: opts.Context,
TenantID: ctx.TenantID,
}),
jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, result, jopts.Fields, jopts.JQ)
}
who := opts.Context
if user != nil {
+1 -3
View File
@@ -97,9 +97,7 @@ func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(logoutResult{Removed: targets}, nil),
jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, logoutResult{Removed: targets}, jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d context(s): %s\n", len(targets), strings.Join(targets, ", "))
return nil
+1 -3
View File
@@ -113,9 +113,7 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, jopts *cmdutil.JSONOp
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(refreshResult{Context: name}, &format.Meta{Context: name}),
jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, refreshResult{Context: name}, jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for context %s\n", name)
return nil
+6 -10
View File
@@ -2,7 +2,6 @@ package auth
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
@@ -12,7 +11,6 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
@@ -207,14 +205,12 @@ func TestRefresh_JSONOutput(t *testing.T) {
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{Success: true, AccessToken: "a", RefreshToken: "r"}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.JSONOptions{}, f, stubSvc(svc)))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.True(t, env.OK)
// payload should not leak the actual token values.
body := out.String()
assert.NotContains(t, body, "ok-refresh", "envelope must not leak refresh token")
assert.NotContains(t, body, "\"a\"", "envelope must not leak the new access token")
assert.NotContains(t, body, "\"r\"", "envelope must not leak the new refresh token")
// payload must not leak the actual token values.
assert.NotContains(t, body, "ok-refresh", "output must not leak refresh token")
assert.NotContains(t, body, "\"a\"", "output must not leak the new access token")
assert.NotContains(t, body, "\"r\"", "output must not leak the new refresh token")
// must mention the context name so agents can confirm what was refreshed
assert.True(t, strings.Contains(body, "prod"), "envelope should reference the refreshed context")
assert.True(t, strings.Contains(body, "prod"), "output should reference the refreshed context")
assert.NotContains(t, body, `"ok":`)
}
+1 -8
View File
@@ -73,23 +73,16 @@ func runStatus(ctx context.Context, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
}
if jopts.Enabled() {
var tenantID uint64
result := statusResult{Context: cfg.CurrentContext}
if user != nil {
result.UserID = user.ID
result.Email = user.Email
result.TenantID = user.TenantID
tenantID = user.TenantID
}
if tenant != nil {
result.TenantName = tenant.Name
}
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(result, &format.Meta{
Context: cfg.CurrentContext,
TenantID: tenantID,
}),
jopts.Fields, jopts.JQ)
return format.WriteJSONFiltered(iostreams.IO.Out, result, jopts.Fields, jopts.JQ)
}
host := ""
+4 -2
View File
@@ -70,8 +70,10 @@ func TestRunStatus_JSONOutput(t *testing.T) {
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
svc := &fakeStatusService{resp: newCurrentUserResponse(&sdk.AuthUser{ID: "u1", Email: "a@b.c", TenantID: 7}, nil)}
require.NoError(t, runStatus(context.Background(), &cmdutil.JSONOptions{}, f, svc))
assert.True(t, strings.HasPrefix(out.String(), `{"ok":true`), "got: %q", out.String())
assert.Contains(t, out.String(), `"email":"a@b.c"`)
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"context":"prod"`), "expected bare object, got: %q", got)
assert.NotContains(t, got, `"ok":`)
assert.Contains(t, got, `"email":"a@b.c"`)
}
func TestRunStatus_NoSDKClient(t *testing.T) {
+3 -4
View File
@@ -12,7 +12,7 @@ import (
)
// authTokenFields lists fields available for `auth token --json=` projection.
// Single-resource envelope shape (data is the token result, not data.items).
// Single-resource shape: filter applies to the bare token object directly.
var authTokenFields = []string{"token", "mode", "context"}
type tokenResult struct {
@@ -117,9 +117,8 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(tokenResult{Token: token, Mode: mode, Context: ctxName},
&format.Meta{Context: ctxName}),
return format.WriteJSONFiltered(iostreams.IO.Out,
tokenResult{Token: token, Mode: mode, Context: ctxName},
jopts.Fields, jopts.JQ)
}
+13 -21
View File
@@ -80,22 +80,16 @@ func TestAuthToken_JSON(t *testing.T) {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil {
t.Fatalf("runToken: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data struct {
Token string `json:"token"`
Mode string `json:"mode"`
Context string `json:"context"`
} `json:"data"`
var got struct {
Token string `json:"token"`
Mode string `json:"mode"`
Context string `json:"context"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, out.String())
}
if !env.OK {
t.Errorf("ok=false")
}
if env.Data.Token != "jwt-xyz" || env.Data.Mode != "bearer" || env.Data.Context != "prod" {
t.Errorf("envelope payload wrong: %+v", env.Data)
if got.Token != "jwt-xyz" || got.Mode != "bearer" || got.Context != "prod" {
t.Errorf("payload wrong: %+v", got)
}
}
@@ -114,17 +108,15 @@ func TestAuthToken_JSON_FieldFilter(t *testing.T) {
if err := runToken(tokenTestFactory(t, cfg, store), jopts); err != nil {
t.Fatalf("runToken: %v", err)
}
var env struct {
Data map[string]any `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", err)
}
if _, has := env.Data["mode"]; has {
t.Errorf("mode should be filtered out: %+v", env.Data)
if _, has := got["mode"]; has {
t.Errorf("mode should be filtered out: %+v", got)
}
if env.Data["token"] != "sk_42" {
t.Errorf("token wrong: %+v", env.Data)
if got["token"] != "sk_42" {
t.Errorf("token wrong: %+v", got)
}
}