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:
+14
-14
@@ -9,13 +9,13 @@
|
||||
// "feels alive" UX a human typing in a terminal expects.
|
||||
//
|
||||
// - Accumulate mode (non-TTY, --no-stream, or --json): buffer every
|
||||
// fragment via sse.Accumulator and emit a single envelope (or a single
|
||||
// fragment via sse.Accumulator and emit a single JSON object (or a single
|
||||
// plain-text answer + references block) once Done. Agents and pipes
|
||||
// get a deterministic single record to parse.
|
||||
//
|
||||
// The SDK's KnowledgeQAStream callback contract is invoked sequentially on
|
||||
// one goroutine, so neither mode needs locking. The runChat core takes a
|
||||
// chatService interface so tests inject a fake without standing up a real
|
||||
// ChatService interface so tests inject a fake without standing up a real
|
||||
// SSE server.
|
||||
package chat
|
||||
|
||||
@@ -49,15 +49,15 @@ type Options struct {
|
||||
NoStream bool
|
||||
}
|
||||
|
||||
// chatService is the narrow SDK surface this command depends on. *sdk.Client
|
||||
// ChatService is the narrow SDK surface this command depends on. *sdk.Client
|
||||
// satisfies it; tests substitute a fake. Compile-time check is at the bottom
|
||||
// of this file.
|
||||
type chatService interface {
|
||||
type ChatService interface {
|
||||
CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error)
|
||||
KnowledgeQAStream(ctx context.Context, sessionID string, req *sdk.KnowledgeQARequest, cb func(*sdk.StreamResponse) error) error
|
||||
}
|
||||
|
||||
// chatData is the success-envelope payload. Mirrors what an agent needs to
|
||||
// chatData is the JSON payload emitted on the --json path. Mirrors what an agent needs to
|
||||
// continue a conversation: the answer text, retrieval references, and the
|
||||
// session pointer to thread follow-ups.
|
||||
type chatData struct {
|
||||
@@ -116,13 +116,13 @@ Modes:
|
||||
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
|
||||
cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
|
||||
cmdutil.AddJSONFlags(cmd, chatFields)
|
||||
aiclient.SetAgentHelp(cmd, "Streams an LLM answer over SSE. Agent / non-TTY callers should pass --json so the full {answer, references, session_id, assistant_message_id} envelope is emitted at completion (no partial chunks). Pass --session to thread follow-ups. Errors: server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.")
|
||||
aiclient.SetAgentHelp(cmd, "Streams an LLM answer over SSE. Agent / non-TTY callers should pass --json so the full {answer, references, session_id, assistant_message_id} object is emitted once at completion (no partial chunks). Pass --session to thread follow-ups. Errors: server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// runChat is the testable core: validate, ensure a session, dispatch the
|
||||
// stream, and route output. Returns a typed error suitable for the envelope.
|
||||
func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc chatService) error {
|
||||
// stream, and route output. Returns a typed error.
|
||||
func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc ChatService) error {
|
||||
if opts.Query == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
|
||||
}
|
||||
@@ -157,12 +157,12 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
// Decide output mode. Stream mode requires:
|
||||
// 1. an interactive stdout (tty)
|
||||
// 2. no --no-stream
|
||||
// 3. no --json (envelope is single-record by definition)
|
||||
// 3. no --json (JSON output is single-record by definition)
|
||||
streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut
|
||||
|
||||
// Surface the auto-created session ID up-front so a user who hits ^C
|
||||
// mid-stream still has the pointer to resume — no need to scroll back
|
||||
// past tokens. Skipped in JSON mode (it ends up in the envelope) and
|
||||
// past tokens. Skipped in JSON mode (it ends up in the data object) and
|
||||
// when the caller already supplied --session.
|
||||
if autoCreated && !jsonOut {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
|
||||
@@ -193,7 +193,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
// Re-surface the auto-created session id on failure so a user who
|
||||
// missed the start-of-stream notice (it scrolls past mid-stream
|
||||
// tokens, especially on ^C) can still recover with --session.
|
||||
// Skipped in JSON mode — the envelope carries it in .data.session_id.
|
||||
// Skipped in JSON mode — the data object carries it in .session_id.
|
||||
if autoCreated && !jsonOut {
|
||||
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
|
||||
}
|
||||
@@ -241,7 +241,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
KBID: opts.KBID,
|
||||
Query: opts.Query,
|
||||
}
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, data, jopts.Fields, jopts.JQ)
|
||||
return jopts.Emit(iostreams.IO.Out, data)
|
||||
}
|
||||
|
||||
// Human / non-JSON paths: streaming mode already wrote the answer body
|
||||
@@ -264,5 +264,5 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
|
||||
return nil
|
||||
}
|
||||
|
||||
// compile-time check: the production SDK client implements chatService.
|
||||
var _ chatService = (*sdk.Client)(nil)
|
||||
// compile-time check: the production SDK client implements ChatService.
|
||||
var _ ChatService = (*sdk.Client)(nil)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// fakeChatService implements chatService for unit tests. Tests configure the
|
||||
// fakeChatService implements ChatService for unit tests. Tests configure the
|
||||
// callback driver via streamEvents (delivered in order) and observe captured
|
||||
// inputs through the exported fields.
|
||||
type fakeChatService struct {
|
||||
@@ -37,7 +37,7 @@ func (f *fakeChatService) CreateSession(_ context.Context, req *sdk.CreateSessio
|
||||
return f.createSessionResp, nil
|
||||
}
|
||||
// Default: return a deterministic session id derived from the title so
|
||||
// envelope assertions don't depend on uuid generation.
|
||||
// JSON assertions don't depend on uuid generation.
|
||||
return &sdk.Session{ID: "sess_auto", Title: req.Title}, nil
|
||||
}
|
||||
|
||||
@@ -56,9 +56,9 @@ func (f *fakeChatService) KnowledgeQAStream(ctx context.Context, sessionID strin
|
||||
return f.streamErr
|
||||
}
|
||||
|
||||
// Sanity: fakeChatService must satisfy chatService. Mirrors the production
|
||||
// var _ chatService = (*sdk.Client)(nil) check at the bottom of chat.go.
|
||||
var _ chatService = (*fakeChatService)(nil)
|
||||
// Sanity: fakeChatService must satisfy ChatService. Mirrors the production
|
||||
// var _ ChatService = (*sdk.Client)(nil) check at the bottom of chat.go.
|
||||
var _ ChatService = (*fakeChatService)(nil)
|
||||
|
||||
func TestChat_StreamMode(t *testing.T) {
|
||||
out, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
@@ -117,7 +117,7 @@ func TestChat_JSONMode(t *testing.T) {
|
||||
}
|
||||
|
||||
// JSON mode must NOT print the human session-hint on stderr; the session
|
||||
// id is carried inside the envelope instead.
|
||||
// id is carried inside the JSON object instead.
|
||||
if errBuf.Len() != 0 {
|
||||
t.Errorf("expected empty stderr in JSON mode, got %q", errBuf.String())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user