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
+82
View File
@@ -0,0 +1,82 @@
package format
import (
"bytes"
"encoding/json"
"io"
)
// WriteJSON serializes v as one-line JSON to w. Bare-data contract: no
// envelope wrapper. Each list command emits its array directly, each
// single-resource command emits its object directly. The shape is whatever
// the producing command marshals.
func WriteJSON(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
return enc.Encode(v)
}
// WriteJSONFiltered serializes v to w with optional field restriction and
// optional jq evaluation.
//
// - len(fields) == 0 → no field filter
// - jqExpr == "" → no jq filter
//
// Field filter rules (mirrors gh CLI's `--json field,field` semantics):
//
// - v marshals to a top-level array → each [*] object is restricted to
// the named keys
// - v marshals to a top-level object → the object is restricted to the
// named keys
// - v marshals to a scalar → unchanged
//
// Unknown field names are silently dropped so users can pass an aspirational
// field set across heterogenous list outputs without per-command tailoring
// (same policy as the old envelope filter).
func WriteJSONFiltered(w io.Writer, v any, fields []string, jqExpr string) error {
raw, err := marshalJSON(v)
if err != nil {
return err
}
if len(fields) > 0 {
raw, err = applyBareFieldFilter(raw, fields)
if err != nil {
return err
}
}
if jqExpr != "" {
return writeJQ(w, raw, jqExpr)
}
_, err = w.Write(raw)
return err
}
// marshalJSON encodes v to a newline-terminated byte slice using the same
// encoder settings as WriteJSON (HTML escaping disabled).
func marshalJSON(v any) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// applyBareFieldFilter dispatches on the JSON shape of raw and restricts
// elements / object keys to the named fields.
func applyBareFieldFilter(raw []byte, fields []string) ([]byte, error) {
trimmed := bytes.TrimSpace(raw)
if len(trimmed) == 0 {
return raw, nil
}
switch trimmed[0] {
case '[':
return filterArrayItems(raw, fields)
case '{':
return filterObjectKeys(raw, fields)
default:
return raw, nil
}
}
+139
View File
@@ -0,0 +1,139 @@
package format_test
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/format"
)
func TestWriteJSON_BareArray(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSON(buf, []map[string]string{
{"id": "1", "name": "alpha"},
{"id": "2", "name": "beta"},
}); err != nil {
t.Fatalf("err = %v", err)
}
if !bytes.HasPrefix(buf.Bytes(), []byte("[")) {
t.Errorf("expected bare JSON array, got %q", buf.String())
}
}
func TestWriteJSON_BareObject(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSON(buf, map[string]any{"id": "kb_x", "name": "Engineering"}); err != nil {
t.Fatalf("err = %v", err)
}
if !bytes.HasPrefix(buf.Bytes(), []byte("{")) {
t.Errorf("expected bare JSON object, got %q", buf.String())
}
if bytes.Contains(buf.Bytes(), []byte(`"ok":`)) || bytes.Contains(buf.Bytes(), []byte(`"data":`)) {
t.Errorf("bare output must not carry envelope keys: %s", buf.String())
}
}
func TestWriteJSONFiltered_FieldsOnArray(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha", "kb_id": "kb_x", "updated_at": "2026-01-01"},
{"id": "2", "name": "beta", "kb_id": "kb_x", "updated_at": "2026-01-02"},
}
if err := format.WriteJSONFiltered(buf, items, []string{"id", "name"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got []map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, buf.String())
}
if len(got) != 2 {
t.Fatalf("items len = %d, want 2", len(got))
}
for i, item := range got {
if _, has := item["kb_id"]; has {
t.Errorf("item[%d] should not have kb_id: %v", i, item)
}
if item["id"] == "" || item["name"] == "" {
t.Errorf("item[%d] missing kept fields: %v", i, item)
}
}
}
func TestWriteJSONFiltered_FieldsOnObject(t *testing.T) {
buf := &bytes.Buffer{}
obj := map[string]any{"id": "kb_x", "name": "Engineering", "owner": "alice"}
if err := format.WriteJSONFiltered(buf, obj, []string{"id", "name"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, buf.String())
}
if _, has := got["owner"]; has {
t.Errorf("should not retain owner: %v", got)
}
if got["id"] != "kb_x" || got["name"] != "Engineering" {
t.Errorf("kept fields missing: %v", got)
}
}
func TestWriteJSONFiltered_UnknownFieldSilent(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSONFiltered(buf, map[string]any{"id": "1"}, []string{"id", "nonexistent"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got map[string]any
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v", err)
}
if got["id"] != "1" {
t.Errorf("id missing: %v", got)
}
if _, has := got["nonexistent"]; has {
t.Errorf("nonexistent should be silently dropped: %v", got)
}
}
func TestWriteJSONFiltered_JQOnly(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha"},
{"id": "2", "name": "beta"},
}
if err := format.WriteJSONFiltered(buf, items, nil, ".[].id"); err != nil {
t.Fatalf("err = %v", err)
}
// gh CLI parity: string results render without JSON quotes.
lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
if len(lines) != 2 || lines[0] != "1" || lines[1] != "2" {
t.Errorf("jq output mismatch: %q", buf.String())
}
}
func TestWriteJSONFiltered_FieldsAndJQ(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha", "secret": "drop-me"},
{"id": "2", "name": "beta", "secret": "drop-me"},
}
// Field filter first → then jq selects from filtered shape.
if err := format.WriteJSONFiltered(buf, items, []string{"id"}, ".[].id"); err != nil {
t.Fatalf("err = %v", err)
}
out := buf.String()
if strings.Contains(out, "drop-me") {
t.Errorf("field filter must drop unrequested keys before jq: %q", out)
}
}
func TestWriteJSONFiltered_NilDataPassthrough(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSONFiltered(buf, nil, []string{"id"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
if strings.TrimSpace(buf.String()) != "null" {
t.Errorf("nil should marshal to bare null, got %q", buf.String())
}
}
+3 -8
View File
@@ -11,9 +11,9 @@ import (
// Envelope is the canonical success/failure shape returned by every command.
//
// v0.2 ADR-3 added Notice / Risk / DryRun. All three are absent on
// read-only commands; write commands populate Risk even on success so
// agents can record what action ran.
// v0.2 ADR-3 added Notice / Risk. Both are absent on read-only commands;
// write commands populate Risk even on success so agents can record what
// action ran.
type Envelope struct {
OK bool `json:"ok"`
Data any `json:"data,omitempty"`
@@ -21,11 +21,6 @@ type Envelope struct {
Meta *Meta `json:"_meta,omitempty"`
Notice *Notice `json:"_notice,omitempty"`
Risk *Risk `json:"risk,omitempty"`
// DryRun is intentionally NOT omitempty: AGENTS.md documents
// `dry_run: false` as the literal default in the schema example, so
// agents that pin the field's presence aren't surprised by it
// disappearing on non-dry-run envelopes.
DryRun bool `json:"dry_run"`
}
// Notice carries system-level advisories independent of the command outcome:
+1 -1
View File
@@ -16,7 +16,7 @@ import (
// - len(fields) == 0 → no field filter (full envelope)
// - jqExpr == "" → no jq filter (just write the envelope)
//
// The envelope structure (ok / data / error / _meta / risk / dry_run / _notice)
// The envelope structure (ok / data / error / _meta / risk / _notice)
// is preserved across field filtering — only Data is rewritten. jq operates
// on the entire envelope JSON so users can `--jq '.data.items[].id'`.
func WriteEnvelopeFiltered(w io.Writer, env Envelope, fields []string, jqExpr string) error {
+2 -3
View File
@@ -109,7 +109,7 @@ func TestWriteEnvelopeFiltered_UnknownFieldSilent(t *testing.T) {
}
func TestWriteEnvelopeFiltered_PreservesEnvelopeFields(t *testing.T) {
// Even with field filter, meta/risk/dry_run/error must be preserved.
// Even with field filter, meta/risk/error must be preserved.
env := format.Success(map[string]any{"items": []any{
map[string]any{"id": "1", "name": "x", "kb_id": "kb"},
}}, &format.Meta{KBID: "kb_x", RequestID: "req_123"})
@@ -119,12 +119,11 @@ func TestWriteEnvelopeFiltered_PreservesEnvelopeFields(t *testing.T) {
t.Fatalf("err = %v", err)
}
var got struct {
OK bool `json:"ok"`
OK bool `json:"ok"`
Meta *format.Meta `json:"_meta"`
Data struct {
Items []map[string]any `json:"items"`
} `json:"data"`
DryRun bool `json:"dry_run"`
}
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, buf.String())