WeKnora/cli/cmd/doc/wait_test.go

341 lines
11 KiB
Go
Raw Normal View History

package doc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"testing"
"time"
sdk "github.com/Tencent/WeKnora/client"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
func TestWaitCmd_Shape(t *testing.T) {
cmd := NewCmdWait(&cmdutil.Factory{})
if !strings.Contains(cmd.Use, "<doc-id>") {
t.Errorf("Use=%q missing <doc-id>", cmd.Use)
}
if f := cmd.Flags().Lookup("timeout"); f == nil {
t.Error("missing --timeout flag")
}
if f := cmd.Flags().Lookup("interval"); f == nil {
t.Error("missing --interval flag")
}
// wait is always wait-all: no fail-fast option. --keep-going is
// intentionally absent; users who want fail-fast compose with shell
// short-circuiting (`wait id1 && wait id2`).
if f := cmd.Flags().Lookup("keep-going"); f != nil {
t.Error("--keep-going should not be registered; wait is always wait-all")
}
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 is a persistent root flag (v0.7), not per-command — skip its lookup here.
}
func TestWaitCmd_DefaultFlagValues(t *testing.T) {
cmd := NewCmdWait(&cmdutil.Factory{})
if err := cmd.ParseFlags(nil); err != nil {
t.Fatalf("ParseFlags: %v", err)
}
tf, _ := cmd.Flags().GetDuration("timeout")
if tf != 10*time.Minute {
t.Errorf("--timeout default = %v, want 10m", tf)
}
in, _ := cmd.Flags().GetDuration("interval")
if in != 2*time.Second {
t.Errorf("--interval default = %v, want 2s", in)
}
}
// ---------------------------------------------------------------------------
// B2: waitForDocs tests
// ---------------------------------------------------------------------------
type fakeKnowledgeSvc struct {
mu sync.Mutex
calls map[string]int // id → call count
sequence map[string][]string // id → parse_status sequence to return
}
func newFakeKBSvc(seq map[string][]string) *fakeKnowledgeSvc {
return &fakeKnowledgeSvc{
calls: make(map[string]int),
sequence: seq,
}
}
func (f *fakeKnowledgeSvc) GetKnowledge(_ context.Context, id string) (*sdk.Knowledge, error) {
f.mu.Lock()
defer f.mu.Unlock()
idx := f.calls[id]
f.calls[id]++
seq, ok := f.sequence[id]
if !ok {
return nil, fmt.Errorf("unexpected id %q", id)
}
if idx >= len(seq) {
idx = len(seq) - 1
}
status := seq[idx]
k := &sdk.Knowledge{ID: id, ParseStatus: status}
if status == "failed" {
k.ErrorMessage = "parse error"
}
return k, nil
}
func TestWaitForDocs_SingleIDCompletes(t *testing.T) {
svc := newFakeKBSvc(map[string][]string{
"doc_x": {"processing", "processing", "completed"},
})
res, err := waitForDocs(context.Background(), []string{"doc_x"}, svc, WaitOptions{
Timeout: 5 * time.Second,
Interval: 1 * time.Millisecond, // fast for tests
})
if err != nil {
t.Fatalf("waitForDocs: %v", err)
}
if len(res.Completed) != 1 || res.Completed[0] != "doc_x" {
t.Errorf("Completed=%v, want [doc_x]", res.Completed)
}
if svc.calls["doc_x"] < 3 {
t.Errorf("expected at least 3 polls, got %d", svc.calls["doc_x"])
}
}
func TestWaitForDocs_SingleIDFails(t *testing.T) {
svc := newFakeKBSvc(map[string][]string{
"doc_x": {"failed"},
})
res, _ := waitForDocs(context.Background(), []string{"doc_x"}, svc, WaitOptions{
Timeout: 5 * time.Second,
Interval: 1 * time.Millisecond,
})
if len(res.Failed) != 1 || res.Failed[0].ID != "doc_x" {
t.Errorf("Failed=%v, want [doc_x]", res.Failed)
}
if res.Failed[0].Message != "parse error" {
t.Errorf("Failed[0].Message=%q, want %q", res.Failed[0].Message, "parse error")
}
}
func TestWaitForDocs_Timeout(t *testing.T) {
svc := newFakeKBSvc(map[string][]string{
"doc_x": {"processing"}, // never completes
})
res, _ := waitForDocs(context.Background(), []string{"doc_x"}, svc, WaitOptions{
Timeout: 20 * time.Millisecond, // tight
Interval: 5 * time.Millisecond,
})
if len(res.Timeout) != 1 || res.Timeout[0] != "doc_x" {
t.Errorf("Timeout=%v, want [doc_x]", res.Timeout)
}
}
// ---------------------------------------------------------------------------
// B3: multi-id wait-all behavior
// ---------------------------------------------------------------------------
func TestWaitForDocs_MultiID_AllSucceed(t *testing.T) {
svc := newFakeKBSvc(map[string][]string{
"a": {"processing", "completed"},
"b": {"completed"},
"c": {"processing", "processing", "completed"},
})
res, err := waitForDocs(context.Background(), []string{"a", "b", "c"}, svc, WaitOptions{
Timeout: 5 * time.Second,
Interval: 1 * time.Millisecond,
})
if err != nil {
t.Fatalf("waitForDocs: %v", err)
}
if len(res.Completed) != 3 {
t.Errorf("Completed=%v (len %d), want 3", res.Completed, len(res.Completed))
}
if len(res.Failed) != 0 || len(res.Timeout) != 0 {
t.Errorf("Failed=%v Timeout=%v, want both empty", res.Failed, res.Timeout)
}
}
// TestWaitForDocs_MultiID_WaitAllOnPartialFailure verifies wait-all
// semantics: even when one id fails terminally, the remaining ids are
// still waited on until they reach their own terminal state.
func TestWaitForDocs_MultiID_WaitAllOnPartialFailure(t *testing.T) {
svc := newFakeKBSvc(map[string][]string{
"a": {"failed"},
"b": {"processing", "completed"},
"c": {"completed"},
})
res, _ := waitForDocs(context.Background(), []string{"a", "b", "c"}, svc, WaitOptions{
Timeout: 5 * time.Second,
Interval: 1 * time.Millisecond,
})
if len(res.Failed) != 1 || res.Failed[0].ID != "a" {
t.Errorf("Failed=%v, want [{a, parse error}]", res.Failed)
}
completedSet := make(map[string]bool)
for _, id := range res.Completed {
completedSet[id] = true
}
if !completedSet["b"] || !completedSet["c"] {
t.Errorf("Completed=%v, want both b and c present", res.Completed)
}
}
// ---------------------------------------------------------------------------
// B5: emitWaitResult rendering tests
// ---------------------------------------------------------------------------
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 TestEmitWaitResult_TextSummary(t *testing.T) {
var buf bytes.Buffer
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
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
res := &WaitResult{
Completed: []string{"a", "b"},
Failed: []FailedDoc{{ID: "c", Message: "parse boom"}},
Timeout: []string{"d"},
}
if err := emitWaitResult(res, fopts, &buf); err != nil {
t.Fatalf("emitWaitResult: %v", err)
}
out := buf.String()
for _, want := range []string{"a", "b", "c", "d", "parse boom"} {
if !strings.Contains(out, want) {
t.Errorf("text output missing %q:\n%s", want, out)
}
}
}
func TestEmitWaitResult_JSONSingleRecord(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
res := &WaitResult{
Completed: []string{"a"},
Failed: []FailedDoc{{ID: "b", Message: "x"}},
}
if err := emitWaitResult(res, fopts, &buf); err != nil {
t.Fatalf("emitWaitResult: %v", err)
}
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup Sweep every CLI output path through the v0.7 envelope contract. FormatOptions.Emit signature changes to (w, data, meta *output.Meta) so list commands surface meta.count / has_more in the wire envelope. TTY indent decision plumbed via FormatOptions.TTY (set by ResolveDefault). --format and --jq promoted to persistent root flags so unknown-subcommand paths still reach the typed-envelope guard (per-command registration would have rejected --format on unknown commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback honored before TTY-resolved default. AddFormatFlag retained for the per-command --jq field-hint Long-text addendum. ~55 production Emit call sites swept across cli/cmd/**: list paths populate meta.count; mutation paths pass nil meta; envelope.profile threaded via globalProfile. Existing JSON-shape tests migrated to decode the envelope wrapper. Multi-target batch operations get a unified shape via new helpers: - output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok pattern; data:[{id, ok, result?|error?}], meta:{count, successes*, failures*}; Successes/Failures *int so explicit zero survives omitempty in all-fail case). - cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow + cmdutil.ClassifyContextErr collapse the three previously-duplicated multi-delete pipelines (doc / chunk / session) into one call site pattern. doc upload --recursive uses the same helpers with a per- file resultFn. Summary error sets Silent:true so the stderr envelope path doesn't duplicate the stdout batch detail (exit 1 preserved via Code → ExitCode). ConfirmDestructive / ConfirmDestructiveBatch extended with action + retryCmd parameters. Every destructive command (kb delete, kb edit, doc delete, doc delete --all, agent delete, agent edit, session delete, chunk delete, auth logout, api -X DELETE) now attaches error.risk.{level:"destructive", action:"<noun.verb>"} + error.retry_command on the exit-10 envelope. kb edit / agent edit also gain the destructive guard wiring (CHANGELOG listed them as gated but they were silently executing without -y). MCP tool handlers' 31 error paths return CallToolResult with IsError + Content text fallback + StructuredContent (envelope.error shape via cmdutil.ErrorToDetail). Handler Out type changed from typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite StructuredContent with a zero-struct on error returns. Success path manually populates CallToolResult.StructuredContent via successResult helper. weknora api cleanup: - -d/--data flag removed; body via --input <file> or --input - (stdin) only. Aligns with gh / curl convention. - HTTP method whitelist removed; any non-empty method accepted. - HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds → envelope.error.retry_after_seconds. - runAPIPaginated raw-passthrough fallback now wraps response in envelope so --paginate never emits bare JSON to stdout. Test sweep: ~60 cmd/** tests migrated to decode envelope shape. 9 wire-contract goldens updated under cli/acceptance/testdata/wire/. Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
var env struct {
OK bool `json:"ok"`
Data WaitResult `json:"data"`
}
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
t.Fatalf("not JSON: %v\n%s", err, buf.String())
}
refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup Sweep every CLI output path through the v0.7 envelope contract. FormatOptions.Emit signature changes to (w, data, meta *output.Meta) so list commands surface meta.count / has_more in the wire envelope. TTY indent decision plumbed via FormatOptions.TTY (set by ResolveDefault). --format and --jq promoted to persistent root flags so unknown-subcommand paths still reach the typed-envelope guard (per-command registration would have rejected --format on unknown commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback honored before TTY-resolved default. AddFormatFlag retained for the per-command --jq field-hint Long-text addendum. ~55 production Emit call sites swept across cli/cmd/**: list paths populate meta.count; mutation paths pass nil meta; envelope.profile threaded via globalProfile. Existing JSON-shape tests migrated to decode the envelope wrapper. Multi-target batch operations get a unified shape via new helpers: - output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok pattern; data:[{id, ok, result?|error?}], meta:{count, successes*, failures*}; Successes/Failures *int so explicit zero survives omitempty in all-fail case). - cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow + cmdutil.ClassifyContextErr collapse the three previously-duplicated multi-delete pipelines (doc / chunk / session) into one call site pattern. doc upload --recursive uses the same helpers with a per- file resultFn. Summary error sets Silent:true so the stderr envelope path doesn't duplicate the stdout batch detail (exit 1 preserved via Code → ExitCode). ConfirmDestructive / ConfirmDestructiveBatch extended with action + retryCmd parameters. Every destructive command (kb delete, kb edit, doc delete, doc delete --all, agent delete, agent edit, session delete, chunk delete, auth logout, api -X DELETE) now attaches error.risk.{level:"destructive", action:"<noun.verb>"} + error.retry_command on the exit-10 envelope. kb edit / agent edit also gain the destructive guard wiring (CHANGELOG listed them as gated but they were silently executing without -y). MCP tool handlers' 31 error paths return CallToolResult with IsError + Content text fallback + StructuredContent (envelope.error shape via cmdutil.ErrorToDetail). Handler Out type changed from typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite StructuredContent with a zero-struct on error returns. Success path manually populates CallToolResult.StructuredContent via successResult helper. weknora api cleanup: - -d/--data flag removed; body via --input <file> or --input - (stdin) only. Aligns with gh / curl convention. - HTTP method whitelist removed; any non-empty method accepted. - HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds → envelope.error.retry_after_seconds. - runAPIPaginated raw-passthrough fallback now wraps response in envelope so --paginate never emits bare JSON to stdout. Test sweep: ~60 cmd/** tests migrated to decode envelope shape. 9 wire-contract goldens updated under cli/acceptance/testdata/wire/. Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
2026-05-21 10:41:56 +00:00
got := env.Data
if len(got.Completed) != 1 || got.Completed[0] != "a" {
t.Errorf("Completed=%v, want [a]", got.Completed)
}
if len(got.Failed) != 1 || got.Failed[0].ID != "b" {
t.Errorf("Failed=%v, want [{b, x}]", got.Failed)
}
}
func TestEmitWaitResult_NDJSONSingleLine(t *testing.T) {
var buf bytes.Buffer
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
res := &WaitResult{Completed: []string{"a"}}
if err := emitWaitResult(res, fopts, &buf); err != nil {
t.Fatalf("emitWaitResult: %v", err)
}
out := buf.String()
// NDJSON: single record = single line ending with \n
if strings.Count(out, "\n") != 1 {
t.Errorf("expected exactly 1 newline, got %q", out)
}
var got WaitResult
if err := json.Unmarshal([]byte(strings.TrimRight(out, "\n")), &got); err != nil {
t.Fatalf("line not JSON: %v\n%s", err, out)
}
if len(got.Completed) != 1 {
t.Error("expected Completed populated")
}
}
// ---------------------------------------------------------------------------
// B4: WaitResult.ExitCode tests
// ---------------------------------------------------------------------------
func TestWaitResult_ExitCode(t *testing.T) {
cases := []struct {
name string
res *WaitResult
want int
}{
{"all completed", &WaitResult{Completed: []string{"a"}}, 0},
{"empty result", &WaitResult{}, 0},
{"any failed", &WaitResult{Failed: []FailedDoc{{ID: "a"}}}, 1},
{"timeout only", &WaitResult{Timeout: []string{"a"}}, 124},
{"failed wins over timeout", &WaitResult{
Failed: []FailedDoc{{ID: "a"}},
Timeout: []string{"b"},
}, 1},
{"failed wins over completed+timeout", &WaitResult{
Completed: []string{"a"},
Failed: []FailedDoc{{ID: "b"}},
Timeout: []string{"c"},
}, 1},
{"timeout wins over completed", &WaitResult{
Completed: []string{"a"},
Timeout: []string{"b"},
}, 124},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := tc.res.ExitCode(); got != tc.want {
t.Errorf("ExitCode = %d, want %d", got, tc.want)
}
})
}
}
// On aggregate failure, doc wait emits the partition envelope to stdout; the
// returned error must be Silent so PrintError does NOT write a second,
// contradictory {ok:false} envelope to stderr. Regression for the dual-envelope
// contract violation (stdout ok:true + stderr ok:false for one invocation).
func TestDocWait_FailureError_IsSilent(t *testing.T) {
// Mirror RunBatch's contract: the failure carries CodeOperationFailed for
// the exit code, but Silent=true suppresses the stderr envelope.
err := cmdutil.NewError(cmdutil.CodeOperationFailed, "1 doc(s) failed").WithSilent()
typed := cmdutil.AsError(err)
if typed == nil {
t.Fatal("expected typed *Error")
}
if !typed.Silent {
t.Error("doc wait failure error must be Silent to avoid a contradictory stderr envelope")
}
if cmdutil.ExitCode(err) != 1 {
t.Errorf("exit code = %d, want 1", cmdutil.ExitCode(err))
}
}
feat(cli)!: v0.10 reliability, agent-UX, and command-surface hardening A hardening + finalization pass over the agent-first CLI: correctness fixes, richer machine-readable signals, flag/naming consistency, and a symmetric config surface. Pre-1.0, so it includes breaking renames. Correctness: - agent update: resolve/validate --model/--rerank-model (was storing a bogus name verbatim, corrupting config.model_id). - doctor: honor WEKNORA_HOST / WEKNORA_API_KEY (headless path no longer reports "no host configured"). - session ask / MCP session_ask: text answer was empty on non-TTY — the agent stream sets Done=true on an intermediate agent_query frame before the answer, and AgentAccumulator treated the first Done as terminal. Terminate on the `complete` event (new sdk.AgentResponseTypeComplete), not a per-frame Done. - batch exit codes: any per-item failure collapses to operation.failed (exit 1), including `doc upload --recursive` partial failures — a permanent per-file failure (e.g. a duplicate) no longer surfaces as a retryable exit 7 an agent would loop on; per-item typed errors stay in the envelope. Agent-first signals & discovery: - error.exit_code in the envelope (type + exit_code disambiguate the input.invalid_argument exit-2-vs-5 split in one JSON read). - meta.hint on empty content search and on draft doc create; doc wait fails fast on a never-parsing draft instead of hanging to --timeout. - retrieval-readiness is visible in the natural flow: kb status / kb check emit retrieval_ready, and kb create hints the fix when no embedding model is bound — an unconfigured KB no longer looks silently healthy. - schema contract completeness: every leaf declares output + >=1 example (drift-guarded); output strings match the meta actually emitted; chunk list and search docs now emit meta.total_count (both previously dropped it). - schema tolerates a quoted multi-word command label; zero-state auth — and `link` with no profile — point at profile setup / the headless WEKNORA_KB_ID path instead of looping on `auth login`. - id-addressed reads tolerate a redundant --kb (doc view/wait, chunk list/view accept and ignore it, declared in schema) so a carried-over --kb doesn't exit 2; streaming commands warn that --jq does not apply to an NDJSON stream. - keep JSON-always as the default; --jq hints spell out the .data path. Consistency & gating: - doc create: drop the deprecated --name alias (--title only; pre-1.0 break). - chunk list --limit aligned to 1..10000; model list --limit/-L with has_more/total_count; api write-gates -X PUT/PATCH (exit 10); skills install expands a leading ~. - docs corrected: search docs / doc list --keyword help is case-insensitive (server does LOWER LIKE); AGENTS.md risk-action list (no phantom kb.init; add model.update / kb.config.set) and batch example (failed item carries `error`); session resume --message id comes from `message list`, not the stream. - auth/profile ergonomics: env credentials are now first-class — `auth token` prints the active WEKNORA_API_KEY / WEKNORA_TOKEN, and auth login/logout/refresh give an env-aware message instead of looping on "run auth login". `auth logout` clears credentials but keeps the profile registered (host preserved for re-login); deleting a profile is `profile remove`'s job (clean logout/remove separation, matching gh / lark). Config surface (symmetric read/write, in-place model edits): - kb config now returns a secret-free KBModelConfigView (was {}); `kb config` reads, new `kb config set` writes; `kb init` removed (misnomer). - kb create --chat-model: retrieval-ready in one step. - model update: edit a model in place (id preserved, references survive) — rotate --api-key-stdin, change base-url / display-name / etc. - session continue-stream renamed to session resume. Docs: AGENTS.md is the single wire-contract source; CHANGELOG slimmed; stale kb-init / continue-stream references removed; skill wire-vocab guard extended. AGENTS.md / weknora-shared SKILL document retrieval_ready (a KB needs an embedding model to be searchable), that --jq does not apply to NDJSON streams, and the env-credential-first auth path; the KB quickstart example now creates a retrieval-ready KB.
2026-07-02 07:53:51 +00:00
// TestWaitForDocs_DraftFailsFast pins that a document stuck in parse_status
// "draft" (inline `doc create` leaves docs here; it never auto-progresses) is
// failed fast with a reparse hint instead of polling until the --timeout.
// Regression: `doc create` + `doc wait` used to hang to a 124 timeout.
func TestWaitForDocs_DraftFailsFast(t *testing.T) {
svc := newFakeKBSvc(map[string][]string{
"doc_draft": {"draft", "draft", "draft"},
})
start := time.Now()
res, _ := waitForDocs(context.Background(), []string{"doc_draft"}, svc, WaitOptions{
Timeout: 5 * time.Second,
Interval: 1 * time.Millisecond,
})
if len(res.Timeout) != 0 {
t.Errorf("draft must NOT time out; got timeout=%v", res.Timeout)
}
if len(res.Failed) != 1 || res.Failed[0].ID != "doc_draft" {
t.Fatalf("draft doc must be failed-fast; got failed=%v", res.Failed)
}
if !strings.Contains(res.Failed[0].Message, "reparse") {
t.Errorf("draft failure message must point to reparse; got %q", res.Failed[0].Message)
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Errorf("draft must fail fast (well under timeout); took %v", elapsed)
}
}