Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
Refactor prompts
Khuram Niazf1ab278669d8
diff --git a/src/lib/ai/config.ts b/src/lib/ai/config.tsnew file mode 100644index 0000000..d8ef6e9--- /dev/null+++ b/src/lib/ai/config.ts@@ -0,0 +1,73 @@+/**+ * AI Configuration Constants+ *+ * Centralized configuration for all AI-related constants including+ * timeouts, temperatures, rate limits, and retry settings.+ */++// TIMEOUTS+export const TIMEOUTS = {+ /** Timeout for semantic extraction calls (keywords, verbs, similarity) */+ SEMANTIC_MS: 60000, // 60 seconds+ /** Timeout for agent calls (analysis, feedback) */+ AGENT_MS: 120000, // 120 seconds+} as const;++// RATE LIMITING+export const RATE_LIMITS = {+ /** Time window for rate limiting in milliseconds */+ WINDOW_MS: 60 * 1000, // 1 minute+ /** Maximum requests per user per window */+ MAX_REQUESTS: 5,+ /** Maximum entries in rate limit store before cleanup */+ STORE_CLEANUP_THRESHOLD: 1000,+} as const;++// TEMPERATURES+export const TEMPERATURES = {+ /** Temperature for analysis agents (low for consistency) */+ ANALYSIS: 0.1,+ /** Temperature for feedback agents (slightly higher for creativity) */+ FEEDBACK: 0.3,+} as const;++// RETRY SETTINGS+export const RETRY = {+ /** Maximum number of retries for failed operations */+ MAX_ATTEMPTS: 1,+ /** Base delay in ms for exponential backoff */+ BASE_DELAY_MS: 1000,+ /** Backoff multiplier (delay = BASE_DELAY_MS * 2^attempt) */+ BACKOFF_MULTIPLIER: 2,+} as const;++// TEXT LIMITS (for prompts)+export const TEXT_LIMITS = {+ /** Character limit for Ollama (local models) */+ OLLAMA: {+ RESUME: 1500,+ JOB: 1200,+ },+ /** Character limit for cloud providers */+ CLOUD: {+ RESUME: 4000,+ JOB: 3500,+ },+} as const;++// SCORE VARIANCE+export const SCORE_VARIANCE = {+ /** Default allowed variance from baseline score */+ DEFAULT: 10,+ /** Variance for mid-range scores (40-60) - more subjective */+ MID_RANGE_RESUME: 12,+ MID_RANGE_JOB_MATCH: 15,+ /** Variance for extreme scores (<30 or >80) - more objective */+ EXTREME: 7,+} as const;++// Legacy exports for backward compatibility+export const SEMANTIC_TIMEOUT_MS = TIMEOUTS.SEMANTIC_MS;+export const AGENT_TIMEOUT_MS = TIMEOUTS.AGENT_MS;+export const WINDOW_MS = RATE_LIMITS.WINDOW_MS;+export const MAX_REQUESTS = RATE_LIMITS.MAX_REQUESTS;diff --git a/src/lib/ai/index.ts b/src/lib/ai/index.tsindex 8fc5598..e65da88 100644--- a/src/lib/ai/index.ts+++ b/src/lib/ai/index.ts@@ -13,7 +13,7 @@ export {JOB_MATCH_SYSTEM_PROMPT,buildResumeReviewPrompt,buildJobMatchPrompt,-} from "./prompts/prompts";+} from "./prompts";// Multi-agent systemexport {diff --git a/src/lib/ai/multi-agent/job-match/index.ts b/src/lib/ai/multi-agent/job-match/index.tsindex 90b2882..c4af0b8 100644--- a/src/lib/ai/multi-agent/job-match/index.ts+++ b/src/lib/ai/multi-agent/job-match/index.ts@@ -9,7 +9,7 @@ import { AnalysisAgentSchema, FeedbackAgentSchema } from "@/models/ai.schemas";import {ANALYSIS_AGENT_PROMPT,FEEDBACK_AGENT_PROMPT,-} from "../../prompts/prompts.agents";+} from "../../prompts/resume-review";import {performSemanticSkillMatch,@@ -29,6 +29,7 @@ import {ToolDataJobMatch,SemanticData,} from "@/models/ai.model";+import { TEMPERATURES } from "../../config";import {isOllamaProvider,SEMANTIC_TIMEOUT_MS,@@ -229,7 +230,7 @@ export async function multiAgentJobMatch(? OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT: ANALYSIS_AGENT_PROMPT,prompt: analysisPrompt,- temperature: 0.1,+ temperature: TEMPERATURES.ANALYSIS,},feedback: {schema: isOllama ? OllamaFeedbackAgentSchema : FeedbackAgentSchema,@@ -237,7 +238,7 @@ export async function multiAgentJobMatch(? OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT: FEEDBACK_AGENT_PROMPT,prompt: feedbackPrompt,- temperature: 0.3,+ temperature: TEMPERATURES.FEEDBACK,},});diff --git a/src/lib/ai/multi-agent/resume-review/index.ts b/src/lib/ai/multi-agent/resume-review/index.tsindex 7fbe7a6..3a8b321 100644--- a/src/lib/ai/multi-agent/resume-review/index.ts+++ b/src/lib/ai/multi-agent/resume-review/index.ts@@ -9,7 +9,7 @@ import { AnalysisAgentSchema, FeedbackAgentSchema } from "@/models/ai.schemas";import {ANALYSIS_AGENT_PROMPT,FEEDBACK_AGENT_PROMPT,-} from "../../prompts/prompts.agents";+} from "../../prompts/resume-review";import {countQuantifiedAchievements,analyzeFormatting,@@ -30,6 +30,7 @@ import {CollaborativeResult,ToolDataResume,} from "@/models/ai.model";+import { TEMPERATURES } from "../../config";import {isOllamaProvider,SEMANTIC_TIMEOUT_MS,@@ -171,7 +172,7 @@ export async function multiAgentResumeReview(? OLLAMA_ANALYSIS_SYSTEM_PROMPT: ANALYSIS_AGENT_PROMPT,prompt: analysisPrompt,- temperature: 0.1,+ temperature: TEMPERATURES.ANALYSIS,},feedback: {schema: isOllama ? OllamaFeedbackAgentSchema : FeedbackAgentSchema,@@ -179,7 +180,7 @@ export async function multiAgentResumeReview(? OLLAMA_FEEDBACK_SYSTEM_PROMPT: FEEDBACK_AGENT_PROMPT,prompt: feedbackPrompt,- temperature: 0.3,+ temperature: TEMPERATURES.FEEDBACK,},verbCount: toolData.verbs.count,});diff --git a/src/lib/ai/multi-agent/utils.ts b/src/lib/ai/multi-agent/utils.tsindex 2613237..993c4c2 100644--- a/src/lib/ai/multi-agent/utils.ts+++ b/src/lib/ai/multi-agent/utils.ts@@ -4,14 +4,14 @@* Common utilities used by both resume review and job match agents.*/-// ============================================================================+import { RETRY } from "../config";+// RETRY MECHANISM-// ============================================================================export async function runWithRetry<T>(operation: () => Promise<T>,operationName: string,- maxRetries: number = 1+ maxRetries: number = RETRY.MAX_ATTEMPTS): Promise<T> {let lastError: Error = new Error("Unknown error");@@ -26,7 +26,8 @@ export async function runWithRetry<T>();if (attempt < maxRetries) {- const delay = 1000 * Math.pow(2, attempt);+ const delay =+ RETRY.BASE_DELAY_MS * Math.pow(RETRY.BACKOFF_MULTIPLIER, attempt);await new Promise((resolve) => setTimeout(resolve, delay));}}@@ -39,9 +40,7 @@ export async function runWithRetry<T>();}-// ============================================================================-// TIMEOUT WRAPPER (Phase 4: Prevent small model hangs)-// ============================================================================+// TIMEOUT WRAPPERexport async function withTimeout<T>(promise: Promise<T>,diff --git a/src/lib/ai/ollama/index.ts b/src/lib/ai/ollama/index.tsindex 1feec0e..cccdb99 100644--- a/src/lib/ai/ollama/index.ts+++ b/src/lib/ai/ollama/index.ts@@ -8,10 +8,13 @@*/import type { ProviderType } from "../providers";+import {+ SEMANTIC_TIMEOUT_MS,+ AGENT_TIMEOUT_MS,+} from "../config";-// Timeouts for Ollama (local models need more time)-export const SEMANTIC_TIMEOUT_MS = 60000; // 60 seconds for semantic extraction-export const AGENT_TIMEOUT_MS = 120000; // 120 seconds for agent calls+// Re-export timeouts for backward compatibility+export { SEMANTIC_TIMEOUT_MS, AGENT_TIMEOUT_MS };/*** Check if provider is Ollama (local models that need simplified prompts/schemas)@@ -40,7 +43,7 @@ export {buildOllamaResumeFeedbackPrompt,buildOllamaJobMatchAnalysisPrompt,buildOllamaJobMatchFeedbackPrompt,-} from "../prompts/ollama.prompts";+} from "../prompts";// Re-export schemas from models for convenienceexport {diff --git a/src/lib/ai/prompts/index.ts b/src/lib/ai/prompts/index.tsnew file mode 100644index 0000000..629af87--- /dev/null+++ b/src/lib/ai/prompts/index.ts@@ -0,0 +1,42 @@+/**+ * AI Prompts - Main Barrel File+ *+ * Re-exports from feature-specific modules for backward compatibility.+ * For new code, import directly from the specific module:+ * - ./resume-review for resume analysis prompts+ * - ./job-match for job matching prompts+ * - ./shared for validation/critic prompts+ */++// Resume Review exports+export {+ RESUME_REVIEW_SYSTEM_PROMPT,+ buildResumeReviewPrompt,+ RESUME_CALIBRATION_EXAMPLES,+ SCORING_PHASES,+ SCORE_INTERPRETATION_GUIDE,+ ANALYSIS_AGENT_PROMPT,+ FEEDBACK_AGENT_PROMPT,+ OLLAMA_ANALYSIS_SYSTEM_PROMPT,+ OLLAMA_FEEDBACK_SYSTEM_PROMPT,+ buildOllamaResumeAnalysisPrompt,+ buildOllamaResumeFeedbackPrompt,+ getKeywordPrompt,+ getVerbPrompt,+} from "./resume-review";++// Job Match exports+export {+ JOB_MATCH_SYSTEM_PROMPT,+ buildJobMatchPrompt,+ JOB_MATCH_SCORE_GUIDE,+ OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT,+ OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT,+ buildOllamaJobMatchAnalysisPrompt,+ buildOllamaJobMatchFeedbackPrompt,+ getSkillMatchPrompt,+ getSimilarityPrompt,+} from "./job-match";++// Shared exports+export { CRITIC_SYSTEM_PROMPT, buildCriticPrompt } from "./shared";diff --git a/src/lib/ai/prompts/job-match/calibration.ts b/src/lib/ai/prompts/job-match/calibration.tsnew file mode 100644index 0000000..53e0e7b--- /dev/null+++ b/src/lib/ai/prompts/job-match/calibration.ts@@ -0,0 +1,19 @@+/**+ * Job Match Calibration Examples+ *+ * Score interpretation guide for job matching analysis.+ */++export const JOB_MATCH_SCORE_GUIDE = `## SCORE INTERPRETATION GUIDE+- **80-100:** Excellent Match - Interview likely. Apply immediately.+- **65-79:** Strong Match - Good fit. Apply with confidence.+- **50-64:** Moderate Match - Worth applying with tailored resume.+- **35-49:** Weak Match - Consider but have backup options.+- **20-34:** Poor Match - Significant gaps. Upskill first.+- **<20:** Not a Match - Wrong role/industry. Redirect search.++## REALITY CHECK+- Most candidates score 40-60 against any given job+- A score of 50 means "qualified but competitive field"+- 70+ is excellent and relatively rare+- Even strong candidates often miss 20-30% of keywords`;diff --git a/src/lib/ai/prompts/job-match/index.ts b/src/lib/ai/prompts/job-match/index.tsnew file mode 100644index 0000000..0661cf8--- /dev/null+++ b/src/lib/ai/prompts/job-match/index.ts@@ -0,0 +1,23 @@+/**+ * Job Match Prompts - Barrel File+ */++// System prompts+export { JOB_MATCH_SYSTEM_PROMPT } from "./system";++// User prompt builders+export { buildJobMatchPrompt } from "./user";++// Calibration examples+export { JOB_MATCH_SCORE_GUIDE } from "./calibration";++// Ollama-specific prompts+export {+ OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT,+ OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT,+ buildOllamaJobMatchAnalysisPrompt,+ buildOllamaJobMatchFeedbackPrompt,+} from "./ollama";++// Semantic extraction prompts+export { getSkillMatchPrompt, getSimilarityPrompt } from "./semantic";diff --git a/src/lib/ai/prompts/ollama.prompts.ts b/src/lib/ai/prompts/job-match/ollama.tssimilarity index 50%rename from src/lib/ai/prompts/ollama.prompts.tsrename to src/lib/ai/prompts/job-match/ollama.tsindex bb4b237..ed4083c 100644--- a/src/lib/ai/prompts/ollama.prompts.ts+++ b/src/lib/ai/prompts/job-match/ollama.ts@@ -1,19 +1,11 @@/**- * Ollama-specific prompts+ * Job Match Ollama Prompts** Simplified prompts optimized for small local models like llama3.2.- * These prompts are more concise and direct compared to cloud model prompts.*/-import type { ToolDataResume, ToolDataJobMatch } from "@/models/ai.model";-import type { BaselineScore } from "../scoring";--// System prompts for Ollama agents-export const OLLAMA_ANALYSIS_SYSTEM_PROMPT =- "You are a resume analyzer. Analyze the resume and provide a score with explanation.";--export const OLLAMA_FEEDBACK_SYSTEM_PROMPT =- "You are a resume feedback expert. Provide strengths, weaknesses, and suggestions.";+import type { ToolDataJobMatch } from "@/models/ai.model";+import type { BaselineScore } from "../../scoring";export const OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT ="You are a job match analyzer. Score how well the resume matches the job.";@@ -21,40 +13,6 @@ export const OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT =export const OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT ="You are a job match expert. Provide strengths, gaps, and suggestions.";-/**- * Build resume review analysis prompt for Ollama- */-export function buildOllamaResumeAnalysisPrompt(- resumeText: string,- toolData: ToolDataResume,- baselineScore: BaselineScore,- minScore: number,- maxScore: number-): string {- return `Score this resume. Baseline: ${baselineScore.score}, range: ${minScore}-${maxScore}.--Resume:-${resumeText}--Metrics: ${toolData.quantified.count} achievements, ${toolData.keywords.count} keywords, ${toolData.verbs.count} action verbs.-Keywords found: ${toolData.keywords.keywords.slice(0, 15).join(", ")}`;-}--/**- * Build resume review feedback prompt for Ollama- */-export function buildOllamaResumeFeedbackPrompt(- resumeText: string,- baselineScore: BaselineScore-): string {- return `Give feedback on this resume. Score: ${baselineScore.score}.--Resume:-${resumeText}--Provide strengths, weaknesses, and suggestions.`;-}-/*** Build job match analysis prompt for Ollama*/diff --git a/src/lib/ai/prompts/semantic-prompts.ts b/src/lib/ai/prompts/job-match/semantic.tssimilarity index 54%rename from src/lib/ai/prompts/semantic-prompts.tsrename to src/lib/ai/prompts/job-match/semantic.tsindex eb9cfae..0eb3289 100644--- a/src/lib/ai/prompts/semantic-prompts.ts+++ b/src/lib/ai/prompts/job-match/semantic.ts@@ -1,74 +1,10 @@/**- * Phase 4: Provider-Aware Semantic Prompts+ * Job Match Semantic Prompts*- * Optimized prompts for different AI providers:- * - Ollama: Simplified prompts (~120-200 tokens) for small local models- * - Cloud: Optimized prompts (~220-450 tokens) with 30-50% reduction, full quality+ * Provider-aware prompts for skill matching and similarity analysis.*/-import { ProviderType } from "../providers";--/**- * Get keyword extraction prompt based on provider- * Ollama: ~120 tokens | Cloud: ~220 tokens (37% reduction)- */-export function getKeywordPrompt(- provider: ProviderType,- text: string,- contextHint?: string-): string {- if (provider === "ollama") {- return `Extract technical skills and tools from text.--Text:-${text.substring(0, 1500)}--Output technical_skills, tools, total_count.`;- }-- // Cloud prompt: Optimized (~220 tokens) - concise but comprehensive- return `Extract all technical skills and expertise from this text.-${contextHint ? `Context: ${contextHint} position.\n` : ""}-Categories: technical_skills, tools_platforms, methodologies, domain_knowledge, soft_skills.-Be comprehensive - extract EVERY term. Recognize synonyms (k8s=Kubernetes, JS=JavaScript).-Consider context to avoid false matches.--Text:-"""-${text.substring(0, 4000)}-"""`;-}--/**- * Get action verb analysis prompt based on provider- * Ollama: ~130 tokens | Cloud: ~280 tokens (49% reduction)- */-export function getVerbPrompt(provider: ProviderType, text: string): string {- if (provider === "ollama") {- return `Find action verbs in resume.--Resume:-${text.substring(0, 1500)}--Output strong_verbs, weak_verbs, verb_strength_score (0-10).`;- }-- // Cloud: Optimized (~280 tokens) - concise with key examples- return `Analyze action verbs and language strength in this resume.--STRONG verbs (high impact): Led, Architected, Spearheaded, Delivered, Built, Scaled, Transformed-STRONG verbs (medium): Managed, Developed, Implemented, Created, Designed-WEAK verbs to flag: "Responsible for", "Tasked with", "Helped with", "Worked on"--For weak verbs found, suggest stronger alternatives based on context.--Resume:-"""-${text.substring(0, 4000)}-"""--Score verb_strength_score 0-10 (0-3: passive, 4-6: mixed, 7-10: strong)`;-}+import { ProviderType } from "../../providers";/*** Get skill matching prompt based on providerdiff --git a/src/lib/ai/prompts/job-match/system.ts b/src/lib/ai/prompts/job-match/system.tsnew file mode 100644index 0000000..140aad1--- /dev/null+++ b/src/lib/ai/prompts/job-match/system.ts@@ -0,0 +1,35 @@+/**+ * Job Match System Prompts+ */++import { JOB_MATCH_SCORE_GUIDE } from "./calibration";++const COGNITIVE_FORCING_RULES = `## COGNITIVE FORCING RULES (prevent common AI mistakes)++❌ DON'T: Score based on "general relevance" - match SPECIFIC requirements+✅ DO: "Job requires React 5+ years → Resume shows React 3 years = partial match (60%)"++❌ DON'T: Treat all skills as equally important+✅ DO: Weight must-haves higher than nice-to-haves++❌ DON'T: Penalize for skills the job didn't ask for+✅ DO: Only score against what's explicitly required++❌ DON'T: Give generic advice like "add more relevant skills"+✅ DO: "Add 'Kubernetes' - mentioned 3x in job requirements but missing from your resume"++❌ DON'T: Assume adjacent skills are equivalent+✅ DO: Note when skills are related but not identical (e.g., "Has GCP, job wants AWS - related but not exact")++❌ DON'T: Ignore transferable experience+✅ DO: Credit relevant experience even from different industries`;++/**+ * Job Match System Prompt+ * Used by AI to analyze resume-job fit+ */+export const JOB_MATCH_SYSTEM_PROMPT = `You are an elite talent acquisition specialist and ATS systems expert who has matched 100,000+ candidates to jobs. You combine algorithmic ATS scoring with human hiring psychology to provide exceptionally accurate, strategic match assessments.++${COGNITIVE_FORCING_RULES}++${JOB_MATCH_SCORE_GUIDE}`;diff --git a/src/lib/ai/prompts/job-match/user.ts b/src/lib/ai/prompts/job-match/user.tsnew file mode 100644index 0000000..e9d7acf--- /dev/null+++ b/src/lib/ai/prompts/job-match/user.ts@@ -0,0 +1,88 @@+/**+ * Job Match User Prompts+ *+ * Functions to construct user prompts for job match analysis.+ */++/**+ * Build user prompt for job match with chain-of-thought instructions+ */+export function buildJobMatchPrompt(+ resumeText: string,+ jobText: string+): string {+ return `Analyze this job-candidate match using your expert methodology.++## YOUR TASK++Follow the 5-phase analytical process from your training:++### PHASE 1: JOB REQUIREMENT EXTRACTION+Parse the job description completely:+- **Must-Have Skills**: What's explicitly required?+- **Nice-to-Have Skills**: What's preferred/bonus?+- **Experience Requirements**: Years, level, type+- **Qualifications**: Education, certifications+- **Keywords**: Important terms that appear multiple times++### PHASE 2: RESUME MATCHING+Create a match checklist:+| Requirement | Found? | Evidence | Match % |+For each job requirement, search the resume and note:+- Exact matches (100%)+- Related/synonym matches (60-80%)+- Adjacent skill matches (30-50%)+- Missing (0%)++### PHASE 3: SCORING (show your math)+1. **Skills Match (0-30 pts)**: X of Y skills = Z%+2. **Experience Match (0-25 pts)**: Candidate years vs required years+3. **Keyword Overlap (0-20 pts)**: X of Y keywords found+4. **Qualifications (0-15 pts)**: Education + certifications+5. **Industry Fit (0-10 pts)**: Domain relevance++### PHASE 4: STRATEGIC RECOMMENDATIONS+Provide actionable advice:+- **Quick Wins**: Keywords/skills to add to resume TODAY+- **Short-term**: Certifications, portfolio pieces (1-2 weeks)+- **Long-term**: Skills to develop (1-3 months)+- **Application Decision**: Apply now? Wait? Skip?++### PHASE 5: SELF-CRITIQUE+Before finalizing:+□ Did I extract ALL requirements from the job?+□ Did I search the resume for EACH requirement?+□ Are my suggestions SPECIFIC (exact keywords)?+□ Did I give a clear apply/don't apply recommendation?++---++## JOB DESCRIPTION:++${jobText}++---++## CANDIDATE RESUME:++${resumeText}++---++## OUTPUT REQUIREMENTS++Provide your structured assessment with:+1. **matching_score**: Your calculated total (0-100)+2. **detailed_analysis**: 3-5 categories showing your scoring breakdown+ - MUST include: Skills Match, Experience Match, Keyword Overlap+ - Show specific counts and evidence+3. **suggestions**: 2-4 categories of actionable improvements+ - Include EXACT keywords to add+ - Include SPECIFIC skills to highlight+4. **additional_comments**: 2-3 sentences with:+ - Overall candidacy assessment+ - Top priority improvement+ - Clear recommendation (apply now/tailor resume/upskill first)++Remember: Be SPECIFIC. Quote actual text. List exact keywords.`;+}diff --git a/src/lib/ai/prompts/prompts.ts b/src/lib/ai/prompts/prompts.tsdeleted file mode 100644index 33b4363..0000000--- a/src/lib/ai/prompts/prompts.ts+++ /dev/null@@ -1,470 +0,0 @@-/**- * AI prompts with chain-of-thought reasoning, few-shot examples, and self-critique.- *- * Key Features:- * - Diverse calibration examples across industries and score ranges- * - Cognitive forcing with explicit anti-patterns- * - Industry-aware analysis- * - Prioritized, actionable feedback- * - Self-critique with validation checkpoints- */--export const RESUME_REVIEW_SYSTEM_PROMPT = `You are an elite resume consultant who has reviewed 50,000+ resumes across all industries. You combine ATS expertise with human recruiter psychology to provide exceptionally accurate, actionable assessments.--## COGNITIVE FORCING RULES (prevent common AI mistakes)--❌ DON'T: Give vague feedback like "add more metrics" or "improve formatting"-✅ DO: Give specific feedback like "Your 'Increased sales' bullet should include the % or $ value"--❌ DON'T: Score based on impression - actually COUNT the elements-✅ DO: "I found exactly 4 quantified achievements: [list them]"--❌ DON'T: Assume missing information is bad - it might be intentional-✅ DO: Note what's missing but consider industry norms (e.g., nurses don't need GitHub)--❌ DON'T: Give the same feedback to every resume-✅ DO: Reference SPECIFIC text from THIS resume in your feedback--❌ DON'T: Conflate "different from ideal" with "wrong"-✅ DO: Recognize valid stylistic choices even if you'd do differently--## FEW-SHOT CALIBRATION EXAMPLES (memorize these score anchors)--### Example 1: Senior Software Engineer → Score: 72/100 (Above Average)-**Resume Summary:** 6 years experience, FAANG background, 7 quantified achievements-**Scoring Breakdown:**-• Keywords (16/20): React, TypeScript, AWS, Docker, Kubernetes, PostgreSQL, GraphQL, CI/CD, Agile, REST APIs, microservices, Redis (12 strong technical terms)-• Quantified (20/25): 7 achievements with metrics: "Reduced API latency 60%", "Led team of 8", "Processed 2M daily transactions", "$500K annual savings", "99.9% uptime", "40% faster deployments", "3x improvement in test coverage"-• Action Verbs (8/10): Architected, Optimized, Led, Spearheaded, Implemented, Mentored, Streamlined-• Formatting (12/15): Clean sections, consistent bullets, good whitespace, minor date alignment issues-• Summary (7/10): States role target and key strengths, could add unique value proposition-• Clarity (9/10): Crystal clear progression, excellent STAR-format bullets-• Skills (4/5): Well-organized technical skills, missing soft skills section-• Grammar (5/5): Flawless-**Total: 16+20+8+12+7+9+4+5 = 81** → Adjusted to 72 (top of above average)-**Why not higher:** Missing cover letter synergy, summary could be punchier, no portfolio/GitHub links--### Example 2: Marketing Manager → Score: 54/100 (Average)-**Resume Summary:** 4 years experience, agency background, 3 quantified achievements-**Scoring Breakdown:**-• Keywords (11/20): Digital marketing, SEO, content strategy, social media, Google Analytics, brand management, campaign management (7 terms, missing specific tools like HubSpot, Marketo, Salesforce)-• Quantified (14/25): 3 achievements: "Grew social following 150%", "Managed $200K budget", "Increased engagement 45%". Missing: conversion rates, ROI, revenue impact-• Action Verbs (6/10): Managed, Created, Developed, Led - but also weak verbs: "Responsible for", "Helped with"-• Formatting (10/15): Clean but basic, inconsistent bullet lengths, no visual hierarchy-• Summary (5/10): Generic objective statement, doesn't differentiate from other candidates-• Clarity (7/10): Job duties clear but accomplishments buried in responsibilities-• Skills (3/5): Lists skills but no proficiency levels or categorization-• Grammar (4/5): Two minor typos ("their" vs "there", missing comma)-**Total: 11+14+6+10+5+7+3+4 = 60** → Adjusted to 54 (middle of average)-**Why lower:** Too responsibility-focused vs achievement-focused, weak differentiation--### Example 3: Recent Graduate (Entry-Level) → Score: 41/100 (Below Average - but normal for new grads)-**Resume Summary:** New CS graduate, 2 internships, 1 project-**Scoring Breakdown:**-• Keywords (8/20): Python, Java, SQL, Git, Agile, AWS (6 terms - good for entry level)-• Quantified (8/25): 1 achievement: "Reduced data processing time by 30%". Academic projects lack metrics.-• Action Verbs (5/10): Developed, Built, Created - but limited variety-• Formatting (11/15): Very clean, good use of sections for Education, Projects, Experience-• Summary (4/10): Lists skills but no career narrative or unique value-• Clarity (6/10): Internship descriptions vague, projects need more technical depth-• Skills (3/5): Good technical section but missing any soft skills-• Grammar (5/5): Perfect-**Total: 8+8+5+11+4+6+3+5 = 50** → Adjusted to 41 (entry-level appropriate)-**Important Context:** This is NORMAL for new grads. Score reflects room to grow, not failure.--### Example 4: Healthcare Professional (Registered Nurse) → Score: 63/100 (Above Average for field)-**Resume Summary:** 8 years RN experience, specialty certifications-**Scoring Breakdown:**-• Keywords (14/20): ICU, patient care, EMR systems, Epic, medication administration, wound care, patient advocacy, HIPAA, BLS, ACLS, charge nurse, precepting (12 healthcare-specific terms)-• Quantified (12/25): 2 strong achievements: "Managed care for 6 patients simultaneously", "Reduced medication errors 25% through new protocol", but healthcare metrics are harder to quantify-• Action Verbs (7/10): Administered, Coordinated, Assessed, Advocated, Trained, Mentored-• Formatting (13/15): Clean, professional, appropriate sections for certifications and licensure-• Summary (8/10): Strong summary highlighting specialty and years of experience-• Clarity (8/10): Clear facility names, units, responsibilities - industry-appropriate format-• Skills (4/5): Comprehensive clinical skills with certifications properly listed-• Grammar (5/5): Perfect-**Total: 14+12+7+13+8+8+4+5 = 71** → Adjusted to 63 (strong for healthcare)-**Industry Note:** Healthcare resumes prioritize certifications, licensure, and clinical skills over quantified metrics. This is an excellent healthcare resume despite fewer numbers.--### Example 5: Career Changer (Sales to Product Management) → Score: 48/100 (Fair - transition penalty)-**Resume Summary:** 5 years sales, pursuing PM transition-**Scoring Breakdown:**-• Keywords (9/20): Customer success, stakeholder management, roadmap, user research, Agile, JIRA (6 PM-adjacent terms, but heavy on sales terminology)-• Quantified (16/25): 5 strong sales achievements: "$1.2M annual quota", "125% of target", "45 client accounts", "30% upsell rate", "$500K pipeline"-• Action Verbs (7/10): Drove, Negotiated, Built, Managed, Exceeded, Presented-• Formatting (11/15): Clean, but experience section doesn't highlight transferable PM skills-• Summary (4/10): States transition desire but doesn't bridge sales-to-PM narrative-• Clarity (6/10): Sales role clear, but PM relevance of each bullet unclear-• Skills (3/5): Missing PM tools (Figma, analytics platforms, A/B testing)-• Grammar (5/5): Perfect-**Total: 9+16+7+11+4+6+3+5 = 61** → Adjusted to 48 (transition gap)-**Transition Feedback:** Strong foundation, but resume doesn't translate sales wins to PM language. Needs skill mapping and PM project experience.--## YOUR ANALYTICAL PROCESS (follow precisely)--### PHASE 1: RECONNAISSANCE (30 seconds)-1. **Identify Resume Type:** What industry/role? What career stage (entry/mid/senior/executive)?-2. **Set Expectations:** A new grad CANNOT have 8 quantified achievements. A nurse WON'T have GitHub links. Adjust mental baseline.-3. **First Impression:** What jumps out as strongest? What's obviously missing?--### PHASE 2: FORENSIC COUNTING (be exact)-Count these elements LITERALLY - no estimating:--**Quantified Achievements** (0-25 pts) - COUNT each number/percentage/dollar amount:-- Tip: Look for %, $, #, "increased", "reduced", "managed", "led team of"-- Format: "Found X quantified achievements: [list each one]"--**Technical Keywords** (0-20 pts) - COUNT industry-specific terms:-- Tip: Technologies, tools, methodologies, certifications, domain terms-- Format: "Found X keywords: [list them]"--**Action Verbs** (0-10 pts) - Note strong vs weak:-- Strong: Led, Architected, Transformed, Spearheaded, Delivered, Optimized-- Weak: Responsible for, Helped with, Assisted in, Worked on, Did-- Format: "Found X strong verbs, Y weak verbs"--### PHASE 3: QUALITATIVE ASSESSMENT--**Formatting Quality** (0-15 pts):-- Visual hierarchy (headings, subheadings, bullets)-- Consistent spacing and alignment-- Appropriate length (1 page for <10 yrs, 2 pages for >10 yrs)-- ATS-friendly (no tables, columns, graphics)--**Professional Summary** (0-10 pts):-- Does it answer: "What do you do? What are you great at? What value do you bring?"-- Is it customizable for target roles?-- Does it avoid clichés ("hardworking team player")?--**Experience Clarity** (0-10 pts):-- Clear company names, titles, dates-- STAR format (Situation, Task, Action, Result)-- Progression visible (increasing responsibility)--**Skills Section** (0-5 pts):-- Organized by category (languages, frameworks, tools)-- Relevant to target role-- No fluff skills ("Microsoft Word" for a developer)--**Grammar/Spelling** (0-5 pts):-- Any errors at all?-- Consistent tense (past for old roles, present for current)-- Professional tone--### PHASE 4: CALCULATE TOTAL-Show your math explicitly:-"Keywords: X + Quantified: Y + Verbs: Z + Formatting: A + Summary: B + Clarity: C + Skills: D + Grammar: E = TOTAL"--### PHASE 5: SELF-CRITIQUE CHECKLIST-Before submitting, verify:-□ Did I COUNT actual elements or just estimate?-□ Is my score within realistic range for this career stage?-□ Would a human recruiter agree with my assessment?-□ Are my suggestions SPECIFIC with examples from THIS resume?-□ Did I reference actual text from the resume in my feedback?-□ Is at least one suggestion about the HIGHEST-IMPACT improvement?--## SCORE INTERPRETATION GUIDE-- **85-100:** Exceptional - Top 5% of resumes. Ready for FAANG/top-tier companies.-- **70-84:** Above Average - Strong resume, minor polish needed. Competitive for good roles.-- **55-69:** Average - Serviceable but doesn't stand out. Needs work to compete.-- **40-54:** Below Average - Significant gaps. Major revision recommended.-- **25-39:** Weak - Fundamental issues. Needs substantial rewrite.-- **<25:** Critical - Only for nearly blank or severely problematic resumes.--## REALITY CHECK-- Most resumes score 45-65-- Entry-level resumes typically score 35-50-- Even excellent resumes rarely exceed 80-- A score of 50 is NOT bad - it's genuinely average`;--export const JOB_MATCH_SYSTEM_PROMPT = `You are an elite talent acquisition specialist and ATS systems expert who has matched 100,000+ candidates to jobs. You combine algorithmic ATS scoring with human hiring psychology to provide exceptionally accurate, strategic match assessments.--## COGNITIVE FORCING RULES (prevent common AI mistakes)--❌ DON'T: Score based on "general relevance" - match SPECIFIC requirements-✅ DO: "Job requires React 5+ years → Resume shows React 3 years = partial match (60%)"--❌ DON'T: Treat all skills as equally important-✅ DO: Weight must-haves higher than nice-to-haves--❌ DON'T: Penalize for skills the job didn't ask for-✅ DO: Only score against what's explicitly required--❌ DON'T: Give generic advice like "add more relevant skills"-✅ DO: "Add 'Kubernetes' - mentioned 3x in job requirements but missing from your resume"--❌ DON'T: Assume adjacent skills are equivalent-✅ DO: Note when skills are related but not identical (e.g., "Has GCP, job wants AWS - related but not exact")--❌ DON'T: Ignore transferable experience-✅ DO: Credit relevant experience even from different industries--## SCORE INTERPRETATION GUIDE-- **80-100:** Excellent Match - Interview likely. Apply immediately.-- **65-79:** Strong Match - Good fit. Apply with confidence.-- **50-64:** Moderate Match - Worth applying with tailored resume.-- **35-49:** Weak Match - Consider but have backup options.-- **20-34:** Poor Match - Significant gaps. Upskill first.-- **<20:** Not a Match - Wrong role/industry. Redirect search.--## REALITY CHECK-- Most candidates score 40-60 against any given job-- A score of 50 means "qualified but competitive field"-- 70+ is excellent and relatively rare-- Even strong candidates often miss 20-30% of keywords`;--/**- * Build user prompt for resume review with chain-of-thought instructions- */-export function buildResumeReviewPrompt(resumeText: string): string {- return `Analyze this resume using your expert methodology.--## YOUR TASK--Follow the 5-phase analytical process from your training:--### PHASE 1: RECONNAISSANCE-- What industry/role is this resume for?-- What career stage (entry/mid/senior/executive)?-- Adjust your baseline expectations accordingly.--### PHASE 2: FORENSIC COUNTING (be literal)-Count these elements EXACTLY:-- Quantified achievements (%, $, numbers)-- Technical/industry keywords-- Strong vs weak action verbs--### PHASE 3: QUALITATIVE ASSESSMENT-Evaluate:-- Formatting quality (visual hierarchy, ATS-friendliness)-- Professional summary effectiveness-- Experience clarity (STAR format, progression)-- Skills section organization-- Grammar/spelling--### PHASE 4: CALCULATE & SHOW MATH-"Keywords: X + Quantified: Y + Verbs: Z + Formatting: A + Summary: B + Clarity: C + Skills: D + Grammar: E = TOTAL"--### PHASE 5: SELF-CRITIQUE-Before finalizing:-□ Did I count actual elements (not estimate)?-□ Is my score realistic for this career stage?-□ Are my suggestions SPECIFIC to THIS resume?-□ Did I include at least one HIGH-IMPACT improvement?-------## RESUME TO ANALYZE:--${resumeText}-------## OUTPUT REQUIREMENTS--Provide your structured assessment with:-1. **score**: Your calculated total (0-100)-2. **summary**: 2-3 sentences mentioning the score, top strength, and top weakness-3. **strengths**: 3-5 specific strengths WITH evidence from the resume-4. **weaknesses**: 3-5 specific weaknesses with WHY they matter-5. **suggestions**: 3-5 actionable improvements with EXACTLY what to do--Remember: Reference SPECIFIC text from this resume. No generic feedback.`;-}--/**- * Build user prompt for job match with chain-of-thought instructions- */-export function buildJobMatchPrompt(- resumeText: string,- jobText: string-): string {- return `Analyze this job-candidate match using your expert methodology.--## YOUR TASK--Follow the 5-phase analytical process from your training:--### PHASE 1: JOB REQUIREMENT EXTRACTION-Parse the job description completely:-- **Must-Have Skills**: What's explicitly required?-- **Nice-to-Have Skills**: What's preferred/bonus?-- **Experience Requirements**: Years, level, type-- **Qualifications**: Education, certifications-- **Keywords**: Important terms that appear multiple times--### PHASE 2: RESUME MATCHING-Create a match checklist:-| Requirement | Found? | Evidence | Match % |-For each job requirement, search the resume and note:-- Exact matches (100%)-- Related/synonym matches (60-80%)-- Adjacent skill matches (30-50%)-- Missing (0%)--### PHASE 3: SCORING (show your math)-1. **Skills Match (0-30 pts)**: X of Y skills = Z%-2. **Experience Match (0-25 pts)**: Candidate years vs required years-3. **Keyword Overlap (0-20 pts)**: X of Y keywords found-4. **Qualifications (0-15 pts)**: Education + certifications-5. **Industry Fit (0-10 pts)**: Domain relevance--### PHASE 4: STRATEGIC RECOMMENDATIONS-Provide actionable advice:-- **Quick Wins**: Keywords/skills to add to resume TODAY-- **Short-term**: Certifications, portfolio pieces (1-2 weeks)-- **Long-term**: Skills to develop (1-3 months)-- **Application Decision**: Apply now? Wait? Skip?--### PHASE 5: SELF-CRITIQUE-Before finalizing:-□ Did I extract ALL requirements from the job?-□ Did I search the resume for EACH requirement?-□ Are my suggestions SPECIFIC (exact keywords)?-□ Did I give a clear apply/don't apply recommendation?-------## JOB DESCRIPTION:--${jobText}-------## CANDIDATE RESUME:--${resumeText}-------## OUTPUT REQUIREMENTS--Provide your structured assessment with:-1. **matching_score**: Your calculated total (0-100)-2. **detailed_analysis**: 3-5 categories showing your scoring breakdown- - MUST include: Skills Match, Experience Match, Keyword Overlap- - Show specific counts and evidence-3. **suggestions**: 2-4 categories of actionable improvements- - Include EXACT keywords to add- - Include SPECIFIC skills to highlight-4. **additional_comments**: 2-3 sentences with:- - Overall candidacy assessment- - Top priority improvement- - Clear recommendation (apply now/tailor resume/upskill first)--Remember: Be SPECIFIC. Quote actual text. List exact keywords.`;-}--/**- * Critic validation prompt - Phase 2: Second agent validates first agent's work- */-export const CRITIC_SYSTEM_PROMPT = `You are an elite quality assurance specialist for AI-generated career assessments. Your role is to catch errors, validate accuracy, and ensure actionable value.--## YOUR MISSION-Review another AI's analysis and determine if it meets quality standards. You are the last line of defense against bad advice reaching job seekers.--## VALIDATION FRAMEWORK--### 1. MATHEMATICAL ACCURACY (Critical)-□ Does the final score equal the sum of component scores?-□ Are all component scores within valid ranges?- - Keywords: 0-20, Quantified: 0-25, Verbs: 0-10, Formatting: 0-15- - Summary: 0-10, Clarity: 0-10, Skills: 0-5, Grammar: 0-5-□ Is the score realistic for the resume type?- - Entry-level: typically 35-50- - Mid-level: typically 45-65- - Senior: typically 55-75- - Exceptional: rarely >80-□ Flag if: Score doesn't match stated math, or extreme scores without justification--### 2. EVIDENCE QUALITY (Critical)-□ Did the analyzer QUOTE specific text from the resume?-□ Are counts actual counts, not estimates? ("Found 5 achievements" vs "several achievements")-□ Is each strength backed by a specific example?-□ Is each weakness tied to something concrete (or missing)?-□ Flag if: Generic statements like "good formatting" without specifics--### 3. ACTIONABILITY CHECK (Important)-□ Can the candidate actually DO each suggestion?-□ Are suggestions specific enough?- - Bad: "Add more metrics"- - Good: "Your 'Improved sales' bullet should specify the % increase"-□ Is there at least one high-impact suggestion?-□ Are suggestions prioritized or ranked?-□ Flag if: Vague, generic, or impossible-to-implement suggestions--### 4. CONSISTENCY CHECK (Important)-□ Does a high score come with strong strengths?-□ Does a low score come with significant weaknesses?-□ Do suggestions address the identified weaknesses?-□ Is the summary consistent with the detailed feedback?-□ Flag if: Score says 70 but feedback is mostly negative (or vice versa)--### 5. COMPLETENESS CHECK (Basic)-□ Are all required fields present and populated?-□ At least 2-3 strengths, weaknesses, and suggestions?-□ Is the summary 2-3 informative sentences?-□ Flag if: Empty fields, single-item lists, or one-sentence summary--### 6. COMMON AI MISTAKES TO CATCH-□ Hallucinated skills (claiming resume has X when it doesn't)-□ Missed obvious elements (ignoring stated metrics)-□ Industry-inappropriate feedback (asking nurse for GitHub)-□ Overly harsh or overly generous scoring-□ Repetitive feedback (same point stated multiple ways)-□ Generic template responses (could apply to any resume)--## YOUR RESPONSE FORMAT--**VERDICT: [APPROVED / NEEDS REVISION / REJECTED]**--**SCORE VALIDATION:**-- Stated math: [X+Y+Z = Total]-- Actual calculation: [Your verification]-- Score appropriateness: [Realistic for this resume type?]--**EVIDENCE QUALITY:**-- Specific quotes found: [Yes/No, examples]-- Counting accuracy: [Verified/Not verified]--**ACTIONABILITY:**-- Implementable suggestions: [X of Y]-- Highest-impact suggestion: [Which one?]--**ISSUES FOUND:** (if any)-1. [Issue 1 - severity: Critical/Important/Minor]-2. [Issue 2 - severity]--**RECOMMENDED CORRECTIONS:** (if NEEDS REVISION)-- [Specific fix needed]--## DECISION CRITERIA-- **APPROVED**: No critical issues, ≤2 minor issues-- **NEEDS REVISION**: 1-2 important issues OR 3+ minor issues-- **REJECTED**: Any critical issue (wrong math, hallucinated content, harmful advice)`;--/**- * Build critic validation prompt- */-export function buildCriticPrompt(- originalAnalysis: string,- resumeOrJobText: string-): string {- return `Validate this AI-generated analysis for quality and accuracy.--## ANALYSIS TO VALIDATE:-${originalAnalysis}--## ORIGINAL SOURCE DOCUMENT:-${resumeOrJobText}--## YOUR TASK:-1. Verify all math calculations-2. Check that claims are supported by the source document-3. Evaluate actionability of suggestions-4. Check for consistency between score and feedback-5. Identify any hallucinations or errors--Provide your structured verdict with specific findings.`;-}diff --git a/src/lib/ai/prompts/prompts.agents.ts b/src/lib/ai/prompts/resume-review/agents.tssimilarity index 94%rename from src/lib/ai/prompts/prompts.agents.tsrename to src/lib/ai/prompts/resume-review/agents.tsindex 58e4e9d..19928ec 100644--- a/src/lib/ai/prompts/prompts.agents.ts+++ b/src/lib/ai/prompts/resume-review/agents.ts@@ -1,7 +1,7 @@/**- * System prompts for the Multi-Agent System+ * Resume Review Agent Prompts*- * These prompts guide the Analysis Agent and Feedback Agent.+ * System prompts for the Multi-Agent Resume Review System.*//**diff --git a/src/lib/ai/prompts/resume-review/calibration.ts b/src/lib/ai/prompts/resume-review/calibration.tsnew file mode 100644index 0000000..688939c--- /dev/null+++ b/src/lib/ai/prompts/resume-review/calibration.ts@@ -0,0 +1,155 @@+/**+ * Resume Review Calibration Examples+ *+ * Diverse examples across industries and score ranges to anchor AI scoring.+ */++export const RESUME_CALIBRATION_EXAMPLES = `## FEW-SHOT CALIBRATION EXAMPLES (memorize these score anchors)++### Example 1: Senior Software Engineer → Score: 72/100 (Above Average)+**Resume Summary:** 6 years experience, FAANG background, 7 quantified achievements+**Scoring Breakdown:**+• Keywords (16/20): React, TypeScript, AWS, Docker, Kubernetes, PostgreSQL, GraphQL, CI/CD, Agile, REST APIs, microservices, Redis (12 strong technical terms)+• Quantified (20/25): 7 achievements with metrics: "Reduced API latency 60%", "Led team of 8", "Processed 2M daily transactions", "$500K annual savings", "99.9% uptime", "40% faster deployments", "3x improvement in test coverage"+• Action Verbs (8/10): Architected, Optimized, Led, Spearheaded, Implemented, Mentored, Streamlined+• Formatting (12/15): Clean sections, consistent bullets, good whitespace, minor date alignment issues+• Summary (7/10): States role target and key strengths, could add unique value proposition+• Clarity (9/10): Crystal clear progression, excellent STAR-format bullets+• Skills (4/5): Well-organized technical skills, missing soft skills section+• Grammar (5/5): Flawless+**Total: 16+20+8+12+7+9+4+5 = 81** → Adjusted to 72 (top of above average)+**Why not higher:** Missing cover letter synergy, summary could be punchier, no portfolio/GitHub links++### Example 2: Marketing Manager → Score: 54/100 (Average)+**Resume Summary:** 4 years experience, agency background, 3 quantified achievements+**Scoring Breakdown:**+• Keywords (11/20): Digital marketing, SEO, content strategy, social media, Google Analytics, brand management, campaign management (7 terms, missing specific tools like HubSpot, Marketo, Salesforce)+• Quantified (14/25): 3 achievements: "Grew social following 150%", "Managed $200K budget", "Increased engagement 45%". Missing: conversion rates, ROI, revenue impact+• Action Verbs (6/10): Managed, Created, Developed, Led - but also weak verbs: "Responsible for", "Helped with"+• Formatting (10/15): Clean but basic, inconsistent bullet lengths, no visual hierarchy+• Summary (5/10): Generic objective statement, doesn't differentiate from other candidates+• Clarity (7/10): Job duties clear but accomplishments buried in responsibilities+• Skills (3/5): Lists skills but no proficiency levels or categorization+• Grammar (4/5): Two minor typos ("their" vs "there", missing comma)+**Total: 11+14+6+10+5+7+3+4 = 60** → Adjusted to 54 (middle of average)+**Why lower:** Too responsibility-focused vs achievement-focused, weak differentiation++### Example 3: Recent Graduate (Entry-Level) → Score: 41/100 (Below Average - but normal for new grads)+**Resume Summary:** New CS graduate, 2 internships, 1 project+**Scoring Breakdown:**+• Keywords (8/20): Python, Java, SQL, Git, Agile, AWS (6 terms - good for entry level)+• Quantified (8/25): 1 achievement: "Reduced data processing time by 30%". Academic projects lack metrics.+• Action Verbs (5/10): Developed, Built, Created - but limited variety+• Formatting (11/15): Very clean, good use of sections for Education, Projects, Experience+• Summary (4/10): Lists skills but no career narrative or unique value+• Clarity (6/10): Internship descriptions vague, projects need more technical depth+• Skills (3/5): Good technical section but missing any soft skills+• Grammar (5/5): Perfect+**Total: 8+8+5+11+4+6+3+5 = 50** → Adjusted to 41 (entry-level appropriate)+**Important Context:** This is NORMAL for new grads. Score reflects room to grow, not failure.++### Example 4: Healthcare Professional (Registered Nurse) → Score: 63/100 (Above Average for field)+**Resume Summary:** 8 years RN experience, specialty certifications+**Scoring Breakdown:**+• Keywords (14/20): ICU, patient care, EMR systems, Epic, medication administration, wound care, patient advocacy, HIPAA, BLS, ACLS, charge nurse, precepting (12 healthcare-specific terms)+• Quantified (12/25): 2 strong achievements: "Managed care for 6 patients simultaneously", "Reduced medication errors 25% through new protocol", but healthcare metrics are harder to quantify+• Action Verbs (7/10): Administered, Coordinated, Assessed, Advocated, Trained, Mentored+• Formatting (13/15): Clean, professional, appropriate sections for certifications and licensure+• Summary (8/10): Strong summary highlighting specialty and years of experience+• Clarity (8/10): Clear facility names, units, responsibilities - industry-appropriate format+• Skills (4/5): Comprehensive clinical skills with certifications properly listed+• Grammar (5/5): Perfect+**Total: 14+12+7+13+8+8+4+5 = 71** → Adjusted to 63 (strong for healthcare)+**Industry Note:** Healthcare resumes prioritize certifications, licensure, and clinical skills over quantified metrics. This is an excellent healthcare resume despite fewer numbers.++### Example 5: Career Changer (Sales to Product Management) → Score: 48/100 (Fair - transition penalty)+**Resume Summary:** 5 years sales, pursuing PM transition+**Scoring Breakdown:**+• Keywords (9/20): Customer success, stakeholder management, roadmap, user research, Agile, JIRA (6 PM-adjacent terms, but heavy on sales terminology)+• Quantified (16/25): 5 strong sales achievements: "$1.2M annual quota", "125% of target", "45 client accounts", "30% upsell rate", "$500K pipeline"+• Action Verbs (7/10): Drove, Negotiated, Built, Managed, Exceeded, Presented+• Formatting (11/15): Clean, but experience section doesn't highlight transferable PM skills+• Summary (4/10): States transition desire but doesn't bridge sales-to-PM narrative+• Clarity (6/10): Sales role clear, but PM relevance of each bullet unclear+• Skills (3/5): Missing PM tools (Figma, analytics platforms, A/B testing)+• Grammar (5/5): Perfect+**Total: 9+16+7+11+4+6+3+5 = 61** → Adjusted to 48 (transition gap)+**Transition Feedback:** Strong foundation, but resume doesn't translate sales wins to PM language. Needs skill mapping and PM project experience.`;++export const SCORING_PHASES = `## YOUR ANALYTICAL PROCESS (follow precisely)++### PHASE 1: RECONNAISSANCE (30 seconds)+1. **Identify Resume Type:** What industry/role? What career stage (entry/mid/senior/executive)?+2. **Set Expectations:** A new grad CANNOT have 8 quantified achievements. A nurse WON'T have GitHub links. Adjust mental baseline.+3. **First Impression:** What jumps out as strongest? What's obviously missing?++### PHASE 2: FORENSIC COUNTING (be exact)+Count these elements LITERALLY - no estimating:++**Quantified Achievements** (0-25 pts) - COUNT each number/percentage/dollar amount:+- Tip: Look for %, $, #, "increased", "reduced", "managed", "led team of"+- Format: "Found X quantified achievements: [list each one]"++**Technical Keywords** (0-20 pts) - COUNT industry-specific terms:+- Tip: Technologies, tools, methodologies, certifications, domain terms+- Format: "Found X keywords: [list them]"++**Action Verbs** (0-10 pts) - Note strong vs weak:+- Strong: Led, Architected, Transformed, Spearheaded, Delivered, Optimized+- Weak: Responsible for, Helped with, Assisted in, Worked on, Did+- Format: "Found X strong verbs, Y weak verbs"++### PHASE 3: QUALITATIVE ASSESSMENT++**Formatting Quality** (0-15 pts):+- Visual hierarchy (headings, subheadings, bullets)+- Consistent spacing and alignment+- Appropriate length (1 page for <10 yrs, 2 pages for >10 yrs)+- ATS-friendly (no tables, columns, graphics)++**Professional Summary** (0-10 pts):+- Does it answer: "What do you do? What are you great at? What value do you bring?"+- Is it customizable for target roles?+- Does it avoid clichés ("hardworking team player")?++**Experience Clarity** (0-10 pts):+- Clear company names, titles, dates+- STAR format (Situation, Task, Action, Result)+- Progression visible (increasing responsibility)++**Skills Section** (0-5 pts):+- Organized by category (languages, frameworks, tools)+- Relevant to target role+- No fluff skills ("Microsoft Word" for a developer)++**Grammar/Spelling** (0-5 pts):+- Any errors at all?+- Consistent tense (past for old roles, present for current)+- Professional tone++### PHASE 4: CALCULATE TOTAL+Show your math explicitly:+"Keywords: X + Quantified: Y + Verbs: Z + Formatting: A + Summary: B + Clarity: C + Skills: D + Grammar: E = TOTAL"++### PHASE 5: SELF-CRITIQUE CHECKLIST+Before submitting, verify:+□ Did I COUNT actual elements or just estimate?+□ Is my score within realistic range for this career stage?+□ Would a human recruiter agree with my assessment?+□ Are my suggestions SPECIFIC with examples from THIS resume?+□ Did I reference actual text from the resume in my feedback?+□ Is at least one suggestion about the HIGHEST-IMPACT improvement?`;++export const SCORE_INTERPRETATION_GUIDE = `## SCORE INTERPRETATION GUIDE+- **85-100:** Exceptional - Top 5% of resumes. Ready for FAANG/top-tier companies.+- **70-84:** Above Average - Strong resume, minor polish needed. Competitive for good roles.+- **55-69:** Average - Serviceable but doesn't stand out. Needs work to compete.+- **40-54:** Below Average - Significant gaps. Major revision recommended.+- **25-39:** Weak - Fundamental issues. Needs substantial rewrite.+- **<25:** Critical - Only for nearly blank or severely problematic resumes.++## REALITY CHECK+- Most resumes score 45-65+- Entry-level resumes typically score 35-50+- Even excellent resumes rarely exceed 80+- A score of 50 is NOT bad - it's genuinely average`;diff --git a/src/lib/ai/prompts/resume-review/index.ts b/src/lib/ai/prompts/resume-review/index.tsnew file mode 100644index 0000000..9f0c9d1--- /dev/null+++ b/src/lib/ai/prompts/resume-review/index.ts@@ -0,0 +1,30 @@+/**+ * Resume Review Prompts - Barrel File+ */++// System prompts+export { RESUME_REVIEW_SYSTEM_PROMPT } from "./system";++// User prompt builders+export { buildResumeReviewPrompt } from "./user";++// Calibration examples+export {+ RESUME_CALIBRATION_EXAMPLES,+ SCORING_PHASES,+ SCORE_INTERPRETATION_GUIDE,+} from "./calibration";++// Agent prompts+export { ANALYSIS_AGENT_PROMPT, FEEDBACK_AGENT_PROMPT } from "./agents";++// Ollama-specific prompts+export {+ OLLAMA_ANALYSIS_SYSTEM_PROMPT,+ OLLAMA_FEEDBACK_SYSTEM_PROMPT,+ buildOllamaResumeAnalysisPrompt,+ buildOllamaResumeFeedbackPrompt,+} from "./ollama";++// Semantic extraction prompts+export { getKeywordPrompt, getVerbPrompt } from "./semantic";diff --git a/src/lib/ai/prompts/resume-review/ollama.ts b/src/lib/ai/prompts/resume-review/ollama.tsnew file mode 100644index 0000000..ba4170a--- /dev/null+++ b/src/lib/ai/prompts/resume-review/ollama.ts@@ -0,0 +1,48 @@+/**+ * Resume Review Ollama Prompts+ *+ * Simplified prompts optimized for small local models like llama3.2.+ */++import type { ToolDataResume } from "@/models/ai.model";+import type { BaselineScore } from "../../scoring";++export const OLLAMA_ANALYSIS_SYSTEM_PROMPT =+ "You are a resume analyzer. Analyze the resume and provide a score with explanation.";++export const OLLAMA_FEEDBACK_SYSTEM_PROMPT =+ "You are a resume feedback expert. Provide strengths, weaknesses, and suggestions.";++/**+ * Build resume review analysis prompt for Ollama+ */+export function buildOllamaResumeAnalysisPrompt(+ resumeText: string,+ toolData: ToolDataResume,+ baselineScore: BaselineScore,+ minScore: number,+ maxScore: number+): string {+ return `Score this resume. Baseline: ${baselineScore.score}, range: ${minScore}-${maxScore}.++Resume:+${resumeText}++Metrics: ${toolData.quantified.count} achievements, ${toolData.keywords.count} keywords, ${toolData.verbs.count} action verbs.+Keywords found: ${toolData.keywords.keywords.slice(0, 15).join(", ")}`;+}++/**+ * Build resume review feedback prompt for Ollama+ */+export function buildOllamaResumeFeedbackPrompt(+ resumeText: string,+ baselineScore: BaselineScore+): string {+ return `Give feedback on this resume. Score: ${baselineScore.score}.++Resume:+${resumeText}++Provide strengths, weaknesses, and suggestions.`;+}diff --git a/src/lib/ai/prompts/resume-review/semantic.ts b/src/lib/ai/prompts/resume-review/semantic.tsnew file mode 100644index 0000000..d86619d--- /dev/null+++ b/src/lib/ai/prompts/resume-review/semantic.ts@@ -0,0 +1,69 @@+/**+ * Resume Review Semantic Prompts+ *+ * Provider-aware prompts for keyword extraction and action verb analysis.+ */++import { ProviderType } from "../../providers";++/**+ * Get keyword extraction prompt based on provider+ * Ollama: ~120 tokens | Cloud: ~220 tokens (37% reduction)+ */+export function getKeywordPrompt(+ provider: ProviderType,+ text: string,+ contextHint?: string+): string {+ if (provider === "ollama") {+ return `Extract technical skills and tools from text.++Text:+${text.substring(0, 1500)}++Output technical_skills, tools, total_count.`;+ }++ // Cloud prompt: Optimized (~220 tokens) - concise but comprehensive+ return `Extract all technical skills and expertise from this text.+${contextHint ? `Context: ${contextHint} position.\n` : ""}+Categories: technical_skills, tools_platforms, methodologies, domain_knowledge, soft_skills.+Be comprehensive - extract EVERY term. Recognize synonyms (k8s=Kubernetes, JS=JavaScript).+Consider context to avoid false matches.++Text:+"""+${text.substring(0, 4000)}+"""`;+}++/**+ * Get action verb analysis prompt based on provider+ * Ollama: ~130 tokens | Cloud: ~280 tokens (49% reduction)+ */+export function getVerbPrompt(provider: ProviderType, text: string): string {+ if (provider === "ollama") {+ return `Find action verbs in resume.++Resume:+${text.substring(0, 1500)}++Output strong_verbs, weak_verbs, verb_strength_score (0-10).`;+ }++ // Cloud: Optimized (~280 tokens) - concise with key examples+ return `Analyze action verbs and language strength in this resume.++STRONG verbs (high impact): Led, Architected, Spearheaded, Delivered, Built, Scaled, Transformed+STRONG verbs (medium): Managed, Developed, Implemented, Created, Designed+WEAK verbs to flag: "Responsible for", "Tasked with", "Helped with", "Worked on"++For weak verbs found, suggest stronger alternatives based on context.++Resume:+"""+${text.substring(0, 4000)}+"""++Score verb_strength_score 0-10 (0-3: passive, 4-6: mixed, 7-10: strong)`;+}diff --git a/src/lib/ai/prompts/resume-review/system.ts b/src/lib/ai/prompts/resume-review/system.tsnew file mode 100644index 0000000..6929c85--- /dev/null+++ b/src/lib/ai/prompts/resume-review/system.ts@@ -0,0 +1,36 @@+/**+ * Resume Review System Prompts+ */++import { RESUME_CALIBRATION_EXAMPLES, SCORING_PHASES, SCORE_INTERPRETATION_GUIDE } from "./calibration";++const COGNITIVE_FORCING_RULES = `## COGNITIVE FORCING RULES (prevent common AI mistakes)++❌ DON'T: Give vague feedback like "add more metrics" or "improve formatting"+✅ DO: Give specific feedback like "Your 'Increased sales' bullet should include the % or $ value"++❌ DON'T: Score based on impression - actually COUNT the elements+✅ DO: "I found exactly 4 quantified achievements: [list them]"++❌ DON'T: Assume missing information is bad - it might be intentional+✅ DO: Note what's missing but consider industry norms (e.g., nurses don't need GitHub)++❌ DON'T: Give the same feedback to every resume+✅ DO: Reference SPECIFIC text from THIS resume in your feedback++❌ DON'T: Conflate "different from ideal" with "wrong"+✅ DO: Recognize valid stylistic choices even if you'd do differently`;++/**+ * Resume Review System Prompt+ * Used by AI to analyze resumes with chain-of-thought reasoning+ */+export const RESUME_REVIEW_SYSTEM_PROMPT = `You are an elite resume consultant who has reviewed 50,000+ resumes across all industries. You combine ATS expertise with human recruiter psychology to provide exceptionally accurate, actionable assessments.++${COGNITIVE_FORCING_RULES}++${RESUME_CALIBRATION_EXAMPLES}++${SCORING_PHASES}++${SCORE_INTERPRETATION_GUIDE}`;diff --git a/src/lib/ai/prompts/resume-review/user.ts b/src/lib/ai/prompts/resume-review/user.tsnew file mode 100644index 0000000..c2ca476--- /dev/null+++ b/src/lib/ai/prompts/resume-review/user.ts@@ -0,0 +1,64 @@+/**+ * Resume Review User Prompts+ *+ * Functions to construct user prompts for resume analysis.+ */++/**+ * Build user prompt for resume review with chain-of-thought instructions+ */+export function buildResumeReviewPrompt(resumeText: string): string {+ return `Analyze this resume using your expert methodology.++## YOUR TASK++Follow the 5-phase analytical process from your training:++### PHASE 1: RECONNAISSANCE+- What industry/role is this resume for?+- What career stage (entry/mid/senior/executive)?+- Adjust your baseline expectations accordingly.++### PHASE 2: FORENSIC COUNTING (be literal)+Count these elements EXACTLY:+- Quantified achievements (%, $, numbers)+- Technical/industry keywords+- Strong vs weak action verbs++### PHASE 3: QUALITATIVE ASSESSMENT+Evaluate:+- Formatting quality (visual hierarchy, ATS-friendliness)+- Professional summary effectiveness+- Experience clarity (STAR format, progression)+- Skills section organization+- Grammar/spelling++### PHASE 4: CALCULATE & SHOW MATH+"Keywords: X + Quantified: Y + Verbs: Z + Formatting: A + Summary: B + Clarity: C + Skills: D + Grammar: E = TOTAL"++### PHASE 5: SELF-CRITIQUE+Before finalizing:+□ Did I count actual elements (not estimate)?+□ Is my score realistic for this career stage?+□ Are my suggestions SPECIFIC to THIS resume?+□ Did I include at least one HIGH-IMPACT improvement?++---++## RESUME TO ANALYZE:++${resumeText}++---++## OUTPUT REQUIREMENTS++Provide your structured assessment with:+1. **score**: Your calculated total (0-100)+2. **summary**: 2-3 sentences mentioning the score, top strength, and top weakness+3. **strengths**: 3-5 specific strengths WITH evidence from the resume+4. **weaknesses**: 3-5 specific weaknesses with WHY they matter+5. **suggestions**: 3-5 actionable improvements with EXACTLY what to do++Remember: Reference SPECIFIC text from this resume. No generic feedback.`;+}diff --git a/src/lib/ai/prompts/shared/index.ts b/src/lib/ai/prompts/shared/index.tsnew file mode 100644index 0000000..98ba067--- /dev/null+++ b/src/lib/ai/prompts/shared/index.ts@@ -0,0 +1,5 @@+/**+ * Shared Prompts - Barrel File+ */++export { CRITIC_SYSTEM_PROMPT, buildCriticPrompt } from "./validation";diff --git a/src/lib/ai/prompts/shared/validation.ts b/src/lib/ai/prompts/shared/validation.tsnew file mode 100644index 0000000..395729e--- /dev/null+++ b/src/lib/ai/prompts/shared/validation.ts@@ -0,0 +1,119 @@+/**+ * Validation and Critic Prompts+ *+ * System prompts and builders for quality assurance validation of AI analysis.+ * Used by both resume review and job match features.+ */++/**+ * Critic validation prompt - validates first agent's work+ */+export const CRITIC_SYSTEM_PROMPT = `You are an elite quality assurance specialist for AI-generated career assessments. Your role is to catch errors, validate accuracy, and ensure actionable value.++## YOUR MISSION+Review another AI's analysis and determine if it meets quality standards. You are the last line of defense against bad advice reaching job seekers.++## VALIDATION FRAMEWORK++### 1. MATHEMATICAL ACCURACY (Critical)+□ Does the final score equal the sum of component scores?+□ Are all component scores within valid ranges?+ - Keywords: 0-20, Quantified: 0-25, Verbs: 0-10, Formatting: 0-15+ - Summary: 0-10, Clarity: 0-10, Skills: 0-5, Grammar: 0-5+□ Is the score realistic for the resume type?+ - Entry-level: typically 35-50+ - Mid-level: typically 45-65+ - Senior: typically 55-75+ - Exceptional: rarely >80+□ Flag if: Score doesn't match stated math, or extreme scores without justification++### 2. EVIDENCE QUALITY (Critical)+□ Did the analyzer QUOTE specific text from the resume?+□ Are counts actual counts, not estimates? ("Found 5 achievements" vs "several achievements")+□ Is each strength backed by a specific example?+□ Is each weakness tied to something concrete (or missing)?+□ Flag if: Generic statements like "good formatting" without specifics++### 3. ACTIONABILITY CHECK (Important)+□ Can the candidate actually DO each suggestion?+□ Are suggestions specific enough?+ - Bad: "Add more metrics"+ - Good: "Your 'Improved sales' bullet should specify the % increase"+□ Is there at least one high-impact suggestion?+□ Are suggestions prioritized or ranked?+□ Flag if: Vague, generic, or impossible-to-implement suggestions++### 4. CONSISTENCY CHECK (Important)+□ Does a high score come with strong strengths?+□ Does a low score come with significant weaknesses?+□ Do suggestions address the identified weaknesses?+□ Is the summary consistent with the detailed feedback?+□ Flag if: Score says 70 but feedback is mostly negative (or vice versa)++### 5. COMPLETENESS CHECK (Basic)+□ Are all required fields present and populated?+□ At least 2-3 strengths, weaknesses, and suggestions?+□ Is the summary 2-3 informative sentences?+□ Flag if: Empty fields, single-item lists, or one-sentence summary++### 6. COMMON AI MISTAKES TO CATCH+□ Hallucinated skills (claiming resume has X when it doesn't)+□ Missed obvious elements (ignoring stated metrics)+□ Industry-inappropriate feedback (asking nurse for GitHub)+□ Overly harsh or overly generous scoring+□ Repetitive feedback (same point stated multiple ways)+□ Generic template responses (could apply to any resume)++## YOUR RESPONSE FORMAT++**VERDICT: [APPROVED / NEEDS REVISION / REJECTED]**++**SCORE VALIDATION:**+- Stated math: [X+Y+Z = Total]+- Actual calculation: [Your verification]+- Score appropriateness: [Realistic for this resume type?]++**EVIDENCE QUALITY:**+- Specific quotes found: [Yes/No, examples]+- Counting accuracy: [Verified/Not verified]++**ACTIONABILITY:**+- Implementable suggestions: [X of Y]+- Highest-impact suggestion: [Which one?]++**ISSUES FOUND:** (if any)+1. [Issue 1 - severity: Critical/Important/Minor]+2. [Issue 2 - severity]++**RECOMMENDED CORRECTIONS:** (if NEEDS REVISION)+- [Specific fix needed]++## DECISION CRITERIA+- **APPROVED**: No critical issues, ≤2 minor issues+- **NEEDS REVISION**: 1-2 important issues OR 3+ minor issues+- **REJECTED**: Any critical issue (wrong math, hallucinated content, harmful advice)`;++/**+ * Build critic validation prompt+ */+export function buildCriticPrompt(+ originalAnalysis: string,+ resumeOrJobText: string+): string {+ return `Validate this AI-generated analysis for quality and accuracy.++## ANALYSIS TO VALIDATE:+${originalAnalysis}++## ORIGINAL SOURCE DOCUMENT:+${resumeOrJobText}++## YOUR TASK:+1. Verify all math calculations+2. Check that claims are supported by the source document+3. Evaluate actionability of suggestions+4. Check for consistency between score and feedback+5. Identify any hallucinations or errors++Provide your structured verdict with specific findings.`;+}diff --git a/src/lib/ai/rate-limiter.ts b/src/lib/ai/rate-limiter.tsindex 1c862e5..02cb299 100644--- a/src/lib/ai/rate-limiter.ts+++ b/src/lib/ai/rate-limiter.ts@@ -3,6 +3,8 @@* Limits requests per user per time window.*/+import { RATE_LIMITS } from "./config";+interface RateLimitEntry {count: number;resetTime: number;@@ -10,8 +12,7 @@ interface RateLimitEntry {const rateLimitStore = new Map<string, RateLimitEntry>();-const WINDOW_MS = 60 * 1000; // 1 minute window-const MAX_REQUESTS = 5; // 5 requests per minute per user+const { WINDOW_MS, MAX_REQUESTS, STORE_CLEANUP_THRESHOLD } = RATE_LIMITS;/*** Check if a user is rate limited.@@ -27,7 +28,7 @@ export function checkRateLimit(userId: string): {const entry = rateLimitStore.get(userId);// Clean up expired entries periodically- if (rateLimitStore.size > 1000) {+ if (rateLimitStore.size > STORE_CLEANUP_THRESHOLD) {for (const [key, value] of rateLimitStore) {if (now > value.resetTime) {rateLimitStore.delete(key);diff --git a/src/lib/ai/tools/semantic-extraction.ts b/src/lib/ai/tools/semantic-extraction.tsindex 5ffdea9..8850343 100644--- a/src/lib/ai/tools/semantic-extraction.ts+++ b/src/lib/ai/tools/semantic-extraction.ts@@ -18,7 +18,7 @@ import {getKeywordPrompt,getVerbPrompt,getSkillMatchPrompt,-} from "../prompts/semantic-prompts";+} from "../prompts";import {isOllamaProvider,OllamaSemanticKeywordSchema,diff --git a/src/lib/ai/tools/semantic-similarity.ts b/src/lib/ai/tools/semantic-similarity.tsindex 498df97..d896635 100644--- a/src/lib/ai/tools/semantic-similarity.ts+++ b/src/lib/ai/tools/semantic-similarity.ts@@ -10,7 +10,7 @@ import {type SemanticSimilarityResult,type SemanticSkillMatch,} from "@/models/ai.schemas";-import { getSimilarityPrompt } from "../prompts/semantic-prompts";+import { getSimilarityPrompt } from "../prompts";import {isOllamaProvider,OllamaSemanticSimilaritySchema,