refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup

Sweep every CLI output path through the v0.7 envelope contract.

FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.

~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.

Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
  pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
  failures*}; Successes/Failures *int so explicit zero survives
  omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
  cmdutil.ClassifyContextErr collapse the three previously-duplicated
  multi-delete pipelines (doc / chunk / session) into one call site
  pattern. doc upload --recursive uses the same helpers with a per-
  file resultFn. Summary error sets Silent:true so the stderr
  envelope path doesn't duplicate the stdout batch detail (exit 1
  preserved via Code → ExitCode).

ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).

MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.

weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
  (stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
  envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
  envelope so --paginate never emits bare JSON to stdout.

Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
This commit is contained in:
nullkey
2026-05-21 18:41:56 +08:00
committed by lyingbug
parent 733bb3aaa1
commit ad150c7126
96 changed files with 2354 additions and 864 deletions
+8 -4
View File
@@ -13,6 +13,7 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
)
@@ -102,7 +103,7 @@ backend storage order is not guaranteed and varies between deployments.`,
// value into the command's flag set.
cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)")
cmd.Flags().IntVar(&opts.PageSize, "page-size", 50, "Items per server batch (1..1000)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (1..10000)")
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
cmd.Flags().StringVar(&opts.Status, "status", "", "Filter by parse status: pending | processing | completed | failed")
cmd.Flags().StringVar(&opts.Keyword, "keyword", "", "Server-side substring match against title / file_name (case-sensitive)")
@@ -122,10 +123,10 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
Message: fmt.Sprintf("--page-size must be in 1..1000, got %d", opts.PageSize),
}
}
if opts.Limit < 0 || opts.Limit > 10000 {
if opts.Limit < 1 || opts.Limit > 10000 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--limit must be in 0..10000 (0 = no cap), got %d", opts.Limit),
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
}
}
if opts.Status != "" && !validDocListStatus(opts.Status) {
@@ -197,12 +198,15 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
})
// --limit applies after sort so users get the top-N most-recent items
// when combined with a single-page fetch where page_size > limit.
truncated := false
if opts.Limit > 0 && len(items) > opts.Limit {
items = items[:opts.Limit]
truncated = true
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, items)
meta := &output.Meta{Count: len(items), HasMore: truncated}
return fopts.Emit(iostreams.IO.Out, items, meta)
}
if len(items) == 0 {
+49 -38
View File
@@ -2,6 +2,7 @@ package doc
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
@@ -56,8 +57,8 @@ func TestList_Success_Human(t *testing.T) {
{ID: "doc2", FileName: "beta.md", FileSize: 0, ParseStatus: "pending", UpdatedAt: now.Add(-2 * 24 * time.Hour)},
}
svc := &fakeListSvc{items: items, total: 2}
opts := &ListOptions{PageSize: 20}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, 1, svc.got.page)
@@ -75,39 +76,48 @@ func TestList_Success_Human(t *testing.T) {
func TestList_Success_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{items: []sdk.Knowledge{{ID: "doc1", FileName: "a.pdf"}}, total: 1}
opts := &ListOptions{PageSize: 20}
opts := &ListOptions{PageSize: 20, Limit: 30}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_xxx"))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `[`), "expected bare JSON array, got %q", got)
var env struct {
OK bool `json:"ok"`
Data []sdk.Knowledge `json:"data"`
}
require.NoError(t, json.Unmarshal([]byte(got), &env), "expected valid JSON envelope, got %q", got)
assert.True(t, env.OK, "envelope.ok must be true")
assert.Contains(t, got, `"id":"doc1"`)
assert.NotContains(t, got, `"ok":`)
assert.NotContains(t, got, `"_meta":`)
}
func TestList_Empty_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{items: nil, total: 0}
opts := &ListOptions{PageSize: 20}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Contains(t, out.String(), "(no documents)")
}
func TestList_Empty_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{items: nil, total: 0}
opts := &ListOptions{PageSize: 20}
opts := &ListOptions{PageSize: 20, Limit: 30}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_xxx"))
got := strings.TrimSpace(out.String())
assert.Equal(t, "[]", got, "empty list must serialize as bare `[]` not null")
var env struct {
OK bool `json:"ok"`
Data []sdk.Knowledge `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "expected valid JSON envelope, got %q", out.String())
assert.True(t, env.OK, "envelope.ok must be true")
assert.Len(t, env.Data, 0, "empty list must produce empty data array, not null")
}
func TestList_HTTPError_500(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{err: errors.New("HTTP error 500: internal")}
opts := &ListOptions{PageSize: 20}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
opts := &ListOptions{PageSize: 20, Limit: 30}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
@@ -187,7 +197,7 @@ func TestList_SortByUpdatedDesc(t *testing.T) {
{ID: "new", FileName: "new.pdf", UpdatedAt: now.Add(-1 * time.Hour)},
}
svc := &fakeListSvc{items: items, total: 2}
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 20, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
got := out.String()
newIdx := strings.Index(got, "new.pdf")
@@ -220,8 +230,8 @@ func TestList_StatusFilter_ForwardedToSDK(t *testing.T) {
chdirIsolated(t)
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Status: "failed"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30, Status: "failed"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "failed", svc.got.filter.ParseStatus,
"--status must be forwarded as filter.ParseStatus for server-side filtering")
}
@@ -230,8 +240,8 @@ func TestList_StatusFilter_RejectsUnknownValue(t *testing.T) {
chdirIsolated(t)
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Status: "bogus"}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
opts := &ListOptions{PageSize: 20, Limit: 30, Status: "bogus"}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -245,8 +255,8 @@ func TestList_StatusFilter_AcceptsAllEnumValues(t *testing.T) {
for _, v := range docListStatusValues {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Status: v}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"),
opts := &ListOptions{PageSize: 20, Limit: 30, Status: v}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"),
"status=%q should be accepted", v)
}
}
@@ -311,7 +321,7 @@ func TestList_Limit_GreaterThanPageSize_NoCap(t *testing.T) {
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
opts := &ListOptions{PageSize: 20, Limit: -1}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -321,7 +331,7 @@ func TestList_Limit_Negative_Rejected(t *testing.T) {
func TestList_AllPages_WalksAllServerPages(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &pagedDocSvc{all: makeDocs(45)}
opts := &ListOptions{PageSize: 20, AllPages: true}
opts := &ListOptions{PageSize: 20, Limit: 10000, AllPages: true}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "kb_xxx"))
// 45 items / page_size 20 = 3 pages: 20 + 20 + 5.
assert.Equal(t, []int{1, 2, 3}, svc.calls)
@@ -345,32 +355,32 @@ func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
func TestList_Keyword_PassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Keyword: "spec"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30, Keyword: "spec"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "spec", svc.got.filter.Keyword)
}
func TestList_FileType_PassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, FileType: "pdf"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30, FileType: "pdf"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "pdf", svc.got.filter.FileType)
}
func TestList_Source_PassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Source: "api"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30, Source: "api"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "api", svc.got.filter.Source)
}
func TestList_TagID_PassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, TagID: "tag_42"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30, TagID: "tag_42"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
assert.Equal(t, "tag_42", svc.got.filter.TagID)
}
@@ -378,8 +388,8 @@ func TestList_StartTime_RFC3339Parses(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
want := "2026-05-01T00:00:00Z"
opts := &ListOptions{PageSize: 20, StartTime: want}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30, StartTime: want}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
parsed, err := time.Parse(time.RFC3339, want)
require.NoError(t, err)
assert.True(t, svc.got.filter.StartTime.Equal(parsed),
@@ -391,8 +401,8 @@ func TestList_EndTime_RFC3339Parses(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
want := "2026-06-30T23:59:59Z"
opts := &ListOptions{PageSize: 20, EndTime: want}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
opts := &ListOptions{PageSize: 20, Limit: 30, EndTime: want}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
parsed, err := time.Parse(time.RFC3339, want)
require.NoError(t, err)
assert.True(t, svc.got.filter.EndTime.Equal(parsed))
@@ -400,8 +410,8 @@ func TestList_EndTime_RFC3339Parses(t *testing.T) {
func TestList_StartTime_InvalidFormat_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
opts := &ListOptions{PageSize: 20, StartTime: "tomorrow"}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
opts := &ListOptions{PageSize: 20, Limit: 30, StartTime: "tomorrow"}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -412,8 +422,8 @@ func TestList_StartTime_InvalidFormat_Rejected(t *testing.T) {
func TestList_EndTime_InvalidFormat_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
opts := &ListOptions{PageSize: 20, EndTime: "2026-05-01"} // date-only, not RFC3339
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
opts := &ListOptions{PageSize: 20, Limit: 30, EndTime: "2026-05-01"} // date-only, not RFC3339
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -428,6 +438,7 @@ func TestList_AllFiltersCombined(t *testing.T) {
svc := &fakeListSvc{}
opts := &ListOptions{
PageSize: 20,
Limit: 30,
Status: "completed",
Keyword: "spec",
FileType: "pdf",
@@ -436,7 +447,7 @@ func TestList_AllFiltersCombined(t *testing.T) {
StartTime: "2026-01-01T00:00:00Z",
EndTime: "2026-12-31T23:59:59Z",
}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
f := svc.got.filter
assert.Equal(t, "completed", f.ParseStatus)
assert.Equal(t, "spec", f.Keyword)
+1 -1
View File
@@ -61,7 +61,7 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
return cmdutil.WrapHTTP(err, "get document %q", id)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, doc)
return fopts.Emit(iostreams.IO.Out, doc, nil)
}
w := iostreams.IO.Out
fmt.Fprintf(w, "ID: %s\n", doc.ID)
+23 -15
View File
@@ -2,6 +2,7 @@ package doc
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
@@ -39,7 +40,7 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
UpdatedAt: time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC),
ProcessedAt: &processed,
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_abc"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -59,7 +60,7 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
func TestView_Human_TitleFallback(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_url", Title: "Pasted article", FileName: ""}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_url"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_url"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -77,7 +78,7 @@ func TestView_Human_OmitsEmptyFields(t *testing.T) {
ID: "doc_abc",
FileName: "x.txt",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_abc"); err != nil {
t.Fatalf("runView: %v", err)
}
// Line-prefix match (not substring): "ERROR:" as a substring could
@@ -101,8 +102,15 @@ func TestView_JSON_BareObject(t *testing.T) {
t.Fatalf("runView: %v", err)
}
got := out.String()
if strings.Contains(got, `"ok":`) || strings.Contains(got, `"data":`) {
t.Errorf("bare output must not carry envelope keys: %q", got)
var env struct {
OK bool `json:"ok"`
Data sdk.Knowledge `json:"data"`
}
if err := json.Unmarshal([]byte(got), &env); err != nil {
t.Fatalf("parse: %v\n%s", err, got)
}
if !env.OK {
t.Errorf("envelope.ok must be true, got %q", got)
}
for _, want := range []string{`"id":"doc_abc"`, `"file_name":"x.txt"`, `"knowledge_base_id":"kb1"`} {
if !strings.Contains(got, want) {
@@ -114,7 +122,7 @@ func TestView_JSON_BareObject(t *testing.T) {
func TestView_NotFound_ClassifiedAs404(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewSvc{err: errors.New("HTTP error 404: not found")}
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "missing")
if err == nil {
t.Fatal("expected error")
}
@@ -130,7 +138,7 @@ func TestView_Title_RendersWhenDifferentFromFileName(t *testing.T) {
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_t", FileName: "raw.pdf", Title: "Quarterly Plan",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -146,7 +154,7 @@ func TestView_Title_OmittedWhenSameAsFileName(t *testing.T) {
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_t", FileName: "policy.pdf", Title: "policy.pdf",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
t.Fatalf("runView: %v", err)
}
for _, l := range strings.Split(out.String(), "\n") {
@@ -159,7 +167,7 @@ func TestView_Title_OmittedWhenSameAsFileName(t *testing.T) {
func TestView_Description(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_d", FileName: "x.pdf", Description: "Annual review"}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_d"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_d"); err != nil {
t.Fatalf("runView: %v", err)
}
if !strings.Contains(out.String(), "Annual review") {
@@ -172,7 +180,7 @@ func TestView_SourceAndChannel(t *testing.T) {
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_s", FileName: "x.pdf", Source: "https://example.com/x", Channel: "web",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_s"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_s"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -190,7 +198,7 @@ func TestView_SummaryAndEnableStatus(t *testing.T) {
SummaryStatus: "completed",
EnableStatus: "disabled",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_st"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_st"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -204,7 +212,7 @@ func TestView_SummaryAndEnableStatus(t *testing.T) {
func TestView_TagID(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_t", FileName: "x.pdf", TagID: "tag_abc"}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -216,7 +224,7 @@ func TestView_TagID(t *testing.T) {
func TestView_StorageSize_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_sz", FileName: "x.pdf", StorageSize: 2 * 1024 * 1024}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_sz"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_sz"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -232,7 +240,7 @@ func TestView_FileHash_Prefix12(t *testing.T) {
FileName: "x.pdf",
FileHash: "abcdef1234567890fedcba0987654321",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_h"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_h"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@@ -249,7 +257,7 @@ func TestView_ErrorMessage_WarnPrefix(t *testing.T) {
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_e", FileName: "x.pdf", ErrorMessage: "parser failed at offset 4096",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_e"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_e"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
+36 -3
View File
@@ -2,6 +2,7 @@ package doc
import (
"context"
"errors"
"fmt"
"io"
"math/rand"
@@ -124,9 +125,24 @@ const (
// bounded by maxConcurrentPolls. Returns the partitioned terminal state.
// Always waits for every id (wait-all semantics).
//
// Duplicate ids are deduplicated at entry — polling the same id twice would
// produce duplicate result entries and waste poll quota.
//
// Exponential backoff starts at opts.Interval, doubles each tick, caps at
// maxBackoffInterval, with up to jitterMax random jitter added per sleep.
func waitForDocs(ctx context.Context, ids []string, svc WaitService, opts WaitOptions) (*WaitResult, error) {
// Dedup ids while preserving first-seen order.
seen := make(map[string]struct{}, len(ids))
deduped := make([]string, 0, len(ids))
for _, id := range ids {
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
deduped = append(deduped, id)
}
ids = deduped
ctx, cancel := context.WithTimeout(ctx, opts.Timeout)
defer cancel()
@@ -161,6 +177,14 @@ func waitForDocs(ctx context.Context, ids []string, svc WaitService, opts WaitOp
for {
select {
case <-ctx.Done():
// Distinguish SIGINT/SIGTERM (Canceled) from --timeout
// (DeadlineExceeded) so a user interrupt does not
// pollute the timeout list with the in-flight ids.
if errors.Is(ctx.Err(), context.Canceled) {
// Signal-driven cancel: root's signal handler
// exits 130; don't classify these ids as timed out.
return
}
addTimeout(id)
return
default:
@@ -168,7 +192,13 @@ func waitForDocs(ctx context.Context, ids []string, svc WaitService, opts WaitOp
doc, err := svc.GetKnowledge(ctx, id)
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
// Check Canceled first — SIGINT during an in-flight
// request surfaces as a context-canceled error; it is
// not a real GetKnowledge failure.
if errors.Is(ctx.Err(), context.Canceled) {
return
}
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
addTimeout(id)
return
}
@@ -191,6 +221,9 @@ func waitForDocs(ctx context.Context, ids []string, svc WaitService, opts WaitOp
select {
case <-ctx.Done():
timer.Stop()
if errors.Is(ctx.Err(), context.Canceled) {
return
}
addTimeout(id)
return
case <-timer.C:
@@ -231,8 +264,8 @@ var _ WaitService = (*sdk.Client)(nil)
func emitWaitResult(r *WaitResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, r)
case cmdutil.FormatText, "":
return fopts.Emit(w, r, nil)
case cmdutil.FormatHuman, "":
return writeWaitText(w, r)
default:
return fmt.Errorf("unsupported --format %q for doc wait", fopts.Mode)
+8 -6
View File
@@ -32,9 +32,7 @@ func TestWaitCmd_Shape(t *testing.T) {
if f := cmd.Flags().Lookup("keep-going"); f != nil {
t.Error("--keep-going should not be registered; wait is always wait-all")
}
if f := cmd.Flags().Lookup("format"); f == nil {
t.Error("missing --format flag (should be registered per-command, Method D)")
}
// --format is a persistent root flag (v0.7), not per-command — skip its lookup here.
}
func TestWaitCmd_DefaultFlagValues(t *testing.T) {
@@ -193,7 +191,7 @@ func TestWaitForDocs_MultiID_WaitAllOnPartialFailure(t *testing.T) {
func TestEmitWaitResult_TextHumanSummary(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
res := &WaitResult{
Completed: []string{"a", "b"},
Failed: []FailedDoc{{ID: "c", Message: "parse boom"}},
@@ -220,10 +218,14 @@ func TestEmitWaitResult_JSONSingleRecord(t *testing.T) {
if err := emitWaitResult(res, fopts, &buf); err != nil {
t.Fatalf("emitWaitResult: %v", err)
}
var got WaitResult
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
var env struct {
OK bool `json:"ok"`
Data WaitResult `json:"data"`
}
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
t.Fatalf("not JSON: %v\n%s", err, buf.String())
}
got := env.Data
if len(got.Completed) != 1 || got.Completed[0] != "a" {
t.Errorf("Completed=%v, want [a]", got.Completed)
}