refactor(cli): drop aiclient package; align AGENTS.md with mainstream

Survey of 10 mainstream CLIs (gh, lark, stripe, vercel, supabase, aws,
azure, gcloud, openai/codex, github-copilot-cli) showed env-gated
per-command --help blurbs are a Stripe-only pattern; gh uses env detect
for telemetry only, and lark relies on installed agent Skills + MCP.
Our cmd/mcp/serve already covers the dominant 2025/26 path, so
internal/aiclient/ (136 LOC + 38 callsites) is net maintenance burden
without precedent.

- Drop internal/aiclient/ entirely (annotations + detect + tests)
- Remove 38 SetAgentHelp callsites + agentAwareHelpFunc / SetHelpFunc
  wiring in cmd/root.go
- Migrate 4 command-level rules to standard Long help (visible to all,
  not env-gated): doc upload mode mutex, kb edit at-least-one,
  kb pin idempotent, search chunks channel mutex
- Rewrite AGENTS.md as a developer guide (gh-style 6 H2 / 167 lines):
  audience preamble + Build / Architecture / Command Structure /
  Testing / Code Style / Error Handling. Drops sections absent in
  surveyed projects (Commit & PR Conventions, Who Uses This CLI)
- Clean 14 internal doc refs (ADR-N, spec §X, v0.X) in source comments
  and docs that pointed at docs/superpowers/ — that directory is
  local-only / uncommitted, so refs are dead for outside readers
