From 8c1093cfdc5e98cb5db1d178003ff6eaefaacaf8 Mon Sep 17 00:00:00 2001 From: Bee <68532117+abeatrix@users.noreply.github.com> Date: Thu, 28 Aug 2025 16:39:56 -0700 Subject: [PATCH] add health checks and generic fallback to PromptRegistry (#5879) * fix: Harden PromptRegistry with health checks and generic fallback - Perform registry health check after loading (validate GENERIC, log counts/warnings) - Always try GENERIC when family-specific variant is missing - Enhance error diagnostics with available variants and registry state - Ensure GENERIC variant exists; create minimal fallback if loading fails - Minor test style cleanup and variants index update to support reliability * simpilfy * variants * Fix import * type safe * remove lazy loading * load and set variants * fix import location --- .../__tests__/integration.test.ts | 4 +- .../system-prompt/registry/PromptRegistry.ts | 94 ++++++++++++++++--- .../variants/generic/template.ts | 2 +- .../system-prompt/variants/gpt-5/template.ts | 2 +- .../prompts/system-prompt/variants/index.ts | 31 +++--- .../variants/next-gen/template.ts | 2 +- .../system-prompt/variants/xs/overrides.ts | 3 +- 7 files changed, 104 insertions(+), 34 deletions(-) diff --git a/src/core/prompts/system-prompt/__tests__/integration.test.ts b/src/core/prompts/system-prompt/__tests__/integration.test.ts index 9da1c64b..a94791f0 100644 --- a/src/core/prompts/system-prompt/__tests__/integration.test.ts +++ b/src/core/prompts/system-prompt/__tests__/integration.test.ts @@ -63,7 +63,9 @@ ${differences} // Helper to compare two strings and return differences const compareStrings = (expected: string, actual: string): string | null => { - if (expected === actual) return null + if (expected === actual) { + return null + } const expectedLines = expected.split("\n") const actualLines = actual.split("\n") diff --git a/src/core/prompts/system-prompt/registry/PromptRegistry.ts b/src/core/prompts/system-prompt/registry/PromptRegistry.ts index 9933e35e..dbe9a975 100644 --- a/src/core/prompts/system-prompt/registry/PromptRegistry.ts +++ b/src/core/prompts/system-prompt/registry/PromptRegistry.ts @@ -3,6 +3,8 @@ import { getModelFamily } from ".." import { getSystemPromptComponents } from "../components" import { registerClineToolSets } from "../tools" import type { ComponentFunction, ComponentRegistry, PromptVariant, SystemPromptContext } from "../types" +import { loadAllVariantConfigs } from "../variants" +import { config as genericConfig } from "../variants/generic/config" import { PromptBuilder } from "./PromptBuilder" export class PromptRegistry { @@ -32,9 +34,37 @@ export class PromptRegistry { await Promise.all([this.loadVariants(), this.loadComponents()]) + // Perform health check to ensure critical variants are available + this.performHealthCheck() + this.loaded = true } + /** + * Perform health check to ensure registry is in a valid state + */ + private performHealthCheck(): void { + const criticalVariants = [ModelFamily.GENERIC] + const missingVariants = criticalVariants.filter((variant) => !this.variants.has(variant)) + + if (missingVariants.length > 0) { + console.error(`Registry health check failed: Missing critical variants: ${missingVariants.join(", ")}`) + console.error(`Available variants: ${Array.from(this.variants.keys()).join(", ")}`) + } + + if (this.variants.size === 0) { + console.error("Registry health check failed: No variants loaded at all") + } + + if (Object.keys(this.components).length === 0) { + console.warn("Registry health check warning: No components loaded") + } + + console.log( + `Registry health check: ${this.variants.size} variants, ${Object.keys(this.components).length} components loaded`, + ) + } + /** * Get prompt by model ID with fallback to generic */ @@ -43,11 +73,31 @@ export class PromptRegistry { // Try model family fallback (e.g., "claude-4" -> "claude") const modelFamily = getModelFamily(context.providerInfo) - const variant = this.variants.get(modelFamily ?? ModelFamily.GENERIC) + let variant = this.variants.get(modelFamily ?? ModelFamily.GENERIC) + + // If no variant found for the detected family, explicitly try generic + if (!variant && modelFamily !== ModelFamily.GENERIC) { + variant = this.variants.get(ModelFamily.GENERIC) + } if (!variant) { + // Enhanced error with debugging information + const availableVariants = Array.from(this.variants.keys()) + const errorDetails = { + requestedModel: context.providerInfo.model.id, + detectedFamily: modelFamily, + availableVariants, + variantsCount: this.variants.size, + componentsCount: Object.keys(this.components).length, + isLoaded: this.loaded, + } + + console.error("Prompt variant lookup failed:", errorDetails) + throw new Error( - `No prompt variant found for model '${context.providerInfo.model.id}' and no generic fallback available`, + `No prompt variant found for model '${context.providerInfo.model.id}' (family: ${modelFamily}) and no generic fallback available. ` + + `Available variants: [${availableVariants.join(", ")}]. ` + + `Registry state: loaded=${this.loaded}, variants=${this.variants.size}, components=${Object.keys(this.components).length}`, ) } @@ -184,30 +234,44 @@ export class PromptRegistry { /** * Load all variants from the variants directory */ - private async loadVariants(): Promise { + private loadVariants(): void { try { - const { VARIANT_CONFIGS } = await import("../variants") + this.variants = new Map() - // Load each variant configuration - const loadPromises = Object.entries(VARIANT_CONFIGS).map(async ([variantId, configLoader]) => { - try { - const config = await configLoader() - await this.loadVariantFromConfig(variantId, config) - } catch (error) { - console.warn(`Warning: Could not load variant '${variantId}':`, error) - } - }) + for (const [id, config] of Object.entries(loadAllVariantConfigs())) { + this.variants.set(id, { ...config, id }) + } - await Promise.all(loadPromises) + // Ensure generic variant is always available as a safety fallback + this.ensureGenericFallback() } catch (error) { console.warn("Warning: Could not load variants:", error) + // Even if variant loading fails completely, create a minimal generic fallback + this.createMinimalGenericFallback() } } + /** + * Ensure generic variant is available, create minimal one if missing + */ + private ensureGenericFallback(): void { + if (!this.variants.has(ModelFamily.GENERIC)) { + console.warn("Generic variant not found, creating minimal fallback") + this.createMinimalGenericFallback() + } + } + + /** + * Create a minimal generic variant as absolute fallback + */ + private createMinimalGenericFallback(): void { + this.loadVariantFromConfig(ModelFamily.GENERIC, genericConfig) + } + /** * Load a single variant from its TypeScript config */ - private async loadVariantFromConfig(variantId: string, config: Omit): Promise { + private loadVariantFromConfig(variantId: string, config: Omit): void { try { const variant: PromptVariant = { ...config, diff --git a/src/core/prompts/system-prompt/variants/generic/template.ts b/src/core/prompts/system-prompt/variants/generic/template.ts index 5bd140d2..2c1504fd 100644 --- a/src/core/prompts/system-prompt/variants/generic/template.ts +++ b/src/core/prompts/system-prompt/variants/generic/template.ts @@ -1,4 +1,4 @@ -import { SystemPromptSection } from "../.." +import { SystemPromptSection } from "../../templates/placeholders" export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}} diff --git a/src/core/prompts/system-prompt/variants/gpt-5/template.ts b/src/core/prompts/system-prompt/variants/gpt-5/template.ts index 97963b78..d77ceb68 100644 --- a/src/core/prompts/system-prompt/variants/gpt-5/template.ts +++ b/src/core/prompts/system-prompt/variants/gpt-5/template.ts @@ -1,4 +1,4 @@ -import { SystemPromptSection } from "../.." +import { SystemPromptSection } from "../../templates/placeholders" export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}} diff --git a/src/core/prompts/system-prompt/variants/index.ts b/src/core/prompts/system-prompt/variants/index.ts index bc6f8733..d59f7636 100644 --- a/src/core/prompts/system-prompt/variants/index.ts +++ b/src/core/prompts/system-prompt/variants/index.ts @@ -7,34 +7,39 @@ */ export { config as genericConfig, type GenericVariantConfig } from "./generic/config" +export { config as gpt5Config, type GPT5VariantConfig } from "./gpt-5/config" export { config as nextGenConfig, type NextGenVariantConfig } from "./next-gen/config" export { config as xsConfig, type XsVariantConfig } from "./xs/config" +import { config as genericConfig } from "./generic/config" +import { config as gpt5Config } from "./gpt-5/config" +import { config as nextGenConfig } from "./next-gen/config" +import { config as xsConfig } from "./xs/config" + /** * Variant Registry for dynamic loading * - * This registry allows for lazy loading of variant configurations, - * which is useful for reducing initial bundle size and enabling - * runtime variant selection. + * This registry allows for loading variant configurations. */ export const VARIANT_CONFIGS = { /** * Generic variant - Fallback for all model types * Optimized for broad compatibility and stable performance */ - generic: () => import("./generic/config").then((m) => m.config), + generic: genericConfig, /** * Next-gen variant - Advanced models with enhanced capabilities * Includes additional features like feedback loops and web fetching */ - "next-gen": () => import("./next-gen/config").then((m) => m.config), + "next-gen": nextGenConfig, + gpt5: gpt5Config, /** * XS variant - Compact models with limited context windows * Streamlined for efficiency with essential tools only */ - xs: () => import("./xs/config").then((m) => m.config), + xs: xsConfig, } as const /** @@ -60,18 +65,16 @@ export function isValidVariantId(id: string): id is VariantId { /** * Load a variant configuration dynamically * @param variantId - The ID of the variant to load - * @returns Promise that resolves to the variant configuration + * @returns Variant configuration */ -export async function loadVariantConfig(variantId: VariantId) { - const loader = VARIANT_CONFIGS[variantId] - return await loader() +export function loadVariantConfig(variantId: VariantId) { + return VARIANT_CONFIGS[variantId] } /** * Load all variant configurations - * @returns Promise that resolves to a map of all variant configurations + * @returns A map of all variant configurations */ -export async function loadAllVariantConfigs() { - const entries = await Promise.all(Object.entries(VARIANT_CONFIGS).map(async ([id, loader]) => [id, await loader()] as const)) - return Object.fromEntries(entries) as Record>> +export function loadAllVariantConfigs() { + return VARIANT_CONFIGS } diff --git a/src/core/prompts/system-prompt/variants/next-gen/template.ts b/src/core/prompts/system-prompt/variants/next-gen/template.ts index 97963b78..d77ceb68 100644 --- a/src/core/prompts/system-prompt/variants/next-gen/template.ts +++ b/src/core/prompts/system-prompt/variants/next-gen/template.ts @@ -1,4 +1,4 @@ -import { SystemPromptSection } from "../.." +import { SystemPromptSection } from "../../templates/placeholders" export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}} diff --git a/src/core/prompts/system-prompt/variants/xs/overrides.ts b/src/core/prompts/system-prompt/variants/xs/overrides.ts index 9ecbf963..9ff1691d 100644 --- a/src/core/prompts/system-prompt/variants/xs/overrides.ts +++ b/src/core/prompts/system-prompt/variants/xs/overrides.ts @@ -1,4 +1,5 @@ -import { PromptVariant, SystemPromptSection } from "../.." +import { SystemPromptSection } from "../../templates/placeholders" +import { PromptVariant } from "../../types" const XS_EDITING_FILES = `FILE EDITING RULES - Default: replace_in_file; write_to_file for new files or full rewrites.