WeKnora/cli/cmd/root.go

246 lines
9.3 KiB
Go
Raw Normal View History

// Package cmd holds the cobra command tree. main.go calls Execute().
//
// v0.0 shipped: version / auth / search.
feat(cli): add agent-first affordance — envelope, exit-10, --dry-run 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.
2026-05-10 18:44:34 +00:00
// v0.1 adds: whoami / doctor / kb (list + view) / context (use).
// v0.2 adds: init / link / kb (create + delete) / doc (list + upload + delete)
// / api / chat. The kb view command is the primary; "get"
// is preserved as a cobra alias for v0.0/v0.1 callers.
package cmd
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
feat(cli): add api passthrough, chat streaming, doctor warn status 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.
2026-05-10 18:44:13 +00:00
apicmd "github.com/Tencent/WeKnora/cli/cmd/api"
"github.com/Tencent/WeKnora/cli/cmd/auth"
feat(cli): add api passthrough, chat streaming, doctor warn status 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.
2026-05-10 18:44:13 +00:00
chatcmd "github.com/Tencent/WeKnora/cli/cmd/chat"
contextcmd "github.com/Tencent/WeKnora/cli/cmd/context"
"github.com/Tencent/WeKnora/cli/cmd/doc"
"github.com/Tencent/WeKnora/cli/cmd/doctor"
initcmd "github.com/Tencent/WeKnora/cli/cmd/init"
"github.com/Tencent/WeKnora/cli/cmd/kb"
linkcmd "github.com/Tencent/WeKnora/cli/cmd/link"
"github.com/Tencent/WeKnora/cli/cmd/search"
"github.com/Tencent/WeKnora/cli/cmd/whoami"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/build"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// Execute is the entry point invoked by main(). Returns the process exit code.
func Execute() int {
root := NewRootCmd(cmdutil.New())
// ExecuteC returns the actually-invoked leaf (or root when invocation
// failed before dispatch); we use it to honor the leaf's --json and
// inherited --format without walking the tree ourselves.
cmd, err := root.ExecuteC()
if err == nil {
return 0
}
err = MapCobraError(err)
refactor(cli): align command surface with gh CLI conventions (ADR-3) 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).
2026-05-10 18:44:20 +00:00
if WantsJSONOutput(cmd) {
cmdutil.PrintErrorEnvelope(iostreams.IO.Out, err)
} else {
cmdutil.PrintError(iostreams.IO.Err, err)
}
return cmdutil.ExitCode(err)
}
// WantsJSONOutput reports whether cmd was invoked with --json, so error
// output matches the success format. Persistent flags inherit automatically
// via cmd.Flags().
//
// Falls back to scanning os.Args when cobra never reached the leaf — e.g.
// unknown subcommand or unknown flag at root level. Without this, `weknora
// bogus --json` would emit a human stderr line instead of the envelope the
// agent asked for.
//
// Exported so the acceptance/contract test helper can replicate Execute()'s
// envelope-printing path without having to call os.Exit-bound Execute() itself.
func WantsJSONOutput(cmd *cobra.Command) bool {
if v, err := cmd.Flags().GetBool("json"); err == nil && v {
return true
}
return argsRequestJSON(os.Args[1:])
}
// argsRequestJSON scans a flag-only slice for --json in the forms pflag
// accepts. Used as a fallback when cobra short-circuits before flag parsing
// (unknown command / unknown flag at root). Mirrors only the subset of pflag
// bool parsing relevant here — `--json=false` is treated as not-JSON,
// matching pflag.
func argsRequestJSON(args []string) bool {
for _, a := range args {
switch {
case a == "--json":
return true
case strings.HasPrefix(a, "--json="):
if isPflagTruthy(strings.TrimPrefix(a, "--json=")) {
return true
}
}
}
return false
}
// isPflagTruthy mirrors pflag's bool parsing for "--flag=<v>" tokens.
// pflag delegates to strconv.ParseBool, which accepts 1/t/T/TRUE/true/True
// as truthy and 0/f/F/FALSE/false/False as falsy. Anything else errors.
func isPflagTruthy(v string) bool {
b, err := strconv.ParseBool(v)
return err == nil && b
}
// MapCobraError tags the textually-emitted cobra errors as cmdutil.FlagError
// so they exit 2 like other user invocation mistakes. SetFlagErrorFunc handles
// flag parse errors at parse time; this catches positional/Args validation
// errors and unknown subcommands that propagate as plain errors.
//
// Pinned to cobra v1.10 message formats (cobra/args.go: ExactArgs / NoArgs;
// cobra/command.go: required-flag / unknown-command). TestMapCobraError_PinnedPrefixes
// guards against a silent break on cobra bumps.
//
// Exported so the acceptance/contract test helper can reuse the mapping when
// replicating Execute()'s error-envelope path in-process.
func MapCobraError(err error) error {
if err == nil {
return nil
}
msg := err.Error()
for _, prefix := range cobraFlagErrorPrefixes {
if strings.HasPrefix(msg, prefix) {
return cmdutil.NewFlagError(err)
}
}
return err
}
// cobraFlagErrorPrefixes lists the text prefixes cobra uses for invocation
// problems we want to surface as exit 2. Pinned per cobra v1.10.
var cobraFlagErrorPrefixes = []string{
"unknown command ",
"required flag(s)",
"accepts ", // ExactArgs / RangeArgs / etc. — `accepts N arg(s), received M`
"requires at least", // MinimumNArgs
"requires at most", // MaximumNArgs
"unknown flag",
"invalid argument", // pflag type-coercion failure (e.g. --top-k=foo)
}
// NewRootCmd builds the cobra tree. Splitting it from Execute() lets tests
chore(cli): remove unused v0.0 scaffolding Foundation PR-1 reserved several internal packages and helpers as scaffolding for follow-up PRs that ended up taking different routes. Audit confirms zero production references; this commit removes them so the cli/ tree reflects what's actually shipped. Removed (148 LOC): cli/internal/safepaths/ — `Validate` / `WithinRoot` / three sentinel errors. Reserved for `weknora doc upload`'s path scrubbing; that command landed in PR-10 using its own `validateUploadPath` (os.Stat + regular-file check) — sufficient for the actual threat model (local CLI invocations). cli/internal/cmdutil/json_flags.go — `AddJSONFlags` helper + unused --jq / --template flag registration. Reserved for PR-3 "lipgloss tables / jq evaluator" which never materialized; every command directly registers BoolVar(&JSONOut, "json", ...) since v0.0 ship time. cmdutil.NewTableExporter — empty alias for jsonExporter, reserved for the same PR-3 renderer. Removed; jsonExporter stays under NewJSONExporter. cmdutil.Options marker interface — empty interface{} reserved as a convention; no command embeds or asserts against it. Stale comments fixed: - cmd/root.go: package comment updated kb (list+get) → kb (list+view+create+delete) and noted the `get` cobra alias. - cmd/root.go: dropped --no-version-check forward-reference (no such flag). - cmd/root.go: removed "(PR-7)" attribution from NewRootCmd doc comment. - cmd/kb/kb.go: same package-comment update. - cmd/chat/chat.go: replaced "PR-7" mention in --help example with a generic placeholder so cobra-rendered help is review-clean. - cmd/search/search.go: removed "Lipgloss tables arrive in PR-3" forward-reference; the inline indent helper is the shipped form. - internal/agent/annotations.go: ShouldUseAgentMode → DetectAIAgent (removed in PR-12). AGENTS.md "Known limitations" section added: Documents that chat / search / doc upload currently surface server-side precondition misses (LLM / vector store / storage engine not configured) as `network.error` with `context deadline exceeded`. A planned future release will introduce a `precondition.*` typed error namespace (server returns HTTP 412 before opening the SSE / streaming response). This documents the limitation honestly for reviewers and integrators rather than claiming a behavior we don't yet have. Tests: 27 cli packages pass (safepaths_test was the 28th — gone with the package). go vet clean.
2026-05-10 18:44:41 +00:00
// drive the tree directly with their own factory. Exported so the
// acceptance/contract suite can construct the tree in-process.
func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
v, commit, date := build.Info()
cmd := &cobra.Command{
Use: "weknora",
Short: "WeKnora CLI — RAG knowledge base from your terminal",
Long: `WeKnora CLI lets you authenticate, browse knowledge bases, and run
hybrid searches against a WeKnora server from your shell or an AI agent.`,
Example: ` weknora auth login --host=https://kb.example.com # one-time setup
weknora kb list # list knowledge bases
refactor(cli): align command surface with gh CLI conventions (ADR-3) 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).
2026-05-10 18:44:20 +00:00
weknora kb view <id> # show one
weknora search "your question" --kb=<id> # hybrid retrieval
weknora doctor --json # health check (agent-readable)`,
SilenceUsage: true,
SilenceErrors: true,
// Version makes cobra auto-register a `--version` global flag that
// prints this string. Mainstream CLIs (gh / kubectl / aws / gcloud)
// all accept both `--version` and a `version` subcommand; the
// subcommand still owns the richer `--json` envelope output.
Version: fmt.Sprintf("%s (commit %s, built %s)", v, commit, date),
PersistentPreRun: func(c *cobra.Command, args []string) {
// Propagate the global --context flag into the Factory for this
// invocation only. Spec §1.2: single-shot override, no disk write.
if v, _ := c.Flags().GetString("context"); v != "" {
f.ContextOverride = v
}
},
}
// Match `weknora version` line format so both forms output the same.
cmd.SetVersionTemplate("weknora {{.Version}}\n")
addGlobalFlags(cmd)
cmd.SetHelpFunc(agentAwareHelpFunc(cmd.HelpFunc()))
// Wrap cobra's flag-parsing errors as FlagError so cmdutil.ExitCode maps
// them to exit 2 (gh-style). "unknown command" errors are detected by
// message prefix in Execute() since cobra emits them as plain errors.
cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error {
return cmdutil.NewFlagError(err)
})
cmd.AddCommand(newVersionCmd(f))
cmd.AddCommand(auth.NewCmdAuth(f))
cmd.AddCommand(search.NewCmdSearch(f))
cmd.AddCommand(whoami.NewCmd(f))
cmd.AddCommand(doctor.NewCmd(f))
cmd.AddCommand(kb.NewCmd(f))
cmd.AddCommand(contextcmd.NewCmd(f))
cmd.AddCommand(initcmd.NewCmd(f))
cmd.AddCommand(linkcmd.NewCmd(f))
cmd.AddCommand(doc.NewCmd(f))
feat(cli): add api passthrough, chat streaming, doctor warn status 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.
2026-05-10 18:44:13 +00:00
cmd.AddCommand(apicmd.NewCmd(f))
cmd.AddCommand(chatcmd.NewCmd(f))
return cmd
}
// addGlobalFlags registers persistent flags available on every subcommand.
// Only flags whose behavior is actually wired are listed — a flag that
// accepts values but does nothing is a worse contract than no flag.
func addGlobalFlags(cmd *cobra.Command) {
pf := cmd.PersistentFlags()
pf.BoolP("yes", "y", false, "Skip confirmation prompts on destructive operations")
pf.String("context", "", "Override the active context for this invocation (no disk write)")
feat(cli): add agent-first affordance — envelope, exit-10, --dry-run 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.
2026-05-10 18:44:34 +00:00
pf.Bool("dry-run", false, "Preview the operation without executing (write commands only; read commands ignore)")
}
// agentAwareHelpFunc wraps cobra's default help to append the AI agent guidance
refactor(cli): align command surface with gh CLI conventions (ADR-3) 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).
2026-05-10 18:44:20 +00:00
// (Annotations[agent.AIAgentHelpKey]) only when an AI coding agent env var is
// detected (CLAUDECODE / CURSOR_AGENT). Help-only render — no behavior switch.
// Stripe pkg/cmd/templates.go pattern, but reduced from mode-switch (v0.2 ADR-3).
func agentAwareHelpFunc(orig func(*cobra.Command, []string)) func(*cobra.Command, []string) {
return func(c *cobra.Command, args []string) {
orig(c, args)
refactor(cli): align command surface with gh CLI conventions (ADR-3) 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).
2026-05-10 18:44:20 +00:00
if agent.DetectAIAgent() == "" {
return
}
extra := agent.FormatAgentGuidance(c)
if extra == "" {
return
}
w := c.OutOrStdout()
fmt.Fprintln(w)
fmt.Fprintln(w, "AI Agent guidance:")
fmt.Fprintln(w, " "+extra)
}
}
// newVersionCmd is the only leaf command shipped in the foundation PR. It
// doubles as the smoke test that proves Factory + iostreams + cobra wiring works.
func newVersionCmd(f *cmdutil.Factory) *cobra.Command {
var jsonOut bool
cmd := &cobra.Command{
Use: "version",
Short: "Show CLI build metadata",
RunE: func(c *cobra.Command, args []string) error {
v, commit, date := build.Info()
if jsonOut {
return cmdutil.NewJSONExporter().Write(c.OutOrStdout(), format.Success(map[string]string{
"version": v,
"commit": commit,
"date": date,
}, nil))
}
fmt.Fprintf(c.OutOrStdout(), "weknora %s (commit %s, built %s)\n", v, commit, date)
return nil
},
}
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output JSON envelope")
return cmd
}