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

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

- Drop internal/aiclient/ entirely (annotations + detect + tests)
- Remove 38 SetAgentHelp callsites + agentAwareHelpFunc / SetHelpFunc
  wiring in cmd/root.go
- Migrate 4 command-level rules to standard Long help (visible to all,
  not env-gated): doc upload mode mutex, kb edit at-least-one,
  kb pin idempotent, search chunks channel mutex
- Rewrite AGENTS.md as a developer guide (gh-style 6 H2 / 167 lines):
  audience preamble + Build / Architecture / Command Structure /
  Testing / Code Style / Error Handling. Drops sections absent in
  surveyed projects (Commit & PR Conventions, Who Uses This CLI)
- Clean 14 internal doc refs (ADR-N, spec §X, v0.X) in source comments
  and docs that pointed at docs/superpowers/ — that directory is
  local-only / uncommitted, so refs are dead for outside readers
- Drop forward-looking "once v0.2 ships" from README
This commit is contained in:
nullkey
2026-05-15 02:16:45 +08:00
committed by lyingbug
parent a0dd989c81
commit f2e8e3f56c
111 changed files with 575 additions and 908 deletions
+123 -315
View File
@@ -1,359 +1,167 @@
# Agent Integration Guide for `weknora` CLI # AGENTS.md
> **Scope.** This file is an **operational reference** for LLM agents 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).
> (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` is designed to be agent-friendly: error messages, output ## Build, Test, and Lint
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:
```bash ```bash
weknora kb list --json=id,name # [{ "id": "kb_x", "name": "Eng" }, …] go build -o weknora . # build (from cli/)
weknora kb view kb_x --json=id # { "id": "kb_x" } 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 Both `go test -count=1 ./...` and `go vet ./...` must pass before committing.
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.
Unknown field names are silently dropped so you can pass an aspirational ## Architecture
field set across heterogenous outputs.
#### jq pipeline: `--jq <expr>` Entry point: `cmd/main.go` → `cmd.Execute()` → `cmd.NewRootCmd(cmdutil.New())`.
`--jq` applies a jq expression to the JSON before printing. The Key packages:
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.
```bash - `cmd/<noun>/` — cobra command implementations, one subdir per noun
weknora kb list --jq '.[].id' # one id per line - `internal/cmdutil/` — `Factory`, `JSONOptions`, typed `Error`, exit-code mapping, destructive-write confirm, KB id-or-name resolve
weknora kb view kb_x --jq .name # bare name - `internal/format/` — bare JSON emitter (`WriteJSON` / `WriteJSONFiltered`)
weknora search chunks "x" --kb e --jq '.[].score' # scores per line - `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<Verb>(f *cmdutil.Factory) *cobra.Command` constructor — flag registration + `cmdutil.AddJSONFlags`
4. Separate `run<Verb>(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 <id>
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 ### JSON Output
filter runs after the field projection.
### 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 ```go
command already wrote before the failure). The error message goes to if jopts.Enabled() {
stderr in this format: return jopts.Emit(iostreams.IO.Out, result)
}
```
<error.code>: <message>[: <wrapped cause>]
hint: <actionable next-step>
``` ```
- `<error.code>` is a `namespace.snake_case` string from a closed `Emit` is the single source for the bare-JSON contract — it honors `--json=fields,...` projection and `--jq <expr>` filtering. Never call `format.WriteJSON*` directly from a command. See `cmd/kb/list.go`.
registry in `cli/internal/cmdutil/errors.go` (`AllCodes()`).
An acceptance test enforces that every code referenced in `cli/cmd/`
is registered.
- `<message>` is the human-readable description.
- `<hint>` is the deterministic next-step hint (omitted when no hint
applies).
Code namespaces: `auth.*` / `resource.*` / `input.*` / `server.*` / ### Destructive Writes
`network.*` / `local.*` / `mcp.*`.
To pattern-match programmatically: split on the first `:` to extract 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`.
the code, or branch on the exit code (see below).
### Exit codes ## Testing
| Code | Meaning | Agent action | ### Narrow Service Fakes
|---|---|---|
| `0` | Success | Continue |
| `1` | Typed `local.*` error or unclassified | Read stderr, decide retry/abort |
| `2` | Flag/argument validation error | Re-check `weknora <command> --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 |
Exit 10 is the wire-level signal for "high-risk write needs explicit Each command's `runX(ctx, opts, jopts, svc, ...)` takes its interface, not `*sdk.Client`. Tests inject plain-struct fakes:
confirmation". **Never bypass exit 10 by auto-passing `-y` without
explicit user permission.**
--- ```go
type fakeBarSvc struct {
## Command surface gotID string
resp *sdk.Bar
Discover the command tree the same way human users do: err error
}
```bash func (f *fakeBarSvc) GetBar(_ context.Context, id string) (*sdk.Bar, error) {
weknora --help # top-level f.gotID = id
weknora kb --help # subtree return f.resp, f.err
weknora kb delete --help # single command flags }
``` ```
The command tree follows `<noun> <verb>`. Verbs are: No mocking library; the narrow-interface design makes fakes 5 lines each.
| Verb | Semantics | Example | ### IOStreams in Tests
|---|---|---|
| `list` | Multi-resource read | `kb list` |
| `view` | Single-resource read | `kb view <id>` |
| `create` | Create resource | `kb create --name X` |
| `edit` | Partial update (only sent fields change) | `kb edit <id> --description X` |
| `delete` | Destructive remove (KB itself) | `kb delete <id> -y` |
| `empty` | Bulk-delete contents, preserve container | `kb empty <id> -y` |
| `upload` | Bulk write content | `doc upload <file>` |
| `download` | Stream resource to disk | `doc download <id> -O file` |
| `pin` / `unpin` | Toggle "pinned" state (idempotent) | `kb pin <id>` |
| `use` | Switch active selection | `context use <name>` |
| `add` / `remove` | Manage local config entries | `context add staging --host ...` |
`auth` subtree: `login` / `logout` / `list` / `status` / `refresh` / ```go
`token`. Context-switching uses `context use <name>` (WeKnora contexts out, errBuf := iostreams.SetForTest(t) // bytes.Buffer sinks, non-TTY
bundle host + tenant + credentials, so they need a richer abstraction ios, _ := iostreams.SetForTestWithTTY(t) // simulate terminal
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.
### Auth security contract ### Confirm Prompts
- **Credential storage**: OS keychain via `go-keyring` (macOS Keychain, Use `testutil.ConfirmPrompter{Answer: bool, Err: error}` from `internal/testutil/`. Single source for the prompt double — do NOT re-define `confirmPrompter` per package.
Windows Credential Manager, freedesktop Secret Service). Falls back to
a 0600 file under `$XDG_CONFIG_HOME/weknora/secrets/<context>/` 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/<pid>/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.
`search` subtree: `search chunks "<q>" --kb X` for hybrid retrieval; ### Assertions
`search kb "<q>"` / `search docs "<q>" --kb X` / `search sessions "<q>"`
for client-side substring filtering on the listing endpoints.
`session` subtree: `list` / `view` / `delete` for chat session Use `testify`. Prefer `require` (not `assert`) for error checks so the test halts immediately, and `assert` for value comparisons:
management. Sessions are the durable wrapper around `chat` invocations.
Top-level RAG / connectivity verbs: `chat`, `search`, `api`, `link`, ```go
`auth`, `context`, `session`, `doctor`, `version`. require.NoError(t, err)
require.ErrorAs(t, err, &typed)
assert.Equal(t, "expected", actual)
```
`doctor` is a deliberate WeKnora addition: RAG deployments routinely ### Acceptance: Wire-Shape Goldens
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/contract/wire_test.go` drives the in-process cobra tree against `httptest.Server` fixtures and compares stdout to `acceptance/testdata/wire/<case>.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 Use for flag validation, error classification, parser edge cases. See `internal/cmdutil/exit_test.go` and `cmd/kb/list_test.go`.
(under "AI Agents:").
1. **Pass `-y/--yes`** on destructive writes (`kb delete` / `kb empty` / ```go
`doc delete` / `session delete` / `context remove` when targeting tests := []struct{ name string; ...}{
the current context) when running headless. Without it, you will {name: "descriptive case", ...},
get exit 10. **Never auto-add `-y`** without the user's explicit }
go-ahead — the exit-10 protocol is the one explicit guard against for _, tt := range tests {
unintended writes. t.Run(tt.name, func(t *testing.T) { /* arrange, act, assert */ })
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.
(Additional safety guidance — e.g. "do not switch context unless the ## Code Style
user asked" — is documented in the affected command's own `--help`.)
--- - 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 | - `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.
| `CLAUDECODE` | `claude-code` | - `cmdutil.Wrapf(code, err, format, args...)` — explicit wrap with a chosen code
| `CURSOR_AGENT` | `cursor` | - `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` 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.
annotation. **No behavior change** — this is help-text rendering only.
To suppress detection (e.g. running `weknora` interactively from inside 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.
Claude Code without the agent footer): `WEKNORA_NO_AGENT_AUTODETECT=1`.
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) — `<cwd>/.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
+43 -2
View File
@@ -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 and the CLI follows [Semantic Versioning](https://semver.org/) independently
of the WeKnora server / frontend release cadence. of the WeKnora server / frontend release cadence.
Earlier history (v0.0 through v0.2) is recorded in the project root CLI history before v0.3 is recorded in the project root
[CHANGELOG.md](../CHANGELOG.md) under the entries that introduced the CLI. [CHANGELOG.md](../CHANGELOG.md) under the release that introduced the CLI.
## [Unreleased] ## [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 <expr>` 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 ### v0.3 — extended management surface and a `session` subtree
#### Added #### Added
+71 -25
View File
@@ -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. hybrid searches against a WeKnora server from your shell or an AI agent.
Available Commands: Available Commands:
agent Manage and invoke custom agents
api Make a raw API request to the WeKnora server api Make a raw API request to the WeKnora server
auth Manage authentication credentials and contexts auth Manage authentication credentials and contexts
chat Ask a streaming RAG question against a knowledge base 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) context Manage CLI contexts (named connection targets)
doc Manage documents in a knowledge base doc Manage documents in a knowledge base
doctor Run 4 self-checks: base URL, auth, server version, credential storage doctor Run 4 self-checks: base URL, auth, server version, credential storage
help Help about any command
kb Manage knowledge bases kb Manage knowledge bases
link Bind the current directory to a knowledge base 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 search Search across chunks, knowledge bases, documents, or sessions
session Manage chat sessions session Manage chat sessions
unlink Remove the directory's knowledge-base binding
version Show CLI build metadata version Show CLI build metadata
``` ```
The command surface mirrors `gh` CLI's `<noun> <verb>` convention. See The command surface mirrors `gh` CLI's `<noun> <verb>` convention. The
[AGENTS.md](AGENTS.md) for the operational contract that AI agents wire contract for AI agents (Claude Code, Cursor, Aider, …) is documented
(Claude Code, Cursor, Aider, …) can rely on: bare-JSON output shape, [below](#wire-contract). For contributing to the CLI source, see
stderr error format, exit-code protocol, error-code registry, and [AGENTS.md](AGENTS.md).
per-command guidance.
--- ---
@@ -35,7 +39,7 @@ per-command guidance.
### From source ### From source
Requires Go 1.24+. Requires Go 1.26+.
```bash ```bash
git clone https://github.com/Tencent/WeKnora.git 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
Pre-built binaries for Linux / macOS / Windows are produced by CI on each 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) release. Grab the latest from the [Releases page](https://github.com/Tencent/WeKnora/releases).
once v0.2 ships.
--- ---
@@ -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 Every command supports `--json`, emitting bare JSON for the resource it
produces — an array for `list` / `search`, a single object for `view` 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 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 On failure, stdout stays empty and the typed error goes to stderr in
`code: message\nhint: ...` form: this format:
```
<code.namespace>: <message>[: <wrapped cause>]
hint: <actionable next-step>
```
Example:
``` ```
auth.unauthenticated: fetch current user: HTTP error 401: ... auth.unauthenticated: fetch current user: HTTP error 401: ...
hint: run `weknora auth login` hint: run `weknora auth login`
``` ```
The typed exit code (3 / 4 / 5 / 6 / 7 / 10) carries the failure The full code registry is in `cli/internal/cmdutil/errors.go`
class for agents that branch on it. The full error-code registry and (`AllCodes()`). Code namespaces: `auth.*` / `resource.*` / `input.*` /
exit-code protocol are documented in [AGENTS.md](AGENTS.md). `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 <cmd> --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 ### Other agent ergonomics
`-y` on a non-TTY/`--json` invocation, destructive commands return
`error.code: input.confirmation_required` and exit code 10** so an - For chat / agent invoke in agent contexts, prefer `--no-stream --json`
agent can ask the user before retrying. — streaming tokens to stdout makes JSON parsing impossible.
- `--json` coexists with the global `--context <name>` for single-shot - `--json` composes with the global `--context <name>` for single-shot
context override. context overrides without disk writes.
- Set `CLAUDECODE` or `CURSOR_AGENT` environment variables to surface - `weknora mcp serve` exposes a curated readonly tool surface over
per-command "AI agents:" guidance in `--help` output. 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 / 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/`.
--- ---
+7 -8
View File
@@ -17,23 +17,22 @@ import (
// cmdutil.NewError(codeXxx, ...) and cmdutil.Wrapf(codeXxx, ...) and verifies // cmdutil.NewError(codeXxx, ...) and cmdutil.Wrapf(codeXxx, ...) and verifies
// that codeXxx is registered in cmdutil.AllCodes(). // 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 // ident. Most SDK call sites go through cmdutil.WrapHTTP(err, ...) which
// the scanner skips entirely (it only inspects NewError / Wrapf selector // the scanner skips entirely (it only inspects NewError / Wrapf selector
// names). A few sites still call ClassifyHTTPError directly to inspect // names). A few sites still call ClassifyHTTPError directly to inspect
// or remap the code; those are call-expression args the scanner also // or remap the code; those are call-expression args the scanner also
// skips. Either way, the codes those paths can yield are bridged via // skips. Either way, the codes those paths can yield are bridged via
// cmdutil.ClassifyHTTPErrorOutputs(), which enumerates every code the // 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. // doesn't false-positive on them.
// //
// Limitations (documented in spec §4.3): // Limitations:
// - Only literal cmdutil.CodeXxx idents are detected; codes assigned to // - Only literal cmdutil.CodeXxx idents are detected; codes assigned to
// a local variable then passed are NOT scanned (rare pattern). // a local variable then passed are NOT scanned (rare pattern).
// - cmdutil.WrapHTTP(...) and cmdutil.ClassifyHTTPError(...) call // - cmdutil.WrapHTTP(...) and cmdutil.ClassifyHTTPError(...) call
// expressions are skipped — the ClassifyHTTPErrorOutputs bridge // expressions are skipped - the ClassifyHTTPErrorOutputs bridge
// covers their dynamic codes. // covers their dynamic codes.
// - v0.x does not enforce a baseline diff (spec ADR-6b); v0.9 will.
func TestAllReferencedCodesAreRegistered(t *testing.T) { func TestAllReferencedCodesAreRegistered(t *testing.T) {
registered := make(map[cmdutil.ErrorCode]struct{}) registered := make(map[cmdutil.ErrorCode]struct{})
for _, c := range cmdutil.AllCodes() { 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). // First arg should be cmdutil.CodeXxx (SelectorExpr ident).
// If it's a function call (e.g. cmdutil.ClassifyHTTPError(err)), skip // 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) arg0Sel, ok := call.Args[0].(*ast.SelectorExpr)
if !ok { if !ok {
return true return true
@@ -128,7 +127,7 @@ func collectErrorCodes(fset *token.FileSet, f *ast.File, out map[cmdutil.ErrorCo
} }
code, ok := identToErrorCode(arg0Sel.Sel.Name) code, ok := identToErrorCode(arg0Sel.Sel.Name)
if !ok { 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. // a clear "code referenced but not registered" message.
code = cmdutil.ErrorCode("UNKNOWN_REF:" + arg0Sel.Sel.Name) 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 // identToErrorCode maps an ident name like "CodeAuthUnauthenticated" to its
// underlying ErrorCode value via a simple switch. Avoids reflect. // 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(). // bookkeeping as adding it to AllCodes().
func identToErrorCode(name string) (cmdutil.ErrorCode, bool) { func identToErrorCode(name string) (cmdutil.ErrorCode, bool) {
switch name { switch name {
+5 -6
View File
@@ -38,13 +38,12 @@ func TestMain(m *testing.M) {
var update = flag.Bool("update", false, "update golden files") var update = flag.Bool("update", false, "update golden files")
// newTestFactory builds a Factory whose Client returns mockClient. // 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 // WEKNORA_BASE_URL is set when mockServer is non-nil. buildClient does not
// not currently honor this env var (it reads from config.Host); commands that // 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 // need the mock URL rely on the mockClient injection above. The env is set
// is set anyway as a forward-affordance for any direct net/http callers // anyway for any direct net/http callers (e.g. doctor's HEAD /health).
// added in PR-7+ (e.g. doctor's PingBaseURL HEAD /health).
func newTestFactory(t *testing.T, mockServer *httptest.Server, mockClient *sdk.Client) *cmdutil.Factory { func newTestFactory(t *testing.T, mockServer *httptest.Server, mockClient *sdk.Client) *cmdutil.Factory {
t.Helper() t.Helper()
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+16 -16
View File
@@ -12,7 +12,7 @@
// line on stderr. // line on stderr.
// //
// Cases intentionally omitted (with reason): // Cases intentionally omitted (with reason):
// - doctor.success — non-offline path emits // - doctor.success - non-offline path emits
// unstable timing // unstable timing
// ("reachable in 2ms"). // ("reachable in 2ms").
// Unit tests in cli/cmd/doctor // Unit tests in cli/cmd/doctor
@@ -20,12 +20,12 @@
// doctor.success_offline is // doctor.success_offline is
// the deterministic sibling // the deterministic sibling
// kept here. // kept here.
// - auth_login.success — requires stdin pipe // - auth_login.success - requires stdin pipe
// (--with-token) + keyring- // (--with-token) + keyring-
// aware Secrets store; the // aware Secrets store; the
// helper does not yet expose // helper does not yet expose
// a stdin hook. // 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 // All cases use leaf-positioned --json (e.g. `version --json`). --json is a
// per-leaf flag, not a global persistent flag. // per-leaf flag, not a global persistent flag.
@@ -45,13 +45,13 @@ import (
) )
// wireCase declares one row in the contract matrix. Optional fields: // wireCase declares one row in the contract matrix. Optional fields:
// server — mock /api/v1/* endpoints; nil means no network. // server - mock /api/v1/* endpoints; nil means no network.
// preConfig — seed config.yaml under the per-test XDG_CONFIG_HOME // preConfig - seed config.yaml under the per-test XDG_CONFIG_HOME
// (set by newTestFactory); use for cases like // (set by newTestFactory); use for cases like
// `context use` that read local state without an // `context use` that read local state without an
// SDK round-trip. // SDK round-trip.
// wantErr — non-zero exit expected. // wantErr - non-zero exit expected.
// wantStderrSubstring — stderr must contain this substring (typically the // wantStderrSubstring - stderr must contain this substring (typically the
// typed error code, e.g. "auth.unauthenticated"). // typed error code, e.g. "auth.unauthenticated").
// Only meaningful when wantErr=true. // Only meaningful when wantErr=true.
type wireCase struct { type wireCase struct {
@@ -66,13 +66,13 @@ type wireCase struct {
// wireCases enumerates every contract scenario whose stdout is golden-pinned. // wireCases enumerates every contract scenario whose stdout is golden-pinned.
// Order is illustrative, not load-bearing. // Order is illustrative, not load-bearing.
var wireCases = []wireCase{ var wireCases = []wireCase{
// 1. version.success — pure local; no client touched. // 1. version.success - pure local; no client touched.
{ {
name: "version.success", name: "version.success",
args: []string{"version", "--json"}, 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. // network checks are skipped. Stable details + summary.
{ {
name: "doctor.success_offline", name: "doctor.success_offline",
@@ -80,7 +80,7 @@ var wireCases = []wireCase{
server: doctorReachable, // ensures buildServices succeeds even if probed 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 // skip on auth_credential + server_version. credential_storage still
// runs (independent). Contract: any check=fail bumps summary.failed // runs (independent). Contract: any check=fail bumps summary.failed
// and RunE returns SilentError → exit 1 with the data object // and RunE returns SilentError → exit 1 with the data object
@@ -92,7 +92,7 @@ var wireCases = []wireCase{
wantErr: true, wantErr: true,
}, },
// 4-7. kb list / get — SDK paths /api/v1/knowledge-bases[/<id>] // 4-7. kb list / get - SDK paths /api/v1/knowledge-bases[/<id>]
{ {
name: "kb_list.success", name: "kb_list.success",
args: []string{"kb", "list", "--json"}, args: []string{"kb", "list", "--json"},
@@ -123,7 +123,7 @@ var wireCases = []wireCase{
wantStderrSubstring: "resource.not_found", 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", name: "context_use.success",
args: []string{"context", "use", "production", "--json"}, 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", name: "auth_status.success",
args: []string{"auth", "status", "--json"}, args: []string{"auth", "status", "--json"},
@@ -156,7 +156,7 @@ var wireCases = []wireCase{
wantStderrSubstring: "auth.unauthenticated", 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_<id> (passed through) or a name (resolved via // --kb accepts either kb_<id> (passed through) or a name (resolved via
// list); UUID-format detection happens client-side, mirroring gcloud // list); UUID-format detection happens client-side, mirroring gcloud
// --project's id-or-name auto-detection. // --project's id-or-name auto-detection.
@@ -185,7 +185,7 @@ var wireCases = []wireCase{
// TestWireGolden is the matrix-runner. Cases are sequential (the // TestWireGolden is the matrix-runner. Cases are sequential (the
// iostreams singleton swap inside helpers.runCmd is package-global; // 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) { func TestWireGolden(t *testing.T) {
for _, tc := range wireCases { for _, tc := range wireCases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
+3 -5
View File
@@ -2,11 +2,9 @@
// //
// Package acceptance is the cli/ subtree top-level home for cross-cutting // Package acceptance is the cli/ subtree top-level home for cross-cutting
// contract / integration tests. Lives outside cli/internal/ so a future // 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: // Sub-packages:
// contract/ — envelope JSON shape golden + error.code registry consistency // contract/ - envelope JSON shape golden + error.code registry consistency
// e2e/ — real WeKnora server blackbox tests (testscript-style) // e2e/ - real WeKnora server blackbox tests (testscript-style)
//
// Layout convention follows spec §4.5.
package acceptance package acceptance
+4 -4
View File
@@ -31,7 +31,7 @@ import (
// TestRAGFullLoop walks the demo MVP path: link a context, create a KB, // 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 // 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. // validating both functional behavior and wire-contract stability.
func TestRAGFullLoop(t *testing.T) { func TestRAGFullLoop(t *testing.T) {
host := mustEnv(t, "WEKNORA_E2E_HOST") host := mustEnv(t, "WEKNORA_E2E_HOST")
@@ -45,7 +45,7 @@ func TestRAGFullLoop(t *testing.T) {
env := append(os.Environ(), env := append(os.Environ(),
"XDG_CONFIG_HOME="+xdg, "XDG_CONFIG_HOME="+xdg,
"XDG_CACHE_HOME="+filepath.Join(xdg, "cache"), "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=", "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)) t.Logf("chat answer (%d chars), %d references", len(chat.Answer), len(chat.References))
if len(chat.References) == 0 { 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. // question, but the demo flow is supposed to.
t.Logf("warning: chat returned 0 references (server may have a different config)") 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 // waitDocReady polls `doc list` until the uploaded document's status indicates
// indexing is complete. WeKnora server uses a few status values across versions // 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 // state so we don't break on a server-side rename. Failed status fails the test
// fast. // fast.
func waitDocReady(t *testing.T, bin string, env []string, kbID, docID string, timeout time.Duration) { func waitDocReady(t *testing.T, bin string, env []string, kbID, docID string, timeout time.Duration) {
+7 -17
View File
@@ -1,18 +1,13 @@
// Package agentcmd holds the `weknora agent` command tree: // Package agentcmd holds the `weknora agent` command tree:
// list / view / invoke. The directory is named `agent/` (matches cobra // list / view / invoke. The directory is named `agent/` (matches cobra
// noun-verb convention) but the Go package is `agentcmd` to avoid // noun-verb convention) but the Go package is `agentcmd` to avoid
// shadowing cli/internal/agent (which owns SetAgentHelp + agent-aware // colliding with cobra's *cobra.Command identifier.
// help rendering for AI coding agents — a distinct concept from
// WeKnora's first-class custom-agent resources).
// //
// Disambiguation in cli/AGENTS.md: "agent" in this subtree refers to // "agent" in this subtree refers to WeKnora's user-defined Custom
// WeKnora's user-defined Custom Agents (server resource: GET/POST // Agents (server resource: GET/POST /agents/...). The CLI's
// /agents/...). The CLI's `agent invoke` calls /agent-chat/:session_id // `agent invoke` calls /agent-chat/:session_id which dispatches the
// which dispatches the agent's configured workflow (system prompt, // agent's configured workflow (system prompt, allowed tools, KB scope,
// allowed tools, KB scope, retrieval thresholds, etc.). This is // retrieval thresholds).
// orthogonal to AGENTS.md / SetAgentHelp, which exists so AI coding
// agents (Claude Code, Cursor) consuming the CLI can read structured
// hints from --help.
package agentcmd package agentcmd
import ( import (
@@ -29,12 +24,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
Short: "Manage and invoke custom agents", Short: "Manage and invoke custom agents",
Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB
scope into an addressable resource. List visible agents, view a single scope into an addressable resource. List visible agents, view a single
agent's configuration, or invoke an agent against a query. 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.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() }, Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
} }
+5 -7
View File
@@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -18,7 +17,7 @@ import (
) )
// agentInvokeFields enumerates fields surfaced for `--json` discovery on // 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, // object with the agent's final answer plus the trace (references,
// tool events). // tool events).
var agentInvokeFields = []string{ var agentInvokeFields = []string{
@@ -36,7 +35,7 @@ type InvokeOptions struct {
// InvokeService is the narrow SDK surface this command depends on. // 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 // agent-agnostic at creation (verified against
// internal/handler/session/handler.go CreateSession, which only persists // internal/handler/session/handler.go CreateSession, which only persists
// {title, description}). The agent ID is supplied per-request via // {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 tools, KB scope, retrieval thresholds) over SSE. By default a fresh session
is auto-created; pass --session to continue an existing conversation. The is auto-created; pass --session to continue an existing conversation. The
agent picks the model, retrieval params, and tool surface from its own 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: Modes:
TTY (default): live answer streaming + tool-trace footer 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().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)") cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
cmdutil.AddJSONFlags(cmd, agentInvokeFields) 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 return cmd
} }
@@ -167,7 +165,7 @@ func runInvoke(ctx context.Context, opts *InvokeOptions, jopts *cmdutil.JSONOpti
return cmdutil.WrapHTTP(streamErr, "agent-chat stream") 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. // so agents don't silently emit a truncated answer as ok=true.
if !acc.Done() { if !acc.Done() {
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event") 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. // 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. // banner.
func renderToolTrace(w io.Writer, events []sse.AgentToolEvent) { func renderToolTrace(w io.Writer, events []sse.AgentToolEvent) {
if len(events) == 0 { if len(events) == 0 {
+2 -4
View File
@@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "github.com/Tencent/WeKnora/cli/internal/text"
@@ -17,7 +16,7 @@ import (
) )
// agentListFields enumerates the fields surfaced for `--json` discovery // 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). // omitted because its sub-fields make filtering noisy (use `--jq` instead).
var agentListFields = []string{ var agentListFields = []string{
"id", "name", "description", "avatar", "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)") cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
cmdutil.AddJSONFlags(cmd, agentListFields) 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 return cmd
} }
@@ -80,7 +78,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
if items == nil { if items == nil {
items = []sdk.Agent{} // ensure JSON [] not null 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. // first. Mirrors kb list / doc list behavior.
sort.Slice(items, func(i, j int) bool { sort.Slice(items, func(i, j int) bool {
return items[i].UpdatedAt.After(items[j].UpdatedAt) return items[i].UpdatedAt.After(items[j].UpdatedAt)
+2 -4
View File
@@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
@@ -15,7 +14,7 @@ import (
// agentViewFields enumerates fields surfaced for `--json` discovery on // agentViewFields enumerates fields surfaced for `--json` discovery on
// `agent view`. Filter applies to the bare Agent object. Config sub-fields // `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. // `--jq '.config'` to reach them.
var agentViewFields = []string{ var agentViewFields = []string{
"id", "name", "description", "avatar", "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 / Long: `Renders the agent's metadata (id / name / description / created-by /
timestamps) plus a compact config summary (mode, model, allowed tools, KB timestamps) plus a compact config summary (mode, model, allowed tools, KB
scope). Pass --json for the full Agent object including the nested config 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 Example: ` weknora agent view ag_abc
weknora agent view ag_abc --json | jq '.config.allowed_tools'`, weknora agent view ag_abc --json | jq '.config.allowed_tools'`,
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
@@ -53,7 +52,6 @@ struct — or --jq '.config' to extract just the config.`,
}, },
} }
cmdutil.AddJSONFlags(cmd, agentViewFields) 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 return cmd
} }
+2 -4
View File
@@ -18,14 +18,13 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" 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 // 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. // is a no-op here. The marker shows up in --help so users can tell.
var apiFields = []string{"<response-shape-varies>"} var apiFields = []string{"<response-shape-varies>"}
@@ -74,7 +73,7 @@ Examples:
} }
method := resolveMethod(opts) method := resolveMethod(opts)
// Escape-hatch DELETE through `weknora api` is just as destructive // 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 method == http.MethodDelete {
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, jopts.Enabled(), "endpoint", args[0]); err != nil { if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, jopts.Enabled(), "endpoint", args[0]); err != nil {
return err return err
@@ -92,7 +91,6 @@ Examples:
cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)") cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)")
cmdutil.AddJSONFlags(cmd, apiFields) cmdutil.AddJSONFlags(cmd, apiFields)
cmd.MarkFlagsMutuallyExclusive("data", "input") 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 return cmd
} }
+2 -2
View File
@@ -201,7 +201,7 @@ func TestAPI_PathWithoutSlash(t *testing.T) {
// withRootHarness wraps `weknora api ...` under a synthetic root cmd that // withRootHarness wraps `weknora api ...` under a synthetic root cmd that
// registers the global `-y/--yes` persistent flag (mirrors addGlobalFlags in // registers the global `-y/--yes` persistent flag (mirrors addGlobalFlags in
// cmd/root.go). Required because api's NewCmd doesn't register --yes itself // 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 { func withRootHarness(api *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"} root := &cobra.Command{Use: "weknora"}
root.PersistentFlags().BoolP("yes", "y", false, "") root.PersistentFlags().BoolP("yes", "y", false, "")
@@ -260,7 +260,7 @@ func TestAPI_DELETE_WithYes_Proceeds(t *testing.T) {
t.Fatalf("execute: %v", err) t.Fatalf("execute: %v", err)
} }
if !called { if !called {
t.Error("DELETE handler not called — confirmation may have blocked") t.Error("DELETE handler not called - confirmation may have blocked")
} }
} }
+1 -1
View File
@@ -21,7 +21,7 @@ const (
) )
// modeFromRefs maps the per-context TokenRef / APIKeyRef presence to a // 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. // matches the precedence in cmdutil.buildClient.
func modeFromRefs(apiKeyRef, tokenRef string) string { func modeFromRefs(apiKeyRef, tokenRef string) string {
switch { switch {
+2 -3
View File
@@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -31,11 +30,12 @@ type listEntry struct {
// NewCmdList builds `weknora auth list`. Per-host enumeration: render one // NewCmdList builds `weknora auth list`. Per-host enumeration: render one
// row per registered context, marking the active one. Reads only // 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 { func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "list", Use: "list",
Short: "List configured authentication contexts", 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, Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error { RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c) jopts, err := cmdutil.CheckJSONFlags(c)
@@ -46,7 +46,6 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
}, },
} }
cmdutil.AddJSONFlags(cmd, authListFields) 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 return cmd
} }
+2 -2
View File
@@ -37,7 +37,7 @@ func TestList_HumanRender(t *testing.T) {
// Mode column. // Mode column.
assert.Contains(t, got, ModeBearer) assert.Contains(t, got, ModeBearer)
assert.Contains(t, got, ModeAPIKey) 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"), assert.Less(t, strings.Index(got, "prod"), strings.Index(got, "staging"),
"contexts should render sorted by name") "contexts should render sorted by name")
} }
@@ -72,7 +72,7 @@ func TestList_JSON_BareArray(t *testing.T) {
} }
func TestModeFromRefs(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. // than pretending the context is a valid login.
assert.Equal(t, ModeUnknown, modeFromRefs("", "")) assert.Equal(t, ModeUnknown, modeFromRefs("", ""))
assert.Equal(t, ModeBearer, modeFromRefs("", "tok")) assert.Equal(t, ModeBearer, modeFromRefs("", "tok"))
+4 -6
View File
@@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -17,7 +16,7 @@ import (
) )
// authLoginFields enumerates the fields surfaced for `--json` discovery on // 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 // keyring; agents who need to verify the credential should re-run
// `auth status`. // `auth status`.
var authLoginFields = []string{ 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") cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
cmdutil.AddJSONFlags(cmd, authLoginFields) cmdutil.AddJSONFlags(cmd, authLoginFields)
_ = cmd.MarkFlagRequired("host") _ = 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 return cmd
} }
@@ -126,7 +124,7 @@ func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOption
opts.APIKey = key opts.APIKey = key
// Validate against the server before persisting so a typo'd / // Validate against the server before persisting so a typo'd /
// expired / wrong-host key fails fast (gh CLI parity). The probe // 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) user, err := defaultAPIKeyValidator(ctx, opts.Host, key)
if err != nil { if err != nil {
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key") 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 // warnOnFileFallback prints a one-shot stderr advisory when the secrets
// store fell back to the plaintext 0600 file backend (keychain unavailable // 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 // users notice that credentials are NOT in the OS keychain before they're
// surprised by it later. doctor's credential_storage check carries the // surprised by it later. doctor's credential_storage check carries the
// same info but agents that bypass doctor would otherwise miss it. // 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 { if _, isFile := store.(*secrets.FileStore); !isFile {
return 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.") fmt.Fprintln(iostreams.IO.Err, " install / unlock the keyring (or use `weknora doctor` to inspect) for OS-backed storage.")
} }
+1 -1
View File
@@ -124,7 +124,7 @@ func stubAPIKeyValidator(fn apiKeyValidator) func() {
func TestRunLogin_WithToken_Empty(t *testing.T) { func TestRunLogin_WithToken_Empty(t *testing.T) {
iostreams.SetForTest(t) iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{}) 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. // a panic-on-call sentinel.
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) { restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
t.Fatal("validator should not be called on empty stdin") t.Fatal("validator should not be called on empty stdin")
+4 -6
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -30,7 +29,7 @@ type logoutResult struct {
// NewCmdLogout builds `weknora auth logout`. Clears stored credentials // NewCmdLogout builds `weknora auth logout`. Clears stored credentials
// (keyring + file fallback) and removes the context entry from config.yaml. // (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 { func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
opts := &LogoutOptions{} opts := &LogoutOptions{}
cmd := &cobra.Command{ 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 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. 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 must rotate them in the server UI; for JWT, the token will continue to be
accepted until it expires.`, accepted until it expires.`,
Example: ` weknora auth logout # current context 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") cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context")
cmdutil.AddJSONFlags(cmd, authLogoutFields) cmdutil.AddJSONFlags(cmd, authLogoutFields)
cmd.MarkFlagsMutuallyExclusive("name", "all") 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 return cmd
} }
@@ -85,7 +83,7 @@ func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
delete(cfg.Contexts, name) delete(cfg.Contexts, name)
} }
// If we removed the active context, pick a remaining one (deterministic by // 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 // invocation surfaces a clear "no current context" error rather than
// silently switching). // silently switching).
if _, stillExists := cfg.Contexts[cfg.CurrentContext]; !stillExists { 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 // clearContextSecrets best-effort deletes every secret slot the context
// references. Errors are swallowed because a missing secret is a no-op // 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) { func clearContextSecrets(store secrets.Store, c config.Context, name string) {
if c.TokenRef != "" { if c.TokenRef != "" {
_ = store.Delete(name, "access") _ = store.Delete(name, "access")
+1 -1
View File
@@ -14,7 +14,7 @@ import (
) )
// newLogoutFactory builds a Factory whose Config closure mutates the supplied // 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 // tests use t.Setenv("XDG_CONFIG_HOME", t.TempDir()) at the call site to
// isolate the on-disk file. // isolate the on-disk file.
func newLogoutFactory(t *testing.T, cfg *config.Config, store secrets.Store) *cmdutil.Factory { func newLogoutFactory(t *testing.T, cfg *config.Config, store secrets.Store) *cmdutil.Factory {
+8 -10
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
@@ -17,11 +16,11 @@ type RefreshOptions struct {
} }
// authRefreshFields enumerates the fields surfaced for `--json` discovery // 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"} var authRefreshFields = []string{"context"}
// refreshResult is the typed payload emitted under data on success. Token // 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 // into stdout / agent transcripts. Agents needing to verify the new token
// can re-run `weknora auth status` (live API check). // can re-run `weknora auth status` (live API check).
type refreshResult struct { type refreshResult struct {
@@ -29,10 +28,10 @@ type refreshResult struct {
} }
// NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access // 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. // 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. // rotate the key via the server UI instead.
func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command { func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
opts := &RefreshOptions{} 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. 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. 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.`, refresh semantic. Rotate the key in the server UI instead.`,
Example: ` weknora auth refresh # refresh the current context Example: ` weknora auth refresh # refresh the current context
weknora auth refresh --name staging # refresh a specific 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)") cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)")
cmdutil.AddJSONFlags(cmd, authRefreshFields) 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 return cmd
} }
// defaultRefresher constructs a fresh, unauthenticated SDK client targeting // 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. // so no bearer / api-key header is needed.
func defaultRefresher(host string) cmdutil.Refresher { func defaultRefresher(host string) cmdutil.Refresher {
return sdk.NewClient(host) 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)) fmt.Sprintf("context %q has no host", name))
} }
if c.RefreshRef == "" { 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 == "" { 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{ return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument, Code: cmdutil.CodeInputInvalidArgument,
+2 -2
View File
@@ -140,7 +140,7 @@ func TestRefresh_NoRefreshTokenStored(t *testing.T) {
"prod": {Host: "https://kb", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"}, "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()) f := newRefreshFactory(t, cfg, secrets.NewMemStore())
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(&fakeRefreshService{})) err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err) require.Error(t, err)
@@ -168,7 +168,7 @@ func TestRefresh_ServerRefused(t *testing.T) {
assert.Contains(t, typed.Hint, "auth login") assert.Contains(t, typed.Hint, "auth login")
// stored access must NOT have been overwritten with empty // stored access must NOT have been overwritten with empty
if v, _ := store.Get("prod", "access"); v == "" { 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 _ = v
} }
} }
+8 -3
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
@@ -37,7 +36,14 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "status", Use: "status",
Short: "Show the active context, principal, and token state", 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 { RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c) jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil { if err != nil {
@@ -51,7 +57,6 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
}, },
} }
cmdutil.AddJSONFlags(cmd, authStatusFields) 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 return cmd
} }
+1 -1
View File
@@ -90,7 +90,7 @@ func TestRunStatus_SDKError_Transport(t *testing.T) {
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }} f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
err := runStatus(context.Background(), nil, f, &fakeStatusService{err: assert.AnError}) err := runStatus(context.Background(), nil, f, &fakeStatusService{err: assert.AnError})
require.Error(t, err) 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. // classify network.error so retry logic / exit code 7 / IsTransient apply.
assert.True(t, cmdutil.IsTransient(err), "expected transient/network classification, got %v", err) assert.True(t, cmdutil.IsTransient(err), "expected transient/network classification, got %v", err)
} }
+5 -7
View File
@@ -5,7 +5,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
) )
@@ -27,7 +26,7 @@ type tokenResult struct {
// curl -H "Authorization: Bearer $WEKNORA_TOKEN" ... # JWT mode // curl -H "Authorization: Bearer $WEKNORA_TOKEN" ... # JWT mode
// curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key 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. // `auth list` shows which mode each context uses.
// //
// Default output: raw token on stdout, no trailing newline (clean $(...)). // 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) 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 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 // 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). // uses for the Authorization header (see factory.go buildClient).
var token, mode string var token, mode string
switch { 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}) 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) fmt.Fprint(iostreams.IO.Out, token)
// Defensive hint to stderr when stdout is an interactive terminal: // Defensive hint to stderr when stdout is an interactive terminal:
// the user likely didn't mean to display the secret on screen. // the user likely didn't mean to display the secret on screen.
// stderr-only so scripts (always non-TTY) are unaffected. Mode-specific // stderr-only so scripts (always non-TTY) are unaffected. Mode-specific
// because api-key tokens are long-lived and rotation is the only // 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() { if iostreams.IO.IsStdoutTTY() {
fmt.Fprintln(iostreams.IO.Err) 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") fmt.Fprintln(iostreams.IO.Err, "hint: pipe to $(weknora auth token) to capture; this terminal scrollback now contains the secret")
if mode == ModeAPIKey { 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 return nil
+3 -3
View File
@@ -165,7 +165,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) {
}, },
} }
store := secrets.NewMemStore() store := secrets.NewMemStore()
// no Set — keyring is empty // no Set - keyring is empty
iostreams.SetForTest(t) iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), nil) err := runToken(tokenTestFactory(t, cfg, store), nil)
if err == 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 // interactive terminal, it ALSO writes a stderr advisory ("you just put the
// secret in your scrollback") + a mode-specific rotation note for api-key // secret in your scrollback") + a mode-specific rotation note for api-key
// credentials. The stdout half must stay clean under all modes so $(...) // 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) { func makeBearerCfg() (*config.Config, *secrets.MemStore) {
cfg := &config.Config{ cfg := &config.Config{
@@ -278,7 +278,7 @@ func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
func TestAuthToken_TTY_JSONMode_NoStderrHint(t *testing.T) { func TestAuthToken_TTY_JSONMode_NoStderrHint(t *testing.T) {
// --json output mode targets script/agent consumers even when stdout // --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 // 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() cfg, store := makeBearerCfg()
_, errBuf := iostreams.SetForTestWithTTY(t) _, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil { if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil {
+6 -8
View File
@@ -1,4 +1,4 @@
// Package chat implements `weknora chat <text>` — the streaming RAG answer // Package chat implements `weknora chat <text>` - the streaming RAG answer
// entry point. // entry point.
// //
// Two output modes share a single SDK call: // Two output modes share a single SDK call:
@@ -27,7 +27,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "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().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)") cmd.Flags().BoolVar(&opts.NoStream, "no-stream", false, "Buffer the full answer before printing (forces accumulate mode)")
cmdutil.AddJSONFlags(cmd, chatFields) 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 return cmd
} }
@@ -161,7 +159,7 @@ func runChat(ctx context.Context, opts *Options, jopts *cmdutil.JSONOptions, svc
streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut streamMode := iostreams.IO.IsStdoutTTY() && !opts.NoStream && !jsonOut
// Surface the auto-created session ID up-front so a user who hits ^C // 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 // past tokens. Skipped in JSON mode (it ends up in the data object) and
// when the caller already supplied --session. // when the caller already supplied --session.
if autoCreated && !jsonOut { 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 // Re-surface the auto-created session id on failure so a user who
// missed the start-of-stream notice (it scrolls past mid-stream // missed the start-of-stream notice (it scrolls past mid-stream
// tokens, especially on ^C) can still recover with --session. // 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 { if autoCreated && !jsonOut {
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID) 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") 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 // connection cleanly mid-stream. Treat as aborted so the user sees the
// truncation rather than a silent partial answer. Includes the empty-body // truncation rather than a silent partial answer. Includes the empty-body
// case (Done frame never arrived AND no content): better to surface the // 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. // model genuinely had nothing to say from the stream getting cut.
if !acc.Done() { if !acc.Done() {
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event") 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 { if jsonOut {
// Prefer the SDK-echoed session id (acc.SessionID) but fall back to // 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 sid := acc.SessionID
if sid == "" { if sid == "" {
sid = sessionID sid = sessionID
+1 -3
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
@@ -32,7 +31,7 @@ type addResult struct {
} }
// NewCmdAdd builds `weknora context add`. Registers a *credentialless* // 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 <n>`, // context are attached separately with `weknora auth login --name <n>`,
// separating "where" the CLI talks to (the host) and "how" it authenticates // separating "where" the CLI talks to (the host) and "how" it authenticates
// (the credential). If you want one command for both, run // (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)") cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)")
cmdutil.AddJSONFlags(cmd, contextAddFields) cmdutil.AddJSONFlags(cmd, contextAddFields)
_ = cmd.MarkFlagRequired("host") _ = 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 return cmd
} }
+1 -1
View File
@@ -3,7 +3,7 @@
// consistent with the rest of this CLI. // consistent with the rest of this CLI.
// //
// Package name `contextcmd` (not `context`) to avoid shadowing stdlib context. // 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 package contextcmd
import ( import (
+2 -4
View File
@@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/format"
@@ -30,7 +29,7 @@ type listEntry struct {
} }
// NewCmdList builds `weknora context list`. Per-host enumeration with an // 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 { func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "list", Use: "list",
@@ -39,7 +38,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
active context (used by subsequent commands when --context is unset) is active context (used by subsequent commands when --context is unset) is
marked with a leading "*". No network requests are issued. 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* 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*.`, the CLI can talk to; "auth list" is the catalog of *how*.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
@@ -52,7 +51,6 @@ the CLI can talk to; "auth list" is the catalog of *how*.`,
}, },
} }
cmdutil.AddJSONFlags(cmd, contextListFields) 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 return cmd
} }
+5 -7
View File
@@ -5,7 +5,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "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 Long: `Deletes the named context from config.yaml and best-effort clears any
keyring references it owned (matches ` + "`weknora auth logout`" + `). 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 <name>`" + ` or pick will error until you select another with ` + "`weknora context use <name>`" + ` or pick
one up via the global ` + "`--context`" + ` flag. Because that change is observable in one up via the global ` + "`--context`" + ` flag. Because that change is observable in
every later command, removing the current context requires explicit -y/--yes 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 Example: ` weknora context remove staging # remove non-current → no prompt
weknora context remove production -y # remove current → confirm`, weknora context remove production -y # remove current → confirm`,
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
@@ -65,7 +64,6 @@ in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`,
}, },
} }
cmdutil.AddJSONFlags(cmd, contextRemoveFields) 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 return cmd
} }
@@ -81,7 +79,7 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
wasCurrent := name == cfg.CurrentContext wasCurrent := name == cfg.CurrentContext
jsonOut := jopts.Enabled() 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`. // remove uses the same low-friction policy as `auth logout`.
if wasCurrent { if wasCurrent {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current context", name); err != nil { 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) return jopts.Emit(iostreams.IO.Out, result)
} }
if wasCurrent { if wasCurrent {
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared — run `weknora context use <name>` to pick another)\n", name) fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared - run `weknora context use <name>` to pick another)\n", name)
} else { } else {
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s\n", name) 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 // clearContextSecrets mirrors auth/logout.go: best-effort delete every secret
// slot the context references. Errors are swallowed so a missing keyring // 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) { func clearContextSecrets(store secrets.Store, c config.Context, name string) {
if c.TokenRef != "" { if c.TokenRef != "" {
_ = store.Delete(name, "access") _ = store.Delete(name, "access")
+1 -3
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config" "github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "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) 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 return cmd
} }
@@ -82,7 +80,7 @@ func notFoundError(name string, cfg *config.Config) error {
return &cmdutil.Error{ return &cmdutil.Error{
Code: cmdutil.CodeLocalContextNotFound, Code: cmdutil.CodeLocalContextNotFound,
Message: fmt.Sprintf("context not found: %s", name), 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) keys := contextKeys(cfg.Contexts)
+2 -2
View File
@@ -118,12 +118,12 @@ func TestUse_CaseSensitive(t *testing.T) {
}} }}
_ = config.Save(cfg) _ = config.Save(cfg)
err := runUse("production", nil) // lowercase — must NOT match "Production" err := runUse("production", nil) // lowercase - must NOT match "Production"
if err == nil { if err == nil {
t.Fatal("expected case-sensitive miss") t.Fatal("expected case-sensitive miss")
} }
cm := err.(*cmdutil.Error) 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") { if !strings.Contains(cm.Hint, "Production") {
t.Errorf("hint should suggest 'Production' (case-different), got %q", cm.Hint) t.Errorf("hint should suggest 'Production' (case-different), got %q", cm.Hint)
} }
-2
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt" "github.com/Tencent/WeKnora/cli/internal/prompt"
@@ -64,7 +63,6 @@ without the user's explicit go-ahead.`,
}, },
} }
cmdutil.AddJSONFlags(cmd, docDeleteFields) 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 return cmd
} }
+1 -1
View File
@@ -115,7 +115,7 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
// TestDelete_NoYes_NonTTY_RequiresConfirmation: when stdout isn't a TTY // TestDelete_NoYes_NonTTY_RequiresConfirmation: when stdout isn't a TTY
// (typical agent pipe / CI), the destructive-write protocol requires // (typical agent pipe / CI), the destructive-write protocol requires
// explicit -y/--yes. The CLI exits 10 with input.confirmation_required, // 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) { func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t) _, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{} svc := &fakeDeleteSvc{}
+1 -1
View File
@@ -5,7 +5,7 @@
// "Doc" is the CLI noun; the underlying SDK type is `Knowledge`. The renaming // "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 // 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 // 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 package doc
import ( import (
+1 -3
View File
@@ -10,7 +10,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "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().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") 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 return cmd
} }
@@ -85,7 +83,7 @@ func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService
// resolveDownloadDest returns the final destination ("-" for stdout, an // resolveDownloadDest returns the final destination ("-" for stdout, an
// absolute or relative path otherwise) after applying the --output flag // absolute or relative path otherwise) after applying the --output flag
// and sanitizing the server-suggested name. A server that returns a path- // 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. // accepted.
func resolveDownloadDest(opts *DownloadOptions, suggested string) (string, error) { func resolveDownloadDest(opts *DownloadOptions, suggested string) (string, error) {
if opts.Output == "-" { if opts.Output == "-" {
+1 -1
View File
@@ -113,7 +113,7 @@ func TestDownload_RejectsServerPathTraversal(t *testing.T) {
require.NoError(t, os.Chdir(tmp)) require.NoError(t, os.Chdir(tmp))
defer os.Chdir(prevWD) 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. // write to cwd.
svc := &fakeDownloadSvc{content: "exfil", filename: "../../etc/shadow"} svc := &fakeDownloadSvc{content: "exfil", filename: "../../etc/shadow"}
require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc")) require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc"))
+3 -5
View File
@@ -11,7 +11,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "github.com/Tencent/WeKnora/cli/internal/text"
@@ -41,7 +40,7 @@ type ListOptions struct {
} }
// docListStatusValues mirrors internal/types/knowledge.go ParseStatus* // 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 // ?parse_status= query. Kept in sync manually since the SDK doesn't
// re-export the enum. // re-export the enum.
var docListStatusValues = []string{"pending", "processing", "completed", "failed"} 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().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") cmd.Flags().StringVar(&opts.Status, "status", "", "Filter by parse status: pending | processing | completed | failed")
cmdutil.AddJSONFlags(cmd, docListFields) 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 return cmd
} }
@@ -114,7 +112,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
if opts.Status != "" && !validDocListStatus(opts.Status) { if opts.Status != "" && !validDocListStatus(opts.Status) {
return &cmdutil.Error{ return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument, 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), 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). // 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). // column. A "-" placeholder hides zero-size entries (URL / text).
func formatSize(bytes int64) string { func formatSize(bytes int64) string {
if bytes <= 0 { if bytes <= 0 {
+2 -5
View File
@@ -161,7 +161,7 @@ func TestList_KBFlagWiredToResolveKB(t *testing.T) {
} }
// With --kb=kb_<id> supplied, ResolveKB short-circuits on the prefix // With --kb=kb_<id> supplied, ResolveKB short-circuits on the prefix
// match without consulting the client. The RunE then asks for the client // 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 // Surfacing "forced-after-resolvekb" (rather than CodeKBIDRequired) is
// the proof point that --kb was honored. // the proof point that --kb was honored.
cmd := NewCmdList(f) cmd := NewCmdList(f)
@@ -292,7 +292,7 @@ func TestList_Limit_LessThanPageSize_SlicesToLimit(t *testing.T) {
opts := &ListOptions{PageSize: 20, Limit: 5} opts := &ListOptions{PageSize: 20, Limit: 5}
require.NoError(t, runList(context.Background(), opts, &cmdutil.JSONOptions{}, svc, "kb_xxx")) require.NoError(t, runList(context.Background(), opts, &cmdutil.JSONOptions{}, svc, "kb_xxx"))
body := out.String() 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_`) got := strings.Count(body, `"id":"doc_`)
assert.Equal(t, 5, got, "--limit 5 must slice 20 returned items to 5; body=\n%s", body) 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") assert.LessOrEqual(t, len(svc.calls), 3, "should not walk past the page that fills --limit")
} }
// (test removed: --page flag was dropped in v0.4 mainstream-alignment;
// --all-pages now walks unconditionally, no mutex case to test.)
+4 -4
View File
@@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" 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. has a generic name like "report.pdf" but you want to surface it as e.g.
"Q3 Marketing Report.pdf" in the UI). "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).`, Use --recursive --glob to upload a directory tree (see Examples).`,
Example: ` weknora doc upload report.pdf Example: ` weknora doc upload report.pdf
weknora doc upload notes.md --kb a32a63ff-fb36-4874-bcaa-30f48570a694 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.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") cmd.Flags().StringVar(&opts.FromURL, "from-url", "", "Ingest a remote `URL` (HTTP/HTTPS) instead of a local file")
cmdutil.AddJSONFlags(cmd, docUploadFields) 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 return cmd
} }
@@ -156,7 +156,7 @@ func runUploadFromURL(ctx context.Context, opts *UploadOptions, jopts *cmdutil.J
if errors.Is(err, sdk.ErrDuplicateURL) { if errors.Is(err, sdk.ErrDuplicateURL) {
// Server returns 409 with the existing knowledge entry's data. // Server returns 409 with the existing knowledge entry's data.
// Surface as resource.already_exists; the data payload (if any) // 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. // what agents branch on.
return cmdutil.Wrapf(cmdutil.CodeResourceAlreadyExists, err, return cmdutil.Wrapf(cmdutil.CodeResourceAlreadyExists, err,
"URL already ingested into this knowledge base") "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. // validateUploadPath checks that path exists and refers to a regular file.
// Symlinks and directories are rejected up-front so users get a typed error // 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 // 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 // `cp` / `git add` do, and the SDK opens the file via os.Open which follows
// symlinks anyway. // symlinks anyway.
func validateUploadPath(path string) error { func validateUploadPath(path string) error {
+2 -2
View File
@@ -19,7 +19,7 @@ type uploadOutcome struct {
} }
// runUploadRecursive walks dir, filters by Glob, and uploads each match // 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 // 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 // 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 // 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 // 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 // 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 { if _, err := filepath.Match(opts.Glob, ""); err != nil {
return &cmdutil.Error{ return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument, Code: cmdutil.CodeInputInvalidArgument,
+1 -1
View File
@@ -109,7 +109,7 @@ func TestUploadRecursive_PartialFailure_Exits1(t *testing.T) {
var typed *cmdutil.Error var typed *cmdutil.Error
require.ErrorAs(t, err, &typed) require.ErrorAs(t, err, &typed)
// CodeServerError preserves the 500 classification of the underlying // 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) assert.Equal(t, cmdutil.CodeServerError, typed.Code)
got := out.String() got := out.String()
-2
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "github.com/Tencent/WeKnora/cli/internal/text"
@@ -52,7 +51,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
}, },
} }
cmdutil.AddJSONFlags(cmd, docViewFields) 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 return cmd
} }
+2 -2
View File
@@ -54,7 +54,7 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
} }
} }
// A doc with no FileName falls back to Title for the NAME line — same // A doc with no FileName falls back to Title for the NAME line - same
// ordering as `doc list` (KnowledgeDisplayName precedence). // ordering as `doc list` (KnowledgeDisplayName precedence).
func TestView_Human_TitleFallback(t *testing.T) { func TestView_Human_TitleFallback(t *testing.T) {
out, _ := iostreams.SetForTest(t) out, _ := iostreams.SetForTest(t)
@@ -69,7 +69,7 @@ func TestView_Human_TitleFallback(t *testing.T) {
} }
// Optional fields (ProcessedAt nil, ErrorMessage empty, EmbeddingModelID // 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: -". // rather than printing "PROCESSED: -".
func TestView_Human_OmitsEmptyFields(t *testing.T) { func TestView_Human_OmitsEmptyFields(t *testing.T) {
out, _ := iostreams.SetForTest(t) out, _ := iostreams.SetForTest(t)
+18 -20
View File
@@ -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): // Status semantics (4-tier):
// //
// ok — passed // ok - passed
// warn — soft problem; non-blocking (e.g. server minor older than CLI, // warn - soft problem; non-blocking (e.g. server minor older than CLI,
// keychain unavailable so falling back to file store) // keychain unavailable so falling back to file store)
// fail — failed; "hint" actionable // fail - failed; "hint" actionable
// skip — cascade-skipped (prereq failed) or --offline mode // skip - cascade-skipped (prereq failed) or --offline mode
// //
// JSON output emits the Result object directly (bare data). Exit-code // JSON output emits the Result object directly (bare data). Exit-code
// signal: // signal:
@@ -28,7 +28,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/build" "github.com/Tencent/WeKnora/cli/internal/build"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/compat" "github.com/Tencent/WeKnora/cli/internal/compat"
@@ -66,7 +65,7 @@ type Check struct {
Hint string `json:"hint,omitempty"` 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 // 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 // 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.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)") 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) 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 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 // 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. // 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 // a soft problem that does not block downstream functionality. Only fail/skip
// cascades into a downstream skip. // cascades into a downstream skip.
func cascade(c *Check, offline bool, prereqs ...*Check) bool { 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"}, {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) { if !cascade(&checks[0], opts.Offline) {
t0 := time.Now() t0 := time.Now()
if err := svc.PingBaseURL(ctx); err != nil { 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 !cascade(&checks[1], opts.Offline, &checks[0]) {
if _, err := svc.GetCurrentUser(ctx); err != nil { if _, err := svc.GetCurrentUser(ctx); err != nil {
checks[1].Status = StatusFail 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]) { if !cascade(&checks[2], opts.Offline, &checks[1]) {
info, fromCache, err := loadOrProbeServerInfo(ctx, opts, svc) info, fromCache, err := loadOrProbeServerInfo(ctx, opts, svc)
if err != nil { 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]) fillCredentialStorageCheck(&checks[3])
return Result{Summary: summarize(checks), Checks: checks} return Result{Summary: summarize(checks), Checks: checks}
} }
// fillVersionCheck applies compat.Compat to (server, cli) version pair and // 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 // the loader knows authoritatively which branch it took, time-based
// derivation from ProbedAt is unreliable since SaveCache uses time.Now(). // 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 — // credStoreFactory is the seam tests use to inject a fake-store outcome -
// keyring success, file-store fallback, or hard failure — without touching // keyring success, file-store fallback, or hard failure - without touching
// the lazy-resolve buildServices contract (round-4 fix). Production stays // the lazy-resolve buildServices contract (round-4 fix). Production stays
// at secrets.NewBestEffortStore. // at secrets.NewBestEffortStore.
var credStoreFactory = func() (secrets.Store, error) { return 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 // SetCredStoreFactoryForTest overrides the credential-storage factory used by
// runChecks and returns a cleanup function that restores the previous value. // runChecks and returns a cleanup function that restores the previous value.
// Exported so out-of-package tests (notably cli/acceptance/contract) can // 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 // OS keyring, which is present on macOS dev machines but not on Linux CI
// runners without libsecret, producing host-dependent test flakes. // 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) // keyring usable → StatusOK (preferred path)
// file fallback → StatusWarn (keyring unavailable, secrets still persist // 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 // construction fails → StatusFail
// //
// Detection of "fallback to file store" relies on the type returned by // Detection of "fallback to file store" relies on the type returned by
@@ -378,7 +376,7 @@ func marker(s Status) string {
// server, not localhost. // server, not localhost.
// //
// Critically: this does NOT pre-resolve f.Client(). doctor's package promise // 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 // e.g. first-time `weknora doctor` to diagnose setup. Pre-resolving Client
// here would early-exit with auth.unauthenticated before any check runs, // here would early-exit with auth.unauthenticated before any check runs,
// contradicting the docs. Instead, GetCurrentUser / GetSystemInfo lazily // 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). // GetSystemInfo lazily resolves the SDK client (same rationale as GetCurrentUser).
// In the cascade ordering, auth_credential gates server_version, so this only // 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). // useful when only credential_storage is checkable (e.g., user not yet logged in).
func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) { func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) {
cli, err := s.f.Client() cli, err := s.f.Client()
+8 -8
View File
@@ -21,7 +21,7 @@ import (
// and would make CI flake on macOS vs Linux vs WSL). Restored in t.Cleanup. // 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 // 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). // the lazy-resolve buildServices contract unchanged (round-4 fix).
func withCredStoreFactory(t *testing.T, fn func() (secrets.Store, error)) { func withCredStoreFactory(t *testing.T, fn func() (secrets.Store, error)) {
t.Helper() t.Helper()
@@ -58,7 +58,7 @@ func TestDoctor_AllOK(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir())
out, _ := iostreams.SetForTest(t) out, _ := iostreams.SetForTest(t)
// Pin credential_storage to ok so this test doesn't probe the host OS // 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. // would otherwise warn and break the AllPassed assertion.
withCredStoreFactory(t, func() (secrets.Store, error) { withCredStoreFactory(t, func() (secrets.Store, error) {
return secrets.NewMemStore(), nil return secrets.NewMemStore(), nil
@@ -107,7 +107,7 @@ func TestDoctor_BaseURLFails_DownstreamSkip(t *testing.T) {
if r.Checks[2].Status != StatusSkip { if r.Checks[2].Status != StatusSkip {
t.Errorf("server_version status = %q, want skip", r.Checks[2].Status) 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" { if r.Checks[3].Name != "credential_storage" {
t.Errorf("Checks[3] = %q, want credential_storage", r.Checks[3].Name) 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) { func TestDoctor_VersionSkewWarns(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t) _, _ = 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. // we want this test to assert ONLY on server_version.
withCredStoreFactory(t, func() (secrets.Store, error) { return secrets.NewMemStore(), nil }) withCredStoreFactory(t, func() (secrets.Store, error) { return secrets.NewMemStore(), nil })
@@ -262,7 +262,7 @@ func TestDoctor_VersionSkewWarns(t *testing.T) {
if v.Status != StatusWarn { if v.Status != StatusWarn {
t.Errorf("server_version status = %q, want warn (server older than CLI)", v.Status) 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 // substring agents may pattern-match. Not asserting full message text
// since compat.Compat owns the wording. // since compat.Compat owns the wording.
if !strings.Contains(v.Details, "older") { if !strings.Contains(v.Details, "older") {
@@ -318,7 +318,7 @@ func TestDoctor_HardErrorStillFails(t *testing.T) {
// TestDoctor_KeychainFallbackWarns covers credential_storage's third // TestDoctor_KeychainFallbackWarns covers credential_storage's third
// state: keyring unavailable, fell back to FileStore (agent containers, // 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. // persist (0600 file perms) but the OS-backed path was unreachable.
func TestDoctor_KeychainFallbackWarns(t *testing.T) { func TestDoctor_KeychainFallbackWarns(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir()) 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 // 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". // "downgraded to file store".
func TestDoctor_CredStoreFactoryError(t *testing.T) { func TestDoctor_CredStoreFactoryError(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir()) 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. // TestDoctor_RunE_FailReturnsSilentError: warn does NOT trigger SilentError.
func TestDoctor_RunE_WarnReturnsNil(t *testing.T) { func TestDoctor_RunE_WarnReturnsNil(t *testing.T) {
t.Setenv("XDG_CACHE_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir())
+2 -4
View File
@@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
@@ -15,7 +14,7 @@ import (
// kbCreateFields enumerates the fields surfaced for `--json` discovery on // kbCreateFields enumerates the fields surfaced for `--json` discovery on
// `kb create`. The result is the full KnowledgeBase struct; these mirror its // `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. // users wanting them can drop --json (no filter) or use --jq.
var kbCreateFields = []string{ var kbCreateFields = []string{
"id", "name", "type", "description", "id", "name", "type", "description",
@@ -33,7 +32,7 @@ type CreateOptions struct {
} }
// CreateService is the narrow SDK surface this command depends on. // 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 { type CreateService interface {
CreateKnowledgeBase(ctx context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error) 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)") cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)")
cmdutil.AddJSONFlags(cmd, kbCreateFields) cmdutil.AddJSONFlags(cmd, kbCreateFields)
_ = cmd.MarkFlagRequired("name") _ = 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 return cmd
} }
+1 -3
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt" "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 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 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.`, exactly to guard against unintended deletes.`,
Example: ` weknora kb delete kb_abc # interactive confirm Example: ` weknora kb delete kb_abc # interactive confirm
weknora kb delete kb_abc -y # no prompt weknora kb delete kb_abc -y # no prompt
@@ -67,7 +66,6 @@ exactly to guard against unintended deletes.`,
}, },
} }
cmdutil.AddJSONFlags(cmd, kbDeleteFields) 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 return cmd
} }
+3 -3
View File
@@ -55,8 +55,8 @@ func TestDelete_NotFound(t *testing.T) {
} }
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) { func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
// SetForTest uses bytes.Buffer for Out — IsStdoutTTY() = false. Without // SetForTest uses bytes.Buffer for Out - IsStdoutTTY() = false. Without
// -y/--yes, exit-10 protocol fires (see AGENTS.md): the CLI must NOT // -y/--yes, exit-10 protocol fires (see cli/README.md): the CLI must NOT
// silently proceed in scripted contexts. // silently proceed in scripted contexts.
iostreams.SetForTest(t) iostreams.SetForTest(t)
svc := &fakeDeleteSvc{} svc := &fakeDeleteSvc{}
@@ -86,7 +86,7 @@ func TestDelete_JSONOutput(t *testing.T) {
} }
// The remaining tests cover the interactive confirm path which only fires // 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) { func TestDelete_ConfirmYes(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t) _, _ = iostreams.SetForTestWithTTY(t)
+5 -4
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
@@ -26,7 +25,7 @@ var kbEditFields = []string{
type EditOptions struct { type EditOptions struct {
// Name/Description are *string so we can distinguish "unset" from "set to // 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 // user passed are sent. Server PUT semantics are "replace everything in the
// request"; if we always sent both, an `--name` invocation would silently // request"; if we always sent both, an `--name` invocation would silently
// clear the description. // clear the description.
@@ -52,7 +51,10 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "edit <id>", Use: "edit <id>",
Short: "Edit a knowledge base's name or description", 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 { RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c) jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil { 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(&name, "name", "", "New name (omit to leave unchanged)")
cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)") cmd.Flags().StringVar(&desc, "description", "", "New description (omit to leave unchanged)")
cmdutil.AddJSONFlags(cmd, kbEditFields) 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 return cmd
} }
+1 -1
View File
@@ -104,7 +104,7 @@ func TestEdit_BothFlags(t *testing.T) {
func TestEdit_NotFound(t *testing.T) { func TestEdit_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t) _, _ = iostreams.SetForTest(t)
// 404 must come from the GetKnowledgeBase pre-fetch in the fetch-then- // 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")} svc := &fakeEditSvc{currentErr: errors.New("HTTP error 404: not found")}
opts := &EditOptions{} opts := &EditOptions{}
opts.Name = stringPtr("x") opts.Name = stringPtr("x")
-2
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt" "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) 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 return cmd
} }
+3 -4
View File
@@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "github.com/Tencent/WeKnora/cli/internal/text"
@@ -18,7 +17,7 @@ import (
// kbListFields enumerates the fields surfaced for `--json` discovery on // kbListFields enumerates the fields surfaced for `--json` discovery on
// `kb list`. Nested config structs (chunking / image / FAQ / VLM / storage // `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. // against the full object.
var kbListFields = []string{ var kbListFields = []string{
"id", "name", "type", "description", "id", "name", "type", "description",
@@ -49,6 +48,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "list", Use: "list",
Short: "List knowledge bases visible to the active context", 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, Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error { RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c) 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().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)") cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return (0 = no cap, 1..10000 = explicit)")
cmdutil.AddJSONFlags(cmd, kbListFields) 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 return cmd
} }
@@ -92,7 +91,7 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
} }
items = filtered 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 // guaranteed, so client-side sort makes output deterministic regardless
// of backend storage choices. // of backend storage choices.
sort.Slice(items, func(i, j int) bool { sort.Slice(items, func(i, j int) bool {
+2 -3
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
@@ -20,7 +19,7 @@ var kbPinFields = []string{"id", "is_pinned"}
type PinOptions struct{} type PinOptions struct{}
// PinService is the narrow SDK surface this command depends on. The CLI // 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. // the server endpoint is only a non-idempotent toggle.
type PinService interface { type PinService interface {
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error) 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{ cmd := &cobra.Command{
Use: use + " <id>", Use: use + " <id>",
Short: short, 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), Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c) 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) 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 return cmd
} }
+1 -2
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "github.com/Tencent/WeKnora/cli/internal/text"
@@ -38,6 +37,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "view <id>", Use: "view <id>",
Short: "Show a knowledge base by ID", 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), Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c) jopts, err := cmdutil.CheckJSONFlags(c)
@@ -52,7 +52,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
}, },
} }
cmdutil.AddJSONFlags(cmd, kbViewFields) cmdutil.AddJSONFlags(cmd, kbViewFields)
aiclient.SetAgentHelp(cmd, "Returns details of one knowledge base by ID (config + counts).")
return cmd return cmd
} }
+3 -5
View File
@@ -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 // directory to a knowledge base by writing .weknora/project.yaml. Always
// overwrites an existing link silently rather than refusing when one is // overwrites an existing link silently rather than refusing when one is
// already present. The cobra Long: text covers the user-facing modes // already present. The cobra Long: text covers the user-facing modes
@@ -14,7 +14,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/projectlink" "github.com/Tencent/WeKnora/cli/internal/projectlink"
@@ -49,7 +48,7 @@ overridden by the --kb flag or WEKNORA_KB_ID env var.
Pass --kb <id-or-name> for non-interactive use (scripts, CI). Run on a TTY Pass --kb <id-or-name> for non-interactive use (scripts, CI). Run on a TTY
without --kb to be prompted from the list of available KBs. Always overwrites 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 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.`, 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") cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name; omit on a TTY for interactive prompt")
cmdutil.AddJSONFlags(cmd, linkFields) 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 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 // 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 // different context, use the global persistent flag (`weknora --context
// staging link --kb my-kb`); the active context at link time is what gets // staging link --kb my-kb`); the active context at link time is what gets
// written. // written.
-2
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/projectlink" "github.com/Tencent/WeKnora/cli/internal/projectlink"
@@ -49,7 +48,6 @@ is present anywhere in the parent chain.`,
}, },
} }
cmdutil.AddJSONFlags(cmd, unlinkFields) 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 return cmd
} }
+1 -1
View File
@@ -29,7 +29,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
Initial tool surface is read-only and curated: kb_list / kb_view / Initial tool surface is read-only and curated: kb_list / kb_view /
doc_list / doc_view / doc_download / search_chunks / chat / agent_list / doc_list / doc_view / doc_download / search_chunks / chat / agent_list /
agent_invoke. Destructive verbs (create / delete / upload) are deliberately 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.`, exit-10 protocol covers that path.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() }, Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
+12 -9
View File
@@ -3,13 +3,12 @@ package mcpcmd
import ( import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
mcpserver "github.com/Tencent/WeKnora/cli/internal/mcp" mcpserver "github.com/Tencent/WeKnora/cli/internal/mcp"
) )
// NewCmdServe builds `weknora mcp serve`. Currently stdio-only; HTTP // 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 { func NewCmdServe(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "serve", Use: "serve",
@@ -18,19 +17,24 @@ func NewCmdServe(f *cmdutil.Factory) *cobra.Command {
stderr; the data channel is reserved for protocol traffic. stderr; the data channel is reserved for protocol traffic.
Authentication is inherited from the active context (or --context). The 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 configured, the process exits with auth.unauthenticated before any MCP
handshake. This way an IDE-side agent sees a clear failure mode rather handshake. This way an IDE-side agent sees a clear failure mode rather
than a server that handshakes successfully then errors on every tool. 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": { "mcpServers": {
"command": "weknora", "weknora": {
"args": ["mcp", "serve"] "command": "weknora",
"args": ["mcp", "serve"]
}
} }
}`, }
Consult your MCP client's documentation for the exact config-file location.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error { RunE: func(c *cobra.Command, _ []string) error {
// Eagerly construct the SDK client. Surfaces auth / // 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) 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 return cmd
} }
+7 -29
View File
@@ -19,7 +19,6 @@ import (
mcpcmd "github.com/Tencent/WeKnora/cli/cmd/mcp" mcpcmd "github.com/Tencent/WeKnora/cli/cmd/mcp"
"github.com/Tencent/WeKnora/cli/cmd/search" "github.com/Tencent/WeKnora/cli/cmd/search"
sessioncmd "github.com/Tencent/WeKnora/cli/cmd/session" 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/build"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format" "github.com/Tencent/WeKnora/cli/internal/format"
@@ -35,8 +34,9 @@ func Execute() int {
// downstream `--json | jq` pipelines never filter error shapes // downstream `--json | jq` pipelines never filter error shapes
// out of the success stream. The typed exit code (3/4/5/6/7/10) // out of the success stream. The typed exit code (3/4/5/6/7/10)
// carries the error class. // carries the error class.
cmdutil.PrintError(iostreams.IO.Err, MapCobraError(err)) mapped := MapCobraError(err)
return cmdutil.ExitCode(MapCobraError(err)) cmdutil.PrintError(iostreams.IO.Err, mapped)
return cmdutil.ExitCode(mapped)
} }
return 0 return 0
} }
@@ -70,7 +70,7 @@ func MapCobraError(err error) error {
var cobraFlagErrorPrefixes = []string{ var cobraFlagErrorPrefixes = []string{
"unknown command ", "unknown command ",
"required flag(s)", "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 least", // MinimumNArgs
"requires at most", // MaximumNArgs "requires at most", // MaximumNArgs
"unknown flag", "unknown flag",
@@ -84,7 +84,7 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
v, commit, date := build.Info() v, commit, date := build.Info()
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "weknora", 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 Long: `WeKnora CLI lets you authenticate, browse knowledge bases, and run
hybrid searches against a WeKnora server from your shell or an AI agent.`, 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 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), Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
PersistentPreRun: func(c *cobra.Command, args []string) { PersistentPreRun: func(c *cobra.Command, args []string) {
// Propagate the global --context flag into the Factory for this // 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 != "" { if v, _ := c.Flags().GetString("context"); v != "" {
f.ContextOverride = 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. // Match `weknora version` line format so both forms output the same.
cmd.SetVersionTemplate("weknora {{.Version}}\n") cmd.SetVersionTemplate("weknora {{.Version}}\n")
addGlobalFlags(cmd) addGlobalFlags(cmd)
cmd.SetHelpFunc(agentAwareHelpFunc(cmd.HelpFunc()))
// Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps // Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps
// them to exit 2. "unknown command" errors are detected by message prefix // them to exit 2. "unknown command" errors are detected by message prefix
// in Execute() since cobra emits them as plain errors. // 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. // 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. // accepts values but does nothing is a worse contract than no flag.
func addGlobalFlags(cmd *cobra.Command) { func addGlobalFlags(cmd *cobra.Command) {
pf := cmd.PersistentFlags() 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)") 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 // versionFields enumerates the fields surfaced for `--json` discovery on
// `version`. Mirrors the version object payload. // `version`. Mirrors the version object payload.
var versionFields = []string{"version", "commit", "date"} var versionFields = []string{"version", "commit", "date"}
+3 -3
View File
@@ -63,7 +63,7 @@ func TestMapCobraError_PinnedPrefixes(t *testing.T) {
}) })
t.Run("required flag(s)", func(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 // register their own required flags. RunE is required: without it cobra
// treats the command as a parent and skips ValidateRequiredFlags. // treats the command as a parent and skips ValidateRequiredFlags.
probe := &cobra.Command{Use: "probe", RunE: func(*cobra.Command, []string) error { return nil }} 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()) "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{ probe := &cobra.Command{
Use: "probe", Use: "probe",
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
@@ -115,7 +115,7 @@ func TestMapCobraError(t *testing.T) {
// TestRoot_ContextFlagPropagation guards the cobra → Factory wiring of the // TestRoot_ContextFlagPropagation guards the cobra → Factory wiring of the
// global --context flag. Without this, a future refactor that disconnects // 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. // per-package TestFactory_ContextOverride only proves the Factory side.
func TestRoot_ContextFlagPropagation(t *testing.T) { func TestRoot_ContextFlagPropagation(t *testing.T) {
cases := []struct { cases := []struct {
+7 -6
View File
@@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
@@ -44,7 +43,7 @@ type ChunksService interface {
// Uses a positional query argument with the KB selected via flag. // Uses a positional query argument with the KB selected via flag.
// //
// The `--kb` flag accepts either a KB UUID (passed through unchanged) or a // 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 { func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
opts := &ChunksOptions{} opts := &ChunksOptions{}
cmd := &cobra.Command{ cmd := &cobra.Command{
@@ -53,6 +52,9 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
Example: ` weknora search chunks "what is RAG?" --kb engineering Example: ` weknora search chunks "what is RAG?" --kb engineering
weknora search chunks "embedding model" --kb kb_abc --limit 20 weknora search chunks "embedding model" --kb kb_abc --limit 20
weknora search chunks "k8s" --kb engineering --no-keyword # vector-only`, 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), Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
opts.Query = strings.TrimSpace(args[0]) opts.Query = strings.TrimSpace(args[0])
@@ -80,7 +82,6 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
} }
bindChunksFlags(cmd, opts) bindChunksFlags(cmd, opts)
_ = cmd.MarkFlagRequired("kb") _ = 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 return cmd
} }
@@ -88,7 +89,7 @@ func NewCmdChunks(f *cmdutil.Factory) *cobra.Command {
// the constructor readable; --kb is marked required by the caller. // the constructor readable; --kb is marked required by the caller.
func bindChunksFlags(cmd *cobra.Command, opts *ChunksOptions) { func bindChunksFlags(cmd *cobra.Command, opts *ChunksOptions) {
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name") cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name")
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.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().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") 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 { if err != nil {
return cmdutil.WrapHTTP(err, "hybrid search") 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 // service appends parent / nearby / relation chunks as context
// enrichment, so the wire response can exceed Limit. Treat --limit as // enrichment, so the wire response can exceed Limit. Treat --limit as
// a hard return-count cap by trimming on the client. Recall isn't // 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) 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 // richer tabular renderer can replace this later without breaking the
// JSON contract. // JSON contract.
func renderChunkResults(results []*sdk.SearchResult, kbID string) error { func renderChunkResults(results []*sdk.SearchResult, kbID string) error {
+1 -1
View File
@@ -46,7 +46,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
// JSON output must surface match_type so machine consumers / agents can // JSON output must surface match_type so machine consumers / agents can
// reason about retrieval channels without re-implementing the wire format. // 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) { func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
out, _ := iostreams.SetForTest(t) out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: []*sdk.SearchResult{ svc := &fakeChunksSvc{results: []*sdk.SearchResult{
+3 -2
View File
@@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "github.com/Tencent/WeKnora/cli/internal/text"
@@ -54,6 +53,9 @@ func NewCmdDocs(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: `docs "<query>"`, Use: `docs "<query>"`,
Short: "Find documents in a knowledge base by name (client-side substring match)", 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 Example: ` weknora search docs "Q3 forecast" --kb finance
weknora search docs "spec" --kb engineering --limit 5`, weknora search docs "spec" --kb engineering --limit 5`,
Args: cobra.ExactArgs(1), 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") cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
cmdutil.AddJSONFlags(cmd, docsFields) cmdutil.AddJSONFlags(cmd, docsFields)
_ = cmd.MarkFlagRequired("kb") _ = 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 return cmd
} }
+7 -3
View File
@@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "github.com/Tencent/WeKnora/cli/internal/text"
@@ -39,7 +38,7 @@ type KBSearchService interface {
ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error) ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error)
} }
// NewCmdKB builds `weknora search kb "<query>"` — substring + case-insensitive // NewCmdKB builds `weknora search kb "<query>"` - substring + case-insensitive
// match across KB names and descriptions visible to the active context. // match across KB names and descriptions visible to the active context.
// Results are sorted by name length (shortest first; usually the closest // Results are sorted by name length (shortest first; usually the closest
// hit) for deterministic output. // hit) for deterministic output.
@@ -48,6 +47,12 @@ func NewCmdKB(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: `kb "<query>"`, Use: `kb "<query>"`,
Short: "Find knowledge bases by name or description (client-side substring match)", 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" Example: ` weknora search kb "marketing"
weknora search kb "team" --limit 5 --json`, weknora search kb "team" --limit 5 --json`,
Args: cobra.ExactArgs(1), 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") cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
cmdutil.AddJSONFlags(cmd, kbSearchFields) 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 return cmd
} }
+1 -3
View File
@@ -5,12 +5,11 @@ package search
import ( import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
) )
// NewCmdSearch builds the `weknora search` parent. Pure dispatcher to the // 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 { func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "search", Use: "search",
@@ -28,7 +27,6 @@ func NewCmdSearch(f *cmdutil.Factory) *cobra.Command {
Args: cobra.NoArgs, Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() }, Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
} }
aiclient.SetAgentHelp(cmd, "Search parent. Use `search chunks/kb/docs/sessions <q>` — there is no bare-positional form.")
cmd.AddCommand(NewCmdChunks(f)) cmd.AddCommand(NewCmdChunks(f))
cmd.AddCommand(NewCmdKB(f)) cmd.AddCommand(NewCmdKB(f))
+2 -3
View File
@@ -20,9 +20,8 @@ func TestSearch_NoArgs_ShowsHelp(t *testing.T) {
require.NoError(t, cmd.Execute()) require.NoError(t, cmd.Execute())
} }
// TestSearch_RejectsPositional: bare positional (e.g. the v0.0-style // TestSearch_RejectsPositional: bare positional `weknora search "<q>" --kb X`
// `weknora search "<q>" --kb X`) must error — the legacy alias was // must error - search is a pure dispatcher with no shortcut form.
// dropped, search is now pure dispatcher.
func TestSearch_RejectsPositional(t *testing.T) { func TestSearch_RejectsPositional(t *testing.T) {
_, _ = iostreams.SetForTest(t) _, _ = iostreams.SetForTest(t)
cmd := NewCmdSearch(&cmdutil.Factory{}) cmd := NewCmdSearch(&cmdutil.Factory{})
+1 -3
View File
@@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "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") cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return")
cmdutil.AddJSONFlags(cmd, sessionsSearchFields) 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 return cmd
} }
@@ -124,7 +122,7 @@ func matchSession(s sdk.Session, needle string) bool {
} }
// sortSessionsByRecency sorts in place by UpdatedAt desc. Server returns // 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 // way, and a stable order is enough for output determinism even if a
// non-conforming string slips through. // non-conforming string slips through.
func sortSessionsByRecency(items []sdk.Session) { func sortSessionsByRecency(items []sdk.Session) {
-2
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt" "github.com/Tencent/WeKnora/cli/internal/prompt"
@@ -64,7 +63,6 @@ without the user's explicit go-ahead.`,
}, },
} }
cmdutil.AddJSONFlags(cmd, sessionDeleteFields) 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 return cmd
} }
+1 -3
View File
@@ -10,7 +10,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text" "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().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)") cmd.Flags().StringVar(&opts.Since, "since", "", "Only show sessions updated within `duration` (e.g. 7d, 24h, 30m)")
cmdutil.AddJSONFlags(cmd, sessionListFields) 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 return cmd
} }
@@ -196,7 +194,7 @@ func parseSinceDuration(s string) (time.Duration, error) {
} }
// fuzzyTime renders a server-provided timestamp string in "2d ago" form. // 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 "-". // format than to silently render "-".
func fuzzyTime(now time.Time, ts string) string { func fuzzyTime(now time.Time, ts string) string {
if ts == "" { if ts == "" {
-2
View File
@@ -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") 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.)
+1 -1
View File
@@ -3,7 +3,7 @@
// //
// Package name `sessioncmd` (not `session`) so callers can `import sdk // Package name `sessioncmd` (not `session`) so callers can `import sdk
// "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without // "github.com/Tencent/WeKnora/client"` and use `sdk.Session` without
// shadowing — same hygiene as `contextcmd`. // shadowing - same hygiene as `contextcmd`.
package sessioncmd package sessioncmd
import ( import (
-2
View File
@@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/aiclient"
"github.com/Tencent/WeKnora/cli/internal/cmdutil" "github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams" "github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client" sdk "github.com/Tencent/WeKnora/client"
@@ -49,7 +48,6 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
}, },
} }
cmdutil.AddJSONFlags(cmd, sessionViewFields) 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 return cmd
} }
-35
View File
@@ -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)
}
-38
View File
@@ -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 ""
}
-62
View File
@@ -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())
})
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ type Refresher interface {
// retry the original request). // retry the original request).
// //
// Single canonical implementation shared by `weknora auth refresh` and the // 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. // six-step sequence with subtly diverging error wording.
func RefreshAndPersist(ctx context.Context, store secrets.Store, refresher Refresher, ctxName string) (string, error) { func RefreshAndPersist(ctx context.Context, store secrets.Store, refresher Refresher, ctxName string) (string, error) {
refresh, err := store.Get(ctxName, "refresh") refresh, err := store.Get(ctxName, "refresh")
+3 -3
View File
@@ -21,7 +21,7 @@ import (
// - 401 on /api/v1/auth/login or /api/v1/auth/refresh: pass through // - 401 on /api/v1/auth/login or /api/v1/auth/refresh: pass through
// (otherwise a stale refresh token causes infinite recursion). // (otherwise a stale refresh token causes infinite recursion).
// - 401 with no initial token configured (api-key contexts): pass through // - 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 // - 401 with non-replayable request body (req.GetBody == nil): pass
// through. The SDK always uses bytes.Buffer bodies; this is a safety // through. The SDK always uses bytes.Buffer bodies; this is a safety
// net for hand-built requests. // net for hand-built requests.
@@ -31,7 +31,7 @@ import (
// the updated currentToken and replay without re-refreshing (singleflight). // the updated currentToken and replay without re-refreshing (singleflight).
// //
// The transport intentionally shadows the SDK's bearerToken (set via // 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 transport's per-request override is the single source of truth for
// the Authorization header. Tokens persisted to the secrets store happen // the Authorization header. Tokens persisted to the secrets store happen
// inside refreshFn (see cmdutil.RefreshAndPersist). // inside refreshFn (see cmdutil.RefreshAndPersist).
@@ -49,7 +49,7 @@ type AuthRetryTransport struct {
// //
// Pass an empty initialToken to indicate "no bearer credential configured" // Pass an empty initialToken to indicate "no bearer credential configured"
// (e.g. an api-key context). In that mode the transport never invokes // (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 { func NewAuthRetryTransport(base http.RoundTripper, initialToken string, refreshFn func(context.Context) (string, error)) *AuthRetryTransport {
if base == nil { if base == nil {
base = http.DefaultTransport base = http.DefaultTransport
+2 -2
View File
@@ -172,7 +172,7 @@ func TestAuthRetry_SkipAuthEndpoints(t *testing.T) {
func TestAuthRetry_NoTokenConfigured_DoesNotInjectAuthz(t *testing.T) { func TestAuthRetry_NoTokenConfigured_DoesNotInjectAuthz(t *testing.T) {
// API-key contexts construct the transport with an empty initial token; // API-key contexts construct the transport with an empty initial token;
// authretry should pass through 401s untouched (no refresh callback exists // 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, "")}} base := &stubTransport{t: t, resps: []*http.Response{resp(401, "")}}
refreshed := false refreshed := false
rt := NewAuthRetryTransport(base, "", func(context.Context) (string, error) { 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) { func TestAuthRetry_ConcurrentRefresh_SingleFlight(t *testing.T) {
// 4 parallel 401s should trigger exactly 1 refresh; all 4 then retry with // 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 // 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 // scripted responses, ordering matters. To keep determinism, build a
// transport that always returns 401 on first call per request, 200 on // transport that always returns 401 on first call per request, 200 on
// second, and gate the refresh callback. // second, and gate the refresh callback.
+1 -1
View File
@@ -21,7 +21,7 @@ import (
// //
// The non-TTY branch is the destructive-write protocol: high-risk writes // The non-TTY branch is the destructive-write protocol: high-risk writes
// always require explicit confirmation in scripted contexts, never silent // 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. // `yes` should be sourced from the persistent global -y/--yes flag.
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error { func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error {
+8 -8
View File
@@ -15,7 +15,7 @@ import (
type ErrorCode string type ErrorCode string
const ( const (
// auth.* — authentication / permission // auth.* - authentication / permission
CodeAuthUnauthenticated ErrorCode = "auth.unauthenticated" CodeAuthUnauthenticated ErrorCode = "auth.unauthenticated"
CodeAuthTokenExpired ErrorCode = "auth.token_expired" CodeAuthTokenExpired ErrorCode = "auth.token_expired"
CodeAuthBadCredential ErrorCode = "auth.bad_credential" CodeAuthBadCredential ErrorCode = "auth.bad_credential"
@@ -28,12 +28,12 @@ const (
CodeResourceAlreadyExists ErrorCode = "resource.already_exists" CodeResourceAlreadyExists ErrorCode = "resource.already_exists"
CodeResourceLocked ErrorCode = "resource.locked" CodeResourceLocked ErrorCode = "resource.locked"
// input.* — flag and argument validation // input.* - flag and argument validation
CodeInputInvalidArgument ErrorCode = "input.invalid_argument" CodeInputInvalidArgument ErrorCode = "input.invalid_argument"
CodeInputMissingFlag ErrorCode = "input.missing_flag" CodeInputMissingFlag ErrorCode = "input.missing_flag"
// CodeInputConfirmationRequired marks a high-risk write that has no // CodeInputConfirmationRequired marks a high-risk write that has no
// interactive UI (non-TTY or --json) and was invoked without -y/--yes. // 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 // error to the user and only retry with -y after explicit human
// approval; never auto-retry. // approval; never auto-retry.
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required" CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
@@ -49,13 +49,13 @@ const (
// server.error so agents can retry with their own --session. // server.error so agents can retry with their own --session.
CodeSessionCreateFailed ErrorCode = "server.session_create_failed" 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" CodeLocalConfigCorrupt ErrorCode = "local.config_corrupt"
CodeLocalKeychainDenied ErrorCode = "local.keychain_denied" CodeLocalKeychainDenied ErrorCode = "local.keychain_denied"
CodeLocalFileIO ErrorCode = "local.file_io" CodeLocalFileIO ErrorCode = "local.file_io"
CodeLocalUnimplemented ErrorCode = "local.unimplemented" CodeLocalUnimplemented ErrorCode = "local.unimplemented"
CodeLocalContextNotFound ErrorCode = "local.context_not_found" 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" CodeKBIDRequired ErrorCode = "local.kb_id_required"
CodeKBNotFound ErrorCode = "local.kb_not_found" CodeKBNotFound ErrorCode = "local.kb_not_found"
CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt" 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, // from its HTTP shape (404 → resource.not_found, 401 → auth.unauthenticated,
// non-HTTP → network.error, …). Shortcut for the universal pattern // non-HTTP → network.error, …). Shortcut for the universal pattern
// `Wrapf(ClassifyHTTPError(err), err, format, args...)` used by every SDK // `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 // Use this for any error returned from a wire call. Stays paired with
// ClassifyHTTPErrorOutputs() in the acceptance/contract test, which // 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). // CancelError marks a user-cancelled operation (Ctrl-C / "no" at confirm).
var CancelError = errors.New("operation cancelled") 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. // They walk the error chain so wrapped errors still match.
// IsAuthError matches any auth.* code. // IsAuthError matches any auth.* code.
@@ -285,6 +285,6 @@ func ClassifyHTTPErrorOutputs() []ErrorCode {
CodeServerRateLimited, // 429 CodeServerRateLimited, // 429
CodeServerError, // 5xx / parse-failure / default CodeServerError, // 5xx / parse-failure / default
CodeInputInvalidArgument, // 4xx (else) CodeInputInvalidArgument, // 4xx (else)
CodeNetworkError, // 非 HTTP error CodeNetworkError, // non-HTTP error
} }
} }
+1 -1
View File
@@ -11,7 +11,7 @@ func TestAllCodes_NonEmpty(t *testing.T) {
if len(codes) == 0 { if len(codes) == 0 {
t.Fatal("AllCodes() should return registered codes") 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{ want := map[cmdutil.ErrorCode]bool{
cmdutil.CodeAuthUnauthenticated: false, cmdutil.CodeAuthUnauthenticated: false,
cmdutil.CodeResourceNotFound: false, cmdutil.CodeResourceNotFound: false,
+6 -6
View File
@@ -6,9 +6,9 @@ import (
"io" "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 // - 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 / // resource.locked, local.* (config_corrupt / keychain_denied / file_io /
// context_not_found / kb_id_required / kb_not_found / projectlink_corrupt / // context_not_found / kb_id_required / kb_not_found / projectlink_corrupt /
// user_aborted / upload_file_not_found), mcp.*, server.session_create_failed, // user_aborted / upload_file_not_found), mcp.*, server.session_create_failed,
@@ -19,8 +19,8 @@ import (
// - 5 input.* (other than confirmation_required) // - 5 input.* (other than confirmation_required)
// - 6 server.rate_limited // - 6 server.rate_limited
// - 7 server.* (other than rate_limited/session_create_failed) / network.* // - 7 server.* (other than rate_limited/session_create_failed) / network.*
// - 10 input.confirmation_required — high-risk write needs explicit -y // - 10 input.confirmation_required - high-risk write needs explicit -y
// (see cli/AGENTS.md) // (see cli/README.md)
// - 130 SIGINT (handled by Go runtime, not this function) // - 130 SIGINT (handled by Go runtime, not this function)
func ExitCode(err error) int { func ExitCode(err error) int {
if err == nil { if err == nil {
@@ -77,7 +77,7 @@ func PrintError(w io.Writer, err error) {
// defaultHint returns a canonical actionable hint for known error codes // defaultHint returns a canonical actionable hint for known error codes
// when the call site didn't set one. `auth.unauthenticated` always points // 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. // list / kb view / search) without per-command hint plumbing.
// //
// Empty string for codes without a stable canonical hint. // Empty string for codes without a stable canonical hint.
@@ -104,7 +104,7 @@ func defaultHint(code ErrorCode) string {
case CodeInputInvalidArgument, CodeInputMissingFlag: case CodeInputInvalidArgument, CodeInputMissingFlag:
return "see `weknora <command> --help` for valid usage" return "see `weknora <command> --help` for valid usage"
case CodeInputConfirmationRequired: 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: case CodeLocalKeychainDenied:
return "verify keyring access; falls back to file storage" return "verify keyring access; falls back to file storage"
case CodeLocalConfigCorrupt: case CodeLocalConfigCorrupt:
+11 -13
View File
@@ -22,7 +22,7 @@ import (
// closure is lazy: --help / completion / `weknora version` must NOT trigger // closure is lazy: --help / completion / `weknora version` must NOT trigger
// HTTP, keyring access, or filesystem I/O beyond the bare minimum. // 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) // - Config: parses ~/.config/weknora/config.yaml (no network)
// - Client: constructs the SDK client; only Secrets is sync.Once-cached, // - Client: constructs the SDK client; only Secrets is sync.Once-cached,
// so callers should hold the returned *sdk.Client across // so callers should hold the returned *sdk.Client across
@@ -33,13 +33,13 @@ import (
// would fork+exec on macOS and DBus-touch on Linux, // would fork+exec on macOS and DBus-touch on Linux,
// defeating the lazy contract above). // 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 // iostreams.IO. The bar to add a new closure is at least 2 commands sharing the
// same dependency; resist factory bloat. // same dependency; resist factory bloat.
// //
// Client returns a *sdk.Client (the WeKnora SDK). Commands that want narrow // 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 // service interfaces declare them in their own files and let the real SDK
// real SDK satisfy them implicitly via duck typing. // satisfy them implicitly via duck typing.
type Factory struct { type Factory struct {
Config func() (*config.Config, error) Config func() (*config.Config, error)
Client func() (*sdk.Client, error) Client func() (*sdk.Client, error)
@@ -47,9 +47,8 @@ type Factory struct {
Secrets func() (secrets.Store, error) Secrets func() (secrets.Store, error)
// ContextOverride, if non-empty, replaces config.CurrentContext for this // ContextOverride, if non-empty, replaces config.CurrentContext for this
// invocation only — set by the global --context flag in PersistentPreRun. // invocation only - set by the global --context flag in PersistentPreRun.
// Buildable Config() / Client() honor it without writing to disk; matches // Buildable Config() / Client() honor it without writing to disk.
// spec §1.2 "weknora --context foo kb list = single-shot override".
ContextOverride string ContextOverride string
} }
@@ -59,7 +58,7 @@ type Factory struct {
// none of them. Client and Secrets closures memoize via sync.Once so the // 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, // SDK client is built (and the keyring is probed) at most once per process,
// even when Factory.ResolveKB internally calls f.Client() before the // 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 // would build two clients with two AuthRetryTransports holding independent
// token state. // token state.
func New() *Factory { 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 // 401-retry transport: on the first 401 from a non-/auth/* endpoint, the
// transport reads the stored refresh token, calls /api/v1/auth/refresh, // transport reads the stored refresh token, calls /api/v1/auth/refresh,
// persists the new pair, and replays the original request with the new // 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. // them propagates as auth.unauthenticated for the caller to handle.
if ctx.TokenRef != "" && ctx.RefreshRef != "" { if ctx.TokenRef != "" && ctx.RefreshRef != "" {
refreshFn := func(rctx context.Context) (string, error) { 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 // tenant from the credential itself (JWT claim or API key prefix); the
// header is only meaningful for explicit cross-tenant switching by users // header is only meaningful for explicit cross-tenant switching by users
// with CanAccessAllTenants. Auto-mirroring the persisted tenant from config // with CanAccessAllTenants. Auto-mirroring the persisted tenant from config
// breaks that contract — explicit flags (`--tenant=N` is the planned v0.1 // breaks that contract - explicit cross-tenant flags would be required
// entry point) are required before sending it. `tenant_id` stays in config // before sending it. `tenant_id` stays in config for `auth status` display only.
// for `auth status` display only.
return sdk.NewClient(ctx.Host, opts...), nil 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 // refreshAccessToken is the closure target injected into AuthRetryTransport's
// refreshFn. A fresh SDK Client is built here rather than reusing the one // 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 // would recurse on refresh. The refresh endpoint is unauthenticated apart
// from the refresh token in the body, so no credential options are needed. // 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) { func refreshAccessToken(ctx context.Context, store secrets.Store, host, ctxName string) (string, error) {
+5 -5
View File
@@ -22,7 +22,7 @@ import (
) )
// TestFactory_Lazy ensures none of the closures execute work at construction // 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) { func TestFactory_Lazy(t *testing.T) {
var configCalls, clientCalls, prompterCalls int var configCalls, clientCalls, prompterCalls int
f := &Factory{ f := &Factory{
@@ -39,7 +39,7 @@ func TestFactory_Lazy(t *testing.T) {
return prompt.AgentPrompter{} 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, configCalls)
assert.Equal(t, 0, clientCalls) assert.Equal(t, 0, clientCalls)
assert.Equal(t, 0, prompterCalls) assert.Equal(t, 0, prompterCalls)
@@ -74,7 +74,7 @@ func TestNew_FoundationDefaults(t *testing.T) {
// TestFactory_ContextOverride verifies the global --context flag mechanism: // TestFactory_ContextOverride verifies the global --context flag mechanism:
// f.ContextOverride replaces config.CurrentContext for this invocation only, // 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) { func TestFactory_ContextOverride(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir) t.Setenv("XDG_CONFIG_HOME", dir)
@@ -234,7 +234,7 @@ func TestBuildClient_HappyPath(t *testing.T) {
func TestBuildClient_SkipsUnreferencedSecrets(t *testing.T) { func TestBuildClient_SkipsUnreferencedSecrets(t *testing.T) {
// If the context doesn't list APIKeyRef, buildClient must not call // 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()} store := &countingSecrets{MemStore: secrets.NewMemStore()}
require.NoError(t, store.Set("p", "access", "jwt")) require.NoError(t, store.Set("p", "access", "jwt"))
f := &Factory{ f := &Factory{
@@ -310,7 +310,7 @@ func TestResolveKB_Chain(t *testing.T) {
t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose") t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose")
dir := t.TempDir() dir := t.TempDir()
resolveKBChdir(t, dir) 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"})) require.NoError(t, projectlink.Save(filepath.Join(dir, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"}))
clientCalls := 0 clientCalls := 0
+2 -2
View File
@@ -7,7 +7,7 @@ import (
) )
// NormalizeHost validates and canonicalizes a `--host` value. Trailing // 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 // 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). // (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, // ValidateHTTPURL applies the same http/https URL rules NormalizeHost uses,
// but parameterized by flagLabel so error messages name the caller's flag // but parameterized by flagLabel so error messages name the caller's flag
// (e.g. "--host", "--from-url"). Returns CodeInputInvalidArgument on any // (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. // "missing" from "malformed" should test for empty before calling.
func ValidateHTTPURL(flagLabel, value string) error { func ValidateHTTPURL(flagLabel, value string) error {
u, err := url.Parse(value) u, err := url.Parse(value)
+1 -1
View File
@@ -118,7 +118,7 @@ func TestAddJSONFlags_JQWithoutJSON(t *testing.T) {
if err.Error() != want { if err.Error() != want {
t.Errorf("wrong message.\nwant: %q\ngot: %q", want, err.Error()) 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. // code stays 1, not 2.
var fe *cmdutil.FlagError var fe *cmdutil.FlagError
if errors.As(err, &fe) { if errors.As(err, &fe) {
+1 -1
View File
@@ -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. // 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. // policy (currently exact case-sensitive) lives in one place.
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) { func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
kbs, err := lister.ListKnowledgeBases(ctx) kbs, err := lister.ListKnowledgeBases(ctx)
+1 -1
View File
@@ -20,7 +20,7 @@ func cachePath() (string, error) {
// LoadCache reads the cached Info. Returns (info, fresh, err). // LoadCache reads the cached Info. Returns (info, fresh, err).
// //
// info == nil when no cache exists (err == nil) // 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) { func LoadCache() (*Info, bool, error) {
p, err := cachePath() p, err := cachePath()
if err != nil { if err != nil {
+1 -1
View File
@@ -28,7 +28,7 @@ func TestCache_RoundTrip(t *testing.T) {
t.Errorf("ServerVersion = %v, want %q", got, want.ServerVersion) 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") p := filepath.Join(dir, "weknora", "server-info.yaml")
if _, err := filepath.Abs(p); err != nil { if _, err := filepath.Abs(p); err != nil {
t.Errorf("path resolution: %v", err) t.Errorf("path resolution: %v", err)
+13 -13
View File
@@ -10,9 +10,9 @@ import (
type Level int type Level int
const ( const (
OK Level = iota // 兼容 OK Level = iota // compatible
SoftWarn // 服务器旧, 部分新功能不可用 SoftWarn // server outdated; some new features may be unavailable
HardError // 不兼容, 需升级 CLI 或 server HardError // incompatible; CLI or server must be upgraded
) )
func (l Level) String() string { func (l Level) String() string {
@@ -27,13 +27,13 @@ func (l Level) String() string {
return "unknown" 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 // same major, client minor <= server minor -> OK
// 同 major, client minor > server minor → SoftWarn (server 旧, 部分新功能不可用) // same major, client minor > server minor -> SoftWarn (some new features may be unavailable)
// 不同 major → HardError // different major -> HardError
// 字符串 unparseable → OK (容错, 不阻塞) // unparseable string -> OK (fail-open, do not block)
// "(unknown)" / "" → OK (dev build / server 字段缺失) // "(unknown)" / "" -> OK (dev build / server field missing)
func Compat(serverVer, cliVer string) (Level, string) { func Compat(serverVer, cliVer string) (Level, string) {
sMaj, sMin, ok := parseSemver(serverVer) sMaj, sMin, ok := parseSemver(serverVer)
if !ok { if !ok {
@@ -44,7 +44,7 @@ func Compat(serverVer, cliVer string) (Level, string) {
return OK, "" return OK, ""
} }
if sMaj != cMaj { 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 { if cMin > sMin {
return SoftWarn, fmt.Sprintf("server is older (server %s, client %s); some new features may be unavailable", serverVer, cliVer) 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 // Accepts the leading "v" common in `git describe` output and Tencent/WeKnora
// tag conventions ("v0.1.0"), since both server `/system/info.version` and // tag conventions ("v0.1.0"), since both server `/system/info.version` and
// the CLI's own ldflags-injected build.Version may carry it. // 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) { func parseSemver(s string) (major, minor int, ok bool) {
if s == "" || s == "(unknown)" { if s == "" || s == "(unknown)" {
return 0, 0, false 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") s = strings.TrimPrefix(s, "v")
// 去掉 prerelease/build metadata // Strip prerelease/build metadata.
if i := strings.IndexAny(s, "-+"); i >= 0 { if i := strings.IndexAny(s, "-+"); i >= 0 {
s = s[:i] s = s[:i]
} }
+2 -2
View File
@@ -19,9 +19,9 @@ func TestCompat(t *testing.T) {
{"client minor lower", "1.5.0", "1.2.0", compat.OK, ""}, {"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"}, {"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"}, {"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, ""}, {"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 tolerance (git describe + Tencent tag convention)
{"v-prefix both", "v1.2.0", "v1.5.0", compat.SoftWarn, "server is older"}, {"v-prefix both", "v1.2.0", "v1.5.0", compat.SoftWarn, "server is older"},
+2 -3
View File
@@ -1,5 +1,5 @@
// Package compat probes server `/system/info` and decides client-server // 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 // 24h TTL state file cache, three-tier compat semantics
// (major-mismatch=hard / minor-mismatch=soft / equal=ok). // (major-mismatch=hard / minor-mismatch=soft / equal=ok).
@@ -20,8 +20,7 @@ type Info struct {
ProbedAt time.Time `yaml:"probed_at"` ProbedAt time.Time `yaml:"probed_at"`
} }
// ProbeService is the narrow SDK surface compat depends on (testability via // ProbeService is the narrow SDK surface compat depends on; tests inject a fake.
// fake; mirrors v0.0 service interface pattern).
type ProbeService interface { type ProbeService interface {
GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error)
} }
+2 -2
View File
@@ -1,8 +1,8 @@
// Package config reads and writes the user-level config at // Package config reads and writes the user-level config at
// $XDG_CONFIG_HOME/weknora/config.yaml. yaml.v3 directly; viper is // $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 // the per-project link (.weknora/project.yaml) is handled by the
// projectlink package (see ADR-16). // projectlink package.
package config package config
import ( import (
+1 -1
View File
@@ -10,7 +10,7 @@ import (
// WriteReferences renders the compact references footer used by chat and // WriteReferences renders the compact references footer used by chat and
// agent invoke: a horizontal rule, one numbered line per reference, // agent invoke: a horizontal rule, one numbered line per reference,
// best-available title + optional score. Skipped entirely when refs is // 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) { func WriteReferences(w io.Writer, refs []*sdk.SearchResult) {
if len(refs) == 0 { if len(refs) == 0 {
return return
+1 -1
View File
@@ -8,7 +8,7 @@
// tree (which would expose auth/link/completion/destructive verbs that // tree (which would expose auth/link/completion/destructive verbs that
// don't belong on an agent-callable surface). // don't belong on an agent-callable surface).
// - Long-running tools (chat / agent_invoke) accumulate the LLM SSE // - 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 // 2025-06-18 does not define streamed tool-result content, so the
// accumulate-and-return pattern is the canonical path. // accumulate-and-return pattern is the canonical path.
// - Handlers receive ctx for cancellation; mid-LLM-stream cancellation // - Handlers receive ctx for cancellation; mid-LLM-stream cancellation
+12 -12
View File
@@ -42,17 +42,17 @@ type agentService interface {
// agentInvokeService composes the two SDK methods agent_invoke needs // agentInvokeService composes the two SDK methods agent_invoke needs
// (CreateSession for the auto-session path + AgentQAStreamWithRequest // (CreateSession for the auto-session path + AgentQAStreamWithRequest
// for the run itself). Declared here alongside the per-domain // for the run itself). Declared here alongside the per-domain
// interfaces above so ServiceClient (server.go) — which embeds the // interfaces above so ServiceClient (server.go) - which embeds the
// four domain interfaces — also satisfies it. // four domain interfaces - also satisfies it.
type agentInvokeService interface { type agentInvokeService interface {
CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error) CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error)
AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) 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 // 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 // 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) { func registerTools(server *mcpsdk.Server, svc ServiceClient) {
addKBList(server, svc) addKBList(server, svc)
addKBView(server, svc) addKBView(server, svc)
@@ -76,7 +76,7 @@ type kbListOutput struct {
func addKBList(server *mcpsdk.Server, svc knowledgeBaseService) { func addKBList(server *mcpsdk.Server, svc knowledgeBaseService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{ mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "kb_list", 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) { }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ kbListInput) (*mcpsdk.CallToolResult, kbListOutput, error) {
items, err := svc.ListKnowledgeBases(ctx) items, err := svc.ListKnowledgeBases(ctx)
if err != nil { if err != nil {
@@ -130,7 +130,7 @@ type docListOutput struct {
func addDocList(server *mcpsdk.Server, svc knowledgeService) { func addDocList(server *mcpsdk.Server, svc knowledgeService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{ mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "doc_list", 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) { }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docListInput) (*mcpsdk.CallToolResult, docListOutput, error) {
if in.KBID == "" { if in.KBID == "" {
return nil, docListOutput{}, fmt.Errorf("kb_id is required") return nil, docListOutput{}, fmt.Errorf("kb_id is required")
@@ -206,7 +206,7 @@ const maxDocDownloadBytes = 1 << 20
func addDocDownload(server *mcpsdk.Server, svc knowledgeService) { func addDocDownload(server *mcpsdk.Server, svc knowledgeService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{ mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "doc_download", 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) { }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, docDownloadOutput, error) {
if in.KnowledgeID == "" { if in.KnowledgeID == "" {
return nil, docDownloadOutput{}, fmt.Errorf("knowledge_id is required") return nil, docDownloadOutput{}, fmt.Errorf("knowledge_id is required")
@@ -250,7 +250,7 @@ type searchChunksOutput struct {
func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) { func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
// Out = any: SDK output schema would derive from searchChunksOutput, // 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 // nilable map[string]any that violates the auto-generated
// type=object constraint when empty. Skipping derivation by using // type=object constraint when empty. Skipping derivation by using
// `any` keeps the structured JSON shape identical while bypassing // `any` keeps the structured JSON shape identical while bypassing
@@ -258,7 +258,7 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
// below. // below.
mcpsdk.AddTool(server, &mcpsdk.Tool{ mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "search_chunks", 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) { }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in searchChunksInput) (*mcpsdk.CallToolResult, any, error) {
if in.KBID == "" { if in.KBID == "" {
return nil, nil, fmt.Errorf("kb_id is required") return nil, nil, fmt.Errorf("kb_id is required")
@@ -366,7 +366,7 @@ type agentListOutput struct {
func addAgentList(server *mcpsdk.Server, svc agentService) { func addAgentList(server *mcpsdk.Server, svc agentService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{ mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "agent_list", 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) { }, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ agentListInput) (*mcpsdk.CallToolResult, agentListOutput, error) {
items, err := svc.ListAgents(ctx) items, err := svc.ListAgents(ctx)
if err != nil { if err != nil {
@@ -415,7 +415,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
Channel: "api", Channel: "api",
} }
// Auto-create session if not supplied. Sessions are agent- // 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 sessionID := in.SessionID
if sessionID == "" { if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp agent_invoke"}) 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 // encodeDownload returns (content, isBase64). Heuristic: if the first 512
// bytes contain a NUL, treat as binary. Otherwise it's UTF-8-ish text. // 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. // good enough to spare an agent from base64-decoding obvious text.
func encodeDownload(buf []byte) (string, bool) { func encodeDownload(buf []byte) (string, bool) {
probe := buf probe := buf
+4 -4
View File
@@ -5,8 +5,8 @@
// .weknora/project.yaml is found, (b) the filesystem root is reached, or // .weknora/project.yaml is found, (b) the filesystem root is reached, or
// (c) the walk exceeds a 64-level depth limit (cycle protection for // (c) the walk exceeds a 64-level depth limit (cycle protection for
// pathological symlink setups). Pattern matches `cargo`, `npm`, and `git` // pathological symlink setups). Pattern matches `cargo`, `npm`, and `git`
// — find-the-project's-root walks; mount-boundary crossing is allowed // - find-the-project's-root walks; mount-boundary crossing is allowed
// (npm/cargo behave the same — a project may straddle a bind-mount). // (npm/cargo behave the same - a project may straddle a bind-mount).
package projectlink package projectlink
import ( import (
@@ -50,7 +50,7 @@ func Discover(startDir string) (string, bool, error) {
return candidate, true, nil return candidate, true, nil
} }
if err != nil && !errors.Is(err, os.ErrNotExist) { 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 // to a parent dir doesn't necessarily mean the project starts
// here. Cargo/npm have the same behavior. // here. Cargo/npm have the same behavior.
// Fall through to parent walk. // 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 // Remove deletes the project link at path. A missing file is reported as
// success so callers can stay idempotent under concurrent-removal races // 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 { func Remove(path string) error {
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("remove project link: %w", err) return fmt.Errorf("remove project link: %w", err)

Some files were not shown because too many files have changed in this diff Show More