chore(cli): polish + docs sync + pre-PR audit fixes

Code-reuse polish (post-implementation review pass):
- Extract text.OneLine(maxWidth, s) helper combining preview-row
  normalization (newline/CR/tab → space) with text.Truncate's
  UTF-8-safe truncation. Replaces agent/view.go truncate1Line (ASCII
  '...' + byte-slice CJK-unsafe) and chunk/list.go singleLine.
- Lift cmdutil.OpenInput(path) for the '-' = stdin / else os.Open
  pattern shared across agent create/edit and the api command.
  Replaces agent/create.go's private openInput.
- Strip inline doc-spec parentheticals from source comments — those
  belong in commit messages and project docs, not in source where
  they rot.

Pre-PR audit fixes:
- doc upload: reject `--metadata` paired with `--from-url` as
  input.invalid_argument up-front (the URL-ingest request type has
  no metadata field server-side, so the pair would otherwise silently
  drop). Long help and CHANGELOG updated to call out the asymmetry.
- doc upload (file path): map sdk.ErrDuplicateFile sentinel to
  resource.already_exists. The sentinel arrives with no "HTTP error <n>:"
  prefix because the SDK short-circuits on file-hash before reading the
  HTTP status, so the previous WrapHTTP fall-through misclassified it
  as network.error with a misleading "check base URL reachability" hint.
  The --from-url branch already handled ErrDuplicateURL this way; this
  closes the asymmetry. Caught by e2e re-upload of an already-ingested
  file; regression test added.
- README exit-10 enumeration adds `agent delete` and `chunk delete`
  (these were missing alongside the v0.5 destructive verbs they were
  meant to gate).

Docs sync:
- cli/README.md: command tree now includes the chunk subtree; adds
  agent / chunk lines to the 5-minute quickstart; adds a "Contributing
  / Reporting issues" section pointing at the repo's SECURITY.md and
  AGENTS.md; drops third-party CLI parallels from the surface
  description.
- cli/AGENTS.md: "Command surface design SOP" gains the
  flag-vs-escape-hatch step. "CRUD command flag canon" renamed to the
  hard-required-flags pattern with the contrast (TTY-prompts-fill)
  defined inline rather than via opaque shorthand.
- cli/CHANGELOG.md: search docs case-sensitivity shift promoted to its
  own #### Breaking changes subsection. MCP doc_list filter count
  corrected from 5 to 6. Drops the bogus go.mod yaml.v3 entry (yaml.v3
  was already a dependency on main; v0.5 added zero go.mod lines).
  Replaces internal-Go identifiers (fuzzyTime, NoOptDefVal) with
  user-language and drops the § section-symbol jargon.
