feat(cli): v0.9 contract harmonization

Make the agent-facing contract uniform across the whole surface:

- cobra parse errors (unknown flag, arg-count) emit the JSON envelope by
  default, not bare prose — via a single DefaultFormatMode shared by the early
  resolver and ResolveDefault.
- a malformed --jq is input.invalid_argument (exit 5), not internal.error.
- destructive-confirmation messages name the real operation (edit/remove,
  not a hardcoded "delete").
- `doc wait` emits one envelope (Silent failure, no contradictory stderr);
  completed marshals as [] not null.
- WEKNORA_AGENT_HELP covers every leaf command, enforced by a coverage drift
  guard; a sibling guard enforces --dry-run on every mutation.
- `search docs`/`search chunks` resolve --kb through the same
  flag→env→project-link chain as `doc list`/`chat` (no longer a hard --kb
  requirement); a linked dir or WEKNORA_KB_ID now works without --kb, and an
  unresolved KB is local.kb_id_required (exit 1). The destructive
  `doc delete --all` keeps its explicit-only rule.
- exit-code and batch/wait ok-semantics documented in the shared skill, README,
  and AGENTS.md.
This commit is contained in:
nullkey
2026-05-29 20:06:53 +08:00
committed by lyingbug
parent 5f98df530c
commit 77b9b6a465
25 changed files with 590 additions and 98 deletions
+45
View File
@@ -0,0 +1,45 @@
package cmd
import (
"bytes"
"encoding/json"
"sort"
"testing"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// TestEveryLeafCommandHasAgentHelp enforces the agent-first contract: every
// leaf (runnable, no subcommands) command must emit a structured AgentHelp JSON
// blob under WEKNORA_AGENT_HELP=1, so an agent never has to scrape human prose.
// Drift guard in the spirit of the K6/K7 skill-parity tests: a new leaf command
// added without SetAgentHelp fails CI here.
//
// Exemptions: cobra's generated `completion`/`help` subtrees carry no
// domain semantics worth a machine blob.
func TestEveryLeafCommandHasAgentHelp(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
root := NewRootCmd(cmdutil.New())
var missing []string
eachLeafCommand(root, func(c *cobra.Command) {
// Invoke the leaf's help func with the agent env set and require JSON.
var buf bytes.Buffer
c.SetOut(&buf)
c.Help()
var ah struct {
UsedFor string `json:"used_for"`
}
if err := json.Unmarshal(buf.Bytes(), &ah); err != nil || ah.UsedFor == "" {
missing = append(missing, c.CommandPath())
}
})
sort.Strings(missing)
if len(missing) > 0 {
t.Errorf("leaf commands missing agent-help JSON (register cmdutil.SetAgentHelp):\n %v\n(%d commands)",
missing, len(missing))
}
}
+28
View File
@@ -0,0 +1,28 @@
package cmd
import "github.com/spf13/cobra"
// eachLeafCommand invokes fn for every runnable leaf command (no real
// subcommands) in the tree rooted at root, skipping cobra's generated
// `completion`/`help` subtrees and hidden commands. Shared by the agent-help
// and dry-run coverage drift guards so they agree, byte-for-byte, on what
// counts as a leaf.
func eachLeafCommand(root *cobra.Command, fn func(*cobra.Command)) {
exempt := map[string]bool{"completion": true, "help": true}
var walk func(c *cobra.Command)
walk = func(c *cobra.Command) {
realKids := 0
for _, k := range c.Commands() {
if exempt[k.Name()] || k.Hidden {
continue
}
realKids++
walk(k)
}
if c == root || realKids > 0 || exempt[c.Name()] {
return // group command or exempt — not a leaf
}
fn(c)
}
walk(root)
}
+81
View File
@@ -0,0 +1,81 @@
package cmd
import (
"sort"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// dryRunExpectation declares, for every leaf command, whether it must register
// --dry-run. The rule (per internal/cmdutil/dryrun.go): commands that change
// server/local state get a preview path. Reads, generate/stream ops, the
// interactive credential flow, and the long-running MCP server are exempt.
//
// This is a drift guard (sibling of TestEveryLeafCommandHasAgentHelp): every
// leaf must appear here, so a newly-added command forces an explicit dry-run
// decision rather than silently inheriting "no preview".
var dryRunExpectation = map[string]bool{
// --- mutations: MUST have --dry-run ---
"kb create": true, "kb edit": true, "kb delete": true, "kb pin": true, "kb unpin": true,
"doc create": true, "doc upload": true, "doc fetch": true, "doc delete": true,
"chunk delete": true,
"session delete": true, "session stop": true,
"agent create": true, "agent edit": true, "agent delete": true,
"profile add": true, "profile use": true, "profile remove": true,
"auth logout": true, "auth refresh": true,
"link": true, "unlink": true,
"api": true, // passthrough: dry-run previews write methods, rejected on GET
// --- exempt: no state change to preview ---
// reads
"kb list": false, "kb view": false, "kb status": false, "kb check": false,
"doc list": false, "doc view": false, "doc download": false,
"doc wait": false, // polling read, no mutation
"chunk list": false, "chunk view": false,
"session list": false, "session view": false,
"agent list": false, "agent view": false, "agent status": false, "agent check": false,
"search chunks": false, "search docs": false, "search kb": false, "search sessions": false,
"auth list": false, "auth status": false, "auth token": false,
"profile list": false,
"doctor": false, "version": false,
// generate / stream ops — the session-creation side effect is incidental,
// not a CRUD write; a no-SDK-call preview would be meaningless.
"chat": false, "session ask": false, "session continue-stream": false,
// auth login VALIDATES credentials against the server and stores them; its
// whole purpose is the server round-trip, which a side-effect-free dry-run
// cannot exercise — so previewing it would be misleading. Exempt by design.
"auth login": false,
// long-running stdio server, not a one-shot command.
"mcp serve": false,
}
func TestDryRunCoverageMatchesExpectation(t *testing.T) {
root := NewRootCmd(cmdutil.New())
var unlisted, wrong []string
eachLeafCommand(root, func(c *cobra.Command) {
key := strings.TrimPrefix(c.CommandPath(), "weknora ")
want, declared := dryRunExpectation[key]
if !declared {
unlisted = append(unlisted, key)
return
}
has := c.Flags().Lookup("dry-run") != nil
if has != want {
wrong = append(wrong, key)
}
})
sort.Strings(unlisted)
sort.Strings(wrong)
if len(unlisted) > 0 {
t.Errorf("leaf commands missing from dryRunExpectation (declare must-have-dry-run true/false):\n %v", unlisted)
}
if len(wrong) > 0 {
t.Errorf("dry-run flag presence disagrees with dryRunExpectation:\n %v", wrong)
}
}
+12 -10
View File
@@ -2,10 +2,11 @@
//
// MCP (Model Context Protocol; https://spec.modelcontextprotocol.io/) is
// the JSON-RPC 2.0 wire protocol agentic IDEs use to call external tools.
// `weknora mcp serve` exposes a curated subset of the CLI's read surface
// as MCP tools so an IDE-side agent can list / view / search / chat against
// the user's active WeKnora profile without shelling out to the CLI per
// call.
// `weknora mcp serve` exposes a curated subset of the CLI as MCP tools so
// an IDE-side agent can list / view / search / chat against the user's
// active WeKnora profile without shelling out to the CLI per call. Most
// tools are read-only; chat and session_ask create conversation/message
// records.
//
// Package name is `mcpcmd` to avoid shadowing `cli/internal/mcp` (the
// transport-and-handlers implementation). Same naming hygiene as
@@ -23,14 +24,15 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "mcp",
Short: "Run weknora as a Model Context Protocol server",
Long: `Exposes weknora's read surface as MCP tools so any
Long: `Exposes weknora's tool surface as MCP tools so any
MCP-compatible client can call them over JSON-RPC.
Initial tool surface is read-only and curated: kb_list / kb_view /
doc_list / doc_view / doc_download / search_chunks / chat / agent_list /
agent_invoke. Destructive verbs (create / delete / upload) are deliberately
excluded - the agent should ask the user before mutating; the CLI's
exit-10 protocol covers that path.`,
Curated 10-tool surface: kb_list / kb_view / doc_list / doc_view /
doc_download / search_chunks / chunk_list / agent_list are read-only;
chat and session_ask create conversation/message records. Destructive
verbs (create / delete / upload) are deliberately excluded - the agent
should ask the user before mutating; the CLI's exit-10 protocol covers
that path.`,
Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
}
+8
View File
@@ -46,5 +46,13 @@ Consult your MCP client's documentation for the exact config-file location.`,
return mcpserver.RunStdio(c.Context(), cli)
},
}
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "run weknora as a long-lived MCP (Model Context Protocol) server over stdio for an IDE/host agent",
Output: "no stdout payload (JSON-RPC 2.0 protocol traffic); logs go to stderr",
Warnings: []string{
"this is a long-running stdio server, not a one-shot command — register it in your MCP client (command: weknora, args: [mcp, serve])",
"exits with auth.unauthenticated at startup if no profile is configured",
},
})
return cmd
}
+14 -8
View File
@@ -53,15 +53,15 @@ func resolveFormatEarly(args []string) {
}
}
switch mode {
case "json", "ndjson", "text":
case "ndjson", "text":
cmdutil.SetFormatMode(mode)
case "":
// nothing to set; leave globalFormatMode at its zero value
default:
// Invalid format value: promote to json so the subsequent
// rejection error (from CheckFormatFlag) still emits as an envelope
// rather than prose. The real validation error will still fire.
cmdutil.SetFormatMode("json")
// "json", "" (no flag/env), or an invalid value all route the cobra-side
// error through the JSON envelope. Cobra parse errors fire before
// PersistentPreRunE runs ResolveDefault, so we apply the same default
// here (DefaultFormatMode) — otherwise the error path would emit prose
// while the success path emits the envelope.
cmdutil.SetFormatMode(string(cmdutil.DefaultFormatMode))
}
}
@@ -135,7 +135,8 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
Long: `Command-line client for the WeKnora RAG server. Manage knowledge bases
and documents, run hybrid search, chat with grounded answers, or expose
a curated read-only MCP tool surface for AI agents.`,
Example: ` weknora auth login --host=https://kb.example.com
Example: ` weknora profile add prod --host=https://kb.example.com --use
weknora auth login
weknora kb list
weknora chat "summarise the design doc"
weknora doctor --format json`,
@@ -253,6 +254,11 @@ func newVersionCmd(f *cmdutil.Factory) *cobra.Command {
},
}
cmdutil.AddFormatFlag(cmd, versionFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "show CLI build metadata (version, commit, build date)",
Examples: []string{"weknora version --format json"},
Output: "envelope.data is {version, commit, date}",
})
return cmd
}
+28
View File
@@ -161,3 +161,31 @@ func TestRoot_ProfileFlagPropagation(t *testing.T) {
})
}
}
// resolveFormatEarly must default to the JSON envelope when no --format/env is
// given, so cobra-side errors (unknown flag, arg-count) — which fire before
// PersistentPreRunE runs ResolveDefault — emit a machine-readable envelope on
// stderr, not bare prose. Regression for the success-path-defaults-to-json /
// error-path-defaults-to-prose asymmetry.
func TestResolveFormatEarly_DefaultsToEnvelope(t *testing.T) {
cases := []struct {
name string
args []string
want bool // true ⇒ expect JSON envelope
}{
{"no format flag (default)", []string{"kb", "view"}, true},
{"explicit --format json", []string{"kb", "view", "--format", "json"}, true},
{"explicit --format text", []string{"kb", "view", "--format", "text"}, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
resolveFormatEarly(tc.args)
err := MapCobraError(errors.New("accepts 1 arg(s), received 0"))
var buf bytes.Buffer
cmdutil.PrintError(&buf, err)
isEnvelope := strings.HasPrefix(strings.TrimSpace(buf.String()), "{")
assert.Equal(t, tc.want, isEnvelope,
"args=%v: got %q", tc.args, buf.String())
})
}
}
+15 -10
View File
@@ -70,23 +70,27 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
kbID, err := cmdutil.ResolveKBFlag(c.Context(), cli, opts.KB)
// Resolve KB via the shared flag→env→project-link chain (same as
// `doc list` / `chat`), so a linked directory or WEKNORA_KB_ID
// works without an explicit --kb. Resolve before building the
// client so an unresolved KB short-circuits to local.kb_id_required
// without a client round-trip.
kbID, err := f.ResolveKB(c)
if err != nil {
return err
}
opts.KBID = kbID
cli, err := f.Client()
if err != nil {
return err
}
return runChunks(c.Context(), opts, fopts, cli)
},
}
bindChunksFlags(cmd, opts)
_ = cmd.MarkFlagRequired("kb")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Hybrid (vector + keyword) chunk retrieval against a knowledge base. Results come with meta.count; use --limit to cap (default 8, tuned for RAG context). Pass --no-vector or --no-keyword to disable one channel.",
RequiredFlags: []string{"<query> (positional)", "--kb"},
UsedFor: "Hybrid (vector + keyword) chunk retrieval against a knowledge base. The KB comes from --kb (id or name), else WEKNORA_KB_ID, else the linked directory. Results come with meta.count; use --limit to cap (default 8, tuned for RAG context). Pass --no-vector or --no-keyword to disable one channel.",
RequiredFlags: []string{"<query> (positional)", "--kb (or WEKNORA_KB_ID / linked directory)"},
Examples: []string{`weknora search chunks "what is RAG?" --kb engineering --format json`},
Output: "envelope.data is an array of SearchResult objects with id, content, score, knowledge_id; meta.count is the returned count; meta.has_more=true if more matched than --limit",
})
@@ -94,9 +98,10 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
}
// bindChunksFlags registers the chunks flag surface in one place to keep
// the constructor readable; --kb is marked required by the caller.
// the constructor readable. --kb is optional: when omitted it falls back to
// WEKNORA_KB_ID / the linked directory via Factory.ResolveKB.
func bindChunksFlags(cmd *cobra.Command, opts *ChunksOptions) {
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name")
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name (overrides env / project link)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 8, "Maximum results to return (default 8 - tuned for RAG context window; list commands default to 30)")
cmd.Flags().Float64Var(&opts.VectorThreshold, "vector-threshold", 0, "Vector retrieval similarity floor (per-channel, pre-fusion); 0 = no filter")
cmd.Flags().Float64Var(&opts.KeywordThreshold, "keyword-threshold", 0, "Keyword retrieval score floor (per-channel, pre-fusion); 0 = no filter")
+39 -7
View File
@@ -137,21 +137,53 @@ func TestRunSearch_NilService(t *testing.T) {
assert.Contains(t, err.Error(), "server.error")
}
// TestNewCmdChunks_RequiresKB asserts that running `search chunks "<query>"`
// without --kb returns an error containing `required flag(s) "kb"`.
// This locks the behavior so a later refactor cannot silently introduce a
// project-link fallback for this destructive-free read path.
func TestNewCmdChunks_RequiresKB(t *testing.T) {
// TestNewCmdChunks_NoKBUsesResolver asserts that `search chunks "<query>"`
// without --kb no longer fails with cobra's `required flag(s) "kb"`. The
// command now resolves the KB through the shared flag→env→project-link chain
// (cmdutil.Factory.ResolveKB), matching `doc list` / `chat`; when nothing
// resolves it reports the typed local.kb_id_required (exit 1), not a cobra
// usage error. This is the inverse of the old lock test, which deliberately
// blocked the link fallback for this read path — the asymmetry with `doc
// list` was not worth keeping (a non-destructive search is the same risk
// profile as a list). The destructive `doc delete --all` keeps its explicit
// --kb rule; that safety guard is unrelated to this path.
func TestNewCmdChunks_NoKBUsesResolver(t *testing.T) {
iostreams.SetForTest(t)
t.Setenv("WEKNORA_KB_ID", "") // no ambient KB from env
t.Chdir(t.TempDir()) // no .weknora project link discoverable
cmd := NewCmdChunks(&cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
// Resolution reaches local.kb_id_required before any client is built,
// so this must never be invoked; make it loud if it is.
Client: func() (*sdk.Client, error) { return nil, errors.New("client should not be built") },
})
cmd.SetArgs([]string{"some query"}) // query but no --kb
cmd.SilenceErrors = true
cmd.SilenceUsage = true
err := cmd.Execute()
require.Error(t, err)
assert.Contains(t, err.Error(), `required flag(s) "kb"`)
assert.NotContains(t, err.Error(), `required flag(s) "kb"`)
typed := cmdutil.AsError(err)
require.NotNil(t, typed)
assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
}
// TestNewCmdChunks_HonorsKBEnv proves the env fallback is wired: with
// WEKNORA_KB_ID set and no --kb, KB resolution succeeds (no kb-required
// error) and the command proceeds to the client step — which here errors,
// confirming we got past resolution using the env value alone.
func TestNewCmdChunks_HonorsKBEnv(t *testing.T) {
iostreams.SetForTest(t)
t.Setenv("WEKNORA_KB_ID", "kb_from_env")
cmd := NewCmdChunks(&cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, errors.New("client boom") },
})
cmd.SetArgs([]string{"some query"}) // no --kb; env supplies it
cmd.SilenceErrors = true
cmd.SilenceUsage = true
err := cmd.Execute()
require.Error(t, err)
assert.NotContains(t, err.Error(), "kb is required")
assert.Contains(t, err.Error(), "client boom")
}
func TestNewCmdChunks_RequiresQuery(t *testing.T) {
+13 -9
View File
@@ -97,27 +97,31 @@ reached or the KB is exhausted. Pass --all-pages=false to stop after one page.`,
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
kbID, err := cmdutil.ResolveKBFlag(c.Context(), cli, opts.KB)
// Resolve KB via the shared flag→env→project-link chain (same as
// `doc list` / `chat`), so a linked directory or WEKNORA_KB_ID
// works without an explicit --kb. Resolve before building the
// client so an unresolved KB short-circuits to local.kb_id_required
// without a client round-trip.
kbID, err := f.ResolveKB(c)
if err != nil {
return err
}
opts.KBID = kbID
cli, err := f.Client()
if err != nil {
return err
}
return runDocsSearch(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name (required)")
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name (overrides env / project link)")
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
cmd.Flags().IntVar(&opts.PageSize, "page-size", docsPageSize, "Items per server batch (1..1000)")
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", true, "Walk every server page until exhausted or --limit hit")
cmdutil.AddFormatFlag(cmd, docsFields...)
_ = cmd.MarkFlagRequired("kb")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Find documents in a knowledge base by keyword (server-side LIKE filter on title/file_name). Results come with meta.count; use --limit to cap and --all-pages=false to stop after one page.",
RequiredFlags: []string{"<query> (positional)", "--kb"},
UsedFor: "Find documents in a knowledge base by keyword (server-side LIKE filter on title/file_name). The KB comes from --kb (id or name), else WEKNORA_KB_ID, else the linked directory. Results come with meta.count; use --limit to cap and --all-pages=false to stop after one page.",
RequiredFlags: []string{"<query> (positional)", "--kb (or WEKNORA_KB_ID / linked directory)"},
Examples: []string{`weknora search docs "spec" --kb engineering --format json`},
Output: "envelope.data is an array of Knowledge objects with id, title, file_name, parse_status; meta.count is the returned count; meta.has_more=true if more matched than --limit",
})
+38
View File
@@ -237,3 +237,41 @@ func TestDocsSearch_HasMore(t *testing.T) {
assert.False(t, m.HasMore, "has_more must be false/absent when results fit under --limit")
})
}
// TestNewCmdDocs_NoKBUsesResolver mirrors the chunks guard: `search docs`
// without --kb resolves the KB through the shared flag→env→project-link
// chain (Factory.ResolveKB), not cobra's required-flag check. With nothing
// to resolve it reports the typed local.kb_id_required, not a usage error.
func TestNewCmdDocs_NoKBUsesResolver(t *testing.T) {
iostreams.SetForTest(t)
t.Setenv("WEKNORA_KB_ID", "")
t.Chdir(t.TempDir())
cmd := NewCmdDocs(&cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, errors.New("client should not be built") },
})
cmd.SetArgs([]string{"some query"}) // query but no --kb
cmd.SilenceErrors = true
cmd.SilenceUsage = true
err := cmd.Execute()
require.Error(t, err)
assert.NotContains(t, err.Error(), `required flag(s) "kb"`)
typed := cmdutil.AsError(err)
require.NotNil(t, typed)
assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
}
// TestNewCmdDocs_HonorsKBEnv proves the env fallback is wired for search docs.
func TestNewCmdDocs_HonorsKBEnv(t *testing.T) {
iostreams.SetForTest(t)
t.Setenv("WEKNORA_KB_ID", "kb_from_env")
cmd := NewCmdDocs(&cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, errors.New("client boom") },
})
cmd.SetArgs([]string{"some query"}) // no --kb; env supplies it
cmd.SilenceErrors = true
cmd.SilenceUsage = true
err := cmd.Execute()
require.Error(t, err)
assert.NotContains(t, err.Error(), "kb is required")
assert.Contains(t, err.Error(), "client boom")
}