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
main
parent
733bb3aaa1
commit
ad150c7126
|
|
@ -124,10 +124,10 @@ var wireCases = []wireCase{
|
|||
wantStderrSubstring: "resource.not_found",
|
||||
},
|
||||
|
||||
// 8. context use - pure local I/O against config.yaml.
|
||||
// 8. profile use - pure local I/O against config.yaml.
|
||||
{
|
||||
name: "context_use.success",
|
||||
args: []string{"context", "use", "production", "--format", "json"},
|
||||
name: "profile_use.success",
|
||||
args: []string{"profile", "use", "production", "--format", "json"},
|
||||
preConfig: func(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "staging",
|
||||
|
|
@ -141,7 +141,7 @@ var wireCases = []wireCase{
|
|||
}
|
||||
},
|
||||
},
|
||||
// (context_use.error_local_context_not_found dropped - see file header.)
|
||||
// (profile_use.error_local_context_not_found dropped - see file header.)
|
||||
|
||||
// 9-10. auth status - SDK /api/v1/auth/me, plus config inspection.
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"context":"","user_id":"usr_abc","email":"user@example.com","tenant_id":42,"tenant_name":"Acme"}
|
||||
{"ok":true,"data":{"profile":"","user_id":"usr_abc","email":"user@example.com","tenant_id":42,"tenant_name":"Acme"}}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"summary":{"all_passed":false,"passed":1,"failed":1,"skipped":2},"checks":[{"name":"base_url_reachable","status":"fail","details":"server returned 500","hint":"verify the host configured for the active context (run `weknora auth login --host=...`) and network reachability"},{"name":"auth_credential","status":"skip","details":"prereq failed: base_url_reachable"},{"name":"server_version","status":"skip","details":"prereq failed: auth_credential"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}
|
||||
{"ok":true,"data":{"summary":{"all_passed":false,"passed":1,"failed":1,"skipped":2},"checks":[{"name":"base_url_reachable","status":"fail","details":"server returned 500","hint":"verify the host configured for the active context (run `weknora auth login --host=...`) and network reachability"},{"name":"auth_credential","status":"skip","details":"prereq failed: base_url_reachable"},{"name":"server_version","status":"skip","details":"prereq failed: auth_credential"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"summary":{"all_passed":false,"passed":1,"failed":0,"skipped":3},"checks":[{"name":"base_url_reachable","status":"skip","details":"offline mode"},{"name":"auth_credential","status":"skip","details":"offline mode"},{"name":"server_version","status":"skip","details":"offline mode"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}
|
||||
{"ok":true,"data":{"summary":{"all_passed":false,"passed":1,"failed":0,"skipped":3},"checks":[{"name":"base_url_reachable","status":"skip","details":"offline mode"},{"name":"auth_credential","status":"skip","details":"offline mode"},{"name":"server_version","status":"skip","details":"offline mode"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
[{"id":"kb1","name":"Onboarding Docs","type":"","is_temporary":false,"is_pinned":false,"description":"","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":5,"chunk_count":128,"is_processing":false,"processing_count":0},{"id":"kb2","name":"API Reference","type":"","is_temporary":false,"is_pinned":false,"description":"","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":12,"chunk_count":340,"is_processing":false,"processing_count":0}]
|
||||
{"ok":true,"data":[{"id":"kb1","name":"Onboarding Docs","type":"","is_temporary":false,"is_pinned":false,"description":"","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":5,"chunk_count":128,"is_processing":false,"processing_count":0},{"id":"kb2","name":"API Reference","type":"","is_temporary":false,"is_pinned":false,"description":"","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":12,"chunk_count":340,"is_processing":false,"processing_count":0}],"meta":{"count":2}}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
[]
|
||||
{"ok":true,"data":[],"meta":{}}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"id":"kb1","name":"Onboarding Docs","type":"","is_temporary":false,"is_pinned":false,"description":"Internal onboarding handbook","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":5,"chunk_count":128,"is_processing":false,"processing_count":0}
|
||||
{"ok":true,"data":{"id":"kb1","name":"Onboarding Docs","type":"","is_temporary":false,"is_pinned":false,"description":"Internal onboarding handbook","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":5,"chunk_count":128,"is_processing":false,"processing_count":0}}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
[{"id":"chunk-1","content":"first chunk content","knowledge_id":"doc-1","chunk_index":0,"knowledge_title":"Doc 1","start_at":0,"end_at":0,"seq":0,"score":0.92,"match_type":0,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""},{"id":"chunk-2","content":"second chunk content","knowledge_id":"doc-2","chunk_index":1,"knowledge_title":"Doc 2","start_at":0,"end_at":0,"seq":0,"score":0.81,"match_type":1,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""}]
|
||||
{"ok":true,"data":[{"id":"chunk-1","content":"first chunk content","knowledge_id":"doc-1","chunk_index":0,"knowledge_title":"Doc 1","start_at":0,"end_at":0,"seq":0,"score":0.92,"match_type":0,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""},{"id":"chunk-2","content":"second chunk content","knowledge_id":"doc-2","chunk_index":1,"knowledge_title":"Doc 2","start_at":0,"end_at":0,"seq":0,"score":0.81,"match_type":1,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""}],"meta":{"count":2}}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"commit":"none","date":"unknown","version":"dev"}
|
||||
{"ok":true,"data":{"commit":"none","date":"unknown","version":"dev"}}
|
||||
|
|
|
|||
|
|
@ -101,8 +101,8 @@ func runAgentCheck(ctx context.Context, svc AgentCheckService, id string) (*Agen
|
|||
func emitAgentCheck(res *AgentCheckResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
return writeAgentCheckText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for agent check", fopts.Mode)
|
||||
|
|
|
|||
|
|
@ -122,10 +122,14 @@ func TestEmitAgentCheck_JSON(t *testing.T) {
|
|||
if err := emitAgentCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
var got AgentCheckResult
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data AgentCheckResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
got := env.Data
|
||||
if got.ModelID != "m_x" {
|
||||
t.Errorf("ModelID=%q, want m_x", got.ModelID)
|
||||
}
|
||||
|
|
@ -138,7 +142,7 @@ func TestEmitAgentCheck_TextHuman(t *testing.T) {
|
|||
trueP := true
|
||||
var buf bytes.Buffer
|
||||
res := &AgentCheckResult{ID: "ag_x", Reachable: true, ModelID: "m_x", KBScopeAllReachable: &trueP}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
if err := emitAgentCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,12 +291,12 @@ func openConfigFile(path string) (io.Reader, string, error) {
|
|||
return r, kind, nil
|
||||
}
|
||||
|
||||
// emitAgent writes the Agent to stdout per the v0.4 wire contract (bare
|
||||
// SDK shape for --format json, human KV otherwise). Shared by create and edit;
|
||||
// defined here for proximity to the create flow.
|
||||
// emitAgent writes the Agent to stdout (bare SDK shape for --format json,
|
||||
// human KV otherwise). Shared by create and edit; defined here for proximity
|
||||
// to the create flow.
|
||||
func emitAgent(fopts *cmdutil.FormatOptions, ag *sdk.Agent) error {
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, ag)
|
||||
return fopts.Emit(iostreams.IO.Out, ag, nil)
|
||||
}
|
||||
renderAgent(iostreams.IO.Out, ag)
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -79,18 +79,29 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
|||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, agentDeleteFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "permanently delete a custom agent",
|
||||
RequiredFlags: []string{"<agent-id> (positional)"},
|
||||
Examples: []string{
|
||||
"weknora agent delete ag_abc -y",
|
||||
"weknora agent delete ag_abc -y --format json",
|
||||
},
|
||||
Warnings: []string{
|
||||
"agent delete removes the configured agent and its workflow. Never auto-add -y.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "agent", opts.AgentID); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "agent", opts.AgentID, "agent.delete", "weknora agent delete "+opts.AgentID+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := svc.DeleteAgent(ctx, opts.AgentID); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete agent %s", opts.AgentID)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.AgentID, Deleted: true})
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.AgentID, Deleted: true}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted agent %s\n", opts.AgentID)
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ func TestDelete_NonTTY_WithYes_Direct(t *testing.T) {
|
|||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc", Yes: true},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{},
|
||||
))
|
||||
assert.Equal(t, "ag_abc", svc.gotID)
|
||||
assert.Contains(t, out.String(), "ag_abc")
|
||||
|
|
@ -56,7 +56,7 @@ func TestDelete_404_PropagatesNotFound(t *testing.T) {
|
|||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_missing", Yes: true},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{},
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -71,7 +71,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
|
|||
require.NoError(t, runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p,
|
||||
))
|
||||
assert.True(t, p.Asked)
|
||||
assert.Equal(t, "ag_abc", svc.gotID)
|
||||
|
|
@ -84,7 +84,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
|||
err := runDelete(
|
||||
context.Background(),
|
||||
&DeleteOptions{AgentID: "ag_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p,
|
||||
)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
|
|
@ -82,15 +83,16 @@ invocation:
|
|||
|
||||
surgical flag > config-file value > zero value
|
||||
|
||||
AI agents: writes to a server resource. Failure surfaces as a typed
|
||||
code on stderr: resource.not_found (agent id or KB id), auth.forbidden,
|
||||
input.invalid_argument (no flags passed, bad file).`
|
||||
AI agents: this is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
with input.confirmation_required. Surface the prompt to the user and only
|
||||
retry with -y after explicit approval. Other failure codes: resource.not_found
|
||||
(agent id or KB id), auth.forbidden, input.invalid_argument (no flags, bad file).`
|
||||
|
||||
const agentEditExample = ` weknora agent edit ag_abc --name "Renamed"
|
||||
weknora agent edit ag_abc --description "" # clear description
|
||||
weknora agent edit ag_abc --add-kb kb_new --remove-kb kb_old
|
||||
weknora agent edit ag_abc --system-prompt-file ./prompt.md
|
||||
weknora agent edit ag_abc --config-file ./tuned.yaml --temperature 0.9`
|
||||
const agentEditExample = ` weknora agent edit ag_abc --name "Renamed" -y
|
||||
weknora agent edit ag_abc --description "" -y # clear description
|
||||
weknora agent edit ag_abc --add-kb kb_new --remove-kb kb_old -y
|
||||
weknora agent edit ag_abc --system-prompt-file ./prompt.md -y
|
||||
weknora agent edit ag_abc --config-file ./tuned.yaml --temperature 0.9 -y`
|
||||
|
||||
// NewCmdEdit builds `weknora agent edit <agent-id>`.
|
||||
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
|
|
@ -147,6 +149,12 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
|||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
yes, _ := cmd.Flags().GetBool("yes")
|
||||
// Build the retry command from the flags the user actually passed.
|
||||
retryCmd := buildAgentEditRetryCmd(cmd, opts.AgentID)
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), yes, fopts.WantsJSON(), "agent", opts.AgentID, "agent.edit", retryCmd); err != nil {
|
||||
return err
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -173,9 +181,55 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
|||
cmd.Flags().StringVar(&configFile, "config-file", "", "Full AgentConfig YAML or JSON (REPLACES current config baseline; surgical flags then apply on top)")
|
||||
|
||||
cmdutil.AddFormatFlag(cmd, agentViewFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "surgically edit a custom agent's configuration",
|
||||
RequiredFlags: []string{"<agent-id> (positional)", "at least one edit flag (--name, --add-kb, etc.)"},
|
||||
Examples: []string{
|
||||
"weknora agent edit ag_abc --name \"Renamed\"",
|
||||
"weknora agent edit ag_abc --add-kb kb_new --remove-kb kb_old",
|
||||
"weknora agent edit ag_abc --config-file ./tuned.yaml",
|
||||
},
|
||||
Warnings: []string{
|
||||
"agent edit can change tool allowlist / KB scope. Surface the exit-10 prompt to the user — only proceed after explicit approval.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
// buildAgentEditRetryCmd constructs a directly-executable retry argv from the
|
||||
// flags the user actually set so agents can surface a precise re-run command.
|
||||
func buildAgentEditRetryCmd(cmd *cobra.Command, id string) string {
|
||||
var parts []string
|
||||
parts = append(parts, "weknora", "agent", "edit", id)
|
||||
cmd.Flags().Visit(func(f *pflag.Flag) {
|
||||
switch f.Name {
|
||||
case "name":
|
||||
parts = append(parts, "--name", f.Value.String())
|
||||
case "description":
|
||||
parts = append(parts, "--description", f.Value.String())
|
||||
case "model":
|
||||
parts = append(parts, "--model", f.Value.String())
|
||||
case "system-prompt":
|
||||
parts = append(parts, "--system-prompt", f.Value.String())
|
||||
case "agent-mode":
|
||||
parts = append(parts, "--agent-mode", f.Value.String())
|
||||
case "rerank-model":
|
||||
parts = append(parts, "--rerank-model", f.Value.String())
|
||||
case "temperature":
|
||||
parts = append(parts, "--temperature", f.Value.String())
|
||||
case "kb-selection-mode":
|
||||
parts = append(parts, "--kb-selection-mode", f.Value.String())
|
||||
case "format":
|
||||
parts = append(parts, "--format", f.Value.String())
|
||||
// --add-kb, --remove-kb, --system-prompt-file, --config-file are excluded
|
||||
// because they are multi-value or file-based; a precise argv is impractical.
|
||||
// The user must reconstruct those manually.
|
||||
}
|
||||
})
|
||||
parts = append(parts, "-y")
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// editHasAnyFlag reports whether opts carries at least one surgical update
|
||||
// signal. Required-flag validation lives in runEdit (not PreRunE) so unit
|
||||
// tests can invoke runEdit with a hand-built EditOptions directly.
|
||||
|
|
|
|||
|
|
@ -7,11 +7,13 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
|
|
@ -247,3 +249,42 @@ func TestEdit_SystemPromptFile(t *testing.T) {
|
|||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "new prompt", svc.updateReq.Config.SystemPrompt)
|
||||
}
|
||||
|
||||
// withRootHarnessAgent wraps `weknora agent edit ...` under a synthetic root
|
||||
// cmd that registers the global persistent flags (mirrors addGlobalFlags in
|
||||
// cmd/root.go).
|
||||
func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
|
||||
root := &cobra.Command{Use: "weknora"}
|
||||
pf := root.PersistentFlags()
|
||||
pf.BoolP("yes", "y", false, "")
|
||||
pf.String("format", "", "Output format: human | json | ndjson")
|
||||
pf.StringP("jq", "q", "", "")
|
||||
ag := &cobra.Command{Use: "agent"}
|
||||
ag.AddCommand(edit)
|
||||
root.AddCommand(ag)
|
||||
root.SetArgs(append([]string{"agent", "edit"}, args...))
|
||||
root.SetContext(context.Background())
|
||||
root.SilenceErrors = true
|
||||
root.SilenceUsage = true
|
||||
return root
|
||||
}
|
||||
|
||||
// TestAgentEdit_RequiresConfirmation asserts that without -y (non-TTY / JSON
|
||||
// mode), agent edit returns input.confirmation_required (exit 10).
|
||||
func TestAgentEdit_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t) // non-TTY
|
||||
f := &cmdutil.Factory{
|
||||
Client: func() (*sdk.Client, error) { return nil, nil },
|
||||
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
|
||||
}
|
||||
root := withRootHarnessAgent(NewCmdEdit(f), "ag_abc", "--name", "Renamed", "--format", "json")
|
||||
err := root.Execute()
|
||||
require.Error(t, err)
|
||||
var ce *cmdutil.Error
|
||||
require.ErrorAs(t, err, &ce)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per destructive-write protocol")
|
||||
// retry command must include -y and the agent id
|
||||
assert.Contains(t, ce.RetryCommand, "-y")
|
||||
assert.Contains(t, ce.RetryCommand, "ag_abc")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,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"
|
||||
)
|
||||
|
|
@ -57,7 +58,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
|||
return runList(c.Context(), opts, fopts, cli)
|
||||
},
|
||||
}
|
||||
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)")
|
||||
cmdutil.AddFormatFlag(cmd, agentListFields...)
|
||||
return cmd
|
||||
}
|
||||
|
|
@ -66,10 +67,10 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
|||
if opts == nil {
|
||||
opts = &ListOptions{}
|
||||
}
|
||||
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),
|
||||
}
|
||||
}
|
||||
items, err := svc.ListAgents(ctx)
|
||||
|
|
@ -85,12 +86,16 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
|||
return items[i].UpdatedAt.After(items[j].UpdatedAt)
|
||||
})
|
||||
// --limit applies after sort so the cap returns the top-N most-recent.
|
||||
// The agent list SDK is unpaginated, so client-side truncation does not
|
||||
// imply server-side has_more — there is no cursor to continue with.
|
||||
// has_more is omitted; callers needing all agents should raise --limit.
|
||||
if opts.Limit > 0 && len(items) > opts.Limit {
|
||||
items = items[:opts.Limit]
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, items)
|
||||
meta := &output.Meta{Count: len(items)}
|
||||
return fopts.Emit(iostreams.IO.Out, items, meta)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ func (f *fakeListSvc) ListAgents(_ context.Context) ([]sdk.Agent, error) {
|
|||
|
||||
func TestList_Empty_Human(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no agents)") {
|
||||
|
|
@ -35,11 +35,21 @@ func TestList_Empty_Human(t *testing.T) {
|
|||
|
||||
func TestList_Empty_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(out.String()); got != "[]" {
|
||||
t.Errorf("expected bare `[]`, got %q", got)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Agent `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse envelope: %v\n%s", err, out.String())
|
||||
}
|
||||
if !env.OK {
|
||||
t.Error("envelope.ok=false")
|
||||
}
|
||||
if len(env.Data) != 0 {
|
||||
t.Errorf("expected empty data, got %d items", len(env.Data))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -50,7 +60,7 @@ func TestList_NonEmpty_Human_RendersColumns(t *testing.T) {
|
|||
{ID: "ag_a", Name: "Research", IsBuiltin: true, UpdatedAt: now.Add(-1 * time.Hour)},
|
||||
{ID: "ag_b", Name: "Triage", UpdatedAt: now.Add(-3 * 24 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -69,13 +79,17 @@ func TestList_NonEmpty_JSON_SortsByUpdatedAtDesc(t *testing.T) {
|
|||
{ID: "ag_new", Name: "new", UpdatedAt: now},
|
||||
{ID: "ag_mid", Name: "mid", UpdatedAt: now.Add(-1 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
var got []sdk.Agent
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Agent `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
got := env.Data
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("len = %d, want 3", len(got))
|
||||
}
|
||||
|
|
@ -92,9 +106,9 @@ func TestList_JSON_JQProjection(t *testing.T) {
|
|||
items := []sdk.Agent{
|
||||
{ID: "ag_x", Name: "Foo", Description: "long description"},
|
||||
}
|
||||
// --jq is the canonical projection mechanism in v0.6+.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".[] | {id, name}"}
|
||||
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
// --jq projects from the envelope; .data[] | ... extracts from the array inside envelope.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data[] | {id, name}"}
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
var got map[string]any
|
||||
|
|
@ -131,20 +145,24 @@ func TestList_Limit_CapsResults(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestList_Limit_Zero_NoCap(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(7)}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
func TestList_Limit_Zero_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(), &ListOptions{Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(7)})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for --limit 0")
|
||||
}
|
||||
got := strings.Count(out.String(), `"id":"ag_`)
|
||||
if got != 7 {
|
||||
t.Errorf("--limit 0 must not cap; got %d, want 7", got)
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T: %v", err, err)
|
||||
}
|
||||
if typed.Code != cmdutil.CodeInputInvalidArgument {
|
||||
t.Errorf("expected CodeInputInvalidArgument, got %v", typed.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeAgents(2)})
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: makeAgents(2)})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for negative --limit")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -87,8 +87,8 @@ func runAgentStatus(ctx context.Context, svc AgentStatusService, id string) (*Ag
|
|||
func emitAgentStatus(res *AgentStatusResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
return writeAgentStatusText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for agent status", fopts.Mode)
|
||||
|
|
|
|||
|
|
@ -80,10 +80,14 @@ func TestEmitAgentStatus_JSON(t *testing.T) {
|
|||
if err := emitAgentStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
var got AgentStatusResult
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data AgentStatusResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
got := env.Data
|
||||
if got.ModelID != "m_x" {
|
||||
t.Errorf("ModelID=%q, want m_x", got.ModelID)
|
||||
}
|
||||
|
|
@ -92,7 +96,7 @@ func TestEmitAgentStatus_JSON(t *testing.T) {
|
|||
func TestEmitAgentStatus_TextHuman(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
res := &AgentStatusResult{ID: "ag_x", Reachable: true, ModelID: "m_x"}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
if err := emitAgentStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ func runView(ctx context.Context, fopts *cmdutil.FormatOptions, svc ViewService,
|
|||
return cmdutil.WrapHTTP(err, "fetch agent %s", agentID)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, a)
|
||||
return fopts.Emit(iostreams.IO.Out, a, nil)
|
||||
}
|
||||
renderAgent(iostreams.IO.Out, a)
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
|
|||
WebSearchEnabled: true,
|
||||
},
|
||||
}}
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_abc"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_abc"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -126,7 +126,7 @@ func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
|||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}}
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_min"); err != nil {
|
||||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_min"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -150,22 +150,26 @@ func TestView_JSON_BareObject(t *testing.T) {
|
|||
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "ag_json"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
var got sdk.Agent
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data sdk.Agent `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
got := env.Data
|
||||
if got.ID != "ag_json" || got.Name != "JSONy" {
|
||||
t.Errorf("bare object shape wrong: id=%s name=%s", got.ID, got.Name)
|
||||
t.Errorf("envelope.data shape wrong: id=%s name=%s", got.ID, got.Name)
|
||||
}
|
||||
if strings.Contains(out.String(), `"ok":`) || strings.Contains(out.String(), `"data":`) {
|
||||
t.Errorf("bare output must not carry envelope keys, got %q", out.String())
|
||||
if !env.OK {
|
||||
t.Errorf("envelope.ok must be true, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestView_404_MapsToResourceNotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{err: errors.New("HTTP error 404: agent not found")}
|
||||
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_missing")
|
||||
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_missing")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,6 @@ import (
|
|||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
|
@ -33,7 +32,6 @@ var apiFields = []string{"<response-shape-varies>"}
|
|||
|
||||
type Options struct {
|
||||
Method string
|
||||
Data string
|
||||
Input string // --input: file path, "-" for stdin
|
||||
Yes bool
|
||||
StdinReader io.Reader // overridden by tests; defaults to iostreams.IO.In
|
||||
|
|
@ -53,18 +51,19 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
|||
cmd := &cobra.Command{
|
||||
Use: "api <path>",
|
||||
Short: "Make a raw API request to the WeKnora server",
|
||||
Long: `Send an HTTP request through the SDK and print the response.
|
||||
Long: `Raw HTTP API access. Body via --input <file> or --input - (stdin).
|
||||
|
||||
The default method is GET; passing --data / --input auto-promotes it to
|
||||
POST. Use -X/--method to override (DELETE / PUT / PATCH / HEAD).
|
||||
The default method is GET; passing --input auto-promotes it to POST. Use
|
||||
-X/--method to override (any non-empty method is accepted: DELETE / PUT /
|
||||
PATCH / HEAD / OPTIONS / TRACE / custom).
|
||||
|
||||
Auth, tenant, and request-id headers are applied automatically from the
|
||||
active context. The response body is written to stdout by default; use
|
||||
--format json to emit a {status, headers, body} JSON object.
|
||||
--format json to emit a {status, headers, body} envelope.
|
||||
|
||||
Examples:
|
||||
weknora api /api/v1/knowledge-bases # GET
|
||||
weknora api /api/v1/knowledge-bases --data '{"name":"foo"}' # POST (auto)
|
||||
weknora api /api/v1/knowledge-bases # GET
|
||||
echo '{"name":"foo"}' | weknora api /api/v1/knowledge-bases --input - # POST (auto)
|
||||
weknora api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
|
|
@ -78,7 +77,7 @@ Examples:
|
|||
// Escape-hatch DELETE through `weknora api` is just as destructive
|
||||
// as `weknora kb delete` - exit-10 protocol must apply (cli/README.md).
|
||||
if method == http.MethodDelete {
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "endpoint", args[0]); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "endpoint", args[0], "api.delete", "weknora api -X DELETE "+args[0]+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
|
@ -90,12 +89,10 @@ Examples:
|
|||
return runAPI(c.Context(), opts, fopts, cli, method, args[0], paginate)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied)")
|
||||
cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Request body as raw string (e.g. JSON)")
|
||||
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when --input is supplied). Any non-empty method is accepted.")
|
||||
cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)")
|
||||
cmd.Flags().Bool("paginate", false, "Follow offset-based pagination (?page=N&page_size=M), merging all pages into a single {data, total} JSON response.")
|
||||
cmdutil.AddFormatFlag(cmd, apiFields...)
|
||||
cmd.MarkFlagsMutuallyExclusive("data", "input")
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
|
@ -127,7 +124,7 @@ func resolveMethod(opts *Options) string {
|
|||
if opts.Method != "" {
|
||||
return strings.ToUpper(opts.Method)
|
||||
}
|
||||
if opts.Data != "" || opts.Input != "" {
|
||||
if opts.Input != "" {
|
||||
return "POST"
|
||||
}
|
||||
return "GET"
|
||||
|
|
@ -151,23 +148,16 @@ func runAPI(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, sv
|
|||
|
||||
// runAPISingle is the original single-call implementation of runAPI.
|
||||
func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, method, path string) error {
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodPut,
|
||||
http.MethodPatch, http.MethodDelete, http.MethodHead:
|
||||
default:
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("unsupported method: %s", method))
|
||||
if method == "" {
|
||||
return cmdutil.NewFlagError(fmt.Errorf("--method cannot be empty"))
|
||||
}
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
|
||||
}
|
||||
|
||||
// Resolve request body. --data and --input are mutually exclusive at
|
||||
// the cobra layer; the second branch is reachable only when --data is
|
||||
// empty.
|
||||
// Resolve request body from --input (file path or `-` for stdin).
|
||||
var body any
|
||||
if opts.Data != "" {
|
||||
body = json.RawMessage(opts.Data)
|
||||
} else if opts.Input != "" {
|
||||
if opts.Input != "" {
|
||||
contents, err := readInput(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -190,7 +180,13 @@ func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptio
|
|||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
code := cmdutil.ClassifyHTTPStatus(resp.StatusCode)
|
||||
return cmdutil.NewError(code, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody))))
|
||||
ce := cmdutil.NewError(code, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody))))
|
||||
if v := resp.Header.Get("Retry-After"); v != "" {
|
||||
if s, perr := strconv.Atoi(v); perr == nil && s > 0 {
|
||||
ce = ce.WithRetryAfter(s)
|
||||
}
|
||||
}
|
||||
return ce
|
||||
}
|
||||
|
||||
out := iostreams.IO.Out
|
||||
|
|
@ -210,14 +206,15 @@ func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptio
|
|||
hdrs[k] = v[0]
|
||||
}
|
||||
}
|
||||
// --jq runs over the full {status, headers, body} object. Per-field
|
||||
// projection isn't meaningful here since the response schema is opaque
|
||||
// to the CLI.
|
||||
return format.WriteJSONFiltered(out, map[string]any{
|
||||
// Route through fopts.Emit so the payload lives under .data in the
|
||||
// success envelope. --jq applies to the full envelope, so users
|
||||
// project with ".data.status", ".data.body", etc.
|
||||
payload := map[string]any{
|
||||
"status": resp.StatusCode,
|
||||
"headers": hdrs,
|
||||
"body": bodyAny,
|
||||
}, nil, fopts.JQ)
|
||||
}
|
||||
return fopts.Emit(out, payload, nil)
|
||||
}
|
||||
|
||||
if _, err := out.Write(respBody); err != nil {
|
||||
|
|
@ -232,7 +229,8 @@ func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptio
|
|||
// runAPIPaginated fetches all offset-based pages for a GET request and writes
|
||||
// a single merged {data, total} JSON object to stdout. If the first page
|
||||
// response does not carry pagination metadata (total + page_size), the raw
|
||||
// response is passed through unchanged (single-call fallback).
|
||||
// response is passed through via passThroughFallback which respects the
|
||||
// --format envelope contract (same shape as runAPISingle's fallback path).
|
||||
func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, path string) error {
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
|
||||
|
|
@ -243,7 +241,7 @@ func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOp
|
|||
pageSize = 50
|
||||
}
|
||||
|
||||
var allData []json.RawMessage
|
||||
allData := []json.RawMessage{}
|
||||
var lastTotal int64
|
||||
page := 1
|
||||
|
||||
|
|
@ -268,18 +266,18 @@ func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOp
|
|||
PageSize int `json:"page_size"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &pageResp); err != nil {
|
||||
// Non-JSON response on first page — pass through verbatim.
|
||||
// Non-JSON response on first page — fall back through the envelope.
|
||||
if page == 1 {
|
||||
return passThroughRaw(body)
|
||||
return passThroughFallback(body, resp, fopts)
|
||||
}
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
|
||||
fmt.Sprintf("--paginate: page %d response not in expected shape: %v", page, err))
|
||||
}
|
||||
|
||||
// Heuristic: if the first page lacks pagination metadata, treat the
|
||||
// response as non-paginated and pass through verbatim.
|
||||
// response as non-paginated and fall back through the envelope.
|
||||
if page == 1 && pageResp.Total == 0 && pageResp.PageSize == 0 {
|
||||
return passThroughRaw(body)
|
||||
return passThroughFallback(body, resp, fopts)
|
||||
}
|
||||
|
||||
allData = append(allData, pageResp.Data...)
|
||||
|
|
@ -296,13 +294,32 @@ func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOp
|
|||
"data": allData,
|
||||
"total": lastTotal,
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, merged)
|
||||
return fopts.Emit(iostreams.IO.Out, merged, nil)
|
||||
}
|
||||
|
||||
// passThroughRaw writes body verbatim to stdout (appending a newline if
|
||||
// absent), mirroring the single-call passthrough path.
|
||||
func passThroughRaw(body []byte) error {
|
||||
// passThroughFallback handles the case where --paginate detects a
|
||||
// non-paginated first-page response. When JSON output is requested, it routes
|
||||
// the body through fopts.Emit in the same {status, headers, body} envelope
|
||||
// shape that runAPISingle produces — keeping the wire contract consistent
|
||||
// regardless of whether --paginate was passed. For human-readable mode it
|
||||
// writes the raw body verbatim (same as the original passThroughRaw behavior).
|
||||
func passThroughFallback(body []byte, resp *http.Response, fopts *cmdutil.FormatOptions) error {
|
||||
out := iostreams.IO.Out
|
||||
if fopts.WantsJSON() {
|
||||
var bodyAny any
|
||||
if len(body) > 0 {
|
||||
if err := json.Unmarshal(body, &bodyAny); err != nil {
|
||||
bodyAny = string(body) // best-effort string fallback
|
||||
}
|
||||
}
|
||||
hdrs := collectHeaders(resp)
|
||||
return fopts.Emit(out, map[string]any{
|
||||
"status": resp.StatusCode,
|
||||
"headers": hdrs,
|
||||
"body": bodyAny,
|
||||
}, nil)
|
||||
}
|
||||
// Human-readable: raw passthrough, same as before.
|
||||
if _, err := out.Write(body); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write response body")
|
||||
}
|
||||
|
|
@ -312,6 +329,18 @@ func passThroughRaw(body []byte) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// collectHeaders extracts the first value of each response header into a flat
|
||||
// map, matching the shape that runAPISingle emits in its JSON envelope.
|
||||
func collectHeaders(resp *http.Response) map[string]string {
|
||||
hdrs := make(map[string]string, len(resp.Header))
|
||||
for k, v := range resp.Header {
|
||||
if len(v) > 0 {
|
||||
hdrs[k] = v[0]
|
||||
}
|
||||
}
|
||||
return hdrs
|
||||
}
|
||||
|
||||
// extractPageSize parses the page_size query parameter from path, returning 0
|
||||
// if absent or unparseable.
|
||||
func extractPageSize(path string) int {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
|
@ -52,7 +53,7 @@ func TestAPI_GetSuccess(t *testing.T) {
|
|||
})
|
||||
defer stop()
|
||||
|
||||
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/foo", false); err != nil {
|
||||
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "GET", "/api/v1/foo", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -77,14 +78,22 @@ func TestAPI_GetSuccess_JSON(t *testing.T) {
|
|||
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "GET", "/api/v1/foo", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
Status int `json:"status"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Body map[string]any `json:"body"`
|
||||
// v0.7 envelope: {ok:true, data:{status, headers, body}}
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Status int `json:"status"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Body map[string]any `json:"body"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode bare JSON: %v\n%s", err, out.String())
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode envelope JSON: %v\n%s", err, out.String())
|
||||
}
|
||||
if !env.OK {
|
||||
t.Errorf("envelope ok: want true, got false")
|
||||
}
|
||||
got := env.Data
|
||||
if got.Status != 200 {
|
||||
t.Errorf("status: want 200, got %d", got.Status)
|
||||
}
|
||||
|
|
@ -96,7 +105,7 @@ func TestAPI_GetSuccess_JSON(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestAPI_PostWithData(t *testing.T) {
|
||||
func TestAPI_PostWithStdinInput(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
var seenBody []byte
|
||||
var seenMethod, seenPath string
|
||||
|
|
@ -109,15 +118,13 @@ func TestAPI_PostWithData(t *testing.T) {
|
|||
})
|
||||
defer stop()
|
||||
|
||||
opts := &Options{Data: `{"name":"foo"}`}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/things", false); err != nil {
|
||||
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/things", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
if seenMethod != http.MethodPost || seenPath != "/api/v1/things" {
|
||||
t.Errorf("server saw %s %s, want POST /api/v1/things", seenMethod, seenPath)
|
||||
}
|
||||
// SDK marshals body via json.Marshal; json.RawMessage round-trips
|
||||
// verbatim so the bytes server-side equal the --data argument.
|
||||
if string(seenBody) != `{"name":"foo"}` {
|
||||
t.Errorf("server received body %q, want %q", seenBody, `{"name":"foo"}`)
|
||||
}
|
||||
|
|
@ -139,7 +146,7 @@ func TestAPI_InputFile(t *testing.T) {
|
|||
defer stop()
|
||||
|
||||
opts := &Options{Input: tmp}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/x", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
if string(seenBody) != payload {
|
||||
|
|
@ -160,7 +167,7 @@ func TestAPI_InputDash_Stdin(t *testing.T) {
|
|||
|
||||
payload := `{"k":"from-stdin"}`
|
||||
opts := &Options{Input: "-", StdinReader: strings.NewReader(payload)}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/x", false); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
if string(seenBody) != payload {
|
||||
|
|
@ -176,7 +183,7 @@ func TestAPI_NotFound(t *testing.T) {
|
|||
})
|
||||
defer stop()
|
||||
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/missing", false)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "GET", "/api/v1/missing", false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for 404")
|
||||
}
|
||||
|
|
@ -185,22 +192,43 @@ func TestAPI_NotFound(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestAPI_InvalidMethod(t *testing.T) {
|
||||
func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
// No server needed: validation should fail before dispatch.
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "FOO", "/api/v1/things", false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for unsupported method")
|
||||
var seenMethod string
|
||||
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
seenMethod = r.Method
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
defer stop()
|
||||
for _, m := range []string{"OPTIONS", "PATCH", "TRACE", "CUSTOM"} {
|
||||
t.Run(m, func(t *testing.T) {
|
||||
seenMethod = ""
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, m, "/api/v1/things", false)
|
||||
if err != nil {
|
||||
t.Fatalf("expected method %q to be accepted, got %v", m, err)
|
||||
}
|
||||
if seenMethod != m {
|
||||
t.Errorf("server saw method %q, want %q", seenMethod, m)
|
||||
}
|
||||
})
|
||||
}
|
||||
var ce *cmdutil.Error
|
||||
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputInvalidArgument {
|
||||
t.Errorf("expected input.invalid_argument, got %v", err)
|
||||
}
|
||||
|
||||
func TestAPI_EmptyMethodRejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil, "", "/api/v1/things", false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty method")
|
||||
}
|
||||
var fe *cmdutil.FlagError
|
||||
if !errors.As(err, &fe) {
|
||||
t.Errorf("expected FlagError, got %T %v", err, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPI_PathWithoutSlash(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "GET", "api/v1/things", false)
|
||||
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil, "GET", "api/v1/things", false)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing leading slash")
|
||||
}
|
||||
|
|
@ -320,13 +348,17 @@ func TestAPI_PaginateMergesPages(t *testing.T) {
|
|||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/knowledge-base?page=1&page_size=2", true); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
Data []map[string]string `json:"data"`
|
||||
Total int `json:"total"`
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Data []map[string]string `json:"data"`
|
||||
Total int `json:"total"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("unmarshal: %v\n%s", err, out.String())
|
||||
}
|
||||
got := env.Data
|
||||
if len(got.Data) != 5 || got.Total != 5 {
|
||||
t.Errorf("got %d records (total %d), want 5/5", len(got.Data), got.Total)
|
||||
}
|
||||
|
|
@ -350,7 +382,7 @@ func TestAPI_PaginateIgnoredForPOST(t *testing.T) {
|
|||
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
opts := &Options{Data: `{"name":"foo"}`}
|
||||
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "POST", "/api/v1/knowledge-base", true); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
|
|
@ -361,18 +393,20 @@ func TestAPI_PaginateIgnoredForPOST(t *testing.T) {
|
|||
|
||||
func TestAPI_PaginateNoMetadataPassesThrough(t *testing.T) {
|
||||
// If response doesn't look paginated (no total/page/page_size), --paginate
|
||||
// should fall back to single-call behavior (don't crash).
|
||||
// should fall back to single-call envelope behavior (same shape as api without --paginate).
|
||||
called := 0
|
||||
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
|
||||
called++
|
||||
hdr := make(http.Header)
|
||||
hdr.Set("Content-Type", "application/json")
|
||||
return &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: io.NopCloser(bytes.NewReader([]byte(`{"hello":"world"}`))),
|
||||
Header: make(http.Header),
|
||||
Header: hdr,
|
||||
}, nil
|
||||
}}
|
||||
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
opts := &Options{}
|
||||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/whoami", true); err != nil {
|
||||
|
|
@ -381,6 +415,27 @@ func TestAPI_PaginateNoMetadataPassesThrough(t *testing.T) {
|
|||
if called != 1 {
|
||||
t.Errorf("called %d times, want 1 (non-paginated response)", called)
|
||||
}
|
||||
// H3a: fallback must produce an envelope, not raw passthrough.
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Status int `json:"status"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Body map[string]any `json:"body"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("non-paginated fallback must emit envelope JSON, unmarshal failed: %v\n%s", err, out.String())
|
||||
}
|
||||
if !env.OK {
|
||||
t.Errorf("envelope ok: want true, got false")
|
||||
}
|
||||
if env.Data.Status != 200 {
|
||||
t.Errorf("envelope data.status: want 200, got %d", env.Data.Status)
|
||||
}
|
||||
if v, ok := env.Data.Body["hello"]; !ok || v.(string) != "world" {
|
||||
t.Errorf("envelope data.body: want {hello:world}, got %v", env.Data.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPI_PaginateServerCapsPageSize covers the case where the user
|
||||
|
|
@ -418,13 +473,17 @@ func TestAPI_PaginateServerCapsPageSize(t *testing.T) {
|
|||
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/items?page=1&page_size=10", true); err != nil {
|
||||
t.Fatalf("runAPI: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
Data []map[string]string `json:"data"`
|
||||
Total int `json:"total"`
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Data []map[string]string `json:"data"`
|
||||
Total int `json:"total"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
|
||||
t.Fatalf("unmarshal: %v\n%s", err, stdout.String())
|
||||
}
|
||||
got := env.Data
|
||||
if len(got.Data) != 5 {
|
||||
t.Errorf("got %d records, want 5 (server-capped page_size should not cause truncation)", len(got.Data))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,14 +39,7 @@ func modeFromRefs(apiKeyRef, tokenRef string) string {
|
|||
func NewCmdAuth(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "auth",
|
||||
Short: "Manage authentication credentials and contexts",
|
||||
// NoArgs makes cobra emit its canonical `unknown command "X" for
|
||||
// "weknora auth"` for any positional, which mapCobraError tags as
|
||||
// FlagError → exit 2. Run (not RunE) is required: a parent with
|
||||
// neither Run nor RunE short-circuits to help and skips Args
|
||||
// validation entirely.
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
Short: "Manage authentication credentials and profiles",
|
||||
}
|
||||
cmd.AddCommand(NewCmdLogin(f, nil))
|
||||
cmd.AddCommand(NewCmdLogout(f))
|
||||
|
|
|
|||
|
|
@ -31,12 +31,13 @@ func TestNewCmdAuth_TreeShape(t *testing.T) {
|
|||
|
||||
func TestNewCmdLogin_FlagsRegistered(t *testing.T) {
|
||||
cmd := NewCmdLogin(&cmdutil.Factory{}, nil)
|
||||
for _, name := range []string{"host", "name", "with-token", "format"} {
|
||||
// --format is a persistent root flag (v0.7); only per-command flags here.
|
||||
for _, name := range []string{"host", "name", "with-token"} {
|
||||
assert.NotNilf(t, cmd.Flags().Lookup(name), "flag %s missing", name)
|
||||
}
|
||||
// `--context` should NOT be a local flag (it's the global persistent flag).
|
||||
// Local registration would silently shadow the global single-shot override.
|
||||
assert.Nil(t, cmd.Flags().Lookup("context"), "auth login must not declare a local --context flag (use --name)")
|
||||
// --profile is the global persistent override; local registration would
|
||||
// silently shadow it.
|
||||
assert.Nil(t, cmd.Flags().Lookup("profile"), "auth login must not declare a local --profile flag (use --name)")
|
||||
}
|
||||
|
||||
func TestNewCmdLogin_InvokesRunF(t *testing.T) {
|
||||
|
|
@ -76,7 +77,7 @@ func TestPersistAPIKey_WritesContext(t *testing.T) {
|
|||
Context: "ci",
|
||||
APIKey: "sk-zzz",
|
||||
}
|
||||
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
|
||||
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil))
|
||||
v, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-zzz", v)
|
||||
cfg, _ := f.Config()
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
type ListOptions struct{}
|
||||
|
|
@ -29,13 +30,13 @@ type listEntry struct {
|
|||
}
|
||||
|
||||
// NewCmdList builds `weknora auth list`. Per-host enumeration: render one
|
||||
// row per registered context, marking the active one. Reads only
|
||||
// row per registered profile, marking the active one. Reads only
|
||||
// ~/.config/weknora/config.yaml - no network, no keyring touch.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List configured authentication contexts",
|
||||
Long: `Show every configured context (name, host, user, mode, current). Read-only; no network or keyring access.`,
|
||||
Short: "List configured authentication profiles",
|
||||
Long: `Show every configured profile (name, host, user, mode, current). Read-only; no network or keyring access.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
|
|
@ -68,10 +69,11 @@ func runList(fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
|
|||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, entries)
|
||||
meta := &output.Meta{Count: len(entries)}
|
||||
return fopts.Emit(iostreams.IO.Out, entries, meta)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` to create one.")
|
||||
fmt.Fprintln(iostreams.IO.Out, "No profiles configured. Run `weknora auth login` to create one.")
|
||||
return nil
|
||||
}
|
||||
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ func TestList_HumanRender(t *testing.T) {
|
|||
"staging": {Host: "https://staging", APIKeyRef: "keychain://staging/api_key"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(cfg)))
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newListFactory(cfg)))
|
||||
|
||||
got := out.String()
|
||||
// One row per context, current marked with `*`.
|
||||
|
|
@ -44,8 +44,8 @@ func TestList_HumanRender(t *testing.T) {
|
|||
|
||||
func TestList_Empty(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(&config.Config{})))
|
||||
assert.Contains(t, out.String(), "No contexts configured")
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newListFactory(&config.Config{})))
|
||||
assert.Contains(t, out.String(), "No profiles configured")
|
||||
}
|
||||
|
||||
func TestList_JSON_BareArray(t *testing.T) {
|
||||
|
|
@ -59,8 +59,13 @@ func TestList_JSON_BareArray(t *testing.T) {
|
|||
}
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, newListFactory(cfg)))
|
||||
|
||||
var got []listEntry
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &got))
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []listEntry `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
|
||||
assert.True(t, env.OK)
|
||||
got := env.Data
|
||||
require.Len(t, got, 2)
|
||||
// Sorted: prod < staging.
|
||||
assert.Equal(t, "prod", got[0].Name)
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ import (
|
|||
// keyring; agents who need to verify the credential should re-run
|
||||
// `auth status`.
|
||||
var authLoginFields = []string{
|
||||
"context", "host", "mode", "user", "tenant_id",
|
||||
"profile", "host", "mode", "user", "tenant_id",
|
||||
}
|
||||
|
||||
// LoginOptions is the configuration captured from flags + prompts.
|
||||
|
|
@ -93,7 +93,7 @@ the current_context in ~/.config/weknora/config.yaml.`,
|
|||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Host, "host", "", "WeKnora server URL, e.g. https://kb.example.com")
|
||||
cmd.Flags().StringVar(&opts.Context, "name", "default", "Context name to register in config.yaml")
|
||||
cmd.Flags().StringVar(&opts.Context, "name", "default", "Profile name to register in config.yaml")
|
||||
cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
|
||||
cmdutil.AddFormatFlag(cmd, authLoginFields...)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
|
|
@ -128,6 +128,13 @@ func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOpti
|
|||
// is /auth/me - read-only, side-effect-free.
|
||||
user, err := defaultAPIKeyValidator(ctx, opts.Host, key)
|
||||
if err != nil {
|
||||
// Transport errors (connection refused, DNS failure) must not be
|
||||
// surfaced as auth.bad_credential — the key may be fine but the
|
||||
// host is unreachable. Classify via WrapHTTP so network errors
|
||||
// get CodeNetworkError and the hint points at `weknora doctor`.
|
||||
if cmdutil.ClassifyHTTPError(err) == cmdutil.CodeNetworkError {
|
||||
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "validate API key: check host reachability")
|
||||
}
|
||||
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key")
|
||||
}
|
||||
return persistAPIKey(opts, fopts, f, user)
|
||||
|
|
@ -157,6 +164,12 @@ func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOpti
|
|||
|
||||
resp, err := svc.Login(ctx, sdk.LoginRequest{Email: opts.Email, Password: opts.Password})
|
||||
if err != nil {
|
||||
// Transport errors (connection refused, DNS failure) must not be
|
||||
// surfaced as auth.bad_credential — credentials may be fine but the
|
||||
// host is unreachable. Classify so network errors get CodeNetworkError.
|
||||
if cmdutil.ClassifyHTTPError(err) == cmdutil.CodeNetworkError {
|
||||
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "login: check host reachability")
|
||||
}
|
||||
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "login")
|
||||
}
|
||||
if !resp.Success || resp.Token == "" {
|
||||
|
|
@ -220,7 +233,7 @@ func persistJWT(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
|||
// loginResult is the typed payload emitted by `--format json`. mode is derived from
|
||||
// whether the server returned a user (password flow) vs API-key flow.
|
||||
type loginResult struct {
|
||||
Context string `json:"context"`
|
||||
Profile string `json:"profile"`
|
||||
Host string `json:"host"`
|
||||
Mode string `json:"mode"` // ModeBearer or ModeAPIKey
|
||||
User string `json:"user,omitempty"`
|
||||
|
|
@ -242,13 +255,13 @@ func saveContextRef(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil
|
|||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
result := loginResult{Context: opts.Context, Host: opts.Host, Mode: ModeAPIKey}
|
||||
result := loginResult{Profile: opts.Context, Host: opts.Host, Mode: ModeAPIKey}
|
||||
if user != nil {
|
||||
result.Mode = ModeBearer
|
||||
result.User = user.Email
|
||||
result.TenantID = user.TenantID
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, result)
|
||||
return fopts.Emit(iostreams.IO.Out, result, nil)
|
||||
}
|
||||
who := opts.Context
|
||||
if user != nil {
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ func TestRunLogin_PasswordMode(t *testing.T) {
|
|||
Host: "https://kb.example.com",
|
||||
Context: "prod",
|
||||
}
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc))
|
||||
|
||||
assert.Equal(t, "a@b.c", svc.got.email)
|
||||
assert.Equal(t, "secret", svc.got.password)
|
||||
|
|
@ -84,7 +84,7 @@ func TestRunLogin_WithToken(t *testing.T) {
|
|||
WithToken: true,
|
||||
StdinReader: strings.NewReader(" sk-1234 \n"),
|
||||
}
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil))
|
||||
got, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-1234", got)
|
||||
cfg, _ := f.Config()
|
||||
|
|
@ -96,7 +96,9 @@ func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
|
|||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
|
||||
return nil, errors.New("HTTP 401: invalid api key")
|
||||
// Use the SDK-format HTTP error message so ClassifyHTTPError detects
|
||||
// this as an HTTP 401, not a transport/network failure.
|
||||
return nil, errors.New("HTTP error 401: invalid api key")
|
||||
})
|
||||
defer restore()
|
||||
opts := &LoginOptions{
|
||||
|
|
@ -105,7 +107,7 @@ func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
|
|||
WithToken: true,
|
||||
StdinReader: strings.NewReader("sk-bad"),
|
||||
}
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -137,7 +139,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
|
|||
WithToken: true,
|
||||
StdinReader: strings.NewReader(""),
|
||||
}
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.missing_flag")
|
||||
}
|
||||
|
|
@ -145,7 +147,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
|
|||
func TestRunLogin_BadHost(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
|
|
@ -154,7 +156,7 @@ func TestRunLogin_LoginRefused(t *testing.T) {
|
|||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "x"})
|
||||
svc := &fakeLoginService{resp: &sdk.LoginResponse{Success: false, Message: "bad password"}}
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc)
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "auth.bad_credential")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,12 +13,13 @@ import (
|
|||
)
|
||||
|
||||
type LogoutOptions struct {
|
||||
Name string // --name: target a specific context (default: current)
|
||||
All bool // --all: clear every context
|
||||
Name string // --name: target a specific profile (default: current)
|
||||
All bool // --all: clear every profile
|
||||
Yes bool // sourced from the global -y/--yes persistent flag
|
||||
}
|
||||
|
||||
// authLogoutFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `auth logout`. The result is the list of context names that were
|
||||
// on `auth logout`. The result is the list of profile names that were
|
||||
// logged out.
|
||||
var authLogoutFields = []string{"removed"}
|
||||
|
||||
|
|
@ -28,21 +29,21 @@ type logoutResult struct {
|
|||
}
|
||||
|
||||
// NewCmdLogout builds `weknora auth logout`. Clears stored credentials
|
||||
// (keyring + file fallback) and removes the context entry from config.yaml.
|
||||
// (keyring + file fallback) and removes the profile entry from config.yaml.
|
||||
// No server-side revocation - local-only credential clear.
|
||||
func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &LogoutOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "logout",
|
||||
Short: "Remove stored credentials for a context",
|
||||
Long: `Clear keyring + file-fallback secrets for one context (or all of
|
||||
them with --all) and drop the context entry from ~/.config/weknora/config.yaml.
|
||||
Short: "Remove stored credentials for a profile",
|
||||
Long: `Clear keyring + file-fallback secrets for one profile (or all of
|
||||
them with --all) and drop the profile entry from ~/.config/weknora/config.yaml.
|
||||
|
||||
Note: this does NOT revoke the credential server-side - for API keys, you
|
||||
must rotate them in the server UI; for JWT, the token will continue to be
|
||||
accepted until it expires.`,
|
||||
Example: ` weknora auth logout # current context
|
||||
weknora auth logout --name staging # specific context
|
||||
Example: ` weknora auth logout # current profile
|
||||
weknora auth logout --name staging # specific profile
|
||||
weknora auth logout --all`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
|
|
@ -51,13 +52,25 @@ accepted until it expires.`,
|
|||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
return runLogout(opts, fopts, f)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to log out (defaults to the current context)")
|
||||
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context")
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Profile to log out (defaults to the current profile)")
|
||||
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured profile")
|
||||
cmdutil.AddFormatFlag(cmd, authLogoutFields...)
|
||||
cmd.MarkFlagsMutuallyExclusive("name", "all")
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "clear stored credentials for one profile (or all) and remove the profile from config",
|
||||
Examples: []string{
|
||||
"weknora auth logout",
|
||||
"weknora auth logout --name staging",
|
||||
"weknora auth logout --all",
|
||||
},
|
||||
Warnings: []string{
|
||||
"auth logout drops stored credentials. The user will need to re-authenticate. Confirm scope before invoking.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
|
@ -67,7 +80,7 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
|||
return err
|
||||
}
|
||||
if len(cfg.Contexts) == 0 {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no contexts configured; nothing to log out")
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no profiles configured; nothing to log out")
|
||||
}
|
||||
|
||||
targets, err := pickLogoutTargets(opts, cfg)
|
||||
|
|
@ -75,6 +88,18 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
|||
return err
|
||||
}
|
||||
|
||||
// Destructive-write protocol: confirm before clearing credentials.
|
||||
scope := fmt.Sprintf("%d profile(s) [%s]", len(targets), strings.Join(targets, ", "))
|
||||
retryCmd := "weknora auth logout -y"
|
||||
if opts.All {
|
||||
retryCmd = "weknora auth logout --all -y"
|
||||
} else if opts.Name != "" {
|
||||
retryCmd = fmt.Sprintf("weknora auth logout --name %s -y", opts.Name)
|
||||
}
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "auth credentials", scope, "auth.logout", retryCmd); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -95,13 +120,13 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
|||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, logoutResult{Removed: targets})
|
||||
return fopts.Emit(iostreams.IO.Out, logoutResult{Removed: targets}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d context(s): %s\n", len(targets), strings.Join(targets, ", "))
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d profile(s): %s\n", len(targets), strings.Join(targets, ", "))
|
||||
return nil
|
||||
}
|
||||
|
||||
// pickLogoutTargets resolves the set of contexts to clear from flags + config.
|
||||
// pickLogoutTargets resolves the set of profiles to clear from flags + config.
|
||||
func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error) {
|
||||
if opts.All {
|
||||
names := make([]string, 0, len(cfg.Contexts))
|
||||
|
|
@ -116,16 +141,16 @@ func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error
|
|||
}
|
||||
if name == "" {
|
||||
return nil, cmdutil.NewError(cmdutil.CodeInputMissingFlag,
|
||||
"no current context set; pass --name <ctx> or --all")
|
||||
"no current profile set; pass --name <profile> or --all")
|
||||
}
|
||||
if _, ok := cfg.Contexts[name]; !ok {
|
||||
return nil, cmdutil.NewError(cmdutil.CodeLocalContextNotFound,
|
||||
fmt.Sprintf("context %q not found in config", name))
|
||||
return nil, cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
|
||||
fmt.Sprintf("profile %q not found in config", name))
|
||||
}
|
||||
return []string{name}, nil
|
||||
}
|
||||
|
||||
// clearContextSecrets best-effort deletes every secret slot the context
|
||||
// clearContextSecrets best-effort deletes every secret slot the profile
|
||||
// references. Errors are swallowed because a missing secret is a no-op
|
||||
// (tested in keyring_test.go) - we don't want a stale ref to block logout.
|
||||
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
)
|
||||
|
||||
|
|
@ -20,8 +21,9 @@ import (
|
|||
func newLogoutFactory(t *testing.T, cfg *config.Config, store secrets.Store) *cmdutil.Factory {
|
||||
t.Helper()
|
||||
return &cmdutil.Factory{
|
||||
Config: func() (*config.Config, error) { return cfg, nil },
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
Config: func() (*config.Config, error) { return cfg, nil },
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
Prompter: func() prompt.Prompter { return &prompt.AgentPrompter{} },
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -45,7 +47,7 @@ func TestLogout_CurrentContext(t *testing.T) {
|
|||
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Empty(t, cfg.CurrentContext, "current_context should clear when removed")
|
||||
assert.NotContains(t, cfg.Contexts, "prod")
|
||||
|
|
@ -73,7 +75,7 @@ func TestLogout_NamedContext(t *testing.T) {
|
|||
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{Name: "staging", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Equal(t, "prod", cfg.CurrentContext, "current_context untouched when removing other")
|
||||
assert.NotContains(t, cfg.Contexts, "staging")
|
||||
|
|
@ -91,7 +93,7 @@ func TestLogout_All(t *testing.T) {
|
|||
"staging": {Host: "https://staging"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{All: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{All: true, Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Empty(t, cfg.Contexts)
|
||||
assert.Empty(t, cfg.CurrentContext)
|
||||
|
|
@ -101,7 +103,7 @@ func TestLogout_NoContexts(t *testing.T) {
|
|||
isolateConfig(t)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
cfg := &config.Config{}
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -115,11 +117,11 @@ func TestLogout_UnknownName(t *testing.T) {
|
|||
CurrentContext: "prod",
|
||||
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeLocalContextNotFound, typed.Code)
|
||||
assert.Equal(t, cmdutil.CodeLocalProfileNotFound, typed.Code)
|
||||
}
|
||||
|
||||
func TestLogout_NoCurrentNoFlag(t *testing.T) {
|
||||
|
|
@ -128,7 +130,7 @@ func TestLogout_NoCurrentNoFlag(t *testing.T) {
|
|||
cfg := &config.Config{
|
||||
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
|
|||
|
|
@ -12,26 +12,26 @@ import (
|
|||
)
|
||||
|
||||
type RefreshOptions struct {
|
||||
Name string // --name: target context (defaults to current)
|
||||
Name string // --name: target profile (defaults to current)
|
||||
}
|
||||
|
||||
// authRefreshFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `auth refresh`. Token values are intentionally omitted - see refreshResult.
|
||||
var authRefreshFields = []string{"context"}
|
||||
var authRefreshFields = []string{"profile"}
|
||||
|
||||
// refreshResult is the typed payload emitted under data on success. Token
|
||||
// values are intentionally NOT included - emitting them would leak secrets
|
||||
// into stdout / agent transcripts. Agents needing to verify the new token
|
||||
// can re-run `weknora auth status` (live API check).
|
||||
type refreshResult struct {
|
||||
Context string `json:"context"`
|
||||
Profile string `json:"profile"`
|
||||
}
|
||||
|
||||
// NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access
|
||||
// token by spending the stored refresh_token via POST /auth/refresh -
|
||||
// the standard OAuth refresh-token grant.
|
||||
//
|
||||
// API-key contexts are rejected - they have no refresh semantic;
|
||||
// API-key profiles are rejected - they have no refresh semantic;
|
||||
// rotate the key via the server UI instead.
|
||||
func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &RefreshOptions{}
|
||||
|
|
@ -42,10 +42,10 @@ func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
|
|||
exchanges it for a new access + refresh token pair via POST /api/v1/auth/refresh.
|
||||
Both new tokens replace the existing entries in the OS keyring.
|
||||
|
||||
API-key contexts are rejected with input.invalid_argument - they have no
|
||||
API-key profiles are rejected with input.invalid_argument - they have no
|
||||
refresh semantic. Rotate the key in the server UI instead.`,
|
||||
Example: ` weknora auth refresh # refresh the current context
|
||||
weknora auth refresh --name staging # refresh a specific context`,
|
||||
Example: ` weknora auth refresh # refresh the current profile
|
||||
weknora auth refresh --name staging # refresh a specific profile`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
|
|
@ -56,7 +56,7 @@ refresh semantic. Rotate the key in the server UI instead.`,
|
|||
return runRefresh(c.Context(), opts, fopts, f, defaultRefresher)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)")
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Profile to refresh (defaults to the current profile)")
|
||||
cmdutil.AddFormatFlag(cmd, authRefreshFields...)
|
||||
return cmd
|
||||
}
|
||||
|
|
@ -79,25 +79,25 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.Format
|
|||
}
|
||||
if name == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
"no current context configured; run `weknora auth login` to set one up")
|
||||
"no current profile configured; run `weknora auth login` to set one up")
|
||||
}
|
||||
c, ok := cfg.Contexts[name]
|
||||
if !ok {
|
||||
return cmdutil.NewError(cmdutil.CodeLocalContextNotFound,
|
||||
fmt.Sprintf("context not found: %s", name))
|
||||
return cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
|
||||
fmt.Sprintf("profile not found: %s", name))
|
||||
}
|
||||
if c.Host == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeLocalConfigCorrupt,
|
||||
fmt.Sprintf("context %q has no host", name))
|
||||
fmt.Sprintf("profile %q has no host", name))
|
||||
}
|
||||
if c.RefreshRef == "" {
|
||||
hint := "api-key contexts can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`"
|
||||
hint := "api-key profiles can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`"
|
||||
if c.APIKeyRef == "" {
|
||||
hint = "no refresh token stored - run `weknora auth login` to authenticate"
|
||||
}
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("context %q has no refresh token", name),
|
||||
Message: fmt.Sprintf("profile %q has no refresh token", name),
|
||||
Hint: hint,
|
||||
}
|
||||
}
|
||||
|
|
@ -111,8 +111,8 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.Format
|
|||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, refreshResult{Context: name})
|
||||
return fopts.Emit(iostreams.IO.Out, refreshResult{Profile: name}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for context %s\n", name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for profile %s\n", name)
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package auth
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
|
@ -71,7 +72,7 @@ func TestRefresh_Happy(t *testing.T) {
|
|||
AccessToken: "new-access",
|
||||
RefreshToken: "new-refresh",
|
||||
}}
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc)))
|
||||
|
||||
assert.Equal(t, "old-refresh", svc.gotTok, "must pass stored refresh token to SDK")
|
||||
gotAccess, _ := store.Get("prod", "access")
|
||||
|
|
@ -96,7 +97,7 @@ func TestRefresh_NamedContext(t *testing.T) {
|
|||
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{
|
||||
Success: true, AccessToken: "new-stg-access", RefreshToken: "new-stg-refresh",
|
||||
}}
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc)))
|
||||
|
||||
assert.Equal(t, "stg-refresh", svc.gotTok, "--name=staging must refresh the staging context, not current")
|
||||
// current is untouched
|
||||
|
|
@ -108,7 +109,7 @@ func TestRefresh_NamedContext(t *testing.T) {
|
|||
func TestRefresh_NoCurrentContext(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f := newRefreshFactory(t, &config.Config{}, secrets.NewMemStore())
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -124,7 +125,7 @@ func TestRefresh_APIKeyContext(t *testing.T) {
|
|||
Contexts: map[string]config.Context{"ci": {Host: "https://kb", APIKeyRef: "mem://ci/api_key"}},
|
||||
}
|
||||
f := newRefreshFactory(t, cfg, store)
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -142,7 +143,7 @@ func TestRefresh_NoRefreshTokenStored(t *testing.T) {
|
|||
}
|
||||
// MemStore is empty - RefreshRef points to a slot that doesn't exist.
|
||||
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -160,7 +161,7 @@ func TestRefresh_ServerRefused(t *testing.T) {
|
|||
}
|
||||
f := newRefreshFactory(t, cfg, store)
|
||||
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{Success: false, Message: "refresh token expired"}}
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -183,7 +184,7 @@ func TestRefresh_TransportError(t *testing.T) {
|
|||
}
|
||||
f := newRefreshFactory(t, cfg, store)
|
||||
svc := &fakeRefreshService{err: errors.New("connection reset")}
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -212,5 +213,10 @@ func TestRefresh_JSONOutput(t *testing.T) {
|
|||
assert.NotContains(t, body, "\"r\"", "output must not leak the new refresh token")
|
||||
// must mention the context name so agents can confirm what was refreshed
|
||||
assert.True(t, strings.Contains(body, "prod"), "output should reference the refreshed context")
|
||||
assert.NotContains(t, body, `"ok":`)
|
||||
// v0.7 envelope: ok:true is expected
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &env))
|
||||
assert.True(t, env.OK, "envelope.ok must be true")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import (
|
|||
// authStatusFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `auth status`. Single-resource shape: filter applies to data itself.
|
||||
var authStatusFields = []string{
|
||||
"context", "user_id", "username", "email", "is_active",
|
||||
"profile", "user_id", "username", "email", "is_active",
|
||||
"can_access_all_tenants", "tenant_id", "tenant_name",
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +28,7 @@ type StatusService interface {
|
|||
// can_access_all_tenants (cross-tenant admin) and is_active (disabled
|
||||
// account) without a second round-trip.
|
||||
type statusResult struct {
|
||||
Context string `json:"context"`
|
||||
Profile string `json:"profile"`
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
|
|
@ -42,13 +42,13 @@ type statusResult struct {
|
|||
func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "status",
|
||||
Short: "Show the active context, principal, and token state",
|
||||
Short: "Show the active profile, principal, and token state",
|
||||
Long: `Live-check the active credential by calling /auth/me. Reports the user
|
||||
and tenant the server resolves the credential to.
|
||||
|
||||
Exits with auth.unauthenticated when the token is invalid or missing - run
|
||||
` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT contexts) to recover.
|
||||
For JWT contexts the SDK transparently refreshes on 401, so this command
|
||||
` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT profiles) to recover.
|
||||
For JWT profiles the SDK transparently refreshes on 401, so this command
|
||||
usually only surfaces a hard auth failure.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
|
|
@ -85,7 +85,7 @@ func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
|||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
result := statusResult{Context: cfg.CurrentContext}
|
||||
result := statusResult{Profile: cfg.CurrentContext}
|
||||
if user != nil {
|
||||
result.UserID = user.ID
|
||||
result.Username = user.Username
|
||||
|
|
@ -97,14 +97,14 @@ func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
|||
if tenant != nil {
|
||||
result.TenantName = tenant.Name
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, result)
|
||||
return fopts.Emit(iostreams.IO.Out, result, nil)
|
||||
}
|
||||
|
||||
host := ""
|
||||
if c, ok := cfg.Contexts[cfg.CurrentContext]; ok {
|
||||
host = c.Host
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "context: %s\n", cfg.CurrentContext)
|
||||
fmt.Fprintf(iostreams.IO.Out, "profile: %s\n", cfg.CurrentContext)
|
||||
fmt.Fprintf(iostreams.IO.Out, "host: %s\n", host)
|
||||
if user != nil {
|
||||
fmt.Fprintf(iostreams.IO.Out, "user: %s (%s)\n", user.Email, user.ID)
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ package auth
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
|
@ -52,9 +52,9 @@ func TestRunStatus_HumanOutput(t *testing.T) {
|
|||
&sdk.AuthTenant{ID: 7, Name: "Acme"},
|
||||
),
|
||||
}
|
||||
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
|
||||
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "context: prod")
|
||||
assert.Contains(t, got, "profile: prod")
|
||||
assert.Contains(t, got, "host: https://kb.example.com")
|
||||
assert.Contains(t, got, "alice@example.com")
|
||||
assert.Contains(t, got, "Acme")
|
||||
|
|
@ -71,14 +71,19 @@ func TestRunStatus_JSONOutput(t *testing.T) {
|
|||
svc := &fakeStatusService{resp: newCurrentUserResponse(&sdk.AuthUser{ID: "u1", Email: "a@b.c", TenantID: 7}, nil)}
|
||||
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, svc))
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"context":"prod"`), "expected bare object, got: %q", got)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]any `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.Equal(t, "prod", env.Data["profile"], "profile field should be prod")
|
||||
assert.Contains(t, got, `"email":"a@b.c"`)
|
||||
}
|
||||
|
||||
func TestRunStatus_NoSDKClient(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &cmdutil.Factory{}, nil)
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &cmdutil.Factory{}, nil)
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsAuthError(err))
|
||||
}
|
||||
|
|
@ -88,7 +93,7 @@ func TestRunStatus_SDKError_Transport(t *testing.T) {
|
|||
testutil.XDGTempDir(t)
|
||||
require.NoError(t, config.Save(&config.Config{CurrentContext: "p", Contexts: map[string]config.Context{"p": {Host: "https://x"}}}))
|
||||
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: assert.AnError})
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, &fakeStatusService{err: assert.AnError})
|
||||
require.Error(t, err)
|
||||
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems -
|
||||
// classify network.error so retry logic / exit code 7 / IsTransient apply.
|
||||
|
|
@ -100,7 +105,7 @@ func TestRunStatus_SDKError_HTTP401(t *testing.T) {
|
|||
testutil.XDGTempDir(t)
|
||||
require.NoError(t, config.Save(&config.Config{CurrentContext: "p", Contexts: map[string]config.Context{"p": {Host: "https://x"}}}))
|
||||
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsAuthError(err))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,15 +11,15 @@ import (
|
|||
|
||||
// authTokenFields lists fields surfaced in `--help` as a hint for `--jq`
|
||||
// projection. Single-resource shape: emits the bare token object directly.
|
||||
var authTokenFields = []string{"token", "mode", "context"}
|
||||
var authTokenFields = []string{"token", "mode", "profile"}
|
||||
|
||||
type tokenResult struct {
|
||||
Token string `json:"token"`
|
||||
Mode string `json:"mode"` // ModeBearer (JWT) or ModeAPIKey
|
||||
Context string `json:"context"`
|
||||
Profile string `json:"profile"`
|
||||
}
|
||||
|
||||
// NewCmdToken builds `weknora auth token`. Prints the active context's
|
||||
// NewCmdToken builds `weknora auth token`. Prints the active profile's
|
||||
// credential to stdout for use in shell pipelines, e.g.
|
||||
//
|
||||
// WEKNORA_TOKEN=$(weknora auth token)
|
||||
|
|
@ -27,27 +27,27 @@ type tokenResult struct {
|
|||
// curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key mode
|
||||
//
|
||||
// The user is responsible for constructing the appropriate header -
|
||||
// `auth list` shows which mode each context uses.
|
||||
// `auth list` shows which mode each profile uses.
|
||||
//
|
||||
// Default output: raw token on stdout, no trailing newline (clean $(...)).
|
||||
// `--format json[=fields]` emits a bare {token, mode, context} object.
|
||||
// `--format json[=fields]` emits a bare {token, mode, profile} object.
|
||||
func NewCmdToken(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "token",
|
||||
Short: "Print the active context's credential to stdout",
|
||||
Long: `Print the active context's credential to stdout, with no trailing
|
||||
Short: "Print the active profile's credential to stdout",
|
||||
Long: `Print the active profile's credential to stdout, with no trailing
|
||||
newline, suitable for shell command substitution.
|
||||
|
||||
The credential is the long-lived API key (mode: api-key) or the access JWT
|
||||
(mode: bearer), depending on how the context was created. Run ` + "`weknora auth list`" + `
|
||||
to see which mode each context uses, and construct the matching HTTP header:
|
||||
(mode: bearer), depending on how the profile was created. Run ` + "`weknora auth list`" + `
|
||||
to see which mode each profile uses, and construct the matching HTTP header:
|
||||
|
||||
Authorization: Bearer <token> # bearer mode
|
||||
X-API-Key: <token> # api-key mode
|
||||
|
||||
` + "`--context <name>`" + ` (global flag) selects a non-active context to read from.`,
|
||||
` + "`--profile <name>`" + ` (global flag) selects a non-active profile to read from.`,
|
||||
Example: ` WEKNORA_TOKEN=$(weknora auth token)
|
||||
weknora auth token --context staging
|
||||
weknora auth token --profile staging
|
||||
weknora auth token --format json`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
|
|
@ -69,17 +69,17 @@ func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
|
|||
return err
|
||||
}
|
||||
ctxName := cfg.CurrentContext
|
||||
if f.ContextOverride != "" {
|
||||
ctxName = f.ContextOverride
|
||||
if f.ProfileOverride != "" {
|
||||
ctxName = f.ProfileOverride
|
||||
}
|
||||
if ctxName == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
"no current context configured")
|
||||
"no current profile configured")
|
||||
}
|
||||
ctx, ok := cfg.Contexts[ctxName]
|
||||
if !ok {
|
||||
return cmdutil.NewError(cmdutil.CodeLocalContextNotFound,
|
||||
fmt.Sprintf("context %q not found", ctxName))
|
||||
return cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
|
||||
fmt.Sprintf("profile %q not found", ctxName))
|
||||
}
|
||||
|
||||
store, err := f.Secrets()
|
||||
|
|
@ -106,16 +106,16 @@ func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
|
|||
token, mode = v, ModeAPIKey
|
||||
default:
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
fmt.Sprintf("context %q has no stored credential; run `weknora auth login`", ctxName))
|
||||
fmt.Sprintf("profile %q has no stored credential; run `weknora auth login`", ctxName))
|
||||
}
|
||||
|
||||
if token == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
fmt.Sprintf("context %q credential is empty in keyring; run `weknora auth login`", ctxName))
|
||||
fmt.Sprintf("profile %q credential is empty in keyring; run `weknora auth login`", ctxName))
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Context: ctxName})
|
||||
return fopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Profile: ctxName}, nil)
|
||||
}
|
||||
|
||||
// No trailing newline - clean $(weknora auth token) substitution.
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ func TestAuthToken_BearerMode_PlainOutput(t *testing.T) {
|
|||
_ = store.Set("prod", "access", "jwt-token-xyz")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
|
||||
if err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
|
|
@ -58,7 +58,7 @@ func TestAuthToken_APIKeyMode_PlainOutput(t *testing.T) {
|
|||
_ = store.Set("ci", "api_key", "sk_test_apikey_42")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if got := out.String(); got != "sk_test_apikey_42" {
|
||||
|
|
@ -80,15 +80,19 @@ func TestAuthToken_JSON(t *testing.T) {
|
|||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
Token string `json:"token"`
|
||||
Mode string `json:"mode"`
|
||||
Context string `json:"context"`
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data struct {
|
||||
Token string `json:"token"`
|
||||
Mode string `json:"mode"`
|
||||
Profile string `json:"profile"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, out.String())
|
||||
}
|
||||
if got.Token != "jwt-xyz" || got.Mode != "bearer" || got.Context != "prod" {
|
||||
got := env.Data
|
||||
if got.Token != "jwt-xyz" || got.Mode != "bearer" || got.Profile != "prod" {
|
||||
t.Errorf("payload wrong: %+v", got)
|
||||
}
|
||||
}
|
||||
|
|
@ -104,7 +108,8 @@ func TestAuthToken_JSON_JQProjection(t *testing.T) {
|
|||
_ = store.Set("ci", "api_key", "sk_42")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: "{token}"}
|
||||
// jq projects from the envelope; .data | {token} extracts from the data object inside envelope.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data | {token}"}
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), fopts); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
|
|
@ -124,7 +129,7 @@ func TestAuthToken_NoCurrentContext(t *testing.T) {
|
|||
cfg := &config.Config{}
|
||||
store := secrets.NewMemStore()
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
|
|
@ -133,7 +138,7 @@ func TestAuthToken_NoCurrentContext(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestAuthToken_ContextOverride(t *testing.T) {
|
||||
func TestAuthToken_ProfileOverride(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "prod",
|
||||
Contexts: map[string]config.Context{
|
||||
|
|
@ -146,10 +151,10 @@ func TestAuthToken_ContextOverride(t *testing.T) {
|
|||
_ = store.Set("staging", "api_key", "staging-key")
|
||||
|
||||
f := tokenTestFactory(t, cfg, store)
|
||||
f.ContextOverride = "staging"
|
||||
f.ProfileOverride = "staging"
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if got := out.String(); got != "staging-key" {
|
||||
|
|
@ -167,7 +172,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) {
|
|||
store := secrets.NewMemStore()
|
||||
// no Set - keyring is empty
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
|
||||
if err == nil {
|
||||
t.Fatal("expected auth.unauthenticated, got nil")
|
||||
}
|
||||
|
|
@ -185,7 +190,7 @@ func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
|
|||
}
|
||||
store := secrets.NewMemStore()
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
|
||||
if err == nil {
|
||||
t.Fatal("expected auth.unauthenticated, got nil")
|
||||
}
|
||||
|
|
@ -229,7 +234,7 @@ func makeAPIKeyCfg() (*config.Config, *secrets.MemStore) {
|
|||
func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
|
||||
cfg, store := makeBearerCfg()
|
||||
out, errBuf := iostreams.SetForTest(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "jwt-xyz" {
|
||||
|
|
@ -243,7 +248,7 @@ func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
|
|||
func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
|
||||
cfg, store := makeBearerCfg()
|
||||
out, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "jwt-xyz" {
|
||||
|
|
@ -260,7 +265,7 @@ func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
|
|||
func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
|
||||
cfg, store := makeAPIKeyCfg()
|
||||
out, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "sk_42" {
|
||||
|
|
|
|||
|
|
@ -17,9 +17,7 @@ import (
|
|||
const chunkLong = `Manage and inspect document chunks.
|
||||
|
||||
Chunks are the indexed pieces of a knowledge document (1 doc → many chunks).
|
||||
Use 'chunk list' to enumerate chunks in stored order (RAG admin / debug).
|
||||
For relevance-ranked retrieval, use 'search chunks "<query>" --kb <id>'
|
||||
instead — that runs hybrid vector + keyword scoring across all chunks.`
|
||||
Use 'chunk list' to enumerate chunks in stored order (RAG admin / debug).`
|
||||
|
||||
// NewCmdChunk builds the parent `chunk` command. Called from cli/cmd/root.go.
|
||||
func NewCmdChunk(f *cmdutil.Factory) *cobra.Command {
|
||||
|
|
@ -27,8 +25,6 @@ func NewCmdChunk(f *cmdutil.Factory) *cobra.Command {
|
|||
Use: "chunk <subcommand>",
|
||||
Short: "Manage document chunks (RAG retrieval debug)",
|
||||
Long: chunkLong,
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
}
|
||||
cmd.AddCommand(NewCmdList(f))
|
||||
cmd.AddCommand(NewCmdView(f))
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package chunkcmd
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
|
|
@ -13,7 +13,7 @@ import (
|
|||
)
|
||||
|
||||
// chunkDeleteFields enumerates the JSON discovery fields for `chunk delete`.
|
||||
// Tracks the single-id result struct; multi-id mode emits MultiDeleteResult.
|
||||
// Tracks the single-id result struct; multi-id mode emits batch envelope.
|
||||
var chunkDeleteFields = []string{"id", "deleted"}
|
||||
|
||||
type DeleteOptions struct {
|
||||
|
|
@ -33,20 +33,6 @@ type deleteResult struct {
|
|||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
|
||||
// MultiDeleteResult is the payload for multi-id deletes. All chunks share the
|
||||
// same --doc parent (server route is DELETE /chunks/{doc}/{id}).
|
||||
type MultiDeleteResult struct {
|
||||
OK []string `json:"ok"`
|
||||
Failed []FailedItem `json:"failed,omitempty"`
|
||||
}
|
||||
|
||||
// FailedItem records an id that failed to delete along with its error message.
|
||||
type FailedItem struct {
|
||||
ID string `json:"id"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
const chunkDeleteLong = `Permanently delete one or more chunks from a document.
|
||||
|
||||
Requires both the chunk id(s) (positional, repeatable) and the parent
|
||||
|
|
@ -105,12 +91,20 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
|||
opts.ChunkID = args[0]
|
||||
return runDelete(c.Context(), opts, fopts, cli, f.Prompter())
|
||||
}
|
||||
res, runErr := runMultiDelete(c.Context(), opts, fopts, cli, f.Prompter(), args)
|
||||
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "chunk", len(args), "chunk.delete", "weknora chunk delete "+strings.Join(args, " ")+" --doc "+opts.DocID+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error {
|
||||
if err := cli.DeleteChunk(ctx, opts.DocID, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete chunk %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// Only emit when the operation actually ran. Pre-flight errors
|
||||
// (e.g. confirmation_required) must leave stdout empty per the
|
||||
// wire contract in README.md.
|
||||
if len(res.OK) > 0 || len(res.Failed) > 0 {
|
||||
if emitErr := emitMultiDelete(res, fopts, iostreams.IO.Out); emitErr != nil {
|
||||
if len(outcomes) > 0 {
|
||||
if emitErr := cmdutil.EmitBatch(outcomes, fopts, iostreams.IO.Out, cmdutil.DeletedAtNow); emitErr != nil {
|
||||
return emitErr
|
||||
}
|
||||
}
|
||||
|
|
@ -120,57 +114,31 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
|
|||
cmd.Flags().StringVar(&opts.DocID, "doc", "", "Parent document id (SDK knowledge_id) the chunks live under")
|
||||
_ = cmd.MarkFlagRequired("doc")
|
||||
cmdutil.AddFormatFlag(cmd, chunkDeleteFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "permanently delete one or more chunks from a document",
|
||||
RequiredFlags: []string{"<chunk-id>... (positional, at least one)", "--doc <doc-id>"},
|
||||
Examples: []string{
|
||||
"weknora chunk delete chunk_abc --doc doc_xyz -y",
|
||||
"weknora chunk delete c1 c2 c3 --doc doc_xyz -y",
|
||||
"weknora chunk delete chunk_abc --doc doc_xyz -y --format json",
|
||||
},
|
||||
Warnings: []string{
|
||||
"chunk delete removes a chunk from a doc permanently. Never auto-add -y unless the user explicitly approves the specific chunk id.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "chunk", opts.ChunkID); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "chunk", opts.ChunkID, "chunk.delete", "weknora chunk delete "+opts.ChunkID+" --doc "+opts.DocID+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := svc.DeleteChunk(ctx, opts.DocID, opts.ChunkID); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete chunk %s", opts.ChunkID)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.ChunkID, Deleted: true})
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.ChunkID, Deleted: true}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted chunk %s\n", opts.ChunkID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runMultiDelete iterates chunkIDs sequentially under opts.DocID, keep-going
|
||||
// on error: a single failure does not abort the run.
|
||||
func runMultiDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, chunkIDs []string) (*MultiDeleteResult, error) {
|
||||
if err := cmdutil.ConfirmDestructiveBatch(p, opts.Yes, fopts.WantsJSON(), "chunk", len(chunkIDs)); err != nil {
|
||||
return &MultiDeleteResult{}, err
|
||||
}
|
||||
res := &MultiDeleteResult{}
|
||||
for _, id := range chunkIDs {
|
||||
if err := svc.DeleteChunk(ctx, opts.DocID, id); err != nil {
|
||||
res.Failed = append(res.Failed, FailedItem{ID: id, Message: err.Error()})
|
||||
continue
|
||||
}
|
||||
res.OK = append(res.OK, id)
|
||||
}
|
||||
if len(res.Failed) > 0 {
|
||||
return res, cmdutil.NewError(cmdutil.CodeOperationFailed, fmt.Sprintf("%d/%d delete(s) failed", len(res.Failed), len(chunkIDs)))
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// emitMultiDelete renders per --format. Mirrors doc / session delete.
|
||||
func emitMultiDelete(res *MultiDeleteResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
for _, id := range res.OK {
|
||||
fmt.Fprintf(w, "OK %s\n", id)
|
||||
}
|
||||
for _, f := range res.Failed {
|
||||
fmt.Fprintf(w, "FAIL %s: %s\n", f.ID, f.Message)
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for chunk delete", fopts.Mode)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
package chunkcmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
|
|
@ -74,7 +76,7 @@ func TestDelete_TTY_ConfirmYes_Calls(t *testing.T) {
|
|||
p := &testutil.ConfirmPrompter{Answer: true}
|
||||
require.NoError(t, runDelete(context.Background(),
|
||||
&DeleteOptions{ChunkID: "c1", DocID: "doc_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p))
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p))
|
||||
assert.True(t, p.Asked)
|
||||
assert.Equal(t, "c1", svc.gotChunkID)
|
||||
}
|
||||
|
|
@ -85,7 +87,7 @@ func TestDelete_TTY_ConfirmNo_Aborts(t *testing.T) {
|
|||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runDelete(context.Background(),
|
||||
&DeleteOptions{ChunkID: "c1", DocID: "doc_abc"},
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p)
|
||||
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -129,12 +131,20 @@ func (f *fakeMultiChunkDeleteSvc) DeleteChunk(_ context.Context, docID, chunkID
|
|||
func TestMultiDelete_AllSucceed_SharedDoc(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiChunkDeleteSvc{}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{DocID: "doc_xyz", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"c1", "c2", "c3"})
|
||||
docID := "doc_xyz"
|
||||
outcomes, err := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"c1", "c2", "c3"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteChunk(ctx, docID, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete chunk %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"c1", "c2", "c3"}, res.OK)
|
||||
assert.Empty(t, res.Failed)
|
||||
require.Len(t, outcomes, 3)
|
||||
for _, oc := range outcomes {
|
||||
assert.Nil(t, oc.Err, "expected no error for %s", oc.ID)
|
||||
}
|
||||
// All calls observed the same --doc.
|
||||
for _, d := range svc.docIDs {
|
||||
assert.Equal(t, "doc_xyz", d)
|
||||
|
|
@ -144,29 +154,90 @@ func TestMultiDelete_AllSucceed_SharedDoc(t *testing.T) {
|
|||
func TestMultiDelete_PartialFailure_KeepsGoing(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiChunkDeleteSvc{failOn: map[string]error{"c2": errors.New("HTTP error 404: not found")}}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{DocID: "doc_xyz", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"c1", "c2", "c3"})
|
||||
docID := "doc_xyz"
|
||||
outcomes, err := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"c1", "c2", "c3"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteChunk(ctx, docID, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete chunk %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeOperationFailed, typed.Code)
|
||||
assert.Equal(t, []string{"c1", "c3"}, res.OK, "keep-going: c3 still attempted after c2 failed")
|
||||
assert.Len(t, res.Failed, 1)
|
||||
assert.Equal(t, "c2", res.Failed[0].ID)
|
||||
require.Len(t, outcomes, 3, "all three ids must appear in outcomes (argv order preserved)")
|
||||
assert.Nil(t, outcomes[0].Err, "c1 should succeed")
|
||||
assert.NotNil(t, outcomes[1].Err, "c2 should fail")
|
||||
assert.Nil(t, outcomes[2].Err, "c3 should succeed (keep-going)")
|
||||
assert.Equal(t, "c2", outcomes[1].ID)
|
||||
}
|
||||
|
||||
func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiChunkDeleteSvc{}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{DocID: "doc_xyz"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"c1", "c2"})
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "chunk", 2, "chunk.delete", "")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err))
|
||||
assert.Empty(t, res.OK)
|
||||
assert.Empty(t, svc.deleted)
|
||||
}
|
||||
|
||||
// TestChunkDelete_MultiID_PartialFailure_BatchEnvelope verifies that the JSON
|
||||
// output for a multi-id partial failure uses the §4.5 batch envelope shape:
|
||||
// {ok:false, data:[{id,ok,result?|error?}...], meta:{count,successes,failures}}.
|
||||
func TestChunkDelete_MultiID_PartialFailure_BatchEnvelope(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiChunkDeleteSvc{failOn: map[string]error{
|
||||
"c2": errors.New("HTTP error 404: not found"),
|
||||
}}
|
||||
docID := "doc_xyz"
|
||||
outcomes, runErr := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"c1", "c2", "c3"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteChunk(ctx, docID, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete chunk %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.Error(t, runErr)
|
||||
require.Len(t, outcomes, 3)
|
||||
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &buf, cmdutil.DeletedAtNow))
|
||||
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
OK bool `json:"ok"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
} `json:"data"`
|
||||
Meta struct {
|
||||
Count int `json:"count"`
|
||||
Successes int `json:"successes"`
|
||||
Failures int `json:"failures"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &env), "envelope must be valid JSON")
|
||||
|
||||
assert.False(t, env.OK, "top-level ok must be false when any item failed")
|
||||
assert.Equal(t, 3, env.Meta.Count)
|
||||
assert.Equal(t, 2, env.Meta.Successes)
|
||||
assert.Equal(t, 1, env.Meta.Failures)
|
||||
require.Len(t, env.Data, 3)
|
||||
assert.Equal(t, "c1", env.Data[0].ID)
|
||||
assert.True(t, env.Data[0].OK)
|
||||
assert.Equal(t, "c2", env.Data[1].ID)
|
||||
assert.False(t, env.Data[1].OK)
|
||||
assert.NotNil(t, env.Data[1].Error)
|
||||
assert.Equal(t, "c3", env.Data[2].ID)
|
||||
assert.True(t, env.Data[2].OK)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,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"
|
||||
)
|
||||
|
|
@ -121,6 +122,7 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
|||
}
|
||||
|
||||
var items []sdk.Chunk
|
||||
truncated := false
|
||||
if opts.AllPages {
|
||||
accum := make([]sdk.Chunk, 0)
|
||||
for page := 1; ; page++ {
|
||||
|
|
@ -131,6 +133,7 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
|||
accum = append(accum, chunks...)
|
||||
if len(accum) >= opts.Limit {
|
||||
accum = accum[:opts.Limit]
|
||||
truncated = true
|
||||
break
|
||||
}
|
||||
if len(chunks) == 0 || int64(len(accum)) >= total {
|
||||
|
|
@ -150,10 +153,12 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
|||
}
|
||||
if 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 {
|
||||
|
|
|
|||
|
|
@ -117,8 +117,12 @@ func TestList_AllPages_LimitTruncatesAccumulated(t *testing.T) {
|
|||
// After page 2: accum=4 >= limit=3 → stop. Third page never requested.
|
||||
assert.LessOrEqual(t, len(svc.calls), 2, "must not walk past limit-hit point")
|
||||
// Result must be exactly --limit items (server returned 4, sliced to 3).
|
||||
var got []sdk.Chunk
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &got))
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Chunk `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
|
||||
got := env.Data
|
||||
assert.Len(t, got, 3, "accumulated must be sliced to exactly --limit")
|
||||
// IDs preserve order: first 3 from the first 2 pages.
|
||||
assert.Equal(t, []string{"c1", "c2", "c3"}, []string{got[0].ID, got[1].ID, got[2].ID})
|
||||
|
|
@ -158,7 +162,7 @@ func TestList_Human_TableHeader(t *testing.T) {
|
|||
}},
|
||||
totals: []int64{1}, errs: []error{nil},
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
body := out.String()
|
||||
for _, want := range []string{"CHUNK_ID", "INDEX", "TYPE", "ENABLED", "PREVIEW", "UPDATED", "c1", "text"} {
|
||||
assert.Contains(t, body, want)
|
||||
|
|
@ -172,7 +176,7 @@ func TestList_Human_PreviewTruncatedTo80(t *testing.T) {
|
|||
pages: [][]sdk.Chunk{{{ID: "c1", Content: long, ChunkType: "text", IsEnabled: true}}},
|
||||
totals: []int64{1}, errs: []error{nil},
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
body := out.String()
|
||||
// 80-col preview means we never see the 100th `a` from the content (only column truncation kicks in).
|
||||
assert.NotContains(t, body, strings.Repeat("a", 100), "preview must be truncated to ~80 chars")
|
||||
|
|
@ -187,12 +191,16 @@ func TestList_JSON_BareArray(t *testing.T) {
|
|||
totals: []int64{1}, errs: []error{nil},
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
var got []sdk.Chunk
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &got))
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Chunk `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
|
||||
got := env.Data
|
||||
require.Len(t, got, 1)
|
||||
assert.Equal(t, "doc_abc", got[0].KnowledgeID)
|
||||
assert.Equal(t, "kb_x", got[0].KnowledgeBaseID)
|
||||
// Bare SDK keys, not custom CLI envelope.
|
||||
// SDK snake_case keys must be present.
|
||||
assert.Contains(t, out.String(), `"knowledge_id":"doc_abc"`)
|
||||
assert.NotContains(t, out.String(), `"doc_id"`)
|
||||
}
|
||||
|
|
@ -201,5 +209,11 @@ func TestList_EmptyResultRendersBareArray(t *testing.T) {
|
|||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{pages: [][]sdk.Chunk{{}}, totals: []int64{0}, errs: []error{nil}}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "[]\n", out.String())
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.Chunk `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
|
||||
assert.True(t, env.OK)
|
||||
assert.Len(t, env.Data, 0, "expected empty data array")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
|
|||
return cmdutil.WrapHTTP(err, "fetch chunk %s", opts.ChunkID)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, ch)
|
||||
return fopts.Emit(iostreams.IO.Out, ch, nil)
|
||||
}
|
||||
renderChunk(iostreams.IO.Out, ch)
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ func TestView_Happy_RendersAllFields(t *testing.T) {
|
|||
CreatedAt: "2026-05-15T11:00:00Z",
|
||||
UpdatedAt: "2026-05-15T12:00:00Z",
|
||||
}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, "c1")
|
||||
assert.Contains(t, body, "doc_abc")
|
||||
|
|
@ -51,7 +51,7 @@ func TestView_HumanLabels_DocAndKB(t *testing.T) {
|
|||
svc := &fakeViewSvc{resp: &sdk.Chunk{
|
||||
ID: "c1", KnowledgeID: "doc_abc", KnowledgeBaseID: "kb_abc",
|
||||
}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
body := out.String()
|
||||
// Human KV uses friendlier DOC_ID / KB_ID labels (the SDK's
|
||||
// knowledge_id / knowledge_base_id are kept only in --format json output).
|
||||
|
|
@ -64,7 +64,7 @@ func TestView_HumanLabels_DocAndKB(t *testing.T) {
|
|||
func TestView_OmitsZeroOrEmpty(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{resp: &sdk.Chunk{ID: "c_min", Content: "x"}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c_min"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c_min"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
body := out.String()
|
||||
// status / start_at / end_at all zero → must be omitted from the human KV.
|
||||
assert.NotContains(t, body, "status:")
|
||||
|
|
@ -81,8 +81,12 @@ func TestView_JSON_BareSDKShape(t *testing.T) {
|
|||
ID: "c_json", KnowledgeID: "doc_abc", KnowledgeBaseID: "kb_abc",
|
||||
}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c_json"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
var got sdk.Chunk
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &got))
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data sdk.Chunk `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
|
||||
got := env.Data
|
||||
assert.Equal(t, "c_json", got.ID)
|
||||
assert.Equal(t, "doc_abc", got.KnowledgeID)
|
||||
// JSON uses SDK snake_case keys (knowledge_id), not human relabel doc_id.
|
||||
|
|
@ -95,7 +99,7 @@ func TestView_JSON_BareSDKShape(t *testing.T) {
|
|||
func TestView_404(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runView(context.Background(), &ViewOptions{ChunkID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runView(context.Background(), &ViewOptions{ChunkID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "resource.not_found")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -334,7 +334,7 @@ func summarize(cs []Check) Summary {
|
|||
// code, set by the caller).
|
||||
func emit(fopts *cmdutil.FormatOptions, r Result) {
|
||||
if fopts.WantsJSON() {
|
||||
_ = fopts.Emit(iostreams.IO.Out, r)
|
||||
_ = fopts.Emit(iostreams.IO.Out, r, nil)
|
||||
return
|
||||
}
|
||||
for _, c := range r.Checks {
|
||||
|
|
|
|||
|
|
@ -279,13 +279,12 @@ func TestDoctor_VersionSkewWarns(t *testing.T) {
|
|||
t.Error("AllPassed must be false when any check is warn")
|
||||
}
|
||||
|
||||
// Wire shape: warn-only run still has summary.failed=0 (bare data
|
||||
// carries the signal; exit code stays 0).
|
||||
// Wire shape: warn-only run has envelope wrapper with ok:true.
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
emit(&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, r)
|
||||
body := out.String()
|
||||
if strings.Contains(body, `"ok":`) {
|
||||
t.Errorf("bare doctor output must not carry envelope keys, got %q", body)
|
||||
if !strings.Contains(body, `"ok":true`) {
|
||||
t.Errorf("doctor output must carry envelope ok:true, got %q", body)
|
||||
}
|
||||
if !strings.Contains(body, `"failed":0`) {
|
||||
t.Errorf("bare output must carry failed:0 on warn-only run, got %q", body)
|
||||
|
|
@ -392,8 +391,9 @@ func TestDoctor_BareJSON_WarnDoesNotSignalFail(t *testing.T) {
|
|||
if !strings.Contains(got, `"failed":0`) {
|
||||
t.Errorf("warn-only result must have summary.failed=0 (exit-0 signal), got %q", got)
|
||||
}
|
||||
if strings.Contains(got, `"ok":`) {
|
||||
t.Errorf("bare output must not carry envelope keys, got %q", got)
|
||||
// v0.7 envelope: ok:true is expected
|
||||
if !strings.Contains(got, `"ok":true`) {
|
||||
t.Errorf("output must carry envelope ok:true, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -428,7 +428,7 @@ func TestDoctor_HumanMarker_Warn(t *testing.T) {
|
|||
{Name: "server_version", Status: StatusWarn, Details: "older"},
|
||||
},
|
||||
}
|
||||
emit(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, r)
|
||||
emit(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, r)
|
||||
got := out.String()
|
||||
if !strings.Contains(got, "⚠") {
|
||||
t.Errorf("human output should contain ⚠ glyph for warn, got %q", got)
|
||||
|
|
@ -479,6 +479,10 @@ func TestDoctor_RunE_FailReturnsSilentError(t *testing.T) {
|
|||
cmd := NewCmd(f)
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
// --format is persistent at root in v0.7; register locally for the
|
||||
// isolated leaf-execution test path.
|
||||
cmd.PersistentFlags().String("format", "", "")
|
||||
cmd.PersistentFlags().String("jq", "", "")
|
||||
cmd.SetArgs([]string{"--format", "json"})
|
||||
cmd.SetContext(context.Background())
|
||||
err := cmd.Execute()
|
||||
|
|
|
|||
|
|
@ -124,8 +124,8 @@ func aggregateFailedCount(ctx context.Context, svc CheckService, kbID string) (i
|
|||
func emitCheck(res *CheckResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
return writeCheckText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for kb check", fopts.Mode)
|
||||
|
|
|
|||
|
|
@ -95,10 +95,14 @@ func TestEmitCheck_JSON(t *testing.T) {
|
|||
if err := emitCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("emitCheck: %v", err)
|
||||
}
|
||||
var got CheckResult
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data CheckResult `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 got.ID != "kb_x" || got.KnowledgeCount != 5 || got.FailedCount != 3 {
|
||||
t.Errorf("got %+v", got)
|
||||
}
|
||||
|
|
@ -112,7 +116,7 @@ func TestEmitCheck_TextHuman(t *testing.T) {
|
|||
IsProcessing: true, ProcessingCount: 1,
|
||||
FailedCount: 2,
|
||||
}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
if err := emitCheck(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("emitCheck: %v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
|
|||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, created)
|
||||
return fopts.Emit(iostreams.IO.Out, created, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package kb
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
|
@ -39,7 +40,7 @@ func TestCreate_Success_Human(t *testing.T) {
|
|||
Description: "team docs",
|
||||
EmbeddingModel: "model_x",
|
||||
}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
|
||||
// Body sent to SDK matches flags.
|
||||
require.NotNil(t, svc.got)
|
||||
|
|
@ -59,7 +60,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
|
|||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_x", Name: "n"}}
|
||||
opts := &CreateOptions{Name: "n"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
|
||||
require.NotNil(t, svc.got)
|
||||
assert.Equal(t, "", svc.got.EmbeddingModelID, "embedding-model unset ⇒ empty in request")
|
||||
|
|
@ -68,7 +69,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
|
|||
func TestCreate_NameRequired(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -80,7 +81,7 @@ func TestCreate_NameRequired(t *testing.T) {
|
|||
func TestCreate_NameWhitespaceOnly(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -91,7 +92,7 @@ func TestCreate_NameWhitespaceOnly(t *testing.T) {
|
|||
func TestCreate_HTTPError_500(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal")}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -102,7 +103,7 @@ func TestCreate_HTTPError_500(t *testing.T) {
|
|||
func TestCreate_HTTPError_409Conflict(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{err: errors.New("HTTP error 409: name exists")}
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -117,16 +118,21 @@ func TestCreate_JSONOutput(t *testing.T) {
|
|||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb_99"`), "expected bare KnowledgeBase object; got %q", got)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data sdk.KnowledgeBase `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.Equal(t, "kb_99", env.Data.ID, "envelope.data.id must be kb_99")
|
||||
assert.Contains(t, got, `"name":"Eng"`)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
}
|
||||
|
||||
func TestCreate_StorageProvider_InjectsRequest(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_s", Name: "n"}}
|
||||
opts := &CreateOptions{Name: "n", StorageProvider: "Local"}
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
|
||||
require.NotNil(t, svc.got.StorageProviderConfig)
|
||||
assert.Equal(t, "local", svc.got.StorageProviderConfig.Provider, "value should be lowercased + trimmed before send")
|
||||
|
|
@ -136,7 +142,7 @@ func TestCreate_StorageProvider_InvalidValueReturnsFlagError(t *testing.T) {
|
|||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{}
|
||||
opts := &CreateOptions{Name: "n", StorageProvider: "azure"}
|
||||
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
|
||||
assert.Equal(t, 2, cmdutil.ExitCode(err), "invalid --storage-provider must exit 2 (flag validation)")
|
||||
|
|
@ -148,7 +154,7 @@ func TestCreate_StorageProvider_OmittedWhenEmpty(t *testing.T) {
|
|||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_n", Name: "n"}}
|
||||
opts := &CreateOptions{Name: "n"} // no --storage-provider
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
|
||||
assert.Nil(t, svc.got.StorageProviderConfig, "empty flag must omit StorageProviderConfig (let server pick default)")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,11 +67,22 @@ exactly to guard against unintended deletes.`,
|
|||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, kbDeleteFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "permanently delete a knowledge base and all its contents",
|
||||
RequiredFlags: []string{"<kb-id> (positional)"},
|
||||
Examples: []string{
|
||||
"weknora kb delete kb_abc -y",
|
||||
"weknora kb delete kb_abc -y --format json",
|
||||
},
|
||||
Warnings: []string{
|
||||
"kb delete is irreversible; whole KB + docs + chunks gone. Never auto-add -y; surface the exit-10 prompt to the user and only retry after explicit approval.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "knowledge base", id); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "knowledge base", id, "kb.delete", "weknora kb delete "+id+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
|
@ -80,7 +91,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOp
|
|||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted knowledge base %s\n", id)
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ package kb
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
|
@ -33,7 +33,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
|
|||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: true}
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_force"))
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_force"))
|
||||
|
||||
assert.True(t, svc.called)
|
||||
assert.Equal(t, "kb_force", svc.gotID)
|
||||
|
|
@ -46,7 +46,7 @@ func TestDelete_NotFound(t *testing.T) {
|
|||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_missing")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_missing")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -61,7 +61,7 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
|||
iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_nontty")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_nontty")
|
||||
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -80,9 +80,14 @@ func TestDelete_JSONOutput(t *testing.T) {
|
|||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, p, "kb_json"))
|
||||
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb_json"`), "expected bare object; got %q", got)
|
||||
assert.Contains(t, got, `"deleted":true`)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]any `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.Equal(t, "kb_json", env.Data["id"], "envelope.data.id must be kb_json")
|
||||
assert.Equal(t, true, env.Data["deleted"], "envelope.data.deleted must be true")
|
||||
}
|
||||
|
||||
// The remaining tests cover the interactive confirm path which only fires
|
||||
|
|
@ -92,7 +97,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
|
|||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: true}
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_yes"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_yes"))
|
||||
|
||||
assert.True(t, p.Asked, "confirm prompt should fire on TTY without --force")
|
||||
assert.True(t, svc.called, "answer=yes ⇒ delete proceeds")
|
||||
|
|
@ -103,7 +108,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
|
|||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_no")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_no")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -118,7 +123,7 @@ func TestDelete_ConfirmPrompterError(t *testing.T) {
|
|||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Err: prompt.ErrAgentNoPrompt}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_err")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_err")
|
||||
require.Error(t, err)
|
||||
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -159,3 +164,26 @@ func TestDelete_JSONOut_WithYes_Proceeds(t *testing.T) {
|
|||
assert.True(t, svc.called)
|
||||
assert.Contains(t, out.String(), `"deleted":true`)
|
||||
}
|
||||
|
||||
func TestKbDelete_NoYes_JSONMode_AttachesRiskAndRetry(t *testing.T) {
|
||||
// Non-TTY + JSON mode without -y must return CodeInputConfirmationRequired
|
||||
// with risk.action == "kb.delete" and retry_command == "weknora kb delete kb_x -y".
|
||||
// Regression test for H1: ConfirmDestructive must attach risk + retry_command.
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
opts := &DeleteOptions{Yes: false}
|
||||
|
||||
err := runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, p, "kb_x")
|
||||
|
||||
require.Error(t, err, "expected confirmation_required error")
|
||||
ce := cmdutil.AsError(err)
|
||||
require.NotNil(t, ce, "expected *cmdutil.Error; got %T %v", err, err)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
|
||||
assert.False(t, svc.called, "SDK must not be called without confirmation")
|
||||
assert.False(t, p.Asked, "--format json must not prompt even on test setup")
|
||||
require.NotNil(t, ce.Risk, "expected risk metadata on confirmation_required error")
|
||||
assert.Equal(t, "kb.delete", ce.Risk.Action, "expected risk.action == kb.delete")
|
||||
assert.Equal(t, "destructive", ce.Risk.Level, "expected risk.level == destructive")
|
||||
assert.Equal(t, "weknora kb delete kb_x -y", ce.RetryCommand, "expected retry_command")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,10 @@ package kb
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
|
|
@ -31,6 +33,7 @@ type EditOptions struct {
|
|||
// clear the description.
|
||||
Name *string
|
||||
Description *string
|
||||
Yes bool // sourced from global -y/--yes persistent flag
|
||||
}
|
||||
|
||||
// EditService is the narrow SDK surface this command depends on. GetKnowledgeBase
|
||||
|
|
@ -53,7 +56,11 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
|||
Short: "Edit a knowledge base's name or description",
|
||||
Long: `Update a knowledge base's name and/or description. At least one of
|
||||
--name / --description must be supplied; fields you omit are preserved
|
||||
server-side.`,
|
||||
server-side.
|
||||
|
||||
AI agents: this is a high-risk write. Without -y/--yes the CLI exits 10
|
||||
with input.confirmation_required. Never auto-pass -y; surface the prompt
|
||||
to the user first.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
|
|
@ -61,6 +68,7 @@ server-side.`,
|
|||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
if c.Flag("name").Changed {
|
||||
opts.Name = &name
|
||||
}
|
||||
|
|
@ -71,15 +79,52 @@ server-side.`,
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runEdit(c.Context(), opts, fopts, cli, args[0])
|
||||
id := args[0]
|
||||
// Build a retry command from the flags the user actually passed so
|
||||
// agents can re-invoke with -y after explicit human approval.
|
||||
retryCmd := buildKBEditRetryCmd(c, id)
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "knowledge base", id, "kb.edit", retryCmd); err != nil {
|
||||
return err
|
||||
}
|
||||
return runEdit(c.Context(), opts, fopts, cli, id)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&name, "name", "", "New name (omit to leave unchanged)")
|
||||
cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)")
|
||||
cmdutil.AddFormatFlag(cmd, kbEditFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "update a knowledge base's name or description",
|
||||
RequiredFlags: []string{"<kb-id> (positional)", "--name or --description (at least one)"},
|
||||
Examples: []string{
|
||||
"weknora kb edit kb_abc --name \"New Name\" -y",
|
||||
"weknora kb edit kb_abc --description \"Updated desc\" --format json -y",
|
||||
},
|
||||
Warnings: []string{
|
||||
"kb edit can change KB ownership / model config. Surface the exit-10 prompt to the user — only proceed after explicit approval.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
// buildKBEditRetryCmd constructs a directly-executable retry argv from the
|
||||
// flags the user actually set so agents can surface a precise re-run command.
|
||||
func buildKBEditRetryCmd(c *cobra.Command, id string) string {
|
||||
var parts []string
|
||||
parts = append(parts, "weknora", "kb", "edit", id)
|
||||
c.Flags().Visit(func(f *pflag.Flag) {
|
||||
switch f.Name {
|
||||
case "name":
|
||||
parts = append(parts, "--name", f.Value.String())
|
||||
case "description":
|
||||
parts = append(parts, "--description", f.Value.String())
|
||||
case "format":
|
||||
parts = append(parts, "--format", f.Value.String())
|
||||
}
|
||||
})
|
||||
parts = append(parts, "-y")
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOptions, svc EditService, id string) error {
|
||||
if opts.Name == nil && opts.Description == nil {
|
||||
return &cmdutil.Error{
|
||||
|
|
@ -112,7 +157,7 @@ func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOption
|
|||
return cmdutil.WrapHTTP(err, "edit knowledge base %s", id)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, updated)
|
||||
return fopts.Emit(iostreams.IO.Out, updated, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Updated knowledge base %s\n", id)
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -5,11 +5,13 @@ import (
|
|||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
|
|
@ -43,7 +45,7 @@ func (f *fakeEditSvc) UpdateKnowledgeBase(_ context.Context, id string, req *sdk
|
|||
func TestEdit_RequiresAtLeastOneFlag(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{}
|
||||
err := runEdit(context.Background(), &EditOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc")
|
||||
err := runEdit(context.Background(), &EditOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -64,7 +66,7 @@ func TestEdit_OnlyName_PreservesCurrentDescription(t *testing.T) {
|
|||
}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("new")
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
|
||||
|
||||
assert.Equal(t, "kb_abc", svc.gotID)
|
||||
require.NotNil(t, svc.gotReq)
|
||||
|
|
@ -83,7 +85,7 @@ func TestEdit_OnlyDescription_PreservesCurrentName(t *testing.T) {
|
|||
}
|
||||
opts := &EditOptions{}
|
||||
opts.Description = stringPtr("new desc")
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
|
||||
|
||||
require.NotNil(t, svc.gotReq)
|
||||
assert.Equal(t, "new desc", svc.gotReq.Description)
|
||||
|
|
@ -96,7 +98,7 @@ func TestEdit_BothFlags(t *testing.T) {
|
|||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("renamed")
|
||||
opts.Description = stringPtr("new desc")
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
|
||||
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
|
||||
assert.Equal(t, "renamed", svc.gotReq.Name)
|
||||
assert.Equal(t, "new desc", svc.gotReq.Description)
|
||||
}
|
||||
|
|
@ -108,7 +110,7 @@ func TestEdit_NotFound(t *testing.T) {
|
|||
svc := &fakeEditSvc{currentErr: errors.New("HTTP error 404: not found")}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("x")
|
||||
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing")
|
||||
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -116,3 +118,48 @@ func TestEdit_NotFound(t *testing.T) {
|
|||
}
|
||||
|
||||
func stringPtr(s string) *string { return &s }
|
||||
|
||||
// withRootHarnessKB wraps `weknora kb edit ...` under a synthetic root cmd
|
||||
// that registers the global persistent flags (mirrors addGlobalFlags in
|
||||
// cmd/root.go). Required because NewCmdEdit reads --yes and --format from the
|
||||
// persistent flag set.
|
||||
func withRootHarnessKB(edit *cobra.Command, args ...string) *cobra.Command {
|
||||
root := &cobra.Command{Use: "weknora"}
|
||||
pf := root.PersistentFlags()
|
||||
pf.BoolP("yes", "y", false, "")
|
||||
pf.String("format", "", "Output format: human | json | ndjson")
|
||||
pf.StringP("jq", "q", "", "")
|
||||
kb := &cobra.Command{Use: "kb"}
|
||||
kb.AddCommand(edit)
|
||||
root.AddCommand(kb)
|
||||
root.SetArgs(append([]string{"kb", "edit"}, args...))
|
||||
root.SetContext(context.Background())
|
||||
root.SilenceErrors = true
|
||||
root.SilenceUsage = true
|
||||
return root
|
||||
}
|
||||
|
||||
// TestKBEdit_RequiresConfirmation asserts that without -y (non-TTY / JSON
|
||||
// mode), kb edit returns input.confirmation_required (exit 10).
|
||||
func TestKBEdit_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t) // non-TTY
|
||||
svc := &fakeEditSvc{
|
||||
current: &sdk.KnowledgeBase{ID: "kb_abc", Name: "old"},
|
||||
resp: &sdk.KnowledgeBase{ID: "kb_abc", Name: "new"},
|
||||
}
|
||||
f := &cmdutil.Factory{
|
||||
Client: func() (*sdk.Client, error) { return nil, nil },
|
||||
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
|
||||
}
|
||||
_ = svc // gate fires before SDK call
|
||||
root := withRootHarnessKB(NewCmdEdit(f), "kb_abc", "--name", "new", "--format", "json")
|
||||
err := root.Execute()
|
||||
require.Error(t, err)
|
||||
var ce *cmdutil.Error
|
||||
require.ErrorAs(t, err, &ce)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err))
|
||||
// retry command must include -y
|
||||
assert.Contains(t, ce.RetryCommand, "-y")
|
||||
assert.Contains(t, ce.RetryCommand, "kb_abc")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,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"
|
||||
)
|
||||
|
|
@ -64,21 +65,21 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
|||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.Pinned, "pinned", false, "Only show pinned knowledge bases")
|
||||
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)")
|
||||
cmdutil.AddFormatFlag(cmd, kbListFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "List knowledge bases in the current tenant. Agents should use --format json to consume a stable {data, total, page, page_size} response.",
|
||||
UsedFor: "List knowledge bases in the current tenant. --format json emits the v0.7 envelope {ok, data:[...], meta:{count}, profile}.",
|
||||
Examples: []string{"weknora kb list --format json"},
|
||||
Output: "array of KnowledgeBase objects with id, name, is_pinned, type, embedding_model_id",
|
||||
Output: "envelope.data is an array of KnowledgeBase objects with id, name, is_pinned, type, embedding_model_id",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
|
||||
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),
|
||||
}
|
||||
}
|
||||
items, err := svc.ListKnowledgeBases(ctx)
|
||||
|
|
@ -104,12 +105,16 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
|||
return items[i].UpdatedAt.After(items[j].UpdatedAt)
|
||||
})
|
||||
// --limit applies after sort so the cap returns the top-N most-recent.
|
||||
// The KB list SDK is unpaginated, so client-side truncation does not
|
||||
// imply server-side has_more — there is no cursor to continue with.
|
||||
// has_more is omitted; callers needing all KBs should raise --limit.
|
||||
if opts.Limit > 0 && len(items) > opts.Limit {
|
||||
items = items[:opts.Limit]
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, items)
|
||||
meta := &output.Meta{Count: len(items)}
|
||||
return fopts.Emit(iostreams.IO.Out, items, meta)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ func (f *fakeListSvc) ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBa
|
|||
|
||||
func TestList_Empty_Human(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no knowledge bases)") {
|
||||
|
|
@ -36,12 +36,21 @@ func TestList_Empty_Human(t *testing.T) {
|
|||
func TestList_Empty_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := strings.TrimSpace(out.String())
|
||||
if got != "[]" {
|
||||
t.Errorf("empty JSON should be bare `[]`, got %q", got)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []sdk.KnowledgeBase `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, out.String())
|
||||
}
|
||||
if !env.OK {
|
||||
t.Error("envelope.ok must be true")
|
||||
}
|
||||
if len(env.Data) != 0 {
|
||||
t.Errorf("expected empty data, got %d items", len(env.Data))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -52,7 +61,7 @@ func TestList_NonEmpty_Human_RenderColumns(t *testing.T) {
|
|||
{ID: "kb1", Name: "Marketing", KnowledgeCount: 5, UpdatedAt: now.Add(-3 * time.Hour)},
|
||||
{ID: "kb2", Name: "Engineering", KnowledgeCount: 1, UpdatedAt: now.Add(-2 * 24 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -69,9 +78,9 @@ func TestList_JSON_JQProjection(t *testing.T) {
|
|||
items := []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "Marketing", Description: "MKT desc", UpdatedAt: now},
|
||||
}
|
||||
// --jq is the canonical projection mechanism in v0.6+.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".[] | {id, name}"}
|
||||
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
// --jq projects from the envelope; .data[] | ... extracts from the array inside envelope.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data[] | {id, name}"}
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
var item map[string]any
|
||||
|
|
@ -93,8 +102,9 @@ func TestList_JSON_JQ(t *testing.T) {
|
|||
{ID: "kb1", Name: "Marketing", UpdatedAt: now},
|
||||
{ID: "kb2", Name: "Engineering", UpdatedAt: now.Add(-time.Hour)},
|
||||
}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ". | length"}
|
||||
if err := runList(context.Background(), &ListOptions{}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
// .data | length counts the items inside the envelope's data array.
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data | length"}
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(out.String()); got != "2" {
|
||||
|
|
@ -110,7 +120,7 @@ func TestList_PinnedFilter(t *testing.T) {
|
|||
{ID: "kb2", Name: "Engineering", IsPinned: false, UpdatedAt: now.Add(-time.Hour)},
|
||||
{ID: "kb3", Name: "Finance", IsPinned: true, UpdatedAt: now.Add(-2 * time.Hour)},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{Pinned: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -127,7 +137,7 @@ func TestList_PinnedFilter_NoPinned_HumanMessage(t *testing.T) {
|
|||
items := []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "Marketing", IsPinned: false, UpdatedAt: time.Now()},
|
||||
}
|
||||
if err := runList(context.Background(), &ListOptions{Pinned: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
|
||||
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "(no pinned knowledge bases)") {
|
||||
|
|
@ -162,22 +172,26 @@ func TestList_Limit_CapsResults(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestList_Limit_Zero_NoCap(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
func TestList_Limit_Zero_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListSvc{items: makeKBs(7)}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
if err := runList(context.Background(), &ListOptions{Limit: 0}, fopts, svc); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
err := runList(context.Background(), &ListOptions{Limit: 0}, fopts, svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for --limit 0")
|
||||
}
|
||||
got := strings.Count(out.String(), `"id":"kb_`)
|
||||
if got != 7 {
|
||||
t.Errorf("--limit 0 must not cap; got %d, want 7", got)
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T: %v", err, err)
|
||||
}
|
||||
if typed.Code != cmdutil.CodeInputInvalidArgument {
|
||||
t.Errorf("expected CodeInputInvalidArgument, got %v", typed.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeKBs(3)})
|
||||
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: makeKBs(3)})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for negative --limit")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ func runPin(ctx context.Context, opts *PinOptions, fopts *cmdutil.FormatOptions,
|
|||
// both fresh-toggle and no-op paths. Human path prints a confirming
|
||||
// line; agents observe via the unchanged is_pinned field.
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, current)
|
||||
return fopts.Emit(iostreams.IO.Out, current, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ %s is already %s\n", id, state)
|
||||
return nil
|
||||
|
|
@ -90,7 +90,7 @@ func runPin(ctx context.Context, opts *PinOptions, fopts *cmdutil.FormatOptions,
|
|||
return cmdutil.WrapHTTP(err, "%s knowledge base %s", verb, id)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, updated)
|
||||
return fopts.Emit(iostreams.IO.Out, updated, nil)
|
||||
}
|
||||
state := "pinned"
|
||||
if !updated.IsPinned {
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ func (f *fakePinSvc) TogglePinKnowledgeBase(_ context.Context, id string) (*sdk.
|
|||
func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true))
|
||||
assert.True(t, svc.toggleCalled, "must call toggle when current state differs")
|
||||
assert.Contains(t, out.String(), "kb_abc")
|
||||
}
|
||||
|
|
@ -52,7 +52,7 @@ func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
|
|||
func TestPin_AlreadyPinned_NoOp(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true))
|
||||
assert.False(t, svc.toggleCalled, "already pinned ⇒ must not call toggle")
|
||||
assert.Contains(t, out.String(), "already pinned")
|
||||
}
|
||||
|
|
@ -60,14 +60,14 @@ func TestPin_AlreadyPinned_NoOp(t *testing.T) {
|
|||
func TestUnpin_PinnedToUnpinned_CallsToggle(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", false))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", false))
|
||||
assert.True(t, svc.toggleCalled)
|
||||
}
|
||||
|
||||
func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", false))
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", false))
|
||||
assert.False(t, svc.toggleCalled, "already unpinned ⇒ must not call toggle")
|
||||
assert.Contains(t, out.String(), "already unpinned")
|
||||
}
|
||||
|
|
@ -75,7 +75,7 @@ func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
|
|||
func TestPin_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{getErr: errors.New("HTTP error 404: not found")}
|
||||
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing", true)
|
||||
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_missing", true)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -89,7 +89,7 @@ func TestPin_ToggleError(t *testing.T) {
|
|||
current: sdk.KnowledgeBase{IsPinned: false},
|
||||
toggleErr: errors.New("HTTP error 500: internal"),
|
||||
}
|
||||
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true)
|
||||
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
|
|||
|
|
@ -95,8 +95,8 @@ func runStatus(ctx context.Context, svc StatusService, id string) (*StatusResult
|
|||
func emitStatus(res *StatusResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
return fopts.Emit(w, res, nil)
|
||||
case cmdutil.FormatHuman, "":
|
||||
return writeStatusText(w, res)
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for kb status", fopts.Mode)
|
||||
|
|
|
|||
|
|
@ -65,10 +65,14 @@ func TestEmitStatus_JSON(t *testing.T) {
|
|||
if err := emitStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("emitStatus: %v", err)
|
||||
}
|
||||
var got StatusResult
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data StatusResult `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 got.ID != "kb_x" || got.KnowledgeCount != 5 {
|
||||
t.Errorf("got %+v", got)
|
||||
}
|
||||
|
|
@ -77,7 +81,7 @@ func TestEmitStatus_JSON(t *testing.T) {
|
|||
func TestEmitStatus_TextHuman(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
res := &StatusResult{ID: "kb_x", Reachable: true, KnowledgeCount: 5, ChunkCount: 20, IsProcessing: true, ProcessingCount: 1}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
if err := emitStatus(res, fopts, &buf); err != nil {
|
||||
t.Fatalf("emitStatus: %v", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
|
|||
return cmdutil.WrapHTTP(err, "get knowledge base %q", id)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, kb)
|
||||
return fopts.Emit(iostreams.IO.Out, kb, nil)
|
||||
}
|
||||
// Human: KEY: VALUE. Nested config structs (chunking_config, vlm_config,
|
||||
// etc.) are intentionally omitted from the human render — those are for
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package kb
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
|
@ -26,7 +27,7 @@ func TestGet_OK_Human(t *testing.T) {
|
|||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{
|
||||
ID: "kb1", Name: "Marketing", KnowledgeCount: 12, ChunkCount: 245,
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runGet: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -44,18 +45,25 @@ func TestGet_OK_JSON(t *testing.T) {
|
|||
t.Fatalf("runGet: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
if !strings.HasPrefix(strings.TrimSpace(got), `{"id":"kb1"`) {
|
||||
t.Errorf("expected bare object starting with id, got %q", got)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data sdk.KnowledgeBase `json:"data"`
|
||||
}
|
||||
if strings.Contains(got, `"ok":true`) {
|
||||
t.Errorf("bare output must not carry envelope keys, got %q", got)
|
||||
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)
|
||||
}
|
||||
if env.Data.ID != "kb1" {
|
||||
t.Errorf("expected id=kb1 in envelope.data, got %q", env.Data.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGet_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{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")
|
||||
}
|
||||
|
|
@ -69,7 +77,7 @@ func TestGet_NotFound(t *testing.T) {
|
|||
func TestView_Pinned_RendersPinnedLine(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Pinned", IsPinned: true}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "PINNED:") {
|
||||
|
|
@ -80,7 +88,7 @@ func TestView_Pinned_RendersPinnedLine(t *testing.T) {
|
|||
func TestView_NotPinned_OmitsPinnedLine(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Plain", IsPinned: false}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
for _, l := range strings.Split(out.String(), "\n") {
|
||||
|
|
@ -93,7 +101,7 @@ func TestView_NotPinned_OmitsPinnedLine(t *testing.T) {
|
|||
func TestView_Temporary_RendersTempLine(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_t", Name: "Tmp", IsTemporary: true}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_t"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_t"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "TEMPORARY:") {
|
||||
|
|
@ -104,7 +112,7 @@ func TestView_Temporary_RendersTempLine(t *testing.T) {
|
|||
func TestView_SummaryModel(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "X", SummaryModelID: "summary-model-x"}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -116,7 +124,7 @@ func TestView_SummaryModel(t *testing.T) {
|
|||
func TestView_TypeAndSource(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "X", Type: "general", Description: "d"}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -128,7 +136,7 @@ func TestView_TypeAndSource(t *testing.T) {
|
|||
func TestView_Processing(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_p", Name: "Busy", IsProcessing: true, ProcessingCount: 3}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_p"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_p"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
@ -140,7 +148,7 @@ func TestView_Processing(t *testing.T) {
|
|||
func TestView_NotProcessing_OmitsProcessingLine(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_idle", Name: "Idle", IsProcessing: false}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_idle"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_idle"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
for _, l := range strings.Split(out.String(), "\n") {
|
||||
|
|
@ -157,7 +165,7 @@ func TestView_CreatedAt_AlwaysRendered(t *testing.T) {
|
|||
CreatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
UpdatedAt: time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC),
|
||||
}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
|
|
@ -145,7 +146,8 @@ func runChunks(ctx context.Context, opts *ChunksOptions, fopts *cmdutil.FormatOp
|
|||
if results == nil {
|
||||
results = []*sdk.SearchResult{}
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, results)
|
||||
meta := &output.Meta{Count: len(results)}
|
||||
return fopts.Emit(iostreams.IO.Out, results, meta)
|
||||
}
|
||||
return renderChunkResults(results, opts.KBID)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ package search
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
|
@ -34,7 +34,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
|
|||
{Score: 0.81, Content: "second chunk", KnowledgeID: "doc-2", MatchType: sdk.MatchTypeKeyword},
|
||||
}}
|
||||
opts := &ChunksOptions{Query: "hello", KBID: "kb_abc", Limit: 5}
|
||||
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
|
||||
assert.Equal(t, "kb_abc", svc.gotKB)
|
||||
assert.Equal(t, "hello", svc.gotQ)
|
||||
|
|
@ -62,15 +62,19 @@ func TestRunSearch_JSONOutput(t *testing.T) {
|
|||
opts := &ChunksOptions{Query: "q", KBID: "kb1", Limit: 1}
|
||||
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), "["), "expected bare JSON array, got: %q", got)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []*sdk.SearchResult `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, `"score":0.9`)
|
||||
}
|
||||
|
||||
func TestRunSearch_EmptyResults(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{results: nil}
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "(no results)")
|
||||
}
|
||||
|
||||
|
|
@ -86,7 +90,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
|
|||
{Score: 0, Content: "enrichment parent"}, // server-padded
|
||||
{Score: 0, Content: "enrichment nearby"}, // server-padded
|
||||
}}
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "3 result(s)")
|
||||
assert.NotContains(t, got, "enrichment parent")
|
||||
|
|
@ -95,7 +99,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
|
|||
|
||||
func TestRunSearch_BothChannelsDisabled(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeChunksSvc{})
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeChunksSvc{})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
|
|
@ -103,7 +107,7 @@ func TestRunSearch_BothChannelsDisabled(t *testing.T) {
|
|||
func TestRunSearch_ServiceError_Transport(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{err: assert.AnError}
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -114,7 +118,7 @@ func TestRunSearch_ServiceError_Transport(t *testing.T) {
|
|||
func TestRunSearch_ServiceError_HTTPNotFound(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeChunksSvc{err: errors.New("HTTP error 404: knowledge base not found")}
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -128,7 +132,7 @@ func TestIndent(t *testing.T) {
|
|||
|
||||
func TestRunSearch_NilService(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil)
|
||||
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "server.error")
|
||||
}
|
||||
|
|
@ -164,7 +168,7 @@ func TestRunSearch_NoVectorPassedThrough(t *testing.T) {
|
|||
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
|
||||
Query: "q", KBID: "kb1", NoVector: true,
|
||||
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NotNil(t, got)
|
||||
assert.True(t, got.DisableVectorMatch)
|
||||
assert.False(t, got.DisableKeywordsMatch)
|
||||
|
|
@ -176,7 +180,7 @@ func TestRunSearch_NoKeywordPassedThrough(t *testing.T) {
|
|||
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
|
||||
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
|
||||
Query: "q", KBID: "kb1", NoKeyword: true,
|
||||
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
require.NotNil(t, got)
|
||||
assert.True(t, got.DisableKeywordsMatch)
|
||||
assert.False(t, got.DisableVectorMatch)
|
||||
|
|
|
|||
|
|
@ -11,6 +11,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"
|
||||
)
|
||||
|
|
@ -45,8 +46,8 @@ type DocsSearchOptions struct {
|
|||
// network can shorten the batch.
|
||||
PageSize int
|
||||
// AllPages walks server pages internally until total exhausted or
|
||||
// --limit accumulated. Default true preserves v0.4 behavior; setting
|
||||
// false stops after the first page (useful for cheap previews).
|
||||
// --limit accumulated. Default true; setting false stops after the
|
||||
// first page (useful for cheap previews).
|
||||
AllPages bool
|
||||
}
|
||||
|
||||
|
|
@ -78,8 +79,7 @@ matching, lower-case the query yourself, e.g.
|
|||
fall back to ` + "`weknora api`" + ` with a custom filter.
|
||||
|
||||
By default, --all-pages=true walks every server page until --limit is
|
||||
reached or the KB is exhausted (matching v0.4 behavior). Pass
|
||||
--all-pages=false to stop after one page.`,
|
||||
reached or the KB is exhausted. Pass --all-pages=false to stop after one page.`,
|
||||
Example: ` weknora search docs "Q3 forecast" --kb finance
|
||||
weknora search docs "spec" --kb engineering --limit 5
|
||||
weknora search docs "spec" --kb engineering --all-pages=false`,
|
||||
|
|
@ -157,7 +157,8 @@ done:
|
|||
if matches == nil {
|
||||
matches = []sdk.Knowledge{}
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, matches)
|
||||
meta := &output.Meta{Count: len(matches)}
|
||||
return fopts.Emit(iostreams.IO.Out, matches, meta)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ package search
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -48,7 +48,7 @@ func TestDocsSearch_Substring(t *testing.T) {
|
|||
},
|
||||
total: 2,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Equal(t, "q3", svc.lastFilter.Keyword, "query must be threaded as filter.Keyword")
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "d1")
|
||||
|
|
@ -62,7 +62,7 @@ func TestDocsSearch_MatchesFileName(t *testing.T) {
|
|||
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "Untitled", FileName: "report.pdf"}}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "d1")
|
||||
}
|
||||
|
||||
|
|
@ -81,7 +81,7 @@ func TestDocsSearch_PaginatesUntilTotal(t *testing.T) {
|
|||
pages: map[int][]sdk.Knowledge{1: page1, 2: page2},
|
||||
total: int64(docsPageSize) + 1,
|
||||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: docsPageSize + 1, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: docsPageSize + 1, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "found")
|
||||
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when more items reported")
|
||||
}
|
||||
|
|
@ -93,7 +93,7 @@ func TestDocsSearch_StopsAtLimit(t *testing.T) {
|
|||
page1[i] = sdk.Knowledge{ID: "match", Title: "needle"}
|
||||
}
|
||||
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
// Must not request page 2 because limit was hit mid-page.
|
||||
assert.Equal(t, []int{1}, svc.calls)
|
||||
}
|
||||
|
|
@ -106,15 +106,19 @@ func TestDocsSearch_JSON(t *testing.T) {
|
|||
}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "match", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
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":"d1"`)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
}
|
||||
|
||||
func TestDocsSearch_NetworkError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDocsSearchSvc{err: errors.New("HTTP error 404: kb not found")}
|
||||
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -161,7 +165,7 @@ func TestSearchDocs_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
|
|||
func TestSearchDocs_KeywordPassedToFilter(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: {{ID: "d1"}}}, total: 1}
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "my-query", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "my-query", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Equal(t, "my-query", svc.lastFilter.Keyword, "Query must be threaded as filter.Keyword on ListKnowledgeWithFilter")
|
||||
// Other filter fields must be empty - search docs only forwards the keyword.
|
||||
assert.Empty(t, svc.lastFilter.ParseStatus)
|
||||
|
|
|
|||
|
|
@ -11,6 +11,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"
|
||||
)
|
||||
|
|
@ -95,7 +96,8 @@ func runKBSearch(ctx context.Context, opts *KBSearchOptions, fopts *cmdutil.Form
|
|||
if matches == nil {
|
||||
matches = []sdk.KnowledgeBase{}
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, matches)
|
||||
meta := &output.Meta{Count: len(matches)}
|
||||
return fopts.Emit(iostreams.IO.Out, matches, meta)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package search
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
|
@ -30,7 +31,7 @@ func TestKBSearch_Substring(t *testing.T) {
|
|||
{ID: "kb2", Name: "Engineering Docs", KnowledgeCount: 50},
|
||||
{ID: "kb3", Name: "Marketing Q4 Plan", KnowledgeCount: 5},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "kb1")
|
||||
assert.Contains(t, got, "kb3")
|
||||
|
|
@ -42,7 +43,7 @@ func TestKBSearch_CaseInsensitive(t *testing.T) {
|
|||
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "ENGINEERING"},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "kb1")
|
||||
}
|
||||
|
||||
|
|
@ -51,7 +52,7 @@ func TestKBSearch_MatchesDescription(t *testing.T) {
|
|||
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
|
||||
{ID: "kb1", Name: "Engineering", Description: "all marketing docs are here"},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "kb1")
|
||||
}
|
||||
|
||||
|
|
@ -62,7 +63,7 @@ func TestKBSearch_SortByNameLength(t *testing.T) {
|
|||
{ID: "kb_short", Name: "marketing"},
|
||||
{ID: "kb_mid", Name: "marketing 2024"},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
got := out.String()
|
||||
// Order: shortest name first.
|
||||
iShort := strings.Index(got, "kb_short")
|
||||
|
|
@ -78,7 +79,7 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
|
|||
{ID: "a", Name: "match-a"}, {ID: "b", Name: "match-b"},
|
||||
{ID: "c", Name: "match-c"}, {ID: "d", Name: "match-d"},
|
||||
}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
got := out.String()
|
||||
count := 0
|
||||
for _, id := range []string{"a", "b", "c", "d"} {
|
||||
|
|
@ -92,7 +93,7 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
|
|||
func TestKBSearch_NoMatches(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{{Name: "foo"}}}
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "(no matches)")
|
||||
}
|
||||
|
||||
|
|
@ -102,15 +103,19 @@ func TestKBSearch_JSON(t *testing.T) {
|
|||
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
|
||||
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.KnowledgeBase `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":"kb1"`)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
}
|
||||
|
||||
func TestKBSearch_NetworkError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeKBSearchSvc{err: errors.New("HTTP error 401: unauthenticated")}
|
||||
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
|
|||
|
|
@ -24,8 +24,6 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
|
|||
weknora search kb "marketing"
|
||||
weknora search docs "Q3 forecast" --kb finance
|
||||
weknora search sessions "onboarding"`,
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
}
|
||||
|
||||
cmd.AddCommand(NewCmdChunks(f))
|
||||
|
|
|
|||
|
|
@ -12,6 +12,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"
|
||||
)
|
||||
|
|
@ -38,8 +39,8 @@ type SessionsSearchOptions struct {
|
|||
// can fetch everything in one round-trip.
|
||||
PageSize int
|
||||
// AllPages walks server pages internally until total exhausted or
|
||||
// --limit accumulated. Default true preserves v0.4 behavior; setting
|
||||
// false stops after the first page (useful for cheap previews).
|
||||
// --limit accumulated. Default true; setting false stops after the
|
||||
// first page (useful for cheap previews).
|
||||
AllPages bool
|
||||
}
|
||||
|
||||
|
|
@ -61,8 +62,8 @@ func NewCmdSessions(f *cmdutil.Factory) *cobra.Command {
|
|||
title or description contains the query (case-insensitive).
|
||||
|
||||
By default, --all-pages=true walks every server page until --limit is
|
||||
reached or the tenant's sessions are exhausted (matching v0.4 behavior).
|
||||
Pass --all-pages=false to stop after one page.`,
|
||||
reached or the tenant's sessions are exhausted. Pass --all-pages=false
|
||||
to stop after one page.`,
|
||||
Example: ` weknora search sessions "onboarding"
|
||||
weknora search sessions "Q3 review" --limit 3 --format json
|
||||
weknora search sessions "Q3 review" --all-pages=false`,
|
||||
|
|
@ -135,7 +136,8 @@ done:
|
|||
if matches == nil {
|
||||
matches = []sdk.Session{}
|
||||
}
|
||||
return fopts.Emit(iostreams.IO.Out, matches)
|
||||
meta := &output.Meta{Count: len(matches)}
|
||||
return fopts.Emit(iostreams.IO.Out, matches, meta)
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ func TestSessionsSearch_TitleAndDescription(t *testing.T) {
|
|||
}},
|
||||
total: 3,
|
||||
}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
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")
|
||||
|
|
@ -52,7 +52,7 @@ func TestSessionsSearch_NoMatches(t *testing.T) {
|
|||
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.FormatText}, svc))
|
||||
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)")
|
||||
}
|
||||
|
||||
|
|
@ -63,14 +63,14 @@ func TestSessionsSearch_PaginatesAndStopsAtLimit(t *testing.T) {
|
|||
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.FormatText}, svc))
|
||||
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.FormatText}, svc)
|
||||
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)
|
||||
|
|
@ -90,7 +90,7 @@ func TestSessionsSearch_RendersFuzzyTime(t *testing.T) {
|
|||
}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
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")
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ package sessioncmd
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
|
|
@ -14,7 +14,7 @@ import (
|
|||
|
||||
// sessionDeleteFields enumerates the fields surfaced for `--format json`
|
||||
// discovery on `session delete`. Tracks the single-id result struct;
|
||||
// multi-id mode emits MultiDeleteResult (ok/failed).
|
||||
// multi-id mode emits batch envelope (§4.5).
|
||||
var sessionDeleteFields = []string{"id", "deleted"}
|
||||
|
||||
type DeleteOptions struct {
|
||||
|
|
@ -32,20 +32,6 @@ type deleteResult struct {
|
|||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
|
||||
// MultiDeleteResult is the payload for multi-id deletes.
|
||||
// ok: ids successfully deleted; failed: ids that could not be deleted.
|
||||
type MultiDeleteResult struct {
|
||||
OK []string `json:"ok"`
|
||||
Failed []FailedItem `json:"failed,omitempty"`
|
||||
}
|
||||
|
||||
// FailedItem records an id that failed to delete along with its error message.
|
||||
type FailedItem struct {
|
||||
ID string `json:"id"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// NewCmdDelete builds `weknora session delete`. Single-id keeps the simpler
|
||||
// code path; multi-id uses keep-going semantics (one -y confirms all,
|
||||
// failures collected, exit 1 if any fail).
|
||||
|
|
@ -89,12 +75,20 @@ without the user's explicit go-ahead.`,
|
|||
if len(args) == 1 {
|
||||
return runDelete(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
|
||||
}
|
||||
res, runErr := runMultiDelete(c.Context(), opts, fopts, cli, f.Prompter(), args)
|
||||
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "session", len(args), "session.delete", "weknora session delete "+strings.Join(args, " ")+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error {
|
||||
if err := cli.DeleteSession(ctx, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// Only emit when the operation actually ran. Pre-flight errors
|
||||
// (e.g. confirmation_required) must leave stdout empty per the
|
||||
// wire contract in README.md.
|
||||
if len(res.OK) > 0 || len(res.Failed) > 0 {
|
||||
if emitErr := emitMultiDelete(res, fopts, iostreams.IO.Out); emitErr != nil {
|
||||
if len(outcomes) > 0 {
|
||||
if emitErr := cmdutil.EmitBatch(outcomes, fopts, iostreams.IO.Out, cmdutil.DeletedAtNow); emitErr != nil {
|
||||
return emitErr
|
||||
}
|
||||
}
|
||||
|
|
@ -102,11 +96,23 @@ without the user's explicit go-ahead.`,
|
|||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, sessionDeleteFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "permanently delete one or more chat sessions and their messages",
|
||||
RequiredFlags: []string{"<session-id>... (positional, at least one)"},
|
||||
Examples: []string{
|
||||
"weknora session delete s_abc -y",
|
||||
"weknora session delete s_a s_b s_c -y",
|
||||
"weknora session delete s_abc -y --format json",
|
||||
},
|
||||
Warnings: []string{
|
||||
"session delete drops chat history for that session permanently. Never auto-add -y.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "session", id); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "session", id, "session.delete", "weknora session delete "+id+" -y"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
|
@ -115,46 +121,8 @@ func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOp
|
|||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true})
|
||||
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted session %s\n", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runMultiDelete iterates ids sequentially, keep-going on error: a single
|
||||
// failure does not abort the run, so the caller sees the full outcome.
|
||||
func runMultiDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, ids []string) (*MultiDeleteResult, error) {
|
||||
if err := cmdutil.ConfirmDestructiveBatch(p, opts.Yes, fopts.WantsJSON(), "session", len(ids)); err != nil {
|
||||
return &MultiDeleteResult{}, err
|
||||
}
|
||||
res := &MultiDeleteResult{}
|
||||
for _, id := range ids {
|
||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||
res.Failed = append(res.Failed, FailedItem{ID: id, Message: err.Error()})
|
||||
continue
|
||||
}
|
||||
res.OK = append(res.OK, id)
|
||||
}
|
||||
if len(res.Failed) > 0 {
|
||||
return res, cmdutil.NewError(cmdutil.CodeOperationFailed, fmt.Sprintf("%d/%d delete(s) failed", len(res.Failed), len(ids)))
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// emitMultiDelete renders per --format. Mirrors doc delete emitMultiDelete.
|
||||
func emitMultiDelete(res *MultiDeleteResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
|
||||
switch fopts.Mode {
|
||||
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
|
||||
return fopts.Emit(w, res)
|
||||
case cmdutil.FormatText, "":
|
||||
for _, id := range res.OK {
|
||||
fmt.Fprintf(w, "OK %s\n", id)
|
||||
}
|
||||
for _, f := range res.Failed {
|
||||
fmt.Fprintf(w, "FAIL %s: %s\n", f.ID, f.Message)
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported --format %q for session delete", fopts.Mode)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
package sessioncmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
|
|
@ -30,7 +32,7 @@ func TestDelete_WithYes(t *testing.T) {
|
|||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_abc"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_abc"))
|
||||
assert.True(t, svc.called)
|
||||
assert.Equal(t, "s_abc", svc.gotID)
|
||||
assert.False(t, p.Asked, "-y must skip prompt")
|
||||
|
|
@ -40,7 +42,7 @@ func TestDelete_WithYes(t *testing.T) {
|
|||
func TestDelete_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "s_missing")
|
||||
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "s_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -50,7 +52,7 @@ func TestDelete_NotFound(t *testing.T) {
|
|||
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "s_x")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "s_x")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -63,7 +65,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
|
|||
_, _ = iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: true}
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_yes"))
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_yes"))
|
||||
assert.True(t, p.Asked)
|
||||
assert.True(t, svc.called)
|
||||
}
|
||||
|
|
@ -72,7 +74,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
|||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_no")
|
||||
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_no")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -102,41 +104,107 @@ func (f *fakeMultiDeleteSvc) DeleteSession(_ context.Context, id string) error {
|
|||
func TestMultiDelete_AllSucceed(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"s_a", "s_b", "s_c"})
|
||||
outcomes, err := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"s_a", "s_b", "s_c"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"s_a", "s_b", "s_c"}, res.OK)
|
||||
assert.Empty(t, res.Failed)
|
||||
require.Len(t, outcomes, 3)
|
||||
for _, oc := range outcomes {
|
||||
assert.Nil(t, oc.Err, "expected no error for %s", oc.ID)
|
||||
}
|
||||
assert.Equal(t, []string{"s_a", "s_b", "s_c"}, svc.deleted)
|
||||
}
|
||||
|
||||
func TestMultiDelete_PartialFailure_KeepsGoing(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{failOn: map[string]error{"s_b": errors.New("HTTP error 404: not found")}}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"s_a", "s_b", "s_c"})
|
||||
outcomes, err := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"s_a", "s_b", "s_c"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.Error(t, err, "any-failed must surface CodeOperationFailed")
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeOperationFailed, typed.Code)
|
||||
assert.Equal(t, []string{"s_a", "s_c"}, res.OK, "keep-going: s_c was still attempted after s_b failed")
|
||||
assert.Len(t, res.Failed, 1)
|
||||
assert.Equal(t, "s_b", res.Failed[0].ID)
|
||||
require.Len(t, outcomes, 3, "all three ids must appear in outcomes (argv order preserved)")
|
||||
assert.Nil(t, outcomes[0].Err, "s_a should succeed")
|
||||
assert.NotNil(t, outcomes[1].Err, "s_b should fail")
|
||||
assert.Nil(t, outcomes[2].Err, "s_c should succeed (keep-going)")
|
||||
assert.Equal(t, "s_b", outcomes[1].ID)
|
||||
}
|
||||
|
||||
func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{}
|
||||
res, err := runMultiDelete(context.Background(),
|
||||
&DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
|
||||
[]string{"s_a", "s_b"})
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
|
||||
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "session", 2, "session.delete", "")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err))
|
||||
assert.Empty(t, res.OK)
|
||||
assert.Empty(t, svc.deleted, "non-TTY without -y must not call DeleteSession")
|
||||
}
|
||||
|
||||
// TestSessionDelete_MultiID_PartialFailure_BatchEnvelope verifies that the JSON
|
||||
// output for a multi-id partial failure uses the §4.5 batch envelope shape:
|
||||
// {ok:false, data:[{id,ok,result?|error?}...], meta:{count,successes,failures}}.
|
||||
func TestSessionDelete_MultiID_PartialFailure_BatchEnvelope(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeMultiDeleteSvc{failOn: map[string]error{
|
||||
"s_b": errors.New("HTTP error 404: not found"),
|
||||
}}
|
||||
outcomes, runErr := cmdutil.RunBatch(context.Background(),
|
||||
[]string{"s_a", "s_b", "s_c"},
|
||||
func(ctx context.Context, id string) error {
|
||||
if err := svc.DeleteSession(ctx, id); err != nil {
|
||||
return cmdutil.WrapHTTP(err, "delete session %s", id)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.Error(t, runErr)
|
||||
require.Len(t, outcomes, 3)
|
||||
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &buf, cmdutil.DeletedAtNow))
|
||||
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
OK bool `json:"ok"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
} `json:"data"`
|
||||
Meta struct {
|
||||
Count int `json:"count"`
|
||||
Successes int `json:"successes"`
|
||||
Failures int `json:"failures"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &env), "envelope must be valid JSON")
|
||||
|
||||
assert.False(t, env.OK, "top-level ok must be false when any item failed")
|
||||
assert.Equal(t, 3, env.Meta.Count)
|
||||
assert.Equal(t, 2, env.Meta.Successes)
|
||||
assert.Equal(t, 1, env.Meta.Failures)
|
||||
require.Len(t, env.Data, 3)
|
||||
assert.Equal(t, "s_a", env.Data[0].ID)
|
||||
assert.True(t, env.Data[0].OK)
|
||||
assert.Equal(t, "s_b", env.Data[1].ID)
|
||||
assert.False(t, env.Data[1].OK)
|
||||
assert.NotNil(t, env.Data[1].Error)
|
||||
assert.Equal(t, "s_c", env.Data[2].ID)
|
||||
assert.True(t, env.Data[2].OK)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,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"
|
||||
)
|
||||
|
|
@ -64,7 +65,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
|||
},
|
||||
}
|
||||
cmd.Flags().IntVar(&opts.PageSize, "page-size", defaultPageSize, "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.Since, "since", "", "Only show sessions updated within `duration` (e.g. 7d, 24h, 30m)")
|
||||
cmdutil.AddFormatFlag(cmd, sessionListFields...)
|
||||
|
|
@ -78,10 +79,10 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
|||
Message: fmt.Sprintf("--page-size must be in 1..%d, got %d", maxPageSize, 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),
|
||||
}
|
||||
}
|
||||
var since time.Duration
|
||||
|
|
@ -136,12 +137,15 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
|
|||
items = filtered
|
||||
}
|
||||
// --limit applies after --since so the cap reflects what the user sees.
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package sessioncmd
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
|
@ -34,7 +35,7 @@ func (f *fakeListService) GetSessionsByTenant(_ context.Context, page, pageSize
|
|||
func TestList_Empty(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{items: nil, total: 0}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "no sessions")
|
||||
}
|
||||
|
||||
|
|
@ -47,7 +48,7 @@ func TestList_Table(t *testing.T) {
|
|||
},
|
||||
total: 2,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "s_1")
|
||||
assert.Contains(t, got, "Design review")
|
||||
|
|
@ -64,25 +65,34 @@ func TestList_JSON_BareArray(t *testing.T) {
|
|||
},
|
||||
total: 47,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
|
||||
// CLI always asks for page 1 of size --page-size; pagination is server-internal.
|
||||
assert.Equal(t, 1, svc.gotPage)
|
||||
assert.Equal(t, 10, svc.gotPageSize)
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(body), `[`), "bare array expected; got %q", body)
|
||||
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")
|
||||
assert.Contains(t, body, `"id":"s_1"`)
|
||||
assert.NotContains(t, body, `"ok":`)
|
||||
assert.NotContains(t, body, `"_meta":`)
|
||||
assert.NotContains(t, body, `"has_more":`)
|
||||
assert.NotContains(t, body, `"total":`)
|
||||
}
|
||||
|
||||
func TestList_NilItems_RendersAsBareEmptyArray(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{items: nil, total: 0}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, "[]", strings.TrimSpace(out.String()))
|
||||
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")
|
||||
}
|
||||
|
||||
func TestList_BadPagination(t *testing.T) {
|
||||
|
|
@ -96,7 +106,7 @@ func TestList_BadPagination(t *testing.T) {
|
|||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := runList(context.Background(), &ListOptions{PageSize: tc.size}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListService{})
|
||||
err := runList(context.Background(), &ListOptions{PageSize: tc.size, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListService{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -108,7 +118,7 @@ func TestList_BadPagination(t *testing.T) {
|
|||
func TestList_NetworkError_TypedCode(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeListService{err: errors.New("HTTP error 401: unauthenticated")}
|
||||
err := runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
||||
err := runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -119,7 +129,7 @@ func TestList_NetworkError_TypedCode(t *testing.T) {
|
|||
func TestList_NonASCIITitle(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{items: []sdk.Session{{ID: "s_zh", Title: strings.Repeat("中文", 50)}}, total: 1}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
|
||||
assert.Contains(t, out.String(), "s_zh")
|
||||
}
|
||||
|
||||
|
|
@ -132,7 +142,7 @@ func TestList_SinceFilter_DropsOldSessions(t *testing.T) {
|
|||
{ID: "yesterday", Title: "yday", UpdatedAt: now.Add(-23 * time.Hour).Format(time.RFC3339)},
|
||||
}
|
||||
require.NoError(t, runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Since: "7d"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Since: "7d", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{items: items, total: 3}))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "recent")
|
||||
|
|
@ -146,7 +156,7 @@ func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
|
|||
t.Run(v, func(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
require.NoError(t, runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Since: v}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0}),
|
||||
"--since=%q should parse", v)
|
||||
})
|
||||
|
|
@ -156,7 +166,7 @@ func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
|
|||
func TestList_SinceFilter_RejectsInvalidDuration(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Since: "bogus"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Since: "bogus", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -168,7 +178,7 @@ func TestList_SinceFilter_RejectsNonPositive(t *testing.T) {
|
|||
_, _ = iostreams.SetForTest(t)
|
||||
for _, v := range []string{"0d", "0h", "-1h"} {
|
||||
err := runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Since: v}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{items: []sdk.Session{}, total: 0})
|
||||
require.Error(t, err, "--since=%q should reject", v)
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -234,7 +244,7 @@ func TestList_Limit_GreaterThanPageSize_NoCap(t *testing.T) {
|
|||
func TestList_Limit_Negative_Rejected(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
err := runList(context.Background(),
|
||||
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
|
||||
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
|
||||
&fakeListService{})
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
|
|
@ -246,7 +256,7 @@ func TestList_AllPages_WalksAllServerPages(t *testing.T) {
|
|||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &pagedSessionSvc{all: makeSessions(45)}
|
||||
require.NoError(t, runList(context.Background(),
|
||||
&ListOptions{PageSize: 20, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
&ListOptions{PageSize: 20, AllPages: true, Limit: 10000}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
||||
assert.Equal(t, []int{1, 2, 3}, svc.calls)
|
||||
got := strings.Count(out.String(), `"id":"s_`)
|
||||
assert.Equal(t, 45, got)
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
|
|||
|
||||
if fopts.WantsJSON() {
|
||||
if !opts.Full {
|
||||
return fopts.Emit(iostreams.IO.Out, s)
|
||||
return fopts.Emit(iostreams.IO.Out, s, nil)
|
||||
}
|
||||
// Project session + messages into a single bare object. Use the
|
||||
// SDK json tags via an embedded *Session so existing keys stay
|
||||
|
|
@ -126,7 +126,7 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
|
|||
*sdk.Session
|
||||
Messages []sdk.Message `json:"messages"`
|
||||
}{Session: s, Messages: msgs}
|
||||
return fopts.Emit(iostreams.IO.Out, payload)
|
||||
return fopts.Emit(iostreams.IO.Out, payload, nil)
|
||||
}
|
||||
|
||||
w := iostreams.IO.Out
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package sessioncmd
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
|
@ -50,7 +51,7 @@ func TestView_Human(t *testing.T) {
|
|||
CreatedAt: "2026-05-10T09:00:00Z",
|
||||
UpdatedAt: "2026-05-12T14:00:00Z",
|
||||
}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_abc"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_abc"))
|
||||
got := out.String()
|
||||
for _, want := range []string{"s_abc", "Design review", "RAG chunking strategy review", "2026-05-12"} {
|
||||
assert.Contains(t, got, want)
|
||||
|
|
@ -64,14 +65,19 @@ func TestView_JSON(t *testing.T) {
|
|||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "s_abc"))
|
||||
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(body), `{"id":"s_abc"`), "bare object expected; got %q", body)
|
||||
assert.NotContains(t, body, `"ok":`)
|
||||
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")
|
||||
assert.Equal(t, "s_abc", env.Data.ID, "envelope.data.id must be s_abc")
|
||||
}
|
||||
|
||||
func TestView_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{err: errors.New("HTTP error 404: not found")}
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_missing")
|
||||
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
|
@ -81,7 +87,7 @@ func TestView_NotFound(t *testing.T) {
|
|||
func TestView_OmitsEmptyDescription(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s_min", Title: "Bare"}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_min"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_min"))
|
||||
// Empty Description should not produce an empty `DESC:` line.
|
||||
for line := range strings.SplitSeq(out.String(), "\n") {
|
||||
if strings.HasPrefix(line, "DESC:") {
|
||||
|
|
@ -101,7 +107,7 @@ func TestView_Full_LoadsMessages(t *testing.T) {
|
|||
{ID: "m2", Role: "assistant", Content: "RAG stands for retrieval-augmented generation.", CreatedAt: time.Date(2026, 5, 15, 14, 32, 5, 0, time.UTC)},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_abc"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_abc"))
|
||||
got := out.String()
|
||||
assert.True(t, svc.loadCall.called, "expected LoadMessages to be called")
|
||||
assert.Equal(t, "s_abc", svc.loadCall.sessionID)
|
||||
|
|
@ -117,7 +123,7 @@ func TestView_Full_NoMessages(t *testing.T) {
|
|||
s: &sdk.Session{ID: "s_empty", Title: "Empty"},
|
||||
msgs: []sdk.Message{},
|
||||
}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_empty"))
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_empty"))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "Messages (0)")
|
||||
}
|
||||
|
|
@ -125,7 +131,7 @@ func TestView_Full_NoMessages(t *testing.T) {
|
|||
func TestView_Full_LimitInvalid_Zero(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
|
|
@ -133,7 +139,7 @@ func TestView_Full_LimitInvalid_Zero(t *testing.T) {
|
|||
func TestView_Full_LimitInvalid_TooLarge(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 1001}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 1001}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
|
|
@ -143,7 +149,7 @@ func TestView_Full_LimitInvalid_TooLarge(t *testing.T) {
|
|||
func TestView_LimitWithoutFull(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
|
||||
err := runView(context.Background(), &ViewOptions{Full: false, Limit: 100, LimitSet: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
|
||||
err := runView(context.Background(), &ViewOptions{Full: false, Limit: 100, LimitSet: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
assert.Contains(t, err.Error(), "--limit")
|
||||
|
|
|
|||
|
|
@ -101,17 +101,12 @@ func MergeAgentConfig(base *sdk.AgentConfig, ov AgentConfigFlags) *sdk.AgentConf
|
|||
return &out
|
||||
}
|
||||
|
||||
// skeletonCommentVersion is embedded in the skeleton header so users
|
||||
// regenerating an outdated template after a schema bump can spot the
|
||||
// version mismatch.
|
||||
const skeletonCommentVersion = "v0.6 / 34 fields"
|
||||
|
||||
// GenerateAgentSkeleton writes a commented YAML template with every
|
||||
// AgentConfig field at its zero value to w. Used by
|
||||
// `agent create --generate-skeleton` so users get a ready-to-edit
|
||||
// starting point without authoring the 34-field schema from memory.
|
||||
// starting point without authoring the full schema from memory.
|
||||
func GenerateAgentSkeleton(w io.Writer) error {
|
||||
const skeleton = `# WeKnora AgentConfig skeleton (` + skeletonCommentVersion + `)
|
||||
const skeleton = `# WeKnora AgentConfig YAML skeleton
|
||||
# Edit this file and pass it to:
|
||||
# weknora agent create "My Agent" --model <id> --config-file <this-file>
|
||||
# Hot-path flags on the create command override values set here.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,128 @@
|
|||
// Package cmdutil — batch.go provides reusable plumbing for multi-target
|
||||
// mutations that emit the §4.5 batch envelope.
|
||||
//
|
||||
// Three pieces:
|
||||
// - BatchOutcome: per-target structured outcome (preserves argv order).
|
||||
// - RunBatch: drives a slice of targets through a closure, collecting
|
||||
// outcomes. Stops on context cancellation; keep-going on per-item err.
|
||||
// - EmitBatch: renders the outcomes — JSON/NDJSON via output.WriteBatchEnvelope,
|
||||
// text via per-item "OK <id>" / "FAIL <id>: <msg>".
|
||||
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
// BatchOutcome is one per-target result preserving argv order. Err==nil ⇒ success.
|
||||
type BatchOutcome struct {
|
||||
ID string
|
||||
Err error
|
||||
}
|
||||
|
||||
// RunBatch invokes op(ctx, id) for each id and collects outcomes in order.
|
||||
// Per-item errors do not abort the run; context cancellation does (the
|
||||
// remainder of the slice is marked with the context error).
|
||||
//
|
||||
// Returns (outcomes, summaryErr). summaryErr is a typed *Error with
|
||||
// CodeOperationFailed when any per-item op failed, nil otherwise. Callers
|
||||
// emit the outcomes before returning summaryErr so partial-success data
|
||||
// reaches stdout.
|
||||
func RunBatch(ctx context.Context, ids []string, op func(context.Context, string) error) ([]BatchOutcome, error) {
|
||||
outcomes := make([]BatchOutcome, 0, len(ids))
|
||||
failed := 0
|
||||
for _, id := range ids {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
outcomes = append(outcomes, BatchOutcome{ID: id, Err: ctx.Err()})
|
||||
failed++
|
||||
continue
|
||||
default:
|
||||
}
|
||||
err := op(ctx, id)
|
||||
outcomes = append(outcomes, BatchOutcome{ID: id, Err: err})
|
||||
if err != nil {
|
||||
failed++
|
||||
}
|
||||
}
|
||||
if failed > 0 {
|
||||
return outcomes, &Error{
|
||||
Code: CodeOperationFailed,
|
||||
Message: fmt.Sprintf("%d/%d operation(s) failed", failed, len(ids)),
|
||||
// Silent suppresses the stderr error envelope because the caller
|
||||
// already emitted the batch envelope to stdout (§4.5). The exit code
|
||||
// still propagates via Error.Code → ExitCode (falls through to 1).
|
||||
Silent: true,
|
||||
}
|
||||
}
|
||||
return outcomes, nil
|
||||
}
|
||||
|
||||
// EmitBatch writes the per-item outcomes per --format. JSON/NDJSON emit
|
||||
// the §4.5 batch envelope; human/text mode emits per-line "OK <id>" /
|
||||
// "FAIL <id>: <msg>".
|
||||
//
|
||||
// resultFn builds the per-item Result map for successes; nil ⇒ omit.
|
||||
// A typical resultFn returns map[string]any{"deleted_at": time.Now()....}.
|
||||
//
|
||||
// Callers wanting a stable per-item timestamp pass time.Now() via
|
||||
// resultFn so tests can pin the clock with SetDeletedAtClock.
|
||||
func EmitBatch(outcomes []BatchOutcome, fopts *FormatOptions, w io.Writer, resultFn func(id string) any) error {
|
||||
if fopts.WantsJSON() {
|
||||
items := make([]output.BatchItem, len(outcomes))
|
||||
for i, o := range outcomes {
|
||||
items[i] = output.BatchItem{ID: o.ID, OK: o.Err == nil}
|
||||
if o.Err != nil {
|
||||
items[i].Error = ErrorToDetail(o.Err)
|
||||
} else if resultFn != nil {
|
||||
items[i].Result = resultFn(o.ID)
|
||||
}
|
||||
}
|
||||
return output.WriteBatchEnvelope(w, items, fopts.TTY, globalProfile)
|
||||
}
|
||||
for _, o := range outcomes {
|
||||
if o.Err == nil {
|
||||
fmt.Fprintf(w, "OK %s\n", o.ID)
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(w, "FAIL %s: %s\n", o.ID, o.Err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deletedAtClock is the clock source for DeletedAtNow. Overridable in tests
|
||||
// to make per-item timestamps deterministic.
|
||||
var deletedAtClock = time.Now
|
||||
|
||||
// DeletedAtNow is the canonical resultFn for delete batches that report
|
||||
// {deleted_at: <RFC3339>} per success. Tests can freeze the clock via
|
||||
// SetDeletedAtClock(func() time.Time { return fixed }).
|
||||
func DeletedAtNow(id string) any {
|
||||
return map[string]any{"deleted_at": deletedAtClock().Format(time.RFC3339)}
|
||||
}
|
||||
|
||||
// SetDeletedAtClock overrides the time source used by DeletedAtNow. Returns
|
||||
// a cleanup func that restores time.Now. For test use only.
|
||||
func SetDeletedAtClock(clock func() time.Time) func() {
|
||||
deletedAtClock = clock
|
||||
return func() { deletedAtClock = time.Now }
|
||||
}
|
||||
|
||||
// ClassifyContextErr maps a context error to the appropriate operation code.
|
||||
// Falls back to CodeOperationFailed when err is nil or not a context signal.
|
||||
func ClassifyContextErr(err error) ErrorCode {
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
return CodeOperationCancelled
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return CodeOperationTimeout
|
||||
default:
|
||||
return CodeOperationFailed
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,193 @@
|
|||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestRunBatch_AllSuccess verifies that 3 ids all succeed: outcomes are
|
||||
// ordered and summaryErr is nil.
|
||||
func TestRunBatch_AllSuccess(t *testing.T) {
|
||||
ids := []string{"a", "b", "c"}
|
||||
op := func(_ context.Context, id string) error { return nil }
|
||||
|
||||
outcomes, err := RunBatch(context.Background(), ids, op)
|
||||
if err != nil {
|
||||
t.Fatalf("expected nil summaryErr; got %v", err)
|
||||
}
|
||||
if len(outcomes) != 3 {
|
||||
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
|
||||
}
|
||||
for i, o := range outcomes {
|
||||
if o.ID != ids[i] {
|
||||
t.Errorf("outcomes[%d].ID = %q, want %q", i, o.ID, ids[i])
|
||||
}
|
||||
if o.Err != nil {
|
||||
t.Errorf("outcomes[%d].Err = %v, want nil", i, o.Err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunBatch_PartialFailure verifies that one failing id yields summaryErr
|
||||
// with CodeOperationFailed while successful outcomes are preserved.
|
||||
func TestRunBatch_PartialFailure(t *testing.T) {
|
||||
ids := []string{"ok1", "fail", "ok2"}
|
||||
errFail := errors.New("something went wrong")
|
||||
op := func(_ context.Context, id string) error {
|
||||
if id == "fail" {
|
||||
return errFail
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
outcomes, summaryErr := RunBatch(context.Background(), ids, op)
|
||||
if summaryErr == nil {
|
||||
t.Fatal("expected non-nil summaryErr")
|
||||
}
|
||||
typedErr := AsError(summaryErr)
|
||||
if typedErr == nil {
|
||||
t.Fatalf("summaryErr is not *Error; got %T %v", summaryErr, summaryErr)
|
||||
}
|
||||
if typedErr.Code != CodeOperationFailed {
|
||||
t.Errorf("summaryErr.Code = %q, want %q", typedErr.Code, CodeOperationFailed)
|
||||
}
|
||||
if !strings.Contains(typedErr.Message, "1/3") {
|
||||
t.Errorf("summaryErr.Message = %q, expected 1/3 ratio", typedErr.Message)
|
||||
}
|
||||
if len(outcomes) != 3 {
|
||||
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
|
||||
}
|
||||
if outcomes[1].Err != errFail {
|
||||
t.Errorf("outcomes[1].Err = %v, want %v", outcomes[1].Err, errFail)
|
||||
}
|
||||
if outcomes[0].Err != nil || outcomes[2].Err != nil {
|
||||
t.Error("expected outcomes[0] and outcomes[2] to have nil Err")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunBatch_ContextCancellation verifies that once the context is cancelled,
|
||||
// remaining ids are marked with the context error without calling op.
|
||||
func TestRunBatch_ContextCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
ids := []string{"first", "second", "third"}
|
||||
opCalled := 0
|
||||
op := func(ctx context.Context, id string) error {
|
||||
opCalled++
|
||||
if id == "first" {
|
||||
cancel() // cancel after the first item
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
outcomes, summaryErr := RunBatch(ctx, ids, op)
|
||||
|
||||
// summaryErr must be non-nil (cancelled items counted as failed)
|
||||
if summaryErr == nil {
|
||||
t.Fatal("expected non-nil summaryErr due to cancellation")
|
||||
}
|
||||
if len(outcomes) != 3 {
|
||||
t.Fatalf("expected 3 outcomes; got %d", len(outcomes))
|
||||
}
|
||||
// "second" and "third" should have ctx.Err() as their error
|
||||
for _, id := range []string{"second", "third"} {
|
||||
var found *BatchOutcome
|
||||
for i := range outcomes {
|
||||
if outcomes[i].ID == id {
|
||||
found = &outcomes[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
t.Fatalf("missing outcome for id %q", id)
|
||||
}
|
||||
if !errors.Is(found.Err, context.Canceled) {
|
||||
t.Errorf("outcome[%s].Err = %v, want context.Canceled", id, found.Err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmitBatch_JSON_Envelope verifies that the JSON path emits a valid §4.5
|
||||
// batch envelope with correct ok/error/result fields.
|
||||
func TestEmitBatch_JSON_Envelope(t *testing.T) {
|
||||
outcomes := []BatchOutcome{
|
||||
{ID: "x", Err: nil},
|
||||
{ID: "y", Err: NewError(CodeResourceNotFound, "not found")},
|
||||
}
|
||||
fopts := &FormatOptions{Mode: FormatJSON, TTY: false}
|
||||
var buf bytes.Buffer
|
||||
|
||||
err := EmitBatch(outcomes, fopts, &buf, func(id string) any {
|
||||
return map[string]any{"deleted_at": "2026-01-01T00:00:00Z"}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("EmitBatch error: %v", err)
|
||||
}
|
||||
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, `"ok":true`) {
|
||||
t.Errorf("expected ok:true in envelope; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"id":"x"`) {
|
||||
t.Errorf("expected id:x; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"id":"y"`) {
|
||||
t.Errorf("expected id:y; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"deleted_at":"2026-01-01T00:00:00Z"`) {
|
||||
t.Errorf("expected result.deleted_at for x; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"type":"resource.not_found"`) {
|
||||
t.Errorf("expected error.type for y; got %q", got)
|
||||
}
|
||||
// meta.failures should be 1
|
||||
if !strings.Contains(got, `"failures":1`) {
|
||||
t.Errorf("expected meta.failures:1; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletedAtNow_FixedClock verifies that SetDeletedAtClock overrides the
|
||||
// timestamp used by DeletedAtNow, making per-item values deterministic in tests.
|
||||
func TestDeletedAtNow_FixedClock(t *testing.T) {
|
||||
fixed := time.Date(2026, 5, 20, 0, 0, 0, 0, time.UTC)
|
||||
defer SetDeletedAtClock(func() time.Time { return fixed })()
|
||||
|
||||
got := DeletedAtNow("irrelevant")
|
||||
m, ok := got.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("DeletedAtNow returned %T, want map[string]any", got)
|
||||
}
|
||||
want := fixed.Format(time.RFC3339)
|
||||
if m["deleted_at"] != want {
|
||||
t.Errorf("deleted_at = %q, want %q", m["deleted_at"], want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmitBatch_Text_PerLine verifies that the human/text path emits
|
||||
// "OK <id>" / "FAIL <id>: <msg>" per line.
|
||||
func TestEmitBatch_Text_PerLine(t *testing.T) {
|
||||
outcomes := []BatchOutcome{
|
||||
{ID: "x", Err: nil},
|
||||
{ID: "y", Err: fmt.Errorf("boom")},
|
||||
}
|
||||
fopts := &FormatOptions{Mode: FormatHuman}
|
||||
var buf bytes.Buffer
|
||||
|
||||
err := EmitBatch(outcomes, fopts, &buf, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("EmitBatch error: %v", err)
|
||||
}
|
||||
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, "OK x\n") {
|
||||
t.Errorf("expected 'OK x' line; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "FAIL y: boom\n") {
|
||||
t.Errorf("expected 'FAIL y: boom' line; got %q", got)
|
||||
}
|
||||
}
|
||||
|
|
@ -13,7 +13,10 @@ import (
|
|||
// — one -y confirms all items in the batch.
|
||||
//
|
||||
// Pass n = total count of items about to be deleted.
|
||||
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string, n int) error {
|
||||
// action is the namespaced action verb (e.g. "doc.delete") for the risk envelope.
|
||||
// retryCmd is the directly-executable retry argv (e.g. "weknora doc delete a b -y");
|
||||
// pass "" when no clean retry argv is available.
|
||||
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string, n int, action, retryCmd string) error {
|
||||
if yes {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -21,7 +24,9 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string,
|
|||
return NewError(
|
||||
CodeInputConfirmationRequired,
|
||||
fmt.Sprintf("delete %d %s(s) requires explicit confirmation: re-run with -y/--yes", n, what),
|
||||
)
|
||||
).
|
||||
WithRetryCommand(retryCmd).
|
||||
WithRisk("destructive", action)
|
||||
}
|
||||
ok, err := p.Confirm(fmt.Sprintf("Delete %d %s(s)? This cannot be undone.", n, what), false)
|
||||
if err != nil {
|
||||
|
|
@ -51,7 +56,10 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, what string,
|
|||
// proceed. See cli/README.md "Exit codes".
|
||||
//
|
||||
// `yes` should be sourced from the persistent global -y/--yes flag.
|
||||
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error {
|
||||
// action is the namespaced action verb (e.g. "kb.delete") for the risk envelope.
|
||||
// retryCmd is the directly-executable retry argv (e.g. "weknora kb delete kb_x -y");
|
||||
// pass "" when no clean retry argv is available.
|
||||
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id, action, retryCmd string) error {
|
||||
if yes {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -59,7 +67,9 @@ func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) e
|
|||
return NewError(
|
||||
CodeInputConfirmationRequired,
|
||||
fmt.Sprintf("delete %s %s requires explicit confirmation: re-run with -y/--yes", what, id),
|
||||
)
|
||||
).
|
||||
WithRetryCommand(retryCmd).
|
||||
WithRisk("destructive", action)
|
||||
}
|
||||
ok, err := p.Confirm(fmt.Sprintf("Delete %s %s? This cannot be undone.", what, id), false)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -4,41 +4,40 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
// Typed format modes. Defined as constants to keep mode comparisons
|
||||
// type-safe and prevent string drift across call sites.
|
||||
// FormatMode is the resolved --format value (typed enum).
|
||||
type FormatMode string
|
||||
|
||||
const (
|
||||
FormatText = "text"
|
||||
FormatJSON = "json"
|
||||
FormatNDJSON = "ndjson"
|
||||
FormatHuman FormatMode = "human"
|
||||
FormatJSON FormatMode = "json"
|
||||
FormatNDJSON FormatMode = "ndjson"
|
||||
)
|
||||
|
||||
// FormatOptions captures the resolved --format + --jq state for a command.
|
||||
// Mode is one of FormatText / FormatJSON / FormatNDJSON, or "" before
|
||||
// Mode is one of FormatHuman / FormatJSON / FormatNDJSON, or "" before
|
||||
// ResolveDefault has been called.
|
||||
type FormatOptions struct {
|
||||
Mode string
|
||||
Mode FormatMode
|
||||
JQ string
|
||||
TTY bool // ResolveDefault populates; Emit reads for indent decision
|
||||
}
|
||||
|
||||
// AddFormatFlag registers --format and --jq on cmd. Optional fieldHints are
|
||||
// appended to cmd.Long as a documentation aid for --jq projection
|
||||
// (e.g., `weknora kb list --format json --jq '.[] | {id, name}'`).
|
||||
//
|
||||
// Uses cmd.Flags() (local) rather than a root persistent flag — only
|
||||
// commands that actually honor --format register it, so cobra rejects
|
||||
// --format on others with "unknown flag" rather than silently ignoring it.
|
||||
// AddFormatFlag attaches the --jq projection field hints (in cmd.Long) for
|
||||
// commands that honor --format. The flags themselves are registered as
|
||||
// persistent globals at the root, so this helper no longer re-registers
|
||||
// them — it only appends documentation. Callers that don't need field
|
||||
// hints can skip this call entirely.
|
||||
func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
|
||||
cmd.Flags().String("format", "", "Output format: text | json | ndjson (default: text in TTY, json in pipe)")
|
||||
cmd.Flags().StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --format json|ndjson)")
|
||||
|
||||
if len(fieldHints) > 0 {
|
||||
sorted := append([]string(nil), fieldHints...)
|
||||
sort.Strings(sorted)
|
||||
|
|
@ -55,7 +54,7 @@ func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
|
|||
// CheckFormatFlag resolves --format + --jq from cmd. Returns:
|
||||
// - (*FormatOptions{Mode:""}, nil) flag not set; caller should call ResolveDefault
|
||||
// - (*FormatOptions{Mode:v,JQ:q}, nil) valid values
|
||||
// - (nil, *FlagError) invalid --format, or --jq with explicit --format text
|
||||
// - (nil, *FlagError) invalid --format, or --jq with explicit --format human
|
||||
//
|
||||
// --jq with --format unset is accepted: ResolveDefault below will promote
|
||||
// the mode to FormatJSON so the filter has somewhere to apply.
|
||||
|
|
@ -64,19 +63,21 @@ func CheckFormatFlag(cmd *cobra.Command) (*FormatOptions, error) {
|
|||
if f := cmd.Flags().Lookup("format"); f != nil {
|
||||
v := f.Value.String()
|
||||
switch v {
|
||||
case "", FormatText, FormatJSON, FormatNDJSON:
|
||||
fopts.Mode = v
|
||||
case "":
|
||||
// unset; caller calls ResolveDefault
|
||||
case "human", "json", "ndjson":
|
||||
fopts.Mode = FormatMode(v)
|
||||
default:
|
||||
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be text | json | ndjson", v))
|
||||
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be human | json | ndjson", v))
|
||||
}
|
||||
}
|
||||
if f := cmd.Flags().Lookup("jq"); f != nil {
|
||||
fopts.JQ = f.Value.String()
|
||||
}
|
||||
// --jq only meaningful for JSON-shaped output. Reject the explicit
|
||||
// `--format text --jq ...` combination; the `--jq` with --format unset
|
||||
// `--format human --jq ...` combination; the `--jq` with --format unset
|
||||
// case is handled by ResolveDefault.
|
||||
if fopts.JQ != "" && fopts.Mode == FormatText {
|
||||
if fopts.JQ != "" && fopts.Mode == FormatHuman {
|
||||
return nil, NewFlagError(errors.New("--jq requires --format json|ndjson"))
|
||||
}
|
||||
return fopts, nil
|
||||
|
|
@ -88,48 +89,68 @@ func (o *FormatOptions) WantsJSON() bool {
|
|||
return o.Mode == FormatJSON || o.Mode == FormatNDJSON
|
||||
}
|
||||
|
||||
// Emit serializes v according to the resolved Mode + JQ. For ndjson, slice
|
||||
// values are split element-per-line (per ndjson.org); for json, v is
|
||||
// emitted as-is. When JQ is set, the jq expression runs against the
|
||||
// marshaled JSON and each result becomes a line. Text mode is the caller's
|
||||
// job — Emit returns an error so a missed dispatch surfaces loudly.
|
||||
func (o *FormatOptions) Emit(w io.Writer, v any) error {
|
||||
// Emit serializes data wrapped in the success envelope (FormatJSON
|
||||
// path) or as bare NDJSON lines (FormatNDJSON path). meta is optional
|
||||
// (pass nil for mutation commands without batch counts).
|
||||
//
|
||||
// FormatJSON path: envelope is {ok:true, data:..., meta?:..., _notice?:...}.
|
||||
// Indent is determined by o.TTY (populated by ResolveDefault).
|
||||
// When o.JQ is set, jq evaluates against the full envelope JSON, so users
|
||||
// project with ".data[]", ".meta.count", etc.
|
||||
//
|
||||
// FormatNDJSON path: emits one bare JSON object per line (no envelope).
|
||||
// Matches spec §5 NDJSON event-passthrough semantics.
|
||||
//
|
||||
// FormatHuman path returns an error so a missed dispatch surfaces loudly.
|
||||
func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
|
||||
switch o.Mode {
|
||||
case FormatJSON:
|
||||
return format.WriteJSONFiltered(w, v, nil, o.JQ)
|
||||
case FormatNDJSON:
|
||||
// jq output is naturally line-per-result → already valid NDJSON.
|
||||
// Without jq, split arrays per ndjson.org (one object per line).
|
||||
if o.JQ != "" {
|
||||
return format.WriteJSONFiltered(w, v, nil, o.JQ)
|
||||
env := output.Envelope{
|
||||
OK: true,
|
||||
Data: data,
|
||||
Meta: meta,
|
||||
Notice: output.GetNotice(),
|
||||
Profile: globalProfile,
|
||||
}
|
||||
return format.WriteJSONFiltered(w, env, nil, o.JQ)
|
||||
}
|
||||
return format.WriteNDJSON(w, v)
|
||||
case FormatText:
|
||||
return fmt.Errorf("FormatOptions.Emit: cannot emit text mode as JSON; caller must render text separately")
|
||||
return output.WriteEnvelope(w, data, meta, o.TTY, globalProfile)
|
||||
case FormatNDJSON:
|
||||
if o.JQ != "" {
|
||||
return format.WriteJSONFiltered(w, data, nil, o.JQ)
|
||||
}
|
||||
return format.WriteNDJSON(w, data)
|
||||
case FormatHuman:
|
||||
return fmt.Errorf("FormatOptions.Emit: cannot emit human mode as JSON; caller must render human-readable separately")
|
||||
default:
|
||||
return fmt.Errorf("FormatOptions.Emit: unknown mode %q", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveDefault fills in Mode using TTY detection when the user didn't pass
|
||||
// --format explicitly. Pass iostreams.IO.IsStdoutTTY() as isTTY.
|
||||
// No-op if Mode is already set.
|
||||
//
|
||||
// `--jq` without an explicit `--format` forces JSON regardless of TTY:
|
||||
// the filter has no meaning in text mode, so silently dropping it would
|
||||
// surprise the user. The `--jq` + `--format text` combination is caught
|
||||
// up-front by CheckFormatFlag.
|
||||
func (o *FormatOptions) ResolveDefault(isTTY bool) {
|
||||
if o.Mode != "" {
|
||||
return
|
||||
}
|
||||
if o.JQ != "" {
|
||||
o.Mode = FormatJSON
|
||||
return
|
||||
}
|
||||
if isTTY {
|
||||
o.Mode = FormatText
|
||||
} else {
|
||||
// ResolveDefault fills in Mode when the caller has not explicitly set it:
|
||||
// - Mode defaults to FormatJSON
|
||||
// - TTY only affects the indent decision (auto-indent in TTY; compact in pipe)
|
||||
// - For human-readable rendering, pass --format human explicitly
|
||||
func (o *FormatOptions) ResolveDefault(tty bool) {
|
||||
o.TTY = tty
|
||||
if o.Mode == "" {
|
||||
o.Mode = FormatJSON
|
||||
}
|
||||
}
|
||||
|
||||
// FromEnv reads WEKNORA_FORMAT and applies it when Mode hasn't been set
|
||||
// by --format. Call between CheckFormatFlag and ResolveDefault.
|
||||
//
|
||||
// Invalid env values are silently ignored (the user's --format on a
|
||||
// later invocation will still take precedence).
|
||||
func (o *FormatOptions) FromEnv() {
|
||||
if o.Mode != "" {
|
||||
return
|
||||
}
|
||||
v := os.Getenv("WEKNORA_FORMAT")
|
||||
switch v {
|
||||
case "human", "json", "ndjson":
|
||||
o.Mode = FormatMode(v)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,88 @@
|
|||
package cmdutil_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
func TestEmit_WrapsInEnvelope(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
data := []map[string]string{{"id": "kb_x"}, {"id": "kb_y"}}
|
||||
if err := fopts.Emit(&buf, data, nil); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, `"ok":true`) {
|
||||
t.Errorf("expected envelope ok:true; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"data":[`) {
|
||||
t.Errorf("expected data array; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmit_WithMeta(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
meta := &output.Meta{Count: 2, HasMore: true}
|
||||
if err := fopts.Emit(&buf, []string{"a", "b"}, meta); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, `"count":2`) {
|
||||
t.Errorf("expected meta.count; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"has_more":true`) {
|
||||
t.Errorf("expected meta.has_more; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmit_NDJSON_NoEnvelope(t *testing.T) {
|
||||
// NDJSON path is event-passthrough; no envelope wrapping per spec §5.
|
||||
var buf bytes.Buffer
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
|
||||
data := []map[string]string{{"id": "a"}, {"id": "b"}}
|
||||
if err := fopts.Emit(&buf, data, nil); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if strings.Contains(got, `"ok":true`) {
|
||||
t.Errorf("NDJSON path should not wrap in envelope; got %q", got)
|
||||
}
|
||||
// Expect 2 lines, one per item
|
||||
lines := strings.Split(strings.TrimRight(got, "\n"), "\n")
|
||||
if len(lines) != 2 {
|
||||
t.Errorf("expected 2 NDJSON lines; got %d: %q", len(lines), got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmit_TTYIndents(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, TTY: true}
|
||||
if err := fopts.Emit(&buf, map[string]string{"id": "x"}, nil); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, "\n \"") {
|
||||
t.Errorf("expected indented multi-line output (TTY=true); got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmit_PopulatesProfile(t *testing.T) {
|
||||
cmdutil.SetProfile("staging")
|
||||
t.Cleanup(func() { cmdutil.SetProfile("") })
|
||||
|
||||
var buf bytes.Buffer
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
|
||||
if err := fopts.Emit(&buf, map[string]string{"id": "x"}, nil); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, `"profile":"staging"`) {
|
||||
t.Errorf("expected profile:staging in envelope; got %q", got)
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
|
@ -13,20 +14,26 @@ func TestCheckFormatFlags(t *testing.T) {
|
|||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
wantMode string // "text" | "json" | "ndjson" | "" (unset)
|
||||
wantMode FormatMode // FormatHuman | FormatJSON | FormatNDJSON | "" (unset)
|
||||
wantErr bool
|
||||
}{
|
||||
// Unset → Mode is "" (caller resolves TTY default via ResolveDefault).
|
||||
// Unset → Mode is "" (caller resolves default via ResolveDefault).
|
||||
{"default", []string{}, "", false},
|
||||
{"explicit text", []string{"--format", "text"}, "text", false},
|
||||
{"json", []string{"--format", "json"}, "json", false},
|
||||
{"ndjson", []string{"--format", "ndjson"}, "ndjson", false},
|
||||
{"explicit human", []string{"--format", "human"}, FormatHuman, false},
|
||||
{"json", []string{"--format", "json"}, FormatJSON, false},
|
||||
{"ndjson", []string{"--format", "ndjson"}, FormatNDJSON, false},
|
||||
{"invalid value", []string{"--format", "yaml"}, "", true},
|
||||
// v0.7 BREAKING: "text" is no longer a valid --format value.
|
||||
{"text rejected", []string{"--format", "text"}, "", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
AddFormatFlag(cmd)
|
||||
// --format / --jq are persistent root flags in production; register
|
||||
// them on this bare cmd so the test can exercise CheckFormatFlag in
|
||||
// isolation.
|
||||
cmd.PersistentFlags().String("format", "", "")
|
||||
cmd.PersistentFlags().String("jq", "", "")
|
||||
cmd.SetArgs(tc.args)
|
||||
cmd.RunE = func(c *cobra.Command, _ []string) error {
|
||||
opts, err := CheckFormatFlag(c)
|
||||
|
|
@ -45,9 +52,9 @@ func TestCheckFormatFlags(t *testing.T) {
|
|||
|
||||
func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &FormatOptions{Mode: "ndjson"}
|
||||
fopts := &FormatOptions{Mode: FormatNDJSON}
|
||||
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
|
||||
if err := fopts.Emit(&buf, arr); err != nil {
|
||||
if err := fopts.Emit(&buf, arr, nil); err != nil {
|
||||
t.Fatalf("Emit: %v", err)
|
||||
}
|
||||
want := `{"id":"a"}` + "\n" + `{"id":"b"}` + "\n"
|
||||
|
|
@ -58,45 +65,68 @@ func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
|
|||
|
||||
func TestFormatOptions_JSONEmitsArray(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &FormatOptions{Mode: "json"}
|
||||
fopts := &FormatOptions{Mode: FormatJSON}
|
||||
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
|
||||
if err := fopts.Emit(&buf, arr); err != nil {
|
||||
if err := fopts.Emit(&buf, arr, nil); err != nil {
|
||||
t.Fatalf("Emit: %v", err)
|
||||
}
|
||||
// Expect a single JSON array, e.g. [{"id":"a"},{"id":"b"}]
|
||||
var got []map[string]string
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("not valid JSON: %v\n%s", err, buf.String())
|
||||
// v0.7: JSON path wraps in success envelope {ok:true, data:[...]}.
|
||||
// Unmarshal the envelope and check data array length.
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []map[string]string `json:"data"`
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Errorf("got %d items, want 2", len(got))
|
||||
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
|
||||
t.Fatalf("not valid envelope JSON: %v\n%s", err, buf.String())
|
||||
}
|
||||
if !env.OK {
|
||||
t.Errorf("expected ok:true in envelope")
|
||||
}
|
||||
if len(env.Data) != 2 {
|
||||
t.Errorf("got %d items, want 2", len(env.Data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatOptions_TextModeReturnsError(t *testing.T) {
|
||||
fopts := &FormatOptions{Mode: "text"}
|
||||
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"})
|
||||
func TestFormatOptions_HumanModeReturnsError(t *testing.T) {
|
||||
fopts := &FormatOptions{Mode: FormatHuman}
|
||||
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"}, nil)
|
||||
if err == nil {
|
||||
t.Error("expected error for text mode, got nil")
|
||||
t.Error("expected error for human mode, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveDefault_AlwaysJSON verifies v0.7 semantics: default is FormatJSON
|
||||
// regardless of whether stdout is a TTY (BREAKING change from v0.6).
|
||||
func TestResolveDefault_AlwaysJSON(t *testing.T) {
|
||||
for _, isTTY := range []bool{true, false} {
|
||||
o := &FormatOptions{}
|
||||
o.ResolveDefault(isTTY)
|
||||
if o.Mode != FormatJSON {
|
||||
t.Errorf("isTTY=%v: expected default FormatJSON, got %v", isTTY, o.Mode)
|
||||
}
|
||||
if o.TTY != isTTY {
|
||||
t.Errorf("isTTY=%v: TTY field not propagated", isTTY)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDefault(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
mode string // pre-set Mode
|
||||
mode FormatMode // pre-set Mode
|
||||
jq string
|
||||
isTTY bool
|
||||
wantMode string
|
||||
wantMode FormatMode
|
||||
}{
|
||||
{"empty isTTY", "", "", true, "text"},
|
||||
{"empty no-tty", "", "", false, "json"},
|
||||
{"already set keeps value tty", "ndjson", "", true, "ndjson"},
|
||||
{"already set keeps value no-tty", "json", "", false, "json"},
|
||||
// v0.7: empty Mode always resolves to FormatJSON regardless of TTY.
|
||||
{"empty isTTY", "", "", true, FormatJSON},
|
||||
{"empty no-tty", "", "", false, FormatJSON},
|
||||
{"already set keeps value tty", FormatNDJSON, "", true, FormatNDJSON},
|
||||
{"already set keeps value no-tty", FormatJSON, "", false, FormatJSON},
|
||||
// --jq with unset --format promotes to JSON regardless of TTY so the
|
||||
// filter has somewhere to apply (silent text drop would surprise users).
|
||||
{"jq forces json on TTY", "", ".[]", true, "json"},
|
||||
{"jq with explicit ndjson preserved", "ndjson", ".[]", true, "ndjson"},
|
||||
// filter has somewhere to apply (silent human drop would surprise users).
|
||||
{"jq forces json on TTY", "", ".[]", true, FormatJSON},
|
||||
{"jq with explicit ndjson preserved", FormatNDJSON, ".[]", true, FormatNDJSON},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
|
@ -117,12 +147,18 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
|
|||
args []string
|
||||
}{
|
||||
{"invalid format value", []string{"--format", "yaml"}},
|
||||
{"jq with explicit text mode", []string{"--format", "text", "--jq", ".id"}},
|
||||
// v0.7: "text" is rejected; "human" is the valid human-readable value.
|
||||
{"text rejected as invalid", []string{"--format", "text"}},
|
||||
{"jq with explicit human mode", []string{"--format", "human", "--jq", ".id"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
AddFormatFlag(cmd)
|
||||
// --format / --jq are persistent root flags in production; register
|
||||
// them on this bare cmd so the test can exercise CheckFormatFlag in
|
||||
// isolation.
|
||||
cmd.PersistentFlags().String("format", "", "")
|
||||
cmd.PersistentFlags().String("jq", "", "")
|
||||
cmd.SetArgs(tc.args)
|
||||
var got error
|
||||
cmd.RunE = func(c *cobra.Command, _ []string) error {
|
||||
|
|
@ -144,3 +180,61 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckFormatFlag_InvalidValueRejected(t *testing.T) {
|
||||
for _, v := range []string{"text", "yaml", "xml", "table"} {
|
||||
v := v
|
||||
t.Run(v, func(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().String("format", "", "")
|
||||
_ = cmd.Flags().Set("format", v)
|
||||
_, err := CheckFormatFlag(cmd)
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for --format %q", v)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "human | json | ndjson") {
|
||||
t.Errorf("expected enum hint for --format %q; got %v", v, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckFormatFlag_HumanAccepted(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().String("format", "", "")
|
||||
_ = cmd.Flags().Set("format", "human")
|
||||
o, err := CheckFormatFlag(cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if o.Mode != FormatHuman {
|
||||
t.Errorf("got %v, want FormatHuman", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromEnv_AppliesWEKNORA_FORMAT(t *testing.T) {
|
||||
t.Setenv("WEKNORA_FORMAT", "ndjson")
|
||||
o := &FormatOptions{}
|
||||
o.FromEnv()
|
||||
if o.Mode != FormatNDJSON {
|
||||
t.Errorf("expected FormatNDJSON from env; got %v", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromEnv_PrecedenceFlagOverridesEnv(t *testing.T) {
|
||||
t.Setenv("WEKNORA_FORMAT", "ndjson")
|
||||
o := &FormatOptions{Mode: FormatJSON}
|
||||
o.FromEnv()
|
||||
if o.Mode != FormatJSON {
|
||||
t.Errorf("flag should win over env; got %v", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromEnv_InvalidValueIgnored(t *testing.T) {
|
||||
t.Setenv("WEKNORA_FORMAT", "yaml")
|
||||
o := &FormatOptions{}
|
||||
o.FromEnv()
|
||||
if o.Mode != "" {
|
||||
t.Errorf("invalid env should be ignored; got %v", o.Mode)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ func AddLogLevelFlag(cmd *cobra.Command) {
|
|||
//
|
||||
// Invalid env values fall through to the next priority (no error — env is
|
||||
// best-effort). The stderr writer is retained in the signature for symmetry
|
||||
// with ApplyLogLevel callers but is unused in v0.6.
|
||||
// with ApplyLogLevel callers but is unused at the OS level.
|
||||
func ResolveLogLevel(cmd *cobra.Command, _ io.Writer) (string, bool) {
|
||||
// Priority 1: explicit --log-level flag.
|
||||
if cmd != nil {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package mcp
|
|||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
|
@ -10,10 +11,57 @@ import (
|
|||
|
||||
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/sse"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// toolErrorResult builds an error CallToolResult with IsError=true, a
|
||||
// human-readable text fallback (Content), and the error envelope payload
|
||||
// (StructuredContent). Reuses cmdutil.ErrorToDetail so the hint / retry /
|
||||
// risk / detail fallback table stays single-source.
|
||||
//
|
||||
// Returns nil when err is nil; callers should only invoke on a real error.
|
||||
//
|
||||
// CAVEAT (go-sdk v1.6.0): SetError(err) clobbers Content; we manually
|
||||
// build CallToolResult instead.
|
||||
func toolErrorResult(err error) *mcpsdk.CallToolResult {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
detail := cmdutil.ErrorToDetail(err)
|
||||
textLine := detail.Type + ": " + detail.Message
|
||||
if detail.Hint != "" {
|
||||
textLine += "\nhint: " + detail.Hint
|
||||
}
|
||||
if detail.RetryCommand != "" {
|
||||
textLine += "\nretry: " + detail.RetryCommand
|
||||
}
|
||||
// StructuredContent accepts any; pass *ErrDetail directly (no round-trip).
|
||||
return &mcpsdk.CallToolResult{
|
||||
IsError: true,
|
||||
Content: []mcpsdk.Content{&mcpsdk.TextContent{Text: textLine}},
|
||||
StructuredContent: detail,
|
||||
}
|
||||
}
|
||||
|
||||
// successResult builds a CallToolResult with StructuredContent = payload.
|
||||
// Using Out=any in all handlers disables the SDK auto-marshal path (which
|
||||
// would overwrite our StructuredContent with a zero-struct when the handler
|
||||
// returns a typed nil). We manually populate both StructuredContent and a
|
||||
// text Content fallback so the shape is identical on success and error.
|
||||
func successResult(payload any) *mcpsdk.CallToolResult {
|
||||
return &mcpsdk.CallToolResult{
|
||||
StructuredContent: payload,
|
||||
Content: []mcpsdk.Content{&mcpsdk.TextContent{Text: marshalToString(payload)}},
|
||||
}
|
||||
}
|
||||
|
||||
func marshalToString(v any) string {
|
||||
b, _ := json.Marshal(v)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Narrow per-domain service interfaces. ServiceClient (server.go) embeds
|
||||
// them all; *sdk.Client satisfies the union implicitly.
|
||||
|
||||
|
|
@ -61,6 +109,13 @@ type agentInvokeService interface {
|
|||
// is a deliberate API expansion - the agent-callable surface is the
|
||||
// reason this CLI ships an MCP server, not its CLI command list, so this
|
||||
// list must be maintained by hand.
|
||||
//
|
||||
// TODO(v0.8): add OutputSchema to each mcpsdk.Tool registration so agents
|
||||
// can type-check responses without structural probing. Currently omitted
|
||||
// because the Out type is `any` on all handlers (required to suppress the
|
||||
// SDK's auto-marshal which clobbers our manually-populated StructuredContent).
|
||||
// When go-sdk exposes a typed OutputSchema field independent of the handler
|
||||
// Out type, populate it from the corresponding *Output struct.
|
||||
func registerTools(server *mcpsdk.Server, svc ServiceClient) {
|
||||
addKBList(server, svc)
|
||||
addKBView(server, svc)
|
||||
|
|
@ -86,15 +141,15 @@ func addKBList(server *mcpsdk.Server, svc knowledgeBaseService) {
|
|||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "kb_list",
|
||||
Description: "List all knowledge bases visible to the active WeKnora tenant. No arguments. Returns items[]: each item carries id, name, description, knowledge_count, is_pinned, updated_at - useful for selecting a kb_id to pass to other tools.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ kbListInput) (*mcpsdk.CallToolResult, kbListOutput, error) {
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ kbListInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
items, err := svc.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
return nil, kbListOutput{}, fmt.Errorf("list knowledge bases: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "list knowledge bases")), nil, nil
|
||||
}
|
||||
if items == nil {
|
||||
items = []sdk.KnowledgeBase{}
|
||||
}
|
||||
return nil, kbListOutput{Items: items}, nil
|
||||
return successResult(kbListOutput{Items: items}), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -108,15 +163,15 @@ func addKBView(server *mcpsdk.Server, svc knowledgeBaseService) {
|
|||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "kb_view",
|
||||
Description: "Fetch a knowledge base by ID. Returns the full record including chunking config, embedding/summary model IDs, knowledge_count, and chunk_count.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in kbViewInput) (*mcpsdk.CallToolResult, *sdk.KnowledgeBase, error) {
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in kbViewInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.KBID == "" {
|
||||
return nil, nil, fmt.Errorf("kb_id is required")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
|
||||
}
|
||||
kb, err := svc.GetKnowledgeBase(ctx, in.KBID)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("get knowledge base: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "get knowledge base")), nil, nil
|
||||
}
|
||||
return nil, kb, nil
|
||||
return successResult(kb), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -146,9 +201,9 @@ func addDocList(server *mcpsdk.Server, svc knowledgeService) {
|
|||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "doc_list",
|
||||
Description: "List documents in a knowledge base, with pagination and optional filters (parse-status, keyword, file_type, source, tag_id, start_time/end_time on updated_at). Returns items[] with id, file_name, title, parse_status, size, updated_at - plus the page/total metadata.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docListInput) (*mcpsdk.CallToolResult, docListOutput, error) {
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docListInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.KBID == "" {
|
||||
return nil, docListOutput{}, fmt.Errorf("kb_id is required")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
|
||||
}
|
||||
page := in.Page
|
||||
if page < 1 {
|
||||
|
|
@ -159,7 +214,7 @@ func addDocList(server *mcpsdk.Server, svc knowledgeService) {
|
|||
size = 20
|
||||
}
|
||||
if size > 1000 {
|
||||
return nil, docListOutput{}, fmt.Errorf("page_size must be in 1..1000")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "page_size must be in 1..1000")), nil, nil
|
||||
}
|
||||
filter := sdk.KnowledgeListFilter{
|
||||
ParseStatus: in.Status,
|
||||
|
|
@ -171,25 +226,25 @@ func addDocList(server *mcpsdk.Server, svc knowledgeService) {
|
|||
if in.StartTime != "" {
|
||||
t, err := time.Parse(time.RFC3339, in.StartTime)
|
||||
if err != nil {
|
||||
return nil, docListOutput{}, fmt.Errorf("start_time must be RFC3339 (e.g. 2006-01-02T15:04:05Z), got %q", in.StartTime)
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("start_time must be RFC3339 (e.g. 2006-01-02T15:04:05Z), got %q", in.StartTime))), nil, nil
|
||||
}
|
||||
filter.StartTime = t
|
||||
}
|
||||
if in.EndTime != "" {
|
||||
t, err := time.Parse(time.RFC3339, in.EndTime)
|
||||
if err != nil {
|
||||
return nil, docListOutput{}, fmt.Errorf("end_time must be RFC3339 (e.g. 2006-01-02T15:04:05Z), got %q", in.EndTime)
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("end_time must be RFC3339 (e.g. 2006-01-02T15:04:05Z), got %q", in.EndTime))), nil, nil
|
||||
}
|
||||
filter.EndTime = t
|
||||
}
|
||||
items, total, err := svc.ListKnowledgeWithFilter(ctx, in.KBID, page, size, filter)
|
||||
if err != nil {
|
||||
return nil, docListOutput{}, fmt.Errorf("list documents: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "list documents")), nil, nil
|
||||
}
|
||||
if items == nil {
|
||||
items = []sdk.Knowledge{}
|
||||
}
|
||||
return nil, docListOutput{Items: items, Page: page, PageSize: size, Total: total}, nil
|
||||
return successResult(docListOutput{Items: items, Page: page, PageSize: size, Total: total}), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -203,15 +258,15 @@ func addDocView(server *mcpsdk.Server, svc knowledgeService) {
|
|||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "doc_view",
|
||||
Description: "Fetch a single document by ID. Returns the Knowledge record (file_name, title, type, parse_status, size, embedding_model_id, source URL if any, etc.).",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docViewInput) (*mcpsdk.CallToolResult, *sdk.Knowledge, error) {
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docViewInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.DocID == "" {
|
||||
return nil, nil, fmt.Errorf("doc_id is required")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
|
||||
}
|
||||
k, err := svc.GetKnowledge(ctx, in.DocID)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("get knowledge: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "get knowledge")), nil, nil
|
||||
}
|
||||
return nil, k, nil
|
||||
return successResult(k), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -242,30 +297,30 @@ func addDocDownload(server *mcpsdk.Server, svc knowledgeService) {
|
|||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "doc_download",
|
||||
Description: "Download a document's raw bytes by ID. Capped at 1 MiB per call - for larger documents, use search_chunks to find the relevant excerpts. is_base64 reports whether content was base64-encoded (heuristic: presence of NUL byte in the first 512 bytes).",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, docDownloadOutput, error) {
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.DocID == "" {
|
||||
return nil, docDownloadOutput{}, fmt.Errorf("doc_id is required")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
|
||||
}
|
||||
name, body, err := svc.OpenKnowledgeFile(ctx, in.DocID)
|
||||
if err != nil {
|
||||
return nil, docDownloadOutput{}, fmt.Errorf("open knowledge file: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "open knowledge file")), nil, nil
|
||||
}
|
||||
defer body.Close()
|
||||
buf, err := io.ReadAll(io.LimitReader(body, maxDocDownloadBytes+1))
|
||||
if err != nil {
|
||||
return nil, docDownloadOutput{}, fmt.Errorf("read knowledge file: %w", err)
|
||||
return toolErrorResult(cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read knowledge file")), nil, nil
|
||||
}
|
||||
if len(buf) > maxDocDownloadBytes {
|
||||
return nil, docDownloadOutput{}, fmt.Errorf("document exceeds the %d-byte per-call cap; use search_chunks for excerpts", maxDocDownloadBytes)
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("document exceeds the %d-byte per-call cap; use search_chunks for excerpts", maxDocDownloadBytes))), nil, nil
|
||||
}
|
||||
content, isBase64 := encodeDownload(buf)
|
||||
return nil, docDownloadOutput{
|
||||
return successResult(docDownloadOutput{
|
||||
DocID: in.DocID,
|
||||
FileName: name,
|
||||
Bytes: len(buf),
|
||||
Content: content,
|
||||
IsBase64: isBase64,
|
||||
}, nil
|
||||
}), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -296,17 +351,17 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
|
|||
Description: "Hybrid (vector + keyword) retrieval against a knowledge base. Returns the top chunks ranked by RRF; use this before chat to ground an answer in cited context. Results include knowledge_id, content, score - feed back into chat as context or display directly.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in searchChunksInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.KBID == "" {
|
||||
return nil, nil, fmt.Errorf("kb_id is required")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
|
||||
}
|
||||
if strings.TrimSpace(in.Query) == "" {
|
||||
return nil, nil, fmt.Errorf("query cannot be empty")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "query cannot be empty")), nil, nil
|
||||
}
|
||||
limit := in.Limit
|
||||
if limit < 1 {
|
||||
limit = 10
|
||||
}
|
||||
if limit > 1000 {
|
||||
return nil, nil, fmt.Errorf("limit must be in 1..1000")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "limit must be in 1..1000")), nil, nil
|
||||
}
|
||||
results, err := svc.HybridSearch(ctx, in.KBID, &sdk.SearchParams{
|
||||
QueryText: in.Query,
|
||||
|
|
@ -315,7 +370,7 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
|
|||
KeywordThreshold: in.KeywordThreshold,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("hybrid search: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "hybrid search")), nil, nil
|
||||
}
|
||||
if len(results) > limit {
|
||||
results = results[:limit]
|
||||
|
|
@ -323,7 +378,7 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
|
|||
if results == nil {
|
||||
results = []*sdk.SearchResult{}
|
||||
}
|
||||
return nil, searchChunksOutput{Results: results}, nil
|
||||
return successResult(searchChunksOutput{Results: results}), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -351,16 +406,16 @@ func addChat(server *mcpsdk.Server, svc chatService) {
|
|||
Description: "Stream a RAG answer from the LLM, grounded in the given knowledge base. The SSE stream is accumulated server-side (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the full accumulated response once the stream completes. Pass session_id to continue a multi-turn conversation; otherwise a fresh session is auto-created.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chatInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.KBID == "" {
|
||||
return nil, nil, fmt.Errorf("kb_id is required")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")), nil, nil
|
||||
}
|
||||
if strings.TrimSpace(in.Query) == "" {
|
||||
return nil, nil, fmt.Errorf("query cannot be empty")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "query cannot be empty")), nil, nil
|
||||
}
|
||||
sessionID := in.SessionID
|
||||
if sessionID == "" {
|
||||
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp chat"})
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create chat session: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "create chat session")), nil, nil
|
||||
}
|
||||
sessionID = sess.ID
|
||||
}
|
||||
|
|
@ -376,16 +431,16 @@ func addChat(server *mcpsdk.Server, svc chatService) {
|
|||
return nil
|
||||
})
|
||||
if streamErr != nil {
|
||||
return nil, nil, fmt.Errorf("knowledge qa stream: %w", streamErr)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(streamErr, "knowledge qa stream")), nil, nil
|
||||
}
|
||||
if !acc.Done() {
|
||||
return nil, nil, fmt.Errorf("stream ended without a terminal event")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")), nil, nil
|
||||
}
|
||||
sid := acc.SessionID
|
||||
if sid == "" {
|
||||
sid = sessionID
|
||||
}
|
||||
return nil, chatOutput{
|
||||
return successResult(chatOutput{
|
||||
Answer: acc.Result(),
|
||||
References: acc.References,
|
||||
Thinking: acc.Thinking(),
|
||||
|
|
@ -393,7 +448,7 @@ func addChat(server *mcpsdk.Server, svc chatService) {
|
|||
AssistantMessageID: acc.AssistantMessageID,
|
||||
KBID: in.KBID,
|
||||
Query: in.Query,
|
||||
}, nil
|
||||
}), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -409,15 +464,15 @@ func addAgentList(server *mcpsdk.Server, svc agentService) {
|
|||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "agent_list",
|
||||
Description: "List the tenant's custom agents. Returns items[] with id, name, description, is_builtin - use to discover an agent_id before agent_invoke.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ agentListInput) (*mcpsdk.CallToolResult, agentListOutput, error) {
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ agentListInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
items, err := svc.ListAgents(ctx)
|
||||
if err != nil {
|
||||
return nil, agentListOutput{}, fmt.Errorf("list agents: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "list agents")), nil, nil
|
||||
}
|
||||
if items == nil {
|
||||
items = []sdk.Agent{}
|
||||
}
|
||||
return nil, agentListOutput{Items: items}, nil
|
||||
return successResult(agentListOutput{Items: items}), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -445,10 +500,10 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
|
|||
Description: "Run a query through a custom agent (system prompt + tool allow-list + KB scope). The agent's SSE stream is accumulated server-side (MCP tools/call has no standard partial-response, so this is NOT streaming); the tool returns the final accumulated response once the stream completes.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in agentInvokeInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.AgentID == "" {
|
||||
return nil, nil, fmt.Errorf("agent_id is required")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "agent_id is required")), nil, nil
|
||||
}
|
||||
if strings.TrimSpace(in.Query) == "" {
|
||||
return nil, nil, fmt.Errorf("query cannot be empty")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "query cannot be empty")), nil, nil
|
||||
}
|
||||
acc := &sse.AgentAccumulator{}
|
||||
req := &sdk.AgentQARequest{
|
||||
|
|
@ -463,7 +518,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
|
|||
if sessionID == "" {
|
||||
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp agent_invoke"})
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create chat session: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "create chat session")), nil, nil
|
||||
}
|
||||
sessionID = sess.ID
|
||||
}
|
||||
|
|
@ -472,12 +527,12 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
|
|||
return nil
|
||||
})
|
||||
if streamErr != nil {
|
||||
return nil, nil, fmt.Errorf("agent-chat stream: %w", streamErr)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(streamErr, "agent-chat stream")), nil, nil
|
||||
}
|
||||
if !acc.Done() {
|
||||
return nil, nil, fmt.Errorf("stream ended without a terminal event")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")), nil, nil
|
||||
}
|
||||
return nil, agentInvokeOutput{
|
||||
return successResult(agentInvokeOutput{
|
||||
Answer: acc.Answer(),
|
||||
References: acc.References,
|
||||
ToolEvents: acc.ToolEvents,
|
||||
|
|
@ -485,7 +540,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
|
|||
SessionID: sessionID,
|
||||
AgentID: in.AgentID,
|
||||
Query: in.Query,
|
||||
}, nil
|
||||
}), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -515,9 +570,9 @@ func addChunkList(server *mcpsdk.Server, svc chunkListService) {
|
|||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "chunk_list",
|
||||
Description: "List chunks of a knowledge document for RAG retrieval debug. Returns at most `limit` chunks starting from ChunkIndex 0; if total chunks exceed limit, truncated_at_limit=true signals the agent to fall back to the CLI for paginated retrieval.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chunkListInput) (*mcpsdk.CallToolResult, chunkListOutput, error) {
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in chunkListInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.DocID == "" {
|
||||
return nil, chunkListOutput{}, fmt.Errorf("doc_id is required")
|
||||
return toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required")), nil, nil
|
||||
}
|
||||
// `limit` is typed as int by chunkListInput, so the SDK rejects
|
||||
// non-numeric values at schema validation (e.g. "limit":"50")
|
||||
|
|
@ -532,16 +587,16 @@ func addChunkList(server *mcpsdk.Server, svc chunkListService) {
|
|||
}
|
||||
chunks, total, err := svc.ListKnowledgeChunks(ctx, in.DocID, 1, limit)
|
||||
if err != nil {
|
||||
return nil, chunkListOutput{}, fmt.Errorf("list knowledge chunks: %w", err)
|
||||
return toolErrorResult(cmdutil.WrapHTTP(err, "list knowledge chunks")), nil, nil
|
||||
}
|
||||
if chunks == nil {
|
||||
chunks = []sdk.Chunk{}
|
||||
}
|
||||
return nil, chunkListOutput{
|
||||
return successResult(chunkListOutput{
|
||||
Chunks: chunks,
|
||||
Total: total,
|
||||
TruncatedAtLimit: total > int64(limit),
|
||||
}, nil
|
||||
}), nil, nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,104 @@
|
|||
package mcp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// TestToolErrorResult_TypedError_PopulatesStructuredContent verifies the
|
||||
// helper maps a typed cmdutil.Error to MCP StructuredContent as *output.ErrDetail.
|
||||
func TestToolErrorResult_TypedError_PopulatesStructuredContent(t *testing.T) {
|
||||
err := cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no creds")
|
||||
res := toolErrorResult(err)
|
||||
if !res.IsError {
|
||||
t.Errorf("expected IsError true")
|
||||
}
|
||||
if res.StructuredContent == nil {
|
||||
t.Fatal("expected StructuredContent populated")
|
||||
}
|
||||
sc, ok := res.StructuredContent.(*output.ErrDetail)
|
||||
if !ok {
|
||||
t.Fatalf("StructuredContent has unexpected type %T", res.StructuredContent)
|
||||
}
|
||||
if sc.Type != "auth.unauthenticated" {
|
||||
t.Errorf("type: got %v want auth.unauthenticated", sc.Type)
|
||||
}
|
||||
// retry_command should fall back to "weknora auth login" via cmdutil default
|
||||
if sc.RetryCommand != "weknora auth login" {
|
||||
t.Errorf("retry_command: got %v", sc.RetryCommand)
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolErrorResult_TextFallback verifies the human-readable Content[0]
|
||||
// contains code + message + (hint? + retry?) lines.
|
||||
func TestToolErrorResult_TextFallback(t *testing.T) {
|
||||
err := cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb_id is required")
|
||||
res := toolErrorResult(err)
|
||||
if len(res.Content) == 0 {
|
||||
t.Fatal("expected Content[0]")
|
||||
}
|
||||
// Assertion is best-effort on the text shape; exact prose may vary
|
||||
// with hint/retry defaults. Lock the type code prefix.
|
||||
text := contentText(t, res.Content[0])
|
||||
if !strings.Contains(text, "local.kb_id_required: kb_id is required") {
|
||||
t.Errorf("text fallback missing code:message; got %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
// contentText extracts the Text field from an mcpsdk.Content value.
|
||||
// Lives in the test file to avoid leaking helpers into production.
|
||||
func contentText(t *testing.T, c any) string {
|
||||
t.Helper()
|
||||
// Direct assertion to the concrete type used by toolErrorResult.
|
||||
if tc, ok := c.(*mcpsdk.TextContent); ok {
|
||||
return tc.Text
|
||||
}
|
||||
// Fallback: some go-sdk versions may expose a GetText() method.
|
||||
if tc, ok := c.(interface{ GetText() string }); ok {
|
||||
return tc.GetText()
|
||||
}
|
||||
t.Fatalf("cannot extract text from Content of type %T", c)
|
||||
return ""
|
||||
}
|
||||
|
||||
// TestToolErrorResult_IsErrorFlagSet verifies IsError is always true.
|
||||
func TestToolErrorResult_IsErrorFlagSet(t *testing.T) {
|
||||
res := toolErrorResult(cmdutil.NewError(cmdutil.CodeInputMissingFlag, "doc_id is required"))
|
||||
if !res.IsError {
|
||||
t.Error("expected IsError=true")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolErrorResult_ContentPresent verifies Content slice is non-empty.
|
||||
func TestToolErrorResult_ContentPresent(t *testing.T) {
|
||||
res := toolErrorResult(cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "page_size must be in 1..1000"))
|
||||
if len(res.Content) == 0 {
|
||||
t.Error("expected at least one Content item")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToolErrorResult_NetworkError verifies a network error code round-trips
|
||||
// through toolErrorResult with the correct type in StructuredContent.
|
||||
func TestToolErrorResult_NetworkError(t *testing.T) {
|
||||
err := cmdutil.NewError(cmdutil.CodeNetworkError, "dial failed")
|
||||
res := toolErrorResult(err)
|
||||
if !res.IsError {
|
||||
t.Error("expected IsError=true")
|
||||
}
|
||||
sc, ok := res.StructuredContent.(*output.ErrDetail)
|
||||
if !ok {
|
||||
t.Fatalf("StructuredContent has unexpected type %T", res.StructuredContent)
|
||||
}
|
||||
if sc.Type != "network.error" {
|
||||
t.Errorf("type: got %v want network.error", sc.Type)
|
||||
}
|
||||
}
|
||||
|
||||
// Suppress unused-import warning if sdk isn't used in this file.
|
||||
var _ = sdk.KnowledgeBase{}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
package output
|
||||
|
||||
import "io"
|
||||
|
||||
// BatchItem is one per-id outcome in a batch operation envelope (§4.5).
|
||||
type BatchItem struct {
|
||||
ID string `json:"id"`
|
||||
OK bool `json:"ok"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *ErrDetail `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// WriteBatchEnvelope writes a batch operation envelope per §4.5.
|
||||
//
|
||||
// Wire shape: {ok, data:[BatchItem...], meta:{count, successes, failures}, profile?}.
|
||||
// Top-level ok = (failures == 0). Per-id ok reflects each item's outcome.
|
||||
// Even when all items fail, the response stays in success-envelope shape
|
||||
// (data array, not error envelope) so agents can iterate detail per id.
|
||||
// profile is the resolved profile name for the invocation; empty string omits the field.
|
||||
func WriteBatchEnvelope(w io.Writer, items []BatchItem, indent bool, profile string) error {
|
||||
if items == nil {
|
||||
items = []BatchItem{}
|
||||
}
|
||||
successes, failures := 0, 0
|
||||
for _, it := range items {
|
||||
if it.OK {
|
||||
successes++
|
||||
} else {
|
||||
failures++
|
||||
}
|
||||
}
|
||||
env := Envelope{
|
||||
OK: failures == 0,
|
||||
Data: items,
|
||||
Meta: &Meta{
|
||||
Count: len(items),
|
||||
Successes: &successes,
|
||||
Failures: &failures,
|
||||
},
|
||||
Notice: GetNotice(),
|
||||
Profile: profile,
|
||||
}
|
||||
return writeJSON(w, env, indent)
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
package output_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
func TestWriteBatchEnvelope_AllSuccess(t *testing.T) {
|
||||
items := []output.BatchItem{
|
||||
{ID: "id1", OK: true, Result: map[string]string{"deleted_at": "2026-05-20T00:00:00Z"}},
|
||||
{ID: "id2", OK: true, Result: map[string]string{"deleted_at": "2026-05-20T00:00:00Z"}},
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := output.WriteBatchEnvelope(&buf, items, false, ""); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, `"ok":true`) {
|
||||
t.Errorf("expected ok:true; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"successes":2`) {
|
||||
t.Errorf("expected successes:2; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"count":2`) {
|
||||
t.Errorf("expected count:2; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBatchEnvelope_PartialFailure(t *testing.T) {
|
||||
items := []output.BatchItem{
|
||||
{ID: "id1", OK: true, Result: map[string]string{"deleted_at": "2026-05-20T00:00:00Z"}},
|
||||
{ID: "id2", OK: false, Error: &output.ErrDetail{Type: "resource.not_found", Message: "id2 not found"}},
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := output.WriteBatchEnvelope(&buf, items, false, ""); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, `"ok":false`) {
|
||||
t.Errorf("expected ok:false (partial failure); got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"successes":1`) || !strings.Contains(got, `"failures":1`) {
|
||||
t.Errorf("expected counts; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"type":"resource.not_found"`) {
|
||||
t.Errorf("expected per-item error; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBatchEnvelope_EmptyItems_EmitsEmptyArray(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
if err := output.WriteBatchEnvelope(&buf, nil, false, ""); err != nil {
|
||||
t.Fatalf("unexpected: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if strings.Contains(got, `"data":null`) {
|
||||
t.Errorf("empty items must marshal to [], not null; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"data":[]`) {
|
||||
t.Errorf("expected data:[]; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"ok":true`) {
|
||||
t.Errorf("expected ok:true for empty batch; got %q", got)
|
||||
}
|
||||
// count:0 is omitted by omitempty; assert no non-zero count appears.
|
||||
if strings.Contains(got, `"count":`) {
|
||||
// If count key is present, it must not be a non-zero value.
|
||||
if !strings.Contains(got, `"count":0`) {
|
||||
t.Errorf("count key present but not zero; got %q", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteBatchEnvelope_AllFail(t *testing.T) {
|
||||
items := []output.BatchItem{
|
||||
{ID: "id1", OK: false, Error: &output.ErrDetail{Type: "auth.forbidden", Message: "no perm"}},
|
||||
{ID: "id2", OK: false, Error: &output.ErrDetail{Type: "resource.not_found", Message: "missing"}},
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := output.WriteBatchEnvelope(&buf, items, false, ""); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
got := buf.String()
|
||||
if !strings.Contains(got, `"ok":false`) {
|
||||
t.Errorf("expected ok:false; got %q", got)
|
||||
}
|
||||
// 全失败仍走 batch envelope shape,不退化到 ErrorEnvelope.
|
||||
// An ErrorEnvelope has a top-level "error" key alongside "ok"; a batch
|
||||
// envelope has a top-level "data" array. Check that "data":[ is present.
|
||||
if !strings.Contains(got, `"data":[`) {
|
||||
t.Errorf("batch all-fail should still use batch shape (data array), not error envelope; got %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"failures":2`) {
|
||||
t.Errorf("expected failures:2; got %q", got)
|
||||
}
|
||||
// H3b invariant: successes:0 must appear even when all items failed.
|
||||
// (*int semantics: nil is omitted; &0 is serialized as 0.)
|
||||
if !strings.Contains(got, `"successes":0`) {
|
||||
t.Errorf("all-fail batch must emit successes:0 (not omit it); invariant successes+failures==count would be broken; got %q", got)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue