diff --git a/cli/acceptance/contract/errorcodes_test.go b/cli/acceptance/contract/errorcodes_test.go index f1332950..4d8265be 100644 --- a/cli/acceptance/contract/errorcodes_test.go +++ b/cli/acceptance/contract/errorcodes_test.go @@ -180,6 +180,22 @@ func identToErrorCode(name string) (cmdutil.ErrorCode, bool) { return cmdutil.CodeLocalUnimplemented, true case "CodeLocalContextNotFound": return cmdutil.CodeLocalContextNotFound, true + case "CodeKBIDRequired": + return cmdutil.CodeKBIDRequired, true + case "CodeKBNotFound": + return cmdutil.CodeKBNotFound, true + case "CodeProjectAlreadyLinked": + return cmdutil.CodeProjectAlreadyLinked, true + case "CodeProjectLinkCorrupt": + return cmdutil.CodeProjectLinkCorrupt, true + case "CodeUserAborted": + return cmdutil.CodeUserAborted, true + case "CodeUploadFileNotFound": + return cmdutil.CodeUploadFileNotFound, true + case "CodeSSEStreamAborted": + return cmdutil.CodeSSEStreamAborted, true + case "CodeSessionCreateFailed": + return cmdutil.CodeSessionCreateFailed, true case "CodeMCPReadonlyMode": return cmdutil.CodeMCPReadonlyMode, true case "CodeMCPToolNotAllowed": diff --git a/cli/cmd/init/init.go b/cli/cmd/init/init.go new file mode 100644 index 00000000..1b50cbe0 --- /dev/null +++ b/cli/cmd/init/init.go @@ -0,0 +1,199 @@ +// Package initcmd implements `weknora init` — creates a per-project link file +// at /.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.`, + 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 new file mode 100644 index 00000000..84c6e630 --- /dev/null +++ b/cli/cmd/init/init_test.go @@ -0,0 +1,162 @@ +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/link/link.go b/cli/cmd/link/link.go new file mode 100644 index 00000000..62c6fb01 --- /dev/null +++ b/cli/cmd/link/link.go @@ -0,0 +1,122 @@ +// 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 + +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 link` flags. +type Options struct { + KBID string // --kb-id + KBName string // --kb + 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. +type linkResult 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 link` command. +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`, + 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().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.") + return cmd +} + +func runLink(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) + + cfg, err := f.Config() + 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 + } + + 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 := linkResult{ + 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 +} + diff --git a/cli/cmd/link/link_test.go b/cli/cmd/link/link_test.go new file mode 100644 index 00000000..044a1b65 --- /dev/null +++ b/cli/cmd/link/link_test.go @@ -0,0 +1,157 @@ +package linkcmd + +import ( + "bytes" + "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" +) + +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) }) +} + +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 +} + +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 TestLink_ByID(t *testing.T) { + dir := t.TempDir() + chdir(t, dir) + out, _ := iostreams.SetForTest(t) + + f := newFactory("default", nil) + opts := &Options{KBID: "kb_xxx"} + require.NoError(t, runLink(context.Background(), opts, f)) + + linkPath := filepath.Join(dir, ".weknora", "project.yaml") + p, err := projectlink.Load(linkPath) + require.NoError(t, err) + assert.Equal(t, "kb_xxx", p.KBID) + assert.Equal(t, "default", p.Context) + assert.Contains(t, out.String(), "✓") +} + +func TestLink_ByName(t *testing.T) { + dir := t.TempDir() + chdir(t, dir) + _, _ = iostreams.SetForTest(t) + + srv := fakeKBServer(t, []sdk.KnowledgeBase{ + {ID: "kb_a", Name: "foo"}, + {ID: "kb_b", Name: "bar"}, + }) + cli := sdk.NewClient(srv.URL) + f := newFactory("default", cli) + opts := &Options{KBName: "foo"} + require.NoError(t, runLink(context.Background(), opts, f)) + + p, err := projectlink.Load(filepath.Join(dir, ".weknora", "project.yaml")) + require.NoError(t, err) + assert.Equal(t, "kb_a", p.KBID) +} + +func TestLink_KBNotFound(t *testing.T) { + dir := t.TempDir() + chdir(t, dir) + _, _ = iostreams.SetForTest(t) + + srv := fakeKBServer(t, []sdk.KnowledgeBase{{ID: "kb_a", Name: "foo"}}) + cli := sdk.NewClient(srv.URL) + f := newFactory("default", cli) + opts := &Options{KBName: "missing"} + err := runLink(context.Background(), opts, f) + require.Error(t, err) + var typed *cmdutil.Error + require.ErrorAs(t, err, &typed) + 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) { + 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{"--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()) +} + +// 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") +} diff --git a/cli/cmd/root.go b/cli/cmd/root.go index a0dc36a7..22287428 100644 --- a/cli/cmd/root.go +++ b/cli/cmd/root.go @@ -15,7 +15,9 @@ import ( "github.com/Tencent/WeKnora/cli/cmd/auth" contextcmd "github.com/Tencent/WeKnora/cli/cmd/context" "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" @@ -174,6 +176,8 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`, 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)) return cmd } diff --git a/cli/internal/cmdutil/errors.go b/cli/internal/cmdutil/errors.go index d330470e..fa598e27 100644 --- a/cli/internal/cmdutil/errors.go +++ b/cli/internal/cmdutil/errors.go @@ -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 : ..." 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, } diff --git a/cli/internal/cmdutil/exit.go b/cli/internal/cmdutil/exit.go index d6ddf151..37f51e57 100644 --- a/cli/internal/cmdutil/exit.go +++ b/cli/internal/cmdutil/exit.go @@ -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 "" } diff --git a/cli/internal/cmdutil/factory.go b/cli/internal/cmdutil/factory.go index 1cb81517..0d098e52 100644 --- a/cli/internal/cmdutil/factory.go +++ b/cli/internal/cmdutil/factory.go @@ -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) { diff --git a/cli/internal/cmdutil/factory_test.go b/cli/internal/cmdutil/factory_test.go index 143993c0..6fa3e704 100644 --- a/cli/internal/cmdutil/factory_test.go +++ b/cli/internal/cmdutil/factory_test.go @@ -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) + }) +} diff --git a/cli/internal/cmdutil/kb.go b/cli/internal/cmdutil/kb.go new file mode 100644 index 00000000..b6db7995 --- /dev/null +++ b/cli/internal/cmdutil/kb.go @@ -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)) +} diff --git a/cli/internal/projectlink/projectlink.go b/cli/internal/projectlink/projectlink.go new file mode 100644 index 00000000..3a5e56d7 --- /dev/null +++ b/cli/internal/projectlink/projectlink.go @@ -0,0 +1,85 @@ +// Package projectlink reads and writes the per-project link file +// .weknora/project.yaml that anchors a working directory to a context+KB. +// +// Discovery walks up from the start directory until either (a) a +// .weknora/project.yaml is found, (b) the filesystem root is reached, or +// (c) the walk exceeds a 64-level depth limit (cycle protection for +// pathological symlink setups). Pattern matches `cargo`, `npm`, and `git` +// — find-the-project's-root walks; mount-boundary crossing is allowed +// (npm/cargo behave the same — a project may straddle a bind-mount). +package projectlink + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "time" + + "github.com/Tencent/WeKnora/cli/internal/xdg" + "gopkg.in/yaml.v3" +) + +// Project is the on-disk schema of .weknora/project.yaml. +type Project struct { + Context string `yaml:"context,omitempty"` + KBID string `yaml:"kb_id"` + CreatedAt time.Time `yaml:"created_at"` +} + +// FileName is the project link file basename relative to .weknora/. +const FileName = "project.yaml" + +// DirName is the project-link directory name. +const DirName = ".weknora" + +const maxWalkDepth = 64 + +// Discover walks up from startDir looking for /. +// Returns (path, true, nil) when found, (root, false, nil) when none is +// found within depth limit, or ("", false, err) on filesystem errors. +func Discover(startDir string) (string, bool, error) { + dir, err := filepath.Abs(startDir) + if err != nil { + return "", false, fmt.Errorf("resolve start dir: %w", err) + } + for range maxWalkDepth { + candidate := filepath.Join(dir, DirName, FileName) + info, err := os.Stat(candidate) + if err == nil && !info.IsDir() { + return candidate, true, nil + } + if err != nil && !errors.Is(err, os.ErrNotExist) { + // Permission errors etc. — keep walking up; missing read access + // to a parent dir doesn't necessarily mean the project starts + // here. Cargo/npm have the same behavior. + // Fall through to parent walk. + } + parent := filepath.Dir(dir) + if parent == dir { + // Hit filesystem root + return "", false, nil + } + dir = parent + } + return "", false, nil +} + +// Load reads and parses the project link file at path. +func Load(path string) (*Project, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("read project link: %w", err) + } + var p Project + if err := yaml.Unmarshal(data, &p); err != nil { + return nil, fmt.Errorf("project link corrupt: %w", err) + } + return &p, nil +} + +// Save writes the project link to path atomically (0600 perms). +// Creates parent .weknora/ directory if missing. +func Save(path string, p *Project) error { + return xdg.WriteAtomicYAML(path, p) +} diff --git a/cli/internal/projectlink/projectlink_test.go b/cli/internal/projectlink/projectlink_test.go new file mode 100644 index 00000000..d89f1923 --- /dev/null +++ b/cli/internal/projectlink/projectlink_test.go @@ -0,0 +1,112 @@ +package projectlink_test + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/Tencent/WeKnora/cli/internal/projectlink" +) + +func TestDiscover_FoundInCwd(t *testing.T) { + dir := t.TempDir() + mkLink(t, dir) + got, found, err := projectlink.Discover(dir) + if err != nil { + t.Fatalf("Discover: %v", err) + } + if !found { + t.Fatalf("expected found=true") + } + want := filepath.Join(dir, ".weknora", "project.yaml") + if got != want { + t.Errorf("got %q, want %q", got, want) + } +} + +func TestDiscover_FoundInParent(t *testing.T) { + root := t.TempDir() + mkLink(t, root) + deep := filepath.Join(root, "a", "b", "c") + if err := os.MkdirAll(deep, 0o755); err != nil { + t.Fatal(err) + } + got, found, err := projectlink.Discover(deep) + if err != nil { + t.Fatalf("Discover: %v", err) + } + if !found { + t.Fatal("expected found=true") + } + if filepath.Dir(filepath.Dir(got)) != root { + t.Errorf("expected discovered file under %q, got %q", root, got) + } +} + +func TestDiscover_NotFound(t *testing.T) { + dir := t.TempDir() + _, found, err := projectlink.Discover(dir) + if err != nil { + t.Fatalf("Discover: %v", err) + } + if found { + t.Fatal("expected found=false in empty tree") + } +} + +func TestLoad_RoundTrip(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ".weknora", "project.yaml") + in := &projectlink.Project{Context: "prod", KBID: "kb_abc", CreatedAt: time.Now().UTC().Round(time.Second)} + if err := projectlink.Save(path, in); err != nil { + t.Fatalf("Save: %v", err) + } + out, err := projectlink.Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + if out.Context != in.Context || out.KBID != in.KBID { + t.Errorf("round trip: got %+v want %+v", out, in) + } +} + +func TestLoad_Corrupt(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ".weknora", "project.yaml") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("not: yaml: : :"), 0o600); err != nil { + t.Fatal(err) + } + _, err := projectlink.Load(path) + if err == nil { + t.Fatal("expected error for corrupt yaml") + } +} + +func TestSave_CreatesParent(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, ".weknora", "project.yaml") + if err := projectlink.Save(path, &projectlink.Project{KBID: "kb_x"}); err != nil { + t.Fatalf("Save: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, ".weknora")); err != nil { + t.Errorf("parent .weknora not created: %v", err) + } + if _, err := os.Stat(path); err != nil { + t.Errorf("file not created: %v", err) + } +} + +func mkLink(t *testing.T, dir string) { + t.Helper() + d := filepath.Join(dir, ".weknora") + if err := os.MkdirAll(d, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(d, "project.yaml"), []byte("kb_id: kb_test\n"), 0o600); err != nil { + t.Fatal(err) + } +}