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
+29 -5
View File
@@ -93,15 +93,19 @@ The three input modes (positional file / --recursive directory walk /
--from-url remote ingest) are mutually exclusive - pass exactly one.
Use --recursive --glob to upload a directory tree (see Examples).
Server-side ingestion knobs apply to all modes:
Server-side ingestion knobs:
--enable-multimodel Toggle multimodal extraction (image-in-PDF → text).
Unset ⇒ server default; pass true or false to override.
Applies to file / --recursive / --from-url.
--metadata key=value Attach arbitrary key/value metadata. Repeatable.
Empty value allowed; duplicate keys ⇒ last-wins.
Malformed values (no '=', empty key) ⇒
input.invalid_argument.
input.invalid_argument. File and --recursive modes
only; rejected on --from-url because the URL-ingest
request type carries no metadata field.
--channel <name> Override the ingestion-channel tag (default "api").
Applies to file / --recursive / --from-url.
URL mode (--from-url) additionally accepts --title, --file-type, and --tag-id.
Passing any of those without --from-url is rejected as input.invalid_argument.`,
@@ -239,15 +243,28 @@ func validateUploadFlags(opts *UploadOptions, args []string) error {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--recursive cannot be combined with --from-url")
}
// The server's URL-ingest request type has no Metadata field; a
// --metadata pair would be silently dropped on the wire. Reject
// up-front so callers don't think they've set metadata when they
// haven't.
if len(opts.Metadata) > 0 {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--metadata is not supported with --from-url (server URL-ingest has no metadata field)")
}
return cmdutil.ValidateHTTPURL("--from-url", opts.FromURL)
}
if !hasPath {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"a file path is required (or pass --from-url)")
}
// --title / --file-type / --tag-id are URL-mode only. Reject silently
// ignoring them in file mode to avoid the "set X, server did nothing"
// surprise.
return rejectURLOnlyFlags(opts)
}
// rejectURLOnlyFlags errors on --title / --file-type / --tag-id when
// --from-url is NOT set. Shared between validateUploadFlags (file mode)
// and runUploadRecursive (directory walk) so a future URL-mode-only flag
// only needs to add one entry here instead of two parallel checks.
func rejectURLOnlyFlags(opts *UploadOptions) error {
if opts.Title != "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--title is only valid with --from-url")
@@ -343,6 +360,13 @@ func runUpload(ctx context.Context, opts *UploadOptions, jopts *cmdutil.JSONOpti
}
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, meta, opts.EnableMultimodel, opts.Name, effectiveChannel(opts))
if err != nil {
if errors.Is(err, sdk.ErrDuplicateFile) {
// SDK returns sentinel without an "HTTP error <status>:" prefix
// (the duplicate is detected by file hash, not by status code),
// so WrapHTTP would misclassify it as network.error.
return cmdutil.Wrapf(cmdutil.CodeResourceAlreadyExists, err,
"file already uploaded to this knowledge base")
}
return cmdutil.WrapHTTP(err, "upload %s", path)
}
return renderUploadSuccess(k, jopts, "Uploaded", opts.Name, path)
+5 -20
View File
@@ -32,26 +32,11 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
Hint: "drop --name or upload files one at a time",
}
}
// URL-mode-only flags are not meaningful for a directory walk; reject
// them so misuse fails fast (mirrors the file-mode path's check in
// validateUploadFlags - that path runs before --recursive dispatches).
if opts.Title != "" {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "--title is only valid with --from-url",
}
}
if opts.FileType != "" {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "--file-type is only valid with --from-url",
}
}
if opts.TagID != "" {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "--tag-id is only valid with --from-url",
}
// URL-mode-only flags are not meaningful for a directory walk;
// rejectURLOnlyFlags is the single source of truth shared with
// file-mode upload.
if err := rejectURLOnlyFlags(opts); err != nil {
return err
}
// Parse --metadata up front so a malformed value aborts before the
// first SDK call - otherwise a typo in `key=value` would only surface
+36 -2
View File
@@ -132,6 +132,25 @@ func TestUpload_HTTPError_409Conflict(t *testing.T) {
assert.Equal(t, cmdutil.CodeResourceAlreadyExists, typed.Code)
}
// TestUpload_DuplicateFileMaps_resource_already_exists pins the contract that
// the SDK's sentinel sdk.ErrDuplicateFile (returned with no "HTTP error <n>:"
// prefix because the duplicate is detected by file-hash short-circuit, not by
// status code) is mapped to resource.already_exists. Prior regression: the
// file-upload path forwarded the sentinel to WrapHTTP, which classified the
// prefix-less message as network.error — symmetric with the --from-url branch
// which already handled ErrDuplicateURL.
func TestUpload_DuplicateFileMaps_resource_already_exists(t *testing.T) {
_, _ = iostreams.SetForTest(t)
path := writeTempFile(t, "dup.md")
svc := &fakeUploadSvc{err: sdk.ErrDuplicateFile}
err := runUpload(context.Background(), &UploadOptions{}, nil, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceAlreadyExists, typed.Code)
}
func TestValidateUploadPath_NotFound(t *testing.T) {
missing := filepath.Join(t.TempDir(), "does-not-exist.pdf")
err := validateUploadPath(missing)
@@ -238,6 +257,21 @@ func TestValidateUploadFlags_FromURL_WithRecursive_Rejected(t *testing.T) {
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
// The server's URL-ingest request type has no Metadata field; the CLI must
// reject --metadata + --from-url upfront so callers don't think they've set
// metadata that the server then silently drops on the wire.
func TestValidateUploadFlags_FromURL_WithMetadata_Rejected(t *testing.T) {
err := validateUploadFlags(&UploadOptions{
FromURL: "https://example.com/x.pdf",
Metadata: []string{"team=alpha"},
}, nil)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
assert.Contains(t, typed.Message, "--metadata is not supported with --from-url")
}
func TestValidateUploadFlags_FromURL_BadScheme(t *testing.T) {
err := validateUploadFlags(&UploadOptions{FromURL: "file:///etc/passwd"}, nil)
require.Error(t, err)
@@ -300,8 +334,8 @@ func TestParseTriBool(t *testing.T) {
{"false", false, false},
{"0", false, false},
{"no", false, false},
{"", false, true}, // explicit empty rejected
{" ", false, true}, // whitespace rejected
{"", false, true}, // explicit empty rejected
{" ", false, true}, // whitespace rejected
{"maybe", false, true},
} {
t.Run(c.in, func(t *testing.T) {