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
main
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

2
cli/.gitignore vendored
View File

@ -1,2 +1,4 @@
bin/
coverage.out
ROADMAP.md
ROADMAP.html

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

View File

@ -12,6 +12,137 @@ CLI history before v0.3 is recorded in the project root
## [Unreleased]
### v0.7 — Agent-first wire contract + 命令面集中清理
#### BREAKING (v0.6 → v0.7)
- **All JSON output now wrapped in symmetric envelope.**
- Success on stdout: `{ok:true, data?:<T>, meta?, _notice?, profile?}` (`data`
omitted on mutation-only success).
- Error on stderr (json mode): `{ok:false, error:{type, message, hint?,
retry_command?, retry_after_seconds?, risk?, detail?}, _notice?}`.
- `meta.count` / `meta.has_more` surface list totals and server-side
pagination state. `meta.next_cursor` / `meta.total_count` /
`meta.request_id` are reserved — populated when the SDK exposes them
(planned for v0.8).
- Migration: replace `jq '.[]'` with `jq '.data[]'`; `.id` → `.data.id`;
list-count consumers read `.meta.count`.
- **`--format` default flips 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
`text | json | ndjson` unchanged.
- Migration: humans on a TTY pass `--format text` (or set
`WEKNORA_FORMAT=text` env) for the prior auto-text behavior.
- **`chat` / `session ask` default to NDJSON event-stream (SDK passthrough).**
- v0.6: TTY rendered a live SSE animation; `--format json` produced a buffered
object; NDJSON was opt-in.
- v0.7: `--format json` and `--format ndjson` both emit one JSON event per line
(no envelope wrapping). CLI injects exactly one `init` event at stream head;
all subsequent events pass through verbatim from the SDK (`answer` /
`tool_call` / `tool_result` / `references` / `thinking` / `reflection` /
`error` / `complete` for chat; agent vocab is a subset).
- For prose rendering: `--format text`.
- **`weknora context` command group renamed to `weknora profile`.**
- Subcommands `context list/add/remove/use` → `profile list/add/remove/use`.
- Global flag `--context` → `--profile`.
- Binding file `.weknora/project.yaml` field `context:` → `profile:`
(no backwards-compat alias; re-run `weknora link` to regenerate).
- `profile use` JSON fields `current_context` / `previous_context` →
`current_profile` / `previous_profile`.
- `weknora link` JSON field `context` → `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`.
- **`weknora agent invoke` removed; use `weknora session ask --agent <id>`.**
- Server route is `POST /sessions/{session_id}/agent-qa` — session-anchored.
- `weknora agent` keeps CRUD only (list / view / create / edit / delete /
status / check).
- Migration: `weknora agent invoke ag_x "Q"` →
`weknora session ask --agent ag_x "Q"` (auto-creates session if none given).
- **`weknora doc upload` split into three commands.**
- `weknora doc upload <file>` — local file only.
- `weknora doc fetch <url>` — server-side remote fetch (was `upload --from-url`).
- `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.
- **`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`.
- Migration: `weknora kb empty kb_x -y` →
`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;
aligns with gh / lark / curl).
- Migration: `weknora api -d '{"foo":1}' /endpoint` →
`echo '{"foo":1}' | weknora api --input - /endpoint`.
- **Batch operations envelope shape — per-item `ok` pattern.**
- `weknora doc delete id1,id2,id3` and similar multi-id mutations now emit:
`{ok, data:[{id, ok, result?|error?}, ...], meta:{count, successes, failures}}`.
- Top-level `ok` = AND-aggregate of per-item `ok` (false on partial failure).
- All-fail stays in batch shape (not error envelope) — agents can iterate
detail per id.
- jq pattern: `jq '.data[] | select(.ok == false) | .id'`.
- **MCP server tool errors now return `StructuredContent`.**
- `CallToolResult{IsError: true, Content:[text-fallback],
StructuredContent:{type, message, hint?, retry_command?, risk?, detail?}}`.
- Shape mirrors stderr `envelope.error` sub-object — one parser handles both.
- **Unknown subcommand emits typed envelope.**
- `input.unknown_subcommand` with `detail.{unknown, command_path, available[]}`
+ `retry_command: "<parent> --help"`. Replaces v0.6's free-form
`"unknown command \"x\" for \"weknora\""` prose.
#### Added
- **`WEKNORA_PROFILE` env var** selects the active profile for a single
invocation (equivalent to `--profile <name>` global flag). Overridden by
explicit `--profile`. Useful for CI scripts that cannot pass global flags.
- **`WEKNORA_FORMAT` env var** sets the default `--format`. Values:
`text | json | ndjson`. Overridden by explicit `--format`. Invalid values
ignored.
- **`error.retry_command`** — directly-executable retry argv, distinct from
prose `hint`. Agents read `retry_command` without regex-parsing `hint`.
- **`error.retry_after_seconds`** — `server.rate_limited` / `server.timeout`
surface server `Retry-After` header verbatim. CLI-direct (`weknora api`)
parses HTTP `Retry-After` headers; SDK-mediated paths will gain coverage
as the SDK exposes typed transport errors.
- **`error.risk.{level, action}`** — destructive writes carry
`{level:"destructive", action:"<noun.verb>"}` (e.g. `doc.delete_all`,
`kb.delete`). Reserved levels `"read"` / `"write"` not yet emitted.
- **`_notice` envelope channel reserved** — open-map infrastructure in place
for deprecation / version_skew / security notices. Producer wiring planned
for v0.8 when the SDK exposes version metadata. Additive non-breaking;
unknown keys must be ignored.
- **`meta.count` / `meta.has_more`** on list commands. `meta.next_cursor` /
`meta.total_count` / `meta.request_id` reserved — populated when the SDK
exposes them (planned for v0.8).
- **`weknora doc fetch <url>`** — new command (see split above).
- **`weknora doc create --text "..."`** — new command (see split above).
- **`weknora session ask --agent <id> "..."`** — new command (replaces
`agent invoke`).
- **`weknora doc delete --all --kb=<id>`** — new mode of `doc delete`
(replaces `kb empty`).
- **NDJSON `init` event** at stream head for `chat` / `session ask` —
carries `session_id` + optional `kb_id` / `agent_id` / `model` / `profile`.
`request_id` field is reserved (not currently populated; planned for v0.8
when the SDK exposes response headers).
- **`AgentHelp.Warnings`** — destructive commands (`kb delete`, `doc delete`,
`agent delete`, `session delete`, `chunk delete`, `profile remove`,
`kb edit`, `agent edit`, `auth logout`) render an "AI agents:" warnings
block in `--help` to set explicit expectations around `-y/--yes`.
#### Changed
- `AGENTS.md` adds `## Wire contract for AI agents`, `## Deliberate deviations
+ mainstream alignments`, `## Pre-1.0 breaking policy`, `## Exit-10
anti-patterns` sections.
- `README.md` adds `### Agent quick start` under `## Wire contract`.
- `chunk` command group help: disambiguation prose vs `search chunks` removed
in favour of plain verb descriptions.
#### Deprecated (will remove in v0.8+)
- *(none — pre-release breaking release; no deprecation alias period.)*
---
### v0.6 — agent runtime hardening: --format, doc wait, --log-level, status, multi-id delete, paginate
#### BREAKING (v0.5 → v0.6)
@ -30,9 +161,9 @@ CLI history before v0.3 is recorded in the project root
#### Added
- **`--format text|json|ndjson`** flag selecting the stdout serialization.
Registered per-command (only commands that honor `--format` register it;
others reject it with `unknown flag` / exit 2). Output mode auto-resolves
to `text` on a TTY and `json` when stdout is piped, so
`weknora kb list | jq` works without an explicit flag.
others reject it with `unknown flag` / exit 2). Output mode auto-resolved
to `text` on a TTY and `json` when stdout was piped (v0.7 promoted the
flag to a persistent global and made the default always `json`).
- **`--jq '<expr>'`** flag pairs with `--format json|ndjson` to filter or
project the JSON output via a jq expression.
- **`weknora doc wait <id> [<id>...]`** — block until every document reaches a

View File

