WeKnora/cli/cmd/api/api_test.go

606 lines
21 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
import (
"bytes"
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
"context"
"encoding/json"
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
"errors"
"fmt"
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
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
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
"github.com/spf13/cobra"
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
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
"github.com/Tencent/WeKnora/cli/internal/prompt"
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
sdk "github.com/Tencent/WeKnora/client"
)
// fakeAPISvc is a test double for Service that delegates each call to a
// caller-supplied do function, giving full control over per-call responses.
type fakeAPISvc struct {
do func(method, path string, body any) (*http.Response, error)
}
func (f *fakeAPISvc) Raw(_ context.Context, method, path string, body any) (*http.Response, error) {
return f.do(method, path, body)
}
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
// newTestClient stands up an httptest server with the supplied handler and
// returns an *sdk.Client targeting it plus a teardown closure. The real SDK is
// used so we exercise the same Raw() code path as production (header
// injection, JSON marshalling, etc.).
func newTestClient(t *testing.T, h http.HandlerFunc) (*sdk.Client, func()) {
t.Helper()
srv := httptest.NewServer(h)
return sdk.NewClient(srv.URL), srv.Close
}
func TestAPI_GetSuccess(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/v1/foo" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"hello":"world"}`))
})
defer stop()
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/foo", false); err != nil {
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
t.Fatalf("runAPI: %v", err)
}
got := out.String()
if !strings.Contains(got, `"hello":"world"`) {
t.Errorf("expected raw JSON body in stdout, got %q", got)
}
if !strings.HasSuffix(got, "\n") {
t.Errorf("expected trailing newline appended, got %q", got)
}
}
func TestAPI_GetSuccess_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Request-Id", "req-123")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"value":42}`))
})
defer stop()
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "GET", "/api/v1/foo", false); err != nil {
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
t.Fatalf("runAPI: %v", err)
}
// The server response is passed through directly under envelope.data — no
// {status, headers, body} wrapper — so consumers project at the server's
// own depth (e.g. .data.value here).
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
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
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
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("decode envelope JSON: %v\n%s", err, out.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
}
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 !env.OK {
t.Errorf("envelope ok: want true, got false")
}
if v, ok := env.Data["value"]; !ok || v.(float64) != 42 {
t.Errorf("data.value: want 42 directly under .data (no .body nesting), got %v", env.Data)
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
}
}
// TestAPI_InlineDataBody verifies -d/--data sends an inline JSON body and
// auto-promotes the method to POST.
func TestAPI_InlineDataBody(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
var seenMethod string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{"id":"new"}`))
})
defer stop()
opts := &Options{Data: `{"name":"foo"}`}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, resolveMethod(opts), "/api/v1/things", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if seenMethod != http.MethodPost {
t.Errorf("inline -d should auto-promote to POST, got %s", seenMethod)
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 string(seenBody) != `{"name":"foo"}` {
t.Errorf("server received body %q, want the inline --data JSON", seenBody)
}
}
// TestAPI_InlineDataMalformed_RejectedAsInput pins that a malformed -d body is
// rejected as input.invalid_argument before any request.
func TestAPI_InlineDataMalformed_RejectedAsInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
_, _ = w.Write([]byte(`{}`))
})
defer stop()
opts := &Options{Data: `{bad`}
err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "POST", "/api/v1/things", false)
var typed *cmdutil.Error
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("want input.invalid_argument for malformed -d, got %v", err)
}
if called {
t.Error("server must not be called with a malformed inline body")
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
}
}
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
func TestAPI_PostWithStdinInput(t *testing.T) {
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
_, _ = iostreams.SetForTest(t)
var seenBody []byte
var seenMethod, seenPath string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
seenPath = r.URL.Path
seenBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"new"}`))
})
defer stop()
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
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/things", false); err != nil {
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
t.Fatalf("runAPI: %v", err)
}
if seenMethod != http.MethodPost || seenPath != "/api/v1/things" {
t.Errorf("server saw %s %s, want POST /api/v1/things", seenMethod, seenPath)
}
if string(seenBody) != `{"name":"foo"}` {
t.Errorf("server received body %q, want %q", seenBody, `{"name":"foo"}`)
}
}
// TestAPI_MalformedInputJSON_RejectedAsInput pins that a non-JSON --input body
// is rejected with input.invalid_argument (exit 5) at the boundary, not the
// confusing network.error (exit 7, "retryable") the SDK's marshal step
// produced. The server must never be called.
func TestAPI_MalformedInputJSON_RejectedAsInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
_, _ = w.Write([]byte(`{}`))
})
defer stop()
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{bad json`)}
err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "POST", "/api/v1/things", false)
if err == nil {
t.Fatal("expected an error for malformed --input JSON")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("want input.invalid_argument, got %v", err)
}
if called {
t.Error("server must not be called with a malformed body")
}
}
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
// TestAPI_InputFile verifies --input <file> reads the request body from disk.
func TestAPI_InputFile(t *testing.T) {
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
_, _ = iostreams.SetForTest(t)
tmp := filepath.Join(t.TempDir(), "body.json")
payload := `{"k":"from-file"}`
if err := os.WriteFile(tmp, []byte(payload), 0o600); err != nil {
t.Fatalf("write temp: %v", err)
}
var seenBody []byte
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{}`))
})
defer stop()
opts := &Options{Input: tmp}
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
t.Errorf("body from --input: got %q, want %q", seenBody, payload)
}
}
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
// TestAPI_InputDash_Stdin verifies the "--input -" form: the payload comes
// from opts.StdinReader (production-default iostreams.IO.In).
func TestAPI_InputDash_Stdin(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{}`))
})
defer stop()
payload := `{"k":"from-stdin"}`
opts := &Options{Input: "-", StdinReader: strings.NewReader(payload)}
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
t.Errorf("body from --input -: got %q, want %q", seenBody, payload)
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
}
}
func TestAPI_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":"missing"}`))
})
defer stop()
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/missing", false)
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 {
t.Fatal("expected error for 404")
}
if !cmdutil.IsNotFound(err) {
t.Errorf("expected resource.not_found, got %v", err)
}
}
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
func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
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
_, _ = iostreams.SetForTest(t)
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
var seenMethod string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
w.WriteHeader(http.StatusOK)
})
defer stop()
for _, m := range []string{"OPTIONS", "PATCH", "TRACE", "CUSTOM"} {
t.Run(m, func(t *testing.T) {
seenMethod = ""
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, m, "/api/v1/things", false)
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 != nil {
t.Fatalf("expected method %q to be accepted, got %v", m, err)
}
if seenMethod != m {
t.Errorf("server saw method %q, want %q", seenMethod, m)
}
})
}
}
func TestAPI_EmptyMethodRejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "", "/api/v1/things", false)
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 {
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
t.Fatal("expected error for empty method")
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
var fe *cmdutil.FlagError
if !errors.As(err, &fe) {
t.Errorf("expected FlagError, got %T %v", err, 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
}
}
func TestAPI_PathWithoutSlash(t *testing.T) {
_, _ = iostreams.SetForTest(t)
feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING) D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
2026-05-21 10:43:18 +00:00
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "GET", "api/v1/things", false)
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 {
t.Fatal("expected error for missing leading slash")
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("expected input.invalid_argument, got %v", err)
}
}
feat(cli): add agent-first affordance — envelope, exit-10, --dry-run Borrows the lark-cli agent-affordance model (https://github.com/larksuite/cli/blob/main/AGENTS.md + skills/lark-shared/SKILL.md) so weknora is designed to be agent-friendly: error messages, output format, and flag design follow conventions agents can rely on. cli/AGENTS.md (operational reference for LLM agents invoking weknora): Public document covering envelope schema, exit-code protocol (0/1/2/10/130), stdout/stderr separation, and behavioral rules. Sensitive commands (\`context use\`, \`kb delete\`, \`doc delete\`, \`init\`) gain "AI agents:" paragraphs in their cobra Long descriptions so guidance shows in --help. format.Envelope schema additions: Risk per-operation classification (read / write / high-risk-write + action description), populated by write commands on both success and failure paths. Notice system advisories (CLI update available, server-CLI version skew); type defined, emit sites land in v0.3. DryRun marker for envelopes returned from --dry-run preview paths. RiskLevel constants realigned to lark's taxonomy: read / write / high-risk-write (was: read / mutating / destructive — not yet wired by any command). cmdutil.Error gains OperationRisk; PrintErrorEnvelope auto-attaches it to envelope.Risk so destructive failure paths surface uniformly. Exit-10 confirmation protocol: New ErrorCode \`input.confirmation_required\` mapped to exit code 10 in cmdutil.ExitCode. ConfirmDestructive now returns this code (with OperationRisk attached) when stdout is non-TTY or --json was set, with -y/--yes absent. Previous behavior — silent proceed in non-TTY — was unsafe: scripts and agents could delete resources with no explicit approval. Three test cases re-pinned around the new contract. This is a wire-contract change for any caller who relied on silent proceed; v0.0/v0.1 had no destructive commands, so the blast radius is contained to v0.2 itself. --dry-run global flag: cmd write paths (kb create/delete, doc upload/delete, api POST/PUT/PATCH/ DELETE) check cmdutil.IsDryRun(cmd) and skip the SDK call, emitting an envelope with dry_run=true plus a Risk classification. Read commands ignore --dry-run by design (no side effect to preview). Human-mode prints \`[dry-run] would <action>\` to stdout. Command discovery: agents introspect via the existing \`--help\` surface (consistent with gh / kubectl / aws / gcloud / terraform — none of them ship a CLI-tree self-description command). An earlier draft added a \`weknora schema\` reflection command; dropped after a mainstream survey found it has no stable analog (lark-cli's schema describes Lark API methods, not its own CLI tree). Tests: 27 cli packages pass at this commit. Added two new tests covering envelope.risk and envelope._notice serialization.
2026-05-10 18:44:34 +00:00
// withRootHarness wraps `weknora api ...` under a synthetic root cmd that
feat(cli): --dry-run + risk metadata + validation parity on 19 mutations Two intertwined agent safety nets that share the same files: 1. --dry-run flag for offline preview of mutation commands 2. Risk: metadata + SetRisk helper for destructive command surfaces Coverage (19 mutation commands with --dry-run): kb.create/edit/delete agent.create/edit/delete doc.create/upload/fetch/delete doc.delete_all (special variant) session.delete chunk.delete profile.add/remove auth.refresh/logout link unlink api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2) Envelope additions (omitempty in non-dry-run paths): meta.dry_run: bool true when --dry-run was used meta.plan: map {action, args} per the per-command taxonomy Risk: metadata -------------- cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with risk.level=destructive + risk.action=<action> on the 9 destructive commands. The SetAgentHelp wrapper prepends a "Risk: <action> (destructive)" line in the default text help path so agents see a clear warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays unchanged — structured agent-help already carries warnings[]. Validation parity with the live path ------------------------------------ Every pure-local validation (flag presence, mutual exclusion, enum bounds, URL/regex format, ResolveKBLocal for KB resolution that does not require an SDK call) runs BEFORE the dry-run gate. This matches the industry-standard "preview shows what live would do" contract: --dry-run accepts exactly the same invocations the live path accepts and rejects exactly the same invocations the live path rejects, modulo the side-effecting work itself. The side-effecting work (SDK calls, file writes, keyring writes, server- side name → id resolution) is what --dry-run actually gates. Each mutation file pairs its RunE validation block with a regression test under *_dry_run_test.go / dryrun_validation_test.go so future refactors don't reintroduce the gap. Helper surface -------------- - HandleDryRun(cmd, dryRun, plan) extracts the early-return so the 19 RunE call sites stay 3 lines each. - EmitDryRun routes through FormatOptions.Emit, inheriting _notice / TTY indent / --jq filtering for free. - ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run paths use it so the plan reports the raw --kb value (UUID or name) without a name → id lookup. Streaming commands (chat, session ask, session continue-stream) are deliberately excluded: a buffered plan makes no sense for an event stream. Lock semantics in the dry-run path: - destructive + --dry-run: exit 0, no exit-10 confirmation prompt - --dry-run + -y: byte-identical envelope to --dry-run alone - --dry-run + --jq: filter applies to the preview envelope normally
2026-05-27 20:28:48 +00:00
// registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go). Required because api's NewCmd doesn't register --yes /
// --format / --jq itself — it inherits them from root in production.
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
func withRootHarness(api *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
feat(cli): --dry-run + risk metadata + validation parity on 19 mutations Two intertwined agent safety nets that share the same files: 1. --dry-run flag for offline preview of mutation commands 2. Risk: metadata + SetRisk helper for destructive command surfaces Coverage (19 mutation commands with --dry-run): kb.create/edit/delete agent.create/edit/delete doc.create/upload/fetch/delete doc.delete_all (special variant) session.delete chunk.delete profile.add/remove auth.refresh/logout link unlink api.{post,put,patch,delete} (api.get + --dry-run rejected, exit 2) Envelope additions (omitempty in non-dry-run paths): meta.dry_run: bool true when --dry-run was used meta.plan: map {action, args} per the per-command taxonomy Risk: metadata -------------- cmdutil.SetRisk(cmd, action) stamps cobra.Annotations with risk.level=destructive + risk.action=<action> on the 9 destructive commands. The SetAgentHelp wrapper prepends a "Risk: <action> (destructive)" line in the default text help path so agents see a clear warning before parsing Usage. WEKNORA_AGENT_HELP=1 JSON path stays unchanged — structured agent-help already carries warnings[]. Validation parity with the live path ------------------------------------ Every pure-local validation (flag presence, mutual exclusion, enum bounds, URL/regex format, ResolveKBLocal for KB resolution that does not require an SDK call) runs BEFORE the dry-run gate. This matches the industry-standard "preview shows what live would do" contract: --dry-run accepts exactly the same invocations the live path accepts and rejects exactly the same invocations the live path rejects, modulo the side-effecting work itself. The side-effecting work (SDK calls, file writes, keyring writes, server- side name → id resolution) is what --dry-run actually gates. Each mutation file pairs its RunE validation block with a regression test under *_dry_run_test.go / dryrun_validation_test.go so future refactors don't reintroduce the gap. Helper surface -------------- - HandleDryRun(cmd, dryRun, plan) extracts the early-return so the 19 RunE call sites stay 3 lines each. - EmitDryRun routes through FormatOptions.Emit, inheriting _notice / TTY indent / --jq filtering for free. - ResolveKBLocal mirrors ResolveKB but never calls the SDK; dry-run paths use it so the plan reports the raw --kb value (UUID or name) without a name → id lookup. Streaming commands (chat, session ask, session continue-stream) are deliberately excluded: a buffered plan makes no sense for an event stream. Lock semantics in the dry-run path: - destructive + --dry-run: exit 0, no exit-10 confirmation prompt - --dry-run + -y: byte-identical envelope to --dry-run alone - --dry-run + --jq: filter applies to the preview envelope normally
2026-05-27 20:28:48 +00:00
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
pf.StringP("jq", "q", "", "")
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
root.AddCommand(api)
root.SetArgs(append([]string{"api"}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
return root
}
// TestAPI_DELETE_RequiresConfirmation pins the exit-10 protocol on the
// escape-hatch DELETE path: agent invokes `weknora api DELETE /...` without
// -y/--yes, must get input.confirmation_required + exit 10. Confirmation is
// enforced in NewCmd.RunE (not runAPI), so the test drives the cobra cmd.
func TestAPI_DELETE_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
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
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", "DELETE")
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
err := root.Execute()
if err == nil {
t.Fatal("expected confirmation_required error for DELETE without -y")
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputConfirmationRequired {
t.Errorf("want input.confirmation_required, got %v", err)
}
if got := cmdutil.ExitCode(err); got != 10 {
t.Errorf("exit code = %d, want 10", got)
}
}
// TestAPI_DELETE_WithYes_Proceeds: -y/--yes opt-in skips confirmation and
// dispatches to the SDK. Server returns 200 to verify the happy-path lands
// on the response body emit.
func TestAPI_DELETE_WithYes_Proceeds(t *testing.T) {
iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
t.Errorf("expected DELETE, got %s", r.Method)
}
called = true
w.WriteHeader(http.StatusOK)
})
defer stop()
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return cli, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
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
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", "DELETE", "-y")
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
if err := root.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !called {
t.Error("DELETE handler not called - confirmation may have blocked")
feat(cli): add agent-first affordance — envelope, exit-10, --dry-run Borrows the lark-cli agent-affordance model (https://github.com/larksuite/cli/blob/main/AGENTS.md + skills/lark-shared/SKILL.md) so weknora is designed to be agent-friendly: error messages, output format, and flag design follow conventions agents can rely on. cli/AGENTS.md (operational reference for LLM agents invoking weknora): Public document covering envelope schema, exit-code protocol (0/1/2/10/130), stdout/stderr separation, and behavioral rules. Sensitive commands (\`context use\`, \`kb delete\`, \`doc delete\`, \`init\`) gain "AI agents:" paragraphs in their cobra Long descriptions so guidance shows in --help. format.Envelope schema additions: Risk per-operation classification (read / write / high-risk-write + action description), populated by write commands on both success and failure paths. Notice system advisories (CLI update available, server-CLI version skew); type defined, emit sites land in v0.3. DryRun marker for envelopes returned from --dry-run preview paths. RiskLevel constants realigned to lark's taxonomy: read / write / high-risk-write (was: read / mutating / destructive — not yet wired by any command). cmdutil.Error gains OperationRisk; PrintErrorEnvelope auto-attaches it to envelope.Risk so destructive failure paths surface uniformly. Exit-10 confirmation protocol: New ErrorCode \`input.confirmation_required\` mapped to exit code 10 in cmdutil.ExitCode. ConfirmDestructive now returns this code (with OperationRisk attached) when stdout is non-TTY or --json was set, with -y/--yes absent. Previous behavior — silent proceed in non-TTY — was unsafe: scripts and agents could delete resources with no explicit approval. Three test cases re-pinned around the new contract. This is a wire-contract change for any caller who relied on silent proceed; v0.0/v0.1 had no destructive commands, so the blast radius is contained to v0.2 itself. --dry-run global flag: cmd write paths (kb create/delete, doc upload/delete, api POST/PUT/PATCH/ DELETE) check cmdutil.IsDryRun(cmd) and skip the SDK call, emitting an envelope with dry_run=true plus a Risk classification. Read commands ignore --dry-run by design (no side effect to preview). Human-mode prints \`[dry-run] would <action>\` to stdout. Command discovery: agents introspect via the existing \`--help\` surface (consistent with gh / kubectl / aws / gcloud / terraform — none of them ship a CLI-tree self-description command). An earlier draft added a \`weknora schema\` reflection command; dropped after a mainstream survey found it has no stable analog (lark-cli's schema describes Lark API methods, not its own CLI tree). Tests: 27 cli packages pass at this commit. Added two new tests covering envelope.risk and envelope._notice serialization.
2026-05-10 18:44:34 +00:00
}
}
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
// asTypedError is a tiny wrapper around errors.As that keeps the call sites
// concise. Returns true on success, populating dst.
func asTypedError(err error, dst **cmdutil.Error) bool {
for e := err; e != nil; {
if t, ok := e.(*cmdutil.Error); ok {
*dst = t
return true
}
type unwrapper interface{ Unwrap() error }
u, ok := e.(unwrapper)
if !ok {
return false
}
e = u.Unwrap()
}
return false
}
func TestAPI_PaginateMergesPages(t *testing.T) {
pages := [][]byte{
[]byte(`{"success":true,"data":[{"id":"1"},{"id":"2"}],"total":5,"page":1,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"3"},{"id":"4"}],"total":5,"page":2,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"5"}],"total":5,"page":3,"page_size":2}`),
}
idx := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
if idx >= len(pages) {
return nil, fmt.Errorf("too many calls; idx=%d", idx)
}
body := pages[idx]
idx++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(body)),
Header: make(http.Header),
}, nil
}}
out, _ := iostreams.SetForTest(t)
opts := &Options{}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/knowledge-base?page=1&page_size=2", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
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
var env struct {
OK bool `json:"ok"`
Data struct {
Data []map[string]string `json:"data"`
Total int `json:"total"`
} `json:"data"`
}
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 := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, out.String())
}
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
got := env.Data
if len(got.Data) != 5 || got.Total != 5 {
t.Errorf("got %d records (total %d), want 5/5", len(got.Data), got.Total)
}
if idx != 3 {
t.Errorf("called %d times, want 3", idx)
}
}
func TestAPI_PaginateIgnoredForPOST(t *testing.T) {
// --paginate should be a no-op for non-GET methods (no pagination
// semantic for POST/PUT/DELETE). Single call expected.
called := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
called++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte(`{"success":true,"data":[],"total":5,"page":1,"page_size":2}`))),
Header: make(http.Header),
}, nil
}}
_, _ = iostreams.SetForTest(t)
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
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "POST", "/api/v1/knowledge-base", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
if called != 1 {
t.Errorf("called %d times, want 1 (POST should not paginate)", called)
}
}
func TestAPI_PaginateNoMetadataPassesThrough(t *testing.T) {
// If response doesn't look paginated (no total/page/page_size), --paginate
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
// should fall back to single-call envelope behavior (same shape as api without --paginate).
called := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
called++
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
hdr := make(http.Header)
hdr.Set("Content-Type", "application/json")
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte(`{"hello":"world"}`))),
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
Header: hdr,
}, 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
out, _ := iostreams.SetForTest(t)
opts := &Options{}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/whoami", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
if called != 1 {
t.Errorf("called %d times, want 1 (non-paginated response)", called)
}
// The non-paginated fallback must emit the SAME flat shape as a single
// call: the server response directly under .data (no {status,headers,body}
// wrapper), so --paginate and single-call project identically.
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
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
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 := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("non-paginated fallback must emit envelope JSON, unmarshal failed: %v\n%s", err, out.String())
}
if !env.OK {
t.Errorf("envelope ok: want true, got false")
}
if v, ok := env.Data["hello"]; !ok || v.(string) != "world" {
t.Errorf("fallback must pass the body through flat under .data (.data.hello), got %v", env.Data)
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
}
}
// TestAPI_PaginateServerCapsPageSize covers the case where the user
// requests --page_size=50 but the server caps page_size at a smaller
// value (e.g. 2). Termination must count actually-collected records
// (len(allData)) not requested-page-count (page*pageSize) — otherwise
// we'd break early and silently truncate results.
func TestAPI_PaginateServerCapsPageSize(t *testing.T) {
// User asks page_size=10; server only ever returns 2 per page (cap).
// Total = 5 records; should make 3 calls (2+2+1) and return all 5.
pages := [][]byte{
[]byte(`{"success":true,"data":[{"id":"1"},{"id":"2"}],"total":5,"page":1,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"3"},{"id":"4"}],"total":5,"page":2,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"5"}],"total":5,"page":3,"page_size":2}`),
}
idx := 0
svc := &fakeAPISvc{do: func(_, _ string, _ any) (*http.Response, error) {
if idx >= len(pages) {
return nil, fmt.Errorf("too many calls; idx=%d", idx)
}
body := pages[idx]
idx++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(body)),
Header: make(http.Header),
}, nil
}}
var stdout bytes.Buffer
iostreams.IO.Out = &stdout
defer func() { iostreams.IO.Out = os.Stdout }()
opts := &Options{}
// User requests page_size=10; server caps at 2 each response.
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/items?page=1&page_size=10", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
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
var env struct {
OK bool `json:"ok"`
Data struct {
Data []map[string]string `json:"data"`
Total int `json:"total"`
} `json:"data"`
}
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 := json.Unmarshal(stdout.Bytes(), &env); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, stdout.String())
}
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
got := env.Data
if len(got.Data) != 5 {
t.Errorf("got %d records, want 5 (server-capped page_size should not cause truncation)", len(got.Data))
}
}
feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening A hardening + finalization pass over the agent-first CLI: correctness fixes, richer machine-readable signals, flag/naming consistency, and a symmetric config surface. Pre-1.0, so it includes breaking renames. Correctness: - agent update: resolve/validate --model/--rerank-model (was storing a bogus name verbatim, corrupting config.model_id). - doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports "no host configured"). - session ask / MCP session_ask: text answer was empty on non-TTY — the agent stream sets Done=true on an intermediate agent_query frame before the answer, and AgentAccumulator treated the first Done as terminal. Terminate on the `complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done. - batch exit codes: any per-item failure collapses to operation.failed (exit 1), including `doc upload --recursive` partial failures — a permanent per-file failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent would loop on; per-item typed errors stay in the envelope. Agent-first signals & discovery: - error.exit_code in the envelope (type + exit_code disambiguate the input.invalid_argument exit-2-vs-5 split in one JSON read). - meta.hint on empty content search and on draft doc create; doc wait fails fast on a never-parsing draft instead of hanging to --timeout. - retrieval-readiness is visible in the natural flow: kb status / kb check emit retrieval_ready, and kb create hints the fix when no embedding model is bound — an unconfigured KB no longer looks silently healthy. - schema contract completeness: every leaf declares output + >=1 example (drift-guarded); output strings match the meta actually emitted; chunk list and search docs now emit meta.total_count (both previously dropped it). - schema tolerates a quoted multi-word command label; zero-state auth — and `link` with no profile — point at profile setup / the headless WEKNORA_KB_ID path instead of looping on `auth login`. - id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view accept and ignore it, declared in schema) so a carried-over --kb doesn't exit 2; streaming commands warn that --jq does not apply to an NDJSON stream. - keep JSON-always as the default; --jq hints spell out the .data path. Consistency & gating: - doc create: drop the deprecated --name alias (--title only; pre-1.0 break). - chunk list --limit aligned to 1..10000; model list --limit/-L with has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install expands a leading ~. - docs corrected: search docs / doc list --keyword help is case-insensitive (server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add model.update / kb.config.set) and batch example (failed item carries `error`); session resume --message id comes from `message list`, not the stream. - auth/profile ergonomics: env credentials are now first-class — `auth token` prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh give an env-aware message instead of looping on "run auth login". `auth logout` clears credentials but keeps the profile registered (host preserved for re-login); deleting a profile is `profile remove`'s job (clean logout/remove separation, matching gh / lark). Config surface (symmetric read/write, in-place model edits): - kb config now returns a secret-free KBModelConfigView (was {}); `kb config` reads, new `kb config set` writes; `kb init` removed (misnomer). - kb create --chat-model: retrieval-ready in one step. - model update: edit a model in place (id preserved, references survive) — rotate --api-key-stdin, change base-url / display-name / etc. - session continue-stream renamed to session resume. Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale kb-init / continue-stream references removed; skill wire-vocab guard extended. AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an embedding model to be searchable), that --jq does not apply to NDJSON streams, and the env-credential-first auth path; the KB quickstart example now creates a retrieval-ready KB.
2026-07-02 07:53:51 +00:00
// TestAPI_PUT_RequiresConfirmation pins the exit-10 write gate on the
// escape-hatch PUT path: `weknora api -X PUT /...` mutates server state the
// same way a typed `kb update` does, so it must require -y (exit 10) rather
// than silently writing. Regression: only DELETE was gated, letting an agent
// bypass the write-confirmation protocol via raw PUT/PATCH.
func TestAPI_PUT_RequiresConfirmation(t *testing.T) {
for _, method := range []string{"PUT", "PATCH"} {
t.Run(method, func(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", method, "-F", "name=x")
err := root.Execute()
if err == nil {
t.Fatalf("expected confirmation_required for %s without -y", method)
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputConfirmationRequired {
t.Errorf("want input.confirmation_required, got %v", err)
}
if got := cmdutil.ExitCode(err); got != 10 {
t.Errorf("exit code = %d, want 10", got)
}
})
}
}
// TestAPI_POST_NotGated: POST is create-shaped and, like typed `kb create`,
// intentionally ungated — it must reach the SDK without a confirmation gate.
func TestAPI_POST_NotGated(t *testing.T) {
iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
})
defer stop()
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return cli, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases", "-X", "POST", "-F", "name=x")
if err := root.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !called {
t.Error("POST handler not called - POST must not be gated")
}
}