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
129 lines
4.2 KiB
Go
129 lines
4.2 KiB
Go
// Package cmdutil — batch.go provides reusable plumbing for multi-target
|
|
// mutations that emit the §4.5 batch envelope.
|
|
//
|
|
// Three pieces:
|
|
// - BatchOutcome: per-target structured outcome (preserves argv order).
|
|
// - RunBatch: drives a slice of targets through a closure, collecting
|
|
// outcomes. Stops on context cancellation; keep-going on per-item err.
|
|
// - EmitBatch: renders the outcomes — JSON/NDJSON via output.WriteBatchEnvelope,
|
|
// text via per-item "OK <id>" / "FAIL <id>: <msg>".
|
|
|
|
package cmdutil
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"time"
|
|
|
|
"github.com/Tencent/WeKnora/cli/internal/output"
|
|
)
|
|
|
|
// BatchOutcome is one per-target result preserving argv order. Err==nil ⇒ success.
|
|
type BatchOutcome struct {
|
|
ID string
|
|
Err error
|
|
}
|
|
|
|
// RunBatch invokes op(ctx, id) for each id and collects outcomes in order.
|
|
// Per-item errors do not abort the run; context cancellation does (the
|
|
// remainder of the slice is marked with the context error).
|
|
//
|
|
// Returns (outcomes, summaryErr). summaryErr is a typed *Error with
|
|
// CodeOperationFailed when any per-item op failed, nil otherwise. Callers
|
|
// emit the outcomes before returning summaryErr so partial-success data
|
|
// reaches stdout.
|
|
func RunBatch(ctx context.Context, ids []string, op func(context.Context, string) error) ([]BatchOutcome, error) {
|
|
outcomes := make([]BatchOutcome, 0, len(ids))
|
|
failed := 0
|
|
for _, id := range ids {
|
|
select {
|
|
case <-ctx.Done():
|
|
outcomes = append(outcomes, BatchOutcome{ID: id, Err: ctx.Err()})
|
|
failed++
|
|
continue
|
|
default:
|
|
}
|
|
err := op(ctx, id)
|
|
outcomes = append(outcomes, BatchOutcome{ID: id, Err: err})
|
|
if err != nil {
|
|
failed++
|
|
}
|
|
}
|
|
if failed > 0 {
|
|
return outcomes, &Error{
|
|
Code: CodeOperationFailed,
|
|
Message: fmt.Sprintf("%d/%d operation(s) failed", failed, len(ids)),
|
|
// Silent suppresses the stderr error envelope because the caller
|
|
// already emitted the batch envelope to stdout (§4.5). The exit code
|
|
// still propagates via Error.Code → ExitCode (falls through to 1).
|
|
Silent: true,
|
|
}
|
|
}
|
|
return outcomes, nil
|
|
}
|
|
|
|
// EmitBatch writes the per-item outcomes per --format. JSON/NDJSON emit
|
|
// the §4.5 batch envelope; text mode emits per-line "OK <id>" /
|
|
// "FAIL <id>: <msg>".
|
|
//
|
|
// resultFn builds the per-item Result map for successes; nil ⇒ omit.
|
|
// A typical resultFn returns map[string]any{"deleted_at": time.Now()....}.
|
|
//
|
|
// Callers wanting a stable per-item timestamp pass time.Now() via
|
|
// resultFn so tests can pin the clock with SetDeletedAtClock.
|
|
func EmitBatch(outcomes []BatchOutcome, fopts *FormatOptions, w io.Writer, resultFn func(id string) any) error {
|
|
if fopts.WantsJSON() {
|
|
items := make([]output.BatchItem, len(outcomes))
|
|
for i, o := range outcomes {
|
|
items[i] = output.BatchItem{ID: o.ID, OK: o.Err == nil}
|
|
if o.Err != nil {
|
|
items[i].Error = ErrorToDetail(o.Err)
|
|
} else if resultFn != nil {
|
|
items[i].Result = resultFn(o.ID)
|
|
}
|
|
}
|
|
return output.WriteBatchEnvelope(w, items, fopts.TTY, globalProfile)
|
|
}
|
|
for _, o := range outcomes {
|
|
if o.Err == nil {
|
|
fmt.Fprintf(w, "OK %s\n", o.ID)
|
|
continue
|
|
}
|
|
fmt.Fprintf(w, "FAIL %s: %s\n", o.ID, o.Err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// deletedAtClock is the clock source for DeletedAtNow. Overridable in tests
|
|
// to make per-item timestamps deterministic.
|
|
var deletedAtClock = time.Now
|
|
|
|
// DeletedAtNow is the canonical resultFn for delete batches that report
|
|
// {deleted_at: <RFC3339>} per success. Tests can freeze the clock via
|
|
// SetDeletedAtClock(func() time.Time { return fixed }).
|
|
func DeletedAtNow(id string) any {
|
|
return map[string]any{"deleted_at": deletedAtClock().Format(time.RFC3339)}
|
|
}
|
|
|
|
// SetDeletedAtClock overrides the time source used by DeletedAtNow. Returns
|
|
// a cleanup func that restores time.Now. For test use only.
|
|
func SetDeletedAtClock(clock func() time.Time) func() {
|
|
deletedAtClock = clock
|
|
return func() { deletedAtClock = time.Now }
|
|
}
|
|
|
|
// ClassifyContextErr maps a context error to the appropriate operation code.
|
|
// Falls back to CodeOperationFailed when err is nil or not a context signal.
|
|
func ClassifyContextErr(err error) ErrorCode {
|
|
switch {
|
|
case errors.Is(err, context.Canceled):
|
|
return CodeOperationCancelled
|
|
case errors.Is(err, context.DeadlineExceeded):
|
|
return CodeOperationTimeout
|
|
default:
|
|
return CodeOperationFailed
|
|
}
|
|
}
|