refactor(cli): align command surface with mainstream conventions

Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe /
flyctl / terraform / vercel / netlify / lark) drove five alignment
fixes — each replaces a weknora-only design choice that mainstream CLIs
do not share. No backwards-compat shims; the CLI has no v0.1 users yet.

1. Single --kb flag (was --kb-id + --kb mutually exclusive)

   Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs
   "by name". Single flag (gh -R, gcloud --project) or positional
   (kubectl, stripe, terraform). Closest analog — gcloud --project —
   collapses identifier types onto one flag.

   Now: every command exposes one --kb flag; client-side prefix
   detection (cmdutil.IsKBID looks for "kb_") routes id-form values
   through directly and name-form values through ListKnowledgeBases.
   Mirrors gcloud --project's id-or-name auto-detection.

   Touched: search, chat, doc list / upload / delete, link.
   Factory.ResolveKB chain trimmed from 5 levels to 4.

2. link supersedes init

   Survey: only vercel and netlify ship both `init` AND `link` as
   siblings, and they keep them semantically distinct. weknora's pair
   wrote the same .weknora/project.yaml file with the same meaning,
   differentiated only by interactivity — that's a flag concern, not
   a command concern.

   Now: cmd/init/ deleted. cmd/link absorbs the interactive flow:
     - link --kb <id-or-name>  → non-interactive write
     - link on a TTY            → interactive prompt (lists KBs)
     - link non-TTY without --kb → CodeKBIDRequired
   Always overwrites silently (matches vercel link / netlify link /
   kubectl apply rather than git init's refuse-if-exists).

   Dead code purged: --force flag, CodeProjectAlreadyLinked error code.

3. whoami dropped

   Survey: 7/7 mainstream CLIs ship exactly one identity command —
   never both a status and a whoami. gh / gcloud / stripe pick status
   (config + live API); aws / kubectl / flyctl pick whoami (live API).

   weknora's auth status was already a superset of whoami (host +
   context + user + email + tenant_id + tenant_name vs user_id +
   tenant_id), so dropping whoami preserves all functionality and
   aligns with the gh / gcloud / stripe form.

4. kb get alias dropped

   `view` was already primary (gh repo view / gh pr view convention);
   `get` was kept as a cobra alias for v0.0/v0.1 callers. With no
   v0.0/v0.1 users to break, the alias is just noise on the command
   surface. Acceptance contract envelope cases renamed kb_get.* →
   kb_view.*; goldens renamed in lockstep.

