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:
+123
-315
@@ -1,359 +1,167 @@
|
||||
# Agent Integration Guide for `weknora` CLI
|
||||
# AGENTS.md
|
||||
|
||||
> **Scope.** This file is an **operational reference** for LLM agents
|
||||
> (Claude Code, Cursor, Codex, Aider, Gemini Coder, etc.) that **invoke
|
||||
> `weknora` on a user's behalf**. It documents the wire shape, exit code,
|
||||
> and behavioral conventions an agent integration relies on.
|
||||
>
|
||||
> This is **not** a contributor guide. If you are an AI coding agent
|
||||
> editing weknora's source, see the repo root `README.md` (and, if added
|
||||
> later, a separate contributor `AGENTS.md` at the repo root).
|
||||
>
|
||||
> **Naming note.** "Agent" appears in two distinct WeKnora contexts:
|
||||
>
|
||||
> - **This file (`AGENTS.md`) + the `agent_help` annotation on each
|
||||
> command's `--help`**: documents the contract for AI coding agents
|
||||
> (you, the LLM-driven CLI consumer).
|
||||
> - **The `weknora agent` subtree** (`agent list / view / invoke`):
|
||||
> manages WeKnora's first-class *Custom Agent* resources — server-side
|
||||
> records (system prompt + model + allowed tools + KB scope) that the
|
||||
> user authored in the web UI. `agent invoke` calls the agent's
|
||||
> configured workflow against a query; it is **not** how you, the AI
|
||||
> coding agent, drive WeKnora — that's `kb` / `doc` / `search` / `chat`
|
||||
> / `mcp serve`.
|
||||
WeKnora CLI (`weknora`) is a noun-verb wrapper around the WeKnora server API; module path `github.com/Tencent/WeKnora/cli`. This file is the developer guide for coding agents and human contributors editing the CLI. The user-facing wire contract (output shape, exit codes, error format) lives in [README.md](README.md).
|
||||
|
||||
`weknora` is designed to be agent-friendly: error messages, output
|
||||
format, and flag design follow conventions agents can rely on.
|
||||
Wire-contract breaking changes are flagged in their PR description and
|
||||
the corresponding `weknora --version` bump — agents should pin a
|
||||
known-good version and re-validate against `--help` output on upgrade.
|
||||
|
||||
The "Output contract" and "Behavioral rules" sections below are the
|
||||
self-contained specification of the wire format; everything an integrator
|
||||
needs is in this document.
|
||||
|
||||
---
|
||||
|
||||
## Output contract
|
||||
|
||||
### Streams
|
||||
|
||||
- **stdout** is the data channel: bare JSON (with `--json`) or
|
||||
human-formatted output (without `--json`). Never carries error text.
|
||||
- **stderr** is logs / progress / warnings / errors / agent guidance
|
||||
footnotes. On failure, the error message + actionable hint go here.
|
||||
|
||||
A non-empty stderr does **not** mean failure — read the exit code instead.
|
||||
|
||||
### JSON output (bare data)
|
||||
|
||||
When `--json` is set on a successful command, stdout contains exactly
|
||||
one JSON value matching the resource the command produces:
|
||||
|
||||
| Command shape | stdout JSON |
|
||||
|---|---|
|
||||
| `list` / `search` | `[ { …resource… }, … ]` (bare array; `[]` when empty) |
|
||||
| `view` / `create` / `edit` | `{ …resource… }` (bare object) |
|
||||
| `delete` / `pin` / write ops | `{ id, …action-result fields… }` (bare object) |
|
||||
| `doctor` | `{ summary: { all_passed, passed, warned, failed, skipped }, checks: [ … ] }` |
|
||||
|
||||
There is no `ok` / `data` / `error` wrapper. Agents read the resource
|
||||
shape directly. Successful runs always return exit 0; failures never
|
||||
emit data JSON on stdout.
|
||||
|
||||
#### Field selection: `--json=field,field,…`
|
||||
|
||||
`--json` accepts a comma-separated field list (passed with `=`) to restrict
|
||||
each top-level object (or each element of a top-level array) to the named
|
||||
keys:
|
||||
## Build, Test, and Lint
|
||||
|
||||
```bash
|
||||
weknora kb list --json=id,name # [{ "id": "kb_x", "name": "Eng" }, …]
|
||||
weknora kb view kb_x --json=id # { "id": "kb_x" }
|
||||
go build -o weknora . # build (from cli/)
|
||||
go test -count=1 ./... # unit + contract tests
|
||||
go test -run TestFoo ./internal/format/ # single test
|
||||
go test ./acceptance/contract/ -args -update # refresh wire goldens
|
||||
go test -tags acceptance_e2e ./acceptance/e2e/... # live-server e2e (gated by env)
|
||||
go vet ./...
|
||||
```
|
||||
|
||||
Note the `=` form: pflag's optional-value parser treats space-separated
|
||||
arguments after a bare `--json` as positionals, so `--json id,name` would
|
||||
be interpreted as bare `--json` plus the positional `id,name`. Always use
|
||||
`--json=field,...` for projection.
|
||||
Both `go test -count=1 ./...` and `go vet ./...` must pass before committing.
|
||||
|
||||
Unknown field names are silently dropped so you can pass an aspirational
|
||||
field set across heterogenous outputs.
|
||||
## Architecture
|
||||
|
||||
#### jq pipeline: `--jq <expr>`
|
||||
Entry point: `cmd/main.go` → `cmd.Execute()` → `cmd.NewRootCmd(cmdutil.New())`.
|
||||
|
||||
`--jq` applies a jq expression to the JSON before printing. The
|
||||
expression sees the same bare shape the command produces (no envelope
|
||||
indirection). String results render without quotes for shell-friendly
|
||||
substitution; non-string results render as JSON.
|
||||
Key packages:
|
||||
|
||||
```bash
|
||||
weknora kb list --jq '.[].id' # one id per line
|
||||
weknora kb view kb_x --jq .name # bare name
|
||||
weknora search chunks "x" --kb e --jq '.[].score' # scores per line
|
||||
- `cmd/<noun>/` — cobra command implementations, one subdir per noun
|
||||
- `internal/cmdutil/` — `Factory`, `JSONOptions`, typed `Error`, exit-code mapping, destructive-write confirm, KB id-or-name resolve
|
||||
- `internal/format/` — bare JSON emitter (`WriteJSON` / `WriteJSONFiltered`)
|
||||
- `internal/iostreams/` — global IO singleton + TTY detection + `SetForTest` swap
|
||||
- `internal/secrets/` — `Store` interface; `KeyringStore` primary, `FileStore` 0600 fallback, `MemStore` for tests
|
||||
- `internal/prompt/` — `TTYPrompter` (huh-based, password no-echo) + `AgentPrompter` (non-TTY no-prompt sentinel)
|
||||
- `internal/sse/` — `Accumulator` for chat / agent invoke SSE streams
|
||||
- `internal/mcp/` — curated stdio MCP server (wired by `cmd/mcp/serve.go`)
|
||||
- `client/` (parent module) — generated SDK
|
||||
|
||||
## Command Structure
|
||||
|
||||
A command `weknora foo bar` lives in `cmd/foo/bar.go` with `bar_test.go`.
|
||||
|
||||
### Canonical Examples
|
||||
|
||||
- **Command + tests**: `cmd/kb/list.go` and `list_test.go`
|
||||
- **Destructive write + confirm protocol**: `cmd/kb/delete.go`
|
||||
- **SSE streaming command**: `cmd/chat/chat.go`
|
||||
- **Factory wiring**: `internal/cmdutil/factory.go`
|
||||
|
||||
### The Options + Narrow Service Pattern
|
||||
|
||||
Every command follows this structure (see `cmd/kb/list.go`):
|
||||
|
||||
1. `Options` struct with flag-bound fields
|
||||
2. `Service` interface declaring only the SDK methods this command calls. `*sdk.Client` satisfies it implicitly via duck typing.
|
||||
3. `NewCmd<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
|
||||
filter runs after the field projection.
|
||||
### JSON Output
|
||||
|
||||
### Errors (stderr, exit code carries the class)
|
||||
Add `--json` / `--jq` via `cmdutil.AddJSONFlags(cmd, fieldNames)`. In `RunE`:
|
||||
|
||||
On failure, stdout is empty (or holds the partial-success output the
|
||||
command already wrote before the failure). The error message goes to
|
||||
stderr in this format:
|
||||
|
||||
```
|
||||
<error.code>: <message>[: <wrapped cause>]
|
||||
hint: <actionable next-step>
|
||||
```go
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, result)
|
||||
}
|
||||
```
|
||||
|
||||
- `<error.code>` is a `namespace.snake_case` string from a closed
|
||||
registry in `cli/internal/cmdutil/errors.go` (`AllCodes()`).
|
||||
An acceptance test enforces that every code referenced in `cli/cmd/`
|
||||
is registered.
|
||||
- `<message>` is the human-readable description.
|
||||
- `<hint>` is the deterministic next-step hint (omitted when no hint
|
||||
applies).
|
||||
`Emit` is the single source for the bare-JSON contract — it honors `--json=fields,...` projection and `--jq <expr>` filtering. Never call `format.WriteJSON*` directly from a command. See `cmd/kb/list.go`.
|
||||
|
||||
Code namespaces: `auth.*` / `resource.*` / `input.*` / `server.*` /
|
||||
`network.*` / `local.*` / `mcp.*`.
|
||||
### Destructive Writes
|
||||
|
||||
To pattern-match programmatically: split on the first `:` to extract
|
||||
the code, or branch on the exit code (see below).
|
||||
Commands that delete / empty / overwrite call `cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), what, id)` before mutation. In non-TTY OR `--json` mode without `-y`, it returns `CodeInputConfirmationRequired` → exit 10. See `internal/cmdutil/confirm.go`.
|
||||
|
||||
### Exit codes
|
||||
## Testing
|
||||
|
||||
| Code | Meaning | Agent action |
|
||||
|---|---|---|
|
||||
| `0` | Success | Continue |
|
||||
| `1` | Typed `local.*` error or unclassified | Read stderr, decide retry/abort |
|
||||
| `2` | Flag/argument validation error | Re-check `weknora <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 |
|
||||
### Narrow Service Fakes
|
||||
|
||||
Exit 10 is the wire-level signal for "high-risk write needs explicit
|
||||
confirmation". **Never bypass exit 10 by auto-passing `-y` without
|
||||
explicit user permission.**
|
||||
Each command's `runX(ctx, opts, jopts, svc, ...)` takes its interface, not `*sdk.Client`. Tests inject plain-struct fakes:
|
||||
|
||||
---
|
||||
|
||||
## Command surface
|
||||
|
||||
Discover the command tree the same way human users do:
|
||||
|
||||
```bash
|
||||
weknora --help # top-level
|
||||
weknora kb --help # subtree
|
||||
weknora kb delete --help # single command flags
|
||||
```go
|
||||
type fakeBarSvc struct {
|
||||
gotID string
|
||||
resp *sdk.Bar
|
||||
err error
|
||||
}
|
||||
func (f *fakeBarSvc) GetBar(_ context.Context, id string) (*sdk.Bar, error) {
|
||||
f.gotID = id
|
||||
return f.resp, f.err
|
||||
}
|
||||
```
|
||||
|
||||
The command tree follows `<noun> <verb>`. Verbs are:
|
||||
No mocking library; the narrow-interface design makes fakes 5 lines each.
|
||||
|
||||
| Verb | Semantics | Example |
|
||||
|---|---|---|
|
||||
| `list` | Multi-resource read | `kb list` |
|
||||
| `view` | Single-resource read | `kb view <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 ...` |
|
||||
### IOStreams in Tests
|
||||
|
||||
`auth` subtree: `login` / `logout` / `list` / `status` / `refresh` /
|
||||
`token`. Context-switching uses `context use <name>` (WeKnora contexts
|
||||
bundle host + tenant + credentials, so they need a richer abstraction
|
||||
than a single per-host token slot). `auth refresh` exchanges the stored
|
||||
refresh token for a new access + refresh pair (OAuth refresh-token
|
||||
grant); it errors with `input.invalid_argument` on API-key contexts
|
||||
which have no refresh semantic. Transparent 401 → refresh → retry is
|
||||
wired into the SDK transport (`cli/internal/cmdutil/authretry.go`)
|
||||
with singleflight de-dup, so most callers never need to invoke `auth
|
||||
refresh` explicitly.
|
||||
```go
|
||||
out, errBuf := iostreams.SetForTest(t) // bytes.Buffer sinks, non-TTY
|
||||
ios, _ := iostreams.SetForTestWithTTY(t) // simulate terminal
|
||||
```
|
||||
|
||||
### Auth security contract
|
||||
### Confirm Prompts
|
||||
|
||||
- **Credential storage**: OS keychain via `go-keyring` (macOS Keychain,
|
||||
Windows Credential Manager, freedesktop Secret Service). Falls back to
|
||||
a 0600 file under `$XDG_CONFIG_HOME/weknora/secrets/<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.
|
||||
Use `testutil.ConfirmPrompter{Answer: bool, Err: error}` from `internal/testutil/`. Single source for the prompt double — do NOT re-define `confirmPrompter` per package.
|
||||
|
||||
`search` subtree: `search chunks "<q>" --kb X` for hybrid retrieval;
|
||||
`search kb "<q>"` / `search docs "<q>" --kb X` / `search sessions "<q>"`
|
||||
for client-side substring filtering on the listing endpoints.
|
||||
### Assertions
|
||||
|
||||
`session` subtree: `list` / `view` / `delete` for chat session
|
||||
management. Sessions are the durable wrapper around `chat` invocations.
|
||||
Use `testify`. Prefer `require` (not `assert`) for error checks so the test halts immediately, and `assert` for value comparisons:
|
||||
|
||||
Top-level RAG / connectivity verbs: `chat`, `search`, `api`, `link`,
|
||||
`auth`, `context`, `session`, `doctor`, `version`.
|
||||
```go
|
||||
require.NoError(t, err)
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, "expected", actual)
|
||||
```
|
||||
|
||||
`doctor` is a deliberate WeKnora addition: RAG deployments routinely
|
||||
break on misconfigured embeddings, storage backends, and credentials,
|
||||
and the structured `{summary: {all_passed, passed, warned, failed,
|
||||
skipped}, checks: [...]}` JSON shape is the cleanest agent-readable
|
||||
surface for that.
|
||||
### Acceptance: Wire-Shape Goldens
|
||||
|
||||
---
|
||||
`acceptance/contract/wire_test.go` drives the in-process cobra tree against `httptest.Server` fixtures and compares stdout to `acceptance/testdata/wire/<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
|
||||
(under "AI Agents:").
|
||||
Use for flag validation, error classification, parser edge cases. See `internal/cmdutil/exit_test.go` and `cmd/kb/list_test.go`.
|
||||
|
||||
1. **Pass `-y/--yes`** on destructive writes (`kb delete` / `kb empty` /
|
||||
`doc delete` / `session delete` / `context remove` when targeting
|
||||
the current context) when running headless. Without it, you will
|
||||
get exit 10. **Never auto-add `-y`** without the user's explicit
|
||||
go-ahead — the exit-10 protocol is the one explicit guard against
|
||||
unintended writes.
|
||||
2. **Prefer typed commands over `weknora api`** for known endpoints.
|
||||
Fallback to `weknora api` only when no typed command covers the
|
||||
call.
|
||||
3. **For chat, prefer `--no-stream --json`** in agent contexts.
|
||||
Streaming tokens to stdout makes JSON parsing impossible.
|
||||
4. **`link` writes to the user's working directory** — only run it
|
||||
when the user invoked it, not as a side effect of unrelated
|
||||
automation.
|
||||
```go
|
||||
tests := []struct{ name string; ...}{
|
||||
{name: "descriptive case", ...},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) { /* arrange, act, assert */ })
|
||||
}
|
||||
```
|
||||
|
||||
(Additional safety guidance — e.g. "do not switch context unless the
|
||||
user asked" — is documented in the affected command's own `--help`.)
|
||||
## Code Style
|
||||
|
||||
---
|
||||
- Add godoc to every exported function, type, and constant. Explain *why*, not *what* — the name already says *what*.
|
||||
- Don't comment to restate the code. Delete comments that narrate the next line.
|
||||
- Don't reference task numbers, commit SHAs, or version tags in inline comments — they belong in CHANGELOG or git log.
|
||||
- Never paste em-dashes (—) into Go source; use ASCII `-` or rewrite. (Markdown docs may use em-dashes.)
|
||||
- Don't add a helper for a single caller — inline.
|
||||
|
||||
## Auto-detection of agent environments
|
||||
## Error Handling
|
||||
|
||||
`weknora` checks these environment variables (case-sensitive):
|
||||
Typed error helpers in `internal/cmdutil/errors.go`:
|
||||
|
||||
| Env var | Detected agent name |
|
||||
|---|---|
|
||||
| `CLAUDECODE` | `claude-code` |
|
||||
| `CURSOR_AGENT` | `cursor` |
|
||||
- `cmdutil.NewError(code, msg)` — fresh typed error
|
||||
- `cmdutil.WrapHTTP(err, format, args...)` — wrap an SDK error + classify from HTTP status (404 → `resource.not_found`, 401 → `auth.unauthenticated`, …). Use at every SDK call site.
|
||||
- `cmdutil.Wrapf(code, err, format, args...)` — explicit wrap with a chosen code
|
||||
- `cmdutil.NewFlagError(err)` — flag / argument problem → exit 2
|
||||
- `cmdutil.SilentError` — exit 1 without printing (when output already emitted)
|
||||
- `cmd.MarkFlagsMutuallyExclusive("a", "b")` — cobra-level mutex
|
||||
|
||||
When any is set, `weknora --help` appends the command's `agent_help`
|
||||
annotation. **No behavior change** — this is help-text rendering only.
|
||||
Errors print to STDERR via `cmdutil.PrintError(w, err)` as `code: msg\nhint: ...`. STDOUT stays bare JSON or empty on failure, so `--json | jq` pipelines never have to filter error shapes.
|
||||
|
||||
To suppress detection (e.g. running `weknora` interactively from inside
|
||||
Claude Code without the agent footer): `WEKNORA_NO_AGENT_AUTODETECT=1`.
|
||||
User-facing exit-code mapping lives in [README.md "Exit codes"](README.md#exit-codes). When adding a new `ErrorCode` constant, also append to `AllCodes()` so the acceptance contract picks it up.
|
||||
|
||||
Agent detection (`CLAUDECODE` / `CURSOR_AGENT` env) also tags the
|
||||
User-Agent header for server-side telemetry — it never changes CLI
|
||||
behavior.
|
||||
|
||||
---
|
||||
|
||||
## Architecture decisions
|
||||
|
||||
A handful of decisions are referenced inline in the source as `ADR-N`. They
|
||||
live here, alongside the contract they shape.
|
||||
|
||||
**ADR-3 — bare-data JSON on stdout, errors on stderr.** Successful
|
||||
commands emit the raw resource shape (`[]Item` for lists, `T` for views,
|
||||
`{id, deleted: true}` for deletes) — no `ok` / `data` / `error`
|
||||
wrapper. Errors are not data; they go to stderr in `code: message\nhint:
|
||||
…` form, and the typed exit code carries the failure class for
|
||||
programmatic branching. This separates "what the command produces" from
|
||||
"how the run went", so `--json | jq` pipelines never have to filter
|
||||
error shapes out of the success stream, and matches the contract of
|
||||
gh / aws / stripe.
|
||||
|
||||
WeKnora-specific shape choices:
|
||||
|
||||
- `link` (project-binding) — `<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
|
||||
|
||||
Reference in New Issue
Block a user