docs(cli): AGENTS + README + CHANGELOG for v0.8

AGENTS.md gains three sections for the v0.8 surfaces:
  - Stream recovery   — session continue-stream replay-from-0 semantics
                        and the dedupe contract agents must implement
  - Dry-run contract  — when --dry-run applies, the meta.{dry_run,plan}
                        envelope shape, exit-code semantics (no exit 10
                        on destructive + --dry-run), the GET-reject rule
                        for `weknora api`, and the validation-parity
                        guarantee with the live path
  - Risk metadata     — what the Risk: prefix in --help means and how
                        cobra.Annotations["risk.{level,action}"] are
                        populated

README.md gains user-facing Dry-run preview and Resuming streams
sections.

CHANGELOG.md adds the v0.8 entry covering the new --dry-run flag,
MCP Tool.Annotations, session continue-stream, and the Risk: line.
This commit is contained in:
nullkey
2026-05-28 04:29:09 +08:00
committed by lyingbug
parent 1bae6b6b6c
commit c29d36238b
3 changed files with 172 additions and 6 deletions
+81 -3
View File
@@ -114,8 +114,9 @@ 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 CLI contract and the server's wire contract are versioned independently:
agents pin against the CLI surface, while server-side event shape evolves on
its own track.
### The one rule
@@ -149,7 +150,7 @@ is or isn't aligned with.
| | |
|---|---|
| **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 convention.) |
| **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. |
### 2. `weknora api DELETE` triggers exit-10 confirmation
@@ -458,6 +459,83 @@ auto-retry this exit code — every exit 10 is a user-in-the-loop decision.
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.
## Stream recovery
The `weknora session continue-stream <session-id> --message <msg-id>` command resumes an SSE event stream for an existing assistant message. Use cases: network-blip recovery, long-running agent invocation polling, completed-stream inspection.
### Server semantics: replay-from-0, not cursor-resume
The server **replays all stored events from the start** of the assistant message, then **tails new events**. This is NOT a cursor-from-disconnect resume. Agents reconnecting mid-stream will receive ALL previously-emitted events again.
### Agent contract
1. **Dedupe by message_id** (or maintain a per-message event hash set). Naively processing all received events causes duplicate side effects (re-running tool calls, re-rendering answers).
2. **Capture message_id from the init event** of the original `chat` or `session ask` invocation — the CLI injects `{"event":"init", "session_id":"...", "message_id":"..."}` as the first NDJSON line.
3. **Handle `local.sse_stream_aborted` typed error**: server-side buffer expired (TTL exceeded) or process restarted (memory mode). The message is no longer recoverable; restart the original query.
### Server-side buffer TTL
| Mode | TTL |
|---|---|
| `STREAM_MANAGER_TYPE=redis` | **1 hour** (server-side; not configurable from the CLI) |
| `STREAM_MANAGER_TYPE=memory` (default) | **Process lifetime** (server restart = data loss; no explicit cleanup logic) |
After TTL, `weknora session continue-stream` returns the typed error `local.sse_stream_aborted`, which maps to exit code 1 per the Error code reference.
## Dry-run contract
The `--dry-run` flag is available on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `weknora api` (POST/PUT/PATCH/DELETE only; GET rejected with FlagError exit 2).
### Envelope shape on dry-run
Success envelope (exit 0) with `data` field omitted (omitempty) and `meta.dry_run=true`:
```json
{"ok":true,"meta":{"dry_run":true,"plan":{"action":"kb.create","args":{"name":"foo","description":"bar"}}},"profile":"prod"}
```
`api` command additionally includes `method` / `path` / `body` in plan:
```json
{"ok":true,"meta":{"dry_run":true,"plan":{"action":"api.post","method":"POST","path":"/api/v1/knowledge-bases","body":{"name":"foo"}}}}
```
### Side effects suppressed
The dry-run path is **offline** — no SDK calls, no Factory.Client() init, no ResolveKB network query, no writes (keyring / `.weknora/project.yaml` / files). Works without active profile or network access.
### Interactions
| Combination | Behavior |
|---|---|
| `--dry-run` (destructive cmd, no `-y`) | NO exit-10; emits plan + exit 0 (preview implies no execution, so the confirmation gate is irrelevant) |
| `--dry-run` + `-y` | Equivalent to single `--dry-run`; `-y` is no-op (dry-run early-exits before ConfirmDestructive) |
| `--dry-run` + `api -X GET` (or default GET) | FlagError exit 2: "--dry-run requires explicit -X POST/PUT/PATCH/DELETE; default GET is read-only with no side effect to preview" |
| `--dry-run` + `--jq <expr>` | jq applied to envelope output normally |
| `--dry-run` + `kb edit my-kb` | plan.args contains user raw input (NOT ResolveKB-resolved); agent verifies kb name correctness |
| `--dry-run` + fetch-then-update (`kb edit / agent edit`) | plan.args contains user-explicit fields ONLY; agent infers server-side fetch-then-update preserves unmentioned fields |
| `--dry-run` + body containing secrets (`--input` payload) | **plan.body echoes the full body to stdout** so the agent can verify what would be sent; avoid piping secret-bearing bodies through dry-run for inspection |
### Streaming commands explicitly excluded
`session ask` and `chat` do NOT support `--dry-run` (streaming and dry-run have a semantic mismatch). For prompt-formation preview, use:
```bash
echo '{"query":"...","kb":"..."}' | weknora api -X POST /api/v1/sessions/<id>/agent-qa --input - --dry-run
```
## Risk metadata
Agents see the same `risk.action` string (in the form `noun.verb`) on three independent surfaces:
1. **Error envelope** — `envelope.error.risk.action` on an exit-10 confirmation-required error, so the agent can decide whether to escalate to the user. 11 unique values: `kb.delete`, `kb.edit`, `agent.delete`, `agent.edit`, `doc.delete`, `doc.delete_all`, `session.delete`, `chunk.delete`, `profile.remove`, `auth.logout`, `api.delete`.
2. **Help text** — a `Risk: <action> (destructive)` line prepended to the top of `--help` output on the 9 destructive cobra commands. `weknora api` is intentionally excluded: it is a generic HTTP passthrough whose risk depends on the method, so a static Risk: line would mislead for non-DELETE methods.
3. **MCP tool annotations** — `Tool.Annotations.destructiveHint` / `readOnlyHint` / `idempotentHint` / `openWorldHint` on every tool returned by `weknora mcp serve`.
The three surfaces do not auto-sync: each is wired separately so agents that only consume one surface still get the signal, but contributors adding a new destructive command must touch all three.
## 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.
+28 -3
View File
@@ -12,6 +12,30 @@ CLI history before v0.3 is recorded in the project root
## [Unreleased]
### v0.8 — Agent safety nets + MCP annotations
#### Added
- `--dry-run` flag on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `weknora api` (POST/PUT/PATCH/DELETE only; GET returns FlagError exit 2).
- envelope `meta.dry_run: true` + `meta.plan: {action, args | method+path+body}` open-map fields (omitempty in non-dry-run envelopes).
- `weknora session continue-stream <session-id> --message <msg-id>` command for SSE event stream replay/recovery.
- MCP `Tool.Annotations` on all 10 MCP serve tools (`destructiveHint` / `readOnlyHint` / `idempotentHint` / `openWorldHint` + `Title`) per MCP spec 2025-06-18.
- `cli/internal/cmdutil/risk.go`: `SetRisk(cmd, action)` helper + `RiskDestructive` const + `GetRisk(cmd)` reader.
- Help output "Risk: <action> (<level>)" line at top of 9 destructive commands' `--help` (via modified `SetAgentHelp` wrapper).
- `cli/AGENTS.md` sections: Stream recovery / Dry-run contract / Risk metadata.
- `cli/README.md` sections: Dry-run preview / Resuming streams.
#### Changed
- `SetAgentHelp` wrapper in `cli/internal/cmdutil/agenthelp.go` now prepends "Risk:" line in default (non-JSON) help branch when `cmd.Annotations["risk.action"]` is set. WEKNORA_AGENT_HELP=1 JSON path unchanged.
- 9 destructive commands' `SetAgentHelp` Warnings standardized: line 1 is a verbatim exit-10 / `-y` reminder; line 2 carries per-command destructive context.
- `cli/cmd/api/api.go` now has `SetAgentHelp` with runtime exit-10 note for `-X DELETE/PUT/PATCH`.
- `cli/cmd/doc/delete.go` Warnings adds a 3rd line describing `--all` blast radius.
- Bumped `github.com/modelcontextprotocol/go-sdk` v1.6.0 → v1.6.1 (patch; opt-in `MCPGODEBUG` env var).
#### Breaking
*(none — v0.8 is fully additive on top of v0.7 envelope shape, NDJSON vocab, and typed code contracts; existing consumers continue to work and the new fields are optional via `omitempty`)*
---
### v0.7 — Agent-first wire contract + command-surface cleanup
#### BREAKING (v0.6 → v0.7)
@@ -67,7 +91,8 @@ CLI history before v0.3 is recorded in the project root
- `weknora doc create --text "..."` — direct text knowledge.
- URL-only flags (`--title`, `--file-type`, `--tag-id`) moved to `doc fetch`.
- Rationale: `upload --from-url` mixed semantics ("send out" vs "pull in");
split matches the server's three endpoints + gh CLI conventions.
the three-verb split matches the server's three endpoints and gives each
one a single unambiguous shape.
- **`weknora kb empty` removed; use `weknora doc delete --all --kb=<id>`.**
- Atomic server `ClearKnowledgeBaseContents` (no list-then-delete race).
- Same exit-10 `-y/--yes` guard as `kb delete`.
@@ -75,8 +100,8 @@ CLI history before v0.3 is recorded in the project root
`weknora doc delete --all --kb=kb_x -y`.
- **`weknora api -d/--data` flag removed; use `--input <file>` or `--input -`
(stdin).**
- `weknora api` now accepts any non-empty HTTP method (whitelist removed;
matches `gh api` / `curl` behaviour).
- `weknora api` now accepts any non-empty HTTP method (whitelist removed)
so the escape hatch can hit endpoints the CLI doesn't natively model.
- Migration: `weknora api -d '{"foo":1}' /endpoint` →
`echo '{"foo":1}' | weknora api --input - /endpoint`.
- **Batch operations envelope shape — per-item `ok` pattern.**
+63
View File
@@ -257,6 +257,69 @@ operations that intentionally go through `weknora api`:
---
## Dry-run preview
Add `--dry-run` to any mutation command to preview the would-be action without executing it. Useful for verifying flag/arg parsing before committing to a destructive operation, or for agent-side action planning.
```bash
# Preview a kb create without actually creating
weknora kb create --name "test-kb" --description "for review" --dry-run
# Output (single line; pretty-printed here for readability):
# {
# "ok": true,
# "meta": {
# "dry_run": true,
# "plan": {
# "action": "kb.create",
# "args": {"name": "test-kb", "description": "for review"}
# }
# }
# }
# Exit code: 0
```
dry-run is **offline**: no network calls, no file IO, no credential touches. Works without an active profile.
For destructive commands, dry-run does NOT trigger the exit-10 confirmation flow:
```bash
weknora kb delete kb_xxxx --dry-run # exit 0, no prompt
weknora kb delete kb_xxxx # exit 10, prompts for -y
```
For the `api` command, dry-run requires explicit write method (POST/PUT/PATCH/DELETE); GET returns FlagError:
```bash
echo '{"name":"foo"}' | weknora api -X POST /api/v1/knowledge-bases --input - --dry-run # OK
weknora api /api/v1/knowledge-bases --dry-run # exit 2: requires explicit -X
```
---
## Resuming streams
The `weknora session continue-stream` command resumes an SSE event stream for an existing assistant message. Useful for network-blip recovery or polling long-running agent invocations:
```bash
# Original streaming call captures session_id + message_id from init event:
weknora session ask "..." --kb kb_xxxx --format ndjson | tee /tmp/stream.ndjson
# {"event":"init","session_id":"sess_abc","message_id":"msg_xyz"}
# ... events flow ...
# [network blip]
# Resume the same stream:
weknora session continue-stream sess_abc --message msg_xyz
# Server REPLAYS all stored events from the start, then tails new ones.
# Agent must dedupe (by message_id or event hash) to avoid double-processing.
```
Server-side buffer TTL: 1 hour for redis mode; process lifetime for memory mode (default). After TTL, expect `local.sse_stream_aborted` typed error.
See `cli/AGENTS.md` "Stream recovery" section for the full agent contract.
---
## Health check
Run `weknora doctor` for a 4-status diagnostic (OK / warn / fail /