- Drop forward-looking "once v0.2 ships" from README
This commit is contained in:
nullkey
2026-05-15 02:16:45 +08:00
committed by lyingbug
parent a0dd989c81
commit f2e8e3f56c
111 changed files with 575 additions and 908 deletions
-2
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
@@ -64,7 +63,6 @@ without the user's explicit go-ahead.`,
},
}
cmdutil.AddJSONFlags(cmd, docDeleteFields)
aiclient.SetAgentHelp(cmd, "Destructively deletes one document by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.")
return cmd
}
+1 -1
View File
@@ -115,7 +115,7 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
// TestDelete_NoYes_NonTTY_RequiresConfirmation: when stdout isn't a TTY
// (typical agent pipe / CI), the destructive-write protocol requires
// explicit -y/--yes. The CLI exits 10 with input.confirmation_required,
// never silently proceeds. See cli/AGENTS.md "Exit codes".
// never silently proceeds. See cli/README.md "Exit codes".
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
+1 -1
View File
@@ -5,7 +5,7 @@
// "Doc" is the CLI noun; the underlying SDK type is `Knowledge`. The renaming
// is deliberate: end-users think of a knowledge entry as the document they
// uploaded, not as an abstract knowledge unit. Mapping happens in this package
// only — the SDK surface and server API keep the original spelling.
// only - the SDK surface and server API keep the original spelling.
package doc
import (
+1 -3
View File
@@ -10,7 +10,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
@@ -57,7 +56,6 @@ Existing files are NOT overwritten unless --clobber is passed.`,
}
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")
aiclient.SetAgentHelp(cmd, "Downloads a document. Agents that pipe the bytes should pass --output - (stdout). The exit code is 0 on success, 1 on resource.not_found, 5 on missing --output when the server didn't supply a filename.")
return cmd
}
@@ -85,7 +83,7 @@ func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService
// resolveDownloadDest returns the final destination ("-" for stdout, an
// absolute or relative path otherwise) after applying the --output flag
// and sanitizing the server-suggested name. A server that returns a path-
// like filename (..\, /etc/foo) is rejected — only the basename is
// like filename (..\, /etc/foo) is rejected - only the basename is
// accepted.
func resolveDownloadDest(opts *DownloadOptions, suggested string) (string, error) {
if opts.Output == "-" {
+1 -1
View File
@@ -113,7 +113,7 @@ func TestDownload_RejectsServerPathTraversal(t *testing.T) {
require.NoError(t, os.Chdir(tmp))
defer os.Chdir(prevWD)
// The server sends "../../etc/shadow" — we accept only "shadow" and
// 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"))
+3 -5
View File
@@ -11,7 +11,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text"
@@ -41,7 +40,7 @@ type ListOptions struct {
}
// docListStatusValues mirrors internal/types/knowledge.go ParseStatus*
// constants — these are the values the server accepts on the
// constants - these are the values the server accepts on the
// ?parse_status= query. Kept in sync manually since the SDK doesn't
// re-export the enum.
var docListStatusValues = []string{"pending", "processing", "completed", "failed"}
@@ -94,7 +93,6 @@ backend storage order is not guaranteed and varies between deployments.`,
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
cmd.Flags().StringVar(&opts.Status, "status", "", "Filter by parse status: pending | processing | completed | failed")
cmdutil.AddJSONFlags(cmd, docListFields)
aiclient.SetAgentHelp(cmd, "Lists docs in the resolved KB as a bare JSON array of Knowledge objects (empty `[]` when none). --status filters server-side; `failed` surfaces ingestion errors. --all-pages walks every server page until exhausted (capped by --limit), useful for one-shot exports.")
return cmd
}
@@ -114,7 +112,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
if opts.Status != "" && !validDocListStatus(opts.Status) {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--status must be one of: %s — got %q",
Message: fmt.Sprintf("--status must be one of: %s - got %q",
strings.Join(docListStatusValues, " | "), opts.Status),
}
}
@@ -189,7 +187,7 @@ func validDocListStatus(s string) bool {
}
// formatSize renders a byte count as a short human string (KB / MB).
// Kept tiny on purpose — go-humanize would pull a transitive dep just for one
// Kept tiny on purpose - go-humanize would pull a transitive dep just for one
// column. A "-" placeholder hides zero-size entries (URL / text).
func formatSize(bytes int64) string {
if bytes <= 0 {
+2 -5
View File
@@ -161,7 +161,7 @@ func TestList_KBFlagWiredToResolveKB(t *testing.T) {
}
// With --kb=kb_<id> supplied, ResolveKB short-circuits on the prefix
// match without consulting the client. The RunE then asks for the client
// to run the actual list — that call triggers the forced error.
// to run the actual list - that call triggers the forced error.
// Surfacing "forced-after-resolvekb" (rather than CodeKBIDRequired) is
// the proof point that --kb was honored.
cmd := NewCmdList(f)
@@ -292,7 +292,7 @@ func TestList_Limit_LessThanPageSize_SlicesToLimit(t *testing.T) {
opts := &ListOptions{PageSize: 20, Limit: 5}
require.NoError(t, runList(context.Background(), opts, &cmdutil.JSONOptions{}, svc, "kb_xxx"))
body := out.String()
// Count occurrences of "id":"doc_" — should be exactly 5.
// Count occurrences of "id":"doc_" - should be exactly 5.
got := strings.Count(body, `"id":"doc_`)
assert.Equal(t, 5, got, "--limit 5 must slice 20 returned items to 5; body=\n%s", body)
}
@@ -338,6 +338,3 @@ func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
assert.LessOrEqual(t, len(svc.calls), 3, "should not walk past the page that fills --limit")
}
// (test removed: --page flag was dropped in v0.4 mainstream-alignment;
// --all-pages now walks unconditionally, no mutex case to test.)
+4 -4
View File
@@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
@@ -69,6 +68,8 @@ Pass --name to override the recorded file name (useful when the local file
has a generic name like "report.pdf" but you want to surface it as e.g.
"Q3 Marketing Report.pdf" in the UI).
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).`,
Example: ` weknora doc upload report.pdf
weknora doc upload notes.md --kb a32a63ff-fb36-4874-bcaa-30f48570a694
@@ -114,7 +115,6 @@ Use --recursive --glob to upload a directory tree (see Examples).`,
cmd.Flags().StringVar(&opts.Glob, "glob", "*", "Filename pattern to filter when --recursive (e.g. '*.pdf')")
cmd.Flags().StringVar(&opts.FromURL, "from-url", "", "Ingest a remote `URL` (HTTP/HTTPS) instead of a local file")
cmdutil.AddJSONFlags(cmd, docUploadFields)
aiclient.SetAgentHelp(cmd, "Three modes (mutually exclusive): local file (positional), --recursive directory walk + --glob, or --from-url remote ingest. Returns data: Knowledge object (file/URL) or aggregate report (recursive). Errors: resource.already_exists (URL previously ingested) / local.upload_file_not_found.")
return cmd
}
@@ -156,7 +156,7 @@ func runUploadFromURL(ctx context.Context, opts *UploadOptions, jopts *cmdutil.J
if errors.Is(err, sdk.ErrDuplicateURL) {
// Server returns 409 with the existing knowledge entry's data.
// Surface as resource.already_exists; the data payload (if any)
// is observable via err's wrap chain — but the typed code is
// is observable via err's wrap chain - but the typed code is
// what agents branch on.
return cmdutil.Wrapf(cmdutil.CodeResourceAlreadyExists, err,
"URL already ingested into this knowledge base")
@@ -190,7 +190,7 @@ func renderUploadSuccess(k *sdk.Knowledge, jopts *cmdutil.JSONOptions, humanVerb
// validateUploadPath checks that path exists and refers to a regular file.
// Symlinks and directories are rejected up-front so users get a typed error
// instead of an opaque SDK failure mid-upload. os.Stat (not Lstat) is used
// here so a symlink to a regular file is accepted — that matches what
// here so a symlink to a regular file is accepted - that matches what
// `cp` / `git add` do, and the SDK opens the file via os.Open which follows
// symlinks anyway.
func validateUploadPath(path string) error {
+2 -2
View File
@@ -19,7 +19,7 @@ type uploadOutcome struct {
}
// runUploadRecursive walks dir, filters by Glob, and uploads each match
// sequentially. Per-file errors do NOT abort the walk — they accumulate
// sequentially. Per-file errors do NOT abort the walk - they accumulate
// and the final return aggregates them so the user sees the full picture
// in one run. Exit semantics: nil error on full success, a typed *cmdutil.Error
// when ≥1 file failed (the typed code mirrors the first failure's
@@ -48,7 +48,7 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
// Sanity-check the pattern up front so a typo doesn't show up as "no
// files matched" per-file. Cobra populates --glob; tests pass it
// explicitly — no in-function default needed.
// explicitly - no in-function default needed.
if _, err := filepath.Match(opts.Glob, ""); err != nil {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
+1 -1
View File
@@ -109,7 +109,7 @@ func TestUploadRecursive_PartialFailure_Exits1(t *testing.T) {
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
// CodeServerError preserves the 500 classification of the underlying
// SDK error — the recursive wrapper just aggregates.
// SDK error - the recursive wrapper just aggregates.
assert.Equal(t, cmdutil.CodeServerError, typed.Code)
got := out.String()
-2
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text"
@@ -52,7 +51,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
},
}
cmdutil.AddJSONFlags(cmd, docViewFields)
aiclient.SetAgentHelp(cmd, "Returns the full Knowledge object for one document: id, kb_id, file metadata, parse_status, processed_at, error_message. Use this instead of paging through `doc list` when you have the doc id.")
return cmd
}
+2 -2
View File
@@ -54,7 +54,7 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
}
}
// A doc with no FileName falls back to Title for the NAME line — same
// A doc with no FileName falls back to Title for the NAME line - same
// ordering as `doc list` (KnowledgeDisplayName precedence).
func TestView_Human_TitleFallback(t *testing.T) {
out, _ := iostreams.SetForTest(t)
@@ -69,7 +69,7 @@ func TestView_Human_TitleFallback(t *testing.T) {
}
// Optional fields (ProcessedAt nil, ErrorMessage empty, EmbeddingModelID
// empty) must not produce empty KEY: lines — the formatter omits them
// empty) must not produce empty KEY: lines - the formatter omits them
// rather than printing "PROCESSED: -".
func TestView_Human_OmitsEmptyFields(t *testing.T) {
out, _ := iostreams.SetForTest(t)