Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

refactor(cli): align command surface with mainstream conventions

nullkey8bcbf5a15459
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index dfdc7ee29..78db2710a 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -96,14 +96,20 @@ The command tree follows `<noun> <verb>` (gh style). Verbs are:
| Verb | Semantics | Example |
|---|---|---|
| `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` |
| `delete` | Destructive remove | `kb delete <id> -y` |
| `upload` | Bulk write content | `doc upload <file>` |
| `use` | Switch active selection | `context use <name>` |
-Top-level RAG / connectivity verbs: `chat`, `search`, `api`, `init`, `link`,
-`auth`, `whoami`, `doctor`, `version`.
+Top-level RAG / connectivity verbs: `chat`, `search`, `api`, `link`,
+`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
the real command unless explicitly asked. The dry-run envelope is the
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.
(Additional safety guidance — e.g. "do not switch context unless the
diff --git a/cli/acceptance/contract/envelope_test.go b/cli/acceptance/contract/envelope_test.go
index e556fff78..e02a0d2c6 100644
--- a/cli/acceptance/contract/envelope_test.go
+++ b/cli/acceptance/contract/envelope_test.go
@@ -72,20 +72,7 @@ var envelopeCases = []envelopeCase{
args: []string{"version", "--json"},
},
- // 2-3. whoami — single SDK call to /api/v1/auth/me.
- {
- 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
+ // 2. doctor.success_offline — only credential_storage runs; the three
// network checks are skipped. Stable details + summary.
{
name: "doctor.success_offline",
@@ -93,7 +80,7 @@ var envelopeCases = []envelopeCase{
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
// runs (independent). v0.2 contract: any check=fail flips envelope.ok
// to false and exits 1 (RunE returns SilentError so the data envelope
@@ -105,7 +92,7 @@ var envelopeCases = []envelopeCase{
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",
args: []string{"kb", "list", "--json"},
@@ -123,18 +110,18 @@ var envelopeCases = []envelopeCase{
wantErr: true,
},
{
- name: "kb_get.success",
- args: []string{"kb", "get", "kb1", "--json"},
+ name: "kb_view.success",
+ args: []string{"kb", "view", "kb1", "--json"},
server: kbGetOne,
},
{
- name: "kb_get.error_resource_not_found",
- args: []string{"kb", "get", "missing", "--json"},
+ name: "kb_view.error_resource_not_found",
+ args: []string{"kb", "view", "missing", "--json"},
server: always404,
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",
args: []string{"context", "use", "production"},
@@ -153,7 +140,7 @@ var envelopeCases = []envelopeCase{
},
// (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",
args: []string{"auth", "status", "--json"},
@@ -166,24 +153,27 @@ var envelopeCases = []envelopeCase{
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",
- args: []string{"search", "query", "--kb-id=kb1", "--top-k=3", "--json"},
+ args: []string{"search", "query", "--kb=kb_1", "--top-k=3", "--json"},
server: searchTwoResults,
},
{
name: "search.error_resource_not_found",
- args: []string{"search", "query", "--kb-id=missing", "--json"},
+ args: []string{"search", "query", "--kb=kb_missing", "--json"},
server: always404,
wantErr: true,
},
{
- // Mutex flag violation. Validation runs before f.Client(), so the
- // server mock is never consumed; we still pass --kb to satisfy the
- // MarkFlagRequired check that fires earlier in cobra's parse phase.
+ // --no-vector + --no-keyword is the input.invalid case; --kb=kb_1 is
+ // just there to satisfy MarkFlagRequired so validation runs deep
+ // enough to hit the mutex-channel check.
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,
},
}
@@ -341,7 +331,7 @@ func kbGetOne(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)
return
}
diff --git a/cli/acceptance/contract/errorcodes_test.go b/cli/acceptance/contract/errorcodes_test.go
index 4d8265be5..f54577c81 100644
--- a/cli/acceptance/contract/errorcodes_test.go
+++ b/cli/acceptance/contract/errorcodes_test.go
@@ -184,8 +184,6 @@ func identToErrorCode(name string) (cmdutil.ErrorCode, bool) {
return cmdutil.CodeKBIDRequired, true
case "CodeKBNotFound":
return cmdutil.CodeKBNotFound, true
- case "CodeProjectAlreadyLinked":
- return cmdutil.CodeProjectAlreadyLinked, true
case "CodeProjectLinkCorrupt":
return cmdutil.CodeProjectLinkCorrupt, true
case "CodeUserAborted":
diff --git a/cli/acceptance/e2e/e2e_test.go b/cli/acceptance/e2e/e2e_test.go
index f83d75dcc..48ad224ce 100644
--- a/cli/acceptance/e2e/e2e_test.go
+++ b/cli/acceptance/e2e/e2e_test.go
@@ -74,7 +74,7 @@ func TestRAGFullLoop(t *testing.T) {
// 2. doc upload
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)
docID, _ := docData["id"].(string)
if docID == "" {
@@ -86,7 +86,7 @@ func TestRAGFullLoop(t *testing.T) {
waitDocReady(t, bin, env, kbID, docID, 90*time.Second)
// 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)
results, _ := searchData["results"].([]any)
if len(results) == 0 {
@@ -96,7 +96,7 @@ func TestRAGFullLoop(t *testing.T) {
// 5. chat — verify LLM answer + references in --json + --no-stream mode
// (--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)
answer, _ := chatData["answer"].(string)
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)
tick := 2 * time.Second
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)
items, _ := data["items"].([]any)
for _, it := range items {
diff --git a/cli/acceptance/testdata/envelopes/kb_get.error_resource_not_found.json b/cli/acceptance/testdata/envelopes/kb_view.error_resource_not_found.json
similarity index 100%
rename from cli/acceptance/testdata/envelopes/kb_get.error_resource_not_found.json
rename to cli/acceptance/testdata/envelopes/kb_view.error_resource_not_found.json
diff --git a/cli/acceptance/testdata/envelopes/kb_get.success.json b/cli/acceptance/testdata/envelopes/kb_view.success.json
similarity index 100%
rename from cli/acceptance/testdata/envelopes/kb_get.success.json
rename to cli/acceptance/testdata/envelopes/kb_view.success.json
diff --git a/cli/acceptance/testdata/envelopes/search.success.json b/cli/acceptance/testdata/envelopes/search.success.json
index 2251f444d..a3dd63f2f 100644
--- a/cli/acceptance/testdata/envelopes/search.success.json
+++ b/cli/acceptance/testdata/envelopes/search.success.json
@@ -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}
diff --git a/cli/cmd/api/api.go b/cli/cmd/api/api.go
index 98a033f71..2c943526c 100644
--- a/cli/cmd/api/api.go
+++ b/cli/cmd/api/api.go
@@ -1,10 +1,12 @@
// Package api implements the `weknora api` raw HTTP passthrough command.
//
-// Mirrors `gh api` ergonomics: 2 positionals (method, path), --data /
-// --data-file mutually exclusive body source, default raw response body to
-// stdout, --json wraps in CLI envelope. Reuses 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.
+// Mirrors `gh api` ergonomics: 1 positional (path) + `-X/--method` flag,
+// default GET (auto-promoted to POST when a body is supplied via --data /
+// --data-file). The two body-source flags are mutually exclusive. Default
+// raw response body to stdout; --json wraps in CLI envelope. Reuses
+// 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
import (
@@ -27,6 +29,7 @@ import (
// Options captures `weknora api` flag state.
type Options struct {
+ Method string
Data string
DataFile string
JSONOut bool
@@ -46,41 +49,45 @@ type Service interface {
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
- Use: "api <method> <path>",
+ Use: "api <path>",
Short: "Make a raw API request to the WeKnora server",
Long: `Send an HTTP request through the SDK and print the response.
-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).
+The default method is GET; passing --data / --data-file auto-promotes it to
+POST. Use -X/--method to override (DELETE / PUT / PATCH / HEAD).
+
+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:
- weknora api GET /api/v1/knowledge-bases
- weknora api POST /api/v1/knowledge-bases --data '{"name":"foo"}'
- weknora api DELETE /api/v1/knowledge-bases/kb_xxx`,
- Args: cobra.ExactArgs(2),
+ weknora api /api/v1/knowledge-bases # GET
+ weknora api /api/v1/knowledge-bases --data '{"name":"foo"}' # POST (auto)
+ weknora api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
+ Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.DryRun = cmdutil.IsDryRun(c)
opts.Yes, _ = c.Flags().GetBool("yes")
- method := strings.ToUpper(args[0])
+ method := resolveMethod(opts)
// Escape-hatch DELETE through `weknora api` is just as destructive
// as `weknora kb delete` — exit-10 protocol must apply (AGENTS.md).
// Dry-run is read-only preview, so it skips confirmation.
- if !opts.DryRun && method == "DELETE" {
- if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, opts.JSONOut, "endpoint", args[1]); err != nil {
+ if !opts.DryRun && method == http.MethodDelete {
+ if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, opts.JSONOut, "endpoint", args[0]); err != nil {
return err
}
}
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()
if err != nil {
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().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)")
@@ -89,14 +96,29 @@ Examples:
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,
-// classify status, and emit either the raw body or a JSON envelope.
-func runAPI(ctx context.Context, opts *Options, svc Service, methodArg, path string) error {
- method := strings.ToUpper(methodArg)
+// classify status, and emit either the raw body or a JSON envelope. The
+// caller is responsible for resolving the method (defaults / auto-POST)
+// 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 {
- case "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD":
+ case http.MethodGet, http.MethodPost, http.MethodPut,
+ http.MethodPatch, http.MethodDelete, http.MethodHead:
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, "/") {
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
// 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
- if method == "DELETE" {
+ if method == http.MethodDelete {
level = format.RiskHighRiskWrite
}
preview := map[string]any{"method": method, "path": path}
diff --git a/cli/cmd/api/api_test.go b/cli/cmd/api/api_test.go
index 873340e86..ed1d6c7a0 100644
--- a/cli/cmd/api/api_test.go
+++ b/cli/cmd/api/api_test.go
@@ -208,7 +208,7 @@ func TestAPI_DELETE_RequiresConfirmation(t *testing.T) {
Client: func() (*sdk.Client, error) { return nil, nil },
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()
if err == nil {
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 },
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 {
t.Fatalf("execute: %v", err)
}
diff --git a/cli/cmd/chat/chat.go b/cli/cmd/chat/chat.go
index 76637f993..2010a6202 100644
--- a/cli/cmd/chat/chat.go
+++ b/cli/cmd/chat/chat.go
@@ -77,7 +77,7 @@ answer back. By default a fresh session is created on first invocation; pass
Modes:
TTY (default): live token streaming + reference footer
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 "Continue?" --session-id sess_abc`,
Args: cobra.MinimumNArgs(1),
@@ -98,12 +98,10 @@ Modes:
return runChat(c.Context(), opts, cli)
},
}
- cmd.Flags().String("kb-id", "", "Knowledge base ID (overrides project link / env)")
- cmd.Flags().String("kb", "", "Knowledge base name (resolved via list)")
+ cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides project link / env)")
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.JSONOut, "json", false, "Emit a single JSON envelope (implies --no-stream)")
- cmd.MarkFlagsMutuallyExclusive("kb-id", "kb")
return cmd
}
diff --git a/cli/cmd/doc/list.go b/cli/cmd/doc/list.go
index 6c3020199..d62f3637f 100644
--- a/cli/cmd/doc/list.go
+++ b/cli/cmd/doc/list.go
@@ -50,13 +50,15 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
Use: "list",
Short: "List documents in a knowledge base",
Long: `Lists documents (uploaded files / web pages / inline text) in the
-resolved knowledge base. KB id resolution follows the standard 5-level chain:
---kb-id flag > --kb name > WEKNORA_KB_ID env > .weknora/project.yaml > error.
+resolved knowledge base. KB resolution follows the standard 4-level chain:
+--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;
backend storage order is not guaranteed and varies between deployments.`,
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`,
Args: cobra.NoArgs,
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)
},
}
- // --kb-id / --kb are read by Factory.ResolveKB; declare them here so
- // Cobra parses the values into the command's flag set.
- cmd.Flags().String("kb-id", "", "Knowledge base id (overrides env / project link)")
- cmd.Flags().String("kb", "", "Knowledge base name (resolved to id)")
+ // --kb is read by Factory.ResolveKB; declare it here so cobra parses the
+ // value into the command's flag set.
+ cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides env / project link)")
cmd.Flags().IntVar(&opts.Page, "page", 1, "Page number (1-based)")
cmd.Flags().IntVar(&opts.PageSize, "page-size", 20, "Items per page")
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-id 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 when not running inside a project.")
return cmd
}
diff --git a/cli/cmd/doc/list_test.go b/cli/cmd/doc/list_test.go
index e9aebe64c..d51b87ac8 100644
--- a/cli/cmd/doc/list_test.go
+++ b/cli/cmd/doc/list_test.go
@@ -135,7 +135,7 @@ func TestList_KBIDRequired(t *testing.T) {
}
cmd := NewCmdList(f)
cmd.SetContext(context.Background())
- cmd.SetArgs([]string{}) // no --kb-id, no --kb
+ cmd.SetArgs([]string{}) // no --kb
cmd.SilenceErrors = true
cmd.SilenceUsage = true
err := cmd.Execute()
@@ -146,9 +146,9 @@ func TestList_KBIDRequired(t *testing.T) {
assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
}
-// TestList_KBIDFlagWiredToResolveKB confirms that a --kb-id passed at the
-// cobra layer reaches Factory.ResolveKB and skips the Client() call.
-func TestList_KBIDFlagWiredToResolveKB(t *testing.T) {
+// TestList_KBFlagWiredToResolveKB confirms that --kb=kb_<id> passed at the
+// cobra layer reaches Factory.ResolveKB and short-circuits without listing.
+func TestList_KBFlagWiredToResolveKB(t *testing.T) {
chdirIsolated(t)
_, _ = iostreams.SetForTest(t)
@@ -162,20 +162,20 @@ func TestList_KBIDFlagWiredToResolveKB(t *testing.T) {
return nil, errors.New("forced-after-resolvekb")
},
}
- // With --kb-id supplied, ResolveKB short-circuits without consulting the
- // client. The RunE then asks for the client to run the actual list — that
- // call triggers the forced error. Surfacing "forced-after-resolvekb"
- // (rather than CodeKBIDRequired) is the proof point that --kb-id was
- // honored.
+ // With --kb=kb_<id> supplied, ResolveKB short-circuits on the prefix
+ // match without consulting the client. The RunE then asks for the client
+ // to run the actual list — that call triggers the forced error.
+ // Surfacing "forced-after-resolvekb" (rather than CodeKBIDRequired) is
+ // the proof point that --kb was honored.
cmd := NewCmdList(f)
cmd.SetContext(context.Background())
- cmd.SetArgs([]string{"--kb-id", "kb_explicit"})
+ cmd.SetArgs([]string{"--kb", "kb_explicit"})
cmd.SilenceErrors = true
cmd.SilenceUsage = true
err := cmd.Execute()
require.Error(t, err, "expected client construction error")
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.
diff --git a/cli/cmd/doc/upload.go b/cli/cmd/doc/upload.go
index 02fd087e8..412b21690 100644
--- a/cli/cmd/doc/upload.go
+++ b/cli/cmd/doc/upload.go
@@ -45,8 +45,9 @@ func NewCmdUpload(f *cmdutil.Factory) *cobra.Command {
Use: "upload <file>",
Short: "Upload a local file to the knowledge base",
Long: `Uploads a file (PDF / DOCX / Markdown / TXT / etc.) to the resolved
-knowledge base. KB id resolution follows the standard 5-level chain:
---kb-id flag > --kb name > WEKNORA_KB_ID env > .weknora/project.yaml > error.
+knowledge base. KB resolution follows the standard 4-level chain:
+--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
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
planned for v0.3.`,
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"`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
@@ -78,12 +80,10 @@ planned for v0.3.`,
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 name (resolved to id)")
+ cmd.Flags().String("kb", "", "Knowledge base id (kb_…) or name (overrides env / project link)")
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.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-id 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 outside a linked project.")
return cmd
}
diff --git a/cli/cmd/init/init.go b/cli/cmd/init/init.go
deleted file mode 100644
index 491553c97..000000000
--- a/cli/cmd/init/init.go
+++ /dev/null
@@ -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))
-}
diff --git a/cli/cmd/init/init_test.go b/cli/cmd/init/init_test.go
deleted file mode 100644
index 84c6e6308..000000000
--- a/cli/cmd/init/init_test.go
+++ /dev/null
@@ -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"`)
-}
diff --git a/cli/cmd/kb/view.go b/cli/cmd/kb/view.go
index ecd70fa90..20da8314d 100644
--- a/cli/cmd/kb/view.go
+++ b/cli/cmd/kb/view.go
@@ -24,16 +24,15 @@ type ViewService interface {
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
}
-// NewCmdView builds `weknora kb view <id>`. The `get` alias is kept for one
-// minor release so v0.0/v0.1 callers don't break; the help text shows `view`
-// as primary, mirroring `gh repo view` (https://cli.github.com/manual/gh_repo_view).
+// NewCmdView builds `weknora kb view <id>`. Mirrors `gh repo view`
+// (https://cli.github.com/manual/gh_repo_view) — the established mainstream
+// verb for single-resource reads.
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
opts := &ViewOptions{}
cmd := &cobra.Command{
- Use: "view <id>",
- Aliases: []string{"get"},
- Short: "Show a knowledge base by ID",
- Args: cobra.ExactArgs(1),
+ Use: "view <id>",
+ Short: "Show a knowledge base by ID",
+ Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
cli, err := f.Client()
if err != nil {
@@ -43,7 +42,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
},
}
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
}
diff --git a/cli/cmd/link/link.go b/cli/cmd/link/link.go
index 62c6fb016..51d30f861 100644
--- a/cli/cmd/link/link.go
+++ b/cli/cmd/link/link.go
@@ -1,7 +1,9 @@
-// Package linkcmd implements `weknora link` — re-points an existing
-// .weknora/project.yaml at a different knowledge base. Distinct from
-// `weknora init`: link assumes the directory is already a project (or you
-// want one without going through the init wizard) and never prompts.
+// Package linkcmd implements `weknora link` — binds the current working
+// directory to a knowledge base by writing .weknora/project.yaml. Always
+// overwrites an existing link silently, mirroring `vercel link` /
+// `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
import (
@@ -22,13 +24,12 @@ import (
// Options captures `weknora link` flags.
type Options struct {
- KBID string // --kb-id
- KBName string // --kb
+ Context string // --context: record a specific context instead of the active one
+ KB string // --kb: kb_<id> or name; empty triggers interactive prompt on TTY
JSONOut bool // --json
}
-// linkResult is the typed payload emitted under data. Keep schema-aligned
-// with init.initResult so agents see the same shape regardless of entry point.
+// linkResult is the typed payload emitted under data.
type linkResult struct {
Context string `json:"context"`
KBID string `json:"kb_id"`
@@ -41,24 +42,30 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: "link",
- Short: "Update or create the project link in the current directory",
- Long: `Writes (overwriting if present) .weknora/project.yaml in the current
-working directory pointing at the supplied knowledge base. Unlike init, link
-never prompts and never fails on an existing file — it is the non-interactive
-re-link path used by scripts that switch between knowledge bases.`,
- Example: ` weknora link --kb-id kb_abc
- weknora link --kb staging`,
+ Short: "Bind the current directory to a knowledge base",
+ Long: `Writes .weknora/project.yaml in the current working directory pointing
+at the supplied knowledge base. Subsequent commands run from this directory
+(or any subdirectory) automatically resolve --kb from the link unless
+overridden by the --kb flag or WEKNORA_KB_ID env var.
+
+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,
RunE: func(c *cobra.Command, _ []string) error {
return runLink(c.Context(), opts, f)
},
}
- 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().StringVar(&opts.Context, "context", "", "Context to record in the link (defaults to active context)")
+ 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.MarkFlagsMutuallyExclusive("kb-id", "kb")
- 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.")
+ agent.SetAgentHelp(cmd, "Writes .weknora/project.yaml binding cwd to a KB. Pass --kb (id or name) for non-interactive use. Always overwrites.")
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)
- cfg, err := f.Config()
+ ctxName, err := resolveContext(opts, f)
if err != nil {
return err
}
- ctxName := cfg.CurrentContext
- if ctxName == "" {
- return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no active context; run `weknora auth login` first")
- }
- kbID, kbName := opts.KBID, ""
- 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
- }
- kbID, kbName = id, opts.KBName
+ kbID, kbName, err := resolveKB(ctx, opts, f)
+ if err != nil {
+ return err
}
link := &projectlink.Project{
@@ -120,3 +115,73 @@ func runLink(ctx context.Context, opts *Options, f *cmdutil.Factory) error {
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))
+}
diff --git a/cli/cmd/link/link_test.go b/cli/cmd/link/link_test.go
index 044a1b65e..4bcbfb826 100644
--- a/cli/cmd/link/link_test.go
+++ b/cli/cmd/link/link_test.go
@@ -1,7 +1,6 @@
package linkcmd
import (
- "bytes"
"context"
"encoding/json"
"errors"
@@ -9,7 +8,6 @@ import (
"net/http/httptest"
"os"
"path/filepath"
- "strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -66,7 +64,7 @@ func TestLink_ByID(t *testing.T) {
out, _ := iostreams.SetForTest(t)
f := newFactory("default", nil)
- opts := &Options{KBID: "kb_xxx"}
+ opts := &Options{KB: "kb_xxx"}
require.NoError(t, runLink(context.Background(), opts, f))
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
@@ -88,7 +86,7 @@ func TestLink_ByName(t *testing.T) {
})
cli := sdk.NewClient(srv.URL)
f := newFactory("default", cli)
- opts := &Options{KBName: "foo"}
+ opts := &Options{KB: "foo"}
require.NoError(t, runLink(context.Background(), opts, f))
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"}})
cli := sdk.NewClient(srv.URL)
f := newFactory("default", cli)
- opts := &Options{KBName: "missing"}
+ opts := &Options{KB: "missing"}
err := runLink(context.Background(), opts, f)
require.Error(t, err)
var typed *cmdutil.Error
@@ -112,46 +110,39 @@ func TestLink_KBNotFound(t *testing.T) {
assert.Equal(t, cmdutil.CodeKBNotFound, typed.Code)
}
-// TestLink_MutuallyExclusive exercises the cobra flag-parse layer. Driving
-// the command with both --kb-id and --kb must surface a usage error before
-// runLink runs.
-func TestLink_MutuallyExclusive(t *testing.T) {
+func TestLink_OverwritesExisting(t *testing.T) {
dir := t.TempDir()
chdir(t, dir)
_, _ = 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)
- cmd := NewCmd(f)
- var stderr bytes.Buffer
- cmd.SetErr(&stderr)
- cmd.SetOut(&bytes.Buffer{})
- cmd.SetArgs([]string{"--kb-id", "kb_a", "--kb", "foo"})
- cmd.SetContext(context.Background())
-
- 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())
+ 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_OneRequired exercises MarkFlagsOneRequired: zero of {kb-id, kb}
-// must be a usage error.
-func TestLink_OneRequired(t *testing.T) {
+// 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()
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")
+ opts := &Options{} // no KB
+ err := runLink(context.Background(), opts, f)
+ require.Error(t, err)
+ var typed *cmdutil.Error
+ require.ErrorAs(t, err, &typed)
+ assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
}
diff --git a/cli/cmd/root.go b/cli/cmd/root.go
index 20e53e265..64bba5655 100644
--- a/cli/cmd/root.go
+++ b/cli/cmd/root.go
@@ -1,10 +1,4 @@
// 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
import (
@@ -21,11 +15,9 @@ import (
contextcmd "github.com/Tencent/WeKnora/cli/cmd/context"
"github.com/Tencent/WeKnora/cli/cmd/doc"
"github.com/Tencent/WeKnora/cli/cmd/doctor"
- initcmd "github.com/Tencent/WeKnora/cli/cmd/init"
"github.com/Tencent/WeKnora/cli/cmd/kb"
linkcmd "github.com/Tencent/WeKnora/cli/cmd/link"
"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/build"
"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(auth.NewCmdAuth(f))
cmd.AddCommand(search.NewCmdSearch(f))
- cmd.AddCommand(whoami.NewCmd(f))
cmd.AddCommand(doctor.NewCmd(f))
cmd.AddCommand(kb.NewCmd(f))
cmd.AddCommand(contextcmd.NewCmd(f))
- cmd.AddCommand(initcmd.NewCmd(f))
cmd.AddCommand(linkcmd.NewCmd(f))
cmd.AddCommand(doc.NewCmd(f))
cmd.AddCommand(apicmd.NewCmd(f))
diff --git a/cli/cmd/search/search.go b/cli/cmd/search/search.go
index b9ed5ba6c..6e21f4327 100644
--- a/cli/cmd/search/search.go
+++ b/cli/cmd/search/search.go
@@ -18,8 +18,8 @@ import (
// Options is the runtime configuration of one search invocation.
type Options struct {
Query string
- KBID string // resolved id, populated by RunE before validate()
- KBName string // raw --kb flag value (name or, for legacy v0.0 callers, id)
+ KB string // raw --kb flag value (kb_<id> or name)
+ KBID string // resolved id, populated by RunE before HybridSearch
TopK int
VectorThreshold float64
KeywordThreshold float64
@@ -34,12 +34,12 @@ type Service interface {
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
-// surface across all commands (init / link / doc / chat) on `--kb-id` (id) +
-// `--kb` (name → id via ListKnowledgeBases). search now follows the same
-// convention. The resolution chain is identical to Factory.ResolveKB.
+// The single `--kb` flag accepts either a `kb_…` id (passed through) or a
+// name (resolved via ListKnowledgeBases). Mirrors gcloud `--project`'s
+// id-or-name auto-detection — the only mainstream pattern that collapses
+// the two forms onto one flag.
func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
@@ -50,7 +50,7 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
opts.Query = strings.TrimSpace(args[0])
// Validate input shape before touching the SDK so flag/arg misuse
// 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 {
return err
}
@@ -58,8 +58,10 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
if err != nil {
return err
}
- if opts.KBID == "" && opts.KBName != "" {
- resolved, rerr := cmdutil.ResolveKBNameToID(c.Context(), cli, opts.KBName)
+ if cmdutil.IsKBID(opts.KB) {
+ opts.KBID = opts.KB
+ } else {
+ resolved, rerr := cmdutil.ResolveKBNameToID(c.Context(), cli, opts.KB)
if rerr != nil {
return rerr
}
@@ -68,16 +70,14 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
return runSearch(c.Context(), opts, cli)
},
}
- cmd.Flags().StringVar(&opts.KBID, "kb-id", "", "Knowledge base id to search")
- cmd.Flags().StringVar(&opts.KBName, "kb", "", "Knowledge base name (resolved to id via list)")
+ cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base id (kb_…) or name")
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.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.NoKeyword, "no-keyword", false, "Disable the keyword channel")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
- cmd.MarkFlagsMutuallyExclusive("kb-id", "kb")
- cmd.MarkFlagsOneRequired("kb-id", "kb")
+ _ = cmd.MarkFlagRequired("kb")
return cmd
}
diff --git a/cli/cmd/whoami/whoami.go b/cli/cmd/whoami/whoami.go
deleted file mode 100644
index 52b1bd7dd..000000000
--- a/cli/cmd/whoami/whoami.go
+++ /dev/null
@@ -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
-}
diff --git a/cli/cmd/whoami/whoami_test.go b/cli/cmd/whoami/whoami_test.go
deleted file mode 100644
index ddb8dd4ee..000000000
--- a/cli/cmd/whoami/whoami_test.go
+++ /dev/null
@@ -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")
- }
-}
diff --git a/cli/internal/cmdutil/errors.go b/cli/internal/cmdutil/errors.go
index c10dadc95..fbb9302c5 100644
--- a/cli/internal/cmdutil/errors.go
+++ b/cli/internal/cmdutil/errors.go
@@ -56,10 +56,9 @@ const (
CodeLocalUnimplemented ErrorCode = "local.unimplemented"
CodeLocalContextNotFound ErrorCode = "local.context_not_found"
// v0.2 KB-resolution chain (spec §1.3) and project-link (spec §2.4) codes.
- CodeKBIDRequired ErrorCode = "local.kb_id_required"
- CodeKBNotFound ErrorCode = "local.kb_not_found"
- CodeProjectAlreadyLinked ErrorCode = "local.project_already_linked"
- CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
+ CodeKBIDRequired ErrorCode = "local.kb_id_required"
+ CodeKBNotFound ErrorCode = "local.kb_not_found"
+ CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
// CodeUserAborted marks a user-cancelled destructive operation (declined a
// confirm prompt). Distinct from SilentError so envelopes still carry a
// stable code; distinct from input.* because the user supplied valid args
@@ -256,7 +255,7 @@ func AllCodes() []ErrorCode {
CodeLocalConfigCorrupt, CodeLocalKeychainDenied, CodeLocalFileIO,
CodeLocalUnimplemented, CodeLocalContextNotFound,
CodeKBIDRequired, CodeKBNotFound,
- CodeProjectAlreadyLinked, CodeProjectLinkCorrupt,
+ CodeProjectLinkCorrupt,
CodeUserAborted, CodeUploadFileNotFound,
CodeSSEStreamAborted, CodeSessionCreateFailed,
// mcp
diff --git a/cli/internal/cmdutil/exit.go b/cli/internal/cmdutil/exit.go
index 4016b6190..3e753c72b 100644
--- a/cli/internal/cmdutil/exit.go
+++ b/cli/internal/cmdutil/exit.go
@@ -141,8 +141,8 @@ func ToErrorBody(err error) *format.ErrorBody {
// 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
// `auth.unauthenticated` envelopes carry "run weknora auth login" — this
-// fallback covers the broad surface (whoami / auth status / kb list / kb get
-// / search) without per-command hint plumbing.
+// fallback covers the broad surface (auth status / kb list / kb get / search)
+// without per-command hint plumbing.
//
// Empty string for codes without a stable canonical hint.
func defaultHint(code ErrorCode) string {
@@ -154,7 +154,7 @@ func defaultHint(code ErrorCode) string {
case CodeAuthForbidden:
return "active context lacks permission for this resource"
case CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch:
- return "verify tenant context with `weknora whoami`"
+ return "verify tenant context with `weknora auth status`"
case CodeNetworkError:
return "check base URL reachability with `weknora doctor`"
case CodeServerIncompatibleVersion:
@@ -176,13 +176,11 @@ func defaultHint(code ErrorCode) string {
case CodeLocalFileIO:
return "check file permissions under $XDG_CONFIG_HOME/weknora/"
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:
return "list available with `weknora kb list`"
- case CodeProjectAlreadyLinked:
- return "use --force to overwrite, or `weknora link` to update"
case CodeProjectLinkCorrupt:
- return "remove .weknora/project.yaml and run `weknora init` again"
+ return "remove .weknora/project.yaml and run `weknora link` again"
case CodeUserAborted:
return "no action taken; pass -y/--yes to skip the confirmation prompt"
case CodeUploadFileNotFound:
diff --git a/cli/internal/cmdutil/factory.go b/cli/internal/cmdutil/factory.go
index cc28bc290..094932fc5 100644
--- a/cli/internal/cmdutil/factory.go
+++ b/cli/internal/cmdutil/factory.go
@@ -22,7 +22,9 @@ import (
//
// Four closures (ADR-4):
// - 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
// - Secrets: builds the OS keyring / file fallback credential store the
// 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
-// 5-level fallback chain (highest to lowest):
-// 1. --kb-id flag (explicit ID)
-// 2. --kb flag (name → id via ListKnowledgeBases)
-// 3. WEKNORA_KB_ID env
-// 4. .weknora/project.yaml (walk-up from cwd)
-// 5. error: kb_id 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.
+// 4-level fallback chain (highest to lowest):
+// 1. --kb flag (kb_<...> id passed through; anything else resolved via
+// ListKnowledgeBases as a name → id lookup; mirrors gcloud --project's
+// id-or-name auto-detection)
+// 2. WEKNORA_KB_ID env (always an explicit id)
+// 3. .weknora/project.yaml (walk-up from cwd)
+// 4. error: kb required
func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) {
- if id, _ := cmd.Flags().GetString("kb-id"); id != "" {
- return id, nil
- }
- if name, _ := cmd.Flags().GetString("kb"); name != "" {
+ if v, _ := cmd.Flags().GetString("kb"); v != "" {
+ if IsKBID(v) {
+ return v, nil
+ }
c, err := f.Client()
if err != nil {
return "", err
}
- return ResolveKBNameToID(cmd.Context(), c, name)
+ return ResolveKBNameToID(cmd.Context(), c, v)
}
if v := os.Getenv("WEKNORA_KB_ID"); v != "" {
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
diff --git a/cli/internal/cmdutil/factory_test.go b/cli/internal/cmdutil/factory_test.go
index 6fa3e704e..31a0ebb36 100644
--- a/cli/internal/cmdutil/factory_test.go
+++ b/cli/internal/cmdutil/factory_test.go
@@ -264,18 +264,15 @@ func (c *countingSecrets) Get(ctx, key string) (string, error) {
return c.MemStore.Get(ctx, key)
}
-// makeResolveKBCmd builds a minimal cobra.Command carrying --kb-id / --kb local
-// flags so cmd.Flags().GetString lookups in ResolveKB exercise the flag path.
-func makeResolveKBCmd(t *testing.T, kbID, kbName string) *cobra.Command {
+// makeResolveKBCmd builds a minimal cobra.Command carrying the single --kb
+// local flag so cmd.Flags().GetString lookups in ResolveKB exercise the flag
+// path. The single flag accepts either a kb_<id> or a name.
+func makeResolveKBCmd(t *testing.T, kb string) *cobra.Command {
t.Helper()
c := &cobra.Command{Use: "x"}
- c.Flags().String("kb-id", "", "")
c.Flags().String("kb", "", "")
- if kbID != "" {
- require.NoError(t, c.Flags().Set("kb-id", kbID))
- }
- if kbName != "" {
- require.NoError(t, c.Flags().Set("kb", kbName))
+ if kb != "" {
+ require.NoError(t, c.Flags().Set("kb", kb))
}
c.SetContext(context.Background())
return c
@@ -305,11 +302,11 @@ func fakeKBServer(t *testing.T, kbs []sdk.KnowledgeBase) *httptest.Server {
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.
func TestResolveKB_Chain(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")
dir := t.TempDir()
resolveKBChdir(t, dir)
@@ -323,7 +320,7 @@ func TestResolveKB_Chain(t *testing.T) {
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)
assert.Equal(t, "kb_explicit", got)
assert.Equal(t, 0, clientCalls)
@@ -338,7 +335,7 @@ func TestResolveKB_Chain(t *testing.T) {
f := &Factory{
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)
assert.Equal(t, "kb_a", got)
})
@@ -349,7 +346,7 @@ func TestResolveKB_Chain(t *testing.T) {
f := &Factory{
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)
var typed *Error
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"}))
f := &Factory{}
- got, err := f.ResolveKB(makeResolveKBCmd(t, "", ""))
+ got, err := f.ResolveKB(makeResolveKBCmd(t, ""))
require.NoError(t, err)
assert.Equal(t, "kb_env", got)
})
@@ -379,7 +376,7 @@ func TestResolveKB_Chain(t *testing.T) {
resolveKBChdir(t, deep)
f := &Factory{}
- got, err := f.ResolveKB(makeResolveKBCmd(t, "", ""))
+ got, err := f.ResolveKB(makeResolveKBCmd(t, ""))
require.NoError(t, err)
assert.Equal(t, "kb_proj", got)
})
@@ -391,7 +388,7 @@ func TestResolveKB_Chain(t *testing.T) {
resolveKBChdir(t, dir)
f := &Factory{}
- _, err := f.ResolveKB(makeResolveKBCmd(t, "", ""))
+ _, err := f.ResolveKB(makeResolveKBCmd(t, ""))
require.Error(t, err)
var typed *Error
require.ErrorAs(t, err, &typed)
diff --git a/cli/internal/cmdutil/kb.go b/cli/internal/cmdutil/kb.go
index b6db79955..37faa6523 100644
--- a/cli/internal/cmdutil/kb.go
+++ b/cli/internal/cmdutil/kb.go
@@ -3,10 +3,21 @@ package cmdutil
import (
"context"
"fmt"
+ "strings"
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
// production *sdk.Client satisfies it; tests inject fakes without standing
// up an HTTP server.
@@ -15,8 +26,8 @@ type KBLister interface {
}
// ResolveKBNameToID looks up a knowledge base by name and returns its ID.
-// Used by `init`, `link`, and `Factory.ResolveKB` — a single lookup so the
-// match policy (currently exact case-sensitive) lives in one place.
+// Used by `link` and `Factory.ResolveKB` — a single lookup so the match
+// policy (currently exact case-sensitive) lives in one place.
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
kbs, err := lister.ListKnowledgeBases(ctx)
if err != nil {