feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING)

D1 — --format default flipped to json regardless of TTY:
- v0.6: smart default (text on TTY, json on pipe).
- v0.7: always json; TTY only affects indent (compact in pipe). Enum
  values unchanged (text | json | ndjson).
- Typed FormatMode enum replaces untyped string consts.
- --format / --jq promoted to persistent root flags so unknown-
  subcommand paths still reach the typed-envelope guard (per-command
  registration in v0.6 would have rejected --format on unknown
  commands as cobra-prose exit 2).
- WEKNORA_FORMAT env var added; precedence --format > env > default.
  Invalid env values silently ignored.

D2 — chat / session ask default to NDJSON event-stream:
- New cli/internal/output/ndjson_stream.go: InitEvent struct +
  EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc
  encodes the must-be-first-line invariant agents key on.
- chat / session ask: --format json AND --format ndjson both emit one
  JSON event per line (no envelope wrapping). CLI injects exactly one
  `init` event at stream head carrying session_id + optional kb_id /
  agent_id / profile. Subsequent events pass through verbatim from the
  SDK (passthrough discipline per spec §5.1).
- --format text keeps the SSE-style live renderer.

context → profile full cascade:
- Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv;
  package contextcmd → profilecmd).
- Global flag --context → --profile. Factory.ContextOverride →
  ProfileOverride. WEKNORA_PROFILE env var honored
  (--profile flag > env > config.CurrentContext). When --profile or
  WEKNORA_PROFILE references a missing profile, the error is
  input.invalid_argument with hint "weknora profile list" — not the
  destructive local.config_corrupt path (which would have told users
  to delete their config file).
- Binding file .weknora/project.yaml field context: → profile:
  (no backwards-compat alias; re-run weknora link).
- profile use JSON fields current_context / previous_context →
  current_profile / previous_profile.
- weknora link JSON field context → profile.
- CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code
  rename).
- Envelope top-level profile field populated via globalProfile (set
  by root PersistentPreRunE from Factory.ActiveProfile). chat /
  session ask NDJSON init event carries the same profile.
- Rationale: "context" collided with LLM context window / RAG context
  / Go context.Context; mainstream multi-credential CLIs (AWS /
  Stripe / OpenAI / Anthropic / lark) all use "profile".

H2/C1' help calibration:
- AgentHelp gains Warnings []string; single SetAgentHelp helper
  routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including
  warnings) vs human help (appends "AI agents:" block from same
  source). Warnings surface as both a structured JSON field and
  visible help-text addendum without drift.
- 9 destructive commands carry warnings: kb / doc / agent / session /
  chunk delete; profile remove; kb / agent edit; auth logout.
- weknora doc wait dedups ids at entry; SIGINT mid-wait returns
  silently (root signal handler maps to exit 130) instead of being
  miscategorised as operation.timeout / operation.failed.

A4 — docs:
- cli/AGENTS.md gains four agent-facing sections: Wire contract for
  AI agents (stdout / stderr / NDJSON / _notice evolution / SDK
  contract boundary); Deliberate deviations + mainstream alignments;
  Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE
  table extended.
