2026-05-10 18:44:06 +00:00
|
|
|
package kb
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
2026-05-17 17:37:47 +00:00
|
|
|
"slices"
|
2026-05-10 18:44:06 +00:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
|
|
|
|
sdk "github.com/Tencent/WeKnora/client"
|
|
|
|
|
)
|
|
|
|
|
|
2026-05-17 17:37:47 +00:00
|
|
|
// kbCreateFields enumerates the fields surfaced for `--format json` discovery
|
|
|
|
|
// on `kb create`. The result is the full KnowledgeBase struct; these mirror
|
|
|
|
|
// its top-level json tags. Nested config objects are intentionally omitted —
|
|
|
|
|
// users wanting them can drop the projection or use --jq.
|
feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
2026-05-14 15:28:14 +00:00
|
|
|
var kbCreateFields = []string{
|
|
|
|
|
"id", "name", "type", "description",
|
|
|
|
|
"is_temporary", "is_pinned",
|
|
|
|
|
"embedding_model_id", "summary_model_id",
|
|
|
|
|
"knowledge_count", "chunk_count",
|
|
|
|
|
"is_processing", "processing_count",
|
|
|
|
|
"created_at", "updated_at",
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-10 18:44:06 +00:00
|
|
|
type CreateOptions struct {
|
2026-05-17 17:37:47 +00:00
|
|
|
Name string
|
|
|
|
|
Description string
|
|
|
|
|
EmbeddingModel string
|
|
|
|
|
StorageProvider string
|
feat(cli): --dry-run + risk metadata + validation parity on 19 mutations
Two intertwined agent safety nets that share the same files:
1. --dry-run flag for offline preview of mutation commands
2. Risk: metadata + SetRisk helper for destructive command surfaces
Coverage (19 mutation commands with --dry-run):
kb.create/edit/delete agent.create/edit/delete
doc.create/upload/fetch/delete doc.delete_all (special variant)
session.delete chunk.delete profile.add/remove
auth.refresh/logout link unlink
api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2)
Envelope additions (omitempty in non-dry-run paths):
meta.dry_run: bool true when --dry-run was used
meta.plan: map {action, args} per the per-command taxonomy
Risk: metadata
--------------
cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with
risk.level=destructive + risk.action=<action> on the 9 destructive
commands. The SetAgentHelp wrapper prepends a "Risk: <action>
(destructive)" line in the default text help path so agents see a clear
warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays
unchanged — structured agent-help already carries warnings[].
Validation parity with the live path
------------------------------------
Every pure-local validation (flag presence, mutual exclusion, enum
bounds, URL/regex format, ResolveKBLocal for KB resolution that does not
require an SDK call) runs BEFORE the dry-run gate. This matches the
industry-standard "preview shows what live would do" contract:
--dry-run accepts exactly the same invocations the live path accepts and
rejects exactly the same invocations the live path rejects, modulo the
side-effecting work itself.
The side-effecting work (SDK calls, file writes, keyring writes, server-
side name → id resolution) is what --dry-run actually gates. Each
mutation file pairs its RunE validation block with a regression test
under *_dry_run_test.go / dryrun_validation_test.go so future refactors
don't reintroduce the gap.
Helper surface
--------------
- HandleDryRun(cmd, dryRun, plan) extracts the early-return so the
19 RunE call sites stay 3 lines each.
- EmitDryRun routes through FormatOptions.Emit, inheriting _notice /
TTY indent / --jq filtering for free.
- ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run
paths use it so the plan reports the raw --kb value (UUID or name)
without a name → id lookup.
Streaming commands (chat, session ask, session continue-stream) are
deliberately excluded: a buffered plan makes no sense for an event
stream.
Lock semantics in the dry-run path:
- destructive + --dry-run: exit 0, no exit-10 confirmation prompt
- --dry-run + -y: byte-identical envelope to --dry-run alone
- --dry-run + --jq: filter applies to the preview envelope normally
2026-05-27 20:28:48 +00:00
|
|
|
DryRun bool
|
2026-05-10 18:44:06 +00:00
|
|
|
}
|
|
|
|
|
|
2026-05-17 17:37:47 +00:00
|
|
|
// storageProviderValues mirrors the server enum in
|
|
|
|
|
// internal/types/knowledgebase.go:StorageProviderConfig.Provider.
|
|
|
|
|
var storageProviderValues = []string{"local", "minio", "cos", "tos", "s3", "oss", "ks3"}
|
|
|
|
|
|
2026-05-10 18:44:06 +00:00
|
|
|
// CreateService is the narrow SDK surface this command depends on.
|
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
2026-05-14 18:16:45 +00:00
|
|
|
// *sdk.Client satisfies it via duck typing.
|
2026-05-10 18:44:06 +00:00
|
|
|
type CreateService interface {
|
|
|
|
|
CreateKnowledgeBase(ctx context.Context, kb *sdk.KnowledgeBase) (*sdk.KnowledgeBase, error)
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-17 17:37:47 +00:00
|
|
|
// NewCmdCreate builds `weknora kb create <name>`. Positional <name> only,
|
|
|
|
|
// consistent with `agent create <name>`.
|
2026-05-10 18:44:06 +00:00
|
|
|
func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
|
|
|
|
|
opts := &CreateOptions{}
|
|
|
|
|
cmd := &cobra.Command{
|
2026-05-17 17:37:47 +00:00
|
|
|
Use: "create <name>",
|
2026-05-10 18:44:06 +00:00
|
|
|
Short: "Create a new knowledge base",
|
2026-05-17 17:37:47 +00:00
|
|
|
Args: cobra.ExactArgs(1),
|
|
|
|
|
RunE: func(c *cobra.Command, args []string) error {
|
|
|
|
|
fopts, err := cmdutil.CheckFormatFlag(c)
|
feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
2026-05-14 15:28:14 +00:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2026-05-17 17:37:47 +00:00
|
|
|
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
|
|
|
|
opts.Name = args[0]
|
feat(cli): --dry-run + risk metadata + validation parity on 19 mutations
Two intertwined agent safety nets that share the same files:
1. --dry-run flag for offline preview of mutation commands
2. Risk: metadata + SetRisk helper for destructive command surfaces
Coverage (19 mutation commands with --dry-run):
kb.create/edit/delete agent.create/edit/delete
doc.create/upload/fetch/delete doc.delete_all (special variant)
session.delete chunk.delete profile.add/remove
auth.refresh/logout link unlink
api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2)
Envelope additions (omitempty in non-dry-run paths):
meta.dry_run: bool true when --dry-run was used
meta.plan: map {action, args} per the per-command taxonomy
Risk: metadata
--------------
cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with
risk.level=destructive + risk.action=<action> on the 9 destructive
commands. The SetAgentHelp wrapper prepends a "Risk: <action>
(destructive)" line in the default text help path so agents see a clear
warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays
unchanged — structured agent-help already carries warnings[].
Validation parity with the live path
------------------------------------
Every pure-local validation (flag presence, mutual exclusion, enum
bounds, URL/regex format, ResolveKBLocal for KB resolution that does not
require an SDK call) runs BEFORE the dry-run gate. This matches the
industry-standard "preview shows what live would do" contract:
--dry-run accepts exactly the same invocations the live path accepts and
rejects exactly the same invocations the live path rejects, modulo the
side-effecting work itself.
The side-effecting work (SDK calls, file writes, keyring writes, server-
side name → id resolution) is what --dry-run actually gates. Each
mutation file pairs its RunE validation block with a regression test
under *_dry_run_test.go / dryrun_validation_test.go so future refactors
don't reintroduce the gap.
Helper surface
--------------
- HandleDryRun(cmd, dryRun, plan) extracts the early-return so the
19 RunE call sites stay 3 lines each.
- EmitDryRun routes through FormatOptions.Emit, inheriting _notice /
TTY indent / --jq filtering for free.
- ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run
paths use it so the plan reports the raw --kb value (UUID or name)
without a name → id lookup.
Streaming commands (chat, session ask, session continue-stream) are
deliberately excluded: a buffered plan makes no sense for an event
stream.
Lock semantics in the dry-run path:
- destructive + --dry-run: exit 0, no exit-10 confirmation prompt
- --dry-run + -y: byte-identical envelope to --dry-run alone
- --dry-run + --jq: filter applies to the preview envelope normally
2026-05-27 20:28:48 +00:00
|
|
|
// Validate --storage-provider enum before the dry-run gate so
|
|
|
|
|
// --dry-run rejects identically to the live path. Same typed
|
|
|
|
|
// FlagError as runCreate (kept there for direct-call callers).
|
|
|
|
|
if opts.StorageProvider != "" {
|
|
|
|
|
v := strings.ToLower(strings.TrimSpace(opts.StorageProvider))
|
|
|
|
|
if !slices.Contains(storageProviderValues, v) {
|
|
|
|
|
return cmdutil.NewFlagError(fmt.Errorf(
|
|
|
|
|
"invalid --storage-provider %q: must be %s",
|
|
|
|
|
opts.StorageProvider, strings.Join(storageProviderValues, " | ")))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
|
|
|
|
|
Action: "kb.create",
|
|
|
|
|
Args: map[string]any{
|
|
|
|
|
"name": opts.Name,
|
|
|
|
|
"description": opts.Description,
|
|
|
|
|
},
|
|
|
|
|
}); handled {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2026-05-10 18:44:06 +00:00
|
|
|
cli, err := f.Client()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2026-05-17 17:37:47 +00:00
|
|
|
return runCreate(c.Context(), opts, fopts, cli)
|
2026-05-10 18:44:06 +00:00
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
cmd.Flags().StringVar(&opts.Description, "description", "", "Knowledge base description (optional)")
|
|
|
|
|
cmd.Flags().StringVar(&opts.EmbeddingModel, "embedding-model", "", "Embedding model ID (optional; server picks default when unset)")
|
2026-05-17 17:37:47 +00:00
|
|
|
cmd.Flags().StringVar(&opts.StorageProvider, "storage-provider", "",
|
|
|
|
|
"Storage provider for documents in this KB: "+strings.Join(storageProviderValues, " | ")+" (optional; server default when unset)")
|
|
|
|
|
cmdutil.AddFormatFlag(cmd, kbCreateFields...)
|
feat(cli): --dry-run + risk metadata + validation parity on 19 mutations
Two intertwined agent safety nets that share the same files:
1. --dry-run flag for offline preview of mutation commands
2. Risk: metadata + SetRisk helper for destructive command surfaces
Coverage (19 mutation commands with --dry-run):
kb.create/edit/delete agent.create/edit/delete
doc.create/upload/fetch/delete doc.delete_all (special variant)
session.delete chunk.delete profile.add/remove
auth.refresh/logout link unlink
api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2)
Envelope additions (omitempty in non-dry-run paths):
meta.dry_run: bool true when --dry-run was used
meta.plan: map {action, args} per the per-command taxonomy
Risk: metadata
--------------
cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with
risk.level=destructive + risk.action=<action> on the 9 destructive
commands. The SetAgentHelp wrapper prepends a "Risk: <action>
(destructive)" line in the default text help path so agents see a clear
warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays
unchanged — structured agent-help already carries warnings[].
Validation parity with the live path
------------------------------------
Every pure-local validation (flag presence, mutual exclusion, enum
bounds, URL/regex format, ResolveKBLocal for KB resolution that does not
require an SDK call) runs BEFORE the dry-run gate. This matches the
industry-standard "preview shows what live would do" contract:
--dry-run accepts exactly the same invocations the live path accepts and
rejects exactly the same invocations the live path rejects, modulo the
side-effecting work itself.
The side-effecting work (SDK calls, file writes, keyring writes, server-
side name → id resolution) is what --dry-run actually gates. Each
mutation file pairs its RunE validation block with a regression test
under *_dry_run_test.go / dryrun_validation_test.go so future refactors
don't reintroduce the gap.
Helper surface
--------------
- HandleDryRun(cmd, dryRun, plan) extracts the early-return so the
19 RunE call sites stay 3 lines each.
- EmitDryRun routes through FormatOptions.Emit, inheriting _notice /
TTY indent / --jq filtering for free.
- ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run
paths use it so the plan reports the raw --kb value (UUID or name)
without a name → id lookup.
Streaming commands (chat, session ask, session continue-stream) are
deliberately excluded: a buffered plan makes no sense for an event
stream.
Lock semantics in the dry-run path:
- destructive + --dry-run: exit 0, no exit-10 confirmation prompt
- --dry-run + -y: byte-identical envelope to --dry-run alone
- --dry-run + --jq: filter applies to the preview envelope normally
2026-05-27 20:28:48 +00:00
|
|
|
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
2026-05-29 12:06:30 +00:00
|
|
|
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
|
|
|
|
UsedFor: "Create a new knowledge base with the given name. Emits the created KB object with its id.",
|
|
|
|
|
RequiredFlags: []string{"<name> (positional)"},
|
|
|
|
|
Output: "envelope.data is the created KnowledgeBase object with id, name, type, embedding_model_id",
|
|
|
|
|
})
|
2026-05-10 18:44:06 +00:00
|
|
|
return cmd
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-17 17:37:47 +00:00
|
|
|
func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOptions, svc CreateService) error {
|
refactor(cli): delete envelope infrastructure, errors to stderr
Removes the entire envelope machinery now that every success path
emits bare JSON:
- cli/internal/format/envelope.go (Envelope, Success, Failure,
SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice,
VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests.
- cli/internal/format/filter.go envelope-specific helpers
(WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter,
filterDataPayload, filterObjectData); the reusable
filterArrayItems / filterObjectKeys / writeJQ stay for bare.go.
- cli/internal/cmdutil/exporter.go + tests (envelope-only).
- cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody +
operationRiskOf + Error.OperationRisk field + OperationRisk struct.
Error path: all errors now go to stderr via cmdutil.PrintError in
`code: message\nhint: ...` form, regardless of --json. Stdout stays
empty (or holds the partial-success the command already wrote) so
downstream `--json | jq` pipelines never have to filter error shapes
out of the success stream. Typed exit codes (3 auth.* / 4
resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.*
+ network.* / 10 input.confirmation_required) carry the failure
class for agents that branch on it.
Acceptance contract:
- envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden).
- testdata/envelopes/ → testdata/wire/.
- Error-path cases assert the typed code substring on stderr.
- Orphan whoami.*.json goldens deleted.
AGENTS.md + README.md rewritten for the bare-data contract:
- Drop envelope schema section + dry-run rule.
- Document bare JSON on stdout + `code: msg\nhint: …` on stderr.
- ADR-3 reframed around bare data and why error separation matters
for `--json | jq` pipelines.
WriteJSONFiltered short-circuits to WriteJSON when both filters are
empty (skip the marshal-buffer round-trip for the common case).
Final review pass:
- Fix wire-contract bug: `--json id,name` (space form) is broken by
pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the
field-discovery help text all switched to `--json=id,name`.
- Fix `weknora api --jq` silently ignored: api.go now routes through
WriteJSONFiltered with jopts.JQ.
- AGENTS.md: drop the false claim that `auth logout` honors `-y`
(logout is local-only with no ConfirmDestructive guard); list the
actual destructive commands instead.
- Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape
(was still parsing `out["data"]` / `env["ok"]`).
- Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated
`format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields,
jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the
format import from 22 cmd/* files.
- Delete single-caller `cmdutil.MustRequireFlag`; inline as
`_ = cmd.MarkFlagRequired(...)` everywhere.
- Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the
only write command relying on runtime --name validation while
`context add` already used the cobra-level mark.
- `context use`: register `--json` / `--jq` (was always emitting JSON
unconditionally with no human path and no flag — diverged from
every other write command); human mode now prints
`✓ Switched context to X (was Y)`.
- Replace per-package `confirmPrompter` / `scriptedConfirm` /
`errPrompter` test doubles with `testutil.ConfirmPrompter`.
- Rename `chatService` → `ChatService` (export to match siblings
`ListService` / `ViewService`); rename `printUploadSuccess` →
`renderUploadSuccess` (siblings use `render*`).
- `defaultHint(CodeResourceNotFound)`: drop the hardcoded
"list available with `weknora kb list`" — misleading on agent /
doc / session 404. Replaced with "verify the resource ID and try
again".
- Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only"
historical tags from production comments and a few test
descriptions.
2026-05-14 17:51:11 +00:00
|
|
|
// Trim defensively in case a caller invokes runCreate directly with
|
2026-05-17 17:37:47 +00:00
|
|
|
// whitespace; the cobra layer enforces a non-empty positional from the CLI.
|
2026-05-10 18:44:06 +00:00
|
|
|
if strings.TrimSpace(opts.Name) == "" {
|
2026-05-17 17:37:47 +00:00
|
|
|
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "knowledge base name is required")
|
2026-05-10 18:44:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
req := &sdk.KnowledgeBase{
|
|
|
|
|
Name: opts.Name,
|
|
|
|
|
Description: opts.Description,
|
|
|
|
|
}
|
|
|
|
|
if opts.EmbeddingModel != "" {
|
|
|
|
|
req.EmbeddingModelID = opts.EmbeddingModel
|
|
|
|
|
}
|
2026-05-17 17:37:47 +00:00
|
|
|
if opts.StorageProvider != "" {
|
|
|
|
|
v := strings.ToLower(strings.TrimSpace(opts.StorageProvider))
|
|
|
|
|
if !slices.Contains(storageProviderValues, v) {
|
|
|
|
|
return cmdutil.NewFlagError(fmt.Errorf(
|
|
|
|
|
"invalid --storage-provider %q: must be %s",
|
|
|
|
|
opts.StorageProvider, strings.Join(storageProviderValues, " | ")))
|
|
|
|
|
}
|
|
|
|
|
req.StorageProviderConfig = &sdk.StorageProviderConfig{Provider: v}
|
|
|
|
|
}
|
2026-05-10 18:44:06 +00:00
|
|
|
|
|
|
|
|
created, err := svc.CreateKnowledgeBase(ctx, req)
|
|
|
|
|
if err != nil {
|
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
|
|
|
return cmdutil.WrapHTTP(err, "create knowledge base")
|
2026-05-10 18:44:06 +00:00
|
|
|
}
|
|
|
|
|
|
2026-05-17 17:37:47 +00:00
|
|
|
if fopts.WantsJSON() {
|
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup
Sweep every CLI output path through the v0.7 envelope contract.
FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.
~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.
Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
failures*}; Successes/Failures *int so explicit zero survives
omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
cmdutil.ClassifyContextErr collapse the three previously-duplicated
multi-delete pipelines (doc / chunk / session) into one call site
pattern. doc upload --recursive uses the same helpers with a per-
file resultFn. Summary error sets Silent:true so the stderr
envelope path doesn't duplicate the stdout batch detail (exit 1
preserved via Code → ExitCode).
ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).
MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.
weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
(stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
envelope so --paginate never emits bare JSON to stdout.
Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.
Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
|
|
|
return fopts.Emit(iostreams.IO.Out, created, nil)
|
2026-05-10 18:44:06 +00:00
|
|
|
}
|
|
|
|
|
fmt.Fprintf(iostreams.IO.Out, "✓ Created knowledge base %q (id: %s)\n", created.Name, created.ID)
|
|
|
|
|
return nil
|
|
|
|
|
}
|