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 job match workflow
Khuram Niaza9b1476654c1
diff --git a/__tests__/ai.actions.spec.ts b/__tests__/ai.actions.spec.tsdeleted file mode 100644index ac0d4b8..0000000--- a/__tests__/ai.actions.spec.ts+++ /dev/null@@ -1,226 +0,0 @@-/**- * AI Library Tests- * Tests for the mathematical scoring and analysis system- */--import {- calculateResumeScore,- calculateJobMatchScore,- validateScore,-} from "@/lib/ai";--describe("AI Library - Analysis Tools", () => {- // ...existing code...- // Note: extractRequiredSkills tests removed - function now uses semantic AI extraction-});--describe("AI Library - Mathematical Scoring", () => {- describe("calculateResumeScore", () => {- it("should calculate score based on metrics", () => {- const result = calculateResumeScore({- quantifiedCount: 12,- keywordCount: 18,- verbCount: 15,- hasBulletPoints: true,- sectionCount: 5,- });-- expect(result.score).toBeGreaterThan(0);- expect(result.score).toBeLessThanOrEqual(100);- expect(result.breakdown).toBeDefined();- expect(result.breakdown.keywords).toBeDefined();- expect(result.breakdown.achievements).toBeDefined();- });-- it("should give low score for minimal metrics", () => {- const result = calculateResumeScore({- quantifiedCount: 0,- keywordCount: 2,- verbCount: 1,- hasBulletPoints: false,- sectionCount: 1,- });-- expect(result.score).toBeLessThan(30);- });-- it("should give high score for excellent metrics", () => {- const result = calculateResumeScore({- quantifiedCount: 15,- keywordCount: 20,- verbCount: 20,- hasBulletPoints: true,- sectionCount: 6,- });-- expect(result.score).toBeGreaterThan(70);- });-- it("should include all breakdown criteria", () => {- const result = calculateResumeScore({- quantifiedCount: 10,- keywordCount: 15,- verbCount: 12,- hasBulletPoints: true,- sectionCount: 5,- });-- expect(result.breakdown).toHaveProperty("keywords");- expect(result.breakdown).toHaveProperty("achievements");- expect(result.breakdown).toHaveProperty("verbs");- expect(result.breakdown).toHaveProperty("formatting");- });- });-- describe("calculateJobMatchScore", () => {- it("should calculate score based on match metrics", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 65,- matchedSkillsCount: 8,- requiredSkillsCount: 12,- experienceYears: 7,- requiredYears: 5,- });-- expect(result.score).toBeGreaterThan(0);- expect(result.score).toBeLessThanOrEqual(100);- expect(result.breakdown).toBeDefined();- });-- it("should give low score for poor match", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 20,- matchedSkillsCount: 2,- requiredSkillsCount: 12,- experienceYears: 1,- requiredYears: 5,- });-- expect(result.score).toBeLessThan(40);- });-- it("should give high score for excellent match", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 90,- matchedSkillsCount: 11,- requiredSkillsCount: 12,- experienceYears: 8,- requiredYears: 5,- });-- expect(result.score).toBeGreaterThan(80);- });-- it("should handle 50% skill match appropriately", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 50,- matchedSkillsCount: 6,- requiredSkillsCount: 12,- experienceYears: 5,- requiredYears: 5,- });-- // Should NOT be zero (was a bug in old system)- expect(result.score).toBeGreaterThan(0);- // Should be in average range (45-65)- expect(result.score).toBeGreaterThanOrEqual(40);- expect(result.score).toBeLessThanOrEqual(70);- });-- it("should give minimum score when at least 1 skill matches", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 10,- matchedSkillsCount: 1,- requiredSkillsCount: 12,- experienceYears: 2,- requiredYears: 5,- });-- // Should have minimum guarantee, not zero- expect(result.score).toBeGreaterThanOrEqual(5);- });- });-- describe("validateScore", () => {- it("should allow score within variance", () => {- const validated = validateScore(75, 70, 10);- expect(validated).toBe(75);- });-- it("should clamp score above max variance", () => {- const validated = validateScore(90, 70, 10);- expect(validated).toBe(80); // 70 + 10- });-- it("should clamp score below min variance", () => {- const validated = validateScore(50, 70, 10);- expect(validated).toBe(60); // 70 - 10- });-- it("should enforce 0-100 bounds", () => {- const validated1 = validateScore(120, 90, 20);- expect(validated1).toBeLessThanOrEqual(100);-- const validated2 = validateScore(-10, 10, 20);- expect(validated2).toBeGreaterThanOrEqual(0);- });-- it("should use default variance of 10", () => {- const validated = validateScore(85, 70);- expect(validated).toBe(80); // 70 + 10 (default variance)- });- });-});--describe("AI Library - Consistency Tests", () => {- it("should produce consistent scores for same resume metrics", () => {- const metrics = {- quantifiedCount: 10,- keywordCount: 15,- verbCount: 12,- hasBulletPoints: true,- sectionCount: 5,- };-- const result1 = calculateResumeScore(metrics);- const result2 = calculateResumeScore(metrics);- const result3 = calculateResumeScore(metrics);-- expect(result1.score).toBe(result2.score);- expect(result2.score).toBe(result3.score);- });-- it("should produce consistent scores for same job match metrics", () => {- const metrics = {- keywordOverlapPercent: 65,- matchedSkillsCount: 8,- requiredSkillsCount: 12,- experienceYears: 7,- requiredYears: 5,- };-- const result1 = calculateJobMatchScore(metrics);- const result2 = calculateJobMatchScore(metrics);- const result3 = calculateJobMatchScore(metrics);-- expect(result1.score).toBe(result2.score);- expect(result2.score).toBe(result3.score);- });-});--// Helper function for creating mock async iterators (if needed for future streaming tests)-function createMockAsyncIterator<T>(items: T[]): AsyncIterable<T> {- let index = 0;- return {- [Symbol.asyncIterator]() {- return {- async next() {- if (index < items.length) {- return { value: items[index++], done: false };- }- return { value: undefined as any, done: true };- },- };- },- };-}diff --git a/__tests__/ai.library.spec.ts b/__tests__/ai.library.spec.tsdeleted file mode 100644index 4e84387..0000000--- a/__tests__/ai.library.spec.ts+++ /dev/null@@ -1,231 +0,0 @@-/**- * AI Library Tests- * Tests for analysis tools, mathematical scoring, and validation functions- *- * Note: This tests the AI library functions used by the API routes.- * The AI functionality is implemented in API routes:- * - /api/ai/resume/review (resume analysis)- * - /api/ai/resume/match (job matching)- */--import {- calculateResumeScore,- calculateJobMatchScore,- validateScore,-} from "@/lib/ai";--describe("AI Library - Analysis Tools", () => {- // ...existing code...- // Note: extractRequiredSkills tests removed - function now uses semantic AI extraction-});--describe("AI Library - Mathematical Scoring", () => {- describe("calculateResumeScore", () => {- it("should calculate score based on metrics", () => {- const result = calculateResumeScore({- quantifiedCount: 12,- keywordCount: 18,- verbCount: 15,- hasBulletPoints: true,- sectionCount: 5,- });-- expect(result.score).toBeGreaterThan(0);- expect(result.score).toBeLessThanOrEqual(100);- expect(result.breakdown).toBeDefined();- expect(result.breakdown.keywords).toBeDefined();- expect(result.breakdown.achievements).toBeDefined();- });-- it("should give low score for minimal metrics", () => {- const result = calculateResumeScore({- quantifiedCount: 0,- keywordCount: 2,- verbCount: 1,- hasBulletPoints: false,- sectionCount: 1,- });-- expect(result.score).toBeLessThan(30);- });-- it("should give high score for excellent metrics", () => {- const result = calculateResumeScore({- quantifiedCount: 15,- keywordCount: 20,- verbCount: 20,- hasBulletPoints: true,- sectionCount: 6,- });-- expect(result.score).toBeGreaterThan(70);- });-- it("should include all breakdown criteria", () => {- const result = calculateResumeScore({- quantifiedCount: 10,- keywordCount: 15,- verbCount: 12,- hasBulletPoints: true,- sectionCount: 5,- });-- expect(result.breakdown).toHaveProperty("keywords");- expect(result.breakdown).toHaveProperty("achievements");- expect(result.breakdown).toHaveProperty("verbs");- expect(result.breakdown).toHaveProperty("formatting");- });- });-- describe("calculateJobMatchScore", () => {- it("should calculate score based on match metrics", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 65,- matchedSkillsCount: 8,- requiredSkillsCount: 12,- experienceYears: 7,- requiredYears: 5,- });-- expect(result.score).toBeGreaterThan(0);- expect(result.score).toBeLessThanOrEqual(100);- expect(result.breakdown).toBeDefined();- });-- it("should give low score for poor match", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 20,- matchedSkillsCount: 2,- requiredSkillsCount: 12,- experienceYears: 1,- requiredYears: 5,- });-- expect(result.score).toBeLessThan(40);- });-- it("should give high score for excellent match", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 90,- matchedSkillsCount: 11,- requiredSkillsCount: 12,- experienceYears: 8,- requiredYears: 5,- });-- expect(result.score).toBeGreaterThan(80);- });-- it("should handle 50% skill match appropriately", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 50,- matchedSkillsCount: 6,- requiredSkillsCount: 12,- experienceYears: 5,- requiredYears: 5,- });-- // Should NOT be zero (was a bug in old system)- expect(result.score).toBeGreaterThan(0);- // Should be in average range (45-65)- expect(result.score).toBeGreaterThanOrEqual(40);- expect(result.score).toBeLessThanOrEqual(70);- });-- it("should give minimum score when at least 1 skill matches", () => {- const result = calculateJobMatchScore({- keywordOverlapPercent: 10,- matchedSkillsCount: 1,- requiredSkillsCount: 12,- experienceYears: 2,- requiredYears: 5,- });-- // Should have minimum guarantee, not zero- expect(result.score).toBeGreaterThanOrEqual(5);- });- });-- describe("validateScore", () => {- it("should allow score within variance", () => {- const validated = validateScore(75, 70, 10);- expect(validated).toBe(75);- });-- it("should clamp score above max variance", () => {- const validated = validateScore(90, 70, 10);- expect(validated).toBe(80); // 70 + 10- });-- it("should clamp score below min variance", () => {- const validated = validateScore(50, 70, 10);- expect(validated).toBe(60); // 70 - 10- });-- it("should enforce 0-100 bounds", () => {- const validated1 = validateScore(120, 90, 20);- expect(validated1).toBeLessThanOrEqual(100);-- const validated2 = validateScore(-10, 10, 20);- expect(validated2).toBeGreaterThanOrEqual(0);- });-- it("should use default variance of 10", () => {- const validated = validateScore(85, 70);- expect(validated).toBe(80); // 70 + 10 (default variance)- });- });-});--describe("AI Library - Consistency Tests", () => {- it("should produce consistent scores for same resume metrics", () => {- const metrics = {- quantifiedCount: 10,- keywordCount: 15,- verbCount: 12,- hasBulletPoints: true,- sectionCount: 5,- };-- const result1 = calculateResumeScore(metrics);- const result2 = calculateResumeScore(metrics);- const result3 = calculateResumeScore(metrics);-- expect(result1.score).toBe(result2.score);- expect(result2.score).toBe(result3.score);- });-- it("should produce consistent scores for same job match metrics", () => {- const metrics = {- keywordOverlapPercent: 65,- matchedSkillsCount: 8,- requiredSkillsCount: 12,- experienceYears: 7,- requiredYears: 5,- };-- const result1 = calculateJobMatchScore(metrics);- const result2 = calculateJobMatchScore(metrics);- const result3 = calculateJobMatchScore(metrics);-- expect(result1.score).toBe(result2.score);- expect(result2.score).toBe(result3.score);- });-});--// Helper function for creating mock async iterators (if needed for future streaming tests)-function createMockAsyncIterator<T>(items: T[]): AsyncIterable<T> {- let index = 0;- return {- [Symbol.asyncIterator]() {- return {- async next() {- if (index < items.length) {- return { value: items[index++], done: false };- }- return { value: undefined as any, done: true };- },- };- },- };-}diff --git a/src/app/api/ai/resume/match/route.ts b/src/app/api/ai/resume/match/route.tsindex 950a911..0d6d3be 100644--- a/src/app/api/ai/resume/match/route.ts+++ b/src/app/api/ai/resume/match/route.ts@@ -9,8 +9,6 @@ import {JobMatchSchema,JOB_MATCH_SYSTEM_PROMPT,buildJobMatchPrompt,- performSemanticSkillMatch,- calculateSemanticSimilarity,AIUnavailableError,preprocessResume,preprocessJob,@@ -21,8 +19,7 @@ import { AiModel } from "@/models/ai.model";/*** Job Match Endpoint- * Matches a resume against a job description using semantic analysis and LLM- * Includes preprocessing of both inputs for consistency and reliability+ * Single comprehensive LLM call for resume-job matching*/export const POST = async (req: NextRequest) => {const session = await auth();@@ -64,13 +61,12 @@ export const POST = async (req: NextRequest) => {getJobDetails(jobId),]);- // Preprocess both resume and job description for consistency+ // Preprocess both resume and job descriptionconst [resumePreprocessResult, jobPreprocessResult] = await Promise.all([preprocessResume(resume),preprocessJob(job),]);- // Check resume preprocessingif (!resumePreprocessResult.success) {return NextResponse.json({@@ -81,7 +77,6 @@ export const POST = async (req: NextRequest) => {);}- // Check job preprocessingif (!jobPreprocessResult.success) {return NextResponse.json({@@ -95,50 +90,19 @@ export const POST = async (req: NextRequest) => {const { normalizedText: resumeText } = resumePreprocessResult.data;const { normalizedText: jobText } = jobPreprocessResult.data;- // Use semantic analysis for skill matching- const [skillMatch, similarity] = await Promise.all([- performSemanticSkillMatch(- resumeText,- jobText,- selectedModel.provider,- selectedModel.model || "llama3.2",- ),- calculateSemanticSimilarity(- resumeText,- jobText,- selectedModel.provider,- selectedModel.model || "llama3.2",- ),- ]);-- const matchedSkills = skillMatch.exact_matches.map((m) => m.skill);- const missingSkills = skillMatch.missing_skills.map((s) => s.skill);- const totalSkills = matchedSkills.length + missingSkills.length;-- const basePrompt = buildJobMatchPrompt(resumeText, jobText);- const fullPrompt = `${basePrompt}--TOOL ANALYSIS RESULTS (use these in your evaluation):-- Semantic similarity: ${similarity.similarity_score}% match-- Skills matched: ${matchedSkills.length} of ${totalSkills} required skills-- Matched skills: ${matchedSkills.slice(0, 10).join(", ") || "none"}-- Missing skills: ${missingSkills.slice(0, 10).join(", ") || "none"}-- Match explanation: ${similarity.match_explanation}--Use these results in your scoring decisions.`;-const model = getModel(selectedModel.provider,selectedModel.model || "llama3.2",);+ // Single comprehensive LLM callconst result = streamText({model,output: Output.object({schema: JobMatchSchema,}),system: JOB_MATCH_SYSTEM_PROMPT,- prompt: fullPrompt,+ prompt: buildJobMatchPrompt(resumeText, jobText),temperature: 0.3,});diff --git a/src/components/profile/AiJobMatchResponseContent.tsx b/src/components/profile/AiJobMatchResponseContent.tsxindex 30fd1ba..1949524 100644--- a/src/components/profile/AiJobMatchResponseContent.tsx+++ b/src/components/profile/AiJobMatchResponseContent.tsx@@ -1,34 +1,16 @@import { RadialChartComponent } from "../RadialChart";import { SheetDescription } from "../ui/sheet";-import { JobMatchResponse, JobMatchAnalysis } from "@/models/ai.model";+import { JobMatchResponse } from "@/models/ai.model";import type { DeepPartial } from "ai";+import { Badge } from "../ui/badge";-const AnalysisSection = ({- title,- items,-}: {- title: string;- items?: DeepPartial<JobMatchAnalysis>[];-}) => {- if (!items || items.length === 0) return null;- return (- <div className="pt-2">- <h2 className="font-semibold mb-2">{title}</h2>- {items.map((analysis, i) => (- <div key={i}>- {analysis?.category && (- <h2 className="font-medium my-1">{analysis.category}</h2>- )}- {analysis?.value && analysis.value.length > 0 && (- <SheetDescription>- {analysis.value.map((v, j) => v && <li key={j}>{v}</li>)}- </SheetDescription>- )}- </div>- ))}- </div>- );-};+const SectionHeader = ({ title }: { title: string }) => (+ <h2 className="font-semibold mb-2 mt-4">{title}</h2>+);++const ListItem = ({ children }: { children: React.ReactNode }) => (+ <li className="ml-4 mb-1">{children}</li>+);export const AiJobMatchResponseContent = ({content,@@ -40,43 +22,232 @@ export const AiJobMatchResponseContent = ({if (!content) return null;const {- detailed_analysis,- matching_score,- suggestions,- additional_comments,+ matchScore,+ recommendation,+ requirements,+ skills,+ experience,+ keywords,+ dealBreakers,+ tailoringTips,+ summary,} = content;return (<>- {matching_score !== undefined && (- <div className="pt-2 flex justify-center">- <RadialChartComponent score={matching_score} />+ {matchScore !== undefined && (+ <div className="pt-2 flex flex-col items-center">+ <RadialChartComponent score={matchScore} />+ {recommendation && (+ <Badge+ variant={+ recommendation === "strong match"+ ? "default"+ : recommendation === "good match"+ ? "secondary"+ : recommendation === "partial match"+ ? "outline"+ : "destructive"+ }+ className="mt-2 capitalize"+ >+ {recommendation}+ </Badge>+ )}</div>)}- <div className={matching_score !== undefined ? "mt-[-50px]" : ""}>- <AnalysisSection- title="Detailed Analysis:"- items={detailed_analysis?.filter(- (item): item is DeepPartial<JobMatchAnalysis> => Boolean(item)++ {summary && (+ <div className={matchScore !== undefined ? "mt-[-30px]" : ""}>+ <SectionHeader title="Summary" />+ <SheetDescription>{summary}</SheetDescription>+ </div>+ )}++ {requirements && (+ <>+ {requirements.met && requirements.met.length > 0 && (+ <>+ <SectionHeader title="Requirements Met" />+ <ul className="text-sm text-muted-foreground">+ {requirements.met.map(+ (req, i) =>+ req && (+ <ListItem key={i}>+ <strong>{req.requirement}</strong>: {req.evidence}+ </ListItem>+ )+ )}+ </ul>+ </>+ )}+ {requirements.partial && requirements.partial.length > 0 && (+ <>+ <SectionHeader title="Partial Matches" />+ <ul className="text-sm text-muted-foreground">+ {requirements.partial.map(+ (req, i) =>+ req && (+ <ListItem key={i}>+ <strong>{req.requirement}</strong>: {req.evidence}{" "}+ <span className="text-amber-600">+ (Gap: {req.gap})+ </span>+ </ListItem>+ )+ )}+ </ul>+ </>)}- />- </div>- <AnalysisSection- title="Suggestions:"- items={suggestions?.filter(- (item): item is DeepPartial<JobMatchAnalysis> => Boolean(item)- )}- />- {additional_comments && additional_comments.length > 0 && (- <div className="pt-2">- <h2 className="font-semibold mb-2">Additional Comments:</h2>- <SheetDescription>- {additional_comments.map(- (comment, i) => comment && <li key={i}>{comment}</li>+ {requirements.missing && requirements.missing.length > 0 && (+ <>+ <SectionHeader title="Missing Requirements" />+ <ul className="text-sm text-muted-foreground">+ {requirements.missing.map(+ (req, i) =>+ req && (+ <ListItem key={i}>+ <strong>{req.requirement}</strong>{" "}+ <Badge+ variant={+ req.importance === "required"+ ? "destructive"+ : "outline"+ }+ className="text-xs mx-1"+ >+ {req.importance}+ </Badge>+ <br />+ <span className="text-muted-foreground text-sm">+ Suggestion: {req.suggestion}+ </span>+ </ListItem>+ )+ )}+ </ul>+ </>+ )}+ </>+ )}++ {skills && (+ <>+ <SectionHeader title="Skills Analysis" />+ <div className="text-sm text-muted-foreground">+ {skills.matched && skills.matched.length > 0 && (+ <div className="mb-2">+ <span className="font-medium">Matched: </span>+ {skills.matched.filter(Boolean).join(", ")}+ </div>)}- </SheetDescription>- </div>+ {skills.transferable && skills.transferable.length > 0 && (+ <div className="mb-2">+ <span className="font-medium">Transferable: </span>+ {skills.transferable.filter(Boolean).join(", ")}+ </div>+ )}+ {skills.missing && skills.missing.length > 0 && (+ <div className="mb-2 text-amber-600">+ <span className="font-medium">Missing: </span>+ {skills.missing.filter(Boolean).join(", ")}+ </div>+ )}+ {skills.bonus && skills.bonus.length > 0 && (+ <div className="mb-2 text-green-600">+ <span className="font-medium">Bonus Skills: </span>+ {skills.bonus.filter(Boolean).join(", ")}+ </div>+ )}+ </div>+ </>+ )}++ {experience && (+ <>+ <SectionHeader title="Experience" />+ <div className="text-sm text-muted-foreground space-y-1">+ {experience.levelMatch && (+ <div>+ <span className="font-medium">Level: </span>+ <span className="capitalize">{experience.levelMatch}</span>+ </div>+ )}+ {experience.yearsRequired !== undefined && (+ <div>+ <span className="font-medium">Years Required: </span>+ {experience.yearsRequired ?? "Not specified"}+ </div>+ )}+ {experience.yearsApparent !== undefined && (+ <div>+ <span className="font-medium">Your Experience: </span>+ {experience.yearsApparent} years+ </div>+ )}+ {experience.relevance && (+ <div>+ <span className="font-medium">Relevance: </span>+ <span className="capitalize">{experience.relevance}</span>+ </div>+ )}+ </div>+ </>+ )}++ {keywords && (+ <>+ <SectionHeader title="Keywords" />+ <div className="text-sm text-muted-foreground">+ {keywords.matched && keywords.matched.length > 0 && (+ <div className="mb-2">+ <span className="font-medium">Found: </span>+ {keywords.matched.filter(Boolean).join(", ")}+ </div>+ )}+ {keywords.missing && keywords.missing.length > 0 && (+ <div className="mb-2 text-amber-600">+ <span className="font-medium">Missing: </span>+ {keywords.missing.filter(Boolean).join(", ")}+ </div>+ )}+ {keywords.addToResume && keywords.addToResume.length > 0 && (+ <div className="mb-2">+ <span className="font-medium">Add to Resume: </span>+ {keywords.addToResume.filter(Boolean).join(", ")}+ </div>+ )}+ </div>+ </>+ )}++ {dealBreakers && dealBreakers.length > 0 && (+ <>+ <SectionHeader title="Deal Breakers" />+ <ul className="text-sm text-red-600">+ {dealBreakers.map(+ (item, i) => item && <ListItem key={i}>{item}</ListItem>+ )}+ </ul>+ </>)}++ {tailoringTips && tailoringTips.length > 0 && (+ <>+ <SectionHeader title="Tailoring Tips" />+ <ul className="text-sm text-muted-foreground">+ {tailoringTips.map(+ (tip, i) =>+ tip && (+ <ListItem key={i}>+ <strong>{tip.section}:</strong> {tip.action}+ </ListItem>+ )+ )}+ </ul>+ </>+ )}+{isStreaming && (<div className="flex items-center gap-2 text-muted-foreground text-sm mt-4 animate-pulse"><div className="h-2 w-2 bg-primary rounded-full"></div>diff --git a/src/components/profile/AiJobMatchSection.tsx b/src/components/profile/AiJobMatchSection.tsxindex 594687c..a752fc6 100644--- a/src/components/profile/AiJobMatchSection.tsx+++ b/src/components/profile/AiJobMatchSection.tsx@@ -138,7 +138,7 @@ export const AiJobMatchSection = ({// Check if we have any content to showconst hasContent =- object && (object.matching_score !== undefined || object.detailed_analysis);+ object && (object.matchScore !== undefined || object.summary);return (<Sheet open={aISectionOpen} onOpenChange={onOpenChange}>diff --git a/src/lib/ai/index.ts b/src/lib/ai/index.tsindex 53284ad..0d45583 100644--- a/src/lib/ai/index.ts+++ b/src/lib/ai/index.ts@@ -4,7 +4,6 @@ export {JobMatchSchema,type ResumeReviewResponse,type JobMatchResponse,- type JobMatchAnalysis,} from "@/models/ai.schemas";// Prompts@@ -47,27 +46,4 @@ export {type TextMetadata,} from "./tools/text-processing";-// Semantic extraction for job matching (still used)-export {- performSemanticSkillMatch,- calculateSemanticSimilarity,- generateMatchExplanation,-} from "./tools";--// Schemas for job matching-export {- SemanticSkillMatchSchema,- SemanticSimilaritySchema,- type SemanticSkillMatch,- type SemanticSimilarityResult,-} from "@/models/ai.schemas";--// Scoring calculators-export {- calculateResumeScore,- calculateJobMatchScore,- validateScore,- SCORING_GUIDELINES,-} from "./scoring";-export { checkRateLimit } from "./rate-limiter";diff --git a/src/lib/ai/ollama/index.ts b/src/lib/ai/ollama/index.tsdeleted file mode 100644index 05d82c6..0000000--- a/src/lib/ai/ollama/index.ts+++ /dev/null@@ -1,43 +0,0 @@-/**- * Ollama-specific AI logic- *- * This module centralizes all Ollama-specific functionality:- * - Result normalizers (Ollama → full schema)- * - Utility functions and constants- */--import type { ProviderType } from "../providers";-import { SEMANTIC_TIMEOUT_MS, AGENT_TIMEOUT_MS } from "../config";--// 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)- */-export function isOllamaProvider(provider: ProviderType): boolean {- return provider === "ollama";-}--// Normalizers-export {- normalizeKeywordExtraction,- normalizeActionVerbAnalysis,- normalizeCombinedResumeAnalysis,- normalizeSkillMatch,- normalizeSemanticSimilarity,-} from "./normalizers";--// Re-export schemas from models for convenience-export {- OllamaSemanticKeywordSchema,- OllamaActionVerbSchema,- OllamaCombinedResumeAnalysisSchema,- OllamaSkillMatchSchema,- OllamaSemanticSimilaritySchema,- type OllamaSemanticKeywordExtraction,- type OllamaActionVerbAnalysis,- type OllamaCombinedResumeAnalysis,- type OllamaSkillMatch,- type OllamaSemanticSimilarity,-} from "@/models/ai.ollama-schemas";diff --git a/src/lib/ai/ollama/normalizers.ts b/src/lib/ai/ollama/normalizers.tsdeleted file mode 100644index ee25aab..0000000--- a/src/lib/ai/ollama/normalizers.ts+++ /dev/null@@ -1,118 +0,0 @@-/**- * Ollama result normalizers- *- * These functions convert Ollama's simplified schema output- * to the full schema format expected by the rest of the application.- */--import type {- OllamaSemanticKeywordExtraction,- OllamaActionVerbAnalysis,- OllamaCombinedResumeAnalysis,- OllamaSkillMatch,- OllamaSemanticSimilarity,-} from "@/models/ai.ollama-schemas";-import type {- SemanticKeywordExtraction,- ActionVerbAnalysis,- CombinedResumeAnalysis,- SemanticSkillMatch,- SemanticSimilarityResult,-} from "@/models/ai.schemas";--/**- * Normalize Ollama keyword extraction to full schema format- */-export function normalizeKeywordExtraction(- ollamaResult: OllamaSemanticKeywordExtraction,-): SemanticKeywordExtraction {- return {- technical_skills: ollamaResult.technical_skills,- tools_platforms: ollamaResult.tools || [],- methodologies: [],- domain_knowledge: [],- soft_skills: [],- total_count: ollamaResult.total_count,- };-}--/**- * Normalize Ollama action verb analysis to full schema format- */-export function normalizeActionVerbAnalysis(- ollamaResult: OllamaActionVerbAnalysis,-): ActionVerbAnalysis {- return {- strong_verbs: ollamaResult.strong_verbs.map((verb) => ({- verb,- context: "Found in resume",- impact_level: "medium" as const,- })),- weak_verbs: ollamaResult.weak_verbs.map((verb) => ({- verb,- context: "Found in resume",- suggestion: "",- })),- verb_strength_score: ollamaResult.verb_strength_score,- };-}--/**- * Normalize Ollama combined resume analysis to full schema format- */-export function normalizeCombinedResumeAnalysis(- ollamaResult: OllamaCombinedResumeAnalysis,-): CombinedResumeAnalysis {- return {- keywords: normalizeKeywordExtraction(ollamaResult.keywords),- verbs: normalizeActionVerbAnalysis(ollamaResult.verbs),- };-}--/**- * Normalize Ollama skill match to full schema format- */-export function normalizeSkillMatch(- ollamaResult: OllamaSkillMatch,-): SemanticSkillMatch {- return {- exact_matches: ollamaResult.matched_skills- .filter((m) => m.skill.trim())- .map((m) => ({- skill: m.skill,- resume_evidence: m.evidence,- job_requirement: "Required by job",- })),- related_matches: [],- missing_skills: ollamaResult.missing_skills- .filter((s) => s.trim())- .map((skill) => ({- skill,- importance: "important" as const,- learnability: "moderate" as const,- })),- overall_match_percentage: ollamaResult.match_percentage,- };-}--/**- * Normalize Ollama semantic similarity to full schema format- */-export function normalizeSemanticSimilarity(- ollamaResult: OllamaSemanticSimilarity,-): SemanticSimilarityResult {- return {- similarity_score: ollamaResult.similarity_score,- match_explanation: ollamaResult.match_explanation,- key_matches: [],- key_gaps: ollamaResult.key_gaps.map((gap) => ({- skill: gap,- note: "Missing from resume",- })),- transferable_skills: [],- application_recommendation:- ollamaResult.similarity_score >= 60- ? "Consider applying - good fit"- : "Consider upskilling before applying",- };-}diff --git a/src/lib/ai/prompts/index.ts b/src/lib/ai/prompts/index.tsindex dd0fe38..2a23fd7 100644--- a/src/lib/ai/prompts/index.ts+++ b/src/lib/ai/prompts/index.ts@@ -5,7 +5,6 @@* 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@@ -18,7 +17,4 @@ export {export {JOB_MATCH_SYSTEM_PROMPT,buildJobMatchPrompt,- JOB_MATCH_SCORE_GUIDE,- getSkillMatchPrompt,- getSimilarityPrompt,} from "./job-match";diff --git a/src/lib/ai/prompts/job-match/calibration.ts b/src/lib/ai/prompts/job-match/calibration.tsdeleted file mode 100644index 53e0e7b..0000000--- a/src/lib/ai/prompts/job-match/calibration.ts+++ /dev/null@@ -1,19 +0,0 @@-/**- * 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.tsindex 1061382..1548af4 100644--- a/src/lib/ai/prompts/job-match/index.ts+++ b/src/lib/ai/prompts/job-match/index.ts@@ -2,14 +2,5 @@* Job Match Prompts - Barrel File*/-// System promptsexport { JOB_MATCH_SYSTEM_PROMPT } from "./system";--// User prompt buildersexport { buildJobMatchPrompt } from "./user";--// Calibration examples-export { JOB_MATCH_SCORE_GUIDE } from "./calibration";--// Semantic extraction prompts-export { getSkillMatchPrompt, getSimilarityPrompt } from "./semantic";diff --git a/src/lib/ai/prompts/job-match/semantic.ts b/src/lib/ai/prompts/job-match/semantic.tsdeleted file mode 100644index 0eb3289..0000000--- a/src/lib/ai/prompts/job-match/semantic.ts+++ /dev/null@@ -1,100 +0,0 @@-/**- * Job Match Semantic Prompts- *- * Provider-aware prompts for skill matching and similarity analysis.- */--import { ProviderType } from "../../providers";--/**- * Get skill matching prompt based on provider- * Ollama: ~200 tokens | Cloud: ~450 tokens (50% reduction)- */-export function getSkillMatchPrompt(- provider: ProviderType,- resumeText: string,- jobText: string-): string {- if (provider === "ollama") {- return `List skills from job that appear in resume.--Job skills needed:-${jobText.substring(0, 1200)}--Resume:-${resumeText.substring(0, 1200)}--Output matched_skills, missing_skills, match_percentage.`;- }-- // Cloud: Optimized (~450 tokens) - structured but concise- return `Compare resume skills vs job requirements as expert recruiter.--For EACH job skill, categorize:-- EXACT MATCH: Same skill in resume. Include: skill, resume_evidence (quote), job_requirement- Example: Job "React" + Resume "Led React migration" = exact match-- RELATED MATCH: Transferable skill. Include: job_skill, resume_skill, similarity (0-100), explanation- Example: Job "PostgreSQL" + Resume "MySQL" = related (85% similar)-- MISSING: Not in resume. Include: skill, importance (critical/important/nice-to-have), learnability (quick/moderate/significant)--Resume:-"""-${resumeText.substring(0, 3000)}-"""--Job:-"""-${jobText.substring(0, 3000)}-"""--Calculate overall_match_percentage = (exact + 0.7*related) / total_skills * 100-Provide evidence quotes for all matches.`;-}--/**- * Get semantic similarity prompt based on provider- * Ollama: ~170 tokens | Cloud: ~380 tokens (46% reduction)- */-export function getSimilarityPrompt(- provider: ProviderType,- resumeText: string,- jobDescription: string-): string {- if (provider === "ollama") {- return `Score resume-job fit 0-100.--Job:-${jobDescription.substring(0, 1200)}--Resume:-${resumeText.substring(0, 1200)}--Output similarity_score, match_explanation, key_gaps.`;- }-- // Cloud: Optimized (~380 tokens) - concise with scoring guidelines- return `Analyze semantic similarity between resume and job as expert recruiter.--Consider: skills alignment (incl. transferable), experience relevance, role fit, culture signals.--Scoring: 80-100 exceptional, 65-79 strong, 50-64 moderate, 35-49 weak, 0-34 poor.-(50-60 is common for decent matches)--Resume:-"""-${resumeText.substring(0, 3500)}-"""--Job:-"""-${jobDescription.substring(0, 3500)}-"""--Return:-1. similarity_score (0-100)-2. match_explanation (2-3 sentences on fit)-3. key_matches (3-5 strong match areas)-4. key_gaps (3-5 gaps with notes)-5. transferable_skills (skills that could apply to gaps)-6. application_recommendation (clear advice)`;-}diff --git a/src/lib/ai/prompts/job-match/system.ts b/src/lib/ai/prompts/job-match/system.tsindex 140aad1..3e52b36 100644--- a/src/lib/ai/prompts/job-match/system.ts+++ b/src/lib/ai/prompts/job-match/system.ts@@ -1,35 +1,28 @@-/**- * 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+ * Single comprehensive LLM call for job-resume matching*/-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}`;+export const JOB_MATCH_SYSTEM_PROMPT = `You are an expert recruiter assessing candidate-job fit. Your role is to provide accurate, actionable analysis comparing resumes against job descriptions.++## ANALYSIS APPROACH+- Match SPECIFIC requirements from the JD against the resume+- Weight must-have skills higher than nice-to-haves+- Only score against what's explicitly required+- Credit transferable skills from different technologies or industries+- Don't penalize for skills the job didn't ask for++## SCORING GUIDELINES+- 80-100: Strong match - high interview likelihood+- 65-79: Good match - apply with confidence+- 50-64: Partial match - tailor resume carefully+- 35-49: Weak match - significant gaps exist+- <35: Poor match - consider other roles++Most candidates score 40-65 against any given job. Be realistic.++## OUTPUT REQUIREMENTS+- Be specific. Reference actual content from both documents.+- Provide exact keywords and phrases to add+- Give actionable tailoring tips with specific sections to modify+- Be honest about deal breakers and gaps`;diff --git a/src/lib/ai/prompts/job-match/user.ts b/src/lib/ai/prompts/job-match/user.tsindex e9d7acf..86d5426 100644--- a/src/lib/ai/prompts/job-match/user.ts+++ b/src/lib/ai/prompts/job-match/user.ts@@ -1,88 +1,33 @@/*** Job Match User Prompts- ** Functions to construct user prompts for job match analysis.*//**- * Build user prompt for job match with chain-of-thought instructions+ * Build user prompt for single comprehensive job match analysis*/export function buildJobMatchPrompt(resumeText: string,- jobText: string+ jobDescription: 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:+ return `Compare this resume against the job description and return a JSON analysis.+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.`;+JOB DESCRIPTION:+${jobDescription}++Analyze the match and provide:+- matchScore (0-100)+- recommendation (strong match/good match/partial match/weak match)+- requirements analysis (met, missing, partial)+- skills comparison (matched, missing, transferable, bonus)+- experience assessment (level match, years, relevance)+- keywords (matched, missing, phrases to add)+- dealBreakers (critical missing requirements)+- tailoringTips (specific resume changes)+- summary (2-3 sentence assessment)++Be specific. Reference actual content from both documents.`;}diff --git a/src/lib/ai/scoring.ts b/src/lib/ai/scoring.tsdeleted file mode 100644index de4ca2d..0000000--- a/src/lib/ai/scoring.ts+++ /dev/null@@ -1,268 +0,0 @@-/**- * Strict Scoring System with Mathematical Constraints- * Ensures accurate, consistent scoring across all analyses- */--/**- * Baseline score result type- */-export type BaselineScore = {- score: number;- breakdown: Record<string, number>;-};--/**- * Resume Review Scoring Calculator- * Returns exact scores based on objective metrics- */-export function calculateResumeScore(data: {- quantifiedCount: number;- keywordCount: number;- verbCount: number;- hasBulletPoints: boolean;- sectionCount: number;-}) {- let score = 0;- const breakdown: Record<string, number> = {};-- // 1. Keywords (0-20 points)- // 0 keywords = 0, 5 keywords = 8, 10 keywords = 14, 15+ keywords = 20- if (data.keywordCount === 0) {- breakdown.keywords = 0;- } else if (data.keywordCount < 5) {- breakdown.keywords = Math.min(data.keywordCount * 1.6, 8);- } else if (data.keywordCount < 10) {- breakdown.keywords = 8 + (data.keywordCount - 5) * 1.2;- } else if (data.keywordCount < 15) {- breakdown.keywords = 14 + (data.keywordCount - 10) * 1.2;- } else {- breakdown.keywords = 20;- }-- // 2. Quantified Achievements (0-25 points)- // 0 achievements = 0, 3 achievements = 10, 6 achievements = 18, 10+ achievements = 25- if (data.quantifiedCount === 0) {- breakdown.achievements = 0;- } else if (data.quantifiedCount < 3) {- breakdown.achievements = data.quantifiedCount * 3.3;- } else if (data.quantifiedCount < 6) {- breakdown.achievements = 10 + (data.quantifiedCount - 3) * 2.7;- } else if (data.quantifiedCount < 10) {- breakdown.achievements = 18 + (data.quantifiedCount - 6) * 1.75;- } else {- breakdown.achievements = 25;- }-- // 3. Action Verbs (0-10 points)- // 0 verbs = 0, 5 verbs = 5, 10 verbs = 8, 15+ verbs = 10- if (data.verbCount === 0) {- breakdown.verbs = 0;- } else if (data.verbCount < 5) {- breakdown.verbs = data.verbCount;- } else if (data.verbCount < 10) {- breakdown.verbs = 5 + (data.verbCount - 5) * 0.6;- } else if (data.verbCount < 15) {- breakdown.verbs = 8 + (data.verbCount - 10) * 0.4;- } else {- breakdown.verbs = 10;- }-- // 4. Formatting (0-15 points)- // Has bullets = 8, No bullets = 3- // 2 sections = 2, 3-4 sections = 5, 5+ sections = 7- breakdown.formatting = 0;- breakdown.formatting += data.hasBulletPoints ? 8 : 3;- if (data.sectionCount < 3) {- breakdown.formatting += 2;- } else if (data.sectionCount < 5) {- breakdown.formatting += 5;- } else {- breakdown.formatting += 7;- }-- // 5-8. Other criteria require manual assessment (default to middle values)- // These will be adjusted by the AI based on content- breakdown.summary = 6; // Default: slightly above average- breakdown.experienceClarity = 6;- breakdown.skillsSection = 3;- breakdown.grammar = 4;-- // Calculate total from breakdown- score = Math.round(- breakdown.keywords +- breakdown.achievements +- breakdown.verbs +- breakdown.formatting +- breakdown.summary +- breakdown.experienceClarity +- breakdown.skillsSection +- breakdown.grammar- );-- return {- score: Math.max(0, Math.min(100, score)),- breakdown,- };-}--/**- * Job Match Scoring Calculator- * Returns exact scores based on objective match metrics- */-export function calculateJobMatchScore(data: {- keywordOverlapPercent: number;- matchedSkillsCount: number;- requiredSkillsCount: number;- experienceYears: number;- requiredYears: number;-}) {- let score = 0;- const breakdown: Record<string, number> = {};-- // 1. Skills Match (0-30 points) - MOST IMPORTANT- // Directly proportional to matched/required ratio- if (data.requiredSkillsCount === 0) {- breakdown.skillsMatch = 15; // No specific skills = average score- } else {- const matchRatio = data.matchedSkillsCount / data.requiredSkillsCount;- breakdown.skillsMatch = Math.round(matchRatio * 30);- // Minimum 5 if at least 1 skill matches- if (data.matchedSkillsCount > 0 && breakdown.skillsMatch < 5) {- breakdown.skillsMatch = 5;- }- }-- // 2. Experience Match (0-25 points)- if (data.requiredYears === 0) {- breakdown.experienceMatch = 15; // No requirement = average- } else {- const yearsRatio = data.experienceYears / data.requiredYears;- if (yearsRatio >= 1.5) {- // Significantly exceeds = full points- breakdown.experienceMatch = 25;- } else if (yearsRatio >= 1.0) {- // Meets requirement = good score- breakdown.experienceMatch = 20;- } else if (yearsRatio >= 0.75) {- // Close but under = decent score- breakdown.experienceMatch = 15;- } else if (yearsRatio >= 0.5) {- // Half the requirement = fair score- breakdown.experienceMatch = 10;- } else {- // Less than half = low score- breakdown.experienceMatch = Math.round(yearsRatio * 20);- }- }-- // 3. Keyword Overlap (0-20 points)- // Direct mapping from percentage- breakdown.keywordOverlap = Math.round(- (data.keywordOverlapPercent / 100) * 20- );- // Minimum 2 if any keywords match- if (data.keywordOverlapPercent > 0 && breakdown.keywordOverlap < 2) {- breakdown.keywordOverlap = 2;- }-- // 4. Qualifications (0-15 points) - Will be adjusted by AI- // Default to middle value, AI will adjust based on education/certs- breakdown.qualifications = 8;-- // 5. Industry Fit (0-10 points) - Will be adjusted by AI- // Default to middle value, AI will adjust based on domain knowledge- breakdown.industryFit = 5;-- // Calculate total- score = Math.round(- breakdown.skillsMatch +- breakdown.experienceMatch +- breakdown.keywordOverlap +- breakdown.qualifications +- breakdown.industryFit- );-- return {- score: Math.max(0, Math.min(100, score)),- breakdown,- };-}--/**- * Validate and constrain a score to realistic ranges- */-export function validateScore(- proposedScore: number,- calculatedScore: number,- allowedVariance: number = 10-): number {- // Ensure score is within allowed variance of calculated score- const minScore = Math.max(0, calculatedScore - allowedVariance);- const maxScore = Math.min(100, calculatedScore + allowedVariance);-- if (proposedScore < minScore) {- console.warn(`Score ${proposedScore} too low, adjusting to ${minScore}`);- return minScore;- }- if (proposedScore > maxScore) {- console.warn(`Score ${proposedScore} too high, adjusting to ${maxScore}`);- return maxScore;- }-- return Math.round(proposedScore);-}--/**- * Calculate context-aware allowed variance based on baseline score- * Mid-range scores get more variance since subjective factors matter more- * Extreme scores get tighter variance since they're more objectively determined- */-export function calculateAllowedVariance(- baselineScore: number,- analysisType: "resume" | "job-match"-): number {- // Mid-range scores (40-60) allow more variance for subjective interpretation- if (baselineScore >= 40 && baselineScore <= 60) {- return analysisType === "resume" ? 12 : 15;- }-- // Slightly above/below average (30-40, 60-70)- if (- (baselineScore >= 30 && baselineScore < 40) ||- (baselineScore > 60 && baselineScore <= 70)- ) {- return 10;- }-- // Extreme scores are more objectively determined, tighter variance- if (baselineScore < 30 || baselineScore > 80) {- return 7;- }-- // Default variance- return 10;-}--/**- * Scoring guidelines for AI agents- */-export const SCORING_GUIDELINES = {- resume: {- excellent:- "85-100: Exceptional resume with 10+ quantified achievements, 15+ keywords, perfect formatting",- good: "70-84: Strong resume with 6-9 achievements, 10-14 keywords, good formatting",- average:- "50-69: Decent resume with 3-5 achievements, 5-9 keywords, acceptable formatting",- fair: "35-49: Weak resume with 1-2 achievements, few keywords, poor formatting",- poor: "0-34: Very weak resume with no achievements, minimal keywords, bad formatting",- },- jobMatch: {- excellent:- "85-100: 90%+ skills match, exceeds experience requirement, 80%+ keyword overlap",- good: "70-84: 70-89% skills match, meets experience requirement, 60-79% keyword overlap",- average:- "50-69: 50-69% skills match, 75%+ experience requirement, 40-59% keyword overlap",- fair: "35-49: 30-49% skills match, 50-74% experience requirement, 20-39% keyword overlap",- poor: "0-34: <30% skills match, <50% experience requirement, <20% keyword overlap",- },-};diff --git a/src/lib/ai/tools/index.ts b/src/lib/ai/tools/index.tsindex da4a30d..04b1efa 100644--- a/src/lib/ai/tools/index.ts+++ b/src/lib/ai/tools/index.ts@@ -6,8 +6,6 @@* - text-processing: Shared text normalization and metadata extraction* - preprocessing: Resume preprocessing (normalization, validation)* - preprocessing-job: Job description preprocessing- * - semantic-extraction: LLM-powered skill matching and extraction- * - semantic-similarity: LLM-powered similarity analysis*/// Error classes@@ -45,12 +43,3 @@ export {type JobMetadata,type PreprocessedJob,} from "./preprocessing-job";--// Semantic extraction (LLM-powered)-export { performSemanticSkillMatch } from "./semantic-extraction";--// Semantic similarity (LLM-powered)-export {- calculateSemanticSimilarity,- generateMatchExplanation,-} from "./semantic-similarity";diff --git a/src/lib/ai/tools/semantic-extraction.ts b/src/lib/ai/tools/semantic-extraction.tsdeleted file mode 100644index 48cdb0f..0000000--- a/src/lib/ai/tools/semantic-extraction.ts+++ /dev/null@@ -1,116 +0,0 @@-/**- * Semantic Extraction Tools- * Uses LLM for dynamic, context-aware extraction instead of hard-coded lists- * Provider-aware prompts for Ollama vs Cloud optimization- */--import { generateText, Output } from "ai";-import { getModel, ProviderType } from "../providers";-import {- CombinedResumeAnalysisSchema,- SemanticSkillMatchSchema,- type CombinedResumeAnalysis,- type SemanticSkillMatch,-} from "@/models/ai.schemas";-// ...existing code...-import { getSkillMatchPrompt } from "../prompts";-import {- isOllamaProvider,- OllamaCombinedResumeAnalysisSchema,- OllamaSkillMatchSchema,- normalizeCombinedResumeAnalysis,- normalizeSkillMatch,-} from "../ollama";-import { AIUnavailableError } from "./errors";--/**- * Extract keywords and analyze action verbs in a single LLM call- * Replaces two separate calls with one optimized call- *- * Benefits:- * - 50% faster (one LLM call vs two)- * - Lower token usage- * - Better context sharing between keyword and verb analysis- *- * @param text - Resume text to analyze- * @param provider - AI provider (ollama/openai)- * @param modelName - Model to use for analysis- * @param contextHint - Optional hint about domain (e.g., "software engineering")- */--/**- * Perform semantic skill matching between resume and job- * Uses LLM to understand skill relationships and transferability- *- * Benefits:- * - Recognizes related skills (PostgreSQL vs MySQL)- * - Assesses skill transferability- * - Provides learnability estimates- * - Gives strategic application advice- *- * @param resumeText - Candidate's resume text- * @param jobText - Job description text- * @param provider - AI provider (ollama/openai)- * @param modelName - Model to use for matching- */-export async function performSemanticSkillMatch(- resumeText: string,- jobText: string,- provider: ProviderType = "ollama",- modelName: string = "llama3.2",-): Promise<SemanticSkillMatch> {- const model = getModel(provider, modelName);- const prompt = getSkillMatchPrompt(provider, resumeText, jobText);-- try {- if (isOllamaProvider(provider)) {- const { output } = await generateText({- model,- output: Output.object({ schema: OllamaSkillMatchSchema }),- prompt,- temperature: 0.2,- });- return normalizeSkillMatch(output);- }-- const { output } = await generateText({- model,- output: Output.object({ schema: SemanticSkillMatchSchema }),- prompt,- temperature: 0.2,- });-- // Post-process cloud result to remove empty strings and duplicates- const cleanedResult = {- exact_matches: output.exact_matches.filter(- (match) =>- match.skill.trim() &&- match.resume_evidence.trim() &&- match.job_requirement.trim(),- ),- related_matches: output.related_matches.filter(- (match) =>- match.job_skill.trim() &&- match.resume_skill.trim() &&- match.explanation.trim(),- ),- missing_skills: output.missing_skills.filter((skill) =>- skill.skill.trim(),- ),- overall_match_percentage: output.overall_match_percentage,- };-- // Remove duplicate skills from missing_skills if they're in exact_matches- const exactSkills = new Set(- cleanedResult.exact_matches.map((m) => m.skill.toLowerCase()),- );- cleanedResult.missing_skills = cleanedResult.missing_skills.filter(- (m) => !exactSkills.has(m.skill.toLowerCase()),- );-- return cleanedResult;- } catch (error) {- console.error("Semantic skill matching failed:", error);- throw new AIUnavailableError("skill matching");- }-}diff --git a/src/lib/ai/tools/semantic-similarity.ts b/src/lib/ai/tools/semantic-similarity.tsdeleted file mode 100644index e40801c..0000000--- a/src/lib/ai/tools/semantic-similarity.ts+++ /dev/null@@ -1,207 +0,0 @@-/**- * Semantic Similarity Tools- * Complete semantic understanding of resume-job fit, replacing keyword overlap- */--import { generateText, Output } from "ai";-import { getModel, ProviderType } from "../providers";-import {- SemanticSimilaritySchema,- type SemanticSimilarityResult,- type SemanticSkillMatch,-} from "@/models/ai.schemas";-import { getSimilarityPrompt } from "../prompts";-import {- isOllamaProvider,- OllamaSemanticSimilaritySchema,- normalizeSemanticSimilarity,- type OllamaSemanticSimilarity,-} from "../ollama";-import { AIUnavailableError } from "./errors";--/**- * Calculate semantic similarity between resume and job description- * This is the core function that replaces keyword overlap entirely- *- * Uses LLM to:- * 1. Calculate overall semantic similarity (0-100)- * 2. Generate human-readable explanation of fit- * 3. Identify key matching areas and gaps- * 4. Provide strategic application advice- *- * @param resumeText - Candidate's resume text- * @param jobDescription - Job description text- * @param provider - AI provider (ollama/openai/deepseek)- * @param modelName - Model to use- * @returns SemanticSimilarityResult with score, explanations, and recommendations- */-export async function calculateSemanticSimilarity(- resumeText: string,- jobDescription: string,- provider: ProviderType = "ollama",- modelName: string = "llama3.2"-): Promise<SemanticSimilarityResult> {- const model = getModel(provider, modelName);- const prompt = getSimilarityPrompt(provider, resumeText, jobDescription);-- try {- if (isOllamaProvider(provider)) {- const { output } = await generateText({- model,- output: Output.object({ schema: OllamaSemanticSimilaritySchema }),- prompt,- temperature: 0.2,- });- return normalizeSemanticSimilarity(output);- }-- const { output } = await generateText({- model,- output: Output.object({ schema: SemanticSimilaritySchema }),- prompt,- temperature: 0.2,- });-- return output;- } catch (error) {- console.error("Semantic similarity calculation failed:", error);- throw new AIUnavailableError("similarity calculation");- }-}--/**- * Generate a comprehensive match explanation combining semantic skill matching- * and overall similarity assessment- *- * This function synthesizes data from performSemanticSkillMatch and calculateSemanticSimilarity- * to create detailed, actionable explanations for the user- *- * @param skillMatch - Result from performSemanticSkillMatch- * @param similarity - Result from calculateSemanticSimilarity- * @returns Structured explanation with fit summary and detailed insights- */-export function generateMatchExplanation(- skillMatch: SemanticSkillMatch,- similarity: SemanticSimilarityResult-): {- summary: string;- fit_assessment: string;- strengths_explanation: string[];- gaps_explanation: string[];- transferable_explanation: string[];- action_items: string[];-} {- // Generate strengths explanation from exact and related matches- const strengthsExplanation: string[] = [];-- skillMatch.exact_matches.slice(0, 3).forEach((match) => {- strengthsExplanation.push(- `✅ **${- match.skill- }**: Directly matches requirement - "${match.resume_evidence.substring(- 0,- 60- )}..."`- );- });-- skillMatch.related_matches.slice(0, 2).forEach((match) => {- strengthsExplanation.push(- `⚡ **${match.resume_skill}** transfers to **${match.job_skill}** (${match.similarity}% similar): ${match.explanation}`- );- });-- // Generate gaps explanation with learnability context- const gapsExplanation: string[] = [];-- skillMatch.missing_skills.slice(0, 4).forEach((skill) => {- const urgencyIcon =- skill.importance === "critical"- ? "🔴"- : skill.importance === "important"- ? "🟡"- : "🟢";- const learnTime =- skill.learnability === "quick"- ? "<1 month"- : skill.learnability === "moderate"- ? "1-3 months"- : "3+ months";- gapsExplanation.push(- `${urgencyIcon} **${skill.skill}** (${skill.importance}): Learning time ~${learnTime}`- );- });-- // Generate transferable skills explanation- const transferableExplanation: string[] = similarity.transferable_skills.map(- (skill) =>- `💡 ${skill.resume_skill} → ${skill.job_skill}: ${skill.how_it_transfers}`- );-- // Generate prioritized action items- const actionItems: string[] = [];-- // Critical missing skills first- const criticalMissing = skillMatch.missing_skills.filter(- (s) => s.importance === "critical"- );- if (criticalMissing.length > 0) {- actionItems.push(- `🔴 Address critical gaps first: ${criticalMissing- .map((s) => s.skill)- .join(", ")}`- );- }-- // Quick wins- const quickLearns = skillMatch.missing_skills.filter(- (s) => s.learnability === "quick" && s.importance !== "nice-to-have"- );- if (quickLearns.length > 0) {- actionItems.push(- `⚡ Quick wins (learn in <1 month): ${quickLearns- .map((s) => s.skill)- .join(", ")}`- );- }-- // Highlight existing transferable skills in application- if (skillMatch.related_matches.length > 0) {- actionItems.push(- `📝 Highlight transferable skills in cover letter: ${skillMatch.related_matches- .slice(0, 3)- .map((m) => m.resume_skill)- .join(", ")}`- );- }-- // Fit assessment based on scores- let fitAssessment: string;- const score = similarity.similarity_score;- if (score >= 75) {- fitAssessment = "Excellent fit - You're a strong candidate for this role.";- } else if (score >= 60) {- fitAssessment = "Good fit - You match most requirements with minor gaps.";- } else if (score >= 45) {- fitAssessment =- "Moderate fit - Some gaps exist but may be worth applying with a tailored resume.";- } else if (score >= 30) {- fitAssessment =- "Weak fit - Significant gaps; consider upskilling before applying.";- } else {- fitAssessment =- "Poor fit - This role may not align with your current skills and experience.";- }-- return {- summary: similarity.match_explanation,- fit_assessment: fitAssessment,- strengths_explanation: strengthsExplanation,- gaps_explanation: gapsExplanation,- transferable_explanation: transferableExplanation,- action_items:- actionItems.length > 0- ? actionItems- : ["No critical actions needed - proceed with application"],- };-}diff --git a/src/models/ai.model.ts b/src/models/ai.model.tsindex d057075..0715ffe 100644--- a/src/models/ai.model.ts+++ b/src/models/ai.model.ts@@ -1,70 +1,16 @@-// Import types needed in this file-import type {- SemanticSkillMatch,- SemanticSimilarityResult,-} from "./ai.schemas";--// Re-export types from new schemas+// Re-export types from schemasexport type {ResumeReviewResponse,JobMatchResponse,- JobMatchAnalysis,- SemanticKeywordExtraction,- ActionVerbAnalysis,- SemanticSkillMatch,- SemanticSimilarityResult,-} from "./ai.schemas";-export {- ResumeReviewSchema,- JobMatchSchema,- SemanticKeywordSchema,- ActionVerbAnalysisSchema,- SemanticSkillMatchSchema,- SemanticSimilaritySchema,+ RequirementMet,+ RequirementMissing,+ RequirementPartial,+ SkillsAnalysis,+ ExperienceAnalysis,+ KeywordsAnalysis,+ TailoringTip,} from "./ai.schemas";--// JOB MATCH TYPES--export interface SemanticData {- skillMatch: SemanticSkillMatch | null;- similarity: SemanticSimilarityResult | null;- matchExplanation: {- summary: string;- fit_assessment: string;- strengths_explanation: string[];- gaps_explanation: string[];- transferable_explanation: string[];- action_items: string[];- } | null;-}--export interface ToolDataResume {- quantified: { count: number; examples: string[] };- keywords: { keywords: string[]; count: number };- verbs: { count: number; verbs: string[] };- formatting: {- hasBulletPoints: boolean;- hasConsistentSpacing: boolean;- averageLineLength: number;- sectionCount: number;- };-}--export interface ToolDataJobMatch {- keywordOverlap: {- overlapPercentage: number;- matchedKeywords: string[];- missingKeywords: string[];- totalJobKeywords: number;- };- resumeKeywords: { keywords: string[]; count: number };- jobKeywords: { keywords: string[]; count: number };- requiredSkills: {- requiredSkills: string[];- preferredSkills: string[];- totalSkills: number;- };-}+export { ResumeReviewSchema, JobMatchSchema } from "./ai.schemas";// AI MODEL@@ -78,9 +24,6 @@ export enum AiProvider {OLLAMA = "ollama",OPENAI = "openai",DEEPSEEK = "deepseek",- // Future providers:- // GEMINI = "gemini",- // CLAUDE = "claude",}// Default models per provider@@ -95,7 +38,6 @@ export enum OpenaiModel {GPT4O_MINI = "gpt-4o-mini",}-// DeepSeek models - fallback if API is unavailableexport enum DeepseekModel {DEEPSEEK_CHAT = "deepseek-chat",DEEPSEEK_REASONER = "deepseek-reasoner",diff --git a/src/models/ai.ollama-schemas.ts b/src/models/ai.ollama-schemas.tsdeleted file mode 100644index 87a3d90..0000000--- a/src/models/ai.ollama-schemas.ts+++ /dev/null@@ -1,84 +0,0 @@-/**- * Phase 4: Simplified Ollama Schemas- *- * These schemas are optimized for small local models like llama3.2:- * - Fewer fields (3-4 vs 5-6)- * - Flatter structure (avoid deep nesting)- * - Simpler descriptions- */--import { z } from "zod";--/**- * Simplified keyword extraction schema for Ollama- * 3 fields vs 6 in the full schema- */-export const OllamaSemanticKeywordSchema = z.object({- technical_skills: z- .array(z.string())- .describe("Languages, frameworks, libraries"),- tools: z.array(z.string()).describe("Platforms, services, tools"),- total_count: z.number().describe("Total skills found"),-});--/**- * Simplified action verb analysis schema for Ollama- * 3 fields vs complex nested structure in full schema- */-export const OllamaActionVerbSchema = z.object({- strong_verbs: z.array(z.string()).describe("Strong action verbs found"),- weak_verbs: z.array(z.string()).describe("Weak verbs to replace"),- verb_strength_score: z- .number()- .min(0)- .max(10)- .describe("Overall strength 0-10"),-});--/**- * Combined schema for Ollama resume analysis (keywords + verbs)- */-export const OllamaCombinedResumeAnalysisSchema = z.object({- keywords: OllamaSemanticKeywordSchema.describe("Skills and keywords"),- verbs: OllamaActionVerbSchema.describe("Action verb analysis"),-});--/**- * Simplified skill matching schema for Ollama- * Flatter structure with simpler matched_skills array- */-export const OllamaSkillMatchSchema = z.object({- matched_skills: z- .array(- z.object({- skill: z.string(),- evidence: z.string(),- }),- )- .describe("Skills found in both"),- missing_skills: z.array(z.string()).describe("Required but not in resume"),- match_percentage: z.number().min(0).max(100),-});--/**- * Simplified semantic similarity schema for Ollama- * 3 fields vs 6 in the full schema- */-export const OllamaSemanticSimilaritySchema = z.object({- similarity_score: z.number().min(0).max(100).describe("Overall fit 0-100"),- match_explanation: z.string().describe("Why good/poor fit (2 sentences)"),- key_gaps: z.array(z.string()).max(3).describe("Top missing skills"),-});--// Type exports for use in normalizer functions-export type OllamaSemanticKeywordExtraction = z.infer<- typeof OllamaSemanticKeywordSchema->;-export type OllamaActionVerbAnalysis = z.infer<typeof OllamaActionVerbSchema>;-export type OllamaCombinedResumeAnalysis = z.infer<- typeof OllamaCombinedResumeAnalysisSchema->;-export type OllamaSkillMatch = z.infer<typeof OllamaSkillMatchSchema>;-export type OllamaSemanticSimilarity = z.infer<- typeof OllamaSemanticSimilaritySchema->;diff --git a/src/models/ai.schemas.ts b/src/models/ai.schemas.tsindex e0b887e..33ac9f4 100644--- a/src/models/ai.schemas.ts+++ b/src/models/ai.schemas.ts@@ -132,407 +132,106 @@ export type ResumeImprovement = z.infer<typeof ImprovementSchema>;export type GrammarError = z.infer<typeof GrammarErrorSchema>;export type GrammarAndSpelling = z.infer<typeof GrammarAndSpellingSchema>;-/**- * Schema for analysis category used in job match response.- */-const AnalysisCategorySchema = z.object({- category: z.string().describe(- `Category title with score breakdown.-- Format: "[Category Name] ([X]/[Max] pts)"-- Examples:- - "Skills Match (22/30 pts)"- - "Experience Match (18/25 pts)"- - "Keyword Overlap (14/20 pts)"- - "Qualifications (10/15 pts)"- - "Industry Fit (7/10 pts)"`,- ),- value: z.array(z.string()).describe(- `List of specific observations with EVIDENCE.-- For Skills Match:- - "✅ React: Found 'Led React migration to v18' in resume"- - "✅ TypeScript: Mentioned 5 times across experience section"- - "⚠️ PostgreSQL: Has MySQL experience (related, not exact)"- - "❌ Kubernetes: Not found in resume"-- For Experience Match:- - "Required: 5+ years backend development"- - "Candidate: 6 years at similar companies (exceeds)"- - "Quality: Led team, built microservices at scale"+// JOB MATCH SCHEMA+// Single LLM call for comprehensive job-resume matching- For Keyword Overlap:- - "Found: React, TypeScript, Node.js, AWS, Docker, Agile, REST API (7 of 10)"- - "Missing: Kubernetes, Redis, GraphQL (3 of 10)"`,- ),+const RequirementMetSchema = z.object({+ requirement: z.string().describe("What the JD asked for"),+ evidence: z.string().describe("Where/how the resume demonstrates this"),});-export type JobMatchAnalysis = z.infer<typeof AnalysisCategorySchema>;--/**- * Schema for job match AI response.- * Designed for maximum actionability and transparency.- */-export const JobMatchSchema = z.object({- matching_score: z- .number()- .min(0)- .max(100)- .describe(- `MUST be a number 0-100. Calculate as sum of 5 criteria:- - Skills Match (0-30): (matched_skills / required_skills) × 30- - Experience Match (0-25): Based on years and relevance- - Keyword Overlap (0-20): (found_keywords / job_keywords) × 20- - Qualifications (0-15): Education and certifications- - Industry Fit (0-10): Domain relevance-- Realistic ranges:- - 80+: Excellent match, interview likely- - 65-79: Strong match, apply with confidence- - 50-64: Moderate match, tailor resume- - 35-49: Weak match, consider upskilling- - <35: Poor match, may not be right fit-- Most candidates score 40-60 against any given job.- NEVER return 0 unless completely unrelated industry/role.`,- ),- detailed_analysis: z- .array(AnalysisCategorySchema)- .min(3)- .max(5)- .describe(- `Array of 3-5 analysis categories showing your scoring breakdown.-- REQUIRED categories (must include these 3):- 1. "Skills Match (X/30 pts)" - List each required skill with ✅/⚠️/❌ and evidence- 2. "Experience Match (X/25 pts)" - Compare years, relevance, quality- 3. "Keyword Overlap (X/20 pts)" - List found vs missing keywords-- OPTIONAL categories (include if relevant):- 4. "Qualifications (X/15 pts)" - Education, certifications match- 5. "Industry Fit (X/10 pts)" - Domain knowledge assessment-- Each category MUST have specific evidence, not vague statements.`,- ),- suggestions: z- .array(AnalysisCategorySchema)- .min(2)- .max(4)- .describe(- `Array of 2-4 suggestion categories with ACTIONABLE improvements.-- Recommended categories:-- 1. "Keywords to Add to Resume" (Quick Win):- - List EXACT terms from job description missing from resume- - Example: ["Add 'Kubernetes' to skills section", "Include 'GraphQL' in project descriptions"]-- 2. "Skills to Highlight" (Quick Win):- - Existing resume content to emphasize more- - Example: ["Move AWS experience to top of skills", "Expand on React migration project"]-- 3. "Experience Gaps to Address" (Short-term):- - Certifications to obtain- - Portfolio pieces to create- - Example: ["Get AWS Solutions Architect cert", "Build a Kubernetes demo project"]-- 4. "Skills to Develop" (Long-term):- - New skills to learn for better match- - Example: ["Learn GraphQL fundamentals", "Get hands-on with PostgreSQL"]-- Each suggestion must be SPECIFIC and IMPLEMENTABLE.`,- ),- additional_comments: z- .array(z.string())- .min(2)- .max(3)- .describe(- `2-3 brief statements that MUST include:-- 1. Overall candidacy assessment:- - "Strong candidate with 70% skill match and relevant experience"- - "Moderate fit - has core skills but missing 2 key requirements"-- 2. Top priority action:- - "Priority: Add PostgreSQL experience or equivalent database skills"- - "Priority: Quantify your React project impact"-- 3. Clear application recommendation:- - "Recommendation: Apply now - strong match"- - "Recommendation: Apply after adding missing keywords to resume"- - "Recommendation: Consider upskilling in [X] before applying"- - "Recommendation: This role may not be the best fit currently"-- Be direct and honest about fit. Don't sugarcoat poor matches.`,- ),+const RequirementMissingSchema = z.object({+ requirement: z.string().describe("What the JD asked for"),+ importance: z.enum(["required", "preferred"]).describe("How critical this requirement is"),+ suggestion: z.string().describe("How to address this gap"),});-export type JobMatchResponse = z.infer<typeof JobMatchSchema>;--// ============================================================================-// SEMANTIC EXTRACTION SCHEMAS (Phase 1 Improvements)-// ============================================================================--/**- * Schema for LLM-based keyword/skill extraction- * Replaces hard-coded keyword lists with dynamic extraction- */-export const SemanticKeywordSchema = z.object({- technical_skills: z.array(z.string()).describe(- `Programming languages, frameworks, libraries extracted from text.- Examples: ["Python", "React", "TypeScript", "Django", "TensorFlow"]- Be comprehensive - extract ALL technical skills mentioned.`,- ),- tools_platforms: z.array(z.string()).describe(- `Development tools, platforms, services, and cloud providers.- Examples: ["Docker", "Kubernetes", "AWS", "GitHub Actions", "JIRA", "Figma"]- Include both infrastructure and productivity tools.`,- ),- methodologies: z.array(z.string()).describe(- `Development methodologies, practices, and processes.- Examples: ["Agile", "Scrum", "TDD", "CI/CD", "DevOps", "Microservices"]- Include architectural patterns and best practices.`,- ),- domain_knowledge: z.array(z.string()).describe(- `Industry-specific knowledge and compliance frameworks.- Examples: ["Healthcare", "HIPAA", "FinTech", "SOX", "GDPR", "FDA regulations"]- Include certifications and domain expertise.`,- ),- soft_skills: z.array(z.string()).describe(- `Leadership and interpersonal skills mentioned.- Examples: ["Team leadership", "Cross-functional collaboration", "Mentoring"]- Only include if explicitly stated or clearly demonstrated.`,- ),- total_count: z- .number()- .describe("Total unique keywords across all categories"),+const RequirementPartialSchema = z.object({+ requirement: z.string().describe("What the JD asked for"),+ gap: z.string().describe("What's lacking or incomplete"),+ evidence: z.string().describe("What the resume does show"),});-export type SemanticKeywordExtraction = z.infer<typeof SemanticKeywordSchema>;--/**- * Schema for action verb analysis- * Replaces hard-coded verb lists with semantic strength assessment- */-export const ActionVerbAnalysisSchema = z.object({- strong_verbs: z- .array(- z.object({- verb: z.string().describe("The action verb found"),- context: z- .string()- .describe("Brief context where it was used (max 50 chars)"),- impact_level: z- .enum(["high", "medium"])- .describe(- "High: Led, Architected, Spearheaded, Delivered. Medium: Managed, Developed, Implemented",- ),- }),- )- .describe(- `Strong action verbs that demonstrate ownership and impact.- High impact: Led, Architected, Spearheaded, Delivered, Drove, Built, Scaled, Transformed- Medium impact: Managed, Developed, Implemented, Created, Designed, Coordinated`,- ),- weak_verbs: z- .array(- z.object({- verb: z.string().describe("The weak verb/phrase found"),- context: z- .string()- .describe("Brief context where it was used (max 50 chars)"),- suggestion: z- .string()- .describe("Stronger alternative verb to use instead"),- }),- )- .describe(- `Weak verbs/phrases that reduce impact.- Examples: "Responsible for", "Helped with", "Assisted in", "Worked on", "Involved in"- These should be replaced with action-oriented alternatives.`,- ),- verb_strength_score: z- .number()- .min(0)- .max(10)- .describe(- `Overall verb strength score 0-10:- 0-3: Mostly passive language- 4-6: Mix of strong and weak verbs- 7-8: Predominantly strong verbs- 9-10: Exceptional action-oriented language throughout`,- ),+const RequirementsSchema = z.object({+ met: z.array(RequirementMetSchema).describe("Requirements fully satisfied by the resume"),+ missing: z.array(RequirementMissingSchema).describe("Requirements not found in the resume"),+ partial: z.array(RequirementPartialSchema).describe("Requirements partially met"),});-export type ActionVerbAnalysis = z.infer<typeof ActionVerbAnalysisSchema>;--/**- * Combined schema for resume analysis (keywords + verbs)- * Single LLM call instead of two separate calls- */-export const CombinedResumeAnalysisSchema = z.object({- keywords: SemanticKeywordSchema.describe(- "All keywords and skills extracted from the resume",- ),- verbs: ActionVerbAnalysisSchema.describe(- "Action verb analysis with strength assessment",- ),+const SkillsAnalysisSchema = z.object({+ matched: z.array(z.string()).describe("Skills that align between resume and JD"),+ missing: z.array(z.string()).describe("Required skills not found in resume"),+ transferable: z.array(z.string()).describe("Resume skills that could apply but aren't exact match"),+ bonus: z.array(z.string()).describe("Resume skills beyond JD requirements"),});-export type CombinedResumeAnalysis = z.infer<- typeof CombinedResumeAnalysisSchema->;--/**- * Schema for skill matching between resume and job- * Provides semantic similarity scoring, not just string matching- */-export const SemanticSkillMatchSchema = z.object({- exact_matches: z- .array(- z.object({- skill: z.string().min(1).describe("The skill that matches exactly"),- resume_evidence: z- .string()- .min(1)- .describe("Quote from resume showing this skill"),- job_requirement: z- .string()- .min(1)- .describe("Quote from job showing this requirement"),- }),- )- .describe("Skills that match exactly between resume and job"),- related_matches: z- .array(- z.object({- job_skill: z.string().min(1).describe("Skill required by job"),- resume_skill: z.string().min(1).describe("Related skill in resume"),- similarity: z- .number()- .min(0)- .max(100)- .describe("Similarity percentage (e.g., PostgreSQL vs MySQL = 85%)"),- explanation: z- .string()- .min(1)- .describe("Why these skills are related/transferable"),- }),- )- .describe(- "Skills that are related/similar but not exact matches (e.g., React vs Vue, PostgreSQL vs MySQL)",- ),- missing_skills: z- .array(- z.object({- skill: z.string().min(1).describe("Required skill not found in resume"),- importance: z- .enum(["critical", "important", "nice-to-have"])- .describe("How important this skill is for the role"),- learnability: z- .enum(["quick", "moderate", "significant"])- .describe(- "How quickly this could be learned: quick (<1 month), moderate (1-3 months), significant (3+ months)",- ),- }),- )- .describe("Skills required by job but not found in resume"),- overall_match_percentage: z+const ExperienceAnalysisSchema = z.object({+ levelMatch: z+ .enum(["overqualified", "match", "underqualified"])+ .describe("How candidate's level compares to requirements"),+ yearsRequired: z.number()- .min(0)- .max(100)- .describe(- "Overall skill match percentage considering exact + related matches",- ),+ .nullable()+ .describe("Years of experience required by JD, null if not specified"),+ yearsApparent: z.number().describe("Apparent years of experience from resume"),+ relevance: z+ .enum(["highly relevant", "somewhat relevant", "different field"])+ .describe("How relevant the candidate's experience is to this role"),});-export type SemanticSkillMatch = z.infer<typeof SemanticSkillMatchSchema>;+const KeywordsAnalysisSchema = z.object({+ matched: z.array(z.string()).describe("JD keywords found in resume"),+ missing: z.array(z.string()).describe("Important JD keywords to add"),+ addToResume: z.array(z.string()).describe("Exact phrases from JD to incorporate"),+});-// ============================================================================-// PHASE 3: SEMANTIC SIMILARITY SCHEMA-// Complete semantic understanding with explanations-// ============================================================================+const TailoringTipSchema = z.object({+ section: z.string().describe("Which resume section to modify"),+ action: z.string().describe("Specific change to make"),+});/**- * Schema for comprehensive semantic similarity analysis- * Replaces keyword overlap with true semantic understanding+ * Comprehensive Job Match Schema+ * Single LLM call returns complete job-resume fit analysis*/-export const SemanticSimilaritySchema = z.object({- similarity_score: z+export const JobMatchSchema = z.object({+ matchScore: z.number().min(0).max(100).describe(- `Overall semantic similarity score (0-100) based on:- - Skills alignment (exact + transferable)- - Experience relevance (years, seniority, industry)- - Role fit (career trajectory alignment)- - Culture signals (values, working style)-- Guidelines:- 80-100: Exceptional fit- 65-79: Strong fit- 50-64: Moderate fit- 35-49: Weak fit- 0-34: Poor fit`,+ `Overall match score 0-100. Realistic ranges:+ - 80-100: Strong match, high interview likelihood+ - 65-79: Good match, apply with confidence+ - 50-64: Partial match, tailor resume carefully+ - 35-49: Weak match, significant gaps exist+ - <35: Poor match, consider other roles`,),-- match_explanation: z.string().describe(- `2-3 sentence explanation of why this candidate is/isn't a good fit.- Start with the key reason (e.g., "Strong technical alignment with 80% skill match...")- Include both positives and concerns.`,- ),-- key_matches: z+ recommendation: z+ .enum(["strong match", "good match", "partial match", "weak match"])+ .describe("Overall recommendation based on match analysis"),+ requirements: RequirementsSchema.describe("Detailed requirements matching analysis"),+ skills: SkillsAnalysisSchema.describe("Skills comparison between resume and JD"),+ experience: ExperienceAnalysisSchema.describe("Experience level and relevance assessment"),+ keywords: KeywordsAnalysisSchema.describe("Keyword overlap and gaps"),+ dealBreakers: z.array(z.string())+ .describe("Critical requirements completely missing that may disqualify candidate"),+ tailoringTips: z+ .array(TailoringTipSchema).min(1).max(5)- .describe(- `Top 3-5 areas where candidate strongly matches requirements.- Examples: "5+ years React experience matches requirement",- "Led team of 8 engineers, exceeds leadership requirement"`,- ),-- key_gaps: z- .array(- z.object({- skill: z.string().describe("The skill or requirement that's missing"),- note: z- .string()- .describe("Brief note on gap severity or how to address"),- }),- )- .max(5)- .describe(- `Top 3-5 gaps between resume and job requirements.- Include severity/importance of each gap.`,- ),-- transferable_skills: z- .array(- z.object({- resume_skill: z.string().describe("Skill the candidate has"),- job_skill: z.string().describe("Required skill it could transfer to"),- how_it_transfers: z- .string()- .describe("Brief explanation of transferability"),- }),- )- .max(4)- .describe(- `Skills in resume that could apply to missing requirements.- Example: MySQL knowledge transfers to PostgreSQL (both SQL databases)`,- ),-- application_recommendation: z.string().describe(- `Clear, actionable recommendation.- Examples:- - "Apply now - strong match, highlight your React migration project"- - "Apply after adding Docker basics - critical gap for this role"- - "Consider upskilling in Kubernetes before applying - key requirement"- - "May not be the best fit - role requires senior-level system design"`,- ),+ .describe("Specific, actionable resume modifications to improve match"),+ summary: z+ .string()+ .describe("2-3 sentence assessment of fit and main action items"),});-export type SemanticSimilarityResult = z.infer<typeof SemanticSimilaritySchema>;+export type JobMatchResponse = z.infer<typeof JobMatchSchema>;+export type RequirementMet = z.infer<typeof RequirementMetSchema>;+export type RequirementMissing = z.infer<typeof RequirementMissingSchema>;+export type RequirementPartial = z.infer<typeof RequirementPartialSchema>;+export type SkillsAnalysis = z.infer<typeof SkillsAnalysisSchema>;+export type ExperienceAnalysis = z.infer<typeof ExperienceAnalysisSchema>;+export type KeywordsAnalysis = z.infer<typeof KeywordsAnalysisSchema>;+export type TailoringTip = z.infer<typeof TailoringTipSchema>;