WeKnora/cli/cmd/api/api.go

518 lines
20 KiB
Go
Raw Normal View History

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
// Package api implements the `weknora api` raw HTTP passthrough command.
//
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
// Shape: one positional (path) + `-X/--method` flag, default GET (auto-
// promoted to POST when a body is supplied via -d/--input). Text mode writes
// the raw response body to stdout; --format json places the parsed server
// response directly under envelope.data (no {status, headers, body} wrapper),
// so `--jq '.data...'` projects at the server's own depth. Reuses
// sdk.Client.Raw which already applies tenant + auth headers.
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
package api
import (
"bytes"
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
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
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
"os"
"strconv"
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
"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"
)
// apiFields is intentionally a marker - api wraps arbitrary HTTP responses
// whose schema the CLI doesn't know, so field hints are meaningless here.
// The marker shows up in --help so users can tell.
var apiFields = []string{"<response-shape-varies>"}
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
type Options struct {
Method string
Input string // --input: file path, "-" for stdin
Data string // -d/--data: inline JSON body (mutually exclusive with --input)
Fields []string // -F/--field: key=value pairs assembled into a JSON object body (mutually exclusive with -d/--input)
Yes bool
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
StdinReader io.Reader // overridden by tests; defaults to iostreams.IO.In
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
}
// Service is the narrow SDK surface this command depends on. The production
// implementation is *sdk.Client, whose Raw method already injects auth /
// tenant / request-id headers (see client.applyAuthHeaders). Tests substitute
// either a fake or a real client pointed at httptest.Server.
type Service interface {
Raw(ctx context.Context, method, path string, body any) (*http.Response, error)
}
// NewCmd returns the `weknora api` command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
Use: "api <path>",
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
Short: "Make a raw API request to the WeKnora server",
Long: `Raw HTTP API access. JSON body via -d/--data (inline) or --input <file>/- (stdin).
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
The default method is GET; supplying a body (-d or --input) auto-promotes it
to POST. Use -X/--method to override (any non-empty method is accepted:
DELETE / PUT / PATCH / HEAD / OPTIONS / TRACE / custom).
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
Auth, tenant, and request-id headers are applied automatically from the
active profile. In text mode (default) the raw server response body is written
to stdout. In --format json the parsed server response is placed directly
under envelope.data — drill in with --jq '.data...' at the server's own depth
(e.g. '.data.data[]' for a list endpoint). Only -X DELETE is confirmation-gated.
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
Examples:
weknora api /api/v1/knowledge-bases # GET
weknora api /api/v1/knowledge-bases -d '{"name":"foo"}' # POST (auto)
weknora api /api/v1/knowledge-bases -F name=foo -F enabled=true # POST, typed body
echo '{"name":"foo"}' | weknora api /api/v1/knowledge-bases --input - # POST via stdin
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
weknora api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
Args: cobra.ExactArgs(1),
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
RunE: func(c *cobra.Command, args []string) error {
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
opts.Yes, _ = c.Flags().GetBool("yes")
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
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
if opts.DryRun {
// --dry-run on the raw escape-hatch is only meaningful when a
// would-be mutation exists to preview. GET (default or explicit)
// is read-only with no side effect, so previewing it is a
// likely user error — signal it via FlagError exit 2 with the
// concrete repair. Use resolveMethod so --input auto-promotes
// GET → POST identically to the live path.
method := resolveMethod(opts)
if method == http.MethodGet {
return cmdutil.NewFlagError(fmt.Errorf(
"--dry-run requires explicit -X POST/PUT/PATCH/DELETE; default GET is read-only with no side effect to preview"))
}
var body any
if hasBody(opts) {
contents, err := resolveBody(opts)
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
if err != nil {
return err
}
// Surface the parsed body in the plan so agents can grep
// meta.plan.body for shape; resolveBody has already validated
// it as JSON.
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
var parsed any
if json.Unmarshal(contents, &parsed) == nil {
body = parsed
} else {
body = string(contents)
}
}
if handled, err := cmdutil.HandleDryRun(c, true, cmdutil.DryRunPlan{
Action: "api." + strings.ToLower(method),
Method: method,
Path: args[0],
Body: body,
}); handled {
return err
}
}
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
method := resolveMethod(opts)
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
// Escape-hatch DELETE through `weknora api` is just as destructive
feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening A hardening + finalization pass over the agent-first CLI: correctness fixes, richer machine-readable signals, flag/naming consistency, and a symmetric config surface. Pre-1.0, so it includes breaking renames. Correctness: - agent update: resolve/validate --model/--rerank-model (was storing a bogus name verbatim, corrupting config.model_id). - doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports "no host configured"). - session ask / MCP session_ask: text answer was empty on non-TTY — the agent stream sets Done=true on an intermediate agent_query frame before the answer, and AgentAccumulator treated the first Done as terminal. Terminate on the `complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done. - batch exit codes: any per-item failure collapses to operation.failed (exit 1), including `doc upload --recursive` partial failures — a permanent per-file failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent would loop on; per-item typed errors stay in the envelope. Agent-first signals & discovery: - error.exit_code in the envelope (type + exit_code disambiguate the input.invalid_argument exit-2-vs-5 split in one JSON read). - meta.hint on empty content search and on draft doc create; doc wait fails fast on a never-parsing draft instead of hanging to --timeout. - retrieval-readiness is visible in the natural flow: kb status / kb check emit retrieval_ready, and kb create hints the fix when no embedding model is bound — an unconfigured KB no longer looks silently healthy. - schema contract completeness: every leaf declares output + >=1 example (drift-guarded); output strings match the meta actually emitted; chunk list and search docs now emit meta.total_count (both previously dropped it). - schema tolerates a quoted multi-word command label; zero-state auth — and `link` with no profile — point at profile setup / the headless WEKNORA_KB_ID path instead of looping on `auth login`. - id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view accept and ignore it, declared in schema) so a carried-over --kb doesn't exit 2; streaming commands warn that --jq does not apply to an NDJSON stream. - keep JSON-always as the default; --jq hints spell out the .data path. Consistency & gating: - doc create: drop the deprecated --name alias (--title only; pre-1.0 break). - chunk list --limit aligned to 1..10000; model list --limit/-L with has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install expands a leading ~. - docs corrected: search docs / doc list --keyword help is case-insensitive (server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add model.update / kb.config.set) and batch example (failed item carries `error`); session resume --message id comes from `message list`, not the stream. - auth/profile ergonomics: env credentials are now first-class — `auth token` prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh give an env-aware message instead of looping on "run auth login". `auth logout` clears credentials but keeps the profile registered (host preserved for re-login); deleting a profile is `profile remove`'s job (clean logout/remove separation, matching gh / lark). Config surface (symmetric read/write, in-place model edits): - kb config now returns a secret-free KBModelConfigView (was {}); `kb config` reads, new `kb config set` writes; `kb init` removed (misnomer). - kb create --chat-model: retrieval-ready in one step. - model update: edit a model in place (id preserved, references survive) — rotate --api-key-stdin, change base-url / display-name / etc. - session continue-stream renamed to session resume. Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale kb-init / continue-stream references removed; skill wire-vocab guard extended. AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an embedding model to be searchable), that --jq does not apply to NDJSON streams, and the env-credential-first auth path; the KB quickstart example now creates a retrieval-ready KB.
2026-07-02 07:53:51 +00:00
// as `weknora kb delete` - exit-10 destructive protocol must apply
// (cli/README.md). PUT/PATCH mutate server state like a typed
// `kb/agent/doc update`, so they get the same exit-10 WRITE gate;
// without it the raw escape hatch bypassed the "an agent cannot
// silently mutate" guarantee. POST stays ungated to match typed
// `create` (also ungated). GET/HEAD are reads.
switch method {
case http.MethodDelete:
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "endpoint", args[0], "api.delete", []string{"weknora", "api", "-X", "DELETE", args[0], "-y"}); err != nil {
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
return err
}
feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening A hardening + finalization pass over the agent-first CLI: correctness fixes, richer machine-readable signals, flag/naming consistency, and a symmetric config surface. Pre-1.0, so it includes breaking renames. Correctness: - agent update: resolve/validate --model/--rerank-model (was storing a bogus name verbatim, corrupting config.model_id). - doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports "no host configured"). - session ask / MCP session_ask: text answer was empty on non-TTY — the agent stream sets Done=true on an intermediate agent_query frame before the answer, and AgentAccumulator treated the first Done as terminal. Terminate on the `complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done. - batch exit codes: any per-item failure collapses to operation.failed (exit 1), including `doc upload --recursive` partial failures — a permanent per-file failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent would loop on; per-item typed errors stay in the envelope. Agent-first signals & discovery: - error.exit_code in the envelope (type + exit_code disambiguate the input.invalid_argument exit-2-vs-5 split in one JSON read). - meta.hint on empty content search and on draft doc create; doc wait fails fast on a never-parsing draft instead of hanging to --timeout. - retrieval-readiness is visible in the natural flow: kb status / kb check emit retrieval_ready, and kb create hints the fix when no embedding model is bound — an unconfigured KB no longer looks silently healthy. - schema contract completeness: every leaf declares output + >=1 example (drift-guarded); output strings match the meta actually emitted; chunk list and search docs now emit meta.total_count (both previously dropped it). - schema tolerates a quoted multi-word command label; zero-state auth — and `link` with no profile — point at profile setup / the headless WEKNORA_KB_ID path instead of looping on `auth login`. - id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view accept and ignore it, declared in schema) so a carried-over --kb doesn't exit 2; streaming commands warn that --jq does not apply to an NDJSON stream. - keep JSON-always as the default; --jq hints spell out the .data path. Consistency & gating: - doc create: drop the deprecated --name alias (--title only; pre-1.0 break). - chunk list --limit aligned to 1..10000; model list --limit/-L with has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install expands a leading ~. - docs corrected: search docs / doc list --keyword help is case-insensitive (server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add model.update / kb.config.set) and batch example (failed item carries `error`); session resume --message id comes from `message list`, not the stream. - auth/profile ergonomics: env credentials are now first-class — `auth token` prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh give an env-aware message instead of looping on "run auth login". `auth logout` clears credentials but keeps the profile registered (host preserved for re-login); deleting a profile is `profile remove`'s job (clean logout/remove separation, matching gh / lark). Config surface (symmetric read/write, in-place model edits): - kb config now returns a secret-free KBModelConfigView (was {}); `kb config` reads, new `kb config set` writes; `kb init` removed (misnomer). - kb create --chat-model: retrieval-ready in one step. - model update: edit a model in place (id preserved, references survive) — rotate --api-key-stdin, change base-url / display-name / etc. - session continue-stream renamed to session resume. Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale kb-init / continue-stream references removed; skill wire-vocab guard extended. AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an embedding model to be searchable), that --jq does not apply to NDJSON streams, and the env-credential-first auth path; the KB quickstart example now creates a retrieval-ready KB.
2026-07-02 07:53:51 +00:00
case http.MethodPut, http.MethodPatch:
if err := cmdutil.ConfirmWrite(f.Prompter(), opts.Yes, fopts.WantsJSON(), "write", "endpoint", args[0], "api."+strings.ToLower(method), apiRetryArgv(opts, method, args[0])); err != nil {
return err
}
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
}
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
cli, err := f.Client()
if err != nil {
return err
}
paginate, _ := c.Flags().GetBool("paginate")
return runAPI(c.Context(), opts, fopts, cli, method, args[0], paginate)
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.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied via -d/--input). Any non-empty method is accepted.")
cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Inline JSON request body (e.g. -d '{\"name\":\"x\"}'). Mutually exclusive with --input.")
cmd.Flags().StringVar(&opts.Input, "input", "", "Read JSON request body from file (use `-` for stdin). Mutually exclusive with -d/--data.")
cmd.Flags().StringArrayVarP(&opts.Fields, "field", "F", nil, "Add a key=value to a JSON object body (repeatable; e.g. -F name=foo -F enabled=true). true/false/null and numbers are typed; everything else is a string. Flat keys only. Mutually exclusive with -d/--input.")
cmd.Flags().Bool("paginate", false, "Follow offset-based pagination (?page=N&page_size=M), merging all pages into a single {data, total} JSON response.")
cmdutil.AddFormatFlag(cmd, apiFields...)
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)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "raw HTTP passthrough to weknora-server API endpoints when typed subcommands are insufficient",
RequiredFlags: []string{"path (positional)"},
Examples: []string{
"weknora api /api/v1/knowledge-bases",
"weknora api /api/v1/knowledge-bases -d '{\"name\":\"foo\"}'",
"weknora api -X POST /api/v1/knowledge-bases -F name=\"Eng Docs\" -F enabled=true",
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
"weknora api -X DELETE /api/v1/knowledge-bases/kb_x -y",
"echo '{\"name\":\"foo\"}' | weknora api /api/v1/knowledge-bases --input -",
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
},
Output: "text mode (default): the raw server response body on stdout. json mode: the parsed server response is placed directly under envelope.data — project with --jq '.data...' at the server's own depth (e.g. '.data.data[]' for a list endpoint, '.data.data.id' for a created object). With --paginate, envelope.data is the merged {data, total}.",
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
Warnings: []string{
feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening A hardening + finalization pass over the agent-first CLI: correctness fixes, richer machine-readable signals, flag/naming consistency, and a symmetric config surface. Pre-1.0, so it includes breaking renames. Correctness: - agent update: resolve/validate --model/--rerank-model (was storing a bogus name verbatim, corrupting config.model_id). - doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports "no host configured"). - session ask / MCP session_ask: text answer was empty on non-TTY — the agent stream sets Done=true on an intermediate agent_query frame before the answer, and AgentAccumulator treated the first Done as terminal. Terminate on the `complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done. - batch exit codes: any per-item failure collapses to operation.failed (exit 1), including `doc upload --recursive` partial failures — a permanent per-file failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent would loop on; per-item typed errors stay in the envelope. Agent-first signals & discovery: - error.exit_code in the envelope (type + exit_code disambiguate the input.invalid_argument exit-2-vs-5 split in one JSON read). - meta.hint on empty content search and on draft doc create; doc wait fails fast on a never-parsing draft instead of hanging to --timeout. - retrieval-readiness is visible in the natural flow: kb status / kb check emit retrieval_ready, and kb create hints the fix when no embedding model is bound — an unconfigured KB no longer looks silently healthy. - schema contract completeness: every leaf declares output + >=1 example (drift-guarded); output strings match the meta actually emitted; chunk list and search docs now emit meta.total_count (both previously dropped it). - schema tolerates a quoted multi-word command label; zero-state auth — and `link` with no profile — point at profile setup / the headless WEKNORA_KB_ID path instead of looping on `auth login`. - id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view accept and ignore it, declared in schema) so a carried-over --kb doesn't exit 2; streaming commands warn that --jq does not apply to an NDJSON stream. - keep JSON-always as the default; --jq hints spell out the .data path. Consistency & gating: - doc create: drop the deprecated --name alias (--title only; pre-1.0 break). - chunk list --limit aligned to 1..10000; model list --limit/-L with has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install expands a leading ~. - docs corrected: search docs / doc list --keyword help is case-insensitive (server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add model.update / kb.config.set) and batch example (failed item carries `error`); session resume --message id comes from `message list`, not the stream. - auth/profile ergonomics: env credentials are now first-class — `auth token` prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh give an env-aware message instead of looping on "run auth login". `auth logout` clears credentials but keeps the profile registered (host preserved for re-login); deleting a profile is `profile remove`'s job (clean logout/remove separation, matching gh / lark). Config surface (symmetric read/write, in-place model edits): - kb config now returns a secret-free KBModelConfigView (was {}); `kb config` reads, new `kb config set` writes; `kb init` removed (misnomer). - kb create --chat-model: retrieval-ready in one step. - model update: edit a model in place (id preserved, references survive) — rotate --api-key-stdin, change base-url / display-name / etc. - session continue-stream renamed to session resume. Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale kb-init / continue-stream references removed; skill wire-vocab guard extended. AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an embedding model to be searchable), that --jq does not apply to NDJSON streams, and the env-credential-first auth path; the KB quickstart example now creates a retrieval-ready KB.
2026-07-02 07:53:51 +00:00
"-X DELETE is destructive-gated and -X PUT/PATCH are write-gated (exit 10 / input.confirmation_required unless -y), matching typed delete/update. -X POST (create-shaped) and GET are unguarded — you own the safety of creates made through this escape hatch.",
"Raw passthrough: the typed error envelope does NOT fully apply. The server's own response goes under envelope.data at its native depth; a non-2xx HTTP status surfaces via the exit code, not a typed error.type/retry_argv. Do not rely on error.type/retryable for `api` the way you do for typed subcommands.",
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
"Raw HTTP passthrough; agents should prefer typed subcommands (kb/doc/session/...) when available.",
},
})
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
return cmd
}
// readInput reads opts.Input and returns its contents. "-" reads from
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
// opts.StdinReader (or iostreams.IO.In as the production default) for
// piped JSON payloads.
//
// The body is sent as a JSON document (the SDK marshals it as json.RawMessage),
// so a non-JSON / malformed payload is validated and rejected here as
// input.invalid_argument (exit 5). Without this, the failure surfaced from the
// SDK's marshal step as a confusing network.error (exit 7, "retryable") —
// looping an agent on a body that can never be sent.
func readInput(opts *Options) ([]byte, error) {
var b []byte
if opts.Input == "-" {
r := opts.StdinReader
if r == nil {
r = iostreams.IO.In
}
var err error
b, err = io.ReadAll(r)
if err != nil {
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read request body from stdin")
}
} else {
var err error
b, err = os.ReadFile(opts.Input)
if err != nil {
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read input file %s", opts.Input)
}
}
if len(bytes.TrimSpace(b)) > 0 && !json.Valid(b) {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--input must be valid JSON (the request body is sent as a JSON document)")
}
return b, nil
}
// resolveBody returns the request body bytes from -d/--data (inline) or
// --input (file/stdin), or nil when neither is set. Inline --data is
// validated as JSON here; --input is validated inside readInput. The two
// flags are mutually exclusive — checked here (rather than cobra's
// MarkFlagsMutuallyExclusive, whose violation surfaces as an unclassified
// internal.error / exit 1) so the conflict reports input.invalid_argument.
func resolveBody(opts *Options) ([]byte, error) {
set := 0
if opts.Data != "" {
set++
}
if opts.Input != "" {
set++
}
if len(opts.Fields) > 0 {
set++
}
if set > 1 {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"-d/--data, --input, and -F/--field are mutually exclusive; supply the body one way")
}
if len(opts.Fields) > 0 {
return buildFieldBody(opts.Fields)
}
if opts.Data != "" {
if !json.Valid([]byte(opts.Data)) {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"-d/--data must be valid JSON (the request body is sent as a JSON document)")
}
return []byte(opts.Data), nil
}
if opts.Input != "" {
return readInput(opts)
}
return nil, nil
}
// hasBody reports whether a request body was supplied via -d or --input.
func hasBody(opts *Options) bool {
return opts.Data != "" || opts.Input != "" || len(opts.Fields) > 0
}
// inferFieldValue maps a -F value string to a typed JSON scalar: literal
// true/false/null and integer/float literals become typed JSON; everything
// else stays a string. A value that looks numeric but must stay a string
// (e.g. a zero-padded id "007") can't be forced here — use -d/--data or
// --input for full control.
func inferFieldValue(v string) any {
switch v {
case "true":
return true
case "false":
return false
case "null":
return nil
}
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
return i
}
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f
}
return v
}
// buildFieldBody assembles -F/--field key=value pairs into a JSON object with
// type inference. Flat keys only. Returns input.invalid_argument (exit 5) for
// a malformed pair or an unsupported @file value.
func buildFieldBody(fields []string) ([]byte, error) {
obj := make(map[string]any, len(fields))
for _, f := range fields {
k, v, ok := strings.Cut(f, "=")
if !ok || k == "" {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("-F/--field must be key=value, got %q", f))
}
if strings.HasPrefix(v, "@") {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("-F %q: @file values are not supported; read a file body with --input", f))
}
obj[k] = inferFieldValue(v)
}
return json.Marshal(obj)
}
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
// resolveMethod implements the auto-method behavior: explicit -X wins;
// otherwise body presence (-d/--data or --input) promotes GET → POST.
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
func resolveMethod(opts *Options) string {
if opts.Method != "" {
return strings.ToUpper(opts.Method)
}
if hasBody(opts) {
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
return "POST"
}
return "GET"
}
feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening A hardening + finalization pass over the agent-first CLI: correctness fixes, richer machine-readable signals, flag/naming consistency, and a symmetric config surface. Pre-1.0, so it includes breaking renames. Correctness: - agent update: resolve/validate --model/--rerank-model (was storing a bogus name verbatim, corrupting config.model_id). - doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports "no host configured"). - session ask / MCP session_ask: text answer was empty on non-TTY — the agent stream sets Done=true on an intermediate agent_query frame before the answer, and AgentAccumulator treated the first Done as terminal. Terminate on the `complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done. - batch exit codes: any per-item failure collapses to operation.failed (exit 1), including `doc upload --recursive` partial failures — a permanent per-file failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent would loop on; per-item typed errors stay in the envelope. Agent-first signals & discovery: - error.exit_code in the envelope (type + exit_code disambiguate the input.invalid_argument exit-2-vs-5 split in one JSON read). - meta.hint on empty content search and on draft doc create; doc wait fails fast on a never-parsing draft instead of hanging to --timeout. - retrieval-readiness is visible in the natural flow: kb status / kb check emit retrieval_ready, and kb create hints the fix when no embedding model is bound — an unconfigured KB no longer looks silently healthy. - schema contract completeness: every leaf declares output + >=1 example (drift-guarded); output strings match the meta actually emitted; chunk list and search docs now emit meta.total_count (both previously dropped it). - schema tolerates a quoted multi-word command label; zero-state auth — and `link` with no profile — point at profile setup / the headless WEKNORA_KB_ID path instead of looping on `auth login`. - id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view accept and ignore it, declared in schema) so a carried-over --kb doesn't exit 2; streaming commands warn that --jq does not apply to an NDJSON stream. - keep JSON-always as the default; --jq hints spell out the .data path. Consistency & gating: - doc create: drop the deprecated --name alias (--title only; pre-1.0 break). - chunk list --limit aligned to 1..10000; model list --limit/-L with has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install expands a leading ~. - docs corrected: search docs / doc list --keyword help is case-insensitive (server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add model.update / kb.config.set) and batch example (failed item carries `error`); session resume --message id comes from `message list`, not the stream. - auth/profile ergonomics: env credentials are now first-class — `auth token` prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh give an env-aware message instead of looping on "run auth login". `auth logout` clears credentials but keeps the profile registered (host preserved for re-login); deleting a profile is `profile remove`'s job (clean logout/remove separation, matching gh / lark). Config surface (symmetric read/write, in-place model edits): - kb config now returns a secret-free KBModelConfigView (was {}); `kb config` reads, new `kb config set` writes; `kb init` removed (misnomer). - kb create --chat-model: retrieval-ready in one step. - model update: edit a model in place (id preserved, references survive) — rotate --api-key-stdin, change base-url / display-name / etc. - session continue-stream renamed to session resume. Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale kb-init / continue-stream references removed; skill wire-vocab guard extended. AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an embedding model to be searchable), that --jq does not apply to NDJSON streams, and the env-credential-first auth path; the KB quickstart example now creates a retrieval-ready KB.
2026-07-02 07:53:51 +00:00
// apiRetryArgv reconstructs a directly-executable `weknora api` argv (with -y)
// for the write-confirmation gate, preserving the method, path and body flags
// the caller passed so an agent can re-run the exact mutation after approval.
func apiRetryArgv(opts *Options, method, path string) []string {
argv := []string{"weknora", "api", "-X", method, path}
switch {
case opts.Data != "":
argv = append(argv, "-d", opts.Data)
case opts.Input != "":
argv = append(argv, "--input", opts.Input)
default:
for _, f := range opts.Fields {
argv = append(argv, "-F", f)
}
}
return append(argv, "-y")
}
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
// runAPI is the testable core: validate inputs, dispatch via Service.Raw,
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
// classify status, and emit either the raw body or a JSON object. The
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
// caller is responsible for resolving the method (defaults / auto-POST)
// and uppercasing it; runAPI guards against unsupported values like
// `-X PATCH-INVALID` reaching the wire.
//
// When paginate is true and method is GET, all offset-based pages are
// fetched and merged into a single {data, total} JSON response. For
// non-GET methods paginate is silently ignored (no offset semantic).
func runAPI(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, method, path string, paginate bool) error {
if paginate && method == http.MethodGet {
return runAPIPaginated(ctx, opts, fopts, svc, path)
}
return runAPISingle(ctx, opts, fopts, svc, method, path)
}
// runAPISingle is the original single-call implementation of runAPI.
func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, method, path string) error {
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
if method == "" {
return cmdutil.NewFlagError(fmt.Errorf("--method cannot be empty"))
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
}
if !strings.HasPrefix(path, "/") {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
}
// Resolve request body from -d/--data (inline) or --input (file / `-`).
// Empty input is treated as no body rather than an empty JSON document
// (which fails to marshal).
contents, err := resolveBody(opts)
if err != nil {
return err
}
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
var body any
if len(bytes.TrimSpace(contents)) > 0 {
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
body = json.RawMessage(contents)
}
resp, err := svc.Raw(ctx, method, path, body)
if err != nil {
// Transport / DNS failure (Raw never returns a typed HTTP error of its
// own; non-2xx responses still surface as resp != nil, 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, "%s %s", method, path)
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
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "read response body")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
code := cmdutil.ClassifyHTTPStatus(resp.StatusCode)
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
ce := cmdutil.NewError(code, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody))))
if v := resp.Header.Get("Retry-After"); v != "" {
if s, perr := strconv.Atoi(v); perr == nil && s > 0 {
ce = ce.WithRetryAfter(s)
}
}
return ce
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
}
return emitRawBody(respBody, fopts)
}
// emitRawBody writes a server response body under the active format. JSON mode
// places the parsed body directly under envelope.data — no {status, headers,
// body} wrapper — so `--jq '.data...'` projects at the server's own shape
// (e.g. `.data.data[]` for a list endpoint) rather than a triple-nested
// `.data.body.data[]`; non-JSON decodes best-effort to a raw string. Text mode
// writes the body verbatim with a trailing newline. Shared by the single and
// paginated-fallback paths so both project identically.
func emitRawBody(body []byte, fopts *cmdutil.FormatOptions) error {
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
out := iostreams.IO.Out
if fopts.WantsJSON() {
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
var bodyAny any
if len(body) > 0 {
if err := json.Unmarshal(body, &bodyAny); err != nil {
bodyAny = string(body)
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
}
}
return fopts.Emit(out, bodyAny, nil)
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
}
if _, err := out.Write(body); err != nil {
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
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write response body")
}
if len(body) > 0 && body[len(body)-1] != '\n' {
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
_, _ = out.Write([]byte{'\n'})
}
return nil
}
// runAPIPaginated fetches all offset-based pages for a GET request and writes
// a single merged {data, total} JSON object to stdout. If the first page
// response does not carry pagination metadata (total + page_size), the raw
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
// response is passed through via passThroughFallback which respects the
// --format envelope contract (same shape as runAPISingle's fallback path).
func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, path string) error {
if !strings.HasPrefix(path, "/") {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
}
pageSize := extractPageSize(path)
if pageSize == 0 {
pageSize = 50
}
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
allData := []json.RawMessage{}
var lastTotal int64
page := 1
for {
curPath := setPageParam(path, page, pageSize)
resp, err := svc.Raw(ctx, http.MethodGet, curPath, nil)
if err != nil {
return cmdutil.WrapHTTP(err, "GET %s", curPath)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
code := cmdutil.ClassifyHTTPStatus(resp.StatusCode)
return cmdutil.NewError(code, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body))))
}
var pageResp struct {
Data []json.RawMessage `json:"data"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
if err := json.Unmarshal(body, &pageResp); err != nil {
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
// Non-JSON response on first page — fall back through the envelope.
if page == 1 {
return emitRawBody(body, fopts)
}
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--paginate: page %d response not in expected shape: %v", page, err))
}
// Heuristic: if the first page lacks pagination metadata, treat the
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
// response as non-paginated and fall back through the envelope.
if page == 1 && pageResp.Total == 0 && pageResp.PageSize == 0 {
return emitRawBody(body, fopts)
}
allData = append(allData, pageResp.Data...)
lastTotal = pageResp.Total
// Termination: accumulated count (not page*pageSize) handles server-capped page sizes.
if int64(len(allData)) >= pageResp.Total || len(pageResp.Data) == 0 {
break
}
page++
}
merged := map[string]any{
"data": allData,
"total": lastTotal,
}
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, merged, nil)
}
// extractPageSize parses the page_size query parameter from path, returning 0
// if absent or unparseable.
func extractPageSize(path string) int {
u, err := url.Parse(path)
if err != nil {
return 0
}
if v := u.Query().Get("page_size"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
return n
}
}
return 0
}
// setPageParam rewrites the page and page_size query parameters in path,
// preserving all other query parameters.
func setPageParam(path string, page, pageSize int) string {
u, err := url.Parse(path)
if err != nil {
return path
}
q := u.Query()
q.Set("page", strconv.Itoa(page))
q.Set("page_size", strconv.Itoa(pageSize))
u.RawQuery = q.Encode()
return u.String()
}
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
// compile-time check: the production SDK client implements Service.
var _ Service = (*sdk.Client)(nil)