ad150c7126
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
144 lines
6.1 KiB
Go
144 lines
6.1 KiB
Go
package search
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
|
sdk "github.com/Tencent/WeKnora/client"
|
|
)
|
|
|
|
type fakeSessionsSearchSvc struct {
|
|
pages map[int][]sdk.Session
|
|
total int
|
|
err error
|
|
calls []int
|
|
}
|
|
|
|
func (f *fakeSessionsSearchSvc) GetSessionsByTenant(_ context.Context, page, pageSize int) ([]sdk.Session, int, error) {
|
|
f.calls = append(f.calls, page)
|
|
if f.err != nil {
|
|
return nil, 0, f.err
|
|
}
|
|
return f.pages[page], f.total, nil
|
|
}
|
|
|
|
func TestSessionsSearch_TitleAndDescription(t *testing.T) {
|
|
out, _ := iostreams.SetForTest(t)
|
|
svc := &fakeSessionsSearchSvc{
|
|
pages: map[int][]sdk.Session{1: {
|
|
{ID: "s1", Title: "Design review", UpdatedAt: "2026-05-12"},
|
|
{ID: "s2", Title: "Random", Description: "with design notes", UpdatedAt: "2026-05-11"},
|
|
{ID: "s3", Title: "Marketing", UpdatedAt: "2026-05-10"},
|
|
}},
|
|
total: 3,
|
|
}
|
|
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
|
got := out.String()
|
|
assert.Contains(t, got, "s1")
|
|
assert.Contains(t, got, "s2")
|
|
assert.NotContains(t, got, "s3")
|
|
}
|
|
|
|
func TestSessionsSearch_NoMatches(t *testing.T) {
|
|
out, _ := iostreams.SetForTest(t)
|
|
svc := &fakeSessionsSearchSvc{
|
|
pages: map[int][]sdk.Session{1: {{Title: "foo"}}},
|
|
total: 1,
|
|
}
|
|
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
|
assert.Contains(t, out.String(), "(no matches)")
|
|
}
|
|
|
|
func TestSessionsSearch_PaginatesAndStopsAtLimit(t *testing.T) {
|
|
_, _ = iostreams.SetForTest(t)
|
|
page1 := make([]sdk.Session, sessionsPageSize)
|
|
for i := range page1 {
|
|
page1[i] = sdk.Session{ID: "m", Title: "needle"}
|
|
}
|
|
svc := &fakeSessionsSearchSvc{pages: map[int][]sdk.Session{1: page1}, total: 1000}
|
|
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
|
assert.Equal(t, []int{1}, svc.calls, "stops paging when limit reached")
|
|
}
|
|
|
|
func TestSessionsSearch_NetworkError(t *testing.T) {
|
|
_, _ = iostreams.SetForTest(t)
|
|
svc := &fakeSessionsSearchSvc{err: errors.New("HTTP error 500: internal")}
|
|
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
|
require.Error(t, err)
|
|
var typed *cmdutil.Error
|
|
require.ErrorAs(t, err, &typed)
|
|
assert.Equal(t, cmdutil.CodeServerError, typed.Code)
|
|
}
|
|
|
|
// TestSessionsSearch_RendersFuzzyTime is a regression guard for the v0.5
|
|
// audit bug: `search sessions` printed UpdatedAt as the raw RFC3339 string
|
|
// while `session list` ran it through text.FuzzyAgoStr — same SDK field,
|
|
// two human renderings. Asserts the human output now renders relative time
|
|
// (and does NOT contain the RFC3339 "T" date/time separator).
|
|
func TestSessionsSearch_RendersFuzzyTime(t *testing.T) {
|
|
out, _ := iostreams.SetForTest(t)
|
|
svc := &fakeSessionsSearchSvc{
|
|
pages: map[int][]sdk.Session{1: {
|
|
{ID: "s1", Title: "needle", UpdatedAt: time.Now().Add(-2 * time.Hour).Format(time.RFC3339)},
|
|
}},
|
|
total: 1,
|
|
}
|
|
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
|
body := out.String()
|
|
assert.Contains(t, body, "hour", "must render relative time (e.g. 'about 2 hours ago'), not raw RFC3339")
|
|
assert.NotContains(t, body, "T0", "raw RFC3339 has 'T' between date and time; fuzzyTime output should not")
|
|
}
|
|
|
|
// TestSearchSessions_AllPagesFlag_DefaultsTrue_WalksAllPages locks in that
|
|
// the historic walk-all-pages behavior is preserved when --all-pages is left
|
|
// at its default (true). Three pages of fake data with matches on each;
|
|
// the run must request more than one page.
|
|
func TestSearchSessions_AllPagesFlag_DefaultsTrue_WalksAllPages(t *testing.T) {
|
|
_, _ = iostreams.SetForTest(t)
|
|
svc := &fakeSessionsSearchSvc{
|
|
pages: map[int][]sdk.Session{
|
|
1: {{ID: "s1", Title: "needle"}, {ID: "s2", Title: "needle"}},
|
|
2: {{ID: "s3", Title: "needle"}},
|
|
3: {},
|
|
},
|
|
total: 3,
|
|
}
|
|
opts := &SessionsSearchOptions{Query: "needle", Limit: 100, PageSize: 2, AllPages: true}
|
|
require.NoError(t, runSessionsSearch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
|
assert.GreaterOrEqual(t, len(svc.calls), 2, "must walk multi pages by default")
|
|
}
|
|
|
|
// TestSearchSessions_AllPagesFalse_StopsAtFirstPage asserts that
|
|
// --all-pages=false caps server round-trips at one even when the server
|
|
// reports far more items available. New v0.5 opt-out for the walk-all default.
|
|
func TestSearchSessions_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
|
|
_, _ = iostreams.SetForTest(t)
|
|
svc := &fakeSessionsSearchSvc{
|
|
pages: map[int][]sdk.Session{1: {{ID: "s1", Title: "needle"}, {ID: "s2", Title: "needle"}}},
|
|
total: 100,
|
|
}
|
|
opts := &SessionsSearchOptions{Query: "needle", Limit: 100, PageSize: 2, AllPages: false}
|
|
require.NoError(t, runSessionsSearch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
|
assert.Len(t, svc.calls, 1, "must stop at first page when --all-pages=false")
|
|
}
|
|
|
|
// TestSearchSessions_PageSizeBound asserts the 1..1000 range guard mirrors
|
|
// the session/doc list cap. Out-of-range values must produce
|
|
// input.invalid_argument and never reach the SDK.
|
|
func TestSearchSessions_PageSizeBound(t *testing.T) {
|
|
for _, ps := range []int{0, -1, 1001} {
|
|
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "t", Limit: 50, PageSize: ps}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeSessionsSearchSvc{})
|
|
require.Error(t, err)
|
|
var typed *cmdutil.Error
|
|
require.ErrorAs(t, err, &typed)
|
|
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code, "page_size=%d", ps)
|
|
}
|
|
}
|