e623e8208f
Removes the entire envelope machinery now that every success path
emits bare JSON:
- cli/internal/format/envelope.go (Envelope, Success, Failure,
SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice,
VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests.
- cli/internal/format/filter.go envelope-specific helpers
(WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter,
filterDataPayload, filterObjectData); the reusable
filterArrayItems / filterObjectKeys / writeJQ stay for bare.go.
- cli/internal/cmdutil/exporter.go + tests (envelope-only).
- cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody +
operationRiskOf + Error.OperationRisk field + OperationRisk struct.
Error path: all errors now go to stderr via cmdutil.PrintError in
`code: message\nhint: ...` form, regardless of --json. Stdout stays
empty (or holds the partial-success the command already wrote) so
downstream `--json | jq` pipelines never have to filter error shapes
out of the success stream. Typed exit codes (3 auth.* / 4
resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.*
+ network.* / 10 input.confirmation_required) carry the failure
class for agents that branch on it.
Acceptance contract:
- envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden).
- testdata/envelopes/ → testdata/wire/.
- Error-path cases assert the typed code substring on stderr.
- Orphan whoami.*.json goldens deleted.
AGENTS.md + README.md rewritten for the bare-data contract:
- Drop envelope schema section + dry-run rule.
- Document bare JSON on stdout + `code: msg\nhint: …` on stderr.
- ADR-3 reframed around bare data and why error separation matters
for `--json | jq` pipelines.
WriteJSONFiltered short-circuits to WriteJSON when both filters are
empty (skip the marshal-buffer round-trip for the common case).
Final review pass:
- Fix wire-contract bug: `--json id,name` (space form) is broken by
pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the
field-discovery help text all switched to `--json=id,name`.
- Fix `weknora api --jq` silently ignored: api.go now routes through
WriteJSONFiltered with jopts.JQ.
- AGENTS.md: drop the false claim that `auth logout` honors `-y`
(logout is local-only with no ConfirmDestructive guard); list the
actual destructive commands instead.
- Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape
(was still parsing `out["data"]` / `env["ok"]`).
- Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated
`format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields,
jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the
format import from 22 cmd/* files.
- Delete single-caller `cmdutil.MustRequireFlag`; inline as
`_ = cmd.MarkFlagRequired(...)` everywhere.
- Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the
only write command relying on runtime --name validation while
`context add` already used the cobra-level mark.
- `context use`: register `--json` / `--jq` (was always emitting JSON
unconditionally with no human path and no flag — diverged from
every other write command); human mode now prints
`✓ Switched context to X (was Y)`.
- Replace per-package `confirmPrompter` / `scriptedConfirm` /
`errPrompter` test doubles with `testutil.ConfirmPrompter`.
- Rename `chatService` → `ChatService` (export to match siblings
`ListService` / `ViewService`); rename `printUploadSuccess` →
`renderUploadSuccess` (siblings use `render*`).
- `defaultHint(CodeResourceNotFound)`: drop the hardcoded
"list available with `weknora kb list`" — misleading on agent /
doc / session 404. Replaced with "verify the resource ID and try
again".
- Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only"
historical tags from production comments and a few test
descriptions.
127 lines
4.1 KiB
Go
127 lines
4.1 KiB
Go
package search
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
"text/tabwriter"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/aiclient"
|
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
|
"github.com/Tencent/WeKnora/cli/internal/text"
|
|
sdk "github.com/Tencent/WeKnora/client"
|
|
)
|
|
|
|
// kbSearchFields enumerates the fields surfaced for `--json` discovery on
|
|
// `search kb`. Subset of KnowledgeBase suitable for list/filter results.
|
|
var kbSearchFields = []string{
|
|
"id", "name", "type", "description",
|
|
"is_temporary", "is_pinned",
|
|
"embedding_model_id", "summary_model_id",
|
|
"knowledge_count", "chunk_count",
|
|
"is_processing", "processing_count",
|
|
"created_at", "updated_at",
|
|
}
|
|
|
|
type KBSearchOptions struct {
|
|
Query string
|
|
Limit int
|
|
}
|
|
|
|
// KBSearchService is the narrow SDK surface this command depends on.
|
|
// Server has no fuzzy-KB-name endpoint; the CLI filters ListKnowledgeBases
|
|
// client-side. Acceptable because tenants typically have ≪ 1000 KBs.
|
|
type KBSearchService interface {
|
|
ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error)
|
|
}
|
|
|
|
// NewCmdKB builds `weknora search kb "<query>"` — substring + case-insensitive
|
|
// match across KB names and descriptions visible to the active context.
|
|
// Results are sorted by name length (shortest first; usually the closest
|
|
// hit) for deterministic output.
|
|
func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
|
|
opts := &KBSearchOptions{}
|
|
cmd := &cobra.Command{
|
|
Use: `kb "<query>"`,
|
|
Short: "Find knowledge bases by name or description (client-side substring match)",
|
|
Example: ` weknora search kb "marketing"
|
|
weknora search kb "team" --limit 5 --json`,
|
|
Args: cobra.ExactArgs(1),
|
|
RunE: func(c *cobra.Command, args []string) error {
|
|
opts.Query = strings.TrimSpace(args[0])
|
|
if opts.Query == "" {
|
|
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
|
|
}
|
|
if opts.Limit < 1 || opts.Limit > 1000 {
|
|
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--limit must be between 1 and 1000")
|
|
}
|
|
jopts, err := cmdutil.CheckJSONFlags(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cli, err := f.Client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return runKBSearch(c.Context(), opts, jopts, cli)
|
|
},
|
|
}
|
|
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
|
|
cmdutil.AddJSONFlags(cmd, kbSearchFields)
|
|
aiclient.SetAgentHelp(cmd, "Lists KBs whose name or description contains the query (case-insensitive). Useful to discover --kb identifiers before running search chunks / doc list.")
|
|
return cmd
|
|
}
|
|
|
|
func runKBSearch(ctx context.Context, opts *KBSearchOptions, jopts *cmdutil.JSONOptions, svc KBSearchService) error {
|
|
items, err := svc.ListKnowledgeBases(ctx)
|
|
if err != nil {
|
|
return cmdutil.WrapHTTP(err, "list knowledge bases")
|
|
}
|
|
matches := filterKBs(items, opts.Query)
|
|
if opts.Limit > 0 && len(matches) > opts.Limit {
|
|
matches = matches[:opts.Limit]
|
|
}
|
|
|
|
if jopts.Enabled() {
|
|
if matches == nil {
|
|
matches = []sdk.KnowledgeBase{}
|
|
}
|
|
return jopts.Emit(iostreams.IO.Out, matches)
|
|
}
|
|
if len(matches) == 0 {
|
|
fmt.Fprintln(iostreams.IO.Out, "(no matches)")
|
|
return nil
|
|
}
|
|
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
|
|
fmt.Fprintln(tw, "ID\tNAME\tDOCS")
|
|
for _, kb := range matches {
|
|
name := text.Truncate(50, kb.Name)
|
|
fmt.Fprintf(tw, "%s\t%s\t%s\n", kb.ID, name, text.Pluralize(int(kb.KnowledgeCount), "doc"))
|
|
}
|
|
return tw.Flush()
|
|
}
|
|
|
|
// filterKBs returns the KBs whose name or description contains q (case-
|
|
// insensitive), sorted by name length so the most-likely match shows
|
|
// first. Ties broken alphabetically for determinism.
|
|
func filterKBs(items []sdk.KnowledgeBase, q string) []sdk.KnowledgeBase {
|
|
needle := strings.ToLower(q)
|
|
out := make([]sdk.KnowledgeBase, 0, len(items))
|
|
for _, kb := range items {
|
|
if text.ContainsFold(needle, kb.Name, kb.Description) {
|
|
out = append(out, kb)
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool {
|
|
if len(out[i].Name) != len(out[j].Name) {
|
|
return len(out[i].Name) < len(out[j].Name)
|
|
}
|
|
return out[i].Name < out[j].Name
|
|
})
|
|
return out
|
|
}
|