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
+3 -9
View File
@@ -1,12 +1,6 @@
// Package agent handles AI agent integration: env-based detection (used to
// trigger AGENT-targeted help text) and per-command help annotations.
//
// v0.2 ADR-3: removed the omnibus `--agent` flag + ApplyAgentSugar
// mode-switch as over-design. Per-command --json + TTY auto-detect cover
// 95% of cases. See cli/AGENTS.md for the full agent contract.
//
// What remains here: a small env-detect for known coding agents, used purely
// to render the AGENT-targeted help section (no behavior change).
// Package aiclient handles AI agent integration: env-based detection
// (used to trigger AGENT-targeted help text) and per-command help
// annotations. See cli/AGENTS.md for the full agent contract.
package aiclient
import "os"
+1 -1
View File
@@ -29,7 +29,7 @@ func TestDetectAIAgent(t *testing.T) {
{name: "claude code", set: map[string]string{"CLAUDECODE": "1"}, want: "claude-code"},
{name: "cursor", set: map[string]string{"CURSOR_AGENT": "yes"}, want: "cursor"},
// Other entries (codex / aider / continue / opencode / gemini-coder)
// were dropped in v0.2 ADR-3 — env names had no official agent docs.
// were dropped — those env names had no official agent docs.
// New entries should arrive with a documented source URL.
{
name: "first-match precedence",
+1 -11
View File
@@ -1,7 +1,6 @@
package cmdutil
import (
"errors"
"fmt"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -25,24 +24,15 @@ import (
// proceed. See cli/AGENTS.md "Exit codes".
//
// `yes` should be sourced from the persistent global -y/--yes flag.
//
// On exit-10 path, the returned *Error carries OperationRisk so the envelope
// printer attaches `risk: {level: "high-risk-write", action: ...}`.
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error {
if yes {
return nil
}
risk := &OperationRisk{Level: "high-risk-write", Action: fmt.Sprintf("delete %s %s", what, id)}
if !iostreams.IO.IsStdoutTTY() || jsonOut {
e := NewError(
return NewError(
CodeInputConfirmationRequired,
fmt.Sprintf("delete %s %s requires explicit confirmation: re-run with -y/--yes", what, id),
)
var typed *Error
if errors.As(e, &typed) {
typed.OperationRisk = risk
}
return e
}
ok, err := p.Confirm(fmt.Sprintf("Delete %s %s? This cannot be undone.", what, id), false)
if err != nil {
+18 -30
View File
@@ -9,9 +9,9 @@ import (
"strings"
)
// ErrorCode is a namespaced stable identifier carried in the failure envelope.
// SemVer governance: v0.x maintains the registry below; new codes are noted
// in release notes. v0.9 introduces a CI compat test (see ADR-6b).
// ErrorCode is a namespaced stable identifier emitted on stderr in the
// `code: message` failure line. SemVer governance: v0.x maintains the
// registry below; new codes are noted in release notes.
type ErrorCode string
const (
@@ -33,9 +33,9 @@ const (
CodeInputMissingFlag ErrorCode = "input.missing_flag"
// CodeInputConfirmationRequired marks a high-risk write that has no
// interactive UI (non-TTY or --json) and was invoked without -y/--yes.
// Mapped to exit code 10 (see cli/AGENTS.md).
// Agents must surface the envelope to the user and only retry with -y
// after explicit human approval; never auto-retry.
// Mapped to exit code 10 (see cli/AGENTS.md). Agents must surface the
// error to the user and only retry with -y after explicit human
// approval; never auto-retry.
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
// server.* / network.*
@@ -60,9 +60,9 @@ const (
CodeKBNotFound ErrorCode = "local.kb_not_found"
CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
// CodeUserAborted marks a user-cancelled destructive operation (declined a
// confirm prompt). Distinct from SilentError so envelopes still carry a
// stable code; distinct from input.* because the user supplied valid args
// and simply chose not to proceed.
// confirm prompt). Distinct from SilentError so the stderr line still
// carries a stable code; distinct from input.* because the user supplied
// valid args and simply chose not to proceed.
CodeUserAborted ErrorCode = "local.user_aborted"
// CodeUploadFileNotFound marks a `weknora doc upload` invocation pointing at
// a path that does not exist. Distinct from CodeLocalFileIO (permission /
@@ -81,7 +81,9 @@ const (
)
// Error is the typed error implementations carry through the call stack.
// RunE returns a *Error and the root command formats it into the envelope.
// RunE returns a *Error and the root command renders it on stderr in
// `code: message[: cause]\nhint: ...` form. Exit code is derived by
// ExitCode().
type Error struct {
Code ErrorCode
Message string
@@ -89,27 +91,13 @@ type Error struct {
Cause error
Retryable bool
HTTPStatus int
// Risk classifies the operation that produced this error. Set by callers
// invoking destructive write paths so envelope.risk surfaces to agents.
// Stored as the format.Risk JSON shape via OperationRisk to avoid an
// import cycle with internal/format.
OperationRisk *OperationRisk
// Silent suppresses the default Failure envelope written by
// PrintErrorEnvelope while preserving the typed Code for ExitCode.
// Set by commands that already wrote their own envelope (e.g. bulk
// operations reporting partial-success data) but still need to surface
// a non-zero exit code matched to the failure class.
// Silent suppresses PrintError's stderr output while preserving the
// typed Code for ExitCode. Set by commands that already wrote their
// own output (e.g. bulk operations reporting partial-success data on
// stdout) but still need to surface a non-zero exit code.
Silent bool
}
// OperationRisk mirrors format.Risk in the cmdutil layer (avoiding a circular
// import). cmdutil → format is OK; the inverse is not, so cmdutil owns its
// own type and ToErrorBody / PrintErrorEnvelope translate.
type OperationRisk struct {
Level string // "read" | "write" | "high-risk-write"
Action string
}
func (e *Error) Error() string {
if e == nil {
return ""
@@ -202,7 +190,7 @@ func matchPrefix(err error, prefix string) bool {
}
// ClassifyHTTPStatus maps an HTTP status code to the canonical ErrorCode.
// Single source of truth so envelope codes stay aligned whether the failure
// Single source of truth so error codes stay aligned whether the failure
// was detected by the SDK (string-formatted error) or by the CLI directly
// (e.g. raw passthrough reading resp.StatusCode).
func ClassifyHTTPStatus(status int) ErrorCode {
@@ -229,7 +217,7 @@ func ClassifyHTTPStatus(status int) ErrorCode {
// parsing the "HTTP error <status>: ..." message format the SDK currently
// emits (client.parseResponse). Until the SDK exposes a typed APIError this
// is the lowest-friction way to surface 401/404/429/etc. as the right
// envelope code instead of every server-side problem collapsing to
// typed code instead of every server-side problem collapsing to
// server.error.
//
// Returns CodeNetworkError when err is not an HTTP error (transport / DNS),
+9 -80
View File
@@ -4,8 +4,6 @@ import (
"errors"
"fmt"
"io"
"github.com/Tencent/WeKnora/cli/internal/format"
)
// ExitCode maps an error to the documented CLI exit code (spec §2.4 + ADR-3).
@@ -56,13 +54,10 @@ func ExitCode(err error) int {
return 1
}
// PrintError writes err to w in human-readable form. The envelope-aware
// JSON formatter is in `internal/format`; this helper is the human path used
// when no command produced its own output.
//
// Typed *Error values surface their Hint as a second line so users see the
// actionable next-step (matches envelope.error.hint visibility in --json).
// Falls through to defaultHint when caller didn't set one.
// PrintError writes err to w (typically stderr) as `code: message\nhint:
// ...`. Typed *Error values surface their Hint as a second line so users
// see the actionable next-step. Falls through to defaultHint when the
// caller didn't set one.
func PrintError(w io.Writer, err error) {
if err == nil || errors.Is(err, SilentError) {
return
@@ -80,76 +75,10 @@ func PrintError(w io.Writer, err error) {
}
}
// PrintErrorEnvelope writes err as a JSON envelope on w. Used in agent mode /
// --json / --format=json output so failures stay machine-parseable. When the
// error carries an OperationRisk (destructive write paths), it's surfaced as
// the envelope-level Risk field so agents can decide whether to surface the
// failure differently to the user.
func PrintErrorEnvelope(w io.Writer, err error) {
if err == nil || errors.Is(err, SilentError) {
return
}
var typed *Error
if errors.As(err, &typed) && typed.Silent {
return
}
env := format.Failure(ToErrorBody(err))
if r := operationRiskOf(err); r != nil {
env.Risk = &format.Risk{Level: format.RiskLevel(r.Level), Action: r.Action}
}
_ = format.WriteEnvelope(w, env)
}
// operationRiskOf extracts an OperationRisk from a typed *Error chain, or nil.
func operationRiskOf(err error) *OperationRisk {
var typed *Error
if errors.As(err, &typed) {
return typed.OperationRisk
}
return nil
}
// ToErrorBody projects err into the canonical envelope ErrorBody. Exposed so
// other emit paths (planned: MCP) reuse the same projection rather than
// reimplementing the typed-error → wire-shape mapping.
func ToErrorBody(err error) *format.ErrorBody {
if err == nil {
return nil
}
body := &format.ErrorBody{Message: err.Error()}
var typed *Error
if errors.As(err, &typed) {
body.Code = string(typed.Code)
body.Message = typed.Message
body.Hint = typed.Hint
if body.Hint == "" {
body.Hint = defaultHint(typed.Code)
}
body.Retryable = typed.Retryable
// Surface the wrapped cause so agents see the actual server / SDK
// error string, not just the wrap message ("hybrid search"). The
// human's printed line and the JSON envelope both end with the
// underlying problem.
if typed.Cause != nil {
body.Message = typed.Message + ": " + typed.Cause.Error()
}
return body
}
var fe *FlagError
if errors.As(err, &fe) {
body.Code = string(CodeInputInvalidArgument)
return body
}
// Unclassified error; consumers see the message but no stable code.
body.Code = string(CodeServerError)
return body
}
// defaultHint returns a canonical actionable hint for known error codes when
// the call site didn't set one. Spec §1.4 zero-config matrix mandates
// `auth.unauthenticated` envelopes carry "run weknora auth login" — this
// fallback covers the broad surface (auth status / kb list / kb get / search)
// without per-command hint plumbing.
// defaultHint returns a canonical actionable hint for known error codes
// when the call site didn't set one. `auth.unauthenticated` always points
// at `weknora auth login` — covers the broad surface (auth status / kb
// list / kb view / search) without per-command hint plumbing.
//
// Empty string for codes without a stable canonical hint.
func defaultHint(code ErrorCode) string {
@@ -171,7 +100,7 @@ func defaultHint(code ErrorCode) string {
case CodeServerTimeout:
return "request timed out; retry, or run `weknora doctor` to check connectivity"
case CodeResourceNotFound:
return "verify the resource ID; list available with `weknora kb list`"
return "verify the resource ID and try again"
case CodeInputInvalidArgument, CodeInputMissingFlag:
return "see `weknora <command> --help` for valid usage"
case CodeInputConfirmationRequired:
-28
View File
@@ -36,34 +36,6 @@ func TestExitCode(t *testing.T) {
}
}
func TestToErrorBody(t *testing.T) {
t.Run("nil returns nil", func(t *testing.T) {
assert.Nil(t, ToErrorBody(nil))
})
t.Run("typed without cause", func(t *testing.T) {
body := ToErrorBody(NewError(CodeResourceNotFound, "kb missing"))
assert.Equal(t, "resource.not_found", body.Code)
assert.Equal(t, "kb missing", body.Message)
})
t.Run("typed with cause surfaces inner", func(t *testing.T) {
inner := errors.New("HTTP error 500: server exploded")
body := ToErrorBody(Wrapf(CodeServerError, inner, "hybrid search"))
assert.Equal(t, "server.error", body.Code)
// Both wrap context AND server cause must appear so agents see what
// actually broke, not just our wrap label.
assert.Equal(t, "hybrid search: HTTP error 500: server exploded", body.Message)
})
t.Run("flag error", func(t *testing.T) {
body := ToErrorBody(NewFlagError(errors.New("bad flag")))
assert.Equal(t, "input.invalid_argument", body.Code)
})
t.Run("unclassified", func(t *testing.T) {
body := ToErrorBody(errors.New("anything"))
assert.Equal(t, "server.error", body.Code)
assert.Equal(t, "anything", body.Message)
})
}
func TestPrintError(t *testing.T) {
t.Run("nil is silent", func(t *testing.T) {
var buf bytes.Buffer
-25
View File
@@ -1,25 +0,0 @@
package cmdutil
import (
"io"
"github.com/Tencent/WeKnora/cli/internal/format"
)
// Exporter renders an envelope to a writer. Currently the only
// implementation is the JSON exporter; the interface stays in case a future
// renderer (templated text, table) needs to plug in without changing call
// sites that already write through Exporter.Write.
type Exporter interface {
Write(w io.Writer, env format.Envelope) error
}
// NewJSONExporter returns an Exporter that emits envelope JSON via
// format.WriteEnvelope (single-source encoder config: no HTML escape).
func NewJSONExporter() Exporter { return &jsonExporter{} }
type jsonExporter struct{}
func (jsonExporter) Write(w io.Writer, env format.Envelope) error {
return format.WriteEnvelope(w, env)
}
-27
View File
@@ -1,27 +0,0 @@
package cmdutil
import (
"bytes"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/format"
)
func TestJSONExporter_WritesEnvelope(t *testing.T) {
var buf bytes.Buffer
exp := NewJSONExporter()
require.NoError(t, exp.Write(&buf, format.Success(map[string]string{"k": "v"}, nil)))
var got map[string]any
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
assert.Equal(t, true, got["ok"])
}
func TestFlagError_IsSentinel(t *testing.T) {
err := NewFlagError(assert.AnError)
_, ok := err.(*FlagError)
assert.True(t, ok)
}
+3 -3
View File
@@ -76,9 +76,9 @@ func New() *Factory {
f.Config = func() (*config.Config, error) {
cfg, err := config.Load()
if err != nil {
// Map raw fs / parse errors to typed codes so envelopes don't
// surface bare `server.error` for what's actually a local IO /
// corrupt-config problem.
// Map raw fs / parse errors to typed codes so the stderr line
// doesn't surface bare `server.error` for what's actually a
// local IO / corrupt-config problem.
if errors.Is(err, config.ErrCorrupt) {
return nil, Wrapf(CodeLocalConfigCorrupt, err, "config malformed")
}
+30 -19
View File
@@ -2,17 +2,20 @@ package cmdutil
import (
"errors"
"io"
"sort"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/Tencent/WeKnora/cli/internal/format"
)
// JSONOptions captures the resolved --json + --jq state after CheckJSONFlags.
// A non-nil value means the user requested JSON output; Fields restricts
// data.items[*] when len(Fields) > 0; JQ is a jq expression applied to the
// final envelope JSON.
// each top-level object (or each element of a top-level array) to the
// listed keys; JQ is a jq expression applied to the final JSON.
type JSONOptions struct {
Fields []string
JQ string
@@ -22,24 +25,32 @@ type JSONOptions struct {
// shorthand for `opts != nil`.
func (o *JSONOptions) Enabled() bool { return o != nil }
// jsonNoOptSentinel marks a bare `--json` (no comma-separated values
// after it). pflag's NoOptDefVal mechanism stores this sentinel into the
// slice; CheckJSONFlags then maps it to "no field filter" (full envelope).
// Emit serializes v as bare JSON to w, honoring the resolved field-filter
// and jq expression. Equivalent to calling format.WriteJSONFiltered with
// o.Fields / o.JQ, but lets call sites stay free of the format import.
// Safe to call on a nil receiver in case the caller composes it with
// Enabled().
func (o *JSONOptions) Emit(w io.Writer, v any) error {
if o == nil {
return format.WriteJSON(w, v)
}
return format.WriteJSONFiltered(w, v, o.Fields, o.JQ)
}
// jsonNoOptSentinel marks a bare `--json` (no comma-separated values after
// it). pflag's NoOptDefVal mechanism stores this sentinel into the slice;
// CheckJSONFlags then maps it to "no field filter" (full payload).
//
// Rationale: WeKnora's envelope is itself the machine-readable contract
// (carries typed error.code / _meta / risk), so a bare `--json` always
// producing the full envelope keeps the standard `weknora kb list --json |
// jq` pattern working. Field discovery moves to per-command `--help`
// "JSON fields available" sections rendered by AddJSONFlags.
// Field discovery moves to per-command `--help` "JSON fields available"
// sections rendered by AddJSONFlags.
const jsonNoOptSentinel = "\x00json-no-value"
// AddJSONFlags registers --json and --jq on cmd.
//
// - `--json` → full envelope (no field filter)
// - `--json id,name` → envelope with data.items[*] / data restricted
// to listed fields
// - `--jq <expr>` → applies a jq expression after marshaling;
// requires --json to be set explicitly
// - `--json` → bare JSON payload, no field filter
// - `--json=id,name` → each object restricted to the listed fields
// - `--jq <expr>` → apply a jq expression to the JSON; requires
// --json to be set explicitly
//
// `fields` is the set of available fields the user may pass; rendered in
// the command's help. Pass nil to skip the help annotation (uncommon).
@@ -48,7 +59,7 @@ func AddJSONFlags(cmd *cobra.Command, fields []string) {
// Backticks reserved for pflag's UnquoteUsage to extract the varname;
// avoid them in the description so the help doesn't render the flag
// name twice.
f.StringSlice("json", nil, "Output JSON envelope (bare for full; --json=id,name for `fields`)")
f.StringSlice("json", nil, "Output bare JSON (--json=id,name to project `fields`)")
f.Lookup("json").NoOptDefVal = jsonNoOptSentinel
f.StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --json)")
@@ -56,7 +67,7 @@ func AddJSONFlags(cmd *cobra.Command, fields []string) {
sorted := append([]string(nil), fields...)
sort.Strings(sorted)
// Append to Long without overwriting per-command prose.
hdr := "\n\nJSON fields available via `--json id,name,...`:\n " +
hdr := "\n\nJSON fields available via `--json=id,name,...`:\n " +
strings.Join(sorted, "\n ")
if cmd.Long != "" {
cmd.Long += hdr
@@ -71,8 +82,8 @@ func AddJSONFlags(cmd *cobra.Command, fields []string) {
// - (*JSONOptions, nil) --json set (possibly with --jq)
// - (nil, error) --jq without --json (plain error, exit 1)
//
// Bare `--json` yields Fields == nil (full envelope). Explicit field list
// yields Fields == []string{"id", "name", ...} (filter applied).
// Bare `--json` yields Fields == nil (no field filter). Explicit field
// list yields Fields == []string{"id", "name", ...} (filter applied).
func CheckJSONFlags(cmd *cobra.Command) (*JSONOptions, error) {
f := cmd.Flags()
jsonFlag := f.Lookup("json")
+5 -4
View File
@@ -32,8 +32,8 @@ func newTestCmd(t *testing.T, captured **cmdutil.JSONOptions) *cobra.Command {
return cmd
}
func TestAddJSONFlags_BareYieldsFullEnvelopeOpts(t *testing.T) {
// `--json` bare → Enabled() with empty Fields → caller emits full envelope.
func TestAddJSONFlags_BareYieldsEnabledOptsWithNoFields(t *testing.T) {
// `--json` bare → Enabled() with empty Fields → caller emits full payload.
var captured *cmdutil.JSONOptions
cmd := newTestCmd(t, &captured)
cmd.SetArgs([]string{"--json"})
@@ -53,8 +53,9 @@ func TestAddJSONFlags_BareYieldsFullEnvelopeOpts(t *testing.T) {
func TestAddJSONFlags_FieldsFlagParsing(t *testing.T) {
// NoOptDefVal sentinel means the `=` form is required for value passing.
// Space form `--json id,name` parses as bare + positional, which is
// documented divergence from gh CLI to keep bare-envelope semantics.
// Space form `--json id,name` parses as bare + positional, which is a
// documented divergence from gh CLI: weknora keeps bare `--json` as a
// shortcut for "full payload".
cases := []struct {
args []string
want []string
-17
View File
@@ -1,17 +0,0 @@
package cmdutil
import (
"fmt"
"github.com/spf13/cobra"
)
// MustRequireFlag panics on programmer error (typo in flag name). cobra's
// MarkFlagRequired only returns an error when the named flag does not exist
// on the command, which means the caller has a typo at registration time —
// non-recoverable. Wrap so command builders stay one-line.
func MustRequireFlag(cmd *cobra.Command, name string) {
if err := cmd.MarkFlagRequired(name); err != nil {
panic(fmt.Sprintf("MarkFlagRequired %q: %v", name, err))
}
}
+4 -5
View File
@@ -1,9 +1,8 @@
// Package config reads and writes the user-level config at
// $XDG_CONFIG_HOME/weknora/config.yaml. yaml.v3 directly; viper is intentionally
// not used (see ADR-2).
//
// v0.0 supports only Load/Save with multi-host context map; project link
// (.weknora/project.toml) is wired in v0.2 (ADR-16).
// $XDG_CONFIG_HOME/weknora/config.yaml. yaml.v3 directly; viper is
// intentionally not used (see ADR-2). Multi-host context map lives here;
// the per-project link (.weknora/project.yaml) is handled by the
// projectlink package (see ADR-16).
package config
import (
+7 -6
View File
@@ -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
-128
View File
@@ -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}
}
-65
View File
@@ -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")
}
+7 -123
View File
@@ -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)
-195
View File
@@ -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())
}
}
+2 -2
View File
@@ -34,8 +34,8 @@ type Store interface {
}
// FileStore writes 0600 plain-text files under $XDG_CONFIG_HOME/weknora/secrets/<context>.
// It is the headless / CI default and the keychain fallback. Real keychain support
// is wired in v0.1 (see ADR-17 for namespace strategy).
// It is the headless / CI default and the keychain fallback (see ADR-17 for
// namespace strategy).
type FileStore struct {
root string
}
+3 -3
View File
@@ -3,9 +3,9 @@
//
// Accumulator is the canonical sink: every callback event appends to a
// buffered Content string and updates terminal-state fields like References
// and SessionID. The non-streaming JSON envelope mode reads .Result() once
// .Done() is true; streaming mode writes Content tokens directly to stdout
// and only consults the accumulator for the final References footer.
// and SessionID. The non-streaming JSON mode reads .Result() once .Done()
// is true; streaming mode writes Content tokens directly to stdout and
// only consults the accumulator for the final References footer.
package sse
import (
+3 -7
View File
@@ -1,11 +1,7 @@
// Package xdg consolidates the XDG-rooted file path lookup and atomic-write
// idioms used by config / compat / secrets / future stores.
//
// Before extraction these patterns were copy-pasted across cli/internal/{config,
// compat, secrets}; reuse review surfaced 3× duplication of Path and 2× of the
// tmp+rename atomic-write recipe. Centralizing here means a single place to fix
// behavior (mode bits, fallback dirs, mkdir order, error wrapping) and one less
// thing to copy when v0.2 adds project-link / state stores.
// idioms used by config / compat / secrets / projectlink. Centralizing means
// a single place to fix behavior (mode bits, fallback dirs, mkdir order,
// error wrapping) instead of copy-pasting across stores.
package xdg
import (