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
feat: add review_resume tool with a nested review generation
Khuram Niaz1339d97e0517
diff --git a/__tests__/agentReviewResumeTool.spec.ts b/__tests__/agentReviewResumeTool.spec.tsnew file mode 100644index 0000000..3e57141--- /dev/null+++ b/__tests__/agentReviewResumeTool.spec.ts@@ -0,0 +1,221 @@+import { buildReviewResumeTool } from "@/lib/agent/tools/reviewResume";+import { resolveResumeForAgent } from "@/lib/agent/resumeLookup";+import { preprocessResume } from "@/lib/ai/tools/preprocessing";+import { saveResumeReviewResult } from "@/actions/profile.actions";+import { APP_CONSTANTS } from "@/lib/constants";+import { TEMPERATURES } from "@/lib/ai/config";+import {+ RESUME_REVIEW_SYSTEM_PROMPT,+ buildResumeReviewPrompt,+} from "@/lib/ai/prompts/resume-review";++vi.mock("@/lib/agent/resumeLookup", () => ({ resolveResumeForAgent: vi.fn() }));+vi.mock("@/lib/ai/tools/preprocessing", () => ({ preprocessResume: vi.fn() }));+vi.mock("@/actions/profile.actions", () => ({+ saveResumeReviewResult: vi.fn(),+}));++const streamText = vi.fn();+vi.mock("ai", async (importOriginal) => {+ const actual = await importOriginal<typeof import("ai")>();+ return { ...actual, streamText: (...args: unknown[]) => streamText(...(args as [])) };+});++const resolve = resolveResumeForAgent as unknown as ReturnType<typeof vi.fn>;+const preprocess = preprocessResume as unknown as ReturnType<typeof vi.fn>;+const save = saveResumeReviewResult as unknown as ReturnType<typeof vi.fn>;++const REVIEW =+ "SCORES: overall=78 impact=72 clarity=81 ats=69\n\n## Summary\n\nSolid resume.";++// A resume long enough that the old 12k get_resume ceiling would have cut it.+const LONG_RESUME = "R".repeat(APP_CONSTANTS.AGENT_CHAT_RESUME_MAX_CHARS + 5_000);++function textStreamOf(chunks: string[]) {+ return {+ textStream: (async function* () {+ for (const chunk of chunks) yield chunk;+ })(),+ };+}++const writer = { write: vi.fn(), merge: vi.fn(), onError: undefined };++const ctx = () => ({+ userId: "session-user",+ pageResumeId: "page-resume",+ model: { id: "fake-model" } as any,+ provider: "ollama",+ modelName: "qwen3.5:9b",+ writer: writer as any,+});++const execute = (agentTool: any, input: any) =>+ agentTool.execute(input, { toolCallId: "call-1", messages: [] });++describe("review_resume agent tool", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resolve.mockResolvedValue({+ status: "ok",+ resume: { id: "r1", title: "Senior Engineer Resume" },+ source: "default",+ ambiguousTitle: false,+ });+ preprocess.mockResolvedValue({+ success: true,+ data: { normalizedText: LONG_RESUME, metadata: {}, isValid: true },+ });+ streamText.mockReturnValue(textStreamOf([REVIEW]));+ save.mockResolvedValue({ success: true });+ });++ // The gate exists to stop unseen writes. This writes only to the caller's+ // own reviewData, and they watch it stream.+ it("has no approval gate", () => {+ expect(buildReviewResumeTool(ctx()).needsApproval).toBeUndefined();+ });++ it("passes the SESSION userId, never one supplied by the model", async () => {+ await execute(buildReviewResumeTool(ctx()), { userId: "attacker-user" });+ expect(resolve).toHaveBeenCalledWith("session-user", expect.anything());+ });++ it("ignores a resumeId the model invents and forwards only the title", async () => {+ await execute(buildReviewResumeTool(ctx()), {+ resumeId: "someone-elses-resume",+ resumeTitle: "Senior Engineer Resume",+ });+ expect(resolve).toHaveBeenCalledWith("session-user", {+ title: "Senior Engineer Resume",+ pageResumeId: "page-resume",+ });+ });++ // Parity, asserted on the exact five inputs the dedicated route uses.+ it("generates with the dedicated route's prompt, temperature and context", async () => {+ await execute(buildReviewResumeTool(ctx()), {});+ const args = streamText.mock.calls[0][0];+ expect(args.system).toBe(RESUME_REVIEW_SYSTEM_PROMPT);+ expect(args.prompt).toBe(buildResumeReviewPrompt(LONG_RESUME));+ expect(args.temperature).toBe(TEMPERATURES.FEEDBACK);+ expect(args.providerOptions.ollama.options.num_ctx).toBe(+ APP_CONSTANTS.AI_OLLAMA_NUM_CTX,+ );+ expect(args.abortSignal).toBeDefined();+ });++ it("sends the resume untruncated, unlike get_resume", async () => {+ await execute(buildReviewResumeTool(ctx()), {});+ expect(streamText.mock.calls[0][0].prompt).toContain(LONG_RESUME);+ });++ it("streams the sub-call's tokens as transient parts keyed by the tool call", async () => {+ streamText.mockReturnValue(textStreamOf(["SCORES: ", "overall=78 ", "impact=72 clarity=81 ats=69\n\nBody"]));+ await execute(buildReviewResumeTool(ctx()), {});+ expect(writer.write).toHaveBeenCalledTimes(3);+ const first = writer.write.mock.calls[0][0];+ expect(first.type).toBe("data-review");+ expect(first.id).toBe("call-1");+ expect(first.transient).toBe(true);+ expect(+ writer.write.mock.calls.map((c: any[]) => c[0].data.delta).join(""),+ ).toContain("SCORES: overall=78");+ });++ it("returns scores and the markdown body, with the scores line stripped", async () => {+ const result = await execute(buildReviewResumeTool(ctx()), {});+ expect(result.status).toBe("ok");+ expect(result.resumeId).toBe("r1");+ expect(result.title).toBe("Senior Engineer Resume");+ expect(result.scores).toEqual({+ overall: 78,+ impact: 72,+ clarity: 81,+ atsCompatibility: 69,+ });+ expect(result.body).not.toContain("SCORES:");+ expect(result.body).toContain("## Summary");+ expect(result.saved).toBe(true);+ });++ it("does not return the resume text to the model", async () => {+ const result = await execute(buildReviewResumeTool(ctx()), {});+ expect(JSON.stringify(result)).not.toContain(LONG_RESUME);+ });++ it("saves the review itself, scoped to the resume it reviewed", async () => {+ await execute(buildReviewResumeTool(ctx()), {});+ expect(save).toHaveBeenCalledTimes(1);+ const [resumeId, payload] = save.mock.calls[0];+ expect(resumeId).toBe("r1");+ const data = JSON.parse(payload);+ expect(data.overall).toBe(78);+ expect(data.atsCompatibility).toBe(69);+ expect(data.body).toContain("## Summary");+ expect(data.provider).toBe("ollama");+ expect(data.model).toBe("qwen3.5:9b");+ expect(data.surface).toBe(APP_CONSTANTS.AGENT_CHAT_REVIEW_SURFACE);+ expect(typeof data.reviewedAt).toBe("string");+ });++ it("reports a save failure in the result instead of swallowing it", async () => {+ save.mockResolvedValue({ success: false, message: "Database is locked." });+ const result = await execute(buildReviewResumeTool(ctx()), {});+ expect(result.status).toBe("ok");+ expect(result.saved).toBe(false);+ expect(result.saveError).toBe("Database is locked.");+ });++ // A half review must never be saved: reviewData is overwrite-only.+ it("fails the generation and saves nothing when no scores line arrives", async () => {+ streamText.mockReturnValue(textStreamOf(["No scores here, just prose."]));+ const result = await execute(buildReviewResumeTool(ctx()), {});+ expect(result.status).toBe("generation_failed");+ expect(save).not.toHaveBeenCalled();+ });++ it("returns generation_failed rather than throwing when the sub-call errors", async () => {+ streamText.mockReturnValue({+ textStream: (async function* () {+ throw new Error("connect ECONNREFUSED 127.0.0.1:11434");+ })(),+ });+ const result = await execute(buildReviewResumeTool(ctx()), {});+ expect(result.status).toBe("generation_failed");+ expect(JSON.stringify(result)).not.toContain("ECONNREFUSED");+ expect(save).not.toHaveBeenCalled();+ });++ it("passes needs_selection straight through without generating", async () => {+ resolve.mockResolvedValue({+ status: "needs_selection",+ resumes: [{ id: "r1", title: "A" }, { id: "r2", title: "B" }],+ });+ const result = await execute(buildReviewResumeTool(ctx()), {});+ expect(result).toEqual({+ status: "needs_selection",+ resumes: [{ id: "r1", title: "A" }, { id: "r2", title: "B" }],+ });+ expect(streamText).not.toHaveBeenCalled();+ expect(save).not.toHaveBeenCalled();+ });++ it("returns no_resumes without generating", async () => {+ resolve.mockResolvedValue({ status: "no_resumes" });+ const result = await execute(buildReviewResumeTool(ctx()), {});+ expect(result).toEqual({ status: "no_resumes" });+ expect(streamText).not.toHaveBeenCalled();+ });++ it("returns unreadable when preprocessing fails", async () => {+ preprocess.mockResolvedValue({+ success: false,+ error: { code: "TOO_SHORT", message: "Resume is too short" },+ });+ const result = await execute(buildReviewResumeTool(ctx()), {});+ expect(result.status).toBe("unreadable");+ expect(result.title).toBe("Senior Engineer Resume");+ expect(streamText).not.toHaveBeenCalled();+ });+});diff --git a/src/lib/agent/prompt.ts b/src/lib/agent/prompt.tsindex 2506334..b402a0d 100644--- a/src/lib/agent/prompt.ts+++ b/src/lib/agent/prompt.ts@@ -27,6 +27,7 @@ export const AGENT_CHAT_SYSTEM_PROMPT = [export const AGENT_TOOL_DESCRIPTIONS = {add_job: "Add a job application to JobSync. Resolves or creates company, job title, location and source by name, and detects duplicates automatically. The user confirms the extracted details before anything is saved.",get_resume: "Read the contents of one of the user's own resumes in JobSync and return it as text. Optionally takes the resume's title; with no title the app uses the resume the user is currently viewing, or their default resume. Returns their resume titles instead if it cannot tell which one they mean.",+ review_resume: "Produce a full scored review of one of the user's own resumes in JobSync. The app generates the review itself, streams it to the user and saves it, then returns the scores and the review text to you. Optionally takes the resume's title; with no title the app uses the resume the user is currently viewing, or their default resume. Returns their resume titles instead if it cannot tell which one they mean.",} as const;export type AgentToolName = keyof typeof AGENT_TOOL_DESCRIPTIONS;diff --git a/src/lib/agent/tools/reviewResume.ts b/src/lib/agent/tools/reviewResume.tsnew file mode 100644index 0000000..1e84f67--- /dev/null+++ b/src/lib/agent/tools/reviewResume.ts@@ -0,0 +1,137 @@+import "server-only";++import { streamText, tool, type LanguageModel, type UIMessageStreamWriter } from "ai";+import { TEMPERATURES } from "@/lib/ai/config";+import { APP_CONSTANTS } from "@/lib/constants";+import { AGENT_TOOL_DESCRIPTIONS } from "@/lib/agent/prompt";+import { AgentReviewResumeSchema } from "@/models/agent.schema";+import { resolveResumeForAgent } from "@/lib/agent/resumeLookup";+import { preprocessResume } from "@/lib/ai/tools/preprocessing";+import {+ RESUME_REVIEW_SYSTEM_PROMPT,+ buildResumeReviewPrompt,+} from "@/lib/ai/prompts/resume-review";+import { parseResumeReview } from "@/lib/ai/resumeReview/parse";+import { saveResumeReviewResult } from "@/actions/profile.actions";+import { AGENT_REVIEW_PART_TYPE } from "@/models/agent.model";+import type { AgentReviewResumeResult } from "@/models/agent.model";+import type { ResumeReviewData } from "@/models/ai.schemas";++type ReviewResumeContext = {+ userId: string;+ pageResumeId?: string;+ model: LanguageModel;+ provider: string;+ modelName: string;+ writer: UIMessageStreamWriter;+};++/**+ * A second generation surface wearing a tool's clothes. execute makes its own+ * streamText call with the dedicated review route's exact inputs, so parity is+ * true by construction rather than by two prompts agreeing. userId and+ * pageResumeId are closure parameters — the same IDOR boundary as the other+ * tools, and it has a dedicated test.+ */+export function buildReviewResumeTool(ctx: ReviewResumeContext) {+ return tool({+ description: AGENT_TOOL_DESCRIPTIONS.review_resume,+ inputSchema: AgentReviewResumeSchema,+ // No needsApproval: this writes only the caller's own reviewData, and+ // they watch the whole thing stream before it lands.+ execute: async (raw, { toolCallId, abortSignal }): Promise<AgentReviewResumeResult> => {+ const lookup = await resolveResumeForAgent(ctx.userId, {+ title: raw?.resumeTitle,+ pageResumeId: ctx.pageResumeId,+ });++ if (lookup.status === "no_resumes") return { status: "no_resumes" };+ if (lookup.status === "needs_selection") {+ return { status: "needs_selection", resumes: lookup.resumes };+ }++ const title = lookup.resume.title;+ const pre = await preprocessResume(lookup.resume);+ if (!pre.success) {+ return {+ status: "unreadable",+ title,+ reason: "It may be too short or missing content. Check it in Profile → Resumes.",+ };+ }++ // Own deadline, plus the outer turn's signal so closing the panel+ // aborts this too.+ const signals: AbortSignal[] = [+ AbortSignal.timeout(APP_CONSTANTS.AI_RESUME_REVIEW_TIMEOUT_MS),+ ];+ if (abortSignal) signals.push(abortSignal);++ let generated = "";+ try {+ const sub = streamText({+ model: ctx.model,+ system: RESUME_REVIEW_SYSTEM_PROMPT,+ prompt: buildResumeReviewPrompt(pre.data.normalizedText),+ temperature: TEMPERATURES.FEEDBACK,+ abortSignal: AbortSignal.any(signals),+ providerOptions: {+ ollama: { options: { num_ctx: APP_CONSTANTS.AI_OLLAMA_NUM_CTX } },+ },+ });++ for await (const delta of sub.textStream) {+ generated += delta;+ ctx.writer.write({+ type: AGENT_REVIEW_PART_TYPE,+ id: toolCallId,+ data: { delta },+ transient: true,+ });+ }+ } catch (error) {+ console.error("[agent-chat] review_resume generation failed:", error);+ return {+ status: "generation_failed",+ title,+ reason: "The review could not be generated. Try again in a moment.",+ };+ }++ const { scores, body } = parseResumeReview(generated);+ // reviewData is overwrite-only with no history, so an unscored or+ // half-finished generation must not be written.+ if (!scores) {+ return {+ status: "generation_failed",+ title,+ reason: "The review came back without a scores line, so nothing was saved.",+ };+ }++ const reviewData: ResumeReviewData = {+ ...scores,+ body,+ reviewedAt: new Date().toISOString(),+ provider: ctx.provider,+ model: ctx.modelName,+ surface: APP_CONSTANTS.AGENT_CHAT_REVIEW_SURFACE,+ };+ const saveResult = await saveResumeReviewResult(+ lookup.resume.id!,+ JSON.stringify(reviewData),+ );+ const saved = saveResult?.success === true;++ return {+ status: "ok",+ resumeId: lookup.resume.id!,+ title,+ scores,+ body,+ saved,+ saveError: saved ? undefined : (saveResult?.message ?? "The review could not be saved."),+ };+ },+ });+}diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex fd8e4ef..6ce7a8a 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -125,6 +125,8 @@ export const APP_CONSTANTS = {// Agent chat (in-app tool-calling panel)AGENT_CHAT_CREATED_VIA: "chat",+ // Provenance on Resume.reviewData, alongside the MCP path's "mcp" marker.+ AGENT_CHAT_REVIEW_SURFACE: "chat",AGENT_CHAT_MAX_STEPS: 4,AGENT_CHAT_MAX_STORED_MESSAGES: 50,AGENT_CHAT_HISTORY_MESSAGES: 20,diff --git a/src/models/agent.model.ts b/src/models/agent.model.tsindex ae8f725..5035120 100644--- a/src/models/agent.model.ts+++ b/src/models/agent.model.ts@@ -1,4 +1,5 @@import type { DescriptionCompleteness } from "@/models/job.model";+import type { ResumeScores } from "@/models/ai.schemas";// Dependency-free by design: client components import these types, so nothing// here may pull in Prisma or server-only code. Type-only imports are erased.@@ -78,5 +79,30 @@ export type AgentGetResumeResult =| { status: "no_resumes" }| { status: "unreadable"; title: string; reason: string };-export const AGENT_CHAT_TOOL_NAMES = ["add_job", "get_resume"] as const;+// Transient stream part carrying the nested review generation's tokens. It is+// never persisted: the finished review lands in the tool result, and keeping+// both would duplicate it in storage and in model context.+export const AGENT_REVIEW_PART_TYPE = "data-review";++export type AgentReviewStreamData = { delta: string };++// What review_resume returns to the model AND to the result card. The resume+// text is deliberately absent — follow-ups answer from `body`, not from the+// serialization.+export type AgentReviewResumeResult =+ | {+ status: "ok";+ resumeId: string;+ title: string;+ scores: ResumeScores;+ body: string;+ saved: boolean;+ saveError?: string;+ }+ | { status: "needs_selection"; resumes: { id: string; title: string }[] }+ | { status: "no_resumes" }+ | { status: "unreadable"; title: string; reason: string }+ | { status: "generation_failed"; title: string; reason: string };++export const AGENT_CHAT_TOOL_NAMES = ["add_job", "get_resume", "review_resume"] as const;export type AgentChatToolName = (typeof AGENT_CHAT_TOOL_NAMES)[number];diff --git a/src/models/agent.schema.ts b/src/models/agent.schema.tsindex 79838ad..9c60f2a 100644--- a/src/models/agent.schema.ts+++ b/src/models/agent.schema.ts@@ -47,3 +47,12 @@ export const AgentGetResumeSchema = z.object({});export type AgentGetResumeInput = z.infer<typeof AgentGetResumeSchema>;++// Same one-optional-field shape as AgentGetResumeSchema, and never an id: the+// model names a resume the way the user did, and the server resolves it+// ownership-scoped.+export const AgentReviewResumeSchema = z.object({+ resumeTitle: z.string().optional().describe("The title of the resume to review, as the user referred to it. Omit this entirely if the user did not name one — the app then uses the resume they are currently viewing, or their default resume."),+});++export type AgentReviewResumeInput = z.infer<typeof AgentReviewResumeSchema>;diff --git a/src/models/ai.schemas.ts b/src/models/ai.schemas.tsindex 4442cd4..7667b5e 100644--- a/src/models/ai.schemas.ts+++ b/src/models/ai.schemas.ts@@ -20,6 +20,9 @@ export type ResumeReviewData = ResumeScores & {reviewedAt?: string;provider?: string;model?: string;+ // Which surface produced it. Optional: rows written before this existed+ // simply do not have it, and ReviewDetails ignores it.+ surface?: string;};// JOB MATCH TYPES