WeKnora/cli/cmd/api/api.go

375 lines
13 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 --data or --input). The two
// body-source flags are mutually exclusive. Default raw response body to
// stdout; --format json emits a {status, headers, body} object. Reuses sdk.Client.Raw which already
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
// 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 (
"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
Yes 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",
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
Long: `Raw HTTP API access. Body via --input <file> or --input - (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
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
The default method is GET; passing --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 context. The response body is written to stdout by default; use
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
--format json to emit a {status, headers, body} envelope.
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:
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
weknora api /api/v1/knowledge-bases # GET
echo '{"name":"foo"}' | weknora api /api/v1/knowledge-bases --input - # POST (auto)
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())
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
// as `weknora kb delete` - exit-10 protocol must apply (cli/README.md).
refactor(cli): drop --dry-run + introduce bare-JSON output path Two intertwined mainstream-alignment moves bundled because they share the migration target (every command's --json path): 1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs (gh, aws, stripe, lark): none expose --dry-run. The mainstream that does (kubectl/git/helm/ansible) operates on declarative manifests or local state where the preview is materially different from the executed action. WeKnora's CLI just echoed the same parameters that would have gone on the wire — the preview added no real signal over `--help` + reading the call site. Removes: - root --dry-run persistent flag + cmdutil/dryrun.go - DryRun fields + EmitDryRun calls in 12 write commands - format.Envelope.DryRun field - 8 corresponding *_test.go cases - --dry-run mention from README.md and CHANGELOG.md - "dry_run":false from 16 golden envelopes 2. Migrate every --json output to bare data: - New format.WriteJSON / WriteJSONFiltered helpers (cli/internal/format/bare.go) share filterArrayItems / filterObjectKeys / writeJQ with the (still-live for now) envelope filter helpers. - Read commands (kb/doc/session list+view, search chunks/docs/ sessions/kb, auth list/status, agent list/view, context list, doctor) emit bare arrays / objects on stdout. - Write commands (kb create/edit/delete/pin/empty, doc upload/ upload_recursive/delete, session delete, auth login/logout/ refresh/token, link/unlink, context add/use/remove, agent invoke, chat, api, version) emit bare result objects. Risk classification dropped — the resource + exit code already convey the action. Per-command shape changes: list / search → []T (was {ok, data:{items:[…]}}) view → T (was {ok, data:T, _meta:…}) create / edit → T delete / pin / etc. → {id, …action result…} doctor → {summary, checks} api → {status, headers, body} _meta dropped on the read path: pagination (page/page_size/total/has_more) — agents iterate with --all-pages or accept --limit (gh CLI parity); kb_id / context echo — caller already knows what it asked for. Acceptance contract goldens regenerated for the new bare shape. Error envelope on stdout (PrintErrorEnvelope) stays live for now — the envelope-infra deletion lands in the next commit.
2026-05-14 15:28:14 +00:00
if method == http.MethodDelete {
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 err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "endpoint", args[0], "api.delete", "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): 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
},
}
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
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when --input is supplied). Any non-empty method is accepted.")
refactor(cli): v0.3 cross-cutting cleanup Cross-cutting findings surfaced by the branch-completion review. Perf bug: - Factory.Client closure was not memoized. Factory.ResolveKB internally calls f.Client() to resolve --kb name → id, then the command's RunE calls f.Client() again. Two SDK clients, two keyring reads, two AuthRetryTransport allocations per name-resolved invocation, with *independent* token state (a refresh in one was invisible to the other). Switched to sync.Once like Secrets already does. Silent bug bait: - cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the empty case; code returned CodeInputInvalidArgument. Aligned doc to code (present-but-empty is a bad value, not a missing flag). Agent contract gaps: - Five user-facing subcommands lacked SetAgentHelp: auth login / logout / list / status and chat. Added concise strings with error- code call-outs so agents can branch without parsing human strings. Helper extraction (≥3 callers): - text.KnowledgeDisplayName(fileName, title, id) — byte-identical formatter that was in both cmd/doc/list.go and cmd/search/docs.go. Takes fields directly so internal/text stays SDK-free. - cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the `Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK call sites. Sed-driven migration; off-pattern shapes in chat.go (used streamErr) and cmdutil/kb.go (in-package) hand-edited. Contract test gains a comment update: post-migration the dominant pattern is WrapHTTP which the AST scanner skips entirely (only NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs() bridge still covers the dynamic codes those paths can yield. UX consistency: - cmd/doc/list.go --page-size help now reads "Items per page (1..1000)" matching cmd/session/list.go. The bounds validation already enforced 1..1000; the help text was the last drift. Comment-discipline sweep: - Deleted the WHAT-only "*Options captures `weknora ...` flag state" docstring across 23 files (context, kb, auth, doc, session, search, chat, doctor, link). Where the line carried a real WHY clause (kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and dropped only the leading WHAT phrase. - Stripped third-party project-name attribution from inline comments and one user-visible flag-help string across ~40 files in cli/cmd and cli/internal (plus 4 test-file comments). Removed phrases like "Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style", "gcloud `--project`", "Stripe pattern", and the embedded GitHub URLs pointing at those projects. Behavioral descriptions and the WHY behind each comment are preserved; only the upstream-name attribution is gone. Inspiration / north-star references belong in cli/AGENTS.md (the design doc) and commit messages, not scattered through every file. Triggered by an audit round that surfaced several false / fragile parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no --name flag; "matches gcloud `--project` id-or-name" — gcloud's --project accepts ID only). Rather than fix them one by one, the whole category of in-comment external-project references was stripped uniformly.
2026-05-12 15:42:20 +00:00
cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin)")
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): 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.
func readInput(opts *Options) ([]byte, error) {
if opts.Input == "-" {
r := opts.StdinReader
if r == nil {
r = iostreams.IO.In
}
b, err := io.ReadAll(r)
if err != nil {
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read request body from stdin")
}
return b, nil
}
b, err := os.ReadFile(opts.Input)
if err != nil {
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read input file %s", opts.Input)
}
return b, 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
// resolveMethod implements the auto-method behavior: explicit -X wins;
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
// otherwise body presence promotes GET → POST.
func resolveMethod(opts *Options) string {
if opts.Method != "" {
return strings.ToUpper(opts.Method)
}
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 opts.Input != "" {
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): 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))
}
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
// Resolve request body from --input (file path or `-` for 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
var body any
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 opts.Input != "" {
contents, err := readInput(opts)
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 != 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
}
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
}
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
// Best-effort decode: if response body is valid JSON, surface the
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
// parsed structure under .body so JSON consumers can drill
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
// in; otherwise fall back to the raw string.
var bodyAny any
if len(respBody) > 0 {
if err := json.Unmarshal(respBody, &bodyAny); err != nil {
bodyAny = string(respBody)
}
}
hdrs := make(map[string]string, len(resp.Header))
for k, v := range resp.Header {
if len(v) > 0 {
hdrs[k] = v[0]
}
}
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
// Route through fopts.Emit so the payload lives under .data in the
// success envelope. --jq applies to the full envelope, so users
// project with ".data.status", ".data.body", etc.
payload := map[string]any{
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
"status": resp.StatusCode,
"headers": hdrs,
"body": bodyAny,
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(out, payload, 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(respBody); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write response body")
}
if len(respBody) > 0 && respBody[len(respBody)-1] != '\n' {
_, _ = 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 {
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 passThroughFallback(body, resp, 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 {
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 passThroughFallback(body, resp, 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)
}
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
// passThroughFallback handles the case where --paginate detects a
// non-paginated first-page response. When JSON output is requested, it routes
// the body through fopts.Emit in the same {status, headers, body} envelope
// shape that runAPISingle produces — keeping the wire contract consistent
// regardless of whether --paginate was passed. For human-readable mode it
// writes the raw body verbatim (same as the original passThroughRaw behavior).
func passThroughFallback(body []byte, resp *http.Response, fopts *cmdutil.FormatOptions) error {
out := iostreams.IO.Out
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 fopts.WantsJSON() {
var bodyAny any
if len(body) > 0 {
if err := json.Unmarshal(body, &bodyAny); err != nil {
bodyAny = string(body) // best-effort string fallback
}
}
hdrs := collectHeaders(resp)
return fopts.Emit(out, map[string]any{
"status": resp.StatusCode,
"headers": hdrs,
"body": bodyAny,
}, nil)
}
// Human-readable: raw passthrough, same as before.
if _, err := out.Write(body); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write response body")
}
if len(body) > 0 && body[len(body)-1] != '\n' {
_, _ = out.Write([]byte{'\n'})
}
return 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
// collectHeaders extracts the first value of each response header into a flat
// map, matching the shape that runAPISingle emits in its JSON envelope.
func collectHeaders(resp *http.Response) map[string]string {
hdrs := make(map[string]string, len(resp.Header))
for k, v := range resp.Header {
if len(v) > 0 {
hdrs[k] = v[0]
}
}
return hdrs
}
// 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)