WeKnora/cli/internal/cmdutil/errors.go

459 lines
18 KiB
Go
Raw Normal View History

// Package cmdutil contains the Factory, Options helpers, error types,
// JSON-flag wiring, and the Exporter abstraction shared by all commands.
package cmdutil
import (
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
"context"
"errors"
"fmt"
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
"regexp"
"strconv"
"strings"
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
"github.com/Tencent/WeKnora/cli/internal/output"
)
refactor(cli): delete envelope infrastructure, errors to stderr Removes the entire envelope machinery now that every success path emits bare JSON: - cli/internal/format/envelope.go (Envelope, Success, Failure, SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice, VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests. - cli/internal/format/filter.go envelope-specific helpers (WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter, filterDataPayload, filterObjectData); the reusable filterArrayItems / filterObjectKeys / writeJQ stay for bare.go. - cli/internal/cmdutil/exporter.go + tests (envelope-only). - cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody + operationRiskOf + Error.OperationRisk field + OperationRisk struct. Error path: all errors now go to stderr via cmdutil.PrintError in `code: message\nhint: ...` form, regardless of --json. Stdout stays empty (or holds the partial-success the command already wrote) so downstream `--json | jq` pipelines never have to filter error shapes out of the success stream. Typed exit codes (3 auth.* / 4 resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.* + network.* / 10 input.confirmation_required) carry the failure class for agents that branch on it. Acceptance contract: - envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden). - testdata/envelopes/ → testdata/wire/. - Error-path cases assert the typed code substring on stderr. - Orphan whoami.*.json goldens deleted. AGENTS.md + README.md rewritten for the bare-data contract: - Drop envelope schema section + dry-run rule. - Document bare JSON on stdout + `code: msg\nhint: …` on stderr. - ADR-3 reframed around bare data and why error separation matters for `--json | jq` pipelines. WriteJSONFiltered short-circuits to WriteJSON when both filters are empty (skip the marshal-buffer round-trip for the common case). Final review pass: - Fix wire-contract bug: `--json id,name` (space form) is broken by pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the field-discovery help text all switched to `--json=id,name`. - Fix `weknora api --jq` silently ignored: api.go now routes through WriteJSONFiltered with jopts.JQ. - AGENTS.md: drop the false claim that `auth logout` honors `-y` (logout is local-only with no ConfirmDestructive guard); list the actual destructive commands instead. - Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape (was still parsing `out["data"]` / `env["ok"]`). - Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated `format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields, jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the format import from 22 cmd/* files. - Delete single-caller `cmdutil.MustRequireFlag`; inline as `_ = cmd.MarkFlagRequired(...)` everywhere. - Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the only write command relying on runtime --name validation while `context add` already used the cobra-level mark. - `context use`: register `--json` / `--jq` (was always emitting JSON unconditionally with no human path and no flag — diverged from every other write command); human mode now prints `✓ Switched context to X (was Y)`. - Replace per-package `confirmPrompter` / `scriptedConfirm` / `errPrompter` test doubles with `testutil.ConfirmPrompter`. - Rename `chatService` → `ChatService` (export to match siblings `ListService` / `ViewService`); rename `printUploadSuccess` → `renderUploadSuccess` (siblings use `render*`). - `defaultHint(CodeResourceNotFound)`: drop the hardcoded "list available with `weknora kb list`" — misleading on agent / doc / session 404. Replaced with "verify the resource ID and try again". - Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only" historical tags from production comments and a few test descriptions.
2026-05-14 17:51:11 +00:00
// ErrorCode is a namespaced stable identifier emitted on stderr in the
// `code: message` failure line. SemVer governance: v0.x maintains the
// registry below; new codes are noted in release notes.
type ErrorCode string
const (
// auth.* - authentication / permission
CodeAuthUnauthenticated ErrorCode = "auth.unauthenticated"
CodeAuthTokenExpired ErrorCode = "auth.token_expired"
CodeAuthBadCredential ErrorCode = "auth.bad_credential"
CodeAuthForbidden ErrorCode = "auth.forbidden"
CodeAuthCrossTenantBlocked ErrorCode = "auth.cross_tenant_blocked"
CodeAuthTenantMismatch ErrorCode = "auth.tenant_mismatch"
// resource.*
CodeResourceNotFound ErrorCode = "resource.not_found"
CodeResourceAlreadyExists ErrorCode = "resource.already_exists"
CodeResourceLocked ErrorCode = "resource.locked"
// input.* - flag and argument validation
CodeInputInvalidArgument ErrorCode = "input.invalid_argument"
CodeInputMissingFlag ErrorCode = "input.missing_flag"
feat(cli): add agent-first affordance — envelope, exit-10, --dry-run Borrows the lark-cli agent-affordance model (https://github.com/larksuite/cli/blob/main/AGENTS.md + skills/lark-shared/SKILL.md) so weknora is designed to be agent-friendly: error messages, output format, and flag design follow conventions agents can rely on. cli/AGENTS.md (operational reference for LLM agents invoking weknora): Public document covering envelope schema, exit-code protocol (0/1/2/10/130), stdout/stderr separation, and behavioral rules. Sensitive commands (\`context use\`, \`kb delete\`, \`doc delete\`, \`init\`) gain "AI agents:" paragraphs in their cobra Long descriptions so guidance shows in --help. format.Envelope schema additions: Risk per-operation classification (read / write / high-risk-write + action description), populated by write commands on both success and failure paths. Notice system advisories (CLI update available, server-CLI version skew); type defined, emit sites land in v0.3. DryRun marker for envelopes returned from --dry-run preview paths. RiskLevel constants realigned to lark's taxonomy: read / write / high-risk-write (was: read / mutating / destructive — not yet wired by any command). cmdutil.Error gains OperationRisk; PrintErrorEnvelope auto-attaches it to envelope.Risk so destructive failure paths surface uniformly. Exit-10 confirmation protocol: New ErrorCode \`input.confirmation_required\` mapped to exit code 10 in cmdutil.ExitCode. ConfirmDestructive now returns this code (with OperationRisk attached) when stdout is non-TTY or --json was set, with -y/--yes absent. Previous behavior — silent proceed in non-TTY — was unsafe: scripts and agents could delete resources with no explicit approval. Three test cases re-pinned around the new contract. This is a wire-contract change for any caller who relied on silent proceed; v0.0/v0.1 had no destructive commands, so the blast radius is contained to v0.2 itself. --dry-run global flag: cmd write paths (kb create/delete, doc upload/delete, api POST/PUT/PATCH/ DELETE) check cmdutil.IsDryRun(cmd) and skip the SDK call, emitting an envelope with dry_run=true plus a Risk classification. Read commands ignore --dry-run by design (no side effect to preview). Human-mode prints \`[dry-run] would <action>\` to stdout. Command discovery: agents introspect via the existing \`--help\` surface (consistent with gh / kubectl / aws / gcloud / terraform — none of them ship a CLI-tree self-description command). An earlier draft added a \`weknora schema\` reflection command; dropped after a mainstream survey found it has no stable analog (lark-cli's schema describes Lark API methods, not its own CLI tree). Tests: 27 cli packages pass at this commit. Added two new tests covering envelope.risk and envelope._notice serialization.
2026-05-10 18:44:34 +00:00
// CodeInputConfirmationRequired marks a high-risk write that has no
// interactive UI (non-TTY or JSON-output mode) and was invoked without
// -y/--yes. Mapped to exit code 10 (see cli/README.md). Agents must
// surface the error to the user and only retry with -y after explicit
// human approval; never auto-retry.
feat(cli): add agent-first affordance — envelope, exit-10, --dry-run Borrows the lark-cli agent-affordance model (https://github.com/larksuite/cli/blob/main/AGENTS.md + skills/lark-shared/SKILL.md) so weknora is designed to be agent-friendly: error messages, output format, and flag design follow conventions agents can rely on. cli/AGENTS.md (operational reference for LLM agents invoking weknora): Public document covering envelope schema, exit-code protocol (0/1/2/10/130), stdout/stderr separation, and behavioral rules. Sensitive commands (\`context use\`, \`kb delete\`, \`doc delete\`, \`init\`) gain "AI agents:" paragraphs in their cobra Long descriptions so guidance shows in --help. format.Envelope schema additions: Risk per-operation classification (read / write / high-risk-write + action description), populated by write commands on both success and failure paths. Notice system advisories (CLI update available, server-CLI version skew); type defined, emit sites land in v0.3. DryRun marker for envelopes returned from --dry-run preview paths. RiskLevel constants realigned to lark's taxonomy: read / write / high-risk-write (was: read / mutating / destructive — not yet wired by any command). cmdutil.Error gains OperationRisk; PrintErrorEnvelope auto-attaches it to envelope.Risk so destructive failure paths surface uniformly. Exit-10 confirmation protocol: New ErrorCode \`input.confirmation_required\` mapped to exit code 10 in cmdutil.ExitCode. ConfirmDestructive now returns this code (with OperationRisk attached) when stdout is non-TTY or --json was set, with -y/--yes absent. Previous behavior — silent proceed in non-TTY — was unsafe: scripts and agents could delete resources with no explicit approval. Three test cases re-pinned around the new contract. This is a wire-contract change for any caller who relied on silent proceed; v0.0/v0.1 had no destructive commands, so the blast radius is contained to v0.2 itself. --dry-run global flag: cmd write paths (kb create/delete, doc upload/delete, api POST/PUT/PATCH/ DELETE) check cmdutil.IsDryRun(cmd) and skip the SDK call, emitting an envelope with dry_run=true plus a Risk classification. Read commands ignore --dry-run by design (no side effect to preview). Human-mode prints \`[dry-run] would <action>\` to stdout. Command discovery: agents introspect via the existing \`--help\` surface (consistent with gh / kubectl / aws / gcloud / terraform — none of them ship a CLI-tree self-description command). An earlier draft added a \`weknora schema\` reflection command; dropped after a mainstream survey found it has no stable analog (lark-cli's schema describes Lark API methods, not its own CLI tree). Tests: 27 cli packages pass at this commit. Added two new tests covering envelope.risk and envelope._notice serialization.
2026-05-10 18:44:34 +00:00
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
// CodeInputUnknownSubcommand marks an invocation that reached a parent
// command path but the first positional argument did not match any
// registered subcommand. Detail includes an `available` list so agents
// can surface valid choices without re-invoking; retry with `<path> --help`.
CodeInputUnknownSubcommand ErrorCode = "input.unknown_subcommand"
// server.* / network.*
CodeServerError ErrorCode = "server.error"
CodeServerTimeout ErrorCode = "server.timeout"
CodeServerRateLimited ErrorCode = "server.rate_limited"
CodeServerIncompatibleVersion ErrorCode = "server.incompatible_version"
CodeNetworkError ErrorCode = "network.error"
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
// CodeSessionCreateFailed marks a chat invocation where the auto-created
// session POST failed. Surfaced as a typed code distinct from generic
// server.error so agents can retry with their own --session.
feat(cli): add api passthrough, chat streaming, doctor warn status Close the v0.2 RAG demo loop and ship the validation infrastructure: - weknora api <method> <path> [--data X | --data-file F] Raw passthrough wrapping client.Raw, gh-style. JSON envelope mode surfaces status / headers / parsed body. Non-2xx routes through cmdutil.ClassifyHTTPStatus (factored out of ClassifyHTTPError so both SDK-error and direct-status paths stay aligned — reuse review). - weknora chat <text> [--session-id S] [--no-stream] KnowledgeQAStream consumer with two output modes: - TTY default: token streaming + references footer - --json / --no-stream / non-TTY: buffered single envelope Auto-creates a session when --session-id is omitted; the id prints to stderr at start AND on stream failure (^C scrolls past the first announcement, so the recovery hint is re-surfaced when the user is most likely to need it). - cli/internal/sse/Accumulator buffers Content / References / SessionID across SDK callbacks. Idempotent post-Done so misbehaving servers don't corrupt state. - doctor: ok → ok / warn / fail / skip warn marks soft issues that don't block: server within compat range but >=1 minor behind CLI; credential storage falling back to file because keyring is unavailable. Envelope.ok stays true on warn, flips false on fail (exit 1). doctor.error_network golden updated. - cli/acceptance/e2e/ real-server RAG full loop Build-tagged //go:build acceptance_e2e — kept out of the default `go test ./...`. Exercises kb create → doc upload → poll ready → search → chat → cleanup against a server pointed at by WEKNORA_E2E_HOST / _TOKEN. - .github/workflows/cli-e2e.yml manual workflow_dispatch + label-gated PR trigger ("acceptance-e2e"). No-ops gracefully when the secrets aren't set so cross-fork PRs can't accidentally fail the suite.
2026-05-10 18:44:13 +00:00
CodeSessionCreateFailed ErrorCode = "server.session_create_failed"
// operation.* - CLI-level wait/poll results
// CodeOperationTimeout marks a CLI-level wait/poll operation that exhausted
// its --timeout window. Distinct from CodeServerTimeout (HTTP 504). Mapped
// to exit 124 (matches the convention from GNU `timeout`).
CodeOperationTimeout ErrorCode = "operation.timeout"
// CodeOperationFailed marks a CLI-level wait/poll operation where one or
// more targets reached a terminal failure (e.g. doc wait found a doc with
// parse_status=failed). Distinct from server.* / network.* because the
// failure is the target's own terminal state, not a transient transport
// issue. Maps to exit 1 via the fall-through bucket.
CodeOperationFailed ErrorCode = "operation.failed"
// CodeOperationCancelled marks a long-running command interrupted by a
// caught signal (SIGINT / SIGTERM after main.go's signal.NotifyContext
// fires). Distinct from CodeUserAborted (declined confirm prompt) — the
// hints differ. main.go overrides the exit code to 130 for cancelled
// contexts so the user-visible exit follows Unix signal convention.
CodeOperationCancelled ErrorCode = "operation.cancelled"
// local.* - config / file / keychain on the user's machine
CodeLocalConfigCorrupt ErrorCode = "local.config_corrupt"
CodeLocalKeychainDenied ErrorCode = "local.keychain_denied"
CodeLocalFileIO ErrorCode = "local.file_io"
CodeLocalUnimplemented ErrorCode = "local.unimplemented"
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
CodeLocalProfileNotFound ErrorCode = "local.profile_not_found"
// KB-resolution chain and project-link codes.
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
CodeKBIDRequired ErrorCode = "local.kb_id_required"
CodeKBNotFound ErrorCode = "local.kb_not_found"
CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
// CodeUserAborted marks a user-cancelled destructive operation (declined a
refactor(cli): delete envelope infrastructure, errors to stderr Removes the entire envelope machinery now that every success path emits bare JSON: - cli/internal/format/envelope.go (Envelope, Success, Failure, SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice, VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests. - cli/internal/format/filter.go envelope-specific helpers (WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter, filterDataPayload, filterObjectData); the reusable filterArrayItems / filterObjectKeys / writeJQ stay for bare.go. - cli/internal/cmdutil/exporter.go + tests (envelope-only). - cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody + operationRiskOf + Error.OperationRisk field + OperationRisk struct. Error path: all errors now go to stderr via cmdutil.PrintError in `code: message\nhint: ...` form, regardless of --json. Stdout stays empty (or holds the partial-success the command already wrote) so downstream `--json | jq` pipelines never have to filter error shapes out of the success stream. Typed exit codes (3 auth.* / 4 resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.* + network.* / 10 input.confirmation_required) carry the failure class for agents that branch on it. Acceptance contract: - envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden). - testdata/envelopes/ → testdata/wire/. - Error-path cases assert the typed code substring on stderr. - Orphan whoami.*.json goldens deleted. AGENTS.md + README.md rewritten for the bare-data contract: - Drop envelope schema section + dry-run rule. - Document bare JSON on stdout + `code: msg\nhint: …` on stderr. - ADR-3 reframed around bare data and why error separation matters for `--json | jq` pipelines. WriteJSONFiltered short-circuits to WriteJSON when both filters are empty (skip the marshal-buffer round-trip for the common case). Final review pass: - Fix wire-contract bug: `--json id,name` (space form) is broken by pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the field-discovery help text all switched to `--json=id,name`. - Fix `weknora api --jq` silently ignored: api.go now routes through WriteJSONFiltered with jopts.JQ. - AGENTS.md: drop the false claim that `auth logout` honors `-y` (logout is local-only with no ConfirmDestructive guard); list the actual destructive commands instead. - Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape (was still parsing `out["data"]` / `env["ok"]`). - Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated `format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields, jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the format import from 22 cmd/* files. - Delete single-caller `cmdutil.MustRequireFlag`; inline as `_ = cmd.MarkFlagRequired(...)` everywhere. - Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the only write command relying on runtime --name validation while `context add` already used the cobra-level mark. - `context use`: register `--json` / `--jq` (was always emitting JSON unconditionally with no human path and no flag — diverged from every other write command); human mode now prints `✓ Switched context to X (was Y)`. - Replace per-package `confirmPrompter` / `scriptedConfirm` / `errPrompter` test doubles with `testutil.ConfirmPrompter`. - Rename `chatService` → `ChatService` (export to match siblings `ListService` / `ViewService`); rename `printUploadSuccess` → `renderUploadSuccess` (siblings use `render*`). - `defaultHint(CodeResourceNotFound)`: drop the hardcoded "list available with `weknora kb list`" — misleading on agent / doc / session 404. Replaced with "verify the resource ID and try again". - Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only" historical tags from production comments and a few test descriptions.
2026-05-14 17:51:11 +00:00
// confirm prompt). Distinct from SilentError so the stderr line still
// carries a stable code; distinct from input.* because the user supplied
// valid args and simply chose not to proceed.
CodeUserAborted ErrorCode = "local.user_aborted"
// CodeUploadFileNotFound marks a `weknora doc upload` invocation pointing at
// a path that does not exist. Distinct from CodeLocalFileIO (permission /
// disk-fault) so the hint can name the actual culprit.
CodeUploadFileNotFound ErrorCode = "local.upload_file_not_found"
// CodeSSEStreamAborted marks a streaming RAG response that began producing
// data and then dropped before the SDK observed a Done event. Distinct
// from network.error (pre-stream transport failure) so users see the
// stream specifically aborted, not a connection that never opened.
CodeSSEStreamAborted ErrorCode = "local.sse_stream_aborted"
// mcp.*
CodeMCPReadonlyMode ErrorCode = "mcp.readonly_mode"
CodeMCPToolNotAllowed ErrorCode = "mcp.tool_not_allowed"
CodeMCPSchemaUnknown ErrorCode = "mcp.schema_unknown_command"
)
// Error is the typed error implementations carry through the call stack.
refactor(cli): delete envelope infrastructure, errors to stderr Removes the entire envelope machinery now that every success path emits bare JSON: - cli/internal/format/envelope.go (Envelope, Success, Failure, SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice, VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests. - cli/internal/format/filter.go envelope-specific helpers (WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter, filterDataPayload, filterObjectData); the reusable filterArrayItems / filterObjectKeys / writeJQ stay for bare.go. - cli/internal/cmdutil/exporter.go + tests (envelope-only). - cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody + operationRiskOf + Error.OperationRisk field + OperationRisk struct. Error path: all errors now go to stderr via cmdutil.PrintError in `code: message\nhint: ...` form, regardless of --json. Stdout stays empty (or holds the partial-success the command already wrote) so downstream `--json | jq` pipelines never have to filter error shapes out of the success stream. Typed exit codes (3 auth.* / 4 resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.* + network.* / 10 input.confirmation_required) carry the failure class for agents that branch on it. Acceptance contract: - envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden). - testdata/envelopes/ → testdata/wire/. - Error-path cases assert the typed code substring on stderr. - Orphan whoami.*.json goldens deleted. AGENTS.md + README.md rewritten for the bare-data contract: - Drop envelope schema section + dry-run rule. - Document bare JSON on stdout + `code: msg\nhint: …` on stderr. - ADR-3 reframed around bare data and why error separation matters for `--json | jq` pipelines. WriteJSONFiltered short-circuits to WriteJSON when both filters are empty (skip the marshal-buffer round-trip for the common case). Final review pass: - Fix wire-contract bug: `--json id,name` (space form) is broken by pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the field-discovery help text all switched to `--json=id,name`. - Fix `weknora api --jq` silently ignored: api.go now routes through WriteJSONFiltered with jopts.JQ. - AGENTS.md: drop the false claim that `auth logout` honors `-y` (logout is local-only with no ConfirmDestructive guard); list the actual destructive commands instead. - Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape (was still parsing `out["data"]` / `env["ok"]`). - Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated `format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields, jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the format import from 22 cmd/* files. - Delete single-caller `cmdutil.MustRequireFlag`; inline as `_ = cmd.MarkFlagRequired(...)` everywhere. - Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the only write command relying on runtime --name validation while `context add` already used the cobra-level mark. - `context use`: register `--json` / `--jq` (was always emitting JSON unconditionally with no human path and no flag — diverged from every other write command); human mode now prints `✓ Switched context to X (was Y)`. - Replace per-package `confirmPrompter` / `scriptedConfirm` / `errPrompter` test doubles with `testutil.ConfirmPrompter`. - Rename `chatService` → `ChatService` (export to match siblings `ListService` / `ViewService`); rename `printUploadSuccess` → `renderUploadSuccess` (siblings use `render*`). - `defaultHint(CodeResourceNotFound)`: drop the hardcoded "list available with `weknora kb list`" — misleading on agent / doc / session 404. Replaced with "verify the resource ID and try again". - Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only" historical tags from production comments and a few test descriptions.
2026-05-14 17:51:11 +00:00
// RunE returns a *Error and the root command renders it on stderr in
// `code: message[: cause]\nhint: ...` form. Exit code is derived by
// ExitCode().
type Error struct {
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
Code ErrorCode
Message string
Hint string
Cause error
refactor(cli): delete envelope infrastructure, errors to stderr Removes the entire envelope machinery now that every success path emits bare JSON: - cli/internal/format/envelope.go (Envelope, Success, Failure, SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice, VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests. - cli/internal/format/filter.go envelope-specific helpers (WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter, filterDataPayload, filterObjectData); the reusable filterArrayItems / filterObjectKeys / writeJQ stay for bare.go. - cli/internal/cmdutil/exporter.go + tests (envelope-only). - cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody + operationRiskOf + Error.OperationRisk field + OperationRisk struct. Error path: all errors now go to stderr via cmdutil.PrintError in `code: message\nhint: ...` form, regardless of --json. Stdout stays empty (or holds the partial-success the command already wrote) so downstream `--json | jq` pipelines never have to filter error shapes out of the success stream. Typed exit codes (3 auth.* / 4 resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.* + network.* / 10 input.confirmation_required) carry the failure class for agents that branch on it. Acceptance contract: - envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden). - testdata/envelopes/ → testdata/wire/. - Error-path cases assert the typed code substring on stderr. - Orphan whoami.*.json goldens deleted. AGENTS.md + README.md rewritten for the bare-data contract: - Drop envelope schema section + dry-run rule. - Document bare JSON on stdout + `code: msg\nhint: …` on stderr. - ADR-3 reframed around bare data and why error separation matters for `--json | jq` pipelines. WriteJSONFiltered short-circuits to WriteJSON when both filters are empty (skip the marshal-buffer round-trip for the common case). Final review pass: - Fix wire-contract bug: `--json id,name` (space form) is broken by pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the field-discovery help text all switched to `--json=id,name`. - Fix `weknora api --jq` silently ignored: api.go now routes through WriteJSONFiltered with jopts.JQ. - AGENTS.md: drop the false claim that `auth logout` honors `-y` (logout is local-only with no ConfirmDestructive guard); list the actual destructive commands instead. - Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape (was still parsing `out["data"]` / `env["ok"]`). - Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated `format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields, jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the format import from 22 cmd/* files. - Delete single-caller `cmdutil.MustRequireFlag`; inline as `_ = cmd.MarkFlagRequired(...)` everywhere. - Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the only write command relying on runtime --name validation while `context add` already used the cobra-level mark. - `context use`: register `--json` / `--jq` (was always emitting JSON unconditionally with no human path and no flag — diverged from every other write command); human mode now prints `✓ Switched context to X (was Y)`. - Replace per-package `confirmPrompter` / `scriptedConfirm` / `errPrompter` test doubles with `testutil.ConfirmPrompter`. - Rename `chatService` → `ChatService` (export to match siblings `ListService` / `ViewService`); rename `printUploadSuccess` → `renderUploadSuccess` (siblings use `render*`). - `defaultHint(CodeResourceNotFound)`: drop the hardcoded "list available with `weknora kb list`" — misleading on agent / doc / session 404. Replaced with "verify the resource ID and try again". - Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only" historical tags from production comments and a few test descriptions.
2026-05-14 17:51:11 +00:00
// Silent suppresses PrintError's stderr output while preserving the
// typed Code for ExitCode. Set by commands that already wrote their
// own output (e.g. bulk operations reporting partial-success data on
// stdout) but still need to surface a non-zero exit code.
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
Silent bool
RetryCommand string // Directly-executable argv, distinct from prose Hint
RetryAfterSeconds int // HTTP Retry-After header semantics (transport-level retry hint)
Detail any // Structured detail for envelope.error.detail (e.g. unknown-subcommand available[])
Risk *RiskInfo
}
// RiskInfo tags an error with destructive-write metadata that surfaces
// in the wire envelope's error.risk field.
type RiskInfo struct {
Level string
Action string
feat(cli): add agent-first affordance — envelope, exit-10, --dry-run Borrows the lark-cli agent-affordance model (https://github.com/larksuite/cli/blob/main/AGENTS.md + skills/lark-shared/SKILL.md) so weknora is designed to be agent-friendly: error messages, output format, and flag design follow conventions agents can rely on. cli/AGENTS.md (operational reference for LLM agents invoking weknora): Public document covering envelope schema, exit-code protocol (0/1/2/10/130), stdout/stderr separation, and behavioral rules. Sensitive commands (\`context use\`, \`kb delete\`, \`doc delete\`, \`init\`) gain "AI agents:" paragraphs in their cobra Long descriptions so guidance shows in --help. format.Envelope schema additions: Risk per-operation classification (read / write / high-risk-write + action description), populated by write commands on both success and failure paths. Notice system advisories (CLI update available, server-CLI version skew); type defined, emit sites land in v0.3. DryRun marker for envelopes returned from --dry-run preview paths. RiskLevel constants realigned to lark's taxonomy: read / write / high-risk-write (was: read / mutating / destructive — not yet wired by any command). cmdutil.Error gains OperationRisk; PrintErrorEnvelope auto-attaches it to envelope.Risk so destructive failure paths surface uniformly. Exit-10 confirmation protocol: New ErrorCode \`input.confirmation_required\` mapped to exit code 10 in cmdutil.ExitCode. ConfirmDestructive now returns this code (with OperationRisk attached) when stdout is non-TTY or --json was set, with -y/--yes absent. Previous behavior — silent proceed in non-TTY — was unsafe: scripts and agents could delete resources with no explicit approval. Three test cases re-pinned around the new contract. This is a wire-contract change for any caller who relied on silent proceed; v0.0/v0.1 had no destructive commands, so the blast radius is contained to v0.2 itself. --dry-run global flag: cmd write paths (kb create/delete, doc upload/delete, api POST/PUT/PATCH/ DELETE) check cmdutil.IsDryRun(cmd) and skip the SDK call, emitting an envelope with dry_run=true plus a Risk classification. Read commands ignore --dry-run by design (no side effect to preview). Human-mode prints \`[dry-run] would <action>\` to stdout. Command discovery: agents introspect via the existing \`--help\` surface (consistent with gh / kubectl / aws / gcloud / terraform — none of them ship a CLI-tree self-description command). An earlier draft added a \`weknora schema\` reflection command; dropped after a mainstream survey found it has no stable analog (lark-cli's schema describes Lark API methods, not its own CLI tree). Tests: 27 cli packages pass at this commit. Added two new tests covering envelope.risk and envelope._notice serialization.
2026-05-10 18:44:34 +00:00
}
func (e *Error) Error() string {
if e == nil {
return ""
}
if e.Cause != nil {
return fmt.Sprintf("%s: %s: %v", e.Code, e.Message, e.Cause)
}
return fmt.Sprintf("%s: %s", e.Code, e.Message)
}
func (e *Error) Unwrap() error { return e.Cause }
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
// WithHint sets a prose-style actionable hint.
func (e *Error) WithHint(hint string) *Error {
e.Hint = hint
return e
}
// WithRetryCommand sets the directly-executable retry argv string.
// Agent 端不用 regex 从 prose hint 提 argv。
// Empty string for codes without a canonical retry command.
func (e *Error) WithRetryCommand(cmd string) *Error {
e.RetryCommand = cmd
return e
}
// WithRetryAfter sets the retry_after_seconds hint (from HTTP Retry-After header).
func (e *Error) WithRetryAfter(s int) *Error {
e.RetryAfterSeconds = s
return e
}
// WithDetail attaches structured error.detail (e.g. unknown-subcommand available[]).
func (e *Error) WithDetail(d any) *Error {
e.Detail = d
return e
}
// WithRisk tags a high-risk write (destructive deletes etc.) for the agent protocol.
func (e *Error) WithRisk(level, action string) *Error {
e.Risk = &RiskInfo{Level: level, Action: action}
return e
}
// AsError unwraps to *Error if the chain contains one. Returns nil if not found.
func AsError(err error) *Error {
var typed *Error
if errors.As(err, &typed) {
return typed
}
return nil
}
// ErrorToDetail converts a typed cmdutil.Error (or fallback) into
// output.ErrDetail for embedding in success-envelope batch items or
// MCP CallToolResult StructuredContent. Hint / RetryCommand fall back
// to defaultHint / defaultRetryCommand when typed value is empty.
// Returns nil when err is nil.
func ErrorToDetail(err error) *output.ErrDetail {
if err == nil {
return nil
}
if typed := AsError(err); typed != nil {
hint := typed.Hint
if hint == "" {
hint = defaultHint(typed.Code)
}
retry := typed.RetryCommand
if retry == "" {
retry = defaultRetryCommand(typed.Code)
}
// Build message without the code prefix — the envelope's separate
// "type" field already carries the code, so repeating it in "message"
// causes agents that render "{type}: {message}" to produce a doubled
// prefix (e.g. "resource.not_found: resource.not_found: ...").
msg := typed.Message
if typed.Cause != nil {
msg = fmt.Sprintf("%s: %v", typed.Message, typed.Cause)
}
detail := &output.ErrDetail{
Type: string(typed.Code),
Message: msg,
Hint: hint,
RetryCommand: retry,
RetryAfterSeconds: typed.RetryAfterSeconds,
Detail: typed.Detail,
}
if typed.Risk != nil {
detail.Risk = &output.RiskDetail{Level: typed.Risk.Level, Action: typed.Risk.Action}
}
return detail
}
// Cobra parse / arg-count errors flow through cmdutil.NewFlagError —
// surface them as input.invalid_argument so the wire envelope carries a
// useful typed code instead of the unclassified "internal.error" bucket.
// ExitCode separately maps FlagError → 2.
var fe *FlagError
if errors.As(err, &fe) {
return &output.ErrDetail{
Type: string(CodeInputInvalidArgument),
Message: err.Error(),
Hint: defaultHint(CodeInputInvalidArgument),
}
}
return &output.ErrDetail{Type: "internal.error", Message: err.Error()}
}
// NewError constructs a typed error.
func NewError(code ErrorCode, message string) *Error {
return &Error{Code: code, Message: message}
}
// Wrapf wraps cause with a typed code and Sprintf-style message.
func Wrapf(code ErrorCode, cause error, format string, args ...any) *Error {
return &Error{Code: code, Message: fmt.Sprintf(format, args...), Cause: cause}
}
refactor(cli): v0.3 cross-cutting cleanup Cross-cutting findings surfaced by the branch-completion review. Perf bug: - Factory.Client closure was not memoized. Factory.ResolveKB internally calls f.Client() to resolve --kb name → id, then the command's RunE calls f.Client() again. Two SDK clients, two keyring reads, two AuthRetryTransport allocations per name-resolved invocation, with *independent* token state (a refresh in one was invisible to the other). Switched to sync.Once like Secrets already does. Silent bug bait: - cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the empty case; code returned CodeInputInvalidArgument. Aligned doc to code (present-but-empty is a bad value, not a missing flag). Agent contract gaps: - Five user-facing subcommands lacked SetAgentHelp: auth login / logout / list / status and chat. Added concise strings with error- code call-outs so agents can branch without parsing human strings. Helper extraction (≥3 callers): - text.KnowledgeDisplayName(fileName, title, id) — byte-identical formatter that was in both cmd/doc/list.go and cmd/search/docs.go. Takes fields directly so internal/text stays SDK-free. - cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the `Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK call sites. Sed-driven migration; off-pattern shapes in chat.go (used streamErr) and cmdutil/kb.go (in-package) hand-edited. Contract test gains a comment update: post-migration the dominant pattern is WrapHTTP which the AST scanner skips entirely (only NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs() bridge still covers the dynamic codes those paths can yield. UX consistency: - cmd/doc/list.go --page-size help now reads "Items per page (1..1000)" matching cmd/session/list.go. The bounds validation already enforced 1..1000; the help text was the last drift. Comment-discipline sweep: - Deleted the WHAT-only "*Options captures `weknora ...` flag state" docstring across 23 files (context, kb, auth, doc, session, search, chat, doctor, link). Where the line carried a real WHY clause (kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and dropped only the leading WHAT phrase. - Stripped third-party project-name attribution from inline comments and one user-visible flag-help string across ~40 files in cli/cmd and cli/internal (plus 4 test-file comments). Removed phrases like "Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style", "gcloud `--project`", "Stripe pattern", and the embedded GitHub URLs pointing at those projects. Behavioral descriptions and the WHY behind each comment are preserved; only the upstream-name attribution is gone. Inspiration / north-star references belong in cli/AGENTS.md (the design doc) and commit messages, not scattered through every file. Triggered by an audit round that surfaced several false / fragile parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no --name flag; "matches gcloud `--project` id-or-name" — gcloud's --project accepts ID only). Rather than fix them one by one, the whole category of in-comment external-project references was stripped uniformly.
2026-05-12 15:42:20 +00:00
// WrapHTTP wraps a transport / response error with the typed code derived
// from its HTTP shape (404 → resource.not_found, 401 → auth.unauthenticated,
// non-HTTP → network.error, …). Shortcut for the universal pattern
// `Wrapf(ClassifyHTTPError(err), err, format, args...)` used by every SDK
// call site - single source for the wrap-and-classify policy.
refactor(cli): v0.3 cross-cutting cleanup Cross-cutting findings surfaced by the branch-completion review. Perf bug: - Factory.Client closure was not memoized. Factory.ResolveKB internally calls f.Client() to resolve --kb name → id, then the command's RunE calls f.Client() again. Two SDK clients, two keyring reads, two AuthRetryTransport allocations per name-resolved invocation, with *independent* token state (a refresh in one was invisible to the other). Switched to sync.Once like Secrets already does. Silent bug bait: - cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the empty case; code returned CodeInputInvalidArgument. Aligned doc to code (present-but-empty is a bad value, not a missing flag). Agent contract gaps: - Five user-facing subcommands lacked SetAgentHelp: auth login / logout / list / status and chat. Added concise strings with error- code call-outs so agents can branch without parsing human strings. Helper extraction (≥3 callers): - text.KnowledgeDisplayName(fileName, title, id) — byte-identical formatter that was in both cmd/doc/list.go and cmd/search/docs.go. Takes fields directly so internal/text stays SDK-free. - cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the `Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK call sites. Sed-driven migration; off-pattern shapes in chat.go (used streamErr) and cmdutil/kb.go (in-package) hand-edited. Contract test gains a comment update: post-migration the dominant pattern is WrapHTTP which the AST scanner skips entirely (only NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs() bridge still covers the dynamic codes those paths can yield. UX consistency: - cmd/doc/list.go --page-size help now reads "Items per page (1..1000)" matching cmd/session/list.go. The bounds validation already enforced 1..1000; the help text was the last drift. Comment-discipline sweep: - Deleted the WHAT-only "*Options captures `weknora ...` flag state" docstring across 23 files (context, kb, auth, doc, session, search, chat, doctor, link). Where the line carried a real WHY clause (kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and dropped only the leading WHAT phrase. - Stripped third-party project-name attribution from inline comments and one user-visible flag-help string across ~40 files in cli/cmd and cli/internal (plus 4 test-file comments). Removed phrases like "Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style", "gcloud `--project`", "Stripe pattern", and the embedded GitHub URLs pointing at those projects. Behavioral descriptions and the WHY behind each comment are preserved; only the upstream-name attribution is gone. Inspiration / north-star references belong in cli/AGENTS.md (the design doc) and commit messages, not scattered through every file. Triggered by an audit round that surfaced several false / fragile parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no --name flag; "matches gcloud `--project` id-or-name" — gcloud's --project accepts ID only). Rather than fix them one by one, the whole category of in-comment external-project references was stripped uniformly.
2026-05-12 15:42:20 +00:00
//
// Use this for any error returned from a wire call. Stays paired with
// ClassifyHTTPErrorOutputs() in the acceptance/contract test, which
// enumerates the codes this helper can yield.
func WrapHTTP(cause error, format string, args ...any) *Error {
return Wrapf(ClassifyHTTPError(cause), cause, format, args...)
}
// FlagError signals user-visible flag/argument problems; the root command
refactor(cli): v0.3 cross-cutting cleanup Cross-cutting findings surfaced by the branch-completion review. Perf bug: - Factory.Client closure was not memoized. Factory.ResolveKB internally calls f.Client() to resolve --kb name → id, then the command's RunE calls f.Client() again. Two SDK clients, two keyring reads, two AuthRetryTransport allocations per name-resolved invocation, with *independent* token state (a refresh in one was invisible to the other). Switched to sync.Once like Secrets already does. Silent bug bait: - cmdutil.NormalizeHost docstring claimed CodeInputMissingFlag for the empty case; code returned CodeInputInvalidArgument. Aligned doc to code (present-but-empty is a bad value, not a missing flag). Agent contract gaps: - Five user-facing subcommands lacked SetAgentHelp: auth login / logout / list / status and chat. Added concise strings with error- code call-outs so agents can branch without parsing human strings. Helper extraction (≥3 callers): - text.KnowledgeDisplayName(fileName, title, id) — byte-identical formatter that was in both cmd/doc/list.go and cmd/search/docs.go. Takes fields directly so internal/text stays SDK-free. - cmdutil.WrapHTTP(cause, fmt, args...) *Error — replaces the `Wrapf(ClassifyHTTPError(err), err, ...)` pattern across 24 SDK call sites. Sed-driven migration; off-pattern shapes in chat.go (used streamErr) and cmdutil/kb.go (in-package) hand-edited. Contract test gains a comment update: post-migration the dominant pattern is WrapHTTP which the AST scanner skips entirely (only NewError/Wrapf selectors inspected); ClassifyHTTPErrorOutputs() bridge still covers the dynamic codes those paths can yield. UX consistency: - cmd/doc/list.go --page-size help now reads "Items per page (1..1000)" matching cmd/session/list.go. The bounds validation already enforced 1..1000; the help text was the last drift. Comment-discipline sweep: - Deleted the WHAT-only "*Options captures `weknora ...` flag state" docstring across 23 files (context, kb, auth, doc, session, search, chat, doctor, link). Where the line carried a real WHY clause (kb/delete, doc/delete, session/delete, kb/edit), kept the WHY and dropped only the leading WHAT phrase. - Stripped third-party project-name attribution from inline comments and one user-visible flag-help string across ~40 files in cli/cmd and cli/internal (plus 4 test-file comments). Removed phrases like "Mirrors `gh X`", "borrowed from lark-cli", "kubectl-style", "gcloud `--project`", "Stripe pattern", and the embedded GitHub URLs pointing at those projects. Behavioral descriptions and the WHY behind each comment are preserved; only the upstream-name attribution is gone. Inspiration / north-star references belong in cli/AGENTS.md (the design doc) and commit messages, not scattered through every file. Triggered by an audit round that surfaced several false / fragile parity claims (e.g. "Mirrors `gh repo edit`" — gh repo edit has no --name flag; "matches gcloud `--project` id-or-name" — gcloud's --project accepts ID only). Rather than fix them one by one, the whole category of in-comment external-project references was stripped uniformly.
2026-05-12 15:42:20 +00:00
// prints help on top of the message and exits 2.
type FlagError struct{ err error }
func (e *FlagError) Error() string { return e.err.Error() }
func (e *FlagError) Unwrap() error { return e.err }
// NewFlagError wraps err as a FlagError.
func NewFlagError(err error) error { return &FlagError{err: err} }
// SilentError skips printing to stderr; useful when a command has already
// emitted a fully-formatted message and exits non-zero.
var SilentError = errors.New("silent error (handled)")
// CancelError marks a user-cancelled operation (Ctrl-C / "no" at confirm).
var CancelError = errors.New("operation cancelled")
// Typed predicates - use these instead of comparing ErrorCode strings.
// They walk the error chain so wrapped errors still match.
// IsAuthError matches any auth.* code.
func IsAuthError(err error) bool { return matchPrefix(err, "auth.") }
// IsNotFound matches resource.not_found.
func IsNotFound(err error) bool { return matchCode(err, CodeResourceNotFound) }
// IsTransient matches network.* and server.timeout / rate_limited (worth retrying).
func IsTransient(err error) bool {
return matchPrefix(err, "network.") ||
matchCode(err, CodeServerTimeout) ||
matchCode(err, CodeServerRateLimited)
}
// IsAuthExpired matches auth.token_expired.
func IsAuthExpired(err error) bool { return matchCode(err, CodeAuthTokenExpired) }
// matchCode returns true if err (or anything it wraps) is a *Error with code == c.
// errors.As walks the wrap chain itself; the explicit unwrap loop is unnecessary.
func matchCode(err error, c ErrorCode) bool {
var e *Error
if !errors.As(err, &e) {
return false
}
return e.Code == c
}
// matchPrefix returns true if err (or anything it wraps) is a *Error whose code
// has the given namespace prefix (e.g. "auth.").
func matchPrefix(err error, prefix string) bool {
var e *Error
if !errors.As(err, &e) {
return false
}
return strings.HasPrefix(string(e.Code), prefix)
}
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
// serverNotFoundRE matches the WeKnora server's structured error-envelope body
// for the typed "not found" code (1003 = ErrNotFound). Server's 1007 is the
// generic ErrInternalServer bucket — including it would mis-classify every
// validation / DB failure (e.g. SQLSTATE 22001 "value too long") as
// resource.not_found, sending agents down the wrong recovery path.
// Matching the structured "code":1003 anchor avoids the free-substring false
// positive (e.g. a stack trace containing "config file not found").
var serverNotFoundRE = regexp.MustCompile(`"code":1003\b`)
// ClassifyHTTPStatus maps an HTTP status code to the canonical ErrorCode.
refactor(cli): delete envelope infrastructure, errors to stderr Removes the entire envelope machinery now that every success path emits bare JSON: - cli/internal/format/envelope.go (Envelope, Success, Failure, SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice, VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests. - cli/internal/format/filter.go envelope-specific helpers (WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter, filterDataPayload, filterObjectData); the reusable filterArrayItems / filterObjectKeys / writeJQ stay for bare.go. - cli/internal/cmdutil/exporter.go + tests (envelope-only). - cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody + operationRiskOf + Error.OperationRisk field + OperationRisk struct. Error path: all errors now go to stderr via cmdutil.PrintError in `code: message\nhint: ...` form, regardless of --json. Stdout stays empty (or holds the partial-success the command already wrote) so downstream `--json | jq` pipelines never have to filter error shapes out of the success stream. Typed exit codes (3 auth.* / 4 resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.* + network.* / 10 input.confirmation_required) carry the failure class for agents that branch on it. Acceptance contract: - envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden). - testdata/envelopes/ → testdata/wire/. - Error-path cases assert the typed code substring on stderr. - Orphan whoami.*.json goldens deleted. AGENTS.md + README.md rewritten for the bare-data contract: - Drop envelope schema section + dry-run rule. - Document bare JSON on stdout + `code: msg\nhint: …` on stderr. - ADR-3 reframed around bare data and why error separation matters for `--json | jq` pipelines. WriteJSONFiltered short-circuits to WriteJSON when both filters are empty (skip the marshal-buffer round-trip for the common case). Final review pass: - Fix wire-contract bug: `--json id,name` (space form) is broken by pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the field-discovery help text all switched to `--json=id,name`. - Fix `weknora api --jq` silently ignored: api.go now routes through WriteJSONFiltered with jopts.JQ. - AGENTS.md: drop the false claim that `auth logout` honors `-y` (logout is local-only with no ConfirmDestructive guard); list the actual destructive commands instead. - Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape (was still parsing `out["data"]` / `env["ok"]`). - Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated `format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields, jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the format import from 22 cmd/* files. - Delete single-caller `cmdutil.MustRequireFlag`; inline as `_ = cmd.MarkFlagRequired(...)` everywhere. - Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the only write command relying on runtime --name validation while `context add` already used the cobra-level mark. - `context use`: register `--json` / `--jq` (was always emitting JSON unconditionally with no human path and no flag — diverged from every other write command); human mode now prints `✓ Switched context to X (was Y)`. - Replace per-package `confirmPrompter` / `scriptedConfirm` / `errPrompter` test doubles with `testutil.ConfirmPrompter`. - Rename `chatService` → `ChatService` (export to match siblings `ListService` / `ViewService`); rename `printUploadSuccess` → `renderUploadSuccess` (siblings use `render*`). - `defaultHint(CodeResourceNotFound)`: drop the hardcoded "list available with `weknora kb list`" — misleading on agent / doc / session 404. Replaced with "verify the resource ID and try again". - Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only" historical tags from production comments and a few test descriptions.
2026-05-14 17:51:11 +00:00
// Single source of truth so error codes stay aligned whether the failure
// was detected by the SDK (string-formatted error) or by the CLI directly
// (e.g. raw passthrough reading resp.StatusCode).
func ClassifyHTTPStatus(status int) ErrorCode {
switch {
case status == 401:
return CodeAuthUnauthenticated
case status == 403:
return CodeAuthForbidden
case status == 404:
return CodeResourceNotFound
case status == 409:
return CodeResourceAlreadyExists
case status == 429:
return CodeServerRateLimited
case status >= 500:
return CodeServerError
case status >= 400:
return CodeInputInvalidArgument
}
return CodeServerError
}
// ClassifyHTTPError maps an SDK HTTP error to the canonical ErrorCode by
// parsing the "HTTP error <status>: ..." message format the SDK currently
// emits (client.parseResponse). Until the SDK exposes a typed APIError this
// is the lowest-friction way to surface 401/404/429/etc. as the right
refactor(cli): delete envelope infrastructure, errors to stderr Removes the entire envelope machinery now that every success path emits bare JSON: - cli/internal/format/envelope.go (Envelope, Success, Failure, SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice, VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests. - cli/internal/format/filter.go envelope-specific helpers (WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter, filterDataPayload, filterObjectData); the reusable filterArrayItems / filterObjectKeys / writeJQ stay for bare.go. - cli/internal/cmdutil/exporter.go + tests (envelope-only). - cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody + operationRiskOf + Error.OperationRisk field + OperationRisk struct. Error path: all errors now go to stderr via cmdutil.PrintError in `code: message\nhint: ...` form, regardless of --json. Stdout stays empty (or holds the partial-success the command already wrote) so downstream `--json | jq` pipelines never have to filter error shapes out of the success stream. Typed exit codes (3 auth.* / 4 resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.* + network.* / 10 input.confirmation_required) carry the failure class for agents that branch on it. Acceptance contract: - envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden). - testdata/envelopes/ → testdata/wire/. - Error-path cases assert the typed code substring on stderr. - Orphan whoami.*.json goldens deleted. AGENTS.md + README.md rewritten for the bare-data contract: - Drop envelope schema section + dry-run rule. - Document bare JSON on stdout + `code: msg\nhint: …` on stderr. - ADR-3 reframed around bare data and why error separation matters for `--json | jq` pipelines. WriteJSONFiltered short-circuits to WriteJSON when both filters are empty (skip the marshal-buffer round-trip for the common case). Final review pass: - Fix wire-contract bug: `--json id,name` (space form) is broken by pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the field-discovery help text all switched to `--json=id,name`. - Fix `weknora api --jq` silently ignored: api.go now routes through WriteJSONFiltered with jopts.JQ. - AGENTS.md: drop the false claim that `auth logout` honors `-y` (logout is local-only with no ConfirmDestructive guard); list the actual destructive commands instead. - Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape (was still parsing `out["data"]` / `env["ok"]`). - Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated `format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields, jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the format import from 22 cmd/* files. - Delete single-caller `cmdutil.MustRequireFlag`; inline as `_ = cmd.MarkFlagRequired(...)` everywhere. - Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the only write command relying on runtime --name validation while `context add` already used the cobra-level mark. - `context use`: register `--json` / `--jq` (was always emitting JSON unconditionally with no human path and no flag — diverged from every other write command); human mode now prints `✓ Switched context to X (was Y)`. - Replace per-package `confirmPrompter` / `scriptedConfirm` / `errPrompter` test doubles with `testutil.ConfirmPrompter`. - Rename `chatService` → `ChatService` (export to match siblings `ListService` / `ViewService`); rename `printUploadSuccess` → `renderUploadSuccess` (siblings use `render*`). - `defaultHint(CodeResourceNotFound)`: drop the hardcoded "list available with `weknora kb list`" — misleading on agent / doc / session 404. Replaced with "verify the resource ID and try again". - Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only" historical tags from production comments and a few test descriptions.
2026-05-14 17:51:11 +00:00
// typed code instead of every server-side problem collapsing to
// server.error.
//
// Returns CodeNetworkError when err is not an HTTP error (transport / DNS),
// and CodeServerError when the status can't be parsed.
func ClassifyHTTPError(err error) ErrorCode {
if err == nil {
return ""
}
msg := err.Error()
rest, ok := strings.CutPrefix(msg, "HTTP error ")
if !ok {
return CodeNetworkError
}
end := strings.IndexByte(rest, ':')
if end <= 0 {
return CodeServerError
}
status, perr := strconv.Atoi(rest[:end])
if perr != nil {
return CodeServerError
}
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
base := ClassifyHTTPStatus(status)
// Server-side 500-misclassification rescue: some servers return HTTP 500
// for logical "not found" cases (e.g. code 1007 "knowledge base not found",
// code 1003 "Knowledge not found") instead of 404. Match the server's known
// error-code envelope precisely to avoid false-positive rescues on generic
// 500 bodies that happen to contain "not found" (e.g. "config file not found
// in stack trace"). The free-substring match would over-match.
body := rest[end+1:]
if base == CodeServerError && serverNotFoundRE.MatchString(body) {
return CodeResourceNotFound
}
return base
}
// AllCodes returns the registered error code set.
// Used by acceptance/contract/errorcodes_test.go to validate that every code
// referenced in cli/cmd/ is present here. Update this list whenever a new
// ErrorCode constant is added above.
func AllCodes() []ErrorCode {
return []ErrorCode{
// auth
CodeAuthUnauthenticated, CodeAuthTokenExpired, CodeAuthBadCredential,
CodeAuthForbidden, CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch,
// resource
CodeResourceNotFound, CodeResourceAlreadyExists, CodeResourceLocked,
// input
feat(cli): add agent-first affordance — envelope, exit-10, --dry-run Borrows the lark-cli agent-affordance model (https://github.com/larksuite/cli/blob/main/AGENTS.md + skills/lark-shared/SKILL.md) so weknora is designed to be agent-friendly: error messages, output format, and flag design follow conventions agents can rely on. cli/AGENTS.md (operational reference for LLM agents invoking weknora): Public document covering envelope schema, exit-code protocol (0/1/2/10/130), stdout/stderr separation, and behavioral rules. Sensitive commands (\`context use\`, \`kb delete\`, \`doc delete\`, \`init\`) gain "AI agents:" paragraphs in their cobra Long descriptions so guidance shows in --help. format.Envelope schema additions: Risk per-operation classification (read / write / high-risk-write + action description), populated by write commands on both success and failure paths. Notice system advisories (CLI update available, server-CLI version skew); type defined, emit sites land in v0.3. DryRun marker for envelopes returned from --dry-run preview paths. RiskLevel constants realigned to lark's taxonomy: read / write / high-risk-write (was: read / mutating / destructive — not yet wired by any command). cmdutil.Error gains OperationRisk; PrintErrorEnvelope auto-attaches it to envelope.Risk so destructive failure paths surface uniformly. Exit-10 confirmation protocol: New ErrorCode \`input.confirmation_required\` mapped to exit code 10 in cmdutil.ExitCode. ConfirmDestructive now returns this code (with OperationRisk attached) when stdout is non-TTY or --json was set, with -y/--yes absent. Previous behavior — silent proceed in non-TTY — was unsafe: scripts and agents could delete resources with no explicit approval. Three test cases re-pinned around the new contract. This is a wire-contract change for any caller who relied on silent proceed; v0.0/v0.1 had no destructive commands, so the blast radius is contained to v0.2 itself. --dry-run global flag: cmd write paths (kb create/delete, doc upload/delete, api POST/PUT/PATCH/ DELETE) check cmdutil.IsDryRun(cmd) and skip the SDK call, emitting an envelope with dry_run=true plus a Risk classification. Read commands ignore --dry-run by design (no side effect to preview). Human-mode prints \`[dry-run] would <action>\` to stdout. Command discovery: agents introspect via the existing \`--help\` surface (consistent with gh / kubectl / aws / gcloud / terraform — none of them ship a CLI-tree self-description command). An earlier draft added a \`weknora schema\` reflection command; dropped after a mainstream survey found it has no stable analog (lark-cli's schema describes Lark API methods, not its own CLI tree). Tests: 27 cli packages pass at this commit. Added two new tests covering envelope.risk and envelope._notice serialization.
2026-05-10 18:44:34 +00:00
CodeInputInvalidArgument, CodeInputMissingFlag, CodeInputConfirmationRequired,
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
CodeInputUnknownSubcommand,
// server / network
CodeServerError, CodeServerTimeout, CodeServerRateLimited,
CodeServerIncompatibleVersion, CodeNetworkError,
// local
CodeLocalConfigCorrupt, CodeLocalKeychainDenied, CodeLocalFileIO,
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
CodeLocalUnimplemented, CodeLocalProfileNotFound,
CodeKBIDRequired, CodeKBNotFound,
refactor(cli): align command surface with mainstream conventions Empirical mainstream-CLI surveys (gh / kubectl / aws / gcloud / stripe / flyctl / terraform / vercel / netlify / lark) drove five alignment fixes — each replaces a weknora-only design choice that mainstream CLIs do not share. No backwards-compat shims; the CLI has no v0.1 users yet. 1. Single --kb flag (was --kb-id + --kb mutually exclusive) Survey: 0/7 mainstream CLIs use two parallel flags for "by id" vs "by name". Single flag (gh -R, gcloud --project) or positional (kubectl, stripe, terraform). Closest analog — gcloud --project — collapses identifier types onto one flag. Now: every command exposes one --kb flag; client-side prefix detection (cmdutil.IsKBID looks for "kb_") routes id-form values through directly and name-form values through ListKnowledgeBases. Mirrors gcloud --project's id-or-name auto-detection. Touched: search, chat, doc list / upload / delete, link. Factory.ResolveKB chain trimmed from 5 levels to 4. 2. link supersedes init Survey: only vercel and netlify ship both `init` AND `link` as siblings, and they keep them semantically distinct. weknora's pair wrote the same .weknora/project.yaml file with the same meaning, differentiated only by interactivity — that's a flag concern, not a command concern. Now: cmd/init/ deleted. cmd/link absorbs the interactive flow: - link --kb <id-or-name> → non-interactive write - link on a TTY → interactive prompt (lists KBs) - link non-TTY without --kb → CodeKBIDRequired Always overwrites silently (matches vercel link / netlify link / kubectl apply rather than git init's refuse-if-exists). Dead code purged: --force flag, CodeProjectAlreadyLinked error code. 3. whoami dropped Survey: 7/7 mainstream CLIs ship exactly one identity command — never both a status and a whoami. gh / gcloud / stripe pick status (config + live API); aws / kubectl / flyctl pick whoami (live API). weknora's auth status was already a superset of whoami (host + context + user + email + tenant_id + tenant_name vs user_id + tenant_id), so dropping whoami preserves all functionality and aligns with the gh / gcloud / stripe form. 4. kb get alias dropped `view` was already primary (gh repo view / gh pr view convention); `get` was kept as a cobra alias for v0.0/v0.1 callers. With no v0.0/v0.1 users to break, the alias is just noise on the command surface. Acceptance contract envelope cases renamed kb_get.* → kb_view.*; goldens renamed in lockstep. 5. api refactored to gh shape (-X/--method, default GET, auto-POST) gh CLI's signature is `gh api <endpoint> [--method M]` — single positional path, method as a flag, default GET, auto-promoted to POST when a body is supplied. weknora's previous `api <method> <path>` inverted this and forced the method to be passed even for GET — a needless deviation from our declared north star. Now: `api <path> [-X METHOD] [--data ...]`. Exit-10 protocol on the DELETE escape-hatch is preserved; -X DELETE still hits ConfirmDestructive when -y absent. Plus: AGENTS.md gains an explicit note that `doctor` is a deliberate divergence from gh / lark — borrowed from `flutter doctor` / `brew doctor` because RAG deployments routinely break on misconfigured embeddings / storage / credentials and a 4-status structured envelope is the cleanest surface for it. Tests: 24 cli packages green (was 26 in PR-14; init + whoami packages removed). Acceptance contract envelope cases for whoami removed, kb_get → kb_view renamed, search args / mock path updated for the kb_<id> form. e2e harness flag args updated. Factory.ResolveKB tests rewritten for the single-flag shape. api_test driver updated for the positional-path / -X-method shape.
2026-05-10 18:44:49 +00:00
CodeProjectLinkCorrupt,
CodeUserAborted, CodeUploadFileNotFound,
CodeSSEStreamAborted, CodeSessionCreateFailed,
// operation
CodeOperationTimeout, CodeOperationFailed, CodeOperationCancelled,
// mcp
CodeMCPReadonlyMode, CodeMCPToolNotAllowed, CodeMCPSchemaUnknown,
}
}
// ClassifyHTTPErrorOutputs returns every code that ClassifyHTTPError can return.
// Bridges the AST-friendly literal model with the dynamic switch inside
// ClassifyHTTPError. errorcodes_test.go uses this to seed the "referenced codes"
// set without trying to AST-introspect a function-call expression.
//
// IMPORTANT: keep in sync with the switch in ClassifyHTTPError.
func ClassifyHTTPErrorOutputs() []ErrorCode {
return []ErrorCode{
CodeAuthUnauthenticated, // 401
CodeAuthForbidden, // 403
CodeResourceNotFound, // 404
CodeResourceAlreadyExists, // 409
CodeServerRateLimited, // 429
CodeServerError, // 5xx / parse-failure / default
CodeInputInvalidArgument, // 4xx (else)
CodeNetworkError, // non-HTTP error
}
}
refactor(cli): symmetric envelope infrastructure (supersedes e623e820) Re-introduce the agent-first symmetric envelope deleted in commit e623e820 (2026-05-15). Under the v0.7 constraint that AI agents are primary consumers, the bare-JSON shape can't carry protocol channels (_notice / risk / meta / request_id / profile) that agents need. Errors-on-stderr and typed exit codes from e623e820 are preserved; the envelope wraps the success/error payloads on top. - cli/internal/output/envelope.go (new): Envelope / ErrorEnvelope / Meta / ErrDetail / RiskDetail structs; WriteEnvelope + WriteErrorEnvelope writers; PendingNotice plumbing for the open-map _notice channel (reserved infra; producer wiring planned for v0.8). - cli/internal/output/envelope_test.go (new): 7 tests covering success / error / TTY indent / Notice / Risk shapes. - cmdutil.Error extended with RetryCommand (directly-executable argv distinct from prose Hint), RetryAfterSeconds (HTTP Retry-After), *RiskInfo (nested level+action; ErrInternalServer- vs-NotFound distinction), Detail (open structured payload), Silent (suppress stderr emit while preserving Code for ExitCode). - ErrorToDetail single source of envelope.error construction; reused by stderr PrintError, MCP StructuredContent, and batch per-item error path. - WithHint / WithRetryCommand / WithRetryAfter / WithDetail / WithRisk builders. IsCancelled helper. AsError unwrap helper. - defaultHint covers ~21 codes; defaultRetryCommand symmetric counterpart for 6 keyway codes. DefaultHint / DefaultRetryCommand exported wrappers for cross-package callers. - ClassifyHTTPError tightened: rescues HTTP 500 with structured server-side code 1003 (ErrNotFound) into resource.not_found. Server's generic 1007 (ErrInternalServer) bucket stays as server.error — including it would mis-route validation failures (e.g. SQLSTATE 22001) as not-found. - PrintError dual-mode: text/human → prose with code:msg / hint / retry lines; json/ndjson → envelope on stderr. Mode pinned by root PersistentPreRunE via SetFormatMode. resolveFormatEarly() scans argv before cobra dispatch so cobra-side validators (unknown flag, arg-count) still surface as envelope when --format json is in effect. Silent typed errors short-circuit the stderr emit. FlagError mapped to input.invalid_argument for the envelope (exit code stays 2 via FlagError class). - Unknown-subcommand guard installed recursively at the root: parents with subcommands but no Run/RunE get a typed RunE that emits input.unknown_subcommand envelope with detail.{unknown, command_path, available[]} and retry_command "<parent> --help". cobra.ArbitraryArgs bypasses legacyArgs validation so the guard receives unmatched argv. - cmdutil.Error.Error() returns "<code>: <message>[: <cause>]" for chain debugging; ErrorToDetail strips the code prefix from envelope.message since the separate type field carries it (prevents the doubled-prefix "code: code: ..." that agents would see). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §0 / §4
2026-05-21 10:40:06 +00:00
// IsCancelled reports whether err is a context cancellation, either via
// the context itself or via wrapped CancelError / context.Canceled /
// context.DeadlineExceeded. Used by streaming commands to distinguish
// SIGINT-driven shutdown from real errors.
func IsCancelled(ctx context.Context, err error) bool {
if errors.Is(err, context.Canceled) {
return true
}
if ctx.Err() == context.Canceled {
return true
}
return false
}