WeKnora/cli/internal/cmdutil/kb.go

55 lines
2.0 KiB
Go
Raw Normal View History

package cmdutil
import (
"context"
"fmt"
fix(cli): correct KB id detection, SSE terminal-frame, and CI test isolation Three defects surfaced during end-to-end RAG verification — the first two block real chat usage, the third makes Linux CI flaky: 1. KB id detection — `IsKBID` was checking `strings.HasPrefix(s, "kb_")`, but WeKnora generates KB ids as bare UUIDs (internal/types/knowledge_base.go: `uuid.New().String()` stored in a `varchar(36)` column). Real ids therefore fell through to the name-resolution path: $ weknora chat ... --kb a32a63ff-fb36-4874-bcaa-30f48570a694 Error: knowledge base not found: a32a63ff-... Switched the discriminator to a UUID regex (`^[0-9a-fA-F]{8}-…-[0-9a-fA-F]{12}$`). KB names are arbitrary user-supplied strings, so the canonical 8-4-4-4-12 form is an unambiguous signal. Mirrors gcloud `--project`'s id-vs-name detection. 2. SSE terminal-frame — the accumulator's `Append` was gating finalization on `r.Done`, but the server's KnowledgeQAStream protocol emits a leading `agent_query` frame with `done=true` to deliver session + message metadata *before* the answer fragments arrive: event: message data: {"response_type":"agent_query","content":"","done":true,…} event: message data: {"response_type":"answer","content":"你好","done":false} … event: message data: {"response_type":"complete","content":"","done":true} The accumulator therefore flipped to `finished=true` on frame #1 and discarded every subsequent answer fragment — `weknora chat … --json` returned `answer: ""` even though the LLM reported completion_tokens > 0. Fixed: terminate only on `response_type == complete`. References still captured opportunistically (they may arrive on a dedicated `references` event before the terminator). 3. doctor credential_storage CI isolation — the check probes the real OS keyring via `secrets.NewBestEffortStore()`: present on macOS dev machines → StatusOK; absent on Linux CI runners without libsecret / Gnome-Keyring → StatusWarn ("falling back to file store"). That host-dependence was leaking into two test classes that assumed StatusOK: * cmd/doctor/doctor_test.go: TestDoctor_AllOK and TestDoctor_NoConfig_StillRunsCredentialStorage already had a withCredStoreFactory seam but didn't use it. Added the pin. * acceptance/contract/envelope_test.go: doctor.success_offline and doctor.error_network golden cases. The contract test runs through the cobra tree in-process and shares cmd/doctor's package-level credStoreFactory var — but couldn't reach it because the existing seam was unexported. Fix: export `doctor.SetCredStoreFactoryForTest(fn) (restore func())` for out-of-package tests; acceptance/contract/helpers_test.go adds a TestMain that pins the factory to a MemStore-returning closure for the whole suite (MemStore is neither *FileStore nor a real keyring, so doctor's type-switch hits StatusOK). Production stays at secrets.NewBestEffortStore — only the test hook is now reachable from across packages. Test fixtures and goldens that used the old `kb_xxx` literals or `Done: true` terminators were rewritten to use real UUIDs and `ResponseType: ResponseTypeComplete` respectively. Per-command --help text and Long descriptions / Examples now show a UUID rather than `kb_…` so users see the correct shape from the start. New TestAccumulator_IgnoresAgentQueryDone pins the SSE terminator bug so it can't regress. Tests: 24 cli packages green on macOS dev + Linux/macOS/Windows CI matrix. Verified end-to-end against a live WeKnora server: `weknora chat "..." --kb <UUID> --no-stream --json` returns the full LLM answer in the envelope, live token streaming in TTY mode works, and the credential_storage check renders deterministic envelopes across hosts.
2026-05-10 20:14:27 +00:00
"regexp"
sdk "github.com/Tencent/WeKnora/client"
)
fix(cli): correct KB id detection, SSE terminal-frame, and CI test isolation Three defects surfaced during end-to-end RAG verification — the first two block real chat usage, the third makes Linux CI flaky: 1. KB id detection — `IsKBID` was checking `strings.HasPrefix(s, "kb_")`, but WeKnora generates KB ids as bare UUIDs (internal/types/knowledge_base.go: `uuid.New().String()` stored in a `varchar(36)` column). Real ids therefore fell through to the name-resolution path: $ weknora chat ... --kb a32a63ff-fb36-4874-bcaa-30f48570a694 Error: knowledge base not found: a32a63ff-... Switched the discriminator to a UUID regex (`^[0-9a-fA-F]{8}-…-[0-9a-fA-F]{12}$`). KB names are arbitrary user-supplied strings, so the canonical 8-4-4-4-12 form is an unambiguous signal. Mirrors gcloud `--project`'s id-vs-name detection. 2. SSE terminal-frame — the accumulator's `Append` was gating finalization on `r.Done`, but the server's KnowledgeQAStream protocol emits a leading `agent_query` frame with `done=true` to deliver session + message metadata *before* the answer fragments arrive: event: message data: {"response_type":"agent_query","content":"","done":true,…} event: message data: {"response_type":"answer","content":"你好","done":false} … event: message data: {"response_type":"complete","content":"","done":true} The accumulator therefore flipped to `finished=true` on frame #1 and discarded every subsequent answer fragment — `weknora chat … --json` returned `answer: ""` even though the LLM reported completion_tokens > 0. Fixed: terminate only on `response_type == complete`. References still captured opportunistically (they may arrive on a dedicated `references` event before the terminator). 3. doctor credential_storage CI isolation — the check probes the real OS keyring via `secrets.NewBestEffortStore()`: present on macOS dev machines → StatusOK; absent on Linux CI runners without libsecret / Gnome-Keyring → StatusWarn ("falling back to file store"). That host-dependence was leaking into two test classes that assumed StatusOK: * cmd/doctor/doctor_test.go: TestDoctor_AllOK and TestDoctor_NoConfig_StillRunsCredentialStorage already had a withCredStoreFactory seam but didn't use it. Added the pin. * acceptance/contract/envelope_test.go: doctor.success_offline and doctor.error_network golden cases. The contract test runs through the cobra tree in-process and shares cmd/doctor's package-level credStoreFactory var — but couldn't reach it because the existing seam was unexported. Fix: export `doctor.SetCredStoreFactoryForTest(fn) (restore func())` for out-of-package tests; acceptance/contract/helpers_test.go adds a TestMain that pins the factory to a MemStore-returning closure for the whole suite (MemStore is neither *FileStore nor a real keyring, so doctor's type-switch hits StatusOK). Production stays at secrets.NewBestEffortStore — only the test hook is now reachable from across packages. Test fixtures and goldens that used the old `kb_xxx` literals or `Done: true` terminators were rewritten to use real UUIDs and `ResponseType: ResponseTypeComplete` respectively. Per-command --help text and Long descriptions / Examples now show a UUID rather than `kb_…` so users see the correct shape from the start. New TestAccumulator_IgnoresAgentQueryDone pins the SSE terminator bug so it can't regress. Tests: 24 cli packages green on macOS dev + Linux/macOS/Windows CI matrix. Verified end-to-end against a live WeKnora server: `weknora chat "..." --kb <UUID> --no-stream --json` returns the full LLM answer in the envelope, live token streaming in TTY mode works, and the credential_storage check renders deterministic envelopes across hosts.
2026-05-10 20:14:27 +00:00
// uuidPattern matches the canonical 8-4-4-4-12 UUID form. WeKnora's KB ids
// are uuid.New().String() output stored as varchar(36); names are arbitrary
// user-supplied strings, so format-detection is unambiguous.
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
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
// IsKBID reports whether s looks like a KB id. Used by Factory.ResolveKB and
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
// any caller that accepts a single id-or-name selector value (id vs name
// auto-detection).
fix(cli): correct KB id detection, SSE terminal-frame, and CI test isolation Three defects surfaced during end-to-end RAG verification — the first two block real chat usage, the third makes Linux CI flaky: 1. KB id detection — `IsKBID` was checking `strings.HasPrefix(s, "kb_")`, but WeKnora generates KB ids as bare UUIDs (internal/types/knowledge_base.go: `uuid.New().String()` stored in a `varchar(36)` column). Real ids therefore fell through to the name-resolution path: $ weknora chat ... --kb a32a63ff-fb36-4874-bcaa-30f48570a694 Error: knowledge base not found: a32a63ff-... Switched the discriminator to a UUID regex (`^[0-9a-fA-F]{8}-…-[0-9a-fA-F]{12}$`). KB names are arbitrary user-supplied strings, so the canonical 8-4-4-4-12 form is an unambiguous signal. Mirrors gcloud `--project`'s id-vs-name detection. 2. SSE terminal-frame — the accumulator's `Append` was gating finalization on `r.Done`, but the server's KnowledgeQAStream protocol emits a leading `agent_query` frame with `done=true` to deliver session + message metadata *before* the answer fragments arrive: event: message data: {"response_type":"agent_query","content":"","done":true,…} event: message data: {"response_type":"answer","content":"你好","done":false} … event: message data: {"response_type":"complete","content":"","done":true} The accumulator therefore flipped to `finished=true` on frame #1 and discarded every subsequent answer fragment — `weknora chat … --json` returned `answer: ""` even though the LLM reported completion_tokens > 0. Fixed: terminate only on `response_type == complete`. References still captured opportunistically (they may arrive on a dedicated `references` event before the terminator). 3. doctor credential_storage CI isolation — the check probes the real OS keyring via `secrets.NewBestEffortStore()`: present on macOS dev machines → StatusOK; absent on Linux CI runners without libsecret / Gnome-Keyring → StatusWarn ("falling back to file store"). That host-dependence was leaking into two test classes that assumed StatusOK: * cmd/doctor/doctor_test.go: TestDoctor_AllOK and TestDoctor_NoConfig_StillRunsCredentialStorage already had a withCredStoreFactory seam but didn't use it. Added the pin. * acceptance/contract/envelope_test.go: doctor.success_offline and doctor.error_network golden cases. The contract test runs through the cobra tree in-process and shares cmd/doctor's package-level credStoreFactory var — but couldn't reach it because the existing seam was unexported. Fix: export `doctor.SetCredStoreFactoryForTest(fn) (restore func())` for out-of-package tests; acceptance/contract/helpers_test.go adds a TestMain that pins the factory to a MemStore-returning closure for the whole suite (MemStore is neither *FileStore nor a real keyring, so doctor's type-switch hits StatusOK). Production stays at secrets.NewBestEffortStore — only the test hook is now reachable from across packages. Test fixtures and goldens that used the old `kb_xxx` literals or `Done: true` terminators were rewritten to use real UUIDs and `ResponseType: ResponseTypeComplete` respectively. Per-command --help text and Long descriptions / Examples now show a UUID rather than `kb_…` so users see the correct shape from the start. New TestAccumulator_IgnoresAgentQueryDone pins the SSE terminator bug so it can't regress. Tests: 24 cli packages green on macOS dev + Linux/macOS/Windows CI matrix. Verified end-to-end against a live WeKnora server: `weknora chat "..." --kb <UUID> --no-stream --json` returns the full LLM answer in the envelope, live token streaming in TTY mode works, and the credential_storage check renders deterministic envelopes across hosts.
2026-05-10 20:14:27 +00:00
func IsKBID(s string) bool { return uuidPattern.MatchString(s) }
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
// KBLister is the narrow SDK surface ResolveKBNameToID depends on. The
// production *sdk.Client satisfies it; tests inject fakes without standing
// up an HTTP server.
type KBLister interface {
ListKnowledgeBases(ctx context.Context) ([]sdk.KnowledgeBase, error)
}
feat(cli): search verb-noun subtree (chunks/kb/docs/sessions) Roadmap 3-1. Verb-noun shape borrowed from gh search (gh search repos / code / commits / issues / prs verified against the gh manual). Subcommands: - `search chunks "<q>" --kb X` — hybrid retrieval (RAG search). - `search kb "<q>"` — case-insensitive substring match across KB names and descriptions; sorted by name length (shortest hits first). - `search docs "<q>" --kb X` — pages through ListKnowledge filtering by title / file_name; stops once --limit matches are found. - `search sessions "<q>"` — pages through GetSessionsByTenant filtering by title / description. kb / docs / sessions are client-side filters because the server has no fuzzy search endpoint for any of them. ListKnowledgeBases returns the full tenant catalog in one call; the doc/session walkers chunk at 200 per request and stop early on limit. The parent `search` command is a pure dispatcher — there is no bare- positional form (no `weknora search "<q>"`). Cleanups surfaced by the post-commit reviewer round: - UX consistency: search docs's displayDocName ordered Title → FileName → "-", while doc list's displayName uses FileName → Title → ID. Same Knowledge rendered differently across commands. Aligned search docs on doc list's existing FileName-first convention. - cmdutil.ResolveKBFlag(ctx, lister, raw) — extracted the `IsKBID ? raw : ResolveKBNameToID` block duplicated across chunks and docs. - text.ContainsFold(needle, fields...) — replaces inline `strings.Contains(strings.ToLower(field), needle)` patterns. 37 unit tests across chunks/kb/docs/sessions plus the parent registration smoke-test. Roadmap: 3-1.
2026-05-12 15:38:01 +00:00
// ResolveKBFlag interprets a raw --kb value (id or name) and returns the
// canonical id. Pass-through when raw already looks like an id; otherwise
// list and match by name. Shared by every command that takes a --kb flag
// directly (search chunks/docs, doc download, link …) so the id-or-name
// policy never drifts.
func ResolveKBFlag(ctx context.Context, lister KBLister, raw string) (string, error) {
if IsKBID(raw) {
return raw, nil
}
return ResolveKBNameToID(ctx, lister, raw)
}
// ResolveKBNameToID looks up a knowledge base by name and returns its ID.
// Used by `link` and `Factory.ResolveKB` - a single lookup so the match
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
// policy (currently exact case-sensitive) lives in one place.
func ResolveKBNameToID(ctx context.Context, lister KBLister, name string) (string, error) {
kbs, err := lister.ListKnowledgeBases(ctx)
if err != nil {
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
return "", WrapHTTP(err, "list knowledge bases")
}
for _, kb := range kbs {
if kb.Name == name {
return kb.ID, nil
}
}
return "", NewError(CodeKBNotFound, fmt.Sprintf("knowledge base not found: %s", name))
}