WeKnora/cli/internal/cmdutil/format_test.go

239 lines
7.0 KiB
Go
Raw Normal View History

feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
package cmdutil
import (
"bytes"
"encoding/json"
"errors"
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
"strings"
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
"testing"
"github.com/spf13/cobra"
)
func TestCheckFormatFlags(t *testing.T) {
cases := []struct {
name string
args []string
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
wantMode FormatMode // FormatText | FormatJSON | FormatNDJSON | "" (unset)
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
wantErr bool
}{
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
// Unset → Mode is "" (caller resolves default via ResolveDefault).
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
{"default", []string{}, "", false},
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
{"explicit text", []string{"--format", "text"}, FormatText, 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
{"json", []string{"--format", "json"}, FormatJSON, false},
{"ndjson", []string{"--format", "ndjson"}, FormatNDJSON, false},
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
{"invalid value", []string{"--format", "yaml"}, "", true},
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
{"human rejected", []string{"--format", "human"}, "", true},
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := &cobra.Command{}
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup Sweep every CLI output path through the v0.7 envelope contract. FormatOptions.Emit signature changes to (w, data, meta *output.Meta) so list commands surface meta.count / has_more in the wire envelope. TTY indent decision plumbed via FormatOptions.TTY (set by ResolveDefault). --format and --jq promoted to persistent root flags so unknown-subcommand paths still reach the typed-envelope guard (per-command registration would have rejected --format on unknown commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback honored before TTY-resolved default. AddFormatFlag retained for the per-command --jq field-hint Long-text addendum. ~55 production Emit call sites swept across cli/cmd/**: list paths populate meta.count; mutation paths pass nil meta; envelope.profile threaded via globalProfile. Existing JSON-shape tests migrated to decode the envelope wrapper. Multi-target batch operations get a unified shape via new helpers: - output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok pattern; data:[{id, ok, result?|error?}], meta:{count, successes*, failures*}; Successes/Failures *int so explicit zero survives omitempty in all-fail case). - cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow + cmdutil.ClassifyContextErr collapse the three previously-duplicated multi-delete pipelines (doc / chunk / session) into one call site pattern. doc upload --recursive uses the same helpers with a per- file resultFn. Summary error sets Silent:true so the stderr envelope path doesn't duplicate the stdout batch detail (exit 1 preserved via Code → ExitCode). ConfirmDestructive / ConfirmDestructiveBatch extended with action + retryCmd parameters. Every destructive command (kb delete, kb edit, doc delete, doc delete --all, agent delete, agent edit, session delete, chunk delete, auth logout, api -X DELETE) now attaches error.risk.{level:"destructive", action:"<noun.verb>"} + error.retry_command on the exit-10 envelope. kb edit / agent edit also gain the destructive guard wiring (CHANGELOG listed them as gated but they were silently executing without -y). MCP tool handlers' 31 error paths return CallToolResult with IsError + Content text fallback + StructuredContent (envelope.error shape via cmdutil.ErrorToDetail). Handler Out type changed from typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite StructuredContent with a zero-struct on error returns. Success path manually populates CallToolResult.StructuredContent via successResult helper. weknora api cleanup: - -d/--data flag removed; body via --input <file> or --input - (stdin) only. Aligns with gh / curl convention. - HTTP method whitelist removed; any non-empty method accepted. - HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds → envelope.error.retry_after_seconds. - runAPIPaginated raw-passthrough fallback now wraps response in envelope so --paginate never emits bare JSON to stdout. Test sweep: ~60 cmd/** tests migrated to decode envelope shape. 9 wire-contract goldens updated under cli/acceptance/testdata/wire/. Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
// --format / --jq are persistent root flags in production; register
// them on this bare cmd so the test can exercise CheckFormatFlag in
// isolation.
cmd.PersistentFlags().String("format", "", "")
cmd.PersistentFlags().String("jq", "", "")
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
cmd.SetArgs(tc.args)
cmd.RunE = func(c *cobra.Command, _ []string) error {
opts, err := CheckFormatFlag(c)
if (err != nil) != tc.wantErr {
t.Fatalf("err=%v wantErr=%v", err, tc.wantErr)
}
if err == nil && opts.Mode != tc.wantMode {
t.Errorf("mode=%q want %q", opts.Mode, tc.wantMode)
}
return nil
}
_ = cmd.Execute()
})
}
}
func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
var buf bytes.Buffer
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
fopts := &FormatOptions{Mode: FormatNDJSON}
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
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 := fopts.Emit(&buf, arr, nil); err != nil {
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
t.Fatalf("Emit: %v", err)
}
want := `{"id":"a"}` + "\n" + `{"id":"b"}` + "\n"
if buf.String() != want {
t.Errorf("got %q want %q", buf.String(), want)
}
}
func TestFormatOptions_JSONEmitsArray(t *testing.T) {
var buf bytes.Buffer
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
fopts := &FormatOptions{Mode: FormatJSON}
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
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 := fopts.Emit(&buf, arr, nil); err != nil {
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
t.Fatalf("Emit: %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
// v0.7: JSON path wraps in success envelope {ok:true, data:[...]}.
// Unmarshal the envelope and check data array length.
var env struct {
OK bool `json:"ok"`
Data []map[string]string `json:"data"`
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +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(buf.Bytes(), &env); err != nil {
t.Fatalf("not valid envelope JSON: %v\n%s", err, buf.String())
}
if !env.OK {
t.Errorf("expected ok:true in envelope")
}
if len(env.Data) != 2 {
t.Errorf("got %d items, want 2", len(env.Data))
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
}
}
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
func TestFormatOptions_TextModeReturnsError(t *testing.T) {
fopts := &FormatOptions{Mode: FormatText}
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
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"}, nil)
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
if err == nil {
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
t.Error("expected error for text mode, got 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
}
}
// TestResolveDefault_AlwaysJSON verifies v0.7 semantics: default is FormatJSON
// regardless of whether stdout is a TTY (BREAKING change from v0.6).
func TestResolveDefault_AlwaysJSON(t *testing.T) {
for _, isTTY := range []bool{true, false} {
o := &FormatOptions{}
o.ResolveDefault(isTTY)
if o.Mode != FormatJSON {
t.Errorf("isTTY=%v: expected default FormatJSON, got %v", isTTY, o.Mode)
}
if o.TTY != isTTY {
t.Errorf("isTTY=%v: TTY field not propagated", isTTY)
}
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
}
}
func TestResolveDefault(t *testing.T) {
cases := []struct {
name 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
mode FormatMode // pre-set Mode
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
jq string
isTTY bool
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
wantMode FormatMode
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +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
// v0.7: empty Mode always resolves to FormatJSON regardless of TTY.
{"empty isTTY", "", "", true, FormatJSON},
{"empty no-tty", "", "", false, FormatJSON},
{"already set keeps value tty", FormatNDJSON, "", true, FormatNDJSON},
{"already set keeps value no-tty", FormatJSON, "", false, FormatJSON},
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
// --jq with unset --format promotes to JSON regardless of TTY so the
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
// filter has somewhere to apply (silent text drop would surprise users).
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
{"jq forces json on TTY", "", ".[]", true, FormatJSON},
{"jq with explicit ndjson preserved", FormatNDJSON, ".[]", true, FormatNDJSON},
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
o := &FormatOptions{Mode: tc.mode, JQ: tc.jq}
o.ResolveDefault(tc.isTTY)
if o.Mode != tc.wantMode {
t.Errorf("mode=%q want %q", o.Mode, tc.wantMode)
}
})
}
}
// TestCheckFormatFlag_InvalidExitTwo guards the contract that flag-value
// validation maps to exit 2 (FlagError class), not the unclassified bucket.
func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
cases := []struct {
name string
args []string
}{
{"invalid format value", []string{"--format", "yaml"}},
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
{"human rejected as invalid", []string{"--format", "human"}},
{"jq with explicit text mode", []string{"--format", "text", "--jq", ".id"}},
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := &cobra.Command{}
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup Sweep every CLI output path through the v0.7 envelope contract. FormatOptions.Emit signature changes to (w, data, meta *output.Meta) so list commands surface meta.count / has_more in the wire envelope. TTY indent decision plumbed via FormatOptions.TTY (set by ResolveDefault). --format and --jq promoted to persistent root flags so unknown-subcommand paths still reach the typed-envelope guard (per-command registration would have rejected --format on unknown commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback honored before TTY-resolved default. AddFormatFlag retained for the per-command --jq field-hint Long-text addendum. ~55 production Emit call sites swept across cli/cmd/**: list paths populate meta.count; mutation paths pass nil meta; envelope.profile threaded via globalProfile. Existing JSON-shape tests migrated to decode the envelope wrapper. Multi-target batch operations get a unified shape via new helpers: - output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok pattern; data:[{id, ok, result?|error?}], meta:{count, successes*, failures*}; Successes/Failures *int so explicit zero survives omitempty in all-fail case). - cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow + cmdutil.ClassifyContextErr collapse the three previously-duplicated multi-delete pipelines (doc / chunk / session) into one call site pattern. doc upload --recursive uses the same helpers with a per- file resultFn. Summary error sets Silent:true so the stderr envelope path doesn't duplicate the stdout batch detail (exit 1 preserved via Code → ExitCode). ConfirmDestructive / ConfirmDestructiveBatch extended with action + retryCmd parameters. Every destructive command (kb delete, kb edit, doc delete, doc delete --all, agent delete, agent edit, session delete, chunk delete, auth logout, api -X DELETE) now attaches error.risk.{level:"destructive", action:"<noun.verb>"} + error.retry_command on the exit-10 envelope. kb edit / agent edit also gain the destructive guard wiring (CHANGELOG listed them as gated but they were silently executing without -y). MCP tool handlers' 31 error paths return CallToolResult with IsError + Content text fallback + StructuredContent (envelope.error shape via cmdutil.ErrorToDetail). Handler Out type changed from typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite StructuredContent with a zero-struct on error returns. Success path manually populates CallToolResult.StructuredContent via successResult helper. weknora api cleanup: - -d/--data flag removed; body via --input <file> or --input - (stdin) only. Aligns with gh / curl convention. - HTTP method whitelist removed; any non-empty method accepted. - HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds → envelope.error.retry_after_seconds. - runAPIPaginated raw-passthrough fallback now wraps response in envelope so --paginate never emits bare JSON to stdout. Test sweep: ~60 cmd/** tests migrated to decode envelope shape. 9 wire-contract goldens updated under cli/acceptance/testdata/wire/. Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
// --format / --jq are persistent root flags in production; register
// them on this bare cmd so the test can exercise CheckFormatFlag in
// isolation.
cmd.PersistentFlags().String("format", "", "")
cmd.PersistentFlags().String("jq", "", "")
feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider Adds the structured-output and agent-help surface plus root-level signal handling so AI agents (and humans working through pipes) get a stable wire contract. * --format text|json|ndjson flag, registered per-command on outputs that need it; default text on TTY, json on pipe. --jq <expr> pairs with json / ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON() helper for the JSON dispatch. * WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value per line, arrays split element-per-line, empty slice → zero bytes). * chat / agent invoke wire --format ndjson via SDK StreamResponse / AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled in every stream + session-create path and emit a stable "operation.cancelled" code on Ctrl-C / SIGTERM. * main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root context so long-running commands run their cancellation cleanup (re-emit auto-created session id, etc); the process exits 130 when the context was signal-cancelled, matching Unix convention. * MCP chat / agent_invoke output schemas extended with thinking / tool_calls / assistant_message_id (server-side accumulated; MCP tools/call has no standard partial-response). doc_view and doc_download now use doc_id (not knowledge_id) so agents see a single id naming convention across all tools — matches the chunk_list / search_chunks schemas and the CLI's <doc-id> positional. * SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list. * kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets the new KB's storage_provider_config.provider at creation time (server does not expose it on update). Required on self-hosted deployments where the server-side default doesn't pre-populate a provider — without it, subsequent doc upload returns a misleading "kb not found".
2026-05-17 17:37:47 +00:00
cmd.SetArgs(tc.args)
var got error
cmd.RunE = func(c *cobra.Command, _ []string) error {
_, err := CheckFormatFlag(c)
got = err
return err
}
_ = cmd.Execute()
if got == nil {
t.Fatal("expected error, got nil")
}
var fe *FlagError
if !errors.As(got, &fe) {
t.Fatalf("error %v is not a *FlagError; would map to exit 1 instead of 2", got)
}
if ExitCode(got) != 2 {
t.Errorf("ExitCode=%d, want 2", ExitCode(got))
}
})
}
}
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 TestCheckFormatFlag_InvalidValueRejected(t *testing.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
for _, v := range []string{"human", "yaml", "xml", "table"} {
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
v := v
t.Run(v, func(t *testing.T) {
cmd := &cobra.Command{}
cmd.Flags().String("format", "", "")
_ = cmd.Flags().Set("format", v)
_, err := CheckFormatFlag(cmd)
if err == nil {
t.Fatalf("expected error for --format %q", v)
}
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 !strings.Contains(err.Error(), "text | json | ndjson") {
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.Errorf("expected enum hint for --format %q; got %v", v, err)
}
})
}
}
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
func TestCheckFormatFlag_TextAccepted(t *testing.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
cmd := &cobra.Command{}
cmd.Flags().String("format", "", "")
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
_ = cmd.Flags().Set("format", "text")
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
o, err := CheckFormatFlag(cmd)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
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 o.Mode != FormatText {
t.Errorf("got %v, want FormatText", o.Mode)
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 TestFromEnv_AppliesWEKNORA_FORMAT(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "ndjson")
o := &FormatOptions{}
o.FromEnv()
if o.Mode != FormatNDJSON {
t.Errorf("expected FormatNDJSON from env; got %v", o.Mode)
}
}
func TestFromEnv_PrecedenceFlagOverridesEnv(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "ndjson")
o := &FormatOptions{Mode: FormatJSON}
o.FromEnv()
if o.Mode != FormatJSON {
t.Errorf("flag should win over env; got %v", o.Mode)
}
}
func TestFromEnv_InvalidValueIgnored(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", "yaml")
o := &FormatOptions{}
o.FromEnv()
if o.Mode != "" {
t.Errorf("invalid env should be ignored; got %v", o.Mode)
}
}