This commit is contained in:
nullkey
2026-05-16 02:42:18 +08:00
committed by lyingbug
parent f89d54362d
commit c87e35b34b
35 changed files with 339 additions and 182 deletions
+10 -20
View File
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
@@ -58,11 +57,11 @@ type createFlagSet struct {
kbsSet bool
}
const agentCreateExample = ` weknora agent create "Support Bot" --model gpt-4
weknora agent create "Code Reviewer" --model gpt-4 --system-prompt-file ./prompt.md --kb kb_eng --kb kb_arch
weknora agent create "From Template" --model gpt-4 --from ag_existing
const agentCreateExample = ` weknora agent create "Support Bot" --model <model-id>
weknora agent create "Code Reviewer" --model <model-id> --system-prompt-file ./prompt.md --kb kb_eng --kb kb_arch
weknora agent create "From Template" --model <model-id> --from ag_existing
weknora agent create --generate-skeleton > my-agent.yaml
weknora agent create "Tuned" --model gpt-4 --config-file ./my-agent.yaml`
weknora agent create "Tuned" --model <model-id> --config-file ./my-agent.yaml`
const agentCreateLong = `Create a new custom agent.
@@ -114,17 +113,16 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts.flags.kbSelectionModeSet = cmd.Flags().Changed("kb-selection-mode")
opts.flags.kbsSet = cmd.Flags().Changed("kb")
// L-5 / §1.5.1: --temperature is bounded 0.0..2.0. Reject
// out-of-range early with a typed input.invalid_argument so
// users don't burn a roundtrip on a value the server would
// also reject.
// --temperature is bounded 0.0..2.0. Reject out-of-range
// early with a typed input.invalid_argument so users don't
// burn a roundtrip on a value the server would also reject.
if opts.flags.temperatureSet && (opts.Temperature < 0.0 || opts.Temperature > 2.0) {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--temperature must be in 0.0..2.0, got %g", opts.Temperature))
}
if systemPromptFile != "" {
r, err := openInput(systemPromptFile)
r, err := cmdutil.OpenInput(systemPromptFile)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--system-prompt-file: %v", err))
}
@@ -219,7 +217,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, jopts *cmdutil.JSONOpti
base = *copied.Config
}
// --kb on --from REPLACES the copied KB list (per spec); when --kb
// --kb on --from REPLACES the copied KB list; when --kb
// is not set, KnowledgeBasesSet stays false inside applyCreateOverrides
// and the copy's KB list passes through unchanged.
cfg := applyCreateOverrides(&base, opts)
@@ -278,18 +276,10 @@ func applyCreateOverrides(base *sdk.AgentConfig, opts *CreateOptions) *sdk.Agent
return cfg
}
// openInput returns a Reader for path; "-" means the global stdin.
func openInput(path string) (io.Reader, error) {
if path == "-" {
return iostreams.IO.In, nil
}
return os.Open(path)
}
// openConfigFile returns a Reader, the detected kind ("yaml"/"json"), or
// an error. Format is inferred from file extension; "-" defaults to YAML.
func openConfigFile(path string) (io.Reader, string, error) {
r, err := openInput(path)
r, err := cmdutil.OpenInput(path)
if err != nil {
return nil, "", err
}
+21 -18
View File
@@ -48,18 +48,18 @@ func (f *fakeCreateSvc) UpdateAgent(_ context.Context, id string, req *sdk.Updat
func TestCreate_HappyPath_MinimalRequired(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new", Name: "Test"}}
opts := &CreateOptions{Name: "Test", Model: "gpt-4"}
opts := &CreateOptions{Name: "Test", Model: "model-x"}
err := runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
require.NoError(t, err)
require.NotNil(t, svc.createReq)
assert.Equal(t, "Test", svc.createReq.Name)
require.NotNil(t, svc.createReq.Config)
assert.Equal(t, "gpt-4", svc.createReq.Config.ModelID)
assert.Equal(t, "model-x", svc.createReq.Config.ModelID)
}
func TestCreate_MissingName_FlagError(t *testing.T) {
cmd := NewCmdCreate(nil)
cmd.SetArgs([]string{"--model", "gpt-4"})
cmd.SetArgs([]string{"--model", "model-x"})
cmd.SilenceUsage = true
cmd.SilenceErrors = true
err := cmd.Execute()
@@ -84,31 +84,31 @@ func TestCreate_ConfigFile_FlagsOverrideFile(t *testing.T) {
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new"}}
opts := &CreateOptions{
Name: "Test",
Model: "gpt-4", // override file
ConfigFileBody: bytes.NewBufferString(`{"agent_mode":"smart-reasoning","model_id":"gpt-3.5","temperature":0.5}`),
Model: "model-x", // override file
ConfigFileBody: bytes.NewBufferString(`{"agent_mode":"smart-reasoning","model_id":"model-y","temperature":0.5}`),
ConfigFileKind: "json",
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
require.NotNil(t, svc.createReq.Config)
assert.Equal(t, "smart-reasoning", svc.createReq.Config.AgentMode, "file value preserved when no flag override")
assert.Equal(t, "gpt-4", svc.createReq.Config.ModelID, "flag overrides file")
assert.Equal(t, "model-x", svc.createReq.Config.ModelID, "flag overrides file")
assert.InDelta(t, 0.5, svc.createReq.Config.Temperature, 0.001)
}
func TestCreate_From_CopiesThenUpdates(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{
copyResp: &sdk.Agent{ID: "ag_clone", Name: "Source", Config: &sdk.AgentConfig{ModelID: "gpt-3.5"}},
copyResp: &sdk.Agent{ID: "ag_clone", Name: "Source", Config: &sdk.AgentConfig{ModelID: "model-y"}},
updateResp: &sdk.Agent{ID: "ag_clone", Name: "Renamed"},
}
opts := &CreateOptions{Name: "Renamed", Model: "gpt-4", From: "ag_source"}
opts := &CreateOptions{Name: "Renamed", Model: "model-x", From: "ag_source"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc))
assert.Equal(t, "ag_source", svc.copySrcID)
require.True(t, svc.updateCalled, "must Update after Copy when overrides present")
assert.Equal(t, "ag_clone", svc.updateID)
assert.Equal(t, "Renamed", svc.updateReq.Name)
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "gpt-4", svc.updateReq.Config.ModelID)
assert.Equal(t, "model-x", svc.updateReq.Config.ModelID)
}
func TestCreate_GenerateSkeleton_NoAPICall(t *testing.T) {
@@ -126,7 +126,7 @@ func TestCreate_RepeatedKB_ImpliesSelectedMode(t *testing.T) {
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new"}}
opts := &CreateOptions{
Name: "Test",
Model: "gpt-4",
Model: "model-x",
KBs: []string{"kb_a", "kb_b"},
flags: createFlagSet{kbsSet: true},
}
@@ -140,7 +140,7 @@ func TestCreate_SystemPromptFile_ReaderRead(t *testing.T) {
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new"}}
opts := &CreateOptions{
Name: "Test",
Model: "gpt-4",
Model: "model-x",
SystemPromptReader: strings.NewReader("You are a helpful assistant.\n"),
flags: createFlagSet{systemPromptSet: true},
}
@@ -157,7 +157,7 @@ func TestCreate_From_PreservesSourceFieldsNotOverridden(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{
copyResp: &sdk.Agent{ID: "ag_clone", Config: &sdk.AgentConfig{
ModelID: "gpt-3.5",
ModelID: "model-y",
SystemPrompt: "Source prompt",
AgentMode: "smart-reasoning",
Temperature: 0.5,
@@ -167,7 +167,7 @@ func TestCreate_From_PreservesSourceFieldsNotOverridden(t *testing.T) {
}
// Only --temperature overridden; other fields should round-trip.
opts := &CreateOptions{
Name: "Renamed", Model: "gpt-3.5", From: "ag_source",
Name: "Renamed", Model: "model-y", From: "ag_source",
Temperature: 0.9,
flags: createFlagSet{temperatureSet: true},
}
@@ -181,17 +181,20 @@ func TestCreate_From_PreservesSourceFieldsNotOverridden(t *testing.T) {
}
func TestCreate_From_KBReplacesSourceList(t *testing.T) {
// --kb on --from REPLACES the copied agent's KB list (spec §2.1).
// --kb on --from REPLACES the copied agent's KB list (instead of
// merging with it). The override semantic matches a from-scratch
// `agent create --kb a --kb b`: whatever was on the source agent is
// discarded for KBs the caller explicitly listed.
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{
copyResp: &sdk.Agent{ID: "ag_clone", Config: &sdk.AgentConfig{
ModelID: "gpt-3.5",
ModelID: "model-y",
KnowledgeBases: []string{"kb_src_a", "kb_src_b"},
}},
updateResp: &sdk.Agent{ID: "ag_clone"},
}
opts := &CreateOptions{
Name: "X", Model: "gpt-3.5", From: "ag_source",
Name: "X", Model: "model-y", From: "ag_source",
KBs: []string{"kb_new"},
flags: createFlagSet{kbsSet: true},
}
@@ -205,7 +208,7 @@ func TestCreate_Temperature_Bounds(t *testing.T) {
for _, badT := range []float64{-0.1, 2.1, 100.0} {
t.Run(fmt.Sprintf("t=%g", badT), func(t *testing.T) {
cmd := NewCmdCreate(nil)
cmd.SetArgs([]string{"Test", "--model", "gpt-4", "--temperature", fmt.Sprintf("%f", badT)})
cmd.SetArgs([]string{"Test", "--model", "model-x", "--temperature", fmt.Sprintf("%f", badT)})
cmd.SilenceUsage = true
cmd.SilenceErrors = true
err := cmd.Execute()
@@ -218,7 +221,7 @@ func TestCreate_Temperature_Bounds(t *testing.T) {
func TestCreate_CopyAgent_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{copyErr: errBadHTTP404}
opts := &CreateOptions{Name: "X", Model: "gpt-4", From: "ag_missing"}
opts := &CreateOptions{Name: "X", Model: "model-x", From: "ag_missing"}
err := runCreate(context.Background(), opts, &cmdutil.JSONOptions{}, svc)
require.Error(t, err)
assert.Contains(t, err.Error(), "resource.not_found")
-1
View File
@@ -15,7 +15,6 @@ import (
// Result payload is a tiny {id, deleted} object — mirrors `kb delete`.
var agentDeleteFields = []string{"id", "deleted"}
// DeleteOptions captures `agent delete` flag state.
type DeleteOptions struct {
AgentID string
Yes bool // sourced from the global -y/--yes persistent flag
+4 -4
View File
@@ -117,15 +117,15 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
opts.flags.kbSelectionModeSet = cmd.Flags().Changed("kb-selection-mode")
opts.flags.configFileSet = cmd.Flags().Changed("config-file")
// L-5 / §1.5.1: --temperature is bounded 0.0..2.0. Reject
// out-of-range early with a typed input.invalid_argument.
// --temperature is bounded 0.0..2.0. Reject out-of-range
// early with a typed input.invalid_argument.
if opts.flags.temperatureSet && (opts.Temperature < 0.0 || opts.Temperature > 2.0) {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--temperature must be in 0.0..2.0, got %g", opts.Temperature))
}
if systemPromptFile != "" {
r, err := openInput(systemPromptFile)
r, err := cmdutil.OpenInput(systemPromptFile)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--system-prompt-file: %v", err))
}
@@ -194,7 +194,7 @@ func runEdit(ctx context.Context, opts *EditOptions, jopts *cmdutil.JSONOptions,
}
}
// L-2 fetch-then-update so omitted fields round-trip unchanged through
// Fetch-then-update so omitted fields round-trip unchanged through
// the full PUT body.
current, err := svc.GetAgent(ctx, opts.AgentID)
if err != nil {
+2 -2
View File
@@ -44,7 +44,7 @@ func TestEdit_FetchThenUpdate_PreservesUntouchedFields(t *testing.T) {
svc := &fakeEditSvc{
getResp: &sdk.Agent{
ID: "ag_abc", Name: "Original", Description: "Keep me",
Config: &sdk.AgentConfig{ModelID: "gpt-4", Temperature: 0.7, KnowledgeBases: []string{"kb_a"}},
Config: &sdk.AgentConfig{ModelID: "model-x", Temperature: 0.7, KnowledgeBases: []string{"kb_a"}},
},
updateResp: &sdk.Agent{ID: "ag_abc"},
}
@@ -59,7 +59,7 @@ func TestEdit_FetchThenUpdate_PreservesUntouchedFields(t *testing.T) {
assert.Equal(t, "Original", svc.updateReq.Name, "Name must round-trip unchanged")
assert.Equal(t, "Updated", svc.updateReq.Description)
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "gpt-4", svc.updateReq.Config.ModelID, "ModelID must round-trip")
assert.Equal(t, "model-x", svc.updateReq.Config.ModelID, "ModelID must round-trip")
assert.Equal(t, []string{"kb_a"}, svc.updateReq.Config.KnowledgeBases, "KBs must round-trip")
assert.InDelta(t, 0.7, svc.updateReq.Config.Temperature, 0.001)
}
+12 -18
View File
@@ -10,9 +10,15 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
)
// promptPreviewWidth caps inline KV row prompt previews. Multi-line prompts
// collapse to one line via text.OneLine; the Templates section gets the
// full multi-line treatment instead.
const promptPreviewWidth = 80
// agentViewFields enumerates fields surfaced for `--json=` field discovery
// on `agent view`. Only top-level Agent keys are listed because the
// `--json=foo,bar` field-projection filter matches flat top-level keys
@@ -77,9 +83,9 @@ func runView(ctx context.Context, jopts *cmdutil.JSONOptions, svc ViewService, a
}
// renderAgent prints a single agent in human-readable form, grouped into
// 10 presentation sections (spec §2.9). Zero-value fields are omitted;
// a section header prints only when at least one of its fields is set.
// Group labels and order match the spec exactly so spec drift surfaces
// 10 presentation sections. Zero-value fields are omitted; a section
// header prints only when at least one of its fields is set. Group
// labels and order are pinned by snapshot tests so future drift surfaces
// as test failure rather than silent divergence.
func renderAgent(w io.Writer, a *sdk.Agent) {
// Identity is always rendered — id/name/created_at/updated_at are
@@ -186,10 +192,10 @@ func renderAgent(w io.Writer, a *sdk.Agent) {
qr = append(qr, row{"Query understand model ID", c.QueryUnderstandModelID})
}
if c.RewritePromptSystem != "" {
qr = append(qr, row{"Rewrite prompt (system)", truncate1Line(c.RewritePromptSystem)})
qr = append(qr, row{"Rewrite prompt (system)", text.OneLine(promptPreviewWidth, c.RewritePromptSystem)})
}
if c.RewritePromptUser != "" {
qr = append(qr, row{"Rewrite prompt (user)", truncate1Line(c.RewritePromptUser)})
qr = append(qr, row{"Rewrite prompt (user)", text.OneLine(promptPreviewWidth, c.RewritePromptUser)})
}
emit("Query rewrite", qr)
@@ -251,7 +257,7 @@ func renderAgent(w io.Writer, a *sdk.Agent) {
fb = append(fb, row{"Response", c.FallbackResponse})
}
if c.FallbackPrompt != "" {
fb = append(fb, row{"Prompt", truncate1Line(c.FallbackPrompt)})
fb = append(fb, row{"Prompt", text.OneLine(promptPreviewWidth, c.FallbackPrompt)})
}
emit("Fallback", fb)
@@ -271,18 +277,6 @@ func renderAgent(w io.Writer, a *sdk.Agent) {
}
}
// truncate1Line collapses newlines and clips long values for inline KV
// rows. Templates section gets full multi-line treatment instead.
func truncate1Line(s string) string {
s = strings.ReplaceAll(s, "\n", " ")
s = strings.ReplaceAll(s, "\r", " ")
const max = 80
if len(s) > max {
return s[:max-3] + "..."
}
return s
}
// writeIndented prints s with the given prefix on every line. Trailing
// newline always added so the next section starts on its own line.
func writeIndented(w io.Writer, s, prefix string) {
+2 -2
View File
@@ -82,7 +82,7 @@ func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
Config: &sdk.AgentConfig{
AgentMode: "smart-reasoning",
SystemPrompt: "You help users.",
ModelID: "gpt-4",
ModelID: "model-x",
Temperature: 0.7,
KBSelectionMode: "selected",
KnowledgeBases: []string{"kb_a"},
@@ -101,7 +101,7 @@ func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
}
}
// Set fields rendered:
for _, want := range []string{"smart-reasoning", "gpt-4", "You help users."} {
for _, want := range []string{"smart-reasoning", "model-x", "You help users."} {
if !strings.Contains(body, want) {
t.Errorf("missing value %q in:\n%s", want, body)
}