2026-05-12 15:33:44 +00:00
package contextcmd
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
type AddOptions struct {
Host string
User string
JSONOut bool
}
// addResult is the typed payload emitted under data on success.
type addResult struct {
Name string ` json:"name" `
Host string ` json:"host" `
User string ` json:"user,omitempty" `
Current bool ` json:"current" `
}
// NewCmdAdd builds `weknora context add`. Registers a *credentialless*
// connection target — host + optional user only. Credentials for the new
// context are attached separately with `weknora auth login --name <n>`,
refactor(cli): v0.3 cross-cutting cleanup
Cross-cutting findings surfaced by the branch-completion review.
Perf bug:
- Factory.Client closure was not memoized. Factory.ResolveKB internally
calls f.Client() to resolve --kb name → id, then the command's RunE
calls f.Client() again. Two SDK clients, two keyring reads, two
AuthRetryTransport allocations per name-resolved invocation, with
*independent* token state (a refresh in one was invisible to the
other). Switched to sync.Once like Secrets already does.
Silent bug bait:
- cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the
empty case; code returned CodeInputInvalidArgument. Aligned doc to
code (present-but-empty is a bad value, not a missing flag).
Agent contract gaps:
- Five user-facing subcommands lacked SetAgentHelp: auth login /
logout / list / status and chat. Added concise strings with error-
code call-outs so agents can branch without parsing human strings.
Helper extraction (≥3 callers):
- text.KnowledgeDisplayName(fileName, title, id) — byte-identical
formatter that was in both cmd/doc/list.go and cmd/search/docs.go.
Takes fields directly so internal/text stays SDK-free.
- cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the
`Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK
call sites. Sed-driven migration; off-pattern shapes in chat.go
(used streamErr) and cmdutil/kb.go (in-package) hand-edited.
Contract test gains a comment update: post-migration the dominant
pattern is WrapHTTP which the AST scanner skips entirely (only
NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs()
bridge still covers the dynamic codes those paths can yield.
UX consistency:
- cmd/doc/list.go --page-size help now reads "Items per page
(1..1000)" matching cmd/session/list.go. The bounds validation
already enforced 1..1000; the help text was the last drift.
Comment-discipline sweep:
- Deleted the WHAT-only "*Options captures `weknora ...` flag state"
docstring across 23 files (context, kb, auth, doc, session, search,
chat, doctor, link). Where the line carried a real WHY clause
(kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and
dropped only the leading WHAT phrase.
- Stripped third-party project-name attribution from inline comments
and one user-visible flag-help string across ~40 files in cli/cmd
and cli/internal (plus 4 test-file comments). Removed phrases like
"Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style",
"gcloud `--project`", "Stripe pattern", and the embedded GitHub
URLs pointing at those projects. Behavioral descriptions and the
WHY behind each comment are preserved; only the upstream-name
attribution is gone. Inspiration / north-star references belong in
cli/AGENTS.md (the design doc) and commit messages, not scattered
through every file.
Triggered by an audit round that surfaced several false / fragile
parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no
--name flag; "matches gcloud `--project` id-or-name" — gcloud's
--project accepts ID only). Rather than fix them one by one, the
whole category of in-comment external-project references was
stripped uniformly.
2026-05-12 15:42:20 +00:00
// separating "where" the CLI talks to (the host) and "how" it authenticates
// (the credential). If you want one command for both, run
// `weknora auth login --name <n> --host <h>` instead.
2026-05-12 15:33:44 +00:00
func NewCmdAdd ( f * cmdutil . Factory ) * cobra . Command {
opts := & AddOptions { }
cmd := & cobra . Command {
Use : "add <name>" ,
Short : "Register a new context (host without credentials)" ,
Long : ` Add a new context entry to config . yaml . Stores host ( and optionally
user ) but does NOT prompt for credentials . Use ` + " ` weknora auth login -- name < n > ` " + ` to
attach credentials in a single step instead , or run ` + " ` weknora auth login -- name < n > ` " + ` after
` + " ` weknora context add ` " + ` to fill them in .
The first context added is auto - selected as the current context . Subsequent
adds leave the current context untouched . ` ,
Example : ` weknora context add staging -- host https : //staging.example.com
weknora context add prod -- host https : //prod.example.com --user alice@example.com`,
Args : cobra . ExactArgs ( 1 ) ,
RunE : func ( c * cobra . Command , args [ ] string ) error {
return runAdd ( opts , args [ 0 ] )
} ,
}
cmd . Flags ( ) . StringVar ( & opts . Host , "host" , "" , "Server base URL, e.g. https://kb.example.com (required)" )
refactor(cli): v0.3 cross-cutting cleanup
Cross-cutting findings surfaced by the branch-completion review.
Perf bug:
- Factory.Client closure was not memoized. Factory.ResolveKB internally
calls f.Client() to resolve --kb name → id, then the command's RunE
calls f.Client() again. Two SDK clients, two keyring reads, two
AuthRetryTransport allocations per name-resolved invocation, with
*independent* token state (a refresh in one was invisible to the
other). Switched to sync.Once like Secrets already does.
Silent bug bait:
- cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the
empty case; code returned CodeInputInvalidArgument. Aligned doc to
code (present-but-empty is a bad value, not a missing flag).
Agent contract gaps:
- Five user-facing subcommands lacked SetAgentHelp: auth login /
logout / list / status and chat. Added concise strings with error-
code call-outs so agents can branch without parsing human strings.
Helper extraction (≥3 callers):
- text.KnowledgeDisplayName(fileName, title, id) — byte-identical
formatter that was in both cmd/doc/list.go and cmd/search/docs.go.
Takes fields directly so internal/text stays SDK-free.
- cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the
`Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK
call sites. Sed-driven migration; off-pattern shapes in chat.go
(used streamErr) and cmdutil/kb.go (in-package) hand-edited.
Contract test gains a comment update: post-migration the dominant
pattern is WrapHTTP which the AST scanner skips entirely (only
NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs()
bridge still covers the dynamic codes those paths can yield.
UX consistency:
- cmd/doc/list.go --page-size help now reads "Items per page
(1..1000)" matching cmd/session/list.go. The bounds validation
already enforced 1..1000; the help text was the last drift.
Comment-discipline sweep:
- Deleted the WHAT-only "*Options captures `weknora ...` flag state"
docstring across 23 files (context, kb, auth, doc, session, search,
chat, doctor, link). Where the line carried a real WHY clause
(kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and
dropped only the leading WHAT phrase.
- Stripped third-party project-name attribution from inline comments
and one user-visible flag-help string across ~40 files in cli/cmd
and cli/internal (plus 4 test-file comments). Removed phrases like
"Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style",
"gcloud `--project`", "Stripe pattern", and the embedded GitHub
URLs pointing at those projects. Behavioral descriptions and the
WHY behind each comment are preserved; only the upstream-name
attribution is gone. Inspiration / north-star references belong in
cli/AGENTS.md (the design doc) and commit messages, not scattered
through every file.
Triggered by an audit round that surfaced several false / fragile
parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no
--name flag; "matches gcloud `--project` id-or-name" — gcloud's
--project accepts ID only). Rather than fix them one by one, the
whole category of in-comment external-project references was
stripped uniformly.
2026-05-12 15:42:20 +00:00
cmd . Flags ( ) . StringVar ( & opts . User , "user" , "" , "Account email shown in 'context list' (optional, cosmetic only)" )
2026-05-12 15:33:44 +00:00
cmd . Flags ( ) . BoolVar ( & opts . JSONOut , "json" , false , "Output JSON envelope" )
_ = cmd . MarkFlagRequired ( "host" )
agent . SetAgentHelp ( cmd , "Adds a context. First context added auto-becomes current. Errors with resource.already_exists if name collides; input.invalid_argument if --host is not an absolute http(s) URL." )
return cmd
}
func runAdd ( opts * AddOptions , name string ) error {
if err := validateName ( name ) ; err != nil {
return err
}
host , err := cmdutil . NormalizeHost ( opts . Host )
if err != nil {
return err
}
cfg , err := config . Load ( )
if err != nil {
return err
}
if _ , exists := cfg . Contexts [ name ] ; exists {
return & cmdutil . Error {
Code : cmdutil . CodeResourceAlreadyExists ,
Message : fmt . Sprintf ( "context %q already exists" , name ) ,
Hint : fmt . Sprintf ( "use a different name, or run `weknora context remove %s` first" , name ) ,
}
}
if cfg . Contexts == nil {
cfg . Contexts = map [ string ] config . Context { }
}
cfg . Contexts [ name ] = config . Context { Host : host , User : opts . User }
wasFirst := cfg . CurrentContext == ""
if wasFirst {
cfg . CurrentContext = name
}
if err := config . Save ( cfg ) ; err != nil {
return cmdutil . Wrapf ( cmdutil . CodeLocalFileIO , err , "save config" )
}
risk := & format . Risk { Level : format . RiskWrite , Action : fmt . Sprintf ( "add context %s" , name ) }
if opts . JSONOut {
return format . WriteEnvelope ( iostreams . IO . Out , format . SuccessWithRisk (
addResult { Name : name , Host : host , User : opts . User , Current : wasFirst } ,
& format . Meta { Context : cfg . CurrentContext } ,
risk ,
) )
}
if wasFirst {
fmt . Fprintf ( iostreams . IO . Out , "✓ Added context %s (now current). Run `weknora auth login --name %s` to attach credentials.\n" , name , name )
} else {
fmt . Fprintf ( iostreams . IO . Out , "✓ Added context %s. Run `weknora auth login --name %s` to attach credentials.\n" , name , name )
}
return nil
}
// validateName enforces the allowlist advertised in the --help hint: letters,
// digits, dash, underscore, dot. The `.` exception lets emails / DNS-like
// names through; the path-traversal `..` is structurally rejected by a
// separate guard because it would let a hand-edited config.yaml claim a
// context whose name walks out of the keyring namespace.
func validateName ( name string ) error {
if name == "" {
return & cmdutil . Error {
Code : cmdutil . CodeInputInvalidArgument ,
Message : "context name must not be empty" ,
}
}
if name == "." || name == ".." || strings . Contains ( name , "/" ) || strings . Contains ( name , "\\" ) {
return & cmdutil . Error {
Code : cmdutil . CodeInputInvalidArgument ,
Message : fmt . Sprintf ( "context name %q is reserved or path-like" , name ) ,
Hint : "use letters, digits, dashes, underscores, or dots" ,
}
}
for _ , r := range name {
switch {
case r >= 'a' && r <= 'z' ,
r >= 'A' && r <= 'Z' ,
r >= '0' && r <= '9' ,
r == '-' || r == '_' || r == '.' :
continue
default :
return & cmdutil . Error {
Code : cmdutil . CodeInputInvalidArgument ,
Message : fmt . Sprintf ( "context name %q contains invalid character %q" , name , r ) ,
Hint : "use letters, digits, dashes, underscores, or dots" ,
}
}
}
return nil
}