/** * HyDRA embedding matcher — T048, FR-005. * * Embeds prompt text via ONNX (Xenova/all-MiniLM-L6-v2 384-dim), * projects to requirement dimensions [reasoning, code_gen, tool_use], * and scores fleet candidates with a shortfall gate. * * Shortfall gate (data-model §Validation): candidate excluded when * any capability dimension shortfall > 0 (quality parity). * * Budget: 80–120 ms (configurable, default 100 ms). */ import { z } from 'zod'; import { EMBEDDING_DIM, type CascadeEmbedderTelemetry, type TextEmbedder } from './embedding-provider.js'; import { type K4CapabilityVector, type ModernBertHeadsPredictor } from './modernbert-heads.js'; import type { Encoder, EncoderCascadeConfig, HydraConfig, HydraHeads } from '../types/schemas.js'; import { type FrugalityWeights } from '../scoring/multi-objective.js'; import type { CandidateScore, ModelProfile, RoutingRequest } from '../types/index.js'; export interface RequirementVector { readonly reasoning: number; readonly code_gen: number; readonly tool_use: number; } export interface EmbeddingProvider { extractRequirements(text: string): Promise; /** * Optional single-pass extraction that also returns the raw 384-dim encoder * embedding (SP-285, #170) for privacy-safe dataset capture. Providers that * project through a non-shared embedding surface (e.g. ModernBERT K=4 heads) * simply omit it; the matcher then captures no embedding for those routes. */ extractRequirementsDetailed?(text: string): Promise<{ requirements: RequirementVector; embedding: readonly number[] | null; }>; /** * Reason codes describing degraded requirement extraction (SP-251, #148) — * e.g. `k4_heads_placeholder` when learned K=4 head weights are missing. * Absent/empty when learned weights are active. */ requirementReasonCodes?(): readonly string[]; /** * Cascade decision telemetry from the most recent extraction (SP-292, #173). * Present only on cascading-embedder-backed providers; null before the first * embed. Absent on single-encoder and ModernBERT K=4 providers. */ cascadeTelemetry?(): CascadeEmbedderTelemetry | null; dispose(): Promise; } export interface MatchResult { readonly selected: CandidateScore | null; readonly candidates: readonly CandidateScore[]; readonly requirements: RequirementVector; /** * Raw 384-dim encoder embedding of the metadata-prefixed routing input * (SP-285, #170). Present only when SMART_ROUTER_DATASET_EMBEDDINGS=1 and * the provider supports single-pass detailed extraction; otherwise null. * Derived vector — never the prompt text. */ readonly embedding?: readonly number[] | null; /** * Decision metadata reason codes for degraded requirement extraction * (SP-251, #148): `hydra_weights_missing` when the learned projection * artifact is missing/invalid, `k4_heads_placeholder` when ModernBERT K=4 * head weights are missing/invalid. Empty when learned weights are active. * Optional on the type for legacy literal constructions; HydraMatcher.match * always populates it. */ readonly requirement_reason_codes?: readonly string[]; /** * Encoder cascade decision telemetry for this match (SP-292, #173): * `encoder_selected`, `token_estimate`, `cascade_threshold`, and the * fallback reason when an over-threshold prompt degraded to the primary * encoder. Absent on legacy call paths and non-cascade providers. */ readonly cascade_telemetry?: CascadeEmbedderTelemetry | null; readonly elapsedMs: number; readonly budgetExceeded: boolean; } export interface HydraMatcherConfig { readonly artifactCachePath: string; readonly encoder?: Encoder; readonly hydraHeads?: HydraHeads; readonly budgetMs?: number; readonly frugality?: FrugalityWeights; readonly projectionWeightsPath?: string; readonly k4HeadWeightsPath?: string; /** * SP-252 / #148: when true, match() refuses to score with placeholder * requirement heads and throws {@link MissingWeightsFailClosedError} carrying * the SP-251 reason codes. Default false keeps fail-open placeholders. */ readonly failClosedOnMissingWeights?: boolean; } /** * Thrown by HydraMatcher.match when `failClosedOnMissingWeights` is enabled and * learned weight artifacts are missing/invalid (SP-252, #148). Carries the * SP-251 reason codes so callers (the router pipeline) can route through the * degraded sandwich with the codes visible on the decision path. */ export declare class MissingWeightsFailClosedError extends Error { readonly name = "MissingWeightsFailClosedError"; /** SP-251 reason codes (e.g. `hydra_weights_missing`, `k4_heads_placeholder`). */ readonly reasonCodes: readonly string[]; constructor(reasonCodes: readonly string[]); } export declare const DEFAULT_HYDRA_PROJECTION_WEIGHTS_PATH: string; export declare const HYDRA_PROJECTION_OUTPUT_DIM = 3; export declare const HydraProjectionWeightsSchema: z.ZodObject<{ version: z.ZodLiteral<1>; embedding_dim: z.ZodLiteral<384>; weights: z.ZodArray>; bias: z.ZodArray; }, z.core.$strip>; export interface HydraProjectionWeights { readonly version: 1; readonly embedding_dim: typeof EMBEDDING_DIM; readonly weights: readonly (readonly number[])[]; readonly bias: readonly number[]; } export interface LoadHydraProjectionWeightsOptions { readonly filePath?: string; } export declare class HydraProjectionWeightsLoaderError extends Error { readonly name = "HydraProjectionWeightsLoaderError"; constructor(message: string, options?: { cause?: unknown; }); } export declare function parseHydraProjectionWeightsJson(raw: string): HydraProjectionWeights; /** * Load HyDRA projection weights from disk. Returns null when the artifact is * missing; throws only when the file exists but is invalid. */ export declare function loadHydraProjectionWeights(options?: LoadHydraProjectionWeightsOptions): HydraProjectionWeights | null; /** Resolve projection weights — missing artifacts fall back to placeholder projection. */ export declare function resolveHydraProjectionWeights(options?: LoadHydraProjectionWeightsOptions): HydraProjectionWeights | null; /** * Project a 384-dim embedding to 3 requirement dimensions. * * Uses learned linear projection (sigmoid(embedding @ W + b)) when weights are * provided; otherwise falls back to deterministic mean-pooled-thirds placeholder. */ export declare function projectToRequirements(embedding: Float32Array, weights?: HydraProjectionWeights | null): RequirementVector; /** * Map ModernBERT K=4 head output to the 3-dim requirement vector used by the * catalog-decoupled shortfall gate. The debugging dimension is predicted for * HyDRA fidelity but excluded from shortfall matching (SP-159, routing-roadmap §2 P3). */ export declare function k4CapabilityVectorToRequirements(vector: K4CapabilityVector): RequirementVector; /** Env var enabling opt-in capture of raw 384-dim embeddings into dataset rows. */ export declare const HYDRA_EMBEDDING_CAPTURE_ENV = "SMART_ROUTER_DATASET_EMBEDDINGS"; /** True when the operator opted into privacy-safe embedding capture. */ export declare function isHydraEmbeddingCaptureEnabled(): boolean; /** * Adapts a shared TextEmbedder for HyDRA requirement extraction. * dispose() delegates to the underlying embedder for shared lifecycle. */ export declare function wrapHydraEmbeddingProvider(embedder: TextEmbedder, projectionWeights?: HydraProjectionWeights | null): EmbeddingProvider; /** * Adapts a ModernBERT K=4 heads predictor for HyDRA requirement extraction. * Debugging dimension is dropped before shortfall gate evaluation. */ export declare function wrapModernBertHeadsEmbeddingProvider(predictor: ModernBertHeadsPredictor): EmbeddingProvider; export declare class HydraMatcher { private readonly provider; private readonly budgetMs; private readonly frugality; private readonly hydraHeads; private readonly projectionWeights; private readonly requirementReasonCodes; private readonly failClosedOnMissingWeights; constructor(provider: EmbeddingProvider, config: HydraMatcherConfig); /** * Decision-metadata reason codes for the requirement extraction path * (SP-251, #148). Placeholder fallback stays fail-open; the codes make the * degraded weight state explicit instead of stderr-only. */ private computeRequirementReasonCodes; /** Active requirement head mode from operator hydra config. */ hydraHeadsMode(): HydraHeads; /** Whether ModernBERT K=4 heads mode is active. */ usesModernBertK4(): boolean; /** Whether learned SP-115 projection weights were loaded at init. */ usesLearnedProjection(): boolean; /** * Reason codes emitted into decision metadata when requirement extraction * fell back to placeholders because learned weight artifacts were * missing/invalid (SP-251, #148). Empty when learned weights are active. */ missingWeightsReasonCodes(): readonly string[]; match(request: RoutingRequest, fleet: readonly ModelProfile[]): Promise; dispose(): Promise; private validateRequirements; } export interface CreateOnnxEmbeddingProviderOptions { readonly encoder?: Encoder; readonly projectionWeightsPath?: string; /** * Opt-in encoder cascade (SP-292, #173). When enabled, the provider is * backed by a lazy dual-session cascading embedder that routes * over-threshold prompts to the long-context encoder and degrades to the * primary encoder with an explicit fallback reason when unavailable. * Default: disabled (single-encoder path unchanged). */ readonly encoderCascade?: EncoderCascadeConfig; } export interface CreateHydraEmbeddingProviderOptions extends CreateOnnxEmbeddingProviderOptions { readonly hydraHeads?: HydraHeads; readonly k4HeadWeightsPath?: string; } /** * Creates an EmbeddingProvider backed by the shared ONNX text embedder. * For multi-matcher setups, create one TextEmbedder via createTextEmbedder * and pass wrapHydraEmbeddingProvider(embedder) to HyDRA while sharing embed(). */ export declare function createOnnxEmbeddingProvider(artifactCachePath: string, options?: CreateOnnxEmbeddingProviderOptions): Promise; /** * Creates an EmbeddingProvider for the configured hydra_heads mode: * - `learned_projection` — MiniLM/Granite embedder + SP-115 linear projection (or placeholder) * - `modernbert_k4` — ModernBERT-base [CLS] with K=4 sigmoid heads (debugging excluded from shortfall) */ export declare function createHydraEmbeddingProvider(artifactCachePath: string, options?: CreateHydraEmbeddingProviderOptions): Promise; /** * Bootstrap HyDRA matcher from operator hydra config (encoder, heads, artifact path). */ export declare function createHydraMatcherFromHydraConfig(hydraConfig: Pick & Partial>, options?: Omit): Promise; //# sourceMappingURL=hydra-matcher.d.ts.map