refactor(cli): resource-command refactors — --kb resolver, MCP session_ask, session stop (BREAKING)

Unify the --kb resolver (accepts name or UUID) across kb/doc/chunk/session/
search/chat/link; `agent create` attaches knowledge bases via --attach-kb
(no longer --kb). Rename the MCP tool agent_invoke → session_ask and drop dead
MCP error codes. Add `session stop` (StopSession), completing the
start / continue-stream / stop triad.

Across these commands, bring the agent contract up to par: --dry-run previews
on mutations (incl. kb pin/unpin, session stop), agent-help blobs on the
read/health surface, accurate destructive-confirmation verbs, and search
has_more truncation signalling so an agent can tell its results were capped.
This commit is contained in:
nullkey
2026-05-29 20:06:30 +08:00
committed by lyingbug
parent a68cc59310
commit c90f4e895e
54 changed files with 807 additions and 93 deletions
+5
View File
@@ -106,6 +106,11 @@ don't require a file upload or remote URL. KB resolution follows the standard
_ = cmd.MarkFlagRequired("text")
cmdutil.AddFormatFlag(cmd, docCreateFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Create a knowledge entry from inline Markdown text. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"--text"},
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, title, parse_status",
})
return cmd
}
+19
View File
@@ -1,6 +1,7 @@
package doc
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -138,3 +139,21 @@ func TestCreate_EmptyText_RejectsBeforeSDK(t *testing.T) {
// Verify the SDK was NOT called.
assert.Nil(t, svc.got.req, "SDK must not be called when --text is empty")
}
// TestCreate_AgentHelp_EmitsUsedFor verifies that when WEKNORA_AGENT_HELP=1
// the `doc create --help` path emits a JSON blob containing "used_for".
// This is the representative test for 3.2; the mechanism is covered by
// internal/cmdutil/agenthelp_test.go — we test the wiring here.
func TestCreate_AgentHelp_EmitsUsedFor(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
_, _ = iostreams.SetForTest(t)
f := &cmdutil.Factory{}
cmd := NewCmdCreate(f)
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.HelpFunc()(cmd, nil)
assert.Contains(t, buf.String(), `"used_for"`)
}
+16 -6
View File
@@ -94,7 +94,7 @@ without the user's explicit go-ahead.`,
if opts.All {
if opts.KB == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--all requires --kb=<id>").
WithHint("specify --kb=<kb-id> to scope the delete-all operation").
WithHint("specify --kb=<uuid-or-name> to scope the delete-all operation").
WithRetryCommand("weknora doc delete --all --kb=<kb-id> -y")
}
if len(args) > 0 {
@@ -122,13 +122,23 @@ without the user's explicit go-ahead.`,
}
if opts.All {
// Resolve KB name → id before the destructive SDK call.
// Must use cmdutil.ResolveKBFlag (id-or-name, lists KBs and
// matches by name) rather than Factory.ResolveKB, which walks
// the project link — a destructive "empty the KB" must never
// inherit an implicit linked KB.
kbID, err := cmdutil.ResolveKBFlag(c.Context(), cli, opts.KB)
if err != nil {
return err
}
opts.KB = kbID
return runDeleteAll(c.Context(), opts, fopts, cli, f.Prompter())
}
// Single-id uses the simpler code path (bare {id, deleted}).
if len(args) == 1 {
return runDelete(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
}
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "document", len(args), "doc.delete", "weknora doc delete "+strings.Join(args, " ")+" -y"); err != nil {
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "document", len(args), "doc.delete", "weknora doc delete "+strings.Join(args, " ")+" -y"); err != nil {
return err
}
outcomes, runErr := cmdutil.RunBatch(c.Context(), args, func(ctx context.Context, id string) error {
@@ -149,13 +159,13 @@ without the user's explicit go-ahead.`,
},
}
cmd.Flags().BoolVar(&opts.All, "all", false, "delete all documents in the KB specified by --kb")
cmd.Flags().StringVar(&opts.KB, "kb", "", "knowledge base ID (required with --all)")
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name (required with --all)")
cmdutil.AddFormatFlag(cmd, docDeleteFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetRisk(cmd, "doc.delete")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "permanently delete one or more documents from a knowledge base",
RequiredFlags: []string{"<doc-id>... (positional) | --all --kb=<id>"},
RequiredFlags: []string{"<doc-id>... (positional) | --all --kb=<uuid-or-name>"},
Examples: []string{
"weknora doc delete doc_abc -y",
"weknora doc delete doc_a doc_b doc_c -y",
@@ -171,7 +181,7 @@ without the user's explicit go-ahead.`,
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "document", id, "doc.delete", "weknora doc delete "+id+" -y"); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "document", id, "doc.delete", "weknora doc delete "+id+" -y"); err != nil {
return err
}
@@ -191,7 +201,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOp
// CodeInputConfirmationRequired (exit 10) with risk metadata so agents can
// surface the risk to the user before re-invoking with -y.
func runDeleteAll(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc AllService, p prompt.Prompter) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "all docs in KB", opts.KB, "doc.delete_all", fmt.Sprintf("weknora doc delete --all --kb=%s -y", opts.KB)); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "all docs in KB", opts.KB, "doc.delete_all", fmt.Sprintf("weknora doc delete --all --kb=%s -y", opts.KB)); err != nil {
return err
}
+57 -2
View File
@@ -6,6 +6,8 @@ import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
@@ -14,7 +16,9 @@ import (
sdk "github.com/Tencent/WeKnora/client"
"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/prompt"
"github.com/Tencent/WeKnora/cli/internal/testutil"
)
@@ -258,7 +262,7 @@ func TestRunMultiDelete_ConfirmBatch_NonTTY_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t) // non-TTY
svc := &fakeDeleteSvc{}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "document", 2, "doc.delete", "")
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "delete", "document", 2, "doc.delete", "")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -270,7 +274,7 @@ func TestRunMultiDelete_ConfirmBatch_TTY_UserAborts(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "document", 3, "doc.delete", "")
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "delete", "document", 3, "doc.delete", "")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -527,3 +531,54 @@ func TestDocDelete_All_ServiceError(t *testing.T) {
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
}
// ---------------------------------------------------------------------------
// KB name resolution tests (--all --kb resolves name → id)
// ---------------------------------------------------------------------------
// TestDocDelete_All_ResolvesKBNameToID verifies that `doc delete --all --kb eng -y`
// resolves the KB name "eng" to its canonical id "kb_eng" before calling
// ClearKnowledgeBaseContents. Uses an httptest.Server to fake both the
// ListKnowledgeBases and ClearKnowledgeBaseContents endpoints so the real
// *sdk.Client can be injected through the factory (mirrors link_test.go pattern).
func TestDocDelete_All_ResolvesKBNameToID(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var clearCalledWith string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/knowledge-bases":
_ = json.NewEncoder(w).Encode(sdk.KnowledgeBaseListResponse{
Success: true,
Data: []sdk.KnowledgeBase{{ID: "kb_eng", Name: "eng"}},
})
case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/knowledge-bases/kb_eng/knowledge":
clearCalledWith = "kb_eng"
_ = json.NewEncoder(w).Encode(map[string]any{
"success": true,
"data": map[string]any{"deleted_count": 3},
})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
cli := sdk.NewClient(srv.URL)
f := &cmdutil.Factory{
Config: func() (*config.Config, error) {
return &config.Config{
CurrentProfile: "default",
Profiles: map[string]config.Profile{"default": {Host: srv.URL}},
}, nil
},
Client: func() (*sdk.Client, error) { return cli, nil },
Prompter: func() prompt.Prompter { return &testutil.ConfirmPrompter{Answer: true} },
}
root := withRootHarnessDoc(NewCmdDelete(f), "--all", "--kb", "eng", "-y")
err := root.Execute()
require.NoError(t, err, "doc delete --all --kb eng -y should succeed")
assert.Equal(t, "kb_eng", clearCalledWith,
"ClearKnowledgeBaseContents must be called with resolved id 'kb_eng', not raw name 'eng'")
}
+51 -8
View File
@@ -14,6 +14,18 @@ import (
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// downloadFields enumerates the fields surfaced for `--format json` discovery on
// `doc download`. Matches the downloadResult struct.
var downloadFields = []string{"path", "bytes", "filename"}
// downloadResult is the typed payload emitted as the success envelope when
// --format json is requested and output is going to a file (not stdout).
type downloadResult struct {
Path string `json:"path"`
Bytes int64 `json:"bytes"`
Filename string `json:"filename"`
}
type DownloadOptions struct {
Output string // --output / -O: target path, "-" for stdout, "" for server-suggested filename
Clobber bool // --clobber: allow overwrite of an existing file
@@ -40,26 +52,43 @@ Default behavior (no --output): writes to the cwd under the filename the
server suggests via Content-Disposition. If the server doesn't suggest
one, the command errors and asks for --output FILE explicitly.
Existing files are NOT overwritten unless --clobber is passed.`,
Existing files are NOT overwritten unless --clobber is passed.
With --format json, on success emits a JSON envelope whose data has
path, bytes, and filename fields. When output is stdout (--output -),
the JSON envelope is suppressed because the raw bytes already occupy
stdout.`,
Example: ` weknora doc download doc_abc # writes ./<server-name>
weknora doc download doc_abc -O report.pdf
weknora doc download doc_abc --output - # stream to stdout (binary safe)
weknora doc download doc_abc -O report.pdf --clobber`,
weknora doc download doc_abc -O report.pdf --clobber
weknora doc download doc_abc -O report.pdf --format json # JSON envelope`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
return runDownload(c.Context(), opts, cli, args[0])
return runDownload(c.Context(), opts, fopts, cli, args[0])
},
}
cmd.Flags().StringVarP(&opts.Output, "output", "O", "", `Output path; "-" for stdout. Defaults to the server-suggested filename.`)
cmd.Flags().BoolVar(&opts.Clobber, "clobber", false, "Overwrite the output file if it already exists")
cmdutil.AddFormatFlag(cmd, downloadFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Download a document's bytes by id. Writes a file (or stdout with --output -).",
RequiredFlags: []string{"<doc-id> (positional)"},
Output: "with --format json (file output): envelope.data has path, bytes, filename; suppressed with --output - (raw bytes to stdout)",
})
return cmd
}
func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService, id string) error {
func runDownload(ctx context.Context, opts *DownloadOptions, fopts *cmdutil.FormatOptions, svc DownloadService, id string) error {
suggested, body, err := svc.OpenKnowledgeFile(ctx, id)
if err != nil {
return cmdutil.WrapHTTP(err, "download %s", id)
@@ -71,13 +100,15 @@ func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService
return err
}
if dest == "-" {
// Raw bytes go to stdout — suppress any JSON envelope regardless of
// --format json because both can't occupy stdout simultaneously.
_, err := io.Copy(iostreams.IO.Out, body)
return err
}
if err := refuseIfExists(dest, opts.Clobber); err != nil {
return err
}
return streamToFile(body, dest)
return streamToFile(body, dest, fopts)
}
// resolveDownloadDest returns the final destination ("-" for stdout, an
@@ -133,20 +164,32 @@ func refuseIfExists(path string, clobber bool) error {
// streamToFile copies body into a newly-created file at path. On any
// streaming error the partial file is removed so callers don't see a
// truncated artifact at the user-visible path.
func streamToFile(body io.Reader, path string) error {
//
// On success: if fopts.WantsJSON(), emits a downloadResult envelope to
// stdout instead of the "✓ Saved" text.
func streamToFile(body io.Reader, path string, fopts *cmdutil.FormatOptions) error {
f, err := os.Create(path)
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "create %s", path)
}
if _, err := io.Copy(f, body); err != nil {
n, copyErr := io.Copy(f, body)
if copyErr != nil {
_ = f.Close()
_ = os.Remove(path)
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write %s", path)
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, copyErr, "write %s", path)
}
if err := f.Close(); err != nil {
_ = os.Remove(path)
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "close %s", path)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, downloadResult{
Path: path,
Bytes: n,
Filename: filepath.Base(path),
}, nil)
}
fmt.Fprintf(iostreams.IO.Err, "✓ Saved %s\n", path)
return nil
}
+58 -8
View File
@@ -2,6 +2,7 @@ package doc
import (
"context"
"encoding/json"
"errors"
"io"
"os"
@@ -34,6 +35,10 @@ func (f *fakeDownloadSvc) OpenKnowledgeFile(_ context.Context, id string) (strin
return f.filename, io.NopCloser(strings.NewReader(f.content)), nil
}
// textFopts returns a text-mode FormatOptions for tests that don't care
// about JSON output.
func textFopts() *cmdutil.FormatOptions { return &cmdutil.FormatOptions{Mode: cmdutil.FormatText} }
func TestDownload_DefaultUsesServerFilename(t *testing.T) {
_, _ = iostreams.SetForTest(t)
tmp := t.TempDir()
@@ -42,7 +47,7 @@ func TestDownload_DefaultUsesServerFilename(t *testing.T) {
defer os.Chdir(prevWD)
svc := &fakeDownloadSvc{content: "PDF-1.4 bytes", filename: "report.pdf"}
require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc"))
require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, textFopts(), svc, "doc_abc"))
got, err := os.ReadFile(filepath.Join(tmp, "report.pdf"))
require.NoError(t, err)
@@ -53,7 +58,7 @@ func TestDownload_OutFile(t *testing.T) {
_, _ = iostreams.SetForTest(t)
dest := filepath.Join(t.TempDir(), "out.bin")
svc := &fakeDownloadSvc{content: "hello", filename: "ignored.txt"}
require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest}, svc, "doc_abc"))
require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest}, textFopts(), svc, "doc_abc"))
got, err := os.ReadFile(dest)
require.NoError(t, err)
@@ -63,14 +68,14 @@ func TestDownload_OutFile(t *testing.T) {
func TestDownload_OutDash_Stdout(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDownloadSvc{content: "binary payload", filename: "report.pdf"}
require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: "-"}, svc, "doc_abc"))
require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: "-"}, textFopts(), svc, "doc_abc"))
assert.Equal(t, "binary payload", out.String())
}
func TestDownload_NoFilenameFromServer_DefaultPath_Errors(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDownloadSvc{content: "x", filename: ""}
err := runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc")
err := runDownload(context.Background(), &DownloadOptions{}, textFopts(), svc, "doc_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -81,7 +86,7 @@ func TestDownload_NoFilenameFromServer_DefaultPath_Errors(t *testing.T) {
func TestDownload_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDownloadSvc{err: errors.New("HTTP error 404: not found")}
err := runDownload(context.Background(), &DownloadOptions{Output: filepath.Join(t.TempDir(), "x")}, svc, "doc_missing")
err := runDownload(context.Background(), &DownloadOptions{Output: filepath.Join(t.TempDir(), "x")}, textFopts(), svc, "doc_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -94,7 +99,7 @@ func TestDownload_RefusesOverwrite(t *testing.T) {
require.NoError(t, os.WriteFile(dest, []byte("OLD"), 0o644))
svc := &fakeDownloadSvc{content: "NEW", filename: ""}
err := runDownload(context.Background(), &DownloadOptions{Output: dest}, svc, "doc_abc")
err := runDownload(context.Background(), &DownloadOptions{Output: dest}, textFopts(), svc, "doc_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -116,7 +121,7 @@ func TestDownload_RejectsServerPathTraversal(t *testing.T) {
// The server sends "../../etc/shadow" - we accept only "shadow" and
// write to cwd.
svc := &fakeDownloadSvc{content: "exfil", filename: "../../etc/shadow"}
require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc"))
require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, textFopts(), svc, "doc_abc"))
// File must land inside cwd; parent dirs untouched.
got, err := os.ReadFile(filepath.Join(tmp, "shadow"))
@@ -145,7 +150,52 @@ func TestDownload_ForceOverwrites(t *testing.T) {
require.NoError(t, os.WriteFile(dest, []byte("OLD"), 0o644))
svc := &fakeDownloadSvc{content: "NEW", filename: ""}
require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest, Clobber: true}, svc, "doc_abc"))
require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest, Clobber: true}, textFopts(), svc, "doc_abc"))
got, _ := os.ReadFile(dest)
assert.Equal(t, "NEW", string(got))
}
// TestDownload_JSONEnvelope verifies that --format json emits a success
// envelope with path/bytes/filename when downloading to a temp file.
func TestDownload_JSONEnvelope(t *testing.T) {
out, _ := iostreams.SetForTest(t)
dest := filepath.Join(t.TempDir(), "report.pdf")
svc := &fakeDownloadSvc{content: "PDF bytes here", filename: "report.pdf"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest}, fopts, svc, "doc_abc"))
// File content must still be written correctly.
got, err := os.ReadFile(dest)
require.NoError(t, err)
assert.Equal(t, "PDF bytes here", string(got))
// stdout must contain the JSON envelope.
var env struct {
OK bool `json:"ok"`
Data struct {
Path string `json:"path"`
Bytes int64 `json:"bytes"`
Filename string `json:"filename"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal([]byte(out.String()), &env), "expected valid JSON envelope, got %q", out.String())
assert.True(t, env.OK)
assert.Equal(t, dest, env.Data.Path)
assert.Equal(t, int64(len("PDF bytes here")), env.Data.Bytes)
assert.Equal(t, "report.pdf", env.Data.Filename)
}
// TestDownload_JSONEnvelope_SuppressedOnStdout verifies that when output is
// stdout (--output -), the JSON envelope is NOT emitted even with --format json
// because raw bytes already occupy stdout.
func TestDownload_JSONEnvelope_SuppressedOnStdout(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDownloadSvc{content: "binary payload", filename: "report.pdf"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: "-"}, fopts, svc, "doc_abc"))
// stdout must contain only the raw bytes, not a JSON envelope.
assert.Equal(t, "binary payload", out.String())
}
+5
View File
@@ -134,6 +134,11 @@ Server-side ingestion knobs:
cmd.Flags().Lookup("enable-multimodel").NoOptDefVal = "true"
cmdutil.AddFormatFlag(cmd, docFetchFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Ingest a remote URL into the resolved knowledge base. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"<url> (positional)"},
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, source, parse_status",
})
return cmd
}
+5
View File
@@ -111,6 +111,11 @@ backend storage order is not guaranteed and varies between deployments.`,
cmd.Flags().StringVar(&opts.StartTime, "start-time", "", "Include docs with updated_at >= this RFC3339 timestamp (e.g. 2006-01-02T15:04:05Z)")
cmd.Flags().StringVar(&opts.EndTime, "end-time", "", "Include docs with updated_at <= this RFC3339 timestamp (e.g. 2006-01-02T15:04:05Z)")
cmdutil.AddFormatFlag(cmd, docListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List documents in the resolved knowledge base. Results come with meta.count; use --limit to cap, --all-pages to walk every server page, --status/--keyword to filter server-side.",
Examples: []string{"weknora doc list --format json", "weknora doc list --all-pages --limit 200 --format json"},
Output: "envelope.data is an array of Knowledge objects with id, title, file_name, parse_status; meta.count is the total returned",
})
return cmd
}
+5
View File
@@ -188,6 +188,11 @@ Server-side ingestion knobs:
cmd.Flags().StringVar(&opts.Channel, "channel", "", "Ingestion-channel tag recorded server-side (default \"api\")")
cmdutil.AddFormatFlag(cmd, docUploadFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Upload a local file to the resolved knowledge base. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"<file> (positional)"},
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, file_name, parse_status",
})
return cmd
}
+6
View File
@@ -52,6 +52,12 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
},
}
cmdutil.AddFormatFlag(cmd, docViewFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "fetch one document's metadata by id",
RequiredFlags: []string{"<doc-id> (positional)"},
Examples: []string{"weknora doc view doc_abc", "weknora doc view doc_abc --jq .data.parse_status"},
Output: "envelope.data is the document object (id, file_name, parse_status, ...)",
})
return cmd
}
+24 -3
View File
@@ -74,13 +74,19 @@ For fail-fast semantics, use shell composition:
return err
}
// The partition (completed/failed/timeout) is already on stdout via
// emitWaitResult. On aggregate failure we still need a non-zero exit,
// but the error is Silent so PrintError does NOT write a second,
// contradictory {ok:false} envelope to stderr — the agent reads the
// failure detail from the stdout partition + the exit code (1/124).
// Same contract as cmdutil.RunBatch.
switch res.ExitCode() {
case 0:
return nil
case 1:
return cmdutil.NewError(cmdutil.CodeOperationFailed, fmt.Sprintf("%d doc(s) failed", len(res.Failed)))
return cmdutil.NewError(cmdutil.CodeOperationFailed, fmt.Sprintf("%d doc(s) failed", len(res.Failed))).WithSilent()
case 124:
return cmdutil.NewError(cmdutil.CodeOperationTimeout, fmt.Sprintf("wait timed out (%d doc(s) still pending)", len(res.Timeout)))
return cmdutil.NewError(cmdutil.CodeOperationTimeout, fmt.Sprintf("wait timed out (%d doc(s) still pending)", len(res.Timeout))).WithSilent()
}
return nil
},
@@ -88,6 +94,19 @@ For fail-fast semantics, use shell composition:
cmd.Flags().DurationVar(&opts.Timeout, "timeout", 10*time.Minute, "Max wait time before exiting 124")
cmd.Flags().DurationVar(&opts.Interval, "interval", 2*time.Second, "Initial poll interval; exponential backoff capped at 15s + jitter")
cmdutil.AddFormatFlag(cmd)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "block until one or more documents reach a terminal parse state (completed or failed), or --timeout elapses",
RequiredFlags: []string{"<doc-id>... (one or more positionals)"},
Examples: []string{
"weknora doc wait doc_abc",
"weknora doc wait doc_a doc_b --timeout 5m",
},
Output: "envelope.data is {completed:[], failed:[{id,message}], timeout:[]}",
Warnings: []string{
"exit code carries the aggregate result: 0 all completed, 1 any failed, 124 timeout",
"ok:true means the wait ran to a terminal state — NOT that every doc succeeded; branch on the exit code or inspect data.failed",
},
})
return cmd
}
@@ -146,7 +165,9 @@ func waitForDocs(ctx context.Context, ids []string, svc WaitService, opts WaitOp
ctx, cancel := context.WithTimeout(ctx, opts.Timeout)
defer cancel()
result := &WaitResult{}
// Completed is non-omitempty (always present in the partition), so start it
// as an empty slice rather than nil — agents see `"completed":[]`, not null.
result := &WaitResult{Completed: []string{}}
var mu sync.Mutex
addCompleted := func(id string) {
mu.Lock()
+20
View File
@@ -291,3 +291,23 @@ func TestWaitResult_ExitCode(t *testing.T) {
})
}
}
// On aggregate failure, doc wait emits the partition envelope to stdout; the
// returned error must be Silent so PrintError does NOT write a second,
// contradictory {ok:false} envelope to stderr. Regression for the dual-envelope
// contract violation (stdout ok:true + stderr ok:false for one invocation).
func TestDocWait_FailureError_IsSilent(t *testing.T) {
// Mirror RunBatch's contract: the failure carries CodeOperationFailed for
// the exit code, but Silent=true suppresses the stderr envelope.
err := cmdutil.NewError(cmdutil.CodeOperationFailed, "1 doc(s) failed").WithSilent()
typed := cmdutil.AsError(err)
if typed == nil {
t.Fatal("expected typed *Error")
}
if !typed.Silent {
t.Error("doc wait failure error must be Silent to avoid a contradictory stderr envelope")
}
if cmdutil.ExitCode(err) != 1 {
t.Errorf("exit code = %d, want 1", cmdutil.ExitCode(err))
}
}