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

+3 -3
View File
@@ -8,7 +8,7 @@ import (
"gopkg.in/yaml.v3"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
// AgentConfigFlags carries hot-path flag values plus per-flag "was set"
@@ -106,9 +106,9 @@ func MergeAgentConfig(base *sdk.AgentConfig, ov AgentConfigFlags) *sdk.AgentConf
// `agent create --generate-skeleton` so users get a ready-to-edit
// starting point without authoring the full schema from memory.
func GenerateAgentSkeleton(w io.Writer) error {
const skeleton = `# WeKnora AgentConfig YAML skeleton
const skeleton = `# Academy AgentConfig YAML skeleton
# Edit this file and pass it to:
# weknora agent create "My Agent" --model <id> --config-file <this-file>
# academy agent create "My Agent" --model <id> --config-file <this-file>
# Hot-path flags on the create command override values set here.
# Operating mode: "quick-answer" or "smart-reasoning".
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
func TestLoadConfigFile_YAML(t *testing.T) {
+8 -8
View File
@@ -16,7 +16,7 @@ import (
)
// AgentHelp is the structured help blob emitted when an agent invokes
// `weknora <command> --help` with WEKNORA_AGENT_HELP=1. Distinct from
// `academy <command> --help` with ACADEMY_AGENT_HELP=1. Distinct from
// cobra's human help text — agent-readable JSON keyed by stable fields
// so an LLM doesn't need to scrape the human help table.
//
@@ -32,23 +32,23 @@ type AgentHelp struct {
}
// agentHelpAnnotation stores the marshaled AgentHelp on the command so the
// `weknora schema` command can introspect any command's contract without
// invoking its help func (and toggling WEKNORA_AGENT_HELP). Shares the
// `academy schema` command can introspect any command's contract without
// invoking its help func (and toggling ACADEMY_AGENT_HELP). Shares the
// annotations map with SetRisk (distinct keys).
const agentHelpAnnotation = "weknora.agent_help"
const agentHelpAnnotation = "academy.agent_help"
// SetAgentHelp attaches agent-targeted help metadata to a command.
//
// Routing:
// - WEKNORA_AGENT_HELP=1: emit the AgentHelp JSON blob to stdout and
// - ACADEMY_AGENT_HELP=1: emit the AgentHelp JSON blob to stdout and
// return — agents get clean parseable JSON, no trailing prose.
// - Otherwise (human help path): if cmd has risk annotations from SetRisk,
// prepend "Risk: <action> (<level>)" line; then render the normal human
// help via origHelp; then append the "AI agents:" Warnings block.
//
// The AgentHelp is also recorded as a JSON annotation so `weknora schema` can
// The AgentHelp is also recorded as a JSON annotation so `academy schema` can
// surface it as a first-class, discoverable command (not only via the
// WEKNORA_AGENT_HELP env toggle on --help).
// ACADEMY_AGENT_HELP env toggle on --help).
func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
if b, err := json.Marshal(ah); err == nil {
if cmd.Annotations == nil {
@@ -58,7 +58,7 @@ func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
}
origHelp := cmd.HelpFunc()
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
if os.Getenv("WEKNORA_AGENT_HELP") == "1" {
if os.Getenv("ACADEMY_AGENT_HELP") == "1" {
emitAgentHelp(c.OutOrStdout(), ah)
return
}
+4 -4
View File
@@ -9,12 +9,12 @@ import (
)
func TestSetAgentHelp_EmitsJSONWhenEnvSet(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
t.Setenv("ACADEMY_AGENT_HELP", "1")
cmd := &cobra.Command{Use: "foo"}
ah := AgentHelp{
UsedFor: "frob a bar",
RequiredFlags: []string{"--name"},
Examples: []string{"weknora foo --name=x"},
Examples: []string{"academy foo --name=x"},
}
SetAgentHelp(cmd, ah)
@@ -35,7 +35,7 @@ func TestSetAgentHelp_EmitsJSONWhenEnvSet(t *testing.T) {
}
func TestSetAgentHelp_FallsThroughToHumanHelp(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "")
t.Setenv("ACADEMY_AGENT_HELP", "")
cmd := &cobra.Command{
Use: "foo",
Short: "frob a bar",
@@ -62,7 +62,7 @@ func TestSetAgentHelp_AgentJSON_NoTrailingWarningsProse(t *testing.T) {
UsedFor: "Delete a knowledge base",
Warnings: []string{"irreversible"},
})
t.Setenv("WEKNORA_AGENT_HELP", "1")
t.Setenv("ACADEMY_AGENT_HELP", "1")
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.HelpFunc()(cmd, nil)
+5 -5
View File
@@ -4,8 +4,8 @@ import (
"context"
"errors"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/secrets"
sdk "academy/client"
)
// Refresher is the narrow SDK surface RefreshAndPersist depends on.
@@ -20,7 +20,7 @@ type Refresher interface {
// persisted as a side-effect, so callers only need the access value to
// retry the original request).
//
// Single canonical implementation shared by `weknora auth refresh` and the
// Single canonical implementation shared by `academy auth refresh` and the
// AuthRetryTransport's refresh closure - both used to inline the same
// six-step sequence with subtly diverging error wording.
func RefreshAndPersist(ctx context.Context, store secrets.Store, refresher Refresher, profileName string) (string, error) {
@@ -29,7 +29,7 @@ func RefreshAndPersist(ctx context.Context, store secrets.Store, refresher Refre
return "", &Error{
Code: CodeAuthTokenExpired,
Message: "refresh token missing for profile " + profileName,
Hint: "run `weknora auth login` to re-authenticate",
Hint: "run `academy auth login` to re-authenticate",
}
}
if err != nil {
@@ -51,7 +51,7 @@ func RefreshAndPersist(ctx context.Context, store secrets.Store, refresher Refre
return "", &Error{
Code: CodeAuthTokenExpired,
Message: msg,
Hint: "run `weknora auth login` to re-authenticate",
Hint: "run `academy auth login` to re-authenticate",
}
}
@@ -6,9 +6,9 @@ import (
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/secrets"
"academy/cli/internal/testutil"
sdk "academy/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"strings"
"sync"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
// AuthRetryTransport wraps a base http.RoundTripper with transparent
+1 -1
View File
@@ -17,7 +17,7 @@ import (
"io"
"time"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/output"
)
// BatchOutcome is one per-target result preserving argv order. Err==nil ⇒ success.
+2 -2
View File
@@ -89,12 +89,12 @@ func CheckSafeArgs(args []string, flags *pflag.FlagSet) error {
// any command logic runs — including the dry-run and exit-10 confirmation gates.
// Every positional in this CLI is an id, name, query, or path; none is
// meaningfully empty. The common agent trigger is capturing an id from a failed
// prior step (KB=$(weknora kb create … --jq .data.id) when the create failed →
// prior step (KB=$(academy kb create … --jq .data.id) when the create failed →
// ""), which otherwise reaches the server as an empty path segment: GET/DELETE
// /resource/ falls through to the LIST route, the array response fails to
// unmarshal into a single-object struct, and the failure is mis-reported as
// network.error ("check base URL"). Worse, an empty-id delete reaches the
// confirmation gate with a malformed `weknora kb delete -y` retry_argv.
// confirmation gate with a malformed `academy kb delete -y` retry_argv.
// Caught here as a clear input.invalid_argument (exit 5) instead.
//
// This is intentionally a global invariant (no command exempts itself); flag
+5 -5
View File
@@ -8,12 +8,12 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"academy/cli/internal/iostreams"
"academy/cli/internal/prompt"
)
// BuildRetryArgv assembles the directly-executable retry argv for a
// confirmation-gated command: head (e.g. []string{"weknora","kb","update",id})
// confirmation-gated command: head (e.g. []string{"academy","kb","update",id})
// followed by each *changed* flag named in allow (as "--name", "value") in
// pflag's visit order, plus a trailing "-y".
//
@@ -75,7 +75,7 @@ func titleFirst(s string) string {
// Pass n = total count of items about to be deleted.
// action is the namespaced action verb (e.g. "doc.delete") for the risk envelope.
// retryArgv is the directly-executable retry argv array
// (e.g. []string{"weknora","doc","delete","a","b","-y"}); pass nil when no
// (e.g. []string{"academy","doc","delete","a","b","-y"}); pass nil when no
// clean retry argv is available.
func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, verb, what string, n int, action string, retryArgv []string) error {
if yes {
@@ -119,7 +119,7 @@ func ConfirmDestructiveBatch(p prompt.Prompter, yes, jsonOut bool, verb, what st
// `yes` should be sourced from the persistent global -y/--yes flag.
// action is the namespaced action verb (e.g. "kb.delete") for the risk envelope.
// retryArgv is the directly-executable retry argv array
// (e.g. []string{"weknora","kb","delete","kb_x","-y"}); pass nil when no
// (e.g. []string{"academy","kb","delete","kb_x","-y"}); pass nil when no
// clean retry argv is available.
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, verb, what, id, action string, retryArgv []string) error {
return confirmGated(p, yes, jsonOut, verb, what, id, action, RiskDestructive, retryArgv)
+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"
"github.com/Tencent/WeKnora/cli/internal/testutil"
"academy/cli/internal/cmdutil"
"academy/cli/internal/iostreams"
"academy/cli/internal/testutil"
)
// The confirmation message verb must match the actual operation: an `edit`
@@ -73,11 +73,11 @@ func TestBuildRetryArgv_ScalarsAndSlices(t *testing.T) {
t.Fatal(err)
}
got := cmdutil.BuildRetryArgv(cmd, []string{"weknora", "agent", "update", "ag_abc"},
got := cmdutil.BuildRetryArgv(cmd, []string{"academy", "agent", "update", "ag_abc"},
"name", "add-kb", "format")
// Visit order is lexicographical among changed flags.
want := []string{
"weknora", "agent", "update", "ag_abc",
"academy", "agent", "update", "ag_abc",
"--add-kb", "kb_new",
"--add-kb", "kb_old",
"--format", "json",
@@ -103,8 +103,8 @@ func TestBuildRetryArgv_SkipsFlagsNotInAllow(t *testing.T) {
t.Fatal(err)
}
got := cmdutil.BuildRetryArgv(cmd, []string{"weknora", "model", "update", "m1"}, "name", "format")
want := []string{"weknora", "model", "update", "m1", "--name", "x", "-y"}
got := cmdutil.BuildRetryArgv(cmd, []string{"academy", "model", "update", "m1"}, "name", "format")
want := []string{"academy", "model", "update", "m1", "--name", "x", "-y"}
if len(got) != len(want) {
t.Fatalf("len got=%d want=%d\ngot=%v\nwant=%v", len(got), len(want), got, want)
}
+3 -3
View File
@@ -9,7 +9,7 @@
// - The api command additionally rejects --dry-run on GET (FlagError).
//
// Side-effect suppression: the dry-run path must NOT call the SDK, write
// the keyring, write .weknora/project.yaml, or write download files.
// the keyring, write .academy/project.yaml, or write download files.
package cmdutil
import (
@@ -19,8 +19,8 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/iostreams"
"academy/cli/internal/output"
)
// DryRunPlan describes the would-be action for envelope meta.plan.
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"academy/cli/internal/iostreams"
)
func TestAddDryRunFlag_RegistersFlag(t *testing.T) {
+4 -4
View File
@@ -10,8 +10,8 @@ import (
"strconv"
"strings"
"github.com/Tencent/WeKnora/cli/internal/output"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/output"
sdk "academy/client"
)
// ErrorCode is a namespaced stable identifier emitted on stderr in the
@@ -99,7 +99,7 @@ const (
// carries a stable code; distinct from input.* because the user supplied
// valid args and simply chose not to proceed.
CodeUserAborted ErrorCode = "local.user_aborted"
// CodeUploadFileNotFound marks a `weknora doc upload` invocation pointing at
// CodeUploadFileNotFound marks a `academy doc upload` invocation pointing at
// a path that does not exist. Distinct from CodeLocalFileIO (permission /
// disk-fault) so the hint can name the actual culprit.
CodeUploadFileNotFound ErrorCode = "local.upload_file_not_found"
@@ -351,7 +351,7 @@ func matchPrefix(err error, prefix string) bool {
return strings.HasPrefix(string(e.Code), prefix)
}
// serverNotFoundRE matches the WeKnora server's structured error-envelope body
// serverNotFoundRE matches the Academy server's structured error-envelope body
// for the typed "not found" code (1003 = ErrNotFound). Server's 1007 is the
// generic ErrInternalServer bucket — including it would mis-classify every
// validation / DB failure (e.g. SQLSTATE 22001 "value too long") as
+1 -1
View File
@@ -3,7 +3,7 @@ package cmdutil_test
import (
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/internal/cmdutil"
)
func TestAllCodes_NonEmpty(t *testing.T) {
+4 -4
View File
@@ -14,13 +14,13 @@ func TestErrorToDetail_NilSafe(t *testing.T) {
func TestError_WithRetryArgv(t *testing.T) {
err := NewError(CodeAuthUnauthenticated, "session expired").
WithHint("run `weknora auth login`").
WithRetryArgv([]string{"weknora", "auth", "login"})
WithHint("run `academy auth login`").
WithRetryArgv([]string{"academy", "auth", "login"})
if !reflect.DeepEqual(err.RetryArgv, []string{"weknora", "auth", "login"}) {
if !reflect.DeepEqual(err.RetryArgv, []string{"academy", "auth", "login"}) {
t.Errorf("RetryArgv not set; got %v", err.RetryArgv)
}
if err.Hint != "run `weknora auth login`" {
if err.Hint != "run `academy auth login`" {
t.Errorf("Hint changed unexpectedly; got %q", err.Hint)
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"testing"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
"github.com/stretchr/testify/assert"
)
+18 -18
View File
@@ -6,7 +6,7 @@ import (
"io"
"strings"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/output"
)
// globalFormatMode tracks the resolved --format value for the current invocation.
@@ -143,46 +143,46 @@ func printErrorEnvelope(w io.Writer, err error) {
// defaultHint returns a canonical actionable hint for known error codes
// when the call site didn't set one. `auth.unauthenticated` always points
// at `weknora auth login` - covers the broad surface (auth status / kb
// at `academy auth login` - covers the broad surface (auth status / kb
// list / kb view / search) without per-command hint plumbing.
//
// Empty string for codes without a stable canonical hint.
func defaultHint(code ErrorCode) string {
switch code {
case CodeAuthUnauthenticated, CodeAuthBadCredential:
return "run `weknora auth login`"
return "run `academy auth login`"
case CodeAuthTokenExpired:
return "your session expired; run `weknora auth login` to re-authenticate"
return "your session expired; run `academy auth login` to re-authenticate"
case CodeAuthForbidden:
return "active profile lacks permission for this resource"
case CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch:
return "verify tenant profile with `weknora auth status`"
return "verify tenant profile with `academy auth status`"
case CodeNetworkError:
return "check base URL reachability with `weknora doctor`"
return "check base URL reachability with `academy doctor`"
case CodeServerIncompatibleVersion:
return "run `weknora doctor` to see version skew details"
return "run `academy doctor` to see version skew details"
case CodeServerRateLimited:
return "rate-limited; retry after a few seconds"
case CodeServerTimeout:
return "request timed out; retry, or run `weknora doctor` to check connectivity"
return "request timed out; retry, or run `academy doctor` to check connectivity"
case CodeResourceNotFound:
return "verify the resource ID and try again"
case CodeInputInvalidArgument, CodeInputMissingFlag:
return "see `weknora <command> --help` for valid usage"
return "see `academy <command> --help` for valid usage"
case CodeInputConfirmationRequired:
return "high-risk write - re-run with -y/--yes after the user explicitly approves"
case CodeLocalKeychainDenied:
return "verify keyring access; falls back to file storage"
case CodeLocalConfigCorrupt:
return "remove ~/.config/weknora/config.yaml and re-run `weknora auth login`"
return "remove ~/.config/academy/config.yaml and re-run `academy auth login`"
case CodeLocalFileIO:
return "check file permissions under $XDG_CONFIG_HOME/weknora/"
return "check file permissions under $XDG_CONFIG_HOME/academy/"
case CodeKBIDRequired:
return "run `weknora link` to bind this directory to a knowledge base, or pass --kb"
return "run `academy link` to bind this directory to a knowledge base, or pass --kb"
case CodeKBNotFound:
return "list available with `weknora kb list`"
return "list available with `academy kb list`"
case CodeProjectLinkCorrupt:
return "remove .weknora/project.yaml and run `weknora link` again"
return "remove .academy/project.yaml and run `academy link` again"
case CodeUserAborted:
return "no action taken; pass -y/--yes to skip the confirmation prompt"
case CodeUploadFileNotFound:
@@ -205,13 +205,13 @@ func defaultHint(code ErrorCode) string {
func defaultRetryArgv(code ErrorCode) []string {
switch code {
case CodeAuthUnauthenticated, CodeAuthBadCredential, CodeAuthTokenExpired:
return []string{"weknora", "auth", "login"}
return []string{"academy", "auth", "login"}
case CodeKBIDRequired:
return []string{"weknora", "link"}
return []string{"academy", "link"}
case CodeNetworkError, CodeServerTimeout:
return []string{"weknora", "doctor"}
return []string{"academy", "doctor"}
case CodeProjectLinkCorrupt:
return []string{"weknora", "link"} // re-bind the project to a KB
return []string{"academy", "link"} // re-bind the project to a KB
case CodeLocalConfigCorrupt:
// Recovery is two steps (delete config + re-login); the prose hint
// already spells it out, so the retry argv stays nil.
+4 -4
View File
@@ -66,7 +66,7 @@ func TestPrintError_JSONMode_WritesEnvelope(t *testing.T) {
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
WithHint("re-run with -y/--yes").
WithRetryArgv([]string{"weknora", "kb", "delete", "kb_x", "-y"})
WithRetryArgv([]string{"academy", "kb", "delete", "kb_x", "-y"})
var buf bytes.Buffer
PrintError(&buf, err)
@@ -78,7 +78,7 @@ func TestPrintError_JSONMode_WritesEnvelope(t *testing.T) {
if !strings.Contains(got, `"type":"input.confirmation_required"`) {
t.Errorf("expected typed code; got %q", got)
}
if !strings.Contains(got, `"retry_argv":["weknora","kb","delete","kb_x","-y"]`) {
if !strings.Contains(got, `"retry_argv":["academy","kb","delete","kb_x","-y"]`) {
t.Errorf("expected retry_argv; got %q", got)
}
}
@@ -105,7 +105,7 @@ func TestPrintError_TextMode_WritesProse(t *testing.T) {
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
WithHint("re-run with -y/--yes").
WithRetryArgv([]string{"weknora", "kb", "delete", "kb_x", "-y"})
WithRetryArgv([]string{"academy", "kb", "delete", "kb_x", "-y"})
var buf bytes.Buffer
PrintError(&buf, err)
@@ -117,7 +117,7 @@ func TestPrintError_TextMode_WritesProse(t *testing.T) {
if !strings.Contains(got, "hint: re-run with -y/--yes") {
t.Errorf("expected hint line; got %q", got)
}
if !strings.Contains(got, "retry: weknora kb delete kb_x -y") {
if !strings.Contains(got, "retry: academy kb delete kb_x -y") {
t.Errorf("expected retry line; got %q", got)
}
}
+41 -41
View File
@@ -12,20 +12,20 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/projectlink"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/config"
"academy/cli/internal/iostreams"
"academy/cli/internal/projectlink"
"academy/cli/internal/prompt"
"academy/cli/internal/secrets"
sdk "academy/client"
)
// Factory is the dependency container injected at command construction. Each
// closure is lazy: --help / completion / `weknora version` must NOT trigger
// closure is lazy: --help / completion / `academy version` must NOT trigger
// HTTP, keyring access, or filesystem I/O beyond the bare minimum.
//
// Four closures:
// - Config: parses ~/.config/weknora/config.yaml (no network)
// - Config: parses ~/.config/academy/config.yaml (no network)
// - Client: constructs the SDK client; only Secrets is sync.Once-cached,
// so callers should hold the returned *sdk.Client across
// multiple SDK calls within one invocation
@@ -39,7 +39,7 @@ import (
// iostreams.IO. The bar to add a new closure is at least 2 commands sharing the
// same dependency; resist factory bloat.
//
// Client returns a *sdk.Client (the WeKnora SDK). Commands that want narrow
// Client returns a *sdk.Client (the Academy SDK). Commands that want narrow
// service interfaces declare them in their own files and let the real SDK
// satisfy them implicitly via duck typing.
type Factory struct {
@@ -112,10 +112,10 @@ func New() *Factory {
// buildClient resolves the active profile, loads the credentials from secrets,
// and constructs a *sdk.Client. Returns CodeAuthUnauthenticated when no
// credentials are available so the user gets the right hint to run
// `weknora auth login`.
// `academy auth login`.
func buildClient(f *Factory) (*sdk.Client, error) {
// Env-credential injection: WEKNORA_TOKEN (bearer) or WEKNORA_API_KEY, with
// WEKNORA_HOST (or the active profile's host), builds an ephemeral client
// Env-credential injection: ACADEMY_TOKEN (bearer) or ACADEMY_API_KEY, with
// ACADEMY_HOST (or the active profile's host), builds an ephemeral client
// that bypasses config.yaml + the keyring — the stateless headless / CI /
// agent path (no disk writes, no `auth login`).
if c, handled, err := buildClientFromEnv(f); handled {
@@ -132,19 +132,19 @@ func buildClient(f *Factory) (*sdk.Client, error) {
// an active profile) — an agent that execs retry_argv would loop. Point
// hint + retry_argv at the real first step: create a profile.
return nil, NewError(CodeAuthUnauthenticated, "no profile configured").
WithHint("add one first: `weknora profile add <name> --host <url> --use`, then `weknora auth login` (or set WEKNORA_API_KEY + WEKNORA_HOST for headless use)").
WithRetryArgv([]string{"weknora", "profile", "add", "--help"})
WithHint("add one first: `academy profile add <name> --host <url> --use`, then `academy auth login` (or set ACADEMY_API_KEY + ACADEMY_HOST for headless use)").
WithRetryArgv([]string{"academy", "profile", "add", "--help"})
}
prof, ok := cfg.Profiles[profileName]
if !ok {
// If the user explicitly overrode the profile (via --profile flag or
// WEKNORA_PROFILE env), it's a bad argument - not a corrupt config file.
// ACADEMY_PROFILE env), it's a bad argument - not a corrupt config file.
// The destructive "remove config.yaml" hint would be catastrophic for a typo.
if f.ProfileOverride != "" {
return nil, NewError(CodeInputInvalidArgument,
fmt.Sprintf("profile %q not configured", profileName)).
WithHint("list available profiles with `weknora profile list`").
WithRetryArgv([]string{"weknora", "profile", "list"})
WithHint("list available profiles with `academy profile list`").
WithRetryArgv([]string{"academy", "profile", "list"})
}
// ProfileOverride is empty: config.CurrentProfile points at a missing entry.
// That's a genuinely corrupt config file.
@@ -203,39 +203,39 @@ func buildClient(f *Factory) (*sdk.Client, error) {
// EnvCredential reports whether stateless env credentials are in effect and
// which kind. Used by `auth status` / `config view` so their host / profile
// output reflects that the env credential (and WEKNORA_HOST) — not the config
// output reflects that the env credential (and ACADEMY_HOST) — not the config
// profile — is what actually authenticated the client. Mirrors buildClientFromEnv's
// precedence (WEKNORA_TOKEN wins over WEKNORA_API_KEY).
// precedence (ACADEMY_TOKEN wins over ACADEMY_API_KEY).
func EnvCredential() (active bool, kind string) {
if strings.TrimSpace(os.Getenv("WEKNORA_TOKEN")) != "" {
return true, "WEKNORA_TOKEN"
if strings.TrimSpace(os.Getenv("ACADEMY_TOKEN")) != "" {
return true, "ACADEMY_TOKEN"
}
if strings.TrimSpace(os.Getenv("WEKNORA_API_KEY")) != "" {
return true, "WEKNORA_API_KEY"
if strings.TrimSpace(os.Getenv("ACADEMY_API_KEY")) != "" {
return true, "ACADEMY_API_KEY"
}
return false, ""
}
// buildClientFromEnv builds an ephemeral SDK client from WEKNORA_TOKEN (bearer
// JWT) or WEKNORA_API_KEY when either is set, bypassing config.yaml + the
// buildClientFromEnv builds an ephemeral SDK client from ACADEMY_TOKEN (bearer
// JWT) or ACADEMY_API_KEY when either is set, bypassing config.yaml + the
// keyring entirely — the stateless path for headless / CI / agent use. Returns
// handled=false (fall through to the profile path) when neither var is set.
//
// Host resolution: WEKNORA_HOST, else the active profile's host (so env creds
// Host resolution: ACADEMY_HOST, else the active profile's host (so env creds
// can target an already-configured host without re-specifying it). When a token
// is supplied, no 401→refresh transport is attached — env creds are ephemeral,
// so a 401 propagates for the caller to supply a fresh token. WEKNORA_TOKEN
// wins over WEKNORA_API_KEY if both are set.
// so a 401 propagates for the caller to supply a fresh token. ACADEMY_TOKEN
// wins over ACADEMY_API_KEY if both are set.
func buildClientFromEnv(f *Factory) (client *sdk.Client, handled bool, err error) {
token := strings.TrimSpace(os.Getenv("WEKNORA_TOKEN"))
apiKey := strings.TrimSpace(os.Getenv("WEKNORA_API_KEY"))
token := strings.TrimSpace(os.Getenv("ACADEMY_TOKEN"))
apiKey := strings.TrimSpace(os.Getenv("ACADEMY_API_KEY"))
if token == "" && apiKey == "" {
return nil, false, nil
}
host := strings.TrimSpace(os.Getenv("WEKNORA_HOST"))
host := strings.TrimSpace(os.Getenv("ACADEMY_HOST"))
if host == "" {
// Best-effort fallback to the active profile's host; ignore config
// errors so env creds + WEKNORA_HOST stay usable with no config at all.
// errors so env creds + ACADEMY_HOST stay usable with no config at all.
if cfg, cerr := f.Config(); cerr == nil && cfg != nil {
if prof, ok := cfg.Profiles[cfg.CurrentProfile]; ok {
host = prof.Host
@@ -244,8 +244,8 @@ func buildClientFromEnv(f *Factory) (client *sdk.Client, handled bool, err error
}
if host == "" {
return nil, true, NewError(CodeInputInvalidArgument,
"WEKNORA_TOKEN / WEKNORA_API_KEY is set but no host is available").
WithHint("set WEKNORA_HOST (e.g. https://kb.example.com) or configure a profile host")
"ACADEMY_TOKEN / ACADEMY_API_KEY is set but no host is available").
WithHint("set ACADEMY_HOST (e.g. https://kb.example.com) or configure a profile host")
}
if token != "" {
return sdk.NewClient(host, sdk.WithBearerToken(token)), true, nil
@@ -273,8 +273,8 @@ func AddIgnoredKBFlag(cmd *cobra.Command) {
// 4-level fallback chain (highest to lowest):
// 1. --kb flag (kb_<...> id passed through; anything else resolved via
// ListKnowledgeBases as a name → id lookup)
// 2. WEKNORA_KB_ID env (always an explicit id)
// 3. .weknora/project.yaml (walk-up from cwd)
// 2. ACADEMY_KB_ID env (always an explicit id)
// 3. .academy/project.yaml (walk-up from cwd)
// 4. error: kb required
func (f *Factory) ResolveKB(cmd *cobra.Command) (string, error) {
if v, _ := cmd.Flags().GetString("kb"); v != "" {
@@ -304,10 +304,10 @@ func (f *Factory) ResolveKBLocal(cmd *cobra.Command) (string, error) {
// resolveKBFromEnvOrLink is the shared fallback tail of ResolveKB /
// ResolveKBLocal (which differ only in how they treat the --kb flag): it reads
// WEKNORA_KB_ID, then the walk-up .weknora/project.yaml link, and returns
// ACADEMY_KB_ID, then the walk-up .academy/project.yaml link, and returns
// CodeKBIDRequired when neither is set. Never calls the SDK.
func (f *Factory) resolveKBFromEnvOrLink() (string, error) {
if v := os.Getenv("WEKNORA_KB_ID"); v != "" {
if v := os.Getenv("ACADEMY_KB_ID"); v != "" {
return v, nil
}
cwd, err := os.Getwd()
@@ -325,7 +325,7 @@ func (f *Factory) resolveKBFromEnvOrLink() (string, error) {
return "", NewError(CodeKBIDRequired, "kb is required")
}
// ApplyLogLevel resolves --log-level / WEKNORA_LOG_LEVEL (in priority order)
// ApplyLogLevel resolves --log-level / ACADEMY_LOG_LEVEL (in priority order)
// and applies the result to the SDK's debug logger. Intended to be called
// from the root command's PersistentPreRunE so the resolved level is in
// effect before any SDK call.
@@ -374,14 +374,14 @@ func refreshAccessToken(ctx context.Context, store secrets.Store, host, profileN
// ActiveProfile returns the resolved profile name for this invocation:
// 1. ProfileOverride (set by --profile flag in root PersistentPreRunE)
// 2. WEKNORA_PROFILE env var
// 2. ACADEMY_PROFILE env var
// 3. Config's CurrentProfile (the persisted active profile name)
// 4. Empty string when nothing is configured (envelope omits the field).
func (f *Factory) ActiveProfile() string {
if f.ProfileOverride != "" {
return f.ProfileOverride
}
if v := os.Getenv("WEKNORA_PROFILE"); v != "" {
if v := os.Getenv("ACADEMY_PROFILE"); v != "" {
return v
}
if f.Config == nil {
+37 -37
View File
@@ -14,11 +14,11 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/projectlink"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/config"
"academy/cli/internal/projectlink"
"academy/cli/internal/prompt"
"academy/cli/internal/secrets"
sdk "academy/client"
)
// TestFactory_Lazy ensures none of the closures execute work at construction
@@ -55,7 +55,7 @@ func TestFactory_Lazy(t *testing.T) {
// TestNew_FoundationDefaults verifies the production New() returns a usable
// Factory and that Client surfaces auth.unauthenticated when no current
// profile is configured (the precondition for `weknora auth login`).
// profile is configured (the precondition for `academy auth login`).
func TestNew_FoundationDefaults(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // empty config → no current profile
f := New()
@@ -80,8 +80,8 @@ func TestFactory_ProfileOverride(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", dir)
// Seed config with two profiles; CurrentProfile = "default"
cfgPath := dir + "/weknora/config.yaml"
require.NoError(t, os.MkdirAll(dir+"/weknora", 0o700))
cfgPath := dir + "/academy/config.yaml"
require.NoError(t, os.MkdirAll(dir+"/academy", 0o700))
require.NoError(t, os.WriteFile(cfgPath, []byte(`
current_profile: default
profiles:
@@ -178,7 +178,7 @@ func TestBuildClient_NoCurrentProfile(t *testing.T) {
// fails with no profile → an agent execing retry_argv would loop); it must
// point at profile creation instead.
detail := ErrorToDetail(err)
assert.NotEqual(t, []string{"weknora", "auth", "login"}, detail.RetryArgv,
assert.NotEqual(t, []string{"academy", "auth", "login"}, detail.RetryArgv,
"zero-state retry_argv must not loop back to auth login")
assert.Contains(t, detail.RetryArgv, "profile", "zero-state retry_argv should point at profile setup")
}
@@ -309,10 +309,10 @@ func fakeKBServer(t *testing.T, kbs []sdk.KnowledgeBase) *httptest.Server {
return srv
}
// TestFactory_ActiveProfile_EnvVarFallback verifies WEKNORA_PROFILE is honoured
// TestFactory_ActiveProfile_EnvVarFallback verifies ACADEMY_PROFILE is honoured
// when no override or config is present.
func TestFactory_ActiveProfile_EnvVarFallback(t *testing.T) {
t.Setenv("WEKNORA_PROFILE", "staging")
t.Setenv("ACADEMY_PROFILE", "staging")
f := &Factory{} // no override, no config
if got := f.ActiveProfile(); got != "staging" {
t.Errorf("expected env fallback to staging; got %q", got)
@@ -320,9 +320,9 @@ func TestFactory_ActiveProfile_EnvVarFallback(t *testing.T) {
}
// TestFactory_ActiveProfile_OverrideWinsEnv verifies ProfileOverride takes
// priority over the WEKNORA_PROFILE env var.
// priority over the ACADEMY_PROFILE env var.
func TestFactory_ActiveProfile_OverrideWinsEnv(t *testing.T) {
t.Setenv("WEKNORA_PROFILE", "staging")
t.Setenv("ACADEMY_PROFILE", "staging")
f := &Factory{ProfileOverride: "prod"}
if got := f.ActiveProfile(); got != "prod" {
t.Errorf("override should win over env; got %q", got)
@@ -334,11 +334,11 @@ func TestFactory_ActiveProfile_OverrideWinsEnv(t *testing.T) {
func TestResolveKB_Chain(t *testing.T) {
t.Run("flag_kb_id_wins", func(t *testing.T) {
// UUID form on --kb → pass-through; no SDK call, no env, no disk.
t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose")
t.Setenv("ACADEMY_KB_ID", "kb_env_should_lose")
dir := t.TempDir()
resolveKBChdir(t, dir)
// Drop a project link too - must be ignored.
require.NoError(t, projectlink.Save(filepath.Join(dir, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"}))
require.NoError(t, projectlink.Save(filepath.Join(dir, ".academy", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"}))
clientCalls := 0
f := &Factory{
@@ -354,7 +354,7 @@ func TestResolveKB_Chain(t *testing.T) {
})
t.Run("flag_kb_name_resolves", func(t *testing.T) {
t.Setenv("WEKNORA_KB_ID", "")
t.Setenv("ACADEMY_KB_ID", "")
srv := fakeKBServer(t, []sdk.KnowledgeBase{
{ID: "kb_a", Name: "foo"},
{ID: "kb_b", Name: "bar"},
@@ -368,7 +368,7 @@ func TestResolveKB_Chain(t *testing.T) {
})
t.Run("flag_kb_name_not_found", func(t *testing.T) {
t.Setenv("WEKNORA_KB_ID", "")
t.Setenv("ACADEMY_KB_ID", "")
srv := fakeKBServer(t, []sdk.KnowledgeBase{{ID: "kb_a", Name: "foo"}})
f := &Factory{
Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil },
@@ -382,10 +382,10 @@ func TestResolveKB_Chain(t *testing.T) {
t.Run("env_var", func(t *testing.T) {
// No flag, env wins over disk.
t.Setenv("WEKNORA_KB_ID", "kb_env")
t.Setenv("ACADEMY_KB_ID", "kb_env")
dir := t.TempDir()
resolveKBChdir(t, dir)
require.NoError(t, projectlink.Save(filepath.Join(dir, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"}))
require.NoError(t, projectlink.Save(filepath.Join(dir, ".academy", "project.yaml"), &projectlink.Project{KBID: "kb_disk_should_lose"}))
f := &Factory{}
got, err := f.ResolveKB(makeResolveKBCmd(t, ""))
@@ -394,9 +394,9 @@ func TestResolveKB_Chain(t *testing.T) {
})
t.Run("project_link_walk_up", func(t *testing.T) {
t.Setenv("WEKNORA_KB_ID", "")
t.Setenv("ACADEMY_KB_ID", "")
root := t.TempDir()
require.NoError(t, projectlink.Save(filepath.Join(root, ".weknora", "project.yaml"), &projectlink.Project{KBID: "kb_proj"}))
require.NoError(t, projectlink.Save(filepath.Join(root, ".academy", "project.yaml"), &projectlink.Project{KBID: "kb_proj"}))
// Run from a deep child to exercise walk-up.
deep := filepath.Join(root, "a", "b", "c")
require.NoError(t, os.MkdirAll(deep, 0o755))
@@ -410,7 +410,7 @@ func TestResolveKB_Chain(t *testing.T) {
t.Run("none", func(t *testing.T) {
// No flag, no env, no project link → CodeKBIDRequired.
t.Setenv("WEKNORA_KB_ID", "")
t.Setenv("ACADEMY_KB_ID", "")
dir := t.TempDir()
resolveKBChdir(t, dir)
@@ -423,24 +423,24 @@ func TestResolveKB_Chain(t *testing.T) {
})
}
// TestBuildClientFromEnv covers the stateless env-credential path: WEKNORA_TOKEN
// / WEKNORA_API_KEY build an ephemeral client with no config/keyring access.
// TestBuildClientFromEnv covers the stateless env-credential path: ACADEMY_TOKEN
// / ACADEMY_API_KEY build an ephemeral client with no config/keyring access.
func TestBuildClientFromEnv(t *testing.T) {
emptyCfg := &Factory{Config: func() (*config.Config, error) { return &config.Config{}, nil }}
t.Run("no env vars falls through to profile path", func(t *testing.T) {
t.Setenv("WEKNORA_TOKEN", "")
t.Setenv("WEKNORA_API_KEY", "")
t.Setenv("ACADEMY_TOKEN", "")
t.Setenv("ACADEMY_API_KEY", "")
c, handled, err := buildClientFromEnv(emptyCfg)
assert.False(t, handled, "no env creds must fall through")
assert.Nil(t, c)
assert.NoError(t, err)
})
t.Run("api key + WEKNORA_HOST builds a client", func(t *testing.T) {
t.Setenv("WEKNORA_TOKEN", "")
t.Setenv("WEKNORA_API_KEY", "sk-test")
t.Setenv("WEKNORA_HOST", "https://kb.example.com")
t.Run("api key + ACADEMY_HOST builds a client", func(t *testing.T) {
t.Setenv("ACADEMY_TOKEN", "")
t.Setenv("ACADEMY_API_KEY", "sk-test")
t.Setenv("ACADEMY_HOST", "https://kb.example.com")
c, handled, err := buildClientFromEnv(emptyCfg)
assert.True(t, handled)
require.NoError(t, err)
@@ -448,9 +448,9 @@ func TestBuildClientFromEnv(t *testing.T) {
})
t.Run("token set but no host is a typed input error", func(t *testing.T) {
t.Setenv("WEKNORA_API_KEY", "")
t.Setenv("WEKNORA_TOKEN", "jwt-token")
t.Setenv("WEKNORA_HOST", "")
t.Setenv("ACADEMY_API_KEY", "")
t.Setenv("ACADEMY_TOKEN", "jwt-token")
t.Setenv("ACADEMY_HOST", "")
c, handled, err := buildClientFromEnv(emptyCfg)
assert.True(t, handled, "env creds set → handled even on host error")
assert.Nil(t, c)
@@ -459,10 +459,10 @@ func TestBuildClientFromEnv(t *testing.T) {
assert.Equal(t, CodeInputInvalidArgument, ce.Code)
})
t.Run("host falls back to the active profile when WEKNORA_HOST unset", func(t *testing.T) {
t.Setenv("WEKNORA_API_KEY", "")
t.Setenv("WEKNORA_TOKEN", "jwt-token")
t.Setenv("WEKNORA_HOST", "")
t.Run("host falls back to the active profile when ACADEMY_HOST unset", func(t *testing.T) {
t.Setenv("ACADEMY_API_KEY", "")
t.Setenv("ACADEMY_TOKEN", "jwt-token")
t.Setenv("ACADEMY_HOST", "")
f := &Factory{Config: func() (*config.Config, error) {
return &config.Config{
CurrentProfile: "p",
+7 -7
View File
@@ -10,8 +10,8 @@ import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/format"
"academy/cli/internal/output"
)
// FormatMode is the resolved --format value (typed enum).
@@ -23,7 +23,7 @@ const (
FormatNDJSON FormatMode = "ndjson"
)
// DefaultFormatMode is the mode used when neither --format nor WEKNORA_FORMAT
// DefaultFormatMode is the mode used when neither --format nor ACADEMY_FORMAT
// is set. Single source of truth shared by FormatOptions.ResolveDefault and
// cmd.resolveFormatEarly (the early cobra-parse-error path) so the two cannot
// drift on what "no flag" defaults to.
@@ -159,9 +159,9 @@ func mapJQError(err error) error {
// human-readable output with `--format text`.
func (o *FormatOptions) ResolveDefault(tty bool) {
o.TTY = tty
// Apply WEKNORA_FORMAT before the hard default so the documented
// Apply ACADEMY_FORMAT before the hard default so the documented
// precedence holds: explicit --format (already set on o.Mode by
// CheckFormatFlag) > WEKNORA_FORMAT > DefaultFormatMode. FromEnv is a
// CheckFormatFlag) > ACADEMY_FORMAT > DefaultFormatMode. FromEnv is a
// no-op when --format was passed. Folded in here because nearly every
// command calls ResolveDefault but only a couple called FromEnv, so the
// env var was silently ignored on success output across the CLI.
@@ -171,7 +171,7 @@ func (o *FormatOptions) ResolveDefault(tty bool) {
}
}
// FromEnv reads WEKNORA_FORMAT and applies it when Mode hasn't been set
// FromEnv reads ACADEMY_FORMAT and applies it when Mode hasn't been set
// by --format. ResolveDefault now calls this, so commands get the env var
// applied automatically; explicit callers (e.g. the root PersistentPreRunE,
// which resolves the error-envelope mode before any command RunE) remain
@@ -183,7 +183,7 @@ func (o *FormatOptions) FromEnv() {
if o.Mode != "" {
return
}
v := os.Getenv("WEKNORA_FORMAT")
v := os.Getenv("ACADEMY_FORMAT")
switch v {
case "text", "json", "ndjson":
o.Mode = FormatMode(v)
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/cmdutil"
"academy/cli/internal/output"
)
func TestEmit_WrapsInEnvelope(t *testing.T) {
+11 -11
View File
@@ -213,8 +213,8 @@ func TestCheckFormatFlag_TextAccepted(t *testing.T) {
}
}
func TestFromEnv_AppliesWEKNORA_FORMAT(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "ndjson")
func TestFromEnv_AppliesACADEMY_FORMAT(t *testing.T) {
t.Setenv("ACADEMY_FORMAT", "ndjson")
o := &FormatOptions{}
o.FromEnv()
if o.Mode != FormatNDJSON {
@@ -223,7 +223,7 @@ func TestFromEnv_AppliesWEKNORA_FORMAT(t *testing.T) {
}
func TestFromEnv_PrecedenceFlagOverridesEnv(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "ndjson")
t.Setenv("ACADEMY_FORMAT", "ndjson")
o := &FormatOptions{Mode: FormatJSON}
o.FromEnv()
if o.Mode != FormatJSON {
@@ -232,7 +232,7 @@ func TestFromEnv_PrecedenceFlagOverridesEnv(t *testing.T) {
}
func TestFromEnv_InvalidValueIgnored(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "yaml")
t.Setenv("ACADEMY_FORMAT", "yaml")
o := &FormatOptions{}
o.FromEnv()
if o.Mode != "" {
@@ -241,33 +241,33 @@ func TestFromEnv_InvalidValueIgnored(t *testing.T) {
}
// TestResolveDefault_AppliesEnv pins that ResolveDefault honours
// WEKNORA_FORMAT. Regression: commands call CheckFormatFlag + ResolveDefault
// ACADEMY_FORMAT. Regression: commands call CheckFormatFlag + ResolveDefault
// but (nearly) none called FromEnv, so the documented env var was silently
// ignored on success output across the whole CLI until ResolveDefault folded
// it in. This is the path every command's RunE actually takes.
func TestResolveDefault_AppliesEnv(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "text")
t.Setenv("ACADEMY_FORMAT", "text")
o := &FormatOptions{} // no --format → Mode empty, as after CheckFormatFlag
o.ResolveDefault(false)
if o.Mode != FormatText {
t.Errorf("WEKNORA_FORMAT=text must drive ResolveDefault to text; got %v", o.Mode)
t.Errorf("ACADEMY_FORMAT=text must drive ResolveDefault to text; got %v", o.Mode)
}
}
// TestResolveDefault_FlagBeatsEnv pins precedence: an explicit --format
// (Mode already set) wins over WEKNORA_FORMAT.
// (Mode already set) wins over ACADEMY_FORMAT.
func TestResolveDefault_FlagBeatsEnv(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "text")
t.Setenv("ACADEMY_FORMAT", "text")
o := &FormatOptions{Mode: FormatJSON} // --format json supplied
o.ResolveDefault(false)
if o.Mode != FormatJSON {
t.Errorf("explicit --format json must beat WEKNORA_FORMAT=text; got %v", o.Mode)
t.Errorf("explicit --format json must beat ACADEMY_FORMAT=text; got %v", o.Mode)
}
}
// TestResolveDefault_NoEnvNoFlag_UsesDefault pins the fallback.
func TestResolveDefault_NoEnvNoFlag_UsesDefault(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "")
t.Setenv("ACADEMY_FORMAT", "")
o := &FormatOptions{}
o.ResolveDefault(false)
if o.Mode != DefaultFormatMode {
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"academy/cli/internal/iostreams"
)
// rfc3339Example is the canonical hint shown when a time-flag value isn't RFC3339.
+2 -2
View File
@@ -5,10 +5,10 @@ import (
"fmt"
"regexp"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
// uuidPattern matches the canonical 8-4-4-4-12 UUID form. WeKnora's KB ids
// uuidPattern matches the canonical 8-4-4-4-12 UUID form. Academy's KB ids
// are uuid.New().String() output stored as varchar(36); names are arbitrary
// user-supplied strings, so format-detection is unambiguous.
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
+4 -4
View File
@@ -29,12 +29,12 @@ const LogLevelDefault = "error"
// (typically the root command). Unlike --format (per-command, Method D),
// --log-level is uniformly applied across all SDK calls so it lives on root.
func AddLogLevelFlag(cmd *cobra.Command) {
cmd.PersistentFlags().String("log-level", "", "Log verbosity: error | warn | info | debug (env: WEKNORA_LOG_LEVEL)")
cmd.PersistentFlags().String("log-level", "", "Log verbosity: error | warn | info | debug (env: ACADEMY_LOG_LEVEL)")
}
// ResolveLogLevel resolves the effective log level using priority (high → low):
// 1. --log-level flag (if explicitly set, even from a parent command's persistent flagset)
// 2. WEKNORA_LOG_LEVEL env (if set to a valid value)
// 2. ACADEMY_LOG_LEVEL env (if set to a valid value)
// 3. Default "error"
//
// Invalid env values fall through to the next priority (no error — env is
@@ -51,8 +51,8 @@ func ResolveLogLevel(cmd *cobra.Command, _ io.Writer) (string, bool) {
}
}
// Priority 2: WEKNORA_LOG_LEVEL env (silently skip invalid values).
if v := os.Getenv("WEKNORA_LOG_LEVEL"); v != "" && validLogLevels[v] {
// Priority 2: ACADEMY_LOG_LEVEL env (silently skip invalid values).
if v := os.Getenv("ACADEMY_LOG_LEVEL"); v != "" && validLogLevels[v] {
return v, false
}
+2 -2
View File
@@ -11,7 +11,7 @@ func TestResolveLogLevel(t *testing.T) {
cases := []struct {
name string
flagVal string // "" means flag not set
envVal string // WEKNORA_LOG_LEVEL
envVal string // ACADEMY_LOG_LEVEL
wantLvl string
wantWarn bool
}{
@@ -22,7 +22,7 @@ func TestResolveLogLevel(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("WEKNORA_LOG_LEVEL", tc.envVal)
t.Setenv("ACADEMY_LOG_LEVEL", tc.envVal)
cmd := &cobra.Command{}
AddLogLevelFlag(cmd)
+3 -3
View File
@@ -4,7 +4,7 @@ import (
"context"
"fmt"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
// ModelLister is the narrow SDK surface ResolveModelRef needs. *sdk.Client
@@ -44,10 +44,10 @@ func ResolveModelRef(ctx context.Context, lister ModelLister, ref, wantType stri
msg = fmt.Sprintf("no %s model named %q", wantType, ref)
}
return "", NewError(CodeResourceNotFound, msg).
WithHint("discover models with `weknora model list`")
WithHint("discover models with `academy model list`")
default:
return "", NewError(CodeInputInvalidArgument,
fmt.Sprintf("%q matches %d models — pass the model id instead", ref, len(matches))).
WithHint("`weknora model list` shows the ids")
WithHint("`academy model list` shows the ids")
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
type fakeModelLister struct {
@@ -10,7 +10,7 @@ import (
"sync/atomic"
"testing"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
+3 -3
View File
@@ -24,7 +24,7 @@ func TestSetAgentHelp_PrependsRiskWhenAnnotated(t *testing.T) {
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetErr(&buf)
t.Setenv("WEKNORA_AGENT_HELP", "")
t.Setenv("ACADEMY_AGENT_HELP", "")
cmd.HelpFunc()(cmd, []string{})
@@ -47,7 +47,7 @@ func TestSetAgentHelp_NoRiskWhenUnannotated(t *testing.T) {
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetErr(&buf)
t.Setenv("WEKNORA_AGENT_HELP", "")
t.Setenv("ACADEMY_AGENT_HELP", "")
cmd.HelpFunc()(cmd, []string{})
@@ -64,7 +64,7 @@ func TestSetAgentHelp_JSONPathUnaffectedByRisk(t *testing.T) {
var buf bytes.Buffer
cmd.SetOut(&buf)
cmd.SetErr(&buf)
t.Setenv("WEKNORA_AGENT_HELP", "1")
t.Setenv("ACADEMY_AGENT_HELP", "1")
cmd.HelpFunc()(cmd, []string{})
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"gopkg.in/yaml.v3"
"github.com/Tencent/WeKnora/cli/internal/xdg"
"academy/cli/internal/xdg"
)
const ttl = 24 * time.Hour
+3 -3
View File
@@ -5,7 +5,7 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/compat"
"academy/cli/internal/compat"
)
func TestCache_RoundTrip(t *testing.T) {
@@ -28,8 +28,8 @@ func TestCache_RoundTrip(t *testing.T) {
t.Errorf("ServerVersion = %v, want %q", got, want.ServerVersion)
}
// File should live at $XDG_CACHE_HOME/weknora/server-info.yaml
p := filepath.Join(dir, "weknora", "server-info.yaml")
// File should live at $XDG_CACHE_HOME/academy/server-info.yaml
p := filepath.Join(dir, "academy", "server-info.yaml")
if _, err := filepath.Abs(p); err != nil {
t.Errorf("path resolution: %v", err)
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/compat"
"academy/cli/internal/compat"
)
func TestCompat(t *testing.T) {
+2 -2
View File
@@ -1,5 +1,5 @@
// Package compat probes server `/system/info` and decides client-server
// version skew level. Used by `weknora doctor`'s server_version check.
// version skew level. Used by `academy doctor`'s server_version check.
//
// 24h TTL state file cache, three-tier compat semantics
// (major-mismatch=hard / minor-mismatch=soft / equal=ok).
@@ -10,7 +10,7 @@ import (
"fmt"
"time"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
// Info is the cached server version snapshot.
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"errors"
"testing"
"github.com/Tencent/WeKnora/cli/internal/compat"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/compat"
sdk "academy/client"
)
type fakeProbeClient struct {
+3 -3
View File
@@ -1,7 +1,7 @@
// Package config reads and writes the user-level config at
// $XDG_CONFIG_HOME/weknora/config.yaml. yaml.v3 directly; viper is
// $XDG_CONFIG_HOME/academy/config.yaml. yaml.v3 directly; viper is
// intentionally not used. Multi-host profile map lives here;
// the per-project link (.weknora/project.yaml) is handled by the
// the per-project link (.academy/project.yaml) is handled by the
// projectlink package.
package config
@@ -12,7 +12,7 @@ import (
"gopkg.in/yaml.v3"
"github.com/Tencent/WeKnora/cli/internal/xdg"
"academy/cli/internal/xdg"
)
// Config is the on-disk schema. Empty zero-value is valid (returned when the
+6 -6
View File
@@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/testutil"
"academy/cli/internal/testutil"
)
func TestLoad_FileMissing(t *testing.T) {
@@ -26,7 +26,7 @@ func TestSaveLoad_RoundTrip(t *testing.T) {
in := &Config{
CurrentProfile: "prod",
Profiles: map[string]Profile{
"prod": {Host: "https://kb.example.com", TenantID: 7, APIKeyRef: "keychain://weknora/prod/access"},
"prod": {Host: "https://kb.example.com", TenantID: 7, APIKeyRef: "keychain://academy/prod/access"},
},
}
require.NoError(t, Save(in))
@@ -51,7 +51,7 @@ func TestSaveLoad_RoundTrip(t *testing.T) {
func TestLoad_Corrupt(t *testing.T) {
dir := testutil.XDGTempDir(t)
p := filepath.Join(dir, "weknora", "config.yaml")
p := filepath.Join(dir, "academy", "config.yaml")
require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o700))
require.NoError(t, os.WriteFile(p, []byte("not: valid: yaml: ::"), 0o600))
@@ -65,7 +65,7 @@ func TestPath_HonorsXDG(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", xdg)
p, err := Path()
require.NoError(t, err)
assert.Equal(t, filepath.Join(xdg, "weknora", "config.yaml"), p)
assert.Equal(t, filepath.Join(xdg, "academy", "config.yaml"), p)
}
func TestPath_FallsBackToHome(t *testing.T) {
@@ -75,7 +75,7 @@ func TestPath_FallsBackToHome(t *testing.T) {
require.NoError(t, err)
// Compare via slash-normalized form so the assertion is platform-agnostic
// (Windows uses backslash; semantics here is "the relative tail").
assert.Contains(t, filepath.ToSlash(p), "/.config/weknora/config.yaml")
assert.Contains(t, filepath.ToSlash(p), "/.config/academy/config.yaml")
}
func TestSave_AtomicReplace(t *testing.T) {
@@ -85,6 +85,6 @@ func TestSave_AtomicReplace(t *testing.T) {
out, err := Load()
require.NoError(t, err)
assert.Equal(t, "b", out.CurrentProfile)
matches, _ := filepath.Glob(filepath.Join(dir, "weknora", "*.tmp"))
matches, _ := filepath.Glob(filepath.Join(dir, "academy", "*.tmp"))
assert.Empty(t, matches)
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/format"
"academy/cli/internal/format"
)
func TestWriteJSON_BareArray(t *testing.T) {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"errors"
"testing"
"github.com/Tencent/WeKnora/cli/internal/format"
"academy/cli/internal/format"
)
// A malformed --jq expression must surface as *format.JQError so the cmdutil
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/format"
"academy/cli/internal/format"
)
func TestWriteNDJSON_ArraySplitsPerElement(t *testing.T) {
+1 -1
View File
@@ -1,6 +1,6 @@
package format
import sdk "github.com/Tencent/WeKnora/client"
import sdk "academy/client"
// ReferenceIndex is the bounded citation pointer exposed by projected JSON,
// text, and MCP output. ChunkID is the chunk the model cited; ParentChunkID is
+1 -1
View File
@@ -3,7 +3,7 @@ package format
import (
"testing"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
func TestIndexReferences_ProjectsLookupFieldsWithoutMutation(t *testing.T) {
+6 -6
View File
@@ -1,6 +1,6 @@
// Package mcp wires the curated weknora tool set to an
// Package mcp wires the curated academy tool set to an
// modelcontextprotocol/go-sdk server. RunStdio is the entry point invoked
// by `weknora mcp serve`.
// by `academy mcp serve`.
//
// Design notes:
//
@@ -24,13 +24,13 @@ import (
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/Tencent/WeKnora/cli/internal/build"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/build"
sdk "academy/client"
)
// ServiceClient bundles the SDK methods the tool registry needs. *sdk.Client
// satisfies it; tests substitute a fake to exercise the tool handlers
// in-process without standing up a real WeKnora server.
// in-process without standing up a real Academy server.
//
// Embedding the full SDK Client would couple every tool test to every SDK
// method; declaring the narrow surface here keeps the seam tight.
@@ -52,7 +52,7 @@ func RunStdio(ctx context.Context, svc ServiceClient) error {
v, _, _ := build.Info()
server := mcpsdk.NewServer(
&mcpsdk.Implementation{
Name: "weknora",
Name: "academy",
Version: v,
},
nil,
+4 -4
View File
@@ -12,7 +12,7 @@ import (
)
// TestSkillReferencedMCPToolsExist is part of the K6 drift guard: the MCP tool
// names the bundled `weknora-shared` skill advertises (in its "CLI vs MCP"
// names the bundled `academy-shared` skill advertises (in its "CLI vs MCP"
// section) must all be registered by registerTools. Guards against a skill
// naming a renamed/removed tool (e.g. the agent_invoke→session_ask rename).
func TestSkillReferencedMCPToolsExist(t *testing.T) {
@@ -20,7 +20,7 @@ func TestSkillReferencedMCPToolsExist(t *testing.T) {
if !ok {
t.Fatal("runtime.Caller failed")
}
skillPath := filepath.Join(filepath.Dir(file), "..", "..", "skills", "weknora-shared", "SKILL.md")
skillPath := filepath.Join(filepath.Dir(file), "..", "..", "skills", "academy-shared", "SKILL.md")
raw, err := os.ReadFile(skillPath)
if err != nil {
t.Fatalf("read skill: %v", err)
@@ -30,7 +30,7 @@ func TestSkillReferencedMCPToolsExist(t *testing.T) {
// Slice the "CLI vs MCP" section (heading → next "## " heading).
start := strings.Index(body, "CLI vs MCP")
if start < 0 {
t.Fatal("weknora-shared SKILL.md has no 'CLI vs MCP' section to validate")
t.Fatal("academy-shared SKILL.md has no 'CLI vs MCP' section to validate")
}
section := body[start:]
if end := strings.Index(section, "\n## "); end >= 0 {
@@ -65,7 +65,7 @@ func TestSkillReferencedMCPToolsExist(t *testing.T) {
for name := range referenced {
if !registered[name] {
t.Errorf("weknora-shared skill references MCP tool %q which is NOT registered (renamed/removed?)", name)
t.Errorf("academy-shared skill references MCP tool %q which is NOT registered (renamed/removed?)", name)
}
}
}
+6 -6
View File
@@ -11,9 +11,9 @@ import (
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/sse"
sdk "academy/client"
)
// toolErrorResult builds an error CallToolResult with IsError=true, a
@@ -158,7 +158,7 @@ type kbListOutput struct {
func addKBList(server *mcpsdk.Server, svc knowledgeBaseService) {
mcpsdk.AddTool(server, &mcpsdk.Tool{
Name: "kb_list",
Description: "List all knowledge bases visible to the active WeKnora tenant. No arguments. Returns items[]: each item carries id, name, description, knowledge_count, is_pinned, updated_at - useful for selecting a kb_id to pass to other tools.",
Description: "List all knowledge bases visible to the active Academy tenant. No arguments. Returns items[]: each item carries id, name, description, knowledge_count, is_pinned, updated_at - useful for selecting a kb_id to pass to other tools.",
Annotations: &mcpsdk.ToolAnnotations{
Title: "List Knowledge Bases",
DestructiveHint: bptr(false),
@@ -480,7 +480,7 @@ func addChat(server *mcpsdk.Server, svc chatService) {
}
sessionID := in.SessionID
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp chat"})
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "academy mcp chat"})
if err != nil {
return toolErrorResult(cmdutil.WrapHTTP(err, "create chat session")), nil, nil
}
@@ -598,7 +598,7 @@ func addSessionAsk(server *mcpsdk.Server, svc sessionAskService) {
// agnostic at creation (verified against server source).
sessionID := in.SessionID
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp session_ask"})
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "academy mcp session_ask"})
if err != nil {
return toolErrorResult(cmdutil.WrapHTTP(err, "create chat session")), nil, nil
}
+5 -5
View File
@@ -7,9 +7,9 @@ import (
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/output"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/cmdutil"
"academy/cli/internal/output"
sdk "academy/client"
)
// TestToolErrorResult_TypedError_PopulatesStructuredContent verifies the
@@ -30,8 +30,8 @@ func TestToolErrorResult_TypedError_PopulatesStructuredContent(t *testing.T) {
if sc.Type != "auth.unauthenticated" {
t.Errorf("type: got %v want auth.unauthenticated", sc.Type)
}
// retry_argv should fall back to ["weknora","auth","login"] via cmdutil default
if !reflect.DeepEqual(sc.RetryArgv, []string{"weknora", "auth", "login"}) {
// retry_argv should fall back to ["academy","auth","login"] via cmdutil default
if !reflect.DeepEqual(sc.RetryArgv, []string{"academy", "auth", "login"}) {
t.Errorf("retry_argv: got %v", sc.RetryArgv)
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
// fakeSvc implements every narrow service interface ServiceClient embeds.
@@ -142,7 +142,7 @@ func (f *fakeSvc) ListKnowledgeChunks(_ context.Context, docID string, page, pag
func newTestServer(t *testing.T, svc ServiceClient) (*mcpsdk.ClientSession, context.CancelFunc) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
server := mcpsdk.NewServer(&mcpsdk.Implementation{Name: "weknora-test", Version: "v0.0.0-test"}, nil)
server := mcpsdk.NewServer(&mcpsdk.Implementation{Name: "academy-test", Version: "v0.0.0-test"}, nil)
registerTools(server, svc)
st, ct := mcpsdk.NewInMemoryTransports()
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/output"
)
func TestWriteBatchEnvelope_AllSuccess(t *testing.T) {
+1 -1
View File
@@ -68,7 +68,7 @@ type ErrDetail struct {
ExitCode int `json:"exit_code,omitempty"`
Hint string `json:"hint,omitempty"`
// RetryArgv is a directly-executable argv array (e.g.
// ["weknora","auth","login"]) so an agent can exec it without
// ["academy","auth","login"]) so an agent can exec it without
// shell-splitting or quote-handling. Distinct from the prose Hint.
RetryArgv []string `json:"retry_argv,omitempty"`
RetryAfterSeconds int `json:"retry_after_seconds,omitempty"`
+3 -3
View File
@@ -5,7 +5,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/output"
)
func TestWriteEnvelope_SuccessWithData(t *testing.T) {
@@ -80,7 +80,7 @@ func TestWriteErrorEnvelope_FullShape(t *testing.T) {
Type: "input.confirmation_required",
Message: "kb delete kb_x requires confirmation",
Hint: "re-run with -y/--yes",
RetryArgv: []string{"weknora", "kb", "delete", "kb_x", "-y"},
RetryArgv: []string{"academy", "kb", "delete", "kb_x", "-y"},
Risk: &output.RiskDetail{
Level: "destructive",
Action: "kb.delete",
@@ -96,7 +96,7 @@ func TestWriteErrorEnvelope_FullShape(t *testing.T) {
if !strings.Contains(got, `"type":"input.confirmation_required"`) {
t.Errorf("missing typed code; got %q", got)
}
if !strings.Contains(got, `"retry_argv":["weknora","kb","delete","kb_x","-y"]`) {
if !strings.Contains(got, `"retry_argv":["academy","kb","delete","kb_x","-y"]`) {
t.Errorf("missing retry_argv; got %q", got)
}
if !strings.Contains(got, `"risk":{"level":"destructive","action":"kb.delete"}`) {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/output"
"academy/cli/internal/output"
)
func TestEmitInit_ForcesTypeField(t *testing.T) {
+7 -7
View File
@@ -1,8 +1,8 @@
// Package projectlink reads and writes the per-project link file
// .weknora/project.yaml that anchors a working directory to a profile+KB.
// .academy/project.yaml that anchors a working directory to a profile+KB.
//
// Discovery walks up from the start directory until either (a) a
// .weknora/project.yaml is found, (b) the filesystem root is reached, or
// .academy/project.yaml is found, (b) the filesystem root is reached, or
// (c) the walk exceeds a 64-level depth limit (cycle protection for
// pathological symlink setups). Pattern matches `cargo`, `npm`, and `git`
// - find-the-project's-root walks; mount-boundary crossing is allowed
@@ -16,22 +16,22 @@ import (
"path/filepath"
"time"
"github.com/Tencent/WeKnora/cli/internal/xdg"
"academy/cli/internal/xdg"
"gopkg.in/yaml.v3"
)
// Project is the on-disk schema of .weknora/project.yaml.
// Project is the on-disk schema of .academy/project.yaml.
type Project struct {
Profile string `yaml:"profile,omitempty"`
KBID string `yaml:"kb_id"`
CreatedAt time.Time `yaml:"created_at"`
}
// FileName is the project link file basename relative to .weknora/.
// FileName is the project link file basename relative to .academy/.
const FileName = "project.yaml"
// DirName is the project-link directory name.
const DirName = ".weknora"
const DirName = ".academy"
const maxWalkDepth = 64
@@ -79,7 +79,7 @@ func Load(path string) (*Project, error) {
}
// Save writes the project link to path atomically (0600 perms).
// Creates parent .weknora/ directory if missing.
// Creates parent .academy/ directory if missing.
func Save(path string, p *Project) error {
return xdg.WriteAtomicYAML(path, p)
}
+8 -8
View File
@@ -6,7 +6,7 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/projectlink"
"academy/cli/internal/projectlink"
)
func TestDiscover_FoundInCwd(t *testing.T) {
@@ -19,7 +19,7 @@ func TestDiscover_FoundInCwd(t *testing.T) {
if !found {
t.Fatalf("expected found=true")
}
want := filepath.Join(dir, ".weknora", "project.yaml")
want := filepath.Join(dir, ".academy", "project.yaml")
if got != want {
t.Errorf("got %q, want %q", got, want)
}
@@ -57,7 +57,7 @@ func TestDiscover_NotFound(t *testing.T) {
func TestLoad_RoundTrip(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, ".weknora", "project.yaml")
path := filepath.Join(dir, ".academy", "project.yaml")
in := &projectlink.Project{Profile: "prod", KBID: "kb_abc", CreatedAt: time.Now().UTC().Round(time.Second)}
if err := projectlink.Save(path, in); err != nil {
t.Fatalf("Save: %v", err)
@@ -73,7 +73,7 @@ func TestLoad_RoundTrip(t *testing.T) {
func TestLoad_Corrupt(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, ".weknora", "project.yaml")
path := filepath.Join(dir, ".academy", "project.yaml")
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
@@ -88,12 +88,12 @@ func TestLoad_Corrupt(t *testing.T) {
func TestSave_CreatesParent(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, ".weknora", "project.yaml")
path := filepath.Join(dir, ".academy", "project.yaml")
if err := projectlink.Save(path, &projectlink.Project{KBID: "kb_x"}); err != nil {
t.Fatalf("Save: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, ".weknora")); err != nil {
t.Errorf("parent .weknora not created: %v", err)
if _, err := os.Stat(filepath.Join(dir, ".academy")); err != nil {
t.Errorf("parent .academy not created: %v", err)
}
if _, err := os.Stat(path); err != nil {
t.Errorf("file not created: %v", err)
@@ -102,7 +102,7 @@ func TestSave_CreatesParent(t *testing.T) {
func mkLink(t *testing.T, dir string) {
t.Helper()
d := filepath.Join(dir, ".weknora")
d := filepath.Join(dir, ".academy")
if err := os.MkdirAll(d, 0o700); err != nil {
t.Fatal(err)
}
+2 -2
View File
@@ -8,8 +8,8 @@ import (
)
// keyringService is the namespace prefix passed to OS keyring backends.
// Final keyring entries look like service="weknora:<profile>", account="<key>".
const keyringService = "weknora"
// Final keyring entries look like service="academy:<profile>", account="<key>".
const keyringService = "academy"
// KeyringStore is the OS-backed credential store: macOS Keychain, GNOME
// libsecret, KWallet, Windows Credential Manager. Falls back to ErrUnsupported
+1 -1
View File
@@ -63,5 +63,5 @@ func TestNewBestEffortStore(t *testing.T) {
func TestKeyringStore_Ref(t *testing.T) {
k := NewKeyringStore()
got := k.Ref("prod", "access")
assert.Equal(t, "keychain://weknora/prod/access", got)
assert.Equal(t, "keychain://academy/prod/access", got)
}
+7 -7
View File
@@ -1,9 +1,9 @@
// Package secrets stores and retrieves credentials. Production wires
// KeyringStore (OS keychain, primary) with FileStore (0600 plaintext under
// $XDG_CONFIG_HOME/weknora/secrets/, used as a fallback when no keyring
// $XDG_CONFIG_HOME/academy/secrets/, used as a fallback when no keyring
// backend is available).
//
// Namespace convention: "weknora:<profile>:<key>" where key is "access",
// Namespace convention: "academy:<profile>:<key>" where key is "access",
// "refresh", or "api_key".
package secrets
@@ -14,7 +14,7 @@ import (
"path/filepath"
"strings"
"github.com/Tencent/WeKnora/cli/internal/xdg"
"academy/cli/internal/xdg"
)
// ErrNotFound is returned when the requested secret does not exist.
@@ -23,7 +23,7 @@ var ErrNotFound = errors.New("secret: not found")
// Store is the abstraction CLI commands depend on; tests inject in-memory impls.
//
// Ref returns a stable URI (e.g. file://<profile>/<key> or
// keychain://weknora/<profile>/<key>) describing where a saved secret lives.
// keychain://academy/<profile>/<key>) describing where a saved secret lives.
// Backends own their scheme so commands never need to type-assert the
// concrete implementation.
type Store interface {
@@ -33,14 +33,14 @@ type Store interface {
Ref(profile, key string) string
}
// FileStore writes 0600 plain-text files under $XDG_CONFIG_HOME/weknora/secrets/<profile>.
// FileStore writes 0600 plain-text files under $XDG_CONFIG_HOME/academy/secrets/<profile>.
// It is the headless / CI default and the keychain fallback.
type FileStore struct {
root string
}
// NewFileStore returns a FileStore rooted at $XDG_CONFIG_HOME/weknora/secrets
// (or ~/.config/weknora/secrets if XDG_CONFIG_HOME is unset). Same convention
// NewFileStore returns a FileStore rooted at $XDG_CONFIG_HOME/academy/secrets
// (or ~/.config/academy/secrets if XDG_CONFIG_HOME is unset). Same convention
// as config.Path - see that file for the rationale (CLI convention).
func NewFileStore() (*FileStore, error) {
root, err := defaultRoot()
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/testutil"
"academy/cli/internal/testutil"
)
func TestFileStore_RoundTrip(t *testing.T) {
+8 -8
View File
@@ -1,4 +1,4 @@
// Package skillparity contains the K6 drift guard: every weknora command and
// Package skillparity contains the K6 drift guard: every academy command and
// long flag referenced in a bundled Agent Skill (cli/skills/**) must still
// exist in the live cobra command tree. A skill that references a renamed or
// removed flag/command is worse than no skill, so this fails CI on drift.
@@ -15,8 +15,8 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/Tencent/WeKnora/cli/cmd"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"academy/cli/cmd"
"academy/cli/internal/cmdutil"
)
var (
@@ -85,17 +85,17 @@ func TestSkillsReferenceLiveCommandsAndFlags(t *testing.T) {
}
// Normalize CRLF → LF before parsing: Windows CI checks out *.md with
// CRLF (git autocrlf), and the \n-anchored codeFence regex would never
// match ```weknora\r\n, resolving zero commands. Keep the tokenizer
// match ```academy\r\n, resolving zero commands. Keep the tokenizer
// OS-independent rather than depend on checkout line endings.
content := strings.ReplaceAll(string(raw), "\r\n", "\n")
rel, _ := filepath.Rel(skillsRoot(t), path)
for _, block := range codeFence.FindAllStringSubmatch(content, -1) {
for _, line := range strings.Split(block[1], "\n") {
idx := strings.Index(line, "weknora ")
idx := strings.Index(line, "academy ")
if idx < 0 {
continue
}
inv := line[idx+len("weknora"):]
inv := line[idx+len("academy"):]
toks := strings.Fields(inv)
if len(toks) == 0 {
continue
@@ -112,7 +112,7 @@ func TestSkillsReferenceLiveCommandsAndFlags(t *testing.T) {
i++ // consume the value
}
}
// Placeholder command (e.g. `weknora <command> --help`) → skip.
// Placeholder command (e.g. `academy <command> --help`) → skip.
if i < len(toks) && strings.HasPrefix(toks[i], "<") {
continue
}
@@ -140,7 +140,7 @@ func TestSkillsReferenceLiveCommandsAndFlags(t *testing.T) {
}
}
if !checkedAny {
t.Fatal("parser resolved no weknora commands from skills — check tokenizer")
t.Fatal("parser resolved no academy commands from skills — check tokenizer")
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
// Package sse provides helpers for consuming server-sent event streams from
// the WeKnora SDK (KnowledgeQAStream, ContinueStream).
// the Academy SDK (KnowledgeQAStream, ContinueStream).
//
// Accumulator is the canonical sink: every callback event appends to a
// buffered Content string and updates terminal-state fields like References
@@ -11,7 +11,7 @@ package sse
import (
"strings"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
// Accumulator buffers a KnowledgeQAStream callback sequence.
+2 -2
View File
@@ -3,8 +3,8 @@ package sse_test
import (
"testing"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/sse"
sdk "academy/client"
)
// terminator is the canonical "stream is done" event the accumulator
+1 -1
View File
@@ -3,7 +3,7 @@ package sse
import (
"strings"
sdk "github.com/Tencent/WeKnora/client"
sdk "academy/client"
)
// AgentToolEvent captures one tool_call / tool_result event from an
+2 -2
View File
@@ -3,8 +3,8 @@ package sse_test
import (
"testing"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/sse"
sdk "academy/client"
)
func TestAgentAccumulator_FinalizesOnlyOnComplete(t *testing.T) {
+2 -2
View File
@@ -6,8 +6,8 @@ import (
"io"
"strings"
"github.com/Tencent/WeKnora/cli/internal/format"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/format"
sdk "academy/client"
)
// ProjectedEvent is the bounded event representation shared by
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
"academy/cli/internal/sse"
sdk "academy/client"
)
func TestProjector_DefaultKeepsOnlyAnswerEvents(t *testing.T) {
+1 -1
View File
@@ -1,7 +1,7 @@
package testutil
import (
"github.com/Tencent/WeKnora/cli/internal/prompt"
"academy/cli/internal/prompt"
)
// ConfirmPrompter is a test double for prompt.Prompter that scripts a single
+1 -1
View File
@@ -11,7 +11,7 @@ import (
// XDGTempDir creates a fresh temp dir and points XDG_CONFIG_HOME at it for the
// duration of t. Use whenever a test exercises code that reads
// $XDG_CONFIG_HOME/weknora/* (config.Load, secrets.NewFileStore, ...).
// $XDG_CONFIG_HOME/academy/* (config.Load, secrets.NewFileStore, ...).
func XDGTempDir(t *testing.T) string {
t.Helper()
dir := t.TempDir()
+2 -2
View File
@@ -3,8 +3,8 @@ package text
// KnowledgeDisplayName picks the most informative human label for a
// knowledge entry. File-uploads use FileName; URL / text entries fall
// back to Title; the ID is the last-resort placeholder so a table cell
// is never empty. Single source for the ordering - `weknora doc list`
// and `weknora search docs` both call this so a Knowledge renders
// is never empty. Single source for the ordering - `academy doc list`
// and `academy search docs` both call this so a Knowledge renders
// identically in either command.
//
// Takes the three fields directly rather than `sdk.Knowledge` so this
+1 -1
View File
@@ -3,7 +3,7 @@ package text_test
import (
"testing"
"github.com/Tencent/WeKnora/cli/internal/text"
"academy/cli/internal/text"
)
func TestOneLine(t *testing.T) {
+1 -1
View File
@@ -3,7 +3,7 @@ package text_test
import (
"testing"
"github.com/Tencent/WeKnora/cli/internal/text"
"academy/cli/internal/text"
)
func TestPluralize(t *testing.T) {
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/text"
"academy/cli/internal/text"
)
func TestFuzzyAgoStr(t *testing.T) {
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/text"
"academy/cli/internal/text"
)
func TestFuzzyAgo(t *testing.T) {
+1 -1
View File
@@ -3,7 +3,7 @@ package text_test
import (
"testing"
"github.com/Tencent/WeKnora/cli/internal/text"
"academy/cli/internal/text"
)
func TestTruncate(t *testing.T) {
+3 -3
View File
@@ -15,19 +15,19 @@ import (
// Path resolves an XDG-rooted file. envVar is one of "XDG_CONFIG_HOME" /
// "XDG_CACHE_HOME" / "XDG_DATA_HOME". fallbackDir is the dot-prefixed dir
// under $HOME used when the env var is unset (".config" / ".cache" / etc.).
// parts join under "weknora/" inside the chosen root.
// parts join under "academy/" inside the chosen root.
//
// Honors the XDG vars on every OS, even macOS - where os.UserConfigDir
// would otherwise return ~/Library/Application Support.
func Path(envVar, fallbackDir string, parts ...string) (string, error) {
if x := os.Getenv(envVar); x != "" {
return filepath.Join(append([]string{x, "weknora"}, parts...)...), nil
return filepath.Join(append([]string{x, "academy"}, parts...)...), nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("locate home dir: %w", err)
}
return filepath.Join(append([]string{home, fallbackDir, "weknora"}, parts...)...), nil
return filepath.Join(append([]string{home, fallbackDir, "academy"}, parts...)...), nil
}
// WriteAtomicYAML marshals v to YAML and writes it atomically at p with mode
+4 -4
View File
@@ -7,7 +7,7 @@ import (
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/xdg"
"academy/cli/internal/xdg"
)
func TestPath_HonorsEnv(t *testing.T) {
@@ -17,7 +17,7 @@ func TestPath_HonorsEnv(t *testing.T) {
if err != nil {
t.Fatalf("Path: %v", err)
}
want := filepath.Join(dir, "weknora", "config.yaml")
want := filepath.Join(dir, "academy", "config.yaml")
if got != want {
t.Errorf("got %q, want %q", got, want)
}
@@ -32,8 +32,8 @@ func TestPath_FallsBackToHome(t *testing.T) {
if !filepath.IsAbs(got) {
t.Errorf("expected absolute path, got %q", got)
}
if !strings.Contains(got, ".cache") || !strings.Contains(got, "weknora") {
t.Errorf("expected ~/.cache/weknora prefix, got %q", got)
if !strings.Contains(got, ".cache") || !strings.Contains(got, "academy") {
t.Errorf("expected ~/.cache/academy prefix, got %q", got)
}
}