2026-05-12 15:38:01 +00:00
|
|
|
package search
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup
Sweep every CLI output path through the v0.7 envelope contract.
FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.
~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.
Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
failures*}; Successes/Failures *int so explicit zero survives
omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
cmdutil.ClassifyContextErr collapse the three previously-duplicated
multi-delete pipelines (doc / chunk / session) into one call site
pattern. doc upload --recursive uses the same helpers with a per-
file resultFn. Summary error sets Silent:true so the stderr
envelope path doesn't duplicate the stdout batch detail (exit 1
preserved via Code → ExitCode).
ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).
MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.
weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
(stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
envelope so --paginate never emits bare JSON to stdout.
Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.
Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
|
|
|
"encoding/json"
|
2026-05-12 15:38:01 +00:00
|
|
|
"errors"
|
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
|
|
|
|
sdk "github.com/Tencent/WeKnora/client"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type fakeChunksSvc struct {
|
|
|
|
|
results []*sdk.SearchResult
|
|
|
|
|
err error
|
|
|
|
|
gotKB string
|
|
|
|
|
gotQ string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (f *fakeChunksSvc) HybridSearch(_ context.Context, kbID string, p *sdk.SearchParams) ([]*sdk.SearchResult, error) {
|
|
|
|
|
f.gotKB = kbID
|
|
|
|
|
f.gotQ = p.QueryText
|
|
|
|
|
return f.results, f.err
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-21 10:43:18 +00:00
|
|
|
func TestRunSearch_TextOutput(t *testing.T) {
|
2026-05-12 15:38:01 +00:00
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
|
|
|
|
{Score: 0.92, Content: "first chunk", KnowledgeID: "doc-1", MatchType: sdk.MatchTypeVector},
|
|
|
|
|
{Score: 0.81, Content: "second chunk", KnowledgeID: "doc-2", MatchType: sdk.MatchTypeKeyword},
|
|
|
|
|
}}
|
|
|
|
|
opts := &ChunksOptions{Query: "hello", KBID: "kb_abc", Limit: 5}
|
2026-05-21 10:43:18 +00:00
|
|
|
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
2026-05-12 15:38:01 +00:00
|
|
|
|
|
|
|
|
assert.Equal(t, "kb_abc", svc.gotKB)
|
|
|
|
|
assert.Equal(t, "hello", svc.gotQ)
|
|
|
|
|
got := out.String()
|
|
|
|
|
assert.Contains(t, got, "2 result(s) from kb=kb_abc")
|
|
|
|
|
assert.Contains(t, got, "first chunk")
|
|
|
|
|
assert.Contains(t, got, "doc-1")
|
|
|
|
|
}
|
|
|
|
|
|
refactor(cli): delete envelope infrastructure, errors to stderr
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.
2026-05-14 17:51:11 +00:00
|
|
|
// JSON output must surface match_type so machine consumers / agents can
|
2026-05-12 15:38:01 +00:00
|
|
|
// reason about retrieval channels without re-implementing the wire format.
|
2026-05-21 10:43:18 +00:00
|
|
|
// (Text renderer keeps default minimal - diagnostic info opt-in via --format json.)
|
2026-05-12 15:38:01 +00:00
|
|
|
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
|
|
|
|
{Score: 0.9, Content: "x", MatchType: sdk.MatchTypeKeyword},
|
|
|
|
|
}}
|
2026-05-17 17:38:30 +00:00
|
|
|
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
2026-05-12 15:38:01 +00:00
|
|
|
assert.Contains(t, out.String(), `"match_type":1`)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestRunSearch_JSONOutput(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeChunksSvc{results: []*sdk.SearchResult{{Score: 0.9, Content: "x"}}}
|
feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
2026-05-14 15:28:14 +00:00
|
|
|
opts := &ChunksOptions{Query: "q", KBID: "kb1", Limit: 1}
|
2026-05-17 17:38:30 +00:00
|
|
|
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
got := out.String()
|
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup
Sweep every CLI output path through the v0.7 envelope contract.
FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.
~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.
Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
failures*}; Successes/Failures *int so explicit zero survives
omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
cmdutil.ClassifyContextErr collapse the three previously-duplicated
multi-delete pipelines (doc / chunk / session) into one call site
pattern. doc upload --recursive uses the same helpers with a per-
file resultFn. Summary error sets Silent:true so the stderr
envelope path doesn't duplicate the stdout batch detail (exit 1
preserved via Code → ExitCode).
ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).
MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.
weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
(stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
envelope so --paginate never emits bare JSON to stdout.
Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.
Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
|
|
|
var env struct {
|
|
|
|
|
OK bool `json:"ok"`
|
|
|
|
|
Data []*sdk.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")
|
refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
|
|
|
assert.Contains(t, got, `"score":0.9`)
|
2026-05-12 15:38:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestRunSearch_EmptyResults(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeChunksSvc{results: nil}
|
2026-05-21 10:43:18 +00:00
|
|
|
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
2026-05-12 15:38:01 +00:00
|
|
|
assert.Contains(t, out.String(), "(no results)")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Server returns primary matches plus parent/related/nearby enrichment chunks,
|
|
|
|
|
// so the wire response can exceed Limit. CLI must trim to honor the user's
|
refactor(cli): v0.3 cross-cutting cleanup
Cross-cutting findings surfaced by the branch-completion review.
Perf bug:
- Factory.Client closure was not memoized. Factory.ResolveKB internally
calls f.Client() to resolve --kb name → id, then the command's RunE
calls f.Client() again. Two SDK clients, two keyring reads, two
AuthRetryTransport allocations per name-resolved invocation, with
*independent* token state (a refresh in one was invisible to the
other). Switched to sync.Once like Secrets already does.
Silent bug bait:
- cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the
empty case; code returned CodeInputInvalidArgument. Aligned doc to
code (present-but-empty is a bad value, not a missing flag).
Agent contract gaps:
- Five user-facing subcommands lacked SetAgentHelp: auth login /
logout / list / status and chat. Added concise strings with error-
code call-outs so agents can branch without parsing human strings.
Helper extraction (≥3 callers):
- text.KnowledgeDisplayName(fileName, title, id) — byte-identical
formatter that was in both cmd/doc/list.go and cmd/search/docs.go.
Takes fields directly so internal/text stays SDK-free.
- cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the
`Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK
call sites. Sed-driven migration; off-pattern shapes in chat.go
(used streamErr) and cmdutil/kb.go (in-package) hand-edited.
Contract test gains a comment update: post-migration the dominant
pattern is WrapHTTP which the AST scanner skips entirely (only
NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs()
bridge still covers the dynamic codes those paths can yield.
UX consistency:
- cmd/doc/list.go --page-size help now reads "Items per page
(1..1000)" matching cmd/session/list.go. The bounds validation
already enforced 1..1000; the help text was the last drift.
Comment-discipline sweep:
- Deleted the WHAT-only "*Options captures `weknora ...` flag state"
docstring across 23 files (context, kb, auth, doc, session, search,
chat, doctor, link). Where the line carried a real WHY clause
(kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and
dropped only the leading WHAT phrase.
- Stripped third-party project-name attribution from inline comments
and one user-visible flag-help string across ~40 files in cli/cmd
and cli/internal (plus 4 test-file comments). Removed phrases like
"Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style",
"gcloud `--project`", "Stripe pattern", and the embedded GitHub
URLs pointing at those projects. Behavioral descriptions and the
WHY behind each comment are preserved; only the upstream-name
attribution is gone. Inspiration / north-star references belong in
cli/AGENTS.md (the design doc) and commit messages, not scattered
through every file.
Triggered by an audit round that surfaced several false / fragile
parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no
--name flag; "matches gcloud `--project` id-or-name" — gcloud's
--project accepts ID only). Rather than fix them one by one, the
whole category of in-comment external-project references was
stripped uniformly.
2026-05-12 15:42:20 +00:00
|
|
|
// hard-limit contract.
|
2026-05-12 15:38:01 +00:00
|
|
|
func TestRunSearch_LimitHardCap(t *testing.T) {
|
|
|
|
|
out, _ := iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
|
|
|
|
|
{Score: 0.9, Content: "primary 1"},
|
|
|
|
|
{Score: 0.8, Content: "primary 2"},
|
|
|
|
|
{Score: 0.7, Content: "primary 3"},
|
|
|
|
|
{Score: 0, Content: "enrichment parent"}, // server-padded
|
|
|
|
|
{Score: 0, Content: "enrichment nearby"}, // server-padded
|
|
|
|
|
}}
|
2026-05-21 10:43:18 +00:00
|
|
|
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
2026-05-12 15:38:01 +00:00
|
|
|
got := out.String()
|
|
|
|
|
assert.Contains(t, got, "3 result(s)")
|
|
|
|
|
assert.NotContains(t, got, "enrichment parent")
|
|
|
|
|
assert.NotContains(t, got, "enrichment nearby")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestRunSearch_BothChannelsDisabled(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
2026-05-21 10:43:18 +00:00
|
|
|
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeChunksSvc{})
|
2026-05-12 15:38:01 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.Contains(t, err.Error(), "input.invalid_argument")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestRunSearch_ServiceError_Transport(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeChunksSvc{err: assert.AnError}
|
2026-05-21 10:43:18 +00:00
|
|
|
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
2026-05-12 15:38:01 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
var typed *cmdutil.Error
|
|
|
|
|
require.ErrorAs(t, err, &typed)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeNetworkError, typed.Code,
|
|
|
|
|
"non-HTTP-shaped errors classify as network.error so IsTransient picks them up")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestRunSearch_ServiceError_HTTPNotFound(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
|
|
|
|
svc := &fakeChunksSvc{err: errors.New("HTTP error 404: knowledge base not found")}
|
2026-05-21 10:43:18 +00:00
|
|
|
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
|
2026-05-12 15:38:01 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
var typed *cmdutil.Error
|
|
|
|
|
require.ErrorAs(t, err, &typed)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestIndent(t *testing.T) {
|
|
|
|
|
assert.Equal(t, " foo\n bar", indent("foo\nbar", " "))
|
|
|
|
|
assert.Equal(t, "", indent("", " "))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestRunSearch_NilService(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
2026-05-21 10:43:18 +00:00
|
|
|
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil)
|
2026-05-12 15:38:01 +00:00
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.Contains(t, err.Error(), "server.error")
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-29 12:06:53 +00:00
|
|
|
// TestNewCmdChunks_NoKBUsesResolver asserts that `search chunks "<query>"`
|
|
|
|
|
// without --kb no longer fails with cobra's `required flag(s) "kb"`. The
|
|
|
|
|
// command now resolves the KB through the shared flag→env→project-link chain
|
|
|
|
|
// (cmdutil.Factory.ResolveKB), matching `doc list` / `chat`; when nothing
|
|
|
|
|
// resolves it reports the typed local.kb_id_required (exit 1), not a cobra
|
|
|
|
|
// usage error. This is the inverse of the old lock test, which deliberately
|
|
|
|
|
// blocked the link fallback for this read path — the asymmetry with `doc
|
|
|
|
|
// list` was not worth keeping (a non-destructive search is the same risk
|
|
|
|
|
// profile as a list). The destructive `doc delete --all` keeps its explicit
|
|
|
|
|
// --kb rule; that safety guard is unrelated to this path.
|
|
|
|
|
func TestNewCmdChunks_NoKBUsesResolver(t *testing.T) {
|
2026-05-29 12:06:30 +00:00
|
|
|
iostreams.SetForTest(t)
|
2026-05-29 12:06:53 +00:00
|
|
|
t.Setenv("WEKNORA_KB_ID", "") // no ambient KB from env
|
|
|
|
|
t.Chdir(t.TempDir()) // no .weknora project link discoverable
|
2026-05-29 12:06:30 +00:00
|
|
|
cmd := NewCmdChunks(&cmdutil.Factory{
|
2026-05-29 12:06:53 +00:00
|
|
|
// Resolution reaches local.kb_id_required before any client is built,
|
|
|
|
|
// so this must never be invoked; make it loud if it is.
|
|
|
|
|
Client: func() (*sdk.Client, error) { return nil, errors.New("client should not be built") },
|
2026-05-29 12:06:30 +00:00
|
|
|
})
|
|
|
|
|
cmd.SetArgs([]string{"some query"}) // query but no --kb
|
|
|
|
|
cmd.SilenceErrors = true
|
|
|
|
|
cmd.SilenceUsage = true
|
|
|
|
|
err := cmd.Execute()
|
|
|
|
|
require.Error(t, err)
|
2026-05-29 12:06:53 +00:00
|
|
|
assert.NotContains(t, err.Error(), `required flag(s) "kb"`)
|
|
|
|
|
typed := cmdutil.AsError(err)
|
|
|
|
|
require.NotNil(t, typed)
|
|
|
|
|
assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestNewCmdChunks_HonorsKBEnv proves the env fallback is wired: with
|
|
|
|
|
// WEKNORA_KB_ID set and no --kb, KB resolution succeeds (no kb-required
|
|
|
|
|
// error) and the command proceeds to the client step — which here errors,
|
|
|
|
|
// confirming we got past resolution using the env value alone.
|
|
|
|
|
func TestNewCmdChunks_HonorsKBEnv(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
|
|
|
|
t.Setenv("WEKNORA_KB_ID", "kb_from_env")
|
|
|
|
|
cmd := NewCmdChunks(&cmdutil.Factory{
|
|
|
|
|
Client: func() (*sdk.Client, error) { return nil, errors.New("client boom") },
|
|
|
|
|
})
|
|
|
|
|
cmd.SetArgs([]string{"some query"}) // no --kb; env supplies it
|
|
|
|
|
cmd.SilenceErrors = true
|
|
|
|
|
cmd.SilenceUsage = true
|
|
|
|
|
err := cmd.Execute()
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.NotContains(t, err.Error(), "kb is required")
|
|
|
|
|
assert.Contains(t, err.Error(), "client boom")
|
2026-05-29 12:06:30 +00:00
|
|
|
}
|
|
|
|
|
|
2026-05-12 15:38:01 +00:00
|
|
|
func TestNewCmdChunks_RequiresQuery(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
|
|
|
|
cmd := NewCmdChunks(&cmdutil.Factory{
|
|
|
|
|
Client: func() (*sdk.Client, error) { return nil, nil },
|
|
|
|
|
})
|
|
|
|
|
cmd.SetArgs([]string{}) // no query
|
|
|
|
|
cmd.SilenceErrors = true
|
|
|
|
|
cmd.SilenceUsage = true
|
|
|
|
|
err := cmd.Execute()
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestNewCmdChunks_RejectsEmptyQuery(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
|
|
|
|
cmd := NewCmdChunks(&cmdutil.Factory{
|
|
|
|
|
Client: func() (*sdk.Client, error) { return nil, nil },
|
|
|
|
|
})
|
|
|
|
|
cmd.SetArgs([]string{" ", "--kb", "kb1"})
|
|
|
|
|
cmd.SilenceErrors = true
|
|
|
|
|
cmd.SilenceUsage = true
|
|
|
|
|
err := cmd.Execute()
|
|
|
|
|
require.Error(t, err)
|
|
|
|
|
assert.Contains(t, err.Error(), "input.invalid_argument")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestRunSearch_NoVectorPassedThrough(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
|
|
|
|
var got *sdk.SearchParams
|
|
|
|
|
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
|
|
|
|
|
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
|
|
|
|
|
Query: "q", KBID: "kb1", NoVector: true,
|
2026-05-21 10:43:18 +00:00
|
|
|
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
2026-05-12 15:38:01 +00:00
|
|
|
require.NotNil(t, got)
|
|
|
|
|
assert.True(t, got.DisableVectorMatch)
|
|
|
|
|
assert.False(t, got.DisableKeywordsMatch)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestRunSearch_NoKeywordPassedThrough(t *testing.T) {
|
|
|
|
|
iostreams.SetForTest(t)
|
|
|
|
|
var got *sdk.SearchParams
|
|
|
|
|
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
|
|
|
|
|
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
|
|
|
|
|
Query: "q", KBID: "kb1", NoKeyword: true,
|
2026-05-21 10:43:18 +00:00
|
|
|
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
|
2026-05-12 15:38:01 +00:00
|
|
|
require.NotNil(t, got)
|
|
|
|
|
assert.True(t, got.DisableKeywordsMatch)
|
|
|
|
|
assert.False(t, got.DisableVectorMatch)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type capturingChunksSvc struct {
|
|
|
|
|
capture func(*sdk.SearchParams)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *capturingChunksSvc) HybridSearch(_ context.Context, _ string, p *sdk.SearchParams) ([]*sdk.SearchResult, error) {
|
|
|
|
|
c.capture(p)
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|