refactor(cli): delete envelope infrastructure, errors to stderr

Removes the entire envelope machinery now that every success path
emits bare JSON:

- cli/internal/format/envelope.go (Envelope, Success, Failure,
  SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice,
  VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests.
- cli/internal/format/filter.go envelope-specific helpers
  (WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter,
  filterDataPayload, filterObjectData); the reusable
  filterArrayItems / filterObjectKeys / writeJQ stay for bare.go.
- cli/internal/cmdutil/exporter.go + tests (envelope-only).
- cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody +
  operationRiskOf + Error.OperationRisk field + OperationRisk struct.

Error path: all errors now go to stderr via cmdutil.PrintError in
`code: message\nhint: ...` form, regardless of --json. Stdout stays
empty (or holds the partial-success the command already wrote) so
downstream `--json | jq` pipelines never have to filter error shapes
out of the success stream. Typed exit codes (3 auth.* / 4
resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.*
+ network.* / 10 input.confirmation_required) carry the failure
class for agents that branch on it.

Acceptance contract:
- envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden).
- testdata/envelopes/ → testdata/wire/.
- Error-path cases assert the typed code substring on stderr.
- Orphan whoami.*.json goldens deleted.

AGENTS.md + README.md rewritten for the bare-data contract:
- Drop envelope schema section + dry-run rule.
- Document bare JSON on stdout + `code: msg\nhint: …` on stderr.
- ADR-3 reframed around bare data and why error separation matters
  for `--json | jq` pipelines.

WriteJSONFiltered short-circuits to WriteJSON when both filters are
empty (skip the marshal-buffer round-trip for the common case).

Final review pass:
- Fix wire-contract bug: `--json id,name` (space form) is broken by
  pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the
  field-discovery help text all switched to `--json=id,name`.
- Fix `weknora api --jq` silently ignored: api.go now routes through
  WriteJSONFiltered with jopts.JQ.
- AGENTS.md: drop the false claim that `auth logout` honors `-y`
  (logout is local-only with no ConfirmDestructive guard); list the
  actual destructive commands instead.
- Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape
  (was still parsing `out["data"]` / `env["ok"]`).
- Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated
  `format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields,
  jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the
  format import from 22 cmd/* files.
- Delete single-caller `cmdutil.MustRequireFlag`; inline as
  `_ = cmd.MarkFlagRequired(...)` everywhere.
- Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the
  only write command relying on runtime --name validation while
  `context add` already used the cobra-level mark.
- `context use`: register `--json` / `--jq` (was always emitting JSON
  unconditionally with no human path and no flag — diverged from
  every other write command); human mode now prints
  `✓ Switched context to X (was Y)`.
- Replace per-package `confirmPrompter` / `scriptedConfirm` /
  `errPrompter` test doubles with `testutil.ConfirmPrompter`.
- Rename `chatService` → `ChatService` (export to match siblings
  `ListService` / `ViewService`); rename `printUploadSuccess` →
  `renderUploadSuccess` (siblings use `render*`).
- `defaultHint(CodeResourceNotFound)`: drop the hardcoded
  "list available with `weknora kb list`" — misleading on agent /
  doc / session 404. Replaced with "verify the resource ID and try
  again".
- Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only"
  historical tags from production comments and a few test
  descriptions.
This commit is contained in:
nullkey
2026-05-15 01:51:11 +08:00
committed by lyingbug
parent cc8254f862
commit e623e8208f
94 changed files with 599 additions and 1421 deletions
+2 -3
View File
@@ -32,7 +32,6 @@ import (
"github.com/Tencent/WeKnora/cli/internal/build"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/compat"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
@@ -207,7 +206,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
// the loader knows authoritatively which branch it took, time-based
// derivation from ProbedAt is unreliable since SaveCache uses time.Now().
//
// v0.2 mapping:
// Mapping:
//
// compat.OK → StatusOK
// compat.SoftWarn → StatusWarn (server older but in-range; soft skew)
@@ -336,7 +335,7 @@ func summarize(cs []Check) Summary {
// code, set by the caller).
func emit(jopts *cmdutil.JSONOptions, r Result) {
if jopts.Enabled() {
_ = format.WriteJSONFiltered(iostreams.IO.Out, r, jopts.Fields, jopts.JQ)
_ = jopts.Emit(iostreams.IO.Out, r)
return
}
for _, c := range r.Checks {
+12 -11
View File
@@ -236,11 +236,12 @@ func TestDoctor_NoCache_BypassesCache(t *testing.T) {
}
}
// TestDoctor_VersionSkewWarns covers the v0.2 soft-skew path: server is older
// TestDoctor_VersionSkewWarns covers the soft-skew path: server is older
// than CLI by ≥ 1 minor (same major, in compat range) → server_version=warn,
// envelope.ok stays true, all_passed=false (so agents reading just the
// boolean still notice). The compat decision lives in cli/internal/compat;
// this test pins the doctor-side mapping (compat.SoftWarn → StatusWarn).
// summary.failed=0 (exit 0), summary.all_passed=false (so agents reading
// just the boolean still notice). The compat decision lives in
// cli/internal/compat; this test pins the doctor-side mapping
// (compat.SoftWarn → StatusWarn).
func TestDoctor_VersionSkewWarns(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t)
@@ -315,7 +316,7 @@ func TestDoctor_HardErrorStillFails(t *testing.T) {
}
}
// TestDoctor_KeychainFallbackWarns covers credential_storage's v0.2 third
// TestDoctor_KeychainFallbackWarns covers credential_storage's third
// state: keyring unavailable, fell back to FileStore (agent containers,
// headless CI, WSL without DBus). The check should warn — secrets still
// persist (0600 file perms) but the OS-backed path was unreachable.
@@ -439,7 +440,7 @@ func TestDoctor_HumanMarker_Warn(t *testing.T) {
// TestDoctor_WarnedField_OmittedAtZero protects the JSON wire compactness:
// `warned` carries omitempty, so a clean run has no warned key. Existing
// agents inspecting older envelopes shouldn't see a sudden new field unless
// agents inspecting older outputs shouldn't see a sudden new field unless
// it actually fired.
func TestDoctor_WarnedField_OmittedAtZero(t *testing.T) {
out, _ := iostreams.SetForTest(t)
@@ -455,14 +456,14 @@ func TestDoctor_WarnedField_OmittedAtZero(t *testing.T) {
emit(&cmdutil.JSONOptions{}, r)
got := out.String()
if strings.Contains(got, `"warned"`) {
t.Errorf("envelope should omit `warned` field when zero, got %q", got)
t.Errorf("output should omit `warned` field when zero, got %q", got)
}
}
// TestDoctor_RunE_FailReturnsSilentError is a behavior test on NewCmd: when
// any check is fail, RunE must return cmdutil.SilentError so the framework
// exit-1 path runs WITHOUT overwriting the data envelope emit() already
// wrote. This is the v0.2 contract change from v0.1's "always nil".
// TestDoctor_RunE_FailReturnsSilentError is a behavior test on NewCmd:
// when any check is fail, RunE must return cmdutil.SilentError so the
// framework exit-1 path runs without writing a second error line on top
// of the data object emit() already wrote.
//
// SilenceErrors/SilenceUsage on the leaf cobra.Command suppress cobra's own
// "Error: ..." + usage dump that would otherwise leak to stderr when running