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
+19 -25
View File
@@ -8,16 +8,15 @@
// fail — failed; "hint" actionable
// skip — cascade-skipped (prereq failed) or --offline mode
//
// Envelope (v0.2):
// - any check is fail → envelope.ok=false, exit 1 (RunE returns SilentError
// so the data envelope is still emitted; the framework's error-envelope
// printer is bypassed for this command)
// - warn only / all ok → envelope.ok=true, exit 0
// - warn does NOT flip envelope.ok
// JSON output emits the Result object directly (bare data). Exit-code
// signal:
// - any check is fail → exit 1 (RunE returns SilentError so the data
// object is still emitted)
// - warn only / all ok → exit 0
//
// data.summary.all_passed gives the agent a one-line short-circuit; v0.2
// keeps it true ONLY when no warn / fail / skip checks are present. Agents
// SHOULD also inspect data.checks[].status to distinguish warn from ok.
// summary.all_passed gives the agent a one-line short-circuit; it is true
// ONLY when no warn / fail / skip checks are present. Agents SHOULD also
// inspect checks[].status to distinguish warn from ok.
package doctor
import (
@@ -71,8 +70,8 @@ type Check struct {
// Summary is the agent-friendly short-circuit payload (spec §1.2).
//
// AllPassed is true only when there are zero warn/fail/skip rows; warn does
// not block exit-0 (envelope.ok stays true) but it does flip AllPassed so
// agents reading just the boolean still notice the soft issue.
// not block exit-0 but it does flip AllPassed so agents reading just the
// boolean still notice the soft issue.
type Summary struct {
AllPassed bool `json:"all_passed"`
Passed int `json:"passed"`
@@ -81,7 +80,7 @@ type Summary struct {
Skipped int `json:"skipped"`
}
// Result is the full envelope data.
// Result is the bare JSON payload.
type Result struct {
Summary Summary `json:"summary"`
Checks []Check `json:"checks"`
@@ -114,9 +113,9 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
cliVer, _, _ := build.Info()
r := runChecks(c.Context(), opts, svc, cliVer)
emit(jopts, r)
// v0.2 exit-code policy: fail → exit 1; warn / ok / skip → exit 0.
// SilentError suppresses both the human "error: ..." line and the
// error envelope printer, so the data envelope already written by
// Exit-code policy: fail → exit 1; warn / ok / skip → exit 0.
// SilentError suppresses both the human "error: ..." line and
// the stderr error formatter, so the JSON already written by
// emit() is the only stdout content.
if r.Summary.Failed > 0 {
return cmdutil.SilentError
@@ -127,7 +126,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache (located at $XDG_CACHE_HOME/weknora/server-info.yaml); force re-probe")
cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage (credential_storage check still runs)")
cmdutil.AddJSONFlags(cmd, doctorFields)
aiclient.SetAgentHelp(cmd, "Returns 4 health checks. AGENT short-circuit: read data.summary.all_passed; if false, inspect data.checks[].status (ok/warn/fail/skip). exit 1 only when any status=fail; warn does not change envelope.ok.")
aiclient.SetAgentHelp(cmd, "Returns 4 health checks as a bare JSON object {summary, checks}. AGENT short-circuit: read summary.all_passed; if false, inspect checks[].status (ok/warn/fail/skip). exit 1 only when any status=fail; warn does not affect exit.")
return cmd
}
@@ -332,17 +331,12 @@ func summarize(cs []Check) Summary {
return s
}
// emit renders the doctor result. JSON path constructs the envelope directly
// rather than calling format.Success because envelope.ok must reflect "no
// fail" — warn does not flip it (per package doc), but fail does. We can't
// use format.Failure either, since that drops the data field.
// emit renders the doctor result. The JSON path emits the Result directly;
// pass/fail signaling is conveyed by summary.failed (and the process exit
// code, set by the caller).
func emit(jopts *cmdutil.JSONOptions, r Result) {
if jopts.Enabled() {
_ = format.WriteEnvelopeFiltered(
iostreams.IO.Out,
format.Envelope{OK: r.Summary.Failed == 0, Data: r},
jopts.Fields, jopts.JQ,
)
_ = format.WriteJSONFiltered(iostreams.IO.Out, r, jopts.Fields, jopts.JQ)
return
}
for _, c := range r.Checks {
+25 -16
View File
@@ -79,7 +79,7 @@ func TestDoctor_AllOK(t *testing.T) {
}
emit(&cmdutil.JSONOptions{}, r)
if !strings.Contains(out.String(), `"all_passed":true`) {
t.Errorf("envelope should embed all_passed=true, got %q", out.String())
t.Errorf("bare output should embed all_passed=true, got %q", out.String())
}
}
@@ -278,14 +278,19 @@ func TestDoctor_VersionSkewWarns(t *testing.T) {
t.Error("AllPassed must be false when any check is warn")
}
// Envelope ok stays true (warn is non-blocking).
// Wire shape: warn-only run still has summary.failed=0 (bare data
// carries the signal; exit code stays 0).
out, _ := iostreams.SetForTest(t)
emit(&cmdutil.JSONOptions{}, r)
if !strings.Contains(out.String(), `"ok":true`) {
t.Errorf("envelope.ok must be true on warn-only run, got %q", out.String())
body := out.String()
if strings.Contains(body, `"ok":`) {
t.Errorf("bare doctor output must not carry envelope keys, got %q", body)
}
if !strings.Contains(out.String(), `"status":"warn"`) {
t.Errorf("envelope must surface status=warn, got %q", out.String())
if !strings.Contains(body, `"failed":0`) {
t.Errorf("bare output must carry failed:0 on warn-only run, got %q", body)
}
if !strings.Contains(body, `"status":"warn"`) {
t.Errorf("bare output must surface status=warn, got %q", body)
}
}
@@ -367,10 +372,10 @@ func TestDoctor_CredStoreFactoryError(t *testing.T) {
}
}
// TestDoctor_EmitEnvelope_OK_WhenWarnOnly pins the wire contract: warn never
// flips envelope.ok. emit() is the seam between Result and what agents
// observe; we test it in isolation rather than relying on summary fields.
func TestDoctor_EmitEnvelope_OK_WhenWarnOnly(t *testing.T) {
// TestDoctor_BareJSON_WarnDoesNotSignalFail pins the wire contract: warn
// keeps summary.failed=0 (so exit code stays 0). emit() is the seam between
// Result and what agents observe.
func TestDoctor_BareJSON_WarnDoesNotSignalFail(t *testing.T) {
out, _ := iostreams.SetForTest(t)
r := Result{
Summary: Summary{AllPassed: false, Passed: 3, Warned: 1},
@@ -383,13 +388,17 @@ func TestDoctor_EmitEnvelope_OK_WhenWarnOnly(t *testing.T) {
}
emit(&cmdutil.JSONOptions{}, r)
got := out.String()
if !strings.Contains(got, `"ok":true`) {
t.Errorf("envelope.ok must be true on warn-only result, got %q", got)
if !strings.Contains(got, `"failed":0`) {
t.Errorf("warn-only result must have summary.failed=0 (exit-0 signal), got %q", got)
}
if strings.Contains(got, `"ok":`) {
t.Errorf("bare output must not carry envelope keys, got %q", got)
}
}
// TestDoctor_EmitEnvelope_NotOK_OnFail pins the dual: any fail flips ok=false.
func TestDoctor_EmitEnvelope_NotOK_OnFail(t *testing.T) {
// TestDoctor_BareJSON_FailRaisesSummary pins the dual: any fail surfaces in
// summary.failed (caller maps that to exit 1 via SilentError).
func TestDoctor_BareJSON_FailRaisesSummary(t *testing.T) {
out, _ := iostreams.SetForTest(t)
r := Result{
Summary: Summary{AllPassed: false, Passed: 2, Failed: 1, Skipped: 1},
@@ -402,8 +411,8 @@ func TestDoctor_EmitEnvelope_NotOK_OnFail(t *testing.T) {
}
emit(&cmdutil.JSONOptions{}, r)
got := out.String()
if !strings.Contains(got, `"ok":false`) {
t.Errorf("envelope.ok must be false when any check fails, got %q", got)
if !strings.Contains(got, `"failed":1`) {
t.Errorf("fail must surface in summary.failed, got %q", got)
}
}