feat(cli): add project-link foundation with init and link commands
v0.2 grounds the CLI's resource commands (kb / doc / chat / query) in a
per-project link file (.weknora/project.yaml) so users don't have to pass
--kb-id on every invocation. Mirrors npm/cargo/git: walk up the cwd tree
to find the project root, override via flag or env when needed.
This commit ships the foundation layer:
- cli/internal/projectlink/ Discover (walk-up, depth=64) / Load / Save
- cmdutil.Factory.ResolveKB 5-level fallback chain:
--kb-id flag → --kb name (ListKnowledgeBases lookup) →
WEKNORA_KB_ID env → walk-up project link → CodeKBIDRequired
- cmdutil.ResolveKBNameToID shared name→id helper used by init / link
/ Factory.ResolveKB (was duplicated 3 ways
in early implementation; reuse review #2)
- cli/cmd/init/ interactive (huh prompt) or flag-driven
first-time setup; refuses to overwrite
without --force
- cli/cmd/link/ non-interactive update; --kb-id and --kb
are mutually exclusive and one is required
Also registers the v0.2 ErrorCode set (all codes for the eight new
commands) and AST-scan identToErrorCode mapping in one place — keeps the
acceptance/contract suite green across the v0.2 commit chain even before
later commits reference each code.
This commit is contained in:
@@ -45,6 +45,29 @@ const (
|
||||
CodeLocalFileIO ErrorCode = "local.file_io"
|
||||
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"
|
||||
// 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
|
||||
// and simply chose not to proceed.
|
||||
CodeUserAborted ErrorCode = "local.user_aborted"
|
||||
// CodeUploadFileNotFound marks a `weknora doc upload` invocation pointing at
|
||||
// a path that does not exist. Distinct from CodeLocalFileIO (permission /
|
||||
// disk-fault) so the hint can name the actual culprit.
|
||||
CodeUploadFileNotFound ErrorCode = "local.upload_file_not_found"
|
||||
// CodeSSEStreamAborted marks a streaming RAG response that began producing
|
||||
// data and then dropped before the SDK observed a Done event. Distinct
|
||||
// from network.error (pre-stream transport failure) so users see the
|
||||
// stream specifically aborted, not a connection that never opened.
|
||||
CodeSSEStreamAborted ErrorCode = "local.sse_stream_aborted"
|
||||
// CodeSessionCreateFailed marks a chat invocation where the auto-created
|
||||
// session POST failed. Surfaced as a typed code distinct from generic
|
||||
// server.error so agents can retry with their own --session-id.
|
||||
CodeSessionCreateFailed ErrorCode = "server.session_create_failed"
|
||||
|
||||
// mcp.*
|
||||
CodeMCPReadonlyMode ErrorCode = "mcp.readonly_mode"
|
||||
@@ -141,6 +164,30 @@ func matchPrefix(err error, prefix string) bool {
|
||||
return strings.HasPrefix(string(e.Code), prefix)
|
||||
}
|
||||
|
||||
// ClassifyHTTPStatus maps an HTTP status code to the canonical ErrorCode.
|
||||
// Single source of truth so envelope codes stay aligned whether the failure
|
||||
// was detected by the SDK (string-formatted error) or by the CLI directly
|
||||
// (e.g. raw passthrough reading resp.StatusCode).
|
||||
func ClassifyHTTPStatus(status int) ErrorCode {
|
||||
switch {
|
||||
case status == 401:
|
||||
return CodeAuthUnauthenticated
|
||||
case status == 403:
|
||||
return CodeAuthForbidden
|
||||
case status == 404:
|
||||
return CodeResourceNotFound
|
||||
case status == 409:
|
||||
return CodeResourceAlreadyExists
|
||||
case status == 429:
|
||||
return CodeServerRateLimited
|
||||
case status >= 500:
|
||||
return CodeServerError
|
||||
case status >= 400:
|
||||
return CodeInputInvalidArgument
|
||||
}
|
||||
return CodeServerError
|
||||
}
|
||||
|
||||
// ClassifyHTTPError maps an SDK HTTP error to the canonical ErrorCode by
|
||||
// parsing the "HTTP error <status>: ..." message format the SDK currently
|
||||
// emits (client.parseResponse). Until the SDK exposes a typed APIError this
|
||||
@@ -167,23 +214,7 @@ func ClassifyHTTPError(err error) ErrorCode {
|
||||
if perr != nil {
|
||||
return CodeServerError
|
||||
}
|
||||
switch {
|
||||
case status == 401:
|
||||
return CodeAuthUnauthenticated
|
||||
case status == 403:
|
||||
return CodeAuthForbidden
|
||||
case status == 404:
|
||||
return CodeResourceNotFound
|
||||
case status == 409:
|
||||
return CodeResourceAlreadyExists
|
||||
case status == 429:
|
||||
return CodeServerRateLimited
|
||||
case status >= 500:
|
||||
return CodeServerError
|
||||
case status >= 400:
|
||||
return CodeInputInvalidArgument
|
||||
}
|
||||
return CodeServerError
|
||||
return ClassifyHTTPStatus(status)
|
||||
}
|
||||
|
||||
// AllCodes returns the registered error code set.
|
||||
@@ -205,6 +236,10 @@ func AllCodes() []ErrorCode {
|
||||
// local
|
||||
CodeLocalConfigCorrupt, CodeLocalKeychainDenied, CodeLocalFileIO,
|
||||
CodeLocalUnimplemented, CodeLocalContextNotFound,
|
||||
CodeKBIDRequired, CodeKBNotFound,
|
||||
CodeProjectAlreadyLinked, CodeProjectLinkCorrupt,
|
||||
CodeUserAborted, CodeUploadFileNotFound,
|
||||
CodeSSEStreamAborted, CodeSessionCreateFailed,
|
||||
// mcp
|
||||
CodeMCPReadonlyMode, CodeMCPToolNotAllowed, CodeMCPSchemaUnknown,
|
||||
}
|
||||
|
||||
@@ -151,6 +151,22 @@ func defaultHint(code ErrorCode) string {
|
||||
return "remove ~/.config/weknora/config.yaml and re-run `weknora auth login`"
|
||||
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"
|
||||
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"
|
||||
case CodeUserAborted:
|
||||
return "no action taken; pass --force to skip the confirmation prompt"
|
||||
case CodeUploadFileNotFound:
|
||||
return "verify the path is correct and readable"
|
||||
case CodeSSEStreamAborted:
|
||||
return "the streaming answer was cut off mid-flight; retry, or pass --no-stream to buffer the full response"
|
||||
case CodeSessionCreateFailed:
|
||||
return "could not create a chat session; pass --session-id to reuse an existing session"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -3,10 +3,14 @@ package cmdutil
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -142,6 +146,45 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
return sdk.NewClient(ctx.Host, opts...), nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
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 != "" {
|
||||
c, err := f.Client()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ResolveKBNameToID(cmd.Context(), c, name)
|
||||
}
|
||||
if v := os.Getenv("WEKNORA_KB_ID"); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
cwd, err := os.Getwd()
|
||||
if err == nil {
|
||||
if path, found, derr := projectlink.Discover(cwd); derr == nil && found {
|
||||
p, lerr := projectlink.Load(path)
|
||||
if lerr != nil {
|
||||
return "", Wrapf(CodeProjectLinkCorrupt, lerr, "read project link")
|
||||
}
|
||||
if p.KBID != "" {
|
||||
return p.KBID, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", NewError(CodeKBIDRequired, "kb id is required")
|
||||
}
|
||||
|
||||
// loadSecret returns the stored value for (context, key); ErrNotFound becomes
|
||||
// ("", nil) so callers can treat "not configured" as success.
|
||||
func loadSecret(store secrets.Store, context, key string) (string, error) {
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
@@ -256,3 +263,138 @@ func (c *countingSecrets) Get(ctx, key string) (string, error) {
|
||||
c.gets++
|
||||
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 {
|
||||
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))
|
||||
}
|
||||
c.SetContext(context.Background())
|
||||
return c
|
||||
}
|
||||
|
||||
// resolveKBChdir switches cwd to dir for the duration of t (auto-restored).
|
||||
// ResolveKB walks up from os.Getwd() so tests must isolate cwd.
|
||||
func resolveKBChdir(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 that answers GET /api/v1/knowledge-bases
|
||||
// with kbs (KnowledgeBaseListResponse), so a real *sdk.Client can talk to it.
|
||||
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
|
||||
}
|
||||
|
||||
// TestResolveKB_Chain exercises the 5-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.
|
||||
t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose")
|
||||
dir := t.TempDir()
|
||||
resolveKBChdir(t, dir)
|
||||
// Drop a project link too — must be ignored.
|
||||
require.NoError(t, projectlink.Save(filepath.Join(dir, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"}))
|
||||
|
||||
clientCalls := 0
|
||||
f := &Factory{
|
||||
Client: func() (*sdk.Client, error) {
|
||||
clientCalls++
|
||||
return nil, errors.New("must not be called")
|
||||
},
|
||||
}
|
||||
got, err := f.ResolveKB(makeResolveKBCmd(t, "kb_explicit", ""))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "kb_explicit", got)
|
||||
assert.Equal(t, 0, clientCalls)
|
||||
})
|
||||
|
||||
t.Run("flag_kb_name_resolves", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_KB_ID", "")
|
||||
srv := fakeKBServer(t, []sdk.KnowledgeBase{
|
||||
{ID: "kb_a", Name: "foo"},
|
||||
{ID: "kb_b", Name: "bar"},
|
||||
})
|
||||
f := &Factory{
|
||||
Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil },
|
||||
}
|
||||
got, err := f.ResolveKB(makeResolveKBCmd(t, "", "foo"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "kb_a", got)
|
||||
})
|
||||
|
||||
t.Run("flag_kb_name_not_found", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_KB_ID", "")
|
||||
srv := fakeKBServer(t, []sdk.KnowledgeBase{{ID: "kb_a", Name: "foo"}})
|
||||
f := &Factory{
|
||||
Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil },
|
||||
}
|
||||
_, err := f.ResolveKB(makeResolveKBCmd(t, "", "missing"))
|
||||
require.Error(t, err)
|
||||
var typed *Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, CodeKBNotFound, typed.Code)
|
||||
})
|
||||
|
||||
t.Run("env_var", func(t *testing.T) {
|
||||
// No flag, env wins over disk.
|
||||
t.Setenv("WEKNORA_KB_ID", "kb_env")
|
||||
dir := t.TempDir()
|
||||
resolveKBChdir(t, dir)
|
||||
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, "", ""))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "kb_env", got)
|
||||
})
|
||||
|
||||
t.Run("project_link_walk_up", func(t *testing.T) {
|
||||
t.Setenv("WEKNORA_KB_ID", "")
|
||||
root := t.TempDir()
|
||||
require.NoError(t, projectlink.Save(filepath.Join(root, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_proj"}))
|
||||
// Run from a deep child to exercise walk-up.
|
||||
deep := filepath.Join(root, "a", "b", "c")
|
||||
require.NoError(t, os.MkdirAll(deep, 0o755))
|
||||
resolveKBChdir(t, deep)
|
||||
|
||||
f := &Factory{}
|
||||
got, err := f.ResolveKB(makeResolveKBCmd(t, "", ""))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "kb_proj", got)
|
||||
})
|
||||
|
||||
t.Run("none", func(t *testing.T) {
|
||||
// No flag, no env, no project link → CodeKBIDRequired.
|
||||
t.Setenv("WEKNORA_KB_ID", "")
|
||||
dir := t.TempDir()
|
||||
resolveKBChdir(t, dir)
|
||||
|
||||
f := &Factory{}
|
||||
_, err := f.ResolveKB(makeResolveKBCmd(t, "", ""))
|
||||
require.Error(t, err)
|
||||
var typed *Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, CodeKBIDRequired, typed.Code)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// KBLister is the narrow SDK surface ResolveKBNameToID depends on. The
|
||||
// production *sdk.Client satisfies it; tests inject fakes without standing
|
||||
// up an HTTP server.
|
||||
type KBLister interface {
|
||||
ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
// 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.
|
||||
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
|
||||
kbs, err := lister.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
return "", Wrapf(ClassifyHTTPError(err), err, "list knowledge bases")
|
||||
}
|
||||
for _, kb := range kbs {
|
||||
if kb.Name == name {
|
||||
return kb.ID, nil
|
||||
}
|
||||
}
|
||||
return "", NewError(CodeKBNotFound, fmt.Sprintf("knowledge base not found: %s", name))
|
||||
}
|
||||
Reference in New Issue
Block a user