Skip to content

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.

feat: Enhance job scoring and automation management with new features and improvements

Khuram Niaz87827e08a1fd
diff --git a/__tests__/greenhouse-rank.spec.ts b/__tests__/greenhouse-rank.spec.ts
index 2d4911e..f178e01 100644
--- a/__tests__/greenhouse-rank.spec.ts
+++ b/__tests__/greenhouse-rank.spec.ts
@@ -1,4 +1,9 @@
-import { scoreJob, passesFloor, locationMatches } from "@/lib/scraper/greenhouse/rank";
+import {
+ scoreJob,
+ passesFloor,
+ locationMatches,
+ buildIdf,
+} from "@/lib/scraper/greenhouse/rank";
import type { JobDetails } from "@/lib/scraper/types";
function job(overrides: Partial<JobDetails>): JobDetails {
@@ -13,8 +18,9 @@ function job(overrides: Partial<JobDetails>): JobDetails {
}
describe("locationMatches", () => {
- it("always passes for remote regardless of preference", () => {
- expect(locationMatches("Remote - Americas", ["Canada"])).toBe(true);
+ it("remote only matches when explicitly listed as a wanted location", () => {
+ expect(locationMatches("Remote - Americas", ["remote"])).toBe(true);
+ expect(locationMatches("Remote - Americas", ["Canada"])).toBe(false);
expect(locationMatches("Fully remote", [])).toBe(true);
});
@@ -82,7 +88,7 @@ describe("scoreJob", () => {
expect(passesFloor(real.components)).toBe(true);
});
- it("location soft-weight raises a matching job above an otherwise-equal one", () => {
+ it("location does not affect the relevance score (gate-only signal)", () => {
const inLoc = scoreJob(
job({ title: "Frontend Engineer", location: "Toronto, Canada" }),
["Frontend Engineer"],
@@ -97,7 +103,10 @@ describe("scoreJob", () => {
[],
["Canada"],
);
- expect(inLoc.score).toBeGreaterThan(outLoc.score);
+ expect(inLoc.score).toBe(outLoc.score);
+ // locScore is still recorded for the breakdown UI.
+ expect(inLoc.components.locScore).toBe(1);
+ expect(outLoc.components.locScore).toBe(0);
});
it("empty locations contributes 0 location weight", () => {
@@ -135,6 +144,48 @@ describe("scoreJob", () => {
});
});
+describe("buildIdf (term rarity weighting)", () => {
+ it("scores a rare-term match above a generic-term match", () => {
+ const corpus = [
+ job({ title: "Software Engineer", description: "engineer" }),
+ job({ title: "Senior Engineer", description: "engineer" }),
+ job({ title: "Staff Engineer", description: "engineer" }),
+ job({ title: "Platform Engineer", description: "kubernetes" }),
+ ];
+ const idf = buildIdf(corpus);
+ expect(idf("engineer")).toBeLessThan(idf("kubernetes"));
+
+ const generic = scoreJob(
+ job({ description: "engineer" }),
+ [],
+ ["engineer", "kubernetes"],
+ [],
+ [],
+ idf,
+ );
+ const rare = scoreJob(
+ job({ description: "kubernetes" }),
+ [],
+ ["engineer", "kubernetes"],
+ [],
+ [],
+ idf,
+ );
+ expect(rare.score).toBeGreaterThan(generic.score);
+ });
+
+ it("default idf (no corpus) preserves count-based behavior", () => {
+ const { components } = scoreJob(
+ job({ title: "Frontend Engineer" }),
+ ["Frontend Engineer"],
+ [],
+ [],
+ [],
+ );
+ expect(components.titleScore).toBe(1); // min(1, 2 hits / 2)
+ });
+});
+
describe("passesFloor", () => {
const base = { titleScore: 0, keywordScore: 0, locScore: 0 };
diff --git a/src/actions/automation.actions.ts b/src/actions/automation.actions.ts
index 52e5c3f..35b604e 100644
--- a/src/actions/automation.actions.ts
+++ b/src/actions/automation.actions.ts
@@ -540,6 +540,38 @@ export async function dismissDiscoveredJob(id: string): Promise<{
}
}
+// Bulk-deletes discovered jobs for one automation. Always keeps accepted jobs
+// (they're tracked) and deletes dismissed ones; includeNew also clears the
+// unreviewed "new" pile.
+export async function clearDiscoveredJobs(options: {
+ automationId: string;
+ includeNew?: boolean;
+}): Promise<{ success: boolean; deleted?: number; message?: string }> {
+ try {
+ const user = await getCurrentUser();
+ if (!user) {
+ return { success: false, message: "Not authenticated" };
+ }
+
+ const { automationId, includeNew = false } = options;
+ const statuses: DiscoveryStatus[] = includeNew
+ ? ["dismissed", "new"]
+ : ["dismissed"];
+
+ const result = await db.job.deleteMany({
+ where: {
+ userId: user.id,
+ automationId,
+ discoveryStatus: { in: statuses },
+ },
+ });
+
+ return { success: true, deleted: result.count };
+ } catch (error) {
+ return formatError(error, "Failed to clear discovered jobs");
+ }
+}
+
export async function acceptDiscoveredJob(id: string): Promise<{
success: boolean;
data?: DiscoveredJob;
diff --git a/src/app/api/automations/[id]/run/route.ts b/src/app/api/automations/[id]/run/route.ts
index 1747cf8..03dcbdc 100644
--- a/src/app/api/automations/[id]/run/route.ts
+++ b/src/app/api/automations/[id]/run/route.ts
@@ -67,23 +67,26 @@ export async function POST(
);
}
- const result: RunnerResult = await runAutomation({
- id: automation.id,
- userId: automation.userId,
- name: automation.name,
- jobBoard: automation.jobBoard as JobBoard,
- keywords: automation.keywords,
- location: automation.location,
- sourceConfig: automation.sourceConfig,
- resumeId: automation.resumeId,
- matchThreshold: automation.matchThreshold,
- scheduleHour: automation.scheduleHour,
- nextRunAt: automation.nextRunAt,
- lastRunAt: automation.lastRunAt,
- status: automation.status as "active" | "paused",
- createdAt: automation.createdAt,
- updatedAt: automation.updatedAt,
- });
+ const result: RunnerResult = await runAutomation(
+ {
+ id: automation.id,
+ userId: automation.userId,
+ name: automation.name,
+ jobBoard: automation.jobBoard as JobBoard,
+ keywords: automation.keywords,
+ location: automation.location,
+ sourceConfig: automation.sourceConfig,
+ resumeId: automation.resumeId,
+ matchThreshold: automation.matchThreshold,
+ scheduleHour: automation.scheduleHour,
+ nextRunAt: automation.nextRunAt,
+ lastRunAt: automation.lastRunAt,
+ status: automation.status as "active" | "paused",
+ createdAt: automation.createdAt,
+ updatedAt: automation.updatedAt,
+ },
+ req.signal,
+ );
return NextResponse.json({
success: true,
diff --git a/src/app/dashboard/automations/[id]/page.tsx b/src/app/dashboard/automations/[id]/page.tsx
index a8487c5..92df032 100644
--- a/src/app/dashboard/automations/[id]/page.tsx
+++ b/src/app/dashboard/automations/[id]/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { format } from "date-fns";
@@ -25,6 +25,7 @@ import {
FileText,
AlertTriangle,
PlayCircle,
+ Square,
} from "lucide-react";
import {
getAutomationById,
@@ -64,6 +65,7 @@ export default function AutomationDetailPage() {
useState<JobMatchData | null>(null);
const [detailOpen, setDetailOpen] = useState(false);
const [runKey, setRunKey] = useState(0);
+ const abortControllerRef = useRef<AbortController | null>(null);
const loadData = useCallback(async () => {
setLoading(true);
@@ -154,18 +156,26 @@ export default function AutomationDetailPage() {
const handleRunNow = async () => {
if (!automation) return;
+ const controller = new AbortController();
+ abortControllerRef.current = controller;
+
setRunNowLoading(true);
setRunKey((prev) => prev + 1);
try {
const response = await fetch(`/api/automations/${automation.id}/run`, {
method: "POST",
+ signal: controller.signal,
});
const data = await response.json();
if (response.ok && data.success) {
+ const statusMsg =
+ data.run.status === "cancelled"
+ ? "Run cancelled"
+ : "Automation run complete";
toast({
- title: "Automation run started",
+ title: statusMsg,
description: `Saved ${data.run.jobsSaved} new jobs`,
});
loadData();
@@ -177,13 +187,24 @@ export default function AutomationDetailPage() {
});
}
} catch (error) {
- toast({
- title: "Error",
- description: "Failed to run automation",
- variant: "destructive",
- });
+ if (error instanceof Error && error.name === "AbortError") {
+ toast({ title: "Run aborted" });
+ } else {
+ toast({
+ title: "Error",
+ description: "Failed to run automation",
+ variant: "destructive",
+ });
+ }
+ } finally {
+ abortControllerRef.current = null;
+ setRunNowLoading(false);
+ loadData();
}
- setRunNowLoading(false);
+ };
+
+ const handleAbortRun = () => {
+ abortControllerRef.current?.abort();
};
const handleViewJobDetails = async (job: DiscoveredJob) => {
@@ -248,20 +269,21 @@ export default function AutomationDetailPage() {
)}
{automation.status === "active" ? "Pause" : "Resume"}
</Button>
- <Button
- variant="outline"
- onClick={handleRunNow}
- disabled={
- runNowLoading || resumeMissing || automation.status === "paused"
- }
- >
- {runNowLoading ? (
- <Loader2 className="h-4 w-4 mr-2 animate-spin" />
- ) : (
+ {runNowLoading ? (
+ <Button variant="destructive" onClick={handleAbortRun}>
+ <Square className="h-4 w-4 mr-2" />
+ Abort Run
+ </Button>
+ ) : (
+ <Button
+ variant="outline"
+ onClick={handleRunNow}
+ disabled={resumeMissing || automation.status === "paused"}
+ >
<PlayCircle className="h-4 w-4 mr-2" />
- )}
- Run Now
- </Button>
+ Run Now
+ </Button>
+ )}
</div>
</div>
@@ -358,6 +380,7 @@ export default function AutomationDetailPage() {
<TabsContent value="jobs" className="mt-4">
<DiscoveredJobsList
jobs={jobs}
+ automationId={automationId}
onRefresh={loadData}
onViewDetails={handleViewJobDetails}
/>
diff --git a/src/components/automations/DiscoveredJobDetail.tsx b/src/components/automations/DiscoveredJobDetail.tsx
index a6b3037..f479828 100644
--- a/src/components/automations/DiscoveredJobDetail.tsx
+++ b/src/components/automations/DiscoveredJobDetail.tsx
@@ -30,6 +30,7 @@ import {
analyzeDiscoveredJob,
} from "@/actions/automation.actions";
import { MatchDetails } from "./MatchDetails";
+import { PrerankBreakdown } from "./PrerankBreakdown";
import { TipTapContentViewer } from "@/components/TipTapContentViewer";
interface DiscoveredJobDetailProps {
@@ -179,6 +180,13 @@ export function DiscoveredJobDetail({
)}
</div>
+ {matchData?.prerankScore != null && (
+ <PrerankBreakdown
+ prerankScore={matchData.prerankScore}
+ components={matchData.prerankComponents}
+ />
+ )}
+
<div>
<h4 className="font-medium mb-2">Description</h4>
<div className="text-sm text-muted-foreground">
diff --git a/src/components/automations/DiscoveredJobsList.tsx b/src/components/automations/DiscoveredJobsList.tsx
index 4d0b801..ecf3512 100644
--- a/src/components/automations/DiscoveredJobsList.tsx
+++ b/src/components/automations/DiscoveredJobsList.tsx
@@ -20,6 +20,17 @@ import {
TableRow,
} from "@/components/ui/table";
import { toast } from "@/components/ui/use-toast";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { buttonVariants } from "@/components/ui/button";
import {
Check,
X,
@@ -29,12 +40,14 @@ import {
MapPin,
Loader2,
Sparkles,
+ Trash2,
} from "lucide-react";
import type { DiscoveredJob } from "@/models/automation.model";
import {
acceptDiscoveredJob,
dismissDiscoveredJob,
analyzeDiscoveredJob,
+ clearDiscoveredJobs,
} from "@/actions/automation.actions";
// A job is "un-analyzed" only when matchData explicitly marks it so (Greenhouse
@@ -48,18 +61,39 @@ function isAnalyzed(job: DiscoveredJob): boolean {
}
}
+// Lexical pre-rank as a percentage (weights sum to ~1, so raw × 100). Only
+// Greenhouse jobs carry it; null for JSearch/legacy jobs.
+function getPrerankPercent(job: DiscoveredJob): number | null {
+ try {
+ const raw = JSON.parse(job.matchData ?? "{}").prerankScore;
+ return typeof raw === "number" ? Math.round(raw * 100) : null;
+ } catch {
+ return null;
+ }
+}
+
interface DiscoveredJobsListProps {
jobs: DiscoveredJob[];
+ automationId: string;
onRefresh: () => void;
onViewDetails?: (job: DiscoveredJob) => void;
}
export function DiscoveredJobsList({
jobs,
+ automationId,
onRefresh,
onViewDetails,
}: DiscoveredJobsListProps) {
const [loadingAction, setLoadingAction] = useState<string | null>(null);
+ const [clearOpen, setClearOpen] = useState(false);
+ const [clearIncludeNew, setClearIncludeNew] = useState(false);
+ const [clearing, setClearing] = useState(false);
+
+ const dismissedCount = jobs.filter(
+ (j) => j.discoveryStatus === "dismissed",
+ ).length;
+ const newCount = jobs.filter((j) => j.discoveryStatus === "new").length;
// Analyzed-first, then by matchScore desc (un-analyzed sort by their lexical
// matchScore value). The analyzed flag lives in matchData JSON, so sort in JS.
@@ -137,6 +171,30 @@ export function DiscoveredJobsList({
}
};
+ const handleClear = async () => {
+ setClearing(true);
+ const result = await clearDiscoveredJobs({
+ automationId,
+ includeNew: clearIncludeNew,
+ });
+ setClearing(false);
+ setClearOpen(false);
+
+ if (result.success) {
+ toast({
+ title: "Discovered jobs cleared",
+ description: `Removed ${result.deleted ?? 0} job(s).`,
+ });
+ onRefresh();
+ } else {
+ toast({
+ title: "Error",
+ description: result.message,
+ variant: "destructive",
+ });
+ }
+ };
+
const getScoreBadgeVariant = (score: number) => {
if (score >= 80) return "default";
if (score >= 65) return "secondary";
@@ -160,10 +218,27 @@ export function DiscoveredJobsList({
return (
<Card>
<CardHeader>
- <CardTitle>Discovered Jobs</CardTitle>
- <CardDescription>
- Jobs found by your automations that match your criteria
- </CardDescription>
+ <div className="flex items-start justify-between gap-4">
+ <div className="space-y-1.5">
+ <CardTitle>Discovered Jobs</CardTitle>
+ <CardDescription>
+ Jobs found by your automations that match your criteria
+ </CardDescription>
+ </div>
+ {dismissedCount + newCount > 0 && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setClearIncludeNew(false);
+ setClearOpen(true);
+ }}
+ >
+ <Trash2 className="h-4 w-4 mr-1.5" />
+ Clear
+ </Button>
+ )}
+ </div>
</CardHeader>
<CardContent>
<Table>
@@ -172,6 +247,7 @@ export function DiscoveredJobsList({
<TableHead>Job</TableHead>
<TableHead>Company</TableHead>
<TableHead>Location</TableHead>
+ <TableHead className="text-center">Pre-rank</TableHead>
<TableHead className="text-center">Match</TableHead>
<TableHead>Status</TableHead>
<TableHead>Discovered</TableHead>
@@ -182,6 +258,7 @@ export function DiscoveredJobsList({
{sortedJobs.map((job) => {
const isLoading = loadingAction === job.id;
const analyzed = isAnalyzed(job);
+ const prerankPercent = getPrerankPercent(job);
return (
<TableRow key={job.id}>
@@ -217,6 +294,18 @@ export function DiscoveredJobsList({
{job.Location?.label || "N/A"}
</div>
</TableCell>
+ <TableCell className="text-center">
+ {prerankPercent != null ? (
+ <span
+ className="font-mono text-sm text-muted-foreground"
+ title="Internal lexical relevance score (not an AI match)"
+ >
+ {prerankPercent}%
+ </span>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </TableCell>
<TableCell className="text-center">
{analyzed ? (
<Badge variant={getScoreBadgeVariant(job.matchScore)}>
@@ -292,6 +381,50 @@ export function DiscoveredJobsList({
</TableBody>
</Table>
</CardContent>
+
+ <AlertDialog open={clearOpen} onOpenChange={setClearOpen}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Clear discovered jobs?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Accepted jobs are always kept. This permanently deletes{" "}
+ {dismissedCount} dismissed job(s)
+ {clearIncludeNew && newCount > 0
+ ? ` and ${newCount} unreviewed new job(s)`
+ : ""}
+ . This action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {newCount > 0 && (
+ <label className="flex items-center gap-2 text-sm">
+ <input
+ type="checkbox"
+ className="h-4 w-4"
+ checked={clearIncludeNew}
+ onChange={(e) => setClearIncludeNew(e.target.checked)}
+ />
+ Also delete {newCount} unreviewed new job(s)
+ </label>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={clearing}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ className={buttonVariants({ variant: "destructive" })}
+ disabled={clearing}
+ onClick={(e) => {
+ e.preventDefault();
+ handleClear();
+ }}
+ >
+ {clearing ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ "Delete"
+ )}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</Card>
);
}
diff --git a/src/components/automations/GreenhouseSearchStep.tsx b/src/components/automations/GreenhouseSearchStep.tsx
index d9766c0..f3f89a7 100644
--- a/src/components/automations/GreenhouseSearchStep.tsx
+++ b/src/components/automations/GreenhouseSearchStep.tsx
@@ -1,7 +1,14 @@
"use client";
import { useState, useTransition } from "react";
-import { X, Loader2, Plus, ChevronsUpDown, CirclePlus } from "lucide-react";
+import {
+ X,
+ Loader2,
+ Plus,
+ ChevronsUpDown,
+ CirclePlus,
+ TriangleAlert,
+} from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
@@ -280,6 +287,12 @@ export function GreenhouseSearchStep({
const atLimit = companies.length >= APP_CONSTANTS.MAX_GREENHOUSE_COMPANIES;
+ // Without target titles or keywords there is no signal to rank jobs against,
+ // so the relevance floor drops everything and nothing is saved.
+ const noSignal =
+ (value.targetTitles?.length ?? 0) === 0 &&
+ (value.keywords?.length ?? 0) === 0;
+
return (
<div className="space-y-5">
<div className="space-y-2">
@@ -435,11 +448,22 @@ export function GreenhouseSearchStep({
}}
/>
+ {noSignal && (
+ <div className="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-400">
+ <TriangleAlert className="h-4 w-4 mt-0.5 shrink-0" />
+ <span>
+ Add at least one target title or keyword. Without them there is
+ nothing to rank jobs against, so this automation will save no
+ listings.
+ </span>
+ </div>
+ )}
+
<EntityStringChipInput
label="Locations"
placeholder="e.g., Canada, Remote"
noun="location"
- description="Optional. Always nudges ranking; gates results when the toggle below is on."
+ description="Optional. Used only to filter results when the toggle below is on (not part of ranking)."
values={value.locations ?? []}
onChange={(next) => onChange({ ...value, locations: next })}
loadOptions={async () => {
diff --git a/src/components/automations/PrerankBreakdown.tsx b/src/components/automations/PrerankBreakdown.tsx
new file mode 100644
index 0000000..2265c79
--- /dev/null
+++ b/src/components/automations/PrerankBreakdown.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import { Badge } from "@/components/ui/badge";
+import { APP_CONSTANTS } from "@/lib/constants";
+import type { PrerankComponents } from "@/models/ai.schemas";
+
+interface PrerankBreakdownProps {
+ prerankScore: number;
+ components?: PrerankComponents;
+}
+
+// Surfaces the internal lexical pre-rank score next to the LLM match so the
+// two can be compared for tuning. The lexical score is never an AI %.
+export function PrerankBreakdown({
+ prerankScore,
+ components,
+}: PrerankBreakdownProps) {
+ const rows = components
+ ? [
+ {
+ label: "Title",
+ weight: APP_CONSTANTS.GREENHOUSE_TITLE_WEIGHT,
+ score: components.titleScore,
+ hits: components.titleHits,
+ },
+ {
+ label: "Keywords",
+ weight: APP_CONSTANTS.GREENHOUSE_SKILL_WEIGHT,
+ score: components.keywordScore,
+ hits: components.keywordHits,
+ },
+ ]
+ : [];
+
+ return (
+ <div className="rounded-md border border-dashed p-3 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Lexical pre-rank</span>
+ <span className="font-mono text-sm">
+ {Math.round(prerankScore * 100)}%
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Internal relevance score used to pick which jobs get AI-analyzed. Each
+ hit is weighted by how rare the term is across the board. Not an AI match
+ — compare it against the % above to gauge pre-rank accuracy.
+ </p>
+ {rows.map((row) => (
+ <div key={row.label} className="text-xs">
+ <div className="flex items-center justify-between">
+ <span className="text-muted-foreground">
+ {row.label} <span className="opacity-60">(×{row.weight})</span>
+ </span>
+ <span className="font-mono">
+ {row.score.toFixed(2)} → +
+ {(row.score * row.weight * 100).toFixed(1)}%
+ </span>
+ </div>
+ {row.hits.length > 0 && (
+ <div className="mt-1 flex flex-wrap gap-1">
+ {row.hits.map((hit) => (
+ <Badge key={hit} variant="secondary" className="text-[10px]">
+ {hit}
+ </Badge>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+ {components && (
+ <div className="text-xs text-muted-foreground">
+ Location:{" "}
+ {components.locScore > 0 ? "matches (gate only)" : "not scored"}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/automations/RunHistoryList.tsx b/src/components/automations/RunHistoryList.tsx
index b7f6e3d..0f702e5 100644
--- a/src/components/automations/RunHistoryList.tsx
+++ b/src/components/automations/RunHistoryList.tsx
@@ -31,6 +31,7 @@ import {
Ban,
Timer,
History,
+ Square,
} from "lucide-react";
import { Fragment } from "react";
import type { AutomationRun, FunnelStage } from "@/models/automation.model";
@@ -56,6 +57,7 @@ const STATUS_CONFIG = {
completed_with_errors: { icon: AlertCircle, color: "text-amber-500", variant: "secondary" as const },
blocked: { icon: Ban, color: "text-red-500", variant: "destructive" as const },
rate_limited: { icon: Timer, color: "text-amber-500", variant: "secondary" as const },
+ cancelled: { icon: Square, color: "text-muted-foreground", variant: "secondary" as const },
};
export function RunHistoryList({ runs }: RunHistoryListProps) {
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 290039f..ce345b1 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -61,9 +61,8 @@ export const APP_CONSTANTS = {
GREENHOUSE_LISTING_CAP: 50, // safety ceiling applied after the relevance floor
GREENHOUSE_FLOOR_MIN_TITLE_HITS: 1,
GREENHOUSE_FLOOR_MIN_KEYWORD_HITS: 2,
- GREENHOUSE_TITLE_WEIGHT: 0.5,
- GREENHOUSE_SKILL_WEIGHT: 0.35,
- GREENHOUSE_LOC_WEIGHT: 0.15,
+ GREENHOUSE_TITLE_WEIGHT: 0.6,
+ GREENHOUSE_SKILL_WEIGHT: 0.4,
GREENHOUSE_FETCH_TIMEOUT_MS: 25_000, // per-board AbortController timeout
GREENHOUSE_FETCH_CONCURRENCY: 5,
diff --git a/src/lib/scraper/greenhouse/pipeline.ts b/src/lib/scraper/greenhouse/pipeline.ts
index c7c39f5..bd59263 100644
--- a/src/lib/scraper/greenhouse/pipeline.ts
+++ b/src/lib/scraper/greenhouse/pipeline.ts
@@ -1,7 +1,7 @@
import { APP_CONSTANTS } from "@/lib/constants";
import type { PrerankComponents } from "@/models/ai.schemas";
import type { JobDetails } from "../types";
-import { scoreJob, passesFloor, locationMatches } from "./rank";
+import { scoreJob, passesFloor, locationMatches, buildIdf } from "./rank";
export interface PipelineConfig {
targetTitles: string[];
@@ -34,13 +34,17 @@ export function runGreenhousePipeline(
fetchedJobs: JobDetails[],
config: PipelineConfig,
resumeSkills: string[],
- options?: { k?: number; cap?: number },
+ options?: { k?: number; cap?: number; corpus?: JobDetails[] },
): PipelineResult {
const k = options?.k ?? APP_CONSTANTS.MAX_JOBS_PER_RUN;
const cap = options?.cap ?? APP_CONSTANTS.GREENHOUSE_LISTING_CAP;
const deduped = fetchedJobs.length;
+ // Term-rarity weights are derived from the full fetched corpus (pre-dedup) so
+ // they stay stable on steady-state runs where few new jobs remain.
+ const idf = buildIdf(options?.corpus ?? fetchedJobs);
+
const gateActive = config.strictLocation && config.locations.length > 0;
const located = gateActive
? fetchedJobs.filter((job) =>
@@ -57,6 +61,7 @@ export function runGreenhousePipeline(
config.keywords,
resumeSkills,
config.locations,
+ idf,
);
return { job, score, components };
});
diff --git a/src/lib/scraper/greenhouse/rank.ts b/src/lib/scraper/greenhouse/rank.ts
index 6c4ffb5..95593af 100644
--- a/src/lib/scraper/greenhouse/rank.ts
+++ b/src/lib/scraper/greenhouse/rank.ts
@@ -34,10 +34,37 @@ function termInText(text: string, term: string): boolean {
return re.test(text);
}
-// "Remote" always passes. Empty preference = no constraint (gate passes all).
+// Run-local inverse document frequency. A term in most board jobs scores ~0
+// (generic, e.g. "engineer"); a rare term scores ~1 (distinctive, e.g.
+// "kubernetes"). Normalized to 0..1 against the corpus size so it slots into
+// the existing hit-count denominators. Memoized per term; phrases and single
+// tokens both resolve via termInText, matching how scoreJob counts hits.
+export function buildIdf(corpus: JobDetails[]): (term: string) => number {
+ const haystacks = corpus.map(
+ (job) => `${job.title} ${job.description}`.toLowerCase(),
+ );
+ const n = haystacks.length;
+ const denom = Math.log(n + 1);
+ const cache = new Map<string, number>();
+
+ return (term: string): number => {
+ if (n === 0 || denom === 0) return 1; // no corpus -> neutral (count behavior)
+ const key = term.trim().toLowerCase();
+ if (!key) return 0;
+ const cached = cache.get(key);
+ if (cached !== undefined) return cached;
+ let df = 0;
+ for (const h of haystacks) if (termInText(h, key)) df++;
+ const idf = Math.log((n + 1) / (df + 1)) / denom; // 0..1
+ cache.set(key, idf);
+ return idf;
+ };
+}
+
+// Empty preference = no constraint (gate passes all). "Remote" is not special:
+// it only matches when the user explicitly lists it as a wanted location.
export function locationMatches(jobLocation: string, wanted: string[]): boolean {
const loc = (jobLocation || "").toLowerCase();
- if (loc.includes("remote")) return true;
if (!wanted || wanted.length === 0) return true;
return wanted.some((w) => {
const ww = w.trim().toLowerCase();
@@ -63,6 +90,7 @@ export function scoreJob(
keywords: string[],
resumeSkills: string[],
locations: string[],
+ idf: (term: string) => number = () => 1,
): { score: number; components: PrerankComponents } {
const targetTokens = new Set<string>();
for (const title of targetTitles) {
@@ -81,8 +109,15 @@ export function scoreJob(
termInText(haystack, term),
);
- const titleScore = Math.min(1, titleHits.length / 2);
- const keywordScore = Math.min(1, keywordHits.length / 3);
+ // Each hit weighted by term rarity (idf); generic tokens contribute ~0.
+ const titleWeight = titleHits.reduce((sum, t) => sum + idf(t), 0);
+ const keywordWeight = keywordHits.reduce((sum, t) => sum + idf(t), 0);
+ const titleScore = Math.min(1, titleWeight / 2);
+ const keywordScore = Math.min(1, keywordWeight / 3);
+
+ // Location is not part of the relevance score (it says nothing about job fit);
+ // it only feeds the optional strict-location gate. Kept in components purely
+ // as an informational signal for the pre-rank breakdown UI.
const locScore =
locations.length === 0
? 0
@@ -93,7 +128,6 @@ export function scoreJob(
const score =
APP_CONSTANTS.GREENHOUSE_TITLE_WEIGHT * titleScore +
APP_CONSTANTS.GREENHOUSE_SKILL_WEIGHT * keywordScore +
- APP_CONSTANTS.GREENHOUSE_LOC_WEIGHT * locScore +
recencyTiebreak(job.postedDate);
return {
diff --git a/src/lib/scraper/runner.ts b/src/lib/scraper/runner.ts
index b8cfd49..04fd835 100644
--- a/src/lib/scraper/runner.ts
+++ b/src/lib/scraper/runner.ts
@@ -140,6 +140,7 @@ interface ResumeWithSections extends PrismaResume {
export async function runAutomation(
automation: Automation,
+ signal?: AbortSignal,
): Promise<RunnerResult> {
console.log(`[Automation ${automation.id}] Starting automation run`);
automationLogger.startRun(automation.id);
@@ -217,6 +218,7 @@ export async function runAutomation(
automation,
run.id,
resume as ResumeWithSections,
+ signal,
);
}
@@ -326,6 +328,11 @@ export async function runAutomation(
// JSearch returns full job details, no separate extraction needed
for (const job of jobsToProcess) {
+ if (signal?.aborted) {
+ automationLogger.log(automation.id, "warning", "Run aborted by user");
+ break;
+ }
+
automationLogger.log(
automation.id,
"info",
@@ -437,11 +444,13 @@ export async function runAutomation(
}
}
- const finalStatus: AutomationRunStatus = aiError
- ? "failed"
- : jobsProcessed < jobsToProcess.length
- ? "completed_with_errors"
- : "completed";
+ const finalStatus: AutomationRunStatus = signal?.aborted
+ ? "cancelled"
+ : aiError
+ ? "failed"
+ : jobsProcessed < jobsToProcess.length
+ ? "completed_with_errors"
+ : "completed";
automationLogger.log(
automation.id,
@@ -555,7 +564,6 @@ function extractResumeSkills(resume: ResumeWithSections): string[] {
const PRERANK_MAX =
APP_CONSTANTS.GREENHOUSE_TITLE_WEIGHT +
APP_CONSTANTS.GREENHOUSE_SKILL_WEIGHT +
- APP_CONSTANTS.GREENHOUSE_LOC_WEIGHT +
0.01;
function scalePrerank(raw: number): number {
@@ -592,6 +600,7 @@ async function runGreenhouseRun(
automation: Automation,
runId: string,
resume: ResumeWithSections,
+ signal?: AbortSignal,
): Promise<RunnerResult> {
const config = parseGreenhouseConfig(automation.sourceConfig);
@@ -657,8 +666,27 @@ async function runGreenhouseRun(
{ jobsDeduplicated },
);
+ if (jobsDeduplicated === 0) {
+ automationLogger.log(
+ automation.id,
+ "info",
+ "[Greenhouse] All fetched jobs already saved — nothing new to process",
+ );
+ automationLogger.endRun(automation.id);
+ return await finalizeRun(runId, {
+ status: "completed",
+ jobsSearched,
+ jobsDeduplicated: 0,
+ jobsProcessed: 0,
+ jobsMatched: 0,
+ jobsSaved: 0,
+ });
+ }
+
const resumeSkills = extractResumeSkills(resume);
- const pipeline = runGreenhousePipeline(dedupedJobs, config, resumeSkills);
+ const pipeline = runGreenhousePipeline(dedupedJobs, config, resumeSkills, {
+ corpus: jobs,
+ });
if (config.strictLocation && config.locations.length > 0) {
automationLogger.log(
@@ -756,6 +784,11 @@ async function runGreenhouseRun(
let analyzeIndex = 0;
for (const scored of pipeline.toAnalyze) {
+ if (signal?.aborted) {
+ automationLogger.log(automation.id, "warning", "[Greenhouse] Run aborted by user");
+ break;
+ }
+
analyzeIndex++;
const saveUnanalyzed = async () => {
try {
@@ -847,7 +880,7 @@ async function runGreenhouseRun(
automationLogger.endRun(automation.id);
return await finalizeRun(runId, {
- status: aiError ? "completed_with_errors" : "completed",
+ status: signal?.aborted ? "cancelled" : aiError ? "completed_with_errors" : "completed",
errorMessage: aiError || undefined,
funnelStats: buildFunnel(analyzed, highlighted),
jobsSearched,
diff --git a/src/models/automation.model.ts b/src/models/automation.model.ts
index 7420724..bae5cb6 100644
--- a/src/models/automation.model.ts
+++ b/src/models/automation.model.ts
@@ -7,7 +7,8 @@ export type AutomationRunStatus =
| "failed"
| "completed_with_errors"
| "blocked"
- | "rate_limited";
+ | "rate_limited"
+ | "cancelled";
export type DiscoveryStatus = "new" | "accepted" | "dismissed";
export type JobBoard = "jsearch" | "greenhouse";