Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 82x 43x 43x 82x 82x 1x 1x 1x 1x 1x 1x 137x 137x 50x 50x 50x 50x 50x 50x 87x 137x 9x 137x 137x 1x 1x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 1x 100x 100x 100x 100x 39x 39x 100x 99x 99x 100x 1x 1x 100x 100x 100x 100x 1x 1x 1x 1x 1x 1x 82x 82x 82x 82x 82x 82x 82x 82x 1x 769x 769x 769x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 279x 279x 279x 279x 279x 279x 279x 279x 279x 12x 12x 12x 48x 48x 1x 1x 1x 1x 1x 1x 1x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 111x 111x 176x 176x 176x 176x 175x 175x 176x 104x 176x 3x 3x 175x 175x 175x 111x 111x 37x 37x 37x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 72x 72x 1x 72x 72x 71x 72x 72x 1x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 37x 72x 72x 72x 72x 72x 1x 1x 72x 72x 72x 72x 72x 72x 71x 71x 72x 72x 72x 71x 72x 72x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 63x 63x 1x 72x 72x 72x 72x 72x 72x 31x 31x 31x 72x 37x 37x 72x 72x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 15x 15x 15x 1x 1x 1x 15x 15x 1x 1x 1x 9x 15x 17x 17x 1x 1x 1x 1x 1x 1x 1x 34x 34x 34x 34x 34x 34x 3x 3x 3x 3x 3x 3x 3x 3x 3x 34x 34x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 1x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 103x 103x 103x 4x 4x 103x 79x 79x 79x 79x 85x 85x 85x 85x 85x 85x 85x 7x 78x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 82x 85x 7x 7x 7x 7x 7x 7x 7x 7x 7x 85x 85x 85x 82x 82x 82x 85x 8x 8x 85x 85x 79x 79x 79x 79x 79x 79x 78x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 1x 1x 1x 78x 79x 79x 79x 79x 79x 7x 7x 7x 7x 7x 7x 79x 3x 3x 72x 72x 72x 72x 72x 79x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 24x 10x 34x 34x 34x 34x 34x 79x 79x 79x 34x 34x 72x 72x 72x 72x 72x 72x 72x 72x | import { AzureOpenAI, APIConnectionTimeoutError, APIUserAbortError } from "openai";
import type { ChatCompletionCreateParamsNonStreaming } from "openai/resources/chat/completions";
import type {
AnalyzeJobRequest,
EvidenceItem,
Fit,
FitEvidence,
JobAnalysisPayload,
JobAnalysisResponse,
} from "../models/job";
import { isJobAnalysisPayload } from "../models/job";
import type { Tier } from "../models/user";
import { resolveModelConfig } from "./modelConfig";
import { fingerprintForRequest, resolveScoringProfile } from "./profileFingerprint";
import {
SPONSORSHIP_LINE,
dealbreakerLinesFromPrompt,
preferenceLines,
profileToPromptText,
} from "../../../shared/types/profile";
import { applyPreferences } from "./applyPreferences";
/** Model output violated the schema even after the repair retry → HTTP 502. */
export class JobSchemaError extends Error {}
/**
* The model did not answer within its time budget. Raised inside the handler,
* so the handler can answer 504 and refund the charge; left to the host's
* 50 s function timeout, the worker is killed before either can happen.
*/
export class ModelTimeoutError extends Error {}
/** Per attempt: normal analyses take 4-14 s. The SDK retries a timed-out attempt once. */
export const MODEL_CALL_TIMEOUT_MS = 20_000;
/**
* Overall limit for all model calls of one analysis, kept under host.json's
* functionTimeout (50 s) so this code, not the host, ends a stalled call.
*/
export const MODEL_DEADLINE_MS = 42_000;
function asModelTimeout(err: unknown): unknown {
return err instanceof APIConnectionTimeoutError || err instanceof APIUserAbortError
? new ModelTimeoutError("The model did not answer in time.")
: err;
}
/** Token counts for one completion call — never content (contracts/model-config.md). */
export interface ModelUsage {
deployment: string;
promptTokens: number;
completionTokens: number;
reasoningTokens: number;
cachedTokens: number;
latencyMs: number;
attempt: 1 | 2;
finishReason: string | null;
}
// One fit-list entry as the model returns it: the label plus the quotes behind
// it (research R9). The wire shape keeps plain label arrays; see splitEvidence.
const EVIDENCE_ITEM_SCHEMA = {
type: "object",
additionalProperties: false,
required: ["label", "postingQuote", "profileQuote"],
properties: {
label: { type: "string" },
postingQuote: { type: ["string", "null"] },
profileQuote: { type: ["string", "null"] },
},
} as const;
// Authoritative structured-output schema — specs/008-job-posting-analyzer/contracts/analyze-job.md
const JOB_ANALYSIS_SCHEMA = {
type: "object",
additionalProperties: false,
required: [
"isJobPosting",
"title",
"company",
"location",
"arrangement",
"arrangementConfidence",
"arrangementEvidence",
"alsoOffers",
"daysInOffice",
"daysRemote",
"remoteRestrictions",
"salary",
"seniority",
"techStack",
"fit",
],
properties: {
isJobPosting: { type: "boolean" },
title: { type: ["string", "null"] },
company: { type: ["string", "null"] },
location: { type: ["string", "null"] },
arrangement: { enum: ["remote", "hybrid", "onsite", "unspecified"] },
arrangementConfidence: { enum: ["explicit", "inferred", "none"] },
arrangementEvidence: {
type: ["string", "null"],
description:
"Verbatim quote from the posting; required when arrangement != unspecified",
},
alsoOffers: {
type: "array",
items: { enum: ["remote", "hybrid", "onsite"] },
maxItems: 2,
description:
"Other arrangements the posting also offers besides `arrangement`; empty when it offers only one",
},
daysInOffice: { type: ["integer", "null"], minimum: 0, maximum: 7 },
daysRemote: { type: ["integer", "null"], minimum: 0, maximum: 7 },
remoteRestrictions: { type: ["string", "null"] },
salary: {
type: ["object", "null"],
additionalProperties: false,
required: ["min", "max", "currency", "period"],
properties: {
min: { type: ["number", "null"] },
max: { type: ["number", "null"] },
currency: { type: ["string", "null"] },
period: { enum: ["year", "month", "day", "hour", null] },
},
},
seniority: {
enum: [
"junior",
"mid",
"senior",
"staff",
"principal",
"manager",
"director",
"executive",
"unspecified",
],
},
techStack: { type: "array", items: { type: "string" }, maxItems: 25 },
fit: {
type: ["object", "null"],
additionalProperties: false,
required: [
"score",
"rationale",
"matching",
"missing",
"desired",
"strengths",
"weaknesses",
],
properties: {
score: { type: "integer", minimum: 0, maximum: 100 },
rationale: { type: "string", maxLength: 600 },
matching: { type: "array", items: EVIDENCE_ITEM_SCHEMA, maxItems: 8 },
missing: { type: "array", items: EVIDENCE_ITEM_SCHEMA, maxItems: 8 },
desired: { type: "array", items: EVIDENCE_ITEM_SCHEMA, maxItems: 10 },
strengths: { type: "array", items: { type: "string" }, maxItems: 5 },
weaknesses: { type: "array", items: { type: "string" }, maxItems: 5 },
},
},
},
} as const;
function buildSystemPrompt(hasProfile: boolean, assumeJobPosting: boolean): string {
const lines = [
"You are a precise job-posting analyzer. Extract structured facts from the page content.",
"Read the ENTIRE page content end to end — every section (overview, responsibilities, requirements, qualifications, nice-to-have, benefits) — before answering any field. Do not base an answer on only the first paragraph or the first section; a detail mentioned once, late in the posting, is as valid as one mentioned in the opening line.",
"Rules:",
"- JSON-LD and microdata JobPosting values are trusted ground truth for title, company, location, and salary unless the body text contradicts them; when the body contradicts structured data, follow the body. Where JSON-LD and microdata disagree with each other, prefer JSON-LD.",
"- NEVER invent a work arrangement or day counts. If the posting does not state or clearly imply the arrangement, answer arrangement=\"unspecified\" with arrangementConfidence=\"none\" and arrangementEvidence=null.",
"- arrangementEvidence MUST be a verbatim substring of the provided content — copy it exactly, never paraphrase.",
"- arrangementConfidence is \"explicit\" when the arrangement is stated outright, \"inferred\" when derived from indirect wording (inference still requires a verbatim evidence quote).",
"- A posting can offer more than one arrangement (a location list that includes \"Remote\", a line such as \"open to remote candidates\", a perks line about a hybrid office). Put the arrangement the posting presents for the role as `arrangement`, put every other arrangement it offers in `alsoOffers`, and use arrangementConfidence \"inferred\" when a location list or an \"open to\" sentence is the evidence. Postings with the same wording must get the same answer. alsoOffers is empty when only one arrangement is offered.",
"- JSON-LD jobLocationType \"TELECOMMUTE\" means arrangement=\"remote\" with confidence \"explicit\".",
"- daysInOffice/daysRemote: only for hybrid roles and only when stated or directly inferable, with the evidence quote covering them; otherwise null.",
"- remoteRestrictions: geographic or timezone limits on remote work (e.g. \"US only\"), else null.",
"- techStack: named programming languages, frameworks, libraries, databases, cloud platforms, and developer tools/infrastructure ONLY — e.g. \"Python\", \"Kubernetes\", \"PostgreSQL\", \"AWS\", \"React\". EXCLUDE generic business/process terms, methodologies, and soft skills even if the posting calls them out prominently (e.g. \"on-call\", \"incident response\", \"vendor management\", \"unit economics\", \"QA\", \"Agile\", \"stakeholder management\") — these are not technologies. Scan the entire posting, including team/stack overviews and nice-to-have lines, not just the main requirements section — a technology named once late in the posting counts. Each entry appears exactly once (no duplicates, no near-duplicate variants of the same name). Max 25 entries, most prominent/required first. If the posting names no concrete technologies, return an empty array — do not pad it with process or domain terms.",
"- isJobPosting: false when the content is not a job posting (news article, list page, etc.); still fill any fields you can.",
];
if (assumeJobPosting) {
lines.push(
"- The user has confirmed this page should be treated as a job posting: set isJobPosting=true and extract on a best-effort basis."
);
}
if (hasProfile) {
lines.push(
"Fit scoring (a candidate profile is provided):",
"- fit.score is 0-100 and measures only how well the posting matches the candidate's skills, experience and seniority; dealbreakers are judged separately and never change the score. Score against this rubric: 85-100: all required skills covered and seniority aligned; 65-84: minor gaps; 40-64: significant gaps or a level mismatch; 0-39: major mismatch. fit.rationale is two to three sentences summarizing the match, drawing on the posting as a whole (not just its opening paragraph).",
"- fit.matching: the required responsibilities and skills from the posting that the candidate's profile clearly covers (short phrases, most important first, at most 8).",
"- fit.missing: required responsibilities and skills from the posting that the profile shows no evidence of (at most 8).",
"- fit.desired: nice-to-have / preferred qualifications from the posting that the profile does not cover.",
"- fit.strengths: what makes this specific role a strong choice for this candidate (e.g. seniority alignment, domain overlap, growth direction).",
"- fit.weaknesses: risks or downsides of this role for this candidate (e.g. skill gaps to close, seniority mismatch, unstated arrangement, below-preference salary).",
"- Every item in fit.matching, fit.missing and fit.desired has a label, a postingQuote and a profileQuote. postingQuote is the shortest verbatim span of the posting that states the requirement; profileQuote is the shortest verbatim span of the candidate profile that covers it. Copy both exactly, never paraphrase. profileQuote is null for fit.missing and fit.desired items, and either quote is null when no span supports the item.",
"- A \"Confirmed skills:\" section in the profile lists skills the candidate states they have. Treat each line there as evidence: a requirement it covers goes in fit.matching, never fit.missing or fit.desired, with that line as its profileQuote, and the score reflects it.",
"- Base every item on the posting and profile text only; never invent skills or requirements.",
"- a fact the posting does not state is not a violation; list it as \"Unverified: …\" in fit.weaknesses instead. Use \"Unverified:\" only for a fact the posting leaves out that matters to the candidate's stated dealbreakers or preferences (salary, arrangement, office days, seniority, location); never for gaps in the candidate's profile (those belong in fit.missing or fit.weaknesses without the prefix), and never twice for the same fact."
);
} else {
lines.push("No candidate profile was provided: set fit to null.");
}
return lines.join("\n");
}
/**
* The profile text the fit call sees: no dealbreaker section, so dealbreakers
* cannot move the score (SC-002) and are judged by their own call (research R8
* fallback). The fingerprint still covers the full profile.
*/
function profileWithoutDealbreakers(req: AnalyzeJobRequest): string | undefined {
if (req.profileData) {
// Dealbreakers and preferences are judged elsewhere; confirmed skills are
// evidence about the candidate, so they stay with the résumé text.
const { text, confirmedSkills } = req.profileData;
if (!text) return undefined;
return profileToPromptText({ text, dealbreakers: [], confirmedSkills });
}
const full = resolveScoringProfile(req);
if (!full || dealbreakerLinesFromPrompt(full).length === 0) return full;
const at = full.lastIndexOf("\n\nDealbreakers:\n");
return at === -1 ? full : full.slice(0, at);
}
/**
* What the judge checks: the dealbreakers plus the preferences only the model
* can read (locations, sponsorship; research R11). They are numbered like any
* dealbreaker, so a violation maps back to the profile's own line.
*/
function dealbreakerLinesFor(req: AnalyzeJobRequest): string[] {
const dealbreakers =
req.profileData?.dealbreakers ?? dealbreakerLinesFromPrompt(req.profile ?? "");
const preferences = req.profileData?.preferences;
const judged = preferenceLines(preferences).filter(
(line) => line.startsWith("Locations or timezones:") || line === SPONSORSHIP_LINE
);
return [...dealbreakers, ...judged];
}
function buildUserMessage(req: AnalyzeJobRequest): string {
const parts: string[] = [];
const profile = profileWithoutDealbreakers(req);
if (profile) {
parts.push(`Candidate profile:\n${profile}`);
}
if (req.extract.jsonLd.length > 0) {
parts.push(`JSON-LD JobPosting data:\n${JSON.stringify(req.extract.jsonLd)}`);
}
for (const source of req.extract.structuredSources ?? []) {
parts.push(`Structured data (${source.kind}):\n${JSON.stringify(source.data)}`);
}
parts.push(`Page title: ${req.extract.title}`);
parts.push(`Page content:\n${req.extract.mainText}`);
return parts.join("\n\n");
}
/**
* The fit call's messages. The eval compares them with and without the
* profile's dealbreakers to show the score cannot depend on them (SC-002).
*/
export function fitCallMessages(req: AnalyzeJobRequest): { role: "system" | "user"; content: string }[] {
return [
{
role: "system",
content: buildSystemPrompt(Boolean(resolveScoringProfile(req)), Boolean(req.assumeJobPosting)),
},
{ role: "user", content: buildUserMessage(req) },
];
}
function normalizeWhitespace(text: string): string {
return text.replace(/\s+/g, " ").trim();
}
/** One fit-list entry as the model returns it (research R9). */
interface ModelFitItem {
label: string;
postingQuote: string | null;
profileQuote: string | null;
}
/** The model-facing shape: only `fit`'s three lists differ from the wire `JobAnalysisPayload`. */
type ModelFit = Omit<Fit, "matching" | "missing" | "desired" | "evidence"> & {
matching?: (ModelFitItem | string)[];
missing?: (ModelFitItem | string)[];
desired?: (ModelFitItem | string)[];
};
type ModelJobAnalysisPayload = Omit<JobAnalysisPayload, "fit"> & { fit: ModelFit | null };
const QUOTE_CAP = 200;
/**
* Anti-hallucination backstop for evidence quotes (research R9): a quote that
* is not a whitespace-normalized substring of its haystack becomes `null`, with
* one warning per drop. A valid quote is capped at 200 characters afterwards,
* because strict mode does not reliably enforce `maxLength`.
*/
function validateQuote(
quote: string | null | undefined,
haystack: string,
what: string,
warn: (message: string) => void
): string | null {
const normalized = normalizeWhitespace(quote ?? "");
if (normalized.length === 0) return null;
if (!haystack.includes(normalized)) {
warn(`${what} quote is not a substring of the input; dropping it`);
return null;
}
return normalized.slice(0, QUOTE_CAP);
}
/**
* Turns the model's `{label, postingQuote, profileQuote}` lists into the wire
* shape: plain label arrays (old clients render these forever, research R4)
* plus `fit.evidence` with validated quotes. An item with a blank label is
* dropped from both. `profileQuote` is always null for `missing` and `desired`.
*/
function splitEvidence(
modelFit: ModelFit,
postingText: string,
profileText: string,
warn: (message: string) => void
): Fit {
const evidence: FitEvidence = {};
const labels: Record<"matching" | "missing" | "desired", string[]> = {
matching: [],
missing: [],
desired: [],
};
for (const list of ["matching", "missing", "desired"] as const) {
const items: EvidenceItem[] = [];
for (const raw of modelFit[list] ?? []) {
const item: ModelFitItem =
typeof raw === "string" ? { label: raw, postingQuote: null, profileQuote: null } : raw;
const label = normalizeWhitespace(item.label ?? "");
if (label.length === 0) continue;
const postingQuote = validateQuote(item.postingQuote, postingText, `${list} "${label}" posting`, warn);
let profileQuote: string | null = null;
if (list === "matching") {
profileQuote = validateQuote(item.profileQuote, profileText, `${list} "${label}" profile`, warn);
} else if (normalizeWhitespace(item.profileQuote ?? "").length > 0) {
warn(`${list} "${label}" profile quote is not allowed on this list; dropping it`);
}
labels[list].push(label);
items.push({ label, postingQuote, profileQuote });
}
evidence[list] = items;
}
const { matching: _m, missing: _x, desired: _d, ...rest } = modelFit;
return { ...rest, ...labels, evidence };
}
/** Categories, not technologies (#31); the prompt asks for names only, this is the backstop. */
const GENERIC_TECH_WORDS = new Set([
"api",
"apis",
"cloud",
"database",
"databases",
"devops",
"pipeline",
"pipelines",
"queue",
"queues",
"storage",
]);
export function namedTechnologies(stack: string[]): string[] {
return stack.filter((entry) => !GENERIC_TECH_WORDS.has(entry.trim().toLowerCase()));
}
function otherArrangements(payload: ModelJobAnalysisPayload): JobAnalysisPayload["alsoOffers"] {
if (payload.arrangement === "unspecified") return [];
const seen = new Set<string>([payload.arrangement]);
return (payload.alsoOffers ?? []).filter((a) => !seen.has(a) && seen.add(a));
}
function toWirePayload(
rawPayload: ModelJobAnalysisPayload,
req: AnalyzeJobRequest,
warn: (message: string) => void
): JobAnalysisPayload {
const payload = {
...rawPayload,
techStack: namedTechnologies(rawPayload.techStack),
alsoOffers: otherArrangements(rawPayload),
};
if (!payload.fit) return { ...payload, fit: null };
const postingText = normalizeWhitespace(
`${JSON.stringify(req.extract.jsonLd)} ${JSON.stringify(req.extract.structuredSources ?? [])} ${req.extract.title} ${req.extract.mainText}`
);
const profileText = normalizeWhitespace(profileWithoutDealbreakers(req) ?? "");
return { ...payload, fit: splitEvidence(payload.fit, postingText, profileText, warn) };
}
/** Anti-hallucination backstop: evidence must be a substring of the model input. */
function validateEvidence(
payload: JobAnalysisPayload,
req: AnalyzeJobRequest,
warn: (message: string) => void
): JobAnalysisPayload {
if (payload.arrangement === "unspecified") return payload;
const haystack = normalizeWhitespace(
`${JSON.stringify(req.extract.jsonLd)} ${JSON.stringify(req.extract.structuredSources ?? [])} ${req.extract.title} ${req.extract.mainText}`
);
const evidence = payload.arrangementEvidence
? normalizeWhitespace(payload.arrangementEvidence)
: "";
if (evidence.length === 0 || !haystack.includes(evidence)) {
warn(
`arrangementEvidence is not a substring of the input; downgrading ${payload.arrangement} -> unspecified`
);
return {
...payload,
arrangement: "unspecified",
arrangementConfidence: "none",
arrangementEvidence: null,
daysInOffice: null,
daysRemote: null,
};
}
return payload;
}
function enforceConsistency(
payload: JobAnalysisPayload,
req: AnalyzeJobRequest
): JobAnalysisPayload {
const result = { ...payload };
if (result.arrangement !== "hybrid") {
result.daysInOffice = null;
result.daysRemote = null;
}
if (!resolveScoringProfile(req)) {
result.fit = null;
}
return result;
}
const DEALBREAKER_SCHEMA = {
type: "object",
additionalProperties: false,
required: ["checks"],
properties: {
checks: {
type: "array",
maxItems: 10,
items: {
type: "object",
additionalProperties: false,
// Quote before verdict, so the verdict is grounded in what was quoted.
required: ["number", "postingSays", "verdict"],
properties: {
number: { type: "integer" },
postingSays: { type: "string" },
verdict: { enum: ["violated", "compatible", "not stated"] },
},
},
},
},
} as const;
const DEALBREAKER_PROMPT = [
"Check a job posting against the candidate's numbered dealbreakers. Do not score fit.",
"Return one check per dealbreaker, in order: postingSays is the shortest VERBATIM substring of the posting that decides it (\"\" if none), then the verdict: violated (the posting states a fact contradicting it), compatible (it states a fact satisfying it), or not stated (silent, vague, or a guess). Silence is never a violation.",
"- Arrangement (\"Remote only\", \"No fully on-site roles\"): decided only by how the role or the company works (remote, hybrid, office days, on-site), including a company-wide work policy anywhere on the page. A conditional line (\"if the posting is specified as Onsite…\"), a home area, relocation, job location, travel or occasional meetups do not decide it. Mind negations: only a fully on-site role violates \"No fully on-site roles\"; hybrid or remote is compatible.",
"- Minimum salary: compare only pay in the same currency and period, violated only if every stated range tops out below it; otherwise not stated.",
"- Location or time zone (\"EU timezones only\"): violated if the role's own location or allowed candidate region is outside it (a US city, \"US only\"); compatible if inside it (UK, London, CET ±2h are European) or that region may apply (\"US and Europe\"). Site menus, search filters and office lists do not count.",
"- Work authorization (\"needs visa sponsorship\"): violated only if the posting states it cannot or will not sponsor visas, or requires existing work authorization or residency (\"US citizens only\", \"must be authorized to work without sponsorship\"); compatible if it offers sponsorship or relocation support; otherwise not stated.",
"- The job description text wins over JSON-LD and page headers.",
].join("\n");
function postingHaystack(req: AnalyzeJobRequest): string {
return normalizeWhitespace(
`${JSON.stringify(req.extract.jsonLd)} ${JSON.stringify(req.extract.structuredSources ?? [])} ${req.extract.title} ${req.extract.mainText}`
).toLowerCase();
}
/**
* The profile lines the judge's checks report as violated (research R8,
* FR-005). A check names its dealbreaker by number, so the reported line is
* the user's exact wording. A violation counts only with a verbatim posting
* quote. Never reads or writes `score`.
*/
export function violatedLines(
checks: { number?: number; postingSays?: string; verdict?: string }[],
lines: string[],
haystack: string,
warn: (message: string) => void
): string[] {
const violated: string[] = [];
for (const check of checks) {
if (check.verdict !== "violated") continue;
const line = Number.isInteger(check.number) ? lines[check.number! - 1] : undefined;
if (line === undefined) {
warn(`dealbreaker ${check.number} is not in the profile; dropping it`);
continue;
}
const quote = normalizeWhitespace(check.postingSays ?? "").toLowerCase();
if (quote.length === 0 || !haystack.includes(quote)) {
warn(`dealbreaker "${line}" has no verbatim posting quote; dropping it`);
continue;
}
if (!violated.includes(line)) violated.push(line);
}
return violated;
}
/**
* #27: the dealbreakers the judge could not check because the posting does not
* say. They become "Unverified" weaknesses, so the user knows the dealbreaker
* was not actually met. A line the fit call already called out is not repeated.
*/
export function unverifiedNotes(
checks: { number?: number; verdict?: string }[],
lines: string[],
existingWeaknesses: string[]
): string[] {
const notes: string[] = [];
for (const check of checks) {
if (check.verdict !== "not stated") continue;
const line = Number.isInteger(check.number) ? lines[check.number! - 1] : undefined;
if (line === undefined) continue;
const mentioned = existingWeaknesses.some(
(w) => /^unverified/i.test(w) && w.toLowerCase().includes(line.toLowerCase())
);
const note = `Unverified: ${line} — the posting doesn't say.`;
if (!mentioned && !notes.includes(note)) notes.push(note);
}
return notes;
}
/**
* Extensions from before PR2 send no `profileData` and ignore
* `dealbreakersViolated`, so the violation is named in the rationale they do
* render. The score is untouched (FR-005). Clients that send `profileData`
* show the banner instead.
*/
function withLegacyDealbreakerNote(rationale: string, violated: string[]): string {
if (violated.length === 0) return rationale;
const noun = violated.length === 1 ? "dealbreaker" : "dealbreakers";
return `${rationale} Violates your ${noun}: ${violated.join("; ")}.`;
}
export async function orchestrateJobAnalysis(
req: AnalyzeJobRequest,
tier: Tier = "free",
warn: (message: string) => void = () => {},
observe?: (usage: ModelUsage) => void
): Promise<JobAnalysisResponse> {
const endpoint = process.env.AZURE_OPENAI_ENDPOINT ?? "";
const apiKey = process.env.AZURE_OPENAI_API_KEY ?? "";
// Throws ModelConfigError before any model call (research R1).
const { deployment, apiVersion, temperature, reasoningEffort } = resolveModelConfig(
tier,
process.env
);
const client = new AzureOpenAI({
endpoint,
apiKey,
deployment,
apiVersion,
timeout: MODEL_CALL_TIMEOUT_MS,
maxRetries: 1,
});
const deadline = AbortSignal.timeout(MODEL_DEADLINE_MS);
const createCompletion = async (params: ChatCompletionCreateParamsNonStreaming) => {
try {
return await client.chat.completions.create(params, { signal: deadline });
} catch (err) {
throw asModelTimeout(err);
}
};
const messages = fitCallMessages(req);
const complete = async (
attempt: 1 | 2,
extraInstruction?: string
): Promise<ModelJobAnalysisPayload | null> => {
const startedAt = Date.now();
const completion = await createCompletion({
model: deployment,
messages: extraInstruction
? [...messages, { role: "system" as const, content: extraInstruction }]
: messages,
response_format: {
type: "json_schema",
json_schema: {
name: "job_analysis",
strict: true,
schema: JOB_ANALYSIS_SCHEMA as unknown as Record<string, unknown>,
},
},
// Each setting is sent only when configured, so a model that rejects
// one is a settings change, not a code change (FR-M04).
...(temperature !== undefined ? { temperature } : {}),
...(reasoningEffort !== undefined ? { reasoning_effort: reasoningEffort } : {}),
// Sized for the full fit breakdown (matching/missing/desired lists with
// their evidence quotes) on top of the extraction fields. max_completion_tokens (not max_tokens)
// — required by the gpt-5.x deployment generation, and accepted by
// gpt-4o-mini too.
max_completion_tokens: 3000,
});
observe?.({
deployment,
promptTokens: completion.usage?.prompt_tokens ?? 0,
completionTokens: completion.usage?.completion_tokens ?? 0,
reasoningTokens: completion.usage?.completion_tokens_details?.reasoning_tokens ?? 0,
cachedTokens: completion.usage?.prompt_tokens_details?.cached_tokens ?? 0,
latencyMs: Date.now() - startedAt,
attempt,
finishReason: completion.choices[0]?.finish_reason ?? null,
});
const content = completion.choices[0]?.message?.content;
if (!content) return null;
let parsed: unknown;
try {
parsed = JSON.parse(content);
} catch {
return null;
}
return isJobAnalysisPayload(parsed) ? (parsed as unknown as ModelJobAnalysisPayload) : null;
};
// Dealbreakers get their own call, run alongside the fit call (research R8
// fallback): the fit call never sees them, so they cannot move the score.
const lines = resolveScoringProfile(req) ? dealbreakerLinesFor(req) : [];
type Judged = { violated: string[]; unverified: { number?: number; verdict?: string }[] };
const judge = async (): Promise<Judged> => {
if (lines.length === 0) return { violated: [], unverified: [] };
try {
const startedAt = Date.now();
const completion = await createCompletion({
model: deployment,
messages: [
{ role: "system" as const, content: DEALBREAKER_PROMPT },
{
role: "user" as const,
content: `${buildUserMessage({ ...req, profile: undefined, profileData: undefined })}\n\nDealbreakers:\n${lines.map((l, i) => `${i + 1}. ${l}`).join("\n")}`,
},
],
response_format: {
type: "json_schema",
json_schema: {
name: "dealbreaker_check",
strict: true,
schema: DEALBREAKER_SCHEMA as unknown as Record<string, unknown>,
},
},
...(temperature !== undefined ? { temperature } : {}),
...(reasoningEffort !== undefined ? { reasoning_effort: reasoningEffort } : {}),
max_completion_tokens: 1000,
});
observe?.({
deployment,
promptTokens: completion.usage?.prompt_tokens ?? 0,
completionTokens: completion.usage?.completion_tokens ?? 0,
reasoningTokens: completion.usage?.completion_tokens_details?.reasoning_tokens ?? 0,
cachedTokens: completion.usage?.prompt_tokens_details?.cached_tokens ?? 0,
latencyMs: Date.now() - startedAt,
attempt: 1,
finishReason: completion.choices[0]?.finish_reason ?? null,
});
const parsed = JSON.parse(completion.choices[0]?.message?.content ?? "") as {
checks?: { number?: number; postingSays?: string; verdict?: string }[];
};
const checks = parsed.checks ?? [];
return {
violated: violatedLines(checks, lines, postingHaystack(req), warn),
unverified: checks.filter((c) => c.verdict === "not stated"),
};
} catch (error) {
warn(`dealbreaker check failed (${error instanceof Error ? error.message : "unknown"}); reporting none`);
return { violated: [], unverified: [] };
}
};
const firstAttempt = complete(1);
const judged = judge();
let modelPayload = await firstAttempt;
if (!modelPayload) {
warn("job analysis output failed to parse; retrying with repair instruction");
modelPayload = await complete(
2,
"Your previous reply was not valid JSON for the required schema. Respond again with ONLY a valid JSON object matching the schema exactly."
);
}
if (!modelPayload) {
throw new JobSchemaError("Model output did not match the job analysis schema.");
}
let payload = toWirePayload(modelPayload, req, warn);
payload = validateEvidence(payload, req, warn);
payload = enforceConsistency(payload, req);
const { violated, unverified } = await judged;
if (payload.fit) {
const unverifiedWeaknesses = unverifiedNotes(
unverified,
lines,
payload.fit.weaknesses ?? []
);
payload = {
...payload,
fit: {
...payload.fit,
rationale: req.profileData
? payload.fit.rationale
: withLegacyDealbreakerNote(payload.fit.rationale, violated),
dealbreakersViolated: violated,
weaknesses: [...(payload.fit.weaknesses ?? []), ...unverifiedWeaknesses],
},
};
}
payload = applyPreferences(payload, req.profileData?.preferences);
const profileFingerprint = fingerprintForRequest(req);
if (payload.fit && profileFingerprint) {
payload = { ...payload, fit: { ...payload.fit, profileFingerprint } };
}
return {
...payload,
model: deployment,
analyzedAt: new Date().toISOString(),
tier,
};
}
|