feat(cli): session subtree + kb edit / pin / empty
Roadmap items 3-5 (session) and 3-6/7/8 (kb manage).
cli/cmd/session/ (new package; sessioncmd to avoid shadowing stdlib):
- session list: paginated table (ID/TITLE/UPDATED). --page / --page-size
with 1..1000 validation. _meta.has_more from page*size < total.
- session view <id>: prints metadata; non-empty fields only. Server
timestamps arrive as strings; parsed best-effort as RFC3339.
- session delete <id>: high-risk-write; exit-10 confirmation in non-
TTY/--json paths; --dry-run emits envelope.risk + dry_run:true.
cli/cmd/kb (extended):
- kb edit <id> [--name N] [--description D]: at least one flag required;
*string options so unset fields stay unset in the PUT body. SDK
UpdateKnowledgeBaseRequest has no embedding_model field, so the
roadmap's --embedding-model dropped.
- kb pin <id> / kb unpin <id>: direct parity with gh issue pin /
gh issue unpin (verified against gh manual). Idempotent: GetKnowledgeBase
reads IsPinned, TogglePinKnowledgeBase fires only on state change.
SDK KnowledgeBase struct gained the IsPinned field (server already
returned it; SDK just hadn't modeled it — non-breaking additive).
- kb empty <id>: high-risk-write; exit-10 confirmation;
--dry-run. Returns deleted_count from the async clear response.
weknora-specific operation; no mainstream parallel.
Golden envelopes for kb_list and kb_view updated to include the new
is_pinned field — strict-additive change.
Cleanups surfaced by the post-commit reviewer round:
- ConfirmPrompter promoted to cli/internal/testutil/ (4-copy threshold
reached: context/remove, kb/delete, kb/empty, session/delete).
kb/delete_test.go's pre-existing local copy left untouched per the
upstream-respect convention.
- kb pin/unpin idempotent no-op path no longer emits a write-class
envelope. Added _meta.warnings "already {un}pinned — no server
call made" and dropped the risk classification on the no-op branch.
- doc list --page-size was unbounded while session list enforces
1..1000. Same validation added to doc list.
18 + 18 unit tests; e2e exit codes verified.
Roadmap: 3-5, 3-6, 3-7, 3-8.
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
package kb
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
// EditOptions captures `weknora kb edit` flags. Name/Description are *string
|
||||
// so we can distinguish "unset" from "set to empty". An unset field is
|
||||
// omitted from the SDK request — only fields the user passed are sent. The
|
||||
// server PUT semantics are "replace everything in the request"; if we
|
||||
// always sent both, an `--name` invocation would silently clear the
|
||||
// description.
|
||||
type EditOptions struct {
|
||||
Name *string
|
||||
Description *string
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// EditService is the narrow SDK surface this command depends on.
|
||||
type EditService interface {
|
||||
UpdateKnowledgeBase(ctx context.Context, id string, req *sdk.UpdateKnowledgeBaseRequest) (*sdk.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
// NewCmdEdit builds `weknora kb edit <id>`. Mirrors `gh repo edit`. At
|
||||
// least one of --name / --description must be provided.
|
||||
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &EditOptions{}
|
||||
var name, desc string
|
||||
cmd := &cobra.Command{
|
||||
Use: "edit <id>",
|
||||
Short: "Edit a knowledge base's name or description",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
if c.Flag("name").Changed {
|
||||
opts.Name = &name
|
||||
}
|
||||
if c.Flag("description").Changed {
|
||||
opts.Description = &desc
|
||||
}
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runEdit(c.Context(), opts, nil, args[0])
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runEdit(c.Context(), opts, cli, args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&name, "name", "", "New name (omit to leave unchanged)")
|
||||
cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)")
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
agent.SetAgentHelp(cmd, "Edits a knowledge base. At least one of --name/--description is required. Fields not passed are preserved server-side. Returns the updated KnowledgeBase.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runEdit(ctx context.Context, opts *EditOptions, svc EditService, id string) error {
|
||||
if opts.Name == nil && opts.Description == nil {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputMissingFlag,
|
||||
Message: "kb edit requires at least one of --name or --description",
|
||||
Hint: "pass --name <name> and/or --description <desc>",
|
||||
}
|
||||
}
|
||||
|
||||
req := &sdk.UpdateKnowledgeBaseRequest{}
|
||||
if opts.Name != nil {
|
||||
req.Name = *opts.Name
|
||||
}
|
||||
if opts.Description != nil {
|
||||
req.Description = *opts.Description
|
||||
}
|
||||
|
||||
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("edit knowledge base %s", id)}
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(opts.JSONOut, req, &format.Meta{KBID: id}, risk)
|
||||
}
|
||||
|
||||
updated, err := svc.UpdateKnowledgeBase(ctx, id, req)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "edit knowledge base %s", id)
|
||||
}
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk))
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Updated knowledge base %s\n", id)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"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/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// fakeEditSvc captures the (id, request) pair handed to UpdateKnowledgeBase.
|
||||
type fakeEditSvc struct {
|
||||
gotID string
|
||||
gotReq *sdk.UpdateKnowledgeBaseRequest
|
||||
resp *sdk.KnowledgeBase
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeEditSvc) UpdateKnowledgeBase(_ context.Context, id string, req *sdk.UpdateKnowledgeBaseRequest) (*sdk.KnowledgeBase, error) {
|
||||
f.gotID = id
|
||||
f.gotReq = req
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
func TestEdit_RequiresAtLeastOneFlag(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{}
|
||||
err := runEdit(context.Background(), &EditOptions{}, svc, "kb_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code)
|
||||
assert.Contains(t, typed.Hint, "--name")
|
||||
assert.Contains(t, typed.Hint, "--description")
|
||||
}
|
||||
|
||||
func TestEdit_OnlyName(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{resp: &sdk.KnowledgeBase{ID: "kb_abc", Name: "new"}}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("new")
|
||||
require.NoError(t, runEdit(context.Background(), opts, svc, "kb_abc"))
|
||||
|
||||
assert.Equal(t, "kb_abc", svc.gotID)
|
||||
require.NotNil(t, svc.gotReq)
|
||||
assert.Equal(t, "new", svc.gotReq.Name)
|
||||
// Description must be empty string (not "<nil>"), so server doesn't
|
||||
// confuse "unset" with "set-to-empty". Actually the SDK ships an empty
|
||||
// string either way — we just verify we didn't accidentally serialize a
|
||||
// description override.
|
||||
assert.Equal(t, "", svc.gotReq.Description)
|
||||
assert.Contains(t, out.String(), "kb_abc")
|
||||
}
|
||||
|
||||
func TestEdit_OnlyDescription(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{resp: &sdk.KnowledgeBase{ID: "kb_abc"}}
|
||||
opts := &EditOptions{}
|
||||
opts.Description = stringPtr("new desc")
|
||||
require.NoError(t, runEdit(context.Background(), opts, svc, "kb_abc"))
|
||||
|
||||
require.NotNil(t, svc.gotReq)
|
||||
assert.Equal(t, "new desc", svc.gotReq.Description)
|
||||
assert.Equal(t, "", svc.gotReq.Name)
|
||||
}
|
||||
|
||||
func TestEdit_BothFlags(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{resp: &sdk.KnowledgeBase{ID: "kb_abc"}}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("renamed")
|
||||
opts.Description = stringPtr("new desc")
|
||||
require.NoError(t, runEdit(context.Background(), opts, svc, "kb_abc"))
|
||||
assert.Equal(t, "renamed", svc.gotReq.Name)
|
||||
assert.Equal(t, "new desc", svc.gotReq.Description)
|
||||
}
|
||||
|
||||
func TestEdit_DryRun_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
opts := &EditOptions{DryRun: true, JSONOut: true}
|
||||
opts.Name = stringPtr("preview")
|
||||
require.NoError(t, runEdit(context.Background(), opts, nil, "kb_abc"))
|
||||
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
|
||||
assert.Contains(t, body, `"dry_run":true`)
|
||||
assert.Contains(t, body, `"write"`)
|
||||
}
|
||||
|
||||
func TestEdit_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEditSvc{err: errors.New("HTTP error 404: not found")}
|
||||
opts := &EditOptions{}
|
||||
opts.Name = stringPtr("x")
|
||||
err := runEdit(context.Background(), opts, svc, "kb_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
|
||||
}
|
||||
|
||||
func stringPtr(s string) *string { return &s }
|
||||
@@ -0,0 +1,98 @@
|
||||
package kb
|
||||
|
||||
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"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// EmptyOptions captures `weknora kb empty` flag state.
|
||||
type EmptyOptions struct {
|
||||
Yes bool
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// EmptyService is the narrow SDK surface this command depends on.
|
||||
type EmptyService interface {
|
||||
ClearKnowledgeBaseContents(ctx context.Context, id string) (*sdk.ClearKnowledgeBaseContentsResponse, error)
|
||||
}
|
||||
|
||||
// emptyResult is the typed payload emitted under data on success.
|
||||
type emptyResult struct {
|
||||
ID string `json:"id"`
|
||||
DeletedCount int `json:"deleted_count"`
|
||||
}
|
||||
|
||||
// NewCmdEmpty builds `weknora kb empty <id>`. Wipes every
|
||||
// document inside the knowledge base; the KB itself is preserved. The
|
||||
// server runs the delete asynchronously and reports the count of documents
|
||||
// that were enqueued for removal.
|
||||
func NewCmdEmpty(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &EmptyOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "empty <id>",
|
||||
Short: "Delete every document in a knowledge base (preserves the KB)",
|
||||
Long: `Removes all documents and chunks from a knowledge base while keeping the
|
||||
KB record (its name, description, and config) intact. The delete is async;
|
||||
the server reports the count of items enqueued for removal.
|
||||
|
||||
Prompts for confirmation by default; pass -y/--yes to skip in agent / CI /
|
||||
piped contexts. Without -y the CLI exits 10 (lark-cli skill protocol).`,
|
||||
Example: ` weknora kb empty kb_abc # interactive confirm
|
||||
weknora kb empty kb_abc -y --json # agent-friendly`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runEmpty(c.Context(), opts, nil, f.Prompter(), args[0])
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runEmpty(c.Context(), opts, cli, f.Prompter(), args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
agent.SetAgentHelp(cmd, "Destructively empties a knowledge base (deletes all documents, preserves the KB record + config). ALWAYS pass -y/--yes in agent mode (non-TTY ⇒ confirm fails). Returns data: {id, deleted_count}. Async — items may still be processing server-side after the call returns.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runEmpty(ctx context.Context, opts *EmptyOptions, svc EmptyService, p prompt.Prompter, id string) error {
|
||||
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("empty knowledge base %s", id)}
|
||||
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(opts.JSONOut, emptyResult{ID: id}, &format.Meta{KBID: id}, risk)
|
||||
}
|
||||
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "all contents of knowledge base", id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := svc.ClearKnowledgeBaseContents(ctx, id)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "empty knowledge base %s", id)
|
||||
}
|
||||
deleted := 0
|
||||
if resp != nil {
|
||||
deleted = resp.DeletedCount
|
||||
}
|
||||
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(
|
||||
emptyResult{ID: id, DeletedCount: deleted}, &format.Meta{KBID: id}, risk,
|
||||
))
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Emptied knowledge base %s (%d document(s) cleared)\n", id, deleted)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"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/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// fakeEmptySvc records calls + scripts the response.
|
||||
type fakeEmptySvc struct {
|
||||
err error
|
||||
gotID string
|
||||
called bool
|
||||
resp *sdk.ClearKnowledgeBaseContentsResponse
|
||||
}
|
||||
|
||||
func (f *fakeEmptySvc) ClearKnowledgeBaseContents(_ context.Context, id string) (*sdk.ClearKnowledgeBaseContentsResponse, error) {
|
||||
f.called = true
|
||||
f.gotID = id
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
if f.resp == nil {
|
||||
return &sdk.ClearKnowledgeBaseContentsResponse{DeletedCount: 0}, nil
|
||||
}
|
||||
return f.resp, nil
|
||||
}
|
||||
|
||||
func TestEmpty_WithYes(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeEmptySvc{resp: &sdk.ClearKnowledgeBaseContentsResponse{DeletedCount: 42}}
|
||||
require.NoError(t, runEmpty(context.Background(), &EmptyOptions{Yes: true}, svc, &testutil.ConfirmPrompter{}, "kb_abc"))
|
||||
assert.True(t, svc.called)
|
||||
assert.Equal(t, "kb_abc", svc.gotID)
|
||||
body := out.String()
|
||||
assert.Contains(t, body, "kb_abc")
|
||||
assert.Contains(t, body, "42")
|
||||
}
|
||||
|
||||
func TestEmpty_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
svc := &fakeEmptySvc{}
|
||||
err := runEmpty(context.Background(), &EmptyOptions{}, svc, &testutil.ConfirmPrompter{}, "kb_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
|
||||
assert.Equal(t, 10, cmdutil.ExitCode(err))
|
||||
assert.False(t, svc.called)
|
||||
}
|
||||
|
||||
func TestEmpty_TTY_ConfirmNo(t *testing.T) {
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
svc := &fakeEmptySvc{}
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runEmpty(context.Background(), &EmptyOptions{}, svc, p, "kb_abc")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeUserAborted, typed.Code)
|
||||
assert.False(t, svc.called)
|
||||
assert.Contains(t, errBuf.String(), "Aborted")
|
||||
}
|
||||
|
||||
func TestEmpty_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeEmptySvc{err: errors.New("HTTP error 404: not found")}
|
||||
err := runEmpty(context.Background(), &EmptyOptions{Yes: true}, svc, &testutil.ConfirmPrompter{}, "kb_missing")
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
|
||||
}
|
||||
|
||||
func TestEmpty_DryRun_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeEmptySvc{}
|
||||
require.NoError(t, runEmpty(context.Background(), &EmptyOptions{DryRun: true, JSONOut: true}, svc, &testutil.ConfirmPrompter{}, "kb_dry"))
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
|
||||
assert.Contains(t, body, `"dry_run":true`)
|
||||
assert.Contains(t, body, `"high-risk-write"`)
|
||||
assert.False(t, svc.called)
|
||||
}
|
||||
+8
-3
@@ -1,6 +1,7 @@
|
||||
// Package kb holds the `weknora kb` command tree: list / view / create / delete.
|
||||
// `view` is the primary read verb (gh repo view convention); `get` survives as
|
||||
// a cobra alias on the view subcommand for v0.0/v0.1 callers.
|
||||
// Package kb holds the `weknora kb` command tree: list / view / create /
|
||||
// edit / delete / pin / unpin / clear-contents. `view` is the primary read
|
||||
// verb (gh repo view convention); `get` survives as a cobra alias on the
|
||||
// view subcommand for v0.0/v0.1 callers.
|
||||
package kb
|
||||
|
||||
import (
|
||||
@@ -20,6 +21,10 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.AddCommand(NewCmdList(f))
|
||||
cmd.AddCommand(NewCmdView(f))
|
||||
cmd.AddCommand(NewCmdCreate(f))
|
||||
cmd.AddCommand(NewCmdEdit(f))
|
||||
cmd.AddCommand(NewCmdDelete(f))
|
||||
cmd.AddCommand(NewCmdPin(f))
|
||||
cmd.AddCommand(NewCmdUnpin(f))
|
||||
cmd.AddCommand(NewCmdEmpty(f))
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package kb
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
// PinOptions captures `weknora kb pin / unpin` flag state.
|
||||
type PinOptions struct {
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// PinService is the narrow SDK surface this command depends on. The CLI
|
||||
// reads current state before toggling so `pin`/`unpin` are idempotent —
|
||||
// the server endpoint is only a non-idempotent toggle.
|
||||
type PinService interface {
|
||||
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
|
||||
TogglePinKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
// NewCmdPin builds `weknora kb pin <id>`.
|
||||
func NewCmdPin(f *cmdutil.Factory) *cobra.Command {
|
||||
return newPinCmd(f, "pin", true, "Pin a knowledge base to the top of the list")
|
||||
}
|
||||
|
||||
// NewCmdUnpin builds `weknora kb unpin <id>`.
|
||||
func NewCmdUnpin(f *cmdutil.Factory) *cobra.Command {
|
||||
return newPinCmd(f, "unpin", false, "Unpin a knowledge base")
|
||||
}
|
||||
|
||||
func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.Command {
|
||||
opts := &PinOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: use + " <id>",
|
||||
Short: short,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runPin(c.Context(), opts, nil, args[0], want)
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runPin(c.Context(), opts, cli, args[0], want)
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
agent.SetAgentHelp(cmd, fmt.Sprintf("Idempotent %s: reads current pin state, toggles only if different. No-op when already in the requested state.", use))
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runPin(ctx context.Context, opts *PinOptions, svc PinService, id string, want bool) error {
|
||||
verb := "pin"
|
||||
if !want {
|
||||
verb = "unpin"
|
||||
}
|
||||
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("%s knowledge base %s", verb, id)}
|
||||
|
||||
if opts.DryRun {
|
||||
// Dry-run can't introspect state without a network call by design (see
|
||||
// kb/delete.go for the same convention). Report what *would* run if
|
||||
// state diverged; agents can disambiguate via a subsequent `kb view`.
|
||||
return cmdutil.EmitDryRun(opts.JSONOut, struct {
|
||||
ID string `json:"id"`
|
||||
Want bool `json:"want_pinned"`
|
||||
}{id, want}, &format.Meta{KBID: id}, risk)
|
||||
}
|
||||
|
||||
current, err := svc.GetKnowledgeBase(ctx, id)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "get knowledge base %s", id)
|
||||
}
|
||||
if current.IsPinned == want {
|
||||
state := "pinned"
|
||||
if !want {
|
||||
state = "unpinned"
|
||||
}
|
||||
// No-op path: tell agents what happened. The risk-write classification
|
||||
// was the *requested* operation, not what occurred — surface it via a
|
||||
// _meta.warning so audit logs don't count a write that wasn't made.
|
||||
if opts.JSONOut {
|
||||
meta := &format.Meta{KBID: id, Warnings: []string{fmt.Sprintf("already %s — no server call made", state)}}
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.Success(current, meta))
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ %s is already %s\n", id, state)
|
||||
return nil
|
||||
}
|
||||
|
||||
updated, err := svc.TogglePinKnowledgeBase(ctx, id)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "%s knowledge base %s", verb, id)
|
||||
}
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(updated, &format.Meta{KBID: id}, risk))
|
||||
}
|
||||
state := "pinned"
|
||||
if !updated.IsPinned {
|
||||
state = "unpinned"
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ %s %s\n", id, state)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// fakePinSvc satisfies PinService: GetKnowledgeBase + TogglePinKnowledgeBase.
|
||||
type fakePinSvc struct {
|
||||
current sdk.KnowledgeBase
|
||||
getErr error
|
||||
toggleErr error
|
||||
toggleCalled bool
|
||||
}
|
||||
|
||||
func (f *fakePinSvc) GetKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
|
||||
if f.getErr != nil {
|
||||
return nil, f.getErr
|
||||
}
|
||||
c := f.current
|
||||
c.ID = id
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (f *fakePinSvc) TogglePinKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
|
||||
f.toggleCalled = true
|
||||
if f.toggleErr != nil {
|
||||
return nil, f.toggleErr
|
||||
}
|
||||
c := f.current
|
||||
c.ID = id
|
||||
c.IsPinned = !c.IsPinned
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, svc, "kb_abc", true))
|
||||
assert.True(t, svc.toggleCalled, "must call toggle when current state differs")
|
||||
assert.Contains(t, out.String(), "kb_abc")
|
||||
}
|
||||
|
||||
func TestPin_AlreadyPinned_NoOp(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, svc, "kb_abc", true))
|
||||
assert.False(t, svc.toggleCalled, "already pinned ⇒ must not call toggle")
|
||||
assert.Contains(t, out.String(), "already pinned")
|
||||
}
|
||||
|
||||
func TestUnpin_PinnedToUnpinned_CallsToggle(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, svc, "kb_abc", false))
|
||||
assert.True(t, svc.toggleCalled)
|
||||
}
|
||||
|
||||
func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{}, svc, "kb_abc", false))
|
||||
assert.False(t, svc.toggleCalled, "already unpinned ⇒ must not call toggle")
|
||||
assert.Contains(t, out.String(), "already unpinned")
|
||||
}
|
||||
|
||||
func TestPin_NotFound(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{getErr: errors.New("HTTP error 404: not found")}
|
||||
err := runPin(context.Background(), &PinOptions{}, svc, "kb_missing", true)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
|
||||
assert.False(t, svc.toggleCalled)
|
||||
}
|
||||
|
||||
func TestPin_ToggleError(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{
|
||||
current: sdk.KnowledgeBase{IsPinned: false},
|
||||
toggleErr: errors.New("HTTP error 500: internal"),
|
||||
}
|
||||
err := runPin(context.Background(), &PinOptions{}, svc, "kb_abc", true)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeServerError, typed.Code)
|
||||
}
|
||||
|
||||
func TestPin_DryRun_StateDiffers(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{DryRun: true, JSONOut: true}, svc, "kb_abc", true))
|
||||
assert.False(t, svc.toggleCalled, "dry-run must not call toggle")
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"dry_run":true`)
|
||||
assert.Contains(t, body, `"write"`)
|
||||
}
|
||||
|
||||
func TestPin_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
|
||||
require.NoError(t, runPin(context.Background(), &PinOptions{JSONOut: true}, svc, "kb_abc", true))
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"is_pinned":true`)
|
||||
assert.Contains(t, body, `"id":"kb_abc"`)
|
||||
}
|
||||
Reference in New Issue
Block a user