diff --git a/.forge/features/career-job-ingestion/spec.md b/.forge/features/career-job-ingestion/spec.md new file mode 100644 index 000000000..dd7bb0ac8 --- /dev/null +++ b/.forge/features/career-job-ingestion/spec.md @@ -0,0 +1,88 @@ +# Career job ingestion + +Status: Approved (2026-11-17), amended 2026-11-19 after review (pending approval) + +## User-facing purpose + +Part of #633. Turns raw listings from every job feed and board into one clean, +deduplicated set of jobs, so Career search (#651/#655) and Discord posts (#654) +show each real opening once with a usable company, track, category, location +and apply link. Adds no UI of its own. + +## Users / actors + +- Members see the results in Career search and in job pings or posts. +- Cron (#652/#653) hands each source's listings to ingestion. +- Officers see no direct surface. Source health reporting belongs to #653. + +## User-visible interface + +- A job seen on several feeds or boards appears once. +- Each job shows its company, title, track (internship or new grad), category, + apply link, and every location the sources gave. Unparsed location text shows + as written. +- Jobs that are no longer posted drop out of default search but stay on members' + applications. +- Discord shows nothing from the first run of a new source. After that, new jobs + go out once. + +## Scope + +### In scope + +- Group listings by company and merge the same job seen across sources. +- Decide the track, classify the role category, and parse U.S. locations. +- Record when a job was first and last seen, and whether it's still active. +- Silent first-run baseline for each source. + +### Out of scope + +- Fetching or parsing feeds (#652), polling and failure handling (#653), + sending to Discord (#654), alert matching (#650), and search (#651). +- An officer view of ingest results. Cron gets counts only. +- Fuzzy title matching across sources. +- Non-U.S. jobs. +- Reposting a reopened job. +- Importing old CS Job Poster data. +- Creating or approving Guild companies. + +## Vocabulary + +- `source`: one feed or employer board, such as a GitHub list or a Greenhouse board. +- `listing`: one entry from one source. +- `job`: the single opening that one or more listings describe. +- `full inventory` vs `rolling feed`: a full inventory lists every open role, so + a missing listing means the role closed. A rolling feed doesn't, so a missing + listing proves nothing. +- `baseline`: a source's first successful run, which is recorded but never posted. + +## Acceptance criteria + +- The same opening from two sources appears as one job, except when the first + listing has only an aggregator link (known limit, see SRD). +- Rerunning an unchanged source changes nothing a member can see. +- Listings that are neither internship nor new grad, or that are only outside + the U.S., never appear. +- A city, a state, U.S. remote, several locations, and unparsed text all display + correctly. +- A job missing from a full inventory goes inactive. A job missing from a rolling + feed doesn't. +- A closed job that reappears is active again, with no second Discord post. +- When sources disagree on track, the first accepted track stays, and a track + change never causes another post. +- Title, description, posted date and compensation follow the latest listing + that provides them; a feed without them doesn't erase them. The employer's own + apply link wins over an aggregator's. +- Two postings that share a generic careers link stay two jobs. +- A job whose listing no longer qualifies (for example, its title becomes + "Senior…") goes inactive on a full inventory. +- An older, delayed run never reopens a job a newer run closed. +- One malformed listing doesn't block the rest of its source. +- A new source's first run posts nothing. New jobs after that are queued for + Discord once, and only if that track has a channel configured. + +## Open questions + +- None. Resolved 2026-11-19: upstream's "recent catch-up" of baseline jobs is not + ported. A new source's first run stays fully silent; those jobs are still + searchable. diff --git a/.forge/features/career-job-ingestion/srd.md b/.forge/features/career-job-ingestion/srd.md new file mode 100644 index 000000000..9034c5530 --- /dev/null +++ b/.forge/features/career-job-ingestion/srd.md @@ -0,0 +1,191 @@ +# Career job ingestion SRD + +Status: Draft, awaiting human review + +## Technical purpose + +`@forge/api` owns the job rules for #633. Cron hands `ingestJobSnapshot` one +source's parsed snapshot. Ingestion classifies, deduplicates, and writes `Job`, +`JobObservation`, `JobLocation`, and `JobSource` state. It doesn't fetch, poll, +or send anything. + +## Relevant principles + +- Keep pure rules (normalize, classify, locations) separate from DB writes so they + can be unit-tested without a database (forge-api "where workflow logic lives"). +- No Discord calls. Ingestion only sets delivery state for #654 to claim. +- Reuse `normalizeCompanyName` (`@forge/validators`) and the U.S. city catalog + (`utils/career/us-cities.ts`). + +## Access policy + +There is no tRPC procedure. The service is exported only through +`@forge/api/job-board.server`, following the `discord-archive.server` pattern, +for cron. Nothing in Blade imports it. + +## Architecture / data flow + +1. Cron adapter (#652) builds a `CareerJobSourceSnapshot` and passes it as is. + Cron must not gate on `careerJobSourceSnapshotSchema`: it rejects the whole + snapshot for one bad listing, while ingestion validates the envelope and then + each listing on its own. +2. Cron reads channel IDs from the #648 config keys and calls + `ingestJobSnapshot(snapshot, destinations)`. +3. Ingestion rejects the snapshot if `complete` is false, or if the snapshot's + envelope (source, fetchedAt, inventory) is invalid. Otherwise it finds or + creates the `JobSource` row by (provider, boardKey). +4. Each listing is validated on its own (an invalid one is counted as + `invalid_listing`, and the rest still ingest), then goes through a pure prepare step: clean the apply URL, decide the + track, parse locations, classify the category, and build the company key and + the identity keys. A rejected listing is counted by reason. +5. Each accepted listing then runs in its own transaction: + - Find the job by observation (sourceId + externalId), then by any identity + key, and insert one only if neither exists. + - Insert or update the observation. + - Refresh the job's fields and add any new location rows. +6. If `inventory = "full"`, observations missing from this run close. A job with + no open observations goes inactive. +7. A successful run sets `baselineCompletedAt` (if unset) and `lastSuccessAt`. + Attempts and errors (`lastAttemptAt`, `lastError`) belong to #653. + +### Identity + +- Candidate keys, strongest first: + - `ats:greenhouse:`, `ats:lever:`, `ats:ashby:`, `ats:workday::` from the apply URL; + - `url:`, only when the URL identifies one posting: some + path segment has a non-year digit right after a posting route (`/jobs/1234/title`, + `/j/AB12CD` on Workable, `/careers/123` on BambooHR), or a non-year run of 4+ + digits on its own, or an ID-named query parameter (`jobId`, `job`, `gh_jid`) + has a digit. Years and page numbers never count, so `/careers/2026`, + `/careers/summer-2026` and `/jobs/page-2` are landing pages. A hash route + (`#/jobs/42`) is kept, cleaned like the path, and counts as the path. An + aggregator URL is never an identity. ATS keys need the ATS's own domain (or + a subdomain); Greenhouse IDs must be numeric and a Workday key needs a + `_` suffix and a tenant (the first host label, or the path + segment after `recruiting` on shared hosts; no key on `www`/`wdN` hosts + without one). A filter parameter such as `department_id` is not a posting + ID; + - `source:["","",""]` (JSON, so a `:` inside + a part can't make two keys equal). +- A new job's `identityKey` is the strongest key it has. Lookup tries every key, so + a later source with a stronger key still finds the job. +- Lookups compare the hash column (Node SHA-256 of the UTF-8 key, which matches + the generated column) and also compare the raw key. A row with a matching hash + but a different raw key is an error. +- A job insert uses `ON CONFLICT (identity_hash) DO NOTHING` and selects the row + again, so two concurrent ingests produce one job. +- Company and title never form an identity. +- Known limit: if an aggregator listing (source key only) creates a job and an + employer board later lists the same posting, the two share no ID, so they + don't match and the job is posted twice. Storing more keys per job wouldn't + help, and upgrading a job's key in place rarely fires because #652 falls back + to the apply URL as `externalId`. Mitigations live outside #649: adapters + send the employer link when a feed row has one (#652), and a company + title + posting guard (#654, needs lead sign-off). + +### Field rules + +- `track`: on a new job, use the adapter's track if given, otherwise classify it + from the title. On an existing job it never changes. +- `title`, `description`, `compensation`, `postedAt`, `category`: take the latest + listing's values. Description and compensation aren't overwritten with null. +- `applyUrl`: keep the employer's own link over an aggregator's (jobright, + simplify, speedyapply). Otherwise take the latest. +- `companyLabel` and `companyKey` come from the first listing. `companyId` is set + when an approved `Company` matches the job's own `companyKey` by + `normalizedDisplayName` or by a normalized alias. Ingestion doesn't follow + `mergedIntoCompanyId`; API reads resolve company merges (#647). Ingestion + never inserts a `Company`. +- A job that reappears gets `active = true` and `inactiveAt = null`. Its delivery + state and receipt stay as they were, so it isn't posted again. It reopens only + when the sighting leaves its observation open and is newer than the job's + closing; a stale snapshot doesn't reopen either, or replace newer job details + or observation metadata. +- A listing rejected this run counts as unseen, so a full inventory closes its + job. + +### Concurrency + +- Callers run one ingest per source at a time, holding the `JobSource` claim + (#647 claim columns, #653 polling). Runs of different sources may overlap: + job row locks (taken in id order, before closing observations) and insert + conflict handling keep that correct. +- Two runs of the same source at once, or an older snapshot finishing after a + newer one, are guarded only where it's cheap: closures are limited to locked + jobs, the baseline is set by one conditional update, and stale sightings don't + reopen jobs or overwrite metadata. A concurrent same-source run can still + create a duplicate job, or re-add a posting a newer full inventory dropped; + the claim prevents those. + +### Delivery state on insert + +- The job is `pending`, with `deliveryTrack = track` and `discordChannelId` set, + only when the source already has `baselineCompletedAt` and + `destinations[track]` is set. +- Otherwise it keeps the default `suppressed`. + +### Track and location rejection + +- `not_student_role`: there's no adapter track, the title has no internship or + new-grad signal, or the title carries a seniority signal (senior, staff, + principal, director, vp, architect). +- `non_us`: every location is explicitly outside the U.S. Any U.S. evidence (a + state code, state name, or "US") keeps a text in scope, so "London, KY" and + "ON-SITE - Austin, TX" stay. A province code counts only after a comma. +- `invalid_apply_url`: the URL has credentials or isn't http(s). +- `invalid_listing`: the listing fails the schema, or its company label has no + ASCII letters or digits to build a company key from. The schema rejects NUL and + lone surrogates in any stored text (including `sourceUrl`) and anywhere in + `sourceData`. Postgres can't store NUL, and stores a lone surrogate as U+FFFD, + so a stored ID would no longer equal the listing's and every later run would + fail its identity check. +- Locations: "A or B" splits only when both sides are "City, ST" places, so + "US or Canada (Remote)" stays one `remote_us` location. +- No locations, or unparsed text, keeps the job with an `unknown` location. + +## tRPC/API behavior + +No procedures. `ingestJobSnapshot` returns: + +``` +{ created, updated, rejected: Record, deactivated, baselined } +``` + +## Validation + +Add `careerJobSourceSnapshotSchema` and its inferred type to +`packages/validators/src/job-board.ts`. The fields are the ones agreed in #633: +`source`, `fetchedAt`, `complete`, `inventory`, and `listings[]` with optional +`track`, `postedAt`, `description`, and `compensation`. Listings are strict (an +unknown field rejects that listing). A description longer than 20,000 +characters is truncated, not rejected. + +## Data / migration / compatibility + +No schema change. Uses the 0065 tables as merged. #670 also writes to +`utils/job-board/` with different file names. + +## Discord integration + +None. #654 claims `pending` rows. + +## Configurability review + +The channel for each track comes from DiscordConfig through the caller. Sources +are rows, not code constants. Category regexes and aggregator hosts are +code-owned rules, like upstream. + +## React / frontend constraints + +None. + +## Testing / verification strategy + +- Unit tests (no database) for normalize, classify, and locations, with fixtures + for each source type. +- Database tests through `provisionDisposableDatabase` cover the ingest flow and + are skipped when no loopback DB is available. + +## Open questions + +- Resolved 2026-11-19: upstream's recent catch-up of baseline jobs is not ported. diff --git a/.forge/features/career-job-ingestion/status.md b/.forge/features/career-job-ingestion/status.md new file mode 100644 index 000000000..13fb08267 --- /dev/null +++ b/.forge/features/career-job-ingestion/status.md @@ -0,0 +1,54 @@ +# Career job ingestion Status + +Current phase: Implemented; review fixes applied, awaiting human review (fixes not committed) + +> This file is the maintained progress tracker for the feature/change. Keep it current whenever decisions, tasks, validation, or open questions change. + +## Decision log + +- 2026-11-13: Cross-source dedupe matches only on IDs: ATS requisition keys and the normalized apply URL, with a source-scoped key as the fallback. No fuzzy or company/title matching, per the #647 SRD. +- 2026-11-13: The API classifies track from the title, using the adapter's track when one is given. Listings that are neither internship nor new grad are rejected. +- 2026-11-13: Listings whose only locations are explicitly outside the U.S. are rejected. Location text that can't be parsed is kept as `unknown`. +- 2026-11-13: Before a source's first successful run finishes, its jobs stay `suppressed`. After that, new jobs become `pending` with a frozen track and the channel that cron passes in. A track with no channel stays `suppressed`. +- 2026-11-17: A closed job that reappears becomes active again with no second Discord post, following #647's one-post-per-job rule. The user first picked "repost", then chose to follow #647 because of spam risk from flaky boards. +- 2026-11-17: When sources disagree on track, the track from the first accepted listing stays. A changed track never causes a repost. +- 2026-11-17: Title, description and compensation update from the latest listing. Apply links prefer the employer's own page over an aggregator. Track and first-seen date never change. +- 2026-11-17: No officer view of ingest results. Ingestion returns counts, including rejections by reason, to cron, and #653 decides how to report them. +- 2026-11-17: Build on the `CareerJobSourceSnapshot` shape from the #652 branch instead of a separate draft. +- 2026-11-19: forge-review (standard) fixes: landing-page and generic Workday URLs are no identity; stale snapshots don't reopen closed jobs; U.S. evidence beats foreign words; each listing is validated alone (`invalid_listing`); long descriptions truncate; company keys always pass `companyKeySchema`. +- 2026-11-28: forge-review of the round-2 fixes: restored URL identity for Workable/BambooHR/slug/iCIMS-style postings (posting route anywhere in the path, years and page numbers excluded); " or " splits only between "City, ST" places; hash routes cleaned like paths; `sourceUrl` NUL check; jsonb check now per string (allows escaped text, rejects lone surrogates). Tests tightened; every fix confirmed by a deliberate break. +- 2026-11-28: CodeRabbit round 2 (18 findings) checked against spec/SRD/#647. Fixed: "constructor" lookups, Greenhouse/Workday domain checks, landing-page paths (`/careers/2026`), hash-route links, " or " location splits, NUL in listings, company match by the job's own key, reopen only with an open observation. Cheap same-source guards: closures limited to locked jobs, conditional baseline, stale observation metadata. Pushed back: persisting learned keys (known limit), same-source concurrent duplicates (JobSource claim, #647/#653). Deferred: batching lookups (performance only). Docs: merges are resolved by API reads; cron passes snapshots as is. +- 2026-11-29: Pre-push forge-review: lone surrogates rejected in every text field (they would make a stored `externalId` mismatch on the next run and stall the source); Workday keys need a real tenant (shared `myworkdaysite.com` hosts read it from the path); `*_id` filter params (`department_id`) no longer make a URL identity; `#//` hash routes no longer throw. Tests added for ATS-only cross-source merge (TC-009), job-level stale reopen (TC-037) and concurrent two-source close (TC-038); every fix confirmed by a deliberate break. Not changed: Ashby/Lever `/embed` keys, foreign cities with no country, plural "Interns" titles, and TC-035 with channels (a run that starts after the other's baseline may legitimately queue). +- 2026-11-19: Spec amended after review: aggregator-first duplicate limit, null-safe detail updates, and four new acceptance criteria (landing-page links, rejected listings close, stale runs don't reopen, malformed listings don't block a source). +- 2026-11-19: A listing rejected this run counts as unseen, so a full inventory closes its job. +- 2026-11-19: Known limit: an aggregator-first job and a later employer listing of the same posting share no ID, so they aren't matched. No change in #649 fixes it: a per-job key table wouldn't help, and in-place key upgrades rarely fire because #652 uses the apply URL as `externalId` when a row has no ID. Mitigations to propose: employer links from adapters (#652) and a company + title posting guard (#654). + +## Open questions + +- Resolved 2026-11-17: #652 owner replied "LGTM" to the contract (https://github.com/KnightHacks/forge/issues/633#issuecomment-6961617503): split `complete` into `complete` plus `inventory: "full" | "rolling"`, look up or create `JobSource` by provider and boardKey, make `track` optional, and move the zod schema into `@forge/validators`. +- Resolved 2026-11-19: upstream's "recent catch-up" posting of first-run jobs is not ported; the baseline stays fully silent, matching #649's "silent first-run baseline". + +## Task list + +- [x] Agree the snapshot contract in #633. +- [x] Complete reverse-prompting for `spec.md`. +- [ ] Human review of `srd.md` (drafted from the approved plan, not reverse-prompted). +- [ ] Human review of `test-cases.md` (drafted from the approved plan, not reverse-prompted). +- [ ] Human approves the full artifact bundle (spec approved 2026-11-17). +- [x] Pure functions: normalize, classify, locations (+ `findUsCity`). +- [x] `ingest.ts` + `job-board.server.ts` export. +- [x] Tests: per-source fixtures + DB ingest scenarios. + +## Validation / commands + +- 2026-11-17 `pnpm format`: pass +- 2026-11-17 `pnpm lint`: pass (0 errors; one max-lines warning in the new integration test) +- 2026-11-17 `pnpm typecheck`: pass (33/33) +- 2026-11-17 `@forge/api` vitest, full suite against local PostgreSQL 16: 151 files, 1248 tests pass, including 13 rule tests and 12 ingest DB tests +- 2026-11-17 `@forge/validators` vitest: 29 files, 380 tests pass + +## Links + +- PRs: #670 (#651 router, shares `utils/job-board/`) +- Issues: #633, #649, #652 (branch `career/job-poster-to-cron`), #653, #654 +- Discord/thread context: diff --git a/.forge/features/career-job-ingestion/test-cases.md b/.forge/features/career-job-ingestion/test-cases.md new file mode 100644 index 000000000..62ba12a8f --- /dev/null +++ b/.forge/features/career-job-ingestion/test-cases.md @@ -0,0 +1,70 @@ +# Career job ingestion Test Cases + +Status: Draft, awaiting human review + +## Scope + +The rules and ingest flow in `@forge/api` `utils/job-board`. + +## Test placement plan + +- `packages/api/src/tests/job-board/ingestion-rules.test.ts` covers the pure + rules, with no database. +- `packages/api/src/tests/integration/job-board-ingest.test.ts` covers the + ingest flow against a disposable PostgreSQL database. + +## Test cases + +| ID | Setup | Action | Expected | +| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------- | +| TC-001 | Apply URLs from Greenhouse (`gh_jid`, path), Lever, Ashby and Workday | Build identity keys | Each yields its `ats:` key first, then `url:` and `source:` | +| TC-002 | URL with `utm_*`, `ref` and a trailing `/apply` | Clean it | Tracking parameters and `/apply` are removed and the host is lowercased | +| TC-003 | Title "Software Engineer Intern", no adapter track | Classify track | `internship` | +| TC-004 | "New Grad SWE" / "Senior Software Engineer" | Classify track | `new_grad` / rejected | +| TC-005 | Adapter track given | Classify track | The adapter's track wins | +| TC-006 | Titles for each category | Classify category | Matches the upstream rules, with unknown roles going to `other` | +| TC-007 | "Orlando, FL", "Florida", "Remote - US", "Seattle, Washington, United States", "Remote" | Parse locations | City (with state and cityKey), state, `remote_us`, city, and `unknown` | +| TC-008 | "London, UK" alone; "London, UK" + "Austin, TX" | Check U.S. scope | Rejected `non_us` / kept | +| TC-009 | Same Greenhouse job from a GitHub feed (`?gh_jid=123` link) and the Greenhouse board (`/jobs/123`) | Ingest both | One Job keyed `ats:greenhouse:123`, with two observations | +| TC-010 | Same snapshot ingested twice | Ingest | Second run: 0 created, every field but `lastSeenAt` unchanged | +| TC-011 | New source | First ingest | All jobs `suppressed`, `baselineCompletedAt` set | +| TC-012 | Baselined source, internship channel set | New internship listing | `pending`, with `deliveryTrack` and channel set | +| TC-013 | Baselined source, no new-grad channel | New new-grad listing | `suppressed` | +| TC-014 | Full inventory missing a listing | Ingest | Observation and job closed; after reopening they can close again | +| TC-015 | Rolling feed missing a listing | Ingest | Job stays active | +| TC-016 | Inactive `sent` job (with receipt) reappears | Ingest | Active again, observation open, still `sent` with the same receipt | +| TC-017 | Existing internship job, new source says `new_grad` | Ingest | Track stays `internship` | +| TC-018 | Aggregator URL first, employer URL later | Ingest | `applyUrl` becomes the employer's link | +| TC-019 | Approved Company whose alias matches | Ingest | `companyId` set, no Company inserted | +| TC-020 | Job also listed by a second source; the full source drops it | Ingest | Job stays active | +| TC-021 | Snapshot with listings rejected for each reason plus one valid | Ingest | Counts per reason; the valid listing is created | +| TC-022 | Run fetched before a newer run closed the job | Ingest stale run | Job and observation stay closed | +| TC-023 | Richer source stored description/compensation; sparse feed re-sees job | Ingest | Stored values kept | +| TC-024 | Two listings with the same careers landing-page URL | Ingest | Two jobs | +| TC-025 | "ON-SITE - Austin, TX", "London, KY", "Mexico, MO", "Austin, TX or Toronto, ON" | Check U.S. scope | All kept; "Toronto, ON", "London, UK" foreign | +| TC-026 | Company label with no ASCII; 120+ character name | Build company key | Rejected `invalid_listing`; key passes `companyKeySchema` | +| TC-027 | `"constructor"`; `notgreenhouse.io/acme/jobs/search`; `/careers/2026`; `?department_id=4`; `#/jobs/42`; `#//jobs/42` | Parse / build keys | `unknown`; no ATS key; no URL key; no URL key; hash route kept and keyed; cleaned to `#/jobs/42` without throwing | +| TC-028 | "Austin, TX or Toronto, ON" and "Portland, OR" | Parse locations | Austin and Portland cities; Toronto dropped as foreign | +| TC-029 | Listing with NUL or a lone surrogate (half an emoji) in a text field or `sourceData` | Validate | Rejected as `invalid_listing` | +| TC-030 | A t20 run closes a job after B closed at t40; B's t30 replay, then a t50 sighting | Ingest | Stays closed after the replay; reopens at t50 | +| TC-031 | Older snapshot replays an observation | Ingest | Newer `sourceData` kept | +| TC-032 | Unlinked "Acme" job later listed as approved company "Beta" | Ingest | `companyId` stays null | +| TC-033 | Workable `/j/AB12CD34EF`, BambooHR `/careers/123`, iCIMS `/jobs/1234/title/job`, `/jobs/page-2` | Build keys | URL key for the postings; none for the page | +| TC-034 | "US or Canada (Remote)"; "Salem, OR or Portland, OR" | Parse locations | One `remote_us`; two Oregon cities | +| TC-035 | Two first runs of one new source at once | Ingest concurrently | Exactly one reports `baselined` | +| TC-036 | Workday `wd5.myworkdaysite.com/recruiting/acme/...` and `/recruiting/beta/...` with the same requisition; `wd5.myworkdayjobs.com/...` with no tenant | Build keys | `ats:workday:acme:…` and `ats:workday:beta:…`; no Workday key | +| TC-037 | Job closed at t40; a delayed t30 run of a source whose observation closed at t10 | Ingest stale run | The observation reopens, the job stays closed | +| TC-038 | Two full sources drop their shared job at the same time | Ingest concurrently | The job closes, reported once | + +## Negative / regression cases + +| ID | Setup | Expected | +| ---------- | ------------------------------------------- | -------------------------- | +| TC-NEG-001 | `complete: false` | Rejected before any write | +| TC-NEG-002 | Four concurrent ingests of one identity | One Job created, 3 updated | +| TC-NEG-003 | Invalid listing (non-http URL, blank title) | Fails validation | +| TC-NEG-004 | Destination that isn't a Discord ID | Rejected before any write | + +## Open questions + +- None. diff --git a/packages/api/package.json b/packages/api/package.json index e5bb4c769..462a5bc14 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -17,6 +17,10 @@ "types": "./src/discord-archive.server.ts", "default": "./src/discord-archive.server.ts" }, + "./job-board.server": { + "types": "./src/job-board.server.ts", + "default": "./src/job-board.server.ts" + }, "./resume-bundle.server": { "types": "./src/resume-bundle.server.ts", "default": "./src/resume-bundle.server.ts" diff --git a/packages/api/src/job-board.server.ts b/packages/api/src/job-board.server.ts new file mode 100644 index 000000000..3952d62a4 --- /dev/null +++ b/packages/api/src/job-board.server.ts @@ -0,0 +1,5 @@ +export { ingestJobSnapshot } from "./utils/job-board/ingest"; +export type { + JobDestinations, + JobIngestResult, +} from "./utils/job-board/ingest"; diff --git a/packages/api/src/tests/integration/job-board-ingest.test.ts b/packages/api/src/tests/integration/job-board-ingest.test.ts new file mode 100644 index 000000000..8daf070aa --- /dev/null +++ b/packages/api/src/tests/integration/job-board-ingest.test.ts @@ -0,0 +1,519 @@ +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; + +import type { db } from "@forge/db/client"; +import type * as JobBoardSchema from "@forge/db/schemas/job-board"; +import type * as KnightHacksSchema from "@forge/db/schemas/knight-hacks"; +import type { DisposableDatabase } from "@forge/db/testing"; +import type { + CareerJobListing, + CareerJobSourceSnapshot, +} from "@forge/validators"; +import { sql } from "@forge/db"; +import { + canRunDatabaseTests, + provisionDisposableDatabase, +} from "@forge/db/testing"; + +import type { ingestJobSnapshot as IngestJobSnapshot } from "../../utils/job-board/ingest"; + +const INTERN_CHANNEL = "123456789012345678"; + +function listing(overrides: Partial = {}): CareerJobListing { + return { + externalId: "row-1", + companyLabel: "Acme", + title: "Software Engineer Intern", + applyUrl: "https://boards.greenhouse.io/acme/jobs/123", + locationTexts: ["Orlando, FL"], + sourceUrl: "https://github.com/simplify/internships", + sourceData: {}, + ...overrides, + }; +} + +function snapshot( + listings: CareerJobListing[], + overrides: Partial = {}, +): CareerJobSourceSnapshot { + return { + source: { + provider: "github", + boardKey: "simplify/internships", + label: "Simplify", + }, + fetchedAt: new Date(), + complete: true, + inventory: "rolling", + listings, + ...overrides, + }; +} + +const greenhouse = { provider: "greenhouse", boardKey: "acme", label: "Acme" }; +/** A second board that lists the same postings as `greenhouse`. */ +const other = { provider: "greenhouse", boardKey: "acme-2", label: "Acme" }; + +describe.skipIf(!canRunDatabaseTests())("job board ingestion", () => { + let client: typeof db; + let schema: typeof JobBoardSchema; + let Company: typeof KnightHacksSchema.Company; + let database: DisposableDatabase; + let ingest: typeof IngestJobSnapshot; + + /** Runs a snapshot at a later instant than the previous one. */ + let clock = Date.UTC(2026, 10, 1); + const run = ( + value: CareerJobSourceSnapshot, + destinations: Parameters[1] = {}, + ) => + ingest({ ...value, fetchedAt: new Date((clock += 60_000)) }, destinations); + + const jobs = () => client.select().from(schema.Job); + const observations = () => client.select().from(schema.JobObservation); + const board = (listings: CareerJobListing[]) => + snapshot(listings, { source: greenhouse, inventory: "full" }); + /** A full-inventory run of `source` at `minutes` past the clock, in any order. */ + const full = ( + source: typeof greenhouse, + listings: CareerJobListing[], + minutes: number, + ) => + ingest( + { + ...snapshot(listings, { source, inventory: "full" }), + fetchedAt: new Date(clock + minutes * 60_000), + }, + {}, + ); + + beforeAll(async () => { + database = await provisionDisposableDatabase("forge_job_ingest"); + vi.stubEnv("DATABASE_URL", database.url); + ({ db: client } = await import("@forge/db/client")); + schema = await import("@forge/db/schemas/job-board"); + ({ Company } = await import("@forge/db/schemas/knight-hacks")); + ({ ingestJobSnapshot: ingest } = + await import("../../utils/job-board/ingest")); + }, 120_000); + + beforeEach(async () => { + await client.execute( + sql`TRUNCATE ${schema.JobLocation}, ${schema.JobObservation}, ${schema.Job}, ${schema.JobSource}, ${Company} CASCADE`, + ); + }); + + afterAll(async () => { + await client.$client.end().catch(() => undefined); + await database.drop(); + }); + + it("TC-011 keeps a new source's first run silent and records the baseline", async () => { + const result = await run(snapshot([listing()]), { + internship: INTERN_CHANNEL, + }); + expect(result).toMatchObject({ created: 1, baselined: true }); + + const [job] = await jobs(); + expect(job).toMatchObject({ + deliveryState: "suppressed", + track: "internship", + category: "swe", + companyKey: "acme", + identityKey: "ats:greenhouse:123", + }); + const [source] = await client.select().from(schema.JobSource); + expect(source?.baselineCompletedAt).not.toBeNull(); + const [location] = await client.select().from(schema.JobLocation); + expect(location).toMatchObject({ + kind: "city", + cityKey: "12-53000", + state: "FL", + }); + }); + + it("TC-012/TC-013 queues new jobs after the baseline only when the track has a channel", async () => { + await run(snapshot([])); + await run( + snapshot([ + listing({ externalId: "a" }), + listing({ + externalId: "b", + track: "new_grad", + applyUrl: "https://acme.com/jobs/ng", + title: "Software Engineer, New Grad", + }), + ]), + { internship: INTERN_CHANNEL, new_grad: null }, + ); + + const byTrack = Object.fromEntries( + (await jobs()).map((job) => [job.track, job]), + ); + expect(byTrack.internship).toMatchObject({ + deliveryState: "pending", + deliveryTrack: "internship", + discordChannelId: INTERN_CHANNEL, + }); + expect(byTrack.new_grad).toMatchObject({ deliveryState: "suppressed" }); + }); + + it("TC-009 merges the same job seen from two sources", async () => { + // Different URLs: only the Greenhouse job ID links them. + await run( + snapshot([listing({ applyUrl: "https://acme.com/careers?gh_jid=123" })]), + ); + await run( + snapshot( + [ + listing({ + externalId: "gh-123", + sourceUrl: "https://boards.greenhouse.io/acme", + }), + ], + { + source: greenhouse, + inventory: "full", + }, + ), + ); + + expect(await jobs()).toHaveLength(1); + expect((await jobs())[0]?.identityKey).toBe("ats:greenhouse:123"); + expect(await client.select().from(schema.JobObservation)).toHaveLength(2); + }); + + it("TC-010 is idempotent for an unchanged source", async () => { + await run(snapshot([listing()])); + const [before] = await jobs(); + const result = await run(snapshot([listing()])); + const [after] = await jobs(); + + expect(result).toMatchObject({ created: 0, updated: 1, baselined: false }); + expect(after?.lastSeenAt.getTime()).toBeGreaterThan( + before?.lastSeenAt.getTime() ?? 0, + ); + expect({ ...after, lastSeenAt: null }).toEqual({ + ...before, + lastSeenAt: null, + }); + expect(await client.select().from(schema.JobLocation)).toHaveLength(1); + }); + + it("TC-014/TC-016 closes jobs missing from a full inventory and reopens them silently", async () => { + const destinations = { internship: INTERN_CHANNEL }; + await run(board([])); + await run(board([listing()]), destinations); + expect((await jobs())[0]).toMatchObject({ deliveryState: "pending" }); + // #654 posts it: the receipt must survive closing and reopening. + const receipt = { + deliveryState: "sent" as const, + discordMessageId: "223456789012345678", + deliveredAt: new Date(Date.UTC(2026, 10, 2)), + }; + await client.update(schema.Job).set(receipt); + + const closed = await run(board([])); + expect(closed.deactivated).toBe(1); + expect((await jobs())[0]?.active).toBe(false); + expect((await jobs())[0]?.inactiveAt).not.toBeNull(); + expect((await observations())[0]?.inactiveAt).not.toBeNull(); + + await run(board([listing()]), destinations); + expect((await jobs())[0]).toMatchObject({ + active: true, + inactiveAt: null, + ...receipt, + }); + expect((await observations())[0]?.inactiveAt).toBeNull(); + + // Reopened observations can close again. + expect((await run(board([]))).deactivated).toBe(1); + }); + + it("does not let a stale snapshot reopen a job a newer run closed", async () => { + await run(board([listing()])); + const stale = new Date(clock + 30_000); + await run(board([])); + await ingest({ ...board([listing()]), fetchedAt: stale }, {}); + expect((await jobs())[0]?.active).toBe(false); + expect((await observations())[0]?.inactiveAt).not.toBeNull(); + }); + + it("does not let a stale snapshot replace newer details", async () => { + await run(snapshot([listing({ title: "Old Software Engineer Intern" })])); + const stale = new Date(clock + 30_000); + await run(snapshot([listing({ title: "New Software Engineer Intern" })])); + await ingest( + { + ...snapshot([listing({ title: "Stale Software Engineer Intern" })]), + fetchedAt: stale, + }, + {}, + ); + expect((await jobs())[0]?.title).toBe("New Software Engineer Intern"); + }); + + it("keeps a job closed when a replay leaves its observation closed", async () => { + await full(greenhouse, [listing({ externalId: "a" })], 10); + await full(other, [listing({ externalId: "b" })], 10); + expect(await jobs()).toHaveLength(1); // A and B are the same job. + await full(other, [], 40); // B closes its observation at t40. + await full(greenhouse, [], 20); // A's delayed t20 run closes the last one. + expect((await jobs())[0]?.active).toBe(false); + + // A replay of B's t30 listing leaves B's observation closed (t40). + await full(other, [listing({ externalId: "b" })], 30); + expect((await jobs())[0]?.active).toBe(false); + + // A fresh B sighting after t40 reopens both. + await full(other, [listing({ externalId: "b" })], 50); + expect((await jobs())[0]?.active).toBe(true); + const observationB = (await observations()).find( + (row) => row.externalId === "b", + ); + expect(observationB?.inactiveAt).toBeNull(); + }); + + it("TC-037 keeps a job closed when a stale sighting reopens only its observation", async () => { + await full(greenhouse, [listing({ externalId: "a" })], 5); + await full(other, [listing({ externalId: "b" })], 5); + await full(other, [], 10); // B's observation closes at t10. + await full(greenhouse, [], 40); // A closes the job at t40. + // B's delayed t30 run reopens B's observation (closed at t10), but the + // job was closed later, at t40, so it stays closed. + await full(other, [listing({ externalId: "b" })], 30); + expect((await jobs())[0]?.active).toBe(false); + }); + + it("TC-038 closes a job once when two sources drop it at the same time", async () => { + const both = (listings: CareerJobListing[]) => + Promise.all([ + run(snapshot(listings, { source: greenhouse, inventory: "full" })), + run(snapshot(listings, { source: other, inventory: "full" })), + ]); + // Repeat so the two closes overlap at least once. + for (let round = 0; round < 5; round++) { + await both([listing()]); + expect((await jobs())[0]?.active).toBe(true); + const results = await both([]); + expect((await jobs())[0]?.active).toBe(false); + expect(results[0].deactivated + results[1].deactivated).toBe(1); + } + }); + + it("keeps newer observation metadata when an older snapshot replays", async () => { + const sighting = (row: string, day: number) => + listing({ + sourceData: { row }, + sourceUrl: `https://github.com/simplify/internships#${row}`, + postedAt: new Date(Date.UTC(2026, 9, day)), + }); + await run(snapshot([sighting("old", 1)])); + const stale = new Date(clock + 30_000); + await run(snapshot([sighting("new", 3)])); + await ingest({ ...snapshot([sighting("stale", 2)]), fetchedAt: stale }, {}); + expect((await observations())[0]).toMatchObject({ + sourceData: { row: "new" }, + sourceUrl: "https://github.com/simplify/internships#new", + postedAt: new Date(Date.UTC(2026, 9, 3)), + }); + }); + + it("links an existing job by its own company key, not a later label", async () => { + await run(snapshot([listing()])); + await client.insert(Company).values({ + displayName: "Beta", + normalizedDisplayName: "beta", + aliases: [], + reviewState: "approved", + }); + await run(snapshot([listing({ companyLabel: "Beta" })])); + expect((await jobs())[0]).toMatchObject({ + companyKey: "acme", + companyId: null, + }); + + // Once Acme itself is approved, the next sighting links the job. + const [acme] = await client + .insert(Company) + .values({ + displayName: "Acme", + normalizedDisplayName: "acme", + aliases: [], + reviewState: "approved", + }) + .returning(); + await run(snapshot([listing({ companyLabel: "Beta" })])); + expect((await jobs())[0]?.companyId).toBe(acme?.id); + }); + + it("reports the baseline from only one of two concurrent first runs", async () => { + const results = await Promise.all([ + run(snapshot([listing()])), + run(snapshot([listing({ externalId: "row-2" })])), + ]); + expect(results.filter((result) => result.baselined)).toHaveLength(1); + }); + + it("keeps stored details when a sparser feed sees the job again", async () => { + await run( + board([ + listing({ + description: "Build compilers.", + compensation: "$40/hr", + postedAt: new Date(Date.UTC(2026, 9, 1)), + }), + ]), + ); + await run(snapshot([listing()])); + expect((await jobs())[0]).toMatchObject({ + description: "Build compilers.", + compensation: "$40/hr", + postedAt: new Date(Date.UTC(2026, 9, 1)), + }); + }); + + it("keeps separate jobs that share a careers landing page", async () => { + const landing = "https://acme.com/careers"; + await run( + snapshot([ + listing({ externalId: "1", applyUrl: landing }), + listing({ externalId: "2", applyUrl: landing, title: "Data Intern" }), + ]), + ); + expect(await jobs()).toHaveLength(2); + }); + + it("TC-015 never closes jobs missing from a rolling feed", async () => { + await run(snapshot([listing()])); + const result = await run(snapshot([])); + expect(result.deactivated).toBe(0); + expect((await jobs())[0]).toMatchObject({ active: true }); + }); + + it("keeps a job open while another source still lists it", async () => { + await run(snapshot([listing()])); + await run( + snapshot([listing({ externalId: "gh" })], { + source: greenhouse, + inventory: "full", + }), + ); + await run(snapshot([], { source: greenhouse, inventory: "full" })); + expect((await jobs())[0]).toMatchObject({ active: true }); + }); + + it("TC-017/TC-018 keeps the first track and prefers the employer link", async () => { + await run( + snapshot([ + listing({ + applyUrl: "https://simplify.jobs/p/1", + externalId: "x", + title: "Intern", + }), + ]), + ); + const [first] = await jobs(); + expect(first?.applyUrl).toBe("https://simplify.jobs/p/1"); + + // Same source row, now pointing at the employer and claiming new grad. + await run( + snapshot([ + listing({ + externalId: "x", + track: "new_grad", + applyUrl: "https://acme.com/jobs/1", + title: "Software Engineer Intern", + }), + ]), + ); + const [job] = await jobs(); + expect(job).toMatchObject({ + id: first?.id, + track: "internship", + applyUrl: "https://acme.com/jobs/1", + title: "Software Engineer Intern", + }); + }); + + it("TC-019 links an approved Guild company by alias without creating one", async () => { + const [company] = await client + .insert(Company) + .values({ + displayName: "Acme Corporation", + normalizedDisplayName: "acme corporation", + aliases: ["Acme"], + reviewState: "approved", + }) + .returning(); + + await run(snapshot([listing()])); + expect((await jobs())[0]?.companyId).toBe(company?.id); + expect(await client.select().from(Company)).toHaveLength(1); + }); + + it("counts rejected listings by reason and still ingests the rest", async () => { + const malformed = { ...listing({ externalId: "blank" }), title: " " }; + const result = await run( + snapshot([ + listing({ externalId: "senior", title: "Senior Engineer" }), + listing({ externalId: "uk", locationTexts: ["London, UK"] }), + listing({ + externalId: "creds", + applyUrl: "https://user:pw@acme.com/jobs/9", + }), + malformed, + listing(), + ]), + ); + expect(result.rejected).toEqual({ + not_student_role: 1, + non_us: 1, + invalid_apply_url: 1, + invalid_listing: 1, + }); + expect(result.created).toBe(1); + expect(await jobs()).toHaveLength(1); + }); + + it("rejects a destination that is not a Discord ID before writing", async () => { + await expect( + run(snapshot([listing()]), { internship: "#internships" }), + ).rejects.toThrow(/not a Discord ID/); + expect(await client.select().from(schema.JobSource)).toHaveLength(0); + }); + + it("TC-NEG-001 rejects an incomplete snapshot before writing", async () => { + await expect( + run(snapshot([listing()], { complete: false })), + ).rejects.toThrow(/incomplete/); + expect(await client.select().from(schema.JobSource)).toHaveLength(0); + }); + + it("TC-NEG-002 creates one job when several sources ingest the same identity at once", async () => { + const sources = ["a", "b", "c", "d"].map((boardKey) => ({ + provider: "greenhouse", + boardKey, + label: boardKey, + })); + // Create the sources first so the runs reach the job insert together. + await Promise.all(sources.map((source) => run(snapshot([], { source })))); + const results = await Promise.all( + sources.map((source) => + run(snapshot([listing({ externalId: source.boardKey })], { source })), + ), + ); + expect(results.reduce((sum, result) => sum + result.created, 0)).toBe(1); + expect(results.reduce((sum, result) => sum + result.updated, 0)).toBe(3); + expect(await jobs()).toHaveLength(1); + expect(await observations()).toHaveLength(4); + }); +}); diff --git a/packages/api/src/tests/job-board/ingestion-rules.test.ts b/packages/api/src/tests/job-board/ingestion-rules.test.ts new file mode 100644 index 000000000..c0a6e7c18 --- /dev/null +++ b/packages/api/src/tests/job-board/ingestion-rules.test.ts @@ -0,0 +1,423 @@ +import { describe, expect, it } from "vitest"; + +import type { CareerJobListing } from "@forge/validators"; +import { + careerJobListingSchema, + careerJobSourceSnapshotSchema, + companyKeySchema, +} from "@forge/validators"; + +import { findUsCity } from "../../utils/career/us-cities"; +import { + classifyCategory, + classifyTrack, +} from "../../utils/job-board/classify"; +import { prepareListing } from "../../utils/job-board/listing"; +import { + isForeignLocation, + parseLocation, +} from "../../utils/job-board/locations"; +import { + cleanApplyUrl, + companyKey, + identityHash, + identityKeys, + preferredApplyUrl, +} from "../../utils/job-board/normalize"; + +const source = { provider: "github", boardKey: "simplify/internships" }; +const SOURCE_KEY = 'source:["github","simplify/internships","row-1"]'; + +function keysFor(applyUrl: string) { + return identityKeys({ ...source, applyUrl, externalId: "row-1" }); +} + +function listing(overrides: Partial = {}): CareerJobListing { + return { + externalId: "row-1", + companyLabel: "Acme, Inc.", + title: "Software Engineer Intern", + applyUrl: "https://boards.greenhouse.io/acme/jobs/123", + locationTexts: ["Orlando, FL"], + sourceUrl: "https://github.com/simplify/internships", + sourceData: {}, + ...overrides, + }; +} + +describe("job identity", () => { + it("TC-001 builds ATS keys first, then URL, then source", () => { + expect(keysFor("https://boards.greenhouse.io/acme/jobs/123")).toEqual([ + "ats:greenhouse:123", + "url:https://boards.greenhouse.io/acme/jobs/123", + SOURCE_KEY, + ]); + expect(keysFor("https://acme.com/careers?gh_jid=987")[0]).toBe( + "ats:greenhouse:987", + ); + expect(keysFor("https://jobs.lever.co/acme/AB-12")[0]).toBe( + "ats:lever:ab-12", + ); + expect(keysFor("https://jobs.ashbyhq.com/acme/Uuid-1")[0]).toBe( + "ats:ashby:uuid-1", + ); + expect( + keysFor( + "https://nvidia.wd5.myworkdayjobs.com/en-US/External/job/US-CA/Software-Intern_JR1234", + )[0], + ).toBe("ats:workday:nvidia:jr1234"); + }); + + it("never uses an aggregator URL as an identity", () => { + expect(keysFor("https://jobright.ai/jobs/info/abc")).toEqual([SOURCE_KEY]); + }); + + it("never uses a shared careers landing page as an identity", () => { + for (const landing of [ + "https://acme.com/careers", + "https://acme.com/careers?year=2026", + "https://acme.com/careers/2026", + "https://acme.com/careers/summer-2026", + "https://acme.wd1.myworkdayjobs.com/en-US/Careers", + "https://acme.com/jobs?department_id=4", + "https://acme.com/search?location_id=1234", + ]) { + expect(keysFor(landing)).toEqual([SOURCE_KEY]); + } + expect(keysFor("https://acme.com/careers?jobId=42")[0]).toBe( + "url:https://acme.com/careers?jobId=42", + ); + expect(keysFor("https://acme.com/careers/software-intern-48213")[0]).toBe( + "url:https://acme.com/careers/software-intern-48213", + ); + expect(keysFor("https://acme.com/careers#/jobs/42")[0]).toBe( + "url:https://acme.com/careers#/jobs/42", + ); + }); + + it("only trusts ATS keys on the ATS's own domain and ID format", () => { + expect(keysFor("https://notgreenhouse.io/acme/jobs/123")).not.toContain( + "ats:greenhouse:123", + ); + expect( + keysFor( + "https://acme.myworkdayjobs.com.evil.net/en-US/External/job/Intern_JR1234", + ), + ).not.toContain("ats:workday:acme:jr1234"); + expect(keysFor("https://boards.greenhouse.io/acme/jobs/search")).toEqual([ + SOURCE_KEY, + ]); + expect(keysFor("https://acme.com/careers?gh_jid=abc")).toEqual([ + SOURCE_KEY, + ]); + }); + + it("TC-036 keeps Workday requisitions apart per employer on shared hosts", () => { + const posting = (tenant: string) => + `https://wd5.myworkdaysite.com/recruiting/${tenant}/External/job/X/Intern_R1`; + expect(keysFor(posting("acme"))[0]).toBe("ats:workday:acme:r1"); + expect(keysFor(posting("beta"))[0]).toBe("ats:workday:beta:r1"); + // No tenant to tell employers apart, so no Workday key at all. + expect( + keysFor("https://wd5.myworkdayjobs.com/en-US/acme/job/X/Intern_R1"), + ).toEqual([SOURCE_KEY]); + }); + + it("finds posting IDs in real job URLs but not in landing pages", () => { + for (const posting of [ + "https://apply.workable.com/acme/j/AB12CD34EF", + "https://acme.bamboohr.com/careers/123", + "https://acme.com/careers/software-engineer-intern-123", + "https://careers-acme.icims.com/jobs/1234/software-intern/job", + "https://www.amazon.jobs/en/jobs/2712345/sde-intern", + "https://acme.taleo.net/careersection/2/jobdetail.ftl?job=12345", + ]) { + expect(keysFor(posting)[0]).toBe(`url:${posting}`); + } + expect(keysFor("https://acme.com/jobs/page-2")).toEqual([SOURCE_KEY]); + }); + + it("keeps source key parts apart when they contain colons", () => { + const key = (boardKey: string, externalId: string) => + identityKeys({ + provider: "github", + boardKey, + externalId, + applyUrl: "https://acme.com/careers", + }).at(-1); + expect(key("acme:engineering", "17")).not.toBe( + key("acme", "engineering:17"), + ); + }); + + it("TC-002 strips tracking params, fragments, and a trailing /apply", () => { + expect( + cleanApplyUrl( + "https://Jobs.Lever.co//acme/ab-12/apply/?utm_source=x&ref=gh&lever-source=y#top", + ), + ).toBe("https://jobs.lever.co/acme/ab-12?lever-source=y"); + expect(cleanApplyUrl("https://acme.com/careers#/jobs/42")).toBe( + "https://acme.com/careers#/jobs/42", + ); + expect( + cleanApplyUrl("https://acme.com/careers#/jobs/42/?utm_source=simplify"), + ).toBe("https://acme.com/careers#/jobs/42"); + // A doubled slash is still a path, not a host, and must not throw. + expect(cleanApplyUrl("https://acme.com/careers#//jobs/42")).toBe( + "https://acme.com/careers#/jobs/42", + ); + expect(cleanApplyUrl("https://acme.com/careers#//")).toBe( + "https://acme.com/careers#/", + ); + expect(cleanApplyUrl("https://acme.com/jobs/42#top")).toBe( + "https://acme.com/jobs/42", + ); + expect(cleanApplyUrl("javascript:alert(1)")).toBeNull(); + expect(cleanApplyUrl("https://user:pw@acme.com/job")).toBeNull(); + }); + + it("prefers an employer link over an aggregator copy", () => { + const employer = "https://acme.com/jobs/1"; + const aggregator = "https://simplify.jobs/p/1"; + expect(preferredApplyUrl(aggregator, employer)).toBe(employer); + expect(preferredApplyUrl(employer, aggregator)).toBe(employer); + }); + + it("builds company keys that company filters accept", () => { + const long = `${"a".repeat(119)} corp`; + expect(companyKeySchema.safeParse(companyKey(long)).success).toBe(true); + expect(companyKey("株式会社")).toBe(""); + }); + + it("hashes keys as SHA-256 hex of UTF-8", () => { + expect(identityHash("abc")).toBe( + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ); + }); +}); + +describe("track and category", () => { + it("TC-003 to TC-005 classifies track from title unless the source sets it", () => { + expect(classifyTrack("Software Engineer Intern")).toBe("internship"); + expect(classifyTrack("Co-op, Firmware")).toBe("internship"); + expect(classifyTrack("New Grad SWE")).toBe("new_grad"); + expect(classifyTrack("Software Engineer I")).toBe("new_grad"); + expect(classifyTrack("Senior Software Engineer")).toBeNull(); + expect(classifyTrack("Software Engineer")).toBeNull(); + expect(classifyTrack("Senior Software Engineer", "new_grad")).toBe( + "new_grad", + ); + }); + + it("TC-006 classifies role categories like CS Job Poster", () => { + expect(classifyCategory("Software Engineer Intern")).toBe("swe"); + expect(classifyCategory("Machine Learning Intern")).toBe("data_ai"); + expect(classifyCategory("Product Manager Intern")).toBe("pm"); + expect(classifyCategory("Quantitative Trader Intern")).toBe("quant"); + expect(classifyCategory("UX Design Intern")).toBe("design"); + expect(classifyCategory("Security Analyst Intern")).toBe("it_security"); + expect(classifyCategory("Data Analyst Intern")).toBe("analyst"); + expect(classifyCategory("FPGA Engineer Intern")).toBe("hardware"); + expect(classifyCategory("Software Security Engineer")).toBe("swe"); + expect( + classifyCategory("Systems Engineer Intern", "Work on FPGA boards"), + ).toBe("hardware"); + expect(classifyCategory("Summer Intern", "It is a great team")).toBe( + "other", + ); + }); +}); + +describe("locations", () => { + const orlando = findUsCity("Orlando", "FL"); + const seattle = findUsCity("Seattle", "WA"); + const redmond = findUsCity("Redmond", "WA"); + + it("TC-007 parses city, state, U.S. remote, and unknown", () => { + expect(orlando?.key).toBe("12-53000"); + expect(parseLocation("Orlando, FL")).toMatchObject({ + kind: "city", + cityKey: orlando?.key, + state: "FL", + }); + expect(parseLocation("Seattle, Washington, United States")).toMatchObject({ + kind: "city", + cityKey: seattle?.key, + }); + expect(parseLocation("United States, Washington, Redmond")).toMatchObject({ + kind: "city", + cityKey: redmond?.key, + }); + expect(parseLocation("NYC")).toMatchObject({ kind: "city", state: "NY" }); + expect(parseLocation("Florida")).toMatchObject({ + kind: "state", + state: "FL", + }); + expect(parseLocation("Nowhereville, TX")).toMatchObject({ + kind: "state", + state: "TX", + }); + expect(parseLocation("Remote - US")).toMatchObject({ kind: "remote_us" }); + expect(parseLocation("Remote - join us")).toMatchObject({ + kind: "unknown", + }); + expect(parseLocation("Remote")).toMatchObject({ + kind: "unknown", + sourceText: "Remote", + }); + expect(parseLocation("constructor")).toMatchObject({ kind: "unknown" }); + expect(parseLocation("Multiple Locations")).toMatchObject({ + kind: "unknown", + }); + }); + + it("TC-008 rejects all-foreign listings and keeps mixed ones", () => { + expect( + prepareListing(listing({ locationTexts: ["London, UK"] }), source), + ).toEqual({ + ok: false, + reason: "non_us", + }); + const mixed = prepareListing( + listing({ locationTexts: ["London, UK / Austin, TX"] }), + source, + ); + expect(mixed.ok && mixed.listing.locations).toEqual([ + expect.objectContaining({ + kind: "city", + state: "TX", + sourceText: "Austin, TX", + }), + ]); + expect(parseLocation("Albuquerque, New Mexico")).toMatchObject({ + kind: "city", + }); + }); + + it("keeps U.S. places that look foreign", () => { + for (const text of [ + "ON-SITE - Austin, TX", + "Austin, TX (ON SITE)", + "London, KY", + "London, ky", + "Mexico, MO", + "Austin, TX or Toronto, ON", + ]) { + expect(isForeignLocation(text)).toBe(false); + } + for (const text of ["Toronto, ON", "London, UK", "Remote - Canada"]) { + expect(isForeignLocation(text)).toBe(true); + } + }); +}); + +describe("prepared listing", () => { + it("rejects listings that are not student roles", () => { + expect( + prepareListing(listing({ title: "Staff Engineer" }), source), + ).toEqual({ + ok: false, + reason: "not_student_role", + }); + }); + + it("rejects a company label with nothing to group by", () => { + expect( + prepareListing(listing({ companyLabel: "株式会社" }), source), + ).toEqual({ ok: false, reason: "invalid_listing" }); + }); + + it("keeps a listing with no locations", () => { + const prepared = prepareListing(listing({ locationTexts: [] }), source); + expect(prepared.ok && prepared.listing.locations).toEqual([]); + }); + + it("normalizes the company key for grouping", () => { + const prepared = prepareListing(listing(), source); + expect(prepared.ok && prepared.listing.companyKey).toBe("acme inc"); + }); + + it('splits places joined by a lowercase "or"', () => { + const prepared = prepareListing( + listing({ + locationTexts: [ + "Austin, TX or Toronto, ON", + "Salem, OR or Portland, OR", + "US or Canada (Remote)", + ], + }), + source, + ); + expect(prepared.ok && prepared.listing.locations).toEqual([ + expect.objectContaining({ + kind: "city", + state: "TX", + sourceText: "Austin, TX", + }), + expect.objectContaining({ + kind: "city", + state: "OR", + sourceText: "Salem, OR", + }), + expect.objectContaining({ + kind: "city", + state: "OR", + sourceText: "Portland, OR", + }), + expect.objectContaining({ + kind: "remote_us", + sourceText: "US or Canada (Remote)", + }), + ]); + }); + + it("rejects listings Postgres could not store", () => { + for (const bad of [ + listing({ externalId: "row\u0000" }), + listing({ companyLabel: "Acme\u0000" }), + listing({ title: "Intern\u0000" }), + listing({ description: "About\u0000" }), + listing({ compensation: "$40\u0000" }), + listing({ locationTexts: ["Austin\u0000, TX"] }), + listing({ sourceUrl: "https://github.com/a\u0000b" }), + listing({ sourceData: { note: "\u0000" } }), + listing({ sourceData: { ["key\u0000"]: 1 } }), + listing({ sourceData: { note: "cut emoji \ud83d" } }), + // Postgres would store U+FFFD, so the next run's ID wouldn't match. + listing({ externalId: "row-\ud83d" }), + listing({ locationTexts: ["Austin \ude00, TX"] }), + ]) { + expect(careerJobListingSchema.safeParse(bad).success).toBe(false); + } + // Escaped text that merely looks like NUL is fine for jsonb. + expect( + careerJobListingSchema.safeParse( + listing({ sourceData: { code: "\\u0000", emoji: "\ud83d\ude00" } }), + ).success, + ).toBe(true); + }); + + it("TC-NEG-003 rejects invalid snapshot input", () => { + const snapshot = { + source: { ...source, label: "Simplify" }, + fetchedAt: new Date(), + complete: true, + inventory: "rolling", + listings: [listing()], + }; + expect(careerJobSourceSnapshotSchema.safeParse(snapshot).success).toBe( + true, + ); + for (const bad of [ + listing({ applyUrl: "ftp://acme.com/job" }), + listing({ title: " " }), + ]) { + expect( + careerJobSourceSnapshotSchema.safeParse({ + ...snapshot, + listings: [bad], + }).success, + ).toBe(false); + } + }); +}); diff --git a/packages/api/src/utils/career/us-cities.ts b/packages/api/src/utils/career/us-cities.ts index 27c9b8c03..b0aeaee3b 100644 --- a/packages/api/src/utils/career/us-cities.ts +++ b/packages/api/src/utils/career/us-cities.ts @@ -54,6 +54,22 @@ export function searchUsCities(query: string, limit: number) { .slice(0, Math.max(0, limit)); } +// A few Census places share a name within a state; the first listed wins. +const citiesByNameAndState = new Map(); +for (const city of cities) { + const key = `${normalizeSearch(city.name)}|${city.state}`; + if (!citiesByNameAndState.has(key)) citiesByNameAndState.set(key, city); +} + +/** Exact lookup by city name and two-letter state code, ignoring case/punctuation. */ +export function findUsCity(name: string, state: string) { + return ( + citiesByNameAndState.get( + `${normalizeSearch(name)}|${state.toUpperCase()}`, + ) ?? null + ); +} + export function getUsCity(key: string) { return citiesByKey.get(key) ?? null; } diff --git a/packages/api/src/utils/job-board/classify.ts b/packages/api/src/utils/job-board/classify.ts new file mode 100644 index 000000000..1425c8cbe --- /dev/null +++ b/packages/api/src/utils/job-board/classify.ts @@ -0,0 +1,106 @@ +import type { JOB_BOARD } from "@forge/consts"; + +// Category rules ported from CS Job Poster `outsource/categories.py`; track +// signals from `job_bot/filters.py` (#633). Categories never exclude a job. + +const ROLE_PATTERNS = { + pm: String.raw`(?:product|program|project) (?:\w+ ){0,2}(?:manager|management)|\b[at]?pm\b`, + quant: String.raw`quant(?:itative)?(?: |$)|algorithmic trad(?:er|ing)`, + design: String.raw`\b(?:ux|ui)\b|user (?:experience|interface)|product design|interaction design`, + data_ai: + String.raw`data (?:engineer|scien)|machine learning|\b(?:ml|ai|nlp)\b|` + + String.raw`artificial intelligence|deep learning|computer vision|applied (?:scientist|research)`, + it_security: + String.raw`cyber ?security|information security|security (?:analyst|operations)|` + + String.raw`soc analyst|penetration test|\b(?:it|help ?desk|sysadmin)\b|` + + String.raw`(?:systems?|network|cloud|database) administrat|technical support|` + + String.raw`desktop support|network engineer`, + hardware: + String.raw`hardware|electrical|electronics|\b(?:fpga|asic|rtl|vlsi)\b|` + + String.raw`chip design|semiconductor|silicon|robotics|mechatronics|physical systems`, + swe: + String.raw`software|\bswe\b|front ?end|back ?end|full ?stack|developer|programmer|` + + String.raw`mobile|embedded|firmware|platform engineer|site reliability|\bsre\b|` + + String.raw`dev ?ops|devsecops|test automation|automation (?:test |qa )?engineer|` + + String.raw`\bsdet\b|quality assurance engineer|cloud engineer|gameplay`, + analyst: String.raw`analyst|analytics|business intelligence|\bbi\b`, +} satisfies Record, string>; + +type PatternKey = keyof typeof ROLE_PATTERNS; + +const ROLE_REGEXES = Object.fromEntries( + Object.entries(ROLE_PATTERNS).map(([key, pattern]) => [ + key, + new RegExp(String.raw`\b(?:${pattern})`), + ]), +) as Record; + +function normalizeText(text: string) { + return text + .replace(/<[^>]+>/g, " ") + .toLowerCase() + .replace(/[^a-z0-9]+/g, " ") + .trim(); +} + +const matches = (text: string, key: PatternKey) => ROLE_REGEXES[key].test(text); + +export function classifyCategory( + title: string, + description = "", +): JOB_BOARD.JobCategory { + const titleText = normalizeText(title); + // The pronoun "it" is not evidence of an IT role in a description. + const summaryText = normalizeText(description.replace(/\b[Ii]t\b/g, "")); + + // Specific families precede the broad software bucket. + for (const key of ["pm", "quant", "design", "data_ai"] as const) { + if (matches(titleText, key)) return key; + } + if (matches(titleText, "analyst")) { + return matches(titleText, "it_security") ? "it_security" : "analyst"; + } + if (/\b(?:software|firmware|embedded software)\b/.test(titleText)) { + return "swe"; + } + for (const key of ["it_security", "analyst", "hardware", "swe"] as const) { + if (matches(titleText, key)) return key; + } + if (titleText.includes("security engineer")) return "it_security"; + if (/\bsystems? engineer/.test(titleText)) { + for (const key of ["it_security", "hardware"] as const) { + if (matches(summaryText, key)) return key; + } + return "swe"; + } + // Only trust a description that points to exactly one family. + const summaryMatches = (Object.keys(ROLE_PATTERNS) as PatternKey[]).filter( + (key) => matches(summaryText, key), + ); + return summaryMatches.length === 1 && summaryMatches[0] + ? summaryMatches[0] + : "other"; +} + +const INTERNSHIP_SIGNAL = /\b(?:intern|internship|co ?op)\b/; +const NEW_GRAD_SIGNAL = + /\b(?:new grad|new graduate|entry level|early career|graduate|(?:software (?:engineer|developer)) (?:i|1))\b/; +// "manager" and "lead" are left out: "Product Manager Intern" is a student role. +const SENIORITY_SIGNAL = + /\b(?:senior|sr|staff|principal|director|vp|architect)\b/; + +/** + * The track for a listing, or null when it isn't a student role. A source + * scoped to one track (curated GitHub lists) is trusted as-is. + */ +export function classifyTrack( + title: string, + hint?: JOB_BOARD.JobTrack, +): JOB_BOARD.JobTrack | null { + if (hint) return hint; + const text = normalizeText(title); + if (INTERNSHIP_SIGNAL.test(text)) return "internship"; + if (SENIORITY_SIGNAL.test(text)) return null; + if (NEW_GRAD_SIGNAL.test(text)) return "new_grad"; + return null; +} diff --git a/packages/api/src/utils/job-board/ingest.ts b/packages/api/src/utils/job-board/ingest.ts new file mode 100644 index 000000000..7422e89be --- /dev/null +++ b/packages/api/src/utils/job-board/ingest.ts @@ -0,0 +1,442 @@ +import { z } from "zod"; + +import type { JOB_BOARD } from "@forge/consts"; +import type { CareerJobSourceSnapshot } from "@forge/validators"; +import { and, eq, inArray, isNull, lt, notExists, sql } from "@forge/db"; +import { db } from "@forge/db/client"; +import { + Job, + JobLocation, + JobObservation, + JobSource, +} from "@forge/db/schemas/job-board"; +import { Company } from "@forge/db/schemas/knight-hacks"; +import { + careerJobListingSchema, + careerJobSourceSnapshotSchema, +} from "@forge/validators"; + +import type { TransactionDb } from "../db"; +import type { ListingRejection, PreparedListing } from "./listing"; +import { prepareListing } from "./listing"; +import { companyKey, identityHash, preferredApplyUrl } from "./normalize"; + +/** Discord channel per track, read by cron from the Career config keys (#648). */ +export type JobDestinations = Partial< + Record +>; + +export interface JobIngestResult { + created: number; + updated: number; + rejected: Partial>; + deactivated: number; + /** True when this run completed the source's silent first-run baseline. */ + baselined: boolean; +} + +const DISCORD_ID = /^[0-9]{17,20}$/; + +// The snapshot envelope is checked whole; each listing is checked on its own +// so one malformed listing is counted as rejected instead of failing the board. +const snapshotEnvelopeSchema = careerJobSourceSnapshotSchema.extend({ + listings: z.array(z.unknown()), +}); + +/** A hash collision on a different raw key: never overwrite, always surface. */ +class IdentityMismatchError extends Error {} + +async function findOrCreateSource(source: CareerJobSourceSnapshot["source"]) { + const boardKeyHash = identityHash(source.boardKey); + await db + .insert(JobSource) + .values(source) + .onConflictDoNothing({ + target: [JobSource.provider, JobSource.boardKeyHash], + }); + const [row] = await db + .select() + .from(JobSource) + .where( + and( + eq(JobSource.provider, source.provider), + eq(JobSource.boardKeyHash, boardKeyHash), + ), + ); + if (row?.boardKey !== source.boardKey) { + throw new IdentityMismatchError( + `Job source ${source.provider} board key does not match its hash.`, + ); + } + return row; +} + +/** Approved Guild companies by normalized display name and alias. Never creates one. */ +async function loadCompanyIds() { + const companies = await db + .select({ + id: Company.id, + normalizedDisplayName: Company.normalizedDisplayName, + aliases: Company.aliases, + }) + .from(Company) + .where(eq(Company.reviewState, "approved")); + const ids = new Map(); + for (const company of companies) { + for (const alias of company.aliases) { + const key = companyKey(alias); + if (key) ids.set(key, company.id); + } + } + // Display names win over aliases that collide with them. + for (const company of companies) { + const key = companyKey(company.normalizedDisplayName); + if (key) ids.set(key, company.id); + } + return ids; +} + +/** The existing job for a listing: by its observation first, then by identity. */ +async function findJob( + tx: TransactionDb, + sourceId: string, + listing: PreparedListing, +) { + const [observation] = await tx + .select({ + jobId: JobObservation.jobId, + externalId: JobObservation.externalId, + }) + .from(JobObservation) + .where( + and( + eq(JobObservation.sourceId, sourceId), + eq(JobObservation.externalIdHash, identityHash(listing.externalId)), + ), + ); + if (observation && observation.externalId !== listing.externalId) { + throw new IdentityMismatchError( + "Observation external ID does not match its hash.", + ); + } + + const condition = observation + ? eq(Job.id, observation.jobId) + : inArray(Job.identityHash, listing.identityKeys.map(identityHash)); + const jobs = await tx.select().from(Job).where(condition).for("update"); + if ( + !observation && + jobs.some((job) => !listing.identityKeys.includes(job.identityKey)) + ) { + throw new IdentityMismatchError( + "Job identity key does not match its hash.", + ); + } + // Prefer the job matched by the strongest key. + return ( + listing.identityKeys + .map((key) => jobs.find((job) => job.identityKey === key)) + .find(Boolean) ?? jobs[0] + ); +} + +async function ingestListing( + sourceId: string, + listing: PreparedListing, + context: { + seenAt: Date; + baselined: boolean; + destinations: JobDestinations; + companyIds: Map; + }, +) { + return db.transaction(async (tx) => { + const { seenAt } = context; + const companyId = context.companyIds.get(listing.companyKey) ?? null; + let job = await findJob(tx, sourceId, listing); + let created = false; + + if (!job) { + const channel = context.destinations[listing.track]; + // Before the baseline, or with no channel for the track, jobs stay suppressed. + const delivery = + context.baselined && channel + ? { + deliveryState: "pending" as const, + deliveryTrack: listing.track, + discordChannelId: channel, + } + : {}; + const identityKey = listing.identityKeys[0]; + const [inserted] = await tx + .insert(Job) + .values({ + identityKey, + companyId, + companyLabel: listing.companyLabel, + companyKey: listing.companyKey, + title: listing.title, + track: listing.track, + category: listing.category, + applyUrl: listing.applyUrl, + description: listing.description, + compensation: listing.compensation, + workArrangement: listing.workArrangement, + postedAt: listing.postedAt, + firstSeenAt: seenAt, + lastSeenAt: seenAt, + ...delivery, + }) + .onConflictDoNothing({ target: Job.identityHash }) + .returning(); + if (inserted) { + job = inserted; + created = true; + } else { + // A concurrent ingest inserted the same identity first. Its row may + // already be stale or closed, so it goes through the update below. + job = await findJob(tx, sourceId, listing); + if (!job) + throw new Error( + `Job ${identityKey} vanished after an insert conflict.`, + ); + } + } + + // The observation goes first: whether the job may reopen depends on + // whether this sighting leaves its observation open. + const fresher = sql`${JobObservation.lastSeenAt} <= ${seenAt}`; + const [observation] = await tx + .insert(JobObservation) + .values({ + sourceId, + jobId: job.id, + externalId: listing.externalId, + sourceUrl: listing.sourceUrl, + sourceData: listing.sourceData, + postedAt: listing.postedAt, + firstSeenAt: seenAt, + lastSeenAt: seenAt, + }) + .onConflictDoUpdate({ + target: [JobObservation.sourceId, JobObservation.externalIdHash], + set: { + // A stale replay keeps the newer sighting's metadata. + sourceUrl: sql`case when ${fresher} then ${listing.sourceUrl} else ${JobObservation.sourceUrl} end`, + sourceData: sql`case when ${fresher} then ${JSON.stringify(listing.sourceData)}::jsonb else ${JobObservation.sourceData} end`, + postedAt: sql`case when ${fresher} then ${listing.postedAt}::timestamptz else ${JobObservation.postedAt} end`, + lastSeenAt: sql`greatest(${JobObservation.lastSeenAt}, ${seenAt})`, + // Same stale-snapshot rule as the job: reopen only if seen after closing. + inactiveAt: sql`case when ${JobObservation.inactiveAt} < ${seenAt} then null else ${JobObservation.inactiveAt} end`, + }, + }) + .returning({ inactiveAt: JobObservation.inactiveAt }); + + if (!created) { + // Track and first-seen never change; a reactivated job is not reposted. + // The job reopens only when this sighting left its observation open and + // is newer than the job's closing. A sighting older than the job's last + // one must not replace its details either. + const reopen = + observation?.inactiveAt === null && + (job.inactiveAt === null || job.inactiveAt < seenAt); + const fresh = seenAt >= job.lastSeenAt; + await tx + .update(Job) + .set({ + ...(fresh && { + title: listing.title, + category: listing.category, + applyUrl: preferredApplyUrl(job.applyUrl, listing.applyUrl), + description: listing.description ?? job.description, + compensation: listing.compensation ?? job.compensation, + workArrangement: listing.workArrangement ?? job.workArrangement, + postedAt: listing.postedAt ?? job.postedAt, + }), + // Match by the job's own company key, which comes from its first + // listing, not by this listing's label. + companyId: + job.companyId ?? context.companyIds.get(job.companyKey) ?? null, + lastSeenAt: sql`greatest(${Job.lastSeenAt}, ${seenAt})`, + ...(reopen && { active: true, inactiveAt: null }), + }) + .where(eq(Job.id, job.id)); + } + + const known = new Set( + ( + await tx + .select({ sourceText: JobLocation.sourceText }) + .from(JobLocation) + .where(eq(JobLocation.jobId, job.id)) + ).map((row) => row.sourceText), + ); + const additions = listing.locations.filter((location) => { + if (known.has(location.sourceText)) return false; + known.add(location.sourceText); + return true; + }); + if (additions.length > 0) { + await tx + .insert(JobLocation) + .values(additions.map((location) => ({ ...location, jobId: job.id }))); + } + + return created; + }); +} + +/** Closes this source's observations missing from a full inventory, then their jobs. */ +async function closeMissing(sourceId: string, seenAt: Date) { + const missing = and( + eq(JobObservation.sourceId, sourceId), + isNull(JobObservation.inactiveAt), + lt(JobObservation.lastSeenAt, seenAt), + ); + return db.transaction(async (tx) => { + const candidates = await tx + .selectDistinct({ jobId: JobObservation.jobId }) + .from(JobObservation) + .where(missing); + if (candidates.length === 0) return 0; + + // Lock the jobs first, in a statement of their own and in id order, like + // the listing transactions do. Two sources closing the last two open + // observations of one job then run one after the other, so the second + // sees the first's closure and deactivates the job. + await tx + .select({ id: Job.id }) + .from(Job) + .where( + inArray( + Job.id, + candidates.map((row) => row.jobId), + ), + ) + .orderBy(Job.id) + .for("update"); + + // Only the locked jobs' observations: one committed after the candidate + // read belongs to a job this transaction doesn't hold. + const closed = await tx + .update(JobObservation) + .set({ inactiveAt: seenAt }) + .where( + and( + missing, + inArray( + JobObservation.jobId, + candidates.map((row) => row.jobId), + ), + ), + ) + .returning({ jobId: JobObservation.jobId }); + const jobIds = [...new Set(closed.map((row) => row.jobId))]; + if (jobIds.length === 0) return 0; + + const openObservation = tx + .select({ id: JobObservation.id }) + .from(JobObservation) + .where( + and( + eq(JobObservation.jobId, Job.id), + isNull(JobObservation.inactiveAt), + ), + ); + const deactivated = await tx + .update(Job) + .set({ active: false, inactiveAt: seenAt }) + .where( + and( + inArray(Job.id, jobIds), + eq(Job.active, true), + notExists(openObservation), + ), + ) + .returning({ id: Job.id }); + return deactivated.length; + }); +} + +/** + * Turns one source's snapshot into deduplicated jobs (#649). Cron-only: see + * `@forge/api/job-board.server`. Throws on an incomplete snapshot or a DB + * failure, leaving the baseline unset so the next run is still silent. + * + * Callers run one ingest per source at a time, holding the `JobSource` claim + * (#647, #653). Runs of different sources may overlap; the job locks and + * conflict handling below cover that. Two runs of the same source at once, or + * an older snapshot finishing after a newer one, are guarded only where it is + * cheap; the claim is what prevents them. + */ +export async function ingestJobSnapshot( + input: CareerJobSourceSnapshot, + destinations: JobDestinations, +): Promise { + const snapshot = snapshotEnvelopeSchema.parse(input); + if (!snapshot.complete) { + throw new Error( + `Job source ${snapshot.source.provider}:${snapshot.source.boardKey} sent an incomplete snapshot.`, + ); + } + for (const [track, channel] of Object.entries(destinations)) { + if (channel && !DISCORD_ID.test(channel)) { + throw new Error( + `Career ${track} channel "${channel}" is not a Discord ID.`, + ); + } + } + + const source = await findOrCreateSource(snapshot.source); + const context = { + seenAt: snapshot.fetchedAt, + baselined: source.baselineCompletedAt !== null, + destinations, + companyIds: await loadCompanyIds(), + }; + const result: JobIngestResult = { + created: 0, + updated: 0, + rejected: {}, + deactivated: 0, + baselined: false, + }; + + for (const raw of snapshot.listings) { + const parsed = careerJobListingSchema.safeParse(raw); + // A rejected listing counts as unseen, so a full inventory closes its job. + const prepared = parsed.success + ? prepareListing(parsed.data, source) + : { ok: false as const, reason: "invalid_listing" as const }; + if (!prepared.ok) { + result.rejected[prepared.reason] = + (result.rejected[prepared.reason] ?? 0) + 1; + continue; + } + if (await ingestListing(source.id, prepared.listing, context)) + result.created++; + else result.updated++; + } + + if (snapshot.inventory === "full") { + result.deactivated = await closeMissing(source.id, snapshot.fetchedAt); + } + + // Only the run that actually sets the baseline reports it. + const now = new Date(); + const [baselinedSource] = await db + .update(JobSource) + .set({ baselineCompletedAt: now, lastSuccessAt: now }) + .where( + and(eq(JobSource.id, source.id), isNull(JobSource.baselineCompletedAt)), + ) + .returning({ id: JobSource.id }); + if (!baselinedSource) { + await db + .update(JobSource) + .set({ lastSuccessAt: now }) + .where(eq(JobSource.id, source.id)); + } + result.baselined = Boolean(baselinedSource); + return result; +} diff --git a/packages/api/src/utils/job-board/listing.ts b/packages/api/src/utils/job-board/listing.ts new file mode 100644 index 000000000..ac5ed9ad7 --- /dev/null +++ b/packages/api/src/utils/job-board/listing.ts @@ -0,0 +1,87 @@ +import type { JOB_BOARD } from "@forge/consts"; +import type { CareerJobListing } from "@forge/validators"; + +import type { ParsedLocation } from "./locations"; +import { classifyCategory, classifyTrack } from "./classify"; +import { + isForeignLocation, + parseLocation, + splitLocationTexts, + workArrangement, +} from "./locations"; +import { cleanApplyUrl, companyKey, identityKeys } from "./normalize"; + +export type ListingRejection = + | "invalid_listing" + | "invalid_apply_url" + | "not_student_role" + | "non_us"; + +export interface PreparedListing { + externalId: string; + identityKeys: [string, ...string[]]; + track: JOB_BOARD.JobTrack; + category: JOB_BOARD.JobCategory; + companyLabel: string; + companyKey: string; + title: string; + applyUrl: string; + description: string | null; + compensation: string | null; + postedAt: Date | null; + workArrangement: JOB_BOARD.JobWorkArrangement | null; + locations: ParsedLocation[]; + sourceUrl: string; + sourceData: Record; +} + +/** Applies every job rule that needs no database. */ +export function prepareListing( + listing: CareerJobListing, + source: { provider: string; boardKey: string }, +): + | { ok: true; listing: PreparedListing } + | { ok: false; reason: ListingRejection } { + const applyUrl = cleanApplyUrl(listing.applyUrl); + if (!applyUrl) return { ok: false, reason: "invalid_apply_url" }; + // A label with no ASCII letters or digits leaves no key to group or filter by. + const key = companyKey(listing.companyLabel); + if (!key) return { ok: false, reason: "invalid_listing" }; + + const track = classifyTrack(listing.title, listing.track); + if (!track) return { ok: false, reason: "not_student_role" }; + + const locationTexts = splitLocationTexts(listing.locationTexts); + // Mixed lists keep their U.S. entries; only an all-foreign listing is dropped. + const usTexts = locationTexts.filter((text) => !isForeignLocation(text)); + if (locationTexts.length > 0 && usTexts.length === 0) { + return { ok: false, reason: "non_us" }; + } + + const description = listing.description?.trim() ?? ""; + const compensation = listing.compensation?.trim() ?? ""; + return { + ok: true, + listing: { + externalId: listing.externalId, + identityKeys: identityKeys({ + ...source, + applyUrl, + externalId: listing.externalId, + }), + track, + category: classifyCategory(listing.title, description), + companyLabel: listing.companyLabel, + companyKey: key, + title: listing.title, + applyUrl, + description: description || null, + compensation: compensation || null, + postedAt: listing.postedAt ?? null, + workArrangement: workArrangement(usTexts), + locations: usTexts.map(parseLocation), + sourceUrl: listing.sourceUrl, + sourceData: listing.sourceData, + }, + }; +} diff --git a/packages/api/src/utils/job-board/locations.ts b/packages/api/src/utils/job-board/locations.ts new file mode 100644 index 000000000..a42326472 --- /dev/null +++ b/packages/api/src/utils/job-board/locations.ts @@ -0,0 +1,243 @@ +import type { JOB_BOARD } from "@forge/consts"; + +import { findUsCity } from "../career/us-cities"; + +// U.S. scope rules ported from CS Job Poster `utils/feed_normalization.py` +// (`is_us_location`) and `utils/normalization.py` (`normalize_location`). + +const STATE_CODES_BY_NAME: Record = { + alabama: "AL", + alaska: "AK", + arizona: "AZ", + arkansas: "AR", + california: "CA", + colorado: "CO", + connecticut: "CT", + delaware: "DE", + florida: "FL", + georgia: "GA", + hawaii: "HI", + idaho: "ID", + illinois: "IL", + indiana: "IN", + iowa: "IA", + kansas: "KS", + kentucky: "KY", + louisiana: "LA", + maine: "ME", + maryland: "MD", + massachusetts: "MA", + michigan: "MI", + minnesota: "MN", + mississippi: "MS", + missouri: "MO", + montana: "MT", + nebraska: "NE", + nevada: "NV", + "new hampshire": "NH", + "new jersey": "NJ", + "new mexico": "NM", + "new york": "NY", + "north carolina": "NC", + "north dakota": "ND", + ohio: "OH", + oklahoma: "OK", + oregon: "OR", + pennsylvania: "PA", + "rhode island": "RI", + "south carolina": "SC", + "south dakota": "SD", + tennessee: "TN", + texas: "TX", + utah: "UT", + vermont: "VT", + virginia: "VA", + washington: "WA", + "west virginia": "WV", + wisconsin: "WI", + wyoming: "WY", + "district of columbia": "DC", +}; +const STATE_CODES = new Set(Object.values(STATE_CODES_BY_NAME)); +const STATE_NAMES = Object.keys(STATE_CODES_BY_NAME).join("|"); + +const CITY_ALIASES: Record = { + nyc: { city: "New York", state: "NY" }, + sf: { city: "San Francisco", state: "CA" }, +}; + +const EXPLICIT_US = new RegExp( + String.raw`\bUnited States\b|\bUSA\b|\bNYC\b|\bSF\b|\b(?:${STATE_NAMES})\b`, + "i", +); +// Case-sensitive: a case-insensitive `us`, `IN` or `OR` would turn prose +// ("join us") into U.S. evidence. +const US_ABBREVIATION = /\bUS\b|\bU\.S\.(?=\s|$|[,)\]-])/; +const US_STATE_CODE = new RegExp( + String.raw`(?:,\s*|\b)(?:${[...STATE_CODES].join("|")})\b`, +); +const FOREIGN = new RegExp( + String.raw`\b(?:Canada|Canadian|Toronto|Vancouver|Montreal|Calgary|Ottawa|Edmonton|Kitchener|` + + String.raw`United Kingdom|UK|London|India|Germany|France|Ireland|Poland|Singapore|Australia|` + + String.raw`Netherlands|Spain|Sweden|(?(record: Record, key: string) { + return Object.hasOwn(record, key) ? record[key] : undefined; +} + +function stateCode(value: string) { + const trimmed = value.trim().replace(/\.$/, ""); + if (STATE_CODES.has(trimmed.toUpperCase()) && trimmed.length === 2) { + return trimmed.toUpperCase(); + } + return ( + ownValue( + STATE_CODES_BY_NAME, + trimmed.toLowerCase().replace(/\s+state$/, ""), + ) ?? null + ); +} + +/** "City, ST", "City, State", "ST", "State", or a city alias; null when none fits. */ +function parseCityState(text: string) { + const alias = ownValue(CITY_ALIASES, text.toLowerCase()); + if (alias) return alias; + + const value = text + .replace(COUNTRY_SUFFIX, "") + .replace(COUNTRY_PREFIX, "") + .trim(); + const parts = value + .split(",") + .map((part) => part.trim()) + .filter(Boolean); + + // Country-first "United States, Washington, Redmond" arrives as "Washington, Redmond". + if (parts.length >= 2 && COUNTRY_PREFIX.test(text)) { + const state = stateCode(parts[0] ?? ""); + if (state) return { city: parts.slice(1).join(" "), state }; + } + if (parts.length >= 2) { + const state = stateCode(parts.at(-1) ?? ""); + if (state) return { city: parts.slice(0, -1).join(" "), state }; + } + if (parts.length === 1 && parts[0]) { + const state = stateCode(parts[0]); + if (state) return { city: null, state }; + const spaced = /^(.+?)\s+([A-Z]{2})$/.exec(parts[0]); + if (spaced?.[1] && spaced[2] && STATE_CODES.has(spaced[2])) { + return { city: spaced[1], state: spaced[2] }; + } + } + return null; +} + +function hasUsEvidence(text: string) { + return ( + EXPLICIT_US.test(text) || + US_ABBREVIATION.test(text) || + US_STATE_CODE.test(text) || + // "City, st" in any case: a state in the city/state slot, not prose. + parseCityState(text) !== null + ); +} + +/** + * Whether a location's text is explicitly outside the U.S. Any U.S. evidence + * wins, so "London, KY" and "Austin, TX or Toronto, ON" stay in scope. + */ +export function isForeignLocation(text: string) { + return ( + (FOREIGN.test(text) || CANADIAN_PROVINCE.test(text)) && !hasUsEvidence(text) + ); +} + +/** + * One location text as a `JobLocation`. Remote alone isn't U.S. evidence, and + * anything unresolved stays `unknown` with its original text. + */ +export function parseLocation(sourceText: string): ParsedLocation { + const text = sourceText.replace(/\s+/g, " ").trim(); + const unknown: ParsedLocation = { + sourceText: text, + kind: "unknown", + cityKey: null, + state: null, + }; + + if (/\bremote\b/i.test(text)) { + return hasUsEvidence(text) ? { ...unknown, kind: "remote_us" } : unknown; + } + + const stripped = text + .replace(/^(?:hybrid|on-?site|in office)\s*[-:(]\s*/i, "") + .replace(/\)$/, ""); + const parsed = parseCityState(stripped); + if (!parsed) return unknown; + + const city = parsed.city ? findUsCity(parsed.city, parsed.state) : null; + if (city) { + return { + sourceText: text, + kind: "city", + cityKey: city.key, + state: city.state, + }; + } + return { + sourceText: text, + kind: "state", + cityKey: null, + state: parsed.state, + }; +} + +/** + * Splits one text that lists several places ("Austin, TX / Remote - US", + * "Austin, TX or Toronto, ON"). An "or" splits only when it is lowercase (so + * "Salem, OR" stays whole) and every side is a "City, ST" place (so + * "US or Canada (Remote)" stays one remote location). + */ +export function splitLocationTexts(texts: string[]) { + return texts + .flatMap((text) => text.split(/\s*(?:;|\||\s\/\s|)\s*/i)) + .flatMap((text) => { + const sides = text.split(/\s+or\s+/); + return sides.length > 1 && sides.every((side) => side.includes(",")) + ? sides + : [text]; + }) + .map((text) => text.trim()) + .filter(Boolean); +} + +/** Work arrangement implied by the location texts, when they say. */ +export function workArrangement( + texts: string[], +): JOB_BOARD.JobWorkArrangement | null { + const joined = texts.join(" "); + if (/\bremote\b/i.test(joined)) return "remote"; + if (/\bhybrid\b/i.test(joined)) return "hybrid"; + return null; +} diff --git a/packages/api/src/utils/job-board/normalize.ts b/packages/api/src/utils/job-board/normalize.ts new file mode 100644 index 000000000..df4713b39 --- /dev/null +++ b/packages/api/src/utils/job-board/normalize.ts @@ -0,0 +1,240 @@ +import { createHash } from "node:crypto"; + +import { normalizeCompanyName } from "@forge/validators"; + +// Ported from CS Job Poster `utils/normalization.py` and +// `utils/feed_normalization.py` (#633). Identity is strict: only employer +// requisition IDs, the apply URL, or the source's own ID ever link listings. + +const TRACKING_QUERY_KEYS = new Set([ + "ref", + "referrer", + "source", + "gh_src", + "gh_source", +]); + +/** Hosts that wrap an employer's application page rather than host it. */ +const AGGREGATOR_HOSTS = new Set([ + "jobright.ai", + "www.jobright.ai", + "simplify.jobs", + "www.simplify.jobs", + "speedyapply.com", + "www.speedyapply.com", +]); + +/** + * Canonical apply URL: https/http only, lowercase host, no tracking params, no + * duplicate or trailing slashes, no trailing `/apply`. A fragment is dropped + * unless it is a hash route (`#/jobs/42`), which is the posting's real address. + * Returns null for anything that isn't an http(s) URL. + */ +export function cleanApplyUrl(raw: string): string | null { + let url: URL; + try { + url = new URL(raw.trim()); + } catch { + return null; + } + if (url.protocol !== "https:" && url.protocol !== "http:") return null; + if (url.username || url.password) return null; + + cleanRoute(url); + if (url.hash.startsWith("#/")) { + // A hash route gets the same cleanup as the real path, so `#/jobs/42/` + // and `#/jobs/42?utm_source=x` match `#/jobs/42`. + // Collapse leading slashes so `#//jobs` stays a path, not a host. + const route = new URL( + url.hash.slice(1).replace(/^\/+/, "/"), + "https://hash.invalid", + ); + cleanRoute(route); + url.hash = route.pathname + route.search; + } else { + url.hash = ""; + } + return url.toString(); +} + +/** Drops tracking params, sorts the rest, and tidies the path in place. */ +function cleanRoute(url: URL) { + for (const key of [...url.searchParams.keys()]) { + const lowered = key.toLowerCase(); + if (TRACKING_QUERY_KEYS.has(lowered) || lowered.startsWith("utm_")) { + url.searchParams.delete(key); + } + } + url.searchParams.sort(); + + let path = url.pathname.replace(/\/{2,}/g, "/").replace(/\/+$/, ""); + if (path.toLowerCase().endsWith("/apply")) path = path.slice(0, -6); + url.pathname = path || "/"; +} + +export function isAggregatorUrl(url: string) { + try { + return AGGREGATOR_HOSTS.has(new URL(url).hostname); + } catch { + return false; + } +} + +/** Keep a direct employer link over an aggregator copy; otherwise take the newest. */ +export function preferredApplyUrl(existing: string, candidate: string) { + return isAggregatorUrl(candidate) && !isAggregatorUrl(existing) + ? existing + : candidate; +} + +/** Whether `host` is `domain` itself or one of its subdomains. */ +function onDomain(host: string, domain: string) { + return host === domain || host.endsWith(`.${domain}`); +} + +/** Employer requisition keys an apply URL proves, strongest first. */ +function atsKeys(url: URL): string[] { + const host = url.hostname; + const parts = url.pathname + .split("/") + .filter((part) => part && part.toLowerCase() !== "apply"); + const keys: string[] = []; + + // Greenhouse job IDs are numeric; anything else (`/jobs/search`) is a page. + const ghJid = url.searchParams.get("gh_jid"); + if (ghJid && /^\d+$/.test(ghJid)) keys.push(`ats:greenhouse:${ghJid}`); + if (onDomain(host, "greenhouse.io") && parts.includes("jobs")) { + const jobId = parts[parts.indexOf("jobs") + 1]; + if (jobId && /^\d+$/.test(jobId)) keys.push(`ats:greenhouse:${jobId}`); + } + if ((host === "jobs.lever.co" || host === "jobs.eu.lever.co") && parts[1]) { + keys.push(`ats:lever:${parts[1].toLowerCase()}`); + } + if (host === "jobs.ashbyhq.com" && parts[1]) { + keys.push(`ats:ashby:${parts[1].toLowerCase()}`); + } + if ( + onDomain(host, "myworkdayjobs.com") || + onDomain(host, "myworkdaysite.com") + ) { + // Only a posting URL ends in `_<requisition>`; landing pages don't. + // The tenant is the first host label (`acme.wd5.myworkdayjobs.com`), or the + // segment after `recruiting` on shared hosts (`wd5.myworkdaysite.com/ + // recruiting/acme/...`). With neither, requisitions can't be told apart + // across employers, so there is no key. + const label = host.split(".")[0] ?? ""; + const recruiting = parts.findIndex( + (part) => part.toLowerCase() === "recruiting", + ); + const tenant = ( + recruiting >= 0 + ? parts[recruiting + 1] + : /^(?:www|wd\d+)$/i.test(label) + ? undefined + : label + )?.toLowerCase(); + const requisition = /_([a-z0-9-]*[0-9][a-z0-9-]*)$/i + .exec(parts.at(-1) ?? "")?.[1] + ?.toLowerCase(); + if (tenant && requisition) { + keys.push(`ats:workday:${tenant}:${requisition}`); + } + } + return [...new Set(keys)]; +} + +/** + * Query parameter names that carry a posting ID (`id`, `jobId`, `job_id`, + * `gh_jid`, `req`...). A filter like `department_id` or `location_id` names a + * search page, not a posting. + */ +const POSTING_ID_PARAM = + /^(?:(?:gh_)?j?id|job|req|requisition|posting)$|(?:job|req|requisition|posting)[_-]?id$/i; + +/** + * Path segments that introduce one posting's ID: `/jobs/42`, `/j/AB12CD` + * (Workable), `/careers/123` (BambooHR), `/positions/R-7`. + */ +const POSTING_ROUTE = + /^(?:j|jobs?|careers?|positions?|postings?|openings?|req|requisitions?|vacanc(?:y|ies))$/i; + +/** + * Digit runs in a path segment that could be an ID. A bare year (`2026`) and a + * page number (`page-2`) never are, so `/careers/2026`, `/careers/summer-2026` + * and `/jobs/page-2` stay landing pages. + */ +function idDigits(segment: string) { + if (/^page[-_]?\d+$/i.test(segment)) return []; + return (segment.match(/\d+/g) ?? []).filter( + (run) => !/^(?:19|20)\d\d$/.test(run), + ); +} + +/** + * Whether a URL points at one posting rather than a careers landing page that + * many listings share. A posting URL carries an ID in some path segment, either + * right after a posting route (`/jobs/1234/software-intern`) or as a long number + * on its own (`/details/200512345/...`), or in an ID-named query parameter. A + * hash route (`#/jobs/42`) counts as the path. + */ +function identifiesPosting(url: URL) { + const path = url.hash.startsWith("#/") + ? (url.hash.slice(1).split("?")[0] ?? "") + : url.pathname; + const segments = path.split("/").filter(Boolean); + const pathId = segments.some((segment, index) => { + const digits = idDigits(segment); + const afterRoute = + index > 0 && POSTING_ROUTE.test(segments[index - 1] ?? ""); + return ( + (afterRoute && digits.length > 0) || digits.some((run) => run.length >= 4) + ); + }); + return ( + pathId || + [...url.searchParams].some( + ([name, value]) => POSTING_ID_PARAM.test(name) && /[0-9]/.test(value), + ) + ); +} + +/** + * Every identity a listing can be matched by, strongest first. The first entry + * becomes a new job's `identityKey`; lookups try all of them. The source key + * is always last, so there is always at least one. + */ +export function identityKeys(input: { + applyUrl: string; + provider: string; + boardKey: string; + externalId: string; +}): [string, ...string[]] { + const url = new URL(input.applyUrl); + const keys: [string, ...string[]] = [ + // JSON keeps the parts apart even when a board key or ID contains ":". + `source:${JSON.stringify([input.provider, input.boardKey, input.externalId])}`, + ]; + // An aggregator URL wraps someone else's posting, and a landing page is + // shared by many postings, so neither identifies a job. + if (!isAggregatorUrl(input.applyUrl) && identifiesPosting(url)) { + keys.unshift(`url:${input.applyUrl}`); + } + keys.unshift(...atsKeys(url)); + return keys; +} + +/** + * SHA-256 hex of the UTF-8 key: the same value as the generated `*_hash` + * columns in `@forge/db` job-board tables. + */ +export function identityHash(key: string) { + return createHash("sha256").update(key, "utf8").digest("hex"); +} + +/** + * Grouping key for a company label, valid for `companyKeySchema`. Empty when + * the label has no ASCII letters or digits, which leaves nothing to group by. + */ +export function companyKey(label: string) { + return normalizeCompanyName(label).slice(0, 120).trim(); +} diff --git a/packages/consts/src/job-board.ts b/packages/consts/src/job-board.ts index c4f081c9e..d3578812e 100644 --- a/packages/consts/src/job-board.ts +++ b/packages/consts/src/job-board.ts @@ -198,3 +198,12 @@ export type JobDeliveryState = (typeof JOB_DELIVERY_STATES)[number]; export const JOB_SEARCH_DEFAULT_LIMIT = 25; export const JOB_SEARCH_MAX_LIMIT = 50; export const JOB_SEARCH_MAX_QUERY_LENGTH = 120; + +/** + * Whether a source snapshot lists every open role. Only a `full` inventory can + * close a listing that disappears; a `rolling` feed (e.g. a GitHub list) drops + * roles for other reasons, so absence there proves nothing. + */ +export const JOB_SOURCE_INVENTORIES = ["full", "rolling"] as const; + +export type JobSourceInventory = (typeof JOB_SOURCE_INVENTORIES)[number]; diff --git a/packages/validators/src/job-board.ts b/packages/validators/src/job-board.ts index 8cf65b632..9b227b8e3 100644 --- a/packages/validators/src/job-board.ts +++ b/packages/validators/src/job-board.ts @@ -307,3 +307,96 @@ export type AlertPreferenceInput = z.infer< typeof alertPreferenceCreateInputSchema >; export type DigestOptInInput = z.infer<typeof digestOptInInputSchema>; + +// PostgreSQL text and jsonb can't store NUL, and a lone UTF-16 surrogate (an +// emoji cut in half) is stored as U+FFFD, so the stored text no longer equals +// the listing's. A listing carrying either is rejected on its own instead of +// failing the database write, or a later identity check, for the board. +const STORABLE_MESSAGE = + "Text can't contain NUL or unpaired surrogate characters."; +const LONE_SURROGATE = + /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/; +const storable = (value: string) => + !value.includes("\0") && !LONE_SURROGATE.test(value); +const text = () => z.string().refine(storable, STORABLE_MESSAGE); +const nonBlankText = (max: number) => text().trim().min(1).max(max); + +/** + * Whether a value can be stored as jsonb: JSON-serializable, and no key or + * string holds NUL or a lone surrogate (jsonb rejects both). Each string is + * checked as JSON.stringify visits it, so escaped text such as the six + * characters `\u0000` is still allowed. + */ +function isStorableJson(value: unknown) { + let ok = true; + try { + JSON.stringify(value, (key, item: unknown) => { + if (!storable(key) || (typeof item === "string" && !storable(item))) { + ok = false; + } + return item; + }); + } catch { + return false; + } + return ok; +} + +/** + * One parsed listing as a cron source adapter hands it to ingestion. `track` is + * set only when the source itself is scoped to one track (e.g. a GitHub + * internship list); otherwise the API classifies it from the title. + */ +export const careerJobListingSchema = z + .object({ + externalId: nonBlankText(2_048), + track: jobTrackSchema.optional(), + companyLabel: nonBlankText(200), + title: nonBlankText(500), + applyUrl: z.url({ protocol: /^https?$/ }).max(4_096), + postedAt: z.date().optional(), + // Truncated, not rejected: long HTML job bodies are common on ATS boards. + description: text() + .transform((value) => value.slice(0, 20_000)) + .optional(), + compensation: text().trim().max(200).optional(), + locationTexts: z.array(nonBlankText(500)).max(100), + // Stored as given (unlike applyUrl, which is re-encoded), so check it here. + sourceUrl: z + .url({ protocol: /^https?$/ }) + .max(4_096) + .refine(storable, STORABLE_MESSAGE), + sourceData: z + .record(z.string(), z.unknown()) + .refine(isStorableJson, "Source data must be storable JSON."), + }) + .strict(); + +/** + * Contract between cron source adapters (#652) and `@forge/api` ingestion + * (#649), agreed in #633. `complete` means the whole response parsed; + * `inventory` says whether missing listings may be closed. + */ +export const careerJobSourceSnapshotSchema = z + .object({ + source: z + .object({ + provider: z + .string() + .max(64) + .regex(/^[a-z][a-z0-9_]*$/), + boardKey: nonBlankText(2_048), + label: nonBlankText(200), + }) + .strict(), + fetchedAt: z.date(), + complete: z.boolean(), + inventory: z.enum(JOB_BOARD.JOB_SOURCE_INVENTORIES), + listings: z.array(careerJobListingSchema), + }) + .strict(); + +export type CareerJobListing = z.infer<typeof careerJobListingSchema>; +export type CareerJobSourceSnapshot = z.infer< + typeof careerJobSourceSnapshotSchema +>;