import { join, resolve } from "node:path"; import { createAiRegistry, type AiConfig } from "@askdb/ai"; import type { AskDbLogger } from "@askdb/core"; import { ASKDB_RAG_EMBEDDERS, ASKDB_RAG_STORES, getAskDbRuntimeConfig, type AskDbRagEmbedder, type AskDbRagStore, type AskDbRuntimeConfig, } from "@askdb/config"; import { aiSdkEmbedderId, buildSchemaIndex, checkIndexMatches, createAiSdkEmbedder, createFileStore, createMemoryStore, createPgvectorStore, detectEmbeddingDimensions, loadChunkerSourcesFromDir, PgvectorDimensionMismatchError, type ChunkType, type Embedder, type Filter, type PgvectorIndexStrategy, type QueryResult, type VectorStore, } from "@askdb/rag"; import { EXPERIMENTAL_ADR_URL, runCommand, type CommandSpec, type Flag } from "./command.js"; import { labelled, showable } from "./error-values.js"; import { createCliLogger, loggingFlags, type CliLoggingFlags } from "./logger.js"; // Every built-in provider is registered and loads its @ai-sdk/* package only when first used, // so ai.embedding alone selects the provider. const ai = createAiRegistry(); /** The removed aliases of `ai` (#811), each refused with its replacement. */ const REMOVED_EMBEDDERS: Readonly> = { openai: '--embedder openai was removed: use --embedder ai, with rag.embedder: "ai" and ai.embedding: { provider: "openai", model } in askdb.config.*.', "ai-sdk": '--embedder ai-sdk was removed: use --embedder ai, with rag.embedder: "ai" and ai.embedding in askdb.config.*.', }; function isCliEmbedder(value: string): value is AskDbRagEmbedder { return (ASKDB_RAG_EMBEDDERS as readonly string[]).includes(value); } function isCliStore(value: string): value is AskDbRagStore { return (ASKDB_RAG_STORES as readonly string[]).includes(value); } /** The chunk types `--types` accepts. A record, so a new `ChunkType` doesn't compile until it's listed here. */ const CHUNK_TYPES: Record = { table: true, column: true, cql: true, question: true, concept: true, relationship: true, "tenant-policy": true, }; function isChunkType(value: string): value is ChunkType { return Object.hasOwn(CHUNK_TYPES, value); } /** The mock embedder is AskDB's own, so its width is the only one the CLI knows. */ const DEFAULT_MOCK_DIMENSIONS = 64; const DEFAULT_PGVECTOR_TABLE = "askdb_rag_chunks"; const RAG_COMMANDS = ["index", "query", "setup-store"] as const; type RagCommand = (typeof RAG_COMMANDS)[number]; function isRagCommand(value: string): value is RagCommand { return (RAG_COMMANDS as readonly string[]).includes(value); } type CliOptions = CliLoggingFlags & { command?: RagCommand; schemaDir?: string; store?: AskDbRagStore; embedder?: AskDbRagEmbedder; question?: string; k?: number; pgUrl?: string; pgTable?: string; dimensions?: number; filterTypes?: ChunkType[]; filePath?: string; embedderModel?: string; force?: boolean; }; export async function runRagCli(argv: readonly string[]): Promise { // With no arguments `askdb rag` prints its help, so it works without a config. return runCommand(ragCommand(), argv.length === 0 ? ["--help"] : argv); } /** `askdb rag [schema-dir]`. Every command reads askdb.config. */ export function ragCommand(): CommandSpec { return { name: "rag", summary: "Chunk, embed, and query a schema artifact directory (experimental)", usage: RAG_USAGE, notes: ragNotes(), flags: RAG_FLAGS, positional(opts, value, index) { if (index === 0) { if (!isRagCommand(value)) { throw new Error(`${labelled("Unknown command", value)} (expected 'index', 'query', or 'setup-store')`); } opts.command = value; return; } if (index > 1) { // Not repeated: a stray value can be a secret, such as a connection string without its flag. throw new Error( "Unexpected extra argument: askdb rag takes one [schema-dir]. Pass other values with their flag, such as --pg-url .", ); } // Failing on it as a path would print it, password included. if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) { throw new Error("The [schema-dir] argument looks like a connection string; pass a connection string with --pg-url."); } opts.schemaDir = value; }, initial: () => ({}), check(opts) { if (!opts.command) throw new Error("Missing command (expected 'index', 'query', or 'setup-store')"); }, needsConfig: () => true, async run(opts) { const runtimeConfig = getAskDbRuntimeConfig(); if (opts.command === "setup-store") return runSetupStore(opts, runtimeConfig); const logger = createCliLogger(opts, runtimeConfig); if (opts.command === "index") return runIndex(opts, logger, runtimeConfig); return runQuery(opts, logger, runtimeConfig); }, }; } async function runIndex(opts: CliOptions, logger: AskDbLogger, runtimeConfig: AskDbRuntimeConfig): Promise { const schemaDir = resolveSchemaDir(opts, runtimeConfig); const sources = loadChunkerSourcesFromDir(schemaDir); const storeConfig = resolveStoreConfig(opts, runtimeConfig, schemaDir); const embedderConfig = resolveEmbedderConfig(opts, runtimeConfig); const embedder = await createEmbedder(embedderConfig); // A new pgvector table needs its width up front: the requested one, else the model's own. The // memory and file stores learn it from the first vector. const dimensions = storeConfig.kind === "pgvector" ? (embedderConfig.dimensions ?? (await detectEmbeddingDimensions(embedder))) : undefined; // Provision (idempotent) and verify the table's vector dimensions up front // so a mismatch fails with a clear message before any chunk is embedded. const store = await openStore(storeConfig, { dimensions, provision: (width) => describeWidth(opts, embedderConfig, width), }); const result = await buildSchemaIndex({ schema: sources, embedder, store, embedderId: embedderConfig.id, // The indexer leaves the lock alone for an ephemeral (memory) store. lockFilePath: lockFilePathFor(schemaDir), force: opts.force, // The logger carries the correlation id; passing it here too would repeat the key on every event. logger, }); process.stdout.write( `${JSON.stringify( { schemaId: sources.schema.schemaId, chunksTotal: result.stats.chunksTotal, chunksIndexed: result.stats.chunksIndexed, chunksReused: result.stats.chunksReused, sensitiveExcluded: result.stats.sensitiveExcluded, sensitiveIncluded: result.stats.sensitiveIncluded, }, null, 2, )}\n`, ); await closeStore(store); return 0; } async function runQuery(opts: CliOptions, logger: AskDbLogger, runtimeConfig: AskDbRuntimeConfig): Promise { if (!opts.question) { throw new Error("Missing --question for query command."); } const schemaDir = resolveSchemaDir(opts, runtimeConfig); const storeConfig = resolveStoreConfig(opts, runtimeConfig, schemaDir); if (storeConfig.kind === "memory") { throw new Error( "query has nothing to search in the memory store: the memory store lives only inside one process, " + "so a separate `index` run cannot populate it. Use --store file or --store pgvector.", ); } const sources = loadChunkerSourcesFromDir(schemaDir); const embedderConfig = resolveEmbedderConfig(opts, runtimeConfig); assertQueryMatchesIndex(schemaDir, sources.schema.schemaId, embedderConfig); const embedder = await createEmbedder(embedderConfig); // Never detect here: without a known width, the pgvector store reads the existing table as it is. const store = await openStore(storeConfig, { dimensions: embedderConfig.dimensions }); const filter: Filter = { schemaId: sources.schema.schemaId }; if (opts.filterTypes && opts.filterTypes.length > 0) { filter.types = opts.filterTypes; } const [vector] = await embedder([opts.question]); const k = opts.k ?? 8; const results = await store.query(vector, k, filter); logger.info( { event: "askdb.rag.cli.query", questionChars: opts.question.length, k, resultCount: results.length, }, "rag query completed", ); process.stdout.write( `${JSON.stringify( { question: opts.question, k, results: results.map((r: QueryResult) => ({ id: r.id, score: Number(r.score.toFixed(6)), type: r.payload.type, schemaId: r.payload.schemaId, refs: r.payload.refs, textPreview: r.payload.text.slice(0, 200), })), }, null, 2, )}\n`, ); await closeStore(store); return 0; } /** The positional ``, else `introspection.outputDir`, the same fallback as `askdb ask --schema`. */ function resolveSchemaDir(opts: CliOptions, runtimeConfig: AskDbRuntimeConfig): string { return resolve(opts.schemaDir ?? runtimeConfig.introspection.outputDir); } function lockFilePathFor(schemaDir: string): string { return join(schemaDir, "schema.lock.json"); } /** * Refuse to query with a different embedder (or dimensions) than the index was * built with — the similarity scores would be meaningless. */ function assertQueryMatchesIndex(schemaDir: string, schemaId: string, embedderConfig: EmbedderConfig): void { const match = checkIndexMatches({ lockFilePath: lockFilePathFor(schemaDir), schemaId, embedderId: embedderConfig.id, dimensions: embedderConfig.dimensions, }); if (match.ok) return; const fix = match.reason === "lock-outdated" ? "Re-run `askdb rag index` before querying." : "Pass the same --embedder/--embedder-model/--dimensions used for `index`, or re-run `index`."; throw new Error(`${match.message} ${fix}`); } async function runSetupStore(opts: CliOptions, runtimeConfig: AskDbRuntimeConfig): Promise { // There's no embedder to ask, so the width has no default; fail before anything connects. const dimensions = opts.dimensions; if (dimensions === undefined) { throw new Error( "setup-store requires --dimensions : the vector width of your embedding model " + "(the same value as ai.embedding.dimensions).", ); } assertSetupStoreFlags(opts); const config = resolvePgvectorConfig(opts, readConfiguredStore(runtimeConfig)); const store = await openStore(config, { dimensions, provision: (width) => `--dimensions asks for ${width}` }); await closeStore(store); process.stdout.write( `pgvector schema ready: table "${config.table ?? DEFAULT_PGVECTOR_TABLE}" (dimensions=${dimensions})\n`, ); return 0; } type EmbedderConfig = | { kind: "mock"; id: string; dimensions: number } | { kind: "ai"; id: string; /** The width to request, from --dimensions or ai.embedding.dimensions; undefined leaves it to the model. */ dimensions: number | undefined; model: string; aiConfig: AiConfig; }; /** * `rag.embedder`: the runtime resolves `ai.embedding` exactly when `rag.embedder` is `"ai"`, and * leaves it undefined for `"mock"`. */ function configuredEmbedder(runtimeConfig: AskDbRuntimeConfig): "ai" | "mock" { return runtimeConfig.ai.embedding ? "ai" : "mock"; } /** * `--embedder`, else `rag.embedder`. The `ai` embedder takes the same path and id as Studio's, so * either accepts an index the other built. */ function resolveEmbedderConfig(opts: CliOptions, runtimeConfig: AskDbRuntimeConfig): EmbedderConfig { const embedding = runtimeConfig.ai.embedding; const choice = opts.embedder ?? configuredEmbedder(runtimeConfig); if (choice === "mock") { // Ignoring it would index with the lexical hash while the user believes the model embedded. if (opts.embedderModel !== undefined) { throw new Error( `--embedder-model applies to the ai embedder, but this run uses the mock embedder ` + `(${opts.embedder ? "from --embedder" : configSource(runtimeConfig, "rag.embedder")}). Drop --embedder-model, ` + 'or embed with ai.embedding (rag.embedder: "ai" in askdb.config.*).', ); } const dimensions = opts.dimensions ?? DEFAULT_MOCK_DIMENSIONS; return { kind: "mock", id: `mock:lexical-${dimensions}`, dimensions }; } // A new rag.embedder value fails to compile here until it has a branch of its own. choice satisfies "ai"; if (!embedding) { throw new Error( `--embedder ${choice} needs ai.embedding in askdb.config.*: set rag.embedder: "ai" and ai.embedding.model.`, ); } // --embedder-model overrides ai.embedding.model. const model = opts.embedderModel ?? embedding.model; const aiConfig = ai.resolveEmbeddingConfigFromSection({ ...embedding, model }); if (!aiConfig) { throw new Error( `askdb rag: embeddings need an API key on the ai.embedding connection ` + `("${embedding.connection.name}" in ai.providerConfig.${embedding.provider}). ` + "Set it in askdb.config.*, or pass --embedder mock.", ); } const dimensions = opts.dimensions ?? embedding.dimensions; return { kind: "ai", // Studio's id. The adapter's canonical provider name (`foundry` resolves to `azure`) keeps ids stable. id: aiSdkEmbedderId({ provider: aiConfig.provider, model, dimensions }), dimensions, model, aiConfig, }; } async function createEmbedder(config: EmbedderConfig): Promise { if (config.kind === "mock") return createMockEmbedder(config.dimensions); const model = await ai.createEmbeddingModel(config.aiConfig, { dimensions: config.dimensions }); return createAiSdkEmbedder({ model }); } /** Where the width a pgvector table refused came from, for the mismatch message. */ function describeWidth(opts: CliOptions, embedderConfig: EmbedderConfig, width: number): string { if (opts.dimensions !== undefined) return `--dimensions asks for ${width}`; if (embedderConfig.kind === "mock") return `the mock embedder writes ${width}`; if (embedderConfig.dimensions !== undefined) return `ai.embedding.dimensions asks for ${width}`; return `embedding model ${embedderConfig.model} returns ${width}`; } /** * Deterministic mock embedder used for tests, CI, and quick smoke-checks. Shared terms such as * "revenue" give chunks similar vectors, so a local smoke test still ranks related chunks first. */ function createMockEmbedder(dim: number): Embedder { return async (texts: string[]) => { return texts.map((text) => { const v = new Array(dim).fill(0); const tokens = text.toLowerCase().match(/[a-z0-9_]+/g) ?? []; for (const token of tokens) { v[stableTokenHash(token) % dim] += 1; } const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)) || 1; return v.map((x) => x / norm); }); }; } function stableTokenHash(token: string): number { let h = 2166136261; for (let i = 0; i < token.length; i++) { h ^= token.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; } type PgvectorConfig = { kind: "pgvector"; connectionString: string; table: string | undefined; indexStrategy: PgvectorIndexStrategy | undefined; }; type StoreConfig = { kind: "memory" } | { kind: "file"; basePath: string } | PgvectorConfig; type ConfiguredStore = { kind: AskDbRagStore; /** Where `kind` came from, for error messages. */ kindSource: string; fileBasePath: string | undefined; pgUrl: string | undefined; pgTable: string | undefined; pgIndexStrategy: string | undefined; }; /** * Every store setting the CLI reads from askdb.config.*, in one place: the store, the file base * path, and the pgvector URL, table and index strategy. The pgvector settings come from the * structured config, so they also serve `--store pgvector` and `setup-store` when another store * is configured. */ function readConfiguredStore(runtimeConfig: AskDbRuntimeConfig): ConfiguredStore { const { store, storeConfig } = runtimeConfig.rag; return { kind: store, kindSource: configSource(runtimeConfig, "rag.store"), fileBasePath: trimmed(storeConfig.file?.basePath), pgUrl: trimmed(storeConfig.pgvector?.databaseUrl), pgTable: trimmed(storeConfig.pgvector?.table), pgIndexStrategy: trimmed(storeConfig.pgvector?.indexStrategy), }; } /** Flags first, then askdb.config.*, then the built-in default. */ function resolveStoreConfig(opts: CliOptions, runtimeConfig: AskDbRuntimeConfig, schemaDir: string): StoreConfig { const configured = readConfiguredStore(runtimeConfig); const kind = opts.store ?? configured.kind; assertStoreFlagsApply(opts, kind, opts.store ? "from --store" : configured.kindSource); if (kind === "memory") return { kind }; if (kind === "file") { const basePath = opts.filePath ?? (configured.fileBasePath ? resolve(configured.fileBasePath) : join(schemaDir, "schema")); return { kind, basePath }; } // A store `@askdb/config` adds fails to compile here instead of falling through to pgvector. kind satisfies "pgvector"; return resolvePgvectorConfig(opts, configured); } function resolvePgvectorConfig(opts: CliOptions, configured: ConfiguredStore): PgvectorConfig { const connectionString = opts.pgUrl ?? configured.pgUrl; if (!connectionString) { throw new Error("pgvector store requires --pg-url, or rag.storeConfig.pgvector.databaseUrl in askdb.config.*."); } return { kind: "pgvector", connectionString, table: opts.pgTable ?? configured.pgTable, indexStrategy: parseIndexStrategy(configured.pgIndexStrategy), }; } const STORE_FLAGS = [ ["filePath", "--file-path", "file"], ["pgUrl", "--pg-url", "pgvector"], ["pgTable", "--pg-table", "pgvector"], ] as const; /** A flag for another store than the one this run uses would be silently ignored, so refuse it. */ function assertStoreFlagsApply(opts: CliOptions, kind: AskDbRagStore, kindSource: string): void { for (const [key, flag, store] of STORE_FLAGS) { if (opts[key] === undefined || kind === store) continue; throw new Error( `${flag} applies to the ${store} store, but this run uses the ${kind} store ` + `(${kindSource}). Pass --store ${store}, or drop ${flag}.`, ); } } /** * Where a setting the flags didn't give came from, for error messages: the `rag` key, or the * default when askdb.config.* has no `rag` block, which a message must not send the user to. */ function configSource(runtimeConfig: AskDbRuntimeConfig, key: "rag.store" | "rag.embedder"): string { const { rag } = runtimeConfig.structured; return rag === undefined || rag === null ? "the default: askdb.config.* has no rag block" : `from ${key}`; } /** setup-store provisions only the pgvector store, whatever `rag.store` is, so another store's flag is a mistake. */ function assertSetupStoreFlags(opts: CliOptions): void { // Ignored, it would provision the configured database while the user meant another. if (opts.schemaDir !== undefined) { throw new Error("setup-store takes no [schema-dir]; pass the connection string with --pg-url and the table with --pg-table."); } if (opts.store !== undefined && opts.store !== "pgvector") { throw new Error(`setup-store provisions only the pgvector store; drop --store ${opts.store}.`); } if (opts.filePath !== undefined) { throw new Error("setup-store provisions only the pgvector store; drop --file-path."); } } /** A record, so a new `PgvectorIndexStrategy` doesn't compile until it's listed here. */ const PGVECTOR_INDEX_STRATEGIES: Record = { ivfflat: true, hnsw: true, none: true }; function isIndexStrategy(value: string): value is PgvectorIndexStrategy { return Object.hasOwn(PGVECTOR_INDEX_STRATEGIES, value); } /** * Validated here because config load checks it only when `rag.store` is `pgvector`, while * setup-store and `--store pgvector` read it whatever the store is. Retire this once * @askdb/config validates the block wherever it's present (#476). */ function parseIndexStrategy(raw: string | undefined): PgvectorIndexStrategy | undefined { const value = raw?.toLowerCase(); if (value === undefined || isIndexStrategy(value)) return value; throw new Error( `Invalid rag.storeConfig.pgvector.indexStrategy "${raw}" (expected ${Object.keys(PGVECTOR_INDEX_STRATEGIES).join(", ")}).`, ); } function trimmed(value: string | undefined): string | undefined { const t = value?.trim(); return t ? t : undefined; } type CliStore = VectorStore & { close?: () => Promise; flush?: () => void; }; /** * Opens the store. `dimensions` reaches only a pgvector store, and only when known. With * `provision`, a pgvector store creates its table when it's missing and refuses an existing table * of another width, with the fix in flags; `provision` says where the refused width came from. */ async function openStore( config: StoreConfig, { dimensions, provision }: { dimensions?: number; provision?: (width: number) => string }, ): Promise { if (config.kind === "memory") return createMemoryStore(); if (config.kind === "file") return createFileStore({ basePath: config.basePath }); const store = createPgvectorStore({ connectionString: config.connectionString, table: config.table, dimensions, indexStrategy: config.indexStrategy, }); if (!provision) return store; try { await store.ensureSchema(); } catch (error) { // The caller never receives this store, so close its pool here. await store.close().catch(() => {}); if (!(error instanceof PgvectorDimensionMismatchError)) throw error; throw new Error( `pgvector table "${error.table}" holds ${error.tableDimensions}-dimension vectors, but ${provision(error.dimensions)}. ` + `Drop the table (DROP TABLE "${error.table}";) and run again, pass --pg-table for a new table, ` + `or pass --dimensions ${error.tableDimensions} if your embedding model supports that width.`, ); } return store; } async function closeStore(store: CliStore): Promise { if (typeof store.flush === "function") store.flush(); if (typeof store.close === "function") await store.close(); } function positiveInteger(flag: string, raw: string): number { const n = Number(raw); if (!Number.isInteger(n) || n <= 0) { throw new Error(`${flag} must be a positive integer${showable(raw) ? ` (got ${raw})` : ""}.`); } return n; } /** Every flag `askdb rag` accepts, for the parser and the help. */ const RAG_FLAGS: readonly Flag[] = [ { names: ["--store"], value: "", help: "Vector store. Default: rag.store.", apply(opts, raw) { if (!isCliStore(raw)) throw new Error(`${labelled("Unknown store", raw)} (expected 'memory', 'file', or 'pgvector').`); opts.store = raw; }, }, { names: ["--embedder"], value: "", help: "Embedder. Default: rag.embedder.", apply(opts, raw) { if (Object.hasOwn(REMOVED_EMBEDDERS, raw)) throw new Error(REMOVED_EMBEDDERS[raw]); if (!isCliEmbedder(raw)) { throw new Error(`${labelled("Unknown embedder", raw)} (expected ${ASKDB_RAG_EMBEDDERS.map((e) => `'${e}'`).join(" or ")}).`); } opts.embedder = raw; }, }, { names: ["--embedder-model"], value: "", help: "Model for the ai embedder. Default: ai.embedding.model.", apply(opts, raw) { // Trimmed as the registry trims it, so the embedder id names the model that embeds. const model = raw.trim(); if (!model) throw new Error("--embedder-model requires a value."); opts.embedderModel = model; }, }, { names: ["--dimensions"], value: "", help: "Vector width. Required by setup-store; index and query default to ai.embedding.dimensions, else the model's own.", apply: (opts, raw) => (opts.dimensions = positiveInteger("--dimensions", raw)), }, { names: ["--force"], help: "index: re-embed every chunk, even ones the store already holds.", apply: (opts) => (opts.force = true), }, { names: ["--question"], value: "", help: "query: the text to search for (required).", apply: (opts, value) => (opts.question = value), }, { names: ["-k", "--k"], value: "", help: "query: how many chunks to return. Default: 8.", apply: (opts, raw) => (opts.k = positiveInteger("-k", raw)), }, { names: ["--types"], value: "", help: "query: only these chunk types, comma-separated.", apply(opts, raw) { // A misspelt type would match nothing and look like an empty index. const types: ChunkType[] = []; for (const type of raw.split(",").map((s) => s.trim()).filter(Boolean)) { if (!isChunkType(type)) { throw new Error(`${labelled("Unknown --types value", type)} (expected ${Object.keys(CHUNK_TYPES).join(", ")}).`); } types.push(type); } opts.filterTypes = types; }, }, { names: ["--file-path"], value: "", help: "File store base path. Default: rag.storeConfig.file.basePath, else /schema.", apply: (opts, value) => (opts.filePath = value), }, { names: ["--pg-url"], value: "", help: "pgvector connection string. Default: rag.storeConfig.pgvector.databaseUrl.", apply: (opts, value) => (opts.pgUrl = value), }, { names: ["--pg-table"], value: "", help: `pgvector table. Default: rag.storeConfig.pgvector.table, else ${DEFAULT_PGVECTOR_TABLE}.`, apply: (opts, value) => (opts.pgTable = value), }, { names: ["--api-key"], value: "", help: "Removed: set the key on a connection in ai.providerConfig in askdb.config.*.", // Secrets on argv leak through shell history and the process list. apply: () => { throw new Error("--api-key was removed; set the key on a connection in ai.providerConfig in askdb.config.*."); }, }, ...loggingFlags(), ]; const RAG_USAGE = [ "askdb rag index [schema-dir] [--store memory|file|pgvector] [--embedder mock|ai] [--embedder-model ] [--dimensions ] [--force]", "askdb rag query [schema-dir] --question \"...\" [-k 8] [--types ] [--store file|pgvector] [--embedder mock|ai] [--embedder-model ] [--dimensions ]", "askdb rag setup-store --dimensions [--pg-url ] [--pg-table askdb_rag_chunks]", ]; function ragNotes(): string[] { return [ `Experimental: @askdb/rag stays 0.x, so a minor release of askdb may change these commands (${EXPERIMENTAL_ADR_URL}).`, "", "Flags override askdb.config.*: [schema-dir] defaults to introspection.outputDir, --store to rag.store,", "--pg-url, --pg-table and --file-path to rag.storeConfig, and --embedder to rag.embedder.", "", "Commands:", " index Chunk and embed a schema directory into the store. Only chunks the store", " doesn't already hold (same id + content hash) are embedded; --force re-embeds everything.", " query Run a similarity query against an indexed store. Use the same embedder/dimensions as `index`.", ` --types takes a comma-separated list of: ${Object.keys(CHUNK_TYPES).join(", ")}.`, " setup-store Create the pgvector extension, table, and indexes at --dimensions, the vector width of", " your embedding model. Idempotent — safe to re-run.", "", "Stores:", " memory in-memory cosine, lives only for one process. Useful for `index` dry runs (writes no schema.lock.json); `query` can't use it.", " file persisted as /schema.embeddings.{bin,json}, or .embeddings.{bin,json} with --file-path .", " pgvector --pg-url [--pg-table askdb_rag_chunks]", "", "Embedders:", " mock deterministic lexical hash, 64 dimensions unless --dimensions. CI-safe.", " ai the ai.embedding model from askdb.config.* (needs rag.embedder: \"ai\"). --embedder-model", " overrides its model; --dimensions requests a width.", ]; }