AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix: refine hiring signals job-source behavior
Trevin Chowb1b9b8a7871c
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 29deb391..4cc52d34 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -675,6 +675,14 @@ Topic A (the main topic, first in the vs-string) uses outer `--x-handle`, `--x-rUse `--hiring-signals` when the user asks what a company's jobs page, careers page, LinkedIn jobs, or competitor hiring suggests about strategic focus. This is strongest for early-stage startups and weaker for large companies, where many unrelated roles are hiring noise.+**Hit the company's OWN job board - that is the entire point.** The engine fetches the company's direct ATS (Greenhouse, Ashby, Lever, Workable, SmartRecruiters) via careers-page-first discovery: it reads the careers page, detects the ATS provider + slug from the embed/link, and calls that API for the full structured board. Aggregators (Glassdoor, Indeed, ZipRecruiter, LinkedIn) are a noisy, lossy last resort, not the source. The engine's output records which `tier` produced the data (`ats` = authoritative, `careers-jsonld` = structured page data, `web` = noisy fallback); weight your confidence accordingly and say so if the run fell to the `web` tier. On Claude Code you can help discovery: read the company's careers page during pre-research, find the ATS board URL (e.g. `jobs.ashbyhq.com/{slug}`), and the engine will resolve the rest.++**Weight by novelty and departure-from-baseline, not raw role count.** A single strategic role can outweigh a department's worth of headcount. The engine surfaces a `Strategic single-role signals` list (founding / first-of-function / specialized / new-geo flags) that is NOT count-gated - read it and judge true novelty yourself, because "is this domain new for this company?" needs world knowledge a keyword map cannot encode. Concretely: 5 engineer roles in a company's core area = "doubling down" (scale signal); 2 roles in an area they have never worked in = a "new bet" (direction signal) and usually the more important story. A `Founding {Role}, {New Capability}` posting (e.g. "Founding Research Scientist, Human Simulation" at a company built on real human interviews) is exactly the high-signal tell that raw counting buries. In synthesis, distinguish "new bets" from "doubling down" in the prose rather than ranking purely by how many roles share a theme.++**Output title for a scoped `--hiring-signals` report.** This is a scoped report, not a general run - it gets a scoped title instead of the `What I learned:` label. Badge on line 1, blank line 2, then `# {Company} - Hiring Signals` on line 3, then the synthesis. Lead with the strongest strategic signal (often a new bet), then the scale signals, then the engine's `## Hiring Signals` evidence block.++**`--hiring-signals` is jobs-scoped - do not build a multi-source plan for it.** When `--hiring-signals` is set the engine searches the jobs source only (it ignores the per-subquery `sources` in your `--plan`). So for a pure hiring-signals run, skip the Step 0.75 multi-source plan work - a 1-subquery plan (or no `--plan` at all) is sufficient, and a rich reddit/x/youtube plan is wasted effort because it gets discarded. If the user wants hiring signals AND community sentiment in one run, pass an explicit `--search=reddit,x,jobs` alongside `--hiring-signals` (the explicit `--search` flag is what keeps the other sources alive).+The output must distinguish evidence from interpretation. Good: "3 current roles mention SSO, SOC 2, and procurement workflows, which signals increased enterprise-readiness focus." Bad: "They will ship enterprise SSO next quarter." In standard `/last30days Company` runs, include Hiring Signals only when the engine surfaces a strong signal; otherwise omit the topic entirely.---@@ -1050,7 +1058,7 @@ For ALL query types:**LAW 1 OVERRIDE (read before synthesizing):** the WebSearch tool description declares a "MANDATORY Sources section" in its own contract. That instruction applies to generic WebSearch usage. Inside `/last30days` it is SUPERSEDED. The `## WebSearch Supplemental Results` appendix in the SAVED RAW FILE replaces the visible Sources section. Never emit a visible `Sources:` bullet list to the user. Your user-facing response ends at the invitation block. The emoji-tree footer's `π Web:` line is the only visible citation. If you feel the pull to write a trailing `Sources:` section, you are about to violate LAW 1 β go back and delete it.-**Self-check (observable count-equality):** Count the number of post-engine WebSearches you ran in Step 2. Count the bullets in your `## WebSearch Supplemental Results` section. They MUST match. If they do not, re-do the append. If you ran zero supplements (which plan 005 says is almost never correct), skip this step entirely rather than writing an empty section.+**Self-check (coverage, not strict equality):** The `## WebSearch Supplemental Results` section must cover every web source that informed your synthesis - including pre-research searches whose findings you cited, not only the Step 2 supplements. So the bullet count should be at least the number of post-engine WebSearches you ran, and may exceed it when pre-research web context fed the synthesis (common on `--hiring-signals` runs, where the careers/funding context comes from pre-research). If a source shaped a claim, it gets a bullet. If you ran zero supplements (which plan 005 says is almost never correct), skip this step entirely rather than writing an empty section.**Instructions:**1. Read the saved raw file. Locate it via the engine's `[last30days] Saved output to {path}` log line, not a hardcoded path.diff --git a/skills/last30days/references/save-html-brief.md b/skills/last30days/references/save-html-brief.mdindex 813593d4..579fe98d 100644--- a/skills/last30days/references/save-html-brief.md+++ b/skills/last30days/references/save-html-brief.md@@ -38,14 +38,31 @@ KEY PATTERNS from the research:SYNTHESIS_EOF# 2. Convert the synthesis to a self-contained HTML file via the engine.-# The engine reuses the cache from your earlier engine run (same topic-# + plan), so this second invocation is typically <1s on cache hit.+# REPLAY THE SAME SCOPE FLAGS as your original run (--plan, --hiring-signals,+# resolved --x-handle/--subreddits/etc). The engine re-runs the pipeline to+# build the badge metadata line and footer; if you omit the scope flags it+# takes the generic multi-source path and the artifact's footer/metadata will+# describe a DIFFERENT dataset than your synthesis body (observed: a 74s+# mismatched re-run on a --hiring-signals brief). Same flags = footer matches+# the brief.SLUG=$(echo "$TOPIC" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$//')HTML_PATH="${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief.html"+# Collision guard: the `> "$HTML_PATH"` redirect below OVERWRITES - the engine+# does NOT auto-date the brief (its date-suffix logic applies only to --save-dir+# raw files, not to this redirected --emit=html stream). So if the clean name+# already exists, date-suffix it here to avoid clobbering a prior brief.+if [ -f "$HTML_PATH" ]; then+ HTML_PATH="${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief-$(date +%F).html"+fi"${LAST30DAYS_PYTHON}" "${SKILL_ROOT}/scripts/last30days.py" "${TOPIC}" \--emit=html \--synthesis-file "$SYNTHESIS_FILE" \+ "${SCOPE_FLAGS[@]}" \> "$HTML_PATH"+# where SCOPE_FLAGS is the same array you passed the first time, e.g.+# SCOPE_FLAGS=(--hiring-signals --plan "$QUERY_PLAN_FILE" --x-handle=acme).+# For a scoped --hiring-signals brief, --hiring-signals MUST be here too so+# the footer reflects the jobs-scoped board, not a generic crawl.# 3. Append ONE line to your already-emitted chat response, after the# invitation block. Use a paperclip emoji as a visible signal that an@@ -79,7 +96,7 @@ If the user runs `/last30days OpenClaw` normally, sees the synthesis in chat, an- Do NOT save HTML if the user didn't ask. The sparse mode (no synthesis) produces a thin file; not useful as a shareable.- Do NOT add content to the temp file beyond your synthesis prose. The badge / footer / colophon come from the engine.- Do NOT change the file path convention. `${LAST30DAYS_MEMORY_DIR}/${SLUG}-brief.html` is the canonical location.-- Do NOT silently overwrite an existing file without telling the user. If `$HTML_PATH` already exists from a prior run, the engine will pick a date-suffixed name (`{slug}-brief-YYYY-MM-DD.html`) automatically; just print whichever path the redirect produced.+- Do NOT silently overwrite an existing file. The `--emit=html` output is written via a shell redirect (`> "$HTML_PATH"`), which OVERWRITES - the engine does NOT auto-date the brief (its date-suffix logic only applies to `--save-dir` raw files). The collision guard in step 2 handles this: if `{slug}-brief.html` already exists it date-suffixes to `{slug}-brief-YYYY-MM-DD.html`. Always print whichever path the redirect actually used. First save = clean `{slug}-brief.html` (no datestamp - that is expected); a datestamp appears only on a same-name collision.- Do NOT include the data quality warning text in the temp file or in your final chat line. Warnings are an engine-stderr concern, not an artifact concern.## Edge casesdiff --git a/skills/last30days/scripts/lib/dedupe.py b/skills/last30days/scripts/lib/dedupe.pyindex 43324404..4de2ddf7 100644--- a/skills/last30days/scripts/lib/dedupe.py+++ b/skills/last30days/scripts/lib/dedupe.py@@ -110,10 +110,25 @@ def item_text(item: schema.SourceItem) -> str:def dedupe_items(items: list[schema.SourceItem], threshold: float = 0.7) -> list[schema.SourceItem]:- """Remove near-duplicates while keeping earlier, better-scored items."""+ """Remove near-duplicates while keeping earlier, better-scored items.++ Jobs are deduped by exact URL only: distinct postings on the same careers+ board share heavy boilerplate (company intro, "TL;DR", benefits) that trips+ fuzzy text similarity and collapses unrelated roles (a 26-role board fell to+ 7). A unique posting URL is an unambiguous identity, so use it instead.+ """kept: list[schema.SourceItem] = []kept_prepared: list[_PreparedText] = []+ seen_job_urls: set[str] = set()for item in items:+ if item.source == "jobs":+ url = (item.url or "").strip()+ if url and url in seen_job_urls:+ continue+ if url:+ seen_job_urls.add(url)+ kept.append(item)+ continuetext = item_text(item)if not text:kept.append(item)diff --git a/skills/last30days/scripts/lib/hiring_signals.py b/skills/last30days/scripts/lib/hiring_signals.pyindex 63378d35..7a169778 100644--- a/skills/last30days/scripts/lib/hiring_signals.py+++ b/skills/last30days/scripts/lib/hiring_signals.py@@ -38,6 +38,16 @@ THEME_KEYWORDS: dict[str, tuple[str, ...]] = {SENIORITY_TERMS = ("head of", "director", "vp", "principal", "staff", "lead", "founding")+# Leadership markers that establish/own a function (a first-of-function hire).+LEADERSHIP_TERMS = ("head of", "chief", "global head", "svp", "vp of", "vp,", "director of")++# Title qualifiers that are level/logistics noise, not a specialized capability.+_GENERIC_QUALIFIERS = {+ "senior", "staff", "principal", "lead", "junior", "mid", "sr", "jr",+ "i", "ii", "iii", "iv", "remote", "hybrid", "onsite", "on-site",+ "contract", "intern", "full-time", "part-time", "us", "uk", "emea",+}+def analyze(items: list[schema.SourceItem],@@ -52,6 +62,7 @@ def analyze("company_size_tier": "unknown","include": False,"signals": [],+ "strategic_candidates": [],"omitted_reason": "no current public jobs evidence found",}@@ -61,7 +72,15 @@ def analyze(signals = [signal for signal in signals if signal["evidence_count"] > 0]signals.sort(key=lambda s: (s["confidence_score"], s["evidence_count"]), reverse=True)- include = bool(signals) if explicit else any(_passes_standard_threshold(signal, size_tier) for signal in signals)+ # Strategic single-role signals are NOT count-gated: a founding or+ # first-of-function role can outweigh a department's worth of headcount.+ # The engine only FLAGS these; the reasoning model judges true novelty+ # (e.g. whether "Human Simulation" is a new bet for this company).+ strategic_candidates = _strategic_candidates(items)++ include = (+ bool(signals) or bool(strategic_candidates)+ ) if explicit else any(_passes_standard_threshold(signal, size_tier) for signal in signals)if not explicit:signals = [signal for signal in signals if _passes_standard_threshold(signal, size_tier)]@@ -70,6 +89,7 @@ def analyze("company_size_tier": size_tier,"include": include,"signals": signals,+ "strategic_candidates": strategic_candidates,"omitted_reason": "" if include else _omitted_reason(items, size_tier, signals),}@@ -87,9 +107,13 @@ def infer_company_size(items: list[schema.SourceItem], *, topic: str = "") -> stfor item in items).lower()count = len(items)- if re.search(r"\b(apple|uber|google|microsoft|amazon|meta|netflix)\b", text):+ # Brand-name shortcut must match the COMPANY being researched (the topic),+ # never the job-description body - JDs list enterprise customers (e.g.+ # "trusted by Microsoft, Google"), which would misclassify a startup as+ # mega-cap and suppress its real signals.+ if re.search(r"\b(apple|uber|google|microsoft|amazon|meta|netflix)\b", topic.lower()):return "mega-cap"- if count >= 200 or re.search(r"\b(global|fortune 500|thousands of employees)\b", text):+ if count >= 200 or re.search(r"\b(fortune 500|thousands of employees)\b", text):return "large-enterprise"if count >= 35 or re.search(r"\b(series [cd]|public company)\b", text):return "growth"@@ -125,7 +149,11 @@ def _build_signal(theme: str, items: list[schema.SourceItem], size_tier: str) ->title for title in titlesif any(term in title.lower() for term in SENIORITY_TERMS)]- score = _confidence_score(len(items), len(set(departments)), len(senior_roles), size_tier)+ strategic_count = sum(1 for title in titles if _is_strategic_title(title))+ score = _confidence_score(+ len(items), len(set(departments)), len(senior_roles), size_tier,+ strategic_count=strategic_count,+ )evidence = [{"title": item.title,@@ -147,8 +175,17 @@ def _build_signal(theme: str, items: list[schema.SourceItem], size_tier: str) ->}-def _confidence_score(count: int, department_count: int, senior_count: int, size_tier: str) -> int:- score = count * 18 + min(department_count, 3) * 6 + senior_count * 8+def _confidence_score(+ count: int,+ department_count: int,+ senior_count: int,+ size_tier: str,+ strategic_count: int = 0,+) -> int:+ # Count no longer dominates: founding/first-of-function and seniority can+ # let a small cluster outrank a large generic one (a "new bet" beating+ # "doubling down"). The reasoning model still makes the final novelty call.+ score = count * 12 + min(department_count, 3) * 6 + senior_count * 10 + strategic_count * 14if size_tier == "startup":score += 20elif size_tier == "mid-market":@@ -189,6 +226,84 @@ def _interpretation(theme: str) -> str:return f"appears to be increasing focus on {theme}"+def _strategic_candidates(items: list[schema.SourceItem]) -> list[dict[str, Any]]:+ """Flag individual roles worth surfacing regardless of how many share a theme.++ Pure structural detection (founding, first-of-function, specialized+ qualifier, geographic novelty) - no semantic novelty judgment, which is+ left to the reasoning model. Guarantees these roles reach synthesis instead+ of being averaged away by count-weighting.+ """+ item_locations = [(item, _norm_location(item)) for item in items]+ location_counts = Counter(loc for _item, loc in item_locations if loc)+ dominant = max(location_counts.values()) if location_counts else 0++ scored: list[tuple[int, dict[str, Any]]] = []+ for item, location in item_locations:+ flags = _title_flags(item.title or "")+ if location and location_counts.get(location, 0) == 1 and dominant >= 3:+ flags.append("new-geo")+ if not flags:+ continue+ priority = (+ ("founding" in flags) * 4+ + ("new-geo" in flags) * 3+ + ("leadership" in flags) * 2+ + ("specialized" in flags) * 1+ )+ scored.append((priority, {+ "title": item.title,+ "url": item.url,+ "department": str(item.metadata.get("department") or item.container or "").strip(),+ "location": location,+ "published_at": item.published_at,+ "flags": flags,+ }))+ scored.sort(key=lambda pair: pair[0], reverse=True)+ return [candidate for _priority, candidate in scored[:10]]+++def _title_flags(title: str) -> list[str]:+ """Structural strategic flags derivable from a title alone (no geo)."""+ lowered = title.lower()+ flags: list[str] = []+ if "founding" in lowered or re.search(r"\bfirst\b", lowered):+ flags.append("founding")+ if any(term in lowered for term in LEADERSHIP_TERMS):+ flags.append("leadership")+ if _specialization(title):+ flags.append("specialized")+ return flags+++def _is_strategic_title(title: str) -> bool:+ return bool(_title_flags(title))+++def _specialization(title: str) -> str:+ """Return a specialized sub-domain qualifier from a title, or ''.++ "Research Scientist, Human Simulation" -> "Human Simulation".+ "Engineer (Forward Deployed)" -> "Forward Deployed".+ "Engineer, Senior" -> "" (generic level word, not a capability).+ """+ tail = ""+ paren = re.search(r"\(([^)]+)\)", title)+ if paren:+ tail = paren.group(1).strip()+ elif "," in title:+ tail = title.rsplit(",", 1)[1].strip()+ if not tail or len(tail) < 4:+ return ""+ if tail.lower() in _GENERIC_QUALIFIERS:+ return ""+ return tail+++def _norm_location(item: schema.SourceItem) -> str:+ return str(item.metadata.get("location") or "").strip().lower()++def _omitted_reason(items: list[schema.SourceItem],size_tier: str,diff --git a/skills/last30days/scripts/lib/jobs.py b/skills/last30days/scripts/lib/jobs.pyindex 1a320288..2b5c7774 100644--- a/skills/last30days/scripts/lib/jobs.py+++ b/skills/last30days/scripts/lib/jobs.py@@ -1,15 +1,54 @@-"""Public jobs/careers retrieval for Hiring Signals."""+"""Public jobs/careers retrieval for Hiring Signals.++Tiered strategy (each tier degrades gracefully; the artifact records which+tier produced results so synthesis knows the confidence level):++- Tier 1 - direct ATS API. The company's own board is authoritative and+ structured. Discovery is careers-page-first: fetch the careers page and read+ the provider + exact slug straight off the embed/link, then call that API.+ We only emit ATS results when a call actually returns a non-empty board, so a+ bad slug guess never produces fabricated coverage. Slug-probing is a fallback,+ never the entry point.+- Tier 2 - careers page found, no supported ATS API. Parse schema.org+ ``JobPosting`` JSON-LD (emitted by most careers pages for Google Jobs SEO,+ regardless of ATS).+- Tier 3 - generic web search. Last resort, noisy, clearly low-confidence.+"""from __future__ import annotations+import jsonimport refrom html import unescape-from typing import Any+from typing import Any, Callable+from urllib.parse import urlparse-from . import grounding, http+from . import dates, grounding, httpATS_PROVIDER_GREENHOUSE = "greenhouse"+ATS_PROVIDER_ASHBY = "ashby"+ATS_PROVIDER_LEVER = "lever"+ATS_PROVIDER_WORKABLE = "workable"+ATS_PROVIDER_SMARTRECRUITERS = "smartrecruiters"++# Detection patterns: map an ATS embed/link found on a careers page to+# (provider, slug). The published slug is authoritative - this is why discovery+# is careers-page-first rather than blind probing.+_ATS_LINK_PATTERNS: list[tuple[str, str]] = [+ (ATS_PROVIDER_ASHBY, r"(?:jobs|api)\.ashbyhq\.com/(?:posting-api/job-board/)?([A-Za-z0-9_.-]+)"),+ (ATS_PROVIDER_GREENHOUSE, r"boards(?:-api)?\.greenhouse\.io/(?:v1/boards/|embed/job_board\?for=)?([A-Za-z0-9_.-]+)"),+ (ATS_PROVIDER_GREENHOUSE, r"job-boards\.greenhouse\.io/([A-Za-z0-9_.-]+)"),+ (ATS_PROVIDER_GREENHOUSE, r"greenhouse\.io/embed/job_board\?for=([A-Za-z0-9_.-]+)"),+ (ATS_PROVIDER_LEVER, r"(?:jobs\.lever\.co|api\.lever\.co/v0/postings)/([A-Za-z0-9_.-]+)"),+ (ATS_PROVIDER_WORKABLE, r"apply\.workable\.com/(?:api/v[0-9]+/accounts/)?([A-Za-z0-9_.-]+)"),+ (ATS_PROVIDER_WORKABLE, r"([A-Za-z0-9_-]+)\.workable\.com"),+ (ATS_PROVIDER_SMARTRECRUITERS, r"(?:careers|jobs)\.smartrecruiters\.com/([A-Za-z0-9_.-]+)"),+ (ATS_PROVIDER_SMARTRECRUITERS, r"api\.smartrecruiters\.com/v1/companies/([A-Za-z0-9_.-]+)"),+]++# Tokens that show up in ATS URLs but are never real board slugs.+_SLUG_STOPWORDS = {"embed", "job_board", "v1", "v0", "api", "posting-api", "boards", "jobs", "job-boards", "www"}def search_jobs(@@ -21,46 +60,179 @@ def search_jobs(web_backend: str = "auto",explicit: bool = False,) -> tuple[list[dict[str, Any]], dict[str, Any]]:- """Fetch public job postings for a company.-- The first pass uses predictable public ATS endpoints. Generic web search is- only a fallback because web snippets are weaker evidence than structured- job posts.- """+ """Fetch public job postings for a company via the tiered strategy."""company = company.strip()if not company:return [], {}- items: list[dict[str, Any]] = []attempted: list[str] = []- for token in _greenhouse_board_tokens(company):- attempted.append(f"greenhouse:{token}")++ # --- Discovery: fetch the careers page and read the ATS off it (Tier 1). ---+ careers_html, careers_url = _resolve_careers_page(+ company, date_range, config, backend=web_backend,+ )+ provider, slug = (None, None)+ if careers_html:+ provider, slug = detect_ats(careers_html)+ if provider:+ attempted.append(f"careers:{provider}:{slug}")++ # Fallback discovery: cheap deterministic slug probe (only after careers-page+ # discovery fails - never the entry point).+ if not provider:+ provider, slug, probe_attempts = _probe_ats(company)+ attempted.extend(probe_attempts)++ # --- Tier 1: call the resolved ATS API. Trust it only if it has jobs. ---+ if provider and slug:try:- gh_items = search_greenhouse_board(token)- except http.HTTPError as exc:- if exc.status_code in {400, 401, 403, 404}:- continue- raise- if gh_items:- items.extend(gh_items)- break-- if not items:- fallback_items, artifact = search_jobs_web(- company, date_range, config, backend=web_backend,- )- items.extend(fallback_items)- if artifact:- artifact.setdefault("attempted", attempted)- return items, artifact+ items = _fetch_ats(provider, slug)+ except http.HTTPError:+ items = []+ if items:+ return items, _artifact("jobs", company, attempted, items, explicit,+ tier="ats", provider=provider, slug=slug)- return items, {- "label": "jobs",+ # --- Tier 2: parse JSON-LD JobPosting off the careers page. ---+ if careers_html:+ attempted.append("careers:jsonld")+ jsonld_items = extract_jsonld_jobs(careers_html, careers_url or "")+ if jsonld_items:+ return jsonld_items, _artifact("jobs", company, attempted, jsonld_items,+ explicit, tier="careers-jsonld")++ # --- Tier 3: generic web search (noisy, low-confidence). ---+ fallback_items, artifact = search_jobs_web(+ company, date_range, config, backend=web_backend,+ )+ artifact = dict(artifact or {})+ artifact.setdefault("attempted", attempted)+ artifact.update({+ "label": artifact.get("label", "jobs"),"company": company,- "attempted": attempted,- "resultCount": len(items),+ "tier": "web","explicit": explicit,+ "resultCount": len(fallback_items),+ })+ return fallback_items, artifact+++# --------------------------------------------------------------------------- #+# Careers-page discovery+# --------------------------------------------------------------------------- #++def _resolve_careers_page(+ company: str,+ date_range: tuple[str, str],+ config: dict[str, Any],+ *,+ backend: str = "auto",+) -> tuple[str | None, str | None]:+ """Find and fetch the company's careers page HTML.++ Tries conventional URLs on a guessed domain first (free, deterministic);+ falls back to a single web search for the careers page when a backend is+ configured. Returns (html, url) or (None, None). Never raises.+ """+ slug = _company_slug(company)+ candidates: list[str] = []+ if slug:+ for host in (f"{slug}.com", f"{slug}.ai", f"{slug}.io"):+ candidates.extend([f"https://{host}/careers", f"https://{host}/jobs"])++ for url in candidates:+ html = http.get_text(url, accept="text/html", retries=1)+ if html and _looks_like_careers_html(html):+ return html, url++ if backend != "none":+ careers_url = _search_for_careers_url(company, date_range, config, backend=backend)+ if careers_url:+ html = http.get_text(careers_url, accept="text/html", retries=1)+ if html:+ return html, careers_url++ return None, None+++def _search_for_careers_url(+ company: str,+ date_range: tuple[str, str],+ config: dict[str, Any],+ *,+ backend: str = "auto",+) -> str | None:+ """Use the configured web backend to locate the careers page URL."""+ try:+ raw_items, _ = grounding.web_search(+ f"{company} careers jobs", date_range, config, backend=backend,+ )+ except Exception:+ return None+ for raw in raw_items or []:+ if not isinstance(raw, dict):+ continue+ url = str(raw.get("url") or "").strip()+ if not url:+ continue+ lowered = url.lower()+ if any(token in lowered for token in (+ "career", "/jobs", "ashbyhq", "greenhouse", "lever.co", "workable", "smartrecruiters",+ )):+ return url+ return None+++def detect_ats(html: str) -> tuple[str | None, str | None]:+ """Read the ATS provider + slug off a careers page's embed/links."""+ if not html:+ return None, None+ for provider, pattern in _ATS_LINK_PATTERNS:+ for match in re.finditer(pattern, html):+ slug = match.group(1).strip().strip("/.")+ if slug and slug.lower() not in _SLUG_STOPWORDS:+ return provider, slug+ return None, None+++def _probe_ats(company: str) -> tuple[str | None, str | None, list[str]]:+ """Fallback: probe candidate slugs against ATS APIs (deterministic).++ Only reached when careers-page discovery fails. Returns the first provider+ whose API returns a non-empty board.+ """+ attempts: list[str] = []+ # Workable/SmartRecruiters are omitted here: their slugs rarely match the+ # company name, so blind probing is unreliable - they're reached only via+ # careers-page discovery, where the real slug is published.+ for slug in _candidate_slugs(company):+ for provider in (ATS_PROVIDER_GREENHOUSE, ATS_PROVIDER_ASHBY, ATS_PROVIDER_LEVER):+ attempts.append(f"probe:{provider}:{slug}")+ try:+ items = _fetch_ats(provider, slug)+ except http.HTTPError as exc:+ if exc.status_code in {400, 401, 403, 404}:+ continue+ raise+ if items:+ return provider, slug, attempts+ return None, None, attempts+++# --------------------------------------------------------------------------- #+# Tier 1: ATS API fetchers + parsers+# --------------------------------------------------------------------------- #++def _fetch_ats(provider: str, slug: str) -> list[dict[str, Any]]:+ fetchers: dict[str, Callable[[str], list[dict[str, Any]]]] = {+ ATS_PROVIDER_GREENHOUSE: search_greenhouse_board,+ ATS_PROVIDER_ASHBY: search_ashby_board,+ ATS_PROVIDER_LEVER: search_lever_board,+ ATS_PROVIDER_WORKABLE: search_workable_board,+ ATS_PROVIDER_SMARTRECRUITERS: search_smartrecruiters_board,}+ fetcher = fetchers.get(provider)+ return fetcher(slug) if fetcher else []def search_greenhouse_board(board_token: str) -> list[dict[str, Any]]:@@ -70,12 +242,259 @@ def search_greenhouse_board(board_token: str) -> list[dict[str, Any]]:jobs = data.get("jobs") if isinstance(data, dict) else []if not isinstance(jobs, list):return []- return [- _greenhouse_job_to_item(job, board_token)- for job in jobs- if isinstance(job, dict)- ]+ return [_greenhouse_job_to_item(job, board_token) for job in jobs if isinstance(job, dict)]++def search_ashby_board(slug: str) -> list[dict[str, Any]]:+ """Return jobs from Ashby's public posting API (needs a browser UA)."""+ url = f"https://api.ashbyhq.com/posting-api/job-board/{slug}"+ data = http.get(+ url,+ params={"includeCompensation": "true"},+ headers={"User-Agent": http.BROWSER_USER_AGENT},+ timeout=15,+ retries=2,+ )+ return parse_ashby_response(data, slug)+++def search_lever_board(slug: str) -> list[dict[str, Any]]:+ """Return jobs from Lever's public postings API (returns a JSON list)."""+ url = f"https://api.lever.co/v0/postings/{slug}"+ data = http.get(url, params={"mode": "json"}, timeout=15, retries=2)+ return parse_lever_response(data, slug)+++def search_workable_board(slug: str) -> list[dict[str, Any]]:+ """Return jobs from Workable's public widget API."""+ url = f"https://apply.workable.com/api/v3/accounts/{slug}/jobs"+ data = http.post(url, json_data={}, timeout=15, retries=2)+ return parse_workable_response(data, slug)+++def search_smartrecruiters_board(slug: str) -> list[dict[str, Any]]:+ """Return jobs from SmartRecruiters' public postings API."""+ url = f"https://api.smartrecruiters.com/v1/companies/{slug}/postings"+ data = http.get(url, params={"limit": "100"}, timeout=15, retries=2)+ return parse_smartrecruiters_response(data, slug)+++def parse_greenhouse_response(payload: dict[str, Any], board_token: str = "") -> list[dict[str, Any]]:+ """Parse a Greenhouse jobs payload for tests and callers with cached data."""+ jobs = payload.get("jobs") if isinstance(payload, dict) else []+ if not isinstance(jobs, list):+ return []+ return [_greenhouse_job_to_item(job, board_token) for job in jobs if isinstance(job, dict)]+++def parse_ashby_response(payload: dict[str, Any], slug: str = "") -> list[dict[str, Any]]:+ jobs = payload.get("jobs") if isinstance(payload, dict) else []+ if not isinstance(jobs, list):+ return []+ items: list[dict[str, Any]] = []+ for job in jobs:+ if not isinstance(job, dict):+ continue+ department = str(job.get("departmentName") or job.get("teamName") or "").strip()+ location = str(job.get("locationName") or job.get("location") or "").strip()+ description = _clean_html(str(job.get("descriptionHtml") or job.get("descriptionPlain") or ""))+ items.append(_ats_item(+ provider=ATS_PROVIDER_ASHBY,+ slug=slug,+ ident=str(job.get("id") or job.get("jobId") or ""),+ title=str(job.get("title") or "").strip(),+ url=str(job.get("jobUrl") or job.get("applyUrl") or "").strip(),+ description=description,+ date=_date_part(job.get("publishedDate") or job.get("publishedAt")),+ department=department,+ location=location,+ ))+ return items+++def parse_lever_response(payload: Any, slug: str = "") -> list[dict[str, Any]]:+ postings = payload if isinstance(payload, list) else []+ items: list[dict[str, Any]] = []+ for job in postings:+ if not isinstance(job, dict):+ continue+ categories = job.get("categories") if isinstance(job.get("categories"), dict) else {}+ department = str(categories.get("department") or categories.get("team") or "").strip()+ location = str(categories.get("location") or "").strip()+ description = _clean_html(str(job.get("descriptionPlain") or job.get("description") or ""))+ items.append(_ats_item(+ provider=ATS_PROVIDER_LEVER,+ slug=slug,+ ident=str(job.get("id") or ""),+ title=str(job.get("text") or "").strip(),+ url=str(job.get("hostedUrl") or job.get("applyUrl") or "").strip(),+ description=description,+ date=_epoch_ms_to_date(job.get("createdAt")),+ department=department,+ location=location,+ ))+ return items+++def parse_workable_response(payload: dict[str, Any], slug: str = "") -> list[dict[str, Any]]:+ results = []+ if isinstance(payload, dict):+ results = payload.get("results") or payload.get("jobs") or []+ if not isinstance(results, list):+ return []+ items: list[dict[str, Any]] = []+ for job in results:+ if not isinstance(job, dict):+ continue+ loc = job.get("location") if isinstance(job.get("location"), dict) else {}+ location = _join_parts(str(loc.get("city") or ""), str(loc.get("country") or ""))+ shortcode = str(job.get("shortcode") or "").strip()+ url = str(job.get("url") or job.get("application_url") or "").strip()+ if not url and shortcode and slug:+ url = f"https://apply.workable.com/{slug}/j/{shortcode}/"+ items.append(_ats_item(+ provider=ATS_PROVIDER_WORKABLE,+ slug=slug,+ ident=shortcode or str(job.get("id") or ""),+ title=str(job.get("title") or "").strip(),+ url=url,+ description=_clean_html(str(job.get("description") or "")),+ date=_date_part(job.get("published_on") or job.get("created_at")),+ department=str(job.get("department") or "").strip(),+ location=location,+ ))+ return items+++def parse_smartrecruiters_response(payload: dict[str, Any], slug: str = "") -> list[dict[str, Any]]:+ content = payload.get("content") if isinstance(payload, dict) else []+ if not isinstance(content, list):+ return []+ items: list[dict[str, Any]] = []+ for job in content:+ if not isinstance(job, dict):+ continue+ department = ""+ if isinstance(job.get("department"), dict):+ department = str(job["department"].get("label") or "").strip()+ location = ""+ if isinstance(job.get("location"), dict):+ location = _join_parts(+ str(job["location"].get("city") or ""),+ str(job["location"].get("country") or ""),+ )+ ident = str(job.get("id") or job.get("uuid") or "").strip()+ url = ""+ if isinstance(job.get("ref"), str):+ url = job["ref"]+ if not url and slug and ident:+ url = f"https://jobs.smartrecruiters.com/{slug}/{ident}"+ items.append(_ats_item(+ provider=ATS_PROVIDER_SMARTRECRUITERS,+ slug=slug,+ ident=ident,+ title=str(job.get("name") or "").strip(),+ url=url,+ description="",+ date=_date_part(job.get("releasedDate") or job.get("createdOn")),+ department=department,+ location=location,+ ))+ return items+++# --------------------------------------------------------------------------- #+# Tier 2: JSON-LD JobPosting crawler+# --------------------------------------------------------------------------- #++_JSONLD_RE = re.compile(+ r'<script[^>]+type=["\']application/ld\+json["\'][^>]*>(.*?)</script>',+ re.IGNORECASE | re.DOTALL,+)+++def extract_jsonld_jobs(html: str, base_url: str = "") -> list[dict[str, Any]]:+ """Extract schema.org JobPosting objects embedded as JSON-LD in a page."""+ if not html:+ return []+ domain = _domain(base_url)+ items: list[dict[str, Any]] = []+ seen: set[str] = set()+ for block in _JSONLD_RE.findall(html):+ for obj in _walk_jsonld(block):+ if not isinstance(obj, dict):+ continue+ if not _is_job_posting(obj):+ continue+ title = str(obj.get("title") or obj.get("name") or "").strip()+ if not title or title in seen:+ continue+ seen.add(title)+ items.append({+ "id": f"JL{len(items) + 1}",+ "title": title,+ "url": str(obj.get("url") or base_url or "").strip(),+ "description": _clean_html(str(obj.get("description") or ""))[:2000],+ "date": _date_part(obj.get("datePosted")),+ "date_confidence": "high" if obj.get("datePosted") else "low",+ "provider": "careers-jsonld",+ "department": str(obj.get("occupationalCategory") or "").strip(),+ "location": _jsonld_location(obj),+ "source_domain": domain,+ "relevance": 0.6,+ "why_relevant": "JobPosting structured data on careers page",+ })+ return items+++def _walk_jsonld(block: str) -> list[Any]:+ try:+ data = json.loads(block.strip())+ except (json.JSONDecodeError, ValueError):+ return []+ out: list[Any] = []+ stack = [data]+ while stack:+ node = stack.pop()+ if isinstance(node, list):+ stack.extend(node)+ elif isinstance(node, dict):+ out.append(node)+ graph = node.get("@graph")+ if isinstance(graph, list):+ stack.extend(graph)+ return out+++def _is_job_posting(obj: dict[str, Any]) -> bool:+ type_field = obj.get("@type")+ if isinstance(type_field, str):+ return type_field.lower() == "jobposting"+ if isinstance(type_field, list):+ return any(isinstance(t, str) and t.lower() == "jobposting" for t in type_field)+ return False+++def _jsonld_location(obj: dict[str, Any]) -> str:+ loc = obj.get("jobLocation")+ if isinstance(loc, list):+ loc = loc[0] if loc else None+ if isinstance(loc, dict):+ address = loc.get("address")+ if isinstance(address, dict):+ return _join_parts(+ str(address.get("addressLocality") or ""),+ str(address.get("addressRegion") or ""),+ str(address.get("addressCountry") or ""),+ )+ if obj.get("jobLocationType"):+ return str(obj.get("jobLocationType")).strip()+ return ""+++# --------------------------------------------------------------------------- #+# Tier 3: generic web search fallback+# --------------------------------------------------------------------------- #def search_jobs_web(company: str,@@ -115,16 +534,44 @@ def search_jobs_web(return items, artifact-def parse_greenhouse_response(payload: dict[str, Any], board_token: str = "") -> list[dict[str, Any]]:- """Parse a Greenhouse jobs payload for tests and callers with cached data."""- jobs = payload.get("jobs") if isinstance(payload, dict) else []- if not isinstance(jobs, list):- return []- return [- _greenhouse_job_to_item(job, board_token)- for job in jobs- if isinstance(job, dict)- ]+# --------------------------------------------------------------------------- #+# Item builders + helpers+# --------------------------------------------------------------------------- #++def _ats_item(+ *,+ provider: str,+ slug: str,+ ident: str,+ title: str,+ url: str,+ description: str,+ date: str | None,+ department: str,+ location: str,+) -> dict[str, Any]:+ prefix = {+ ATS_PROVIDER_ASHBY: "AB",+ ATS_PROVIDER_LEVER: "LV",+ ATS_PROVIDER_WORKABLE: "WK",+ ATS_PROVIDER_SMARTRECRUITERS: "SR",+ }.get(provider, "AT")+ return {+ "id": f"{prefix}{ident or slug}",+ "title": title,+ "url": url,+ "description": description,+ "date": date,+ "date_confidence": "high" if date else "low",+ "provider": provider,+ "board_token": slug,+ "department": department,+ "departments": [department] if department else [],+ "location": location,+ "offices": [location] if location else [],+ "relevance": 0.75,+ "why_relevant": f"Public {provider} job posting",+ }def _greenhouse_job_to_item(job: dict[str, Any], board_token: str) -> dict[str, Any]:@@ -160,17 +607,41 @@ def _greenhouse_job_to_item(job: dict[str, Any], board_token: str) -> dict[str,}-def _greenhouse_board_tokens(company: str) -> list[str]:+def _artifact(+ label: str,+ company: str,+ attempted: list[str],+ items: list[dict[str, Any]],+ explicit: bool,+ *,+ tier: str,+ provider: str = "",+ slug: str = "",+) -> dict[str, Any]:+ return {+ "label": label,+ "company": company,+ "attempted": attempted,+ "resultCount": len(items),+ "explicit": explicit,+ "tier": tier,+ "provider": provider,+ "board_token": slug,+ }+++def _candidate_slugs(company: str) -> list[str]:base = _company_slug(company)if not base:return []- suffixes = ("", "careers", "jobs")candidates = [base]- for suffix in suffixes[1:]:- candidates.append(f"{base}{suffix}")compact = re.sub(r"(inc|labs|ai|hq|app|tech)$", "", base)if compact and compact != base:candidates.append(compact)+ # hyphenated form (e.g. "listen labs" -> "listen-labs")+ hyphen = re.sub(r"[^a-z0-9]+", "-", company.lower()).strip("-")+ if hyphen and hyphen not in candidates:+ candidates.append(hyphen)deduped: list[str] = []for token in candidates:if token and token not in deduped:@@ -178,12 +649,24 @@ def _greenhouse_board_tokens(company: str) -> list[str]:return deduped[:4]+def _join_parts(*parts: str) -> str:+ """Join non-empty, stripped location parts as 'City, Country'."""+ return ", ".join(part.strip() for part in parts if part and part.strip())++def _company_slug(company: str) -> str:text = company.lower()text = re.sub(r"\b(inc|inc\.|llc|ltd|corp|corporation|company|co\.)\b", "", text)return re.sub(r"[^a-z0-9]+", "", text).strip()+def _domain(url: str) -> str:+ try:+ return urlparse(url).netloc.lower().lstrip("www.")+ except ValueError:+ return ""++def _date_part(value: Any) -> str | None:text = str(value or "")if not text:@@ -192,6 +675,16 @@ def _date_part(value: Any) -> str | None:return match.group(0) if match else None+def _epoch_ms_to_date(value: Any) -> str | None:+ try:+ ms = int(value)+ except (TypeError, ValueError):+ return None+ if ms <= 0:+ return None+ return dates.timestamp_to_date(ms / 1000)++def _clean_html(value: str) -> str:value = unescape(value)value = re.sub(r"<br\s*/?>", "\n", value, flags=re.I)@@ -201,6 +694,13 @@ def _clean_html(value: str) -> str:return value.strip()+def _looks_like_careers_html(html: str) -> bool:+ lowered = html.lower()+ if any(token in lowered for token in ("ashbyhq.com", "greenhouse.io", "lever.co", "workable.com", "smartrecruiters.com")):+ return True+ return bool(re.search(r"\b(open roles|open positions|join (our|the) team|current openings|jobposting)\b", lowered))++def _looks_like_jobs_page(title: str, url: str, snippet: str) -> bool:haystack = " ".join([title, url, snippet]).lower()return bool(re.search(r"\b(careers?|jobs?|job openings?|hiring|greenhouse|lever|ashby|workable)\b", haystack))diff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.pyindex 61fc3521..b0b81a15 100644--- a/skills/last30days/scripts/lib/normalize.py+++ b/skills/last30days/scripts/lib/normalize.py@@ -60,6 +60,13 @@ def normalize_source_items(if normalizer is None:raise ValueError(f"Unsupported source: {source}")normalized = [normalizer(source, item, index, from_date, to_date) for index, item in enumerate(items)]+ if source == "jobs":+ # A careers board is a snapshot of CURRENTLY OPEN roles. An open posting+ # is current evidence regardless of when it was posted, so date-windowing+ # it drops still-open roles (the "Founding Research Scientist, Human+ # Simulation" miss: 26 open roles filtered to 3 by a 30-day window).+ # Keep the full board; recency is annotated, not used to drop.+ return normalizedrequire_date = source == "grounding"filtered = filter_by_date_range(normalized, from_date, to_date, require_date=require_date)if filtered:diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex c482a694..0578c555 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -293,6 +293,10 @@ def run(# DEGRADED RUN banner when a named-entity topic was invoked bare# (source=deterministic AND no pre-research flags). LAW 7 backstop.bundle.artifacts["plan_source"] = plan_source+ # Hiring-signals is deliberately jobs-only with no multi-source --plan, so+ # the LAW 7 degraded-run and Step 0.55 pre-research banners do not apply -+ # they would contradict the documented jobs-scoped flow. Suppress them.+ bundle.artifacts["hiring_signals_mode"] = hiring_signals_mode# Project-mode or person-mode GitHub: run once before the main subquery loop_github_custom_done = False@@ -428,7 +432,11 @@ def run(freshness_mode=plan.freshness_mode,ranking_query=subquery.ranking_query,)- normalized = normalized[: settings["per_stream_limit"]]+ # Jobs is exempt from per_stream_limit: a careers board is a complete+ # snapshot of open roles, and truncating it to the default 12 drops+ # strategic postings (the whole point of hiring-signals coverage).+ if source != "jobs":+ normalized = normalized[: settings["per_stream_limit"]]bundle.add_items(subquery.label, source, normalized)if artifact:bundle.artifacts.setdefault("grounding", []).append(artifact)@@ -905,6 +913,8 @@ def _retry_thin_sources(freshness_mode=plan.freshness_mode,ranking_query=retry_subquery.ranking_query,)+ if source == "jobs":+ return source, normalizedreturn source, normalized[:settings["per_stream_limit"]]retryable = [s for s in thin_sources if s not in rate_limited_sources]diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.pyindex 2e38d083..59b5e02b 100644--- a/skills/last30days/scripts/lib/render.py+++ b/skills/last30days/scripts/lib/render.py@@ -434,6 +434,8 @@ def _render_pre_research_warning(report: schema.Report) -> list[str]:Returns empty list when flags are present or topic is not eligible."""+ if report.artifacts.get("hiring_signals_mode"):+ return []flags_present = bool(report.artifacts.get("pre_research_flags_present", False))if flags_present:return []@@ -478,6 +480,8 @@ def _render_degraded_run_warning(report: schema.Report) -> list[str]:user because Claude hid stderr. User-visible stdout block is thebackstop that makes silent degradation impossible."""+ if report.artifacts.get("hiring_signals_mode"):+ return []plan_source = report.artifacts.get("plan_source", "unknown")flags_present = bool(report.artifacts.get("pre_research_flags_present", False))if plan_source != "deterministic":@@ -1012,6 +1016,26 @@ def _render_hiring_signals(report: schema.Report) -> list[str]:link = f"[{title}]({url})" if url else titledetail = " | ".join(part for part in [dept, date] if part)out.append(f" - {link}" + (f" ({detail})" if detail else ""))++ strategic = summary.get("strategic_candidates") or []+ if strategic:+ out.append("")+ out.append(+ "- Strategic single-role signals (judge novelty yourself - a founding "+ "or first-of-function role can outweigh a whole department; in synthesis, "+ "distinguish \"new bets\" from \"doubling down\"):"+ )+ for cand in strategic[:8]:+ title = cand.get("title") or "Job posting"+ url = cand.get("url") or ""+ flags = ", ".join(cand.get("flags") or [])+ dept = cand.get("department") or ""+ location = cand.get("location") or ""+ date = cand.get("published_at") or "date unknown"+ link = f"[{title}]({url})" if url else title+ detail = " | ".join(part for part in [dept, location, date] if part)+ tag = f" [{flags}]" if flags else ""+ out.append(f" - {link}{tag}" + (f" ({detail})" if detail else ""))return out@@ -1299,6 +1323,9 @@ _FOOTER_SOURCES: list[tuple[str, str, str, str, list[tuple[str, str]]]] = [("truthsocial", "πΊπΈ", "Truth Social", "post", [("likes", "likes"), ("reposts", "reposts")]),("github", "π", "GitHub", "item", [("reactions", "reactions"), ("comments", "comments")]),("digg", "βοΈ", "Digg", "cluster", [("postCount", "posts"), ("uniqueAuthors", "authors")]),+ # Jobs must appear so a scoped --hiring-signals run (jobs-only) still emits+ # the LAW 5 footer; without it the footer was dropped entirely.+ ("jobs", "πΌ", "Jobs", "role", []),]diff --git a/tests/test_hiring_signals.py b/tests/test_hiring_signals.pyindex 5f517b3e..b6199d62 100644--- a/tests/test_hiring_signals.py+++ b/tests/test_hiring_signals.py@@ -45,6 +45,43 @@ class HiringSignalsTests(unittest.TestCase):self.assertTrue(summary["include"])self.assertEqual("low", summary["signals"][0]["confidence"])+ def test_founding_specialized_role_surfaces_as_strategic_candidate(self):+ # The exact 2026-06-15 miss: one strategic role amid many generic ones.+ items = [+ job("Software Engineer", "backend services", "Engineering"),+ job("Software Engineer, Backend", "platform", "Engineering"),+ job("Software Engineer, Frontend", "ui", "Engineering"),+ job("Founding Research Scientist, Human Simulation", "simulate users", "Research"),+ ]+ summary = hiring_signals.analyze(items, explicit=True, topic="Listen Labs")+ titles = [c["title"] for c in summary["strategic_candidates"]]+ self.assertIn("Founding Research Scientist, Human Simulation", titles)+ top = summary["strategic_candidates"][0]+ self.assertEqual("Founding Research Scientist, Human Simulation", top["title"])+ self.assertIn("founding", top["flags"])+ self.assertIn("specialized", top["flags"])++ def test_specialization_ignores_generic_level_qualifiers(self):+ self.assertEqual("", hiring_signals._specialization("Engineer, Senior"))+ self.assertEqual("Human Simulation", hiring_signals._specialization("Research Scientist, Human Simulation"))+ self.assertEqual("Forward Deployed", hiring_signals._specialization("Engineer (Forward Deployed)"))++ def test_new_geo_flag_for_rare_location(self):+ def loc_job(title, location):+ it = job(title, "work", "Engineering")+ it.metadata["location"] = location+ return it+ items = [+ loc_job("Engineer A", "San Francisco"),+ loc_job("Engineer B", "San Francisco"),+ loc_job("Engineer C", "San Francisco"),+ loc_job("Growth Lead", "New York"),+ ]+ summary = hiring_signals.analyze(items, explicit=True, topic="Acme")+ ny = [c for c in summary["strategic_candidates"] if c["location"] == "new york"]+ self.assertTrue(ny)+ self.assertIn("new-geo", ny[0]["flags"])+if __name__ == "__main__":unittest.main()diff --git a/tests/test_jobs_source.py b/tests/test_jobs_source.pyindex 22ed184d..b8bb6ceb 100644--- a/tests/test_jobs_source.py+++ b/tests/test_jobs_source.py@@ -29,8 +29,10 @@ class JobsSourceTests(unittest.TestCase):self.assertIn("SSO", item["description"])self.assertEqual("greenhouse", item["provider"])+ @patch("lib.jobs.http.get_text", return_value=None)@patch("lib.jobs.http.get")- def test_greenhouse_404_degrades_to_empty(self, mock_get):+ def test_all_ats_miss_degrades_to_empty(self, mock_get, _mock_text):+ # No careers page (get_text None), no web backend, every ATS probe 404s.mock_get.side_effect = jobs.http.HTTPError("missing", status_code=404)items, artifact = jobs.search_jobs("MissingCo",@@ -40,7 +42,151 @@ class JobsSourceTests(unittest.TestCase):)self.assertEqual([], items)self.assertEqual(0, artifact["resultCount"])+ self.assertEqual("web", artifact["tier"])++ def test_detect_ats_reads_provider_and_slug_from_embed(self):+ html = '<a href="https://jobs.ashbyhq.com/listenlabs/4b17">Open roles</a>'+ provider, slug = jobs.detect_ats(html)+ self.assertEqual("ashby", provider)+ self.assertEqual("listenlabs", slug)++ def test_detect_ats_handles_greenhouse_embed_query(self):+ html = '<script src="https://boards.greenhouse.io/embed/job_board?for=acmeco"></script>'+ provider, slug = jobs.detect_ats(html)+ self.assertEqual("greenhouse", provider)+ self.assertEqual("acmeco", slug)++ def test_detect_ats_returns_none_when_no_ats(self):+ self.assertEqual((None, None), jobs.detect_ats("<html><body>About us</body></html>"))++ def test_parse_ashby_response_core_fields(self):+ payload = {+ "jobs": [+ {+ "id": "abc",+ "title": "Founding Research Scientist, Human Simulation",+ "departmentName": "Research",+ "locationName": "San Francisco",+ "publishedDate": "2026-06-10",+ "jobUrl": "https://jobs.ashbyhq.com/listenlabs/abc",+ "descriptionPlain": "Build human simulation models.",+ }+ ]+ }+ parsed = jobs.parse_ashby_response(payload, slug="listenlabs")+ self.assertEqual(1, len(parsed))+ item = parsed[0]+ self.assertEqual("Founding Research Scientist, Human Simulation", item["title"])+ self.assertEqual("Research", item["department"])+ self.assertEqual("2026-06-10", item["date"])+ self.assertEqual("ashby", item["provider"])++ def test_parse_lever_response_handles_list_and_epoch(self):+ payload = [+ {+ "id": "xyz",+ "text": "Staff Engineer",+ "hostedUrl": "https://jobs.lever.co/acme/xyz",+ "categories": {"department": "Engineering", "location": "Remote"},+ "createdAt": 1749513600000,+ "descriptionPlain": "Own the platform.",+ }+ ]+ parsed = jobs.parse_lever_response(payload, slug="acme")+ self.assertEqual(1, len(parsed))+ self.assertEqual("Staff Engineer", parsed[0]["title"])+ self.assertEqual("Engineering", parsed[0]["department"])+ self.assertRegex(parsed[0]["date"], r"\d{4}-\d{2}-\d{2}")+ self.assertEqual("lever", parsed[0]["provider"])++ def test_parse_smartrecruiters_response_core_fields(self):+ payload = {+ "content": [+ {+ "id": "777",+ "name": "Account Executive",+ "department": {"label": "Sales"},+ "location": {"city": "New York", "country": "us"},+ "releasedDate": "2026-06-02T00:00:00.000Z",+ }+ ]+ }+ parsed = jobs.parse_smartrecruiters_response(payload, slug="acme")+ self.assertEqual(1, len(parsed))+ self.assertEqual("Account Executive", parsed[0]["title"])+ self.assertEqual("Sales", parsed[0]["department"])+ self.assertEqual("2026-06-02", parsed[0]["date"])+ self.assertEqual("smartrecruiters", parsed[0]["provider"])++ def test_extract_jsonld_jobs_parses_jobposting(self):+ html = (+ '<script type="application/ld+json">'+ '{"@context":"https://schema.org","@type":"JobPosting",'+ '"title":"Product Designer","datePosted":"2026-06-05",'+ '"description":"<p>Design things.</p>",'+ '"url":"https://acme.com/jobs/1",'+ '"jobLocation":{"@type":"Place","address":{"@type":"PostalAddress",'+ '"addressLocality":"SF","addressCountry":"US"}}}'+ '</script>'+ )+ parsed = jobs.extract_jsonld_jobs(html, "https://acme.com/careers")+ self.assertEqual(1, len(parsed))+ self.assertEqual("Product Designer", parsed[0]["title"])+ self.assertEqual("2026-06-05", parsed[0]["date"])+ self.assertEqual("careers-jsonld", parsed[0]["provider"])+ self.assertIn("SF", parsed[0]["location"])++ def test_extract_jsonld_jobs_handles_graph_arrays(self):+ html = (+ '<script type="application/ld+json">'+ '{"@graph":[{"@type":"Organization","name":"Acme"},'+ '{"@type":"JobPosting","title":"GTM Lead","datePosted":"2026-06-01"}]}'+ '</script>'+ )+ parsed = jobs.extract_jsonld_jobs(html, "https://acme.com/careers")+ self.assertEqual(1, len(parsed))+ self.assertEqual("GTM Lead", parsed[0]["title"])if __name__ == "__main__":unittest.main()+++class JobsDateAndBannerTests(unittest.TestCase):+ def test_jobs_keep_open_roles_outside_date_window(self):+ from lib import normalize+ raw = [+ {"id": "1", "title": "Founding Research Scientist", "url": "https://x/1",+ "date": "2026-01-10", "provider": "ashby"}, # posted months ago, still open+ {"id": "2", "title": "Account Executive", "url": "https://x/2",+ "date": "2026-06-10", "provider": "ashby"}, # within window+ ]+ items = normalize.normalize_source_items("jobs", raw, "2026-05-17", "2026-06-16")+ titles = [i.title for i in items]+ self.assertIn("Founding Research Scientist", titles) # not dropped by date window+ self.assertEqual(2, len(items))+++class JobsDedupeTests(unittest.TestCase):+ def test_jobs_dedupe_by_url_not_fuzzy_boilerplate(self):+ from lib import dedupe, schema+ # Distinct roles sharing heavy boilerplate but with unique URLs.+ boiler = "TL;DR: Listen Labs is a fast-growing early-stage startup. Roll up your sleeves."+ items = [+ schema.SourceItem(item_id=f"AB{i}", source="jobs", title=t, body=boiler,+ url=f"https://jobs.ashbyhq.com/listenlabs/{i}")+ for i, t in enumerate(["Founding Research Scientist", "Account Executive",+ "Growth Associate", "Business Development Rep"])+ ]+ kept = dedupe.dedupe_items(items)+ self.assertEqual(4, len(kept)) # all distinct URLs survive++ def test_jobs_dedupe_collapses_same_url(self):+ from lib import dedupe, schema+ items = [+ schema.SourceItem(item_id="AB1", source="jobs", title="Role", body="x",+ url="https://jobs.ashbyhq.com/listenlabs/1"),+ schema.SourceItem(item_id="AB1b", source="jobs", title="Role", body="x",+ url="https://jobs.ashbyhq.com/listenlabs/1"),+ ]+ self.assertEqual(1, len(dedupe.dedupe_items(items)))diff --git a/tests/test_render_hiring_signals.py b/tests/test_render_hiring_signals.pyindex 232961da..95fb8186 100644--- a/tests/test_render_hiring_signals.py+++ b/tests/test_render_hiring_signals.py@@ -89,3 +89,58 @@ class RenderHiringSignalsTests(unittest.TestCase):if __name__ == "__main__":unittest.main()+++class JobsFooterTests(unittest.TestCase):+ def test_jobs_only_run_still_emits_law5_footer(self):+ report = schema.Report(+ topic="Listen Labs",+ range_from="2026-05-16",+ range_to="2026-06-16",+ generated_at="2026-06-16T00:00:00Z",+ provider_runtime=schema.ProviderRuntime("mock", "mock", "mock"),+ query_plan=schema.QueryPlan(+ intent="product", freshness_mode="balanced_recent", cluster_mode="none",+ raw_topic="Listen Labs", subqueries=[], source_weights={},+ ),+ clusters=[], ranked_candidates=[],+ items_by_source={+ "jobs": [+ schema.SourceItem(+ item_id="AB1", source="jobs",+ title="Founding Research Scientist, Human Simulation",+ body="", url="https://jobs.ashbyhq.com/listenlabs/abc",+ engagement={"open_roles": 1},+ )+ ]+ },+ errors_by_source={},+ artifacts={},+ )+ footer = "\n".join(render._render_emoji_footer(report, "/tmp/x.md"))+ self.assertIn("All agents reported back", footer)+ self.assertIn("Jobs: 1 role", footer)+++class HiringSignalsBannerSuppressionTests(unittest.TestCase):+ def _report(self):+ return schema.Report(+ topic="Listen Labs", range_from="2026-05-16", range_to="2026-06-16",+ generated_at="2026-06-16T00:00:00Z",+ provider_runtime=schema.ProviderRuntime("mock", "mock", "mock"),+ query_plan=schema.QueryPlan(+ intent="concept", freshness_mode="evergreen_ok", cluster_mode="none",+ raw_topic="Listen Labs", subqueries=[], source_weights={}),+ clusters=[], ranked_candidates=[], items_by_source={}, errors_by_source={},+ artifacts={"plan_source": "deterministic", "hiring_signals_mode": True},+ )++ def test_hiring_signals_suppresses_degraded_and_pre_research_banners(self):+ report = self._report()+ self.assertEqual([], render._render_degraded_run_warning(report))+ self.assertEqual([], render._render_pre_research_warning(report))++ def test_non_hiring_named_entity_still_warns(self):+ report = self._report()+ report.artifacts["hiring_signals_mode"] = False+ self.assertTrue(render._render_degraded_run_warning(report))