Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion skillgraph-web/app/(app)/market/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { Button } from "@/components/ui/button";

interface SkillItem { skill: string; count: number; change: number | null }
interface MarketData { topSkills: SkillItem[]; role: string; totalJobsAnalyzed: number; week: number; lastUpdated: string }
interface MarketData { topSkills: SkillItem[]; role: string; totalJobsAnalyzed: number; week: number | null; lastUpdated: string | null }

const roles = ['All Roles', 'Industrial AI Engineer', 'Data Analyst', 'ML Engineer', 'DevOps Engineer', 'Full Stack Dev'];
const tabs = ['Skill Demand', 'Live Job Search', 'Salary Explorer'];
Expand All @@ -28,15 +28,15 @@

// Tab 2: Job Search State
const [jobQuery, setJobQuery] = useState('');
const [jobs, setJobs] = useState<any[]>([]);

Check warning on line 31 in skillgraph-web/app/(app)/market/page.tsx

View workflow job for this annotation

GitHub Actions / Typecheck, lint & test (skillgraph-web)

Unexpected any. Specify a different type
const [searchingJobs, setSearchingJobs] = useState(false);
const [selectedJob, setSelectedJob] = useState<any>(null);

Check warning on line 33 in skillgraph-web/app/(app)/market/page.tsx

View workflow job for this annotation

GitHub Actions / Typecheck, lint & test (skillgraph-web)

Unexpected any. Specify a different type
const [jobDetailsLoading, setJobDetailsLoading] = useState(false);

// Tab 3: Salary State
const [salaryTitle, setSalaryTitle] = useState('');
const [salaryLocation, setSalaryLocation] = useState('India');
const [salaries, setSalaries] = useState<any[]>([]);

Check warning on line 39 in skillgraph-web/app/(app)/market/page.tsx

View workflow job for this annotation

GitHub Actions / Typecheck, lint & test (skillgraph-web)

Unexpected any. Specify a different type
const [searchingSalary, setSearchingSalary] = useState(false);
const [lookupError, setLookupError] = useState('');

Expand Down
2 changes: 1 addition & 1 deletion skillgraph-web/app/(app)/openclaw/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@