5. api refactored to gh shape (-X/--method, default GET, auto-POST)

   gh CLI's signature is `gh api <endpoint> [--method M]` — single
   positional path, method as a flag, default GET, auto-promoted to
   POST when a body is supplied. weknora's previous `api <method>
   <path>` inverted this and forced the method to be passed even for
   GET — a needless deviation from our declared north star.

   Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol
   on the DELETE escape-hatch is preserved; -X DELETE still hits
   ConfirmDestructive when -y absent.

Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate
divergence from gh / lark — borrowed from `flutter doctor` / `brew
doctor` because RAG deployments routinely break on misconfigured
embeddings / storage / credentials and a 4-status structured envelope
is the cleanest surface for it.

Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages
removed). Acceptance contract envelope cases for whoami removed,
kb_get → kb_view renamed, search args / mock path updated for the
kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests
rewritten for the single-flag shape. api_test driver updated for the
positional-path / -X-method shape.
This commit is contained in:
nullkey
2026-05-11 02:44:49 +08:00
committed by lyingbug
parent f7d7c8054d
commit 8bcbf5a154
27 changed files with 320 additions and 778 deletions
+10 -4
View File
@@ -96,14 +96,20 @@ The command tree follows `<noun> <verb>` (gh style). Verbs are:
| Verb | Semantics | Example | | Verb | Semantics | Example |
|---|---|---| |---|---|---|
| `list` | Multi-resource read | `kb list` | | `list` | Multi-resource read | `kb list` |
| `view` | Single-resource read (alias `get` for v0.0/v0.1 callers) | `kb view <id>` | | `view` | Single-resource read | `kb view <id>` |
| `create` | Create resource | `kb create --name X` | | `create` | Create resource | `kb create --name X` |
| `delete` | Destructive remove | `kb delete <id> -y` | | `delete` | Destructive remove | `kb delete <id> -y` |
| `upload` | Bulk write content | `doc upload <file>` | | `upload` | Bulk write content | `doc upload <file>` |
| `use` | Switch active selection | `context use <name>` | | `use` | Switch active selection | `context use <name>` |
Top-level RAG / connectivity verbs: `chat`, `search`, `api`, `init`, `link`, Top-level RAG / connectivity verbs: `chat`, `search`, `api`, `link`,
`auth`, `whoami`, `doctor`, `version`. `auth`, `doctor`, `version`.
`doctor` is a deliberate divergence from gh / lark (neither ships a
health-check command); the precedent is `flutter doctor` / `brew doctor`.
Kept because RAG deployments routinely break on misconfigured embeddings,
storage backends, and credentials, and a structured 4-status envelope
(ok/warn/fail/skip) is the cleanest agent-readable surface for that.
--- ---
@@ -123,7 +129,7 @@ appears in each command's `--help` output (under "AI agents:").
4. **Honor `--dry-run`** — when the user passes it, don't follow up with 4. **Honor `--dry-run`** — when the user passes it, don't follow up with
the real command unless explicitly asked. The dry-run envelope is the the real command unless explicitly asked. The dry-run envelope is the
answer. answer.
5. **`init` writes to the user's working directory** — only run it when 5. **`link` writes to the user's working directory** — only run it when
the user invoked it, not as a side effect of unrelated automation. the user invoked it, not as a side effect of unrelated automation.
(Additional safety guidance — e.g. "do not switch context unless the (Additional safety guidance — e.g. "do not switch context unless the
+20 -30
View File
@@ -72,20 +72,7 @@ var envelopeCases = []envelopeCase{
args: []string{"version", "--json"}, args: []string{"version", "--json"},
}, },
// 2-3. whoami — single SDK call to /api/v1/auth/me. // 2. doctor.success_offline — only credential_storage runs; the three
{
name: "whoami.success",
args: []string{"whoami", "--json"},
server: whoamiOK,
},
{
name: "whoami.error_auth_unauthenticated",
args: []string{"whoami", "--json"},
server: always401,
wantErr: true,
},
// 4. doctor.success_offline — only credential_storage runs; the three
// network checks are skipped. Stable details + summary. // network checks are skipped. Stable details + summary.
{ {
name: "doctor.success_offline", name: "doctor.success_offline",
@@ -93,7 +80,7 @@ var envelopeCases = []envelopeCase{
server: doctorReachable, // ensures buildServices succeeds even if probed server: doctorReachable, // ensures buildServices succeeds even if probed
}, },
// 5. doctor.error_network — base_url returns 500 → ping fail → cascade // 3. doctor.error_network — base_url returns 500 → ping fail → cascade
// skip on auth_credential + server_version. credential_storage still // skip on auth_credential + server_version. credential_storage still
// runs (independent). v0.2 contract: any check=fail flips envelope.ok // runs (independent). v0.2 contract: any check=fail flips envelope.ok
// to false and exits 1 (RunE returns SilentError so the data envelope // to false and exits 1 (RunE returns SilentError so the data envelope
@@ -105,7 +92,7 @@ var envelopeCases = []envelopeCase{
wantErr: true, wantErr: true,
}, },
// 6-9. kb list / get — SDK paths /api/v1/knowledge-bases[/<id>] // 4-7. kb list / get — SDK paths /api/v1/knowledge-bases[/<id>]
{ {
name: "kb_list.success", name: "kb_list.success",
args: []string{"kb", "list", "--json"}, args: []string{"kb", "list", "--json"},
@@ -123,18 +110,18 @@ var envelopeCases = []envelopeCase{
wantErr: true, wantErr: true,
}, },
{ {
name: "kb_get.success", name: "kb_view.success",
args: []string{"kb", "get", "kb1", "--json"}, args: []string{"kb", "view", "kb1", "--json"},
server: kbGetOne, server: kbGetOne,
}, },
{ {
name: "kb_get.error_resource_not_found", name: "kb_view.error_resource_not_found",
args: []string{"kb", "get", "missing", "--json"}, args: []string{"kb", "view", "missing", "--json"},
server: always404, server: always404,
wantErr: true, wantErr: true,
}, },
// 10-11. context use — pure local I/O against config.yaml. // 8. context use — pure local I/O against config.yaml.
{ {
name: "context_use.success", name: "context_use.success",
args: []string{"context", "use", "production"}, args: []string{"context", "use", "production"},
@@ -153,7 +140,7 @@ var envelopeCases = []envelopeCase{
}, },
// (context_use.error_local_context_not_found dropped — see file header.) // (context_use.error_local_context_not_found dropped — see file header.)
// 11-12. auth status — SDK /api/v1/auth/me, plus config inspection. // 9-10. auth status — SDK /api/v1/auth/me, plus config inspection.
{ {
name: "auth_status.success", name: "auth_status.success",
args: []string{"auth", "status", "--json"}, args: []string{"auth", "status", "--json"},
@@ -166,24 +153,27 @@ var envelopeCases = []envelopeCase{
wantErr: true, wantErr: true,
}, },
// 14-16. search — top-level command, positional query, --kb required. // 11-13. search — top-level command, positional query, --kb required.
// --kb accepts either kb_<id> (passed through) or a name (resolved via
// list); kb_ prefix detection happens client-side, mirroring gcloud
// --project's id-or-name auto-detection.
{ {
name: "search.success", name: "search.success",
args: []string{"search", "query", "--kb-id=kb1", "--top-k=3", "--json"}, args: []string{"search", "query", "--kb=kb_1", "--top-k=3", "--json"},
server: searchTwoResults, server: searchTwoResults,
}, },
{ {
name: "search.error_resource_not_found", name: "search.error_resource_not_found",
args: []string{"search", "query", "--kb-id=missing", "--json"}, args: []string{"search", "query", "--kb=kb_missing", "--json"},
server: always404, server: always404,
wantErr: true, wantErr: true,
}, },
{ {
// Mutex flag violation. Validation runs before f.Client(), so the // --no-vector + --no-keyword is the input.invalid case; --kb=kb_1 is
// server mock is never consumed; we still pass --kb to satisfy the // just there to satisfy MarkFlagRequired so validation runs deep
// MarkFlagRequired check that fires earlier in cobra's parse phase. // enough to hit the mutex-channel check.
name: "search.error_input_invalid", name: "search.error_input_invalid",
args: []string{"search", "query", "--kb-id=kb1", "--no-vector", "--no-keyword", "--json"}, args: []string{"search", "query", "--kb=kb_1", "--no-vector", "--no-keyword", "--json"},
wantErr: true, wantErr: true,
}, },
} }
@@ -341,7 +331,7 @@ func kbGetOne(w http.ResponseWriter, r *http.Request) {
} }
func searchTwoResults(w http.ResponseWriter, r *http.Request) { func searchTwoResults(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/knowledge-bases/kb1/hybrid-search") { if !strings.Contains(r.URL.Path, "/knowledge-bases/kb_1/hybrid-search") {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
return return
} }
@@ -184,8 +184,6 @@ func identToErrorCode(name string) (cmdutil.ErrorCode, bool) {
return cmdutil.CodeKBIDRequired, true return cmdutil.CodeKBIDRequired, true
case "CodeKBNotFound": case "CodeKBNotFound":
return cmdutil.CodeKBNotFound, true return cmdutil.CodeKBNotFound, true
case "CodeProjectAlreadyLinked":
return cmdutil.CodeProjectAlreadyLinked, true
case "CodeProjectLinkCorrupt": case "CodeProjectLinkCorrupt":
return cmdutil.CodeProjectLinkCorrupt, true return cmdutil.CodeProjectLinkCorrupt, true
case "CodeUserAborted": case "CodeUserAborted":
+4 -4
View File
@@ -74,7 +74,7 @@ func TestRAGFullLoop(t *testing.T) {
// 2. doc upload // 2. doc upload
docPath := writeSampleDoc(t) docPath := writeSampleDoc(t)
uploadOut := runJSON(t, bin, env, "doc", "upload", docPath, "--kb-id", kbID, "--json") uploadOut := runJSON(t, bin, env, "doc", "upload", docPath, "--kb", kbID, "--json")
docData, _ := uploadOut["data"].(map[string]any) docData, _ := uploadOut["data"].(map[string]any)
docID, _ := docData["id"].(string) docID, _ := docData["id"].(string)
if docID == "" { if docID == "" {
@@ -86,7 +86,7 @@ func TestRAGFullLoop(t *testing.T) {
waitDocReady(t, bin, env, kbID, docID, 90*time.Second) waitDocReady(t, bin, env, kbID, docID, 90*time.Second)
// 4. search — verify retrieval returns chunks // 4. search — verify retrieval returns chunks
searchOut := runJSON(t, bin, env, "search", "sample", "--kb-id", kbID, "--top-k", "5", "--json") searchOut := runJSON(t, bin, env, "search", "sample", "--kb", kbID, "--top-k", "5", "--json")
searchData, _ := searchOut["data"].(map[string]any) searchData, _ := searchOut["data"].(map[string]any)
results, _ := searchData["results"].([]any) results, _ := searchData["results"].([]any)
if len(results) == 0 { if len(results) == 0 {
@@ -96,7 +96,7 @@ func TestRAGFullLoop(t *testing.T) {
// 5. chat — verify LLM answer + references in --json + --no-stream mode // 5. chat — verify LLM answer + references in --json + --no-stream mode
// (--no-stream forces accumulator path; --json gates envelope output) // (--no-stream forces accumulator path; --json gates envelope output)
chatOut := runJSON(t, bin, env, "chat", "summarize the document briefly", "--kb-id", kbID, "--no-stream", "--json") chatOut := runJSON(t, bin, env, "chat", "summarize the document briefly", "--kb", kbID, "--no-stream", "--json")
chatData, _ := chatOut["data"].(map[string]any) chatData, _ := chatOut["data"].(map[string]any)
answer, _ := chatData["answer"].(string) answer, _ := chatData["answer"].(string)
if strings.TrimSpace(answer) == "" { if strings.TrimSpace(answer) == "" {
@@ -203,7 +203,7 @@ func waitDocReady(t *testing.T, bin string, env []string, kbID, docID string, ti
deadline := time.Now().Add(timeout) deadline := time.Now().Add(timeout)
tick := 2 * time.Second tick := 2 * time.Second
for time.Now().Before(deadline) { for time.Now().Before(deadline) {
out := runJSON(t, bin, env, "doc", "list", "--kb-id", kbID, "--page-size", "100", "--json") out := runJSON(t, bin, env, "doc", "list", "--kb", kbID, "--page-size", "100", "--json")
data, _ := out["data"].(map[string]any) data, _ := out["data"].(map[string]any)
items, _ := data["items"].([]any) items, _ := data["items"].([]any)
for _, it := range items { for _, it := range items {
+1 -1
View File
@@ -1 +1 @@
{"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":{"kb_id":"kb1"},"dry_run":false} {"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":{"kb_id":"kb_1"},"dry_run":false}
+47 -25
View File
@@ -1,10 +1,12 @@
// Package api implements the `weknora api` raw HTTP passthrough command. // Package api implements the `weknora api` raw HTTP passthrough command.
// //
// Mirrors `gh api` ergonomics: 2 positionals (method, path), --data / // Mirrors `gh api` ergonomics: 1 positional (path) + `-X/--method` flag,
// --data-file mutually exclusive body source, default raw response body to // default GET (auto-promoted to POST when a body is supplied via --data /
// stdout, --json wraps in CLI envelope. Reuses sdk.Client.Raw which already // --data-file). The two body-source flags are mutually exclusive. Default
// applies tenant + auth headers; v0.2 does not support --header (SDK Raw // raw response body to stdout; --json wraps in CLI envelope. Reuses
// signature lacks header param) — that's planned for v0.3. // sdk.Client.Raw which already applies tenant + auth headers; v0.2 does not
// support --header (SDK Raw signature lacks header param) — that's planned
// for v0.3.
package api package api
import ( import (
@@ -27,6 +29,7 @@ import (
// Options captures `weknora api` flag state. // Options captures `weknora api` flag state.
type Options struct { type Options struct {
Method string
Data string Data string
DataFile string DataFile string
JSONOut bool JSONOut bool
@@ -46,41 +49,45 @@ type Service interface {
func NewCmd(f *cmdutil.Factory) *cobra.Command { func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{} opts := &Options{}
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "api <method> <path>", Use: "api <path>",
Short: "Make a raw API request to the WeKnora server", Short: "Make a raw API request to the WeKnora server",
Long: `Send an HTTP request through the SDK and print the response. Long: `Send an HTTP request through the SDK and print the response.
Auth, tenant, and request-id headers are applied automatically from the active The default method is GET; passing --data / --data-file auto-promotes it to
context. The response body is written to stdout by default; use --json to wrap POST. Use -X/--method to override (DELETE / PUT / PATCH / HEAD).
it in the CLI envelope (status / headers / body).
Auth, tenant, and request-id headers are applied automatically from the
active context. The response body is written to stdout by default; use
--json to wrap it in the CLI envelope (status / headers / body).
Examples: Examples:
weknora api GET /api/v1/knowledge-bases weknora api /api/v1/knowledge-bases # GET
weknora api POST /api/v1/knowledge-bases --data '{"name":"foo"}' weknora api /api/v1/knowledge-bases --data '{"name":"foo"}' # POST (auto)
weknora api DELETE /api/v1/knowledge-bases/kb_xxx`, weknora api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
Args: cobra.ExactArgs(2), Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
opts.DryRun = cmdutil.IsDryRun(c) opts.DryRun = cmdutil.IsDryRun(c)
opts.Yes, _ = c.Flags().GetBool("yes") opts.Yes, _ = c.Flags().GetBool("yes")
method := strings.ToUpper(args[0]) method := resolveMethod(opts)
// Escape-hatch DELETE through `weknora api` is just as destructive // Escape-hatch DELETE through `weknora api` is just as destructive
// as `weknora kb delete` — exit-10 protocol must apply (AGENTS.md). // as `weknora kb delete` — exit-10 protocol must apply (AGENTS.md).
// Dry-run is read-only preview, so it skips confirmation. // Dry-run is read-only preview, so it skips confirmation.
if !opts.DryRun && method == "DELETE" { if !opts.DryRun && method == http.MethodDelete {
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, opts.JSONOut, "endpoint", args[1]); err != nil { if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, opts.JSONOut, "endpoint", args[0]); err != nil {
return err return err
} }
} }
if opts.DryRun { if opts.DryRun {
return runAPI(c.Context(), opts, nil, args[0], args[1]) return runAPI(c.Context(), opts, nil, method, args[0])
} }
cli, err := f.Client() cli, err := f.Client()
if err != nil { if err != nil {
return err return err
} }
return runAPI(c.Context(), opts, cli, args[0], args[1]) return runAPI(c.Context(), opts, cli, method, args[0])
}, },
} }
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.Data, "data", "d", "", "Request body as raw string (e.g. JSON)")
cmd.Flags().StringVar(&opts.DataFile, "data-file", "", "Read request body from file") cmd.Flags().StringVar(&opts.DataFile, "data-file", "", "Read request body from file")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Wrap response in JSON envelope (status/headers/body)") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Wrap response in JSON envelope (status/headers/body)")
@@ -89,14 +96,29 @@ Examples:
return cmd return cmd
} }
// resolveMethod implements gh's auto-method behavior: explicit -X wins;
// otherwise body presence promotes GET → POST.
func resolveMethod(opts *Options) string {
if opts.Method != "" {
return strings.ToUpper(opts.Method)
}
if opts.Data != "" || opts.DataFile != "" {
return "POST"
}
return "GET"
}
// runAPI is the testable core: validate inputs, dispatch via Service.Raw, // runAPI is the testable core: validate inputs, dispatch via Service.Raw,
// classify status, and emit either the raw body or a JSON envelope. // classify status, and emit either the raw body or a JSON envelope. The
func runAPI(ctx context.Context, opts *Options, svc Service, methodArg, path string) error { // caller is responsible for resolving the method (defaults / auto-POST)
method := strings.ToUpper(methodArg) // and uppercasing it; runAPI guards against unsupported values like
// `-X PATCH-INVALID` reaching the wire.
func runAPI(ctx context.Context, opts *Options, svc Service, method, path string) error {
switch method { switch method {
case "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD": case http.MethodGet, http.MethodPost, http.MethodPut,
http.MethodPatch, http.MethodDelete, http.MethodHead:
default: default:
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("unsupported method: %s", methodArg)) return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("unsupported method: %s", method))
} }
if !strings.HasPrefix(path, "/") { if !strings.HasPrefix(path, "/") {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path)) return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
@@ -118,9 +140,9 @@ func runAPI(ctx context.Context, opts *Options, svc Service, methodArg, path str
// --dry-run only meaningful for write methods; GET/HEAD have no side // --dry-run only meaningful for write methods; GET/HEAD have no side
// effect to preview, so we proceed normally even with --dry-run. // effect to preview, so we proceed normally even with --dry-run.
if opts.DryRun && method != "GET" && method != "HEAD" { if opts.DryRun && method != http.MethodGet && method != http.MethodHead {
level := format.RiskWrite level := format.RiskWrite
if method == "DELETE" { if method == http.MethodDelete {
level = format.RiskHighRiskWrite level = format.RiskHighRiskWrite
} }
preview := map[string]any{"method": method, "path": path} preview := map[string]any{"method": method, "path": path}
+2 -2
View File
@@ -208,7 +208,7 @@ func TestAPI_DELETE_RequiresConfirmation(t *testing.T) {
Client: func() (*sdk.Client, error) { return nil, nil }, Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} }, Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
} }
root := withRootHarness(NewCmd(f), "DELETE", "/api/v1/knowledge-bases/kb_xxx") root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", "DELETE")
err := root.Execute() err := root.Execute()
if err == nil { if err == nil {
t.Fatal("expected confirmation_required error for DELETE without -y") t.Fatal("expected confirmation_required error for DELETE without -y")
@@ -240,7 +240,7 @@ func TestAPI_DELETE_WithYes_Proceeds(t *testing.T) {
Client: func() (*sdk.Client, error) { return cli, nil }, Client: func() (*sdk.Client, error) { return cli, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} }, Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
} }
root := withRootHarness(NewCmd(f), "DELETE", "/api/v1/knowledge-bases/kb_xxx", "-y") root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", "DELETE", "-y")
if err := root.Execute(); err != nil { if err := root.Execute(); err != nil {
t.Fatalf("execute: %v", err) t.Fatalf("execute: %v", err)
} }
+2 -4
View File
@@ -77,7 +77,7 @@ answer back. By default a fresh session is created on first invocation; pass
Modes: Modes:
TTY (default): live token streaming + reference footer TTY (default): live token streaming + reference footer
Pipe / --no-stream / --json: buffered, emitted once on completion`, Pipe / --no-stream / --json: buffered, emitted once on completion`,
Example: ` weknora chat "What is RRF?" --kb-id kb_123 Example: ` weknora chat "What is RRF?" --kb kb_123
weknora chat "Summarise this design doc" --kb my-kb --json weknora chat "Summarise this design doc" --kb my-kb --json
weknora chat "Continue?" --session-id sess_abc`, weknora chat "Continue?" --session-id sess_abc`,
Args: cobra.MinimumNArgs(1), Args: cobra.MinimumNArgs(1),
@@ -98,12 +98,10 @@ Modes:
return runChat(c.Context(), opts, cli) return runChat(c.Context(), opts, cli)
}, },
} }
cmd.Flags().String("kb-id", "", "Knowledge base ID (overrides project link / env)") cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides project link / env)")
cmd.Flags().String("kb", "", "Knowledge base name (resolved via list)")
cmd.Flags().StringVar(&opts.SessionID, "session-id", "", "Continue an existing chat session (skip auto-create)") cmd.Flags().StringVar(&opts.SessionID, "session-id", "", "Continue an existing chat session (skip auto-create)")
cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)") cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Emit a single JSON envelope (implies --no-stream)") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Emit a single JSON envelope (implies --no-stream)")
cmd.MarkFlagsMutuallyExclusive("kb-id", "kb")
return cmd return cmd
} }
+9 -9
View File
@@ -50,13 +50,15 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
Use: "list", Use: "list",
Short: "List documents in a knowledge base", Short: "List documents in a knowledge base",
Long: `Lists documents (uploaded files / web pages / inline text) in the Long: `Lists documents (uploaded files / web pages / inline text) in the
resolved knowledge base. KB id resolution follows the standard 5-level chain: resolved knowledge base. KB resolution follows the standard 4-level chain:
--kb-id flag > --kb name > WEKNORA_KB_ID env > .weknora/project.yaml > error. --kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error. The --kb
flag accepts either a kb_<id> or a name (resolved via list).
Default sort is updated_at desc so the most recent uploads surface first; Default sort is updated_at desc so the most recent uploads surface first;
backend storage order is not guaranteed and varies between deployments.`, backend storage order is not guaranteed and varies between deployments.`,
Example: ` weknora doc list # uses project link / env Example: ` weknora doc list # uses project link / env
weknora doc list --kb-id kb_abc # explicit weknora doc list --kb kb_abc # explicit id
weknora doc list --kb my-kb # resolved by name
weknora doc list --page 2 --json # paginated envelope output`, weknora doc list --page 2 --json # paginated envelope output`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error { RunE: func(c *cobra.Command, _ []string) error {
@@ -71,15 +73,13 @@ backend storage order is not guaranteed and varies between deployments.`,
return runList(c.Context(), opts, cli, kbID) return runList(c.Context(), opts, cli, kbID)
}, },
} }
// --kb-id / --kb are read by Factory.ResolveKB; declare them here so // --kb is read by Factory.ResolveKB; declare it here so cobra parses the
// Cobra parses the values into the command's flag set. // value into the command's flag set.
cmd.Flags().String("kb-id", "", "Knowledge base id (overrides env / project link)") cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides env / project link)")
cmd.Flags().String("kb", "", "Knowledge base name (resolved to id)")
cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)") cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)")
cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page") cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmd.MarkFlagsMutuallyExclusive("kb-id", "kb") agent.SetAgentHelp(cmd, "Lists docs in the resolved KB. Returns data: {items, page, page_size, total, kb_id}; pass --kb when not running inside a project.")
agent.SetAgentHelp(cmd, "Lists docs in the resolved KB. Returns data: {items, page, page_size, total, kb_id}; pass --kb-id when not running inside a project.")
return cmd return cmd
} }
+11 -11
View File
@@ -135,7 +135,7 @@ func TestList_KBIDRequired(t *testing.T) {
} }
cmd := NewCmdList(f) cmd := NewCmdList(f)
cmd.SetContext(context.Background()) cmd.SetContext(context.Background())
cmd.SetArgs([]string{}) // no --kb-id, no --kb cmd.SetArgs([]string{}) // no --kb
cmd.SilenceErrors = true cmd.SilenceErrors = true
cmd.SilenceUsage = true cmd.SilenceUsage = true
err := cmd.Execute() err := cmd.Execute()
@@ -146,9 +146,9 @@ func TestList_KBIDRequired(t *testing.T) {
assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code) assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
} }
// TestList_KBIDFlagWiredToResolveKB confirms that a --kb-id passed at the // TestList_KBFlagWiredToResolveKB confirms that --kb=kb_<id> passed at the
// cobra layer reaches Factory.ResolveKB and skips the Client() call. // cobra layer reaches Factory.ResolveKB and short-circuits without listing.
func TestList_KBIDFlagWiredToResolveKB(t *testing.T) { func TestList_KBFlagWiredToResolveKB(t *testing.T) {
chdirIsolated(t) chdirIsolated(t)
_, _ = iostreams.SetForTest(t) _, _ = iostreams.SetForTest(t)
@@ -162,20 +162,20 @@ func TestList_KBIDFlagWiredToResolveKB(t *testing.T) {
return nil, errors.New("forced-after-resolvekb") return nil, errors.New("forced-after-resolvekb")
}, },
} }
// With --kb-id supplied, ResolveKB short-circuits without consulting the // With --kb=kb_<id> supplied, ResolveKB short-circuits on the prefix
// client. The RunE then asks for the client to run the actual list — that // match without consulting the client. The RunE then asks for the client
// call triggers the forced error. Surfacing "forced-after-resolvekb" // to run the actual list — that call triggers the forced error.
// (rather than CodeKBIDRequired) is the proof point that --kb-id was // Surfacing "forced-after-resolvekb" (rather than CodeKBIDRequired) is
// honored. // the proof point that --kb was honored.
cmd := NewCmdList(f) cmd := NewCmdList(f)
cmd.SetContext(context.Background()) cmd.SetContext(context.Background())
cmd.SetArgs([]string{"--kb-id", "kb_explicit"}) cmd.SetArgs([]string{"--kb", "kb_explicit"})
cmd.SilenceErrors = true cmd.SilenceErrors = true
cmd.SilenceUsage = true cmd.SilenceUsage = true
err := cmd.Execute() err := cmd.Execute()
require.Error(t, err, "expected client construction error") require.Error(t, err, "expected client construction error")
assert.Contains(t, err.Error(), "forced-after-resolvekb", assert.Contains(t, err.Error(), "forced-after-resolvekb",
"should surface the Client closure error, not a kb-id-required error") "should surface the Client closure error, not a kb-required error")
} }
// pinning the sort order: most-recent-first regardless of input order. // pinning the sort order: most-recent-first regardless of input order.
+7 -7
View File
@@ -45,8 +45,9 @@ func NewCmdUpload(f *cmdutil.Factory) *cobra.Command {
Use: "upload <file>", Use: "upload <file>",
Short: "Upload a local file to the knowledge base", Short: "Upload a local file to the knowledge base",
Long: `Uploads a file (PDF / DOCX / Markdown / TXT / etc.) to the resolved Long: `Uploads a file (PDF / DOCX / Markdown / TXT / etc.) to the resolved
knowledge base. KB id resolution follows the standard 5-level chain: knowledge base. KB resolution follows the standard 4-level chain:
--kb-id flag > --kb name > WEKNORA_KB_ID env > .weknora/project.yaml > error. --kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error. The --kb
flag accepts either a kb_<id> or a name (resolved via list).
Pass --name to override the recorded file name (useful when the local file Pass --name to override the recorded file name (useful when the local file
has a generic name like "report.pdf" but you want to surface it as e.g. has a generic name like "report.pdf" but you want to surface it as e.g.
@@ -55,7 +56,8 @@ has a generic name like "report.pdf" but you want to surface it as e.g.
v0.2 ships single-file upload only; --recursive / --glob and progress UI are v0.2 ships single-file upload only; --recursive / --glob and progress UI are
planned for v0.3.`, planned for v0.3.`,
Example: ` weknora doc upload report.pdf Example: ` weknora doc upload report.pdf
weknora doc upload notes.md --kb-id kb_abc weknora doc upload notes.md --kb kb_abc
weknora doc upload notes.md --kb my-kb
weknora doc upload q3.pdf --name "Q3 Marketing Report.pdf"`, weknora doc upload q3.pdf --name "Q3 Marketing Report.pdf"`,
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
@@ -78,12 +80,10 @@ planned for v0.3.`,
return runUpload(c.Context(), opts, cli, kbID, path) return runUpload(c.Context(), opts, cli, kbID, path)
}, },
} }
cmd.Flags().String("kb-id", "", "Knowledge base id (overrides env / project link)") cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides env / project link)")
cmd.Flags().String("kb", "", "Knowledge base name (resolved to id)")
cmd.Flags().StringVar(&opts.Name, "name", "", "Custom file name to record (defaults to base name)") cmd.Flags().StringVar(&opts.Name, "name", "", "Custom file name to record (defaults to base name)")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmd.MarkFlagsMutuallyExclusive("kb-id", "kb") agent.SetAgentHelp(cmd, "Uploads one local file to the resolved KB. Refuses non-regular files (dir / symlink). Returns data: Knowledge object with id, parse_status. Pass --kb outside a linked project.")
agent.SetAgentHelp(cmd, "Uploads one local file to the resolved KB. Refuses non-regular files (dir / symlink). Returns data: Knowledge object with id, parse_status. Pass --kb-id outside a linked project.")
return cmd return cmd
} }
-203
View File
@@ -1,203 +0,0 @@
// Package initcmd implements `weknora init` — creates a per-project link file
// at <cwd>/.weknora/project.yaml that anchors the working tree to a context
// + knowledge-base id (spec §2.4 "weknora init").
//
// Package name is `initcmd` (not `init`) to avoid colliding with Go's reserved
// init() function naming. The cobra Use: string is "init" — what users type.
package initcmd
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"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/projectlink"
)
// Options captures `weknora init` flags.
type Options struct {
Context string // --context: override active context for this link
KBID string // --kb-id
KBName string // --kb
Yes bool // --yes: skip interactive prompt
Force bool // --force: overwrite existing link
JSONOut bool // --json
}
// initResult is the typed payload emitted under data.
type initResult struct {
Context string `json:"context"`
KBID string `json:"kb_id"`
KBName string `json:"kb_name,omitempty"`
ProjectLinkPath string `json:"project_link_path"`
}
// NewCmd builds the `weknora init` command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: "init",
Short: "Link the current directory to a context + knowledge base",
Long: `Writes a .weknora/project.yaml in the current working directory that pins
the active context and a knowledge-base id. Subsequent commands run from this
directory (or any subdirectory) automatically resolve --kb-id from the link
unless overridden by the --kb-id / --kb flags or WEKNORA_KB_ID env var.
Mirrors the npm init / cargo init / git init UX pattern: one-time setup that
removes the need to re-pass --kb-id on every command.
AI agents: ` + "`init`" + ` writes to the user's working directory. Only run
it when the user explicitly asked to link this directory — don't run it as a
side effect of unrelated automation.`,
Example: ` weknora init --kb-id kb_abc # explicit id
weknora init --kb engineering --yes # name → id, no prompt
weknora init # interactive (TTY)
weknora init --force --kb-id kb_xyz # overwrite existing link`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
return runInit(c.Context(), opts, f)
},
}
cmd.Flags().StringVar(&opts.Context, "context", "", "Context to record in the link (defaults to active context)")
cmd.Flags().StringVar(&opts.KBID, "kb-id", "", "Knowledge base id to link")
cmd.Flags().StringVar(&opts.KBName, "kb", "", "Knowledge base name (resolved to id)")
cmd.Flags().BoolVar(&opts.Yes, "yes", false, "Skip interactive prompt")
cmd.Flags().BoolVar(&opts.Force, "force", false, "Overwrite an existing .weknora/project.yaml")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmd.MarkFlagsMutuallyExclusive("kb-id", "kb")
agent.SetAgentHelp(cmd, "Creates .weknora/project.yaml linking cwd to a context + KB. Pass --kb-id (or --kb name) and --yes for non-interactive use; --force overwrites an existing link.")
return cmd
}
func runInit(ctx context.Context, opts *Options, f *cmdutil.Factory) error {
cwd, err := os.Getwd()
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "get cwd")
}
linkPath := filepath.Join(cwd, projectlink.DirName, projectlink.FileName)
// Pre-flight: refuse to clobber unless --force.
if _, statErr := os.Stat(linkPath); statErr == nil && !opts.Force {
return cmdutil.NewError(cmdutil.CodeProjectAlreadyLinked, fmt.Sprintf("project already linked: %s", linkPath))
}
// Resolve context: --context flag wins, else config.CurrentContext.
ctxName, err := resolveContext(opts, f)
if err != nil {
return err
}
// Resolve KB: --kb-id > --kb > interactive prompt.
kbID, kbName, err := resolveKB(ctx, opts, f)
if err != nil {
return err
}
link := &projectlink.Project{
Context: ctxName,
KBID: kbID,
CreatedAt: time.Now().UTC(),
}
if err := projectlink.Save(linkPath, link); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write project link")
}
r := initResult{
Context: ctxName,
KBID: kbID,
KBName: kbName,
ProjectLinkPath: linkPath,
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(r, &format.Meta{
Context: ctxName,
KBID: kbID,
}))
}
if kbName != "" {
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb=%s, id=%s)\n", linkPath, ctxName, kbName, kbID)
} else {
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb_id=%s)\n", linkPath, ctxName, kbID)
}
return nil
}
// resolveContext returns the context name to record in the link.
func resolveContext(opts *Options, f *cmdutil.Factory) (string, error) {
if opts.Context != "" {
return opts.Context, nil
}
cfg, err := f.Config()
if err != nil {
return "", err
}
if cfg.CurrentContext == "" {
return "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no active context; run `weknora auth login` first")
}
return cfg.CurrentContext, nil
}
// resolveKB applies the --kb-id / --kb / prompt fallback chain. Returns
// (kbID, kbName) where kbName is empty when only --kb-id was supplied.
func resolveKB(ctx context.Context, opts *Options, f *cmdutil.Factory) (string, string, error) {
if opts.KBID != "" {
return opts.KBID, "", nil
}
if opts.KBName != "" {
cli, err := f.Client()
if err != nil {
return "", "", err
}
id, err := cmdutil.ResolveKBNameToID(ctx, cli, opts.KBName)
if err != nil {
return "", "", err
}
return id, opts.KBName, nil
}
// No flag: try interactive prompt when allowed.
if opts.Yes || !iostreams.IO.IsStdoutTTY() {
return "", "", cmdutil.NewError(cmdutil.CodeKBIDRequired, "--kb-id or --kb is required (no TTY / --yes set)")
}
cli, err := f.Client()
if err != nil {
return "", "", err
}
return promptForKB(ctx, cli, f)
}
// promptForKB lists available knowledge bases on stderr, then asks the user
// for an id or name (huh-backed Input via TTYPrompter). Resolved against the
// listed set so a typed name is converted to the canonical id.
func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory) (string, string, error) {
kbs, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return "", "", cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list knowledge bases")
}
if len(kbs) == 0 {
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active context; create one first")
}
fmt.Fprintln(iostreams.IO.Err, "Available knowledge bases:")
for _, kb := range kbs {
fmt.Fprintf(iostreams.IO.Err, " %s %s\n", kb.ID, kb.Name)
}
p := f.Prompter()
answer, err := p.Input("Knowledge base id or name", "")
if err != nil {
return "", "", cmdutil.Wrapf(cmdutil.CodeInputMissingFlag, err, "kb prompt")
}
for _, kb := range kbs {
if kb.ID == answer || kb.Name == answer {
return kb.ID, kb.Name, nil
}
}
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, fmt.Sprintf("knowledge base not found: %s", answer))
}
-162
View File
@@ -1,162 +0,0 @@
package initcmd
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"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/projectlink"
sdk "github.com/Tencent/WeKnora/client"
)
// chdir switches cwd to dir for the duration of the test.
func chdir(t *testing.T, dir string) {
t.Helper()
prev, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(dir))
t.Cleanup(func() { _ = os.Chdir(prev) })
}
// fakeKBServer returns an httptest server answering ListKnowledgeBases.
func fakeKBServer(t *testing.T, kbs []sdk.KnowledgeBase) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/knowledge-bases", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(sdk.KnowledgeBaseListResponse{Success: true, Data: kbs})
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
// newFactory builds a minimal Factory for init tests with the supplied
// CurrentContext + Client closure. Tests inject the cobra-level deps directly
// because runInit is the test boundary (matches kb/list_test.go pattern).
func newFactory(currentCtx string, client *sdk.Client) *cmdutil.Factory {
cfg := &config.Config{
CurrentContext: currentCtx,
Contexts: map[string]config.Context{
currentCtx: {Host: "https://example"},
},
}
return &cmdutil.Factory{
Config: func() (*config.Config, error) { return cfg, nil },
Client: func() (*sdk.Client, error) {
if client == nil {
return nil, errors.New("client not configured")
}
return client, nil
},
}
}
func TestInit_CreatesWithFlags_Yes(t *testing.T) {
dir := t.TempDir()
chdir(t, dir)
out, _ := iostreams.SetForTest(t)
f := newFactory("default", nil)
opts := &Options{Context: "default", KBID: "kb_explicit", Yes: true}
require.NoError(t, runInit(context.Background(), opts, f))
// Verify file written with the right contents.
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
p, err := projectlink.Load(linkPath)
require.NoError(t, err)
assert.Equal(t, "kb_explicit", p.KBID)
assert.Equal(t, "default", p.Context)
assert.False(t, p.CreatedAt.IsZero(), "CreatedAt should be stamped")
// Human output mentions the path + ✓.
assert.Contains(t, out.String(), "✓")
assert.Contains(t, out.String(), "kb_explicit")
}
func TestInit_CreatesWithFlags_KBName(t *testing.T) {
dir := t.TempDir()
chdir(t, dir)
_, _ = iostreams.SetForTest(t)
srv := fakeKBServer(t, []sdk.KnowledgeBase{
{ID: "kb_a", Name: "engineering"},
{ID: "kb_b", Name: "marketing"},
})
cli := sdk.NewClient(srv.URL)
f := newFactory("default", cli)
opts := &Options{Context: "default", KBName: "engineering", Yes: true}
require.NoError(t, runInit(context.Background(), opts, f))
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
p, err := projectlink.Load(linkPath)
require.NoError(t, err)
assert.Equal(t, "kb_a", p.KBID, "KB name 'engineering' should resolve to kb_a")
}
func TestInit_RefusesWhenExists(t *testing.T) {
dir := t.TempDir()
chdir(t, dir)
_, _ = iostreams.SetForTest(t)
// Pre-seed an existing link.
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
require.NoError(t, projectlink.Save(linkPath, &projectlink.Project{KBID: "kb_pre"}))
f := newFactory("default", nil)
opts := &Options{Context: "default", KBID: "kb_new", Yes: true} // no --force
err := runInit(context.Background(), opts, f)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeProjectAlreadyLinked, typed.Code)
// Original kb_pre must NOT be overwritten.
p, err := projectlink.Load(linkPath)
require.NoError(t, err)
assert.Equal(t, "kb_pre", p.KBID)
}
func TestInit_ForceOverwrites(t *testing.T) {
dir := t.TempDir()
chdir(t, dir)
_, _ = iostreams.SetForTest(t)
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
require.NoError(t, projectlink.Save(linkPath, &projectlink.Project{KBID: "kb_pre"}))
f := newFactory("default", nil)
opts := &Options{Context: "default", KBID: "kb_new", Yes: true, Force: true}
require.NoError(t, runInit(context.Background(), opts, f))
p, err := projectlink.Load(linkPath)
require.NoError(t, err)
assert.Equal(t, "kb_new", p.KBID, "--force must overwrite the prior link")
}
func TestInit_JSONOutput(t *testing.T) {
dir := t.TempDir()
chdir(t, dir)
out, _ := iostreams.SetForTest(t)
f := newFactory("default", nil)
opts := &Options{Context: "default", KBID: "kb_explicit", Yes: true, JSONOut: true}
require.NoError(t, runInit(context.Background(), opts, f))
got := out.String()
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)
assert.Contains(t, got, `"kb_id":"kb_explicit"`)
assert.Contains(t, got, `"project_link_path"`)
}
+7 -8
View File
@@ -24,16 +24,15 @@ type ViewService interface {
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error) GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
} }
// NewCmdView builds `weknora kb view <id>`. The `get` alias is kept for one // NewCmdView builds `weknora kb view <id>`. Mirrors `gh repo view`
// minor release so v0.0/v0.1 callers don't break; the help text shows `view` // (https://cli.github.com/manual/gh_repo_view) — the established mainstream
// as primary, mirroring `gh repo view` (https://cli.github.com/manual/gh_repo_view). // verb for single-resource reads.
func NewCmdView(f *cmdutil.Factory) *cobra.Command { func NewCmdView(f *cmdutil.Factory) *cobra.Command {
opts := &ViewOptions{} opts := &ViewOptions{}
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "view <id>", Use: "view <id>",
Aliases: []string{"get"}, Short: "Show a knowledge base by ID",
Short: "Show a knowledge base by ID", Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
cli, err := f.Client() cli, err := f.Client()
if err != nil { if err != nil {
@@ -43,7 +42,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
}, },
} }
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
agent.SetAgentHelp(cmd, "Returns details of one knowledge base by ID (config + counts). Aliased as `kb get` for v0.0/v0.1 compat.") agent.SetAgentHelp(cmd, "Returns details of one knowledge base by ID (config + counts).")
return cmd return cmd
} }
+101 -36
View File
@@ -1,7 +1,9 @@
// Package linkcmd implements `weknora link` — re-points an existing // Package linkcmd implements `weknora link` — binds the current working
// .weknora/project.yaml at a different knowledge base. Distinct from // directory to a knowledge base by writing .weknora/project.yaml. Always
// `weknora init`: link assumes the directory is already a project (or you // overwrites an existing link silently, mirroring `vercel link` /
// want one without going through the init wizard) and never prompts. // `netlify link` / `kubectl apply` rather than `git init`'s
// refuse-if-exists posture. The cobra Long: text covers the user-facing
// modes (--kb / TTY / non-TTY).
package linkcmd package linkcmd
import ( import (
@@ -22,13 +24,12 @@ import (
// Options captures `weknora link` flags. // Options captures `weknora link` flags.
type Options struct { type Options struct {
KBID string // --kb-id Context string // --context: record a specific context instead of the active one
KBName string // --kb KB string // --kb: kb_<id> or name; empty triggers interactive prompt on TTY
JSONOut bool // --json JSONOut bool // --json
} }
// linkResult is the typed payload emitted under data. Keep schema-aligned // linkResult is the typed payload emitted under data.
// with init.initResult so agents see the same shape regardless of entry point.
type linkResult struct { type linkResult struct {
Context string `json:"context"` Context string `json:"context"`
KBID string `json:"kb_id"` KBID string `json:"kb_id"`
@@ -41,24 +42,30 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{} opts := &Options{}
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "link", Use: "link",
Short: "Update or create the project link in the current directory", Short: "Bind the current directory to a knowledge base",
Long: `Writes (overwriting if present) .weknora/project.yaml in the current Long: `Writes .weknora/project.yaml in the current working directory pointing
working directory pointing at the supplied knowledge base. Unlike init, link at the supplied knowledge base. Subsequent commands run from this directory
never prompts and never fails on an existing file — it is the non-interactive (or any subdirectory) automatically resolve --kb from the link unless
re-link path used by scripts that switch between knowledge bases.`, overridden by the --kb flag or WEKNORA_KB_ID env var.
Example: ` weknora link --kb-id kb_abc
weknora link --kb staging`, Pass --kb <id-or-name> for non-interactive use (scripts, CI). Run on a TTY
without --kb to be prompted from the list of available KBs. Always overwrites
any existing link — re-run to switch.
AI agents: link writes to the user's working directory. Only run it when the
user explicitly asked to bind this directory; don't run it as a side effect.`,
Example: ` weknora link --kb kb_abc # explicit id
weknora link --kb engineering # name → id
weknora link # interactive (TTY)`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error { RunE: func(c *cobra.Command, _ []string) error {
return runLink(c.Context(), opts, f) return runLink(c.Context(), opts, f)
}, },
} }
cmd.Flags().StringVar(&opts.KBID, "kb-id", "", "Knowledge base id to link") cmd.Flags().StringVar(&opts.Context, "context", "", "Context to record in the link (defaults to active context)")
cmd.Flags().StringVar(&opts.KBName, "kb", "", "Knowledge base name (resolved to id)") cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base id (kb_…) or name; omit on a TTY for interactive prompt")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmd.MarkFlagsMutuallyExclusive("kb-id", "kb") agent.SetAgentHelp(cmd, "Writes .weknora/project.yaml binding cwd to a KB. Pass --kb (id or name) for non-interactive use. Always overwrites.")
cmd.MarkFlagsOneRequired("kb-id", "kb")
agent.SetAgentHelp(cmd, "Re-points .weknora/project.yaml to a KB. Pass --kb-id (or --kb name); never prompts, always overwrites.")
return cmd return cmd
} }
@@ -69,26 +76,14 @@ func runLink(ctx context.Context, opts *Options, f *cmdutil.Factory) error {
} }
linkPath := filepath.Join(cwd, projectlink.DirName, projectlink.FileName) linkPath := filepath.Join(cwd, projectlink.DirName, projectlink.FileName)
cfg, err := f.Config() ctxName, err := resolveContext(opts, f)
if err != nil { if err != nil {
return err return err
} }
ctxName := cfg.CurrentContext
if ctxName == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no active context; run `weknora auth login` first")
}
kbID, kbName := opts.KBID, "" kbID, kbName, err := resolveKB(ctx, opts, f)
if opts.KBName != "" { if err != nil {
cli, err := f.Client() return err
if err != nil {
return err
}
id, err := cmdutil.ResolveKBNameToID(ctx, cli, opts.KBName)
if err != nil {
return err
}
kbID, kbName = id, opts.KBName
} }
link := &projectlink.Project{ link := &projectlink.Project{
@@ -120,3 +115,73 @@ func runLink(ctx context.Context, opts *Options, f *cmdutil.Factory) error {
return nil return nil
} }
// resolveContext picks the auth context to record in the link.
func resolveContext(opts *Options, f *cmdutil.Factory) (string, error) {
if opts.Context != "" {
return opts.Context, nil
}
cfg, err := f.Config()
if err != nil {
return "", err
}
if cfg.CurrentContext == "" {
return "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no active context; run `weknora auth login` first")
}
return cfg.CurrentContext, nil
}
// resolveKB resolves --kb to (kbID, kbName). Name is empty when the user
// passed an id directly. Falls through to an interactive prompt on a TTY
// when --kb is empty; errors on non-TTY.
func resolveKB(ctx context.Context, opts *Options, f *cmdutil.Factory) (string, string, error) {
if opts.KB != "" {
if cmdutil.IsKBID(opts.KB) {
return opts.KB, "", nil
}
cli, err := f.Client()
if err != nil {
return "", "", err
}
id, err := cmdutil.ResolveKBNameToID(ctx, cli, opts.KB)
if err != nil {
return "", "", err
}
return id, opts.KB, nil
}
if !iostreams.IO.IsStdoutTTY() {
return "", "", cmdutil.NewError(cmdutil.CodeKBIDRequired, "--kb is required (no TTY for interactive prompt)")
}
cli, err := f.Client()
if err != nil {
return "", "", err
}
return promptForKB(ctx, cli, f)
}
// promptForKB lists available knowledge bases on stderr, then asks the user
// for an id or name. Resolved against the listed set so a typed name is
// converted to the canonical id.
func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory) (string, string, error) {
kbs, err := svc.ListKnowledgeBases(ctx)
if err != nil {
return "", "", cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "list knowledge bases")
}
if len(kbs) == 0 {
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active context; create one first")
}
fmt.Fprintln(iostreams.IO.Err, "Available knowledge bases:")
for _, kb := range kbs {
fmt.Fprintf(iostreams.IO.Err, " %s %s\n", kb.ID, kb.Name)
}
p := f.Prompter()
answer, err := p.Input("Knowledge base id or name", "")
if err != nil {
return "", "", cmdutil.Wrapf(cmdutil.CodeInputMissingFlag, err, "kb prompt")
}
for _, kb := range kbs {
if kb.ID == answer || kb.Name == answer {
return kb.ID, kb.Name, nil
}
}
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, fmt.Sprintf("knowledge base not found: %s", answer))
}
+33 -42
View File
@@ -1,7 +1,6 @@
package linkcmd package linkcmd
import ( import (
"bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -9,7 +8,6 @@ import (
"net/http/httptest" "net/http/httptest"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@@ -66,7 +64,7 @@ func TestLink_ByID(t *testing.T) {
out, _ := iostreams.SetForTest(t) out, _ := iostreams.SetForTest(t)
f := newFactory("default", nil) f := newFactory("default", nil)
opts := &Options{KBID: "kb_xxx"} opts := &Options{KB: "kb_xxx"}
require.NoError(t, runLink(context.Background(), opts, f)) require.NoError(t, runLink(context.Background(), opts, f))
linkPath := filepath.Join(dir, ".weknora", "project.yaml") linkPath := filepath.Join(dir, ".weknora", "project.yaml")
@@ -88,7 +86,7 @@ func TestLink_ByName(t *testing.T) {
}) })
cli := sdk.NewClient(srv.URL) cli := sdk.NewClient(srv.URL)
f := newFactory("default", cli) f := newFactory("default", cli)
opts := &Options{KBName: "foo"} opts := &Options{KB: "foo"}
require.NoError(t, runLink(context.Background(), opts, f)) require.NoError(t, runLink(context.Background(), opts, f))
p, err := projectlink.Load(filepath.Join(dir, ".weknora", "project.yaml")) p, err := projectlink.Load(filepath.Join(dir, ".weknora", "project.yaml"))
@@ -104,7 +102,7 @@ func TestLink_KBNotFound(t *testing.T) {
srv := fakeKBServer(t, []sdk.KnowledgeBase{{ID: "kb_a", Name: "foo"}}) srv := fakeKBServer(t, []sdk.KnowledgeBase{{ID: "kb_a", Name: "foo"}})
cli := sdk.NewClient(srv.URL) cli := sdk.NewClient(srv.URL)
f := newFactory("default", cli) f := newFactory("default", cli)
opts := &Options{KBName: "missing"} opts := &Options{KB: "missing"}
err := runLink(context.Background(), opts, f) err := runLink(context.Background(), opts, f)
require.Error(t, err) require.Error(t, err)
var typed *cmdutil.Error var typed *cmdutil.Error
@@ -112,46 +110,39 @@ func TestLink_KBNotFound(t *testing.T) {
assert.Equal(t, cmdutil.CodeKBNotFound, typed.Code) assert.Equal(t, cmdutil.CodeKBNotFound, typed.Code)
} }
// TestLink_MutuallyExclusive exercises the cobra flag-parse layer. Driving func TestLink_OverwritesExisting(t *testing.T) {
// the command with both --kb-id and --kb must surface a usage error before dir := t.TempDir()
// runLink runs. chdir(t, dir)
func TestLink_MutuallyExclusive(t *testing.T) { _, _ = iostreams.SetForTest(t)
// Pre-existing link.
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
require.NoError(t, projectlink.Save(linkPath, &projectlink.Project{
Context: "default", KBID: "kb_old",
}))
f := newFactory("default", nil)
opts := &Options{KB: "kb_new"}
require.NoError(t, runLink(context.Background(), opts, f))
p, err := projectlink.Load(linkPath)
require.NoError(t, err)
assert.Equal(t, "kb_new", p.KBID, "link should overwrite silently")
}
// TestLink_NonInteractive_NoKB exercises the non-TTY-without-flag error path.
// SetForTest gives us a non-TTY iostreams, so omitting --kb must error rather
// than hang on a prompt.
func TestLink_NonInteractive_NoKB(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
chdir(t, dir) chdir(t, dir)
_, _ = iostreams.SetForTest(t) _, _ = iostreams.SetForTest(t)
f := newFactory("default", nil) f := newFactory("default", nil)
cmd := NewCmd(f) opts := &Options{} // no KB
var stderr bytes.Buffer err := runLink(context.Background(), opts, f)
cmd.SetErr(&stderr) require.Error(t, err)
cmd.SetOut(&bytes.Buffer{}) var typed *cmdutil.Error
cmd.SetArgs([]string{"--kb-id", "kb_a", "--kb", "foo"}) require.ErrorAs(t, err, &typed)
cmd.SetContext(context.Background()) assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
err := cmd.Execute()
require.Error(t, err, "expected mutually-exclusive flag error")
assert.True(t,
strings.Contains(err.Error(), "if any flags in the group") ||
strings.Contains(err.Error(), "mutually exclusive") ||
strings.Contains(err.Error(), "exclusive"),
"error should mention mutual exclusivity, got %q", err.Error())
}
// TestLink_OneRequired exercises MarkFlagsOneRequired: zero of {kb-id, kb}
// must be a usage error.
func TestLink_OneRequired(t *testing.T) {
dir := t.TempDir()
chdir(t, dir)
_, _ = iostreams.SetForTest(t)
f := newFactory("default", nil)
cmd := NewCmd(f)
var stderr bytes.Buffer
cmd.SetErr(&stderr)
cmd.SetOut(&bytes.Buffer{})
cmd.SetArgs([]string{}) // neither flag
cmd.SetContext(context.Background())
err := cmd.Execute()
require.Error(t, err, "expected required-flag error")
} }
-10
View File
@@ -1,10 +1,4 @@
// Package cmd holds the cobra command tree. main.go calls Execute(). // Package cmd holds the cobra command tree. main.go calls Execute().
//
// v0.0 shipped: version / auth / search.
// v0.1 adds: whoami / doctor / kb (list + view) / context (use).
// v0.2 adds: init / link / kb (create + delete) / doc (list + upload + delete)
// / api / chat. The kb view command is the primary; "get"
// is preserved as a cobra alias for v0.0/v0.1 callers.
package cmd package cmd
import ( import (
@@ -21,11 +15,9 @@ import (
contextcmd "github.com/Tencent/WeKnora/cli/cmd/context" contextcmd "github.com/Tencent/WeKnora/cli/cmd/context"
"github.com/Tencent/WeKnora/cli/cmd/doc" "github.com/Tencent/WeKnora/cli/cmd/doc"
"github.com/Tencent/WeKnora/cli/cmd/doctor" "github.com/Tencent/WeKnora/cli/cmd/doctor"
initcmd "github.com/Tencent/WeKnora/cli/cmd/init"
"github.com/Tencent/WeKnora/cli/cmd/kb" "github.com/Tencent/WeKnora/cli/cmd/kb"
linkcmd "github.com/Tencent/WeKnora/cli/cmd/link" linkcmd "github.com/Tencent/WeKnora/cli/cmd/link"
"github.com/Tencent/WeKnora/cli/cmd/search" "github.com/Tencent/WeKnora/cli/cmd/search"
"github.com/Tencent/WeKnora/cli/cmd/whoami"
"github.com/Tencent/WeKnora/cli/internal/agent" "github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/build" "github.com/Tencent/WeKnora/cli/internal/build"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
@@ -177,11 +169,9 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`,
cmd.AddCommand(newVersionCmd(f)) cmd.AddCommand(newVersionCmd(f))
cmd.AddCommand(auth.NewCmdAuth(f)) cmd.AddCommand(auth.NewCmdAuth(f))
cmd.AddCommand(search.NewCmdSearch(f)) cmd.AddCommand(search.NewCmdSearch(f))
cmd.AddCommand(whoami.NewCmd(f))
cmd.AddCommand(doctor.NewCmd(f)) cmd.AddCommand(doctor.NewCmd(f))
cmd.AddCommand(kb.NewCmd(f)) cmd.AddCommand(kb.NewCmd(f))
cmd.AddCommand(contextcmd.NewCmd(f)) cmd.AddCommand(contextcmd.NewCmd(f))
cmd.AddCommand(initcmd.NewCmd(f))
cmd.AddCommand(linkcmd.NewCmd(f)) cmd.AddCommand(linkcmd.NewCmd(f))
cmd.AddCommand(doc.NewCmd(f)) cmd.AddCommand(doc.NewCmd(f))
cmd.AddCommand(apicmd.NewCmd(f)) cmd.AddCommand(apicmd.NewCmd(f))
+14 -14
View File
@@ -18,8 +18,8 @@ import (
// Options is the runtime configuration of one search invocation. // Options is the runtime configuration of one search invocation.
type Options struct { type Options struct {
Query string Query string
KBID string // resolved id, populated by RunE before validate() KB string // raw --kb flag value (kb_<id> or name)
KBName string // raw --kb flag value (name or, for legacy v0.0 callers, id) KBID string // resolved id, populated by RunE before HybridSearch
TopK int TopK int
VectorThreshold float64 VectorThreshold float64
KeywordThreshold float64 KeywordThreshold float64
@@ -34,12 +34,12 @@ type Service interface {
HybridSearch(ctx context.Context, kbID string, params *sdk.SearchParams) ([]*sdk.SearchResult, error) HybridSearch(ctx context.Context, kbID string, params *sdk.SearchParams) ([]*sdk.SearchResult, error)
} }
// NewCmdSearch builds `weknora search "<query>" --kb-id <id> | --kb <name>`. // NewCmdSearch builds `weknora search "<query>" --kb <id-or-name>`.
// //
// v0.0 shipped a single `--kb <id>` flag. v0.2 standardizes the KB-resolution // The single `--kb` flag accepts either a `kb_…` id (passed through) or a
// surface across all commands (init / link / doc / chat) on `--kb-id` (id) + // name (resolved via ListKnowledgeBases). Mirrors gcloud `--project`'s
// `--kb` (name → id via ListKnowledgeBases). search now follows the same // id-or-name auto-detection — the only mainstream pattern that collapses
// convention. The resolution chain is identical to Factory.ResolveKB. // the two forms onto one flag.
func NewCmdSearch(f *cmdutil.Factory) *cobra.Command { func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
opts := &Options{} opts := &Options{}
cmd := &cobra.Command{ cmd := &cobra.Command{
@@ -50,7 +50,7 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
opts.Query = strings.TrimSpace(args[0]) opts.Query = strings.TrimSpace(args[0])
// Validate input shape before touching the SDK so flag/arg misuse // Validate input shape before touching the SDK so flag/arg misuse
// surfaces fast (no auth / no client construction). KB resolution // surfaces fast (no auth / no client construction). KB resolution
// happens *after* — it needs a client. // happens *after* — name → id needs a live client.
if err := opts.validate(); err != nil { if err := opts.validate(); err != nil {
return err return err
} }
@@ -58,8 +58,10 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
if err != nil { if err != nil {
return err return err
} }
if opts.KBID == "" && opts.KBName != "" { if cmdutil.IsKBID(opts.KB) {
resolved, rerr := cmdutil.ResolveKBNameToID(c.Context(), cli, opts.KBName) opts.KBID = opts.KB
} else {
resolved, rerr := cmdutil.ResolveKBNameToID(c.Context(), cli, opts.KB)
if rerr != nil { if rerr != nil {
return rerr return rerr
} }
@@ -68,16 +70,14 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
return runSearch(c.Context(), opts, cli) return runSearch(c.Context(), opts, cli)
}, },
} }
cmd.Flags().StringVar(&opts.KBID, "kb-id", "", "Knowledge base id to search") cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base id (kb_…) or name")
cmd.Flags().StringVar(&opts.KBName, "kb", "", "Knowledge base name (resolved to id via list)")
cmd.Flags().IntVar(&opts.TopK, "top-k", 8, "Maximum results to return") cmd.Flags().IntVar(&opts.TopK, "top-k", 8, "Maximum results to return")
cmd.Flags().Float64Var(&opts.VectorThreshold, "vector-threshold", 0, "Vector retrieval similarity floor (per-channel, pre-fusion); 0 = no filter") cmd.Flags().Float64Var(&opts.VectorThreshold, "vector-threshold", 0, "Vector retrieval similarity floor (per-channel, pre-fusion); 0 = no filter")
cmd.Flags().Float64Var(&opts.KeywordThreshold, "keyword-threshold", 0, "Keyword retrieval score floor (per-channel, pre-fusion); 0 = no filter") cmd.Flags().Float64Var(&opts.KeywordThreshold, "keyword-threshold", 0, "Keyword retrieval score floor (per-channel, pre-fusion); 0 = no filter")
cmd.Flags().BoolVar(&opts.NoVector, "no-vector", false, "Disable the vector channel") cmd.Flags().BoolVar(&opts.NoVector, "no-vector", false, "Disable the vector channel")
cmd.Flags().BoolVar(&opts.NoKeyword, "no-keyword", false, "Disable the keyword channel") cmd.Flags().BoolVar(&opts.NoKeyword, "no-keyword", false, "Disable the keyword channel")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmd.MarkFlagsMutuallyExclusive("kb-id", "kb") _ = cmd.MarkFlagRequired("kb")
cmd.MarkFlagsOneRequired("kb-id", "kb")
return cmd return cmd
} }
-77
View File
@@ -1,77 +0,0 @@
// Package whoami implements `weknora whoami` — a top-level standalone leaf,
// the simplified counterpart of `auth status` that prints only user_id and
// tenant_id (spec §1.2). Use `auth status` for full diagnostics.
package whoami
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"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"
)
// Options captures the (sparse) configuration of `weknora whoami`.
type Options struct {
JSONOut bool
}
// Service is the narrow SDK surface this command depends on.
type Service interface {
GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResponse, error)
}
// result is the typed payload emitted by `--json`.
type result struct {
UserID string `json:"user_id"`
TenantID uint64 `json:"tenant_id,omitempty"`
}
// NewCmd builds the `weknora whoami` command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: "whoami",
Short: "Print user_id and tenant_id of the active context",
RunE: func(c *cobra.Command, _ []string) error {
cli, err := f.Client()
if err != nil {
return err
}
return runWhoami(c.Context(), opts, cli)
},
}
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
agent.SetAgentHelp(cmd, "Returns the active context principal as JSON envelope. Quick identity check; for full diagnostics use `weknora auth status`.")
return cmd
}
func runWhoami(ctx context.Context, opts *Options, svc Service) error {
if svc == nil {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no SDK client available; run `weknora auth login`")
}
resp, err := svc.GetCurrentUser(ctx)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "fetch current user")
}
if resp == nil || resp.Data.User == nil {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "server returned empty user; run `weknora auth login`")
}
r := result{UserID: resp.Data.User.ID}
if resp.Data.Tenant != nil {
r.TenantID = resp.Data.Tenant.ID
}
if opts.JSONOut {
return cmdutil.NewJSONExporter().Write(iostreams.IO.Out, format.Success(r, nil))
}
fmt.Fprintf(iostreams.IO.Out, "user_id: %s\n", r.UserID)
if r.TenantID != 0 {
fmt.Fprintf(iostreams.IO.Out, "tenant_id: %d\n", r.TenantID)
}
return nil
}
-80
View File
@@ -1,80 +0,0 @@
package whoami
import (
"context"
"errors"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeSvc struct {
resp *sdk.CurrentUserResponse
err error
}
func (f *fakeSvc) GetCurrentUser(_ context.Context) (*sdk.CurrentUserResponse, error) {
return f.resp, f.err
}
func newRespOK() *sdk.CurrentUserResponse {
r := &sdk.CurrentUserResponse{}
r.Data.User = &sdk.AuthUser{ID: "usr_abc"}
r.Data.Tenant = &sdk.AuthTenant{ID: 42}
return r
}
func TestWhoami_Human(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeSvc{resp: newRespOK()}
if err := runWhoami(context.Background(), &Options{}, svc); err != nil {
t.Fatalf("runWhoami: %v", err)
}
got := out.String()
if !strings.Contains(got, "user_id:") || !strings.Contains(got, "usr_abc") {
t.Errorf("expected user_id: usr_abc in %q", got)
}
if !strings.Contains(got, "tenant_id:") || !strings.Contains(got, "42") {
t.Errorf("expected tenant_id: 42 in %q", got)
}
}
func TestWhoami_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeSvc{resp: newRespOK()}
if err := runWhoami(context.Background(), &Options{JSONOut: true}, svc); err != nil {
t.Fatalf("runWhoami: %v", err)
}
got := out.String()
if !strings.Contains(got, `"ok":true`) {
t.Errorf("expected ok:true in %q", got)
}
if !strings.Contains(got, `"user_id":"usr_abc"`) {
t.Errorf("expected user_id field in %q", got)
}
}
func TestWhoami_Unauthenticated(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeSvc{err: errors.New("HTTP error 401: unauthenticated")}
err := runWhoami(context.Background(), &Options{}, svc)
if err == nil {
t.Fatal("expected error")
}
if !cmdutil.IsAuthError(err) {
t.Errorf("expected auth error, got %v", err)
}
}
func TestWhoami_NilUser(t *testing.T) {
// SDK could return success but without user pointer (server bug or partial response)
_, _ = iostreams.SetForTest(t)
svc := &fakeSvc{resp: &sdk.CurrentUserResponse{}} // Data.User == nil
err := runWhoami(context.Background(), &Options{}, svc)
if err == nil {
t.Fatal("expected error for nil user")
}
}
+4 -5
View File
@@ -56,10 +56,9 @@ const (
CodeLocalUnimplemented ErrorCode = "local.unimplemented" CodeLocalUnimplemented ErrorCode = "local.unimplemented"
CodeLocalContextNotFound ErrorCode = "local.context_not_found" CodeLocalContextNotFound ErrorCode = "local.context_not_found"
// v0.2 KB-resolution chain (spec §1.3) and project-link (spec §2.4) codes. // v0.2 KB-resolution chain (spec §1.3) and project-link (spec §2.4) codes.
CodeKBIDRequired ErrorCode = "local.kb_id_required" CodeKBIDRequired ErrorCode = "local.kb_id_required"
CodeKBNotFound ErrorCode = "local.kb_not_found" CodeKBNotFound ErrorCode = "local.kb_not_found"
CodeProjectAlreadyLinked ErrorCode = "local.project_already_linked" CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
// CodeUserAborted marks a user-cancelled destructive operation (declined a // CodeUserAborted marks a user-cancelled destructive operation (declined a
// confirm prompt). Distinct from SilentError so envelopes still carry a // confirm prompt). Distinct from SilentError so envelopes still carry a
// stable code; distinct from input.* because the user supplied valid args // stable code; distinct from input.* because the user supplied valid args
@@ -256,7 +255,7 @@ func AllCodes() []ErrorCode {
CodeLocalConfigCorrupt, CodeLocalKeychainDenied, CodeLocalFileIO, CodeLocalConfigCorrupt, CodeLocalKeychainDenied, CodeLocalFileIO,
CodeLocalUnimplemented, CodeLocalContextNotFound, CodeLocalUnimplemented, CodeLocalContextNotFound,
CodeKBIDRequired, CodeKBNotFound, CodeKBIDRequired, CodeKBNotFound,
CodeProjectAlreadyLinked, CodeProjectLinkCorrupt, CodeProjectLinkCorrupt,
CodeUserAborted, CodeUploadFileNotFound, CodeUserAborted, CodeUploadFileNotFound,
CodeSSEStreamAborted, CodeSessionCreateFailed, CodeSSEStreamAborted, CodeSessionCreateFailed,
// mcp // mcp
+5 -7
View File
@@ -141,8 +141,8 @@ func ToErrorBody(err error) *format.ErrorBody {
// defaultHint returns a canonical actionable hint for known error codes when // defaultHint returns a canonical actionable hint for known error codes when
// the call site didn't set one. Spec §1.4 zero-config matrix mandates // the call site didn't set one. Spec §1.4 zero-config matrix mandates
// `auth.unauthenticated` envelopes carry "run weknora auth login" — this // `auth.unauthenticated` envelopes carry "run weknora auth login" — this
// fallback covers the broad surface (whoami / auth status / kb list / kb get // fallback covers the broad surface (auth status / kb list / kb get / search)
// / search) without per-command hint plumbing. // without per-command hint plumbing.
// //
// Empty string for codes without a stable canonical hint. // Empty string for codes without a stable canonical hint.
func defaultHint(code ErrorCode) string { func defaultHint(code ErrorCode) string {
@@ -154,7 +154,7 @@ func defaultHint(code ErrorCode) string {
case CodeAuthForbidden: case CodeAuthForbidden:
return "active context lacks permission for this resource" return "active context lacks permission for this resource"
case CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch: case CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch:
return "verify tenant context with `weknora whoami`" return "verify tenant context with `weknora auth status`"
case CodeNetworkError: case CodeNetworkError:
return "check base URL reachability with `weknora doctor`" return "check base URL reachability with `weknora doctor`"
case CodeServerIncompatibleVersion: case CodeServerIncompatibleVersion:
@@ -176,13 +176,11 @@ func defaultHint(code ErrorCode) string {
case CodeLocalFileIO: case CodeLocalFileIO:
return "check file permissions under $XDG_CONFIG_HOME/weknora/" return "check file permissions under $XDG_CONFIG_HOME/weknora/"
case CodeKBIDRequired: case CodeKBIDRequired:
return "run `weknora init` to link a knowledge base, or pass --kb-id" return "run `weknora link` to bind this directory to a knowledge base, or pass --kb"
case CodeKBNotFound: case CodeKBNotFound:
return "list available with `weknora kb list`" return "list available with `weknora kb list`"
case CodeProjectAlreadyLinked:
return "use --force to overwrite, or `weknora link` to update"
case CodeProjectLinkCorrupt: case CodeProjectLinkCorrupt:
return "remove .weknora/project.yaml and run `weknora init` again" return "remove .weknora/project.yaml and run `weknora link` again"
case CodeUserAborted: case CodeUserAborted:
return "no action taken; pass -y/--yes to skip the confirmation prompt" return "no action taken; pass -y/--yes to skip the confirmation prompt"
case CodeUploadFileNotFound: case CodeUploadFileNotFound:
+16 -16
View File
@@ -22,7 +22,9 @@ import (
// //
// Four closures (ADR-4): // Four closures (ADR-4):
// - Config: parses ~/.config/weknora/config.yaml (no network) // - Config: parses ~/.config/weknora/config.yaml (no network)
// - Client: constructs the SDK client (network: server compat probe + cached) // - Client: constructs the SDK client; only Secrets is sync.Once-cached,
// so callers should hold the returned *sdk.Client across
// multiple SDK calls within one invocation
// - Prompter: returns interactive prompter; agent mode returns AgentPrompter // - Prompter: returns interactive prompter; agent mode returns AgentPrompter
// - Secrets: builds the OS keyring / file fallback credential store the // - Secrets: builds the OS keyring / file fallback credential store the
// first time it is requested (probing the keyring at startup // first time it is requested (probing the keyring at startup
@@ -147,25 +149,23 @@ func buildClient(f *Factory) (*sdk.Client, error) {
} }
// ResolveKB returns the active KB id for the running command, applying the // ResolveKB returns the active KB id for the running command, applying the
// 5-level fallback chain (highest to lowest): // 4-level fallback chain (highest to lowest):
// 1. --kb-id flag (explicit ID) // 1. --kb flag (kb_<...> id passed through; anything else resolved via
// 2. --kb flag (name → id via ListKnowledgeBases) // ListKnowledgeBases as a name → id lookup; mirrors gcloud --project's
// 3. WEKNORA_KB_ID env // id-or-name auto-detection)
// 4. .weknora/project.yaml (walk-up from cwd) // 2. WEKNORA_KB_ID env (always an explicit id)
// 5. error: kb_id required // 3. .weknora/project.yaml (walk-up from cwd)
// // 4. error: kb required
// Sub-commands that need a KB declare both --kb-id and --kb local flags;
// commands that don't (e.g. kb list, init) skip this method entirely.
func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) { func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) {
if id, _ := cmd.Flags().GetString("kb-id"); id != "" { if v, _ := cmd.Flags().GetString("kb"); v != "" {
return id, nil if IsKBID(v) {
} return v, nil
if name, _ := cmd.Flags().GetString("kb"); name != "" { }
c, err := f.Client() c, err := f.Client()
if err != nil { if err != nil {
return "", err return "", err
} }
return ResolveKBNameToID(cmd.Context(), c, name) return ResolveKBNameToID(cmd.Context(), c, v)
} }
if v := os.Getenv("WEKNORA_KB_ID"); v != "" { if v := os.Getenv("WEKNORA_KB_ID"); v != "" {
return v, nil return v, nil
@@ -182,7 +182,7 @@ func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) {
} }
} }
} }
return "", NewError(CodeKBIDRequired, "kb id is required") return "", NewError(CodeKBIDRequired, "kb is required")
} }
// loadSecret returns the stored value for (context, key); ErrNotFound becomes // loadSecret returns the stored value for (context, key); ErrNotFound becomes
+14 -17
View File
@@ -264,18 +264,15 @@ func (c *countingSecrets) Get(ctx, key string) (string, error) {
return c.MemStore.Get(ctx, key) return c.MemStore.Get(ctx, key)
} }
// makeResolveKBCmd builds a minimal cobra.Command carrying --kb-id / --kb local // makeResolveKBCmd builds a minimal cobra.Command carrying the single --kb
// flags so cmd.Flags().GetString lookups in ResolveKB exercise the flag path. // local flag so cmd.Flags().GetString lookups in ResolveKB exercise the flag
func makeResolveKBCmd(t *testing.T, kbID, kbName string) *cobra.Command { // path. The single flag accepts either a kb_<id> or a name.
func makeResolveKBCmd(t *testing.T, kb string) *cobra.Command {
t.Helper() t.Helper()
c := &cobra.Command{Use: "x"} c := &cobra.Command{Use: "x"}
c.Flags().String("kb-id", "", "")
c.Flags().String("kb", "", "") c.Flags().String("kb", "", "")
if kbID != "" { if kb != "" {
require.NoError(t, c.Flags().Set("kb-id", kbID)) require.NoError(t, c.Flags().Set("kb", kb))
}
if kbName != "" {
require.NoError(t, c.Flags().Set("kb", kbName))
} }
c.SetContext(context.Background()) c.SetContext(context.Background())
return c return c
@@ -305,11 +302,11 @@ func fakeKBServer(t *testing.T, kbs []sdk.KnowledgeBase) *httptest.Server {
return srv return srv
} }
// TestResolveKB_Chain exercises the 5-level fallback chain. Each sub-test // TestResolveKB_Chain exercises the 4-level fallback chain. Each sub-test
// isolates cwd / env / closure from the others. // isolates cwd / env / closure from the others.
func TestResolveKB_Chain(t *testing.T) { func TestResolveKB_Chain(t *testing.T) {
t.Run("flag_kb_id_wins", func(t *testing.T) { t.Run("flag_kb_id_wins", func(t *testing.T) {
// flag → no SDK call, no env, no disk. // kb_<id> form → no SDK call, no env, no disk.
t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose") t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose")
dir := t.TempDir() dir := t.TempDir()
resolveKBChdir(t, dir) resolveKBChdir(t, dir)
@@ -323,7 +320,7 @@ func TestResolveKB_Chain(t *testing.T) {
return nil, errors.New("must not be called") return nil, errors.New("must not be called")
}, },
} }
got, err := f.ResolveKB(makeResolveKBCmd(t, "kb_explicit", "")) got, err := f.ResolveKB(makeResolveKBCmd(t, "kb_explicit"))
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "kb_explicit", got) assert.Equal(t, "kb_explicit", got)
assert.Equal(t, 0, clientCalls) assert.Equal(t, 0, clientCalls)
@@ -338,7 +335,7 @@ func TestResolveKB_Chain(t *testing.T) {
f := &Factory{ f := &Factory{
Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil }, Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil },
} }
got, err := f.ResolveKB(makeResolveKBCmd(t, "", "foo")) got, err := f.ResolveKB(makeResolveKBCmd(t, "foo"))
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "kb_a", got) assert.Equal(t, "kb_a", got)
}) })
@@ -349,7 +346,7 @@ func TestResolveKB_Chain(t *testing.T) {
f := &Factory{ f := &Factory{
Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil }, Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil },
} }
_, err := f.ResolveKB(makeResolveKBCmd(t, "", "missing")) _, err := f.ResolveKB(makeResolveKBCmd(t, "missing"))
require.Error(t, err) require.Error(t, err)
var typed *Error var typed *Error
require.ErrorAs(t, err, &typed) require.ErrorAs(t, err, &typed)
@@ -364,7 +361,7 @@ func TestResolveKB_Chain(t *testing.T) {
require.NoError(t, projectlink.Save(filepath.Join(dir, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"})) require.NoError(t, projectlink.Save(filepath.Join(dir, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"}))
f := &Factory{} f := &Factory{}
got, err := f.ResolveKB(makeResolveKBCmd(t, "", "")) got, err := f.ResolveKB(makeResolveKBCmd(t, ""))
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "kb_env", got) assert.Equal(t, "kb_env", got)
}) })
@@ -379,7 +376,7 @@ func TestResolveKB_Chain(t *testing.T) {
resolveKBChdir(t, deep) resolveKBChdir(t, deep)
f := &Factory{} f := &Factory{}
got, err := f.ResolveKB(makeResolveKBCmd(t, "", "")) got, err := f.ResolveKB(makeResolveKBCmd(t, ""))
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "kb_proj", got) assert.Equal(t, "kb_proj", got)
}) })
@@ -391,7 +388,7 @@ func TestResolveKB_Chain(t *testing.T) {
resolveKBChdir(t, dir) resolveKBChdir(t, dir)
f := &Factory{} f := &Factory{}
_, err := f.ResolveKB(makeResolveKBCmd(t, "", "")) _, err := f.ResolveKB(makeResolveKBCmd(t, ""))
require.Error(t, err) require.Error(t, err)
var typed *Error var typed *Error
require.ErrorAs(t, err, &typed) require.ErrorAs(t, err, &typed)
+13 -2
View File
@@ -3,10 +3,21 @@ package cmdutil
import ( import (
"context" "context"
"fmt" "fmt"
"strings"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
) )
// kbIDPrefix is the server-emitted prefix that marks a string as a KB id
// (rather than a KB name). The single `--kb` flag uses it for client-side
// id-vs-name auto-detection — the same pattern gcloud uses for --project
// (numeric id vs project-id form).
const kbIDPrefix = "kb_"
// IsKBID reports whether s looks like a KB id. Used by Factory.ResolveKB and
// any caller that accepts a single id-or-name selector value.
func IsKBID(s string) bool { return strings.HasPrefix(s, kbIDPrefix) }
// KBLister is the narrow SDK surface ResolveKBNameToID depends on. The // KBLister is the narrow SDK surface ResolveKBNameToID depends on. The
// production *sdk.Client satisfies it; tests inject fakes without standing // production *sdk.Client satisfies it; tests inject fakes without standing
// up an HTTP server. // up an HTTP server.
@@ -15,8 +26,8 @@ type KBLister interface {
} }
// ResolveKBNameToID looks up a knowledge base by name and returns its ID. // ResolveKBNameToID looks up a knowledge base by name and returns its ID.
// Used by `init`, `link`, and `Factory.ResolveKB` — a single lookup so the // Used by `link` and `Factory.ResolveKB` — a single lookup so the match
// match policy (currently exact case-sensitive) lives in one place. // policy (currently exact case-sensitive) lives in one place.
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) { func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
kbs, err := lister.ListKnowledgeBases(ctx) kbs, err := lister.ListKnowledgeBases(ctx)
if err != nil { if err != nil {