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:
@@ -6,10 +6,9 @@ import (
|
||||
"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.
|
||||
// WriteJSON serializes v as one-line JSON to w. Bare-data contract: list
|
||||
// commands emit their array directly, single-resource commands emit their
|
||||
// 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)
|
||||
@@ -31,9 +30,11 @@ func WriteJSON(w io.Writer, v any) error {
|
||||
// - 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).
|
||||
// field set across heterogenous list outputs.
|
||||
func WriteJSONFiltered(w io.Writer, v any, fields []string, jqExpr string) error {
|
||||
if len(fields) == 0 && jqExpr == "" {
|
||||
return WriteJSON(w, v)
|
||||
}
|
||||
raw, err := marshalJSON(v)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
// Package format renders command output: JSON envelope, jq, template, table.
|
||||
//
|
||||
// Non-TTY default = JSON envelope (ADR-5). Envelope schema is the contract
|
||||
// shared with `weknora mcp serve` tools and external agents.
|
||||
package format
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Envelope is the canonical success/failure shape returned by every command.
|
||||
//
|
||||
// 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"`
|
||||
Error *ErrorBody `json:"error,omitempty"`
|
||||
Meta *Meta `json:"_meta,omitempty"`
|
||||
Notice *Notice `json:"_notice,omitempty"`
|
||||
Risk *Risk `json:"risk,omitempty"`
|
||||
}
|
||||
|
||||
// Notice carries system-level advisories independent of the command outcome:
|
||||
// CLI update available, server-CLI version skew, etc. Agents read these to
|
||||
// surface upgrade prompts to users without polluting `data`.
|
||||
type Notice struct {
|
||||
Update *UpdateNotice `json:"update,omitempty"`
|
||||
VersionSkew *VersionSkewNotice `json:"version_skew,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateNotice indicates a newer CLI version is available.
|
||||
type UpdateNotice struct {
|
||||
Available bool `json:"available"`
|
||||
Current string `json:"current"`
|
||||
Latest string `json:"latest,omitempty"`
|
||||
}
|
||||
|
||||
// VersionSkewNotice indicates the server is behind the CLI within the compat
|
||||
// window. `Level` mirrors doctor's status semantics: "warn" (degraded but
|
||||
// functional) or "error" (out of compat).
|
||||
type VersionSkewNotice struct {
|
||||
Client string `json:"client"`
|
||||
Server string `json:"server"`
|
||||
Level string `json:"level"`
|
||||
}
|
||||
|
||||
// Risk classifies the operation the user is performing — not the error.
|
||||
// Agents inspect this on every envelope. When Level == RiskHighRiskWrite and
|
||||
// the operation requires confirmation (no -y), the CLI exits 10. See
|
||||
// cli/AGENTS.md "Exit codes".
|
||||
type Risk struct {
|
||||
Level RiskLevel `json:"level"`
|
||||
Action string `json:"action,omitempty"`
|
||||
}
|
||||
|
||||
// Meta carries non-payload context fields useful to agents and observability.
|
||||
//
|
||||
// Pagination metadata (Page / PageSize / Total) lives here rather than in
|
||||
// data.{...} so every list command's `data` field has the same shape —
|
||||
// always `{items: [...]}` — and agents can branch on the resource type
|
||||
// without per-list parser variants.
|
||||
type Meta struct {
|
||||
Context string `json:"context,omitempty"`
|
||||
TenantID uint64 `json:"tenant_id,omitempty"`
|
||||
KBID string `json:"kb_id,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
HasMore bool `json:"has_more,omitempty"`
|
||||
Page int `json:"page,omitempty"`
|
||||
PageSize int `json:"page_size,omitempty"`
|
||||
Total int64 `json:"total,omitempty"`
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
AppliedFilters []string `json:"applied_filters,omitempty"`
|
||||
}
|
||||
|
||||
// RiskLevel classifies an operation. Agents use this to decide whether to
|
||||
// retry, require explicit user approval, or stop.
|
||||
type RiskLevel string
|
||||
|
||||
const (
|
||||
RiskRead RiskLevel = "read"
|
||||
RiskWrite RiskLevel = "write"
|
||||
RiskHighRiskWrite RiskLevel = "high-risk-write"
|
||||
)
|
||||
|
||||
// ErrorBody is the failure shape. `code` is a stable namespaced ID (e.g.
|
||||
// "auth.unauthenticated"); `hint` is an actionable next step. Operation-level
|
||||
// risk lives at the envelope level (Envelope.Risk), not here.
|
||||
type ErrorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
Context string `json:"context,omitempty"`
|
||||
Retryable bool `json:"retryable,omitempty"`
|
||||
ConsoleURL string `json:"console_url,omitempty"`
|
||||
Details map[string]any `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// WriteEnvelope serializes env as one-line JSON to w. Used for non-TTY output
|
||||
// and for `--json` per-command mode (the omnibus `--agent` mode-switch was
|
||||
// removed in v0.2 ADR-3; see cli/AGENTS.md for the agent contract).
|
||||
func WriteEnvelope(w io.Writer, env Envelope) error {
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
return enc.Encode(env)
|
||||
}
|
||||
|
||||
// Success constructs a success envelope.
|
||||
func Success(data any, meta *Meta) Envelope {
|
||||
return Envelope{OK: true, Data: data, Meta: meta}
|
||||
}
|
||||
|
||||
// SuccessWithRisk is Success + a per-operation Risk classification. Used by
|
||||
// every write command (kb create/delete, doc upload/delete, api POST/PUT/
|
||||
// DELETE, ...) so an agent reading any envelope can tell what kind of
|
||||
// operation produced it without parsing the data shape.
|
||||
func SuccessWithRisk(data any, meta *Meta, risk *Risk) Envelope {
|
||||
return Envelope{OK: true, Data: data, Meta: meta, Risk: risk}
|
||||
}
|
||||
|
||||
// Failure constructs a failure envelope.
|
||||
func Failure(err *ErrorBody) Envelope {
|
||||
return Envelope{OK: false, Error: err}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package format
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSuccessEnvelope(t *testing.T) {
|
||||
env := Success(map[string]string{"id": "kb_abc"}, &Meta{Context: "prod", RequestID: "cli-01"})
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, WriteEnvelope(&buf, env))
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
assert.Equal(t, true, got["ok"])
|
||||
assert.NotNil(t, got["data"])
|
||||
assert.NotNil(t, got["_meta"])
|
||||
assert.Nil(t, got["error"])
|
||||
}
|
||||
|
||||
func TestFailureEnvelope(t *testing.T) {
|
||||
env := Failure(&ErrorBody{
|
||||
Code: "auth.unauthenticated",
|
||||
Message: "no creds",
|
||||
Hint: "run weknora auth login",
|
||||
Retryable: false,
|
||||
})
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, WriteEnvelope(&buf, env))
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
assert.Equal(t, false, got["ok"])
|
||||
errBody := got["error"].(map[string]any)
|
||||
assert.Equal(t, "auth.unauthenticated", errBody["code"])
|
||||
assert.Equal(t, "run weknora auth login", errBody["hint"])
|
||||
}
|
||||
|
||||
func TestEnvelope_RiskAndNotice(t *testing.T) {
|
||||
env := Success(map[string]string{"id": "kb_x"}, nil)
|
||||
env.Risk = &Risk{Level: RiskHighRiskWrite, Action: "delete kb_x"}
|
||||
env.Notice = &Notice{Update: &UpdateNotice{Available: true, Current: "0.2.0", Latest: "0.3.0"}}
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, WriteEnvelope(&buf, env))
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
risk := got["risk"].(map[string]any)
|
||||
assert.Equal(t, "high-risk-write", risk["level"])
|
||||
assert.Equal(t, "delete kb_x", risk["action"])
|
||||
notice := got["_notice"].(map[string]any)
|
||||
upd := notice["update"].(map[string]any)
|
||||
assert.Equal(t, true, upd["available"])
|
||||
assert.Equal(t, "0.3.0", upd["latest"])
|
||||
}
|
||||
|
||||
func TestEnvelope_NoEscapeHTML(t *testing.T) {
|
||||
// Hints / messages may include & or <; ensure we don't HTML-escape them
|
||||
// (would break agent jq pipelines).
|
||||
env := Failure(&ErrorBody{Code: "x", Message: "a & b < c"})
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, WriteEnvelope(&buf, env))
|
||||
assert.Contains(t, buf.String(), "a & b < c")
|
||||
}
|
||||
@@ -9,127 +9,12 @@ import (
|
||||
"github.com/itchyny/gojq"
|
||||
)
|
||||
|
||||
// WriteEnvelopeFiltered serializes env to w, optionally restricting
|
||||
// data.items[*] (for list envelopes) or data (for single-resource envelopes)
|
||||
// to the named fields, then applying a jq expression on the result.
|
||||
//
|
||||
// - len(fields) == 0 → no field filter (full envelope)
|
||||
// - jqExpr == "" → no jq filter (just write the envelope)
|
||||
//
|
||||
// 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 {
|
||||
raw, err := marshalEnvelope(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(fields) > 0 {
|
||||
raw, err = applyFieldFilter(raw, fields)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if jqExpr != "" {
|
||||
return writeJQ(w, raw, jqExpr)
|
||||
}
|
||||
_, err = w.Write(raw)
|
||||
return err
|
||||
}
|
||||
|
||||
// marshalEnvelope returns the canonical newline-terminated envelope JSON used
|
||||
// by the non-filtered path. Identical to WriteEnvelope but as bytes.
|
||||
func marshalEnvelope(env Envelope) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// applyFieldFilter rewrites envelope.data so that nested objects keep only
|
||||
// the named keys. The shape rules:
|
||||
//
|
||||
// - data is an object with `items` (the standard list envelope shape):
|
||||
// filter each items[*] to the named fields.
|
||||
// - data is an object without `items` (single-resource envelope):
|
||||
// filter data itself.
|
||||
// - data is an array (uncommon — currently no command produces this, but
|
||||
// defensive): filter each [*].
|
||||
// - data is nil / scalar: unchanged.
|
||||
//
|
||||
// Unknown field names are silently ignored so a user may pass an
|
||||
// aspirational field set across heterogenous list outputs without per-
|
||||
// command tailoring.
|
||||
func applyFieldFilter(envelopeJSON []byte, fields []string) ([]byte, error) {
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.Unmarshal(envelopeJSON, &raw); err != nil {
|
||||
return nil, fmt.Errorf("field filter: parse envelope: %w", err)
|
||||
}
|
||||
dataRaw, ok := raw["data"]
|
||||
if !ok || len(dataRaw) == 0 || string(dataRaw) == "null" {
|
||||
return envelopeJSON, nil
|
||||
}
|
||||
|
||||
filtered, err := filterDataPayload(dataRaw, fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw["data"] = filtered
|
||||
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// filterDataPayload dispatches on the shape of the data JSON value.
|
||||
func filterDataPayload(dataRaw json.RawMessage, fields []string) (json.RawMessage, error) {
|
||||
trimmed := bytes.TrimSpace(dataRaw)
|
||||
if len(trimmed) == 0 {
|
||||
return dataRaw, nil
|
||||
}
|
||||
switch trimmed[0] {
|
||||
case '{':
|
||||
return filterObjectData(dataRaw, fields)
|
||||
case '[':
|
||||
return filterArrayItems(dataRaw, fields)
|
||||
default:
|
||||
// scalar (number / string / bool / null) — nothing to filter
|
||||
return dataRaw, nil
|
||||
}
|
||||
}
|
||||
|
||||
// filterObjectData filters either data.items[*] (list shape) or data (single
|
||||
// resource).
|
||||
func filterObjectData(dataRaw json.RawMessage, fields []string) (json.RawMessage, error) {
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(dataRaw, &obj); err != nil {
|
||||
return nil, fmt.Errorf("field filter: parse data object: %w", err)
|
||||
}
|
||||
if items, ok := obj["items"]; ok {
|
||||
filtered, err := filterArrayItems(items, fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
obj["items"] = filtered
|
||||
return json.Marshal(obj)
|
||||
}
|
||||
// Single-resource envelope: filter the data object itself.
|
||||
return filterObjectKeys(dataRaw, fields)
|
||||
}
|
||||
|
||||
// filterArrayItems applies filterObjectKeys to each element of an array.
|
||||
// Non-object elements (e.g. an array of strings) are passed through.
|
||||
func filterArrayItems(arrayRaw json.RawMessage, fields []string) (json.RawMessage, error) {
|
||||
var items []json.RawMessage
|
||||
if err := json.Unmarshal(arrayRaw, &items); err != nil {
|
||||
return nil, fmt.Errorf("field filter: parse data items: %w", err)
|
||||
return nil, fmt.Errorf("field filter: parse array: %w", err)
|
||||
}
|
||||
for i, item := range items {
|
||||
trimmed := bytes.TrimSpace(item)
|
||||
@@ -161,21 +46,20 @@ func filterObjectKeys(objRaw json.RawMessage, fields []string) (json.RawMessage,
|
||||
return json.Marshal(dst)
|
||||
}
|
||||
|
||||
// writeJQ evaluates expr against envelopeJSON and writes each result line
|
||||
// by line to w. String results render without quotes (so `--jq '.x.name'`
|
||||
// yields shell-friendly bare strings); non-string results use
|
||||
// encoding/json.
|
||||
// writeJQ evaluates expr against raw and writes each result line by line to w.
|
||||
// String results render without quotes (so `--jq '.name'` yields shell-friendly
|
||||
// bare strings); non-string results use encoding/json.
|
||||
//
|
||||
// Returns input.invalid_argument-shaped errors via plain errors.New + fmt;
|
||||
// the caller is responsible for wrapping with cmdutil.NewError if it wants
|
||||
// the typed envelope code.
|
||||
func writeJQ(w io.Writer, envelopeJSON []byte, expr string) error {
|
||||
// the typed code.
|
||||
func writeJQ(w io.Writer, raw []byte, expr string) error {
|
||||
query, err := gojq.Parse(expr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jq parse: %w", err)
|
||||
}
|
||||
var input any
|
||||
if err := json.Unmarshal(envelopeJSON, &input); err != nil {
|
||||
if err := json.Unmarshal(raw, &input); err != nil {
|
||||
return fmt.Errorf("jq input parse: %w", err)
|
||||
}
|
||||
iter := query.Run(input)
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
package format_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
func TestWriteEnvelopeFiltered_NoFilter(t *testing.T) {
|
||||
env := format.Success(map[string]any{"items": []any{
|
||||
map[string]any{"id": "1", "name": "alpha"},
|
||||
}}, &format.Meta{KBID: "kb_x"})
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteEnvelopeFiltered(buf, env, nil, ""); 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["ok"] != true {
|
||||
t.Errorf("ok = %v, want true", got["ok"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteEnvelopeFiltered_FieldsOnListItems(t *testing.T) {
|
||||
env := format.Success(map[string]any{"items": []any{
|
||||
map[string]any{"id": "1", "name": "alpha", "kb_id": "kb_x", "updated_at": "2026-01-01"},
|
||||
map[string]any{"id": "2", "name": "beta", "kb_id": "kb_x", "updated_at": "2026-01-02"},
|
||||
}}, nil)
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteEnvelopeFiltered(buf, env, []string{"id", "name"}, ""); err != nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
|
||||
var got struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Items []map[string]string `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, buf.String())
|
||||
}
|
||||
if len(got.Data.Items) != 2 {
|
||||
t.Fatalf("items len = %d, want 2", len(got.Data.Items))
|
||||
}
|
||||
for i, item := range got.Data.Items {
|
||||
if _, has := item["kb_id"]; has {
|
||||
t.Errorf("item[%d] should not have kb_id: %v", i, item)
|
||||
}
|
||||
if _, has := item["updated_at"]; has {
|
||||
t.Errorf("item[%d] should not have updated_at: %v", i, item)
|
||||
}
|
||||
if item["id"] == "" || item["name"] == "" {
|
||||
t.Errorf("item[%d] missing required keys: %v", i, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteEnvelopeFiltered_FieldsOnSingleObject(t *testing.T) {
|
||||
env := format.Success(map[string]any{
|
||||
"id": "kb_x",
|
||||
"name": "Engineering",
|
||||
"owner": "alice",
|
||||
}, nil)
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteEnvelopeFiltered(buf, env, []string{"id", "name"}, ""); err != nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
|
||||
var got struct {
|
||||
Data map[string]string `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, buf.String())
|
||||
}
|
||||
if _, has := got.Data["owner"]; has {
|
||||
t.Errorf("should not have owner: %v", got.Data)
|
||||
}
|
||||
if got.Data["id"] != "kb_x" || got.Data["name"] != "Engineering" {
|
||||
t.Errorf("missing kept fields: %v", got.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteEnvelopeFiltered_UnknownFieldSilent(t *testing.T) {
|
||||
env := format.Success(map[string]any{"id": "1"}, nil)
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteEnvelopeFiltered(buf, env, []string{"id", "nonexistent"}, ""); err != nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
var got struct {
|
||||
Data map[string]string `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if got.Data["id"] != "1" {
|
||||
t.Errorf("id missing: %v", got.Data)
|
||||
}
|
||||
if _, has := got.Data["nonexistent"]; has {
|
||||
t.Errorf("nonexistent should be silently dropped: %v", got.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteEnvelopeFiltered_PreservesEnvelopeFields(t *testing.T) {
|
||||
// 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"})
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteEnvelopeFiltered(buf, env, []string{"id"}, ""); err != nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
var got struct {
|
||||
OK bool `json:"ok"`
|
||||
Meta *format.Meta `json:"_meta"`
|
||||
Data struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, buf.String())
|
||||
}
|
||||
if got.Meta == nil || got.Meta.RequestID != "req_123" {
|
||||
t.Errorf("_meta lost or mangled: %+v", got.Meta)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteEnvelopeFiltered_JQOnly(t *testing.T) {
|
||||
env := format.Success(map[string]any{"items": []any{
|
||||
map[string]any{"id": "1", "name": "alpha"},
|
||||
map[string]any{"id": "2", "name": "beta"},
|
||||
}}, nil)
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteEnvelopeFiltered(buf, env, nil, ".data.items[].id"); err != nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
// gh CLI parity: string results render without JSON quotes
|
||||
// (see https://github.com/cli/cli/blob/trunk/pkg/export/filter.go).
|
||||
lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
|
||||
if len(lines) != 2 {
|
||||
t.Fatalf("expected 2 lines, got %d: %q", len(lines), buf.String())
|
||||
}
|
||||
if lines[0] != "1" || lines[1] != "2" {
|
||||
t.Errorf("wrong output: %q", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteEnvelopeFiltered_FieldsAndJQ(t *testing.T) {
|
||||
env := format.Success(map[string]any{"items": []any{
|
||||
map[string]any{"id": "1", "name": "alpha", "kb_id": "kb"},
|
||||
map[string]any{"id": "2", "name": "beta", "kb_id": "kb"},
|
||||
}}, nil)
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteEnvelopeFiltered(buf, env, []string{"id", "name"}, ".data.items | length"); err != nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
out := strings.TrimSpace(buf.String())
|
||||
if out != "2" {
|
||||
t.Errorf("expected '2', got %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteEnvelopeFiltered_JQParseError(t *testing.T) {
|
||||
env := format.Success(map[string]any{"x": 1}, nil)
|
||||
buf := &bytes.Buffer{}
|
||||
err := format.WriteEnvelopeFiltered(buf, env, nil, ".[invalid jq")
|
||||
if err == nil {
|
||||
t.Fatal("expected parse error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "jq parse") {
|
||||
t.Errorf("expected 'jq parse' in error, got %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteEnvelopeFiltered_ScalarDataPassThrough(t *testing.T) {
|
||||
// Defensive: scalar data should not crash field filter.
|
||||
env := format.Success("just a string", nil)
|
||||
buf := &bytes.Buffer{}
|
||||
if err := format.WriteEnvelopeFiltered(buf, env, []string{"id"}, ""); err != nil {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
if !strings.Contains(buf.String(), `"just a string"`) {
|
||||
t.Errorf("scalar data lost: %s", buf.String())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user