export default function OpenClawPage() {
const [config, setConfig] = useState<OpenClawConfig | null>(null);
const [applications, setApplications] = useState<any[]>([]);

Check warning on line 44 in skillgraph-web/app/(app)/openclaw/page.tsx

View workflow job for this annotation

GitHub Actions / Typecheck, lint & test (skillgraph-web)

Unexpected any. Specify a different type
const [stats, setStats] = useState<AppStats>({ total: 0, preparedToday: 0, readyToApply: 0, avgMatchScore: 0 });
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
Expand Down Expand Up @@ -179,7 +179,7 @@
<div className="mb-6">
<AgentStatusCard
isActive={config?.isActive ?? false}
preparedToday={stats.handledToday ?? stats.preparedToday}
handledToday={stats.handledToday ?? stats.preparedToday}
readyToApply={stats.readyToApply}
dailyLimit={config?.dailyLimit ?? 10}
totalApplications={stats.total}
Expand Down
3 changes: 3 additions & 0 deletions skillgraph-web/app/api/extension/prepare/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { checkFilters, filtersFromConfig } from '@/lib/openclaw/filters'
import { OPEN_STATUSES } from '@/lib/openclaw/status'
import { createTailoredResume, resumeFileName, NoResumeSource } from '@/lib/resume/tailor'
import { readPrivateFile } from '@/lib/storage'
import { tailoringLimitReached } from '@/lib/openclaw/limits'

const bodySchema = z.object({
platform: z.enum(EXTENSION_PLATFORMS),
Expand Down Expand Up @@ -64,6 +65,8 @@ export async function POST(req: NextRequest) {
}
}

const limited = await tailoringLimitReached(userId)
if (limited) return limited
const resume = await createTailoredResume(userId, { company: job.company, role: job.role, jdText: job.jdText, sourceUrl: job.url })

const applicationId = existing
Expand Down
95 changes: 32 additions & 63 deletions skillgraph-web/app/api/market/skills/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,87 +17,56 @@ export async function GET(req: NextRequest) {
}
}

async function computeSkillDemand(role: string | null) {
// Get current ISO week number
const now = new Date()
const start = new Date(now.getFullYear(), 0, 1)
const currentWeek = Math.ceil(((now.getTime() - start.getTime()) / 86400000 + start.getDay() + 1) / 7)

const whereClause = {
demandWeek: currentWeek,
...(role ? { role: { contains: role, mode: 'insensitive' as const } } : {}),
}

// Try to get data for current week
let jobs = await prisma.jobPosting.findMany({ where: whereClause, take: 500 })

let weekToReport = currentWeek;

// FALLBACK: If current week is empty, find the most recent week with data
if (jobs.length === 0) {
const mostRecent = await prisma.jobPosting.findFirst({
orderBy: { demandWeek: 'desc' },
select: { demandWeek: true }
});
if (mostRecent) {
weekToReport = mostRecent.demandWeek;
jobs = await prisma.jobPosting.findMany({
where: {
demandWeek: weekToReport,
...(role ? { role: { contains: role, mode: 'insensitive' as const } } : {}),
},
take: 500
});
}
}
const DAY = 24 * 60 * 60 * 1000

// Aggregate skill frequency
const skillFreq: Record<string, number> = {}
/** Skills asked for by role, counted per job posting. */
function skillCounts(jobs: { requiredSkills: unknown }[]) {
const freq: Record<string, number> = {}
for (const job of jobs) {
const skills = (job.requiredSkills as string[]) || []
for (const skill of skills) {
if (skill && skill.length > 1) {
skillFreq[skill] = (skillFreq[skill] || 0) + 1
}
}
const skills = Array.isArray(job.requiredSkills) ? (job.requiredSkills as string[]) : []
for (const skill of skills) if (skill && skill.length > 1) freq[skill] = (freq[skill] || 0) + 1
}
return freq
}

// Change = shift in the share of postings that ask for the skill, versus the previous week with data
/**
* Demand from the most recent week of loaded postings, compared with the week before it.
* Weeks are taken from when postings were loaded (scrapedAt), not the stored week number,
* which has no year and would mix this year's data with last year's.
*/
async function computeSkillDemand(role: string | null) {
const roleFilter = role ? { role: { contains: role, mode: 'insensitive' as const } } : {}
const prev = await prisma.jobPosting.findFirst({
where: { demandWeek: { lt: weekToReport }, ...roleFilter },
orderBy: { demandWeek: 'desc' },
select: { demandWeek: true },
})
const prevJobs = prev
? await prisma.jobPosting.findMany({ where: { demandWeek: prev.demandWeek, ...roleFilter }, select: { requiredSkills: true }, take: 500 })
: []
const prevFreq: Record<string, number> = {}
for (const job of prevJobs) {
for (const skill of (job.requiredSkills as string[]) || []) prevFreq[skill] = (prevFreq[skill] || 0) + 1
}
const latest = await prisma.jobPosting.findFirst({ where: roleFilter, orderBy: { scrapedAt: 'desc' }, select: { scrapedAt: true, demandWeek: true } })
if (!latest) return { week: null, role: role ?? 'All Roles', topSkills: [], totalJobsAnalyzed: 0, lastUpdated: null }

const end = latest.scrapedAt.getTime()
const window = (from: number, to: number) =>
prisma.jobPosting.findMany({
where: { ...roleFilter, scrapedAt: { gt: new Date(from), lte: new Date(to) } },
select: { requiredSkills: true },
take: 500,
})
const [jobs, prevJobs] = await Promise.all([window(end - 7 * DAY, end), window(end - 14 * DAY, end - 7 * DAY)])

const freq = skillCounts(jobs)
const prevFreq = skillCounts(prevJobs)
const share = (count: number, total: number) => (total > 0 ? (count / total) * 100 : 0)

const topSkills = Object.entries(skillFreq)
const topSkills = Object.entries(freq)
.sort(([, a], [, b]) => b - a)
.slice(0, 20)
.map(([skill, count]) => ({
skill,
count,
// Percentage points; null when there is no earlier week to compare with
// Percentage-point shift in the share of postings asking for the skill; null without an earlier week
change: prevJobs.length > 0 ? Math.round(share(count, jobs.length) - share(prevFreq[skill] ?? 0, prevJobs.length)) : null,
}))

const lastScraped = await prisma.jobPosting.findFirst({
orderBy: { scrapedAt: 'desc' },
select: { scrapedAt: true },
})

return {
week: weekToReport,
week: latest.demandWeek,
role: role ?? 'All Roles',
topSkills,
totalJobsAnalyzed: jobs.length,
lastUpdated: lastScraped?.scrapedAt ?? null,
lastUpdated: latest.scrapedAt,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'
import { ok, unauthorized, badRequest, serverError, aiFailure } from '@/lib/api'
import { createTailoredResume, NoResumeSource } from '@/lib/resume/tailor'
import { tailoringLimitReached } from '@/lib/openclaw/limits'

// POST /api/openclaw/applications/:id/tailor — build a résumé tailored to this job (for jobs the
// student evaluated themselves; the agent and the extension tailor automatically)
Expand All @@ -19,6 +20,9 @@ export async function POST(_req: NextRequest, { params }: { params: Promise<{ id
})
if (!app) return NextResponse.json({ error: 'Application not found' }, { status: 404 })

const limited = await tailoringLimitReached(session.user.id)
if (limited) return limited

const { listing } = app
const resume = await createTailoredResume(
session.user.id,
Expand Down
8 changes: 4 additions & 4 deletions skillgraph-web/components/openclaw/AgentStatusCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button";

interface AgentStatusCardProps {
isActive: boolean;
preparedToday: number;
handledToday: number;
readyToApply: number;
dailyLimit: number;
totalApplications: number;
Expand All @@ -16,7 +16,7 @@ interface AgentStatusCardProps {

export default function AgentStatusCard({
isActive,
preparedToday,
handledToday,
readyToApply,
dailyLimit,
totalApplications,
Expand Down Expand Up @@ -73,11 +73,11 @@ export default function AgentStatusCard({
<div className="bg-background/50 rounded-lg p-3 text-center border border-border">
<div className="text-2xl font-heading font-black text-foreground">{readyToApply}</div>
<div className="text-[10px] uppercase tracking-wider text-muted-foreground mt-0.5">Ready to apply</div>
<div className="text-[10px] text-muted-foreground mt-1">{preparedToday} / {dailyLimit} prepared or submitted today</div>
<div className="text-[10px] text-muted-foreground mt-1">{handledToday} / {dailyLimit} prepared or submitted today</div>
<div className="w-full bg-muted rounded-full h-1.5 mt-1">
<div
className="gradient-primary h-1.5 rounded-full transition-all"
style={{ width: `${Math.min((preparedToday / Math.max(dailyLimit, 1)) * 100, 100)}%` }}
style={{ width: `${Math.min((handledToday / Math.max(dailyLimit, 1)) * 100, 100)}%` }}
/>
</div>
</div>
Expand Down
40 changes: 27 additions & 13 deletions skillgraph-web/lib/openclaw/filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,29 +40,43 @@ export function filtersFromConfig(config: {
}
}

const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

/**
* Whether `text` contains `term` as a whole word or phrase: "Java" doesn't match "JavaScript",
* "AI" doesn't match "maintain". Terms ending in symbols ("C++", "Node.js", "5+ years") still match.
*/
export function containsTerm(text: string, term: string): boolean {
const t = norm(term)
if (!t) return false
const start = /^[a-z0-9]/.test(t) ? '(?<![a-z0-9])' : ''
const end = /[a-z0-9]$/.test(t) ? '(?![a-z0-9])' : ''
return new RegExp(`${start}${escapeRegex(t)}${end}`).test(norm(text))
}

/** A role matches when the title contains the whole target, or all its distinctive words. */
function roleMatches(title: string, target: string) {
const t = norm(title)
const want = norm(target)
if (t.includes(want)) return true
const words = want.split(/[^a-z0-9+#.]+/).filter(w => w && !ROLE_STOPWORDS.has(w))
return words.length > 0 && words.every(w => t.includes(w))
if (containsTerm(title, target)) return true
const words = norm(target).split(/[^a-z0-9+#.]+/).filter(w => w && !ROLE_STOPWORDS.has(w))
return words.length > 0 && words.every(w => containsTerm(title, w))
}

/**
* Upper end of a CTC band in lakhs per annum, or null if it can't be read.
* Understands "8-12 LPA", "6.5-7 Lacs P.A.", "12 lakhs", "₹6,00,000 - ₹9,00,000", "1200000-1800000 INR"
* and monthly amounts ("₹40,000 - ₹50,000 per month"); hourly pay returns null.
* monthly amounts ("₹40,000 - ₹50,000 per month", "60,000 a month") and thousands written as
* "25k". Hourly pay returns null.
*/
export function maxCtcLpa(band: string | null): number | null {
if (!band) return null
const text = band.toLowerCase().replace(/,/g, '')
// Foreign-currency bands can't be compared with a rupee minimum
if (/[$€£]|\b(usd|eur|gbp|aud|cad|sgd)\b/.test(text)) return null
// Hourly pay (Glassdoor shows some roles this way) can't be compared with an annual CTC
if (/per hour|hourly|\/\s*h(ou)?r\b/.test(text)) return null
const monthly = /per month|monthly|\/\s*mo(nth)?\b|\bp\.?m\.?(\s|$)/.test(text)
const nums = [...text.matchAll(/\d+(?:\.\d+)?/g)].map(m => Number(m[0])).filter(n => n > 0)
if (/per hour|hourly|an hour|\/\s*h(ou)?r\b/.test(text)) return null
const monthly = /per month|a month|monthly|per mensem|\/\s*mo(nth)?\b|\bp\.?m\.?(\s|$)/.test(text)
// "25k" / "25 K" are thousands
const nums = [...text.matchAll(/(\d+(?:\.\d+)?)\s*(k\b)?/g)].map(m => Number(m[1]) * (m[2] ? 1000 : 1)).filter(n => n > 0)
if (nums.length === 0) return null
const max = Math.max(...nums)
if (/lpa|lakh|lac|\bl\b/.test(text) || max < 200) return monthly ? max * 12 : max
Expand All @@ -75,7 +89,7 @@ export function checkFilters(job: Pick<JobListing, 'company' | 'role' | 'locatio
const pass: string[] = []
const haystack = norm(`${job.role}\n${job.jdText}`)

const blocked = f.blacklistedCompanies.find(c => norm(job.company).includes(norm(c)))
const blocked = f.blacklistedCompanies.find(c => containsTerm(job.company, c))
if (blocked) fail.push(`${job.company} is on your blocked companies list`)

if (f.targetRoles.length > 0) {
Expand All @@ -86,7 +100,7 @@ export function checkFilters(job: Pick<JobListing, 'company' | 'role' | 'locatio

if (f.preferredCities.length > 0 && job.location) {
const wantsRemote = f.preferredCities.some(c => REMOTE.test(c))
const city = f.preferredCities.find(c => !REMOTE.test(c) && norm(job.location!).includes(norm(c)))
const city = f.preferredCities.find(c => !REMOTE.test(c) && containsTerm(job.location!, c))
if (city) pass.push(`Location matches ${city}`)
else if (wantsRemote && REMOTE.test(job.location)) pass.push('Remote role')
else fail.push(`${job.location} isn’t one of your cities (${f.preferredCities.join(', ')})`)
Expand All @@ -98,11 +112,11 @@ export function checkFilters(job: Pick<JobListing, 'company' | 'role' | 'locatio
else pass.push(`Pays up to ₹${ctc} LPA`)
}

const excluded = f.excludeKeywords.find(k => haystack.includes(norm(k)))
const excluded = f.excludeKeywords.find(k => containsTerm(haystack, k))
if (excluded) fail.push(`Mentions “${excluded}”, which you excluded`)

if (f.includeKeywords.length > 0) {
const hit = f.includeKeywords.find(k => haystack.includes(norm(k)))
const hit = f.includeKeywords.find(k => containsTerm(haystack, k))
if (hit) pass.push(`Mentions “${hit}”`)
else fail.push(`Mentions none of your keywords (${f.includeKeywords.join(', ')})`)
}
Expand Down
32 changes: 32 additions & 0 deletions skillgraph-web/lib/openclaw/limits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* The plan's daily OpenClaw allowance (lib/billing/plans.ts → openclawPerDay), counted as job-tailored
* résumés generated today. Shared by the browser extension and "Tailor CV"; the nightly agent
* applies the same plan limit to what it prepares or submits.
*/
import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { getEntitlements } from '@/lib/billing'

function startOfToday() {
const d = new Date()
d.setHours(0, 0, 0, 0)
return d
}

/** A 402 response when today's allowance is used up, otherwise null. */
export async function tailoringLimitReached(userId: string): Promise<NextResponse | null> {
const [{ limits, plan }, usedToday] = await Promise.all([
getEntitlements(userId),
prisma.resumeVersion.count({ where: { userId, generatedBy: 'AI', createdAt: { gte: startOfToday() } } }),
])
if (usedToday < limits.openclawPerDay) return null
return NextResponse.json(
{
error: plan === 'student_free'
? `You've tailored ${usedToday} résumés today, the Free plan's daily limit. Upgrade to Pro on the Billing page for more.`
: `Daily limit of ${limits.openclawPerDay} tailored résumés reached. It resets at midnight.`,
code: 'plan_limit',
},
{ status: 402 },
)
}
17 changes: 15 additions & 2 deletions skillgraph-web/lib/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ export type RateLimitRule = {
windowMs: number
methods?: string[]
match: (pathname: string) => boolean
/** Count per client IP even for signed-in or token callers (a ceiling that forged tokens can't escape). */
keyBy?: 'ip'
}

const MINUTE = 60_000
Expand Down Expand Up @@ -209,6 +211,15 @@ export const RATE_LIMIT_RULES: RateLimitRule[] = [
p.startsWith('/api/market/job-details') ||
p.startsWith('/api/market/company-salary'),
},
{
// Extension calls are limited per token (rules above) plus this per-IP ceiling: generous enough for a
// campus behind one IP, and a stream of made-up tokens can't each get a fresh bucket
name: 'extension_ip',
limit: 600,
windowMs: 15 * MINUTE,
keyBy: 'ip',
match: (p) => p.startsWith('/api/extension/'),
},
]

export type RateLimitResult =
Expand All @@ -222,13 +233,15 @@ export type RateLimitResult =
export async function checkRateLimit(
method: string,
pathname: string,
clientKey: string
clientKey: string,
ip = 'unknown'
): Promise<RateLimitResult> {
for (const rule of RATE_LIMIT_RULES) {
if (rule.methods && !rule.methods.includes(method)) continue
if (!rule.match(pathname)) continue

const { count, resetAt } = await store.increment(`${rule.name}:${clientKey}`, rule.windowMs)
const key = rule.keyBy === 'ip' ? `ip:${ip}` : clientKey
const { count, resetAt } = await store.increment(`${rule.name}:${key}`, rule.windowMs)
if (count > rule.limit) {
return { limited: true, rule, retryAfterSec: Math.max(1, Math.ceil((resetAt - Date.now()) / 1000)) }
}
Expand Down
Loading
Loading