From f2e8e3f56cca9d1af045db1428d1d0024d5cf66b Mon Sep 17 00:00:00 2001 From: nullkey Date: Fri, 15 May 2026 02:16:45 +0800 Subject: [PATCH] refactor(cli): drop aiclient package; align AGENTS.md with mainstream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- cli/AGENTS.md | 438 ++++++--------------- cli/CHANGELOG.md | 45 ++- cli/README.md | 96 +++-- cli/acceptance/contract/errorcodes_test.go | 15 +- cli/acceptance/contract/helpers_test.go | 11 +- cli/acceptance/contract/wire_test.go | 32 +- cli/acceptance/doc.go | 8 +- cli/acceptance/e2e/e2e_test.go | 8 +- cli/cmd/agent/agent.go | 24 +- cli/cmd/agent/invoke.go | 12 +- cli/cmd/agent/list.go | 6 +- cli/cmd/agent/view.go | 6 +- cli/cmd/api/api.go | 6 +- cli/cmd/api/api_test.go | 4 +- cli/cmd/auth/auth.go | 2 +- cli/cmd/auth/list.go | 5 +- cli/cmd/auth/list_test.go | 4 +- cli/cmd/auth/login.go | 10 +- cli/cmd/auth/login_test.go | 2 +- cli/cmd/auth/logout.go | 10 +- cli/cmd/auth/logout_test.go | 2 +- cli/cmd/auth/refresh.go | 18 +- cli/cmd/auth/refresh_test.go | 4 +- cli/cmd/auth/status.go | 11 +- cli/cmd/auth/status_test.go | 2 +- cli/cmd/auth/token.go | 12 +- cli/cmd/auth/token_test.go | 6 +- cli/cmd/chat/chat.go | 14 +- cli/cmd/context/add.go | 4 +- cli/cmd/context/context.go | 2 +- cli/cmd/context/list.go | 6 +- cli/cmd/context/remove.go | 12 +- cli/cmd/context/use.go | 4 +- cli/cmd/context/use_test.go | 4 +- cli/cmd/doc/delete.go | 2 - cli/cmd/doc/delete_test.go | 2 +- cli/cmd/doc/doc.go | 2 +- cli/cmd/doc/download.go | 4 +- cli/cmd/doc/download_test.go | 2 +- cli/cmd/doc/list.go | 8 +- cli/cmd/doc/list_test.go | 7 +- cli/cmd/doc/upload.go | 8 +- cli/cmd/doc/upload_recursive.go | 4 +- cli/cmd/doc/upload_recursive_test.go | 2 +- cli/cmd/doc/view.go | 2 - cli/cmd/doc/view_test.go | 4 +- cli/cmd/doctor/doctor.go | 38 +- cli/cmd/doctor/doctor_test.go | 16 +- cli/cmd/kb/create.go | 6 +- cli/cmd/kb/delete.go | 4 +- cli/cmd/kb/delete_test.go | 6 +- cli/cmd/kb/edit.go | 9 +- cli/cmd/kb/edit_test.go | 2 +- cli/cmd/kb/empty.go | 2 - cli/cmd/kb/list.go | 7 +- cli/cmd/kb/pin.go | 5 +- cli/cmd/kb/view.go | 3 +- cli/cmd/link/link.go | 8 +- cli/cmd/link/unlink.go | 2 - cli/cmd/mcp/mcp.go | 2 +- cli/cmd/mcp/serve.go | 21 +- cli/cmd/root.go | 36 +- cli/cmd/root_test.go | 6 +- cli/cmd/search/chunks.go | 13 +- cli/cmd/search/chunks_test.go | 2 +- cli/cmd/search/docs.go | 5 +- cli/cmd/search/kb.go | 10 +- cli/cmd/search/search.go | 4 +- cli/cmd/search/search_test.go | 5 +- cli/cmd/search/sessions.go | 4 +- cli/cmd/session/delete.go | 2 - cli/cmd/session/list.go | 4 +- cli/cmd/session/list_test.go | 2 - cli/cmd/session/session.go | 2 +- cli/cmd/session/view.go | 2 - cli/internal/aiclient/annotations.go | 35 -- cli/internal/aiclient/detect.go | 38 -- cli/internal/aiclient/detect_test.go | 62 --- cli/internal/cmdutil/authrefresh.go | 2 +- cli/internal/cmdutil/authretry.go | 6 +- cli/internal/cmdutil/authretry_test.go | 4 +- cli/internal/cmdutil/confirm.go | 2 +- cli/internal/cmdutil/errors.go | 16 +- cli/internal/cmdutil/errors_codes_test.go | 2 +- cli/internal/cmdutil/exit.go | 12 +- cli/internal/cmdutil/factory.go | 24 +- cli/internal/cmdutil/factory_test.go | 10 +- cli/internal/cmdutil/host.go | 4 +- cli/internal/cmdutil/jsonflags_test.go | 2 +- cli/internal/cmdutil/kb.go | 2 +- cli/internal/compat/cache.go | 2 +- cli/internal/compat/cache_test.go | 2 +- cli/internal/compat/compat.go | 26 +- cli/internal/compat/compat_test.go | 4 +- cli/internal/compat/version_check.go | 5 +- cli/internal/config/config.go | 4 +- cli/internal/format/references.go | 2 +- cli/internal/mcp/server.go | 2 +- cli/internal/mcp/tools.go | 24 +- cli/internal/projectlink/projectlink.go | 8 +- cli/internal/prompt/prompt.go | 9 +- cli/internal/secrets/keyring.go | 2 +- cli/internal/secrets/secrets.go | 19 +- cli/internal/sse/accumulator.go | 6 +- cli/internal/sse/accumulator_test.go | 4 +- cli/internal/sse/agent_accumulator.go | 4 +- cli/internal/testutil/prompter.go | 2 +- cli/internal/text/displayname.go | 2 +- cli/internal/text/pluralize.go | 3 +- cli/internal/text/truncate.go | 10 +- cli/internal/xdg/xdg.go | 2 +- 111 files changed, 575 insertions(+), 908 deletions(-) delete mode 100644 cli/internal/aiclient/annotations.go delete mode 100644 cli/internal/aiclient/detect.go delete mode 100644 cli/internal/aiclient/detect_test.go diff --git a/cli/AGENTS.md b/cli/AGENTS.md index d2332178..6feb9322 100644 --- a/cli/AGENTS.md +++ b/cli/AGENTS.md @@ -1,359 +1,167 @@ -# Agent Integration Guide for `weknora` CLI +# AGENTS.md -> **Scope.** This file is an **operational reference** for LLM agents -> (Claude Code, Cursor, Codex, Aider, Gemini Coder, etc.) that **invoke -> `weknora` on a user's behalf**. It documents the wire shape, exit code, -> and behavioral conventions an agent integration relies on. -> -> This is **not** a contributor guide. If you are an AI coding agent -> editing weknora's source, see the repo root `README.md` (and, if added -> later, a separate contributor `AGENTS.md` at the repo root). -> -> **Naming note.** "Agent" appears in two distinct WeKnora contexts: -> -> - **This file (`AGENTS.md`) + the `agent_help` annotation on each -> command's `--help`**: documents the contract for AI coding agents -> (you, the LLM-driven CLI consumer). -> - **The `weknora agent` subtree** (`agent list / view / invoke`): -> manages WeKnora's first-class *Custom Agent* resources — server-side -> records (system prompt + model + allowed tools + KB scope) that the -> user authored in the web UI. `agent invoke` calls the agent's -> configured workflow against a query; it is **not** how you, the AI -> coding agent, drive WeKnora — that's `kb` / `doc` / `search` / `chat` -> / `mcp serve`. +WeKnora CLI (`weknora`) is a noun-verb wrapper around the WeKnora server API; module path `github.com/Tencent/WeKnora/cli`. This file is the developer guide for coding agents and human contributors editing the CLI. The user-facing wire contract (output shape, exit codes, error format) lives in [README.md](README.md). -`weknora` is designed to be agent-friendly: error messages, output -format, and flag design follow conventions agents can rely on. -Wire-contract breaking changes are flagged in their PR description and -the corresponding `weknora --version` bump — agents should pin a -known-good version and re-validate against `--help` output on upgrade. - -The "Output contract" and "Behavioral rules" sections below are the -self-contained specification of the wire format; everything an integrator -needs is in this document. - ---- - -## Output contract - -### Streams - -- **stdout** is the data channel: bare JSON (with `--json`) or - human-formatted output (without `--json`). Never carries error text. -- **stderr** is logs / progress / warnings / errors / agent guidance - footnotes. On failure, the error message + actionable hint go here. - -A non-empty stderr does **not** mean failure — read the exit code instead. - -### JSON output (bare data) - -When `--json` is set on a successful command, stdout contains exactly -one JSON value matching the resource the command produces: - -| Command shape | stdout JSON | -|---|---| -| `list` / `search` | `[ { …resource… }, … ]` (bare array; `[]` when empty) | -| `view` / `create` / `edit` | `{ …resource… }` (bare object) | -| `delete` / `pin` / write ops | `{ id, …action-result fields… }` (bare object) | -| `doctor` | `{ summary: { all_passed, passed, warned, failed, skipped }, checks: [ … ] }` | - -There is no `ok` / `data` / `error` wrapper. Agents read the resource -shape directly. Successful runs always return exit 0; failures never -emit data JSON on stdout. - -#### Field selection: `--json=field,field,…` - -`--json` accepts a comma-separated field list (passed with `=`) to restrict -each top-level object (or each element of a top-level array) to the named -keys: +## Build, Test, and Lint ```bash -weknora kb list --json=id,name # [{ "id": "kb_x", "name": "Eng" }, …] -weknora kb view kb_x --json=id # { "id": "kb_x" } +go build -o weknora . # build (from cli/) +go test -count=1 ./... # unit + contract tests +go test -run TestFoo ./internal/format/ # single test +go test ./acceptance/contract/ -args -update # refresh wire goldens +go test -tags acceptance_e2e ./acceptance/e2e/... # live-server e2e (gated by env) +go vet ./... ``` -Note the `=` form: pflag's optional-value parser treats space-separated -arguments after a bare `--json` as positionals, so `--json id,name` would -be interpreted as bare `--json` plus the positional `id,name`. Always use -`--json=field,...` for projection. +Both `go test -count=1 ./...` and `go vet ./...` must pass before committing. -Unknown field names are silently dropped so you can pass an aspirational -field set across heterogenous outputs. +## Architecture -#### jq pipeline: `--jq ` +Entry point: `cmd/main.go` → `cmd.Execute()` → `cmd.NewRootCmd(cmdutil.New())`. -`--jq` applies a jq expression to the JSON before printing. The -expression sees the same bare shape the command produces (no envelope -indirection). String results render without quotes for shell-friendly -substitution; non-string results render as JSON. +Key packages: -```bash -weknora kb list --jq '.[].id' # one id per line -weknora kb view kb_x --jq .name # bare name -weknora search chunks "x" --kb e --jq '.[].score' # scores per line +- `cmd//` — cobra command implementations, one subdir per noun +- `internal/cmdutil/` — `Factory`, `JSONOptions`, typed `Error`, exit-code mapping, destructive-write confirm, KB id-or-name resolve +- `internal/format/` — bare JSON emitter (`WriteJSON` / `WriteJSONFiltered`) +- `internal/iostreams/` — global IO singleton + TTY detection + `SetForTest` swap +- `internal/secrets/` — `Store` interface; `KeyringStore` primary, `FileStore` 0600 fallback, `MemStore` for tests +- `internal/prompt/` — `TTYPrompter` (huh-based, password no-echo) + `AgentPrompter` (non-TTY no-prompt sentinel) +- `internal/sse/` — `Accumulator` for chat / agent invoke SSE streams +- `internal/mcp/` — curated stdio MCP server (wired by `cmd/mcp/serve.go`) +- `client/` (parent module) — generated SDK + +## Command Structure + +A command `weknora foo bar` lives in `cmd/foo/bar.go` with `bar_test.go`. + +### Canonical Examples + +- **Command + tests**: `cmd/kb/list.go` and `list_test.go` +- **Destructive write + confirm protocol**: `cmd/kb/delete.go` +- **SSE streaming command**: `cmd/chat/chat.go` +- **Factory wiring**: `internal/cmdutil/factory.go` + +### The Options + Narrow Service Pattern + +Every command follows this structure (see `cmd/kb/list.go`): + +1. `Options` struct with flag-bound fields +2. `Service` interface declaring only the SDK methods this command calls. `*sdk.Client` satisfies it implicitly via duck typing. +3. `NewCmd(f *cmdutil.Factory) *cobra.Command` constructor — flag registration + `cmdutil.AddJSONFlags` +4. Separate `run(ctx, opts, jopts, svc, args...)` with the business logic — the test injection point + +Key rules: + +- Each command owns its own `Service` interface; do NOT share interfaces across `cmd/*` packages. Per-file dependency graph is the goal. +- Lazy-init `f.Client()` / `f.Secrets()` / `f.Prompter()` inside `RunE`, not the constructor (else `--help` forces auth). +- Required flags: `_ = cmd.MarkFlagRequired("name")` — cobra returns the error only on registration-time typo. +- New subtrees register in `cmd/root.go NewRootCmd`. Verb subtrees register their leaves in the subtree's own `NewCmd`. + +### Command Examples and Help Text + +Use a Go raw string with `weknora` as the example prefix. Keep one-line `Short` ≤ 70 chars; `Long` may run multi-paragraph; `Example` always includes `weknora` so copy-paste works: + +```go +Example: ` weknora kb view + weknora kb view kb_abc --json + weknora kb view kb_abc --json=id,name`, ``` -`--jq` requires `--json`. Combining with `--json=id,name` is fine — the -filter runs after the field projection. +### JSON Output -### Errors (stderr, exit code carries the class) +Add `--json` / `--jq` via `cmdutil.AddJSONFlags(cmd, fieldNames)`. In `RunE`: -On failure, stdout is empty (or holds the partial-success output the -command already wrote before the failure). The error message goes to -stderr in this format: - -``` -: [: ] -hint: +```go +if jopts.Enabled() { + return jopts.Emit(iostreams.IO.Out, result) +} ``` -- `` is a `namespace.snake_case` string from a closed - registry in `cli/internal/cmdutil/errors.go` (`AllCodes()`). - An acceptance test enforces that every code referenced in `cli/cmd/` - is registered. -- `` is the human-readable description. -- `` is the deterministic next-step hint (omitted when no hint - applies). +`Emit` is the single source for the bare-JSON contract — it honors `--json=fields,...` projection and `--jq ` filtering. Never call `format.WriteJSON*` directly from a command. See `cmd/kb/list.go`. -Code namespaces: `auth.*` / `resource.*` / `input.*` / `server.*` / -`network.*` / `local.*` / `mcp.*`. +### Destructive Writes -To pattern-match programmatically: split on the first `:` to extract -the code, or branch on the exit code (see below). +Commands that delete / empty / overwrite call `cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), what, id)` before mutation. In non-TTY OR `--json` mode without `-y`, it returns `CodeInputConfirmationRequired` → exit 10. See `internal/cmdutil/confirm.go`. -### Exit codes +## Testing -| Code | Meaning | Agent action | -|---|---|---| -| `0` | Success | Continue | -| `1` | Typed `local.*` error or unclassified | Read stderr, decide retry/abort | -| `2` | Flag/argument validation error | Re-check `weknora --help` | -| `3` | `auth.*` (token missing / expired / forbidden) | Re-auth then retry | -| `4` | `resource.not_found` | Verify the resource id | -| `5` | `input.*` (other than confirmation_required) | Adjust args and retry | -| `6` | `server.rate_limited` | Back off, then retry | -| `7` | `server.*` / `network.*` | Transient; retry with backoff | -| `10` | **`input.confirmation_required`** — high-risk write needs `-y` | Ask the human, retry with `-y` only after explicit approval | -| `130` | Cancelled (SIGINT / Ctrl-C) | Stop, do not retry | +### Narrow Service Fakes -Exit 10 is the wire-level signal for "high-risk write needs explicit -confirmation". **Never bypass exit 10 by auto-passing `-y` without -explicit user permission.** +Each command's `runX(ctx, opts, jopts, svc, ...)` takes its interface, not `*sdk.Client`. Tests inject plain-struct fakes: ---- - -## Command surface - -Discover the command tree the same way human users do: - -```bash -weknora --help # top-level -weknora kb --help # subtree -weknora kb delete --help # single command flags +```go +type fakeBarSvc struct { + gotID string + resp *sdk.Bar + err error +} +func (f *fakeBarSvc) GetBar(_ context.Context, id string) (*sdk.Bar, error) { + f.gotID = id + return f.resp, f.err +} ``` -The command tree follows ` `. Verbs are: +No mocking library; the narrow-interface design makes fakes 5 lines each. -| Verb | Semantics | Example | -|---|---|---| -| `list` | Multi-resource read | `kb list` | -| `view` | Single-resource read | `kb view ` | -| `create` | Create resource | `kb create --name X` | -| `edit` | Partial update (only sent fields change) | `kb edit --description X` | -| `delete` | Destructive remove (KB itself) | `kb delete -y` | -| `empty` | Bulk-delete contents, preserve container | `kb empty -y` | -| `upload` | Bulk write content | `doc upload ` | -| `download` | Stream resource to disk | `doc download -O file` | -| `pin` / `unpin` | Toggle "pinned" state (idempotent) | `kb pin ` | -| `use` | Switch active selection | `context use ` | -| `add` / `remove` | Manage local config entries | `context add staging --host ...` | +### IOStreams in Tests -`auth` subtree: `login` / `logout` / `list` / `status` / `refresh` / -`token`. Context-switching uses `context use ` (WeKnora contexts -bundle host + tenant + credentials, so they need a richer abstraction -than a single per-host token slot). `auth refresh` exchanges the stored -refresh token for a new access + refresh pair (OAuth refresh-token -grant); it errors with `input.invalid_argument` on API-key contexts -which have no refresh semantic. Transparent 401 → refresh → retry is -wired into the SDK transport (`cli/internal/cmdutil/authretry.go`) -with singleflight de-dup, so most callers never need to invoke `auth -refresh` explicitly. +```go +out, errBuf := iostreams.SetForTest(t) // bytes.Buffer sinks, non-TTY +ios, _ := iostreams.SetForTestWithTTY(t) // simulate terminal +``` -### Auth security contract +### Confirm Prompts -- **Credential storage**: OS keychain via `go-keyring` (macOS Keychain, - Windows Credential Manager, freedesktop Secret Service). Falls back to - a 0600 file under `$XDG_CONFIG_HOME/weknora/secrets//` only - when no keyring backend is available. `auth login` prints a stderr - warning at fallback time; `weknora doctor` flags it under - `credential_storage`. -- **`auth login --with-token`**: reads the API key from **stdin**, never - from a flag value (so it never appears in `ps` / shell history). The - key is validated against `/auth/me` **before** being persisted — a - typo / expired / wrong-host key fails fast with - `auth.bad_credential` and nothing is written. -- **No env-var token bypass**: WeKnora does NOT honor a `WEKNORA_TOKEN` - env var as an implicit credential source — by design, to avoid the - process-environment leak surface (`/proc//environ`, `ps -E`, - multi-tenant CI runners). CI / scripts should pipe the key via - `weknora auth login --with-token` into the keyring (or the file - fallback under an isolated `$XDG_CONFIG_HOME`). -- **`auth status` / `auth list`**: never emit token values, in either - human or JSON modes. The `mode` field (`bearer` / `api-key`) signals - which credential class is stored, not the value. -- **`auth token`**: the only command that prints the stored credential. - Stdout has **no trailing newline** so `$(weknora auth token)` is - clean; when stdout is a TTY, a stderr advisory warns the user that - the secret just landed in scrollback, plus an extra note for api-key - mode (long-lived, rotate at the server). -- **`auth refresh` `--json`**: returns only `{context}` — never the new - access or refresh token. Agents that need to verify the new - credential should re-run `auth status` (live `/auth/me` probe). -- **`auth logout`**: local-only — deletes the keyring entry + file - fallback + the context entry in `config.yaml`. **Does NOT revoke - server-side.** For JWT, the issued token stays valid until expiry; - for API keys, rotate them in the server UI. +Use `testutil.ConfirmPrompter{Answer: bool, Err: error}` from `internal/testutil/`. Single source for the prompt double — do NOT re-define `confirmPrompter` per package. -`search` subtree: `search chunks "" --kb X` for hybrid retrieval; -`search kb ""` / `search docs "" --kb X` / `search sessions ""` -for client-side substring filtering on the listing endpoints. +### Assertions -`session` subtree: `list` / `view` / `delete` for chat session -management. Sessions are the durable wrapper around `chat` invocations. +Use `testify`. Prefer `require` (not `assert`) for error checks so the test halts immediately, and `assert` for value comparisons: -Top-level RAG / connectivity verbs: `chat`, `search`, `api`, `link`, -`auth`, `context`, `session`, `doctor`, `version`. +```go +require.NoError(t, err) +require.ErrorAs(t, err, &typed) +assert.Equal(t, "expected", actual) +``` -`doctor` is a deliberate WeKnora addition: RAG deployments routinely -break on misconfigured embeddings, storage backends, and credentials, -and the structured `{summary: {all_passed, passed, warned, failed, -skipped}, checks: [...]}` JSON shape is the cleanest agent-readable -surface for that. +### Acceptance: Wire-Shape Goldens ---- +`acceptance/contract/wire_test.go` drives the in-process cobra tree against `httptest.Server` fixtures and compares stdout to `acceptance/testdata/wire/.json`. Error-path cases also assert stderr contains the typed code substring (e.g. `auth.unauthenticated`). Update goldens with `go test ./acceptance/contract/ -args -update`. -## Behavioral rules +### Table-Driven Tests -Per-command guidance also appears in each command's `--help` output -(under "AI Agents:"). +Use for flag validation, error classification, parser edge cases. See `internal/cmdutil/exit_test.go` and `cmd/kb/list_test.go`. -1. **Pass `-y/--yes`** on destructive writes (`kb delete` / `kb empty` / - `doc delete` / `session delete` / `context remove` when targeting - the current context) when running headless. Without it, you will - get exit 10. **Never auto-add `-y`** without the user's explicit - go-ahead — the exit-10 protocol is the one explicit guard against - unintended writes. -2. **Prefer typed commands over `weknora api`** for known endpoints. - Fallback to `weknora api` only when no typed command covers the - call. -3. **For chat, prefer `--no-stream --json`** in agent contexts. - Streaming tokens to stdout makes JSON parsing impossible. -4. **`link` writes to the user's working directory** — only run it - when the user invoked it, not as a side effect of unrelated - automation. +```go +tests := []struct{ name string; ...}{ + {name: "descriptive case", ...}, +} +for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { /* arrange, act, assert */ }) +} +``` -(Additional safety guidance — e.g. "do not switch context unless the -user asked" — is documented in the affected command's own `--help`.) +## Code Style ---- +- Add godoc to every exported function, type, and constant. Explain *why*, not *what* — the name already says *what*. +- Don't comment to restate the code. Delete comments that narrate the next line. +- Don't reference task numbers, commit SHAs, or version tags in inline comments — they belong in CHANGELOG or git log. +- Never paste em-dashes (—) into Go source; use ASCII `-` or rewrite. (Markdown docs may use em-dashes.) +- Don't add a helper for a single caller — inline. -## Auto-detection of agent environments +## Error Handling -`weknora` checks these environment variables (case-sensitive): +Typed error helpers in `internal/cmdutil/errors.go`: -| Env var | Detected agent name | -|---|---| -| `CLAUDECODE` | `claude-code` | -| `CURSOR_AGENT` | `cursor` | +- `cmdutil.NewError(code, msg)` — fresh typed error +- `cmdutil.WrapHTTP(err, format, args...)` — wrap an SDK error + classify from HTTP status (404 → `resource.not_found`, 401 → `auth.unauthenticated`, …). Use at every SDK call site. +- `cmdutil.Wrapf(code, err, format, args...)` — explicit wrap with a chosen code +- `cmdutil.NewFlagError(err)` — flag / argument problem → exit 2 +- `cmdutil.SilentError` — exit 1 without printing (when output already emitted) +- `cmd.MarkFlagsMutuallyExclusive("a", "b")` — cobra-level mutex -When any is set, `weknora --help` appends the command's `agent_help` -annotation. **No behavior change** — this is help-text rendering only. +Errors print to STDERR via `cmdutil.PrintError(w, err)` as `code: msg\nhint: ...`. STDOUT stays bare JSON or empty on failure, so `--json | jq` pipelines never have to filter error shapes. -To suppress detection (e.g. running `weknora` interactively from inside -Claude Code without the agent footer): `WEKNORA_NO_AGENT_AUTODETECT=1`. +User-facing exit-code mapping lives in [README.md "Exit codes"](README.md#exit-codes). When adding a new `ErrorCode` constant, also append to `AllCodes()` so the acceptance contract picks it up. -Agent detection (`CLAUDECODE` / `CURSOR_AGENT` env) also tags the -User-Agent header for server-side telemetry — it never changes CLI -behavior. - ---- - -## Architecture decisions - -A handful of decisions are referenced inline in the source as `ADR-N`. They -live here, alongside the contract they shape. - -**ADR-3 — bare-data JSON on stdout, errors on stderr.** Successful -commands emit the raw resource shape (`[]Item` for lists, `T` for views, -`{id, deleted: true}` for deletes) — no `ok` / `data` / `error` -wrapper. Errors are not data; they go to stderr in `code: message\nhint: -…` form, and the typed exit code carries the failure class for -programmatic branching. This separates "what the command produces" from -"how the run went", so `--json | jq` pipelines never have to filter -error shapes out of the success stream, and matches the contract of -gh / aws / stripe. - -WeKnora-specific shape choices: - -- `link` (project-binding) — `/.weknora/project.yaml` walk-up - matches how RAG users scope work to a specific knowledge base. There - is no per-host config model competing with it; `context use` is the - separate mechanism for switching the credential set. -- `chat` / `search` are domain-specific verbs (LLM streaming + - retrieval) with no equivalent in pure-API CLIs. -- `context use` switches the active credential set; contexts bundle - host + tenant + credential, so a richer abstraction than a single - per-host token slot is required. -- `doctor` (4-status: ok / warn / fail / skip per check, plus a - summary object) is the agent-readable surface for RAG-deployment - misconfiguration (embeddings, storage, credentials) — failure modes - that the underlying SDK can't classify on its own. Agents short- - circuit on `summary.all_passed`; exit code is non-zero iff any - check is `fail`. - -Verb canon: `list / view / create / edit / delete / upload / download -/ pin / unpin / use`. WeKnora-specific verbs for resource semantics -the common set lacks: `empty` (bulk-delete contents preserving the -container), `refresh` (token), `add` / `remove` (context CRUD), -`link` / `unlink` (project bind / unbind), `invoke` (run a custom -agent), `serve` (long-lived MCP transport). - -**ADR-4 — Factory closures + narrow Service interfaces.** `cmdutil.Factory` -exposes four lazy closures (Config / Client / Prompter / Secrets) that -commands may invoke, but each subcommand declares its own narrow `Service` -interface for the SDK calls it actually makes. The production `*sdk.Client` -satisfies these implicitly via duck typing; tests inject fakes. Splitting -the boundaries this way means a subcommand's test can stand up an -`httptest.Server` (or a hand-rolled struct) without standing up the full -SDK, and the dependency graph of any one command is visible in one file. - ---- - -## Known limitations - -The following classes of failure currently surface as `error.code = -"network.error"` with `context deadline exceeded` rather than a precise -typed code. A future release will introduce a `precondition.*` -namespace (server returns HTTP 412 with a typed remediation body before -opening the SSE / streaming response): - -- `weknora chat` when no chat model is configured for the active tenant -- `weknora search chunks` when no retriever / vector store is configured -- `weknora doc upload` when no storage engine is selected for the KB - -Workaround until then: if a chat / search / upload call times out -without producing a first-byte response, check the server's tenant -configuration (LLM / vector store / storage engine) before retrying. A -planned `weknora doctor --server-config` will probe these directly. - ---- - -## Reporting issues - -If the CLI's behavior contradicts this document, that is a bug. File at -https://github.com/Tencent/WeKnora/issues with: - -- The exact command line -- `weknora --version` output -- The output (stdout + stderr) you got vs the output this document - promises diff --git a/cli/CHANGELOG.md b/cli/CHANGELOG.md index a32d1ff0..05e34924 100644 --- a/cli/CHANGELOG.md +++ b/cli/CHANGELOG.md @@ -7,11 +7,52 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and the CLI follows [Semantic Versioning](https://semver.org/) independently of the WeKnora server / frontend release cadence. -Earlier history (v0.0 through v0.2) is recorded in the project root -[CHANGELOG.md](../CHANGELOG.md) under the entries that introduced the CLI. +CLI history before v0.3 is recorded in the project root +[CHANGELOG.md](../CHANGELOG.md) under the release that introduced the CLI. ## [Unreleased] +### v0.4 — output contract hardening and mainstream alignment + +#### Breaking changes +- Dropped the JSON envelope. `stdout` now emits bare typed data + (`{...}` or `[...]`); errors are written to `stderr` as `code: msg` + with an actionable `hint:` line. Pipelines using `--json | jq` no + longer have to filter out an envelope wrapper. +- Dropped `--dry-run`. Destructive writes still require `-y/--yes`; + non-TTY callers that omit `-y` exit with code 10 and + `input.confirmation_required` so an agent must surface the prompt + to a human before retrying. +- Dropped the per-command AI footer that rendered when `CLAUDECODE` + or `CURSOR_AGENT` was set. The same machine-readable guidance now + lives in the standard `--help` (visible to all callers) and in + `mcp serve`'s tool descriptions. + +#### Added +- `weknora mcp serve` — curated read-only stdio MCP server exposing 9 + tools (`kb_list`, `kb_view`, `doc_list`, `doc_view`, `doc_download`, + `search_chunks`, `chat`, `agent_list`, `agent_invoke`). Destructive + verbs are intentionally excluded. +- `weknora agent list` / `agent view` / `agent invoke` — manage and + call WeKnora's server-side Custom Agent resources. +- `weknora auth token` — print the active credential to `stdout` for + scripting (raw secret by default; `--json` emits `{token, mode, context}`). +- `weknora doc upload --from-url` — ingest a remote URL. +- `--json=fields,...` field projection and `--jq ` filtering on + every command that emits JSON. +- `--limit` and `--all-pages` on list / search commands for bounded + output and explicit pagination control. +- Per-resource filter flags: `kb list --pinned`, `doc list --status`, + `session list --since`. + +#### Changed +- Go toolchain bumped from 1.24 to 1.26. +- `auth login --with-token` validates the supplied key against + `/auth/me` before persisting, and prints an advisory if the keyring + is unavailable and credentials fall back to a 0600 file under + `$XDG_CONFIG_HOME/weknora/secrets/`. +- AGENTS.md rewritten as a developer guide (~170 lines, 6 H2 sections). + ### v0.3 — extended management surface and a `session` subtree #### Added diff --git a/cli/README.md b/cli/README.md index ad516b47..3681c1f4 100644 --- a/cli/README.md +++ b/cli/README.md @@ -10,24 +10,28 @@ WeKnora CLI lets you authenticate, browse knowledge bases, and run hybrid searches against a WeKnora server from your shell or an AI agent. Available Commands: + agent Manage and invoke custom agents api Make a raw API request to the WeKnora server auth Manage authentication credentials and contexts chat Ask a streaming RAG question against a knowledge base + completion Generate the autocompletion script for the specified shell context Manage CLI contexts (named connection targets) doc Manage documents in a knowledge base doctor Run 4 self-checks: base URL, auth, server version, credential storage + help Help about any command kb Manage knowledge bases link Bind the current directory to a knowledge base + mcp Run weknora as a Model Context Protocol server search Search across chunks, knowledge bases, documents, or sessions session Manage chat sessions + unlink Remove the directory's knowledge-base binding version Show CLI build metadata ``` -The command surface mirrors `gh` CLI's ` ` convention. See -[AGENTS.md](AGENTS.md) for the operational contract that AI agents -(Claude Code, Cursor, Aider, …) can rely on: bare-JSON output shape, -stderr error format, exit-code protocol, error-code registry, and -per-command guidance. +The command surface mirrors `gh` CLI's ` ` convention. The +wire contract for AI agents (Claude Code, Cursor, Aider, …) is documented +[below](#wire-contract). For contributing to the CLI source, see +[AGENTS.md](AGENTS.md). --- @@ -35,7 +39,7 @@ per-command guidance. ### From source -Requires Go 1.24+. +Requires Go 1.26+. ```bash git clone https://github.com/Tencent/WeKnora.git @@ -47,8 +51,7 @@ sudo mv weknora /usr/local/bin/ # or anywhere on $PATH ### Pre-built binaries Pre-built binaries for Linux / macOS / Windows are produced by CI on each -release. Grab the latest from the [Releases page](https://github.com/Tencent/WeKnora/releases) -once v0.2 ships. +release. Grab the latest from the [Releases page](https://github.com/Tencent/WeKnora/releases). --- @@ -106,7 +109,20 @@ weknora auth logout --all --- -## JSON output +## Wire contract + +Designed to be agent-first. Stable across minor releases; breaking +changes announced in the changelog and the corresponding +`weknora --version` bump. + +### Streams + +- **stdout** is the data channel: bare JSON with `--json`, or + human-formatted output. Never carries error text. +- **stderr** is logs, progress, warnings, and errors. A non-empty + stderr does **not** mean failure — read the exit code. + +### JSON output Every command supports `--json`, emitting bare JSON for the resource it produces — an array for `list` / `search`, a single object for `view` @@ -119,32 +135,62 @@ weknora kb list --json=id,name # project to listed fields weknora kb list --json --jq '.[].id' # jq over the bare data ``` +Note the `=` form for projection: pflag's optional-value parser treats +space-separated arguments after a bare `--json` as positionals, so +`--json id,name` would be interpreted as bare `--json` + the positional +`id,name`. Always use `--json=field,...`. + +### Errors + On failure, stdout stays empty and the typed error goes to stderr in -`code: message\nhint: ...` form: +this format: + +``` +: [: ] +hint: +``` + +Example: ``` auth.unauthenticated: fetch current user: HTTP error 401: ... hint: run `weknora auth login` ``` -The typed exit code (3 / 4 / 5 / 6 / 7 / 10) carries the failure -class for agents that branch on it. The full error-code registry and -exit-code protocol are documented in [AGENTS.md](AGENTS.md). +The full code registry is in `cli/internal/cmdutil/errors.go` +(`AllCodes()`). Code namespaces: `auth.*` / `resource.*` / `input.*` / +`server.*` / `network.*` / `local.*` / `mcp.*`. ---- +### Exit codes -## Agent / scripting integration +| Code | Meaning | Agent action | +|---|---|---| +| `0` | success | continue | +| `1` | typed `local.*` or unclassified | read stderr, decide retry/abort | +| `2` | flag / argument validation error | re-check `weknora --help` | +| `3` | `auth.*` (token missing / expired / forbidden) | re-auth, then retry | +| `4` | `resource.not_found` | verify the resource id | +| `5` | `input.*` (other than `confirmation_required`) | adjust args, retry | +| `6` | `server.rate_limited` | back off, retry | +| `7` | `server.*` / `network.*` | transient — retry with backoff | +| `10` | **`input.confirmation_required`** (high-risk write) | ask the human, retry with `-y` only after explicit approval | +| `130` | cancelled (SIGINT / Ctrl-C) | stop, do not retry | -Designed to be agent-first: +**Exit 10** is the wire-level signal for "destructive write needs +explicit confirmation". Pass `-y/--yes` on `kb delete` / `kb empty` / +`doc delete` / `session delete` / `context remove` (on the current +context) when running headless. **Never auto-add `-y` without the +user's explicit go-ahead** — exit 10 is the guard against unintended +writes. -- `-y/--yes` skips confirmation prompts for high-risk writes. **Without - `-y` on a non-TTY/`--json` invocation, destructive commands return - `error.code: input.confirmation_required` and exit code 10** so an - agent can ask the user before retrying. -- `--json` coexists with the global `--context ` for single-shot - context override. -- Set `CLAUDECODE` or `CURSOR_AGENT` environment variables to surface - per-command "AI agents:" guidance in `--help` output. +### Other agent ergonomics + +- For chat / agent invoke in agent contexts, prefer `--no-stream --json` + — streaming tokens to stdout makes JSON parsing impossible. +- `--json` composes with the global `--context ` for single-shot + context overrides without disk writes. +- `weknora mcp serve` exposes a curated readonly tool surface over + stdio MCP for Claude Desktop / Code / custom MCP clients. --- @@ -171,7 +217,7 @@ go vet ./... ``` CI (`.github/workflows/cli.yml`) runs build + unit + contract tests on Linux / -macOS / Windows × Go 1.24, path-filtered to changes under `cli/`. +macOS / Windows × Go 1.26, path-filtered to changes under `cli/`. --- diff --git a/cli/acceptance/contract/errorcodes_test.go b/cli/acceptance/contract/errorcodes_test.go index 12e98c4d..44bec796 100644 --- a/cli/acceptance/contract/errorcodes_test.go +++ b/cli/acceptance/contract/errorcodes_test.go @@ -17,23 +17,22 @@ import ( // cmdutil.NewError(codeXxx, ...) and cmdutil.Wrapf(codeXxx, ...) and verifies // that codeXxx is registered in cmdutil.AllCodes(). // -// ClassifyHTTPError is dynamic — callers don't pass a literal CodeXxx +// ClassifyHTTPError is dynamic - callers don't pass a literal CodeXxx // ident. Most SDK call sites go through cmdutil.WrapHTTP(err, ...) which // the scanner skips entirely (it only inspects NewError / Wrapf selector // names). A few sites still call ClassifyHTTPError directly to inspect // or remap the code; those are call-expression args the scanner also // skips. Either way, the codes those paths can yield are bridged via // cmdutil.ClassifyHTTPErrorOutputs(), which enumerates every code the -// switch can return — added to the registered set so the AST scanner +// switch can return - added to the registered set so the AST scanner // doesn't false-positive on them. // -// Limitations (documented in spec §4.3): +// Limitations: // - Only literal cmdutil.CodeXxx idents are detected; codes assigned to // a local variable then passed are NOT scanned (rare pattern). // - cmdutil.WrapHTTP(...) and cmdutil.ClassifyHTTPError(...) call -// expressions are skipped — the ClassifyHTTPErrorOutputs bridge +// expressions are skipped - the ClassifyHTTPErrorOutputs bridge // covers their dynamic codes. -// - v0.x does not enforce a baseline diff (spec ADR-6b); v0.9 will. func TestAllReferencedCodesAreRegistered(t *testing.T) { registered := make(map[cmdutil.ErrorCode]struct{}) for _, c := range cmdutil.AllCodes() { @@ -117,7 +116,7 @@ func collectErrorCodes(fset *token.FileSet, f *ast.File, out map[cmdutil.ErrorCo } // First arg should be cmdutil.CodeXxx (SelectorExpr ident). // If it's a function call (e.g. cmdutil.ClassifyHTTPError(err)), skip - // — bridge handles those. + // - bridge handles those. arg0Sel, ok := call.Args[0].(*ast.SelectorExpr) if !ok { return true @@ -128,7 +127,7 @@ func collectErrorCodes(fset *token.FileSet, f *ast.File, out map[cmdutil.ErrorCo } code, ok := identToErrorCode(arg0Sel.Sel.Name) if !ok { - // Unknown ident name — record as bogus so the test fails with + // Unknown ident name - record as bogus so the test fails with // a clear "code referenced but not registered" message. code = cmdutil.ErrorCode("UNKNOWN_REF:" + arg0Sel.Sel.Name) } @@ -140,7 +139,7 @@ func collectErrorCodes(fset *token.FileSet, f *ast.File, out map[cmdutil.ErrorCo // identToErrorCode maps an ident name like "CodeAuthUnauthenticated" to its // underlying ErrorCode value via a simple switch. Avoids reflect. -// Keep in sync with cmdutil.AllCodes() — adding a new const here is the same +// Keep in sync with cmdutil.AllCodes() - adding a new const here is the same // bookkeeping as adding it to AllCodes(). func identToErrorCode(name string) (cmdutil.ErrorCode, bool) { switch name { diff --git a/cli/acceptance/contract/helpers_test.go b/cli/acceptance/contract/helpers_test.go index 95c37a3e..3c285295 100644 --- a/cli/acceptance/contract/helpers_test.go +++ b/cli/acceptance/contract/helpers_test.go @@ -38,13 +38,12 @@ func TestMain(m *testing.M) { var update = flag.Bool("update", false, "update golden files") // newTestFactory builds a Factory whose Client returns mockClient. -// Caller must NOT use t.Parallel() — see iostreams.SetForTest contract. +// Caller must NOT use t.Parallel() - see iostreams.SetForTest contract. // -// WEKNORA_BASE_URL is set when mockServer is non-nil. v0.0 buildClient does -// not currently honor this env var (it reads from config.Host); commands that -// need the mock URL must rely on the mockClient injection above. The env -// is set anyway as a forward-affordance for any direct net/http callers -// added in PR-7+ (e.g. doctor's PingBaseURL HEAD /health). +// WEKNORA_BASE_URL is set when mockServer is non-nil. buildClient does not +// currently honor this env var (it reads from config.Host); commands that +// need the mock URL rely on the mockClient injection above. The env is set +// anyway for any direct net/http callers (e.g. doctor's HEAD /health). func newTestFactory(t *testing.T, mockServer *httptest.Server, mockClient *sdk.Client) *cmdutil.Factory { t.Helper() t.Setenv("XDG_CONFIG_HOME", t.TempDir()) diff --git a/cli/acceptance/contract/wire_test.go b/cli/acceptance/contract/wire_test.go index 6b2332db..25933aff 100644 --- a/cli/acceptance/contract/wire_test.go +++ b/cli/acceptance/contract/wire_test.go @@ -12,7 +12,7 @@ // line on stderr. // // Cases intentionally omitted (with reason): -// - doctor.success — non-offline path emits +// - doctor.success - non-offline path emits // unstable timing // ("reachable in 2ms"). // Unit tests in cli/cmd/doctor @@ -20,12 +20,12 @@ // doctor.success_offline is // the deterministic sibling // kept here. -// - auth_login.success — requires stdin pipe +// - auth_login.success - requires stdin pipe // (--with-token) + keyring- // aware Secrets store; the // helper does not yet expose // a stdin hook. -// - auth_login.error_auth_unauthenticated — same setup as above. +// - auth_login.error_auth_unauthenticated - same setup as above. // // All cases use leaf-positioned --json (e.g. `version --json`). --json is a // per-leaf flag, not a global persistent flag. @@ -45,13 +45,13 @@ import ( ) // wireCase declares one row in the contract matrix. Optional fields: -// server — mock /api/v1/* endpoints; nil means no network. -// preConfig — seed config.yaml under the per-test XDG_CONFIG_HOME +// server - mock /api/v1/* endpoints; nil means no network. +// preConfig - seed config.yaml under the per-test XDG_CONFIG_HOME // (set by newTestFactory); use for cases like // `context use` that read local state without an // SDK round-trip. -// wantErr — non-zero exit expected. -// wantStderrSubstring — stderr must contain this substring (typically the +// wantErr - non-zero exit expected. +// wantStderrSubstring - stderr must contain this substring (typically the // typed error code, e.g. "auth.unauthenticated"). // Only meaningful when wantErr=true. type wireCase struct { @@ -66,13 +66,13 @@ type wireCase struct { // wireCases enumerates every contract scenario whose stdout is golden-pinned. // Order is illustrative, not load-bearing. var wireCases = []wireCase{ - // 1. version.success — pure local; no client touched. + // 1. version.success - pure local; no client touched. { name: "version.success", args: []string{"version", "--json"}, }, - // 2. doctor.success_offline — only credential_storage runs; the three + // 2. doctor.success_offline - only credential_storage runs; the three // network checks are skipped. Stable details + summary. { name: "doctor.success_offline", @@ -80,7 +80,7 @@ var wireCases = []wireCase{ server: doctorReachable, // ensures buildServices succeeds even if probed }, - // 3. doctor.error_network — base_url returns 500 → ping fail → cascade + // 3. doctor.error_network - base_url returns 500 → ping fail → cascade // skip on auth_credential + server_version. credential_storage still // runs (independent). Contract: any check=fail bumps summary.failed // and RunE returns SilentError → exit 1 with the data object @@ -92,7 +92,7 @@ var wireCases = []wireCase{ wantErr: true, }, - // 4-7. kb list / get — SDK paths /api/v1/knowledge-bases[/] + // 4-7. kb list / get - SDK paths /api/v1/knowledge-bases[/] { name: "kb_list.success", args: []string{"kb", "list", "--json"}, @@ -123,7 +123,7 @@ var wireCases = []wireCase{ wantStderrSubstring: "resource.not_found", }, - // 8. context use — pure local I/O against config.yaml. + // 8. context use - pure local I/O against config.yaml. { name: "context_use.success", args: []string{"context", "use", "production", "--json"}, @@ -140,9 +140,9 @@ var wireCases = []wireCase{ } }, }, - // (context_use.error_local_context_not_found dropped — see file header.) + // (context_use.error_local_context_not_found dropped - see file header.) - // 9-10. auth status — SDK /api/v1/auth/me, plus config inspection. + // 9-10. auth status - SDK /api/v1/auth/me, plus config inspection. { name: "auth_status.success", args: []string{"auth", "status", "--json"}, @@ -156,7 +156,7 @@ var wireCases = []wireCase{ wantStderrSubstring: "auth.unauthenticated", }, - // 11-13. search chunks — verb-noun shape (gh search parity), positional query, --kb required. + // 11-13. search chunks - verb-noun shape (gh search parity), positional query, --kb required. // --kb accepts either kb_ (passed through) or a name (resolved via // list); UUID-format detection happens client-side, mirroring gcloud // --project's id-or-name auto-detection. @@ -185,7 +185,7 @@ var wireCases = []wireCase{ // TestWireGolden is the matrix-runner. Cases are sequential (the // iostreams singleton swap inside helpers.runCmd is package-global; -// t.Parallel is contractually forbidden — see helpers_test.go). +// t.Parallel is contractually forbidden - see helpers_test.go). func TestWireGolden(t *testing.T) { for _, tc := range wireCases { t.Run(tc.name, func(t *testing.T) { diff --git a/cli/acceptance/doc.go b/cli/acceptance/doc.go index b9e27076..0d0d7a36 100644 --- a/cli/acceptance/doc.go +++ b/cli/acceptance/doc.go @@ -2,11 +2,9 @@ // // Package acceptance is the cli/ subtree top-level home for cross-cutting // contract / integration tests. Lives outside cli/internal/ so a future -// reviewer immediately sees "this is the contract surface — change with care". +// reviewer immediately sees "this is the contract surface - change with care". // // Sub-packages: -// contract/ — envelope JSON shape golden + error.code registry consistency -// e2e/ — real WeKnora server blackbox tests (testscript-style) -// -// Layout convention follows spec §4.5. +// contract/ - envelope JSON shape golden + error.code registry consistency +// e2e/ - real WeKnora server blackbox tests (testscript-style) package acceptance diff --git a/cli/acceptance/e2e/e2e_test.go b/cli/acceptance/e2e/e2e_test.go index 9a94ccbe..70283e5c 100644 --- a/cli/acceptance/e2e/e2e_test.go +++ b/cli/acceptance/e2e/e2e_test.go @@ -31,7 +31,7 @@ import ( // TestRAGFullLoop walks the demo MVP path: link a context, create a KB, // upload a doc, wait for indexing, search it, then chat against it. Each -// step parses the CLI's bare JSON to extract IDs for the next step — +// step parses the CLI's bare JSON to extract IDs for the next step - // validating both functional behavior and wire-contract stability. func TestRAGFullLoop(t *testing.T) { host := mustEnv(t, "WEKNORA_E2E_HOST") @@ -45,7 +45,7 @@ func TestRAGFullLoop(t *testing.T) { env := append(os.Environ(), "XDG_CONFIG_HOME="+xdg, "XDG_CACHE_HOME="+filepath.Join(xdg, "cache"), - // SDK debug off — explicit so the CI run isn't noisy. + // SDK debug off - explicit so the CI run isn't noisy. "WEKNORA_SDK_DEBUG=", ) @@ -102,7 +102,7 @@ func TestRAGFullLoop(t *testing.T) { } t.Logf("chat answer (%d chars), %d references", len(chat.Answer), len(chat.References)) if len(chat.References) == 0 { - // Soft warning — some servers may not surface references for every + // Soft warning - some servers may not surface references for every // question, but the demo flow is supposed to. t.Logf("warning: chat returned 0 references (server may have a different config)") } @@ -189,7 +189,7 @@ matching (lexical) to balance recall and precision. // waitDocReady polls `doc list` until the uploaded document's status indicates // indexing is complete. WeKnora server uses a few status values across versions -// ("ready", "completed", "ok") — accept any non-pending/non-processing/non-failed +// ("ready", "completed", "ok") - accept any non-pending/non-processing/non-failed // state so we don't break on a server-side rename. Failed status fails the test // fast. func waitDocReady(t *testing.T, bin string, env []string, kbID, docID string, timeout time.Duration) { diff --git a/cli/cmd/agent/agent.go b/cli/cmd/agent/agent.go index 7748f70c..100d3b79 100644 --- a/cli/cmd/agent/agent.go +++ b/cli/cmd/agent/agent.go @@ -1,18 +1,13 @@ // Package agentcmd holds the `weknora agent` command tree: // list / view / invoke. The directory is named `agent/` (matches cobra // noun-verb convention) but the Go package is `agentcmd` to avoid -// shadowing cli/internal/agent (which owns SetAgentHelp + agent-aware -// help rendering for AI coding agents — a distinct concept from -// WeKnora's first-class custom-agent resources). +// colliding with cobra's *cobra.Command identifier. // -// Disambiguation in cli/AGENTS.md: "agent" in this subtree refers to -// WeKnora's user-defined Custom Agents (server resource: GET/POST -// /agents/...). The CLI's `agent invoke` calls /agent-chat/:session_id -// which dispatches the agent's configured workflow (system prompt, -// allowed tools, KB scope, retrieval thresholds, etc.). This is -// orthogonal to AGENTS.md / SetAgentHelp, which exists so AI coding -// agents (Claude Code, Cursor) consuming the CLI can read structured -// hints from --help. +// "agent" in this subtree refers to WeKnora's user-defined Custom +// Agents (server resource: GET/POST /agents/...). The CLI's +// `agent invoke` calls /agent-chat/:session_id which dispatches the +// agent's configured workflow (system prompt, allowed tools, KB scope, +// retrieval thresholds). package agentcmd import ( @@ -29,12 +24,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { Short: "Manage and invoke custom agents", Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB scope into an addressable resource. List visible agents, view a single -agent's configuration, or invoke an agent against a query. - -Distinct from the per-CLI ` + "`AGENTS.md`" + ` reference: that file documents the -contract for AI coding agents (Claude Code / Cursor) running ` + "`weknora`" + ` -on a user's behalf. This subtree manages WeKnora's first-class custom-agent -resources stored on the server.`, +agent's configuration, or invoke an agent against a query.`, Args: cobra.NoArgs, Run: func(c *cobra.Command, _ []string) { _ = c.Help() }, } diff --git a/cli/cmd/agent/invoke.go b/cli/cmd/agent/invoke.go index 17cf61c5..2875e7cf 100644 --- a/cli/cmd/agent/invoke.go +++ b/cli/cmd/agent/invoke.go @@ -9,7 +9,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/format" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -18,7 +17,7 @@ import ( ) // agentInvokeFields enumerates fields surfaced for `--json` discovery on -// `agent invoke`. Matches invokeData below — the single-shot result +// `agent invoke`. Matches invokeData below - the single-shot result // object with the agent's final answer plus the trace (references, // tool events). var agentInvokeFields = []string{ @@ -36,7 +35,7 @@ type InvokeOptions struct { // InvokeService is the narrow SDK surface this command depends on. // -// CreateSession is called when --session is omitted — sessions are +// CreateSession is called when --session is omitted - sessions are // agent-agnostic at creation (verified against // internal/handler/session/handler.go CreateSession, which only persists // {title, description}). The agent ID is supplied per-request via @@ -68,7 +67,7 @@ func NewCmdInvoke(f *cmdutil.Factory) *cobra.Command { tools, KB scope, retrieval thresholds) over SSE. By default a fresh session is auto-created; pass --session to continue an existing conversation. The agent picks the model, retrieval params, and tool surface from its own -config — agent invoke is the thin shim that streams the result. +config - agent invoke is the thin shim that streams the result. Modes: TTY (default): live answer streaming + tool-trace footer @@ -94,7 +93,6 @@ Modes: cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)") cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)") cmdutil.AddJSONFlags(cmd, agentInvokeFields) - aiclient.SetAgentHelp(cmd, "Streams an agent's answer over SSE. Pass --json (or run non-TTY) to receive a single completed {answer, references, tool_events, …} JSON object instead of partial chunks. Errors: resource.not_found (unknown agent_id) / server.session_create_failed (auto-create) / local.sse_stream_aborted (mid-stream).") return cmd } @@ -167,7 +165,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti return cmdutil.WrapHTTP(streamErr, "agent-chat stream") } - // Server closed cleanly but never sent a Done event — treat as aborted + // Server closed cleanly but never sent a Done event - treat as aborted // so agents don't silently emit a truncated answer as ok=true. if !acc.Done() { return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event") @@ -204,7 +202,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti } // renderToolTrace prints a compact tool-event footer in human mode. -// Skipped when the agent emitted no tool events — silent beats an empty +// Skipped when the agent emitted no tool events - silent beats an empty // banner. func renderToolTrace(w io.Writer, events []sse.AgentToolEvent) { if len(events) == 0 { diff --git a/cli/cmd/agent/list.go b/cli/cmd/agent/list.go index aeab1cc3..5bbb609f 100644 --- a/cli/cmd/agent/list.go +++ b/cli/cmd/agent/list.go @@ -9,7 +9,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" @@ -17,7 +16,7 @@ import ( ) // agentListFields enumerates the fields surfaced for `--json` discovery -// on `agent list`. Mirrors the json tags on sdk.Agent — nested Config is +// on `agent list`. Mirrors the json tags on sdk.Agent - nested Config is // omitted because its sub-fields make filtering noisy (use `--jq` instead). var agentListFields = []string{ "id", "name", "description", "avatar", @@ -59,7 +58,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)") cmdutil.AddJSONFlags(cmd, agentListFields) - aiclient.SetAgentHelp(cmd, "Lists tenant-visible agents (built-in + custom) as a bare JSON array of Agent objects (empty `[]` when none). --limit caps the returned slice. Use `--json=id,name` to project fields, `--jq` for arbitrary reshape.") return cmd } @@ -80,7 +78,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions, if items == nil { items = []sdk.Agent{} // ensure JSON [] not null } - // Default sort: updated_at desc — most recently-edited agents surface + // Default sort: updated_at desc - most recently-edited agents surface // first. Mirrors kb list / doc list behavior. sort.Slice(items, func(i, j int) bool { return items[i].UpdatedAt.After(items[j].UpdatedAt) diff --git a/cli/cmd/agent/view.go b/cli/cmd/agent/view.go index 3c4d5214..9d225d45 100644 --- a/cli/cmd/agent/view.go +++ b/cli/cmd/agent/view.go @@ -7,7 +7,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" @@ -15,7 +14,7 @@ import ( // agentViewFields enumerates fields surfaced for `--json` discovery on // `agent view`. Filter applies to the bare Agent object. Config sub-fields -// are intentionally omitted — too granular for naked projection; use +// are intentionally omitted - too granular for naked projection; use // `--jq '.config'` to reach them. var agentViewFields = []string{ "id", "name", "description", "avatar", @@ -36,7 +35,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command { Long: `Renders the agent's metadata (id / name / description / created-by / timestamps) plus a compact config summary (mode, model, allowed tools, KB scope). Pass --json for the full Agent object including the nested config -struct — or --jq '.config' to extract just the config.`, +struct - or --jq '.config' to extract just the config.`, Example: ` weknora agent view ag_abc weknora agent view ag_abc --json | jq '.config.allowed_tools'`, Args: cobra.ExactArgs(1), @@ -53,7 +52,6 @@ struct — or --jq '.config' to extract just the config.`, }, } cmdutil.AddJSONFlags(cmd, agentViewFields) - aiclient.SetAgentHelp(cmd, "Fetches an agent by ID. Returns the full sdk.Agent (with nested config) as a bare JSON object. Errors: resource.not_found when the agent ID does not exist or is not visible to the active tenant.") return cmd } diff --git a/cli/cmd/api/api.go b/cli/cmd/api/api.go index 6f519fe7..e9abdbfa 100644 --- a/cli/cmd/api/api.go +++ b/cli/cmd/api/api.go @@ -18,14 +18,13 @@ 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/format" "github.com/Tencent/WeKnora/cli/internal/iostreams" sdk "github.com/Tencent/WeKnora/client" ) -// apiFields is intentionally a marker — api wraps arbitrary HTTP responses +// apiFields is intentionally a marker - api wraps arbitrary HTTP responses // whose schema the CLI doesn't know, so the `--json=id,name` field-filter // is a no-op here. The marker shows up in --help so users can tell. var apiFields = []string{""} @@ -74,7 +73,7 @@ Examples: } method := resolveMethod(opts) // Escape-hatch DELETE through `weknora api` is just as destructive - // as `weknora kb delete` — exit-10 protocol must apply (AGENTS.md). + // as `weknora kb delete` - exit-10 protocol must apply (cli/README.md). if method == http.MethodDelete { if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, jopts.Enabled(), "endpoint", args[0]); err != nil { return err @@ -92,7 +91,6 @@ Examples: cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)") cmdutil.AddJSONFlags(cmd, apiFields) cmd.MarkFlagsMutuallyExclusive("data", "input") - aiclient.SetAgentHelp(cmd, "Raw HTTP passthrough. Auth / tenant / request-id headers injected from the active context. --json wraps as {status, headers, body}; --json field filtering is ignored here (response shape unknown to CLI) — use --jq for reshape. DELETE triggers exit-10 confirm. Non-2xx maps to typed errors via ClassifyHTTPStatus (4xx → input.invalid_argument / auth.* / resource.not_found; 5xx → server.error). --data and --input are mutually exclusive.") return cmd } diff --git a/cli/cmd/api/api_test.go b/cli/cmd/api/api_test.go index 9cc78b56..82de0133 100644 --- a/cli/cmd/api/api_test.go +++ b/cli/cmd/api/api_test.go @@ -201,7 +201,7 @@ func TestAPI_PathWithoutSlash(t *testing.T) { // withRootHarness wraps `weknora api ...` under a synthetic root cmd that // registers the global `-y/--yes` persistent flag (mirrors addGlobalFlags in // cmd/root.go). Required because api's NewCmd doesn't register --yes itself -// — it inherits from root in production. +// - it inherits from root in production. func withRootHarness(api *cobra.Command, args ...string) *cobra.Command { root := &cobra.Command{Use: "weknora"} root.PersistentFlags().BoolP("yes", "y", false, "") @@ -260,7 +260,7 @@ func TestAPI_DELETE_WithYes_Proceeds(t *testing.T) { t.Fatalf("execute: %v", err) } if !called { - t.Error("DELETE handler not called — confirmation may have blocked") + t.Error("DELETE handler not called - confirmation may have blocked") } } diff --git a/cli/cmd/auth/auth.go b/cli/cmd/auth/auth.go index 1b7e7166..fa7275ec 100644 --- a/cli/cmd/auth/auth.go +++ b/cli/cmd/auth/auth.go @@ -21,7 +21,7 @@ const ( ) // modeFromRefs maps the per-context TokenRef / APIKeyRef presence to a -// canonical credential-mode token. Bearer wins when both are present — +// canonical credential-mode token. Bearer wins when both are present - // matches the precedence in cmdutil.buildClient. func modeFromRefs(apiKeyRef, tokenRef string) string { switch { diff --git a/cli/cmd/auth/list.go b/cli/cmd/auth/list.go index 9ece8674..d76c001d 100644 --- a/cli/cmd/auth/list.go +++ b/cli/cmd/auth/list.go @@ -7,7 +7,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/format" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -31,11 +30,12 @@ type listEntry struct { // NewCmdList builds `weknora auth list`. Per-host enumeration: render one // row per registered context, marking the active one. Reads only -// ~/.config/weknora/config.yaml — no network, no keyring touch. +// ~/.config/weknora/config.yaml - no network, no keyring touch. func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List configured authentication contexts", + Long: `Show every configured context (name, host, user, mode, current). Read-only; no network or keyring access.`, Args: cobra.NoArgs, RunE: func(c *cobra.Command, _ []string) error { jopts, err := cmdutil.CheckJSONFlags(c) @@ -46,7 +46,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { }, } cmdutil.AddJSONFlags(cmd, authListFields) - aiclient.SetAgentHelp(cmd, "Lists configured auth contexts (name/host/user/mode/current). Read-only, no network, no keyring access. Use to confirm context names before --context or `auth login --name`.") return cmd } diff --git a/cli/cmd/auth/list_test.go b/cli/cmd/auth/list_test.go index 755c7294..0763aefc 100644 --- a/cli/cmd/auth/list_test.go +++ b/cli/cmd/auth/list_test.go @@ -37,7 +37,7 @@ func TestList_HumanRender(t *testing.T) { // Mode column. assert.Contains(t, got, ModeBearer) assert.Contains(t, got, ModeAPIKey) - // Sorted alphabetically — prod after staging? No: "prod" < "staging". + // Sorted alphabetically - prod after staging? No: "prod" < "staging". assert.Less(t, strings.Index(got, "prod"), strings.Index(got, "staging"), "contexts should render sorted by name") } @@ -72,7 +72,7 @@ func TestList_JSON_BareArray(t *testing.T) { } func TestModeFromRefs(t *testing.T) { - // Hand-edited config with neither ref set — surface "unknown" rather + // Hand-edited config with neither ref set - surface "unknown" rather // than pretending the context is a valid login. assert.Equal(t, ModeUnknown, modeFromRefs("", "")) assert.Equal(t, ModeBearer, modeFromRefs("", "tok")) diff --git a/cli/cmd/auth/login.go b/cli/cmd/auth/login.go index 50ebc36a..b10b1ba3 100644 --- a/cli/cmd/auth/login.go +++ b/cli/cmd/auth/login.go @@ -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/config" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -17,7 +16,7 @@ import ( ) // authLoginFields enumerates the fields surfaced for `--json` discovery on -// `auth login`. The post-login summary has no token values — they stay in the +// `auth login`. The post-login summary has no token values - they stay in the // keyring; agents who need to verify the credential should re-run // `auth status`. var authLoginFields = []string{ @@ -97,7 +96,6 @@ the current_context in ~/.config/weknora/config.yaml.`, cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password") cmdutil.AddJSONFlags(cmd, authLoginFields) _ = cmd.MarkFlagRequired("host") - aiclient.SetAgentHelp(cmd, "Authenticates and stores credentials. --with-token reads an API key from stdin (no password prompt, agent-safe). Otherwise email/password prompts fire — non-TTY callers must pipe `--with-token` or pre-set --name. Errors: auth.bad_credential on wrong password; input.invalid_argument on bad --host; input.missing_flag when --with-token has empty stdin.") return cmd } @@ -126,7 +124,7 @@ func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOption opts.APIKey = key // Validate against the server before persisting so a typo'd / // expired / wrong-host key fails fast (gh CLI parity). The probe - // is /auth/me — read-only, side-effect-free. + // is /auth/me - read-only, side-effect-free. user, err := defaultAPIKeyValidator(ctx, opts.Host, key) if err != nil { return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key") @@ -268,7 +266,7 @@ func validateHost(host string) error { // warnOnFileFallback prints a one-shot stderr advisory when the secrets // store fell back to the plaintext 0600 file backend (keychain unavailable -// — typical on headless CI, WSL without DBus, agent containers). Helps +// - typical on headless CI, WSL without DBus, agent containers). Helps // users notice that credentials are NOT in the OS keychain before they're // surprised by it later. doctor's credential_storage check carries the // same info but agents that bypass doctor would otherwise miss it. @@ -276,7 +274,7 @@ func warnOnFileFallback(store secrets.Store) { if _, isFile := store.(*secrets.FileStore); !isFile { return } - fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable — credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.") + fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable - credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.") fmt.Fprintln(iostreams.IO.Err, " install / unlock the keyring (or use `weknora doctor` to inspect) for OS-backed storage.") } diff --git a/cli/cmd/auth/login_test.go b/cli/cmd/auth/login_test.go index 39503b4c..8a395759 100644 --- a/cli/cmd/auth/login_test.go +++ b/cli/cmd/auth/login_test.go @@ -124,7 +124,7 @@ func stubAPIKeyValidator(fn apiKeyValidator) func() { func TestRunLogin_WithToken_Empty(t *testing.T) { iostreams.SetForTest(t) f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{}) - // Validator must NOT be called when stdin is empty — verify by setting + // Validator must NOT be called when stdin is empty - verify by setting // a panic-on-call sentinel. restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) { t.Fatal("validator should not be called on empty stdin") diff --git a/cli/cmd/auth/logout.go b/cli/cmd/auth/logout.go index 7f6fc669..1c019549 100644 --- a/cli/cmd/auth/logout.go +++ b/cli/cmd/auth/logout.go @@ -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/config" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -30,7 +29,7 @@ type logoutResult struct { // NewCmdLogout builds `weknora auth logout`. Clears stored credentials // (keyring + file fallback) and removes the context entry from config.yaml. -// No server-side revocation — local-only credential clear. +// No server-side revocation - local-only credential clear. func NewCmdLogout(f *cmdutil.Factory) *cobra.Command { opts := &LogoutOptions{} cmd := &cobra.Command{ @@ -39,7 +38,7 @@ func NewCmdLogout(f *cmdutil.Factory) *cobra.Command { Long: `Clear keyring + file-fallback secrets for one context (or all of them with --all) and drop the context entry from ~/.config/weknora/config.yaml. -Note: this does NOT revoke the credential server-side — for API keys, you +Note: this does NOT revoke the credential server-side - for API keys, you must rotate them in the server UI; for JWT, the token will continue to be accepted until it expires.`, Example: ` weknora auth logout # current context @@ -58,7 +57,6 @@ accepted until it expires.`, cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context") cmdutil.AddJSONFlags(cmd, authLogoutFields) cmd.MarkFlagsMutuallyExclusive("name", "all") - aiclient.SetAgentHelp(cmd, "Clears local credentials only; the server-side token / api-key continues to be valid until expired or rotated. Returns data.removed: [...names]. Errors: auth.unauthenticated when no contexts configured.") return cmd } @@ -85,7 +83,7 @@ func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto delete(cfg.Contexts, name) } // If we removed the active context, pick a remaining one (deterministic by - // map order would be flaky — leave CurrentContext empty so the next + // map order would be flaky - leave CurrentContext empty so the next // invocation surfaces a clear "no current context" error rather than // silently switching). if _, stillExists := cfg.Contexts[cfg.CurrentContext]; !stillExists { @@ -128,7 +126,7 @@ func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error // clearContextSecrets best-effort deletes every secret slot the context // references. Errors are swallowed because a missing secret is a no-op -// (tested in keyring_test.go) — we don't want a stale ref to block logout. +// (tested in keyring_test.go) - we don't want a stale ref to block logout. func clearContextSecrets(store secrets.Store, c config.Context, name string) { if c.TokenRef != "" { _ = store.Delete(name, "access") diff --git a/cli/cmd/auth/logout_test.go b/cli/cmd/auth/logout_test.go index 97fc23d4..165f4954 100644 --- a/cli/cmd/auth/logout_test.go +++ b/cli/cmd/auth/logout_test.go @@ -14,7 +14,7 @@ import ( ) // newLogoutFactory builds a Factory whose Config closure mutates the supplied -// cfg in place — runLogout writes back via config.Save which touches disk, so +// cfg in place - runLogout writes back via config.Save which touches disk, so // tests use t.Setenv("XDG_CONFIG_HOME", t.TempDir()) at the call site to // isolate the on-disk file. func newLogoutFactory(t *testing.T, cfg *config.Config, store secrets.Store) *cmdutil.Factory { diff --git a/cli/cmd/auth/refresh.go b/cli/cmd/auth/refresh.go index f1fcbc21..eeec4662 100644 --- a/cli/cmd/auth/refresh.go +++ b/cli/cmd/auth/refresh.go @@ -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" sdk "github.com/Tencent/WeKnora/client" @@ -17,11 +16,11 @@ type RefreshOptions struct { } // authRefreshFields enumerates the fields surfaced for `--json` discovery -// on `auth refresh`. Token values are intentionally omitted — see refreshResult. +// on `auth refresh`. Token values are intentionally omitted - see refreshResult. var authRefreshFields = []string{"context"} // refreshResult is the typed payload emitted under data on success. Token -// values are intentionally NOT included — emitting them would leak secrets +// values are intentionally NOT included - emitting them would leak secrets // into stdout / agent transcripts. Agents needing to verify the new token // can re-run `weknora auth status` (live API check). type refreshResult struct { @@ -29,10 +28,10 @@ type refreshResult struct { } // NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access -// token by spending the stored refresh_token via POST /auth/refresh — +// token by spending the stored refresh_token via POST /auth/refresh - // the standard OAuth refresh-token grant. // -// API-key contexts are rejected — they have no refresh semantic; +// API-key contexts are rejected - they have no refresh semantic; // rotate the key via the server UI instead. func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command { opts := &RefreshOptions{} @@ -43,7 +42,7 @@ func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command { exchanges it for a new access + refresh token pair via POST /api/v1/auth/refresh. Both new tokens replace the existing entries in the OS keyring. -API-key contexts are rejected with input.invalid_argument — they have no +API-key contexts are rejected with input.invalid_argument - they have no refresh semantic. Rotate the key in the server UI instead.`, Example: ` weknora auth refresh # refresh the current context weknora auth refresh --name staging # refresh a specific context`, @@ -58,12 +57,11 @@ refresh semantic. Rotate the key in the server UI instead.`, } cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)") cmdutil.AddJSONFlags(cmd, authRefreshFields) - aiclient.SetAgentHelp(cmd, "Renews the access token using the stored refresh token. Errors with auth.token_expired when refresh itself is rejected — surface the hint to re-run auth login.") return cmd } // defaultRefresher constructs a fresh, unauthenticated SDK client targeting -// host — the /auth/refresh endpoint reads the refresh token from the body, +// host - the /auth/refresh endpoint reads the refresh token from the body, // so no bearer / api-key header is needed. func defaultRefresher(host string) cmdutil.Refresher { return sdk.NewClient(host) @@ -92,9 +90,9 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, jopts *cmdutil.JSONOp fmt.Sprintf("context %q has no host", name)) } if c.RefreshRef == "" { - hint := "api-key contexts can't be refreshed — rotate the key in the server UI and run `weknora auth login --with-token`" + hint := "api-key contexts can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`" if c.APIKeyRef == "" { - hint = "no refresh token stored — run `weknora auth login` to authenticate" + hint = "no refresh token stored - run `weknora auth login` to authenticate" } return &cmdutil.Error{ Code: cmdutil.CodeInputInvalidArgument, diff --git a/cli/cmd/auth/refresh_test.go b/cli/cmd/auth/refresh_test.go index 790c13c2..60051628 100644 --- a/cli/cmd/auth/refresh_test.go +++ b/cli/cmd/auth/refresh_test.go @@ -140,7 +140,7 @@ func TestRefresh_NoRefreshTokenStored(t *testing.T) { "prod": {Host: "https://kb", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"}, }, } - // MemStore is empty — RefreshRef points to a slot that doesn't exist. + // MemStore is empty - RefreshRef points to a slot that doesn't exist. f := newRefreshFactory(t, cfg, secrets.NewMemStore()) err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(&fakeRefreshService{})) require.Error(t, err) @@ -168,7 +168,7 @@ func TestRefresh_ServerRefused(t *testing.T) { assert.Contains(t, typed.Hint, "auth login") // stored access must NOT have been overwritten with empty if v, _ := store.Get("prod", "access"); v == "" { - // Was never set in this test, that's fine — main thing is no panic. + // Was never set in this test, that's fine - main thing is no panic. _ = v } } diff --git a/cli/cmd/auth/status.go b/cli/cmd/auth/status.go index 476e1b71..891dbff8 100644 --- a/cli/cmd/auth/status.go +++ b/cli/cmd/auth/status.go @@ -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" sdk "github.com/Tencent/WeKnora/client" @@ -37,7 +36,14 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "status", Short: "Show the active context, principal, and token state", - Args: cobra.NoArgs, + Long: `Live-check the active credential by calling /auth/me. Reports the user +and tenant the server resolves the credential to. + +Exits with auth.unauthenticated when the token is invalid or missing - run +` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT contexts) to recover. +For JWT contexts the SDK transparently refreshes on 401, so this command +usually only surfaces a hard auth failure.`, + Args: cobra.NoArgs, RunE: func(c *cobra.Command, args []string) error { jopts, err := cmdutil.CheckJSONFlags(c) if err != nil { @@ -51,7 +57,6 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command { }, } cmdutil.AddJSONFlags(cmd, authStatusFields) - aiclient.SetAgentHelp(cmd, "Live-checks the active credential by calling /auth/me. Returns {context, user_id, email, tenant_id, tenant_name}. Errors: auth.unauthenticated when token is invalid or missing (run `auth login` / `auth refresh`).") return cmd } diff --git a/cli/cmd/auth/status_test.go b/cli/cmd/auth/status_test.go index 0c7bd472..0524bba7 100644 --- a/cli/cmd/auth/status_test.go +++ b/cli/cmd/auth/status_test.go @@ -90,7 +90,7 @@ func TestRunStatus_SDKError_Transport(t *testing.T) { f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }} err := runStatus(context.Background(), nil, f, &fakeStatusService{err: assert.AnError}) require.Error(t, err) - // Non-HTTP errors (DNS / TCP) are transport problems, not auth problems — + // Non-HTTP errors (DNS / TCP) are transport problems, not auth problems - // classify network.error so retry logic / exit code 7 / IsTransient apply. assert.True(t, cmdutil.IsTransient(err), "expected transient/network classification, got %v", err) } diff --git a/cli/cmd/auth/token.go b/cli/cmd/auth/token.go index fd1ff082..54b32013 100644 --- a/cli/cmd/auth/token.go +++ b/cli/cmd/auth/token.go @@ -5,7 +5,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" ) @@ -27,7 +26,7 @@ type tokenResult struct { // curl -H "Authorization: Bearer $WEKNORA_TOKEN" ... # JWT mode // curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key mode // -// The user is responsible for constructing the appropriate header — +// The user is responsible for constructing the appropriate header - // `auth list` shows which mode each context uses. // // Default output: raw token on stdout, no trailing newline (clean $(...)). @@ -60,7 +59,6 @@ to see which mode each context uses, and construct the matching HTTP header: }, } cmdutil.AddJSONFlags(cmd, authTokenFields) - aiclient.SetAgentHelp(cmd, "Prints the active context's credential to stdout for scripting. Default: raw secret, no trailing newline. With --json: bare {token, mode, context} object. Errors: auth.unauthenticated when no active context or no stored credential (run `auth login`); local.keychain_denied when the keyring rejects the read.") return cmd } @@ -89,7 +87,7 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error { } // Resolve the stored credential. Prefer bearer (JWT) when both refs - // are present — JWT is the more capable mode and what `buildClient` + // are present - JWT is the more capable mode and what `buildClient` // uses for the Authorization header (see factory.go buildClient). var token, mode string switch { @@ -119,18 +117,18 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error { return jopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Context: ctxName}) } - // No trailing newline — clean $(weknora auth token) substitution. + // No trailing newline - clean $(weknora auth token) substitution. fmt.Fprint(iostreams.IO.Out, token) // Defensive hint to stderr when stdout is an interactive terminal: // the user likely didn't mean to display the secret on screen. // stderr-only so scripts (always non-TTY) are unaffected. Mode-specific // because api-key tokens are long-lived and rotation is the only - // recourse on leak — bearer tokens self-expire via refresh. + // recourse on leak - bearer tokens self-expire via refresh. if iostreams.IO.IsStdoutTTY() { fmt.Fprintln(iostreams.IO.Err) fmt.Fprintln(iostreams.IO.Err, "hint: pipe to $(weknora auth token) to capture; this terminal scrollback now contains the secret") if mode == ModeAPIKey { - fmt.Fprintln(iostreams.IO.Err, "note: api-key credentials are long-lived — rotate via your auth provider if exposed (no `auth refresh` path)") + fmt.Fprintln(iostreams.IO.Err, "note: api-key credentials are long-lived - rotate via your auth provider if exposed (no `auth refresh` path)") } } return nil diff --git a/cli/cmd/auth/token_test.go b/cli/cmd/auth/token_test.go index 5760a9b3..7e775535 100644 --- a/cli/cmd/auth/token_test.go +++ b/cli/cmd/auth/token_test.go @@ -165,7 +165,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) { }, } store := secrets.NewMemStore() - // no Set — keyring is empty + // no Set - keyring is empty iostreams.SetForTest(t) err := runToken(tokenTestFactory(t, cfg, store), nil) if err == nil { @@ -200,7 +200,7 @@ func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) { // interactive terminal, it ALSO writes a stderr advisory ("you just put the // secret in your scrollback") + a mode-specific rotation note for api-key // credentials. The stdout half must stay clean under all modes so $(...) -// substitution is unaffected — tests assert both axes. +// substitution is unaffected - tests assert both axes. func makeBearerCfg() (*config.Config, *secrets.MemStore) { cfg := &config.Config{ @@ -278,7 +278,7 @@ func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) { func TestAuthToken_TTY_JSONMode_NoStderrHint(t *testing.T) { // --json output mode targets script/agent consumers even when stdout // happens to be a TTY (e.g. an IDE running the CLI on the user's - // behalf). Hint would pollute their parsing — suppress. + // behalf). Hint would pollute their parsing - suppress. cfg, store := makeBearerCfg() _, errBuf := iostreams.SetForTestWithTTY(t) if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil { diff --git a/cli/cmd/chat/chat.go b/cli/cmd/chat/chat.go index 9dea3baf..6cb23b90 100644 --- a/cli/cmd/chat/chat.go +++ b/cli/cmd/chat/chat.go @@ -1,4 +1,4 @@ -// Package chat implements `weknora chat ` — the streaming RAG answer +// Package chat implements `weknora chat ` - the streaming RAG answer // entry point. // // Two output modes share a single SDK call: @@ -27,7 +27,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/format" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -116,7 +115,6 @@ Modes: cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)") cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)") cmdutil.AddJSONFlags(cmd, chatFields) - aiclient.SetAgentHelp(cmd, "Streams an LLM answer over SSE. Agent / non-TTY callers should pass --json so the full {answer, references, session_id, assistant_message_id} object is emitted once at completion (no partial chunks). Pass --session to thread follow-ups. Errors: server.session_create_failed when auto-create fails; local.sse_stream_aborted on mid-stream disconnect.") return cmd } @@ -161,7 +159,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut // Surface the auto-created session ID up-front so a user who hits ^C - // mid-stream still has the pointer to resume — no need to scroll back + // mid-stream still has the pointer to resume - no need to scroll back // past tokens. Skipped in JSON mode (it ends up in the data object) and // when the caller already supplied --session. if autoCreated && !jsonOut { @@ -193,7 +191,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc // Re-surface the auto-created session id on failure so a user who // missed the start-of-stream notice (it scrolls past mid-stream // tokens, especially on ^C) can still recover with --session. - // Skipped in JSON mode — the data object carries it in .session_id. + // Skipped in JSON mode - the data object carries it in .session_id. if autoCreated && !jsonOut { fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID) } @@ -212,11 +210,11 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc return cmdutil.WrapHTTP(streamErr, "knowledge qa stream") } - // SDK returned nil but we never saw a Done event — server closed the + // SDK returned nil but we never saw a Done event - server closed the // connection cleanly mid-stream. Treat as aborted so the user sees the // truncation rather than a silent partial answer. Includes the empty-body // case (Done frame never arrived AND no content): better to surface the - // abort than emit ok=true with answer="" — agents can't distinguish the + // abort than emit ok=true with answer="" - agents can't distinguish the // model genuinely had nothing to say from the stream getting cut. if !acc.Done() { return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event") @@ -227,7 +225,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc if jsonOut { // Prefer the SDK-echoed session id (acc.SessionID) but fall back to - // our local sessionID — agents must always see a usable pointer. + // our local sessionID - agents must always see a usable pointer. sid := acc.SessionID if sid == "" { sid = sessionID diff --git a/cli/cmd/context/add.go b/cli/cmd/context/add.go index e7938651..c0180cdc 100644 --- a/cli/cmd/context/add.go +++ b/cli/cmd/context/add.go @@ -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/config" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -32,7 +31,7 @@ type addResult struct { } // NewCmdAdd builds `weknora context add`. Registers a *credentialless* -// connection target — host + optional user only. Credentials for the new +// connection target - host + optional user only. Credentials for the new // context are attached separately with `weknora auth login --name `, // separating "where" the CLI talks to (the host) and "how" it authenticates // (the credential). If you want one command for both, run @@ -64,7 +63,6 @@ adds leave the current context untouched.`, cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)") cmdutil.AddJSONFlags(cmd, contextAddFields) _ = cmd.MarkFlagRequired("host") - aiclient.SetAgentHelp(cmd, "Adds a context. First context added auto-becomes current. Errors with resource.already_exists if name collides; input.invalid_argument if --host is not an absolute http(s) URL.") return cmd } diff --git a/cli/cmd/context/context.go b/cli/cmd/context/context.go index 11119965..aacef85a 100644 --- a/cli/cmd/context/context.go +++ b/cli/cmd/context/context.go @@ -3,7 +3,7 @@ // consistent with the rest of this CLI. // // Package name `contextcmd` (not `context`) to avoid shadowing stdlib context. -// The cobra Use: string is "context" — this is what users type. +// The cobra Use: string is "context" - this is what users type. package contextcmd import ( diff --git a/cli/cmd/context/list.go b/cli/cmd/context/list.go index f05827ea..76f4ef24 100644 --- a/cli/cmd/context/list.go +++ b/cli/cmd/context/list.go @@ -7,7 +7,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/config" "github.com/Tencent/WeKnora/cli/internal/format" @@ -30,7 +29,7 @@ type listEntry struct { } // NewCmdList builds `weknora context list`. Per-host enumeration with an -// active marker. Reads only config.yaml — no network, no keyring touch. +// active marker. Reads only config.yaml - no network, no keyring touch. func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "list", @@ -39,7 +38,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { active context (used by subsequent commands when --context is unset) is marked with a leading "*". No network requests are issued. -The credential mode (api-key vs password) is intentionally not shown here — +The credential mode (api-key vs password) is intentionally not shown here - run "weknora auth list" for that. "context list" is the catalog of *where* the CLI can talk to; "auth list" is the catalog of *how*.`, Args: cobra.NoArgs, @@ -52,7 +51,6 @@ the CLI can talk to; "auth list" is the catalog of *how*.`, }, } cmdutil.AddJSONFlags(cmd, contextListFields) - aiclient.SetAgentHelp(cmd, "Lists CLI contexts (name/host/user/current). Read-only, no network. Use this before context use to verify the target name exists.") return cmd } diff --git a/cli/cmd/context/remove.go b/cli/cmd/context/remove.go index 7bc2f12c..d2092b8f 100644 --- a/cli/cmd/context/remove.go +++ b/cli/cmd/context/remove.go @@ -5,7 +5,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/config" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -43,11 +42,11 @@ func NewCmdRemove(f *cmdutil.Factory) *cobra.Command { Long: `Deletes the named context from config.yaml and best-effort clears any keyring references it owned (matches ` + "`weknora auth logout`" + `). -Removing the current context also clears CurrentContext — subsequent commands +Removing the current context also clears CurrentContext - subsequent commands will error until you select another with ` + "`weknora context use `" + ` or pick one up via the global ` + "`--context`" + ` flag. Because that change is observable in every later command, removing the current context requires explicit -y/--yes -in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`, +in scripted / --json invocations (exit code 10; see cli/README.md).`, Example: ` weknora context remove staging # remove non-current → no prompt weknora context remove production -y # remove current → confirm`, Args: cobra.ExactArgs(1), @@ -65,7 +64,6 @@ in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`, }, } cmdutil.AddJSONFlags(cmd, contextRemoveFields) - aiclient.SetAgentHelp(cmd, "Removes a context entry. Removing the current context requires -y in non-TTY/--json (exit-10). Always best-effort clears keyring refs.") return cmd } @@ -81,7 +79,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto wasCurrent := name == cfg.CurrentContext jsonOut := jopts.Enabled() - // Confirmation only fires for removing the current context — non-current + // Confirmation only fires for removing the current context - non-current // remove uses the same low-friction policy as `auth logout`. if wasCurrent { if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current context", name); err != nil { @@ -105,7 +103,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto return jopts.Emit(iostreams.IO.Out, result) } if wasCurrent { - fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared — run `weknora context use ` to pick another)\n", name) + fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared - run `weknora context use ` to pick another)\n", name) } else { fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s\n", name) } @@ -114,7 +112,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto // clearContextSecrets mirrors auth/logout.go: best-effort delete every secret // slot the context references. Errors are swallowed so a missing keyring -// entry doesn't block remove (logout has had the same policy since v0.2). +// entry doesn't block remove (same policy as `auth logout`). func clearContextSecrets(store secrets.Store, c config.Context, name string) { if c.TokenRef != "" { _ = store.Delete(name, "access") diff --git a/cli/cmd/context/use.go b/cli/cmd/context/use.go index c3ada836..281b188d 100644 --- a/cli/cmd/context/use.go +++ b/cli/cmd/context/use.go @@ -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/config" "github.com/Tencent/WeKnora/cli/internal/iostreams" @@ -43,7 +42,6 @@ the global --context flag instead, which writes nothing to disk.`, }, } cmdutil.AddJSONFlags(cmd, contextUseFields) - aiclient.SetAgentHelp(cmd, "Switches default CLI context. With --json: returns {current_context, previous_context}. Errors with local.context_not_found and a did-you-mean hint when name unknown.") return cmd } @@ -82,7 +80,7 @@ func notFoundError(name string, cfg *config.Config) error { return &cmdutil.Error{ Code: cmdutil.CodeLocalContextNotFound, Message: fmt.Sprintf("context not found: %s", name), - Hint: "no contexts registered — run `weknora auth login` first", + Hint: "no contexts registered - run `weknora auth login` first", } } keys := contextKeys(cfg.Contexts) diff --git a/cli/cmd/context/use_test.go b/cli/cmd/context/use_test.go index e1159463..5155a2f6 100644 --- a/cli/cmd/context/use_test.go +++ b/cli/cmd/context/use_test.go @@ -118,12 +118,12 @@ func TestUse_CaseSensitive(t *testing.T) { }} _ = config.Save(cfg) - err := runUse("production", nil) // lowercase — must NOT match "Production" + err := runUse("production", nil) // lowercase - must NOT match "Production" if err == nil { t.Fatal("expected case-sensitive miss") } cm := err.(*cmdutil.Error) - // did-you-mean kicks in (distance 1 — "P"→"p") + // did-you-mean kicks in (distance 1 - "P"→"p") if !strings.Contains(cm.Hint, "Production") { t.Errorf("hint should suggest 'Production' (case-different), got %q", cm.Hint) } diff --git a/cli/cmd/doc/delete.go b/cli/cmd/doc/delete.go index 4500d7f3..0990ef38 100644 --- a/cli/cmd/doc/delete.go +++ b/cli/cmd/doc/delete.go @@ -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 } diff --git a/cli/cmd/doc/delete_test.go b/cli/cmd/doc/delete_test.go index a864e9d1..40fb273d 100644 --- a/cli/cmd/doc/delete_test.go +++ b/cli/cmd/doc/delete_test.go @@ -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{} diff --git a/cli/cmd/doc/doc.go b/cli/cmd/doc/doc.go index 6dc4c1e6..52b5607b 100644 --- a/cli/cmd/doc/doc.go +++ b/cli/cmd/doc/doc.go @@ -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 ( diff --git a/cli/cmd/doc/download.go b/cli/cmd/doc/download.go index dd92cde6..a6768a00 100644 --- a/cli/cmd/doc/download.go +++ b/cli/cmd/doc/download.go @@ -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 == "-" { diff --git a/cli/cmd/doc/download_test.go b/cli/cmd/doc/download_test.go index 44342f72..6a2d1f54 100644 --- a/cli/cmd/doc/download_test.go +++ b/cli/cmd/doc/download_test.go @@ -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")) diff --git a/cli/cmd/doc/list.go b/cli/cmd/doc/list.go index 17b076e7..340b86e3 100644 --- a/cli/cmd/doc/list.go +++ b/cli/cmd/doc/list.go @@ -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 { diff --git a/cli/cmd/doc/list_test.go b/cli/cmd/doc/list_test.go index 4d1ecc7a..74726830 100644 --- a/cli/cmd/doc/list_test.go +++ b/cli/cmd/doc/list_test.go @@ -161,7 +161,7 @@ func TestList_KBFlagWiredToResolveKB(t *testing.T) { } // With --kb=kb_ 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.) - diff --git a/cli/cmd/doc/upload.go b/cli/cmd/doc/upload.go index 56749f09..d4b5d760 100644 --- a/cli/cmd/doc/upload.go +++ b/cli/cmd/doc/upload.go @@ -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 { diff --git a/cli/cmd/doc/upload_recursive.go b/cli/cmd/doc/upload_recursive.go index 325db3fc..980f479c 100644 --- a/cli/cmd/doc/upload_recursive.go +++ b/cli/cmd/doc/upload_recursive.go @@ -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, diff --git a/cli/cmd/doc/upload_recursive_test.go b/cli/cmd/doc/upload_recursive_test.go index db790d96..db5f094e 100644 --- a/cli/cmd/doc/upload_recursive_test.go +++ b/cli/cmd/doc/upload_recursive_test.go @@ -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() diff --git a/cli/cmd/doc/view.go b/cli/cmd/doc/view.go index bd78a212..eacb6d75 100644 --- a/cli/cmd/doc/view.go +++ b/cli/cmd/doc/view.go @@ -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 } diff --git a/cli/cmd/doc/view_test.go b/cli/cmd/doc/view_test.go index 7165c20d..8a92125b 100644 --- a/cli/cmd/doc/view_test.go +++ b/cli/cmd/doc/view_test.go @@ -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) diff --git a/cli/cmd/doctor/doctor.go b/cli/cmd/doctor/doctor.go index e4b2a6fe..a701be6b 100644 --- a/cli/cmd/doctor/doctor.go +++ b/cli/cmd/doctor/doctor.go @@ -1,12 +1,12 @@ -// Package doctor implements `weknora doctor` — 4-item self-check (spec §1.2). +// Package doctor implements `weknora doctor` - 4-item self-check. // // Status semantics (4-tier): // -// ok — passed -// warn — soft problem; non-blocking (e.g. server minor older than CLI, +// ok - passed +// warn - soft problem; non-blocking (e.g. server minor older than CLI, // keychain unavailable so falling back to file store) -// fail — failed; "hint" actionable -// skip — cascade-skipped (prereq failed) or --offline mode +// fail - failed; "hint" actionable +// skip - cascade-skipped (prereq failed) or --offline mode // // JSON output emits the Result object directly (bare data). Exit-code // signal: @@ -28,7 +28,6 @@ import ( "github.com/spf13/cobra" - "github.com/Tencent/WeKnora/cli/internal/aiclient" "github.com/Tencent/WeKnora/cli/internal/build" "github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/compat" @@ -66,7 +65,7 @@ type Check struct { Hint string `json:"hint,omitempty"` } -// Summary is the agent-friendly short-circuit payload (spec §1.2). +// Summary is the agent-friendly short-circuit payload. // // AllPassed is true only when there are zero warn/fail/skip rows; warn does // not block exit-0 but it does flip AllPassed so agents reading just the @@ -125,7 +124,6 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache (located at $XDG_CACHE_HOME/weknora/server-info.yaml); force re-probe") cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage (credential_storage check still runs)") cmdutil.AddJSONFlags(cmd, doctorFields) - aiclient.SetAgentHelp(cmd, "Returns 4 health checks as a bare JSON object {summary, checks}. AGENT short-circuit: read summary.all_passed; if false, inspect checks[].status (ok/warn/fail/skip). exit 1 only when any status=fail; warn does not affect exit.") return cmd } @@ -133,7 +131,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { // offline-mode skip and prereq-failed skip. Returns true when the check has // been completed (Status set on c) and the caller should NOT run its body. // -// A prereq is considered "passing" if its Status is OK or Warn — warn signals +// A prereq is considered "passing" if its Status is OK or Warn - warn signals // a soft problem that does not block downstream functionality. Only fail/skip // cascades into a downstream skip. func cascade(c *Check, offline bool, prereqs ...*Check) bool { @@ -160,7 +158,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string) {Name: "credential_storage"}, } - // 1. base_url_reachable — gated by offline only. + // 1. base_url_reachable - gated by offline only. if !cascade(&checks[0], opts.Offline) { t0 := time.Now() if err := svc.PingBaseURL(ctx); err != nil { @@ -173,7 +171,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string) } } - // 2. auth_credential — needs base_url. + // 2. auth_credential - needs base_url. if !cascade(&checks[1], opts.Offline, &checks[0]) { if _, err := svc.GetCurrentUser(ctx); err != nil { checks[1].Status = StatusFail @@ -184,7 +182,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string) } } - // 3. server_version — needs auth_credential. + // 3. server_version - needs auth_credential. if !cascade(&checks[2], opts.Offline, &checks[1]) { info, fromCache, err := loadOrProbeServerInfo(ctx, opts, svc) if err != nil { @@ -195,14 +193,14 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string) } } - // 4. credential_storage — independent of network; never gated by offline. + // 4. credential_storage - independent of network; never gated by offline. fillCredentialStorageCheck(&checks[3]) return Result{Summary: summarize(checks), Checks: checks} } // fillVersionCheck applies compat.Compat to (server, cli) version pair and -// sets Status/Details/Hint on c. fromCache toggles the "cached" suffix — +// sets Status/Details/Hint on c. fromCache toggles the "cached" suffix - // the loader knows authoritatively which branch it took, time-based // derivation from ProbedAt is unreliable since SaveCache uses time.Now(). // @@ -239,8 +237,8 @@ func fillVersionCheck(c *Check, info *compat.Info, cliVer string, fromCache bool } } -// credStoreFactory is the seam tests use to inject a fake-store outcome — -// keyring success, file-store fallback, or hard failure — without touching +// credStoreFactory is the seam tests use to inject a fake-store outcome - +// keyring success, file-store fallback, or hard failure - without touching // the lazy-resolve buildServices contract (round-4 fix). Production stays // at secrets.NewBestEffortStore. var credStoreFactory = func() (secrets.Store, error) { return secrets.NewBestEffortStore() } @@ -248,7 +246,7 @@ var credStoreFactory = func() (secrets.Store, error) { return secrets.NewBestEff // SetCredStoreFactoryForTest overrides the credential-storage factory used by // runChecks and returns a cleanup function that restores the previous value. // Exported so out-of-package tests (notably cli/acceptance/contract) can -// pin the credential_storage outcome — otherwise the check probes the real +// pin the credential_storage outcome - otherwise the check probes the real // OS keyring, which is present on macOS dev machines but not on Linux CI // runners without libsecret, producing host-dependent test flakes. // @@ -269,7 +267,7 @@ func SetCredStoreFactoryForTest(fn func() (secrets.Store, error)) (restore func( // // keyring usable → StatusOK (preferred path) // file fallback → StatusWarn (keyring unavailable, secrets still persist -// with 0600 file perms — agent containers / WSL hit this) +// with 0600 file perms - agent containers / WSL hit this) // construction fails → StatusFail // // Detection of "fallback to file store" relies on the type returned by @@ -378,7 +376,7 @@ func marker(s Status) string { // server, not localhost. // // Critically: this does NOT pre-resolve f.Client(). doctor's package promise -// (top comment) is that credential_storage runs even when no auth is set up — +// (top comment) is that credential_storage runs even when no auth is set up - // e.g. first-time `weknora doctor` to diagnose setup. Pre-resolving Client // here would early-exit with auth.unauthenticated before any check runs, // contradicting the docs. Instead, GetCurrentUser / GetSystemInfo lazily @@ -443,7 +441,7 @@ func (s *realServices) GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResp // GetSystemInfo lazily resolves the SDK client (same rationale as GetCurrentUser). // In the cascade ordering, auth_credential gates server_version, so this only -// runs when auth_credential succeeded — but the lazy resolution keeps doctor +// runs when auth_credential succeeded - but the lazy resolution keeps doctor // useful when only credential_storage is checkable (e.g., user not yet logged in). func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) { cli, err := s.f.Client() diff --git a/cli/cmd/doctor/doctor_test.go b/cli/cmd/doctor/doctor_test.go index bc59ad78..7c5d3bdf 100644 --- a/cli/cmd/doctor/doctor_test.go +++ b/cli/cmd/doctor/doctor_test.go @@ -21,7 +21,7 @@ import ( // and would make CI flake on macOS vs Linux vs WSL). Restored in t.Cleanup. // // The hook intentionally lives at package scope (rather than as a runChecks -// parameter) so the production call site stays a zero-arg function — keeping +// parameter) so the production call site stays a zero-arg function - keeping // the lazy-resolve buildServices contract unchanged (round-4 fix). func withCredStoreFactory(t *testing.T, fn func() (secrets.Store, error)) { t.Helper() @@ -58,7 +58,7 @@ func TestDoctor_AllOK(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) out, _ := iostreams.SetForTest(t) // Pin credential_storage to ok so this test doesn't probe the host OS - // keyring — macOS dev machines have Keychain, Linux CI without libsecret + // keyring - macOS dev machines have Keychain, Linux CI without libsecret // would otherwise warn and break the AllPassed assertion. withCredStoreFactory(t, func() (secrets.Store, error) { return secrets.NewMemStore(), nil @@ -107,7 +107,7 @@ func TestDoctor_BaseURLFails_DownstreamSkip(t *testing.T) { if r.Checks[2].Status != StatusSkip { t.Errorf("server_version status = %q, want skip", r.Checks[2].Status) } - // credential_storage 与网络无关,应该独立运行(不受 base_url fail 影响) + // credential_storage is network-independent and runs regardless of base_url failures. if r.Checks[3].Name != "credential_storage" { t.Errorf("Checks[3] = %q, want credential_storage", r.Checks[3].Name) } @@ -245,7 +245,7 @@ func TestDoctor_NoCache_BypassesCache(t *testing.T) { func TestDoctor_VersionSkewWarns(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) _, _ = iostreams.SetForTest(t) - // Force keyring path to ok so credential_storage doesn't itself warn — + // Force keyring path to ok so credential_storage doesn't itself warn - // we want this test to assert ONLY on server_version. withCredStoreFactory(t, func() (secrets.Store, error) { return secrets.NewMemStore(), nil }) @@ -262,7 +262,7 @@ func TestDoctor_VersionSkewWarns(t *testing.T) { if v.Status != StatusWarn { t.Errorf("server_version status = %q, want warn (server older than CLI)", v.Status) } - // compat.Compat hint contains "server is older" — that's the load-bearing + // compat.Compat hint contains "server is older" - that's the load-bearing // substring agents may pattern-match. Not asserting full message text // since compat.Compat owns the wording. if !strings.Contains(v.Details, "older") { @@ -318,7 +318,7 @@ func TestDoctor_HardErrorStillFails(t *testing.T) { // TestDoctor_KeychainFallbackWarns covers credential_storage's third // state: keyring unavailable, fell back to FileStore (agent containers, -// headless CI, WSL without DBus). The check should warn — secrets still +// headless CI, WSL without DBus). The check should warn - secrets still // persist (0600 file perms) but the OS-backed path was unreachable. func TestDoctor_KeychainFallbackWarns(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) @@ -355,7 +355,7 @@ func TestDoctor_KeychainFallbackWarns(t *testing.T) { } // TestDoctor_CredStoreFactoryError surfaces the constructor failure path as -// fail (not warn) — distinguishes "cannot persist credentials at all" from +// fail (not warn) - distinguishes "cannot persist credentials at all" from // "downgraded to file store". func TestDoctor_CredStoreFactoryError(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) @@ -487,7 +487,7 @@ func TestDoctor_RunE_FailReturnsSilentError(t *testing.T) { } } -// TestDoctor_RunE_WarnReturnsNil — soft skew path stays exit-0. Pairs with +// TestDoctor_RunE_WarnReturnsNil - soft skew path stays exit-0. Pairs with // TestDoctor_RunE_FailReturnsSilentError: warn does NOT trigger SilentError. func TestDoctor_RunE_WarnReturnsNil(t *testing.T) { t.Setenv("XDG_CACHE_HOME", t.TempDir()) diff --git a/cli/cmd/kb/create.go b/cli/cmd/kb/create.go index b7d4cc15..0659d43c 100644 --- a/cli/cmd/kb/create.go +++ b/cli/cmd/kb/create.go @@ -7,7 +7,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" @@ -15,7 +14,7 @@ import ( // kbCreateFields enumerates the fields surfaced for `--json` discovery on // `kb create`. The result is the full KnowledgeBase struct; these mirror its -// top-level json tags. Nested config objects are intentionally omitted — +// top-level json tags. Nested config objects are intentionally omitted - // users wanting them can drop --json (no filter) or use --jq. var kbCreateFields = []string{ "id", "name", "type", "description", @@ -33,7 +32,7 @@ type CreateOptions struct { } // CreateService is the narrow SDK surface this command depends on. -// *sdk.Client satisfies it via duck typing (ADR-4). +// *sdk.Client satisfies it via duck typing. type CreateService interface { CreateKnowledgeBase(ctx context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error) } @@ -62,7 +61,6 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)") cmdutil.AddJSONFlags(cmd, kbCreateFields) _ = cmd.MarkFlagRequired("name") - aiclient.SetAgentHelp(cmd, "Creates a knowledge base under the active context. --name is required; --description and --embedding-model are optional. Returns the full KnowledgeBase object including the new id.") return cmd } diff --git a/cli/cmd/kb/delete.go b/cli/cmd/kb/delete.go index 3035b6ed..d439c79b 100644 --- a/cli/cmd/kb/delete.go +++ b/cli/cmd/kb/delete.go @@ -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" @@ -47,7 +46,7 @@ Pass -y/--yes (global flag) to skip the prompt (required in agent / CI / piped c AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10 and writes input.confirmation_required to stderr. NEVER auto-pass -y -without the user's explicit go-ahead — the exit-10 protocol exists +without the user's explicit go-ahead - the exit-10 protocol exists exactly to guard against unintended deletes.`, Example: ` weknora kb delete kb_abc # interactive confirm weknora kb delete kb_abc -y # no prompt @@ -67,7 +66,6 @@ exactly to guard against unintended deletes.`, }, } cmdutil.AddJSONFlags(cmd, kbDeleteFields) - aiclient.SetAgentHelp(cmd, "Destructively deletes a knowledge base by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.") return cmd } diff --git a/cli/cmd/kb/delete_test.go b/cli/cmd/kb/delete_test.go index aa08b1e8..60f41926 100644 --- a/cli/cmd/kb/delete_test.go +++ b/cli/cmd/kb/delete_test.go @@ -55,8 +55,8 @@ func TestDelete_NotFound(t *testing.T) { } func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) { - // SetForTest uses bytes.Buffer for Out — IsStdoutTTY() = false. Without - // -y/--yes, exit-10 protocol fires (see AGENTS.md): the CLI must NOT + // SetForTest uses bytes.Buffer for Out - IsStdoutTTY() = false. Without + // -y/--yes, exit-10 protocol fires (see cli/README.md): the CLI must NOT // silently proceed in scripted contexts. iostreams.SetForTest(t) svc := &fakeDeleteSvc{} @@ -86,7 +86,7 @@ func TestDelete_JSONOutput(t *testing.T) { } // The remaining tests cover the interactive confirm path which only fires -// under IsStdoutTTY() && !JSONOut — exercised via SetForTestWithTTY. +// under IsStdoutTTY() && !JSONOut - exercised via SetForTestWithTTY. func TestDelete_ConfirmYes(t *testing.T) { _, _ = iostreams.SetForTestWithTTY(t) diff --git a/cli/cmd/kb/edit.go b/cli/cmd/kb/edit.go index 70bc58bf..b5faf80f 100644 --- a/cli/cmd/kb/edit.go +++ b/cli/cmd/kb/edit.go @@ -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" sdk "github.com/Tencent/WeKnora/client" @@ -26,7 +25,7 @@ var kbEditFields = []string{ type EditOptions struct { // Name/Description are *string so we can distinguish "unset" from "set to - // empty". An unset field is omitted from the SDK request — only fields the + // empty". An unset field is omitted from the SDK request - only fields the // user passed are sent. Server PUT semantics are "replace everything in the // request"; if we always sent both, an `--name` invocation would silently // clear the description. @@ -52,7 +51,10 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "edit ", Short: "Edit a knowledge base's name or description", - Args: cobra.ExactArgs(1), + Long: `Update a knowledge base's name and/or description. At least one of +--name / --description must be supplied; fields you omit are preserved +server-side.`, + Args: cobra.ExactArgs(1), RunE: func(c *cobra.Command, args []string) error { jopts, err := cmdutil.CheckJSONFlags(c) if err != nil { @@ -74,7 +76,6 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command { cmd.Flags().StringVar(&name, "name", "", "New name (omit to leave unchanged)") cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)") cmdutil.AddJSONFlags(cmd, kbEditFields) - aiclient.SetAgentHelp(cmd, "Edits a knowledge base. At least one of --name/--description is required. Fields not passed are preserved server-side. Returns the updated KnowledgeBase.") return cmd } diff --git a/cli/cmd/kb/edit_test.go b/cli/cmd/kb/edit_test.go index 9ec861a3..653379b0 100644 --- a/cli/cmd/kb/edit_test.go +++ b/cli/cmd/kb/edit_test.go @@ -104,7 +104,7 @@ func TestEdit_BothFlags(t *testing.T) { func TestEdit_NotFound(t *testing.T) { _, _ = iostreams.SetForTest(t) // 404 must come from the GetKnowledgeBase pre-fetch in the fetch-then- - // update flow — that's the first server roundtrip when the id is bad. + // update flow - that's the first server roundtrip when the id is bad. svc := &fakeEditSvc{currentErr: errors.New("HTTP error 404: not found")} opts := &EditOptions{} opts.Name = stringPtr("x") diff --git a/cli/cmd/kb/empty.go b/cli/cmd/kb/empty.go index 34d508d1..dbad63bd 100644 --- a/cli/cmd/kb/empty.go +++ b/cli/cmd/kb/empty.go @@ -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" @@ -63,7 +62,6 @@ piped contexts. Without -y the CLI exits 10 in non-interactive mode.`, }, } cmdutil.AddJSONFlags(cmd, kbEmptyFields) - aiclient.SetAgentHelp(cmd, "Destructively empties a knowledge base (deletes all documents, preserves the KB record + config). ALWAYS pass -y/--yes in agent mode (non-TTY ⇒ confirm fails). Returns data: {id, deleted_count}. Async — items may still be processing server-side after the call returns.") return cmd } diff --git a/cli/cmd/kb/list.go b/cli/cmd/kb/list.go index b07167ee..03073f9c 100644 --- a/cli/cmd/kb/list.go +++ b/cli/cmd/kb/list.go @@ -9,7 +9,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" @@ -18,7 +17,7 @@ import ( // kbListFields enumerates the fields surfaced for `--json` discovery on // `kb list`. Nested config structs (chunking / image / FAQ / VLM / storage -// / extract) are intentionally omitted — users wanting those can use `--jq` +// / extract) are intentionally omitted - users wanting those can use `--jq` // against the full object. var kbListFields = []string{ "id", "name", "type", "description", @@ -49,6 +48,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List knowledge bases visible to the active context", + Long: `List knowledge bases visible to the active context, sorted by most recently updated. Pass --pinned to restrict to pinned KBs.`, Args: cobra.NoArgs, RunE: func(c *cobra.Command, _ []string) error { jopts, err := cmdutil.CheckJSONFlags(c) @@ -65,7 +65,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd.Flags().BoolVar(&opts.Pinned, "pinned", false, "Only show pinned knowledge bases") cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)") cmdutil.AddJSONFlags(cmd, kbListFields) - aiclient.SetAgentHelp(cmd, "Lists all knowledge bases as a bare JSON array of {id, name, ...} objects (empty `[]` when none). --pinned restricts to pinned KBs (client-side filter). --limit caps the returned slice. Use `--json` (bare) for full objects, `--json=id,name` to project fields, or `--jq` for arbitrary reshape.") return cmd } @@ -92,7 +91,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions, } items = filtered } - // Spec §1.2: default sort by updated_at desc. Server return order is not + // Default sort by updated_at desc. Server return order is not // guaranteed, so client-side sort makes output deterministic regardless // of backend storage choices. sort.Slice(items, func(i, j int) bool { diff --git a/cli/cmd/kb/pin.go b/cli/cmd/kb/pin.go index 2fc8be07..f6eea525 100644 --- a/cli/cmd/kb/pin.go +++ b/cli/cmd/kb/pin.go @@ -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" sdk "github.com/Tencent/WeKnora/client" @@ -20,7 +19,7 @@ var kbPinFields = []string{"id", "is_pinned"} type PinOptions struct{} // PinService is the narrow SDK surface this command depends on. The CLI -// reads current state before toggling so `pin`/`unpin` are idempotent — +// reads current state before toggling so `pin`/`unpin` are idempotent - // the server endpoint is only a non-idempotent toggle. type PinService interface { GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error) @@ -42,6 +41,7 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C cmd := &cobra.Command{ Use: use + " ", Short: short, + Long: short + ". Idempotent: reads the current pin state and toggles only if different, so re-running on a KB already in the target state is a no-op.", Args: cobra.ExactArgs(1), RunE: func(c *cobra.Command, args []string) error { jopts, err := cmdutil.CheckJSONFlags(c) @@ -56,7 +56,6 @@ func newPinCmd(f *cmdutil.Factory, use string, want bool, short string) *cobra.C }, } cmdutil.AddJSONFlags(cmd, kbPinFields) - aiclient.SetAgentHelp(cmd, fmt.Sprintf("Idempotent %s: reads current pin state, toggles only if different. No-op when already in the requested state.", use)) return cmd } diff --git a/cli/cmd/kb/view.go b/cli/cmd/kb/view.go index f29e37c1..81d54fc2 100644 --- a/cli/cmd/kb/view.go +++ b/cli/cmd/kb/view.go @@ -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" @@ -38,6 +37,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "view ", Short: "Show a knowledge base by ID", + Long: `Fetch a knowledge base's full configuration: chunking settings, embedding / summary model IDs, knowledge_count, chunk_count.`, Args: cobra.ExactArgs(1), RunE: func(c *cobra.Command, args []string) error { jopts, err := cmdutil.CheckJSONFlags(c) @@ -52,7 +52,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command { }, } cmdutil.AddJSONFlags(cmd, kbViewFields) - aiclient.SetAgentHelp(cmd, "Returns details of one knowledge base by ID (config + counts).") return cmd } diff --git a/cli/cmd/link/link.go b/cli/cmd/link/link.go index 1aa64e8c..c02f8abd 100644 --- a/cli/cmd/link/link.go +++ b/cli/cmd/link/link.go @@ -1,4 +1,4 @@ -// Package linkcmd implements `weknora link` — binds the current working +// Package linkcmd implements `weknora link` - binds the current working // directory to a knowledge base by writing .weknora/project.yaml. Always // overwrites an existing link silently rather than refusing when one is // already present. The cobra Long: text covers the user-facing modes @@ -14,7 +14,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/projectlink" @@ -49,7 +48,7 @@ overridden by the --kb flag or WEKNORA_KB_ID env var. Pass --kb for non-interactive use (scripts, CI). Run on a TTY without --kb to be prompted from the list of available KBs. Always overwrites -any existing link — re-run to switch. +any existing link - re-run to switch. AI agents: link writes to the user's working directory. Only run it when the user explicitly asked to bind this directory; don't run it as a side effect.`, @@ -67,7 +66,6 @@ user explicitly asked to bind this directory; don't run it as a side effect.`, } cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name; omit on a TTY for interactive prompt") cmdutil.AddJSONFlags(cmd, linkFields) - aiclient.SetAgentHelp(cmd, "Writes .weknora/project.yaml binding cwd to a KB. Pass --kb (id or name) for non-interactive use. Always overwrites.") return cmd } @@ -115,7 +113,7 @@ func runLink(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, f * } // resolveContext picks the auth context to record in the link. There is no -// per-invocation override flag on `weknora link` itself — to record under a +// per-invocation override flag on `weknora link` itself - to record under a // different context, use the global persistent flag (`weknora --context // staging link --kb my-kb`); the active context at link time is what gets // written. diff --git a/cli/cmd/link/unlink.go b/cli/cmd/link/unlink.go index d6927295..e092a276 100644 --- a/cli/cmd/link/unlink.go +++ b/cli/cmd/link/unlink.go @@ -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/projectlink" @@ -49,7 +48,6 @@ is present anywhere in the parent chain.`, }, } cmdutil.AddJSONFlags(cmd, unlinkFields) - aiclient.SetAgentHelp(cmd, "Removes .weknora/project.yaml (the cwd → KB binding). Walks up from cwd. Errors with input.invalid_argument when no link is present in the parent chain.") return cmd } diff --git a/cli/cmd/mcp/mcp.go b/cli/cmd/mcp/mcp.go index a2ec1ea9..313b57a5 100644 --- a/cli/cmd/mcp/mcp.go +++ b/cli/cmd/mcp/mcp.go @@ -29,7 +29,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { 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 +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() }, diff --git a/cli/cmd/mcp/serve.go b/cli/cmd/mcp/serve.go index eb57bfbf..22844db5 100644 --- a/cli/cmd/mcp/serve.go +++ b/cli/cmd/mcp/serve.go @@ -3,13 +3,12 @@ package mcpcmd import ( "github.com/spf13/cobra" - "github.com/Tencent/WeKnora/cli/internal/aiclient" "github.com/Tencent/WeKnora/cli/internal/cmdutil" mcpserver "github.com/Tencent/WeKnora/cli/internal/mcp" ) // NewCmdServe builds `weknora mcp serve`. Currently stdio-only; HTTP -// (streamable / SSE) is roadmap 5-7. +// (streamable / SSE) transports may be added later. func NewCmdServe(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "serve", @@ -18,19 +17,24 @@ func NewCmdServe(f *cmdutil.Factory) *cobra.Command { stderr; the data channel is reserved for protocol traffic. Authentication is inherited from the active context (or --context). The -server eagerly resolves the SDK client at startup — if no context is +server eagerly resolves the SDK client at startup - if no context is configured, the process exits with auth.unauthenticated before any MCP handshake. This way an IDE-side agent sees a clear failure mode rather than a server that handshakes successfully then errors on every tool. -To use with Claude Code, add to ~/.claude/mcp_servers.json: +To register with your MCP client (Claude Desktop / Code / Cursor / etc.), +add an entry pointing at this binary under "mcpServers": { - "weknora": { - "command": "weknora", - "args": ["mcp", "serve"] + "mcpServers": { + "weknora": { + "command": "weknora", + "args": ["mcp", "serve"] + } } - }`, + } + +Consult your MCP client's documentation for the exact config-file location.`, Args: cobra.NoArgs, RunE: func(c *cobra.Command, _ []string) error { // Eagerly construct the SDK client. Surfaces auth / @@ -42,6 +46,5 @@ To use with Claude Code, add to ~/.claude/mcp_servers.json: return mcpserver.RunStdio(c.Context(), cli) }, } - aiclient.SetAgentHelp(cmd, "Long-lived stdio MCP server. stdin/stdout for JSON-RPC, stderr for logs. Exposes 9 read-only tools; destructive verbs intentionally excluded. Auth inherited from active context — exit and relaunch with --context to switch. chat / agent_invoke accumulate server-side and return a single result (MCP spec has no streaming-content extension).") return cmd } diff --git a/cli/cmd/root.go b/cli/cmd/root.go index 7c67b6e6..31ddbd49 100644 --- a/cli/cmd/root.go +++ b/cli/cmd/root.go @@ -19,7 +19,6 @@ import ( mcpcmd "github.com/Tencent/WeKnora/cli/cmd/mcp" "github.com/Tencent/WeKnora/cli/cmd/search" sessioncmd "github.com/Tencent/WeKnora/cli/cmd/session" - "github.com/Tencent/WeKnora/cli/internal/aiclient" "github.com/Tencent/WeKnora/cli/internal/build" "github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/format" @@ -35,8 +34,9 @@ func Execute() int { // downstream `--json | jq` pipelines never filter error shapes // out of the success stream. The typed exit code (3/4/5/6/7/10) // carries the error class. - cmdutil.PrintError(iostreams.IO.Err, MapCobraError(err)) - return cmdutil.ExitCode(MapCobraError(err)) + mapped := MapCobraError(err) + cmdutil.PrintError(iostreams.IO.Err, mapped) + return cmdutil.ExitCode(mapped) } return 0 } @@ -70,7 +70,7 @@ func MapCobraError(err error) error { var cobraFlagErrorPrefixes = []string{ "unknown command ", "required flag(s)", - "accepts ", // ExactArgs / RangeArgs / etc. — `accepts N arg(s), received M` + "accepts ", // ExactArgs / RangeArgs / etc. - `accepts N arg(s), received M` "requires at least", // MinimumNArgs "requires at most", // MaximumNArgs "unknown flag", @@ -84,7 +84,7 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command { v, commit, date := build.Info() cmd := &cobra.Command{ Use: "weknora", - Short: "WeKnora CLI — RAG knowledge base from your terminal", + Short: "WeKnora CLI - RAG knowledge base from your terminal", Long: `WeKnora CLI lets you authenticate, browse knowledge bases, and run hybrid searches against a WeKnora server from your shell or an AI agent.`, Example: ` weknora auth login --host=https://kb.example.com # one-time setup @@ -101,7 +101,7 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`, Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date), PersistentPreRun: func(c *cobra.Command, args []string) { // Propagate the global --context flag into the Factory for this - // invocation only. Spec §1.2: single-shot override, no disk write. + // invocation only - single-shot override, no disk write. if v, _ := c.Flags().GetString("context"); v != "" { f.ContextOverride = v } @@ -110,7 +110,6 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`, // Match `weknora version` line format so both forms output the same. cmd.SetVersionTemplate("weknora {{.Version}}\n") addGlobalFlags(cmd) - cmd.SetHelpFunc(agentAwareHelpFunc(cmd.HelpFunc())) // Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps // them to exit 2. "unknown command" errors are detected by message prefix // in Execute() since cobra emits them as plain errors. @@ -136,7 +135,7 @@ hybrid searches against a WeKnora server from your shell or an AI agent.`, } // addGlobalFlags registers persistent flags available on every subcommand. -// Only flags whose behavior is actually wired are listed — a flag that +// Only flags whose behavior is actually wired are listed - a flag that // accepts values but does nothing is a worse contract than no flag. func addGlobalFlags(cmd *cobra.Command) { pf := cmd.PersistentFlags() @@ -144,27 +143,6 @@ func addGlobalFlags(cmd *cobra.Command) { pf.String("context", "", "Override the active context for this invocation (no disk write)") } -// agentAwareHelpFunc wraps cobra's default help to append the AI agent -// guidance (Annotations[aiclient.AIAgentHelpKey]) only when an AI coding -// agent env var is detected (CLAUDECODE / CURSOR_AGENT). Help-only -// render — no behavior switch. -func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command, []string) { - return func(c *cobra.Command, args []string) { - orig(c, args) - if aiclient.DetectAIAgent() == "" { - return - } - extra := aiclient.FormatAgentGuidance(c) - if extra == "" { - return - } - w := c.OutOrStdout() - fmt.Fprintln(w) - fmt.Fprintln(w, "AI Agent guidance:") - fmt.Fprintln(w, " "+extra) - } -} - // versionFields enumerates the fields surfaced for `--json` discovery on // `version`. Mirrors the version object payload. var versionFields = []string{"version", "commit", "date"} diff --git a/cli/cmd/root_test.go b/cli/cmd/root_test.go index cb58582e..0c2462a9 100644 --- a/cli/cmd/root_test.go +++ b/cli/cmd/root_test.go @@ -63,7 +63,7 @@ func TestMapCobraError_PinnedPrefixes(t *testing.T) { }) t.Run("required flag(s)", func(t *testing.T) { - // Self-contained probe — the pin must hold even before resource commands + // Self-contained probe - the pin must hold even before resource commands // register their own required flags. RunE is required: without it cobra // treats the command as a parent and skips ValidateRequiredFlags. probe := &cobra.Command{Use: "probe", RunE: func(*cobra.Command, []string) error { return nil }} @@ -77,7 +77,7 @@ func TestMapCobraError_PinnedPrefixes(t *testing.T) { "cobra required-flag prefix changed; update cobraFlagErrorPrefixes. got: %q", err.Error()) }) - t.Run("accepts N arg(s) — ExactArgs", func(t *testing.T) { + t.Run("accepts N arg(s) - ExactArgs", func(t *testing.T) { probe := &cobra.Command{ Use: "probe", Args: cobra.ExactArgs(1), @@ -115,7 +115,7 @@ func TestMapCobraError(t *testing.T) { // TestRoot_ContextFlagPropagation guards the cobra → Factory wiring of the // global --context flag. Without this, a future refactor that disconnects -// PersistentPreRun from f.ContextOverride would only fail e2e — the +// PersistentPreRun from f.ContextOverride would only fail e2e - the // per-package TestFactory_ContextOverride only proves the Factory side. func TestRoot_ContextFlagPropagation(t *testing.T) { cases := []struct { diff --git a/cli/cmd/search/chunks.go b/cli/cmd/search/chunks.go index 9b465fa0..7db58807 100644 --- a/cli/cmd/search/chunks.go +++ b/cli/cmd/search/chunks.go @@ -7,7 +7,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" @@ -44,7 +43,7 @@ type ChunksService interface { // Uses a positional query argument with the KB selected via flag. // // The `--kb` flag accepts either a KB UUID (passed through unchanged) or a -// name (resolved via ListKnowledgeBases — see cmdutil.ResolveKBFlag). +// name (resolved via ListKnowledgeBases - see cmdutil.ResolveKBFlag). func NewCmdChunks(f *cmdutil.Factory) *cobra.Command { opts := &ChunksOptions{} cmd := &cobra.Command{ @@ -53,6 +52,9 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command { Example: ` weknora search chunks "what is RAG?" --kb engineering weknora search chunks "embedding model" --kb kb_abc --limit 20 weknora search chunks "k8s" --kb engineering --no-keyword # vector-only`, + Long: `Hybrid (vector + keyword) retrieval against the knowledge base. Pass +--no-vector or --no-keyword to disable one channel; you cannot disable both. +--limit caps the returned slice client-side.`, Args: cobra.ExactArgs(1), RunE: func(c *cobra.Command, args []string) error { opts.Query = strings.TrimSpace(args[0]) @@ -80,7 +82,6 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command { } bindChunksFlags(cmd, opts) _ = cmd.MarkFlagRequired("kb") - aiclient.SetAgentHelp(cmd, "Hybrid retrieval; returns ranked chunk list. The server may include parent/nearby/relation chunks beyond match_count; --limit caps the returned slice client-side. Pass --no-vector or --no-keyword to disable a channel (mutually exclusive both-off).") return cmd } @@ -88,7 +89,7 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command { // the constructor readable; --kb is marked required by the caller. func bindChunksFlags(cmd *cobra.Command, opts *ChunksOptions) { cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name") - 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().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") cmd.Flags().BoolVar(&opts.NoVector, "no-vector", false, "Disable the vector channel") @@ -129,7 +130,7 @@ func runChunks(ctx context.Context, opts *ChunksOptions, jopts *cmdutil.JSONOpti if err != nil { return cmdutil.WrapHTTP(err, "hybrid search") } - // match_count is the server's *primary-match* cap — after that, the + // match_count is the server's *primary-match* cap - after that, the // service appends parent / nearby / relation chunks as context // enrichment, so the wire response can exceed Limit. Treat --limit as // a hard return-count cap by trimming on the client. Recall isn't @@ -148,7 +149,7 @@ func runChunks(ctx context.Context, opts *ChunksOptions, jopts *cmdutil.JSONOpti return renderChunkResults(results, opts.KBID) } -// renderChunkResults prints a compact pretty list. Minimal stopgap — a +// renderChunkResults prints a compact pretty list. Minimal stopgap - a // richer tabular renderer can replace this later without breaking the // JSON contract. func renderChunkResults(results []*sdk.SearchResult, kbID string) error { diff --git a/cli/cmd/search/chunks_test.go b/cli/cmd/search/chunks_test.go index 026a1db7..2a2701ab 100644 --- a/cli/cmd/search/chunks_test.go +++ b/cli/cmd/search/chunks_test.go @@ -46,7 +46,7 @@ func TestRunSearch_HumanOutput(t *testing.T) { // JSON output must surface match_type so machine consumers / agents can // reason about retrieval channels without re-implementing the wire format. -// (Human renderer keeps default minimal — diagnostic info opt-in via --json.) +// (Human renderer keeps default minimal - diagnostic info opt-in via --json.) func TestRunSearch_JSONIncludesMatchType(t *testing.T) { out, _ := iostreams.SetForTest(t) svc := &fakeChunksSvc{results: []*sdk.SearchResult{ diff --git a/cli/cmd/search/docs.go b/cli/cmd/search/docs.go index fbcbe50a..fff14865 100644 --- a/cli/cmd/search/docs.go +++ b/cli/cmd/search/docs.go @@ -9,7 +9,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" @@ -54,6 +53,9 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: `docs ""`, Short: "Find documents in a knowledge base by name (client-side substring match)", + Long: `Pages through the KB's documents and surfaces every entry whose title or +filename contains the query (case-insensitive). Useful for finding a +specific upload to download or delete by id.`, Example: ` weknora search docs "Q3 forecast" --kb finance weknora search docs "spec" --kb engineering --limit 5`, Args: cobra.ExactArgs(1), @@ -85,7 +87,6 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command { cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return") cmdutil.AddJSONFlags(cmd, docsFields) _ = cmd.MarkFlagRequired("kb") - aiclient.SetAgentHelp(cmd, "Lists documents in --kb whose title or file_name contains the query. Pages through the KB sequentially; stops once limit hits found. Returns the full Knowledge object so agents can derive id / file_size / processed_at without a second call.") return cmd } diff --git a/cli/cmd/search/kb.go b/cli/cmd/search/kb.go index 3a327db4..b2a9ad1b 100644 --- a/cli/cmd/search/kb.go +++ b/cli/cmd/search/kb.go @@ -9,7 +9,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" @@ -39,7 +38,7 @@ type KBSearchService interface { ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error) } -// NewCmdKB builds `weknora search kb ""` — substring + case-insensitive +// NewCmdKB builds `weknora search kb ""` - substring + case-insensitive // match across KB names and descriptions visible to the active context. // Results are sorted by name length (shortest first; usually the closest // hit) for deterministic output. @@ -48,6 +47,12 @@ func NewCmdKB(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: `kb ""`, Short: "Find knowledge bases by name or description (client-side substring match)", + Long: `Substring + case-insensitive match across KB names and descriptions visible +to the active context. Results are sorted by name length (shortest first; +usually the closest hit) for deterministic output. + +This is name-discovery only - for searching *inside* a knowledge base's +content, use ` + "`weknora search chunks`" + `.`, Example: ` weknora search kb "marketing" weknora search kb "team" --limit 5 --json`, Args: cobra.ExactArgs(1), @@ -72,7 +77,6 @@ func NewCmdKB(f *cmdutil.Factory) *cobra.Command { } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return") cmdutil.AddJSONFlags(cmd, kbSearchFields) - aiclient.SetAgentHelp(cmd, "Lists KBs whose name or description contains the query (case-insensitive). Useful to discover --kb identifiers before running search chunks / doc list.") return cmd } diff --git a/cli/cmd/search/search.go b/cli/cmd/search/search.go index a9f02a5b..0be79af0 100644 --- a/cli/cmd/search/search.go +++ b/cli/cmd/search/search.go @@ -5,12 +5,11 @@ package search import ( "github.com/spf13/cobra" - "github.com/Tencent/WeKnora/cli/internal/aiclient" "github.com/Tencent/WeKnora/cli/internal/cmdutil" ) // NewCmdSearch builds the `weknora search` parent. Pure dispatcher to the -// four subcommands — users must pick a verb (chunks / kb / docs / sessions). +// four subcommands - users must pick a verb (chunks / kb / docs / sessions). func NewCmdSearch(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "search", @@ -28,7 +27,6 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command { Args: cobra.NoArgs, Run: func(c *cobra.Command, _ []string) { _ = c.Help() }, } - aiclient.SetAgentHelp(cmd, "Search parent. Use `search chunks/kb/docs/sessions ` — there is no bare-positional form.") cmd.AddCommand(NewCmdChunks(f)) cmd.AddCommand(NewCmdKB(f)) diff --git a/cli/cmd/search/search_test.go b/cli/cmd/search/search_test.go index 6d9020c1..ca7d80b8 100644 --- a/cli/cmd/search/search_test.go +++ b/cli/cmd/search/search_test.go @@ -20,9 +20,8 @@ func TestSearch_NoArgs_ShowsHelp(t *testing.T) { require.NoError(t, cmd.Execute()) } -// TestSearch_RejectsPositional: bare positional (e.g. the v0.0-style -// `weknora search "" --kb X`) must error — the legacy alias was -// dropped, search is now pure dispatcher. +// TestSearch_RejectsPositional: bare positional `weknora search "" --kb X` +// must error - search is a pure dispatcher with no shortcut form. func TestSearch_RejectsPositional(t *testing.T) { _, _ = iostreams.SetForTest(t) cmd := NewCmdSearch(&cmdutil.Factory{}) diff --git a/cli/cmd/search/sessions.go b/cli/cmd/search/sessions.go index ca5accf0..b5df648a 100644 --- a/cli/cmd/search/sessions.go +++ b/cli/cmd/search/sessions.go @@ -9,7 +9,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" @@ -67,7 +66,6 @@ func NewCmdSessions(f *cmdutil.Factory) *cobra.Command { } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return") cmdutil.AddJSONFlags(cmd, sessionsSearchFields) - aiclient.SetAgentHelp(cmd, "Lists chat sessions whose title or description contains the query. Pages through the tenant sequentially; stops once limit matches found. Returns full Session objects so agents can pivot to session view/delete by id.") return cmd } @@ -124,7 +122,7 @@ func matchSession(s sdk.Session, needle string) bool { } // sortSessionsByRecency sorts in place by UpdatedAt desc. Server returns -// strings; we compare lexically — RFC3339 timestamps sort correctly that +// strings; we compare lexically - RFC3339 timestamps sort correctly that // way, and a stable order is enough for output determinism even if a // non-conforming string slips through. func sortSessionsByRecency(items []sdk.Session) { diff --git a/cli/cmd/session/delete.go b/cli/cmd/session/delete.go index cef8b34b..887fe05b 100644 --- a/cli/cmd/session/delete.go +++ b/cli/cmd/session/delete.go @@ -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, sessionDeleteFields) - aiclient.SetAgentHelp(cmd, "Destructively deletes a chat session by id. ALWAYS pass -y/--yes in agent mode (no TTY ⇒ confirm prompt fails). Returns data: {id, deleted:true}.") return cmd } diff --git a/cli/cmd/session/list.go b/cli/cmd/session/list.go index 75dba700..c6441a6b 100644 --- a/cli/cmd/session/list.go +++ b/cli/cmd/session/list.go @@ -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" "github.com/Tencent/WeKnora/cli/internal/text" @@ -68,7 +67,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)") cmd.Flags().StringVar(&opts.Since, "since", "", "Only show sessions updated within `duration` (e.g. 7d, 24h, 30m)") cmdutil.AddJSONFlags(cmd, sessionListFields) - aiclient.SetAgentHelp(cmd, "Lists chat sessions as a bare JSON array of Session objects (empty `[]` when none). --all-pages drains every server page in one call (capped by --limit). --since filters client-side after fetch.") return cmd } @@ -196,7 +194,7 @@ func parseSinceDuration(s string) (time.Duration, error) { } // fuzzyTime renders a server-provided timestamp string in "2d ago" form. -// Returns the raw input if parsing fails — better to surface the unknown +// Returns the raw input if parsing fails - better to surface the unknown // format than to silently render "-". func fuzzyTime(now time.Time, ts string) string { if ts == "" { diff --git a/cli/cmd/session/list_test.go b/cli/cmd/session/list_test.go index 410510f5..96deae47 100644 --- a/cli/cmd/session/list_test.go +++ b/cli/cmd/session/list_test.go @@ -262,5 +262,3 @@ func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) { assert.LessOrEqual(t, len(svc.calls), 3, "must not fetch beyond what fills --limit") } -// (test removed: --page flag was dropped in v0.4 mainstream-alignment; -// --all-pages now walks unconditionally, no mutex case to test.) diff --git a/cli/cmd/session/session.go b/cli/cmd/session/session.go index 43202c08..0ee63c2f 100644 --- a/cli/cmd/session/session.go +++ b/cli/cmd/session/session.go @@ -3,7 +3,7 @@ // // Package name `sessioncmd` (not `session`) so callers can `import sdk // "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without -// shadowing — same hygiene as `contextcmd`. +// shadowing - same hygiene as `contextcmd`. package sessioncmd import ( diff --git a/cli/cmd/session/view.go b/cli/cmd/session/view.go index e4dbec07..95b3032f 100644 --- a/cli/cmd/session/view.go +++ b/cli/cmd/session/view.go @@ -7,7 +7,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" @@ -49,7 +48,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command { }, } cmdutil.AddJSONFlags(cmd, sessionViewFields) - aiclient.SetAgentHelp(cmd, "Shows a chat session's metadata (title, description, timestamps). Errors with resource.not_found if id is unknown.") return cmd } diff --git a/cli/internal/aiclient/annotations.go b/cli/internal/aiclient/annotations.go deleted file mode 100644 index 001fe85c..00000000 --- a/cli/internal/aiclient/annotations.go +++ /dev/null @@ -1,35 +0,0 @@ -package aiclient - -import ( - "strings" - - "github.com/spf13/cobra" -) - -// AIAgentHelpKey is the cobra Annotation key used to attach an AI-agent-specific -// help blurb to a command. The blurb is appended to --help output only when -// agent mode is active. -const AIAgentHelpKey = "ai_agent_help" - -// FormatAgentGuidance returns the agent-targeted help text registered on cmd, -// or "" if none. Render it after the standard help when DetectAIAgent() != "" -// (an AI coding agent env var is set). -func FormatAgentGuidance(cmd *cobra.Command) string { - if cmd == nil { - return "" - } - v, ok := cmd.Annotations[AIAgentHelpKey] - if !ok { - return "" - } - return strings.TrimSpace(v) -} - -// SetAgentHelp is a small helper that initializes Annotations and stores the -// blurb under AIAgentHelpKey. Use it in NewCmdX constructors before returning. -func SetAgentHelp(cmd *cobra.Command, blurb string) { - if cmd.Annotations == nil { - cmd.Annotations = map[string]string{} - } - cmd.Annotations[AIAgentHelpKey] = strings.TrimSpace(blurb) -} diff --git a/cli/internal/aiclient/detect.go b/cli/internal/aiclient/detect.go deleted file mode 100644 index ee990584..00000000 --- a/cli/internal/aiclient/detect.go +++ /dev/null @@ -1,38 +0,0 @@ -// Package aiclient handles AI agent integration: env-based detection -// (used to trigger AGENT-targeted help text) and per-command help -// annotations. See cli/AGENTS.md for the full agent contract. -package aiclient - -import "os" - -// AIAgentName identifies the detected coding agent invoking the CLI. Empty -// string means no agent detected (or detection is disabled). -type AIAgentName string - -// aiAgentEnvs maps environment variable presence to a coding agent name. -// The earlier 7-entry list (CODEX_*, AIDER_PROMPT, CONTINUE_GLOBAL_DIR, -// OPENCODE_RUNNING, GEMINICODER_PROFILE) did not have official agent docs -// backing those env names; removed in v0.2 to avoid maintaining an -// unverified hardcoded list. New entries should document the source URL. -var aiAgentEnvs = []struct { - env string - name AIAgentName -}{ - {"CLAUDECODE", "claude-code"}, - {"CURSOR_AGENT", "cursor"}, -} - -// DetectAIAgent returns the first known agent name whose env var is set to a -// non-empty value, or "" if none are present. Detection is suppressed when -// WEKNORA_NO_AGENT_AUTODETECT is truthy. Tests substitute via t.Setenv. -func DetectAIAgent() AIAgentName { - if v := os.Getenv("WEKNORA_NO_AGENT_AUTODETECT"); v != "" && v != "0" && v != "false" { - return "" - } - for _, a := range aiAgentEnvs { - if os.Getenv(a.env) != "" { - return a.name - } - } - return "" -} diff --git a/cli/internal/aiclient/detect_test.go b/cli/internal/aiclient/detect_test.go deleted file mode 100644 index 3d4079e6..00000000 --- a/cli/internal/aiclient/detect_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package aiclient - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -// clearAgentEnv unsets every env var DetectAIAgent inspects, so a developer -// running these tests from inside Claude Code / Cursor doesn't see false -// positives. -func clearAgentEnv(t *testing.T) { - t.Helper() - for _, a := range aiAgentEnvs { - t.Setenv(a.env, "") - } - t.Setenv("WEKNORA_NO_AGENT_AUTODETECT", "") - t.Setenv("WEKNORA_AGENT", "") -} - -func TestDetectAIAgent(t *testing.T) { - cases := []struct { - name string - set map[string]string - want AIAgentName - }{ - {name: "empty env", set: nil, want: ""}, - {name: "unrelated env", set: map[string]string{"PATH": "/usr/bin"}, want: ""}, - {name: "claude code", set: map[string]string{"CLAUDECODE": "1"}, want: "claude-code"}, - {name: "cursor", set: map[string]string{"CURSOR_AGENT": "yes"}, want: "cursor"}, - // Other entries (codex / aider / continue / opencode / gemini-coder) - // were dropped — those env names had no official agent docs. - // New entries should arrive with a documented source URL. - { - name: "first-match precedence", - set: map[string]string{"CLAUDECODE": "1", "CURSOR_AGENT": "1"}, - want: "claude-code", - }, - {name: "empty value treated as unset", set: map[string]string{"CLAUDECODE": ""}, want: ""}, - { - name: "WEKNORA_NO_AGENT_AUTODETECT=1 suppresses detection", - set: map[string]string{"CLAUDECODE": "1", "WEKNORA_NO_AGENT_AUTODETECT": "1"}, - want: "", - }, - { - name: "WEKNORA_NO_AGENT_AUTODETECT=0 still allows detection", - set: map[string]string{"CLAUDECODE": "1", "WEKNORA_NO_AGENT_AUTODETECT": "0"}, - want: "claude-code", - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - clearAgentEnv(t) - for k, v := range tc.set { - t.Setenv(k, v) - } - assert.Equal(t, tc.want, DetectAIAgent()) - }) - } -} - diff --git a/cli/internal/cmdutil/authrefresh.go b/cli/internal/cmdutil/authrefresh.go index 4461c488..361c3a99 100644 --- a/cli/internal/cmdutil/authrefresh.go +++ b/cli/internal/cmdutil/authrefresh.go @@ -21,7 +21,7 @@ type Refresher interface { // retry the original request). // // Single canonical implementation shared by `weknora auth refresh` and the -// AuthRetryTransport's refresh closure — both used to inline the same +// AuthRetryTransport's refresh closure - both used to inline the same // six-step sequence with subtly diverging error wording. func RefreshAndPersist(ctx context.Context, store secrets.Store, refresher Refresher, ctxName string) (string, error) { refresh, err := store.Get(ctxName, "refresh") diff --git a/cli/internal/cmdutil/authretry.go b/cli/internal/cmdutil/authretry.go index b73b69c3..3a18c398 100644 --- a/cli/internal/cmdutil/authretry.go +++ b/cli/internal/cmdutil/authretry.go @@ -21,7 +21,7 @@ import ( // - 401 on /api/v1/auth/login or /api/v1/auth/refresh: pass through // (otherwise a stale refresh token causes infinite recursion). // - 401 with no initial token configured (api-key contexts): pass through -// — api-key credentials have no refresh semantic. +// - api-key credentials have no refresh semantic. // - 401 with non-replayable request body (req.GetBody == nil): pass // through. The SDK always uses bytes.Buffer bodies; this is a safety // net for hand-built requests. @@ -31,7 +31,7 @@ import ( // the updated currentToken and replay without re-refreshing (singleflight). // // The transport intentionally shadows the SDK's bearerToken (set via -// WithBearerToken). After a refresh, the SDK is unaware of the new token — +// WithBearerToken). After a refresh, the SDK is unaware of the new token - // the transport's per-request override is the single source of truth for // the Authorization header. Tokens persisted to the secrets store happen // inside refreshFn (see cmdutil.RefreshAndPersist). @@ -49,7 +49,7 @@ type AuthRetryTransport struct { // // Pass an empty initialToken to indicate "no bearer credential configured" // (e.g. an api-key context). In that mode the transport never invokes -// refreshFn — a 401 is propagated as-is. +// refreshFn - a 401 is propagated as-is. func NewAuthRetryTransport(base http.RoundTripper, initialToken string, refreshFn func(context.Context) (string, error)) *AuthRetryTransport { if base == nil { base = http.DefaultTransport diff --git a/cli/internal/cmdutil/authretry_test.go b/cli/internal/cmdutil/authretry_test.go index 2f67db7f..279ec6cf 100644 --- a/cli/internal/cmdutil/authretry_test.go +++ b/cli/internal/cmdutil/authretry_test.go @@ -172,7 +172,7 @@ func TestAuthRetry_SkipAuthEndpoints(t *testing.T) { func TestAuthRetry_NoTokenConfigured_DoesNotInjectAuthz(t *testing.T) { // API-key contexts construct the transport with an empty initial token; // authretry should pass through 401s untouched (no refresh callback exists - // for api-key — they're rejected at the auth-refresh layer). + // for api-key - they're rejected at the auth-refresh layer). base := &stubTransport{t: t, resps: []*http.Response{resp(401, "")}} refreshed := false rt := NewAuthRetryTransport(base, "", func(context.Context) (string, error) { @@ -192,7 +192,7 @@ func TestAuthRetry_NoTokenConfigured_DoesNotInjectAuthz(t *testing.T) { func TestAuthRetry_ConcurrentRefresh_SingleFlight(t *testing.T) { // 4 parallel 401s should trigger exactly 1 refresh; all 4 then retry with // the new token. Use a server that 401s first request from each unique - // path then 200s on retry — except we use one shared transport with + // path then 200s on retry - except we use one shared transport with // scripted responses, ordering matters. To keep determinism, build a // transport that always returns 401 on first call per request, 200 on // second, and gate the refresh callback. diff --git a/cli/internal/cmdutil/confirm.go b/cli/internal/cmdutil/confirm.go index 3915599e..24208f11 100644 --- a/cli/internal/cmdutil/confirm.go +++ b/cli/internal/cmdutil/confirm.go @@ -21,7 +21,7 @@ import ( // // The non-TTY branch is the destructive-write protocol: high-risk writes // always require explicit confirmation in scripted contexts, never silent -// proceed. See cli/AGENTS.md "Exit codes". +// proceed. See cli/README.md "Exit codes". // // `yes` should be sourced from the persistent global -y/--yes flag. func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error { diff --git a/cli/internal/cmdutil/errors.go b/cli/internal/cmdutil/errors.go index 6170a205..ba0b4b86 100644 --- a/cli/internal/cmdutil/errors.go +++ b/cli/internal/cmdutil/errors.go @@ -15,7 +15,7 @@ import ( type ErrorCode string const ( - // auth.* — authentication / permission + // auth.* - authentication / permission CodeAuthUnauthenticated ErrorCode = "auth.unauthenticated" CodeAuthTokenExpired ErrorCode = "auth.token_expired" CodeAuthBadCredential ErrorCode = "auth.bad_credential" @@ -28,12 +28,12 @@ const ( CodeResourceAlreadyExists ErrorCode = "resource.already_exists" CodeResourceLocked ErrorCode = "resource.locked" - // input.* — flag and argument validation + // input.* - flag and argument validation CodeInputInvalidArgument ErrorCode = "input.invalid_argument" CodeInputMissingFlag ErrorCode = "input.missing_flag" // CodeInputConfirmationRequired marks a high-risk write that has no // interactive UI (non-TTY or --json) and was invoked without -y/--yes. - // Mapped to exit code 10 (see cli/AGENTS.md). Agents must surface the + // Mapped to exit code 10 (see cli/README.md). Agents must surface the // error to the user and only retry with -y after explicit human // approval; never auto-retry. CodeInputConfirmationRequired ErrorCode = "input.confirmation_required" @@ -49,13 +49,13 @@ const ( // server.error so agents can retry with their own --session. CodeSessionCreateFailed ErrorCode = "server.session_create_failed" - // local.* — config / file / keychain on the user's machine + // local.* - config / file / keychain on the user's machine CodeLocalConfigCorrupt ErrorCode = "local.config_corrupt" CodeLocalKeychainDenied ErrorCode = "local.keychain_denied" CodeLocalFileIO ErrorCode = "local.file_io" CodeLocalUnimplemented ErrorCode = "local.unimplemented" CodeLocalContextNotFound ErrorCode = "local.context_not_found" - // v0.2 KB-resolution chain (spec §1.3) and project-link (spec §2.4) codes. + // KB-resolution chain and project-link codes. CodeKBIDRequired ErrorCode = "local.kb_id_required" CodeKBNotFound ErrorCode = "local.kb_not_found" CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt" @@ -124,7 +124,7 @@ func Wrapf(code ErrorCode, cause error, format string, args ...any) *Error { // from its HTTP shape (404 → resource.not_found, 401 → auth.unauthenticated, // non-HTTP → network.error, …). Shortcut for the universal pattern // `Wrapf(ClassifyHTTPError(err), err, format, args...)` used by every SDK -// call site — single source for the wrap-and-classify policy. +// call site - single source for the wrap-and-classify policy. // // Use this for any error returned from a wire call. Stays paired with // ClassifyHTTPErrorOutputs() in the acceptance/contract test, which @@ -150,7 +150,7 @@ var SilentError = errors.New("silent error (handled)") // CancelError marks a user-cancelled operation (Ctrl-C / "no" at confirm). var CancelError = errors.New("operation cancelled") -// Typed predicates — use these instead of comparing ErrorCode strings. +// Typed predicates - use these instead of comparing ErrorCode strings. // They walk the error chain so wrapped errors still match. // IsAuthError matches any auth.* code. @@ -285,6 +285,6 @@ func ClassifyHTTPErrorOutputs() []ErrorCode { CodeServerRateLimited, // 429 CodeServerError, // 5xx / parse-failure / default CodeInputInvalidArgument, // 4xx (else) - CodeNetworkError, // 非 HTTP error + CodeNetworkError, // non-HTTP error } } diff --git a/cli/internal/cmdutil/errors_codes_test.go b/cli/internal/cmdutil/errors_codes_test.go index d72cbae5..50769b41 100644 --- a/cli/internal/cmdutil/errors_codes_test.go +++ b/cli/internal/cmdutil/errors_codes_test.go @@ -11,7 +11,7 @@ func TestAllCodes_NonEmpty(t *testing.T) { if len(codes) == 0 { t.Fatal("AllCodes() should return registered codes") } - // Sentinel: 至少包含这几个 v0.0 已知 code + // Sentinel: contains the baseline error codes the registry must always carry. want := map[cmdutil.ErrorCode]bool{ cmdutil.CodeAuthUnauthenticated: false, cmdutil.CodeResourceNotFound: false, diff --git a/cli/internal/cmdutil/exit.go b/cli/internal/cmdutil/exit.go index b0ecfce7..b73b4ea2 100644 --- a/cli/internal/cmdutil/exit.go +++ b/cli/internal/cmdutil/exit.go @@ -6,9 +6,9 @@ import ( "io" ) -// ExitCode maps an error to the documented CLI exit code (spec §2.4 + ADR-3). +// ExitCode maps an error to the documented CLI exit code. // - 0 success -// - 1 generic / unknown typed error — fallback for: resource.already_exists, +// - 1 generic / unknown typed error - fallback for: resource.already_exists, // resource.locked, local.* (config_corrupt / keychain_denied / file_io / // context_not_found / kb_id_required / kb_not_found / projectlink_corrupt / // user_aborted / upload_file_not_found), mcp.*, server.session_create_failed, @@ -19,8 +19,8 @@ import ( // - 5 input.* (other than confirmation_required) // - 6 server.rate_limited // - 7 server.* (other than rate_limited/session_create_failed) / network.* -// - 10 input.confirmation_required — high-risk write needs explicit -y -// (see cli/AGENTS.md) +// - 10 input.confirmation_required - high-risk write needs explicit -y +// (see cli/README.md) // - 130 SIGINT (handled by Go runtime, not this function) func ExitCode(err error) int { if err == nil { @@ -77,7 +77,7 @@ func PrintError(w io.Writer, err error) { // defaultHint returns a canonical actionable hint for known error codes // when the call site didn't set one. `auth.unauthenticated` always points -// at `weknora auth login` — covers the broad surface (auth status / kb +// at `weknora auth login` - covers the broad surface (auth status / kb // list / kb view / search) without per-command hint plumbing. // // Empty string for codes without a stable canonical hint. @@ -104,7 +104,7 @@ func defaultHint(code ErrorCode) string { case CodeInputInvalidArgument, CodeInputMissingFlag: return "see `weknora --help` for valid usage" case CodeInputConfirmationRequired: - return "high-risk write — re-run with -y/--yes after the user explicitly approves" + return "high-risk write - re-run with -y/--yes after the user explicitly approves" case CodeLocalKeychainDenied: return "verify keyring access; falls back to file storage" case CodeLocalConfigCorrupt: diff --git a/cli/internal/cmdutil/factory.go b/cli/internal/cmdutil/factory.go index c9b1fd43..931d4e7a 100644 --- a/cli/internal/cmdutil/factory.go +++ b/cli/internal/cmdutil/factory.go @@ -22,7 +22,7 @@ import ( // closure is lazy: --help / completion / `weknora version` must NOT trigger // HTTP, keyring access, or filesystem I/O beyond the bare minimum. // -// Four closures (ADR-4): +// Four closures: // - Config: parses ~/.config/weknora/config.yaml (no network) // - Client: constructs the SDK client; only Secrets is sync.Once-cached, // so callers should hold the returned *sdk.Client across @@ -33,13 +33,13 @@ import ( // would fork+exec on macOS and DBus-touch on Linux, // defeating the lazy contract above). // -// IOStreams is intentionally NOT a Factory closure — it is the package singleton +// IOStreams is intentionally NOT a Factory closure - it is the package singleton // iostreams.IO. The bar to add a new closure is at least 2 commands sharing the // same dependency; resist factory bloat. // // Client returns a *sdk.Client (the WeKnora SDK). Commands that want narrow -// service interfaces (per ADR-4) declare them in their own files and let the -// real SDK satisfy them implicitly via duck typing. +// service interfaces declare them in their own files and let the real SDK +// satisfy them implicitly via duck typing. type Factory struct { Config func() (*config.Config, error) Client func() (*sdk.Client, error) @@ -47,9 +47,8 @@ type Factory struct { Secrets func() (secrets.Store, error) // ContextOverride, if non-empty, replaces config.CurrentContext for this - // invocation only — set by the global --context flag in PersistentPreRun. - // Buildable Config() / Client() honor it without writing to disk; matches - // spec §1.2 "weknora --context foo kb list = single-shot override". + // invocation only - set by the global --context flag in PersistentPreRun. + // Buildable Config() / Client() honor it without writing to disk. ContextOverride string } @@ -59,7 +58,7 @@ type Factory struct { // none of them. Client and Secrets closures memoize via sync.Once so the // SDK client is built (and the keyring is probed) at most once per process, // even when Factory.ResolveKB internally calls f.Client() before the -// command's RunE calls it again — without this, name-resolved --kb paths +// command's RunE calls it again - without this, name-resolved --kb paths // would build two clients with two AuthRetryTransports holding independent // token state. func New() *Factory { @@ -157,7 +156,7 @@ func buildClient(f *Factory) (*sdk.Client, error) { // 401-retry transport: on the first 401 from a non-/auth/* endpoint, the // transport reads the stored refresh token, calls /api/v1/auth/refresh, // persists the new pair, and replays the original request with the new - // bearer. API-key contexts skip this (no refresh semantic) — a 401 from + // bearer. API-key contexts skip this (no refresh semantic) - a 401 from // them propagates as auth.unauthenticated for the caller to handle. if ctx.TokenRef != "" && ctx.RefreshRef != "" { refreshFn := func(rctx context.Context) (string, error) { @@ -171,9 +170,8 @@ func buildClient(f *Factory) (*sdk.Client, error) { // tenant from the credential itself (JWT claim or API key prefix); the // header is only meaningful for explicit cross-tenant switching by users // with CanAccessAllTenants. Auto-mirroring the persisted tenant from config - // breaks that contract — explicit flags (`--tenant=N` is the planned v0.1 - // entry point) are required before sending it. `tenant_id` stays in config - // for `auth status` display only. + // breaks that contract - explicit cross-tenant flags would be required + // before sending it. `tenant_id` stays in config for `auth status` display only. return sdk.NewClient(ctx.Host, opts...), nil } @@ -231,7 +229,7 @@ func LoadSecret(store secrets.Store, context, key string) (string, error) { // refreshAccessToken is the closure target injected into AuthRetryTransport's // refreshFn. A fresh SDK Client is built here rather than reusing the one -// being constructed — that one is itself wrapped by the transport, which +// being constructed - that one is itself wrapped by the transport, which // would recurse on refresh. The refresh endpoint is unauthenticated apart // from the refresh token in the body, so no credential options are needed. func refreshAccessToken(ctx context.Context, store secrets.Store, host, ctxName string) (string, error) { diff --git a/cli/internal/cmdutil/factory_test.go b/cli/internal/cmdutil/factory_test.go index 6b447a39..086c41b6 100644 --- a/cli/internal/cmdutil/factory_test.go +++ b/cli/internal/cmdutil/factory_test.go @@ -22,7 +22,7 @@ import ( ) // TestFactory_Lazy ensures none of the closures execute work at construction -// time — `--help` / `completion` must not trigger HTTP / keyring access. +// time - `--help` / `completion` must not trigger HTTP / keyring access. func TestFactory_Lazy(t *testing.T) { var configCalls, clientCalls, prompterCalls int f := &Factory{ @@ -39,7 +39,7 @@ func TestFactory_Lazy(t *testing.T) { return prompt.AgentPrompter{} }, } - // Asserting on closure presence — none should have run yet. + // Asserting on closure presence - none should have run yet. assert.Equal(t, 0, configCalls) assert.Equal(t, 0, clientCalls) assert.Equal(t, 0, prompterCalls) @@ -74,7 +74,7 @@ func TestNew_FoundationDefaults(t *testing.T) { // TestFactory_ContextOverride verifies the global --context flag mechanism: // f.ContextOverride replaces config.CurrentContext for this invocation only, -// without writing to disk. Spec §1.2. +// without writing to disk. func TestFactory_ContextOverride(t *testing.T) { dir := t.TempDir() t.Setenv("XDG_CONFIG_HOME", dir) @@ -234,7 +234,7 @@ func TestBuildClient_HappyPath(t *testing.T) { func TestBuildClient_SkipsUnreferencedSecrets(t *testing.T) { // If the context doesn't list APIKeyRef, buildClient must not call - // Get(api_key) — a perf invariant: avoid keychain trips for unused creds. + // Get(api_key) - a perf invariant: avoid keychain trips for unused creds. store := &countingSecrets{MemStore: secrets.NewMemStore()} require.NoError(t, store.Set("p", "access", "jwt")) f := &Factory{ @@ -310,7 +310,7 @@ func TestResolveKB_Chain(t *testing.T) { t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose") dir := t.TempDir() resolveKBChdir(t, dir) - // Drop a project link too — must be ignored. + // Drop a project link too - must be ignored. require.NoError(t, projectlink.Save(filepath.Join(dir, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"})) clientCalls := 0 diff --git a/cli/internal/cmdutil/host.go b/cli/internal/cmdutil/host.go index 9576445e..5d123867 100644 --- a/cli/internal/cmdutil/host.go +++ b/cli/internal/cmdutil/host.go @@ -7,7 +7,7 @@ import ( ) // NormalizeHost validates and canonicalizes a `--host` value. Trailing -// slashes are trimmed. Every failure path returns CodeInputInvalidArgument — +// slashes are trimmed. Every failure path returns CodeInputInvalidArgument - // a present-but-empty flag is treated as a bad value, not as a missing flag // (cobra's required-flag layer is what catches the absent case). // @@ -30,7 +30,7 @@ func NormalizeHost(host string) (string, error) { // ValidateHTTPURL applies the same http/https URL rules NormalizeHost uses, // but parameterized by flagLabel so error messages name the caller's flag // (e.g. "--host", "--from-url"). Returns CodeInputInvalidArgument on any -// failure. Empty `value` is not pre-checked here — callers that distinguish +// failure. Empty `value` is not pre-checked here - callers that distinguish // "missing" from "malformed" should test for empty before calling. func ValidateHTTPURL(flagLabel, value string) error { u, err := url.Parse(value) diff --git a/cli/internal/cmdutil/jsonflags_test.go b/cli/internal/cmdutil/jsonflags_test.go index 6149a3c6..e1c58bca 100644 --- a/cli/internal/cmdutil/jsonflags_test.go +++ b/cli/internal/cmdutil/jsonflags_test.go @@ -118,7 +118,7 @@ func TestAddJSONFlags_JQWithoutJSON(t *testing.T) { if err.Error() != want { t.Errorf("wrong message.\nwant: %q\ngot: %q", want, err.Error()) } - // Must NOT be a FlagError — gh emits this as a plain error so exit + // Must NOT be a FlagError - gh emits this as a plain error so exit // code stays 1, not 2. var fe *cmdutil.FlagError if errors.As(err, &fe) { diff --git a/cli/internal/cmdutil/kb.go b/cli/internal/cmdutil/kb.go index 7c2377c9..a8d5e16c 100644 --- a/cli/internal/cmdutil/kb.go +++ b/cli/internal/cmdutil/kb.go @@ -38,7 +38,7 @@ func ResolveKBFlag(ctx context.Context, lister KBLister, raw string) (string, er } // ResolveKBNameToID looks up a knowledge base by name and returns its ID. -// Used by `link` and `Factory.ResolveKB` — a single lookup so the match +// Used by `link` and `Factory.ResolveKB` - a single lookup so the match // policy (currently exact case-sensitive) lives in one place. func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) { kbs, err := lister.ListKnowledgeBases(ctx) diff --git a/cli/internal/compat/cache.go b/cli/internal/compat/cache.go index a3ecd08e..5f42fe63 100644 --- a/cli/internal/compat/cache.go +++ b/cli/internal/compat/cache.go @@ -20,7 +20,7 @@ func cachePath() (string, error) { // LoadCache reads the cached Info. Returns (info, fresh, err). // // info == nil when no cache exists (err == nil) -// fresh == false 当 cache 不存在 / TTL 过期 +// fresh == false when the cache is missing or TTL-expired func LoadCache() (*Info, bool, error) { p, err := cachePath() if err != nil { diff --git a/cli/internal/compat/cache_test.go b/cli/internal/compat/cache_test.go index fde8f971..d22a4b63 100644 --- a/cli/internal/compat/cache_test.go +++ b/cli/internal/compat/cache_test.go @@ -28,7 +28,7 @@ func TestCache_RoundTrip(t *testing.T) { t.Errorf("ServerVersion = %v, want %q", got, want.ServerVersion) } - // 文件应在 $XDG_CACHE_HOME/weknora/server-info.yaml + // File should live at $XDG_CACHE_HOME/weknora/server-info.yaml p := filepath.Join(dir, "weknora", "server-info.yaml") if _, err := filepath.Abs(p); err != nil { t.Errorf("path resolution: %v", err) diff --git a/cli/internal/compat/compat.go b/cli/internal/compat/compat.go index 9d809aa9..20790211 100644 --- a/cli/internal/compat/compat.go +++ b/cli/internal/compat/compat.go @@ -10,9 +10,9 @@ import ( type Level int const ( - OK Level = iota // 兼容 - SoftWarn // 服务器旧, 部分新功能不可用 - HardError // 不兼容, 需升级 CLI 或 server + OK Level = iota // compatible + SoftWarn // server outdated; some new features may be unavailable + HardError // incompatible; CLI or server must be upgraded ) func (l Level) String() string { @@ -27,13 +27,13 @@ func (l Level) String() string { return "unknown" } -// Compat compares client/server version. v0.x 阶段允许漂移: +// Compat compares client/server versions. Cross-minor drift is allowed: // -// 同 major, client minor ≤ server minor → OK -// 同 major, client minor > server minor → SoftWarn (server 旧, 部分新功能不可用) -// 不同 major → HardError -// 字符串 unparseable → OK (容错, 不阻塞) -// "(unknown)" / "" → OK (dev build / server 字段缺失) +// same major, client minor <= server minor -> OK +// same major, client minor > server minor -> SoftWarn (some new features may be unavailable) +// different major -> HardError +// unparseable string -> OK (fail-open, do not block) +// "(unknown)" / "" -> OK (dev build / server field missing) func Compat(serverVer, cliVer string) (Level, string) { sMaj, sMin, ok := parseSemver(serverVer) if !ok { @@ -44,7 +44,7 @@ func Compat(serverVer, cliVer string) (Level, string) { return OK, "" } if sMaj != cMaj { - return HardError, fmt.Sprintf("incompatible: client %s vs server %s — upgrade required", cliVer, serverVer) + return HardError, fmt.Sprintf("incompatible: client %s vs server %s - upgrade required", cliVer, serverVer) } if cMin > sMin { return SoftWarn, fmt.Sprintf("server is older (server %s, client %s); some new features may be unavailable", serverVer, cliVer) @@ -56,14 +56,14 @@ func Compat(serverVer, cliVer string) (Level, string) { // Accepts the leading "v" common in `git describe` output and Tencent/WeKnora // tag conventions ("v0.1.0"), since both server `/system/info.version` and // the CLI's own ldflags-injected build.Version may carry it. -// Returns ok=false 当字符串无法识别 (空 / "(unknown)" / 非数字)。 +// Returns ok=false when the string is unrecognizable (empty / "(unknown)" / non-numeric). func parseSemver(s string) (major, minor int, ok bool) { if s == "" || s == "(unknown)" { return 0, 0, false } - // 接受 "v" 前缀:git describe + Tencent tag 都带 v + // Accept the "v" prefix; both `git describe` output and Tencent/WeKnora tags carry it. s = strings.TrimPrefix(s, "v") - // 去掉 prerelease/build metadata + // Strip prerelease/build metadata. if i := strings.IndexAny(s, "-+"); i >= 0 { s = s[:i] } diff --git a/cli/internal/compat/compat_test.go b/cli/internal/compat/compat_test.go index b3dd7af0..ce6613fd 100644 --- a/cli/internal/compat/compat_test.go +++ b/cli/internal/compat/compat_test.go @@ -19,9 +19,9 @@ func TestCompat(t *testing.T) { {"client minor lower", "1.5.0", "1.2.0", compat.OK, ""}, {"client minor higher", "1.2.0", "1.5.0", compat.SoftWarn, "server is older"}, {"different major", "1.9.9", "2.0.0", compat.HardError, "incompatible"}, - {"client unset", "1.2.3", "(unknown)", compat.OK, ""}, // dev build, 不报警 + {"client unset", "1.2.3", "(unknown)", compat.OK, ""}, // dev build; no warning {"server unset", "", "1.2.3", compat.OK, ""}, - {"malformed server", "garbage", "1.2.3", compat.OK, ""}, // 不阻塞 + {"malformed server", "garbage", "1.2.3", compat.OK, ""}, // fail-open // "v" prefix tolerance (git describe + Tencent tag convention) {"v-prefix both", "v1.2.0", "v1.5.0", compat.SoftWarn, "server is older"}, diff --git a/cli/internal/compat/version_check.go b/cli/internal/compat/version_check.go index b200a2d8..cf5b46b8 100644 --- a/cli/internal/compat/version_check.go +++ b/cli/internal/compat/version_check.go @@ -1,5 +1,5 @@ // Package compat probes server `/system/info` and decides client-server -// version skew level. Used by `weknora doctor` 的 server_version 检查项。 +// version skew level. Used by `weknora doctor`'s server_version check. // // 24h TTL state file cache, three-tier compat semantics // (major-mismatch=hard / minor-mismatch=soft / equal=ok). @@ -20,8 +20,7 @@ type Info struct { ProbedAt time.Time `yaml:"probed_at"` } -// ProbeService is the narrow SDK surface compat depends on (testability via -// fake; mirrors v0.0 service interface pattern). +// ProbeService is the narrow SDK surface compat depends on; tests inject a fake. type ProbeService interface { GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) } diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go index bec2e511..cc1a41f1 100644 --- a/cli/internal/config/config.go +++ b/cli/internal/config/config.go @@ -1,8 +1,8 @@ // Package config reads and writes the user-level config at // $XDG_CONFIG_HOME/weknora/config.yaml. yaml.v3 directly; viper is -// intentionally not used (see ADR-2). Multi-host context map lives here; +// intentionally not used. Multi-host context map lives here; // the per-project link (.weknora/project.yaml) is handled by the -// projectlink package (see ADR-16). +// projectlink package. package config import ( diff --git a/cli/internal/format/references.go b/cli/internal/format/references.go index 1bfdf040..9fdaeff5 100644 --- a/cli/internal/format/references.go +++ b/cli/internal/format/references.go @@ -10,7 +10,7 @@ import ( // WriteReferences renders the compact references footer used by chat and // agent invoke: a horizontal rule, one numbered line per reference, // best-available title + optional score. Skipped entirely when refs is -// empty — agent-friendly silence beats an empty banner. +// empty - agent-friendly silence beats an empty banner. func WriteReferences(w io.Writer, refs []*sdk.SearchResult) { if len(refs) == 0 { return diff --git a/cli/internal/mcp/server.go b/cli/internal/mcp/server.go index f6fa249f..075ba1e1 100644 --- a/cli/internal/mcp/server.go +++ b/cli/internal/mcp/server.go @@ -8,7 +8,7 @@ // tree (which would expose auth/link/completion/destructive verbs that // don't belong on an agent-callable surface). // - Long-running tools (chat / agent_invoke) accumulate the LLM SSE -// stream server-side and return a single CallToolResult — MCP spec +// stream server-side and return a single CallToolResult - MCP spec // 2025-06-18 does not define streamed tool-result content, so the // accumulate-and-return pattern is the canonical path. // - Handlers receive ctx for cancellation; mid-LLM-stream cancellation diff --git a/cli/internal/mcp/tools.go b/cli/internal/mcp/tools.go index d58387b2..53bee936 100644 --- a/cli/internal/mcp/tools.go +++ b/cli/internal/mcp/tools.go @@ -42,17 +42,17 @@ type agentService interface { // agentInvokeService composes the two SDK methods agent_invoke needs // (CreateSession for the auto-session path + AgentQAStreamWithRequest // for the run itself). Declared here alongside the per-domain -// interfaces above so ServiceClient (server.go) — which embeds the -// four domain interfaces — also satisfies it. +// interfaces above so ServiceClient (server.go) - which embeds the +// four domain interfaces - also satisfies it. type agentInvokeService interface { CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error) AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error } // registerTools wires the curated 9 tools onto server. Adding a tool here -// is a deliberate API expansion — the agent-callable surface is the +// is a deliberate API expansion - the agent-callable surface is the // reason this CLI ships an MCP server, not its CLI command list, so this -// list must be maintained by hand (see also AGENTS.md mcp serve section). +// list must be maintained by hand. func registerTools(server *mcpsdk.Server, svc ServiceClient) { addKBList(server, svc) addKBView(server, svc) @@ -76,7 +76,7 @@ type kbListOutput struct { func addKBList(server *mcpsdk.Server, svc knowledgeBaseService) { mcpsdk.AddTool(server, &mcpsdk.Tool{ Name: "kb_list", - Description: "List all knowledge bases visible to the active WeKnora tenant. No arguments. Returns items[]: each item carries id, name, description, knowledge_count, is_pinned, updated_at — useful for selecting a kb_id to pass to other tools.", + Description: "List all knowledge bases visible to the active WeKnora tenant. No arguments. Returns items[]: each item carries id, name, description, knowledge_count, is_pinned, updated_at - useful for selecting a kb_id to pass to other tools.", }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ kbListInput) (*mcpsdk.CallToolResult, kbListOutput, error) { items, err := svc.ListKnowledgeBases(ctx) if err != nil { @@ -130,7 +130,7 @@ type docListOutput struct { func addDocList(server *mcpsdk.Server, svc knowledgeService) { mcpsdk.AddTool(server, &mcpsdk.Tool{ Name: "doc_list", - Description: "List documents in a knowledge base, with pagination and optional parse-status filter. Returns items[] with id, file_name, title, parse_status, size, updated_at — plus the page/total metadata.", + Description: "List documents in a knowledge base, with pagination and optional parse-status filter. Returns items[] with id, file_name, title, parse_status, size, updated_at - plus the page/total metadata.", }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docListInput) (*mcpsdk.CallToolResult, docListOutput, error) { if in.KBID == "" { return nil, docListOutput{}, fmt.Errorf("kb_id is required") @@ -206,7 +206,7 @@ const maxDocDownloadBytes = 1 << 20 func addDocDownload(server *mcpsdk.Server, svc knowledgeService) { mcpsdk.AddTool(server, &mcpsdk.Tool{ Name: "doc_download", - Description: "Download a document's raw bytes by ID. Capped at 1 MiB per call — for larger documents, use search_chunks to find the relevant excerpts. is_base64 reports whether content was base64-encoded (heuristic: presence of NUL byte in the first 512 bytes).", + Description: "Download a document's raw bytes by ID. Capped at 1 MiB per call - for larger documents, use search_chunks to find the relevant excerpts. is_base64 reports whether content was base64-encoded (heuristic: presence of NUL byte in the first 512 bytes).", }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, docDownloadOutput, error) { if in.KnowledgeID == "" { return nil, docDownloadOutput{}, fmt.Errorf("knowledge_id is required") @@ -250,7 +250,7 @@ type searchChunksOutput struct { func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) { // Out = any: SDK output schema would derive from searchChunksOutput, - // which embeds *sdk.SearchResult — and SearchResult.Metadata is a + // which embeds *sdk.SearchResult - and SearchResult.Metadata is a // nilable map[string]any that violates the auto-generated // type=object constraint when empty. Skipping derivation by using // `any` keeps the structured JSON shape identical while bypassing @@ -258,7 +258,7 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) { // below. mcpsdk.AddTool(server, &mcpsdk.Tool{ Name: "search_chunks", - Description: "Hybrid (vector + keyword) retrieval against a knowledge base. Returns the top chunks ranked by RRF; use this before chat to ground an answer in cited context. Results include knowledge_id, content, score — feed back into chat as context or display directly.", + Description: "Hybrid (vector + keyword) retrieval against a knowledge base. Returns the top chunks ranked by RRF; use this before chat to ground an answer in cited context. Results include knowledge_id, content, score - feed back into chat as context or display directly.", }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in searchChunksInput) (*mcpsdk.CallToolResult, any, error) { if in.KBID == "" { return nil, nil, fmt.Errorf("kb_id is required") @@ -366,7 +366,7 @@ type agentListOutput struct { func addAgentList(server *mcpsdk.Server, svc agentService) { mcpsdk.AddTool(server, &mcpsdk.Tool{ Name: "agent_list", - Description: "List the tenant's custom agents. Returns items[] with id, name, description, is_builtin — use to discover an agent_id before agent_invoke.", + Description: "List the tenant's custom agents. Returns items[] with id, name, description, is_builtin - use to discover an agent_id before agent_invoke.", }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ agentListInput) (*mcpsdk.CallToolResult, agentListOutput, error) { items, err := svc.ListAgents(ctx) if err != nil { @@ -415,7 +415,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) { Channel: "api", } // Auto-create session if not supplied. Sessions are agent- - // agnostic at creation (Q3 — verified against server source). + // agnostic at creation (Q3 - verified against server source). sessionID := in.SessionID if sessionID == "" { sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp agent_invoke"}) @@ -447,7 +447,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) { // encodeDownload returns (content, isBase64). Heuristic: if the first 512 // bytes contain a NUL, treat as binary. Otherwise it's UTF-8-ish text. -// Matches what /usr/bin/file's "binary" heuristic does at a coarse level — +// Matches what /usr/bin/file's "binary" heuristic does at a coarse level - // good enough to spare an agent from base64-decoding obvious text. func encodeDownload(buf []byte) (string, bool) { probe := buf diff --git a/cli/internal/projectlink/projectlink.go b/cli/internal/projectlink/projectlink.go index 344f4873..a50db13c 100644 --- a/cli/internal/projectlink/projectlink.go +++ b/cli/internal/projectlink/projectlink.go @@ -5,8 +5,8 @@ // .weknora/project.yaml is found, (b) the filesystem root is reached, or // (c) the walk exceeds a 64-level depth limit (cycle protection for // pathological symlink setups). Pattern matches `cargo`, `npm`, and `git` -// — find-the-project's-root walks; mount-boundary crossing is allowed -// (npm/cargo behave the same — a project may straddle a bind-mount). +// - find-the-project's-root walks; mount-boundary crossing is allowed +// (npm/cargo behave the same - a project may straddle a bind-mount). package projectlink import ( @@ -50,7 +50,7 @@ func Discover(startDir string) (string, bool, error) { return candidate, true, nil } if err != nil && !errors.Is(err, os.ErrNotExist) { - // Permission errors etc. — keep walking up; missing read access + // Permission errors etc. - keep walking up; missing read access // to a parent dir doesn't necessarily mean the project starts // here. Cargo/npm have the same behavior. // Fall through to parent walk. @@ -86,7 +86,7 @@ func Save(path string, p *Project) error { // Remove deletes the project link at path. A missing file is reported as // success so callers can stay idempotent under concurrent-removal races -// — the post-condition (no file at path) holds in either case. +// - the post-condition (no file at path) holds in either case. func Remove(path string) error { if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("remove project link: %w", err) diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.go index bdb58d71..cced123e 100644 --- a/cli/internal/prompt/prompt.go +++ b/cli/internal/prompt/prompt.go @@ -1,8 +1,7 @@ -// Package prompt defines the interactive-input abstraction. -// -// Production impl will use charmbracelet/huh in v0.0 commands that need -// password input (auth login). Foundation PR ships only the interface + -// a sentinel error so non-TTY contexts surface the right error. +// Package prompt defines the interactive-input abstraction. Production +// uses charmbracelet/huh (TTYPrompter) for password input; non-TTY +// contexts get AgentPrompter, which rejects every interactive call with +// ErrAgentNoPrompt so commands can map it to a typed missing-flag error. package prompt import "errors" diff --git a/cli/internal/secrets/keyring.go b/cli/internal/secrets/keyring.go index 78ca6b36..48376722 100644 --- a/cli/internal/secrets/keyring.go +++ b/cli/internal/secrets/keyring.go @@ -21,7 +21,7 @@ type KeyringStore struct{} func NewKeyringStore() *KeyringStore { return &KeyringStore{} } // service returns the per-context service identifier. Splitting by context -// (rather than by host) follows the Supabase pattern (ADR-17): a user with +// (rather than by host) follows the Supabase pattern: a user with // two tenants on the same host gets two distinct keyring namespaces. func (k *KeyringStore) service(context string) string { return keyringService + ":" + context diff --git a/cli/internal/secrets/secrets.go b/cli/internal/secrets/secrets.go index 6e6b3627..2190583f 100644 --- a/cli/internal/secrets/secrets.go +++ b/cli/internal/secrets/secrets.go @@ -1,10 +1,10 @@ -// Package secrets stores and retrieves credentials. +// Package secrets stores and retrieves credentials. Production wires +// KeyringStore (OS keychain, primary) with FileStore (0600 plaintext under +// $XDG_CONFIG_HOME/weknora/secrets/, used as a fallback when no keyring +// backend is available). // -// v0.0 ships a file-only Store implementation (0600 perms under -// $XDG_CONFIG_HOME/weknora/secrets/). The OS keyring backend lands in v0.1 -// once auth login is needed in TTY contexts (current PR is foundation only). -// -// Namespace convention: "weknora::" where key is "access" or "refresh". +// Namespace convention: "weknora::" where key is "access", +// "refresh", or "api_key". package secrets import ( @@ -34,15 +34,14 @@ type Store interface { } // FileStore writes 0600 plain-text files under $XDG_CONFIG_HOME/weknora/secrets/. -// It is the headless / CI default and the keychain fallback (see ADR-17 for -// namespace strategy). +// It is the headless / CI default and the keychain fallback. type FileStore struct { root string } // NewFileStore returns a FileStore rooted at $XDG_CONFIG_HOME/weknora/secrets // (or ~/.config/weknora/secrets if XDG_CONFIG_HOME is unset). Same convention -// as config.Path — see that file for the rationale (CLI convention). +// as config.Path - see that file for the rationale (CLI convention). func NewFileStore() (*FileStore, error) { root, err := defaultRoot() if err != nil { @@ -91,7 +90,7 @@ func (f *FileStore) Delete(context, key string) error { // Ref returns the file:// URI under which a secret would be stored. Path // component is forward-slash-normalized per RFC 8089 (file:///path on Unix, -// file:///C:/... on Windows) — the wire format must not depend on platform +// file:///C:/... on Windows) - the wire format must not depend on platform // path separator since this string is persisted to config.yaml and may be // consumed by tooling on a different OS. func (f *FileStore) Ref(context, key string) string { diff --git a/cli/internal/sse/accumulator.go b/cli/internal/sse/accumulator.go index 5fb702fc..4067eb04 100644 --- a/cli/internal/sse/accumulator.go +++ b/cli/internal/sse/accumulator.go @@ -16,12 +16,12 @@ import ( // Accumulator buffers a KnowledgeQAStream callback sequence. // -// Zero value is ready to use. Not safe for concurrent Append calls — the SDK +// Zero value is ready to use. Not safe for concurrent Append calls - the SDK // invokes its callback sequentially on a single goroutine, so this matches // the only contract that exists today. // // Demuxes by ResponseType so the answer string is not polluted by thinking -// or reflection fragments — the model layer (internal/models/chat/ +// or reflection fragments - the model layer (internal/models/chat/ // remote_api.go) emits ResponseTypeThinking events whenever the upstream // LLM produces reasoning_content (GPT-5 / Claude extended thinking), and // without demux those would be silently concatenated into Result(). @@ -64,7 +64,7 @@ func (a *Accumulator) Append(r *sdk.StreamResponse) { if r.AssistantMessageID != "" && a.AssistantMessageID == "" { a.AssistantMessageID = r.AssistantMessageID } - // Capture references whenever they arrive — they may land on a + // Capture references whenever they arrive - they may land on a // dedicated `references` event before the terminal `complete`. if r.KnowledgeReferences != nil { a.References = r.KnowledgeReferences diff --git a/cli/internal/sse/accumulator_test.go b/cli/internal/sse/accumulator_test.go index 7547c851..e944a2c4 100644 --- a/cli/internal/sse/accumulator_test.go +++ b/cli/internal/sse/accumulator_test.go @@ -47,7 +47,7 @@ func TestAccumulator_FinalizesOnComplete(t *testing.T) { func TestAccumulator_IgnoresAgentQueryDone(t *testing.T) { // Server emits a leading agent_query frame with done=true to deliver - // session metadata; the accumulator must NOT treat that as terminal — + // session metadata; the accumulator must NOT treat that as terminal - // otherwise the answer fragments that follow would be discarded. a := &sse.Accumulator{} a.Append(&sdk.StreamResponse{ @@ -108,7 +108,7 @@ func TestAccumulator_CapturesSessionMetadata(t *testing.T) { } func TestAccumulator_FirstSessionMetadataWins(t *testing.T) { - // Subsequent events must not overwrite the first non-empty value — the + // Subsequent events must not overwrite the first non-empty value - the // session id is set once at session start and any later override would be // a server bug we should not silently mask. a := &sse.Accumulator{} diff --git a/cli/internal/sse/agent_accumulator.go b/cli/internal/sse/agent_accumulator.go index 318332e1..dcdd22a4 100644 --- a/cli/internal/sse/agent_accumulator.go +++ b/cli/internal/sse/agent_accumulator.go @@ -21,11 +21,11 @@ type AgentToolEvent struct { // AgentAccumulator buffers an AgentQAStream callback sequence. Distinct // from Accumulator (KnowledgeQAStream) because the agent event model is -// wider — events include thinking / reflection / tool_call / tool_result +// wider - events include thinking / reflection / tool_call / tool_result // / answer / references / error, with a flat `Done bool` on each frame // rather than the ResponseType=complete sentinel KnowledgeQAStream emits. // -// Zero value is ready to use. Not safe for concurrent Append calls — the +// Zero value is ready to use. Not safe for concurrent Append calls - the // SDK callback contract is sequential on a single goroutine. // // API mirrors sse.Accumulator: private builders + accessor methods so the diff --git a/cli/internal/testutil/prompter.go b/cli/internal/testutil/prompter.go index 3a13afb0..6d31db9e 100644 --- a/cli/internal/testutil/prompter.go +++ b/cli/internal/testutil/prompter.go @@ -6,7 +6,7 @@ import ( // ConfirmPrompter is a test double for prompt.Prompter that scripts a single // Confirm answer (with optional error). Input/Password are stubbed to return -// prompt.ErrAgentNoPrompt — assert it via `Asked` after the call. +// prompt.ErrAgentNoPrompt - assert it via `Asked` after the call. // // Use across cmd/* tests where a command's confirm-prompt branch needs to be // exercised. Avoid maintaining per-command copies of the same shape. diff --git a/cli/internal/text/displayname.go b/cli/internal/text/displayname.go index 6877ea00..faf4fdd6 100644 --- a/cli/internal/text/displayname.go +++ b/cli/internal/text/displayname.go @@ -3,7 +3,7 @@ package text // KnowledgeDisplayName picks the most informative human label for a // knowledge entry. File-uploads use FileName; URL / text entries fall // back to Title; the ID is the last-resort placeholder so a table cell -// is never empty. Single source for the ordering — `weknora doc list` +// is never empty. Single source for the ordering - `weknora doc list` // and `weknora search docs` both call this so a Knowledge renders // identically in either command. // diff --git a/cli/internal/text/pluralize.go b/cli/internal/text/pluralize.go index 13166211..7375e16d 100644 --- a/cli/internal/text/pluralize.go +++ b/cli/internal/text/pluralize.go @@ -5,8 +5,7 @@ package text import "fmt" // Pluralize returns " " or " s". Simple suffix "s" only; -// irregular forms (person/people) are not supported (add PluralizeIrregular -// when needed, per spec §2.1). +// irregular forms (person/people) are not supported. func Pluralize(n int, thing string) string { if n == 1 { return fmt.Sprintf("%d %s", n, thing) diff --git a/cli/internal/text/truncate.go b/cli/internal/text/truncate.go index 03afc749..76248109 100644 --- a/cli/internal/text/truncate.go +++ b/cli/internal/text/truncate.go @@ -4,14 +4,14 @@ import "github.com/mattn/go-runewidth" const ellipsis = "…" -// Truncate cuts s to at most maxWidth display columns (CJK / emoji 占 2 列; -// ASCII 占 1 列), appending "…" if truncated. Display width, not rune count. +// Truncate cuts s to at most maxWidth display columns (CJK / emoji occupy +// 2 columns; ASCII 1), appending "…" if truncated. Display width, not rune count. // // Edge cases: // -// maxWidth ≤ 0 → "" -// s 已 ≤ maxWidth → s 原样返回 -// ellipsis 占 1 列, 所以 truncate 时 budget = maxWidth - 1 +// maxWidth <= 0 -> "" +// s already fits -> s returned unchanged +// ellipsis is 1 column, so truncate budget = maxWidth - 1 func Truncate(maxWidth int, s string) string { if maxWidth <= 0 { return "" diff --git a/cli/internal/xdg/xdg.go b/cli/internal/xdg/xdg.go index feb38868..dd87f86d 100644 --- a/cli/internal/xdg/xdg.go +++ b/cli/internal/xdg/xdg.go @@ -17,7 +17,7 @@ import ( // under $HOME used when the env var is unset (".config" / ".cache" / etc.). // parts join under "weknora/" inside the chosen root. // -// Honors the XDG vars on every OS, even macOS — where os.UserConfigDir +// Honors the XDG vars on every OS, even macOS - where os.UserConfigDir // would otherwise return ~/Library/Application Support. func Path(envVar, fallbackDir string, parts ...string) (string, error) { if x := os.Getenv(envVar); x != "" {