Files
Enterprise-Knowledge-Base/cli/README.md
T
nullkey e623e8208f refactor(cli): delete envelope infrastructure, errors to stderr
Removes the entire envelope machinery now that every success path
emits bare JSON:

- cli/internal/format/envelope.go (Envelope, Success, Failure,
  SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice,
  VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests.
- cli/internal/format/filter.go envelope-specific helpers
  (WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter,
  filterDataPayload, filterObjectData); the reusable
  filterArrayItems / filterObjectKeys / writeJQ stay for bare.go.
- cli/internal/cmdutil/exporter.go + tests (envelope-only).
- cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody +
  operationRiskOf + Error.OperationRisk field + OperationRisk struct.

Error path: all errors now go to stderr via cmdutil.PrintError in
`code: message\nhint: ...` form, regardless of --json. Stdout stays
empty (or holds the partial-success the command already wrote) so
downstream `--json | jq` pipelines never have to filter error shapes
out of the success stream. Typed exit codes (3 auth.* / 4
resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.*
+ network.* / 10 input.confirmation_required) carry the failure
class for agents that branch on it.

Acceptance contract:
- envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden).
- testdata/envelopes/ → testdata/wire/.
- Error-path cases assert the typed code substring on stderr.
- Orphan whoami.*.json goldens deleted.

AGENTS.md + README.md rewritten for the bare-data contract:
- Drop envelope schema section + dry-run rule.
- Document bare JSON on stdout + `code: msg\nhint: …` on stderr.
- ADR-3 reframed around bare data and why error separation matters
  for `--json | jq` pipelines.

WriteJSONFiltered short-circuits to WriteJSON when both filters are
empty (skip the marshal-buffer round-trip for the common case).

Final review pass:
- Fix wire-contract bug: `--json id,name` (space form) is broken by
  pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the
  field-discovery help text all switched to `--json=id,name`.
- Fix `weknora api --jq` silently ignored: api.go now routes through
  WriteJSONFiltered with jopts.JQ.
- AGENTS.md: drop the false claim that `auth logout` honors `-y`
  (logout is local-only with no ConfirmDestructive guard); list the
  actual destructive commands instead.
- Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape
  (was still parsing `out["data"]` / `env["ok"]`).
- Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated
  `format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields,
  jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the
  format import from 22 cmd/* files.
- Delete single-caller `cmdutil.MustRequireFlag`; inline as
  `_ = cmd.MarkFlagRequired(...)` everywhere.
- Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the
  only write command relying on runtime --name validation while
  `context add` already used the cobra-level mark.
- `context use`: register `--json` / `--jq` (was always emitting JSON
  unconditionally with no human path and no flag — diverged from
  every other write command); human mode now prints
  `✓ Switched context to X (was Y)`.
- Replace per-package `confirmPrompter` / `scriptedConfirm` /
  `errPrompter` test doubles with `testutil.ConfirmPrompter`.
- Rename `chatService` → `ChatService` (export to match siblings
  `ListService` / `ViewService`); rename `printUploadSuccess` →
  `renderUploadSuccess` (siblings use `render*`).
- `defaultHint(CodeResourceNotFound)`: drop the hardcoded
  "list available with `weknora kb list`" — misleading on agent /
  doc / session 404. Replaced with "verify the resource ID and try
  again".
- Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only"
  historical tags from production comments and a few test
  descriptions.
2026-05-15 12:03:56 +08:00

181 lines
5.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# weknora — WeKnora CLI
A command-line interface for the WeKnora RAG knowledge-base server. Lets you
authenticate, manage knowledge bases and documents, run hybrid search, and
ask streaming RAG questions from your terminal or from an AI agent.
```bash
$ weknora --help
WeKnora CLI lets you authenticate, browse knowledge bases, and run
hybrid searches against a WeKnora server from your shell or an AI agent.
Available Commands:
api Make a raw API request to the WeKnora server
auth Manage authentication credentials and contexts
chat Ask a streaming RAG question against a knowledge base
context Manage CLI contexts (named connection targets)
doc Manage documents in a knowledge base
doctor Run 4 self-checks: base URL, auth, server version, credential storage
kb Manage knowledge bases
link Bind the current directory to a knowledge base
search Search across chunks, knowledge bases, documents, or sessions
session Manage chat sessions
version Show CLI build metadata
```
The command surface mirrors `gh` CLI's `<noun> <verb>` convention. See
[AGENTS.md](AGENTS.md) for the operational contract that AI agents
(Claude Code, Cursor, Aider, …) can rely on: bare-JSON output shape,
stderr error format, exit-code protocol, error-code registry, and
per-command guidance.
---
## Install
### From source
Requires Go 1.24+.
```bash
git clone https://github.com/Tencent/WeKnora.git
cd WeKnora/cli
go build -o weknora .
sudo mv weknora /usr/local/bin/ # or anywhere on $PATH
```
### Pre-built binaries
Pre-built binaries for Linux / macOS / Windows are produced by CI on each
release. Grab the latest from the [Releases page](https://github.com/Tencent/WeKnora/releases)
once v0.2 ships.
---
## 5-minute quickstart
```bash
# 1. Log in to your WeKnora server (interactive password prompt)
weknora auth login --host https://kb.example.com
# 2. Or pipe an API key from stdin (for CI / agents)
echo "sk-..." | weknora auth login --host https://kb.example.com --with-token
# 3. List knowledge bases
weknora kb list
# 4. Bind this directory to a knowledge base — subsequent commands auto-resolve --kb
weknora link --kb my-knowledge-base
# 5. Upload a document
weknora doc upload notes.md
# 6. Search
weknora search chunks "what is reciprocal rank fusion?"
# 7. Ask the LLM (streams to terminal)
weknora chat "summarise the design doc"
```
---
## Multi-context
Switch between several WeKnora servers (or several tenants on the same server)
without re-logging in:
```bash
weknora auth login --host https://prod.example.com --name prod
weknora auth login --host https://staging.example.com --name staging --with-token < .staging-key
weknora auth list
weknora context use prod
```
Credentials are persisted to your OS keyring (Keychain on macOS, libsecret on
Linux, Wincred on Windows) when available, otherwise to a 0600-mode file
under `$XDG_CONFIG_HOME/weknora/secrets/`. The active context lives in
`~/.config/weknora/config.yaml`.
To remove a context's stored credentials:
```bash
weknora auth logout # current context
weknora auth logout --name staging # specific
weknora auth logout --all
```
---
## JSON output
Every command supports `--json`, emitting bare JSON for the resource it
produces — an array for `list` / `search`, a single object for `view`
and write outcomes:
```bash
weknora kb list --json # [{ "id": "kb_x", "name": "Eng" }, …]
weknora kb view kb_x --json # { "id": "kb_x", "name": "Eng", … }
weknora kb list --json=id,name # project to listed fields
weknora kb list --json --jq '.[].id' # jq over the bare data
```
On failure, stdout stays empty and the typed error goes to stderr in
`code: message\nhint: ...` form:
```
auth.unauthenticated: fetch current user: HTTP error 401: ...
hint: run `weknora auth login`
```
The typed exit code (3 / 4 / 5 / 6 / 7 / 10) carries the failure
class for agents that branch on it. The full error-code registry and
exit-code protocol are documented in [AGENTS.md](AGENTS.md).
---
## Agent / scripting integration
Designed to be agent-first:
- `-y/--yes` skips confirmation prompts for high-risk writes. **Without
`-y` on a non-TTY/`--json` invocation, destructive commands return
`error.code: input.confirmation_required` and exit code 10** so an
agent can ask the user before retrying.
- `--json` coexists with the global `--context <name>` for single-shot
context override.
- Set `CLAUDECODE` or `CURSOR_AGENT` environment variables to surface
per-command "AI agents:" guidance in `--help` output.
---
## Health check
Run `weknora doctor` for a 4-status diagnostic (OK / warn / fail /
skip) covering base URL reachability, authentication, server-CLI
version skew, and credential storage backend. Add `--json` for
machine-readable output, `--offline` to skip network checks.
---
## Development
```bash
# Run unit + contract tests
go test ./...
# Run the real-server e2e suite (requires WEKNORA_E2E_HOST + token env vars)
go test -tags acceptance_e2e ./acceptance/e2e/...
# Static analysis
go vet ./...
```
CI (`.github/workflows/cli.yml`) runs build + unit + contract tests on Linux /
macOS / Windows × Go 1.24, path-filtered to changes under `cli/`.
---
## License
MIT — see the repository [LICENSE](../LICENSE).