2ce348d020
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
124 lines
3.9 KiB
Go
124 lines
3.9 KiB
Go
package cmdutil
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestExitCode(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
err error
|
|
want int
|
|
}{
|
|
{"nil success", nil, 0},
|
|
{"flag error", NewFlagError(errors.New("bad flag")), 2},
|
|
{"silent", SilentError, 1},
|
|
{"auth.* prefix", NewError(CodeAuthUnauthenticated, "x"), 3},
|
|
{"auth.token_expired", NewError(CodeAuthTokenExpired, "x"), 3},
|
|
{"resource.not_found", NewError(CodeResourceNotFound, "x"), 4},
|
|
{"input.* prefix", NewError(CodeInputInvalidArgument, "x"), 5},
|
|
{"input.missing_flag", NewError(CodeInputMissingFlag, "x"), 5},
|
|
{"server.rate_limited", NewError(CodeServerRateLimited, "x"), 6},
|
|
{"server.* prefix", NewError(CodeServerError, "x"), 7},
|
|
{"server.timeout", NewError(CodeServerTimeout, "x"), 7},
|
|
{"network.* prefix", NewError(CodeNetworkError, "x"), 7},
|
|
{"unknown error", errors.New("plain"), 1},
|
|
{"local.* prefix", NewError(CodeLocalConfigCorrupt, "x"), 1},
|
|
{"operation.timeout", NewError(CodeOperationTimeout, "timed out"), 124},
|
|
{"operation.failed → 1 (fall-through bucket)", NewError(CodeOperationFailed, "failed"), 1},
|
|
{"operation.cancelled → 1 (main overrides to 130 on signal-cancelled ctx)", NewError(CodeOperationCancelled, "cancelled"), 1},
|
|
{"server.session_create_failed → 1 (workflow, not transient)", NewError(CodeSessionCreateFailed, "x"), 1},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
assert.Equal(t, tc.want, ExitCode(tc.err))
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestPrintError(t *testing.T) {
|
|
t.Run("nil is silent", func(t *testing.T) {
|
|
var buf bytes.Buffer
|
|
PrintError(&buf, nil)
|
|
assert.Empty(t, buf.String())
|
|
})
|
|
t.Run("SilentError is silent", func(t *testing.T) {
|
|
var buf bytes.Buffer
|
|
PrintError(&buf, SilentError)
|
|
assert.Empty(t, buf.String())
|
|
})
|
|
t.Run("typed error prints message", func(t *testing.T) {
|
|
var buf bytes.Buffer
|
|
PrintError(&buf, NewError(CodeAuthUnauthenticated, "no creds"))
|
|
assert.Contains(t, buf.String(), "auth.unauthenticated")
|
|
assert.Contains(t, buf.String(), "no creds")
|
|
})
|
|
}
|
|
|
|
func TestPrintError_JSONMode_WritesEnvelope(t *testing.T) {
|
|
t.Cleanup(func() { SetFormatMode("") })
|
|
SetFormatMode("json")
|
|
|
|
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
|
|
WithHint("re-run with -y/--yes").
|
|
WithRetryCommand("weknora kb delete kb_x -y")
|
|
|
|
var buf bytes.Buffer
|
|
PrintError(&buf, err)
|
|
|
|
got := buf.String()
|
|
if !strings.Contains(got, `"ok":false`) {
|
|
t.Errorf("expected envelope ok:false; got %q", got)
|
|
}
|
|
if !strings.Contains(got, `"type":"input.confirmation_required"`) {
|
|
t.Errorf("expected typed code; got %q", got)
|
|
}
|
|
if !strings.Contains(got, `"retry_command":"weknora kb delete kb_x -y"`) {
|
|
t.Errorf("expected retry_command; got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestPrintError_JSONMode_IncludesRetryAfter(t *testing.T) {
|
|
t.Cleanup(func() { SetFormatMode("") })
|
|
SetFormatMode("json")
|
|
|
|
err := NewError(CodeServerRateLimited, "rate limited").
|
|
WithRetryAfter(30)
|
|
|
|
var buf bytes.Buffer
|
|
PrintError(&buf, err)
|
|
|
|
got := buf.String()
|
|
if !strings.Contains(got, `"retry_after_seconds":30`) {
|
|
t.Errorf("expected retry_after_seconds:30; got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestPrintError_TextMode_WritesProse(t *testing.T) {
|
|
t.Cleanup(func() { SetFormatMode("") })
|
|
SetFormatMode("text")
|
|
|
|
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
|
|
WithHint("re-run with -y/--yes").
|
|
WithRetryCommand("weknora kb delete kb_x -y")
|
|
|
|
var buf bytes.Buffer
|
|
PrintError(&buf, err)
|
|
|
|
got := buf.String()
|
|
if !strings.Contains(got, "input.confirmation_required: kb delete kb_x requires confirmation") {
|
|
t.Errorf("expected prose code:message line; got %q", got)
|
|
}
|
|
if !strings.Contains(got, "hint: re-run with -y/--yes") {
|
|
t.Errorf("expected hint line; got %q", got)
|
|
}
|
|
if !strings.Contains(got, "retry: weknora kb delete kb_x -y") {
|
|
t.Errorf("expected retry line; got %q", got)
|
|
}
|
|
}
|