refactor: 项目更名 WeKnora → Academy
Build & Publish (dsh-academy) / End-to-end inside dsh (latest, advisory) (push) Skipped
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Frontend / Docker multi-stage image (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-academy) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-academy) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-academy) / Publish to npm (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Helm / chart (push) Canceled after 0s

- 全量替换代码/配置/文档中的项目名(保留上游 GitHub 链接、weixin 文档域名、Docker Hub 镜像名)
- 重命名 32 个含项目名的文件/目录;Go module 路径改为 academy(含 client/cli 子模块)
- docreader proto 描述符采用等长替换,保持序列化字节布局有效
- Dockerfile.app 构建网络修复: browserskill 离线产物通道、PyPI/apt 国内镜像
- 运行验证: go build ✓ docker compose up ✓ 健康检查 ✓
This commit is contained in:
runny committed 2026-11-13 20:52:51 +08:00
1 parent 9097ee699d
commit 9058149576
3136 files changed
+18018 -18004

No files matched your search

+56 -56
View File
@@ -1,8 +1,8 @@
# AGENTS.md
This is the WeKnora CLI (`weknora`), a command-line client for the WeKnora RAG server. The module path is `github.com/Tencent/WeKnora/cli`.
This is the Academy CLI (`academy`), a command-line client for the Academy 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) 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.
The wire contract for AI agents *consuming* `academy` 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
@@ -55,8 +55,8 @@ Errors emit an error envelope on stderr (`--format json`) or prose
"error": {
"type": "auth.unauthenticated",
"message": "fetch current user: HTTP error 401",
"hint": "run `weknora auth login`",
"retry_argv": ["weknora", "auth", "login"],
"hint": "run `academy auth login`",
"retry_argv": ["academy", "auth", "login"],
"retry_after_seconds": 0,
"risk": {"level": "destructive", "action": "noun.verb"},
"detail": {}
@@ -125,21 +125,21 @@ Make errors structured, actionable, and specific.
| 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. |
| `ACADEMY_PROFILE` | Active profile name. Equivalent to the global `--profile <name>` flag; overridden by `--profile`. Useful in CI scripts that cannot pass global flags. |
| `ACADEMY_FORMAT` | Default `--format` value (`text \| json \| ndjson`). Overridden by explicit `--format`. Invalid values ignored silently. |
| `ACADEMY_KB_ID` | Default KB ID for commands that accept `--kb`. Overridden by `--kb`. |
| `ACADEMY_LOG_LEVEL` | SDK debug log level (`error \| warn \| info \| debug`). Overridden by `--log-level`. |
| `ACADEMY_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.
> subcommand (`academy version --format json`) or `ACADEMY_AGENT_HELP=1
> academy <cmd> --help`. Planned fix for v0.8.
## Design decisions worth flagging
Five design decisions readers may want context on: where WeKnora picks an
Five design decisions readers may want context on: where Academy picks an
opinionated default, what the trade-off is, and what mainstream practice it
is or isn't aligned with.
@@ -147,28 +147,28 @@ is or isn't aligned with.
| | |
|---|---|
| **WeKnora** | success envelope → stdout; error envelope → stderr |
| **Rationale** | `weknora ... --format json \| jq '.data[]'` must not mix error objects into the data stream. Channel split lets pipeline consumers suppress errors with `2>/dev/null` and still get clean JSON on stdout. |
| **Academy** | success envelope → stdout; error envelope → stderr |
| **Rationale** | `academy ... --format json \| jq '.data[]'` must not mix error objects into the data stream. Channel split lets pipeline consumers suppress errors with `2>/dev/null` and still get clean JSON on stdout. |
### 2. `weknora api DELETE` triggers exit-10 confirmation
### 2. `academy api DELETE` triggers exit-10 confirmation
| | |
|---|---|
| **WeKnora** | DELETE triggers exit-10 (`input.confirmation_required`); user bypasses with `-y/--yes` |
| **Academy** | DELETE triggers exit-10 (`input.confirmation_required`); user bypasses with `-y/--yes` |
| **Rationale** | DELETE is irreversible. Most raw-API CLI commands rely on restricted credentials for safety, but self-hosted deployments may not have restricted-credential infrastructure available. Defensive default because agents are common consumers. |
### 3. `retry_argv` distinct from `hint`
| | |
|---|---|
| **WeKnora** | two separate fields: `retry_argv` (suggested next argv as a string array, directly executable for non-destructive errors; informational only on exit-10) + `hint` (prose) |
| **Academy** | two separate fields: `retry_argv` (suggested next argv as a string array, 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_argv` for human review, not auto-execution. |
### 4. NDJSON event stream has no envelope wrapping
| | |
|---|---|
| **WeKnora** | streaming commands (`chat`, `session ask`) emit bare `{type:...}` per line; no envelope |
| **Academy** | streaming commands (`chat`, `session ask`) emit bare `{type:...}` per line; no envelope |
| **Rationale** | This matches established practice across NDJSON-emitting CLIs and webhook protocols. A streaming envelope requires unwrap before dispatch — net burden with no benefit. |
### 5. No `schema_version` field in payload
@@ -176,8 +176,8 @@ is or isn't aligned with.
| | |
|---|---|
| **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. |
| **Academy** | 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 `academy --version` and skill version binding. |
## Pre-1.0 breaking policy
@@ -193,7 +193,7 @@ For agents: pin the CLI version in your skill's `tested_against` field; bump
## Build, Test, and Lint
```bash
go build -o weknora . # build (from cli/)
go build -o academy . # build (from cli/)
go test -count=1 ./... # unit + contract tests
go test -run TestFoo ./internal/format/ # single test
go test ./acceptance/contract/ -args -update # refresh wire goldens
@@ -221,7 +221,7 @@ Key packages:
## Command Structure
A command `weknora foo bar` lives in `cmd/foo/bar.go` with `bar_test.go`.
A command `academy foo bar` lives in `cmd/foo/bar.go` with `bar_test.go`.
### Canonical Examples
@@ -248,12 +248,12 @@ Key rules:
### Command Examples and Help Text
Use a Go raw string with `weknora` as the example prefix. Keep one-line `Short` ≤ 70 chars; `Long` may run multi-paragraph; `Example` always includes `weknora` so copy-paste works:
Use a Go raw string with `academy` as the example prefix. Keep one-line `Short` ≤ 70 chars; `Long` may run multi-paragraph; `Example` always includes `academy` so copy-paste works:
```go
Example: ` weknora kb view <id>
weknora kb view kb_abc --format json
weknora kb view kb_abc --format json --jq '{id, name}'`,
Example: ` academy kb view <id>
academy kb view kb_abc --format json
academy kb view kb_abc --format json --jq '{id, name}'`,
```
### JSON Output
@@ -359,10 +359,10 @@ User-facing exit-code mapping lives in [README.md "Exit codes"](README.md#exit-c
## Error code reference
> **Audience:** AI agents and scripted callers parsing `weknora` stderr.
> **Audience:** AI agents and scripted callers parsing `academy` stderr.
> Code authors writing new error sites — see [`## Error Handling`](#error-handling) above.
When `weknora` exits non-zero, stderr carries a structured triplet:
When `academy` exits non-zero, stderr carries a structured triplet:
```
<code>: <message>
@@ -378,35 +378,35 @@ Agents parse the first colon to extract the typed code. The exit code class (see
| Code | Exit | Retryable | Default hint |
|---|---|---|---|
| `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.unauthenticated` | 3 | no (run `auth login`) | run `academy auth login` |
| `auth.token_expired` | 3 | yes (after refresh) | your session expired; run `academy auth login` to re-authenticate |
| `auth.bad_credential` | 3 | no (re-login) | run `academy auth login` |
| `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 |
| `auth.cross_tenant_blocked` | 3 | no | verify tenant context with `academy auth status` |
| `auth.tenant_mismatch` | 3 | no | verify tenant context with `academy auth status` |
| `input.invalid_argument` | 5 | no | see `academy <command> --help` for valid usage |
| `input.missing_flag` | 5 | no | see `academy <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) |
| `server.error` | 7 | yes (with backoff for 5xx) | (no canonical hint) |
| `server.timeout` | 7 | yes (with backoff) | request timed out; retry, or run `weknora doctor` to check connectivity |
| `server.timeout` | 7 | yes (with backoff) | request timed out; retry, or run `academy doctor` to check connectivity |
| `server.rate_limited` | 6 | yes (back off, then retry) | rate-limited; retry after a few seconds |
| `server.session_create_failed` | 1 | yes (with backoff) | could not create a chat session; pass `--session` to reuse an existing session |
| `server.incompatible_version` | 7 | no (upgrade required) | run `weknora doctor` to see version skew details |
| `network.error` | 7 | yes (with backoff) | check base URL reachability with `weknora doctor` |
| `server.incompatible_version` | 7 | no (upgrade required) | run `academy doctor` to see version skew details |
| `network.error` | 7 | yes (with backoff) | check base URL reachability with `academy doctor` |
| `operation.timeout` | 124 | yes (raise `--timeout`) | wait timed out; raise `--timeout` or check the underlying job |
| `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.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.config_corrupt` | 1 | no (manual fix) | remove `~/.config/academy/config.yaml` and re-run `academy auth login` |
| `local.profile_not_found` | 1 | no | (no canonical hint; check `academy profile list`) |
| `local.file_io` | 1 | no | check file permissions under `$XDG_CONFIG_HOME/academy/` |
| `local.kb_id_required` | 1 | no | run `academy link` to bind this directory to a knowledge base, or pass `--kb` |
| `local.kb_not_found` | 1 | no | list available with `academy 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.project_link_corrupt` | 1 | no | remove `.academy/project.yaml` and run `academy link` again |
| `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 |
@@ -420,7 +420,7 @@ Agents parse the first colon to extract the typed code. The exit code class (see
For common retry patterns, AI agents can hardcode:
- `network.*` → retry with exponential backoff
- `auth.token_expired` → run `weknora auth refresh`, then retry once
- `auth.token_expired` → run `academy auth refresh`, then retry once
- `server.rate_limited` → back off (Retry-After if present) then retry
- `operation.timeout` → raise `--timeout` and retry, or surface to user
- `input.confirmation_required` → **NEVER** auto-pass `-y` without explicit user authorization
@@ -457,7 +457,7 @@ auto-retry this exit code — every exit 10 is a user-in-the-loop decision.
## Stream recovery
The `weknora session resume <session-id> --message <msg-id>` command resumes an SSE event stream for an existing assistant message. Use cases: network-blip recovery, long-running agent invocation polling, completed-stream inspection.
The `academy session resume <session-id> --message <msg-id>` command resumes an SSE event stream for an existing assistant message. Use cases: network-blip recovery, long-running agent invocation polling, completed-stream inspection.
### Server semantics: replay-from-0, not cursor-resume
@@ -476,11 +476,11 @@ The server **replays all stored events from the start** of the assistant message
| `STREAM_MANAGER_TYPE=redis` | **1 hour** (server-side; not configurable from the CLI) |
| `STREAM_MANAGER_TYPE=memory` (default) | **Process lifetime** (server restart = data loss; no explicit cleanup logic) |
After TTL, `weknora session resume` returns the typed error `local.sse_stream_aborted`, which maps to exit code 1 per the Error code reference.
After TTL, `academy session resume` returns the typed error `local.sse_stream_aborted`, which maps to exit code 1 per the Error code reference.
## Dry-run contract
The `--dry-run` flag is available on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `weknora api` (POST/PUT/PATCH/DELETE only; GET rejected with FlagError exit 2).
The `--dry-run` flag is available on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `academy api` (POST/PUT/PATCH/DELETE only; GET rejected with FlagError exit 2).
### Envelope shape on dry-run
@@ -498,7 +498,7 @@ Success envelope (exit 0) with `data` field omitted (omitempty) and `meta.dry_ru
### Side effects suppressed
The dry-run path is **offline** — no SDK calls, no Factory.Client() init, no ResolveKB network query, no writes (keyring / `.weknora/project.yaml` / files). Works without active profile or network access.
The dry-run path is **offline** — no SDK calls, no Factory.Client() init, no ResolveKB network query, no writes (keyring / `.academy/project.yaml` / files). Works without active profile or network access.
### Interactions
@@ -517,7 +517,7 @@ The dry-run path is **offline** — no SDK calls, no Factory.Client() init, no R
`session ask` and `chat` do NOT support `--dry-run` (streaming and dry-run have a semantic mismatch). For prompt-formation preview, use:
```bash
echo '{"query":"...","kb":"..."}' | weknora api -X POST /api/v1/sessions/<id>/agent-qa --input - --dry-run
echo '{"query":"...","kb":"..."}' | academy api -X POST /api/v1/sessions/<id>/agent-qa --input - --dry-run
```
## Risk metadata
@@ -526,15 +526,15 @@ Agents see the same `risk.action` string (in the form `noun.verb`) on three inde
1. **Error envelope** — `envelope.error.risk.action` on an exit-10 confirmation-required error, so the agent can decide whether to escalate to the user. 11 unique values: `kb.delete`, `kb.edit`, `agent.delete`, `agent.edit`, `doc.delete`, `doc.delete_all`, `session.delete`, `chunk.delete`, `profile.remove`, `auth.logout`, `api.delete`.
2. **Help text** — a `Risk: <action> (destructive)` line prepended to the top of `--help` output on the 9 destructive cobra commands. `weknora api` is intentionally excluded: it is a generic HTTP passthrough whose risk depends on the method, so a static Risk: line would mislead for non-DELETE methods.
2. **Help text** — a `Risk: <action> (destructive)` line prepended to the top of `--help` output on the 9 destructive cobra commands. `academy api` is intentionally excluded: it is a generic HTTP passthrough whose risk depends on the method, so a static Risk: line would mislead for non-DELETE methods.
3. **MCP tool annotations** — `Tool.Annotations.destructiveHint` / `readOnlyHint` / `idempotentHint` / `openWorldHint` on every tool returned by `weknora mcp serve`.
3. **MCP tool annotations** — `Tool.Annotations.destructiveHint` / `readOnlyHint` / `idempotentHint` / `openWorldHint` on every tool returned by `academy mcp serve`.
The three surfaces do not auto-sync: each is wired separately so agents that only consume one surface still get the signal, but contributors adding a new destructive command must touch all three.
## MCP Tool Surface
WeKnora's MCP server exposes a curated read-only tool surface. Many MCP servers in the wild ship write / mutation operations on by default and rely on credential-scope or sandbox restrictions for safety. WeKnora opts for curation instead: the server side doesn't yet enforce per-token scope, so an agent holding a user's token has full write access. Until server-side scope ships, the CLI keeps mutation tools out of the MCP surface as a belt-and-braces second line of defense. When server scope arrives this stance can loosen.
Academy'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. Academy 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.
The curated 10 tools (`cli/internal/mcp/tools.go`):
@@ -562,7 +562,7 @@ Before specifying any CLI command, do this in order:
3. For each field, decide: hot-path flag / config-file only / hidden / never-expose.
4. Cross-check pagination signatures: an SDK `(ctx, id, page, pageSize)` shape demands `--limit` + `--all-pages` + `--page-size` on the CLI side.
5. ONLY THEN consult mainstream CLI conventions to choose flag names, positionals, mutex, and confirm semantics.
6. Decide which fields are "top use case" (flag) / "advanced" (`--config-file` or escape hatch via `weknora api`). Don't try to flag-cover every SDK field — mature CLIs that curate ship a tighter surface; CLIs that 1:1 mirror their API pay the UX cost.
6. Decide which fields are "top use case" (flag) / "advanced" (`--config-file` or escape hatch via `academy api`). Don't try to flag-cover every SDK field — mature CLIs that curate ship a tighter surface; CLIs that 1:1 mirror their API pay the UX cost.
Rationale: earlier drafts produced three categories of schema errors — fields that didn't exist on the underlying SDK, wrong field counts in user-facing docs, and missing pagination flags — that all stemmed from "design from convention, not from SDK." The fix is canonical: the SDK schema is the ground truth; convention decides names and shapes around that ground truth.
@@ -581,12 +581,12 @@ Reasons hard-required-flags is the v0.5+ default:
- Admin / debug commands have no natural human-interactive prompt to lean on.
- Agent-friendly: MCP callers do not stall waiting for stdin prompts.
- Consistent with every existing non-auth WeKnora command.
- Consistent with every existing non-auth Academy command.
- **Agent help blob**: Commands MAY call
`cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{...})` to expose a stable
JSON used_for / required_flags / examples / output / warnings shape.
Activated by `WEKNORA_AGENT_HELP=1` at `--help` time. Warnings are
Activated by `ACADEMY_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`.
+74 -74
View File
@@ -1,11 +1,11 @@
# Changelog — `weknora` CLI
# Changelog — `academy` CLI
All notable changes to the `weknora` CLI (the binary under `cli/` in this
All notable changes to the `academy` CLI (the binary under `cli/` in this
repository) will be documented in this file.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and the CLI follows [Semantic Versioning](https://semver.org/) independently
of the WeKnora server / frontend release cadence.
of the Academy server / frontend release cadence.
CLI history before v0.3 is recorded in the project root
[CHANGELOG.md](../CHANGELOG.md) under the release that introduced the CLI.
@@ -38,8 +38,8 @@ CLI history before v0.3 is recorded in the project root
embedding model is bound); `kb create` hints the fix when it is false.
- `model create` / `model update` / `model delete` (`update` rotates key /
base-url in place, preserving the id).
- Stateless env-credential auth: `WEKNORA_API_KEY` / `WEKNORA_TOKEN` +
`WEKNORA_HOST`, a zero-disk path for headless / agent use. `auth logout` now
- Stateless env-credential auth: `ACADEMY_API_KEY` / `ACADEMY_TOKEN` +
`ACADEMY_HOST`, a zero-disk path for headless / agent use. `auth logout` now
keeps the profile registered (use `profile remove` to delete it entirely).
- `meta.total_count` on paginated list / search output (full result size before
client-side `--limit` truncation).
@@ -70,7 +70,7 @@ CLI history before v0.3 is recorded in the project root
### v0.9 — auth/profile model harmonization + flag cleanup
#### Added
- `weknora session stop <session-id>` command to abort an in-flight agent run.
- `academy session stop <session-id>` command to abort an in-flight agent run.
- `profile add --use`: switch to the newly-added profile immediately (instead of only auto-selecting the first profile added).
- `-L` shorthand on `session view` (alias for `--limit`).
- `doc download --format json` now emits a success envelope (was bare).
@@ -83,7 +83,7 @@ CLI history before v0.3 is recorded in the project root
- **`--kb` now accepts a knowledge-base name *or* id** on `doc delete --all` and `search chunks` / `search docs`; it stays required (no silent project-link fallback on these commands).
- **`agent create --kb` renamed to `--attach-kb`** to disambiguate from the global `--kb` scope flag.
- **MCP tool `agent_invoke` renamed to `session_ask`** (clean rename — external MCP clients must update cached tool schemas).
- **`auth login` drops `--host` and `--name`.** It authenticates the active profile; create it first with `weknora profile add <name> --host <h> --use`. Target a non-active profile with the global `weknora --profile <name> auth login`.
- **`auth login` drops `--host` and `--name`.** It authenticates the active profile; create it first with `academy profile add <name> --host <h> --use`. Target a non-active profile with the global `academy --profile <name> auth login`.
- **`auth logout` and `auth refresh` drop `--name`.** They act on the active profile; target another with the global `--profile <name>`.
#### Removed
@@ -94,9 +94,9 @@ CLI history before v0.3 is recorded in the project root
### v0.8 — Agent safety nets + MCP annotations
#### Added
- `--dry-run` flag on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `weknora api` (POST/PUT/PATCH/DELETE only; GET returns FlagError exit 2).
- `--dry-run` flag on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `academy api` (POST/PUT/PATCH/DELETE only; GET returns FlagError exit 2).
- envelope `meta.dry_run: true` + `meta.plan: {action, args | method+path+body}` open-map fields (omitempty in non-dry-run envelopes).
- `weknora session continue-stream <session-id> --message <msg-id>` command for SSE event stream replay/recovery.
- `academy session continue-stream <session-id> --message <msg-id>` command for SSE event stream replay/recovery.
- MCP `Tool.Annotations` on all 10 MCP serve tools (`destructiveHint` / `readOnlyHint` / `idempotentHint` / `openWorldHint` + `Title`) per MCP spec 2025-06-18.
- `cli/internal/cmdutil/risk.go`: `SetRisk(cmd, action)` helper + `RiskDestructive` const + `GetRisk(cmd)` reader.
- Help output "Risk: <action> (<level>)" line at top of 9 destructive commands' `--help` (via modified `SetAgentHelp` wrapper).
@@ -104,7 +104,7 @@ CLI history before v0.3 is recorded in the project root
- `cli/README.md` sections: Dry-run preview / Resuming streams.
#### Changed
- `SetAgentHelp` wrapper in `cli/internal/cmdutil/agenthelp.go` now prepends "Risk:" line in default (non-JSON) help branch when `cmd.Annotations["risk.action"]` is set. WEKNORA_AGENT_HELP=1 JSON path unchanged.
- `SetAgentHelp` wrapper in `cli/internal/cmdutil/agenthelp.go` now prepends "Risk:" line in default (non-JSON) help branch when `cmd.Annotations["risk.action"]` is set. ACADEMY_AGENT_HELP=1 JSON path unchanged.
- 9 destructive commands' `SetAgentHelp` Warnings standardized: line 1 is a verbatim exit-10 / `-y` reminder; line 2 carries per-command destructive context.
- `cli/cmd/api/api.go` now has `SetAgentHelp` with runtime exit-10 note for `-X DELETE/PUT/PATCH`.
- `cli/cmd/doc/delete.go` Warnings adds a 3rd line describing `--all` blast radius.
@@ -134,7 +134,7 @@ CLI history before v0.3 is recorded in the project root
- 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.
`ACADEMY_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.
@@ -144,47 +144,47 @@ CLI history before v0.3 is recorded in the project root
`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`.**
- **`academy context` command group renamed to `academy profile`.**
- Subcommands `context list/add/remove/use` → `profile list/add/remove/use`.
- Global flag `--context` → `--profile`.
- On-disk config `~/.config/weknora/config.yaml` keys `current_context:` /
- On-disk config `~/.config/academy/config.yaml` keys `current_context:` /
`contexts:` → `current_profile:` / `profiles:` (no backwards-compat
alias; delete the file or rename the keys by hand to migrate).
- Binding file `.weknora/project.yaml` field `context:` → `profile:`
(re-run `weknora link` to regenerate).
- Binding file `.academy/project.yaml` field `context:` → `profile:`
(re-run `academy link` to regenerate).
- `profile use` JSON fields `current_context` / `previous_context` →
`current_profile` / `previous_profile`.
- `weknora link` JSON field `context` → `profile`.
- `academy 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) settle on `profile` as the term of art.
- **`weknora agent invoke` removed; use `weknora session ask --agent <id>`.**
- **`academy agent invoke` removed; use `academy 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 /
- `academy 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.
- Migration: `academy agent invoke ag_x "Q"` →
`academy session ask --agent ag_x "Q"` (auto-creates session if none given).
- **`academy doc upload` split into three commands.**
- `academy doc upload <file>` — local file only.
- `academy doc fetch <url>` — server-side remote fetch (was `upload --from-url`).
- `academy 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");
the three-verb split matches the server's three endpoints and gives each
one a single unambiguous shape.
- **`weknora kb empty` removed; use `weknora doc delete --all --kb=<id>`.**
- **`academy kb empty` removed; use `academy 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 -`
- Migration: `academy kb empty kb_x -y` →
`academy doc delete --all --kb=kb_x -y`.
- **`academy api -d/--data` flag removed; use `--input <file>` or `--input -`
(stdin).**
- `weknora api` now accepts any non-empty HTTP method (whitelist removed)
- `academy api` now accepts any non-empty HTTP method (whitelist removed)
so the escape hatch can hit endpoints the CLI doesn't natively model.
- Migration: `weknora api -d '{"foo":1}' /endpoint` →
`echo '{"foo":1}' | weknora api --input - /endpoint`.
- Migration: `academy api -d '{"foo":1}' /endpoint` →
`echo '{"foo":1}' | academy api --input - /endpoint`.
- **Batch operations envelope shape — per-item `ok` pattern.**
- `weknora doc delete id1,id2,id3` and similar multi-id mutations now emit:
- `academy 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
@@ -197,24 +197,24 @@ CLI history before v0.3 is recorded in the project root
- **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.
- **`weknora chat` requires the query as a single quoted argument.**
- v0.6: `MinimumNArgs(1)` silently joined `weknora chat hello world` into
`"unknown command \"x\" for \"academy\""` prose.
- **`academy chat` requires the query as a single quoted argument.**
- v0.6: `MinimumNArgs(1)` silently joined `academy chat hello world` into
`"hello world"`.
- v0.7: `ExactArgs(1)` rejects multi-arg with exit 2; matches
`weknora session ask`. Quote the query: `weknora chat "hello world"`.
`academy session ask`. Quote the query: `academy chat "hello world"`.
#### Added
- **`WEKNORA_PROFILE` env var** selects the active profile for a single
- **`ACADEMY_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:
- **`ACADEMY_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`)
surface server `Retry-After` header verbatim. CLI-direct (`academy 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
@@ -227,11 +227,11 @@ CLI history before v0.3 is recorded in the project root
- **`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
- **`academy doc fetch <url>`** — new command (see split above).
- **`academy doc create --text "..."`** — new command (see split above).
- **`academy session ask --agent <id> "..."`** — new command (replaces
`agent invoke`).
- **`weknora doc delete --all --kb=<id>`** — new mode of `doc delete`
- **`academy 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`.
@@ -266,7 +266,7 @@ CLI history before v0.3 is recorded in the project root
- **`--no-stream` flag removed** on `chat` / `agent invoke` → use
**`--format json`** to buffer the full answer before printing. The bare
text-accumulate use case (TTY but no streaming) is dropped.
- **`WEKNORA_SDK_DEBUG=1` env removed** → use **`WEKNORA_LOG_LEVEL=debug`**.
- **`ACADEMY_SDK_DEBUG=1` env removed** → use **`ACADEMY_LOG_LEVEL=debug`**.
- **`kb create --name <name>` flag removed** → use positional
**`kb create <name>`** (consistent with `agent create <name>`).
@@ -278,13 +278,13 @@ CLI history before v0.3 is recorded in the project root
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
- **`academy doc wait <id> [<id>...]`** — block until every document reaches a
terminal `parse_status`. Always wait-all — use shell composition
(`wait id1 && wait id2`) for fail-fast.
- `--timeout DURATION` (default 10m; exit 124 on hit)
- `--interval DURATION` (default 2s; exponential backoff to 15s + jitter)
- Multi-id concurrent (max 5 parallel); exit code priority 1 > 124 > 0
- **`--log-level error|warn|info|debug`** persistent flag + `WEKNORA_LOG_LEVEL`
- **`--log-level error|warn|info|debug`** persistent flag + `ACADEMY_LOG_LEVEL`
env. Wires into the SDK's debug logger via the additive
`client.SetDebugLevel(level string)` function.
- **`kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3>`** —
@@ -292,25 +292,25 @@ CLI history before v0.3 is recorded in the project root
(server only accepts it on create, not update). Required on self-hosted
deployments where the server-side default doesn't pre-populate a
provider — without it, subsequent `doc upload` returns `kb not found`.
- **`weknora kb status <id>`** — fast health snapshot (1 HTTP). Returns
- **`academy kb status <id>`** — fast health snapshot (1 HTTP). Returns
reachable / counts / is_processing.
- **`weknora kb check <id>`** — deep verification: status fields + `failed_count`
- **`academy kb check <id>`** — deep verification: status fields + `failed_count`
aggregated via doc list page-walk (1 + N HTTP). The verb split between
`status` (read state cheaply) and `check` (actively verify) communicates
cost to the caller.
- **`weknora agent status <id>`** — fast health snapshot (1 HTTP):
- **`academy agent status <id>`** — fast health snapshot (1 HTTP):
reachable / model_id.
- **`weknora agent check <id>`** — deep verification: status fields +
- **`academy agent check <id>`** — deep verification: status fields +
`kb_scope_all_reachable` from probing each KB in scope (1 + N HTTP). Same
status/check verb split as kb status/check.
- **`weknora doc delete <doc-id> [<doc-id>...]`** — positional multi-id.
- **`academy doc delete <doc-id> [<doc-id>...]`** — positional multi-id.
Default keep-going on failure. Single `-y/--yes` confirms the entire
batch; non-TTY without `-y` still exits 10.
- **`weknora session delete <session-id> [<session-id>...]`** — positional
- **`academy session delete <session-id> [<session-id>...]`** — positional
multi-id with the same keep-going semantics as `doc delete`.
- **`weknora chunk delete <chunk-id> [<chunk-id>...] --doc <doc-id>`** — positional
- **`academy chunk delete <chunk-id> [<chunk-id>...] --doc <doc-id>`** — positional
multi-id, all chunks share the same `--doc` parent (server route requires it).
- **`weknora api <path> --paginate`** — follows weknora's offset-based
- **`academy api <path> --paginate`** — follows academy's offset-based
pagination (`?page=N&page_size=M`) and merges all pages into a single
`{data, total}` JSON response.
- **MCP `chat` and `agent_invoke` tools** output schemas extended with
@@ -319,7 +319,7 @@ CLI history before v0.3 is recorded in the project root
no standard partial-response).
- **`SetAgentHelp` pattern** — `cmdutil.SetAgentHelp(cmd, AgentHelp{...})`
exposes a stable JSON used_for / required_flags / examples / output
shape, activated by `WEKNORA_AGENT_HELP=1` at `--help` time. Applied
shape, activated by `ACADEMY_AGENT_HELP=1` at `--help` time. Applied
to `chat` and `kb list` as proof-of-pattern; extending to another
command requires touching only that command's `NewCmd`.
- **`cli/AGENTS.md`** gains an "Error code reference" section (35 typed
@@ -392,40 +392,40 @@ CLI history before v0.3 is recorded in the project root
### v0.5 — agent CRUD, chunk subtree, MCP chunk_list, audit-driven cleanup
#### Added
- `weknora agent create <name> --model <id>` / `agent edit <id>` /
- `academy agent create <name> --model <id>` / `agent edit <id>` /
`agent delete <id>` — hybrid surface (hot-path flags for the common
fields + `--config-file` YAML/JSON for the long tail +
`--generate-skeleton` template emit). `--from <agent-id>` copies
from an existing agent.
- `weknora chunk list --doc <doc-id>` / `chunk view <chunk-id>` /
- `academy chunk list --doc <doc-id>` / `chunk view <chunk-id>` /
`chunk delete <chunk-id> --doc <doc-id>` — new subtree for RAG retrieval
debug. Paginated with v0.4 `--limit` / `--page-size` / `--all-pages` canon.
- `weknora mcp serve` adds `chunk_list` as the 10th curated tool.
- `weknora agent view <id>` human output now renders all 34 AgentConfig
- `academy mcp serve` adds `chunk_list` as the 10th curated tool.
- `academy agent view <id>` human output now renders all 34 AgentConfig
fields (previously 7), grouped into 10 presentation sections.
- `--all-pages` / `--page-size` on `search docs` and `search sessions`
(catching up with `session list` / `doc list` canon from v0.3+v0.4).
- `weknora doc list` gains `--keyword` / `--file-type` / `--source` /
- `academy doc list` gains `--keyword` / `--file-type` / `--source` /
`--tag-id` / `--start-time` / `--end-time` (RFC3339) — matches the
SDK's `KnowledgeListFilter` surface. Time flags reject malformed
input with `input.invalid_argument`.
- MCP `doc_list` tool gains the same 6 filter fields (`keyword`,
`file_type`, `source`, `tag_id`, `start_time`, `end_time`) so agents
have parity with the CLI.
- `weknora session view --full` (with `--limit`, default 50, bounds
- `academy session view --full` (with `--limit`, default 50, bounds
1..1000) loads chat history via `LoadMessages` and renders messages
inline after session metadata. JSON mode projects messages into a
`messages` array. `--limit` without `--full` errors with
`input.invalid_argument`.
- `weknora kb view` human render now includes `TYPE`, `PINNED` (badge,
- `academy kb view` human render now includes `TYPE`, `PINNED` (badge,
only when set), `TEMPORARY` (badge), `PROCESSING` (with doc count,
only when active), `SUMMARY MODEL`, and `CREATED`. Nested config
structs stay JSON-only.
- `weknora doc view` human render expands to include `TITLE` (when
- `academy doc view` human render expands to include `TITLE` (when
distinct from filename), `DESC`, `SOURCE`, `CHANNEL`, `TAG`,
`STORAGE` (human-readable bytes), `SUMMARY`, `ENABLED`, and `HASH`
(12-char prefix). All omit-empty.
- `weknora doc upload` gains `--enable-multimodel` (tri-state:
- `academy doc upload` gains `--enable-multimodel` (tri-state:
unset/true/false), repeatable `--metadata key=value`, and
`--channel` flags. `--enable-multimodel` and `--channel` apply to
file / `--recursive` / `--from-url`; `--metadata` is file /
@@ -454,14 +454,14 @@ CLI history before v0.3 is recorded in the project root
symmetric `ErrDuplicateURL` correctly.
#### Breaking changes
- `weknora search docs` now applies the keyword filter server-side via
- `academy search docs` now applies the keyword filter server-side via
`ListKnowledgeWithFilter` (was: page through every doc and
substring-match client-side). Smaller wire payload on large KBs.
**The match is now case-sensitive** (server uses `LIKE %keyword%`),
whereas the previous client-side path lowered both sides. Callers
that relied on case-insensitive matching (e.g. `search docs Q3`
finding `q3 retro`) must lower-case the query themselves, or fall
back to `weknora api` with a custom filter.
back to `academy api` with a custom filter.
#### Changed
- `cli/AGENTS.md` MCP curation rationale rewritten: curated read-only
@@ -473,7 +473,7 @@ CLI history before v0.3 is recorded in the project root
section includes a step reminding contributors to decide
flag-vs-escape-hatch per field rather than trying to flag-mirror
every SDK capability.
- `cli/README.md` now documents the `weknora api` raw HTTP passthrough
- `cli/README.md` now documents the `academy api` raw HTTP passthrough
as the canonical escape hatch for deep KB config, per-request `chat`
/ `agent invoke` overrides, and operations without a CLI verb.
@@ -494,15 +494,15 @@ CLI history before v0.3 is recorded in the project root
tool descriptions.
#### Added
- `weknora mcp serve` — curated read-only stdio MCP server exposing 9
- `academy mcp serve` — curated read-only stdio MCP server exposing 9
tools (`kb_list`, `kb_view`, `doc_list`, `doc_view`, `doc_download`,
`search_chunks`, `chat`, `agent_list`, `agent_invoke`). Destructive
verbs are intentionally excluded.
- `weknora agent list` / `agent view` / `agent invoke` — manage and
call WeKnora's server-side Custom Agent resources.
- `weknora auth token` — print the active credential to `stdout` for
- `academy agent list` / `agent view` / `agent invoke` — manage and
call Academy's server-side Custom Agent resources.
- `academy auth token` — print the active credential to `stdout` for
scripting (raw secret by default; `--json` emits `{token, mode, context}`).
- `weknora doc upload --from-url` — ingest a remote URL.
- `academy doc upload --from-url` — ingest a remote URL.
- `--json=fields,...` field projection and `--jq <expr>` filtering on
every command that emits JSON.
- `--limit` and `--all-pages` on list / search commands for bounded
@@ -515,7 +515,7 @@ CLI history before v0.3 is recorded in the project root
- `auth login --with-token` validates the supplied key against
`/auth/me` before persisting, and prints an advisory if the keyring
is unavailable and credentials fall back to a 0600 file under
`$XDG_CONFIG_HOME/weknora/secrets/`.
`$XDG_CONFIG_HOME/academy/secrets/`.
- AGENTS.md rewritten as a developer guide (~170 lines, 6 H2 sections).
### v0.3 — extended management surface and a `session` subtree
@@ -556,7 +556,7 @@ CLI history before v0.3 is recorded in the project root
management.
- `api --input FILE` / `api --input -` — body source for raw HTTP
passthrough (file or stdin); mutually exclusive with `--data`.
- `unlink` — remove the cwd's `.weknora/project.yaml` so subsequent
- `unlink` — remove the cwd's `.academy/project.yaml` so subsequent
commands stop auto-resolving `--kb` from it. Walks up from cwd so a
user in a subdirectory can unlink without cd-ing to the project root.
- Completion smoke test guards against cobra bumps silently breaking
+4 -4
View File
@@ -1,16 +1,16 @@
# Makefile for the WeKnora CLI (cli/ Go module).
# Makefile for the Academy CLI (cli/ Go module).
#
# Usage:
# make build compile to ./bin/weknora with version metadata
# make build compile to ./bin/academy with version metadata
# make test go test ./...
# make test-coverage same with coverage report
# make lint go vet (golangci-lint planned)
# make tidy go mod tidy
# make clean remove ./bin
BINARY := weknora
BINARY := academy
BUILD_DIR := bin
PKG := github.com/Tencent/WeKnora/cli
PKG := academy/cli
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
+95 -95
View File
@@ -1,18 +1,18 @@
# weknora — WeKnora CLI
# academy — Academy CLI
A command-line interface for the WeKnora RAG knowledge-base server. Lets you
A command-line interface for the Academy RAG knowledge-base server. Lets you
authenticate, manage knowledge bases and documents, run hybrid search, and
ask streaming RAG questions from your terminal or from an AI agent.
```bash
$ weknora --help
Command-line client for the WeKnora RAG server. Manage knowledge bases
$ academy --help
Command-line client for the Academy RAG server. Manage knowledge bases
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 custom agents (CRUD + status/check)
api Make a raw API request to the WeKnora server
api Make a raw API request to the Academy server
auth Manage authentication credentials and profiles
chat Ask a streaming RAG question against a knowledge base
chunk Manage document chunks (RAG retrieval debug)
@@ -24,7 +24,7 @@ Available Commands:
help Help about any command
kb Manage knowledge bases
link Bind the current directory to a knowledge base
mcp Run weknora as a Model Context Protocol server
mcp Run academy as a Model Context Protocol server
message Inspect and manage messages inside chat sessions
model Manage models (list / view / create / update / delete)
profile Manage CLI profiles (named connection targets)
@@ -49,9 +49,9 @@ Requires Go 1.26+.
```bash
git clone https://github.com/Tencent/WeKnora.git
cd WeKnora/cli
go build -o weknora .
sudo mv weknora /usr/local/bin/ # or anywhere on $PATH
cd Academy/cli
go build -o academy .
sudo mv academy /usr/local/bin/ # or anywhere on $PATH
```
### Pre-built binaries
@@ -65,77 +65,77 @@ until then, use the from-source build above.
## 5-minute quickstart
```bash
# 1. Register your WeKnora server as a profile and make it active
weknora profile add prod --host https://kb.example.com --use
# 1. Register your Academy server as a profile and make it active
academy profile add prod --host https://kb.example.com --use
# 2. Authenticate the active profile (interactive password prompt)
weknora auth login
academy auth login
# 2b. Or pipe an API key from stdin (for CI / AI agents)
echo "sk-..." | weknora auth login --with-token
echo "sk-..." | academy auth login --with-token
# 3. List knowledge bases
weknora kb list
academy kb list
# 4. Bind this directory to a knowledge base — subsequent commands auto-resolve --kb
weknora link --kb my-knowledge-base
academy link --kb my-knowledge-base
# 5. Upload a document, then block until parsing finishes
weknora doc upload notes.md
weknora doc wait doc_abc # exit 0 completed, 1 failed, 124 --timeout, 130 ^C
weknora doc reparse doc_abc # re-trigger parsing if it failed, then wait again
academy doc upload notes.md
academy doc wait doc_abc # exit 0 completed, 1 failed, 124 --timeout, 130 ^C
academy doc reparse doc_abc # re-trigger parsing if it failed, then wait again
# 6. Search
weknora search chunks "what is reciprocal rank fusion?"
academy search chunks "what is reciprocal rank fusion?"
# 7. Ask the LLM (streams to terminal)
weknora chat "summarise the design doc"
academy chat "summarise the design doc"
# 8. Manage custom agents and run them (see `weknora agent --help` / `weknora session --help`)
weknora model list # discover a model id for --model
weknora agent list
weknora session ask --agent ag_abc "what's our q4 retention plan?"
# 8. Manage custom agents and run them (see `academy agent --help` / `academy session --help`)
academy model list # discover a model id for --model
academy agent list
academy 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
academy chunk list --doc doc_xyz
# 10. Inspect messages in a session / search across sessions
weknora message list --session sess_abc
weknora message search "retry policy" # cross-session Q&A retrieval
academy message list --session sess_abc
academy message search "retry policy" # cross-session Q&A retrieval
# 11. Resolve a pending tool approval (agent run blocked on approval event)
weknora session tool-approval resolve pend_xxx -y # approve (after user go-ahead)
weknora session resume sess_abc --message msg_xyz # resume the blocked stream
academy session tool-approval resolve pend_xxx -y # approve (after user go-ahead)
academy session resume sess_abc --message msg_xyz # resume the blocked stream
# 12. Health & verification verbs
weknora kb status kb_abc # fast snapshot: reachable / counts / processing flag (1 HTTP)
weknora kb check kb_abc # deep verify: also aggregates failed_count via doc list (1+N HTTP)
weknora agent status ag_abc # fast: reachable / model_id
weknora agent check ag_abc # deep: probes every KB in the agent's scope
academy kb status kb_abc # fast snapshot: reachable / counts / processing flag (1 HTTP)
academy kb check kb_abc # deep verify: also aggregates failed_count via doc list (1+N HTTP)
academy agent status ag_abc # fast: reachable / model_id
academy agent check ag_abc # deep: probes every KB in the agent's scope
```
---
### Agent quick start
For AI agents (any MCP-capable host) integrating WeKnora:
For AI agents (any MCP-capable host) integrating Academy:
1. Install: build from source (see [Install](#install))
2. Authenticate. In a sandbox / CI, the **stateless** path needs no `auth login`
and writes nothing to disk — just set two env vars:
```bash
export WEKNORA_API_KEY="sk-…" # or WEKNORA_TOKEN for a bearer JWT
export WEKNORA_HOST="https://kb.example.com"
weknora kb list # already authenticated
export ACADEMY_API_KEY="sk-…" # or ACADEMY_TOKEN for a bearer JWT
export ACADEMY_HOST="https://kb.example.com"
academy kb list # already authenticated
```
Or, for a persisted local profile:
```bash
weknora profile add prod --host <server-url> --use
weknora auth login
academy profile add prod --host <server-url> --use
academy auth login
```
3. Register MCP in the host's MCP config:
```json
{"mcpServers": {"weknora": {"command": "weknora", "args": ["mcp", "serve"]}}}
{"mcpServers": {"academy": {"command": "academy", "args": ["mcp", "serve"]}}}
```
4. Read the [wire contract](AGENTS.md#wire-contract-for-ai-agents) before
parsing `--format json` output.
@@ -143,21 +143,21 @@ For AI agents (any MCP-capable host) integrating WeKnora:
any destructive call.
**Bundled Agent Skills.** This CLI ships [Agent Skills](https://agentskills.io/specification)
under [`skills/`](skills/) that teach an agent to drive WeKnora without trial and error:
under [`skills/`](skills/) that teach an agent to drive Academy without trial and error:
- [`weknora-shared`](skills/weknora-shared/SKILL.md) — **read first**: auth/profile
- [`academy-shared`](skills/academy-shared/SKILL.md) — **read first**: auth/profile
sequence, `--kb` resolution, the JSON-envelope + exit-code contract, the exit-10
protocol, `--dry-run`, and CLI-vs-MCP selection.
- [`weknora-rag-search`](skills/weknora-rag-search/SKILL.md) — when to use `chat`
- [`academy-rag-search`](skills/academy-rag-search/SKILL.md) — when to use `chat`
vs `session ask` vs `search chunks`, plus retrieval gotchas.
Install them with the CLI (the skills are embedded in the binary, no checkout
needed):
```bash
weknora skills install # writes to ~/.claude/skills
weknora skills install --dir <agent-skills-dir> --force # other agents / overwrite
weknora skills list --format json # what would be installed
academy skills install # writes to ~/.claude/skills
academy skills install --dir <agent-skills-dir> --force # other agents / overwrite
academy skills list --format json # what would be installed
```
Existing files are left untouched without `--force`; `--dry-run` previews the
@@ -174,27 +174,27 @@ on the *active* profile (override per-invocation with the global `--profile`
flag). Create a profile first, then authenticate it:
```bash
weknora profile add prod --host https://prod.example.com --use # add + switch
weknora auth login # authenticate active (prod)
academy profile add prod --host https://prod.example.com --use # add + switch
academy auth login # authenticate active (prod)
weknora profile add staging --host https://staging.example.com # add (stays inactive)
echo "sk-..." | weknora --profile staging auth login --with-token # authenticate staging
academy profile add staging --host https://staging.example.com # add (stays inactive)
echo "sk-..." | academy --profile staging auth login --with-token # authenticate staging
weknora auth list
weknora profile use prod # switch back
academy auth list
academy profile use prod # switch back
```
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 profile lives in
`~/.config/weknora/config.yaml`.
under `$XDG_CONFIG_HOME/academy/secrets/`. The active profile lives in
`~/.config/academy/config.yaml`.
To remove a profile's stored credentials:
```bash
weknora auth logout # active profile
weknora --profile staging auth logout # specific profile
weknora auth logout --all
academy auth logout # active profile
academy --profile staging auth logout # specific profile
academy auth logout --all
```
---
@@ -203,7 +203,7 @@ weknora auth logout --all
Designed to be AI-agent-first. Stable across minor releases; breaking
changes announced in the changelog and the corresponding
`weknora --version` bump. This section is the human overview; the complete,
`academy --version` bump. This section is the human overview; the complete,
authoritative contract (envelope field stability, error taxonomy, streaming,
confirmation and dry-run protocols) lives in **[AGENTS.md](AGENTS.md)**.
@@ -222,16 +222,16 @@ symmetric envelope `{ok, data, meta?}` — `data` is an array for `list` /
against the whole envelope, so reach into list items with `.data[]`:
```bash
weknora kb list --format json # {"ok":true,"data":[{"id":"kb_x",…}],"meta":{"count":1,…}}
weknora kb view kb_x --format json # {"ok":true,"data":{"id":"kb_x","name":"Eng",…}}
weknora kb list --format json --jq '.data[] | {id, name}' # project listed fields out of each item
weknora kb list --format json --jq '.data[].id' # ids only
weknora kb list --format json --jq '.meta.count' # number returned
academy kb list --format json # {"ok":true,"data":[{"id":"kb_x",…}],"meta":{"count":1,…}}
academy kb view kb_x --format json # {"ok":true,"data":{"id":"kb_x","name":"Eng",…}}
academy kb list --format json --jq '.data[] | {id, name}' # project listed fields out of each item
academy kb list --format json --jq '.data[].id' # ids only
academy kb list --format json --jq '.meta.count' # number returned
```
`--format ndjson` is also accepted for streaming list commands; each
element is emitted as its own JSON line. `--format json` is the default
regardless of TTY — running `weknora kb list | jq` works without an
regardless of TTY — running `academy kb list | jq` works without an
explicit flag. Use `--format text` for human-readable output.
### Errors
@@ -248,7 +248,7 @@ Example:
```
auth.unauthenticated: fetch current user: HTTP error 401: ...
hint: run `weknora auth login`
hint: run `academy auth login`
```
Under `--format json` the same failure is the typed error envelope on stderr
@@ -262,7 +262,7 @@ taxonomy.
|---|---|---|
| `0` | success | continue |
| `1` | typed `local.*` / `operation.failed` / unclassified | read stderr, decide retry/abort |
| `2` | flag / argument validation error | re-check `weknora <cmd> --help` |
| `2` | flag / argument validation error | re-check `academy <cmd> --help` |
| `3` | `auth.*` (token missing / expired / forbidden) | re-auth, then retry |
| `4` | `resource.not_found` | verify the resource id |
| `5` | `input.*` (other than `confirmation_required`) | adjust args, retry |
@@ -272,7 +272,7 @@ taxonomy.
| `124` | `operation.timeout` (e.g. `doc wait --timeout` reached) | raise `--timeout` or check the underlying job |
| `130` | cancelled by signal — typed `operation.cancelled` errors exit 1; `main.go` promotes the process exit to 130 when the root context was signal-cancelled (SIGINT / SIGTERM) | stop, do not retry |
Run `weknora exit-codes` for the machine-readable matrix (JSON); `weknora help exit-codes` for the human-readable table.
Run `academy exit-codes` for the machine-readable matrix (JSON); `academy help exit-codes` for the human-readable table.
**Exit 10** is the wire-level signal for "destructive write needs
explicit confirmation". Pass `-y/--yes` on `kb delete` /
@@ -290,10 +290,10 @@ is the guard against unintended writes.
the unmodified raw stream.
- `--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
- `academy mcp serve` exposes a curated read-only tool surface over
stdio MCP for any MCP-compatible client.
- `weknora schema` enumerates every command with its `used_for`, and
`weknora schema <cmd path>` (e.g. `weknora schema doc update`) prints that
- `academy schema` enumerates every command with its `used_for`, and
`academy schema <cmd path>` (e.g. `academy schema doc update`) prints that
command's full contract — `used_for`, `required_flags`, `examples`,
`output`, `warnings`, `risk`, and local `flags` — as the standard envelope,
so an agent can discover the surface without scraping `--help` prose.
@@ -302,27 +302,27 @@ is the guard against unintended writes.
## Advanced operations not exposed as flags
WeKnora CLI exposes top use cases as polished commands; deep
Academy CLI exposes top use cases as polished commands; deep
configuration goes through the raw HTTP passthrough. CLI flag coverage
targets common workflows, not 1:1 API parity. Examples of deep
operations that intentionally go through `weknora api`:
operations that intentionally go through `academy api`:
- **Tuning a KB's nested config** — chunking strategy, summary model,
multimodal extraction defaults, FAQ thresholds, VLM model. Use
`weknora api PUT /api/v1/knowledge-bases/<id> --input -` with a JSON
`academy api PUT /api/v1/knowledge-bases/<id> --input -` with a JSON
body matching the server's `UpdateKnowledgeBaseRequest`. (Note: the
storage provider is set once at create time via
`kb create --storage-provider <name>` and is not updatable.)
- **Per-request `chat` parameters** — multi-KB scope, summary model
override, image attachments, web search toggle. Use `weknora api POST
override, image attachments, web search toggle. Use `academy api POST
/api/v1/knowledge-chat/<session-id> --input -`.
- **Per-request `session ask --agent` overrides** — same shape via
`weknora api POST /api/v1/agent-chat/<session-id> --input -`.
`academy api POST /api/v1/agent-chat/<session-id> --input -`.
- **Operations without a CLI verb** — register / change-password /
OIDC flows, organization / sharing endpoints, tenant management.
`weknora api --help` documents the raw passthrough. Run
`weknora doctor` first to verify auth and base URL.
`academy api --help` documents the raw passthrough. Run
`academy doctor` first to verify auth and base URL.
---
@@ -332,7 +332,7 @@ Add `--dry-run` to any mutation command to preview the would-be action without e
```bash
# Preview a kb create without actually creating
weknora kb create --name "test-kb" --description "for review" --dry-run
academy kb create --name "test-kb" --description "for review" --dry-run
# Output (single line; pretty-printed here for readability):
# {
@@ -353,32 +353,32 @@ dry-run is **offline**: no network calls, no file IO, no credential touches. Wor
For destructive commands, dry-run does NOT trigger the exit-10 confirmation flow:
```bash
weknora kb delete kb_xxxx --dry-run # exit 0, no prompt
weknora kb delete kb_xxxx # exit 10, prompts for -y
academy kb delete kb_xxxx --dry-run # exit 0, no prompt
academy kb delete kb_xxxx # exit 10, prompts for -y
```
For the `api` command, dry-run requires explicit write method (POST/PUT/PATCH/DELETE); GET returns FlagError:
```bash
echo '{"name":"foo"}' | weknora api -X POST /api/v1/knowledge-bases --input - --dry-run # OK
weknora api /api/v1/knowledge-bases --dry-run # exit 2: requires explicit -X
echo '{"name":"foo"}' | academy api -X POST /api/v1/knowledge-bases --input - --dry-run # OK
academy api /api/v1/knowledge-bases --dry-run # exit 2: requires explicit -X
```
---
## Resuming streams
The `weknora session resume` command resumes an SSE event stream for an existing assistant message. Useful for network-blip recovery or polling long-running agent invocations:
The `academy session resume` command resumes an SSE event stream for an existing assistant message. Useful for network-blip recovery or polling long-running agent invocations:
```bash
# Original streaming call captures session_id + message_id from init event:
weknora session ask "..." --agent ag_xxxx --format ndjson | tee /tmp/stream.ndjson
academy session ask "..." --agent ag_xxxx --format ndjson | tee /tmp/stream.ndjson
# {"type":"init","session_id":"sess_abc","message_id":"msg_xyz"}
# ... events flow ...
# [network blip]
# Resume the same stream:
weknora session resume sess_abc --message msg_xyz
academy session resume sess_abc --message msg_xyz
# Server REPLAYS all stored events from the start, then tails new ones.
# Agent must dedupe (by message_id or event hash) to avoid double-processing.
```
@@ -390,10 +390,10 @@ An agent run may pause the stream on a tool-approval event until a human approve
```bash
# 1. Stream pauses with a tool-approval event carrying a pending_id.
# 2. Surface the pending tool call to the user; get explicit go-ahead.
weknora session tool-approval resolve pend_xxx -y # approve
# weknora session tool-approval resolve pend_xxx --reject --reason "..." -y # reject
academy session tool-approval resolve pend_xxx -y # approve
# academy session tool-approval resolve pend_xxx --reject --reason "..." -y # reject
# 3. Resume the stream — server replays + tails from where the run was blocked.
weknora session resume sess_abc --message msg_xyz
academy session resume sess_abc --message msg_xyz
```
Pass `--modified-args '{"key":"value"}'` to replace tool arguments on approve (must be a non-empty JSON object). Never auto-pass `-y` — the approval is the exit-10 human-in-the-loop gate.
@@ -406,7 +406,7 @@ See `cli/AGENTS.md` "Stream recovery" section for the full agent contract.
## Health check
Run `weknora doctor` for a 4-status diagnostic (OK / warn / fail /
Run `academy doctor` for a 4-status diagnostic (OK / warn / fail /
skip) covering base URL reachability, authentication, server-CLI
version skew, and credential storage backend. Add `--format json` for
machine-readable output, `--offline` to skip network checks.
@@ -416,12 +416,12 @@ a fast vs deep choice:
| Verb | Cost | Use |
|---|---|---|
| `weknora kb status <kb-id>` | 1 HTTP | live counts / processing flag |
| `weknora kb check <kb-id>` | 1+N HTTP | adds `failed_count` via doc-list page-walk |
| `weknora agent status <agent-id>` | 1 HTTP | reachable / model_id |
| `weknora agent check <agent-id>` | 1+N HTTP | also probes every KB in the agent's scope |
| `academy kb status <kb-id>` | 1 HTTP | live counts / processing flag |
| `academy kb check <kb-id>` | 1+N HTTP | adds `failed_count` via doc-list page-walk |
| `academy agent status <agent-id>` | 1 HTTP | reachable / model_id |
| `academy agent check <agent-id>` | 1+N HTTP | also probes every KB in the agent's scope |
`weknora doc wait <doc-id> [<doc-id>...]` blocks until each document
`academy doc wait <doc-id> [<doc-id>...]` blocks until each document
reaches a terminal `parse_status` (completed or failed). Exit codes:
0 (all completed), 1 (any failed), 124 (`--timeout` reached), 130
(Ctrl-C / SIGTERM). Multi-target is polled concurrently (max 5 in
@@ -435,7 +435,7 @@ flight; pipe through `xargs -P` for more).
# Run unit + contract tests
go test ./...
# Run the real-server e2e suite (requires WEKNORA_E2E_HOST + token env vars)
# Run the real-server e2e suite (requires ACADEMY_E2E_HOST + token env vars)
go test -tags acceptance_e2e ./acceptance/e2e/...
# Static analysis
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
// TestAllReferencedCodesAreRegistered scans cli/cmd/ for every literal use of
+8 -8
View File
@@ -10,12 +10,12 @@ import (
"path/filepath"
"testing"
"github.com/Tencent/WeKnora/cli/cmd"
"github.com/Tencent/WeKnora/cli/cmd/doctor"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/cmd"
"academy/cli/cmd/doctor"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/secrets"
sdk "academy/client"
)
// TestMain pins the doctor credential-storage outcome for the whole suite.
@@ -40,7 +40,7 @@ var update = flag.Bool("update", false, "update golden files")
// newTestFactory builds a Factory whose Client returns mockClient.
// Caller must NOT use t.Parallel() - see iostreams.SetForTest contract.
//
// WEKNORA_BASE_URL is set when mockServer is non-nil. buildClient does not
// ACADEMY_BASE_URL is set when mockServer is non-nil. buildClient does not
// currently honor this env var (it reads from config.Host); commands that
// need the mock URL rely on the mockClient injection above. The env is set
// anyway for any direct net/http callers (e.g. doctor's HEAD /health).
@@ -49,7 +49,7 @@ func newTestFactory(t *testing.T, mockServer *httptest.Server, mockClient *sdk.C
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if mockServer != nil {
t.Setenv("WEKNORA_BASE_URL", mockServer.URL)
t.Setenv("ACADEMY_BASE_URL", mockServer.URL)
}
f := cmdutil.New()
if mockClient != nil {
+2 -2
View File
@@ -40,8 +40,8 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/config"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/config"
sdk "academy/client"
)
// wireCase declares one row in the contract matrix. Optional fields:
+1 -1
View File
@@ -7,5 +7,5 @@
// Sub-packages:
//
// contract/ - envelope JSON shape golden + error.code registry consistency
// e2e/ - real WeKnora server blackbox tests (testscript-style)
// e2e/ - real Academy server blackbox tests (testscript-style)
package acceptance
+18 -18
View File
@@ -1,6 +1,6 @@
//go:build acceptance_e2e
// Package e2e_test drives the WeKnora CLI binary against a real running
// Package e2e_test drives the Academy CLI binary against a real running
// server to validate the RAG closing loop end-to-end.
//
// Build tag isolation: //go:build acceptance_e2e excludes this file from
@@ -8,11 +8,11 @@
// requested. To run:
//
// cd cli
// WEKNORA_E2E_HOST=https://kb.example.com \
// WEKNORA_E2E_TOKEN=eyJhbGc... \
// ACADEMY_E2E_HOST=https://kb.example.com \
// ACADEMY_E2E_TOKEN=eyJhbGc... \
// go test -tags=acceptance_e2e -v ./acceptance/e2e/...
//
// Optional WEKNORA_E2E_KB_NAME_PREFIX customizes the throwaway KB name (default
// Optional ACADEMY_E2E_KB_NAME_PREFIX customizes the throwaway KB name (default
// "cli-e2e-"). Cleanup runs even on test failure via t.Cleanup so the server
// doesn't accumulate test debris.
package e2e_test
@@ -34,14 +34,14 @@ import (
// step parses the CLI's bare JSON to extract IDs for the next step -
// validating both functional behavior and wire-contract stability.
func TestRAGFullLoop(t *testing.T) {
host := mustEnv(t, "WEKNORA_E2E_HOST")
token := mustEnv(t, "WEKNORA_E2E_TOKEN")
prefix := envOr("WEKNORA_E2E_KB_NAME_PREFIX", "cli-e2e-")
host := mustEnv(t, "ACADEMY_E2E_HOST")
token := mustEnv(t, "ACADEMY_E2E_TOKEN")
prefix := envOr("ACADEMY_E2E_KB_NAME_PREFIX", "cli-e2e-")
bin := buildBinary(t)
xdg := t.TempDir()
// Inject host + token as WEKNORA_HOST / WEKNORA_TOKEN env vars. The
// Inject host + token as ACADEMY_HOST / ACADEMY_TOKEN env vars. The
// CLI's env-credential path (buildClientFromEnv) takes precedence
// over profile config, so this bypasses the secrets-store dance
// entirely — no keychain access, no file:// ref plumbing. This is
@@ -49,18 +49,18 @@ func TestRAGFullLoop(t *testing.T) {
env := append(os.Environ(),
"XDG_CONFIG_HOME="+xdg,
"XDG_CACHE_HOME="+filepath.Join(xdg, "cache"),
"WEKNORA_HOST="+host,
"WEKNORA_TOKEN="+token,
"ACADEMY_HOST="+host,
"ACADEMY_TOKEN="+token,
// SDK debug off - explicit so the CI run isn't noisy.
"WEKNORA_LOG_LEVEL=error",
"ACADEMY_LOG_LEVEL=error",
)
// 1. kb create → KnowledgeBase object (envelope-wrapped: {ok, data})
// The CLI now requires explicit model binding so uploaded docs are
// immediately searchable. Use the server's builtin model IDs (they
// exist on every deployment that configures builtin_models.yaml).
embeddingModel := envOr("WEKNORA_E2E_EMBEDDING_MODEL", "Qwen/Qwen3-Embedding-8B")
chatModel := envOr("WEKNORA_E2E_CHAT_MODEL", "deepseek-ai/DeepSeek-V3.2")
embeddingModel := envOr("ACADEMY_E2E_EMBEDDING_MODEL", "Qwen/Qwen3-Embedding-8B")
chatModel := envOr("ACADEMY_E2E_CHAT_MODEL", "deepseek-ai/DeepSeek-V3.2")
kbName := prefix + fmt.Sprintf("%d", time.Now().UnixNano())
var created struct {
OK bool `json:"ok"`
@@ -174,7 +174,7 @@ func envOr(key, fallback string) string {
func buildBinary(t *testing.T) string {
t.Helper()
dir := t.TempDir()
out := filepath.Join(dir, "weknora")
out := filepath.Join(dir, "academy")
// Repo layout: this test sits at cli/acceptance/e2e/, so cli/ is two levels up.
cmd := exec.Command("go", "build", "-o", out, ".")
cmd.Dir = filepath.Join("..", "..")
@@ -191,13 +191,13 @@ func buildBinary(t *testing.T) string {
// window.
func writeSampleDoc(t *testing.T) string {
t.Helper()
content := `WeKnora E2E Sample Document
content := `Academy E2E Sample Document
This sample document is used by the WeKnora CLI acceptance test suite to
This sample document is used by the Academy CLI acceptance test suite to
validate the end-to-end retrieval-augmented generation pipeline.
向量检索的核心思想是把文本通过 embedding 模型映射到高维向量空间,然后通过余弦相似度
等度量找出语义最接近的内容片段。WeKnora 支持 vector + keyword 的混合检索模式。
等度量找出语义最接近的内容片段。Academy 支持 vector + keyword 的混合检索模式。
The hybrid search mode combines vector similarity (semantic) with keyword
matching (lexical) to balance recall and precision.
@@ -211,7 +211,7 @@ matching (lexical) to balance recall and precision.
}
// waitDocReady polls `doc list` until the uploaded document's status indicates
// indexing is complete. WeKnora server uses a few status values across versions
// indexing is complete. Academy server uses a few status values across versions
// ("ready", "completed", "ok") - accept any non-pending/non-processing/non-failed
// state so we don't break on a server-side rename. Failed status fails the test
// fast.
+1 -1
View File
@@ -1 +1 @@
{"ok":true,"data":{"summary":{"all_passed":false,"passed":1,"failed":1,"skipped":2},"checks":[{"name":"base_url_reachable","status":"fail","details":"server returned 500","hint":"verify the host configured for the active profile (run `weknora profile list` / `weknora profile add <n> --host=...`) and network reachability"},{"name":"auth_credential","status":"skip","details":"prereq failed: base_url_reachable"},{"name":"server_version","status":"skip","details":"prereq failed: auth_credential"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}}
{"ok":true,"data":{"summary":{"all_passed":false,"passed":1,"failed":1,"skipped":2},"checks":[{"name":"base_url_reachable","status":"fail","details":"server returned 500","hint":"verify the host configured for the active profile (run `academy profile list` / `academy profile add <n> --host=...`) and network reachability"},{"name":"auth_credential","status":"skip","details":"prereq failed: base_url_reachable"},{"name":"server_version","status":"skip","details":"prereq failed: auth_credential"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}}
+6 -6
View File
@@ -1,21 +1,21 @@
// Package agentcmd holds the `weknora agent` command tree:
// Package agentcmd holds the `academy agent` command tree:
// list / view / create / update / delete / status / check. The directory is
// named `agent/` to match the cobra subcommand; the Go package is `agentcmd`
// to avoid colliding with cobra's *cobra.Command identifier.
//
// "agent" in this subtree refers to WeKnora's user-defined Custom
// "agent" in this subtree refers to Academy's user-defined Custom
// Agents (server resource: GET/POST /agents/...) and handles CRUD
// operations only. Agent invocation has moved to `weknora session ask
// operations only. Agent invocation has moved to `academy session ask
// --agent <id>` (see cli/cmd/session/ask.go).
package agentcmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
// NewCmd builds the `weknora agent` parent and registers leaves. Called
// NewCmd builds the `academy agent` parent and registers leaves. Called
// from cli/cmd/root.go.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
@@ -23,7 +23,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
Short: "Manage custom agents (CRUD + status/check)",
Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB
scope into an addressable resource. Create, update, list, view, check,
or delete agents. To invoke an agent, use: weknora session ask --agent <id>`,
or delete agents. To invoke an agent, use: academy session ask --agent <id>`,
}
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdView(f))
+8 -8
View File
@@ -7,9 +7,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// AgentCheckResult is the deep-verification response for `agent check <id>`.
@@ -32,7 +32,7 @@ type AgentCheckService interface {
var agentCheckFields = []string{"id", "reachable", "model_id", "kb_scope_all_reachable"}
// NewCmdCheck builds `weknora agent check <id>`.
// NewCmdCheck builds `academy agent check <id>`.
func NewCmdCheck(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "check <agent-id>",
@@ -44,11 +44,11 @@ Performs 1 + N HTTP calls:
N GET /kb/{kb_id} for each id in agent.config.knowledge_bases
— sets kb_scope_all_reachable = true iff every probe succeeds
Use 'weknora agent status <id>' for a fast read-only health snapshot
Use 'academy agent status <id>' for a fast read-only health snapshot
(1 HTTP call, no KB probing). Use 'agent check' when you need to verify
the agent's downstream dependencies are all reachable.`,
Example: ` weknora agent check ag_abc
weknora agent check ag_abc --format json`,
Example: ` academy agent check ag_abc
academy agent check ag_abc --format json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -71,7 +71,7 @@ the agent's downstream dependencies are all reachable.`,
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "verify a custom agent end-to-end: status plus kb_scope reachability",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent check agent_abc"},
Examples: []string{"academy agent check agent_abc"},
Output: "envelope.data is {id, reachable, ...} with kb_scope reachability folded in",
})
return cmd
+2 -2
View File
@@ -8,8 +8,8 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
sdk "academy/client"
)
type fakeAgentCheckSvc struct {
+13 -13
View File
@@ -9,9 +9,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// CreateService is the narrow SDK surface this command depends on.
@@ -58,16 +58,16 @@ type createFlagSet struct {
kbsSet bool
}
const agentCreateExample = ` weknora agent create "Support Bot" --model <model-id>
weknora agent create "Code Reviewer" --model <model-id> --system-prompt-file ./prompt.md --attach-kb kb_eng --attach-kb kb_arch
weknora agent create "From Template" --model <model-id> --from ag_existing
weknora agent create --generate-skeleton > my-agent.yaml
weknora agent create "Tuned" --model <model-id> --config-file ./my-agent.yaml`
const agentCreateExample = ` academy agent create "Support Bot" --model <model-id>
academy agent create "Code Reviewer" --model <model-id> --system-prompt-file ./prompt.md --attach-kb kb_eng --attach-kb kb_arch
academy agent create "From Template" --model <model-id> --from ag_existing
academy agent create --generate-skeleton > my-agent.yaml
academy agent create "Tuned" --model <model-id> --config-file ./my-agent.yaml`
const agentCreateLong = `Create a new custom agent.
--model is required (an agent without a model cannot invoke); discover a
valid model id with 'weknora model list'. The 7
valid model id with 'academy model list'. The 7
optional hot-path flags cover the most frequently set AgentConfig fields;
for the remaining 27 use --config-file with a YAML or JSON document
matching the AgentConfig schema (run --generate-skeleton to get a
@@ -84,7 +84,7 @@ AI agents: writes a new resource server-side. Failure surfaces as a
typed code on stderr: input.invalid_argument (bad flags, bad file, or
bad model), resource.not_found (--from <missing>), auth.unauthenticated.`
// NewCmdCreate builds `weknora agent create <name> --model <id>`.
// NewCmdCreate builds `academy agent create <name> --model <id>`.
func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts := &CreateOptions{}
var systemPromptFile, configFile string
@@ -222,9 +222,9 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
UsedFor: "Create a new custom agent. --model is required and accepts a model id or name; --attach-kb (repeatable) accepts KB ids or names. Emits the created Agent object.",
RequiredFlags: []string{"<name> (positional)", "--model"},
Examples: []string{
`weknora agent create "Support Bot" --model gpt-4o`,
`weknora agent create "Support Bot" --model gpt-4o --attach-kb kb_eng --system-prompt "You are a support assistant."`,
`weknora agent create --generate-skeleton # print a blank config to fill in (no --model needed)`,
`academy agent create "Support Bot" --model gpt-4o`,
`academy agent create "Support Bot" --model gpt-4o --attach-kb kb_eng --system-prompt "You are a support assistant."`,
`academy agent create --generate-skeleton # print a blank config to fill in (no --model needed)`,
},
Output: "envelope.data is the created Agent object with id, name, config",
})
+3 -3
View File
@@ -11,9 +11,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// fakeCreateSvc records all three SDK methods this command may invoke.
+10 -10
View File
@@ -6,9 +6,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
)
// agentDeleteFields enumerates the JSON discovery fields for `agent delete`.
@@ -51,11 +51,11 @@ and writes input.confirmation_required to stderr. NEVER auto-pass -y
without the user's explicit go-ahead — the exit-10 protocol exists
exactly to guard against unintended deletes.`
const agentDeleteExample = ` weknora agent delete ag_abc # interactive confirm
weknora agent delete ag_abc -y # no prompt
weknora agent delete ag_abc -y --format json # bare {id, deleted:true} JSON`
const agentDeleteExample = ` academy agent delete ag_abc # interactive confirm
academy agent delete ag_abc -y # no prompt
academy agent delete ag_abc -y --format json # bare {id, deleted:true} JSON`
// NewCmdDelete builds `weknora agent delete <agent-id>`.
// NewCmdDelete builds `academy agent delete <agent-id>`.
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
opts := &DeleteOptions{}
cmd := &cobra.Command{
@@ -95,8 +95,8 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
RequiredFlags: []string{"<agent-id> (positional)"},
Output: "envelope.data is {id, deleted:true}",
Examples: []string{
"weknora agent delete ag_abc -y",
"weknora agent delete ag_abc -y --format json",
"academy agent delete ag_abc -y",
"academy agent delete ag_abc -y --format json",
},
Warnings: []string{
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
@@ -107,7 +107,7 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "agent", opts.AgentID, "agent.delete", []string{"weknora", "agent", "delete", opts.AgentID, "-y"}); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "agent", opts.AgentID, "agent.delete", []string{"academy", "agent", "delete", opts.AgentID, "-y"}); err != nil {
return err
}
if err := svc.DeleteAgent(ctx, opts.AgentID); err != nil {
+3 -3
View File
@@ -7,9 +7,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/testutil"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/testutil"
)
type fakeDeleteSvc struct {
+13 -13
View File
@@ -9,9 +9,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// EditService is the narrow SDK surface this command depends on. The fetch
@@ -92,13 +92,13 @@ with input.confirmation_required. Surface the prompt to the user and only
retry with -y after explicit approval. Other failure codes: resource.not_found
(agent id or KB id), auth.forbidden, input.invalid_argument (no flags, bad file).`
const agentEditExample = ` weknora agent update ag_abc --name "Renamed" -y
weknora agent update ag_abc --description "" -y # clear description
weknora agent update ag_abc --add-kb kb_new --remove-kb kb_old -y
weknora agent update ag_abc --system-prompt-file ./prompt.md -y
weknora agent update ag_abc --config-file ./tuned.yaml --temperature 0.9 -y`
const agentEditExample = ` academy agent update ag_abc --name "Renamed" -y
academy agent update ag_abc --description "" -y # clear description
academy agent update ag_abc --add-kb kb_new --remove-kb kb_old -y
academy agent update ag_abc --system-prompt-file ./prompt.md -y
academy agent update ag_abc --config-file ./tuned.yaml --temperature 0.9 -y`
// NewCmdEdit builds `weknora agent update <agent-id>`.
// NewCmdEdit builds `academy agent update <agent-id>`.
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
opts := &EditOptions{}
var systemPromptFile, configFile string
@@ -219,7 +219,7 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
// Build the retry command from the flags the user actually passed.
// Include list-shaped and file-path flags so exit-10 retry_argv reproduces
// the original update (BuildRetryArgv expands StringSlice as repeats).
retryCmd := cmdutil.BuildRetryArgv(cmd, []string{"weknora", "agent", "update", opts.AgentID},
retryCmd := cmdutil.BuildRetryArgv(cmd, []string{"academy", "agent", "update", opts.AgentID},
"name", "description", "model", "system-prompt", "system-prompt-file",
"agent-mode", "rerank-model", "temperature", "add-kb", "remove-kb",
"kb-selection-mode", "config-file", "format")
@@ -272,9 +272,9 @@ func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
UsedFor: "surgically update a custom agent's configuration",
RequiredFlags: []string{"<agent-id> (positional)", "at least one update flag (--name, --add-kb, etc.)"},
Examples: []string{
"weknora agent update ag_abc --name \"Renamed\"",
"weknora agent update ag_abc --add-kb kb_new --remove-kb kb_old",
"weknora agent update ag_abc --config-file ./tuned.yaml",
"academy agent update ag_abc --name \"Renamed\"",
"academy agent update ag_abc --add-kb kb_new --remove-kb kb_old",
"academy agent update ag_abc --config-file ./tuned.yaml",
},
Output: "envelope.data is the updated Agent object (id, name, config) after the update is applied",
Warnings: []string{
+4 -4
View File
@@ -7,10 +7,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
sdk "academy/client"
)
// agentDryRunFactory builds a Factory whose Client closure panics if invoked —
+7 -7
View File
@@ -12,10 +12,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
sdk "academy/client"
)
// fakeEditSvc scripts GetAgent (fetch baseline) + UpdateAgent (apply
@@ -292,11 +292,11 @@ func TestEdit_SystemPromptFile(t *testing.T) {
assert.Equal(t, "new prompt", svc.updateReq.Config.SystemPrompt)
}
// withRootHarnessAgent wraps `weknora agent update ...` under a synthetic root
// withRootHarnessAgent wraps `academy agent update ...` under a synthetic root
// cmd that registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go).
func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
root := &cobra.Command{Use: "academy"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "Output format: text | json | ndjson")
@@ -352,7 +352,7 @@ func TestAgentEdit_RetryArgvPreservesAddKB(t *testing.T) {
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
// pflag Visit is lexicographical among changed flags.
assert.Equal(t, []string{
"weknora", "agent", "update", "ag_abc",
"academy", "agent", "update", "ag_abc",
"--add-kb", "kb_new",
"--format", "json",
"--remove-kb", "kb_old",
+7 -7
View File
@@ -9,11 +9,11 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
"academy/cli/internal/text"
sdk "academy/client"
)
// agentListFields enumerates the fields surfaced for `--format json` discovery
@@ -38,7 +38,7 @@ type ListOptions struct {
Limit int
}
// NewCmdList builds `weknora agent list`.
// NewCmdList builds `academy agent list`.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{}
cmd := &cobra.Command{
@@ -67,7 +67,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmdutil.AddFormatFlag(cmd, agentListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List custom agents visible to the active tenant. The SDK returns all agents in one call (no server-side pagination); meta.count reflects the full tenant set, --limit caps client-side.",
Examples: []string{"weknora agent list --format json", "weknora agent list --limit 10 --format json"},
Examples: []string{"academy agent list --format json", "academy agent list --limit 10 --format json"},
Output: "envelope.data is an array of Agent objects with id, name, is_builtin; meta.total_count is the full tenant set and meta.has_more=true means --limit truncated it (raise --limit to get the rest)",
})
return cmd
+3 -3
View File
@@ -9,9 +9,9 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type fakeListSvc struct {
+8 -8
View File
@@ -7,9 +7,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// AgentStatusResult is the shallow health snapshot for `agent status <id>`.
@@ -41,11 +41,11 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
Returns: reachable / model_id.
For downstream KB reachability verification use 'weknora agent check <id>'
For downstream KB reachability verification use 'academy agent check <id>'
(active verification, 1 + N HTTP). For full agent config / metadata use
'weknora agent view <id>'.`,
Example: ` weknora agent status ag_abc
weknora agent status ag_abc --format json`,
'academy agent view <id>'.`,
Example: ` academy agent status ag_abc
academy agent status ag_abc --format json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -68,7 +68,7 @@ For downstream KB reachability verification use 'weknora agent check <id>'
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "shallow health probe of a custom agent: reachability without kb_scope verification",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent status agent_abc"},
Examples: []string{"academy agent status agent_abc"},
Output: "envelope.data is {id, reachable, ...}; use `agent check` for deep kb_scope verification",
})
return cmd
+2 -2
View File
@@ -8,8 +8,8 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
sdk "academy/client"
)
type fakeAgentStatusSvc struct {
+9 -9
View File
@@ -8,10 +8,10 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/text"
sdk "academy/client"
)
// promptPreviewWidth caps inline KV row prompt previews. Multi-line prompts
@@ -34,7 +34,7 @@ type ViewService interface {
GetAgent(ctx context.Context, agentID string) (*sdk.Agent, error)
}
// NewCmdView builds `weknora agent view <agent-id>`.
// NewCmdView builds `academy agent view <agent-id>`.
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "view <agent-id>",
@@ -46,9 +46,9 @@ fields are omitted; sections with no set fields are suppressed entirely.
Pass --format json for the bare SDK Agent object (config nested, not flattened).
Use --jq to project specific fields or reach into nested config.`,
Example: ` weknora agent view ag_abc
weknora agent view ag_abc --format json --jq '{id, name, config}' # top-level projection
weknora agent view ag_abc --format json --jq '.config.system_prompt'`,
Example: ` academy agent view ag_abc
academy agent view ag_abc --format json --jq '{id, name, config}' # top-level projection
academy agent view ag_abc --format json --jq '.config.system_prompt'`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -67,7 +67,7 @@ Use --jq to project specific fields or reach into nested config.`,
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "fetch one custom agent's full configuration by id",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent view agent_abc"},
Examples: []string{"academy agent view agent_abc"},
Output: "envelope.data is the custom agent (id, name, description, is_builtin, and a nested config object holding model/kb_scope/...)",
})
return cmd
+3 -3
View File
@@ -9,9 +9,9 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type fakeViewSvc struct {
+6 -6
View File
@@ -8,19 +8,19 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
// TestEveryLeafCommandHasAgentHelp enforces the agent-first contract: every
// leaf (runnable, no subcommands) command must emit a structured AgentHelp JSON
// blob under WEKNORA_AGENT_HELP=1, so an agent never has to scrape human prose.
// blob under ACADEMY_AGENT_HELP=1, so an agent never has to scrape human prose.
// Drift guard in the spirit of the K6/K7 skill-parity tests: a new leaf command
// added without SetAgentHelp fails CI here.
//
// Exemptions: cobra's generated `completion`/`help` subtrees carry no
// domain semantics worth a machine blob.
func TestEveryLeafCommandHasAgentHelp(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
t.Setenv("ACADEMY_AGENT_HELP", "1")
root := NewRootCmd(cmdutil.New())
var missing []string
@@ -44,7 +44,7 @@ func TestEveryLeafCommandHasAgentHelp(t *testing.T) {
}
}
// renderAgentHelp runs a leaf's help under WEKNORA_AGENT_HELP=1 and decodes the
// renderAgentHelp runs a leaf's help under ACADEMY_AGENT_HELP=1 and decodes the
// machine blob (used_for / output / examples) an agent would read.
func renderAgentHelp(t *testing.T, c *cobra.Command) struct {
UsedFor string `json:"used_for"`
@@ -71,7 +71,7 @@ func renderAgentHelp(t *testing.T, c *cobra.Command) struct {
// envelope (e.g. deletes emit {id, deleted:true}); an empty Output is a contract
// gap, not a valid state. Sibling drift guard to the agent-help test above.
func TestEveryLeafCommandDeclaresOutput(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
t.Setenv("ACADEMY_AGENT_HELP", "1")
root := NewRootCmd(cmdutil.New())
var missing []string
@@ -91,7 +91,7 @@ func TestEveryLeafCommandDeclaresOutput(t *testing.T) {
// TestEveryLeafCommandHasExample enforces that every leaf ships at least one
// runnable example — agents learn invocation shape from examples, not prose.
func TestEveryLeafCommandHasExample(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
t.Setenv("ACADEMY_AGENT_HELP", "1")
root := NewRootCmd(cmdutil.New())
var missing []string
+22 -22
View File
@@ -1,4 +1,4 @@
// Package api implements the `weknora api` raw HTTP passthrough command.
// Package api implements the `academy api` raw HTTP passthrough command.
//
// Shape: one positional (path) + `-X/--method` flag, default GET (auto-
// promoted to POST when a body is supplied via -d/--input). Text mode writes
@@ -22,9 +22,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// apiFields is intentionally a marker - api wraps arbitrary HTTP responses
@@ -50,12 +50,12 @@ type Service interface {
Raw(ctx context.Context, method, path string, body any) (*http.Response, error)
}
// NewCmd returns the `weknora api` command.
// NewCmd returns the `academy api` command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: "api <path>",
Short: "Make a raw API request to the WeKnora server",
Short: "Make a raw API request to the Academy server",
Long: `Raw HTTP API access. JSON body via -d/--data (inline) or --input <file>/- (stdin).
The default method is GET; supplying a body (-d or --input) auto-promotes it
@@ -71,11 +71,11 @@ With --paginate, text mode writes the merged {data, total} JSON object with a
trailing newline and no envelope.
Examples:
weknora api /api/v1/knowledge-bases # GET
weknora api /api/v1/knowledge-bases -d '{"name":"foo"}' # POST (auto)
weknora api /api/v1/knowledge-bases -F name=foo -F enabled=true # POST, typed body
echo '{"name":"foo"}' | weknora api /api/v1/knowledge-bases --input - # POST via stdin
weknora api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
academy api /api/v1/knowledge-bases # GET
academy api /api/v1/knowledge-bases -d '{"name":"foo"}' # POST (auto)
academy api /api/v1/knowledge-bases -F name=foo -F enabled=true # POST, typed body
echo '{"name":"foo"}' | academy api /api/v1/knowledge-bases --input - # POST via stdin
academy api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Yes, _ = c.Flags().GetBool("yes")
@@ -122,8 +122,8 @@ Examples:
}
}
method := resolveMethod(opts)
// Escape-hatch DELETE through `weknora api` is just as destructive
// as `weknora kb delete` - exit-10 destructive protocol must apply
// Escape-hatch DELETE through `academy api` is just as destructive
// as `academy kb delete` - exit-10 destructive protocol must apply
// (cli/README.md). PUT/PATCH mutate server state like a typed
// `kb/agent/doc update`, so they get the same exit-10 WRITE gate;
// without it the raw escape hatch bypassed the "an agent cannot
@@ -131,7 +131,7 @@ Examples:
// `create` (also ungated). GET/HEAD are reads.
switch method {
case http.MethodDelete:
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "endpoint", args[0], "api.delete", []string{"weknora", "api", "-X", "DELETE", args[0], "-y"}); err != nil {
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "endpoint", args[0], "api.delete", []string{"academy", "api", "-X", "DELETE", args[0], "-y"}); err != nil {
return err
}
case http.MethodPut, http.MethodPatch:
@@ -155,14 +155,14 @@ Examples:
cmdutil.AddFormatFlag(cmd, apiFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "raw HTTP passthrough to weknora-server API endpoints when typed subcommands are insufficient",
UsedFor: "raw HTTP passthrough to academy-server API endpoints when typed subcommands are insufficient",
RequiredFlags: []string{"path (positional)"},
Examples: []string{
"weknora api /api/v1/knowledge-bases",
"weknora api /api/v1/knowledge-bases -d '{\"name\":\"foo\"}'",
"weknora api -X POST /api/v1/knowledge-bases -F name=\"Eng Docs\" -F enabled=true",
"weknora api -X DELETE /api/v1/knowledge-bases/kb_x -y",
"echo '{\"name\":\"foo\"}' | weknora api /api/v1/knowledge-bases --input -",
"academy api /api/v1/knowledge-bases",
"academy api /api/v1/knowledge-bases -d '{\"name\":\"foo\"}'",
"academy api -X POST /api/v1/knowledge-bases -F name=\"Eng Docs\" -F enabled=true",
"academy api -X DELETE /api/v1/knowledge-bases/kb_x -y",
"echo '{\"name\":\"foo\"}' | academy api /api/v1/knowledge-bases --input -",
},
Output: "text mode: the raw server response body on stdout. " +
"json mode (default): the parsed server response is placed directly under envelope.data - " +
@@ -311,11 +311,11 @@ func resolveMethod(opts *Options) string {
return "GET"
}
// apiRetryArgv reconstructs a directly-executable `weknora api` argv (with -y)
// apiRetryArgv reconstructs a directly-executable `academy api` argv (with -y)
// for the write-confirmation gate, preserving the method, path and body flags
// the caller passed so an agent can re-run the exact mutation after approval.
func apiRetryArgv(opts *Options, method, path string) []string {
argv := []string{"weknora", "api", "-X", method, path}
argv := []string{"academy", "api", "-X", method, path}
switch {
case opts.Data != "":
argv = append(argv, "-d", opts.Data)
+4 -4
View File
@@ -9,10 +9,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
sdk "academy/client"
)
// apiDryRunFactory builds a Factory whose Client closure panics if invoked —
+8 -8
View File
@@ -19,10 +19,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
sdk "academy/client"
)
// fakeAPISvc is a test double for Service that delegates each call to a
@@ -306,12 +306,12 @@ func TestAPI_PathWithoutSlash(t *testing.T) {
}
}
// withRootHarness wraps `weknora api ...` under a synthetic root cmd that
// withRootHarness wraps `academy api ...` under a synthetic root cmd that
// registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go). Required because api's NewCmd doesn't register --yes /
// --format / --jq itself — it inherits them from root in production.
func withRootHarness(api *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
root := &cobra.Command{Use: "academy"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
@@ -325,7 +325,7 @@ func withRootHarness(api *cobra.Command, args ...string) *cobra.Command {
}
// TestAPI_DELETE_RequiresConfirmation pins the exit-10 protocol on the
// escape-hatch DELETE path: agent invokes `weknora api DELETE /...` without
// escape-hatch DELETE path: agent invokes `academy api DELETE /...` without
// -y/--yes, must get input.confirmation_required + exit 10. Confirmation is
// enforced in NewCmd.RunE (not runAPI), so the test drives the cobra cmd.
func TestAPI_DELETE_RequiresConfirmation(t *testing.T) {
@@ -659,7 +659,7 @@ func TestAPI_PaginateServerCapsPageSize(t *testing.T) {
}
// TestAPI_PUT_RequiresConfirmation pins the exit-10 write gate on the
// escape-hatch PUT path: `weknora api -X PUT /...` mutates server state the
// escape-hatch PUT path: `academy api -X PUT /...` mutates server state the
// same way a typed `kb update` does, so it must require -y (exit 10) rather
// than silently writing. Regression: only DELETE was gated, letting an agent
// bypass the write-confirmation protocol via raw PUT/PATCH.
+7 -7
View File
@@ -15,10 +15,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/cmd"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/cmd"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
func TestAPI_PaginateFormats(t *testing.T) {
@@ -110,8 +110,8 @@ func TestAPI_PaginateFormats(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", tc.env)
t.Setenv("WEKNORA_PROFILE", "")
t.Setenv("ACADEMY_FORMAT", tc.env)
t.Setenv("ACADEMY_PROFILE", "")
out, errOut := iostreams.SetForTest(t)
if tc.tty {
out, errOut = iostreams.SetForTestWithTTY(t)
@@ -209,7 +209,7 @@ func (w *paginationFailWriter) Write(p []byte) (int, error) {
func TestAPI_PaginateTextWriteError(t *testing.T) {
for _, tail := range []bool{false, true} {
t.Run(strconv.FormatBool(tail), func(t *testing.T) {
t.Setenv("WEKNORA_PROFILE", "")
t.Setenv("ACADEMY_PROFILE", "")
iostreams.SetForTest(t)
sentinel := errors.New("synthetic output failure")
out := &paginationFailWriter{err: sentinel, tail: tail}
+2 -2
View File
@@ -5,7 +5,7 @@ package auth
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
// Credential-mode tokens used in the JSON output of auth list / login /
@@ -34,7 +34,7 @@ func modeFromRefs(apiKeyRef, tokenRef string) string {
}
}
// NewCmdAuth builds the `weknora auth` command tree and registers its
// NewCmdAuth builds the `academy auth` command tree and registers its
// subcommands. Called from cli/cmd/root.go.
func NewCmdAuth(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
+7 -7
View File
@@ -9,13 +9,13 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
"academy/cli/internal/secrets"
"academy/cli/internal/testutil"
sdk "academy/client"
)
func TestNewCmdAuth_TreeShape(t *testing.T) {
+7 -7
View File
@@ -14,12 +14,12 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
"academy/cli/internal/secrets"
sdk "academy/client"
)
// authDryRunFactory builds a Factory whose Client closure panics if invoked —
@@ -44,7 +44,7 @@ func authDryRunFactory(t *testing.T, cfg *config.Config) *cmdutil.Factory {
// withRootHarnessAuth wraps an auth subcommand under a synthetic root cmd
// that registers the global persistent flags.
func withRootHarnessAuth(sub *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
root := &cobra.Command{Use: "academy"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
+8 -8
View File
@@ -7,10 +7,10 @@ import (
"github.com/spf13/cobra"
"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"
"academy/cli/internal/cmdutil"
"academy/cli/internal/format"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
)
type ListOptions struct{}
@@ -29,9 +29,9 @@ type listEntry struct {
Current bool `json:"current"`
}
// NewCmdList builds `weknora auth list`. Per-host enumeration: render one
// NewCmdList builds `academy auth list`. Per-host enumeration: render one
// row per registered profile, marking the active one. Reads only
// ~/.config/weknora/config.yaml - no network, no keyring touch.
// ~/.config/academy/config.yaml - no network, no keyring touch.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
@@ -50,7 +50,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmdutil.AddFormatFlag(cmd, authListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "list configured profiles and their credential mode (bearer / api-key)",
Examples: []string{"weknora auth list", "weknora auth list --jq '.data[].name'"},
Examples: []string{"academy auth list", "academy auth list --jq '.data[].name'"},
Output: "envelope.data is an array of profiles with name, host, mode, and which is active",
})
return cmd
@@ -78,7 +78,7 @@ func runList(fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
return fopts.Emit(iostreams.IO.Out, entries, meta)
}
if len(entries) == 0 {
fmt.Fprintln(iostreams.IO.Out, "No profiles configured. Run `weknora auth login` to create one.")
fmt.Fprintln(iostreams.IO.Out, "No profiles configured. Run `academy auth login` to create one.")
return nil
}
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
+3 -3
View File
@@ -8,9 +8,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
)
func newListFactory(cfg *config.Config) *cmdutil.Factory {
+18 -18
View File
@@ -8,11 +8,11 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/secrets"
sdk "academy/client"
)
// authLoginFields enumerates the fields surfaced for `--format json` discovery on
@@ -26,7 +26,7 @@ var authLoginFields = []string{
// LoginOptions is the configuration captured from flags + prompts. Host and
// Profile are resolved from the active profile in config (not from flags) -
// `auth login` authenticates the already-existing active profile, created
// beforehand with `weknora profile add <name> --host <h> --use`.
// beforehand with `academy profile add <name> --host <h> --use`.
type LoginOptions struct {
Host string // resolved from the active profile's Host in config
Profile string // resolved active profile name (honors global --profile)
@@ -65,22 +65,22 @@ var defaultAPIKeyValidator apiKeyValidator = func(ctx context.Context, host, api
return resp.Data.User, nil
}
// NewCmdLogin builds the `weknora auth login` command. runF is the testable
// NewCmdLogin builds the `academy auth login` command. runF is the testable
// entrypoint (left nil for production; see cli/cmd/auth/login_test.go).
func NewCmdLogin(f *cmdutil.Factory, runF func(context.Context, *LoginOptions, *cmdutil.FormatOptions, *cmdutil.Factory, LoginService) error) *cobra.Command {
opts := &LoginOptions{}
cmd := &cobra.Command{
Use: "login",
Short: "Authenticate the active profile against its WeKnora server",
Short: "Authenticate the active profile against its Academy server",
Long: `Authenticate the active profile by email + password (interactive prompt) or
pipe an API key with --with-token.
` + "`auth login`" + ` operates on the active profile (override with the global
--profile flag). Create the profile first with
` + "`weknora profile add <name> --host <h> --use`" + `, then run ` + "`weknora auth login`" + `.
` + "`academy profile add <name> --host <h> --use`" + `, then run ` + "`academy auth login`" + `.
Credentials are persisted to the OS keyring when available; otherwise to a
0600 file under $XDG_CONFIG_HOME/weknora/secrets.`,
0600 file under $XDG_CONFIG_HOME/academy/secrets.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -103,10 +103,10 @@ Credentials are persisted to the OS keyring when available; otherwise to a
cmdutil.AddFormatFlag(cmd, authLoginFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "authenticate the active profile; --with-token reads an API key from stdin (non-interactive)",
Examples: []string{`echo "$WEKNORA_API_KEY" | weknora auth login --with-token`},
Examples: []string{`echo "$ACADEMY_API_KEY" | academy auth login --with-token`},
Output: "envelope.data is {profile, host, mode, email, tenant_id} on success (email matches `auth status`)",
Warnings: []string{
"a profile must exist and be active first (`weknora profile add <n> --host <url> --use`)",
"a profile must exist and be active first (`academy profile add <n> --host <url> --use`)",
"password login is interactive-only (no flags) — agents must use --with-token with the key piped to stdin",
},
})
@@ -119,7 +119,7 @@ Credentials are persisted to the OS keyring when available; otherwise to a
// add`'s job. Returns typed errors when no active profile is configured or
// the profile lacks a host.
func resolveActiveProfile(f *cmdutil.Factory) (name, host string, err error) {
// f.Config() already folds the global --profile / WEKNORA_PROFILE override
// f.Config() already folds the global --profile / ACADEMY_PROFILE override
// into cfg.CurrentProfile (same source f.ActiveProfile reads), so one load
// resolves the active profile — matches logout/refresh.
cfg, err := f.Config()
@@ -128,10 +128,10 @@ func resolveActiveProfile(f *cmdutil.Factory) (name, host string, err error) {
}
active := cfg.CurrentProfile
if active == "" {
msg := "no active profile; run `weknora profile add <name> --host <h> --use` first"
msg := "no active profile; run `academy profile add <name> --host <h> --use` first"
if envActive, kind := cmdutil.EnvCredential(); envActive {
msg = "no active profile to log in — you are already authenticated this session via " + kind +
"; `auth login` only persists a named profile, so run `weknora profile add <name> --host <h> --use` first if you want one"
"; `auth login` only persists a named profile, so run `academy profile add <name> --host <h> --use` first if you want one"
}
return "", "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, msg)
}
@@ -197,7 +197,7 @@ func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOpti
// Transport errors (connection refused, DNS failure) must not be
// surfaced as auth.bad_credential — the key may be fine but the
// host is unreachable. Classify via WrapHTTP so network errors
// get CodeNetworkError and the hint points at `weknora doctor`.
// get CodeNetworkError and the hint points at `academy doctor`.
if cmdutil.ClassifyHTTPError(err) == cmdutil.CodeNetworkError {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "validate API key: check host reachability")
}
@@ -381,8 +381,8 @@ func warnOnFileFallback(store secrets.Store) {
if _, isFile := store.(*secrets.FileStore); !isFile {
return
}
fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable - credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.")
fmt.Fprintln(iostreams.IO.Err, " install / unlock the keyring (or use `weknora doctor` to inspect) for OS-backed storage.")
fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable - credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/academy/secrets/.")
fmt.Fprintln(iostreams.IO.Err, " install / unlock the keyring (or use `academy doctor` to inspect) for OS-backed storage.")
}
// readStdinTrimmed reads all of r and returns the result with surrounding
+7 -7
View File
@@ -10,13 +10,13 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
"academy/cli/internal/secrets"
"academy/cli/internal/testutil"
sdk "academy/client"
)
// fakeLoginService captures the email/password it received.
+14 -14
View File
@@ -6,10 +6,10 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/secrets"
)
type LogoutOptions struct {
@@ -28,7 +28,7 @@ type logoutResult struct {
Removed []string `json:"removed"`
}
// NewCmdLogout builds `weknora auth logout`. Clears stored credentials
// NewCmdLogout builds `academy auth logout`. Clears stored credentials
// (keyring + file fallback) and removes the profile entry from config.yaml.
// No server-side revocation - local-only credential clear.
func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
@@ -37,14 +37,14 @@ func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
Use: "logout",
Short: "Remove stored credentials for a profile",
Long: `Clear keyring + file-fallback secrets for one profile (or all of
them with --all) and drop the profile entry from ~/.config/weknora/config.yaml.
them with --all) and drop the profile entry from ~/.config/academy/config.yaml.
Note: this does NOT revoke the credential server-side - for API keys, you
must rotate them in the server UI; for JWT, the token will continue to be
accepted until it expires.`,
Example: ` weknora auth logout # active profile
weknora --profile staging auth logout # specific profile
weknora auth logout --all`,
Example: ` academy auth logout # active profile
academy --profile staging auth logout # specific profile
academy auth logout --all`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -92,9 +92,9 @@ accepted until it expires.`,
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "clear stored credentials for the active profile (or --all); the profile itself stays registered (host preserved) so `auth login` can re-auth it — use `profile remove` to delete the profile entirely",
Examples: []string{
"weknora auth logout",
"weknora --profile staging auth logout",
"weknora auth logout --all",
"academy auth logout",
"academy --profile staging auth logout",
"academy auth logout --all",
},
Output: "envelope.data is {removed: [profile names cleared]}",
Warnings: []string{
@@ -125,9 +125,9 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
// Destructive-write protocol: confirm before clearing credentials.
scope := fmt.Sprintf("%d profile(s) [%s]", len(targets), strings.Join(targets, ", "))
retryCmd := []string{"weknora", "auth", "logout", "-y"}
retryCmd := []string{"academy", "auth", "logout", "-y"}
if opts.All {
retryCmd = []string{"weknora", "auth", "logout", "--all", "-y"}
retryCmd = []string{"academy", "auth", "logout", "--all", "-y"}
}
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "auth credentials", scope, "auth.logout", retryCmd); err != nil {
return err
+5 -5
View File
@@ -6,11 +6,11 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
"academy/cli/internal/secrets"
)
// newLogoutFactory builds a Factory whose Config closure mutates the supplied
+16 -16
View File
@@ -6,9 +6,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type RefreshOptions struct {
@@ -22,12 +22,12 @@ var authRefreshFields = []string{"profile"}
// refreshResult is the typed payload emitted under data on success. Token
// values are intentionally NOT included - emitting them would leak secrets
// into stdout / agent transcripts. Agents needing to verify the new token
// can re-run `weknora auth status` (live API check).
// can re-run `academy auth status` (live API check).
type refreshResult struct {
Profile string `json:"profile"`
}
// NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access
// NewCmdRefresh builds `academy auth refresh`. Renews the JWT access
// token by spending the stored refresh_token via POST /auth/refresh -
// the standard OAuth refresh-token grant.
//
@@ -38,14 +38,14 @@ func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "refresh",
Short: "Renew the JWT access token using the stored refresh token",
Long: `Reads the refresh token previously stored by ` + "`weknora auth login`" + ` and
Long: `Reads the refresh token previously stored by ` + "`academy auth login`" + ` and
exchanges it for a new access + refresh token pair via POST /api/v1/auth/refresh.
Both new tokens replace the existing entries in the OS keyring.
API-key profiles are rejected with input.invalid_argument - they have no
refresh semantic. Rotate the key in the server UI instead.`,
Example: ` weknora auth refresh # refresh the active profile
weknora --profile staging auth refresh # refresh a specific profile`,
Example: ` academy auth refresh # refresh the active profile
academy --profile staging auth refresh # refresh a specific profile`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -67,7 +67,7 @@ refresh semantic. Rotate the key in the server UI instead.`,
"authenticated via "+kind+" (stateless env credential): there is no stored JWT to refresh — env credentials are supplied fresh each call, so no refresh is needed")
}
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no active profile configured; run `weknora auth login` to set one up")
"no active profile configured; run `academy auth login` to set one up")
}
prof, ok := cfg.Profiles[name]
if !ok {
@@ -79,9 +79,9 @@ refresh semantic. Rotate the key in the server UI instead.`,
fmt.Sprintf("profile %q has no host", name))
}
if prof.RefreshRef == "" {
hint := "api-key profiles can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`"
hint := "api-key profiles can't be refreshed - rotate the key in the server UI and run `academy auth login --with-token`"
if prof.APIKeyRef == "" {
hint = "no refresh token stored - run `weknora auth login` to authenticate"
hint = "no refresh token stored - run `academy auth login` to authenticate"
}
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
@@ -104,8 +104,8 @@ refresh semantic. Rotate the key in the server UI instead.`,
UsedFor: "Renew the JWT access token for the active profile (override with the global --profile) using the stored refresh token. API-key profiles are rejected.",
Output: "envelope.data has profile name that was refreshed",
Examples: []string{
"weknora auth refresh",
"weknora --profile staging auth refresh",
"academy auth refresh",
"academy --profile staging auth refresh",
},
})
return cmd
@@ -130,7 +130,7 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.Format
"authenticated via "+kind+" (stateless env credential): there is no stored JWT to refresh — env credentials are supplied fresh each call, so no refresh is needed")
}
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no active profile configured; run `weknora auth login` to set one up")
"no active profile configured; run `academy auth login` to set one up")
}
c, ok := cfg.Profiles[name]
if !ok {
@@ -142,9 +142,9 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.Format
fmt.Sprintf("profile %q has no host", name))
}
if c.RefreshRef == "" {
hint := "api-key profiles can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`"
hint := "api-key profiles can't be refreshed - rotate the key in the server UI and run `academy auth login --with-token`"
if c.APIKeyRef == "" {
hint = "no refresh token stored - run `weknora auth login` to authenticate"
hint = "no refresh token stored - run `academy auth login` to authenticate"
}
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
+7 -7
View File
@@ -10,13 +10,13 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
"academy/cli/internal/secrets"
"academy/cli/internal/testutil"
sdk "academy/client"
)
// fakeRefreshService scripts a RefreshToken response.
+10 -10
View File
@@ -8,9 +8,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// authStatusFields enumerates the fields surfaced for `--format json` discovery
@@ -42,7 +42,7 @@ type statusResult struct {
TenantName string `json:"tenant_name,omitempty"`
}
// NewCmdStatus builds the `weknora auth status` command.
// NewCmdStatus builds the `academy auth status` command.
func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "status",
@@ -51,7 +51,7 @@ func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
and tenant the server resolves the credential to.
Exits with auth.unauthenticated when the token is invalid or missing - run
` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT profiles) to recover.
` + "`academy auth login`" + ` (or ` + "`auth refresh`" + ` for JWT profiles) to recover.
For JWT profiles the SDK transparently refreshes on 401, so this command
usually only surfaces a hard auth failure.`,
Args: cobra.NoArgs,
@@ -71,7 +71,7 @@ usually only surfaces a hard auth failure.`,
cmdutil.AddFormatFlag(cmd, authStatusFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "show the active profile, the authenticated principal, and token state",
Examples: []string{"weknora auth status", "weknora auth status --jq .data.tenant_id"},
Examples: []string{"academy auth status", "academy auth status --jq .data.tenant_id"},
Output: "envelope.data is {profile, host, auth_source, user_id, username, email, tenant_id, tenant_name, ...}; auth_source is 'profile + keyring' or a stateless env credential; exit 3 if unauthenticated",
})
return cmd
@@ -79,7 +79,7 @@ usually only surfaces a hard auth failure.`,
func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, svc StatusService) error {
if svc == nil {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no SDK client available; run `weknora auth login`")
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no SDK client available; run `academy auth login`")
}
resp, err := svc.GetCurrentUser(ctx)
if err != nil {
@@ -94,8 +94,8 @@ func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
}
// Effective host + auth source. Stateless env credentials
// (WEKNORA_TOKEN/WEKNORA_API_KEY) override the profile + keyring for the
// client, so report the host they authenticate against (WEKNORA_HOST) and
// (ACADEMY_TOKEN/ACADEMY_API_KEY) override the profile + keyring for the
// client, so report the host they authenticate against (ACADEMY_HOST) and
// that they are in effect — not the bypassed config profile's host.
host := ""
if c, ok := cfg.Profiles[cfg.CurrentProfile]; ok {
@@ -104,7 +104,7 @@ func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
authSource := "profile + keyring"
if active, kind := cmdutil.EnvCredential(); active {
authSource = kind + " env (stateless)"
if h := strings.TrimSpace(os.Getenv("WEKNORA_HOST")); h != "" {
if h := strings.TrimSpace(os.Getenv("ACADEMY_HOST")); h != "" {
host = h
}
}
+4 -4
View File
@@ -6,10 +6,10 @@ import (
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
sdk "academy/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
+6 -6
View File
@@ -9,12 +9,12 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
"academy/cli/internal/testutil"
sdk "academy/client"
)
type fakeStatusService struct {
+21 -21
View File
@@ -6,8 +6,8 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
)
// authTokenFields lists fields surfaced in `--help` as a hint for `--jq`
@@ -20,12 +20,12 @@ type tokenResult struct {
Profile string `json:"profile"`
}
// NewCmdToken builds `weknora auth token`. Prints the active profile's
// NewCmdToken builds `academy auth token`. Prints the active profile's
// credential to stdout for use in shell pipelines, e.g.
//
// WEKNORA_TOKEN=$(weknora auth token)
// curl -H "Authorization: Bearer $WEKNORA_TOKEN" ... # JWT mode
// curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key mode
// ACADEMY_TOKEN=$(academy auth token)
// curl -H "Authorization: Bearer $ACADEMY_TOKEN" ... # JWT mode
// curl -H "X-API-Key: $ACADEMY_TOKEN" ... # api-key mode
//
// The user is responsible for constructing the appropriate header -
// `auth list` shows which mode each profile uses.
@@ -40,26 +40,26 @@ func NewCmdToken(f *cmdutil.Factory) *cobra.Command {
newline, suitable for shell command substitution.
The credential is the long-lived API key (mode: api-key) or the access JWT
(mode: bearer), depending on how the profile was created. Run ` + "`weknora auth list`" + `
(mode: bearer), depending on how the profile was created. Run ` + "`academy auth list`" + `
to see which mode each profile uses, and construct the matching HTTP header:
Authorization: Bearer <token> # bearer mode
X-API-Key: <token> # api-key mode
` + "`--profile <name>`" + ` (global flag) selects a non-active profile to read from.`,
Example: ` WEKNORA_TOKEN=$(weknora auth token)
weknora auth token --profile staging
weknora auth token --format json`,
Example: ` ACADEMY_TOKEN=$(academy auth token)
academy auth token --profile staging
academy auth token --format json`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
// `auth token` is a scalar scripting helper (WEKNORA_TOKEN=$(...)),
// `auth token` is a scalar scripting helper (ACADEMY_TOKEN=$(...)),
// so it defaults to the raw token — overriding the global json
// default, the same way `doc download` streams raw bytes. Explicit
// --format json / WEKNORA_FORMAT=json still emit the
// --format json / ACADEMY_FORMAT=json still emit the
// {token,mode,profile} envelope.
fopts.FromEnv()
if fopts.Mode == "" {
@@ -78,9 +78,9 @@ to see which mode each profile uses, and construct the matching HTTP header:
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "print the active profile's raw credential to stdout for shell capture",
Examples: []string{
"WEKNORA_TOKEN=$(weknora auth token)",
"weknora auth token --profile staging",
"weknora auth token --format json",
"ACADEMY_TOKEN=$(academy auth token)",
"academy auth token --profile staging",
"academy auth token --format json",
},
Output: "raw token on stdout (no envelope, no trailing newline) by default; --format json emits {token, mode, profile}",
Warnings: []string{
@@ -96,7 +96,7 @@ func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
// erroring on the absence of a stored profile.
if active, kind := cmdutil.EnvCredential(); active {
mode := ModeBearer
if kind == "WEKNORA_API_KEY" {
if kind == "ACADEMY_API_KEY" {
mode = ModeAPIKey
}
return emitToken(fopts, os.Getenv(kind), mode, "(env)")
@@ -143,12 +143,12 @@ func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
token, mode = v, ModeAPIKey
default:
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
fmt.Sprintf("profile %q has no stored credential; run `weknora auth login`", profileName))
fmt.Sprintf("profile %q has no stored credential; run `academy auth login`", profileName))
}
if token == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
fmt.Sprintf("profile %q credential is empty in keyring; run `weknora auth login`", profileName))
fmt.Sprintf("profile %q credential is empty in keyring; run `academy auth login`", profileName))
}
return emitToken(fopts, token, mode, profileName)
@@ -156,7 +156,7 @@ func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
// emitToken renders a resolved credential: the {token, mode, profile} envelope
// under --format json, else the raw token on stdout (no trailing newline, for
// clean $(weknora auth token) capture) with a TTY-only leak hint on stderr.
// clean $(academy auth token) capture) with a TTY-only leak hint on stderr.
func emitToken(fopts *cmdutil.FormatOptions, token, mode, profile string) error {
if token == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "active credential is empty")
@@ -165,7 +165,7 @@ func emitToken(fopts *cmdutil.FormatOptions, token, mode, profile string) error
return fopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Profile: profile}, nil)
}
// No trailing newline - clean $(weknora auth token) substitution.
// No trailing newline - clean $(academy auth token) substitution.
fmt.Fprint(iostreams.IO.Out, token)
// Defensive hint to stderr when stdout is an interactive terminal:
// the user likely didn't mean to display the secret on screen.
@@ -174,7 +174,7 @@ func emitToken(fopts *cmdutil.FormatOptions, token, mode, profile string) error
// recourse on leak - bearer tokens self-expire via refresh.
if iostreams.IO.IsStdoutTTY() {
fmt.Fprintln(iostreams.IO.Err)
fmt.Fprintln(iostreams.IO.Err, "hint: pipe to $(weknora auth token) to capture; this terminal scrollback now contains the secret")
fmt.Fprintln(iostreams.IO.Err, "hint: pipe to $(academy auth token) to capture; this terminal scrollback now contains the secret")
if mode == ModeAPIKey {
fmt.Fprintln(iostreams.IO.Err, "note: api-key credentials are long-lived - rotate via your auth provider if exposed (no `auth refresh` path)")
}
+6 -6
View File
@@ -5,10 +5,10 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/secrets"
)
// tokenTestFactory wires a config + in-memory secrets store the same way
@@ -24,8 +24,8 @@ func tokenTestFactory(t *testing.T, cfg *config.Config, store *secrets.MemStore)
}
// TestAuthToken_DefaultIsRawToken locks the scripting contract: with no
// explicit --format, `weknora auth token` emits the raw token (so
// WEKNORA_TOKEN=$(weknora auth token) works), NOT the JSON envelope — even
// explicit --format, `academy auth token` emits the raw token (so
// ACADEMY_TOKEN=$(academy auth token) works), NOT the JSON envelope — even
// though the global --format default is json. Explicit --format json still
// emits the {token,mode,profile} envelope (covered by the JSON test below).
func TestAuthToken_DefaultIsRawToken(t *testing.T) {
+14 -14
View File
@@ -1,4 +1,4 @@
// Package chat implements `weknora chat <text>` - the streaming RAG answer
// Package chat implements `academy chat <text>` - the streaming RAG answer
// entry point.
//
// Three output modes share a single SDK call:
@@ -28,11 +28,11 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"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"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
"academy/cli/internal/sse"
sdk "academy/client"
)
// chatFields enumerates the fields surfaced for `--jq` projection discovery
@@ -64,13 +64,13 @@ type ChatService interface {
KnowledgeQAStream(ctx context.Context, sessionID string, req *sdk.KnowledgeQARequest, cb func(*sdk.StreamResponse) error, opts ...sdk.ResourceURLOptions) error
}
// NewCmd builds `weknora chat <text>`.
// NewCmd builds `academy chat <text>`.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: `chat "<text>"`,
Short: "Ask a streaming RAG question against a knowledge base",
Long: `Send a query to the WeKnora knowledge-chat endpoint and stream the
Long: `Send a query to the Academy knowledge-chat endpoint and stream the
answer back. By default a fresh session is created on first invocation; pass
--session to continue an existing conversation.
@@ -83,9 +83,9 @@ Modes:
Pass --reference to include bounded kb_id/chunk_id reference indexes. Pass
--verbose to include reasoning, tool activity, and lifecycle frames. Combine
both flags for the complete projected stream.`,
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`,
Example: ` academy chat "What is RRF?" --kb a32a63ff-fb36-4874-bcaa-30f48570a694
academy chat "Summarise this design doc" --kb my-kb --format json
academy chat "Continue?" --session sess_abc`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Query = strings.TrimSpace(args[0])
@@ -118,8 +118,8 @@ both flags for the complete projected stream.`,
UsedFor: "Ask a RAG question against a knowledge base. Default JSON returns a bounded answer-event projection. --reference adds indexed citations; --verbose adds reasoning, tools, and lifecycle events. --format ndjson streams raw SDK events; --format text renders the selected events live.",
RequiredFlags: []string{"<text> (positional)", "--kb"},
Examples: []string{
`weknora chat "What is RRF?" --kb kb_abc`,
`weknora chat "What is RRF?" --kb kb_abc --jq '[.data.events[].content] | join("")'`,
`academy chat "What is RRF?" --kb kb_abc`,
`academy chat "What is RRF?" --kb kb_abc --jq '[.data.events[].content] | join("")'`,
},
Output: "Default --format json: {ok,data:{events:[answer...],session_id,kb_id,query}}. --reference adds kb_id/chunk_id reference events; --verbose adds execution events. --format ndjson remains raw.",
})
@@ -146,7 +146,7 @@ func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, s
sessionID := opts.SessionID
autoCreated := false
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora chat"})
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "academy chat"})
if err != nil {
// Ctrl-C during session creation: classify as cancelled so the
// hint nudges the user toward retry-with-signal-clean, not
+4 -4
View File
@@ -7,10 +7,10 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/sse"
sdk "academy/client"
)
// fakeChatService implements ChatService for unit tests. Tests configure the
+1 -1
View File
@@ -11,7 +11,7 @@ package chunkcmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
const chunkLong = `Manage and inspect document chunks.
+13 -13
View File
@@ -6,9 +6,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
)
// chunkDeleteFields enumerates the JSON discovery fields for `chunk delete`.
@@ -62,12 +62,12 @@ and writes input.confirmation_required to stderr. NEVER auto-pass -y
without the user's explicit go-ahead — the exit-10 protocol exists
exactly to guard against unintended deletes.`
const chunkDeleteExample = ` weknora chunk delete chunk_abc --doc doc_xyz # interactive confirm
weknora chunk delete chunk_abc --doc doc_xyz -y # no prompt
weknora chunk delete chunk_abc --doc doc_xyz -y --format json # bare {id, deleted:true} JSON
weknora chunk delete c1 c2 c3 --doc doc_xyz -y # delete 3 chunks under same doc, keep-going`
const chunkDeleteExample = ` academy chunk delete chunk_abc --doc doc_xyz # interactive confirm
academy chunk delete chunk_abc --doc doc_xyz -y # no prompt
academy chunk delete chunk_abc --doc doc_xyz -y --format json # bare {id, deleted:true} JSON
academy chunk delete c1 c2 c3 --doc doc_xyz -y # delete 3 chunks under same doc, keep-going`
// NewCmdDelete builds `weknora chunk delete <chunk-id> [<chunk-id>...] --doc <doc-id>`.
// NewCmdDelete builds `academy chunk delete <chunk-id> [<chunk-id>...] --doc <doc-id>`.
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
opts := &DeleteOptions{}
cmd := &cobra.Command{
@@ -100,7 +100,7 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
opts.ChunkID = args[0]
return runDelete(c.Context(), opts, fopts, cli, f.Prompter())
}
batchRetry := append([]string{"weknora", "chunk", "delete"}, args...)
batchRetry := append([]string{"academy", "chunk", "delete"}, args...)
batchRetry = append(batchRetry, "--doc", opts.DocID, "-y")
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "chunk", len(args), "chunk.delete", batchRetry); err != nil {
return err
@@ -132,9 +132,9 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
UsedFor: "permanently delete one or more chunks from a document",
RequiredFlags: []string{"<chunk-id>... (positional, at least one)", "--doc <doc-id>"},
Examples: []string{
"weknora chunk delete chunk_abc --doc doc_xyz -y",
"weknora chunk delete c1 c2 c3 --doc doc_xyz -y",
"weknora chunk delete chunk_abc --doc doc_xyz -y --format json",
"academy chunk delete chunk_abc --doc doc_xyz -y",
"academy chunk delete c1 c2 c3 --doc doc_xyz -y",
"academy chunk delete chunk_abc --doc doc_xyz -y --format json",
},
Output: "envelope.data shape depends on the form: a single chunk id -> {id, deleted:true}; multiple ids -> batch envelope (top-level status success|partial|error, ok=(failures==0), data per-item [{id, ok, error?}], meta.successes/failures — read data[].ok per id).",
Warnings: []string{
@@ -146,7 +146,7 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "chunk", opts.ChunkID, "chunk.delete", []string{"weknora", "chunk", "delete", opts.ChunkID, "--doc", opts.DocID, "-y"}); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "chunk", opts.ChunkID, "chunk.delete", []string{"academy", "chunk", "delete", opts.ChunkID, "--doc", opts.DocID, "-y"}); err != nil {
return err
}
if err := svc.DeleteChunk(ctx, opts.DocID, opts.ChunkID); err != nil {
+3 -3
View File
@@ -10,9 +10,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/testutil"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/testutil"
)
type fakeChunkDeleteSvc struct {
+10 -10
View File
@@ -8,11 +8,11 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
"academy/cli/internal/text"
sdk "academy/client"
)
const (
@@ -72,11 +72,11 @@ AI agents: prefer 'search chunks' for retrieval tasks. Use 'chunk list'
only when you need to enumerate / verify the chunking output of a
specific document.`
const chunkListExample = ` weknora chunk list --doc doc_abc
weknora chunk list --doc doc_abc --all-pages --page-size 100
weknora chunk list --doc doc_abc --format json | jq '.[] | {id, chunk_index}'`
const chunkListExample = ` academy chunk list --doc doc_abc
academy chunk list --doc doc_abc --all-pages --page-size 100
academy chunk list --doc doc_abc --format json | jq '.[] | {id, chunk_index}'`
// NewCmdList builds `weknora chunk list --doc <doc-id>`.
// NewCmdList builds `academy chunk list --doc <doc-id>`.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{}
cmd := &cobra.Command{
@@ -114,7 +114,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List chunks of a specific document in stored order (admin/debug). Results come with meta.count; use --limit (1..10000) and --all-pages to paginate. Prefer 'search chunks' for RAG retrieval.",
RequiredFlags: []string{"--doc"},
Examples: []string{"weknora chunk list --doc doc_abc --format json", "weknora chunk list --doc doc_abc --all-pages --format json"},
Examples: []string{"academy chunk list --doc doc_abc --format json", "academy chunk list --doc doc_abc --all-pages --format json"},
Output: "envelope.data is an array of Chunk objects with id, chunk_index, content, is_enabled; meta.count is the returned count, meta.total_count the document's full chunk count, meta.has_more true when --limit truncated",
})
return cmd
+3 -3
View File
@@ -9,9 +9,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type listCall struct {
+9 -9
View File
@@ -7,9 +7,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// chunkViewFields enumerates the 23 SDK Chunk fields surfaced for `--format json`
@@ -37,7 +37,7 @@ const chunkViewLong = `Show a single chunk with all SDK fields.
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
less or use --format json for large chunks. Academy chunks are typically bounded
by the ingest pipeline (~1000 tokens / a few KB), so unconditional full
rendering is reasonable.
@@ -53,11 +53,11 @@ invoke citation) is sufficient for view.
Typed exit codes:
resource.not_found no chunk with the given id (exit 4)`
const chunkViewExample = ` weknora chunk view chunk_abc
weknora chunk view chunk_abc --format json | jq '.content'
weknora chunk view chunk_abc --format json --jq '{id, chunk_index, is_enabled}'`
const chunkViewExample = ` academy chunk view chunk_abc
academy chunk view chunk_abc --format json | jq '.content'
academy chunk view chunk_abc --format json --jq '{id, chunk_index, is_enabled}'`
// NewCmdView builds `weknora chunk view <chunk-id>`.
// NewCmdView builds `academy chunk view <chunk-id>`.
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
opts := &ViewOptions{}
cmd := &cobra.Command{
@@ -85,7 +85,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "fetch one chunk's fields and content by id (scope-less; no --doc needed)",
RequiredFlags: []string{"<chunk-id> (positional)"},
Examples: []string{"weknora chunk view chunk_abc"},
Examples: []string{"academy chunk view chunk_abc"},
Output: "envelope.data is the chunk object (id, content, knowledge_id, ...)",
})
return cmd
+3 -3
View File
@@ -9,9 +9,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type fakeViewSvc struct {
+2 -2
View File
@@ -5,7 +5,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
// TestCompletion_AllShells smoke-tests cobra's auto-registered completion
@@ -21,7 +21,7 @@ func TestCompletion_AllShells(t *testing.T) {
}{
{"bash", "bash completion", 1024},
{"zsh", "#compdef", 1024},
{"fish", "complete -c weknora", 1024},
{"fish", "complete -c academy", 1024},
{"powershell", "Register-ArgumentCompleter", 1024},
}
for _, tc := range cases {
+3 -3
View File
@@ -1,4 +1,4 @@
// Package configcmd holds the `weknora config` command tree.
// Package configcmd holds the `academy config` command tree.
//
// Currently a single read-only `view` subcommand that prints the resolved
// CLI configuration and its resolution chain. No mutation, no network.
@@ -11,10 +11,10 @@ package configcmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
// NewCmd builds the `weknora config` parent command.
// NewCmd builds the `academy config` parent command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
+24 -24
View File
@@ -8,13 +8,13 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"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/projectlink"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"github.com/Tencent/WeKnora/cli/internal/xdg"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/format"
"academy/cli/internal/iostreams"
"academy/cli/internal/projectlink"
"academy/cli/internal/secrets"
"academy/cli/internal/xdg"
)
// viewFields enumerates the fields surfaced for `--format json` discovery on
@@ -46,7 +46,7 @@ type viewData struct {
ProjectLink string `json:"project_link"`
}
// NewCmdView builds `weknora config view`. Read-only inspection of the
// NewCmdView builds `academy config view`. Read-only inspection of the
// resolved config and resolution chain. Never builds the SDK client and
// never issues a network request: KB resolution uses ResolveKBLocal, secrets
// storage is detected from the store type, and everything else is read from
@@ -77,11 +77,11 @@ even when no profile or KB is configured (sources report "(none)" /
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "inspect the resolved CLI config and resolution chain (active profile, host, kb, log level, default format, file paths) without mutating or hitting the network",
Examples: []string{
"weknora config view",
"weknora config view --format json",
"weknora config view --jq '.data.active_profile'",
"academy config view",
"academy config view --format json",
"academy config view --jq '.data.active_profile'",
},
Output: "envelope.data is {active_profile, profile_source, auth_source, host, kb_id, kb_source, log_level, log_level_source, format_default, config_file, cache_dir, secrets, project_link}. auth_source reports whether the active credential is the profile+keyring or a stateless WEKNORA_TOKEN/WEKNORA_API_KEY env override.",
Output: "envelope.data is {active_profile, profile_source, auth_source, host, kb_id, kb_source, log_level, log_level_source, format_default, config_file, cache_dir, secrets, project_link}. auth_source reports whether the active credential is the profile+keyring or a stateless ACADEMY_TOKEN/ACADEMY_API_KEY env override.",
})
return cmd
}
@@ -129,14 +129,14 @@ func resolveView(cmd *cobra.Command, f *cmdutil.Factory) viewData {
}
}
// Auth source: stateless env credentials (WEKNORA_TOKEN/WEKNORA_API_KEY)
// Auth source: stateless env credentials (ACADEMY_TOKEN/ACADEMY_API_KEY)
// override the profile + keyring for the actual client, so report that —
// otherwise host/profile above would silently describe a profile the env
// credential bypassed. WEKNORA_HOST (when set) is the host that env cred
// credential bypassed. ACADEMY_HOST (when set) is the host that env cred
// authenticates against.
if active, kind := cmdutil.EnvCredential(); active {
d.AuthSource = kind + " env (stateless; bypasses profile + keyring)"
if h := strings.TrimSpace(os.Getenv("WEKNORA_HOST")); h != "" {
if h := strings.TrimSpace(os.Getenv("ACADEMY_HOST")); h != "" {
d.Host = h
}
} else if d.ActiveProfile != "" {
@@ -173,8 +173,8 @@ func resolveProfile(f *cmdutil.Factory) (name, source string) {
if f.ProfileOverride != "" {
return f.ProfileOverride, "--profile flag"
}
if v := os.Getenv("WEKNORA_PROFILE"); v != "" {
return v, "WEKNORA_PROFILE env"
if v := os.Getenv("ACADEMY_PROFILE"); v != "" {
return v, "ACADEMY_PROFILE env"
}
if f.Config != nil {
if cfg, err := f.Config(); err == nil && cfg != nil && cfg.CurrentProfile != "" {
@@ -196,8 +196,8 @@ func resolveKB(cmd *cobra.Command, f *cmdutil.Factory) (id, source string) {
if v, _ := cmd.Flags().GetString("kb"); v != "" {
return id, "--kb flag"
}
if v := os.Getenv("WEKNORA_KB_ID"); v != "" {
return id, "WEKNORA_KB_ID env"
if v := os.Getenv("ACADEMY_KB_ID"); v != "" {
return id, "ACADEMY_KB_ID env"
}
if cwd, werr := os.Getwd(); werr == nil {
if path, found, derr := projectlink.Discover(cwd); derr == nil && found {
@@ -216,14 +216,14 @@ func resolveLogLevel(cmd *cobra.Command) (level, source string) {
return level, "--log-level flag"
}
}
if v := os.Getenv("WEKNORA_LOG_LEVEL"); v != "" && cmdutil.IsValidLogLevel(v) {
return level, "WEKNORA_LOG_LEVEL env"
if v := os.Getenv("ACADEMY_LOG_LEVEL"); v != "" && cmdutil.IsValidLogLevel(v) {
return level, "ACADEMY_LOG_LEVEL env"
}
return level, "default"
}
// resolveFormatDefault reports the configured default output format: the
// config.yaml defaults.format value, else WEKNORA_FORMAT, else the hard
// config.yaml defaults.format value, else ACADEMY_FORMAT, else the hard
// default. This is the *default* used when --format is unset — not the
// per-invocation --format flag value.
func resolveFormatDefault() string {
@@ -231,7 +231,7 @@ func resolveFormatDefault() string {
if err == nil && cfg != nil && cfg.Defaults.Format != "" {
return cfg.Defaults.Format
}
if v := os.Getenv("WEKNORA_FORMAT"); v == "text" || v == "json" || v == "ndjson" {
if v := os.Getenv("ACADEMY_FORMAT"); v == "text" || v == "json" || v == "ndjson" {
return v
}
return string(cmdutil.DefaultFormatMode)
@@ -261,7 +261,7 @@ func resolveSecrets(f *cmdutil.Factory) string {
return "file"
}
// resolveProjectLink reports the discovered .weknora/project.yaml path or
// resolveProjectLink reports the discovered .academy/project.yaml path or
// "(none)". Walks up from cwd like ResolveKBLocal does.
func resolveProjectLink() string {
cwd, err := os.Getwd()
+8 -8
View File
@@ -7,10 +7,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type viewEnvelope struct {
@@ -101,7 +101,7 @@ func networkFreeFactory(t *testing.T) *cmdutil.Factory {
return f
}
// TestConfigView_EnvCredentialSurfaced: when WEKNORA_API_KEY + WEKNORA_HOST are
// TestConfigView_EnvCredentialSurfaced: when ACADEMY_API_KEY + ACADEMY_HOST are
// set, config view reports the env override (auth_source + the env host), not
// the bypassed config profile's host.
func TestConfigView_EnvCredentialSurfaced(t *testing.T) {
@@ -111,10 +111,10 @@ func TestConfigView_EnvCredentialSurfaced(t *testing.T) {
Profiles: map[string]config.Profile{"prod": {Host: "https://configured.example.com"}},
}
require.NoError(t, config.Save(cfg))
t.Setenv("WEKNORA_API_KEY", "sk-test")
t.Setenv("WEKNORA_HOST", "https://env-override.example.com")
t.Setenv("ACADEMY_API_KEY", "sk-test")
t.Setenv("ACADEMY_HOST", "https://env-override.example.com")
env := runViewJSON(t, networkFreeFactory(t))
assert.Contains(t, env.Data.AuthSource, "WEKNORA_API_KEY env")
assert.Contains(t, env.Data.AuthSource, "ACADEMY_API_KEY env")
assert.Equal(t, "https://env-override.example.com", env.Data.Host, "host must be the env override, not the profile host")
}
+15 -15
View File
@@ -1,4 +1,4 @@
// Package doc — create.go implements `weknora doc create --text "..."`.
// Package doc — create.go implements `academy doc create --text "..."`.
// Allows creating a knowledge entry directly from inline text content without
// uploading a file or fetching a remote URL.
package doc
@@ -10,10 +10,10 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
sdk "academy/client"
)
// docCreateFields enumerates the fields surfaced for `--format json` discovery
@@ -43,7 +43,7 @@ type CreateService interface {
) (*sdk.Knowledge, error)
}
// NewCmdCreate builds `weknora doc create --text "..."`.
// NewCmdCreate builds `academy doc create --text "..."`.
func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts := &CreateOptions{}
cmd := &cobra.Command{
@@ -52,15 +52,15 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
Long: `Create a new knowledge entry by passing Markdown content directly via --text.
Useful for short snippets, agent-generated content, or structured notes that
don't require a file upload or remote URL. KB resolution follows the standard
4-level chain: --kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error.
4-level chain: --kb flag > ACADEMY_KB_ID env > .academy/project.yaml > error.
--text <content> Document text in Markdown format (required).
--title <title> Display title stored with the entry (matches doc update --title).
--tag-id <id> Associate the new entry with a tag.
--channel <name> Override the ingestion-channel tag (default "api").`,
Example: ` weknora doc create --text "# Meeting Notes\n\nAction items: ..."
weknora doc create --text "$(cat notes.md)" --title "Sprint Notes" --kb my-kb
weknora doc create --text "API usage guide" --title "API Guide" --tag-id tag_abc`,
Example: ` academy doc create --text "# Meeting Notes\n\nAction items: ..."
academy doc create --text "$(cat notes.md)" --title "Sprint Notes" --kb my-kb
academy doc create --text "API usage guide" --title "API Guide" --tag-id tag_abc`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -108,11 +108,11 @@ don't require a file upload or remote URL. KB resolution follows the standard
cmdutil.AddFormatFlag(cmd, docCreateFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Create a knowledge entry from inline Markdown text. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"--text", "--kb (or WEKNORA_KB_ID / project link)"},
UsedFor: "Create a knowledge entry from inline Markdown text. KB resolved via --kb flag, ACADEMY_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"--text", "--kb (or ACADEMY_KB_ID / project link)"},
Examples: []string{
`weknora doc create --kb kb_eng --text "# Runbook\n\nRestart steps: ..."`,
`weknora doc create --kb kb_eng --text "$(cat notes.md)" --title "Sprint Notes"`,
`academy doc create --kb kb_eng --text "# Runbook\n\nRestart steps: ..."`,
`academy doc create --kb kb_eng --text "$(cat notes.md)" --title "Sprint Notes"`,
},
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, title, parse_status",
})
@@ -143,7 +143,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
// timeout or `search` into empty results.
var meta *output.Meta
if k.ParseStatus == "draft" {
meta = &output.Meta{Hint: "document created in parse_status=draft (not yet indexed) — run `weknora doc reparse " + k.ID + "` to parse & make it searchable"}
meta = &output.Meta{Hint: "document created in parse_status=draft (not yet indexed) — run `academy doc reparse " + k.ID + "` to parse & make it searchable"}
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, k, meta)
+5 -5
View File
@@ -10,9 +10,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// fakeCreateSvc captures call arguments and returns canned responses.
@@ -151,12 +151,12 @@ func TestCreate_EmptyText_RejectsBeforeSDK(t *testing.T) {
assert.Nil(t, svc.got.req, "SDK must not be called when --text is empty")
}
// TestCreate_AgentHelp_EmitsUsedFor verifies that when WEKNORA_AGENT_HELP=1
// TestCreate_AgentHelp_EmitsUsedFor verifies that when ACADEMY_AGENT_HELP=1
// the `doc create --help` path emits a JSON blob containing "used_for".
// This is the representative test for 3.2; the mechanism is covered by
// internal/cmdutil/agenthelp_test.go — we test the wiring here.
func TestCreate_AgentHelp_EmitsUsedFor(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
t.Setenv("ACADEMY_AGENT_HELP", "1")
_, _ = iostreams.SetForTest(t)
f := &cmdutil.Factory{}
+19 -19
View File
@@ -6,11 +6,11 @@ import (
"github.com/spf13/cobra"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
)
// docDeleteFields enumerates the fields surfaced for `--format json` discovery
@@ -42,7 +42,7 @@ type deleteResult struct {
Deleted bool `json:"deleted"`
}
// NewCmdDelete builds `weknora doc delete`. Single-id keeps the simpler
// NewCmdDelete builds `academy doc delete`. Single-id keeps the simpler
// code path (one confirm prompt, exit 0/1); multi-id uses keep-going
// semantics (one -y confirms all, failures collected, exit 1 if any fail);
// --all --kb=<id> atomically clears every document in a knowledge base.
@@ -71,13 +71,13 @@ All-in-KB (--all --kb=<kb-id>):
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
and writes input.confirmation_required to stderr. NEVER auto-pass -y
without the user's explicit go-ahead.`,
Example: ` weknora doc delete doc_abc # interactive confirm
weknora doc delete doc_abc -y # no prompt
weknora doc delete doc_abc -y --format json # bare {id, deleted:true} JSON
weknora doc delete doc_a doc_b doc_c -y # delete 3, keep-going
weknora doc delete doc_a doc_b --format json # multi-id JSON output
weknora doc delete --all --kb=kb_x -y # clear all docs in kb_x
weknora doc delete --all --kb=kb_x -y --format json # agent-friendly`,
Example: ` academy doc delete doc_abc # interactive confirm
academy doc delete doc_abc -y # no prompt
academy doc delete doc_abc -y --format json # bare {id, deleted:true} JSON
academy doc delete doc_a doc_b doc_c -y # delete 3, keep-going
academy doc delete doc_a doc_b --format json # multi-id JSON output
academy doc delete --all --kb=kb_x -y # clear all docs in kb_x
academy doc delete --all --kb=kb_x -y --format json # agent-friendly`,
Args: cobra.ArbitraryArgs,
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -94,7 +94,7 @@ without the user's explicit go-ahead.`,
if opts.KB == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "--all requires --kb=<id>").
WithHint("specify --kb=<uuid-or-name> to scope the delete-all operation").
WithRetryArgv([]string{"weknora", "doc", "delete", "--all", "--kb=<kb-id>", "-y"})
WithRetryArgv([]string{"academy", "doc", "delete", "--all", "--kb=<kb-id>", "-y"})
}
if len(args) > 0 {
return cmdutil.NewFlagError(fmt.Errorf("--all is exclusive with positional doc ids"))
@@ -137,7 +137,7 @@ without the user's explicit go-ahead.`,
if len(args) == 1 {
return runDelete(c.Context(), opts, fopts, cli, f.Prompter(), args[0])
}
batchRetry := append([]string{"weknora", "doc", "delete"}, args...)
batchRetry := append([]string{"academy", "doc", "delete"}, args...)
batchRetry = append(batchRetry, "-y")
if err := cmdutil.ConfirmDestructiveBatch(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "document", len(args), "doc.delete", batchRetry); err != nil {
return err
@@ -168,9 +168,9 @@ without the user's explicit go-ahead.`,
UsedFor: "permanently delete one or more documents from a knowledge base",
RequiredFlags: []string{"<doc-id>... (positional) | --all --kb=<uuid-or-name>"},
Examples: []string{
"weknora doc delete doc_abc -y",
"weknora doc delete doc_a doc_b doc_c -y",
"weknora doc delete --all --kb=kb_x -y --format json",
"academy doc delete doc_abc -y",
"academy doc delete doc_a doc_b doc_c -y",
"academy doc delete --all --kb=kb_x -y --format json",
},
Output: "envelope.data shape depends on the form: a single doc id -> {id, deleted:true}; multiple doc ids -> batch envelope (top-level status success|partial|error, ok=(failures==0), data per-item [{id, ok, error?}], meta.successes/failures — read data[].ok per id, ok:true overall does not survive a partial failure / exit 1); --all --kb -> {kb_id, deleted_count}.",
Warnings: []string{
@@ -183,7 +183,7 @@ without the user's explicit go-ahead.`,
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "document", id, "doc.delete", []string{"weknora", "doc", "delete", id, "-y"}); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "document", id, "doc.delete", []string{"academy", "doc", "delete", id, "-y"}); err != nil {
return err
}
@@ -203,7 +203,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOp
// CodeInputConfirmationRequired (exit 10) with risk metadata so agents can
// surface the risk to the user before re-invoking with -y.
func runDeleteAll(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc AllService, p prompt.Prompter) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "all docs in KB", opts.KB, "doc.delete_all", []string{"weknora", "doc", "delete", "--all", "--kb=" + opts.KB, "-y"}); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "all docs in KB", opts.KB, "doc.delete_all", []string{"academy", "doc", "delete", "--all", "--kb=" + opts.KB, "-y"}); err != nil {
return err
}
+6 -6
View File
@@ -13,13 +13,13 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/testutil"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
"academy/cli/internal/testutil"
)
// fakeAllSvc implements AllService for --all mode tests.
+3 -3
View File
@@ -1,4 +1,4 @@
// Package doc implements the `weknora doc` subtree (list / view / upload /
// Package doc implements the `academy doc` subtree (list / view / upload /
// fetch / create / download / delete / wait). Upload supports --recursive /
// --glob for bulk ingestion from local files. Fetch ingests a remote URL.
// Create adds a knowledge entry from inline text content.
@@ -12,10 +12,10 @@ package doc
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
// NewCmd builds the `weknora doc` parent command.
// NewCmd builds the `academy doc` parent command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "doc",
+10 -10
View File
@@ -10,8 +10,8 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
)
// downloadFields enumerates the fields surfaced for `--format json` discovery on
@@ -38,7 +38,7 @@ type DownloadService interface {
OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error)
}
// NewCmdDownload builds `weknora doc download <id>`. Positional id, output
// NewCmdDownload builds `academy doc download <id>`. Positional id, output
// flag, `-` sentinel for stdout. Flags: `-O, --output <file>` for
// destination, `--clobber` for overwrite control.
func NewCmdDownload(f *cmdutil.Factory) *cobra.Command {
@@ -58,11 +58,11 @@ With --format json, on success emits a JSON envelope whose data has
path, bytes, and filename fields. When output is stdout (--output -),
the JSON envelope is suppressed because the raw bytes already occupy
stdout.`,
Example: ` weknora doc download doc_abc # writes ./<server-name>
weknora doc download doc_abc -O report.pdf
weknora doc download doc_abc --output - # stream to stdout (binary safe)
weknora doc download doc_abc -O report.pdf --clobber
weknora doc download doc_abc -O report.pdf --format json # JSON envelope`,
Example: ` academy doc download doc_abc # writes ./<server-name>
academy doc download doc_abc -O report.pdf
academy doc download doc_abc --output - # stream to stdout (binary safe)
academy doc download doc_abc -O report.pdf --clobber
academy doc download doc_abc -O report.pdf --format json # JSON envelope`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -86,8 +86,8 @@ stdout.`,
RequiredFlags: []string{"<doc-id> (positional)"},
Output: "with --format json (file output): envelope.data has path, bytes, filename; suppressed with --output - (raw bytes to stdout)",
Examples: []string{
"weknora doc download doc_abc --output ./manual.pdf",
"weknora doc download doc_abc --output - > manual.pdf",
"academy doc download doc_abc --output ./manual.pdf",
"academy doc download doc_abc --output - > manual.pdf",
},
})
return cmd
+2 -2
View File
@@ -13,8 +13,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
)
// fakeDownloadSvc scripts an OpenKnowledgeFile response. The fake returns
+5 -5
View File
@@ -15,10 +15,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
sdk "academy/client"
)
// docDryRunFactory builds a Factory whose Client closure panics if invoked —
@@ -43,7 +43,7 @@ func docDryRunFactory(t *testing.T) *cmdutil.Factory {
// registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go).
func withRootHarnessDoc(sub *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
root := &cobra.Command{Use: "academy"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
+13 -13
View File
@@ -1,4 +1,4 @@
// Package doc — fetch.go implements `weknora doc fetch <url>`.
// Package doc — fetch.go implements `academy doc fetch <url>`.
package doc
import (
@@ -8,9 +8,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// docFetchFields enumerates the fields surfaced for `--format json` discovery
@@ -45,7 +45,7 @@ type FetchService interface {
) (*sdk.Knowledge, error)
}
// NewCmdFetch builds `weknora doc fetch <url>`.
// NewCmdFetch builds `academy doc fetch <url>`.
func NewCmdFetch(f *cmdutil.Factory) *cobra.Command {
opts := &FetchOptions{}
cmd := &cobra.Command{
@@ -53,7 +53,7 @@ func NewCmdFetch(f *cmdutil.Factory) *cobra.Command {
Short: "Fetch a remote document into a knowledge base",
Long: `Server fetches the document at the given URL and ingests it into the resolved
knowledge base. KB resolution follows the standard 4-level chain:
--kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error.
--kb flag > ACADEMY_KB_ID env > .academy/project.yaml > error.
When the URL has a known file extension (.pdf, .docx, .md, .txt) the server
automatically switches from web-page-crawl mode to file-download mode. Pass
@@ -71,10 +71,10 @@ Server-side ingestion knobs:
--enable-multimodel Toggle multimodal extraction (image-in-PDF → text).
Unset ⇒ server default; pass true or false to override.
--channel <name> Override the ingestion-channel tag (default "api").`,
Example: ` weknora doc fetch https://example.com/whitepaper.pdf
weknora doc fetch https://example.com/no-ext --file-type pdf --title "Whitepaper"
weknora doc fetch https://example.com/article.html --name "Q3 Article" --tag-id tag_abc
weknora doc fetch https://example.com/report.pdf --kb my-kb --enable-multimodel`,
Example: ` academy doc fetch https://example.com/whitepaper.pdf
academy doc fetch https://example.com/no-ext --file-type pdf --title "Whitepaper"
academy doc fetch https://example.com/article.html --name "Q3 Article" --tag-id tag_abc
academy doc fetch https://example.com/report.pdf --kb my-kb --enable-multimodel`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.URL = args[0]
@@ -135,10 +135,10 @@ Server-side ingestion knobs:
cmdutil.AddFormatFlag(cmd, docFetchFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Ingest a remote URL into the resolved knowledge base. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"<url> (positional)", "--kb (or WEKNORA_KB_ID / project link)"},
UsedFor: "Ingest a remote URL into the resolved knowledge base. KB resolved via --kb flag, ACADEMY_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"<url> (positional)", "--kb (or ACADEMY_KB_ID / project link)"},
Examples: []string{
`weknora doc fetch https://example.com/whitepaper.pdf --kb kb_eng`,
`academy doc fetch https://example.com/whitepaper.pdf --kb kb_eng`,
},
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, source, parse_status",
})
+3 -3
View File
@@ -9,9 +9,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// fakeFetchSvc captures call arguments and returns canned responses.
+13 -13
View File
@@ -9,11 +9,11 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
"academy/cli/internal/text"
sdk "academy/client"
)
// docListFields enumerates the fields surfaced for `--format json` discovery on
@@ -58,7 +58,7 @@ type ListService interface {
ListKnowledgeWithFilter(ctx context.Context, kbID string, page, pageSize int, filter sdk.KnowledgeListFilter) ([]sdk.Knowledge, int64, error)
}
// NewCmdList builds `weknora doc list`.
// NewCmdList builds `academy doc list`.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{}
cmd := &cobra.Command{
@@ -66,15 +66,15 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
Short: "List documents in a knowledge base",
Long: `Lists documents (uploaded files / web pages / inline text) in the
resolved knowledge base. KB resolution follows the standard 4-level chain:
--kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error. The --kb
--kb flag > ACADEMY_KB_ID env > .academy/project.yaml > error. The --kb
flag accepts either a KB UUID (passed through) or a name (resolved via list).
Default sort is updated_at desc so the most recent uploads surface first;
backend storage order is not guaranteed and varies between deployments.`,
Example: ` weknora doc list # uses project link / env
weknora doc list --kb a32a63ff-fb36-4874-bcaa-30f48570a694 # explicit UUID
weknora doc list --kb my-kb # resolved by name
weknora doc list --all-pages --format json # walk every page`,
Example: ` academy doc list # uses project link / env
academy doc list --kb a32a63ff-fb36-4874-bcaa-30f48570a694 # explicit UUID
academy doc list --kb my-kb # resolved by name
academy doc list --all-pages --format json # walk every page`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -115,7 +115,7 @@ backend storage order is not guaranteed and varies between deployments.`,
cmdutil.AddFormatFlag(cmd, docListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List documents in the resolved knowledge base. Results come with meta.count; use --limit to cap, --all-pages to walk every server page, --status/--keyword to filter server-side.",
Examples: []string{"weknora doc list --format json", "weknora doc list --all-pages --limit 200 --format json"},
Examples: []string{"academy doc list --format json", "academy doc list --all-pages --limit 200 --format json"},
Output: "envelope.data is an array of Knowledge objects with id, title, file_name, parse_status; meta.count is the returned count; meta.total_count is the server-side total before client-side --limit truncation; meta.has_more=true when --limit truncated",
})
return cmd
@@ -209,7 +209,7 @@ func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOption
}
// Default sort: updated_at desc. Server return order is not guaranteed,
// so client-side sort makes output deterministic regardless of backend
// storage choices. Mirrors `weknora kb list`.
// storage choices. Mirrors `academy kb list`.
sort.Slice(items, func(i, j int) bool {
return items[i].UpdatedAt.After(items[j].UpdatedAt)
})
+3 -3
View File
@@ -8,9 +8,9 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
+7 -7
View File
@@ -13,10 +13,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// fakeListSvc captures the request args and returns canned responses.
@@ -38,7 +38,7 @@ func (f *fakeListSvc) ListKnowledgeWithFilter(_ context.Context, kbID string, pa
}
// chdirIsolated parks cwd in a fresh tempdir so Factory.ResolveKB doesn't pick
// up a stray .weknora/project.yaml from the repo. Also clears WEKNORA_KB_ID
// up a stray .academy/project.yaml from the repo. Also clears ACADEMY_KB_ID
// for the duration of the test.
func chdirIsolated(t *testing.T) {
t.Helper()
@@ -46,7 +46,7 @@ func chdirIsolated(t *testing.T) {
require.NoError(t, err)
require.NoError(t, os.Chdir(t.TempDir()))
t.Cleanup(func() { _ = os.Chdir(prev) })
t.Setenv("WEKNORA_KB_ID", "")
t.Setenv("ACADEMY_KB_ID", "")
}
func TestList_Success_Text(t *testing.T) {
@@ -127,7 +127,7 @@ func TestList_HTTPError_500(t *testing.T) {
// TestList_KBIDRequired drives the cobra layer to verify Factory.ResolveKB's
// "no source supplied" path bubbles up as CodeKBIDRequired. Isolates cwd so
// no project.yaml sneaks in, and clears WEKNORA_KB_ID.
// no project.yaml sneaks in, and clears ACADEMY_KB_ID.
func TestList_KBIDRequired(t *testing.T) {
chdirIsolated(t)
_, _ = iostreams.SetForTest(t)
+10 -10
View File
@@ -6,10 +6,10 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/text"
sdk "academy/client"
)
// docReparseFields enumerates the fields surfaced for `--format json` discovery
@@ -27,7 +27,7 @@ type ReparseService interface {
ReparseKnowledge(ctx context.Context, id string) (*sdk.Knowledge, error)
}
// NewCmdReparse builds `weknora doc reparse <doc-id>`.
// NewCmdReparse builds `academy doc reparse <doc-id>`.
func NewCmdReparse(f *cmdutil.Factory) *cobra.Command {
opts := &ReparseOptions{}
cmd := &cobra.Command{
@@ -36,7 +36,7 @@ func NewCmdReparse(f *cmdutil.Factory) *cobra.Command {
Long: `Re-trigger server-side parsing of a document — the recovery path when a
document's parse_status is failed, or after its source changed. The document
keeps its id; parsing restarts asynchronously, so follow with
'weknora doc wait <doc-id>' to block until it reaches a terminal status.`,
'academy doc wait <doc-id>' to block until it reaches a terminal status.`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -64,10 +64,10 @@ keeps its id; parsing restarts asynchronously, so follow with
UsedFor: "re-run parsing on a document (recovery after parse_status=failed, or a changed source)",
RequiredFlags: []string{"<doc-id> (positional)"},
Examples: []string{
"weknora doc reparse doc_abc",
"weknora doc reparse doc_abc --format json",
"academy doc reparse doc_abc",
"academy doc reparse doc_abc --format json",
},
Output: "envelope.data is the Knowledge object with parse_status reset to the re-processing state; poll `weknora doc wait <doc-id>` for completion",
Output: "envelope.data is the Knowledge object with parse_status reset to the re-processing state; poll `academy doc wait <doc-id>` for completion",
})
return cmd
}
@@ -91,6 +91,6 @@ func runReparse(ctx context.Context, opts *ReparseOptions, fopts *cmdutil.Format
if k.ParseStatus != "" {
fmt.Fprintf(w, " parse_status: %s\n", k.ParseStatus)
}
fmt.Fprintf(w, " next: weknora doc wait %s\n", id)
fmt.Fprintf(w, " next: academy doc wait %s\n", id)
return nil
}
+3 -3
View File
@@ -9,9 +9,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type fakeReparseSvc struct {
+7 -7
View File
@@ -6,9 +6,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// docUpdateFields enumerates the fields surfaced for `--format json` discovery
@@ -34,7 +34,7 @@ type UpdateService interface {
UpdateKnowledge(ctx context.Context, k *sdk.Knowledge) error
}
// NewCmdUpdate builds `weknora doc update <doc-id>`. At least one of
// NewCmdUpdate builds `academy doc update <doc-id>`. At least one of
// --title / --description must be provided.
func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command {
opts := &UpdateOptions{}
@@ -89,7 +89,7 @@ to the user first.`,
}
// Build a retry command from the flags the user actually passed so
// agents can re-invoke with -y after explicit human approval.
retryCmd := cmdutil.BuildRetryArgv(c, []string{"weknora", "doc", "update", id}, "title", "description", "format")
retryCmd := cmdutil.BuildRetryArgv(c, []string{"academy", "doc", "update", id}, "title", "description", "format")
if err := cmdutil.ConfirmWrite(f.Prompter(), opts.Yes, fopts.WantsJSON(), "update", "document", id, "doc.update", retryCmd); err != nil {
return err
}
@@ -106,8 +106,8 @@ to the user first.`,
UsedFor: "update a document's title or description (content is not editable — re-upload for that)",
RequiredFlags: []string{"<doc-id> (positional)", "--title or --description (at least one)"},
Examples: []string{
`weknora doc update doc_abc --title "Q3 Runbook" -y`,
`weknora doc update doc_abc --description "archived" --format json -y`,
`academy doc update doc_abc --title "Q3 Runbook" -y`,
`academy doc update doc_abc --description "archived" --format json -y`,
},
Output: "envelope.data is the Knowledge object with the new title/description",
Warnings: []string{
+4 -4
View File
@@ -9,10 +9,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
sdk "academy/client"
)
type fakeUpdateSvc struct {
+18 -18
View File
@@ -10,9 +10,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// uploadChannel is the default ingestion-channel tag the server records for
@@ -66,7 +66,7 @@ type UploadService interface {
) (*sdk.Knowledge, error)
}
// NewCmdUpload builds `weknora doc upload <file>`.
// NewCmdUpload builds `academy doc upload <file>`.
func NewCmdUpload(f *cmdutil.Factory) *cobra.Command {
opts := &UploadOptions{}
cmd := &cobra.Command{
@@ -74,7 +74,7 @@ func NewCmdUpload(f *cmdutil.Factory) *cobra.Command {
Short: "Upload a local file to the knowledge base",
Long: `Uploads a file (PDF / DOCX / Markdown / TXT / etc.) to the resolved
knowledge base. KB resolution follows the standard 4-level chain:
--kb flag > WEKNORA_KB_ID env > .weknora/project.yaml > error. The --kb
--kb flag > ACADEMY_KB_ID env > .academy/project.yaml > error. The --kb
flag accepts either a KB UUID (passed through) or a name (resolved via list).
Pass --name to override the recorded file name (useful when the local file
@@ -85,8 +85,8 @@ The two input modes (positional file / --recursive directory walk) are
mutually exclusive - pass exactly one. Use --recursive --glob to upload a
directory tree (see Examples); subdirectories are preserved as knowledge-base
folders, so a nested file lands at its path relative to the walked directory.
To ingest a remote URL use "weknora doc fetch";
to create an entry from inline text use "weknora doc create".
To ingest a remote URL use "academy doc fetch";
to create an entry from inline text use "academy doc create".
Server-side ingestion knobs:
@@ -99,12 +99,12 @@ Server-side ingestion knobs:
input.invalid_argument.
--channel <name> Override the ingestion-channel tag (default "api").
Applies to file / --recursive.`,
Example: ` weknora doc upload report.pdf
weknora doc upload notes.md --kb a32a63ff-fb36-4874-bcaa-30f48570a694
weknora doc upload notes.md --kb my-kb
weknora doc upload q3.pdf --name "Q3 Marketing Report.pdf"
weknora doc upload report.pdf --enable-multimodel --metadata team=alpha --metadata sprint=Q4
weknora doc upload ./docs --recursive --glob '*.pdf' --metadata team=alpha`,
Example: ` academy doc upload report.pdf
academy doc upload notes.md --kb a32a63ff-fb36-4874-bcaa-30f48570a694
academy doc upload notes.md --kb my-kb
academy doc upload q3.pdf --name "Q3 Marketing Report.pdf"
academy doc upload report.pdf --enable-multimodel --metadata team=alpha --metadata sprint=Q4
academy doc upload ./docs --recursive --glob '*.pdf' --metadata team=alpha`,
Args: cobra.MaximumNArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -192,11 +192,11 @@ Server-side ingestion knobs:
cmdutil.AddFormatFlag(cmd, docUploadFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Upload a local file to the resolved knowledge base. KB resolved via --kb flag, WEKNORA_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"<file> (positional)", "--kb (or WEKNORA_KB_ID / project link)"},
UsedFor: "Upload a local file to the resolved knowledge base. KB resolved via --kb flag, ACADEMY_KB_ID env, or project link. Emits the created Knowledge object with its id.",
RequiredFlags: []string{"<file> (positional)", "--kb (or ACADEMY_KB_ID / project link)"},
Examples: []string{
`weknora doc upload report.pdf --kb kb_eng`,
`weknora doc upload report.pdf --kb kb_eng --jq .data.id # then: doc wait <id>`,
`academy doc upload report.pdf --kb kb_eng`,
`academy doc upload report.pdf --kb kb_eng --jq .data.id # then: doc wait <id>`,
},
Output: "envelope.data is the created Knowledge object with id, knowledge_base_id, file_name, parse_status",
})
@@ -250,7 +250,7 @@ func validateUploadFlags(opts *UploadOptions, args []string) error {
// MinimumNArgs(1) would emit — consistent with every other command
// that requires a positional argument.
return cmdutil.NewFlagError(errors.New(
"a file path is required (or use `weknora doc fetch` for URLs, `weknora doc create` for inline text)"))
"a file path is required (or use `academy doc fetch` for URLs, `academy doc create` for inline text)"))
}
return nil
}
+3 -3
View File
@@ -9,9 +9,9 @@ import (
"path/filepath"
"strings"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
)
// uploadedFile holds the server-side result for a successful per-file upload.
+3 -3
View File
@@ -13,9 +13,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// scriptedUploadSvc records every CreateKnowledgeFromFile call and returns
+3 -3
View File
@@ -12,9 +12,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// fakeUploadSvc captures call arguments and returns canned responses.
+8 -8
View File
@@ -6,10 +6,10 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/text"
sdk "academy/client"
)
// docViewFields enumerates the fields surfaced for `--format json` discovery on
@@ -29,14 +29,14 @@ type ViewService interface {
GetKnowledge(ctx context.Context, id string) (*sdk.Knowledge, error)
}
// NewCmdView builds `weknora doc view <id>`.
// NewCmdView builds `academy doc view <id>`.
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
opts := &ViewOptions{}
cmd := &cobra.Command{
Use: "view <doc-id>",
Short: "Show a document by ID",
Example: ` weknora doc view doc_abc
weknora doc view doc_abc --format json`,
Example: ` academy doc view doc_abc
academy doc view doc_abc --format json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -56,7 +56,7 @@ func NewCmdView(f *cmdutil.Factory) *cobra.Command {
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "fetch one document's metadata by id",
RequiredFlags: []string{"<doc-id> (positional)"},
Examples: []string{"weknora doc view doc_abc", "weknora doc view doc_abc --jq .data.parse_status"},
Examples: []string{"academy doc view doc_abc", "academy doc view doc_abc --jq .data.parse_status"},
Output: "envelope.data is the document object (id, file_name, parse_status, ...)",
})
return cmd
+3 -3
View File
@@ -8,9 +8,9 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// fakeViewSvc scripts a GetKnowledge response. Tests bypass cobra and call
+12 -12
View File
@@ -9,11 +9,11 @@ import (
"sync"
"time"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
)
// WaitOptions captures `doc wait` flag state.
@@ -23,11 +23,11 @@ type WaitOptions struct {
Interval time.Duration
}
// NewCmdWait builds `weknora doc wait <id> [<id>...]`.
// NewCmdWait builds `academy doc wait <id> [<id>...]`.
//
// Multi-id behaviour is always wait-all: blocks until every id reaches a
// terminal state. Use shell composition
// (`weknora doc wait id1 && weknora doc wait id2`) when fail-fast is
// (`academy doc wait id1 && academy doc wait id2`) when fail-fast is
// desired.
func NewCmdWait(f *cmdutil.Factory) *cobra.Command {
opts := &WaitOptions{}
@@ -46,10 +46,10 @@ Exit codes:
Multi-id is polled concurrently (max 5 parallel; use 'xargs -P' for more).
For fail-fast semantics, use shell composition:
weknora doc wait id1 && weknora doc wait id2 && weknora doc wait id3`,
Example: ` weknora doc wait doc_abc
weknora doc wait id1 id2 id3 --timeout 20m
weknora doc wait id1 id2 --format ndjson`,
academy doc wait id1 && academy doc wait id2 && academy doc wait id3`,
Example: ` academy doc wait doc_abc
academy doc wait id1 id2 id3 --timeout 20m
academy doc wait id1 id2 --format ndjson`,
Args: cobra.MinimumNArgs(1),
RunE: func(c *cobra.Command, args []string) error {
// Validate flags FIRST so an invalid --format doesn't cost the
@@ -99,8 +99,8 @@ For fail-fast semantics, use shell composition:
UsedFor: "block until one or more documents reach a terminal parse state (completed or failed), or --timeout elapses",
RequiredFlags: []string{"<doc-id>... (one or more positionals)"},
Examples: []string{
"weknora doc wait doc_abc",
"weknora doc wait doc_a doc_b --timeout 5m",
"academy doc wait doc_abc",
"academy doc wait doc_a doc_b --timeout 5m",
},
Output: "envelope.data is {completed:[], failed:[{id,message}], timeout:[]}",
Warnings: []string{
@@ -241,7 +241,7 @@ func waitForDocs(ctx context.Context, ids []string, svc WaitService, opts WaitOp
// auto-enqueues). It never progresses on its own, so
// waiting would hang to the --timeout (124). Fail fast with
// the exact unblock command instead of silently polling.
addFailed(FailedDoc{ID: id, Message: "parse_status=draft: not queued for parsing — run `weknora doc reparse " + id + "` to index it"})
addFailed(FailedDoc{ID: id, Message: "parse_status=draft: not queued for parsing — run `academy doc reparse " + id + "` to index it"})
return
}
+2 -2
View File
@@ -10,9 +10,9 @@ import (
"testing"
"time"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
func TestWaitCmd_Shape(t *testing.T) {
+25 -25
View File
@@ -1,4 +1,4 @@
// Package doctor implements `weknora doctor` - 4-item self-check.
// Package doctor implements `academy doctor` - 4-item self-check.
//
// Status semantics (4-tier):
//
@@ -29,13 +29,13 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/build"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/compat"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/build"
"academy/cli/internal/cmdutil"
"academy/cli/internal/compat"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/secrets"
sdk "academy/client"
)
// doctorFields enumerates the fields surfaced for `--format json` discovery on
@@ -94,7 +94,7 @@ type Services interface {
GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error)
}
// NewCmd builds `weknora doctor`.
// NewCmd builds `academy doctor`.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
@@ -124,15 +124,15 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command {
return nil
},
}
cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache (located at $XDG_CACHE_HOME/weknora/server-info.yaml); force re-probe")
cmd.Flags().BoolVar(&opts.NoCache, "no-cache", false, "Bypass server-info cache (located at $XDG_CACHE_HOME/academy/server-info.yaml); force re-probe")
cmd.Flags().BoolVar(&opts.Offline, "offline", false, "Skip network checks; only verify local keyring/file storage (credential_storage check still runs)")
cmdutil.AddFormatFlag(cmd, doctorFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "run self-checks: base-url reachability, auth credential, server version, credential storage",
Examples: []string{
"weknora doctor",
"weknora doctor --offline",
"weknora doctor --no-cache --format json",
"academy doctor",
"academy doctor --offline",
"academy doctor --no-cache --format json",
},
Output: "envelope.data is {summary:{all_passed,passed,warned,failed,skipped}, checks:[{name,status,details,hint?}]}",
})
@@ -175,7 +175,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
t0 := time.Now()
if err := svc.PingBaseURL(ctx); err != nil {
checks[0].Status = StatusFail
checks[0].Hint = "verify the host configured for the active profile (run `weknora profile list` / `weknora profile add <n> --host=...`) and network reachability"
checks[0].Hint = "verify the host configured for the active profile (run `academy profile list` / `academy profile add <n> --host=...`) and network reachability"
checks[0].Details = err.Error()
} else {
checks[0].Status = StatusOK
@@ -187,7 +187,7 @@ func runChecks(ctx context.Context, opts *Options, svc Services, cliVer string)
if !cascade(&checks[1], opts.Offline, &checks[0]) {
if _, err := svc.GetCurrentUser(ctx); err != nil {
checks[1].Status = StatusFail
checks[1].Hint = "run `weknora auth login`"
checks[1].Hint = "run `academy auth login`"
checks[1].Details = err.Error()
} else {
checks[1].Status = StatusOK
@@ -297,7 +297,7 @@ func fillCredentialStorageCheck(c *Check) {
if _, isFile := store.(*secrets.FileStore); isFile {
c.Status = StatusWarn
c.Details = "falling back to file store: keychain unavailable"
c.Hint = "secrets persist at 0600 under $XDG_CONFIG_HOME/weknora/secrets/; install / unlock keyring for OS-backed storage"
c.Hint = "secrets persist at 0600 under $XDG_CONFIG_HOME/academy/secrets/; install / unlock keyring for OS-backed storage"
return
}
c.Status = StatusOK
@@ -389,7 +389,7 @@ func marker(s Status) string {
//
// Critically: this does NOT pre-resolve f.Client(). doctor's package promise
// (top comment) is that credential_storage runs even when no auth is set up -
// e.g. first-time `weknora doctor` to diagnose setup. Pre-resolving Client
// e.g. first-time `academy doctor` to diagnose setup. Pre-resolving Client
// here would early-exit with auth.unauthenticated before any check runs,
// contradicting the docs. Instead, GetCurrentUser / GetSystemInfo lazily
// resolve and surface their own failure as a per-check StatusFail.
@@ -405,12 +405,12 @@ func buildServices(f *cmdutil.Factory) (Services, error) {
// mirror the client builder (buildClientFromEnv) so doctor probes the host the
// real commands actually connect to; tier 1 is a doctor-local test/dev knob:
//
// 1. WEKNORA_BASE_URL — doctor-only probe override (used by tests); NOT read
// 1. ACADEMY_BASE_URL — doctor-only probe override (used by tests); NOT read
// by the client builder, so setting it points doctor at a host no real
// command uses. Kept for test/dev harnesses; leave unset in normal use.
// 2. WEKNORA_HOST — when stateless env credentials (WEKNORA_TOKEN /
// WEKNORA_API_KEY) are in effect, i.e. the headless agent path. Without
// this, `WEKNORA_API_KEY=… WEKNORA_HOST=… weknora doctor` falsely reported
// 2. ACADEMY_HOST — when stateless env credentials (ACADEMY_TOKEN /
// ACADEMY_API_KEY) are in effect, i.e. the headless agent path. Without
// this, `ACADEMY_API_KEY=… ACADEMY_HOST=… academy doctor` falsely reported
// "no host configured" and exited 1 while every other command worked.
// 3. active profile host — the configured default.
func resolveDoctorHost(cfg *config.Config) string {
@@ -418,15 +418,15 @@ func resolveDoctorHost(cfg *config.Config) string {
if ctx, ok := cfg.Profiles[cfg.CurrentProfile]; ok {
host = ctx.Host
}
// Env credentials authenticate via WEKNORA_HOST, bypassing the profile.
// Env credentials authenticate via ACADEMY_HOST, bypassing the profile.
// Honor it only when such creds are actually set, matching the client
// builder (a bare WEKNORA_HOST without creds is ignored there too).
// builder (a bare ACADEMY_HOST without creds is ignored there too).
if envActive, _ := cmdutil.EnvCredential(); envActive {
if v := strings.TrimSpace(os.Getenv("WEKNORA_HOST")); v != "" {
if v := strings.TrimSpace(os.Getenv("ACADEMY_HOST")); v != "" {
host = v
}
}
if v := os.Getenv("WEKNORA_BASE_URL"); v != "" {
if v := os.Getenv("ACADEMY_BASE_URL"); v != "" {
host = v
}
return host
+28 -28
View File
@@ -8,12 +8,12 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/compat"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/compat"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/secrets"
sdk "academy/client"
)
// withCredStoreFactory swaps the package-level credStoreFactory hook for the
@@ -173,7 +173,7 @@ func TestDoctor_CacheHit_SkipsProbe(t *testing.T) {
// TestDoctor_NoConfig_StillRunsCredentialStorage guards the package-doc
// promise that credential_storage runs even with zero configuration. Round-4
// reviewer surfaced that buildServices used to abort on f.Client() failure,
// silently violating the doc for any first-time user running `weknora doctor`
// silently violating the doc for any first-time user running `academy doctor`
// to diagnose setup. The lazy-resolve fix means missing auth surfaces as
// auth_credential=fail, not a top-level command exit.
func TestDoctor_NoConfig_StillRunsCredentialStorage(t *testing.T) {
@@ -510,10 +510,10 @@ func TestDoctor_RunE_WarnReturnsNil(t *testing.T) {
}
// TestResolveDoctorHost_EnvCredentials - doctor's base_url probe must honor
// WEKNORA_HOST when stateless env credentials are in effect (the headless
// ACADEMY_HOST when stateless env credentials are in effect (the headless
// agent path), mirroring buildClientFromEnv. Regression: doctor previously
// read only the active profile host, so `WEKNORA_API_KEY=... WEKNORA_HOST=...
// weknora doctor` reported "no host configured" and exited 1 while every
// read only the active profile host, so `ACADEMY_API_KEY=... ACADEMY_HOST=...
// academy doctor` reported "no host configured" and exited 1 while every
// other command worked.
func TestResolveDoctorHost_EnvCredentials(t *testing.T) {
cfg := &config.Config{
@@ -521,39 +521,39 @@ func TestResolveDoctorHost_EnvCredentials(t *testing.T) {
Profiles: map[string]config.Profile{"prod": {Host: "https://profile-host"}},
}
t.Run("env creds + WEKNORA_HOST wins over profile", func(t *testing.T) {
t.Setenv("WEKNORA_TOKEN", "")
t.Setenv("WEKNORA_API_KEY", "sk-test")
t.Setenv("WEKNORA_HOST", "https://env-host:8080")
t.Setenv("WEKNORA_BASE_URL", "")
t.Run("env creds + ACADEMY_HOST wins over profile", func(t *testing.T) {
t.Setenv("ACADEMY_TOKEN", "")
t.Setenv("ACADEMY_API_KEY", "sk-test")
t.Setenv("ACADEMY_HOST", "https://env-host:8080")
t.Setenv("ACADEMY_BASE_URL", "")
if got := resolveDoctorHost(cfg); got != "https://env-host:8080" {
t.Errorf("want env host, got %q", got)
}
})
t.Run("env creds without WEKNORA_HOST falls back to profile", func(t *testing.T) {
t.Setenv("WEKNORA_API_KEY", "sk-test")
t.Setenv("WEKNORA_HOST", "")
t.Setenv("WEKNORA_BASE_URL", "")
t.Run("env creds without ACADEMY_HOST falls back to profile", func(t *testing.T) {
t.Setenv("ACADEMY_API_KEY", "sk-test")
t.Setenv("ACADEMY_HOST", "")
t.Setenv("ACADEMY_BASE_URL", "")
if got := resolveDoctorHost(cfg); got != "https://profile-host" {
t.Errorf("want profile host, got %q", got)
}
})
t.Run("no env creds ignores WEKNORA_HOST (matches client builder)", func(t *testing.T) {
t.Setenv("WEKNORA_TOKEN", "")
t.Setenv("WEKNORA_API_KEY", "")
t.Setenv("WEKNORA_HOST", "https://should-be-ignored")
t.Setenv("WEKNORA_BASE_URL", "")
t.Run("no env creds ignores ACADEMY_HOST (matches client builder)", func(t *testing.T) {
t.Setenv("ACADEMY_TOKEN", "")
t.Setenv("ACADEMY_API_KEY", "")
t.Setenv("ACADEMY_HOST", "https://should-be-ignored")
t.Setenv("ACADEMY_BASE_URL", "")
if got := resolveDoctorHost(cfg); got != "https://profile-host" {
t.Errorf("want profile host, got %q", got)
}
})
t.Run("WEKNORA_BASE_URL test override always wins", func(t *testing.T) {
t.Setenv("WEKNORA_API_KEY", "sk-test")
t.Setenv("WEKNORA_HOST", "https://env-host")
t.Setenv("WEKNORA_BASE_URL", "https://base-url-override")
t.Run("ACADEMY_BASE_URL test override always wins", func(t *testing.T) {
t.Setenv("ACADEMY_API_KEY", "sk-test")
t.Setenv("ACADEMY_HOST", "https://env-host")
t.Setenv("ACADEMY_BASE_URL", "https://base-url-override")
if got := resolveDoctorHost(cfg); got != "https://base-url-override" {
t.Errorf("want base-url override, got %q", got)
}
+2 -2
View File
@@ -7,7 +7,7 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
// dryRunExpectation declares, for every leaf command, whether it must register
@@ -93,7 +93,7 @@ func TestDryRunCoverageMatchesExpectation(t *testing.T) {
var unlisted, wrong []string
eachLeafCommand(root, func(c *cobra.Command) {
key := strings.TrimPrefix(c.CommandPath(), "weknora ")
key := strings.TrimPrefix(c.CommandPath(), "academy ")
want, declared := dryRunExpectation[key]
if !declared {
unlisted = append(unlisted, key)
+9 -9
View File
@@ -7,9 +7,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
)
type exitCodeRow struct {
@@ -23,8 +23,8 @@ func exitCodeRows() []exitCodeRow {
return []exitCodeRow{
{0, "success", "", "continue"},
{1, "typed local.* / operation.failed / unclassified", "local.*, operation.failed, operation.cancelled, server.session_create_failed, internal.error", "read stderr, decide retry/abort"},
{2, "flag / argument validation error (cobra parse: unknown flag, arg count, missing required flag)", "input.invalid_argument (same type as exit 5; distinguish by exit code)", "re-check weknora <cmd> --help"},
{3, "authentication / authorization", "auth.*", "re-auth (weknora auth login), then retry"},
{2, "flag / argument validation error (cobra parse: unknown flag, arg count, missing required flag)", "input.invalid_argument (same type as exit 5; distinguish by exit code)", "re-check academy <cmd> --help"},
{3, "authentication / authorization", "auth.*", "re-auth (academy auth login), then retry"},
{4, "resource not found", "resource.not_found", "verify the resource id"},
{5, "invalid input value (typed validation, not a parse error)", "input.* (other than confirmation_required)", "adjust args, retry"},
{6, "rate limited", "server.rate_limited", "back off, retry"},
@@ -35,11 +35,11 @@ func exitCodeRows() []exitCodeRow {
}
}
// newCmdExitCodes builds the `weknora exit-codes` help-topic command.
// `weknora help exit-codes` renders Long for humans; running it directly
// newCmdExitCodes builds the `academy exit-codes` help-topic command.
// `academy help exit-codes` renders Long for humans; running it directly
// emits the machine-readable matrix (json by default, per the agent-first
// output contract). Listed in the command tree (not hidden) so humans have a
// discoverable path to it via `weknora help`, not only the README.
// discoverable path to it via `academy help`, not only the README.
func newCmdExitCodes() *cobra.Command {
cmd := &cobra.Command{
Use: "exit-codes",
@@ -66,7 +66,7 @@ func newCmdExitCodes() *cobra.Command {
cmdutil.AddFormatFlag(cmd, "code", "meaning", "error_types", "agent_action")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Machine-readable exit code matrix: what each code means and what to do next.",
Examples: []string{"weknora exit-codes", "weknora help exit-codes"},
Examples: []string{"academy exit-codes", "academy help exit-codes"},
Output: "envelope.data is an array of {code, meaning, error_types, agent_action}",
})
cmd.Long = "Exit codes and the agent action for each:\n\n" + exitCodesLongTable()
+2 -2
View File
@@ -8,8 +8,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
)
func TestExitCodesRows_CoversDocumentedMatrix(t *testing.T) {
+8 -8
View File
@@ -7,9 +7,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// CheckResult is the deep-verification response for `kb check <id>`.
@@ -41,7 +41,7 @@ var kbCheckFields = []string{
"is_processing", "processing_count", "failed_count",
}
// NewCmdCheck builds `weknora kb check <id>`.
// NewCmdCheck builds `academy kb check <id>`.
func NewCmdCheck(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "check <kb-id>",
@@ -52,11 +52,11 @@ Performs 1 + N HTTP calls:
1 GET /kb/{id} — reachable + counts + processing state
N page-walk doc list with parse_status=failed — failed_count
Use 'weknora kb status <id>' for a fast read-only health snapshot
Use 'academy kb status <id>' for a fast read-only health snapshot
(1 HTTP call, no failed_count). Use 'kb check' when you need
verification including failed-doc aggregation.`,
Example: ` weknora kb check kb_abc
weknora kb check kb_abc --format json`,
Example: ` academy kb check kb_abc
academy kb check kb_abc --format json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -79,7 +79,7 @@ verification including failed-doc aggregation.`,
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "verify a knowledge base end-to-end: status plus failed-doc aggregation",
RequiredFlags: []string{"<kb-id> (positional)"},
Examples: []string{"weknora kb check kb_abc"},
Examples: []string{"academy kb check kb_abc"},
Output: "envelope.data is {id, reachable, retrieval_ready, failed_count, ...}; retrieval_ready=false means no embedding model is bound (run `kb config set`); deeper than `kb status`",
})
return cmd
+2 -2
View File
@@ -8,8 +8,8 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
sdk "academy/client"
)
type fakeCheckSvc struct {
+10 -10
View File
@@ -6,9 +6,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// kbConfigFields enumerates the fields surfaced for `--format json` discovery on
@@ -22,15 +22,15 @@ type ConfigService interface {
GetInitializationConfig(ctx context.Context, kbID string) (*sdk.KBModelConfigView, error)
}
// NewCmdConfig builds `weknora kb config <kb-id>` — read-only inspection of a
// knowledge base's model configuration. Write it with `weknora kb config set`.
// NewCmdConfig builds `academy kb config <kb-id>` — read-only inspection of a
// knowledge base's model configuration. Write it with `academy kb config set`.
func NewCmdConfig(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "config <kb-id>",
Short: "Show a knowledge base's model configuration (set it with `config set`)",
Long: `Show the model configuration bound to a knowledge base: embedding, llm
(chat), rerank, and multimodal model names + source. retrieval_ready is false
until an embedding model is bound — configure it with 'weknora kb config set'.
until an embedding model is bound — configure it with 'academy kb config set'.
Provider API keys are never shown.`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
@@ -48,12 +48,12 @@ Provider API keys are never shown.`,
}
// `kb config` reads (this command's RunE); `kb config set` writes. Same
// read/write pairing as mainstream config surfaces.
cmd.AddCommand(newKBModelWriteCmd(f, "set <kb-id>", []string{"weknora", "kb", "config", "set"}))
cmd.AddCommand(newKBModelWriteCmd(f, "set <kb-id>", []string{"academy", "kb", "config", "set"}))
cmdutil.AddFormatFlag(cmd, kbConfigFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "show a KB's model config (embedding/llm/rerank/multimodal by name, secret-free). retrieval_ready=false => run `weknora kb config set`. Write config with `weknora kb config set`.",
UsedFor: "show a KB's model config (embedding/llm/rerank/multimodal by name, secret-free). retrieval_ready=false => run `academy kb config set`. Write config with `academy kb config set`.",
RequiredFlags: []string{"<kb-id> (positional)"},
Examples: []string{"weknora kb config kb_abc --jq .data.embedding_model_id"},
Examples: []string{"academy kb config kb_abc --jq .data.embedding_model_id"},
Output: "envelope.data is {retrieval_ready, embedding{configured,model_name,source,dimension}, llm{...}, rerank{enabled,model_name}, multimodal{enabled}} — secret-free (no provider api keys)",
})
return cmd
@@ -77,7 +77,7 @@ func runConfig(ctx context.Context, fopts *cmdutil.FormatOptions, svc ConfigServ
fmt.Fprintf(w, "%-13s %s\n", "RERANK:", rerankLabel(cfg.Rerank))
fmt.Fprintf(w, "%-13s %v\n", "MULTIMODAL:", cfg.Multimodal.Enabled)
if !cfg.RetrievalReady {
fmt.Fprintln(w, "\n(not retrieval-ready — no embedding model; run `weknora kb config set <kb-id> --chat-model <id> --embedding-model <id>`)")
fmt.Fprintln(w, "\n(not retrieval-ready — no embedding model; run `academy kb config set <kb-id> --chat-model <id> --embedding-model <id>`)")
}
return nil
}
+10 -10
View File
@@ -7,9 +7,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type ConfigSetOptions struct {
@@ -28,7 +28,7 @@ type ConfigSetService interface {
}
// newKBModelWriteCmd builds the `kb config set` model-binding write command.
// head is the argv prefix used for the risk action and retry_argv (weknora kb
// head is the argv prefix used for the risk action and retry_argv (academy kb
// config set).
func newKBModelWriteCmd(f *cmdutil.Factory, use string, head []string) *cobra.Command {
opts := &ConfigSetOptions{}
@@ -39,7 +39,7 @@ func newKBModelWriteCmd(f *cmdutil.Factory, use string, head []string) *cobra.Co
Long: `Bind already-registered models to a knowledge base so it can embed, retrieve,
and generate. Both --chat-model (LLM, used for generation/summary) and
--embedding-model (used for retrieval) are required; register models first with
'weknora model create' and discover ids with 'weknora model list'.
'academy model create' and discover ids with 'academy model list'.
High-risk write: changing a KB's embedding model affects how its content is
indexed and searched (the server refuses to CHANGE it once the KB has
@@ -87,16 +87,16 @@ applying the change.`,
return runConfigSet(c.Context(), opts, fopts, cli, kbID)
},
}
cmd.Flags().StringVar(&opts.ChatModel, "chat-model", "", "Chat / LLM model id or name for generation & summary (required) — see `weknora model list`")
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model id or name for retrieval (required) — see `weknora model list`")
cmd.Flags().StringVar(&opts.ChatModel, "chat-model", "", "Chat / LLM model id or name for generation & summary (required) — see `academy model list`")
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model id or name for retrieval (required) — see `academy model list`")
cmdutil.AddFormatFlag(cmd, kbConfigFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetRisk(cmd, action)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "bind models to a KB so it becomes retrieval-ready. --chat-model and --embedding-model are required and accept a model id or name; discover them with `weknora model list`. Read the result back with `weknora kb config`.",
UsedFor: "bind models to a KB so it becomes retrieval-ready. --chat-model and --embedding-model are required and accept a model id or name; discover them with `academy model list`. Read the result back with `academy kb config`.",
RequiredFlags: []string{"<kb-id> (positional)", "--chat-model", "--embedding-model"},
Examples: []string{
"weknora kb config set kb_abc --chat-model model_llm --embedding-model model_emb -y",
"academy kb config set kb_abc --chat-model model_llm --embedding-model model_emb -y",
},
Output: "envelope.data is the resulting secret-free config view {retrieval_ready, embedding, llm, rerank, multimodal}",
Warnings: []string{
@@ -121,7 +121,7 @@ func validateConfigSetFlags(opts *ConfigSetOptions) error {
return &cmdutil.Error{
Code: cmdutil.CodeInputMissingFlag,
Message: "kb config set requires " + strings.Join(missing, " and "),
Hint: "discover model ids with `weknora model list` (or register one with `weknora model create`), then pass --chat-model <id> --embedding-model <id>",
Hint: "discover model ids with `academy model list` (or register one with `academy model create`), then pass --chat-model <id> --embedding-model <id>",
}
}
+5 -5
View File
@@ -10,10 +10,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
sdk "academy/client"
)
type fakeInitSvc struct {
@@ -103,7 +103,7 @@ func (s *readbackErrSvc) GetInitializationConfig(_ context.Context, _ string) (*
// keyed off the sub's own name (unlike withRootHarnessKB which is hardcoded to
// `update`).
func withRootKB(sub *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
root := &cobra.Command{Use: "academy"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
+3 -3
View File
@@ -8,9 +8,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
type fakeConfigSvc struct {
+11 -11
View File
@@ -7,10 +7,10 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
sdk "academy/client"
)
// kbCreateFields enumerates the fields surfaced for `--format json` discovery
@@ -45,7 +45,7 @@ type CreateService interface {
CreateKnowledgeBase(ctx context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error)
}
// NewCmdCreate builds `weknora kb create <name>`. Positional <name> only,
// NewCmdCreate builds `academy kb create <name>`. Positional <name> only,
// consistent with `agent create <name>`.
func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts := &CreateOptions{}
@@ -86,14 +86,14 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
}
// --embedding-model accepts a model id or name (a UUID passes
// through; a name resolves among Embedding models). Configuring a
// KB's models fully is `weknora kb config set`; this just pre-sets the
// KB's models fully is `academy kb config set`; this just pre-sets the
// embedding model at creation.
if opts.EmbeddingModel, err = cmdutil.ResolveModelRef(c.Context(), cli, opts.EmbeddingModel, "Embedding"); err != nil {
return err
}
// --chat-model (id or name) pre-sets the KB's LLM at creation, so a
// KB can be born retrieval-ready in one step. Full model config
// (rerank / multimodal) is still `weknora kb config set`.
// (rerank / multimodal) is still `academy kb config set`.
if opts.ChatModel, err = cmdutil.ResolveModelRef(c.Context(), cli, opts.ChatModel, "KnowledgeQA"); err != nil {
return err
}
@@ -111,9 +111,9 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
UsedFor: "Create a new knowledge base with the given name. Emits the created KB object with its id.",
RequiredFlags: []string{"<name> (positional)"},
Examples: []string{
`weknora kb create "Eng Docs"`,
`weknora kb create "Eng Docs" --embedding-model text-embedding-3-small --chat-model gpt-4o-mini # retrieval-ready in one step`,
`weknora kb create "Eng Docs" --jq .data.id # capture id to chain into doc upload --kb`,
`academy kb create "Eng Docs"`,
`academy kb create "Eng Docs" --embedding-model text-embedding-3-small --chat-model gpt-4o-mini # retrieval-ready in one step`,
`academy kb create "Eng Docs" --jq .data.id # capture id to chain into doc upload --kb`,
},
Output: "envelope.data is the created KnowledgeBase object with id, name, type, embedding_model_id, summary_model_id",
})
@@ -155,7 +155,7 @@ func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOp
// the agent to discover a silent-draft KB via a later empty search.
var meta *output.Meta
if created.EmbeddingModelID == "" {
meta = &output.Meta{Hint: "retrieval_ready=false: no embedding model bound. Uploaded docs will not be searchable until you run `weknora kb config set " + created.ID + " --embedding-model <id> --chat-model <id>` (create the KB with --embedding-model/--chat-model to skip this step)."}
meta = &output.Meta{Hint: "retrieval_ready=false: no embedding model bound. Uploaded docs will not be searchable until you run `academy kb config set " + created.ID + " --embedding-model <id> --chat-model <id>` (create the KB with --embedding-model/--chat-model to skip this step)."}
}
if fopts.WantsJSON() {
+5 -5
View File
@@ -9,10 +9,10 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
sdk "academy/client"
)
// kbDryRunFactory builds a Factory whose Client closure panics if invoked —
@@ -37,7 +37,7 @@ func kbDryRunFactory(t *testing.T) *cmdutil.Factory {
// cmd/root.go). Required because kb subcommands inherit --yes / --format /
// --jq from root in production.
func withRootHarness(sub *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
root := &cobra.Command{Use: "academy"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
+3 -3
View File
@@ -10,9 +10,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
sdk "academy/client"
)
// fakeCreateSvc captures the request and returns canned responses.
+10 -10
View File
@@ -6,9 +6,9 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
)
// kbDeleteFields enumerates the fields surfaced for `--format json` discovery
@@ -32,7 +32,7 @@ type deleteResult struct {
Deleted bool `json:"deleted"`
}
// NewCmdDelete builds `weknora kb delete`. The global -y/--yes persistent
// NewCmdDelete builds `academy kb delete`. The global -y/--yes persistent
// flag is the single skip-prompt switch for the destructive-write
// confirmation pattern.
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
@@ -49,9 +49,9 @@ AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
and writes input.confirmation_required to stderr. NEVER auto-pass -y
without the user's explicit go-ahead — the exit-10 protocol exists
exactly to guard against unintended deletes.`,
Example: ` weknora kb delete kb_abc # interactive confirm
weknora kb delete kb_abc -y # no prompt
weknora kb delete kb_abc -y --format json # bare {id, deleted:true} JSON`,
Example: ` academy kb delete kb_abc # interactive confirm
academy kb delete kb_abc -y # no prompt
academy kb delete kb_abc -y --format json # bare {id, deleted:true} JSON`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -83,8 +83,8 @@ exactly to guard against unintended deletes.`,
RequiredFlags: []string{"<kb-id> (positional)"},
Output: "envelope.data is {id, deleted:true}",
Examples: []string{
"weknora kb delete kb_abc -y",
"weknora kb delete kb_abc -y --format json",
"academy kb delete kb_abc -y",
"academy kb delete kb_abc -y --format json",
},
Warnings: []string{
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
@@ -95,7 +95,7 @@ exactly to guard against unintended deletes.`,
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter, id string) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "knowledge base", id, "kb.delete", []string{"weknora", "kb", "delete", id, "-y"}); err != nil {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "knowledge base", id, "kb.delete", []string{"academy", "kb", "delete", id, "-y"}); err != nil {
return err
}
Loaded 100 of 3136 files, more files were not shown because too many files have changed in this diff. Show more