@ -11,13 +11,13 @@ and documents, run hybrid search, chat with grounded answers, or expose
a curated read-only MCP tool surface for AI agents.
Available Commands:
agent Manage and invoke custom agents
agent Manage custom agents (CRUD + status/check)
api Make a raw API request to the WeKnora server
auth Manage authentication credentials and contexts
auth Manage authentication credentials and profiles
chat Ask a streaming RAG question against a knowledge base
chunk Manage document chunks (RAG retrieval debug)
completion Generate the autocompletion script for the specified shell
context Manage CLI contexts (named connection targets)
profile Manage CLI profiles (named connection targets)
doc Manage documents in a knowledge base
doctor Run 4 self-checks: base URL, auth, server version, credential storage
help Help about any command
@ -80,9 +80,9 @@ weknora search chunks "what is reciprocal rank fusion?"
# 7. Ask the LLM (streams to terminal)
weknora chat "summarise the design doc"
# 8. Manage custom agents (full hybrid surface: see `weknora agent --help`)
# 8. Manage custom agents and run them (see `weknora agent --help` / `weknora session --help`)
weknora agent list
weknora agent invoke ag_abc "what's our q4 retention plan?"
weknora session ask --agent ag_abc "what's our q4 retention plan?"
# 9. Inspect a document's chunks for RAG retrieval debug
weknora chunk list --doc doc_xyz
@ -96,6 +96,26 @@ weknora agent check ag_abc # deep: probes every KB in the agent's scope
---
### Agent quick start
For AI agents (Claude Code, Cursor, Gemini CLI, etc.) integrating WeKnora:
1. Install: `brew install weknora` or `go install github.com/Tencent/WeKnora/cli@latest`
2. Authenticate (background; extract login URL for the user):
```bash
weknora auth login --host <server-url>
```
3. Register MCP in the host's MCP config:
```json
{"mcpServers": {"weknora": {"command": "weknora", "args": ["mcp", "serve"]}}}
```
4. Read the [wire contract](AGENTS.md#wire-contract-for-ai-agents) before
parsing `--format json` output.
5. Read the [exit-10 anti-patterns](AGENTS.md#exit-10-anti-patterns) before
any destructive call.
---
## Multi-context
Switch between several WeKnora servers (or several tenants on the same server)
@ -105,15 +125,15 @@ without re-logging in:
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
weknora profile 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
under `$XDG_CONFIG_HOME/weknora/secrets/`. The active profile lives in
`~/.config/weknora/config.yaml`.
To remove a context's stored credentials:
To remove a profile's stored credentials:
```bash
weknora auth logout # current context
@ -150,9 +170,9 @@ weknora kb list --format json --jq '.[].id' # jq over the bare da
```
`--format ndjson` is also accepted for streaming list commands; each
element is emitted as its own JSON line. When stdout is not a TTY (pipe
or redirect), `--format json` is the default — running `weknora kb list
| jq` works without an explicit flag.
element is emitted as its own JSON line. `--format json` is the default
regardless of TTY — running `weknora kb list | jq` works without an
explicit flag. Use `--format text` for human-readable output.
### Errors
@ -193,18 +213,19 @@ wait/poll outcomes: `operation.timeout`, `operation.failed`, `operation.cancelle
| `130` | `operation.cancelled` (SIGINT / SIGTERM) | stop, do not retry |
**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) / `agent delete` / `chunk delete` when running headless.
explicit confirmation". Pass `-y/--yes` on `kb delete` /
`doc delete` (including `--all --kb=<id>`) / `session delete` /
`profile remove` (on the current profile) / `agent delete` /
`chunk delete` when running headless.
**Never auto-add `-y` without the user's explicit go-ahead** — exit 10
is the guard against unintended writes.
### Other agent ergonomics
- For chat / agent invoke in agent contexts, pass `--format json` —
- For chat / session ask in agent contexts, pass `--format json` —
streaming tokens to stdout makes JSON parsing impossible.
- `--format json` composes with the global `--context <name>` for
single-shot context overrides without disk writes.
- `--format json` composes with the global `--profile <name>` for
single-shot profile overrides without disk writes.
- `weknora mcp serve` exposes a curated read-only tool surface over
stdio MCP for any MCP-compatible client.
@ -226,7 +247,7 @@ operations that intentionally go through `weknora api`:
- **Per-request `chat` parameters** — multi-KB scope, summary model
override, image attachments, web search toggle. Use `weknora api POST
/api/v1/knowledge-chat/<session-id> --input -`.
- **Per-request `agent invoke` overrides** — same shape via
- **Per-request `session ask --agent` overrides** — same shape via
`weknora api POST /api/v1/agent-chat/<session-id> --input -`.
- **Operations without a CLI verb** — register / change-password /
OIDC flows, organization / sharing endpoints, tenant management.

View File

@ -1 +0,0 @@
{"current_context":"production","previous_context":"staging"}

View File

@ -0,0 +1 @@
{"ok":true,"data":{"current_profile":"production","previous_profile":"staging"},"profile":"staging"}

View File

@ -102,7 +102,7 @@ func emitAgentCheck(res *AgentCheckResult, fopts *cmdutil.FormatOptions, w io.Wr
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res, nil)
case cmdutil.FormatHuman, "":
case cmdutil.FormatText, "":
return writeAgentCheckText(w, res)
default:
return fmt.Errorf("unsupported --format %q for agent check", fopts.Mode)

View File

@ -138,11 +138,11 @@ func TestEmitAgentCheck_JSON(t *testing.T) {
}
}
func TestEmitAgentCheck_TextHuman(t *testing.T) {
func TestEmitAgentCheck_Text(t *testing.T) {
trueP := true
var buf bytes.Buffer
res := &AgentCheckResult{ID: "ag_x", Reachable: true, ModelID: "m_x", KBScopeAllReachable: &trueP}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
if err := emitAgentCheck(res, fopts, &buf); err != nil {
t.Fatalf("%v", err)
}

View File

@ -292,7 +292,7 @@ func openConfigFile(path string) (io.Reader, string, error) {
}
// emitAgent writes the Agent to stdout (bare SDK shape for --format json,
// human KV otherwise). Shared by create and edit; defined here for proximity
// text KV otherwise). Shared by create and edit; defined here for proximity
// to the create flow.
func emitAgent(fopts *cmdutil.FormatOptions, ag *sdk.Agent) error {
if fopts.WantsJSON() {

View File

@ -44,7 +44,7 @@ func TestDelete_NonTTY_WithYes_Direct(t *testing.T) {
require.NoError(t, runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_abc", Yes: true},
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{},
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
))
assert.Equal(t, "ag_abc", svc.gotID)
assert.Contains(t, out.String(), "ag_abc")
@ -56,7 +56,7 @@ func TestDelete_404_PropagatesNotFound(t *testing.T) {
err := runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_missing", Yes: true},
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{},
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
)
require.Error(t, err)
var typed *cmdutil.Error
@ -71,7 +71,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
require.NoError(t, runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_abc"},
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p,
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
))
assert.True(t, p.Asked)
assert.Equal(t, "ag_abc", svc.gotID)
@ -84,7 +84,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
err := runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_abc"},
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p,
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
)
require.Error(t, err)
var typed *cmdutil.Error

View File

@ -257,7 +257,7 @@ func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "Output format: human | json | ndjson")
pf.String("format", "", "Output format: text | json | ndjson")
pf.StringP("jq", "q", "", "")
ag := &cobra.Command{Use: "agent"}
ag.AddCommand(edit)

View File

@ -23,9 +23,9 @@ func (f *fakeListSvc) ListAgents(_ context.Context) ([]sdk.Agent, error) {
return f.items, f.err
}
func TestList_Empty_Human(t *testing.T) {
func TestList_Empty_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}); err != nil {
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no agents)") {
@ -53,14 +53,14 @@ func TestList_Empty_JSON(t *testing.T) {
}
}
func TestList_NonEmpty_Human_RendersColumns(t *testing.T) {
func TestList_NonEmpty_Text_RendersColumns(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.Agent{
{ID: "ag_a", Name: "Research", IsBuiltin: true, UpdatedAt: now.Add(-1 * time.Hour)},
{ID: "ag_b", Name: "Triage", UpdatedAt: now.Add(-3 * 24 * time.Hour)},
}
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
@ -162,7 +162,7 @@ func TestList_Limit_Zero_Rejected(t *testing.T) {
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: makeAgents(2)})
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeAgents(2)})
if err == nil {
t.Fatal("expected error for negative --limit")
}

View File

@ -88,7 +88,7 @@ func emitAgentStatus(res *AgentStatusResult, fopts *cmdutil.FormatOptions, w io.
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res, nil)
case cmdutil.FormatHuman, "":
case cmdutil.FormatText, "":
return writeAgentStatusText(w, res)
default:
return fmt.Errorf("unsupported --format %q for agent status", fopts.Mode)

View File

@ -93,10 +93,10 @@ func TestEmitAgentStatus_JSON(t *testing.T) {
}
}
func TestEmitAgentStatus_TextHuman(t *testing.T) {
func TestEmitAgentStatus_Text(t *testing.T) {
var buf bytes.Buffer
res := &AgentStatusResult{ID: "ag_x", Reachable: true, ModelID: "m_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
if err := emitAgentStatus(res, fopts, &buf); err != nil {
t.Fatalf("%v", err)
}

View File

@ -23,7 +23,7 @@ func (f *fakeViewSvc) GetAgent(_ context.Context, _ string) (*sdk.Agent, error)
return f.resp, f.err
}
func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
func TestView_Text_RendersMetadataAndConfig(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Agent{
ID: "ag_abc",
@ -41,7 +41,7 @@ func TestView_Human_RendersMetadataAndConfig(t *testing.T) {
WebSearchEnabled: true,
},
}}
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_abc"); err != nil {
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_abc"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -69,7 +69,7 @@ func TestAgentViewFields_TopLevelOnly(t *testing.T) {
}
// TestRenderAgent_RendersAllGroupsWithOmitEmpty validates the grouped
// human rendering: present groups print, zero-value fields omit, and an
// text rendering: present groups print, zero-value fields omit, and an
// entire section is suppressed when all of its fields are zero.
func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
@ -84,7 +84,7 @@ func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
KBSelectionMode: "selected",
KnowledgeBases: []string{"kb_a"},
FAQPriorityEnabled: true,
WebSearchEnabled: false, // zero — omitted in human
WebSearchEnabled: false, // zero — omitted in text
FallbackStrategy: "fixed",
FallbackResponse: "I don't know.",
},
@ -118,7 +118,7 @@ func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
}
}
func TestView_Human_OmitsEmptyFields(t *testing.T) {
func TestView_Text_OmitsEmptyFields(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Agent{
ID: "ag_min",
@ -126,7 +126,7 @@ func TestView_Human_OmitsEmptyFields(t *testing.T) {
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}}
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_min"); err != nil {
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_min"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -169,7 +169,7 @@ func TestView_JSON_BareObject(t *testing.T) {
func TestView_404_MapsToResourceNotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewSvc{err: errors.New("HTTP error 404: agent not found")}
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "ag_missing")
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_missing")
if err == nil {
t.Fatal("expected error, got nil")
}

View File

@ -53,7 +53,7 @@ func TestAPI_GetSuccess(t *testing.T) {
})
defer stop()
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "GET", "/api/v1/foo", false); err != nil {
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/foo", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
got := out.String()
@ -119,7 +119,7 @@ func TestAPI_PostWithStdinInput(t *testing.T) {
defer stop()
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/things", false); err != nil {
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/things", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if seenMethod != http.MethodPost || seenPath != "/api/v1/things" {
@ -146,7 +146,7 @@ func TestAPI_InputFile(t *testing.T) {
defer stop()
opts := &Options{Input: tmp}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/x", false); err != nil {
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
@ -167,7 +167,7 @@ func TestAPI_InputDash_Stdin(t *testing.T) {
payload := `{"k":"from-stdin"}`
opts := &Options{Input: "-", StdinReader: strings.NewReader(payload)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "POST", "/api/v1/x", false); err != nil {
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
@ -183,7 +183,7 @@ func TestAPI_NotFound(t *testing.T) {
})
defer stop()
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, "GET", "/api/v1/missing", false)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/missing", false)
if err == nil {
t.Fatal("expected error for 404")
}
@ -203,7 +203,7 @@ func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
for _, m := range []string{"OPTIONS", "PATCH", "TRACE", "CUSTOM"} {
t.Run(m, func(t *testing.T) {
seenMethod = ""
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, cli, m, "/api/v1/things", false)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, m, "/api/v1/things", false)
if err != nil {
t.Fatalf("expected method %q to be accepted, got %v", m, err)
}
@ -216,7 +216,7 @@ func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
func TestAPI_EmptyMethodRejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil, "", "/api/v1/things", false)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "", "/api/v1/things", false)
if err == nil {
t.Fatal("expected error for empty method")
}
@ -228,7 +228,7 @@ func TestAPI_EmptyMethodRejected(t *testing.T) {
func TestAPI_PathWithoutSlash(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil, "GET", "api/v1/things", false)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "GET", "api/v1/things", false)
if err == nil {
t.Fatal("expected error for missing leading slash")
}

View File

@ -77,7 +77,7 @@ func TestPersistAPIKey_WritesContext(t *testing.T) {
Context: "ci",
APIKey: "sk-zzz",
}
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil))
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
v, _ := store.Get("ci", "api_key")
assert.Equal(t, "sk-zzz", v)
cfg, _ := f.Config()

View File

@ -19,7 +19,7 @@ func newListFactory(cfg *config.Config) *cmdutil.Factory {
}
}
func TestList_HumanRender(t *testing.T) {
func TestList_TextRender(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cfg := &config.Config{
CurrentContext: "prod",
@ -28,7 +28,7 @@ func TestList_HumanRender(t *testing.T) {
"staging": {Host: "https://staging", APIKeyRef: "keychain://staging/api_key"},
},
}
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newListFactory(cfg)))
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(cfg)))
got := out.String()
// One row per context, current marked with `*`.
@ -44,7 +44,7 @@ func TestList_HumanRender(t *testing.T) {
func TestList_Empty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newListFactory(&config.Config{})))
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(&config.Config{})))
assert.Contains(t, out.String(), "No profiles configured")
}

View File

@ -62,7 +62,7 @@ func TestRunLogin_PasswordMode(t *testing.T) {
Host: "https://kb.example.com",
Context: "prod",
}
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc))
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
assert.Equal(t, "a@b.c", svc.got.email)
assert.Equal(t, "secret", svc.got.password)
@ -84,7 +84,7 @@ func TestRunLogin_WithToken(t *testing.T) {
WithToken: true,
StdinReader: strings.NewReader(" sk-1234 \n"),
}
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil))
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
got, _ := store.Get("ci", "api_key")
assert.Equal(t, "sk-1234", got)
cfg, _ := f.Config()
@ -107,7 +107,7 @@ func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
WithToken: true,
StdinReader: strings.NewReader("sk-bad"),
}
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -139,7 +139,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
WithToken: true,
StdinReader: strings.NewReader(""),
}
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "input.missing_flag")
}
@ -147,7 +147,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
func TestRunLogin_BadHost(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
@ -156,7 +156,7 @@ func TestRunLogin_LoginRefused(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "x"})
svc := &fakeLoginService{resp: &sdk.LoginResponse{Success: false, Message: "bad password"}}
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc)
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc)
require.Error(t, err)
assert.Contains(t, err.Error(), "auth.bad_credential")
}

View File

@ -47,7 +47,7 @@ func TestLogout_CurrentContext(t *testing.T) {
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
},
}
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
assert.Empty(t, cfg.CurrentContext, "current_context should clear when removed")
assert.NotContains(t, cfg.Contexts, "prod")
@ -75,7 +75,7 @@ func TestLogout_NamedContext(t *testing.T) {
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
},
}
require.NoError(t, runLogout(&LogoutOptions{Name: "staging", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{Name: "staging", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
assert.Equal(t, "prod", cfg.CurrentContext, "current_context untouched when removing other")
assert.NotContains(t, cfg.Contexts, "staging")
@ -93,7 +93,7 @@ func TestLogout_All(t *testing.T) {
"staging": {Host: "https://staging"},
},
}
require.NoError(t, runLogout(&LogoutOptions{All: true, Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{All: true, Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
assert.Empty(t, cfg.Contexts)
assert.Empty(t, cfg.CurrentContext)
@ -103,7 +103,7 @@ func TestLogout_NoContexts(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
cfg := &config.Config{}
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -117,7 +117,7 @@ func TestLogout_UnknownName(t *testing.T) {
CurrentContext: "prod",
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
}
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -130,7 +130,7 @@ func TestLogout_NoCurrentNoFlag(t *testing.T) {
cfg := &config.Config{
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
}
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)

View File

@ -72,7 +72,7 @@ func TestRefresh_Happy(t *testing.T) {
AccessToken: "new-access",
RefreshToken: "new-refresh",
}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc)))
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
assert.Equal(t, "old-refresh", svc.gotTok, "must pass stored refresh token to SDK")
gotAccess, _ := store.Get("prod", "access")
@ -97,7 +97,7 @@ func TestRefresh_NamedContext(t *testing.T) {
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{
Success: true, AccessToken: "new-stg-access", RefreshToken: "new-stg-refresh",
}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc)))
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
assert.Equal(t, "stg-refresh", svc.gotTok, "--name=staging must refresh the staging context, not current")
// current is untouched
@ -109,7 +109,7 @@ func TestRefresh_NamedContext(t *testing.T) {
func TestRefresh_NoCurrentContext(t *testing.T) {
iostreams.SetForTest(t)
f := newRefreshFactory(t, &config.Config{}, secrets.NewMemStore())
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -125,7 +125,7 @@ func TestRefresh_APIKeyContext(t *testing.T) {
Contexts: map[string]config.Context{"ci": {Host: "https://kb", APIKeyRef: "mem://ci/api_key"}},
}
f := newRefreshFactory(t, cfg, store)
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -143,7 +143,7 @@ func TestRefresh_NoRefreshTokenStored(t *testing.T) {
}
// MemStore is empty - RefreshRef points to a slot that doesn't exist.
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -161,7 +161,7 @@ func TestRefresh_ServerRefused(t *testing.T) {
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{Success: false, Message: "refresh token expired"}}
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -184,7 +184,7 @@ func TestRefresh_TransportError(t *testing.T) {
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{err: errors.New("connection reset")}
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)

View File

@ -33,7 +33,7 @@ func newCurrentUserResponse(user *sdk.AuthUser, tenant *sdk.AuthTenant) *sdk.Cur
return r
}
func TestRunStatus_HumanOutput(t *testing.T) {
func TestRunStatus_TextOutput(t *testing.T) {
out, _ := iostreams.SetForTest(t)
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{
@ -52,7 +52,7 @@ func TestRunStatus_HumanOutput(t *testing.T) {
&sdk.AuthTenant{ID: 7, Name: "Acme"},
),
}
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc))
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
got := out.String()
assert.Contains(t, got, "profile: prod")
assert.Contains(t, got, "host: https://kb.example.com")
@ -83,7 +83,7 @@ func TestRunStatus_JSONOutput(t *testing.T) {
func TestRunStatus_NoSDKClient(t *testing.T) {
iostreams.SetForTest(t)
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &cmdutil.Factory{}, nil)
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &cmdutil.Factory{}, nil)
require.Error(t, err)
assert.True(t, cmdutil.IsAuthError(err))
}
@ -93,7 +93,7 @@ func TestRunStatus_SDKError_Transport(t *testing.T) {
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{CurrentContext: "p", Contexts: map[string]config.Context{"p": {Host: "https://x"}}}))
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, &fakeStatusService{err: assert.AnError})
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: assert.AnError})
require.Error(t, err)
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems -
// classify network.error so retry logic / exit code 7 / IsTransient apply.
@ -105,7 +105,7 @@ func TestRunStatus_SDKError_HTTP401(t *testing.T) {
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{CurrentContext: "p", Contexts: map[string]config.Context{"p": {Host: "https://x"}}}))
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
require.Error(t, err)
assert.True(t, cmdutil.IsAuthError(err))
}

View File

@ -34,7 +34,7 @@ func TestAuthToken_BearerMode_PlainOutput(t *testing.T) {
_ = store.Set("prod", "access", "jwt-token-xyz")
out, _ := iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err != nil {
t.Fatalf("runToken: %v", err)
}
@ -58,7 +58,7 @@ func TestAuthToken_APIKeyMode_PlainOutput(t *testing.T) {
_ = store.Set("ci", "api_key", "sk_test_apikey_42")
out, _ := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if got := out.String(); got != "sk_test_apikey_42" {
@ -129,7 +129,7 @@ func TestAuthToken_NoCurrentContext(t *testing.T) {
cfg := &config.Config{}
store := secrets.NewMemStore()
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err == nil {
t.Fatal("expected error, got nil")
}
@ -154,7 +154,7 @@ func TestAuthToken_ProfileOverride(t *testing.T) {
f.ProfileOverride = "staging"
out, _ := iostreams.SetForTest(t)
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if got := out.String(); got != "staging-key" {
@ -172,7 +172,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) {
store := secrets.NewMemStore()
// no Set - keyring is empty
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err == nil {
t.Fatal("expected auth.unauthenticated, got nil")
}
@ -190,7 +190,7 @@ func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
}
store := secrets.NewMemStore()
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err == nil {
t.Fatal("expected auth.unauthenticated, got nil")
}
@ -234,7 +234,7 @@ func makeAPIKeyCfg() (*config.Config, *secrets.MemStore) {
func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
cfg, store := makeBearerCfg()
out, errBuf := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "jwt-xyz" {
@ -248,7 +248,7 @@ func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
cfg, store := makeBearerCfg()
out, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "jwt-xyz" {
@ -265,7 +265,7 @@ func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
cfg, store := makeAPIKeyCfg()
out, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "sk_42" {

View File

@ -3,15 +3,16 @@
//
// Two output modes share a single SDK call:
//
// - Stream mode (TTY + text format): write each StreamResponse.Content
// - Stream mode (TTY + --format text): write each StreamResponse.Content
// fragment directly to iostreams.IO.Out as it arrives, then print a
// footer with knowledge references. This is the "feels alive" UX a
// human typing in a terminal expects.
//
// - Accumulate mode (--format json / pipe): buffer every fragment via
// sse.Accumulator and emit a single JSON object (or a single plain-text
// answer + references block) once Done. Agents and pipes get a
// deterministic single record to parse.
// - NDJSON mode (--format json / --format ndjson / pipe): inject a CLI
// "init" event at stream head, then pass through every SDK event verbatim
// as NDJSON lines. Agents and pipes get a live event stream they can
// parse incrementally. --format json routes here too — buffered JSON
// envelope makes no sense for a streaming command (§5).
//
// The SDK's KnowledgeQAStream callback contract is invoked sequentially on
// one goroutine, so neither mode needs locking. The runChat core takes a
@ -21,8 +22,6 @@ package chat
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
@ -31,15 +30,18 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
// chatFields enumerates the fields surfaced for `--format json` discovery
// on `chat`. Mirrors the chatData struct json tags.
// chatFields enumerates the NDJSON init-event fields surfaced for
// `--format json` / `--format ndjson` discovery on `chat`. Reflects the
// InitEvent head line + the raw SDK event vocabulary (§5).
var chatFields = []string{
"answer", "references", "thinking",
"session_id", "assistant_message_id", "kb_id", "query",
"session_id", "kb_id",
// SDK event fields (pass-through): response_type, content, done,
// knowledge_references, assistant_message_id, session_id
}
type Options struct {
@ -56,23 +58,6 @@ type ChatService interface {
KnowledgeQAStream(ctx context.Context, sessionID string, req *sdk.KnowledgeQARequest, cb func(*sdk.StreamResponse) error) error
}
// chatData is the JSON payload emitted on the JSON path. Mirrors what an
// agent needs to continue a conversation: the answer text, retrieval
// references, and the session pointer to thread follow-ups.
type chatData struct {
Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"`
// Thinking holds the reasoning / reflection text emitted by reasoning
// models via response_type=thinking frames. Omitted when empty
// (non-reasoning model or model didn't surface reasoning for this
// query).
Thinking string `json:"thinking,omitempty"`
SessionID string `json:"session_id"`
AssistantMessageID string `json:"assistant_message_id,omitempty"`
KBID string `json:"kb_id"`
Query string `json:"query"`
}
// NewCmd builds `weknora chat <text>`.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
@ -84,8 +69,12 @@ answer back. By default a fresh session is created on first invocation; pass
--session to continue an existing conversation.
Modes:
TTY (text format, default): live token streaming + reference footer
--format json / pipe: buffered, emitted once on completion`,
--format text: live token streaming + reference footer
--format json / --format ndjson / pipe (default): NDJSON event stream —
one init line at head (session_id, kb_id),
then raw SDK events verbatim. Both json
and ndjson flags produce the same NDJSON
stream (§5).`,
Example: ` weknora chat "What is RRF?" --kb a32a63ff-fb36-4874-bcaa-30f48570a694
weknora chat "Summarise this design doc" --kb my-kb --format json
weknora chat "Continue?" --session sess_abc`,
@ -116,10 +105,10 @@ Modes:
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
cmdutil.AddFormatFlag(cmd, chatFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Ask a streaming RAG question against a knowledge base and get a single answer + cited chunks. Agents should use --format json for parseable output.",
UsedFor: "Ask a streaming RAG question against a knowledge base. Produces an NDJSON event stream: init line (session_id, kb_id) then raw SDK events. Use --format json or --format ndjson.",
RequiredFlags: []string{"--kb"},
Examples: []string{`weknora chat "What is RRF?" --kb kb_abc --format json`},
Output: "answer / references / session_id / thinking — see chatData struct (chat.go)",
Output: "NDJSON stream: {type:init, session_id, kb_id} then SDK events (response_type, content, done, knowledge_references, ...)",
})
return cmd
}
@ -139,7 +128,10 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
return cmdutil.NewError(cmdutil.CodeServerError, "chat: no SDK client available")
}
jsonOut := fopts != nil && fopts.Mode == cmdutil.FormatJSON
// Streaming commands route --format json AND --format ndjson to the
// NDJSON event-stream path. A buffered envelope makes no sense for a
// streaming command (§5). Only --format text uses the live renderer.
ndjsonMode := fopts != nil && (fopts.Mode == cmdutil.FormatJSON || fopts.Mode == cmdutil.FormatNDJSON)
sessionID := opts.SessionID
autoCreated := false
@ -149,7 +141,7 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
// Ctrl-C during session creation: classify as cancelled so the
// hint nudges the user toward retry-with-signal-clean, not
// "pass --session" as session_create_failed would.
if isCancelled(ctx, err) {
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
}
// Map HTTP-shaped failures, but tag generic transport / unknown
@ -164,21 +156,40 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
autoCreated = true
}
// Decide output mode. Stream mode requires:
// 1. an interactive stdout (tty)
// 2. no --format json (JSON output is single-record by definition)
// 3. no --format ndjson (handled by the early-return branch below)
streamMode := iostreams.IO.IsStdoutTTY() && !jsonOut &&
(fopts == nil || fopts.Mode != cmdutil.FormatNDJSON)
if ndjsonMode {
return runChatNDJSON(ctx, opts, sessionID, svc)
}
// 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
// past tokens. Skipped in JSON mode (it ends up in the data object) and
// when the caller already supplied --session.
if autoCreated && !jsonOut {
// past tokens. Skipped in NDJSON mode (it appears in the init event).
if autoCreated {
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
}
return runChatText(ctx, opts, sessionID, autoCreated, svc)
}
// runChatNDJSON handles --format json and --format ndjson paths.
// Emits a CLI init event at stream head, then passes every SDK event through
// verbatim as NDJSON lines. No buffering — callers parse the stream
// incrementally (§5).
func runChatNDJSON(ctx context.Context, opts *Options, sessionID string, svc ChatService) error {
w := iostreams.IO.Out
// 1. Inject the CLI-managed init event at the head of the stream (§5.3).
// Carries the session pointer + retrieval context callers need for
// follow-up threading.
initEv := output.InitEvent{
SessionID: sessionID,
KBID: opts.KBID,
Profile: cmdutil.GetProfile(),
}
if err := output.EmitInit(w, initEv); err != nil {
return err
}
// 2. Open SDK stream and pass each event through as a bare NDJSON line.
req := &sdk.KnowledgeQARequest{
Query: opts.Query,
KnowledgeBaseIDs: []string{opts.KBID},
@ -186,22 +197,30 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
WebSearchEnabled: false,
Channel: "api",
}
cb := func(r *sdk.StreamResponse) error {
return output.EmitSDKEvent(w, r)
}
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
}
return cmdutil.WrapHTTP(err, "knowledge qa stream")
}
return nil
}
// --format ndjson: stream raw SDK events as NDJSON. Encoder hoisted out
// of callback to avoid per-event allocation.
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
enc := json.NewEncoder(iostreams.IO.Out)
enc.SetEscapeHTML(false)
cb := func(r *sdk.StreamResponse) error {
return enc.Encode(r)
}
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
if isCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
}
return cmdutil.WrapHTTP(err, "knowledge qa stream")
}
return nil
// runChatText handles the --format text path. Streams content fragments
// live on TTY; accumulates then renders on non-TTY pipes.
func runChatText(ctx context.Context, opts *Options, sessionID string, autoCreated bool, svc ChatService) error {
// Stream mode requires an interactive stdout.
streamMode := iostreams.IO.IsStdoutTTY()
req := &sdk.KnowledgeQARequest{
Query: opts.Query,
KnowledgeBaseIDs: []string{opts.KBID},
AgentEnabled: false,
WebSearchEnabled: false,
Channel: "api",
}
acc := &sse.Accumulator{}
@ -221,12 +240,11 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
// Re-surface the auto-created session id on failure so a user who
// missed the start-of-stream notice (it scrolls past mid-stream
// tokens, especially on ^C) can still recover with --session.
// Skipped in JSON mode - the data object carries it in .session_id.
if autoCreated && !jsonOut {
if autoCreated {
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
}
// Context cancelled (Ctrl-C) → user-aborted, exit 130 lineage.
if isCancelled(ctx, streamErr) {
if cmdutil.IsCancelled(ctx, streamErr) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, streamErr, "chat cancelled")
}
// Stream began (we observed at least one event) but never reached a
@ -253,29 +271,9 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
answer := acc.Result()
references := acc.References
if jsonOut {
// Prefer the SDK-echoed session id (acc.SessionID) but fall back to
// our local sessionID - agents must always see a usable pointer.
sid := acc.SessionID
if sid == "" {
sid = sessionID
}
data := chatData{
Answer: answer,
References: references,
Thinking: acc.Thinking(),
SessionID: sid,
AssistantMessageID: acc.AssistantMessageID,
KBID: opts.KBID,
Query: opts.Query,
}
return fopts.Emit(iostreams.IO.Out, data)
}
// Human / non-JSON paths: streaming mode already wrote the answer body
// via the callback, so we only need to render the trailing references
// (and a closing newline). Accumulate + non-JSON writes the answer here
// for the first time.
// Streaming mode already wrote the answer body via the callback, so we
// only need to render the trailing references (and a closing newline).
// Non-TTY accumulate path writes the answer here for the first time.
out := iostreams.IO.Out
if streamMode {
// Ensure the answer line ends cleanly before the references footer.
@ -292,19 +290,5 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
return nil
}
// isCancelled reports whether err or ctx represents a context-cancelled
// state — true on Ctrl-C / SIGTERM after main.go's signal.NotifyContext
// fires. Wrapping URL/transport layers may rewrite context.Canceled into
// something errors.Is no longer recognises, so we fall back to ctx.Err().
func isCancelled(ctx context.Context, err error) bool {
if errors.Is(err, context.Canceled) {
return true
}
if ctx.Err() == context.Canceled {
return true
}
return false
}
// compile-time check: the production SDK client implements ChatService.
var _ ChatService = (*sdk.Client)(nil)

View File

@ -1,11 +1,9 @@
package chat
import (
"bytes"
"context"
"encoding/json"
"errors"
"os"
"strings"
"testing"
@ -62,8 +60,8 @@ func (f *fakeChatService) KnowledgeQAStream(ctx context.Context, sessionID strin
// var _ ChatService = (*sdk.Client)(nil) check at the bottom of chat.go.
var _ ChatService = (*fakeChatService)(nil)
// textOpts returns a FormatOptions configured for the text (human) render
// path — the most common shape under test.
// textOpts returns a FormatOptions configured for the text render path —
// the most common shape under test.
func textOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
}
@ -109,57 +107,105 @@ func TestChat_StreamMode(t *testing.T) {
}
}
func TestChat_JSONMode(t *testing.T) {
out, errBuf := iostreams.SetForTestWithTTY(t)
// TestChat_NDJSON_FirstLineIsInit verifies that the NDJSON path (--format json)
// always injects an "init" line first carrying session_id and kb_id.
func TestChat_NDJSON_FirstLineIsInit(t *testing.T) {
out, errBuf := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{Content: "answer body"},
{AssistantMessageID: "msg_99"},
{ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{{KnowledgeID: "k1"}}},
{ResponseType: sdk.ResponseTypeAnswer, Content: "answer"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb_42"}
if err := runChat(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc); err != nil {
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
// JSON mode must NOT print the human session-hint on stderr; the session
// id is carried inside the JSON object instead.
// NDJSON mode must NOT print the session hint to stderr.
if errBuf.Len() != 0 {
t.Errorf("expected empty stderr in JSON mode, got %q", errBuf.String())
t.Errorf("expected empty stderr in NDJSON mode, got %q", errBuf.String())
}
var got struct {
Answer string `json:"answer"`
SessionID string `json:"session_id"`
AssistantMessageID string `json:"assistant_message_id"`
KBID string `json:"kb_id"`
Query string `json:"query"`
References []struct {
KnowledgeID string `json:"knowledge_id"`
} `json:"references"`
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
if len(lines) == 0 {
t.Fatal("no output")
}
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("decode JSON: %v\n%s", err, out.String())
var first struct {
Type string `json:"type"`
SessionID string `json:"session_id"`
KBID string `json:"kb_id"`
}
if got.Answer != "answer body" {
t.Errorf("answer: got %q", got.Answer)
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
t.Fatalf("first line not JSON: %v\n %s", err, lines[0])
}
if got.SessionID != "sess_auto" {
t.Errorf("session_id: got %q", got.SessionID)
if first.Type != "init" {
t.Errorf("first line type: got %q, want init", first.Type)
}
if got.AssistantMessageID != "msg_99" {
t.Errorf("assistant_message_id: got %q", got.AssistantMessageID)
if first.SessionID != "sess_auto" {
t.Errorf("init.session_id: got %q, want sess_auto", first.SessionID)
}
if got.KBID != "kb_42" {
t.Errorf("kb_id: got %q", got.KBID)
if first.KBID != "kb_42" {
t.Errorf("init.kb_id: got %q, want kb_42", first.KBID)
}
if got.Query != "q" {
t.Errorf("query: got %q", got.Query)
}
// TestChat_NDJSON_PassthroughEvents verifies that the NDJSON path emits
// init + N SDK events = N+1 total lines (no buffering, no extra wrapping).
func TestChat_NDJSON_PassthroughEvents(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
if len(got.References) != 1 || got.References[0].KnowledgeID != "k1" {
t.Errorf("references payload missing: %+v", got.References)
opts := &Options{Query: "q", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
// 1 init + 2 SDK events = 3 lines.
if len(lines) != 3 {
t.Fatalf("got %d lines, want 3:\n%s", len(lines), out.String())
}
// Each must be valid JSON.
for i, line := range lines {
var obj map[string]any
if err := json.Unmarshal([]byte(line), &obj); err != nil {
t.Errorf("line %d not valid JSON: %v\n %s", i+1, err, line)
}
}
}
// TestChat_NDJSON_JSONEqualsNDJSON verifies that --format json and --format ndjson
// produce identical byte output on a streaming command.
func TestChat_NDJSON_JSONEqualsNDJSON(t *testing.T) {
events := []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
}
runWith := func(mode cmdutil.FormatMode) string {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{streamEvents: events}
opts := &Options{Query: "q", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: mode}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat(%s): %v", mode, err)
}
return out.String()
}
jsonOut := runWith(cmdutil.FormatJSON)
ndjsonOut := runWith(cmdutil.FormatNDJSON)
if jsonOut != ndjsonOut {
t.Errorf("--format json and --format ndjson differ:\n json: %q\n ndjson: %q", jsonOut, ndjsonOut)
}
}
@ -346,8 +392,46 @@ func TestChat_SessionCreate404SurfacesNotFound(t *testing.T) {
}
}
// TestChat_NDJSON_InitIncludesProfile verifies that when a profile is set,
// the NDJSON init event carries the profile field.
func TestChat_NDJSON_InitIncludesProfile(t *testing.T) {
cmdutil.SetProfile("prod")
t.Cleanup(func() { cmdutil.SetProfile("") })
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
if len(lines) == 0 {
t.Fatal("no output")
}
var initLine struct {
Type string `json:"type"`
Profile string `json:"profile"`
}
if err := json.Unmarshal([]byte(lines[0]), &initLine); err != nil {
t.Fatalf("first line not JSON: %v\n %s", err, lines[0])
}
if initLine.Type != "init" {
t.Errorf("type: got %q, want init", initLine.Type)
}
if initLine.Profile != "prod" {
t.Errorf("profile: got %q, want prod", initLine.Profile)
}
}
func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
// Fake stream emits 3 events: thinking, answer, complete.
// With the init injection, total output is 4 lines (1 init + 3 SDK events).
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "search KB"},
@ -355,47 +439,50 @@ func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
},
}
var stdout bytes.Buffer
prev := iostreams.IO.Out
iostreams.IO.Out = &stdout
defer func() { iostreams.IO.Out = prev }()
// Also redirect stderr so the auto-created session hint doesn't write to
// real stderr during tests.
prevErr := iostreams.IO.Err
iostreams.IO.Err = os.Stderr
defer func() { iostreams.IO.Err = prevErr }()
out, _ := iostreams.SetForTest(t)
opts := &Options{Query: "hi", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(stdout.String(), "\n"), "\n")
if len(lines) != 3 {
t.Fatalf("got %d lines, want 3:\n%s", len(lines), stdout.String())
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
// 1 init + 3 SDK events = 4 lines.
if len(lines) != 4 {
t.Fatalf("got %d lines, want 4:\n%s", len(lines), out.String())
}
// Each line must be valid JSON with the right response_type.
var first map[string]any
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
t.Fatalf("line 1 not JSON: %v", err)
// First line: CLI-injected init event.
var initLine map[string]any
if err := json.Unmarshal([]byte(lines[0]), &initLine); err != nil {
t.Fatalf("line 1 (init) not JSON: %v", err)
}
if first["response_type"] != "thinking" {
t.Errorf("first event response_type=%v, want thinking", first["response_type"])
if initLine["type"] != "init" {
t.Errorf("first line type=%v, want init", initLine["type"])
}
// Second line: answer.
// Second line: thinking event (SDK passthrough).
var second map[string]any
if err := json.Unmarshal([]byte(lines[1]), &second); err != nil {
t.Fatalf("line 2 not JSON: %v", err)
}
if second["response_type"] != "answer" {
t.Errorf("second event response_type=%v, want answer", second["response_type"])
if second["response_type"] != "thinking" {
t.Errorf("second event response_type=%v, want thinking", second["response_type"])
}
// Third line: complete with done=true.
// Third line: answer.
var third map[string]any
if err := json.Unmarshal([]byte(lines[2]), &third); err != nil {
t.Fatalf("line 3 not JSON: %v", err)
}
if third["done"] != true {
t.Errorf("third event done=%v, want true", third["done"])
if third["response_type"] != "answer" {
t.Errorf("third event response_type=%v, want answer", third["response_type"])
}
// Fourth line: complete with done=true.
var fourth map[string]any
if err := json.Unmarshal([]byte(lines[3]), &fourth); err != nil {
t.Fatalf("line 4 not JSON: %v", err)
}
if fourth["done"] != true {
t.Errorf("fourth event done=%v, want true", fourth["done"])
}
}

View File

@ -76,7 +76,7 @@ func TestDelete_TTY_ConfirmYes_Calls(t *testing.T) {
p := &testutil.ConfirmPrompter{Answer: true}
require.NoError(t, runDelete(context.Background(),
&DeleteOptions{ChunkID: "c1", DocID: "doc_abc"},
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p))
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p))
assert.True(t, p.Asked)
assert.Equal(t, "c1", svc.gotChunkID)
}
@ -87,7 +87,7 @@ func TestDelete_TTY_ConfirmNo_Aborts(t *testing.T) {
p := &testutil.ConfirmPrompter{Answer: false}
err := runDelete(context.Background(),
&DeleteOptions{ChunkID: "c1", DocID: "doc_abc"},
&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p)
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -177,7 +177,7 @@ func TestMultiDelete_PartialFailure_KeepsGoing(t *testing.T) {
func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeMultiChunkDeleteSvc{}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "chunk", 2, "chunk.delete", "")
require.Error(t, err)
var typed *cmdutil.Error

View File

@ -154,7 +154,7 @@ func TestList_MissingDoc_FlagError(t *testing.T) {
require.Error(t, cmd.Execute(), "expect required-flag error for missing --doc")
}
func TestList_Human_TableHeader(t *testing.T) {
func TestList_Text_TableHeader(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{
pages: [][]sdk.Chunk{{
@ -162,21 +162,21 @@ func TestList_Human_TableHeader(t *testing.T) {
}},
totals: []int64{1}, errs: []error{nil},
}
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
body := out.String()
for _, want := range []string{"CHUNK_ID", "INDEX", "TYPE", "ENABLED", "PREVIEW", "UPDATED", "c1", "text"} {
assert.Contains(t, body, want)
}
}
func TestList_Human_PreviewTruncatedTo80(t *testing.T) {
func TestList_Text_PreviewTruncatedTo80(t *testing.T) {
out, _ := iostreams.SetForTest(t)
long := strings.Repeat("a", 200)
svc := &fakeListSvc{
pages: [][]sdk.Chunk{{{ID: "c1", Content: long, ChunkType: "text", IsEnabled: true}}},
totals: []int64{1}, errs: []error{nil},
}
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{DocID: "doc_abc", Limit: 50, PageSize: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
body := out.String()
// 80-col preview means we never see the 100th `a` from the content (only column truncation kicks in).
assert.NotContains(t, body, strings.Repeat("a", 100), "preview must be truncated to ~80 chars")

View File

@ -35,7 +35,7 @@ type ViewOptions struct {
const chunkViewLong = `Show a single chunk with all SDK fields.
Human output is a key-value block; pass --format json for the bare 23-field SDK
Text output is a key-value block; pass --format json for the bare 23-field SDK
Chunk object. Content renders verbatim regardless of size — pipe to
less or use --format json for large chunks. WeKnora chunks are typically bounded
by the ingest pipeline (~1000 tokens / a few KB), so unconditional full

View File

@ -37,7 +37,7 @@ func TestView_Happy_RendersAllFields(t *testing.T) {
CreatedAt: "2026-05-15T11:00:00Z",
UpdatedAt: "2026-05-15T12:00:00Z",
}}
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
body := out.String()
assert.Contains(t, body, "c1")
assert.Contains(t, body, "doc_abc")
@ -51,9 +51,9 @@ func TestView_HumanLabels_DocAndKB(t *testing.T) {
svc := &fakeViewSvc{resp: &sdk.Chunk{
ID: "c1", KnowledgeID: "doc_abc", KnowledgeBaseID: "kb_abc",
}}
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
body := out.String()
// Human KV uses friendlier DOC_ID / KB_ID labels (the SDK's
// Text KV uses friendlier DOC_ID / KB_ID labels (the SDK's
// knowledge_id / knowledge_base_id are kept only in --format json output).
assert.Contains(t, body, "doc_id")
assert.Contains(t, body, "kb_id")
@ -64,7 +64,7 @@ func TestView_HumanLabels_DocAndKB(t *testing.T) {
func TestView_OmitsZeroOrEmpty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Chunk{ID: "c_min", Content: "x"}}
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c_min"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runView(context.Background(), &ViewOptions{ChunkID: "c_min"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
body := out.String()
// status / start_at / end_at all zero → must be omitted from the human KV.
assert.NotContains(t, body, "status:")
@ -89,7 +89,7 @@ func TestView_JSON_BareSDKShape(t *testing.T) {
got := env.Data
assert.Equal(t, "c_json", got.ID)
assert.Equal(t, "doc_abc", got.KnowledgeID)
// JSON uses SDK snake_case keys (knowledge_id), not human relabel doc_id.
// JSON uses SDK snake_case keys (knowledge_id), not text relabel doc_id.
assert.Contains(t, out.String(), `"knowledge_id":"doc_abc"`)
assert.Contains(t, out.String(), `"knowledge_base_id":"kb_abc"`)
assert.NotContains(t, out.String(), `"doc_id"`)
@ -99,7 +99,7 @@ func TestView_JSON_BareSDKShape(t *testing.T) {
func TestView_404(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewSvc{err: errors.New("HTTP error 404: not found")}
err := runView(context.Background(), &ViewOptions{ChunkID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runView(context.Background(), &ViewOptions{ChunkID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
assert.Contains(t, err.Error(), "resource.not_found")
}

View File

@ -1,27 +0,0 @@
// Package contextcmd holds the `weknora context` command tree
// (list / add / remove / use).
//
// Package name `contextcmd` (not `context`) to avoid shadowing stdlib context.
// The cobra Use: string is "context" - this is what users type.
package contextcmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// NewCmd builds the `weknora context` parent command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "context",
Short: "Manage CLI contexts (named connection targets)",
Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
}
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdAdd(f))
cmd.AddCommand(NewCmdRemove(f))
cmd.AddCommand(NewCmdUse(f))
return cmd
}

View File

@ -34,11 +34,11 @@ func (f *fakeCreateSvc) CreateManualKnowledge(
return f.resp, f.err
}
func TestCreate_Success_Human(t *testing.T) {
func TestCreate_Success_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_1", Title: "Sprint Notes"}}
opts := &CreateOptions{Text: "# Sprint Notes\n\nAction items: ...", Name: "Sprint Notes"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, "# Sprint Notes\n\nAction items: ...", svc.got.req.Content)
@ -51,7 +51,7 @@ func TestCreate_Success_NoName_FallsBackToTitle(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_2", Title: "Server Title"}}
opts := &CreateOptions{Text: "Some content"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
// When --name is omitted the display falls back to k.Title from the server response.
assert.Contains(t, out.String(), "Server Title")
}
@ -60,7 +60,7 @@ func TestCreate_Success_NoName_NoTitle_FallsBackToID(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_manual_3"}}
opts := &CreateOptions{Text: "Some content"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Contains(t, out.String(), "doc_manual_3")
}
@ -68,7 +68,7 @@ func TestCreate_TagID_Forwarded(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_t"}}
opts := &CreateOptions{Text: "content", TagID: "tag_42"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "tag_42", svc.got.req.TagID)
}
@ -76,7 +76,7 @@ func TestCreate_Channel_Override(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_ch"}}
opts := &CreateOptions{Text: "content", Channel: "browser_extension"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "browser_extension", svc.got.req.Channel)
}
@ -84,7 +84,7 @@ func TestCreate_Channel_DefaultIsAPI(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "doc_ch"}}
opts := &CreateOptions{Text: "content"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, uploadChannel, svc.got.req.Channel)
}
@ -109,7 +109,7 @@ func TestCreate_ServerError_Wraps(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal server error")}
err := runCreate(context.Background(),
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -120,7 +120,7 @@ func TestCreate_HTTPError_400_Wraps(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{err: errors.New("HTTP error 400: bad request")}
err := runCreate(context.Background(),
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
&CreateOptions{Text: "content"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -133,7 +133,7 @@ func TestCreate_EmptyText_RejectsBeforeSDK(t *testing.T) {
// defensive guard; cobra's MarkFlagRequired catches it earlier in RunE).
svc := &fakeCreateSvc{resp: &sdk.Knowledge{ID: "should-not-reach"}}
err := runCreate(context.Background(),
&CreateOptions{Text: ""}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
&CreateOptions{Text: ""}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
require.Error(t, err)
// Verify the SDK was NOT called.
assert.Nil(t, svc.got.req, "SDK must not be called when --text is empty")

View File

@ -76,7 +76,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
opts := &DeleteOptions{Yes: true}
// Force=true short-circuits the confirm path; the prompter must not be
// consulted, so any value works.
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc"))
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc"))
assert.Equal(t, "doc_abc", svc.got)
assert.Equal(t, 1, svc.calls)
@ -104,7 +104,7 @@ func TestDelete_Success_JSON(t *testing.T) {
func TestDelete_NotFound_404(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "doc_missing")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "doc_missing")
require.Error(t, err)
var typed *cmdutil.Error
@ -115,7 +115,7 @@ func TestDelete_NotFound_404(t *testing.T) {
func TestDelete_HTTPError_500(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{err: errors.New("HTTP error 500: internal")}
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "doc_x")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "doc_x")
require.Error(t, err)
var typed *cmdutil.Error
@ -129,7 +129,7 @@ func TestDelete_HTTPError_500(t *testing.T) {
func TestDelete_ConfirmYes(t *testing.T) {
out, _ := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc")
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: true}, "doc_abc")
require.NoError(t, err)
assert.Equal(t, 1, svc.calls, "user said yes ⇒ delete proceeds")
assert.Contains(t, out.String(), "✓")
@ -138,7 +138,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
func TestDelete_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc")
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: false}, "doc_abc")
require.Error(t, err)
assert.Equal(t, 0, svc.calls, "user said no ⇒ SDK must NOT be called")
@ -154,7 +154,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
func TestDelete_AgentPrompterErrors(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
require.Error(t, err)
assert.Equal(t, 0, svc.calls)
@ -170,7 +170,7 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Err: errors.New("no tty")}, "doc_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -269,7 +269,7 @@ func TestRunMultiDelete_ConfirmBatch_NonTTY_RequiresConfirmation(t *testing.T) {
func TestRunMultiDelete_ConfirmBatch_TTY_UserAborts(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{Answer: false}, false, fopts.WantsJSON(), "document", 3, "doc.delete", "")
require.Error(t, err)
var typed *cmdutil.Error
@ -341,7 +341,7 @@ func TestEmitMultiDelete_Text(t *testing.T) {
{ID: "a", Err: nil},
{ID: "b", Err: errors.New("boom")},
}
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &buf, nil)
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &buf, nil)
require.NoError(t, err)
out := buf.String()
@ -356,7 +356,7 @@ func TestEmitMultiDelete_TextEmpty(t *testing.T) {
{ID: "x", Err: nil},
{ID: "y", Err: nil},
}
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &buf, nil)
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &buf, nil)
require.NoError(t, err)
out := buf.String()
@ -367,7 +367,7 @@ func TestEmitMultiDelete_TextEmpty(t *testing.T) {
func TestEmitMultiDelete_UnsupportedFormat(t *testing.T) {
// EmitBatch defers unsupported format handling to WriteBatchEnvelope; for
// non-JSON formats it falls through to human text. Verify it does not error.
// non-JSON formats it falls through to text. Verify it does not error.
var buf bytes.Buffer
outcomes := []cmdutil.BatchOutcome{}
err := cmdutil.EmitBatch(outcomes, &cmdutil.FormatOptions{Mode: "yaml"}, &buf, nil)
@ -494,7 +494,7 @@ func TestDocDelete_All_WithYes_TextMode(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeAllSvc{resp: &sdk.ClearKnowledgeBaseContentsResponse{DeletedCount: 5}}
opts := &DeleteOptions{All: true, KB: "kb_y", Yes: true}
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{})
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{})
require.NoError(t, err)
assert.True(t, svc.called)
body := out.String()
@ -507,7 +507,7 @@ func TestDocDelete_All_TTY_UserAborts(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeAllSvc{}
opts := &DeleteOptions{All: true, KB: "kb_z", Yes: false}
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{Answer: false})
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{Answer: false})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -521,7 +521,7 @@ func TestDocDelete_All_ServiceError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeAllSvc{err: errors.New("HTTP error 404: not found")}
opts := &DeleteOptions{All: true, KB: "kb_missing", Yes: true}
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{})
err := runDeleteAll(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)

View File

@ -34,11 +34,11 @@ func (f *fakeFetchSvc) CreateKnowledgeFromURL(
return f.resp, f.err
}
func TestFetch_Success_Human(t *testing.T) {
func TestFetch_Success_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_url_1", FileName: "whitepaper.pdf"}}
opts := &FetchOptions{URL: "https://example.com/whitepaper.pdf"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, "https://example.com/whitepaper.pdf", svc.got.req.URL)
@ -51,7 +51,7 @@ func TestFetch_WithName_PassesAsFileName(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_url_2"}}
opts := &FetchOptions{URL: "https://example.com/article.html", Name: "Q3 Article"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "Q3 Article", svc.got.req.FileName,
"--name must be forwarded as FileName (server uses it for file-vs-crawl mode hint)")
}
@ -60,7 +60,7 @@ func TestFetch_Title(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/a.pdf", Title: "My Title"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "My Title", svc.got.req.Title)
}
@ -68,7 +68,7 @@ func TestFetch_FileType(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/no-ext", FileType: "pdf"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "pdf", svc.got.req.FileType)
}
@ -76,7 +76,7 @@ func TestFetch_TagID(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/a.pdf", TagID: "tag_99"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "tag_99", svc.got.req.TagID)
}
@ -85,7 +85,7 @@ func TestFetch_EnableMultimodel_Forwarded(t *testing.T) {
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
mm := true
opts := &FetchOptions{URL: "https://example.com/a.pdf", EnableMultimodel: &mm}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
require.NotNil(t, svc.got.req.EnableMultimodel)
assert.True(t, *svc.got.req.EnableMultimodel)
}
@ -94,7 +94,7 @@ func TestFetch_Channel_Override(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/a.pdf", Channel: "web"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "web", svc.got.req.Channel)
}
@ -102,7 +102,7 @@ func TestFetch_Channel_DefaultIsAPI(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{resp: &sdk.Knowledge{ID: "doc_u"}}
opts := &FetchOptions{URL: "https://example.com/a.pdf"}
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runFetch(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, uploadChannel, svc.got.req.Channel)
}
@ -130,7 +130,7 @@ func TestFetch_DuplicateURL_Maps_resource_already_exists(t *testing.T) {
err: sdk.ErrDuplicateURL,
}
err := runFetch(context.Background(),
&FetchOptions{URL: "https://example.com/dup.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
&FetchOptions{URL: "https://example.com/dup.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -141,7 +141,7 @@ func TestFetch_ServerError_Wraps(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{err: errors.New("HTTP error 500: internal server error")}
err := runFetch(context.Background(),
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -156,6 +156,6 @@ func TestFetch_KBResolutionFailure_Propagates(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeFetchSvc{err: errors.New("HTTP error 404: knowledge base not found")}
err := runFetch(context.Background(),
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "")
&FetchOptions{URL: "https://example.com/doc.pdf"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "")
require.Error(t, err)
}

View File

@ -49,7 +49,7 @@ func chdirIsolated(t *testing.T) {
t.Setenv("WEKNORA_KB_ID", "")
}
func TestList_Success_Human(t *testing.T) {
func TestList_Success_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.Knowledge{
@ -58,7 +58,7 @@ func TestList_Success_Human(t *testing.T) {
}
svc := &fakeListSvc{items: items, total: 2}
opts := &ListOptions{PageSize: 20, Limit: 30}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, 1, svc.got.page)
@ -90,11 +90,11 @@ func TestList_Success_JSON(t *testing.T) {
assert.NotContains(t, got, `"_meta":`)
}
func TestList_Empty_Human(t *testing.T) {
func TestList_Empty_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListSvc{items: nil, total: 0}
opts := &ListOptions{PageSize: 20, Limit: 30}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Contains(t, out.String(), "(no documents)")
}
@ -117,7 +117,7 @@ func TestList_HTTPError_500(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{err: errors.New("HTTP error 500: internal")}
opts := &ListOptions{PageSize: 20, Limit: 30}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
@ -197,7 +197,7 @@ func TestList_SortByUpdatedDesc(t *testing.T) {
{ID: "new", FileName: "new.pdf", UpdatedAt: now.Add(-1 * time.Hour)},
}
svc := &fakeListSvc{items: items, total: 2}
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 20, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 20, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
got := out.String()
newIdx := strings.Index(got, "new.pdf")
@ -231,7 +231,7 @@ func TestList_StatusFilter_ForwardedToSDK(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Limit: 30, Status: "failed"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "failed", svc.got.filter.ParseStatus,
"--status must be forwarded as filter.ParseStatus for server-side filtering")
}
@ -241,7 +241,7 @@ func TestList_StatusFilter_RejectsUnknownValue(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Limit: 30, Status: "bogus"}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx")
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -256,7 +256,7 @@ func TestList_StatusFilter_AcceptsAllEnumValues(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Limit: 30, Status: v}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"),
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"),
"status=%q should be accepted", v)
}
}
@ -321,7 +321,7 @@ func TestList_Limit_GreaterThanPageSize_NoCap(t *testing.T) {
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
opts := &ListOptions{PageSize: 20, Limit: -1}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -356,7 +356,7 @@ func TestList_Keyword_PassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Limit: 30, Keyword: "spec"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "spec", svc.got.filter.Keyword)
}
@ -364,7 +364,7 @@ func TestList_FileType_PassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Limit: 30, FileType: "pdf"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "pdf", svc.got.filter.FileType)
}
@ -372,7 +372,7 @@ func TestList_Source_PassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Limit: 30, Source: "api"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "api", svc.got.filter.Source)
}
@ -380,7 +380,7 @@ func TestList_TagID_PassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListSvc{}
opts := &ListOptions{PageSize: 20, Limit: 30, TagID: "tag_42"}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
assert.Equal(t, "tag_42", svc.got.filter.TagID)
}
@ -389,7 +389,7 @@ func TestList_StartTime_RFC3339Parses(t *testing.T) {
svc := &fakeListSvc{}
want := "2026-05-01T00:00:00Z"
opts := &ListOptions{PageSize: 20, Limit: 30, StartTime: want}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
parsed, err := time.Parse(time.RFC3339, want)
require.NoError(t, err)
assert.True(t, svc.got.filter.StartTime.Equal(parsed),
@ -402,7 +402,7 @@ func TestList_EndTime_RFC3339Parses(t *testing.T) {
svc := &fakeListSvc{}
want := "2026-06-30T23:59:59Z"
opts := &ListOptions{PageSize: 20, Limit: 30, EndTime: want}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
parsed, err := time.Parse(time.RFC3339, want)
require.NoError(t, err)
assert.True(t, svc.got.filter.EndTime.Equal(parsed))
@ -411,7 +411,7 @@ func TestList_EndTime_RFC3339Parses(t *testing.T) {
func TestList_StartTime_InvalidFormat_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
opts := &ListOptions{PageSize: 20, Limit: 30, StartTime: "tomorrow"}
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -423,7 +423,7 @@ func TestList_StartTime_InvalidFormat_Rejected(t *testing.T) {
func TestList_EndTime_InvalidFormat_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
opts := &ListOptions{PageSize: 20, Limit: 30, EndTime: "2026-05-01"} // date-only, not RFC3339
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{}, "kb_xxx")
err := runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}, "kb_xxx")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -447,7 +447,7 @@ func TestList_AllFiltersCombined(t *testing.T) {
StartTime: "2026-01-01T00:00:00Z",
EndTime: "2026-12-31T23:59:59Z",
}
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx"))
require.NoError(t, runList(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx"))
f := svc.got.filter
assert.Equal(t, "completed", f.ParseStatus)
assert.Equal(t, "spec", f.Keyword)

View File

@ -207,11 +207,11 @@ func validateUploadFlags(opts *UploadOptions, args []string) error {
}
// renderUploadSuccess emits the post-upload result. JSON path is the bare
// Knowledge object; human path prints a checkmark line. Shared by single-
// file upload and URL ingest; humanVerb varies (uploaded/ingested) and
// Knowledge object; text path prints a checkmark line. Shared by single-
// file upload and URL ingest; verb varies (uploaded/ingested) and
// fallbackDisplay covers the case when the server-recorded file_name is
// blank (URL ingest pre-redirect).
func renderUploadSuccess(k *sdk.Knowledge, fopts *cmdutil.FormatOptions, humanVerb, customName, fallbackDisplay string) error {
func renderUploadSuccess(k *sdk.Knowledge, fopts *cmdutil.FormatOptions, verb, customName, fallbackDisplay string) error {
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, k, nil)
}
@ -222,7 +222,7 @@ func renderUploadSuccess(k *sdk.Knowledge, fopts *cmdutil.FormatOptions, humanVe
if displayed == "" {
displayed = fallbackDisplay
}
fmt.Fprintf(iostreams.IO.Out, "✓ %s %q (id: %s)\n", humanVerb, displayed, k.ID)
fmt.Fprintf(iostreams.IO.Out, "✓ %s %q (id: %s)\n", verb, displayed, k.ID)
return nil
}

View File

@ -68,7 +68,7 @@ func TestUploadRecursive_WalksAllFiles(t *testing.T) {
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*"}
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
sort.Strings(svc.called)
assert.Equal(t, []string{"a.pdf", "b.pdf", "c.pdf"}, svc.called)
@ -85,7 +85,7 @@ func TestUploadRecursive_GlobFilter(t *testing.T) {
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*.pdf"}
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
sort.Strings(svc.called)
assert.Equal(t, []string{"doc.pdf", "keep.pdf"}, svc.called)
@ -103,7 +103,7 @@ func TestUploadRecursive_PartialFailure_Exits1(t *testing.T) {
"bad.pdf": {err: errors.New("HTTP error 500: internal")},
}}
opts := &UploadOptions{Recursive: true, Glob: "*"}
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
require.Error(t, err)
var typed *cmdutil.Error
@ -126,7 +126,7 @@ func TestUploadRecursive_NoMatches(t *testing.T) {
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*.pdf"}
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
assert.Len(t, svc.called, 0)
assert.Contains(t, strings.ToLower(out.String()), "no files matched")
}
@ -135,7 +135,7 @@ func TestUploadRecursive_NotADirectory(t *testing.T) {
_, _ = iostreams.SetForTest(t)
path := writeTempFile(t, "single.pdf")
svc := &scriptedUploadSvc{}
err := runUploadRecursive(context.Background(), &UploadOptions{Recursive: true, Glob: "*"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
err := runUploadRecursive(context.Background(), &UploadOptions{Recursive: true, Glob: "*"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -149,7 +149,7 @@ func TestUploadRecursive_RejectsNameFlag(t *testing.T) {
mkTree(t, dir, "a.pdf")
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*", Name: "single-name.pdf"}
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -171,7 +171,7 @@ func TestUploadRecursive_PropagatesMultimodelAndMetadata(t *testing.T) {
Metadata: []string{"team=alpha"},
Channel: "browser_extension",
}
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir))
require.NoError(t, runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir))
require.NotNil(t, svc.lastEnableMultimodel)
assert.True(t, *svc.lastEnableMultimodel)
@ -186,7 +186,7 @@ func TestUploadRecursive_MetadataInvalid_NoCalls(t *testing.T) {
svc := &scriptedUploadSvc{}
opts := &UploadOptions{Recursive: true, Glob: "*", Metadata: []string{"badformat"}}
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", dir)
err := runUploadRecursive(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", dir)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)

View File

@ -52,12 +52,12 @@ func writeTempFile(t *testing.T, name string) string {
return path
}
func TestUpload_Success_Human(t *testing.T) {
func TestUpload_Success_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
path := writeTempFile(t, "report.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_99", FileName: "report.pdf"}}
opts := &UploadOptions{}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
assert.Equal(t, "kb_xxx", svc.got.kbID)
assert.Equal(t, path, svc.got.filePath)
@ -79,7 +79,7 @@ func TestUpload_Success_CustomName(t *testing.T) {
path := writeTempFile(t, "q3.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_88", FileName: "q3.pdf"}}
opts := &UploadOptions{Name: "Q3 Marketing Report.pdf"}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
assert.Equal(t, "Q3 Marketing Report.pdf", svc.got.customName)
}
@ -105,7 +105,7 @@ func TestUpload_HTTPError_500(t *testing.T) {
_, _ = iostreams.SetForTest(t)
path := writeTempFile(t, "x.txt")
svc := &fakeUploadSvc{err: errors.New("HTTP error 500: internal")}
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
@ -117,7 +117,7 @@ func TestUpload_HTTPError_409Conflict(t *testing.T) {
_, _ = iostreams.SetForTest(t)
path := writeTempFile(t, "dup.pdf")
svc := &fakeUploadSvc{err: errors.New("HTTP error 409: file exists")}
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
@ -133,7 +133,7 @@ func TestUpload_DuplicateFileMaps_resource_already_exists(t *testing.T) {
_, _ = iostreams.SetForTest(t)
path := writeTempFile(t, "dup.md")
svc := &fakeUploadSvc{err: sdk.ErrDuplicateFile}
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
err := runUpload(context.Background(), &UploadOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
@ -199,7 +199,7 @@ func TestUpload_EnableMultimodel_Set_True(t *testing.T) {
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_mm", FileName: "mm.pdf"}}
mm := true
opts := &UploadOptions{EnableMultimodel: &mm}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NotNil(t, svc.got.enableMultimodel, "expected non-nil *bool when flag set")
assert.True(t, *svc.got.enableMultimodel)
}
@ -210,7 +210,7 @@ func TestUpload_EnableMultimodel_Set_False(t *testing.T) {
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_mm", FileName: "mm.pdf"}}
mm := false
opts := &UploadOptions{EnableMultimodel: &mm}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
require.NotNil(t, svc.got.enableMultimodel, "explicit false must still surface as non-nil *bool")
assert.False(t, *svc.got.enableMultimodel)
}
@ -254,7 +254,7 @@ func TestUpload_Metadata_ParseKV(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"foo=bar", "baz=qux"}}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
assert.Equal(t, map[string]string{"foo": "bar", "baz": "qux"}, svc.got.metadata)
}
@ -263,7 +263,7 @@ func TestUpload_Metadata_EmptyValueAllowed(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"foo="}}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
assert.Equal(t, map[string]string{"foo": ""}, svc.got.metadata)
}
@ -272,7 +272,7 @@ func TestUpload_Metadata_LastWins(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"k=v1", "k=v2"}}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
assert.Equal(t, map[string]string{"k": "v2"}, svc.got.metadata)
}
@ -281,7 +281,7 @@ func TestUpload_Metadata_InvalidFormat_NoEquals(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"foo"}}
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -293,7 +293,7 @@ func TestUpload_Metadata_InvalidFormat_EmptyKey(t *testing.T) {
path := writeTempFile(t, "m.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_m", FileName: "m.pdf"}}
opts := &UploadOptions{Metadata: []string{"=bar"}}
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path)
err := runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -305,7 +305,7 @@ func TestUpload_Channel_Override(t *testing.T) {
path := writeTempFile(t, "c.pdf")
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_c", FileName: "c.pdf"}}
opts := &UploadOptions{Channel: "browser_extension"}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
assert.Equal(t, "browser_extension", svc.got.channel)
}
@ -315,6 +315,6 @@ func TestUpload_Channel_DefaultStillAPI(t *testing.T) {
svc := &fakeUploadSvc{resp: &sdk.Knowledge{ID: "doc_c", FileName: "c.pdf"}}
// Empty Channel is the runUpload contract for "use default".
opts := &UploadOptions{}
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_xxx", path))
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_xxx", path))
assert.Equal(t, uploadChannel, svc.got.channel)
}

View File

@ -24,7 +24,7 @@ func (f *fakeViewSvc) GetKnowledge(_ context.Context, _ string) (*sdk.Knowledge,
return f.doc, f.err
}
func TestView_Human_RendersExpectedFields(t *testing.T) {
func TestView_Text_RendersExpectedFields(t *testing.T) {
out, _ := iostreams.SetForTest(t)
processed := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
svc := &fakeViewSvc{doc: &sdk.Knowledge{
@ -40,7 +40,7 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
UpdatedAt: time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC),
ProcessedAt: &processed,
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_abc"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -57,10 +57,10 @@ func TestView_Human_RendersExpectedFields(t *testing.T) {
// A doc with no FileName falls back to Title for the NAME line - same
// ordering as `doc list` (KnowledgeDisplayName precedence).
func TestView_Human_TitleFallback(t *testing.T) {
func TestView_Text_TitleFallback(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_url", Title: "Pasted article", FileName: ""}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_url"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_url"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -72,13 +72,13 @@ func TestView_Human_TitleFallback(t *testing.T) {
// Optional fields (ProcessedAt nil, ErrorMessage empty, EmbeddingModelID
// empty) must not produce empty KEY: lines - the formatter omits them
// rather than printing "PROCESSED: -".
func TestView_Human_OmitsEmptyFields(t *testing.T) {
func TestView_Text_OmitsEmptyFields(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_abc",
FileName: "x.txt",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_abc"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_abc"); err != nil {
t.Fatalf("runView: %v", err)
}
// Line-prefix match (not substring): "ERROR:" as a substring could
@ -122,7 +122,7 @@ func TestView_JSON_BareObject(t *testing.T) {
func TestView_NotFound_ClassifiedAs404(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewSvc{err: errors.New("HTTP error 404: not found")}
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "missing")
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
if err == nil {
t.Fatal("expected error")
}
@ -131,14 +131,14 @@ func TestView_NotFound_ClassifiedAs404(t *testing.T) {
}
}
// --- expanded human render: title/desc/source/channel/etc. ---
// --- expanded text render: title/desc/source/channel/etc. ---
func TestView_Title_RendersWhenDifferentFromFileName(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_t", FileName: "raw.pdf", Title: "Quarterly Plan",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -154,7 +154,7 @@ func TestView_Title_OmittedWhenSameAsFileName(t *testing.T) {
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_t", FileName: "policy.pdf", Title: "policy.pdf",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
t.Fatalf("runView: %v", err)
}
for _, l := range strings.Split(out.String(), "\n") {
@ -167,7 +167,7 @@ func TestView_Title_OmittedWhenSameAsFileName(t *testing.T) {
func TestView_Description(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_d", FileName: "x.pdf", Description: "Annual review"}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_d"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_d"); err != nil {
t.Fatalf("runView: %v", err)
}
if !strings.Contains(out.String(), "Annual review") {
@ -180,7 +180,7 @@ func TestView_SourceAndChannel(t *testing.T) {
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_s", FileName: "x.pdf", Source: "https://example.com/x", Channel: "web",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_s"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_s"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -198,7 +198,7 @@ func TestView_SummaryAndEnableStatus(t *testing.T) {
SummaryStatus: "completed",
EnableStatus: "disabled",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_st"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_st"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -212,7 +212,7 @@ func TestView_SummaryAndEnableStatus(t *testing.T) {
func TestView_TagID(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_t", FileName: "x.pdf", TagID: "tag_abc"}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_t"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -221,10 +221,10 @@ func TestView_TagID(t *testing.T) {
}
}
func TestView_StorageSize_Human(t *testing.T) {
func TestView_StorageSize_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_sz", FileName: "x.pdf", StorageSize: 2 * 1024 * 1024}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_sz"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_sz"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -240,7 +240,7 @@ func TestView_FileHash_Prefix12(t *testing.T) {
FileName: "x.pdf",
FileHash: "abcdef1234567890fedcba0987654321",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_h"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_h"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -257,7 +257,7 @@ func TestView_ErrorMessage_WarnPrefix(t *testing.T) {
svc := &fakeViewSvc{doc: &sdk.Knowledge{
ID: "doc_e", FileName: "x.pdf", ErrorMessage: "parser failed at offset 4096",
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "doc_e"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "doc_e"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()

View File

@ -265,7 +265,7 @@ func emitWaitResult(r *WaitResult, fopts *cmdutil.FormatOptions, w io.Writer) er
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, r, nil)
case cmdutil.FormatHuman, "":
case cmdutil.FormatText, "":
return writeWaitText(w, r)
default:
return fmt.Errorf("unsupported --format %q for doc wait", fopts.Mode)

View File

@ -189,9 +189,9 @@ func TestWaitForDocs_MultiID_WaitAllOnPartialFailure(t *testing.T) {
// B5: emitWaitResult rendering tests
// ---------------------------------------------------------------------------
func TestEmitWaitResult_TextHumanSummary(t *testing.T) {
func TestEmitWaitResult_TextSummary(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
res := &WaitResult{
Completed: []string{"a", "b"},
Failed: []FailedDoc{{ID: "c", Message: "parse boom"}},

View File

@ -354,7 +354,7 @@ func emit(fopts *cmdutil.FormatOptions, r Result) {
r.Summary.Passed, r.Summary.Warned, r.Summary.Failed, r.Summary.Skipped)
}
// marker returns the human-mode prefix glyph for a check status.
// marker returns the text-mode prefix glyph for a check status.
//
// Agent / JSON consumers read the stable status string from
// data.checks[].status; the glyphs are presentation-only and never appear

View File

@ -417,10 +417,10 @@ func TestDoctor_BareJSON_FailRaisesSummary(t *testing.T) {
}
}
// TestDoctor_HumanMarker_Warn confirms the human-mode glyph appears for warn
// TestDoctor_TextMarker_Warn confirms the human-mode glyph appears for warn
// rows. Glyph choice is presentation-only; we pin via substring (no width
// alignment assertion since terminal-width handling is environmental).
func TestDoctor_HumanMarker_Warn(t *testing.T) {
func TestDoctor_TextMarker_Warn(t *testing.T) {
out, _ := iostreams.SetForTest(t)
r := Result{
Summary: Summary{Warned: 1},
@ -428,13 +428,13 @@ func TestDoctor_HumanMarker_Warn(t *testing.T) {
{Name: "server_version", Status: StatusWarn, Details: "older"},
},
}
emit(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, r)
emit(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, r)
got := out.String()
if !strings.Contains(got, "⚠") {
t.Errorf("human output should contain ⚠ glyph for warn, got %q", got)
t.Errorf("text output should contain ⚠ glyph for warn, got %q", got)
}
if !strings.Contains(got, "warn") {
t.Errorf("human output should still contain status word `warn`, got %q", got)
t.Errorf("text output should still contain status word `warn`, got %q", got)
}
}

View File

@ -125,7 +125,7 @@ func emitCheck(res *CheckResult, fopts *cmdutil.FormatOptions, w io.Writer) erro
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res, nil)
case cmdutil.FormatHuman, "":
case cmdutil.FormatText, "":
return writeCheckText(w, res)
default:
return fmt.Errorf("unsupported --format %q for kb check", fopts.Mode)

View File

@ -108,7 +108,7 @@ func TestEmitCheck_JSON(t *testing.T) {
}
}
func TestEmitCheck_TextHuman(t *testing.T) {
func TestEmitCheck_Text(t *testing.T) {
var buf bytes.Buffer
res := &CheckResult{
ID: "kb_x", Reachable: true,
@ -116,7 +116,7 @@ func TestEmitCheck_TextHuman(t *testing.T) {
IsProcessing: true, ProcessingCount: 1,
FailedCount: 2,
}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
if err := emitCheck(res, fopts, &buf); err != nil {
t.Fatalf("emitCheck: %v", err)
}

View File

@ -27,7 +27,7 @@ func (f *fakeCreateSvc) CreateKnowledgeBase(_ context.Context, kb *sdk.Knowledge
return f.resp, f.err
}
func TestCreate_Success_Human(t *testing.T) {
func TestCreate_Success_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{
ID: "kb_new",
@ -40,7 +40,7 @@ func TestCreate_Success_Human(t *testing.T) {
Description: "team docs",
EmbeddingModel: "model_x",
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
// Body sent to SDK matches flags.
require.NotNil(t, svc.got)
@ -60,7 +60,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_x", Name: "n"}}
opts := &CreateOptions{Name: "n"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NotNil(t, svc.got)
assert.Equal(t, "", svc.got.EmbeddingModelID, "embedding-model unset ⇒ empty in request")
@ -69,7 +69,7 @@ func TestCreate_Success_OmitsEmbeddingModelWhenEmpty(t *testing.T) {
func TestCreate_NameRequired(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runCreate(context.Background(), &CreateOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@ -81,7 +81,7 @@ func TestCreate_NameRequired(t *testing.T) {
func TestCreate_NameWhitespaceOnly(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runCreate(context.Background(), &CreateOptions{Name: " "}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@ -92,7 +92,7 @@ func TestCreate_NameWhitespaceOnly(t *testing.T) {
func TestCreate_HTTPError_500(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{err: errors.New("HTTP error 500: internal")}
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runCreate(context.Background(), &CreateOptions{Name: "x"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@ -103,7 +103,7 @@ func TestCreate_HTTPError_500(t *testing.T) {
func TestCreate_HTTPError_409Conflict(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{err: errors.New("HTTP error 409: name exists")}
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runCreate(context.Background(), &CreateOptions{Name: "dup"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
@ -132,7 +132,7 @@ func TestCreate_StorageProvider_InjectsRequest(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_s", Name: "n"}}
opts := &CreateOptions{Name: "n", StorageProvider: "Local"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NotNil(t, svc.got.StorageProviderConfig)
assert.Equal(t, "local", svc.got.StorageProviderConfig.Provider, "value should be lowercased + trimmed before send")
@ -142,7 +142,7 @@ func TestCreate_StorageProvider_InvalidValueReturnsFlagError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
opts := &CreateOptions{Name: "n", StorageProvider: "azure"}
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
assert.Equal(t, 2, cmdutil.ExitCode(err), "invalid --storage-provider must exit 2 (flag validation)")
@ -154,7 +154,7 @@ func TestCreate_StorageProvider_OmittedWhenEmpty(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{resp: &sdk.KnowledgeBase{ID: "kb_n", Name: "n"}}
opts := &CreateOptions{Name: "n"} // no --storage-provider
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Nil(t, svc.got.StorageProviderConfig, "empty flag must omit StorageProviderConfig (let server pick default)")
}

View File

@ -33,7 +33,7 @@ func TestDelete_Success_WithForce(t *testing.T) {
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
opts := &DeleteOptions{Yes: true}
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_force"))
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_force"))
assert.True(t, svc.called)
assert.Equal(t, "kb_force", svc.gotID)
@ -46,7 +46,7 @@ func TestDelete_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
p := &testutil.ConfirmPrompter{}
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_missing")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_missing")
require.Error(t, err)
var typed *cmdutil.Error
@ -61,7 +61,7 @@ func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_nontty")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_nontty")
require.Error(t, err)
var typed *cmdutil.Error
@ -97,7 +97,7 @@ func TestDelete_ConfirmYes(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: true}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_yes"))
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_yes"))
assert.True(t, p.Asked, "confirm prompt should fire on TTY without --force")
assert.True(t, svc.called, "answer=yes ⇒ delete proceeds")
@ -108,7 +108,7 @@ func TestDelete_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: false}
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_no")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_no")
require.Error(t, err)
var typed *cmdutil.Error
@ -123,7 +123,7 @@ func TestDelete_ConfirmPrompterError(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Err: prompt.ErrAgentNoPrompt}
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "kb_err")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "kb_err")
require.Error(t, err)
var typed *cmdutil.Error

View File

@ -45,7 +45,7 @@ func (f *fakeEditSvc) UpdateKnowledgeBase(_ context.Context, id string, req *sdk
func TestEdit_RequiresAtLeastOneFlag(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{}
err := runEdit(context.Background(), &EditOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc")
err := runEdit(context.Background(), &EditOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -66,7 +66,7 @@ func TestEdit_OnlyName_PreservesCurrentDescription(t *testing.T) {
}
opts := &EditOptions{}
opts.Name = stringPtr("new")
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
assert.Equal(t, "kb_abc", svc.gotID)
require.NotNil(t, svc.gotReq)
@ -85,7 +85,7 @@ func TestEdit_OnlyDescription_PreservesCurrentName(t *testing.T) {
}
opts := &EditOptions{}
opts.Description = stringPtr("new desc")
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
require.NotNil(t, svc.gotReq)
assert.Equal(t, "new desc", svc.gotReq.Description)
@ -98,7 +98,7 @@ func TestEdit_BothFlags(t *testing.T) {
opts := &EditOptions{}
opts.Name = stringPtr("renamed")
opts.Description = stringPtr("new desc")
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc"))
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc"))
assert.Equal(t, "renamed", svc.gotReq.Name)
assert.Equal(t, "new desc", svc.gotReq.Description)
}
@ -110,7 +110,7 @@ func TestEdit_NotFound(t *testing.T) {
svc := &fakeEditSvc{currentErr: errors.New("HTTP error 404: not found")}
opts := &EditOptions{}
opts.Name = stringPtr("x")
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_missing")
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -127,7 +127,7 @@ func withRootHarnessKB(edit *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "Output format: human | json | ndjson")
pf.String("format", "", "Output format: text | json | ndjson")
pf.StringP("jq", "q", "", "")
kb := &cobra.Command{Use: "kb"}
kb.AddCommand(edit)

View File

@ -23,9 +23,9 @@ func (f *fakeListSvc) ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBa
return f.items, f.err
}
func TestList_Empty_Human(t *testing.T) {
func TestList_Empty_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: []sdk.KnowledgeBase{}}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no knowledge bases)") {
@ -54,14 +54,14 @@ func TestList_Empty_JSON(t *testing.T) {
}
}
func TestList_NonEmpty_Human_RenderColumns(t *testing.T) {
func TestList_NonEmpty_Text_RenderColumns(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.KnowledgeBase{
{ID: "kb1", Name: "Marketing", KnowledgeCount: 5, UpdatedAt: now.Add(-3 * time.Hour)},
{ID: "kb2", Name: "Engineering", KnowledgeCount: 1, UpdatedAt: now.Add(-2 * 24 * time.Hour)},
}
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
@ -120,7 +120,7 @@ func TestList_PinnedFilter(t *testing.T) {
{ID: "kb2", Name: "Engineering", IsPinned: false, UpdatedAt: now.Add(-time.Hour)},
{ID: "kb3", Name: "Finance", IsPinned: true, UpdatedAt: now.Add(-2 * time.Hour)},
}
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
@ -132,12 +132,12 @@ func TestList_PinnedFilter(t *testing.T) {
}
}
func TestList_PinnedFilter_NoPinned_HumanMessage(t *testing.T) {
func TestList_PinnedFilter_NoPinned_TextMessage(t *testing.T) {
out, _ := iostreams.SetForTest(t)
items := []sdk.KnowledgeBase{
{ID: "kb1", Name: "Marketing", IsPinned: false, UpdatedAt: time.Now()},
}
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: items}); err != nil {
if err := runList(context.Background(), &ListOptions{Pinned: true, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no pinned knowledge bases)") {
@ -191,7 +191,7 @@ func TestList_Limit_Zero_Rejected(t *testing.T) {
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListSvc{items: makeKBs(3)})
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeKBs(3)})
if err == nil {
t.Fatal("expected error for negative --limit")
}

View File

@ -76,7 +76,7 @@ func runPin(ctx context.Context, opts *PinOptions, fopts *cmdutil.FormatOptions,
}
// No-op path: the resource is already in the requested state. We
// emit the current resource so callers see the canonical shape on
// both fresh-toggle and no-op paths. Human path prints a confirming
// both fresh-toggle and no-op paths. Text path prints a confirming
// line; agents observe via the unchanged is_pinned field.
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, current, nil)

View File

@ -44,7 +44,7 @@ func (f *fakePinSvc) TogglePinKnowledgeBase(_ context.Context, id string) (*sdk.
func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true))
assert.True(t, svc.toggleCalled, "must call toggle when current state differs")
assert.Contains(t, out.String(), "kb_abc")
}
@ -52,7 +52,7 @@ func TestPin_UnpinnedToPinned_CallsToggle(t *testing.T) {
func TestPin_AlreadyPinned_NoOp(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true))
assert.False(t, svc.toggleCalled, "already pinned ⇒ must not call toggle")
assert.Contains(t, out.String(), "already pinned")
}
@ -60,14 +60,14 @@ func TestPin_AlreadyPinned_NoOp(t *testing.T) {
func TestUnpin_PinnedToUnpinned_CallsToggle(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: true}}
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", false))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", false))
assert.True(t, svc.toggleCalled)
}
func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakePinSvc{current: sdk.KnowledgeBase{IsPinned: false}}
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", false))
require.NoError(t, runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", false))
assert.False(t, svc.toggleCalled, "already unpinned ⇒ must not call toggle")
assert.Contains(t, out.String(), "already unpinned")
}
@ -75,7 +75,7 @@ func TestUnpin_AlreadyUnpinned_NoOp(t *testing.T) {
func TestPin_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakePinSvc{getErr: errors.New("HTTP error 404: not found")}
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_missing", true)
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_missing", true)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -89,7 +89,7 @@ func TestPin_ToggleError(t *testing.T) {
current: sdk.KnowledgeBase{IsPinned: false},
toggleErr: errors.New("HTTP error 500: internal"),
}
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_abc", true)
err := runPin(context.Background(), &PinOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_abc", true)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)

View File

@ -96,7 +96,7 @@ func emitStatus(res *StatusResult, fopts *cmdutil.FormatOptions, w io.Writer) er
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res, nil)
case cmdutil.FormatHuman, "":
case cmdutil.FormatText, "":
return writeStatusText(w, res)
default:
return fmt.Errorf("unsupported --format %q for kb status", fopts.Mode)

View File

@ -78,10 +78,10 @@ func TestEmitStatus_JSON(t *testing.T) {
}
}
func TestEmitStatus_TextHuman(t *testing.T) {
func TestEmitStatus_Text(t *testing.T) {
var buf bytes.Buffer
res := &StatusResult{ID: "kb_x", Reachable: true, KnowledgeCount: 5, ChunkCount: 20, IsProcessing: true, ProcessingCount: 1}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
if err := emitStatus(res, fopts, &buf); err != nil {
t.Fatalf("emitStatus: %v", err)
}

View File

@ -64,9 +64,9 @@ func runView(ctx context.Context, opts *ViewOptions, fopts *cmdutil.FormatOption
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, kb, nil)
}
// Human: KEY: VALUE. Nested config structs (chunking_config, vlm_config,
// etc.) are intentionally omitted from the human render — those are for
// `--format json | jq '.chunking_config'` workflows.
// Text mode: KEY: VALUE. Nested config structs (chunking_config,
// vlm_config, etc.) are intentionally omitted from the text render —
// those are for `--format json | jq '.chunking_config'` workflows.
w := iostreams.IO.Out
fmt.Fprintf(w, "ID: %s\n", kb.ID)
fmt.Fprintf(w, "NAME: %s\n", kb.Name)

View File

@ -22,12 +22,12 @@ func (f *fakeGetSvc) GetKnowledgeBase(ctx context.Context, id string) (*sdk.Know
return f.kb, f.err
}
func TestGet_OK_Human(t *testing.T) {
func TestGet_OK_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{
ID: "kb1", Name: "Marketing", KnowledgeCount: 12, ChunkCount: 245,
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runGet: %v", err)
}
got := out.String()
@ -63,7 +63,7 @@ func TestGet_OK_JSON(t *testing.T) {
func TestGet_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeGetSvc{err: errors.New("HTTP error 404: not found")}
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "missing")
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "missing")
if err == nil {
t.Fatal("expected error")
}
@ -72,12 +72,12 @@ func TestGet_NotFound(t *testing.T) {
}
}
// --- expanded human render: badges + extra KV lines ---
// --- expanded text render: badges + extra KV lines ---
func TestView_Pinned_RendersPinnedLine(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Pinned", IsPinned: true}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
if !strings.Contains(out.String(), "PINNED:") {
@ -88,7 +88,7 @@ func TestView_Pinned_RendersPinnedLine(t *testing.T) {
func TestView_NotPinned_OmitsPinnedLine(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "Plain", IsPinned: false}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
for _, l := range strings.Split(out.String(), "\n") {
@ -101,7 +101,7 @@ func TestView_NotPinned_OmitsPinnedLine(t *testing.T) {
func TestView_Temporary_RendersTempLine(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_t", Name: "Tmp", IsTemporary: true}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_t"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_t"); err != nil {
t.Fatalf("runView: %v", err)
}
if !strings.Contains(out.String(), "TEMPORARY:") {
@ -112,7 +112,7 @@ func TestView_Temporary_RendersTempLine(t *testing.T) {
func TestView_SummaryModel(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "X", SummaryModelID: "summary-model-x"}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -124,7 +124,7 @@ func TestView_SummaryModel(t *testing.T) {
func TestView_TypeAndSource(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb1", Name: "X", Type: "general", Description: "d"}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -136,7 +136,7 @@ func TestView_TypeAndSource(t *testing.T) {
func TestView_Processing(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_p", Name: "Busy", IsProcessing: true, ProcessingCount: 3}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_p"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_p"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
@ -148,7 +148,7 @@ func TestView_Processing(t *testing.T) {
func TestView_NotProcessing_OmitsProcessingLine(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeGetSvc{kb: &sdk.KnowledgeBase{ID: "kb_idle", Name: "Idle", IsProcessing: false}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb_idle"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb_idle"); err != nil {
t.Fatalf("runView: %v", err)
}
for _, l := range strings.Split(out.String(), "\n") {
@ -165,7 +165,7 @@ func TestView_CreatedAt_AlwaysRendered(t *testing.T) {
CreatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),
UpdatedAt: time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC),
}}
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "kb1"); err != nil {
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "kb1"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()

View File

@ -21,7 +21,7 @@ import (
// linkFields enumerates the fields surfaced for `--format json` discovery on
// `link`. Tracks the small linkResult struct.
var linkFields = []string{"context", "kb_id", "kb_name", "project_link_path"}
var linkFields = []string{"profile", "kb_id", "kb_name", "project_link_path"}
type Options struct {
KB string // --kb: KB UUID or name; empty triggers interactive prompt on TTY
@ -29,7 +29,7 @@ type Options struct {
// linkResult is the typed payload emitted under data.
type linkResult struct {
Context string `json:"context"`
Profile string `json:"profile"`
KBID string `json:"kb_id"`
KBName string `json:"kb_name,omitempty"`
ProjectLinkPath string `json:"project_link_path"`
@ -77,7 +77,7 @@ func runLink(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, f
}
linkPath := filepath.Join(cwd, projectlink.DirName, projectlink.FileName)
ctxName, err := resolveContext(f)
profileName, err := resolveProfile(f)
if err != nil {
return err
}
@ -88,7 +88,7 @@ func runLink(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, f
}
link := &projectlink.Project{
Context: ctxName,
Profile: profileName,
KBID: kbID,
CreatedAt: time.Now().UTC(),
}
@ -97,34 +97,34 @@ func runLink(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, f
}
r := linkResult{
Context: ctxName,
Profile: profileName,
KBID: kbID,
KBName: kbName,
ProjectLinkPath: linkPath,
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, r)
return fopts.Emit(iostreams.IO.Out, r, nil)
}
if kbName != "" {
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb=%s, id=%s)\n", linkPath, ctxName, kbName, kbID)
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb=%s, id=%s)\n", linkPath, profileName, kbName, kbID)
} else {
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb_id=%s)\n", linkPath, ctxName, kbID)
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb_id=%s)\n", linkPath, profileName, kbID)
}
return nil
}
// resolveContext picks the auth context to record in the link. There is no
// resolveProfile picks the active profile to record in the link. There is no
// per-invocation override flag on `weknora link` itself - to record under a
// different context, use the global persistent flag (`weknora --context
// staging link --kb my-kb`); the active context at link time is what gets
// different profile, use the global persistent flag (`weknora --profile
// staging link --kb my-kb`); the active profile at link time is what gets
// written.
func resolveContext(f *cmdutil.Factory) (string, error) {
func resolveProfile(f *cmdutil.Factory) (string, error) {
cfg, err := f.Config()
if err != nil {
return "", err
}
if cfg.CurrentContext == "" {
return "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no active context; run `weknora auth login` first")
return "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no active profile; run `weknora auth login` first")
}
return cfg.CurrentContext, nil
}
@ -166,7 +166,7 @@ func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory)
return "", "", cmdutil.WrapHTTP(err, "list knowledge bases")
}
if len(kbs) == 0 {
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active context; create one first")
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active profile; create one first")
}
fmt.Fprintln(iostreams.IO.Err, "Available knowledge bases:")
for _, kb := range kbs {

View File

@ -71,7 +71,7 @@ func TestLink_ByID(t *testing.T) {
p, err := projectlink.Load(linkPath)
require.NoError(t, err)
assert.Equal(t, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", p.KBID)
assert.Equal(t, "default", p.Context)
assert.Equal(t, "default", p.Profile)
assert.Contains(t, out.String(), "✓")
}
@ -118,7 +118,7 @@ func TestLink_OverwritesExisting(t *testing.T) {
// Pre-existing link.
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
require.NoError(t, projectlink.Save(linkPath, &projectlink.Project{
Context: "default", KBID: "11111111-1111-4111-8111-111111111111",
Profile: "default", KBID: "11111111-1111-4111-8111-111111111111",
}))
f := newFactory("default", nil)

View File

@ -72,7 +72,7 @@ func runUnlink(opts *UnlinkOptions, fopts *cmdutil.FormatOptions) error {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "remove %s", linkPath)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, unlinkResult{ProjectLinkPath: linkPath})
return fopts.Emit(iostreams.IO.Out, unlinkResult{ProjectLinkPath: linkPath}, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Unlinked %s\n", linkPath)
return nil

View File

@ -1,6 +1,7 @@
package linkcmd
import (
"encoding/json"
"errors"
"os"
"path/filepath"
@ -20,7 +21,7 @@ func mkLinkFile(t *testing.T, dir string) string {
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
if err := projectlink.Save(full, &projectlink.Project{Context: "default", KBID: "kb_abc"}); err != nil {
if err := projectlink.Save(full, &projectlink.Project{Profile: "default", KBID: "kb_abc"}); err != nil {
t.Fatalf("save: %v", err)
}
return full
@ -89,12 +90,19 @@ func TestUnlink_JSON_BareObject(t *testing.T) {
t.Fatalf("runUnlink: %v", err)
}
got := out.String()
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal([]byte(got), &env); err != nil {
t.Fatalf("parse: %v\n%s", err, got)
}
if !env.OK {
t.Errorf("envelope.ok must be true, got %q", got)
}
for _, want := range []string{`"project_link_path"`, projectlink.DirName} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in output:\n%s", want, got)
}
}
if strings.Contains(got, `"ok":`) {
t.Errorf("bare output must not carry envelope keys, got %q", got)
}
}

View File

@ -1,4 +1,4 @@
package contextcmd
package profilecmd
import (
"fmt"
@ -16,9 +16,9 @@ type AddOptions struct {
User string
}
// contextAddFields enumerates the fields surfaced for `--format json` discovery on
// `context add`. The result describes the newly-registered context.
var contextAddFields = []string{
// profileAddFields enumerates the fields surfaced for `--format json` discovery on
// `profile add`. The result describes the newly-registered profile.
var profileAddFields = []string{
"name", "host", "user", "current",
}
@ -30,9 +30,9 @@ type addResult struct {
Current bool `json:"current"`
}
// NewCmdAdd builds `weknora context add`. Registers a *credentialless*
// NewCmdAdd builds `weknora profile add`. Registers a *credentialless*
// connection target - host + optional user only. Credentials for the new
// context are attached separately with `weknora auth login --name <n>`,
// profile are attached separately with `weknora auth login --name <n>`,
// separating "where" the CLI talks to (the host) and "how" it authenticates
// (the credential). If you want one command for both, run
// `weknora auth login --name <n> --host <h>` instead.
@ -40,16 +40,16 @@ func NewCmdAdd(f *cmdutil.Factory) *cobra.Command {
opts := &AddOptions{}
cmd := &cobra.Command{
Use: "add <name>",
Short: "Register a new context (host without credentials)",
Long: `Add a new context entry to config.yaml. Stores host (and optionally
Short: "Register a new profile (host without credentials)",
Long: `Add a new profile entry to config.yaml. Stores host (and optionally
user) but does NOT prompt for credentials. Use ` + "`weknora auth login --name <n>`" + ` to
attach credentials in a single step instead, or run ` + "`weknora auth login --name <n>`" + ` after
` + "`weknora context add`" + ` to fill them in.
` + "`weknora profile add`" + ` to fill them in.
The first context added is auto-selected as the current context. Subsequent
adds leave the current context untouched.`,
Example: ` weknora context add staging --host https://staging.example.com
weknora context add prod --host https://prod.example.com --user alice@example.com`,
The first profile added is auto-selected as the current profile. Subsequent
adds leave the current profile untouched.`,
Example: ` weknora profile add staging --host https://staging.example.com
weknora profile add prod --host https://prod.example.com --user alice@example.com`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@ -61,8 +61,8 @@ adds leave the current context untouched.`,
},
}
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)")
cmdutil.AddFormatFlag(cmd, contextAddFields...)
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'profile list' (optional, cosmetic only)")
cmdutil.AddFormatFlag(cmd, profileAddFields...)
_ = cmd.MarkFlagRequired("host")
return cmd
}
@ -83,8 +83,8 @@ func runAdd(opts *AddOptions, fopts *cmdutil.FormatOptions, name string) error {
if _, exists := cfg.Contexts[name]; exists {
return &cmdutil.Error{
Code: cmdutil.CodeResourceAlreadyExists,
Message: fmt.Sprintf("context %q already exists", name),
Hint: fmt.Sprintf("use a different name, or run `weknora context remove %s` first", name),
Message: fmt.Sprintf("profile %q already exists", name),
Hint: fmt.Sprintf("use a different name, or run `weknora profile remove %s` first", name),
}
}
if cfg.Contexts == nil {
@ -100,12 +100,12 @@ func runAdd(opts *AddOptions, fopts *cmdutil.FormatOptions, name string) error {
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst})
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst}, nil)
}
if wasFirst {
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
} else {
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name)
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name)
}
return nil
}
@ -114,18 +114,18 @@ func runAdd(opts *AddOptions, fopts *cmdutil.FormatOptions, name string) error {
// digits, dash, underscore, dot. The `.` exception lets emails / DNS-like
// names through; the path-traversal `..` is structurally rejected by a
// separate guard because it would let a hand-edited config.yaml claim a
// context whose name walks out of the keyring namespace.
// profile whose name walks out of the keyring namespace.
func validateName(name string) error {
if name == "" {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "context name must not be empty",
Message: "profile name must not be empty",
}
}
if name == "." || name == ".." || strings.Contains(name, "/") || strings.Contains(name, "\\") {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("context name %q is reserved or path-like", name),
Message: fmt.Sprintf("profile name %q is reserved or path-like", name),
Hint: "use letters, digits, dashes, underscores, or dots",
}
}
@ -139,7 +139,7 @@ func validateName(name string) error {
default:
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("context name %q contains invalid character %q", name, r),
Message: fmt.Sprintf("profile name %q contains invalid character %q", name, r),
Hint: "use letters, digits, dashes, underscores, or dots",
}
}

View File

@ -1,4 +1,4 @@
package contextcmd
package profilecmd
import (
"encoding/json"
@ -24,7 +24,7 @@ func TestAdd_HappyPath(t *testing.T) {
}
c, ok := cfg.Contexts["staging"]
if !ok {
t.Fatalf("staging not in Contexts; got keys=%v", contextKeys(cfg.Contexts))
t.Fatalf("staging not in Contexts; got keys=%v", profileKeys(cfg.Contexts))
}
if c.Host != "https://my.example.com" {
t.Errorf("Host=%q, want https://my.example.com", c.Host)
@ -32,9 +32,9 @@ func TestAdd_HappyPath(t *testing.T) {
if c.User != "alice@example.com" {
t.Errorf("User=%q, want alice@example.com", c.User)
}
// First context auto-becomes current.
// First profile auto-becomes current.
if cfg.CurrentContext != "staging" {
t.Errorf("first context should auto-become current, got CurrentContext=%q", cfg.CurrentContext)
t.Errorf("first profile should auto-become current, got CurrentContext=%q", cfg.CurrentContext)
}
if !strings.Contains(out.String(), "staging") {
t.Errorf("output should mention added name, got %q", out.String())
@ -67,7 +67,7 @@ func TestAdd_DuplicateName(t *testing.T) {
// Existing entry must NOT be overwritten.
got, _ := config.Load()
if got.Contexts["staging"].Host != "https://old.example.com" {
t.Errorf("existing context overwritten; Host=%q", got.Contexts["staging"].Host)
t.Errorf("existing profile overwritten; Host=%q", got.Contexts["staging"].Host)
}
}
@ -98,7 +98,7 @@ func TestAdd_BadHost(t *testing.T) {
}
}
func TestAdd_SecondContextDoesNotChangeCurrent(t *testing.T) {
func TestAdd_SecondProfileDoesNotChangeCurrent(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t)
@ -115,7 +115,7 @@ func TestAdd_SecondContextDoesNotChangeCurrent(t *testing.T) {
}
got, _ := config.Load()
if got.CurrentContext != "production" {
t.Errorf("adding a second context must not switch current; got %q", got.CurrentContext)
t.Errorf("adding a second profile must not switch current; got %q", got.CurrentContext)
}
}
@ -126,10 +126,14 @@ func TestAdd_JSON(t *testing.T) {
if err := runAdd(&AddOptions{Host: "https://my.example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, "staging"); err != nil {
t.Fatalf("runAdd: %v", err)
}
var got map[string]any
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
}
got := env.Data
if got["name"] != "staging" {
t.Errorf("name should be staging, got %v", got)
}
@ -137,6 +141,6 @@ func TestAdd_JSON(t *testing.T) {
t.Errorf("host wrong: %v", got)
}
if got["current"] != true {
t.Errorf("first added context must be current=true, got %v", got)
t.Errorf("first added profile must be current=true, got %v", got)
}
}

View File

@ -1,4 +1,4 @@
package contextcmd
package profilecmd
import (
"fmt"
@ -11,13 +11,14 @@ import (
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
)
type ListOptions struct{}
// contextListFields enumerates the fields surfaced for `--format json` discovery on
// `context list`. Each entry is a per-context summary row.
var contextListFields = []string{
// profileListFields enumerates the fields surfaced for `--format json` discovery on
// `profile list`. Each entry is a per-profile summary row.
var profileListFields = []string{
"name", "host", "user", "current",
}
@ -28,18 +29,18 @@ type listEntry struct {
Current bool `json:"current"`
}
// NewCmdList builds `weknora context list`. Per-host enumeration with an
// NewCmdList builds `weknora profile list`. Per-host enumeration with an
// active marker. Reads only config.yaml - no network, no keyring touch.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List configured contexts",
Long: `Show every context registered in ~/.config/weknora/config.yaml. The
active context (used by subsequent commands when --context is unset) is
Short: "List configured profiles",
Long: `Show every profile registered in ~/.config/weknora/config.yaml. The
active profile (used by subsequent commands when --profile is unset) is
marked with a leading "*". No network requests are issued.
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. "profile list" is the catalog of *where*
the CLI can talk to; "auth list" is the catalog of *how*.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
@ -51,7 +52,7 @@ the CLI can talk to; "auth list" is the catalog of *how*.`,
return runList(fopts)
},
}
cmdutil.AddFormatFlag(cmd, contextListFields...)
cmdutil.AddFormatFlag(cmd, profileListFields...)
return cmd
}
@ -72,10 +73,11 @@ func runList(fopts *cmdutil.FormatOptions) error {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, entries)
meta := &output.Meta{Count: len(entries)}
return fopts.Emit(iostreams.IO.Out, entries, meta)
}
if len(entries) == 0 {
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` (or `weknora context add`) to create one.")
fmt.Fprintln(iostreams.IO.Out, "No profiles configured. Run `weknora auth login` (or `weknora profile add`) to create one.")
return nil
}
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)

View File

@ -1,4 +1,4 @@
package contextcmd
package profilecmd
import (
"encoding/json"
@ -17,8 +17,8 @@ func TestList_Empty(t *testing.T) {
if err := runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "No contexts") {
t.Errorf("empty output should mention `No contexts`, got %q", out.String())
if !strings.Contains(out.String(), "No profiles") {
t.Errorf("empty output should mention `No profiles`, got %q", out.String())
}
}
@ -56,7 +56,7 @@ func TestList_MultipleSorted(t *testing.T) {
// active marker on staging row
stgLine := lineContaining(got, "staging")
if !strings.HasPrefix(stgLine, "*") {
t.Errorf("active context row must start with `*`, got %q", stgLine)
t.Errorf("active profile row must start with `*`, got %q", stgLine)
}
}
@ -79,10 +79,14 @@ func TestList_JSON(t *testing.T) {
t.Fatalf("runList: %v", err)
}
var rows []map[string]any
if err := json.Unmarshal(out.Bytes(), &rows); err != nil {
var env struct {
OK bool `json:"ok"`
Data []map[string]any `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
}
rows := env.Data
if len(rows) != 2 {
t.Fatalf("expected 2 entries, got %d", len(rows))
}

View File

@ -0,0 +1,26 @@
// Package profilecmd holds the `weknora profile` command tree
// (list / add / remove / use).
//
// Package name `profilecmd` (not `profile`) to keep the pattern consistent
// with other cmd subpackages.
// The cobra Use: string is "profile" - this is what users type.
package profilecmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// NewCmd builds the `weknora profile` parent command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "profile",
Short: "Manage CLI profiles (named connection targets)",
}
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdAdd(f))
cmd.AddCommand(NewCmdRemove(f))
cmd.AddCommand(NewCmdUse(f))
return cmd
}

View File

@ -1,4 +1,4 @@
package contextcmd
package profilecmd
import (
"fmt"
@ -16,9 +16,9 @@ type RemoveOptions struct {
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
}
// contextRemoveFields enumerates the fields surfaced for `--format json` discovery on
// `context remove`. The result reports the disposition of the removed entry.
var contextRemoveFields = []string{
// profileRemoveFields enumerates the fields surfaced for `--format json` discovery on
// `profile remove`. The result reports the disposition of the removed entry.
var profileRemoveFields = []string{
"name", "removed", "was_current",
}
@ -29,26 +29,26 @@ type removeResult struct {
WasCurrent bool `json:"was_current"`
}
// NewCmdRemove builds `weknora context remove`. Drops the entry from
// NewCmdRemove builds `weknora profile remove`. Drops the entry from
// config.yaml and best-effort clears keyring references. Removing a
// non-current context is low-friction (no prompt). Removing the *current*
// context triggers the destructive-write confirmation protocol (exit 10),
// non-current profile is low-friction (no prompt). Removing the *current*
// profile triggers the destructive-write confirmation protocol (exit 10),
// because subsequent commands will have no default connection target.
func NewCmdRemove(f *cmdutil.Factory) *cobra.Command {
opts := &RemoveOptions{}
cmd := &cobra.Command{
Use: "remove <name>",
Short: "Remove a context (drops entry, clears keyring refs)",
Long: `Deletes the named context from config.yaml and best-effort clears any
Short: "Remove a profile (drops entry, clears keyring refs)",
Long: `Deletes the named profile from config.yaml and best-effort clears any
keyring references it owned (matches ` + "`weknora auth logout`" + `).
Removing the current context also clears CurrentContext - subsequent commands
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
every later command, removing the current context requires explicit -y/--yes
Removing the current profile also clears CurrentContext - subsequent commands
will error until you select another with ` + "`weknora profile use <name>`" + ` or pick
one up via the global ` + "`--profile`" + ` flag. Because that change is observable in
every later command, removing the current profile requires explicit -y/--yes
in scripted / --format json invocations (exit code 10; see cli/README.md).`,
Example: ` weknora context remove staging # remove non-current → no prompt
weknora context remove production -y # remove current → confirm`,
Example: ` weknora profile remove staging # remove non-current → no prompt
weknora profile remove production -y # remove current → confirm`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@ -64,7 +64,18 @@ in scripted / --format json invocations (exit code 10; see cli/README.md).`,
return runRemove(opts, fopts, args[0], store, f.Prompter())
},
}
cmdutil.AddFormatFlag(cmd, contextRemoveFields...)
cmdutil.AddFormatFlag(cmd, profileRemoveFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "remove a named profile and its stored credentials",
RequiredFlags: []string{"<name> (positional)"},
Examples: []string{
"weknora profile remove staging",
"weknora profile remove production -y",
},
Warnings: []string{
"profile remove drops the named profile and its stored credentials. Never auto-add -y.",
},
})
return cmd
}
@ -80,10 +91,10 @@ func runRemove(opts *RemoveOptions, fopts *cmdutil.FormatOptions, name string, s
wasCurrent := name == cfg.CurrentContext
jsonOut := fopts.WantsJSON()
// Confirmation only fires for removing the current context - non-current
// Confirmation only fires for removing the current profile - non-current
// remove uses the same low-friction policy as `auth logout`.
if wasCurrent {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current context", name); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current profile", name, "profile.remove", fmt.Sprintf("weknora profile remove %s -y", name)); err != nil {
return err
}
}
@ -97,24 +108,24 @@ func runRemove(opts *RemoveOptions, fopts *cmdutil.FormatOptions, name string, s
if err := config.Save(cfg); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
}
clearContextSecrets(store, ctx, name)
clearProfileSecrets(store, ctx, name)
result := removeResult{Name: name, Removed: true, WasCurrent: wasCurrent}
if jsonOut {
return fopts.Emit(iostreams.IO.Out, result)
return fopts.Emit(iostreams.IO.Out, result, nil)
}
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 profile %s (current profile cleared - run `weknora profile use <name>` to pick another)\n", name)
} else {
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s\n", name)
fmt.Fprintf(iostreams.IO.Out, "✓ Removed profile %s\n", name)
}
return nil
}
// clearContextSecrets mirrors auth/logout.go: best-effort delete every secret
// slot the context references. Errors are swallowed so a missing keyring
// clearProfileSecrets mirrors auth/logout.go: best-effort delete every secret
// slot the profile references. Errors are swallowed so a missing keyring
// entry doesn't block remove (same policy as `auth logout`).
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
func clearProfileSecrets(store secrets.Store, c config.Context, name string) {
if c.TokenRef != "" {
_ = store.Delete(name, "access")
}

View File

@ -1,4 +1,4 @@
package contextcmd
package profilecmd
import (
"errors"
@ -13,7 +13,7 @@ import (
)
// seedStore returns a MemStore pre-loaded with sentinel values for every
// secret slot a context might reference. Tests assert deletion by checking
// secret slot a profile might reference. Tests assert deletion by checking
// `secrets.ErrNotFound` post-runRemove.
func seedStore(t *testing.T, name string, slots ...string) *secrets.MemStore {
t.Helper()
@ -66,7 +66,7 @@ func TestRemove_NonCurrent_NoPromptNeeded(t *testing.T) {
}
assertDeleted(t, store, "staging", "api_key")
if !strings.Contains(out.String(), "staging") {
t.Errorf("output should mention removed context, got %q", out.String())
t.Errorf("output should mention removed profile, got %q", out.String())
}
}
@ -90,8 +90,8 @@ func TestRemove_NotFound_WithDidYouMean(t *testing.T) {
if !ok {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if cm.Code != cmdutil.CodeLocalContextNotFound {
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeLocalContextNotFound)
if cm.Code != cmdutil.CodeLocalProfileNotFound {
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeLocalProfileNotFound)
}
if !strings.Contains(cm.Hint, "production") {
t.Errorf("hint should suggest 'production', got %q", cm.Hint)
@ -164,7 +164,7 @@ func TestRemove_Current_WithYes_ClearsCurrent(t *testing.T) {
t.Errorf("removing current must clear CurrentContext, got %q", got.CurrentContext)
}
assertDeleted(t, store, "production", "access")
if !strings.Contains(out.String(), "current context cleared") {
if !strings.Contains(out.String(), "current profile cleared") {
t.Errorf("output should warn about cleared current, got %q", out.String())
}
}

View File

@ -1,4 +1,4 @@
package contextcmd
package profilecmd
import (
"fmt"
@ -11,27 +11,27 @@ import (
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// contextUseFields enumerates fields surfaced for `--format json` discovery on
// `context use`.
var contextUseFields = []string{"current_context", "previous_context"}
// profileUseFields enumerates fields surfaced for `--format json` discovery on
// `profile use`.
var profileUseFields = []string{"current_profile", "previous_profile"}
// NewCmdUse builds the `weknora context use <name>` command.
// NewCmdUse builds the `weknora profile use <name>` command.
func NewCmdUse(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "use <name>",
Short: "Switch the default context for subsequent commands",
Long: `Switches the default context written in config.yaml. Names are case-sensitive.
Short: "Switch the default profile for subsequent commands",
Long: `Switches the default profile written in config.yaml. Names are case-sensitive.
The active context is what every subsequent command uses for auth + host. The
global --context flag (e.g. weknora --context staging kb list) overrides for
The active profile is what every subsequent command uses for auth + host. The
global --profile flag (e.g. weknora --profile staging kb list) overrides for
one command without writing to disk.
AI agents: Do NOT switch the active context unless the user explicitly asked
you to. Context selection is a user preference; one-shot overrides should use
the global --context flag instead, which writes nothing to disk.`,
Example: ` weknora context use staging # persist switch
weknora --context staging kb list # one-shot override (no disk write)
weknora context use staging --format json # {current_context, previous_context}`,
AI agents: Do NOT switch the active profile unless the user explicitly asked
you to. Profile selection is a user preference; one-shot overrides should use
the global --profile flag instead, which writes nothing to disk.`,
Example: ` weknora profile use staging # persist switch
weknora --profile staging kb list # one-shot override (no disk write)
weknora profile use staging --format json # {current_profile, previous_profile}`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@ -42,13 +42,13 @@ the global --context flag instead, which writes nothing to disk.`,
return runUse(args[0], fopts)
},
}
cmdutil.AddFormatFlag(cmd, contextUseFields...)
cmdutil.AddFormatFlag(cmd, profileUseFields...)
return cmd
}
type useResult struct {
CurrentContext string `json:"current_context"`
PreviousContext string `json:"previous_context,omitempty"`
CurrentProfile string `json:"current_profile"`
PreviousProfile string `json:"previous_profile,omitempty"`
}
func runUse(name string, fopts *cmdutil.FormatOptions) error {
@ -64,14 +64,14 @@ func runUse(name string, fopts *cmdutil.FormatOptions) error {
if err := config.Save(cfg); err != nil {
return err
}
result := useResult{CurrentContext: name, PreviousContext: prev}
result := useResult{CurrentProfile: name, PreviousProfile: prev}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, result)
return fopts.Emit(iostreams.IO.Out, result, nil)
}
if prev != "" && prev != name {
fmt.Fprintf(iostreams.IO.Out, "✓ Switched context to %s (was %s)\n", name, prev)
fmt.Fprintf(iostreams.IO.Out, "✓ Switched profile to %s (was %s)\n", name, prev)
} else {
fmt.Fprintf(iostreams.IO.Out, "✓ Active context: %s\n", name)
fmt.Fprintf(iostreams.IO.Out, "✓ Active profile: %s\n", name)
}
return nil
}
@ -79,27 +79,27 @@ func runUse(name string, fopts *cmdutil.FormatOptions) error {
func notFoundError(name string, cfg *config.Config) error {
if len(cfg.Contexts) == 0 {
return &cmdutil.Error{
Code: cmdutil.CodeLocalContextNotFound,
Message: fmt.Sprintf("context not found: %s", name),
Hint: "no contexts registered - run `weknora auth login` first",
Code: cmdutil.CodeLocalProfileNotFound,
Message: fmt.Sprintf("profile not found: %s", name),
Hint: "no profiles registered - run `weknora auth login` first",
}
}
keys := contextKeys(cfg.Contexts)
keys := profileKeys(cfg.Contexts)
candidate := closestMatch(name, keys)
var hint string
if candidate != "" && candidate != name {
hint = fmt.Sprintf("did you mean: %q?", candidate)
} else {
hint = fmt.Sprintf("available contexts: %v", keys)
hint = fmt.Sprintf("available profiles: %v", keys)
}
return &cmdutil.Error{
Code: cmdutil.CodeLocalContextNotFound,
Message: fmt.Sprintf("context not found: %s", name),
Code: cmdutil.CodeLocalProfileNotFound,
Message: fmt.Sprintf("profile not found: %s", name),
Hint: hint,
}
}
func contextKeys(m map[string]config.Context) []string {
func profileKeys(m map[string]config.Context) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)

View File

@ -1,4 +1,4 @@
package contextcmd
package profilecmd
import (
"strings"
@ -36,7 +36,7 @@ func TestUse_OK(t *testing.T) {
t.Errorf("CurrentContext = %q, want production", got.CurrentContext)
}
if !strings.Contains(out.String(), "production") {
t.Errorf("output should mention switched-to context, got %q", out.String())
t.Errorf("output should mention switched-to profile, got %q", out.String())
}
}
@ -60,8 +60,8 @@ func TestUse_NotFound_WithDidYouMean(t *testing.T) {
if !ok {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if cm.Code != cmdutil.CodeLocalContextNotFound {
t.Errorf("code = %q, want %q", cm.Code, cmdutil.CodeLocalContextNotFound)
if cm.Code != cmdutil.CodeLocalProfileNotFound {
t.Errorf("code = %q, want %q", cm.Code, cmdutil.CodeLocalProfileNotFound)
}
if cm.Hint != `did you mean: "production"?` {
t.Errorf("hint should be exact `did you mean: \"production\"?`, got %q", cm.Hint)
@ -95,7 +95,7 @@ func TestUse_NotFound_DeterministicTieBreak(t *testing.T) {
}
}
func TestUse_NotFound_EmptyContexts(t *testing.T) {
func TestUse_NotFound_EmptyProfiles(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t)
@ -105,7 +105,7 @@ func TestUse_NotFound_EmptyContexts(t *testing.T) {
}
cm := err.(*cmdutil.Error)
if !strings.Contains(cm.Hint, "auth login") {
t.Errorf("hint should mention `auth login` for empty Contexts, got %q", cm.Hint)
t.Errorf("hint should mention `auth login` for empty profiles, got %q", cm.Hint)
}
}

View File

@ -53,7 +53,7 @@ func resolveFormatEarly(args []string) {
}
}
switch mode {
case "json", "ndjson", "human":
case "json", "ndjson", "text":
cmdutil.SetFormatMode(mode)
case "":
// nothing to set; leave globalFormatMode at its zero value
@ -219,7 +219,7 @@ func addGlobalFlags(cmd *cobra.Command) {
// instead of being rejected as "unknown flag" exit 2 by cobra. Commands
// that don't produce JSON output (e.g. `completion bash`) ignore the flag
// rather than error — the unified agent contract is worth the trade.
pf.String("format", "", "Output format: human | json | ndjson (default: json)")
pf.String("format", "", "Output format: text | json | ndjson (default: json)")
pf.StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --format json|ndjson)")
}

View File

@ -27,14 +27,14 @@ func (f *fakeChunksSvc) HybridSearch(_ context.Context, kbID string, p *sdk.Sear
return f.results, f.err
}
func TestRunSearch_HumanOutput(t *testing.T) {
func TestRunSearch_TextOutput(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
{Score: 0.92, Content: "first chunk", KnowledgeID: "doc-1", MatchType: sdk.MatchTypeVector},
{Score: 0.81, Content: "second chunk", KnowledgeID: "doc-2", MatchType: sdk.MatchTypeKeyword},
}}
opts := &ChunksOptions{Query: "hello", KBID: "kb_abc", Limit: 5}
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runChunks(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Equal(t, "kb_abc", svc.gotKB)
assert.Equal(t, "hello", svc.gotQ)
@ -46,7 +46,7 @@ func TestRunSearch_HumanOutput(t *testing.T) {
// JSON output must surface match_type so machine consumers / agents can
// reason about retrieval channels without re-implementing the wire format.
// (Human renderer keeps default minimal - diagnostic info opt-in via --format json.)
// (Text renderer keeps default minimal - diagnostic info opt-in via --format json.)
func TestRunSearch_JSONIncludesMatchType(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: []*sdk.SearchResult{
@ -74,7 +74,7 @@ func TestRunSearch_JSONOutput(t *testing.T) {
func TestRunSearch_EmptyResults(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChunksSvc{results: nil}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "(no results)")
}
@ -90,7 +90,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
{Score: 0, Content: "enrichment parent"}, // server-padded
{Score: 0, Content: "enrichment nearby"}, // server-padded
}}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", Limit: 3}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
assert.Contains(t, got, "3 result(s)")
assert.NotContains(t, got, "enrichment parent")
@ -99,7 +99,7 @@ func TestRunSearch_LimitHardCap(t *testing.T) {
func TestRunSearch_BothChannelsDisabled(t *testing.T) {
iostreams.SetForTest(t)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeChunksSvc{})
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1", NoVector: true, NoKeyword: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeChunksSvc{})
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
@ -107,7 +107,7 @@ func TestRunSearch_BothChannelsDisabled(t *testing.T) {
func TestRunSearch_ServiceError_Transport(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeChunksSvc{err: assert.AnError}
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -118,7 +118,7 @@ func TestRunSearch_ServiceError_Transport(t *testing.T) {
func TestRunSearch_ServiceError_HTTPNotFound(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeChunksSvc{err: errors.New("HTTP error 404: knowledge base not found")}
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "missing"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -132,7 +132,7 @@ func TestIndent(t *testing.T) {
func TestRunSearch_NilService(t *testing.T) {
iostreams.SetForTest(t)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, nil)
err := runChunks(context.Background(), &ChunksOptions{Query: "q", KBID: "kb1"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "server.error")
}
@ -168,7 +168,7 @@ func TestRunSearch_NoVectorPassedThrough(t *testing.T) {
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
Query: "q", KBID: "kb1", NoVector: true,
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NotNil(t, got)
assert.True(t, got.DisableVectorMatch)
assert.False(t, got.DisableKeywordsMatch)
@ -180,7 +180,7 @@ func TestRunSearch_NoKeywordPassedThrough(t *testing.T) {
svc := &capturingChunksSvc{capture: func(p *sdk.SearchParams) { got = p }}
require.NoError(t, runChunks(context.Background(), &ChunksOptions{
Query: "q", KBID: "kb1", NoKeyword: true,
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
require.NotNil(t, got)
assert.True(t, got.DisableKeywordsMatch)
assert.False(t, got.DisableVectorMatch)

View File

@ -48,7 +48,7 @@ func TestDocsSearch_Substring(t *testing.T) {
},
total: 2,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "q3", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Equal(t, "q3", svc.lastFilter.Keyword, "query must be threaded as filter.Keyword")
got := out.String()
assert.Contains(t, got, "d1")
@ -62,7 +62,7 @@ func TestDocsSearch_MatchesFileName(t *testing.T) {
pages: map[int][]sdk.Knowledge{1: {{ID: "d1", Title: "Untitled", FileName: "report.pdf"}}},
total: 1,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "report", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "d1")
}
@ -81,7 +81,7 @@ func TestDocsSearch_PaginatesUntilTotal(t *testing.T) {
pages: map[int][]sdk.Knowledge{1: page1, 2: page2},
total: int64(docsPageSize) + 1,
}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: docsPageSize + 1, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: docsPageSize + 1, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "found")
assert.Equal(t, []int{1, 2}, svc.calls, "must page past the first batch when more items reported")
}
@ -93,7 +93,7 @@ func TestDocsSearch_StopsAtLimit(t *testing.T) {
page1[i] = sdk.Knowledge{ID: "match", Title: "needle"}
}
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: page1}, total: 1000}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "needle", KBID: "kb1", Limit: 3, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
// Must not request page 2 because limit was hit mid-page.
assert.Equal(t, []int{1}, svc.calls)
}
@ -118,7 +118,7 @@ func TestDocsSearch_JSON(t *testing.T) {
func TestDocsSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDocsSearchSvc{err: errors.New("HTTP error 404: kb not found")}
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runDocsSearch(context.Background(), &DocsSearchOptions{Query: "x", KBID: "missing", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -165,7 +165,7 @@ func TestSearchDocs_AllPagesFalse_StopsAtFirstPage(t *testing.T) {
func TestSearchDocs_KeywordPassedToFilter(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDocsSearchSvc{pages: map[int][]sdk.Knowledge{1: {{ID: "d1"}}}, total: 1}
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "my-query", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runDocsSearch(context.Background(), &DocsSearchOptions{Query: "my-query", KBID: "kb1", Limit: 20, PageSize: docsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Equal(t, "my-query", svc.lastFilter.Keyword, "Query must be threaded as filter.Keyword on ListKnowledgeWithFilter")
// Other filter fields must be empty - search docs only forwards the keyword.
assert.Empty(t, svc.lastFilter.ParseStatus)

View File

@ -31,7 +31,7 @@ func TestKBSearch_Substring(t *testing.T) {
{ID: "kb2", Name: "Engineering Docs", KnowledgeCount: 50},
{ID: "kb3", Name: "Marketing Q4 Plan", KnowledgeCount: 5},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
assert.Contains(t, got, "kb1")
assert.Contains(t, got, "kb3")
@ -43,7 +43,7 @@ func TestKBSearch_CaseInsensitive(t *testing.T) {
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
{ID: "kb1", Name: "ENGINEERING"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "engineering", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "kb1")
}
@ -52,7 +52,7 @@ func TestKBSearch_MatchesDescription(t *testing.T) {
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{
{ID: "kb1", Name: "Engineering", Description: "all marketing docs are here"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "kb1")
}
@ -63,7 +63,7 @@ func TestKBSearch_SortByNameLength(t *testing.T) {
{ID: "kb_short", Name: "marketing"},
{ID: "kb_mid", Name: "marketing 2024"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
// Order: shortest name first.
iShort := strings.Index(got, "kb_short")
@ -79,7 +79,7 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
{ID: "a", Name: "match-a"}, {ID: "b", Name: "match-b"},
{ID: "c", Name: "match-c"}, {ID: "d", Name: "match-d"},
}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "match", Limit: 2}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
count := 0
for _, id := range []string{"a", "b", "c", "d"} {
@ -93,7 +93,7 @@ func TestKBSearch_LimitHardCap(t *testing.T) {
func TestKBSearch_NoMatches(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{items: []sdk.KnowledgeBase{{Name: "foo"}}}
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "bar", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "(no matches)")
}
@ -115,7 +115,7 @@ func TestKBSearch_JSON(t *testing.T) {
func TestKBSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeKBSearchSvc{err: errors.New("HTTP error 401: unauthenticated")}
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runKBSearch(context.Background(), &KBSearchOptions{Query: "x", Limit: 20}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)

View File

@ -39,7 +39,7 @@ func TestSessionsSearch_TitleAndDescription(t *testing.T) {
}},
total: 3,
}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "design", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
assert.Contains(t, got, "s1")
assert.Contains(t, got, "s2")
@ -52,7 +52,7 @@ func TestSessionsSearch_NoMatches(t *testing.T) {
pages: map[int][]sdk.Session{1: {{Title: "foo"}}},
total: 1,
}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "missing", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "(no matches)")
}
@ -63,14 +63,14 @@ func TestSessionsSearch_PaginatesAndStopsAtLimit(t *testing.T) {
page1[i] = sdk.Session{ID: "m", Title: "needle"}
}
svc := &fakeSessionsSearchSvc{pages: map[int][]sdk.Session{1: page1}, total: 1000}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 5, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Equal(t, []int{1}, svc.calls, "stops paging when limit reached")
}
func TestSessionsSearch_NetworkError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeSessionsSearchSvc{err: errors.New("HTTP error 500: internal")}
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "x", Limit: 20, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -90,7 +90,7 @@ func TestSessionsSearch_RendersFuzzyTime(t *testing.T) {
}},
total: 1,
}
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runSessionsSearch(context.Background(), &SessionsSearchOptions{Query: "needle", Limit: 10, PageSize: sessionsPageSize, AllPages: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
body := out.String()
assert.Contains(t, body, "hour", "must render relative time (e.g. 'about 2 hours ago'), not raw RFC3339")
assert.NotContains(t, body, "T0", "raw RFC3339 has 'T' between date and time; fuzzyTime output should not")

View File

@ -60,11 +60,12 @@ The 'weknora agent' subtree handles CRUD only (list / view / create /
edit / delete / status / check).
Modes:
TTY (human format, default): live answer streaming + tool-trace footer
--format json / --format ndjson / pipe: NDJSON event stream — one init line
at head (session_id, agent_id), then raw SDK
agent events verbatim. Both json and ndjson
flags produce the same NDJSON stream (§5).`,
--format text: live answer streaming + tool-trace footer
--format json / --format ndjson / pipe (default): NDJSON event stream —
one init line at head (session_id, agent_id),
then raw SDK agent events verbatim. Both
json and ndjson flags produce the same
NDJSON stream (§5).`,
Example: ` weknora session ask --agent ag_x "Summarize Q3 sales"
weknora session ask --session sess_x --agent ag_x "Follow-up question"
weknora session ask --agent ag_x "Multi-step task" --format ndjson`,
@ -112,8 +113,7 @@ func runAsk(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions,
// Streaming commands route --format json AND --format ndjson to the
// NDJSON event-stream path. A buffered envelope makes no sense for a
// streaming command (§5). Only --format human (or TTY default) uses the
// live renderer.
// streaming command (§5). Only --format text uses the live renderer.
ndjsonMode := fopts != nil && (fopts.Mode == cmdutil.FormatJSON || fopts.Mode == cmdutil.FormatNDJSON)
sessionID := opts.SessionID
@ -145,7 +145,7 @@ func runAsk(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOptions,
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
}
return runAskHuman(ctx, opts, sessionID, autoCreated, svc)
return runAskText(ctx, opts, sessionID, autoCreated, svc)
}
// runAskNDJSON handles --format json and --format ndjson paths.
@ -184,9 +184,9 @@ func runAskNDJSON(ctx context.Context, opts *AskOptions, sessionID string, svc A
return nil
}
// runAskHuman handles the TTY / human-text path. Streams answer fragments
// runAskText handles the --format text path. Streams answer fragments
// live on TTY; accumulates then renders on non-TTY pipes.
func runAskHuman(ctx context.Context, opts *AskOptions, sessionID string, autoCreated bool, svc AskService) error {
func runAskText(ctx context.Context, opts *AskOptions, sessionID string, autoCreated bool, svc AskService) error {
// Stream mode requires an interactive stdout.
streamMode := iostreams.IO.IsStdoutTTY()
@ -243,9 +243,9 @@ func runAskHuman(ctx context.Context, opts *AskOptions, sessionID string, autoCr
return nil
}
// renderAskToolTrace prints a compact tool-event footer in human mode.
// Skipped when the agent emitted no tool events — silent beats an empty
// banner.
// renderAskToolTrace prints a compact tool-event footer in --format text
// mode. Skipped when the agent emitted no tool events — silent beats an
// empty banner.
func renderAskToolTrace(w io.Writer, events []sse.AgentToolEvent) {
if len(events) == 0 {
return
@ -262,7 +262,7 @@ func renderAskToolTrace(w io.Writer, events []sse.AgentToolEvent) {
}
// truncateAskInline shrinks a multi-line result to a single line + ellipsis
// for the human tool-trace footer.
// for the text tool-trace footer.
func truncateAskInline(s string, maxLen int) string {
s = strings.ReplaceAll(s, "\n", " ")
if len(s) <= maxLen {

View File

@ -63,10 +63,10 @@ func referencesEvent(refs []*sdk.SearchResult) *sdk.AgentStreamResponse {
}
}
// textOpts returns a FormatOptions configured for the text (human) render
// path — the most common shape under test.
// textOpts returns a FormatOptions configured for the text render path —
// the most common shape under test.
func textOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
}
// ndjsonOpts returns a FormatOptions for the NDJSON event-stream path.
@ -253,7 +253,7 @@ func TestSessionAsk_StreamAbortBeforeDone_MapsToSSEStreamAborted(t *testing.T) {
streamErr: errors.New("connection reset"),
}
opts := &AskOptions{AgentID: "ag", Query: "x"}
// Human path (textOpts) validates Done; NDJSON path does not buffer.
// Text path (textOpts) validates Done; NDJSON path does not buffer.
err := runAsk(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected stream-aborted error")
@ -311,8 +311,8 @@ func TestSessionAsk_Cancellation_MapsToOperationCancelled(t *testing.T) {
}
}
// Sanity: human-mode output writes the answer body and a tool-trace footer.
func TestSessionAsk_Human_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
// Sanity: text-mode output writes the answer body and a tool-trace footer.
func TestSessionAsk_Text_Accumulate_PrintsAnswerAndFooter(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &scriptedAskSvc{events: []*sdk.AgentStreamResponse{
answerEvent("hello"),

View File

@ -32,7 +32,7 @@ func TestDelete_WithYes(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_abc"))
require.NoError(t, runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_abc"))
assert.True(t, svc.called)
assert.Equal(t, "s_abc", svc.gotID)
assert.False(t, p.Asked, "-y must skip prompt")
@ -42,7 +42,7 @@ func TestDelete_WithYes(t *testing.T) {
func TestDelete_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{err: errors.New("HTTP error 404: not found")}
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "s_missing")
err := runDelete(context.Background(), &DeleteOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "s_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -52,7 +52,7 @@ func TestDelete_NotFound(t *testing.T) {
func TestDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, &testutil.ConfirmPrompter{}, "s_x")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{}, "s_x")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -65,7 +65,7 @@ func TestDelete_TTY_ConfirmYes(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: true}
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_yes"))
require.NoError(t, runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_yes"))
assert.True(t, p.Asked)
assert.True(t, svc.called)
}
@ -74,7 +74,7 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: false}
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, p, "s_no")
err := runDelete(context.Background(), &DeleteOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p, "s_no")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -145,7 +145,7 @@ func TestMultiDelete_PartialFailure_KeepsGoing(t *testing.T) {
func TestMultiDelete_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeMultiDeleteSvc{}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
err := cmdutil.ConfirmDestructiveBatch(&testutil.ConfirmPrompter{}, false, fopts.WantsJSON(), "session", 2, "session.delete", "")
require.Error(t, err)
var typed *cmdutil.Error

View File

@ -35,7 +35,7 @@ func (f *fakeListService) GetSessionsByTenant(_ context.Context, page, pageSize
func TestList_Empty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: nil, total: 0}
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "no sessions")
}
@ -48,7 +48,7 @@ func TestList_Table(t *testing.T) {
},
total: 2,
}
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
got := out.String()
assert.Contains(t, got, "s_1")
assert.Contains(t, got, "Design review")
@ -106,7 +106,7 @@ func TestList_BadPagination(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := runList(context.Background(), &ListOptions{PageSize: tc.size, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &fakeListService{})
err := runList(context.Background(), &ListOptions{PageSize: tc.size, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListService{})
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -118,7 +118,7 @@ func TestList_BadPagination(t *testing.T) {
func TestList_NetworkError_TypedCode(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeListService{err: errors.New("HTTP error 401: unauthenticated")}
err := runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc)
err := runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -129,7 +129,7 @@ func TestList_NetworkError_TypedCode(t *testing.T) {
func TestList_NonASCIITitle(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeListService{items: []sdk.Session{{ID: "s_zh", Title: strings.Repeat("中文", 50)}}, total: 1}
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc))
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc))
assert.Contains(t, out.String(), "s_zh")
}
@ -142,7 +142,7 @@ func TestList_SinceFilter_DropsOldSessions(t *testing.T) {
{ID: "yesterday", Title: "yday", UpdatedAt: now.Add(-23 * time.Hour).Format(time.RFC3339)},
}
require.NoError(t, runList(context.Background(),
&ListOptions{PageSize: 30, Since: "7d", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
&ListOptions{PageSize: 30, Since: "7d", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
&fakeListService{items: items, total: 3}))
got := out.String()
assert.Contains(t, got, "recent")
@ -156,7 +156,7 @@ func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
t.Run(v, func(t *testing.T) {
_, _ = iostreams.SetForTest(t)
require.NoError(t, runList(context.Background(),
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
&fakeListService{items: []sdk.Session{}, total: 0}),
"--since=%q should parse", v)
})
@ -166,7 +166,7 @@ func TestList_SinceFilter_ParseDuration_Variants(t *testing.T) {
func TestList_SinceFilter_RejectsInvalidDuration(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(),
&ListOptions{PageSize: 30, Since: "bogus", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
&ListOptions{PageSize: 30, Since: "bogus", Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
&fakeListService{items: []sdk.Session{}, total: 0})
require.Error(t, err)
var typed *cmdutil.Error
@ -178,7 +178,7 @@ func TestList_SinceFilter_RejectsNonPositive(t *testing.T) {
_, _ = iostreams.SetForTest(t)
for _, v := range []string{"0d", "0h", "-1h"} {
err := runList(context.Background(),
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
&ListOptions{PageSize: 30, Since: v, Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
&fakeListService{items: []sdk.Session{}, total: 0})
require.Error(t, err, "--since=%q should reject", v)
var typed *cmdutil.Error
@ -244,7 +244,7 @@ func TestList_Limit_GreaterThanPageSize_NoCap(t *testing.T) {
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(),
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman},
&ListOptions{PageSize: 30, Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText},
&fakeListService{})
require.Error(t, err)
var typed *cmdutil.Error

View File

@ -42,7 +42,7 @@ func (f *fakeViewService) LoadMessages(_ context.Context, sessionID string, limi
return f.msgs, f.msgsErr
}
func TestView_Human(t *testing.T) {
func TestView_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewService{s: &sdk.Session{
ID: "s_abc",
@ -51,7 +51,7 @@ func TestView_Human(t *testing.T) {
CreatedAt: "2026-05-10T09:00:00Z",
UpdatedAt: "2026-05-12T14:00:00Z",
}}
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_abc"))
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_abc"))
got := out.String()
for _, want := range []string{"s_abc", "Design review", "RAG chunking strategy review", "2026-05-12"} {
assert.Contains(t, got, want)
@ -77,7 +77,7 @@ func TestView_JSON(t *testing.T) {
func TestView_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewService{err: errors.New("HTTP error 404: not found")}
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_missing")
err := runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_missing")
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@ -87,7 +87,7 @@ func TestView_NotFound(t *testing.T) {
func TestView_OmitsEmptyDescription(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewService{s: &sdk.Session{ID: "s_min", Title: "Bare"}}
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_min"))
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_min"))
// Empty Description should not produce an empty `DESC:` line.
for line := range strings.SplitSeq(out.String(), "\n") {
if strings.HasPrefix(line, "DESC:") {
@ -107,7 +107,7 @@ func TestView_Full_LoadsMessages(t *testing.T) {
{ID: "m2", Role: "assistant", Content: "RAG stands for retrieval-augmented generation.", CreatedAt: time.Date(2026, 5, 15, 14, 32, 5, 0, time.UTC)},
},
}
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_abc"))
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_abc"))
got := out.String()
assert.True(t, svc.loadCall.called, "expected LoadMessages to be called")
assert.Equal(t, "s_abc", svc.loadCall.sessionID)
@ -123,7 +123,7 @@ func TestView_Full_NoMessages(t *testing.T) {
s: &sdk.Session{ID: "s_empty", Title: "Empty"},
msgs: []sdk.Message{},
}
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s_empty"))
require.NoError(t, runView(context.Background(), &ViewOptions{Full: true, Limit: 50}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s_empty"))
got := out.String()
assert.Contains(t, got, "Messages (0)")
}
@ -131,7 +131,7 @@ func TestView_Full_NoMessages(t *testing.T) {
func TestView_Full_LimitInvalid_Zero(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
@ -139,7 +139,7 @@ func TestView_Full_LimitInvalid_Zero(t *testing.T) {
func TestView_Full_LimitInvalid_TooLarge(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 1001}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
err := runView(context.Background(), &ViewOptions{Full: true, Limit: 1001}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
@ -149,7 +149,7 @@ func TestView_Full_LimitInvalid_TooLarge(t *testing.T) {
func TestView_LimitWithoutFull(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewService{s: &sdk.Session{ID: "s"}}
err := runView(context.Background(), &ViewOptions{Full: false, Limit: 100, LimitSet: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, svc, "s")
err := runView(context.Background(), &ViewOptions{Full: false, Limit: 100, LimitSet: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "s")
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
assert.Contains(t, err.Error(), "--limit")

View File

@ -1,13 +1,14 @@
// Package-level note:
//
// SetAgentHelp wires structured agent-targeted help onto a cobra command.
// Current coverage: chat, kb list. Adding it to another command requires
// touching only that command's NewCmd (a 5-line copy of the existing call
// sites).
// Current coverage: chat, kb list, and destructive commands. Adding it to
// another command requires touching only that command's NewCmd (a 5-line
// copy of the existing call sites).
package cmdutil
import (
"encoding/json"
"fmt"
"io"
"os"
@ -18,20 +19,25 @@ import (
// `weknora <command> --help` with WEKNORA_AGENT_HELP=1. Distinct from
// cobra's human help text — agent-readable JSON keyed by stable fields
// so an LLM doesn't need to scrape the human help table.
//
// Warnings surface both as a JSON field (agent introspection) and as an
// "AI agents:" block appended to human help. The two channels share a
// single source list so they cannot drift.
type AgentHelp struct {
UsedFor string `json:"used_for"`
RequiredFlags []string `json:"required_flags,omitempty"`
Examples []string `json:"examples,omitempty"`
Output string `json:"output,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
// SetAgentHelp attaches agent-targeted help metadata to a command. The
// original HelpFunc is preserved for the human path; the agent path
// activates only when WEKNORA_AGENT_HELP=1 (so human `--help` is
// unaffected).
// SetAgentHelp attaches agent-targeted help metadata to a command.
//
// Currently applied to a small set of representative commands (chat,
// kb list); extend by calling SetAgentHelp in each command's NewCmd.
// Routing:
// - WEKNORA_AGENT_HELP=1: emit the AgentHelp JSON blob to stdout and
// return — agents get clean parseable JSON, no trailing prose.
// - Otherwise: render the normal human help, then append an
// "AI agents:" block when Warnings is non-empty.
func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
origHelp := cmd.HelpFunc()
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
@ -40,6 +46,14 @@ func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
return
}
origHelp(c, args)
if len(ah.Warnings) > 0 {
w := c.OutOrStdout()
fmt.Fprintln(w)
fmt.Fprintln(w, "AI agents:")
for _, msg := range ah.Warnings {
fmt.Fprintln(w, "- "+msg)
}
}
})
}

View File

@ -55,3 +55,46 @@ func TestSetAgentHelp_FallsThroughToHumanHelp(t *testing.T) {
t.Errorf("human help missing from output:\n%s", buf.String())
}
}
func TestSetAgentHelp_AgentJSON_NoTrailingWarningsProse(t *testing.T) {
cmd := &cobra.Command{Use: "kb-delete-test"}
SetAgentHelp(cmd, AgentHelp{
UsedFor: "Delete a knowledge base",
Warnings: []string{"irreversible"},
})
t.Setenv("WEKNORA_AGENT_HELP", "1")
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.HelpFunc()(cmd, nil)
// Should be parseable as a single JSON object with the warnings field.
var got AgentHelp
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("agent-help output is not valid JSON: %v\n%s", err, buf.String())
}
if len(got.Warnings) != 1 || got.Warnings[0] != "irreversible" {
t.Errorf("warnings field missing or wrong: %v", got.Warnings)
}
// Should NOT contain the human-prose "AI agents:" block
if bytes.Contains(buf.Bytes(), []byte("AI agents:")) {
t.Errorf("agent JSON path leaked human prose:\n%s", buf.String())
}
}
func TestSetAgentHelp_HumanHelp_AppendsWarningsBlock(t *testing.T) {
cmd := &cobra.Command{Use: "kb-delete-test", Short: "short"}
SetAgentHelp(cmd, AgentHelp{
UsedFor: "Delete a KB",
Warnings: []string{"irreversible"},
})
// Env unset → human help path
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.HelpFunc()(cmd, nil)
if !bytes.Contains(buf.Bytes(), []byte("AI agents:")) {
t.Errorf("human help should include AI agents: block; got:\n%s", buf.String())
}
if !bytes.Contains(buf.Bytes(), []byte("- irreversible")) {
t.Errorf("human help should list warning; got:\n%s", buf.String())
}
}

View File

@ -65,7 +65,7 @@ func RunBatch(ctx context.Context, ids []string, op func(context.Context, string
}
// EmitBatch writes the per-item outcomes per --format. JSON/NDJSON emit
// the §4.5 batch envelope; human/text mode emits per-line "OK <id>" /
// the §4.5 batch envelope; text mode emits per-line "OK <id>" /
// "FAIL <id>: <msg>".
//
// resultFn builds the per-item Result map for successes; nil ⇒ omit.

View File

@ -175,7 +175,7 @@ func TestEmitBatch_Text_PerLine(t *testing.T) {
{ID: "x", Err: nil},
{ID: "y", Err: fmt.Errorf("boom")},
}
fopts := &FormatOptions{Mode: FormatHuman}
fopts := &FormatOptions{Mode: FormatText}
var buf bytes.Buffer
err := EmitBatch(outcomes, fopts, &buf, nil)

View File

@ -92,8 +92,8 @@ func ExitCode(err error) int {
}
// PrintError writes err to w (typically stderr) in dual mode:
// - text/human: code: msg\nhint: ...\nretry: ...
// - json/ndjson: {ok:false, error:{...}, _notice?:...}
// - text: code: msg\nhint: ...\nretry: ...
// - json/ndjson: {ok:false, error:{...}, _notice?:...}
//
// Mode is read from globalFormatMode (set by root PersistentPreRunE).
func PrintError(w io.Writer, err error) {

View File

@ -101,7 +101,7 @@ func TestPrintError_JSONMode_IncludesRetryAfter(t *testing.T) {
func TestPrintError_TextMode_WritesProse(t *testing.T) {
t.Cleanup(func() { SetFormatMode("") })
SetFormatMode("human")
SetFormatMode("text")
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
WithHint("re-run with -y/--yes").

View File

@ -47,10 +47,10 @@ type Factory struct {
Prompter func() prompt.Prompter
Secrets func() (secrets.Store, error)
// ContextOverride, if non-empty, replaces config.CurrentContext for this
// invocation only - set by the global --context flag in PersistentPreRun.
// ProfileOverride, if non-empty, replaces config.CurrentContext for this
// invocation only - set by the global --profile flag in PersistentPreRun.
// Buildable Config() / Client() honor it without writing to disk.
ContextOverride string
ProfileOverride string
}
// New constructs a production Factory wired to real config / SDK client.
@ -84,8 +84,8 @@ func New() *Factory {
}
return nil, Wrapf(CodeLocalFileIO, err, "load config")
}
if f.ContextOverride != "" {
cfg.CurrentContext = f.ContextOverride
if f.ProfileOverride != "" {
cfg.CurrentContext = f.ProfileOverride
}
return cfg, nil
}
@ -117,16 +117,27 @@ func buildClient(f *Factory) (*sdk.Client, error) {
if err != nil {
return nil, err
}
ctxName := cfg.CurrentContext
if ctxName == "" {
return nil, NewError(CodeAuthUnauthenticated, "no current context configured; run `weknora auth login` to set one up")
profileName := cfg.CurrentContext
if profileName == "" {
return nil, NewError(CodeAuthUnauthenticated, "no current profile configured; run `weknora auth login` to set one up")
}
ctx, ok := cfg.Contexts[ctxName]
ctx, ok := cfg.Contexts[profileName]
if !ok {
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("config references unknown context %q", ctxName))
// If the user explicitly overrode the profile (via --profile flag or
// WEKNORA_PROFILE env), it's a bad argument - not a corrupt config file.
// The destructive "remove config.yaml" hint would be catastrophic for a typo.
if f.ProfileOverride != "" {
return nil, NewError(CodeInputInvalidArgument,
fmt.Sprintf("profile %q not configured", profileName)).
WithHint("list available profiles with `weknora profile list`").
WithRetryCommand("weknora profile list")
}
// ProfileOverride is empty: config.CurrentContext points at a missing entry.
// That's a genuinely corrupt config file.
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("config references unknown profile %q", profileName))
}
if ctx.Host == "" {
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("context %q has no host", ctxName))
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("profile %q has no host", profileName))
}
opts := []sdk.ClientOption{}
@ -139,7 +150,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
// authenticated invocation.
var accessToken string
if ctx.TokenRef != "" {
if access, err := LoadSecret(store, ctxName, "access"); err != nil {
if access, err := LoadSecret(store, profileName, "access"); err != nil {
return nil, err
} else if access != "" {
accessToken = access
@ -147,7 +158,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
}
}
if ctx.APIKeyRef != "" {
if apiKey, err := LoadSecret(store, ctxName, "api_key"); err != nil {
if apiKey, err := LoadSecret(store, profileName, "api_key"); err != nil {
return nil, err
} else if apiKey != "" {
opts = append(opts, sdk.WithAPIKey(apiKey))
@ -161,7 +172,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
// them propagates as auth.unauthenticated for the caller to handle.
if ctx.TokenRef != "" && ctx.RefreshRef != "" {
refreshFn := func(rctx context.Context) (string, error) {
return refreshAccessToken(rctx, store, ctx.Host, ctxName)
return refreshAccessToken(rctx, store, ctx.Host, profileName)
}
opts = append(opts, sdk.WithTransport(
NewAuthRetryTransport(http.DefaultTransport, accessToken, refreshFn),
@ -255,6 +266,28 @@ func LoadSecret(store secrets.Store, context, key string) (string, error) {
// being constructed - that one is itself wrapped by the transport, which
// would recurse on refresh. The refresh endpoint is unauthenticated apart
// 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) {
return RefreshAndPersist(ctx, store, sdk.NewClient(host), ctxName)
func refreshAccessToken(ctx context.Context, store secrets.Store, host, profileName string) (string, error) {
return RefreshAndPersist(ctx, store, sdk.NewClient(host), profileName)
}
// ActiveProfile returns the resolved profile name for this invocation:
// 1. ProfileOverride (set by --profile flag in root PersistentPreRunE)
// 2. WEKNORA_PROFILE env var
// 3. Config's CurrentContext (the active context / profile name)
// 4. Empty string when nothing is configured (envelope omits the field).
func (f *Factory) ActiveProfile() string {
if f.ProfileOverride != "" {
return f.ProfileOverride
}
if v := os.Getenv("WEKNORA_PROFILE"); v != "" {
return v
}
if f.Config == nil {
return ""
}
cfg, err := f.Config()
if err != nil || cfg == nil {
return ""
}
return cfg.CurrentContext
}

View File

@ -72,10 +72,10 @@ func TestNew_FoundationDefaults(t *testing.T) {
assert.Equal(t, CodeAuthUnauthenticated, typed.Code)
}
// TestFactory_ContextOverride verifies the global --context flag mechanism:
// f.ContextOverride replaces config.CurrentContext for this invocation only,
// TestFactory_ProfileOverride verifies the global --profile flag mechanism:
// f.ProfileOverride replaces config.CurrentContext for this invocation only,
// without writing to disk.
func TestFactory_ContextOverride(t *testing.T) {
func TestFactory_ProfileOverride(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
@ -94,14 +94,14 @@ contexts:
f := New()
t.Run("no override: returns CurrentContext from disk", func(t *testing.T) {
f.ContextOverride = ""
f.ProfileOverride = ""
cfg, err := f.Config()
require.NoError(t, err)
assert.Equal(t, "default", cfg.CurrentContext)
})
t.Run("override applied: ContextOverride wins over disk", func(t *testing.T) {
f.ContextOverride = "other"
t.Run("override applied: ProfileOverride wins over disk", func(t *testing.T) {
f.ProfileOverride = "other"
cfg, err := f.Config()
require.NoError(t, err)
assert.Equal(t, "other", cfg.CurrentContext)
@ -302,6 +302,26 @@ func fakeKBServer(t *testing.T, kbs []sdk.KnowledgeBase) *httptest.Server {
return srv
}
// TestFactory_ActiveProfile_EnvVarFallback verifies WEKNORA_PROFILE is honoured
// when no override or config is present.
func TestFactory_ActiveProfile_EnvVarFallback(t *testing.T) {
t.Setenv("WEKNORA_PROFILE", "staging")
f := &Factory{} // no override, no config
if got := f.ActiveProfile(); got != "staging" {
t.Errorf("expected env fallback to staging; got %q", got)
}
}
// TestFactory_ActiveProfile_OverrideWinsEnv verifies ProfileOverride takes
// priority over the WEKNORA_PROFILE env var.
func TestFactory_ActiveProfile_OverrideWinsEnv(t *testing.T) {
t.Setenv("WEKNORA_PROFILE", "staging")
f := &Factory{ProfileOverride: "prod"}
if got := f.ActiveProfile(); got != "prod" {
t.Errorf("override should win over env; got %q", got)
}
}
// TestResolveKB_Chain exercises the 4-level fallback chain. Each sub-test
// isolates cwd / env / closure from the others.
func TestResolveKB_Chain(t *testing.T) {

View File

@ -18,13 +18,13 @@ import (
type FormatMode string
const (
FormatHuman FormatMode = "human"
FormatText FormatMode = "text"
FormatJSON FormatMode = "json"
FormatNDJSON FormatMode = "ndjson"
)
// FormatOptions captures the resolved --format + --jq state for a command.
// Mode is one of FormatHuman / FormatJSON / FormatNDJSON, or "" before
// Mode is one of FormatText / FormatJSON / FormatNDJSON, or "" before
// ResolveDefault has been called.
type FormatOptions struct {
Mode FormatMode
@ -54,7 +54,7 @@ func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
// CheckFormatFlag resolves --format + --jq from cmd. Returns:
// - (*FormatOptions{Mode:""}, nil) flag not set; caller should call ResolveDefault
// - (*FormatOptions{Mode:v,JQ:q}, nil) valid values
// - (nil, *FlagError) invalid --format, or --jq with explicit --format human
// - (nil, *FlagError) invalid --format, or --jq with explicit --format text
//
// --jq with --format unset is accepted: ResolveDefault below will promote
// the mode to FormatJSON so the filter has somewhere to apply.
@ -65,26 +65,26 @@ func CheckFormatFlag(cmd *cobra.Command) (*FormatOptions, error) {
switch v {
case "":
// unset; caller calls ResolveDefault
case "human", "json", "ndjson":
case "text", "json", "ndjson":
fopts.Mode = FormatMode(v)
default:
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be human | json | ndjson", v))
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be text | json | ndjson", v))
}
}
if f := cmd.Flags().Lookup("jq"); f != nil {
fopts.JQ = f.Value.String()
}
// --jq only meaningful for JSON-shaped output. Reject the explicit
// `--format human --jq ...` combination; the `--jq` with --format unset
// `--format text --jq ...` combination; the `--jq` with --format unset
// case is handled by ResolveDefault.
if fopts.JQ != "" && fopts.Mode == FormatHuman {
if fopts.JQ != "" && fopts.Mode == FormatText {
return nil, NewFlagError(errors.New("--jq requires --format json|ndjson"))
}
return fopts, nil
}
// WantsJSON reports whether the resolved mode is JSON or NDJSON. Used by
// callers to choose between the JSON emit path and human text rendering.
// callers to choose between the JSON emit path and text rendering.
func (o *FormatOptions) WantsJSON() bool {
return o.Mode == FormatJSON || o.Mode == FormatNDJSON
}
@ -101,7 +101,7 @@ func (o *FormatOptions) WantsJSON() bool {
// FormatNDJSON path: emits one bare JSON object per line (no envelope).
// Matches spec §5 NDJSON event-passthrough semantics.
//
// FormatHuman path returns an error so a missed dispatch surfaces loudly.
// FormatText path returns an error so a missed dispatch surfaces loudly.
func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
switch o.Mode {
case FormatJSON:
@ -121,8 +121,8 @@ func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
return format.WriteJSONFiltered(w, data, nil, o.JQ)
}
return format.WriteNDJSON(w, data)
case FormatHuman:
return fmt.Errorf("FormatOptions.Emit: cannot emit human mode as JSON; caller must render human-readable separately")
case FormatText:
return fmt.Errorf("FormatOptions.Emit: cannot emit text mode as JSON; caller must render human-readable separately")
default:
return fmt.Errorf("FormatOptions.Emit: unknown mode %q", o.Mode)
}
@ -131,7 +131,7 @@ func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
// ResolveDefault fills in Mode when the caller has not explicitly set it:
// - Mode defaults to FormatJSON
// - TTY only affects the indent decision (auto-indent in TTY; compact in pipe)
// - For human-readable rendering, pass --format human explicitly
// - For human-readable rendering, pass --format text explicitly
func (o *FormatOptions) ResolveDefault(tty bool) {
o.TTY = tty
if o.Mode == "" {
@ -150,7 +150,7 @@ func (o *FormatOptions) FromEnv() {
}
v := os.Getenv("WEKNORA_FORMAT")
switch v {
case "human", "json", "ndjson":
case "text", "json", "ndjson":
o.Mode = FormatMode(v)
}
}

View File

@ -14,17 +14,16 @@ func TestCheckFormatFlags(t *testing.T) {
cases := []struct {
name string
args []string
wantMode FormatMode // FormatHuman | FormatJSON | FormatNDJSON | "" (unset)
wantMode FormatMode // FormatText | FormatJSON | FormatNDJSON | "" (unset)
wantErr bool
}{
// Unset → Mode is "" (caller resolves default via ResolveDefault).
{"default", []string{}, "", false},
{"explicit human", []string{"--format", "human"}, FormatHuman, false},
{"explicit text", []string{"--format", "text"}, FormatText, false},
{"json", []string{"--format", "json"}, FormatJSON, false},
{"ndjson", []string{"--format", "ndjson"}, FormatNDJSON, false},
{"invalid value", []string{"--format", "yaml"}, "", true},
// v0.7 BREAKING: "text" is no longer a valid --format value.
{"text rejected", []string{"--format", "text"}, "", true},
{"human rejected", []string{"--format", "human"}, "", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@ -87,11 +86,11 @@ func TestFormatOptions_JSONEmitsArray(t *testing.T) {
}
}
func TestFormatOptions_HumanModeReturnsError(t *testing.T) {
fopts := &FormatOptions{Mode: FormatHuman}
func TestFormatOptions_TextModeReturnsError(t *testing.T) {
fopts := &FormatOptions{Mode: FormatText}
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"}, nil)
if err == nil {
t.Error("expected error for human mode, got nil")
t.Error("expected error for text mode, got nil")
}
}
@ -124,7 +123,7 @@ func TestResolveDefault(t *testing.T) {
{"already set keeps value tty", FormatNDJSON, "", true, FormatNDJSON},
{"already set keeps value no-tty", FormatJSON, "", false, FormatJSON},
// --jq with unset --format promotes to JSON regardless of TTY so the
// filter has somewhere to apply (silent human drop would surprise users).
// filter has somewhere to apply (silent text drop would surprise users).
{"jq forces json on TTY", "", ".[]", true, FormatJSON},
{"jq with explicit ndjson preserved", FormatNDJSON, ".[]", true, FormatNDJSON},
}
@ -147,9 +146,8 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
args []string
}{
{"invalid format value", []string{"--format", "yaml"}},
// v0.7: "text" is rejected; "human" is the valid human-readable value.
{"text rejected as invalid", []string{"--format", "text"}},
{"jq with explicit human mode", []string{"--format", "human", "--jq", ".id"}},
{"human rejected as invalid", []string{"--format", "human"}},
{"jq with explicit text mode", []string{"--format", "text", "--jq", ".id"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@ -182,7 +180,7 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
}
func TestCheckFormatFlag_InvalidValueRejected(t *testing.T) {
for _, v := range []string{"text", "yaml", "xml", "table"} {
for _, v := range []string{"human", "yaml", "xml", "table"} {
v := v
t.Run(v, func(t *testing.T) {
cmd := &cobra.Command{}
@ -192,23 +190,23 @@ func TestCheckFormatFlag_InvalidValueRejected(t *testing.T) {
if err == nil {
t.Fatalf("expected error for --format %q", v)
}
if !strings.Contains(err.Error(), "human | json | ndjson") {
if !strings.Contains(err.Error(), "text | json | ndjson") {
t.Errorf("expected enum hint for --format %q; got %v", v, err)
}
})
}
}
func TestCheckFormatFlag_HumanAccepted(t *testing.T) {
func TestCheckFormatFlag_TextAccepted(t *testing.T) {
cmd := &cobra.Command{}
cmd.Flags().String("format", "", "")
_ = cmd.Flags().Set("format", "human")
_ = cmd.Flags().Set("format", "text")
o, err := CheckFormatFlag(cmd)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if o.Mode != FormatHuman {
t.Errorf("got %v, want FormatHuman", o.Mode)
if o.Mode != FormatText {
t.Errorf("got %v, want FormatText", o.Mode)
}
}

View File

@ -0,0 +1,43 @@
package output
import (
"encoding/json"
"io"
)
// InitEvent is the CLI-injected lifecycle event written at the head of a
// streaming command's NDJSON output (§5.3). Carries enough context for an
// agent to thread follow-ups (session id, kb id, model, profile).
//
// Type field is always "init"; the JSON tag fixes the wire shape.
type InitEvent struct {
Type string `json:"type"`
SessionID string `json:"session_id"`
AgentID string `json:"agent_id,omitempty"`
KBID string `json:"kb_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
Model string `json:"model,omitempty"`
Profile string `json:"profile,omitempty"`
}
// WriteNDJSONLine emits one NDJSON event line to w.
func WriteNDJSONLine(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
return enc.Encode(v)
}
// EmitInit writes the lifecycle init event to start an NDJSON stream.
// MUST be called before any other writes to w within an NDJSON stream —
// agents key on lines[0].type == "init" to discover session/profile/kb
// context. Sets Type=init regardless of caller-supplied value.
func EmitInit(w io.Writer, ev InitEvent) error {
ev.Type = "init"
return WriteNDJSONLine(w, ev)
}
// EmitSDKEvent passes through the raw SDK event as one NDJSON line.
// SDK is source of truth for event vocab (§5.1).
func EmitSDKEvent(w io.Writer, ev any) error {
return WriteNDJSONLine(w, ev)
}

View File

@ -0,0 +1,74 @@
package output_test
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/output"
)
func TestEmitInit_ForcesTypeField(t *testing.T) {
var buf bytes.Buffer
// Pass an InitEvent with Type deliberately set to something wrong; EmitInit
// must overwrite it with "init".
ev := output.InitEvent{Type: "wrong", SessionID: "sess_x"}
if err := output.EmitInit(&buf, ev); err != nil {
t.Fatalf("EmitInit: %v", err)
}
var got struct {
Type string `json:"type"`
SessionID string `json:"session_id"`
}
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, buf.String())
}
if got.Type != "init" {
t.Errorf("type: got %q, want init", got.Type)
}
if got.SessionID != "sess_x" {
t.Errorf("session_id: got %q, want sess_x", got.SessionID)
}
}
func TestEmitInit_OmitsEmptyOptionalFields(t *testing.T) {
var buf bytes.Buffer
// Only SessionID set; all optional fields should be absent from JSON.
ev := output.InitEvent{SessionID: "sess_only"}
if err := output.EmitInit(&buf, ev); err != nil {
t.Fatalf("EmitInit: %v", err)
}
line := buf.String()
for _, field := range []string{"kb_id", "agent_id", "model", "profile", "request_id"} {
if strings.Contains(line, `"`+field+`"`) {
t.Errorf("optional field %q should be omitted when empty, got: %s", field, line)
}
}
}
func TestEmitSDKEvent_PassthroughVerbatim(t *testing.T) {
var buf bytes.Buffer
payload := map[string]any{"type": "answer", "content": "hi"}
if err := output.EmitSDKEvent(&buf, payload); err != nil {
t.Fatalf("EmitSDKEvent: %v", err)
}
var got map[string]any
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, buf.String())
}
if got["type"] != "answer" {
t.Errorf("type: got %v, want answer", got["type"])
}
if got["content"] != "hi" {
t.Errorf("content: got %v, want hi", got["content"])
}
// Must be a single NDJSON line terminated by newline.
raw := buf.String()
if !strings.HasSuffix(raw, "\n") {
t.Errorf("NDJSON line must end with newline, got %q", raw)
}
if strings.Count(raw, "\n") != 1 {
t.Errorf("expected exactly one newline, got %d in %q", strings.Count(raw, "\n"), raw)
}
}

View File

@ -1,5 +1,5 @@
// Package projectlink reads and writes the per-project link file
// .weknora/project.yaml that anchors a working directory to a context+KB.
// .weknora/project.yaml that anchors a working directory to a profile+KB.
//
// Discovery walks up from the start directory until either (a) a
// .weknora/project.yaml is found, (b) the filesystem root is reached, or
@ -22,7 +22,7 @@ import (
// Project is the on-disk schema of .weknora/project.yaml.
type Project struct {
Context string `yaml:"context,omitempty"`
Profile string `yaml:"profile,omitempty"`
KBID string `yaml:"kb_id"`
CreatedAt time.Time `yaml:"created_at"`
}

View File

@ -58,7 +58,7 @@ func TestDiscover_NotFound(t *testing.T) {
func TestLoad_RoundTrip(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, ".weknora", "project.yaml")
in := &projectlink.Project{Context: "prod", KBID: "kb_abc", CreatedAt: time.Now().UTC().Round(time.Second)}
in := &projectlink.Project{Profile: "prod", KBID: "kb_abc", CreatedAt: time.Now().UTC().Round(time.Second)}
if err := projectlink.Save(path, in); err != nil {
t.Fatalf("Save: %v", err)
}
@ -66,7 +66,7 @@ func TestLoad_RoundTrip(t *testing.T) {
if err != nil {
t.Fatalf("Load: %v", err)
}
if out.Context != in.Context || out.KBID != in.KBID {
if out.Profile != in.Profile || out.KBID != in.KBID {
t.Errorf("round trip: got %+v want %+v", out, in)
}
}