- cli/README.md adds Agent quick start under Wire contract.
- cli/CHANGELOG.md v0.7 section: BREAKING entries with migration
  notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command /
  retry_after_seconds / risk / _notice reserved infra / meta.count /
  meta.has_more / doc fetch / doc create / session ask / doc delete
  --all / NDJSON init), Changed (docs additions), Deprecated (none —
  pre-release one-shot breaking).

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
This commit is contained in:
nullkey
2026-05-21 18:43:18 +08:00
committed by lyingbug
parent a2e368b1e8
commit 2ce348d020
91 changed files with 1440 additions and 753 deletions
+219 -10
View File
@@ -2,7 +2,185 @@
This is the WeKnora CLI (`weknora`), a command-line client for the WeKnora RAG server. The module path is `github.com/Tencent/WeKnora/cli`.
The wire contract for AI agents *consuming* `weknora` output (JSON shape, exit codes, error format) lives in [README.md](README.md) — read that if you're integrating with the CLI binary, not modifying it.
The wire contract for AI agents *consuming* `weknora` output (JSON shape, exit codes, error format) is documented below and in [README.md](README.md). Read this file if you're integrating with the CLI binary — build / test / architecture details follow the wire contract sections.
## Wire contract for AI agents
This CLI's primary consumers include AI agents (Claude Code, Cursor, Gemini CLI,
etc.). Output format is the agent-facing API. **Every error message and every
JSON field you write becomes part of an agent's decision-making input.**
### Stdout (success path)
All `--format json` (default) commands emit a symmetric envelope:
```json
{
"ok": true,
"data": "<T>",
"meta": {"count": 0, "has_more": false},
"_notice": {},
"profile": "default"
}
```
`data` is omitted on mutation-only success (no payload). `meta` carries list
counters (`count`, `has_more`) and batch successes/failures. `meta.next_cursor`,
`meta.total_count`, and `meta.request_id` are reserved — not currently
populated; planned for v0.8 when the SDK exposes pagination cursors and response
headers. `_notice` is reserved — open-map infrastructure is in place for
deprecation / version_skew / security notices; producer wiring planned for v0.8.
`profile` echoes the resolved profile name.
### Stderr (error path)
Errors emit an error envelope on stderr (`--format json`) or prose
`code: message\nhint: ...\nretry: ...` (`--format text`):
```json
{
"ok": false,
"error": {
"type": "auth.unauthenticated",
"message": "fetch current user: HTTP error 401",
"hint": "run `weknora auth login`",
"retry_command": "weknora auth login --host https://kb.example.com",
"retry_after_seconds": 0,
"risk": {"level": "destructive", "action": "noun.verb"},
"detail": {}
},
"_notice": {}
}
```
`type` is the typed code (see [Error code reference](#error-code-reference)
below). `hint` is prose; `retry_command` is the suggested next argv (single
shell-escaped string). For non-destructive errors agents may execute it; on
exit-10 (`input.confirmation_required`) it is informational only — the human
must approve the destructive write explicitly. See "Exit-10 anti-patterns" for
details. Note: tokens in `retry_command` are built via `fmt.Sprintf` with
user-supplied IDs unquoted — callers that auto-execute must shell-quote each
token (emitting as a JSON array is planned for v0.8).
`retry_after_seconds` mirrors HTTP `Retry-After`. `risk` tags high-risk writes.
`detail` carries structured per-error context (e.g. `unknown_subcommand`'s
`available[]` list).
### NDJSON event stream (chat / session ask)
`--format json` and `--format ndjson` both produce one JSON event per line —
no envelope wrapping. The CLI injects exactly one event (`init`) at the head;
all subsequent events pass through verbatim from the SDK:
```
{"type":"init","session_id":"...","kb_id":"...","profile":"...","agent_id":"..."}
{"type":"thinking","content":"..."}
{"type":"answer","content":"Hello"}
{"type":"tool_call","name":"...","input":{}}
{"type":"complete","done":true}
```
For prose rendering, pass `--format text`.
### `_notice` evolution policy
`_notice` is an open map. New keys are **additive non-breaking**; agents MUST
ignore unknown keys. v0.7 reserves three keys: `deprecation` / `version_skew` /
`security`. New keys follow snake_case convention. The `_notice` field is
currently always empty — producer wiring is planned for v0.8 when the SDK
exposes version metadata. The wire infrastructure is in place so adding a
producer in v0.8 will not change the envelope shape.
### CLI vs server SDK contract boundary
CLI 1.0 contract covers:
- ✅ Envelope wire shape (success + error)
- ✅ CLI-injected events (`init` only)
- ✅ NDJSON line shape (bare `{type:...,...}`)
- ✅ Passthrough discipline (CLI doesn't rename SDK events)
CLI 1.0 contract does NOT cover:
- ❌ Specific SDK event names (`answer` / `tool_call` / `complete` / ...)
- ❌ SDK event field shapes (server's own version contract)
Analogy: kubectl 1.0 doesn't lock K8s API resource schemas; you handle K8s
version separately. WeKnora CLI 1.0 same.
### The one rule
Every error message you write will be parsed by an AI to decide its next action.
Make errors structured, actionable, and specific.
### Environment variables
| Variable | Purpose |
|---|---|
| `WEKNORA_PROFILE` | Active profile name. Equivalent to the global `--profile <name>` flag; overridden by `--profile`. Useful in CI scripts that cannot pass global flags. |
| `WEKNORA_FORMAT` | Default `--format` value (`text \| json \| ndjson`). Overridden by explicit `--format`. Invalid values ignored silently. |
| `WEKNORA_KB_ID` | Default KB ID for commands that accept `--kb`. Overridden by `--kb`. |
| `WEKNORA_LOG_LEVEL` | SDK debug log level (`error \| warn \| info \| debug`). Overridden by `--log-level`. |
| `WEKNORA_AGENT_HELP` | Set to `1` to emit structured JSON agent-help (machine-readable) instead of human help text when `--help` is invoked. |
> **Note for agents — machine-readable version and help:** The `--version` flag
> and `--help` flag on the root command bypass `--format json` and always emit
> prose (cobra built-in paths). For machine-readable output use the `version`
> subcommand (`weknora version --format json`) or `WEKNORA_AGENT_HELP=1
> weknora <cmd> --help`. Planned fix for v0.8.
## Deliberate deviations + mainstream alignments
Five design decisions: four deliberate deviations from mainstream CLI
conventions, one mainstream alignment.
### 1. Channel split: success → stdout, error → stderr
| | |
|---|---|
| **Mainstream** | lark CLI puts both success and error envelopes on stdout |
| **WeKnora** | success envelope → stdout; error envelope → stderr |
| **Rationale** | `weknora ... --format json \| jq '.data[]'` must not mix error objects into the data stream. Channel split lets pipeline consumers suppress errors with `2>/dev/null` and still get clean JSON on stdout. (kubectl follows this; gh does not.) |
### 2. `weknora api DELETE` triggers exit-10 confirmation
| | |
|---|---|
| **Mainstream** | gh `gh api` / lark / Stripe CLI raw-API commands don't prompt confirm; they rely on restricted API keys |
| **WeKnora** | DELETE triggers exit-10 (`input.confirmation_required`); user bypasses with `-y/--yes` |
| **Rationale** | DELETE is irreversible; self-hosted deployments may not have restricted credential infrastructure. Defensive default because agents are common consumers. |
### 3. `retry_command` distinct from `hint`
| | |
|---|---|
| **Mainstream** | lark embeds fix commands inside prose hint strings |
| **WeKnora** | two separate fields: `retry_command` (suggested next argv, directly-executable for non-destructive errors; informational only on exit-10) + `hint` (prose) |
| **Rationale** | Agents don't regex-extract argv from prose — known fragility. Trade-off: one extra envelope field. On exit-10, the user must approve the destructive write; agents surface `retry_command` for human review, not auto-execution. |
### 4. NDJSON event stream has no envelope wrapping — mainstream alignment
| | |
|---|---|
| **Mainstream** | 4/4 CLIs with NDJSON event streams (Claude Code / Codex / Gemini / lark webhook) use bare `{type:...}` — zero use envelope wrapping |
| **WeKnora** | same as mainstream |
| **Rationale** | Streaming envelope requires unwrap before dispatch — net burden with no benefit. This is not a deviation; it is explicit alignment with the surveyed field. |
### 5. No `schema_version` field in payload
| | |
|---|---|
| **Mainstream** | some APIs (Anthropic / OpenAI) embed a `version` field in payload |
| **WeKnora** | version identity via CLI binary semver + CHANGELOG `### BREAKING` + skill `tested_against` + CI parity tests |
| **Rationale** | Mainstream CLIs don't embed version in payload. Agents have complete version awareness via `weknora --version` and skill version binding. |
## Pre-1.0 breaking policy
CLI is in `v0.x` pre-release. Breaking changes ship together in concentrated
batches (v0.5 / v0.6 / v0.7) rather than scattered across patch releases.
After 1.0, any breaking change requires a 2-version deprecation period.
`CHANGELOG.md` `### BREAKING` section is authoritative.
For agents: pin the CLI version in your skill's `tested_against` field; bump
`tested_against` only after manually validating against the new CLI.
## Build, Test, and Lint
@@ -29,7 +207,7 @@ Key packages:
- `internal/iostreams/` — global IO singleton + TTY detection + `SetForTest` swap
- `internal/secrets/` — `Store` interface; `KeyringStore` primary, `FileStore` 0600 fallback, `MemStore` for tests
- `internal/prompt/` — `TTYPrompter` (password no-echo) + `AgentPrompter` (non-TTY no-prompt sentinel)
- `internal/sse/` — `Accumulator` for chat / agent invoke SSE streams
- `internal/sse/` — `Accumulator` for chat / session ask SSE streams
- `internal/mcp/` — curated 10-tool stdio MCP server (wired by `cmd/mcp/serve.go`); see [MCP tool surface](#mcp-tool-surface) for the curation rationale and inventory
- `client/` (parent module) — generated SDK
@@ -195,12 +373,13 @@ Agents parse the first colon to extract the typed code. The exit code class (see
| `auth.unauthenticated` | 3 | no (run `auth login`) | run `weknora auth login` |
| `auth.token_expired` | 3 | yes (after refresh) | your session expired; run `weknora auth login` to re-authenticate |
| `auth.bad_credential` | 3 | no (re-login) | run `weknora auth login` |
| `auth.forbidden` | 3 | no | active context lacks permission for this resource |
| `auth.forbidden` | 3 | no | active profile lacks permission for this resource |
| `auth.cross_tenant_blocked` | 3 | no | verify tenant context with `weknora auth status` |
| `auth.tenant_mismatch` | 3 | no | verify tenant context with `weknora auth status` |
| `input.invalid_argument` | 5 | no | see `weknora <command> --help` for valid usage |
| `input.missing_flag` | 5 | no | see `weknora <command> --help` for valid usage |
| `input.confirmation_required` | 10 | **NO automatic retry** | high-risk write - re-run with `-y/--yes` after the user explicitly approves |
| `input.unknown_subcommand` | 5 | no | invocation reached a command path with no matching subcommand. Detail includes `available` list; retry with `<path> --help`. |
| `resource.not_found` | 4 | no | verify the resource ID and try again |
| `resource.already_exists` | 1 | no | use a different name or fetch the existing resource |
| `resource.locked` | 1 | maybe (transient lock) | (no canonical hint; check resource state) |
@@ -214,13 +393,13 @@ Agents parse the first colon to extract the typed code. The exit code class (see
| `operation.failed` | 1 | no (target reached terminal failure) | one or more targets reached a terminal failure (e.g. doc parse_status=failed) |
| `operation.cancelled` | 1 (main overrides to 130) | no | command interrupted by SIGINT / SIGTERM. The typed code maps to exit 1, but `main` raises the exit to 130 when the root context was signal-cancelled so the user-visible exit follows Unix signal convention. |
| `local.config_corrupt` | 1 | no (manual fix) | remove `~/.config/weknora/config.yaml` and re-run `weknora auth login` |
| `local.context_not_found` | 1 | no | (no canonical hint; check `weknora context list`) |
| `local.profile_not_found` | 1 | no | (no canonical hint; check `weknora profile list`) |
| `local.file_io` | 1 | no | check file permissions under `$XDG_CONFIG_HOME/weknora/` |
| `local.kb_id_required` | 1 | no | run `weknora link` to bind this directory to a knowledge base, or pass `--kb` |
| `local.kb_not_found` | 1 | no | list available with `weknora kb list` |
| `local.keychain_denied` | 1 | no (system-level) | verify keyring access; falls back to file storage |
| `local.project_link_corrupt` | 1 | no | remove `.weknora/project.yaml` and run `weknora link` again |
| `local.sse_stream_aborted` | 1 | yes (rerun chat / agent invoke) | the streaming answer was cut off mid-flight; retry, or pass `--format json` to buffer the full response |
| `local.sse_stream_aborted` | 1 | yes (rerun chat / session ask) | the streaming answer was cut off mid-flight; retry, or pass `--format json` to buffer the full response |
| `local.unimplemented` | 1 | no | (planned in a future release) |
| `local.upload_file_not_found` | 1 | no | verify the path is correct and readable |
| `local.user_aborted` | 1 | no (user said no) | no action taken; pass `-y/--yes` to skip the confirmation prompt |
@@ -241,6 +420,35 @@ For common retry patterns, agents can hardcode:
- `input.confirmation_required` → **NEVER** auto-pass `-y` without explicit user authorization
- `*.invalid_argument` / `*.missing_flag` → surface to user (don't retry)
## Exit-10 anti-patterns
Exit code 10 (`input.confirmation_required`) marks a destructive write where the
CLI refused to proceed without explicit user approval. The retry envelope includes
`retry_command` showing the exact argv that would proceed. AI agents must NEVER
auto-retry this exit code — every exit 10 is a user-in-the-loop decision.
**Don't do these:**
1. **Auto-add `-y/--yes` and retry.** The flag exists for the user, not the agent.
Surface the exit-10 envelope to the user verbatim and wait for explicit go-ahead.
2. **Parse the retry_command and run it.** The retry_command is *informational* --
showing what *would* execute. Running it without user input collapses two steps
the user is supposed to see.
3. **Wrap the call in a retry-with-backoff loop.** Exit 10 is not transient. It's
a "this needs human approval" signal, not a transient transport error.
4. **Treat exit 10 as a generic error and fall back to a less-destructive verb.**
The user asked for the destructive verb. If they want something else they'll
say so. Don't substitute.
5. **Auto-add `-y` because the *previous* exit-10 was approved.** Each invocation
stands on its own. The user's prior approval doesn't extend to similar calls.
6. **Skip the prompt by switching to `--format json`.** JSON mode still emits
`input.confirmation_required` (just in envelope form). It's the same gate.
## MCP Tool Surface
WeKnora's MCP server exposes a curated read-only tool surface. Many MCP servers in the wild ship write / mutation operations on by default and rely on credential-scope or sandbox restrictions for safety. WeKnora opts for curation instead: the server side doesn't yet enforce per-token scope, so an agent holding a user's token has full write access. Until server-side scope ships, the CLI keeps mutation tools out of the MCP surface as a belt-and-braces second line of defense. When server scope arrives this stance can loosen.
@@ -292,12 +500,13 @@ Reasons hard-required-flags is the v0.5+ default:
- Agent-friendly: MCP callers do not stall waiting for stdin prompts.
- Consistent with every existing non-auth WeKnora command.
- **Agent help blob (v0.6, partial)**: Commands MAY call
- **Agent help blob**: Commands MAY call
`cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{...})` to expose a stable
JSON used_for / required_flags / examples / output shape. Activated by
`WEKNORA_AGENT_HELP=1` at `--help` time. Currently applied to `chat`
and `kb list` only — extending to another command requires touching
only that command's `NewCmd`.
JSON used_for / required_flags / examples / output / warnings shape.
Activated by `WEKNORA_AGENT_HELP=1` at `--help` time. Warnings are
always rendered in human help (stderr, not env-gated). Applied to
`chat`, `kb list`, `session ask`, and all destructive commands.
Extending to another command requires touching only that command's `NewCmd`.
## Status / check verb pair pattern