返回 last30days-skill
hiring_signals.py
根目录 / skills / last30days / scripts / lib / hiring_signals.py
1 """Hiring Signals analysis from normalized jobs SourceItems."""
2
3 from __future__ import annotations
4
5 import re
6 from collections import Counter, defaultdict
7 from typing import Any
8
9 from . import job_boilerplate, schema
10
11
12 # Bare words a company's own text uses on every role ("growth", "design",
13 # "solutions", "platform", "model", "insights", "admin", "warehouse") are
14 # left out or narrowed to the role phrase that carries them.
15 THEME_KEYWORDS: dict[str, tuple[str, ...]] = {
16 "enterprise readiness": (
17 "enterprise", "soc 2", "sso", "security", "compliance", "procurement",
18 "governance", "audit",
19 ),
20 "go-to-market": (
21 "sales", "account executive", "customer success", "solutions engineer",
22 "solution engineer", "solutions architect", "solution architect",
23 "partnership", "revenue", "demand generation", "marketing",
24 ),
25 "ai and machine learning": (
26 "machine learning", "ml", "ai", "llm", "language model", "foundation model",
27 "research scientist", "applied scientist", "data scientist",
28 ),
29 "infrastructure and reliability": (
30 "infrastructure", "platform engineer", "platform engineering", "devops", "sre",
31 "site reliability", "reliability", "cloud", "distributed systems", "backend",
32 "data center", "data centre",
33 ),
34 "product expansion": (
35 "product manager", "product designer", "product design", "growth engineer",
36 "growth marketing", "growth product", "mobile", "frontend", "ux",
37 ),
38 "data and analytics": (
39 "data", "analytics", "business intelligence", "data warehouse", "etl",
40 ),
41 }
42
43 # Phrases a keyword must not be followed by: a "Data Center Technician" works on
44 # infrastructure, not data and analytics.
45 _KEYWORD_EXCLUSIONS: dict[str, str] = {
46 "data": r"(?!\s+cent(?:er|re)s?\b)",
47 }
48
49 SENIORITY_TERMS = ("head of", "director", "vp", "principal", "staff", "lead", "founding")
50
51 # Leadership markers that establish/own a function (a first-of-function hire).
52 LEADERSHIP_TERMS = (
53 "head of", "chief", "global head", "svp", "vp of", "vp,", "director of",
54 "general manager", "vice president",
55 )
56
57 # Title qualifiers that are level/logistics noise, not a specialized capability.
58 _GENERIC_QUALIFIERS = {
59 "senior", "staff", "principal", "lead", "junior", "mid", "sr", "jr",
60 "i", "ii", "iii", "iv", "remote", "hybrid", "onsite", "on-site",
61 "contract", "intern", "full-time", "part-time", "us", "uk", "emea",
62 }
63 # Words a title tail made only of says a level or a team, not a capability:
64 # "Engineer, Entry Level", "Engineer, Multiple Teams".
65 _LEVEL_AND_TEAM_WORDS = {
66 *_GENERIC_QUALIFIERS, "entry", "level", "new", "grad", "graduate", "associate",
67 "experienced", "internship", "team", "teams", "multiple", "various", "all", "any",
68 "org", "organization", "group", "department", "division", "general",
69 }
70 # Regions a title tail names that are places, not specialties.
71 _REGION_WORDS = {
72 "apac", "latam", "americas", "north america", "europe", "global", "worldwide",
73 "usa", "united states",
74 }
75
76
77 def analyze(
78 items: list[schema.SourceItem],
79 *,
80 explicit: bool,
81 topic: str = "",
82 ) -> dict[str, Any]:
83 """Return a structured Hiring Signals summary for report artifacts."""
84 if not items:
85 return {
86 "mode": "explicit" if explicit else "standard",
87 "company_size_tier": "unknown",
88 "include": False,
89 "signals": [],
90 "strategic_candidates": [],
91 "omitted_reason": "no current public jobs evidence found",
92 }
93
94 size_tier = infer_company_size(items, topic=topic)
95 themes = _theme_items(items)
96 signals = [_build_signal(theme, theme_items, size_tier) for theme, theme_items in themes.items()]
97 signals = [signal for signal in signals if signal["evidence_count"] > 0]
98 signals.sort(key=lambda s: (s["confidence_score"], s["evidence_count"]), reverse=True)
99
100 # Strategic single-role signals are NOT count-gated: a founding or
101 # first-of-function role can outweigh a department's worth of headcount.
102 # The engine only FLAGS these; the reasoning model judges true novelty
103 # (e.g. whether "Human Simulation" is a new bet for this company).
104 strategic_candidates = _strategic_candidates(items)
105
106 include = (
107 bool(signals) or bool(strategic_candidates)
108 ) if explicit else any(_passes_standard_threshold(signal, size_tier) for signal in signals)
109 if not explicit:
110 signals = [signal for signal in signals if _passes_standard_threshold(signal, size_tier)]
111 _assign_evidence(signals, themes)
112
113 return {
114 "mode": "explicit" if explicit else "standard",
115 "company_size_tier": size_tier,
116 "include": include,
117 "signals": signals,
118 "strategic_candidates": strategic_candidates,
119 "omitted_reason": "" if include else _omitted_reason(items, size_tier, signals),
120 }
121
122
123 def infer_company_size(items: list[schema.SourceItem], *, topic: str = "") -> str:
124 """Infer a coarse company-size tier from jobs evidence."""
125 topic_lower = topic.lower()
126 firmographic_text = " ".join(
127 " ".join([
128 str(item.metadata.get("company_size") or ""),
129 topic,
130 ])
131 for item in items
132 ).lower()
133 text = " ".join(
134 " ".join([
135 item.title,
136 item.body[:1000],
137 str(item.metadata.get("company_size") or ""),
138 str(item.metadata.get("source_domain") or ""),
139 topic,
140 ])
141 for item in items
142 ).lower()
143 count = len(items)
144 # Brand-name shortcut must match the COMPANY being researched (the topic),
145 # never the job-description body - JDs list enterprise customers (e.g.
146 # "trusted by Microsoft, Google"), which would misclassify a startup as
147 # mega-cap and suppress its real signals.
148 if re.search(r"\b(apple|uber|google|microsoft|amazon|meta|netflix)\b", topic_lower):
149 return "mega-cap"
150 if count >= 200 or re.search(r"\b(fortune 500|thousands of employees)\b", firmographic_text):
151 return "large-enterprise"
152 if count >= 35 or re.search(r"\b(series [cd]|public company)\b", text):
153 return "growth"
154 if count <= 12 or re.search(r"\b(founding|seed|series a|early[- ]stage|startup)\b", text):
155 return "startup"
156 return "mid-market"
157
158
159 # Keywords match as whole words (plural "s" allowed), so "ai" does not match "retail" or
160 # "training" and "ml" does not match "html".
161 _THEME_PATTERNS: dict[str, re.Pattern[str]] = {
162 theme: re.compile(r"\b(?:" + "|".join(
163 re.escape(keyword) + r"s?\b" + _KEYWORD_EXCLUSIONS.get(keyword, "")
164 for keyword in keywords
165 ) + ")")
166 for theme, keywords in THEME_KEYWORDS.items()
167 }
168 _ALL_KEYWORDS = frozenset(keyword for keywords in THEME_KEYWORDS.values() for keyword in keywords)
169
170
171 def _keyword(matched: str) -> str:
172 """The keyword a match stands for: its text, less a plural "s"."""
173 return matched if matched in _ALL_KEYWORDS else matched[:-1]
174
175
176 # Where a theme keyword was found, strongest first. A title says what the role
177 # is; a department says where it sits; a description sentence only hints.
178 _TITLE_MATCH, _DEPARTMENT_MATCH, _BODY_MATCH = 3, 2, 1
179
180 # Examples kept per theme.
181 EVIDENCE_PER_THEME = 5
182
183
184 def _department(item: schema.SourceItem) -> str:
185 return str(item.metadata.get("department") or item.container or "").strip()
186
187
188 def _description(item: schema.SourceItem) -> str:
189 """The posting's description, without the title, department and location lines.
190
191 Normalized job bodies open with those fields; they are matched on their own.
192 """
193 header = {
194 job_boilerplate.key(part)
195 for part in (item.title, _department(item), str(item.metadata.get("location") or ""))
196 if part
197 }
198 return "\n".join(
199 line for line in str(item.body or "").splitlines()
200 if job_boilerplate.key(line) not in header
201 )
202
203
204 def _match_strength(
205 pattern: re.Pattern[str], title: str, department: str, body: str,
206 ) -> tuple[int, int]:
207 """(strongest field matched, distinct keywords matched), or (0, 0)."""
208 best = 0
209 keywords: set[str] = set()
210 for field, text in ((_TITLE_MATCH, title), (_DEPARTMENT_MATCH, department), (_BODY_MATCH, body)):
211 hits = {_keyword(match.group()) for match in pattern.finditer(text)}
212 if hits:
213 best = max(best, field)
214 keywords |= hits
215 return best, len(keywords)
216
217
218 def _ranked_theme_items(
219 items: list[schema.SourceItem],
220 ) -> dict[str, list[tuple[tuple[int, int], schema.SourceItem]]]:
221 """Each theme's roles with their match strength, strongest first.
222
223 Themes match a role's title and department, and its description only after
224 sentences that ``job_boilerplate.BOILERPLATE_MIN_ROLES`` or more distinct
225 roles share are removed: company text every posting repeats themes nothing.
226 """
227 descriptions = [_description(item) for item in items]
228 shared = job_boilerplate.shared_sentence_counts(
229 (item.title, _department(item), text) for item, text in zip(items, descriptions)
230 )
231 themed: dict[str, list[tuple[tuple[int, int], schema.SourceItem]]] = defaultdict(list)
232 for item, text in zip(items, descriptions):
233 title = item.title.lower()
234 department = _department(item).lower()
235 body = " ".join(job_boilerplate.role_sentences(text, shared)).lower()
236 matched = False
237 for theme, pattern in _THEME_PATTERNS.items():
238 strength = _match_strength(pattern, title, department, body)
239 if strength[0]:
240 themed[theme].append((strength, item))
241 matched = True
242 if not matched:
243 fallback = department or "general hiring"
244 themed[fallback].append(((0, 0), item))
245 # sort is stable: equal strengths keep the board's order.
246 return {
247 theme: sorted(ranked, key=lambda pair: pair[0], reverse=True)
248 for theme, ranked in themed.items()
249 }
250
251
252 def _theme_items(items: list[schema.SourceItem]) -> dict[str, list[schema.SourceItem]]:
253 return {
254 theme: [item for _strength, item in ranked]
255 for theme, ranked in _ranked_theme_items(items).items()
256 }
257
258
259 def _evidence_entry(item: schema.SourceItem) -> dict[str, Any]:
260 return {
261 "title": item.title,
262 "url": item.url,
263 "department": item.metadata.get("department") or item.container or "",
264 "published_at": item.published_at,
265 }
266
267
268 def _assign_evidence(
269 signals: list[dict[str, Any]], themes: dict[str, list[schema.SourceItem]],
270 ) -> None:
271 """Give each signal up to ``EVIDENCE_PER_THEME`` examples no other signal shows.
272
273 Signals take turns in their ranked order, each taking its strongest role not
274 yet shown, so every theme gets its best distinct example before any gets a
275 second. ``evidence_count`` stays the theme's full role count.
276 """
277 shown: set[str] = set()
278 picks: list[list[schema.SourceItem]] = [[] for _signal in signals]
279 cursors = [0] * len(signals)
280 for _round in range(EVIDENCE_PER_THEME):
281 for index, signal in enumerate(signals):
282 ranked = themes.get(signal["theme"], [])
283 while cursors[index] < len(ranked):
284 item = ranked[cursors[index]]
285 cursors[index] += 1
286 role = item.url or item.item_id
287 if role not in shown:
288 shown.add(role)
289 picks[index].append(item)
290 break
291 for signal, items in zip(signals, picks):
292 signal["evidence"] = [_evidence_entry(item) for item in items]
293
294
295 def _build_signal(theme: str, items: list[schema.SourceItem], size_tier: str) -> dict[str, Any]:
296 titles = [item.title for item in items if item.title]
297 departments = [
298 str(item.metadata.get("department") or item.container or "").strip()
299 for item in items
300 if str(item.metadata.get("department") or item.container or "").strip()
301 ]
302 senior_roles = [
303 title for title in titles
304 if any(term in title.lower() for term in SENIORITY_TERMS)
305 ]
306 strategic_count = sum(1 for title in titles if _is_strategic_title(title))
307 score = _confidence_score(
308 len(items), len(set(departments)), len(senior_roles), size_tier,
309 strategic_count=strategic_count,
310 )
311 evidence = [_evidence_entry(item) for item in items[:EVIDENCE_PER_THEME]]
312 return {
313 "theme": theme,
314 "interpretation": _interpretation(theme),
315 "confidence": _confidence_label(score),
316 "confidence_score": score,
317 "evidence_count": len(items),
318 "departments": [name for name, _count in Counter(departments).most_common(3)],
319 "senior_roles": senior_roles[:3],
320 "evidence": evidence,
321 }
322
323
324 def _confidence_score(
325 count: int,
326 department_count: int,
327 senior_count: int,
328 size_tier: str,
329 strategic_count: int = 0,
330 ) -> int:
331 # Count no longer dominates: founding/first-of-function and seniority can
332 # let a small cluster outrank a large generic one (a "new bet" beating
333 # "doubling down"). The reasoning model still makes the final novelty call.
334 score = count * 12 + min(department_count, 3) * 6 + senior_count * 10 + strategic_count * 14
335 if size_tier == "startup":
336 score += 20
337 elif size_tier == "mid-market":
338 score += 10
339 elif size_tier == "growth":
340 score -= 5
341 elif size_tier == "large-enterprise":
342 score -= 25
343 elif size_tier == "mega-cap":
344 score -= 40
345 return max(0, min(100, score))
346
347
348 def _passes_standard_threshold(signal: dict[str, Any], size_tier: str) -> bool:
349 thresholds = {
350 "startup": (2, 50),
351 "mid-market": (3, 58),
352 "growth": (4, 65),
353 "large-enterprise": (6, 78),
354 "mega-cap": (8, 86),
355 "unknown": (3, 62),
356 }
357 min_count, min_score = thresholds.get(size_tier, thresholds["unknown"])
358 return signal["evidence_count"] >= min_count and signal["confidence_score"] >= min_score
359
360
361 def _confidence_label(score: int) -> str:
362 if score >= 75:
363 return "high"
364 if score >= 50:
365 return "medium"
366 return "low"
367
368
369 def _interpretation(theme: str) -> str:
370 if theme == "general hiring":
371 return "hiring activity is visible, but the priority signal is diffuse"
372 return f"appears to be increasing focus on {theme}"
373
374
375 def _strategic_candidates(items: list[schema.SourceItem]) -> list[dict[str, Any]]:
376 """Flag individual roles worth surfacing regardless of how many share a theme.
377
378 Pure structural detection (founding, first-of-function, specialized
379 qualifier, geographic novelty) - no semantic novelty judgment, which is
380 left to the reasoning model. Guarantees these roles reach synthesis instead
381 of being averaged away by count-weighting.
382 """
383 item_locations = [(item, _norm_location(item)) for item in items]
384 # A place counts once however the board spells it: "Seattle, WA" is
385 # the "Seattle" another role names.
386 place_counts = Counter(place_key(loc) for _item, loc in item_locations if place_key(loc))
387 dominant = max(place_counts.values()) if place_counts else 0
388 places = set(place_counts)
389
390 scored: list[tuple[int, dict[str, Any]]] = []
391 for item, location in item_locations:
392 flags = _title_flags(item.title or "", places=places)
393 if location and place_counts.get(place_key(location), 0) == 1 and dominant >= 3:
394 flags.append("new-geo")
395 if not flags:
396 continue
397 priority = (
398 ("founding" in flags) * 4
399 + ("new-geo" in flags) * 3
400 + ("leadership" in flags) * 2
401 + ("specialized" in flags) * 1
402 )
403 scored.append((priority, {
404 "title": item.title,
405 "url": item.url,
406 "department": str(item.metadata.get("department") or item.container or "").strip(),
407 "location": location,
408 "published_at": item.published_at,
409 "flags": flags,
410 }))
411 scored.sort(key=lambda pair: pair[0], reverse=True)
412 return [candidate for _priority, candidate in scored[:10]]
413
414
415 def _title_flags(title: str, *, places: set[str] | frozenset[str] = frozenset()) -> list[str]:
416 """Structural strategic flags derivable from a title alone (no geo).
417
418 ``places`` are the ``place_key`` of every location on the board, so a
419 title tail naming one of them is not taken for a specialty.
420 """
421 lowered = title.lower()
422 flags: list[str] = []
423 if "founding" in lowered or re.search(r"\bfirst\b", lowered):
424 flags.append("founding")
425 if any(term in lowered for term in LEADERSHIP_TERMS) or re.search(r"\bgm\b", lowered):
426 flags.append("leadership")
427 if _specialization(title, places=places):
428 flags.append("specialized")
429 return flags
430
431
432 def _is_strategic_title(title: str) -> bool:
433 return bool(_title_flags(title))
434
435
436 def _specialization(title: str, *, places: set[str] | frozenset[str] = frozenset()) -> str:
437 """Return a specialized sub-domain qualifier from a title, or ''.
438
439 "Research Scientist, Human Simulation" -> "Human Simulation".
440 "Engineer (Forward Deployed)" -> "Forward Deployed".
441 "Engineer, Senior" -> "" (generic level word, not a capability).
442 "Engineer, Multiple Teams" -> "" (team words only).
443 "Engineer, Seattle" -> "" when ``places`` holds "seattle".
444 """
445 tail = ""
446 paren = re.search(r"\(([^)]+)\)", title)
447 if paren:
448 tail = paren.group(1).strip()
449 elif "," in title:
450 tail = title.rsplit(",", 1)[1].strip()
451 if not tail or len(tail) < 4:
452 return ""
453 lowered = tail.lower()
454 if lowered in _GENERIC_QUALIFIERS or lowered in _REGION_WORDS:
455 return ""
456 if place_key(lowered) in places:
457 return ""
458 words = re.findall(r"[a-z0-9]+", lowered)
459 if all(word in _LEVEL_AND_TEAM_WORDS or word.isdigit() for word in words):
460 return ""
461 return tail
462
463
464 def place_key(location: str) -> str:
465 """The city, or the country when that is all it names, a location
466 string starts with: "Seattle, WA" and "Seattle, Washington, USA" are
467 both "seattle"."""
468 return location.split(",", 1)[0].strip().lower()
469
470
471 def _norm_location(item: schema.SourceItem) -> str:
472 return str(item.metadata.get("location") or "").strip().lower()
473
474
475 def _omitted_reason(
476 items: list[schema.SourceItem],
477 size_tier: str,
478 signals: list[dict[str, Any]],
479 ) -> str:
480 if not items:
481 return "no current public jobs evidence found"
482 if size_tier in {"large-enterprise", "mega-cap"}:
483 return "jobs evidence is too diffuse for the inferred company size"
484 if not signals:
485 return "jobs evidence did not cluster into a clear signal"
486 return "jobs evidence is too thin for standard-report inclusion"
487
487 lines PYTHON