2026-05-12 15:34:33 +00:00
|
|
|
package sessioncmd
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
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
2026-05-21 10:41:56 +00:00
|
|
|
"encoding/json"
|
2026-05-12 15:34:33 +00:00
|
|
|
"errors"
|
2026-05-14 15:28:14 +00:00
|
|
|
"fmt"
|
2026-05-12 15:34:33 +00:00
|
|
|
"strings"
|
|
|
|
|
"testing"
|
2026-05-14 15:28:14 +00:00
|
|
|
"time"
|
2026-05-12 15:34:33 +00:00
|
|
|
|
|
|
|
|
"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"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// fakeListService scripts a GetSessionsByTenant response.
|
|
|
|
|
type fakeListService struct {
|
|
|
|
|
items []sdk.Session
|
|
|
|
|
total int
|
|
|
|
|
err error
|
|
|
|
|
gotPage int
|
|
|
|
|
gotPageSize int
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (f *fakeListService) GetSessionsByTenant(_ context.Context, page, pageSize int) ([]sdk.Session, int, error) {
|
|
|
|
|
f.gotPage = page
|
|
|
|
|
f.gotPageSize = pageSize
|
|
|
|
|
return f.items, f.total, f.err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_Empty(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{items: nil, total: 0}
|
2026-05-21 10:43:18 +00:00
|
|
|
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
2026-05-12 15:34:33 +00:00
|
|
|
assert.Contains(t, out.String(), "no sessions")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_Table(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{
|
|
|
|
|
items: []sdk.Session{
|
|
|
|
|
{ID: "s_1", Title: "Design review", CreatedAt: "2026-05-10T09:00:00Z", UpdatedAt: "2026-05-12T14:00:00Z"},
|
|
|
|
|
{ID: "s_2", Title: "RAG bug repro", CreatedAt: "2026-05-09T08:00:00Z", UpdatedAt: "2026-05-11T11:00:00Z"},
|
|
|
|
|
},
|
|
|
|
|
total: 2,
|
|
|
|
|
}
|
2026-05-21 10:43:18 +00:00
|
|
|
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
2026-05-12 15:34:33 +00:00
|
|
|
got := out.String()
|
|
|
|
|
assert.Contains(t, got, "s_1")
|
|
|
|
|
assert.Contains(t, got, "Design review")
|
|
|
|
|
assert.Contains(t, got, "s_2")
|
|
|
|
|
assert.Equal(t, 1, svc.gotPage)
|
|
|
|
|
assert.Equal(t, 30, svc.gotPageSize)
|
|
|
|
|
}
|
|
|
|
|
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
func TestList_JSON_BareArray(t *testing.T) {
|
2026-05-12 15:34:33 +00:00
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{
|
|
|
|
|
items: []sdk.Session{
|
|
|
|
|
{ID: "s_1", Title: "T1", UpdatedAt: "2026-05-12T14:00:00Z"},
|
|
|
|
|
},
|
|
|
|
|
total: 47,
|
|
|
|
|
}
|
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
2026-05-21 10:41:56 +00:00
|
|
|
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
2026-05-12 15:34:33 +00:00
|
|
|
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
// CLI always asks for page 1 of size --page-size; pagination is server-internal.
|
2026-05-14 15:28:14 +00:00
|
|
|
assert.Equal(t, 1, svc.gotPage)
|
2026-05-12 15:34:33 +00:00
|
|
|
assert.Equal(t, 10, svc.gotPageSize)
|
|
|
|
|
body := out.String()
|
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
2026-05-21 10:41:56 +00:00
|
|
|
var env struct {
|
|
|
|
|
OK bool `json:"ok"`
|
|
|
|
|
Data []sdk.Session `json:"data"`
|
|
|
|
|
}
|
|
|
|
|
require.NoError(t, json.Unmarshal([]byte(body), &env), "expected valid JSON envelope; got %q", body)
|
|
|
|
|
assert.True(t, env.OK, "envelope.ok must be true")
|
2026-05-12 15:34:33 +00:00
|
|
|
assert.Contains(t, body, `"id":"s_1"`)
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
assert.NotContains(t, body, `"_meta":`)
|
|
|
|
|
assert.NotContains(t, body, `"has_more":`)
|
2026-05-12 15:34:33 +00:00
|
|
|
}
|
|
|
|
|
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
func TestList_NilItems_RendersAsBareEmptyArray(t *testing.T) {
|
2026-05-12 15:34:33 +00:00
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{items: nil, total: 0}
|
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
2026-05-21 10:41:56 +00:00
|
|
|
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
|
|
|
|
var env struct {
|
|
|
|
|
OK bool `json:"ok"`
|
|
|
|
|
Data []sdk.Session `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, "expected empty data array")
|
2026-05-12 15:34:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_BadPagination(t *testing.T) {
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
cases := []struct {
|
2026-05-14 15:28:14 +00:00
|
|
|
size int
|
|
|
|
|
name string
|
2026-05-12 15:34:33 +00:00
|
|
|
}{
|
2026-05-14 15:28:14 +00:00
|
|
|
{0, "size < 1"},
|
|
|
|
|
{1001, "size > max"},
|
2026-05-12 15:34:33 +00:00
|
|
|
}
|
|
|
|
|
for _, tc := range cases {
|
|
|
|
|
t.Run(tc.name, func(t *testing.T) {
|
2026-05-21 10:43:18 +00:00
|
|
|
err := runList(context.Background(), &ListOptions{PageSize: tc.size, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListService{})
|
2026-05-12 15:34:33 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
var typed *cmdutil.Error
|
|
|
|
|
require.ErrorAs(t, err, &typed)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_NetworkError_TypedCode(t *testing.T) {
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{err: errors.New("HTTP error 401: unauthenticated")}
|
2026-05-21 10:43:18 +00:00
|
|
|
err := runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
2026-05-12 15:34:33 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
var typed *cmdutil.Error
|
|
|
|
|
require.ErrorAs(t, err, &typed)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Sanity: title with multi-rune content (CJK) should not crash truncation.
|
|
|
|
|
func TestList_NonASCIITitle(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{items: []sdk.Session{{ID: "s_zh", Title: strings.Repeat("中文", 50)}}, total: 1}
|
2026-05-21 10:43:18 +00:00
|
|
|
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
2026-05-12 15:34:33 +00:00
|
|
|
assert.Contains(t, out.String(), "s_zh")
|
|
|
|
|
}
|
2026-05-14 15:28:14 +00:00
|
|
|
|
|
|
|
|
func TestList_SinceFilter_DropsOldSessions(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
now := time.Now()
|
|
|
|
|
items := []sdk.Session{
|
|
|
|
|
{ID: "recent", Title: "today", UpdatedAt: now.Add(-1 * time.Hour).Format(time.RFC3339)},
|
|
|
|
|
{ID: "old", Title: "last month", UpdatedAt: now.Add(-30 * 24 * time.Hour).Format(time.RFC3339)},
|
|
|
|
|
{ID: "yesterday", Title: "yday", UpdatedAt: now.Add(-23 * time.Hour).Format(time.RFC3339)},
|
|
|
|
|
}
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
2026-05-21 10:43:18 +00:00
|
|
|
&ListOptions{PageSize: 30, Since: "7d", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
2026-05-14 15:28:14 +00:00
|
|
|
&fakeListService{items: items, total: 3}))
|
|
|
|
|
got := out.String()
|
|
|
|
|
assert.Contains(t, got, "recent")
|
|
|
|
|
assert.Contains(t, got, "yesterday")
|
|
|
|
|
assert.NotContains(t, got, "old", "30-day-old session should be filtered out by --since 7d")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
|
|
|
|
|
cases := []string{"24h", "1h30m", "30m", "7d", "0.5d", "168h"}
|
|
|
|
|
for _, v := range cases {
|
|
|
|
|
t.Run(v, func(t *testing.T) {
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
2026-05-21 10:43:18 +00:00
|
|
|
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
2026-05-14 15:28:14 +00:00
|
|
|
&fakeListService{items: []sdk.Session{}, total: 0}),
|
|
|
|
|
"--since=%q should parse", v)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_SinceFilter_RejectsInvalidDuration(t *testing.T) {
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
err := runList(context.Background(),
|
2026-05-21 10:43:18 +00:00
|
|
|
&ListOptions{PageSize: 30, Since: "bogus", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
2026-05-14 15:28:14 +00:00
|
|
|
&fakeListService{items: []sdk.Session{}, total: 0})
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
var typed *cmdutil.Error
|
|
|
|
|
require.ErrorAs(t, err, &typed)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_SinceFilter_RejectsNonPositive(t *testing.T) {
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
for _, v := range []string{"0d", "0h", "-1h"} {
|
|
|
|
|
err := runList(context.Background(),
|
2026-05-21 10:43:18 +00:00
|
|
|
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
2026-05-14 15:28:14 +00:00
|
|
|
&fakeListService{items: []sdk.Session{}, total: 0})
|
|
|
|
|
require.Error(t, err, "--since=%q should reject", v)
|
|
|
|
|
var typed *cmdutil.Error
|
|
|
|
|
require.ErrorAs(t, err, &typed)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-05-14 15:28:14 +00:00
|
|
|
|
|
|
|
|
// makeSessions builds N sessions with distinct IDs and descending UpdatedAt.
|
|
|
|
|
func makeSessions(n int) []sdk.Session {
|
|
|
|
|
base := time.Now()
|
|
|
|
|
out := make([]sdk.Session, n)
|
|
|
|
|
for i := 0; i < n; i++ {
|
|
|
|
|
out[i] = sdk.Session{
|
|
|
|
|
ID: fmt.Sprintf("s_%03d", i),
|
|
|
|
|
Title: fmt.Sprintf("title-%03d", i),
|
|
|
|
|
UpdatedAt: base.Add(-time.Duration(i) * time.Minute).Format(time.RFC3339),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// pagedSessionSvc returns server-paginated session results from a flat slice
|
|
|
|
|
// and records page numbers requested.
|
|
|
|
|
type pagedSessionSvc struct {
|
|
|
|
|
all []sdk.Session
|
|
|
|
|
calls []int
|
|
|
|
|
pageSize int
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (p *pagedSessionSvc) GetSessionsByTenant(_ context.Context, page, pageSize int) ([]sdk.Session, int, error) {
|
|
|
|
|
p.calls = append(p.calls, page)
|
|
|
|
|
p.pageSize = pageSize
|
|
|
|
|
start := (page - 1) * pageSize
|
|
|
|
|
if start >= len(p.all) {
|
|
|
|
|
return []sdk.Session{}, len(p.all), nil
|
|
|
|
|
}
|
|
|
|
|
end := start + pageSize
|
|
|
|
|
if end > len(p.all) {
|
|
|
|
|
end = len(p.all)
|
|
|
|
|
}
|
|
|
|
|
return p.all[start:end], len(p.all), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_Limit_LessThanPageSize_SlicesToLimit(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{items: makeSessions(20), total: 20}
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
2026-05-17 17:38:30 +00:00
|
|
|
&ListOptions{PageSize: 20, Limit: 5}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
2026-05-14 15:28:14 +00:00
|
|
|
got := strings.Count(out.String(), `"id":"s_`)
|
|
|
|
|
assert.Equal(t, 5, got, "--limit 5 must slice 20 items down to 5")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_Limit_GreaterThanPageSize_NoCap(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{items: makeSessions(10), total: 10}
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
2026-05-17 17:38:30 +00:00
|
|
|
&ListOptions{PageSize: 10, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
2026-05-14 15:28:14 +00:00
|
|
|
got := strings.Count(out.String(), `"id":"s_`)
|
|
|
|
|
assert.Equal(t, 10, got)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
|
|
|
|
_, _ = iostreams.SetForTest(t)
|
|
|
|
|
err := runList(context.Background(),
|
2026-05-21 10:43:18 +00:00
|
|
|
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
2026-05-14 15:28:14 +00:00
|
|
|
&fakeListService{})
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
var typed *cmdutil.Error
|
|
|
|
|
require.ErrorAs(t, err, &typed)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_AllPages_WalksAllServerPages(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &pagedSessionSvc{all: makeSessions(45)}
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
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
2026-05-21 10:41:56 +00:00
|
|
|
&ListOptions{PageSize: 20, AllPages: true, Limit: 10000}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
2026-05-14 15:28:14 +00:00
|
|
|
assert.Equal(t, []int{1, 2, 3}, svc.calls)
|
|
|
|
|
got := strings.Count(out.String(), `"id":"s_`)
|
|
|
|
|
assert.Equal(t, 45, got)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &pagedSessionSvc{all: makeSessions(200)}
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
2026-05-17 17:38:30 +00:00
|
|
|
&ListOptions{PageSize: 20, AllPages: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
2026-05-14 15:28:14 +00:00
|
|
|
got := strings.Count(out.String(), `"id":"s_`)
|
|
|
|
|
assert.Equal(t, 50, got)
|
|
|
|
|
assert.LessOrEqual(t, len(svc.calls), 3, "must not fetch beyond what fills --limit")
|
|
|
|
|
}
|
2026-06-26 12:40:59 +00:00
|
|
|
|
|
|
|
|
// TestList_JSON_TotalCount_SinglePage asserts that meta.total_count is populated
|
|
|
|
|
// from the server total when doing a single-page fetch.
|
|
|
|
|
func TestList_JSON_TotalCount_SinglePage(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{
|
|
|
|
|
items: []sdk.Session{{ID: "s_1", Title: "T1", UpdatedAt: "2026-05-12T14:00:00Z"}},
|
|
|
|
|
total: 42,
|
|
|
|
|
}
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
|
|
|
|
&ListOptions{PageSize: 10, Limit: 30},
|
|
|
|
|
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
|
|
|
|
body := out.String()
|
|
|
|
|
assert.Contains(t, body, `"total_count":42`, "single-page fetch must surface server total in meta.total_count")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestList_JSON_TotalCount_AllPages asserts meta.total_count is populated
|
|
|
|
|
// from the server total when walking all pages.
|
|
|
|
|
func TestList_JSON_TotalCount_AllPages(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &pagedSessionSvc{all: makeSessions(45)}
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
|
|
|
|
&ListOptions{PageSize: 20, AllPages: true, Limit: 10000},
|
|
|
|
|
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
|
|
|
|
body := out.String()
|
|
|
|
|
assert.Contains(t, body, `"total_count":45`, "--all-pages fetch must surface server total in meta.total_count")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestList_JSON_TotalCount_Zero_Present asserts that when server returns total=0
|
|
|
|
|
// on an empty list, meta.total_count (and meta.count) still serialize as 0. The
|
|
|
|
|
// *int + omitempty pattern omits only nil, so the agent contract stays stable:
|
|
|
|
|
// an empty result reports 0, not a missing key.
|
|
|
|
|
func TestList_JSON_TotalCount_Zero_Present(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeListService{items: nil, total: 0}
|
|
|
|
|
require.NoError(t, runList(context.Background(),
|
|
|
|
|
&ListOptions{PageSize: 30, Limit: 30},
|
|
|
|
|
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
|
|
|
|
body := out.String()
|
|
|
|
|
assert.Contains(t, body, `"total_count":0`, "zero server total must serialize as 0 on empty list")
|
|
|
|
|
assert.Contains(t, body, `"count":0`, "empty list must report count:0, not omit it")
|
|
|
|
|
}
|