refactor(cli): drop aiclient package; align AGENTS.md with mainstream
Survey of 10 mainstream CLIs (gh, lark, stripe, vercel, supabase, aws, azure, gcloud, openai/codex, github-copilot-cli) showed env-gated per-command --help blurbs are a Stripe-only pattern; gh uses env detect for telemetry only, and lark relies on installed agent Skills + MCP. Our cmd/mcp/serve already covers the dominant 2025/26 path, so internal/aiclient/ (136 LOC + 38 callsites) is net maintenance burden without precedent. - Drop internal/aiclient/ entirely (annotations + detect + tests) - Remove 38 SetAgentHelp callsites + agentAwareHelpFunc / SetHelpFunc wiring in cmd/root.go - Migrate 4 command-level rules to standard Long help (visible to all, not env-gated): doc upload mode mutex, kb edit at-least-one, kb pin idempotent, search chunks channel mutex - Rewrite AGENTS.md as a developer guide (gh-style 6 H2 / 167 lines): audience preamble + Build / Architecture / Command Structure / Testing / Code Style / Error Handling. Drops sections absent in surveyed projects (Commit & PR Conventions, Who Uses This CLI) - Clean 14 internal doc refs (ADR-N, spec §X, v0.X) in source comments and docs that pointed at docs/superpowers/ — that directory is local-only / uncommitted, so refs are dead for outside readers - Drop forward-looking "once v0.2 ships" from README
This commit is contained in:
@@ -1,35 +0,0 @@
|
||||
package aiclient
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// AIAgentHelpKey is the cobra Annotation key used to attach an AI-agent-specific
|
||||
// help blurb to a command. The blurb is appended to --help output only when
|
||||
// agent mode is active.
|
||||
const AIAgentHelpKey = "ai_agent_help"
|
||||
|
||||
// FormatAgentGuidance returns the agent-targeted help text registered on cmd,
|
||||
// or "" if none. Render it after the standard help when DetectAIAgent() != ""
|
||||
// (an AI coding agent env var is set).
|
||||
func FormatAgentGuidance(cmd *cobra.Command) string {
|
||||
if cmd == nil {
|
||||
return ""
|
||||
}
|
||||
v, ok := cmd.Annotations[AIAgentHelpKey]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
|
||||
// SetAgentHelp is a small helper that initializes Annotations and stores the
|
||||
// blurb under AIAgentHelpKey. Use it in NewCmdX constructors before returning.
|
||||
func SetAgentHelp(cmd *cobra.Command, blurb string) {
|
||||
if cmd.Annotations == nil {
|
||||
cmd.Annotations = map[string]string{}
|
||||
}
|
||||
cmd.Annotations[AIAgentHelpKey] = strings.TrimSpace(blurb)
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Package aiclient handles AI agent integration: env-based detection
|
||||
// (used to trigger AGENT-targeted help text) and per-command help
|
||||
// annotations. See cli/AGENTS.md for the full agent contract.
|
||||
package aiclient
|
||||
|
||||
import "os"
|
||||
|
||||
// AIAgentName identifies the detected coding agent invoking the CLI. Empty
|
||||
// string means no agent detected (or detection is disabled).
|
||||
type AIAgentName string
|
||||
|
||||
// aiAgentEnvs maps environment variable presence to a coding agent name.
|
||||
// The earlier 7-entry list (CODEX_*, AIDER_PROMPT, CONTINUE_GLOBAL_DIR,
|
||||
// OPENCODE_RUNNING, GEMINICODER_PROFILE) did not have official agent docs
|
||||
// backing those env names; removed in v0.2 to avoid maintaining an
|
||||
// unverified hardcoded list. New entries should document the source URL.
|
||||
var aiAgentEnvs = []struct {
|
||||
env string
|
||||
name AIAgentName
|
||||
}{
|
||||
{"CLAUDECODE", "claude-code"},
|
||||
{"CURSOR_AGENT", "cursor"},
|
||||
}
|
||||
|
||||
// DetectAIAgent returns the first known agent name whose env var is set to a
|
||||
// non-empty value, or "" if none are present. Detection is suppressed when
|
||||
// WEKNORA_NO_AGENT_AUTODETECT is truthy. Tests substitute via t.Setenv.
|
||||
func DetectAIAgent() AIAgentName {
|
||||
if v := os.Getenv("WEKNORA_NO_AGENT_AUTODETECT"); v != "" && v != "0" && v != "false" {
|
||||
return ""
|
||||
}
|
||||
for _, a := range aiAgentEnvs {
|
||||
if os.Getenv(a.env) != "" {
|
||||
return a.name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package aiclient
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// clearAgentEnv unsets every env var DetectAIAgent inspects, so a developer
|
||||
// running these tests from inside Claude Code / Cursor doesn't see false
|
||||
// positives.
|
||||
func clearAgentEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, a := range aiAgentEnvs {
|
||||
t.Setenv(a.env, "")
|
||||
}
|
||||
t.Setenv("WEKNORA_NO_AGENT_AUTODETECT", "")
|
||||
t.Setenv("WEKNORA_AGENT", "")
|
||||
}
|
||||
|
||||
func TestDetectAIAgent(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
set map[string]string
|
||||
want AIAgentName
|
||||
}{
|
||||
{name: "empty env", set: nil, want: ""},
|
||||
{name: "unrelated env", set: map[string]string{"PATH": "/usr/bin"}, want: ""},
|
||||
{name: "claude code", set: map[string]string{"CLAUDECODE": "1"}, want: "claude-code"},
|
||||
{name: "cursor", set: map[string]string{"CURSOR_AGENT": "yes"}, want: "cursor"},
|
||||
// Other entries (codex / aider / continue / opencode / gemini-coder)
|
||||
// were dropped — those env names had no official agent docs.
|
||||
// New entries should arrive with a documented source URL.
|
||||
{
|
||||
name: "first-match precedence",
|
||||
set: map[string]string{"CLAUDECODE": "1", "CURSOR_AGENT": "1"},
|
||||
want: "claude-code",
|
||||
},
|
||||
{name: "empty value treated as unset", set: map[string]string{"CLAUDECODE": ""}, want: ""},
|
||||
{
|
||||
name: "WEKNORA_NO_AGENT_AUTODETECT=1 suppresses detection",
|
||||
set: map[string]string{"CLAUDECODE": "1", "WEKNORA_NO_AGENT_AUTODETECT": "1"},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "WEKNORA_NO_AGENT_AUTODETECT=0 still allows detection",
|
||||
set: map[string]string{"CLAUDECODE": "1", "WEKNORA_NO_AGENT_AUTODETECT": "0"},
|
||||
want: "claude-code",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
clearAgentEnv(t)
|
||||
for k, v := range tc.set {
|
||||
t.Setenv(k, v)
|
||||
}
|
||||
assert.Equal(t, tc.want, DetectAIAgent())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ type Refresher interface {
|
||||
// retry the original request).
|
||||
//
|
||||
// Single canonical implementation shared by `weknora auth refresh` and the
|
||||
// AuthRetryTransport's refresh closure — both used to inline the same
|
||||
// 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, ctxName string) (string, error) {
|
||||
refresh, err := store.Get(ctxName, "refresh")
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
// - 401 on /api/v1/auth/login or /api/v1/auth/refresh: pass through
|
||||
// (otherwise a stale refresh token causes infinite recursion).
|
||||
// - 401 with no initial token configured (api-key contexts): pass through
|
||||
// — api-key credentials have no refresh semantic.
|
||||
// - api-key credentials have no refresh semantic.
|
||||
// - 401 with non-replayable request body (req.GetBody == nil): pass
|
||||
// through. The SDK always uses bytes.Buffer bodies; this is a safety
|
||||
// net for hand-built requests.
|
||||
@@ -31,7 +31,7 @@ import (
|
||||
// the updated currentToken and replay without re-refreshing (singleflight).
|
||||
//
|
||||
// The transport intentionally shadows the SDK's bearerToken (set via
|
||||
// WithBearerToken). After a refresh, the SDK is unaware of the new token —
|
||||
// WithBearerToken). After a refresh, the SDK is unaware of the new token -
|
||||
// the transport's per-request override is the single source of truth for
|
||||
// the Authorization header. Tokens persisted to the secrets store happen
|
||||
// inside refreshFn (see cmdutil.RefreshAndPersist).
|
||||
@@ -49,7 +49,7 @@ type AuthRetryTransport struct {
|
||||
//
|
||||
// Pass an empty initialToken to indicate "no bearer credential configured"
|
||||
// (e.g. an api-key context). In that mode the transport never invokes
|
||||
// refreshFn — a 401 is propagated as-is.
|
||||
// refreshFn - a 401 is propagated as-is.
|
||||
func NewAuthRetryTransport(base http.RoundTripper, initialToken string, refreshFn func(context.Context) (string, error)) *AuthRetryTransport {
|
||||
if base == nil {
|
||||
base = http.DefaultTransport
|
||||
|
||||
@@ -172,7 +172,7 @@ func TestAuthRetry_SkipAuthEndpoints(t *testing.T) {
|
||||
func TestAuthRetry_NoTokenConfigured_DoesNotInjectAuthz(t *testing.T) {
|
||||
// API-key contexts construct the transport with an empty initial token;
|
||||
// authretry should pass through 401s untouched (no refresh callback exists
|
||||
// for api-key — they're rejected at the auth-refresh layer).
|
||||
// for api-key - they're rejected at the auth-refresh layer).
|
||||
base := &stubTransport{t: t, resps: []*http.Response{resp(401, "")}}
|
||||
refreshed := false
|
||||
rt := NewAuthRetryTransport(base, "", func(context.Context) (string, error) {
|
||||
@@ -192,7 +192,7 @@ func TestAuthRetry_NoTokenConfigured_DoesNotInjectAuthz(t *testing.T) {
|
||||
func TestAuthRetry_ConcurrentRefresh_SingleFlight(t *testing.T) {
|
||||
// 4 parallel 401s should trigger exactly 1 refresh; all 4 then retry with
|
||||
// the new token. Use a server that 401s first request from each unique
|
||||
// path then 200s on retry — except we use one shared transport with
|
||||
// path then 200s on retry - except we use one shared transport with
|
||||
// scripted responses, ordering matters. To keep determinism, build a
|
||||
// transport that always returns 401 on first call per request, 200 on
|
||||
// second, and gate the refresh callback.
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
//
|
||||
// The non-TTY branch is the destructive-write protocol: high-risk writes
|
||||
// always require explicit confirmation in scripted contexts, never silent
|
||||
// proceed. See cli/AGENTS.md "Exit codes".
|
||||
// proceed. See cli/README.md "Exit codes".
|
||||
//
|
||||
// `yes` should be sourced from the persistent global -y/--yes flag.
|
||||
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error {
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
type ErrorCode string
|
||||
|
||||
const (
|
||||
// auth.* — authentication / permission
|
||||
// auth.* - authentication / permission
|
||||
CodeAuthUnauthenticated ErrorCode = "auth.unauthenticated"
|
||||
CodeAuthTokenExpired ErrorCode = "auth.token_expired"
|
||||
CodeAuthBadCredential ErrorCode = "auth.bad_credential"
|
||||
@@ -28,12 +28,12 @@ const (
|
||||
CodeResourceAlreadyExists ErrorCode = "resource.already_exists"
|
||||
CodeResourceLocked ErrorCode = "resource.locked"
|
||||
|
||||
// input.* — flag and argument validation
|
||||
// input.* - flag and argument validation
|
||||
CodeInputInvalidArgument ErrorCode = "input.invalid_argument"
|
||||
CodeInputMissingFlag ErrorCode = "input.missing_flag"
|
||||
// CodeInputConfirmationRequired marks a high-risk write that has no
|
||||
// interactive UI (non-TTY or --json) and was invoked without -y/--yes.
|
||||
// Mapped to exit code 10 (see cli/AGENTS.md). Agents must surface the
|
||||
// Mapped to exit code 10 (see cli/README.md). Agents must surface the
|
||||
// error to the user and only retry with -y after explicit human
|
||||
// approval; never auto-retry.
|
||||
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
|
||||
@@ -49,13 +49,13 @@ const (
|
||||
// server.error so agents can retry with their own --session.
|
||||
CodeSessionCreateFailed ErrorCode = "server.session_create_failed"
|
||||
|
||||
// local.* — config / file / keychain on the user's machine
|
||||
// local.* - config / file / keychain on the user's machine
|
||||
CodeLocalConfigCorrupt ErrorCode = "local.config_corrupt"
|
||||
CodeLocalKeychainDenied ErrorCode = "local.keychain_denied"
|
||||
CodeLocalFileIO ErrorCode = "local.file_io"
|
||||
CodeLocalUnimplemented ErrorCode = "local.unimplemented"
|
||||
CodeLocalContextNotFound ErrorCode = "local.context_not_found"
|
||||
// v0.2 KB-resolution chain (spec §1.3) and project-link (spec §2.4) codes.
|
||||
// KB-resolution chain and project-link codes.
|
||||
CodeKBIDRequired ErrorCode = "local.kb_id_required"
|
||||
CodeKBNotFound ErrorCode = "local.kb_not_found"
|
||||
CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
|
||||
@@ -124,7 +124,7 @@ func Wrapf(code ErrorCode, cause error, format string, args ...any) *Error {
|
||||
// from its HTTP shape (404 → resource.not_found, 401 → auth.unauthenticated,
|
||||
// non-HTTP → network.error, …). Shortcut for the universal pattern
|
||||
// `Wrapf(ClassifyHTTPError(err), err, format, args...)` used by every SDK
|
||||
// call site — single source for the wrap-and-classify policy.
|
||||
// call site - single source for the wrap-and-classify policy.
|
||||
//
|
||||
// Use this for any error returned from a wire call. Stays paired with
|
||||
// ClassifyHTTPErrorOutputs() in the acceptance/contract test, which
|
||||
@@ -150,7 +150,7 @@ var SilentError = errors.New("silent error (handled)")
|
||||
// CancelError marks a user-cancelled operation (Ctrl-C / "no" at confirm).
|
||||
var CancelError = errors.New("operation cancelled")
|
||||
|
||||
// Typed predicates — use these instead of comparing ErrorCode strings.
|
||||
// Typed predicates - use these instead of comparing ErrorCode strings.
|
||||
// They walk the error chain so wrapped errors still match.
|
||||
|
||||
// IsAuthError matches any auth.* code.
|
||||
@@ -285,6 +285,6 @@ func ClassifyHTTPErrorOutputs() []ErrorCode {
|
||||
CodeServerRateLimited, // 429
|
||||
CodeServerError, // 5xx / parse-failure / default
|
||||
CodeInputInvalidArgument, // 4xx (else)
|
||||
CodeNetworkError, // 非 HTTP error
|
||||
CodeNetworkError, // non-HTTP error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ func TestAllCodes_NonEmpty(t *testing.T) {
|
||||
if len(codes) == 0 {
|
||||
t.Fatal("AllCodes() should return registered codes")
|
||||
}
|
||||
// Sentinel: 至少包含这几个 v0.0 已知 code
|
||||
// Sentinel: contains the baseline error codes the registry must always carry.
|
||||
want := map[cmdutil.ErrorCode]bool{
|
||||
cmdutil.CodeAuthUnauthenticated: false,
|
||||
cmdutil.CodeResourceNotFound: false,
|
||||
|
||||
@@ -6,9 +6,9 @@ import (
|
||||
"io"
|
||||
)
|
||||
|
||||
// ExitCode maps an error to the documented CLI exit code (spec §2.4 + ADR-3).
|
||||
// ExitCode maps an error to the documented CLI exit code.
|
||||
// - 0 success
|
||||
// - 1 generic / unknown typed error — fallback for: resource.already_exists,
|
||||
// - 1 generic / unknown typed error - fallback for: resource.already_exists,
|
||||
// resource.locked, local.* (config_corrupt / keychain_denied / file_io /
|
||||
// context_not_found / kb_id_required / kb_not_found / projectlink_corrupt /
|
||||
// user_aborted / upload_file_not_found), mcp.*, server.session_create_failed,
|
||||
@@ -19,8 +19,8 @@ import (
|
||||
// - 5 input.* (other than confirmation_required)
|
||||
// - 6 server.rate_limited
|
||||
// - 7 server.* (other than rate_limited/session_create_failed) / network.*
|
||||
// - 10 input.confirmation_required — high-risk write needs explicit -y
|
||||
// (see cli/AGENTS.md)
|
||||
// - 10 input.confirmation_required - high-risk write needs explicit -y
|
||||
// (see cli/README.md)
|
||||
// - 130 SIGINT (handled by Go runtime, not this function)
|
||||
func ExitCode(err error) int {
|
||||
if err == nil {
|
||||
@@ -77,7 +77,7 @@ func PrintError(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 `weknora 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.
|
||||
@@ -104,7 +104,7 @@ func defaultHint(code ErrorCode) string {
|
||||
case CodeInputInvalidArgument, CodeInputMissingFlag:
|
||||
return "see `weknora <command> --help` for valid usage"
|
||||
case CodeInputConfirmationRequired:
|
||||
return "high-risk write — re-run with -y/--yes after the user explicitly approves"
|
||||
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:
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
// closure is lazy: --help / completion / `weknora version` must NOT trigger
|
||||
// HTTP, keyring access, or filesystem I/O beyond the bare minimum.
|
||||
//
|
||||
// Four closures (ADR-4):
|
||||
// Four closures:
|
||||
// - Config: parses ~/.config/weknora/config.yaml (no network)
|
||||
// - Client: constructs the SDK client; only Secrets is sync.Once-cached,
|
||||
// so callers should hold the returned *sdk.Client across
|
||||
@@ -33,13 +33,13 @@ import (
|
||||
// would fork+exec on macOS and DBus-touch on Linux,
|
||||
// defeating the lazy contract above).
|
||||
//
|
||||
// IOStreams is intentionally NOT a Factory closure — it is the package singleton
|
||||
// IOStreams is intentionally NOT a Factory closure - it is the package singleton
|
||||
// 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
|
||||
// service interfaces (per ADR-4) declare them in their own files and let the
|
||||
// real SDK satisfy them implicitly via duck typing.
|
||||
// service interfaces declare them in their own files and let the real SDK
|
||||
// satisfy them implicitly via duck typing.
|
||||
type Factory struct {
|
||||
Config func() (*config.Config, error)
|
||||
Client func() (*sdk.Client, error)
|
||||
@@ -47,9 +47,8 @@ type Factory struct {
|
||||
Secrets func() (secrets.Store, error)
|
||||
|
||||
// ContextOverride, if non-empty, replaces config.CurrentContext for this
|
||||
// invocation only — set by the global --context flag in PersistentPreRun.
|
||||
// Buildable Config() / Client() honor it without writing to disk; matches
|
||||
// spec §1.2 "weknora --context foo kb list = single-shot override".
|
||||
// invocation only - set by the global --context flag in PersistentPreRun.
|
||||
// Buildable Config() / Client() honor it without writing to disk.
|
||||
ContextOverride string
|
||||
}
|
||||
|
||||
@@ -59,7 +58,7 @@ type Factory struct {
|
||||
// none of them. Client and Secrets closures memoize via sync.Once so the
|
||||
// SDK client is built (and the keyring is probed) at most once per process,
|
||||
// even when Factory.ResolveKB internally calls f.Client() before the
|
||||
// command's RunE calls it again — without this, name-resolved --kb paths
|
||||
// command's RunE calls it again - without this, name-resolved --kb paths
|
||||
// would build two clients with two AuthRetryTransports holding independent
|
||||
// token state.
|
||||
func New() *Factory {
|
||||
@@ -157,7 +156,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
// 401-retry transport: on the first 401 from a non-/auth/* endpoint, the
|
||||
// transport reads the stored refresh token, calls /api/v1/auth/refresh,
|
||||
// persists the new pair, and replays the original request with the new
|
||||
// bearer. API-key contexts skip this (no refresh semantic) — a 401 from
|
||||
// bearer. API-key contexts skip this (no refresh semantic) - a 401 from
|
||||
// them propagates as auth.unauthenticated for the caller to handle.
|
||||
if ctx.TokenRef != "" && ctx.RefreshRef != "" {
|
||||
refreshFn := func(rctx context.Context) (string, error) {
|
||||
@@ -171,9 +170,8 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
// tenant from the credential itself (JWT claim or API key prefix); the
|
||||
// header is only meaningful for explicit cross-tenant switching by users
|
||||
// with CanAccessAllTenants. Auto-mirroring the persisted tenant from config
|
||||
// breaks that contract — explicit flags (`--tenant=N` is the planned v0.1
|
||||
// entry point) are required before sending it. `tenant_id` stays in config
|
||||
// for `auth status` display only.
|
||||
// breaks that contract - explicit cross-tenant flags would be required
|
||||
// before sending it. `tenant_id` stays in config for `auth status` display only.
|
||||
return sdk.NewClient(ctx.Host, opts...), nil
|
||||
}
|
||||
|
||||
@@ -231,7 +229,7 @@ func LoadSecret(store secrets.Store, context, key string) (string, error) {
|
||||
|
||||
// refreshAccessToken is the closure target injected into AuthRetryTransport's
|
||||
// refreshFn. A fresh SDK Client is built here rather than reusing the one
|
||||
// being constructed — that one is itself wrapped by the transport, which
|
||||
// being constructed - that one is itself wrapped by the transport, which
|
||||
// would recurse on refresh. The refresh endpoint is unauthenticated apart
|
||||
// from the refresh token in the body, so no credential options are needed.
|
||||
func refreshAccessToken(ctx context.Context, store secrets.Store, host, ctxName string) (string, error) {
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
)
|
||||
|
||||
// TestFactory_Lazy ensures none of the closures execute work at construction
|
||||
// time — `--help` / `completion` must not trigger HTTP / keyring access.
|
||||
// time - `--help` / `completion` must not trigger HTTP / keyring access.
|
||||
func TestFactory_Lazy(t *testing.T) {
|
||||
var configCalls, clientCalls, prompterCalls int
|
||||
f := &Factory{
|
||||
@@ -39,7 +39,7 @@ func TestFactory_Lazy(t *testing.T) {
|
||||
return prompt.AgentPrompter{}
|
||||
},
|
||||
}
|
||||
// Asserting on closure presence — none should have run yet.
|
||||
// Asserting on closure presence - none should have run yet.
|
||||
assert.Equal(t, 0, configCalls)
|
||||
assert.Equal(t, 0, clientCalls)
|
||||
assert.Equal(t, 0, prompterCalls)
|
||||
@@ -74,7 +74,7 @@ func TestNew_FoundationDefaults(t *testing.T) {
|
||||
|
||||
// TestFactory_ContextOverride verifies the global --context flag mechanism:
|
||||
// f.ContextOverride replaces config.CurrentContext for this invocation only,
|
||||
// without writing to disk. Spec §1.2.
|
||||
// without writing to disk.
|
||||
func TestFactory_ContextOverride(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", dir)
|
||||
@@ -234,7 +234,7 @@ func TestBuildClient_HappyPath(t *testing.T) {
|
||||
|
||||
func TestBuildClient_SkipsUnreferencedSecrets(t *testing.T) {
|
||||
// If the context doesn't list APIKeyRef, buildClient must not call
|
||||
// Get(api_key) — a perf invariant: avoid keychain trips for unused creds.
|
||||
// Get(api_key) - a perf invariant: avoid keychain trips for unused creds.
|
||||
store := &countingSecrets{MemStore: secrets.NewMemStore()}
|
||||
require.NoError(t, store.Set("p", "access", "jwt"))
|
||||
f := &Factory{
|
||||
@@ -310,7 +310,7 @@ func TestResolveKB_Chain(t *testing.T) {
|
||||
t.Setenv("WEKNORA_KB_ID", "kb_env_should_lose")
|
||||
dir := t.TempDir()
|
||||
resolveKBChdir(t, dir)
|
||||
// Drop a project link too — must be ignored.
|
||||
// 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"}))
|
||||
|
||||
clientCalls := 0
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
// NormalizeHost validates and canonicalizes a `--host` value. Trailing
|
||||
// slashes are trimmed. Every failure path returns CodeInputInvalidArgument —
|
||||
// slashes are trimmed. Every failure path returns CodeInputInvalidArgument -
|
||||
// a present-but-empty flag is treated as a bad value, not as a missing flag
|
||||
// (cobra's required-flag layer is what catches the absent case).
|
||||
//
|
||||
@@ -30,7 +30,7 @@ func NormalizeHost(host string) (string, error) {
|
||||
// ValidateHTTPURL applies the same http/https URL rules NormalizeHost uses,
|
||||
// but parameterized by flagLabel so error messages name the caller's flag
|
||||
// (e.g. "--host", "--from-url"). Returns CodeInputInvalidArgument on any
|
||||
// failure. Empty `value` is not pre-checked here — callers that distinguish
|
||||
// failure. Empty `value` is not pre-checked here - callers that distinguish
|
||||
// "missing" from "malformed" should test for empty before calling.
|
||||
func ValidateHTTPURL(flagLabel, value string) error {
|
||||
u, err := url.Parse(value)
|
||||
|
||||
@@ -118,7 +118,7 @@ func TestAddJSONFlags_JQWithoutJSON(t *testing.T) {
|
||||
if err.Error() != want {
|
||||
t.Errorf("wrong message.\nwant: %q\ngot: %q", want, err.Error())
|
||||
}
|
||||
// Must NOT be a FlagError — gh emits this as a plain error so exit
|
||||
// Must NOT be a FlagError - gh emits this as a plain error so exit
|
||||
// code stays 1, not 2.
|
||||
var fe *cmdutil.FlagError
|
||||
if errors.As(err, &fe) {
|
||||
|
||||
@@ -38,7 +38,7 @@ func ResolveKBFlag(ctx context.Context, lister KBLister, raw string) (string, er
|
||||
}
|
||||
|
||||
// ResolveKBNameToID looks up a knowledge base by name and returns its ID.
|
||||
// Used by `link` and `Factory.ResolveKB` — a single lookup so the match
|
||||
// Used by `link` and `Factory.ResolveKB` - a single lookup so the match
|
||||
// policy (currently exact case-sensitive) lives in one place.
|
||||
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
|
||||
kbs, err := lister.ListKnowledgeBases(ctx)
|
||||
|
||||
@@ -20,7 +20,7 @@ func cachePath() (string, error) {
|
||||
// LoadCache reads the cached Info. Returns (info, fresh, err).
|
||||
//
|
||||
// info == nil when no cache exists (err == nil)
|
||||
// fresh == false 当 cache 不存在 / TTL 过期
|
||||
// fresh == false when the cache is missing or TTL-expired
|
||||
func LoadCache() (*Info, bool, error) {
|
||||
p, err := cachePath()
|
||||
if err != nil {
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestCache_RoundTrip(t *testing.T) {
|
||||
t.Errorf("ServerVersion = %v, want %q", got, want.ServerVersion)
|
||||
}
|
||||
|
||||
// 文件应在 $XDG_CACHE_HOME/weknora/server-info.yaml
|
||||
// File should live at $XDG_CACHE_HOME/weknora/server-info.yaml
|
||||
p := filepath.Join(dir, "weknora", "server-info.yaml")
|
||||
if _, err := filepath.Abs(p); err != nil {
|
||||
t.Errorf("path resolution: %v", err)
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
type Level int
|
||||
|
||||
const (
|
||||
OK Level = iota // 兼容
|
||||
SoftWarn // 服务器旧, 部分新功能不可用
|
||||
HardError // 不兼容, 需升级 CLI 或 server
|
||||
OK Level = iota // compatible
|
||||
SoftWarn // server outdated; some new features may be unavailable
|
||||
HardError // incompatible; CLI or server must be upgraded
|
||||
)
|
||||
|
||||
func (l Level) String() string {
|
||||
@@ -27,13 +27,13 @@ func (l Level) String() string {
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// Compat compares client/server version. v0.x 阶段允许漂移:
|
||||
// Compat compares client/server versions. Cross-minor drift is allowed:
|
||||
//
|
||||
// 同 major, client minor ≤ server minor → OK
|
||||
// 同 major, client minor > server minor → SoftWarn (server 旧, 部分新功能不可用)
|
||||
// 不同 major → HardError
|
||||
// 字符串 unparseable → OK (容错, 不阻塞)
|
||||
// "(unknown)" / "" → OK (dev build / server 字段缺失)
|
||||
// same major, client minor <= server minor -> OK
|
||||
// same major, client minor > server minor -> SoftWarn (some new features may be unavailable)
|
||||
// different major -> HardError
|
||||
// unparseable string -> OK (fail-open, do not block)
|
||||
// "(unknown)" / "" -> OK (dev build / server field missing)
|
||||
func Compat(serverVer, cliVer string) (Level, string) {
|
||||
sMaj, sMin, ok := parseSemver(serverVer)
|
||||
if !ok {
|
||||
@@ -44,7 +44,7 @@ func Compat(serverVer, cliVer string) (Level, string) {
|
||||
return OK, ""
|
||||
}
|
||||
if sMaj != cMaj {
|
||||
return HardError, fmt.Sprintf("incompatible: client %s vs server %s — upgrade required", cliVer, serverVer)
|
||||
return HardError, fmt.Sprintf("incompatible: client %s vs server %s - upgrade required", cliVer, serverVer)
|
||||
}
|
||||
if cMin > sMin {
|
||||
return SoftWarn, fmt.Sprintf("server is older (server %s, client %s); some new features may be unavailable", serverVer, cliVer)
|
||||
@@ -56,14 +56,14 @@ func Compat(serverVer, cliVer string) (Level, string) {
|
||||
// Accepts the leading "v" common in `git describe` output and Tencent/WeKnora
|
||||
// tag conventions ("v0.1.0"), since both server `/system/info.version` and
|
||||
// the CLI's own ldflags-injected build.Version may carry it.
|
||||
// Returns ok=false 当字符串无法识别 (空 / "(unknown)" / 非数字)。
|
||||
// Returns ok=false when the string is unrecognizable (empty / "(unknown)" / non-numeric).
|
||||
func parseSemver(s string) (major, minor int, ok bool) {
|
||||
if s == "" || s == "(unknown)" {
|
||||
return 0, 0, false
|
||||
}
|
||||
// 接受 "v" 前缀:git describe + Tencent tag 都带 v
|
||||
// Accept the "v" prefix; both `git describe` output and Tencent/WeKnora tags carry it.
|
||||
s = strings.TrimPrefix(s, "v")
|
||||
// 去掉 prerelease/build metadata
|
||||
// Strip prerelease/build metadata.
|
||||
if i := strings.IndexAny(s, "-+"); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
|
||||
@@ -19,9 +19,9 @@ func TestCompat(t *testing.T) {
|
||||
{"client minor lower", "1.5.0", "1.2.0", compat.OK, ""},
|
||||
{"client minor higher", "1.2.0", "1.5.0", compat.SoftWarn, "server is older"},
|
||||
{"different major", "1.9.9", "2.0.0", compat.HardError, "incompatible"},
|
||||
{"client unset", "1.2.3", "(unknown)", compat.OK, ""}, // dev build, 不报警
|
||||
{"client unset", "1.2.3", "(unknown)", compat.OK, ""}, // dev build; no warning
|
||||
{"server unset", "", "1.2.3", compat.OK, ""},
|
||||
{"malformed server", "garbage", "1.2.3", compat.OK, ""}, // 不阻塞
|
||||
{"malformed server", "garbage", "1.2.3", compat.OK, ""}, // fail-open
|
||||
|
||||
// "v" prefix tolerance (git describe + Tencent tag convention)
|
||||
{"v-prefix both", "v1.2.0", "v1.5.0", compat.SoftWarn, "server is older"},
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package compat probes server `/system/info` and decides client-server
|
||||
// version skew level. Used by `weknora doctor` 的 server_version 检查项。
|
||||
// version skew level. Used by `weknora doctor`'s server_version check.
|
||||
//
|
||||
// 24h TTL state file cache, three-tier compat semantics
|
||||
// (major-mismatch=hard / minor-mismatch=soft / equal=ok).
|
||||
@@ -20,8 +20,7 @@ type Info struct {
|
||||
ProbedAt time.Time `yaml:"probed_at"`
|
||||
}
|
||||
|
||||
// ProbeService is the narrow SDK surface compat depends on (testability via
|
||||
// fake; mirrors v0.0 service interface pattern).
|
||||
// ProbeService is the narrow SDK surface compat depends on; tests inject a fake.
|
||||
type ProbeService interface {
|
||||
GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Package config reads and writes the user-level config at
|
||||
// $XDG_CONFIG_HOME/weknora/config.yaml. yaml.v3 directly; viper is
|
||||
// intentionally not used (see ADR-2). Multi-host context map lives here;
|
||||
// intentionally not used. Multi-host context map lives here;
|
||||
// the per-project link (.weknora/project.yaml) is handled by the
|
||||
// projectlink package (see ADR-16).
|
||||
// projectlink package.
|
||||
package config
|
||||
|
||||
import (
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
// WriteReferences renders the compact references footer used by chat and
|
||||
// agent invoke: a horizontal rule, one numbered line per reference,
|
||||
// best-available title + optional score. Skipped entirely when refs is
|
||||
// empty — agent-friendly silence beats an empty banner.
|
||||
// empty - agent-friendly silence beats an empty banner.
|
||||
func WriteReferences(w io.Writer, refs []*sdk.SearchResult) {
|
||||
if len(refs) == 0 {
|
||||
return
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
// tree (which would expose auth/link/completion/destructive verbs that
|
||||
// don't belong on an agent-callable surface).
|
||||
// - Long-running tools (chat / agent_invoke) accumulate the LLM SSE
|
||||
// stream server-side and return a single CallToolResult — MCP spec
|
||||
// stream server-side and return a single CallToolResult - MCP spec
|
||||
// 2025-06-18 does not define streamed tool-result content, so the
|
||||
// accumulate-and-return pattern is the canonical path.
|
||||
// - Handlers receive ctx for cancellation; mid-LLM-stream cancellation
|
||||
|
||||
+12
-12
@@ -42,17 +42,17 @@ type agentService interface {
|
||||
// agentInvokeService composes the two SDK methods agent_invoke needs
|
||||
// (CreateSession for the auto-session path + AgentQAStreamWithRequest
|
||||
// for the run itself). Declared here alongside the per-domain
|
||||
// interfaces above so ServiceClient (server.go) — which embeds the
|
||||
// four domain interfaces — also satisfies it.
|
||||
// interfaces above so ServiceClient (server.go) - which embeds the
|
||||
// four domain interfaces - also satisfies it.
|
||||
type agentInvokeService interface {
|
||||
CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error)
|
||||
AgentQAStreamWithRequest(ctx context.Context, sessionID string, req *sdk.AgentQARequest, cb sdk.AgentEventCallback) error
|
||||
}
|
||||
|
||||
// registerTools wires the curated 9 tools onto server. Adding a tool here
|
||||
// is a deliberate API expansion — the agent-callable surface is the
|
||||
// is a deliberate API expansion - the agent-callable surface is the
|
||||
// reason this CLI ships an MCP server, not its CLI command list, so this
|
||||
// list must be maintained by hand (see also AGENTS.md mcp serve section).
|
||||
// list must be maintained by hand.
|
||||
func registerTools(server *mcpsdk.Server, svc ServiceClient) {
|
||||
addKBList(server, svc)
|
||||
addKBView(server, svc)
|
||||
@@ -76,7 +76,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 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.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ kbListInput) (*mcpsdk.CallToolResult, kbListOutput, error) {
|
||||
items, err := svc.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
@@ -130,7 +130,7 @@ type docListOutput struct {
|
||||
func addDocList(server *mcpsdk.Server, svc knowledgeService) {
|
||||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "doc_list",
|
||||
Description: "List documents in a knowledge base, with pagination and optional parse-status filter. Returns items[] with id, file_name, title, parse_status, size, updated_at — plus the page/total metadata.",
|
||||
Description: "List documents in a knowledge base, with pagination and optional parse-status filter. Returns items[] with id, file_name, title, parse_status, size, updated_at - plus the page/total metadata.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docListInput) (*mcpsdk.CallToolResult, docListOutput, error) {
|
||||
if in.KBID == "" {
|
||||
return nil, docListOutput{}, fmt.Errorf("kb_id is required")
|
||||
@@ -206,7 +206,7 @@ const maxDocDownloadBytes = 1 << 20
|
||||
func addDocDownload(server *mcpsdk.Server, svc knowledgeService) {
|
||||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "doc_download",
|
||||
Description: "Download a document's raw bytes by ID. Capped at 1 MiB per call — for larger documents, use search_chunks to find the relevant excerpts. is_base64 reports whether content was base64-encoded (heuristic: presence of NUL byte in the first 512 bytes).",
|
||||
Description: "Download a document's raw bytes by ID. Capped at 1 MiB per call - for larger documents, use search_chunks to find the relevant excerpts. is_base64 reports whether content was base64-encoded (heuristic: presence of NUL byte in the first 512 bytes).",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in docDownloadInput) (*mcpsdk.CallToolResult, docDownloadOutput, error) {
|
||||
if in.KnowledgeID == "" {
|
||||
return nil, docDownloadOutput{}, fmt.Errorf("knowledge_id is required")
|
||||
@@ -250,7 +250,7 @@ type searchChunksOutput struct {
|
||||
|
||||
func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
|
||||
// Out = any: SDK output schema would derive from searchChunksOutput,
|
||||
// which embeds *sdk.SearchResult — and SearchResult.Metadata is a
|
||||
// which embeds *sdk.SearchResult - and SearchResult.Metadata is a
|
||||
// nilable map[string]any that violates the auto-generated
|
||||
// type=object constraint when empty. Skipping derivation by using
|
||||
// `any` keeps the structured JSON shape identical while bypassing
|
||||
@@ -258,7 +258,7 @@ func addSearchChunks(server *mcpsdk.Server, svc knowledgeService) {
|
||||
// below.
|
||||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "search_chunks",
|
||||
Description: "Hybrid (vector + keyword) retrieval against a knowledge base. Returns the top chunks ranked by RRF; use this before chat to ground an answer in cited context. Results include knowledge_id, content, score — feed back into chat as context or display directly.",
|
||||
Description: "Hybrid (vector + keyword) retrieval against a knowledge base. Returns the top chunks ranked by RRF; use this before chat to ground an answer in cited context. Results include knowledge_id, content, score - feed back into chat as context or display directly.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, in searchChunksInput) (*mcpsdk.CallToolResult, any, error) {
|
||||
if in.KBID == "" {
|
||||
return nil, nil, fmt.Errorf("kb_id is required")
|
||||
@@ -366,7 +366,7 @@ type agentListOutput struct {
|
||||
func addAgentList(server *mcpsdk.Server, svc agentService) {
|
||||
mcpsdk.AddTool(server, &mcpsdk.Tool{
|
||||
Name: "agent_list",
|
||||
Description: "List the tenant's custom agents. Returns items[] with id, name, description, is_builtin — use to discover an agent_id before agent_invoke.",
|
||||
Description: "List the tenant's custom agents. Returns items[] with id, name, description, is_builtin - use to discover an agent_id before agent_invoke.",
|
||||
}, func(ctx context.Context, _ *mcpsdk.CallToolRequest, _ agentListInput) (*mcpsdk.CallToolResult, agentListOutput, error) {
|
||||
items, err := svc.ListAgents(ctx)
|
||||
if err != nil {
|
||||
@@ -415,7 +415,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
|
||||
Channel: "api",
|
||||
}
|
||||
// Auto-create session if not supplied. Sessions are agent-
|
||||
// agnostic at creation (Q3 — verified against server source).
|
||||
// agnostic at creation (Q3 - verified against server source).
|
||||
sessionID := in.SessionID
|
||||
if sessionID == "" {
|
||||
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora mcp agent_invoke"})
|
||||
@@ -447,7 +447,7 @@ func addAgentInvoke(server *mcpsdk.Server, svc agentInvokeService) {
|
||||
|
||||
// encodeDownload returns (content, isBase64). Heuristic: if the first 512
|
||||
// bytes contain a NUL, treat as binary. Otherwise it's UTF-8-ish text.
|
||||
// Matches what /usr/bin/file's "binary" heuristic does at a coarse level —
|
||||
// Matches what /usr/bin/file's "binary" heuristic does at a coarse level -
|
||||
// good enough to spare an agent from base64-decoding obvious text.
|
||||
func encodeDownload(buf []byte) (string, bool) {
|
||||
probe := buf
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
// .weknora/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
|
||||
// (npm/cargo behave the same — a project may straddle a bind-mount).
|
||||
// - find-the-project's-root walks; mount-boundary crossing is allowed
|
||||
// (npm/cargo behave the same - a project may straddle a bind-mount).
|
||||
package projectlink
|
||||
|
||||
import (
|
||||
@@ -50,7 +50,7 @@ func Discover(startDir string) (string, bool, error) {
|
||||
return candidate, true, nil
|
||||
}
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
// Permission errors etc. — keep walking up; missing read access
|
||||
// Permission errors etc. - keep walking up; missing read access
|
||||
// to a parent dir doesn't necessarily mean the project starts
|
||||
// here. Cargo/npm have the same behavior.
|
||||
// Fall through to parent walk.
|
||||
@@ -86,7 +86,7 @@ func Save(path string, p *Project) error {
|
||||
|
||||
// Remove deletes the project link at path. A missing file is reported as
|
||||
// success so callers can stay idempotent under concurrent-removal races
|
||||
// — the post-condition (no file at path) holds in either case.
|
||||
// - the post-condition (no file at path) holds in either case.
|
||||
func Remove(path string) error {
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("remove project link: %w", err)
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// Package prompt defines the interactive-input abstraction.
|
||||
//
|
||||
// Production impl will use charmbracelet/huh in v0.0 commands that need
|
||||
// password input (auth login). Foundation PR ships only the interface +
|
||||
// a sentinel error so non-TTY contexts surface the right error.
|
||||
// Package prompt defines the interactive-input abstraction. Production
|
||||
// uses charmbracelet/huh (TTYPrompter) for password input; non-TTY
|
||||
// contexts get AgentPrompter, which rejects every interactive call with
|
||||
// ErrAgentNoPrompt so commands can map it to a typed missing-flag error.
|
||||
package prompt
|
||||
|
||||
import "errors"
|
||||
|
||||
@@ -21,7 +21,7 @@ type KeyringStore struct{}
|
||||
func NewKeyringStore() *KeyringStore { return &KeyringStore{} }
|
||||
|
||||
// service returns the per-context service identifier. Splitting by context
|
||||
// (rather than by host) follows the Supabase pattern (ADR-17): a user with
|
||||
// (rather than by host) follows the Supabase pattern: a user with
|
||||
// two tenants on the same host gets two distinct keyring namespaces.
|
||||
func (k *KeyringStore) service(context string) string {
|
||||
return keyringService + ":" + context
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// Package secrets stores and retrieves credentials.
|
||||
// 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
|
||||
// backend is available).
|
||||
//
|
||||
// v0.0 ships a file-only Store implementation (0600 perms under
|
||||
// $XDG_CONFIG_HOME/weknora/secrets/). The OS keyring backend lands in v0.1
|
||||
// once auth login is needed in TTY contexts (current PR is foundation only).
|
||||
//
|
||||
// Namespace convention: "weknora:<context>:<key>" where key is "access" or "refresh".
|
||||
// Namespace convention: "weknora:<context>:<key>" where key is "access",
|
||||
// "refresh", or "api_key".
|
||||
package secrets
|
||||
|
||||
import (
|
||||
@@ -34,15 +34,14 @@ type Store interface {
|
||||
}
|
||||
|
||||
// FileStore writes 0600 plain-text files under $XDG_CONFIG_HOME/weknora/secrets/<context>.
|
||||
// It is the headless / CI default and the keychain fallback (see ADR-17 for
|
||||
// namespace strategy).
|
||||
// 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
|
||||
// as config.Path — see that file for the rationale (CLI convention).
|
||||
// as config.Path - see that file for the rationale (CLI convention).
|
||||
func NewFileStore() (*FileStore, error) {
|
||||
root, err := defaultRoot()
|
||||
if err != nil {
|
||||
@@ -91,7 +90,7 @@ func (f *FileStore) Delete(context, key string) error {
|
||||
|
||||
// Ref returns the file:// URI under which a secret would be stored. Path
|
||||
// component is forward-slash-normalized per RFC 8089 (file:///path on Unix,
|
||||
// file:///C:/... on Windows) — the wire format must not depend on platform
|
||||
// file:///C:/... on Windows) - the wire format must not depend on platform
|
||||
// path separator since this string is persisted to config.yaml and may be
|
||||
// consumed by tooling on a different OS.
|
||||
func (f *FileStore) Ref(context, key string) string {
|
||||
|
||||
@@ -16,12 +16,12 @@ import (
|
||||
|
||||
// Accumulator buffers a KnowledgeQAStream callback sequence.
|
||||
//
|
||||
// Zero value is ready to use. Not safe for concurrent Append calls — the SDK
|
||||
// Zero value is ready to use. Not safe for concurrent Append calls - the SDK
|
||||
// invokes its callback sequentially on a single goroutine, so this matches
|
||||
// the only contract that exists today.
|
||||
//
|
||||
// Demuxes by ResponseType so the answer string is not polluted by thinking
|
||||
// or reflection fragments — the model layer (internal/models/chat/
|
||||
// or reflection fragments - the model layer (internal/models/chat/
|
||||
// remote_api.go) emits ResponseTypeThinking events whenever the upstream
|
||||
// LLM produces reasoning_content (GPT-5 / Claude extended thinking), and
|
||||
// without demux those would be silently concatenated into Result().
|
||||
@@ -64,7 +64,7 @@ func (a *Accumulator) Append(r *sdk.StreamResponse) {
|
||||
if r.AssistantMessageID != "" && a.AssistantMessageID == "" {
|
||||
a.AssistantMessageID = r.AssistantMessageID
|
||||
}
|
||||
// Capture references whenever they arrive — they may land on a
|
||||
// Capture references whenever they arrive - they may land on a
|
||||
// dedicated `references` event before the terminal `complete`.
|
||||
if r.KnowledgeReferences != nil {
|
||||
a.References = r.KnowledgeReferences
|
||||
|
||||
@@ -47,7 +47,7 @@ func TestAccumulator_FinalizesOnComplete(t *testing.T) {
|
||||
|
||||
func TestAccumulator_IgnoresAgentQueryDone(t *testing.T) {
|
||||
// Server emits a leading agent_query frame with done=true to deliver
|
||||
// session metadata; the accumulator must NOT treat that as terminal —
|
||||
// session metadata; the accumulator must NOT treat that as terminal -
|
||||
// otherwise the answer fragments that follow would be discarded.
|
||||
a := &sse.Accumulator{}
|
||||
a.Append(&sdk.StreamResponse{
|
||||
@@ -108,7 +108,7 @@ func TestAccumulator_CapturesSessionMetadata(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAccumulator_FirstSessionMetadataWins(t *testing.T) {
|
||||
// Subsequent events must not overwrite the first non-empty value — the
|
||||
// Subsequent events must not overwrite the first non-empty value - the
|
||||
// session id is set once at session start and any later override would be
|
||||
// a server bug we should not silently mask.
|
||||
a := &sse.Accumulator{}
|
||||
|
||||
@@ -21,11 +21,11 @@ type AgentToolEvent struct {
|
||||
|
||||
// AgentAccumulator buffers an AgentQAStream callback sequence. Distinct
|
||||
// from Accumulator (KnowledgeQAStream) because the agent event model is
|
||||
// wider — events include thinking / reflection / tool_call / tool_result
|
||||
// wider - events include thinking / reflection / tool_call / tool_result
|
||||
// / answer / references / error, with a flat `Done bool` on each frame
|
||||
// rather than the ResponseType=complete sentinel KnowledgeQAStream emits.
|
||||
//
|
||||
// Zero value is ready to use. Not safe for concurrent Append calls — the
|
||||
// Zero value is ready to use. Not safe for concurrent Append calls - the
|
||||
// SDK callback contract is sequential on a single goroutine.
|
||||
//
|
||||
// API mirrors sse.Accumulator: private builders + accessor methods so the
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
|
||||
// ConfirmPrompter is a test double for prompt.Prompter that scripts a single
|
||||
// Confirm answer (with optional error). Input/Password are stubbed to return
|
||||
// prompt.ErrAgentNoPrompt — assert it via `Asked` after the call.
|
||||
// prompt.ErrAgentNoPrompt - assert it via `Asked` after the call.
|
||||
//
|
||||
// Use across cmd/* tests where a command's confirm-prompt branch needs to be
|
||||
// exercised. Avoid maintaining per-command copies of the same shape.
|
||||
|
||||
@@ -3,7 +3,7 @@ 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`
|
||||
// is never empty. Single source for the ordering - `weknora doc list`
|
||||
// and `weknora search docs` both call this so a Knowledge renders
|
||||
// identically in either command.
|
||||
//
|
||||
|
||||
@@ -5,8 +5,7 @@ package text
|
||||
import "fmt"
|
||||
|
||||
// Pluralize returns "<n> <thing>" or "<n> <thing>s". Simple suffix "s" only;
|
||||
// irregular forms (person/people) are not supported (add PluralizeIrregular
|
||||
// when needed, per spec §2.1).
|
||||
// irregular forms (person/people) are not supported.
|
||||
func Pluralize(n int, thing string) string {
|
||||
if n == 1 {
|
||||
return fmt.Sprintf("%d %s", n, thing)
|
||||
|
||||
@@ -4,14 +4,14 @@ import "github.com/mattn/go-runewidth"
|
||||
|
||||
const ellipsis = "…"
|
||||
|
||||
// Truncate cuts s to at most maxWidth display columns (CJK / emoji 占 2 列;
|
||||
// ASCII 占 1 列), appending "…" if truncated. Display width, not rune count.
|
||||
// Truncate cuts s to at most maxWidth display columns (CJK / emoji occupy
|
||||
// 2 columns; ASCII 1), appending "…" if truncated. Display width, not rune count.
|
||||
//
|
||||
// Edge cases:
|
||||
//
|
||||
// maxWidth ≤ 0 → ""
|
||||
// s 已 ≤ maxWidth → s 原样返回
|
||||
// ellipsis 占 1 列, 所以 truncate 时 budget = maxWidth - 1
|
||||
// maxWidth <= 0 -> ""
|
||||
// s already fits -> s returned unchanged
|
||||
// ellipsis is 1 column, so truncate budget = maxWidth - 1
|
||||
func Truncate(maxWidth int, s string) string {
|
||||
if maxWidth <= 0 {
|
||||
return ""
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
// under $HOME used when the env var is unset (".config" / ".cache" / etc.).
|
||||
// parts join under "weknora/" inside the chosen root.
|
||||
//
|
||||
// Honors the XDG vars on every OS, even macOS — where os.UserConfigDir
|
||||
// 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 != "" {
|
||||
|
||||
Reference in New Issue
Block a user