Borrows the lark-cli agent-affordance model
(https://github.com/larksuite/cli/blob/main/AGENTS.md +
skills/lark-shared/SKILL.md) so weknora is designed to be agent-friendly:
error messages, output format, and flag design follow conventions agents
can rely on.
cli/AGENTS.md (operational reference for LLM agents invoking weknora):
Public document covering envelope schema, exit-code protocol
(0/1/2/10/130), stdout/stderr separation, and behavioral rules.
Sensitive commands (\`context use\`, \`kb delete\`, \`doc delete\`, \`init\`)
gain "AI agents:" paragraphs in their cobra Long descriptions so
guidance shows in --help.
format.Envelope schema additions:
Risk per-operation classification (read / write / high-risk-write +
action description), populated by write commands on both success
and failure paths.
Notice system advisories (CLI update available, server-CLI version
skew); type defined, emit sites land in v0.3.
DryRun marker for envelopes returned from --dry-run preview paths.
RiskLevel constants realigned to lark's taxonomy: read / write /
high-risk-write (was: read / mutating / destructive — not yet wired by
any command).
cmdutil.Error gains OperationRisk; PrintErrorEnvelope auto-attaches it
to envelope.Risk so destructive failure paths surface uniformly.
Exit-10 confirmation protocol:
New ErrorCode \`input.confirmation_required\` mapped to exit code 10 in
cmdutil.ExitCode. ConfirmDestructive now returns this code (with
OperationRisk attached) when stdout is non-TTY or --json was set, with
-y/--yes absent. Previous behavior — silent proceed in non-TTY — was
unsafe: scripts and agents could delete resources with no explicit
approval. Three test cases re-pinned around the new contract.
This is a wire-contract change for any caller who relied on silent
proceed; v0.0/v0.1 had no destructive commands, so the blast radius is
contained to v0.2 itself.
--dry-run global flag:
cmd write paths (kb create/delete, doc upload/delete, api POST/PUT/PATCH/
DELETE) check cmdutil.IsDryRun(cmd) and skip the SDK call, emitting an
envelope with dry_run=true plus a Risk classification. Read commands
ignore --dry-run by design (no side effect to preview). Human-mode
prints \`[dry-run] would <action>\` to stdout.
Command discovery: agents introspect via the existing \`--help\` surface
(consistent with gh / kubectl / aws / gcloud / terraform — none of them
ship a CLI-tree self-description command). An earlier draft added a
\`weknora schema\` reflection command; dropped after a mainstream survey
found it has no stable analog (lark-cli's schema describes Lark API
methods, not its own CLI tree).
Tests: 27 cli packages pass at this commit. Added two new tests covering
envelope.risk and envelope._notice serialization.
Audited the v0.0~v0.2 21-command surface against gh / kubectl / cargo /
npm / git / docker / flyctl / vercel / supabase / brew. WeKnora was
cherry-picking from multiple heritages, producing an inconsistent feel:
the kb subtree mixed gh verbs (create / delete / list) with a kubectl
verb (get); confirmation flag duplicated --force (docker/kubectl) with
global -y/--yes (gh/vercel/npm); the --agent flag stretched Stripe's
telemetry-tag pattern into a behavior-mode switch that no mainstream
CLI does.
ADR-3 picks gh as the primary north star. Documented deviations remain
for project-link (vercel/cargo), chat (openai-cli), context (kubectl-
light), and doctor (brew/flutter). The decision and its deviations are
documented self-contained in cli/AGENTS.md.
Surface changes:
- kb get → kb view (gh repo view convention); "get" kept as cobra Alias
for v0.0/v0.1 callers — see https://cli.github.com/manual/gh_repo_view.
- kb delete --force / doc delete --force removed in favor of the global
-y/--yes persistent flag (gh repo delete --yes convention). One
mechanism skips destructive prompts; ConfirmDestructive's parameter
renamed `force` → `yes` to match.
- --agent omnibus mode-switch removed. Stripe's DetectAIAgent (the
cited inspiration) only tags User-Agent for telemetry, never flips
behavior; gh / kubectl / aws / docker / flyctl all decline this kind
of flag. The 7-env auto-detect list is reduced to the two entries
Stripe also recognizes (CLAUDECODE, CURSOR_AGENT) — the other five
had no agent-documented source. ApplyAgentSugar / ShouldUseAgentMode
and the dead --no-interactive / --no-progress globals are deleted
entirely.
- DetectAIAgent and SetAgentHelp annotations are kept: env detection
now only triggers AGENT-targeted help text rendering (no behavior
change), matching Stripe's narrower scope.
Tests: 27 cli packages green (acceptance/contract still pins kb get
golden; the alias keeps it valid).
Close the v0.2 RAG demo loop and ship the validation infrastructure:
- weknora api <method> <path> [--data X | --data-file F]
Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode
surfaces status / headers / parsed body. Non-2xx routes through
cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so
both SDK-error and direct-status paths stay aligned — reuse review).
- weknora chat <text> [--session-id S] [--no-stream]
KnowledgeQAStream consumer with two output modes:
- TTY default: token streaming + references footer
- --json / --no-stream / non-TTY: buffered single envelope
Auto-creates a session when --session-id is omitted; the id prints
to stderr at start AND on stream failure (^C scrolls past the
first announcement, so the recovery hint is re-surfaced when the
user is most likely to need it).
- cli/internal/sse/Accumulator
buffers Content / References / SessionID across SDK callbacks.
Idempotent post-Done so misbehaving servers don't corrupt state.
- doctor: ok → ok / warn / fail / skip
warn marks soft issues that don't block: server within compat range
but >=1 minor behind CLI; credential storage falling back to file
because keyring is unavailable. Envelope.ok stays true on warn,
flips false on fail (exit 1). doctor.error_network golden updated.
- cli/acceptance/e2e/ real-server RAG full loop
Build-tagged //go:build acceptance_e2e — kept out of the default
`go test ./...`. Exercises kb create → doc upload → poll ready →
search → chat → cleanup against a server pointed at by
WEKNORA_E2E_HOST / _TOKEN.
- .github/workflows/cli-e2e.yml
manual workflow_dispatch + label-gated PR trigger
("acceptance-e2e"). No-ops gracefully when the secrets aren't set
so cross-fork PRs can't accidentally fail the suite.
Add the resource-management surface to the v0.2 CLI:
- weknora kb create --name X [--description Y] [--embedding-model Z]
- weknora kb delete <id> [--force]
- weknora doc list [--kb-id X | --kb NAME] [--page N] [--page-size M]
- weknora doc upload <file> [--kb-id X | --kb NAME] [--name custom]
- weknora doc delete <id> [--force]
doc/* uses Factory.ResolveKB so the cwd's project link is honored when
--kb-id is omitted. doc upload validates path existence with os.Stat
(rejects directories; follows symlinks to mirror SDK os.Open behavior).
doc list sorts by updated_at desc so newer items surface first.
Both delete commands route through cmdutil.ConfirmDestructive — the
"destructive op needs explicit user opt-in" pattern was about to be
copy-pasted across the new subtree, so it was extracted with the delete
commands as their first consumer. Saves the same dedup pass when v0.3
adds session/agent delete. (PR-12 later renames the flag from --force
to the global -y/--yes for gh-style consistency.)
iostreams.SetForTestWithTTY pairs with the existing SetForTest helper:
the latter never reports stdout as a TTY (singleton replacement uses an
in-memory buffer), so the confirm-yes / confirm-no test branches need a
TTY-on variant.
v0.2 grounds the CLI's resource commands (kb / doc / chat / query) in a
per-project link file (.weknora/project.yaml) so users don't have to pass
--kb-id on every invocation. Mirrors npm/cargo/git: walk up the cwd tree
to find the project root, override via flag or env when needed.
This commit ships the foundation layer:
- cli/internal/projectlink/ Discover (walk-up, depth=64) / Load / Save
- cmdutil.Factory.ResolveKB 5-level fallback chain:
--kb-id flag → --kb name (ListKnowledgeBases lookup) →
WEKNORA_KB_ID env → walk-up project link → CodeKBIDRequired
- cmdutil.ResolveKBNameToID shared name→id helper used by init / link
/ Factory.ResolveKB (was duplicated 3 ways
in early implementation; reuse review #2)
- cli/cmd/init/ interactive (huh prompt) or flag-driven
first-time setup; refuses to overwrite
without --force
- cli/cmd/link/ non-interactive update; --kb-id and --kb
are mutually exclusive and one is required
Also registers the v0.2 ErrorCode set (all codes for the eight new
commands) and AST-scan identToErrorCode mapping in one place — keeps the
acceptance/contract suite green across the v0.2 commit chain even before
later commits reference each code.
cli/acceptance/contract/:
envelope_test.go — 16 envelope golden cases (9 commands × {success/error
variants}; 3 cases dropped with rationale: doctor.success
non-offline has unstable timing detail; auth_login.* needs
stdin/keyring scaffold deferred to v0.2; context_use.error
needs leaf-local --json deferred to follow-up)
errorcodes_test.go — single-direction AST scan of cli/cmd/ extracting first
arg of cmdutil.NewError / cmdutil.Wrapf calls;
ClassifyHTTPError dynamic-classify bridged via
cmdutil.ClassifyHTTPErrorOutputs() per spec §4.3.
testdata/envelopes/ — 16 JSON golden files
helpers_test.go (PR-6 scaffold) extended:
runCmd now wires cobra Out/Err sinks (version uses c.OutOrStdout) AND
replicates cmd.Execute()'s error-envelope path so error-case goldens are
populated. Without this, every error scenario's golden was 0 bytes.
cli/cmd/root.go: mapCobraError → MapCobraError, wantsJSONOutput → WantsJSONOutput
(exported so the contract test helper can replicate Execute()'s
envelope-printing path without calling Execute() itself).
root_test.go updated to use new exported names.
.github/dependabot.yml (新增):gomod /cli + github-actions weekly,gh-style
ignore semver-major to avoid noise. Open-source
dependency safety,independent of release cadence.
v0.1 不发布到任何分发平台 (release infra 推迟到发布窗口 milestone)。
text/ gh-style display-width string helpers (Truncate / FuzzyAgo / Pluralize)
compat/ server-CLI version skew probe (kubectl) + 24h TTL cache (gh internal/update)
acceptance/contract/ helpers_test.go for in-process cobra exec + golden assert
(uses iostreams.SetForTest singleton replacement; no t.Parallel)
cmdutil/errors.go: AllCodes() + ClassifyHTTPErrorOutputs() bridge for the
contract test suite (no behavior change in error handling)
go-runewidth promoted from indirect to direct (used by text.Truncate for
display-width-aware CJK truncation).
acceptance/contract/helpers_test.go forward-references cmd.NewRootCmd which
is exported in PR-7 — that file does not compile until then by design.
The fourth and final v0.0 command — chunk hybrid retrieval, the demo
headline operation per ADR-3 (only one search command in the tree).
Maps to client.HybridSearch / GET /knowledge-bases/{id}/hybrid-search;
no SDK or server changes.
Flags:
- --kb (required): target knowledge base
- --top-k (default 8): max results
- --vector-threshold / --keyword-threshold: similarity floors
- --no-vector / --no-keyword: disable individual channels (mutually
exclusive at the validation gate; checked before the SDK client is
built so flag misuse fails fast)
- --json: emit envelope JSON (otherwise pretty list)
Service interface narrowed to just HybridSearch; tests inject fakes via
Factory.Client closure override.
Pretty rendering is a minimal text indent today; lipgloss tables arrive
in PR-3 of v0.2 (format/ split into presenters/style/tableprinter).
First two leaf commands and the auth/ command group, registered under
the root command tree.
auth login:
- Email + password (interactive huh prompter) OR --with-token (read API
key from stdin) for headless / CI use
- Validates --host (required, must be http/https URL)
- Persists access + refresh tokens (password mode) or api_key (token mode)
into the secrets store wired in PR-3 — uses Store.Ref to record the
URI scheme without leaking concrete backend type
- Writes the named context to ~/.config/weknora/config.yaml and sets it
as current_context
- Typed loginResult payload for --json output (no map[string]any)
auth status:
- Calls client.GetCurrentUser -> /auth/me, prints context / host / user /
tenant. --json emits a typed statusResult envelope with _meta.context
and tenant_id populated for agents.
- Service interface narrowed to just GetCurrentUser; tests inject fakes
by overriding Factory.Client (no runF gymnastics).
cmd/root.go: register \`auth\` parent under the root tree.
Adds the OS keyring secret backend and the huh-based TTY Prompter so
PR-4 (auth login) can persist credentials and read interactive input.
The Factory's Client closure SDK wiring + Secrets closure landed in
PR-1's foundation tree to keep PR-1 self-contained.
internal/secrets/keyring.go:
- KeyringStore: zalando/go-keyring backed; namespace "weknora:<context>".
KeyringStore.Ref -> keychain://weknora/<context>/<key>
- NewBestEffortStore probes the OS keyring with a sentinel get and falls
back to FileStore on unsupported platforms (WSL without DBus, etc.)
internal/prompt/tty.go:
- TTYPrompter: huh.NewForm / huh.NewInput / huh.NewConfirm wrapper
satisfying Prompter. Used when iostreams.IO reports both stdout and
stderr are TTYs.
Dependencies (zalando/go-keyring, charmbracelet/huh) are declared in
PR-1's go.mod since the foundation tree referenced them via the Store
interface and TTY-detection helpers.