From 73b146fdb64a39632540e2cd740e4cba0bd4ad80 Mon Sep 17 00:00:00 2001 From: Jesus Gonzalez Date: Thu, 19 Nov 2026 11:16:29 -0500 Subject: [PATCH 1/3] added career job ingestion, dedupe and classification services Co-Authored-By: Claude Opus 5.5 --- .forge/features/career-job-ingestion/spec.md | 79 ++++ .forge/features/career-job-ingestion/srd.md | 135 +++++++ .../features/career-job-ingestion/status.md | 47 +++ .../career-job-ingestion/test-cases.md | 50 +++ packages/api/package.json | 4 + packages/api/src/job-board.server.ts | 5 + .../integration/job-board-ingest.test.ts | 303 +++++++++++++++ .../tests/job-board/ingestion-rules.test.ts | 230 +++++++++++ packages/api/src/utils/career/us-cities.ts | 16 + packages/api/src/utils/job-board/classify.ts | 106 ++++++ packages/api/src/utils/job-board/ingest.ts | 360 ++++++++++++++++++ packages/api/src/utils/job-board/listing.ts | 83 ++++ packages/api/src/utils/job-board/locations.ts | 205 ++++++++++ packages/api/src/utils/job-board/normalize.ts | 135 +++++++ packages/consts/src/job-board.ts | 9 + packages/validators/src/job-board.ts | 52 +++ 16 files changed, 1819 insertions(+) create mode 100644 .forge/features/career-job-ingestion/spec.md create mode 100644 .forge/features/career-job-ingestion/srd.md create mode 100644 .forge/features/career-job-ingestion/status.md create mode 100644 .forge/features/career-job-ingestion/test-cases.md create mode 100644 packages/api/src/job-board.server.ts create mode 100644 packages/api/src/tests/integration/job-board-ingest.test.ts create mode 100644 packages/api/src/tests/job-board/ingestion-rules.test.ts create mode 100644 packages/api/src/utils/job-board/classify.ts create mode 100644 packages/api/src/utils/job-board/ingest.ts create mode 100644 packages/api/src/utils/job-board/listing.ts create mode 100644 packages/api/src/utils/job-board/locations.ts create mode 100644 packages/api/src/utils/job-board/normalize.ts diff --git a/.forge/features/career-job-ingestion/spec.md b/.forge/features/career-job-ingestion/spec.md new file mode 100644 index 000000000..eb69aef1f --- /dev/null +++ b/.forge/features/career-job-ingestion/spec.md @@ -0,0 +1,79 @@ +# Career job ingestion + +Status: Approved (2026-11-17) + +## 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. +- 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. + The employer's own apply link wins over an aggregator's. +- 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 + +- Should upstream's "recent catch-up" of baseline jobs be ported? Currently skipped. diff --git a/.forge/features/career-job-ingestion/srd.md b/.forge/features/career-job-ingestion/srd.md new file mode 100644 index 000000000..c6b733463 --- /dev/null +++ b/.forge/features/career-job-ingestion/srd.md @@ -0,0 +1,135 @@ +# 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`, which the + `careerJobSourceSnapshotSchema` validator checks. +2. Cron reads channel IDs from the #648 config keys and calls + `ingestJobSnapshot(snapshot, destinations)`. +3. Ingestion rejects the snapshot if `complete` is false. Otherwise it finds or + creates the `JobSource` row by (provider, boardKey). +4. Each listing 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), `lastSuccessAt`, and + `lastAttemptAt`. + +### Identity + +- Candidate keys, strongest first: + - `ats:greenhouse:`, `ats:lever:`, `ats:ashby:`, `ats:workday::` from the apply URL; + - `url:`; + - `source:::`. +- 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. + +### 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 by `normalizedDisplayName` or by a + normalized alias, following `mergedIntoCompanyId`. Ingestion never inserts a + `Company`. +- A job that reappears gets `active = true` and `inactiveAt = null`. Its delivery + state stays as it was, so it isn't posted again. + +### 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. +- 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 an optional +`track`. + +## 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 + +- Should upstream's recent catch-up of baseline jobs be ported? Currently skipped. diff --git a/.forge/features/career-job-ingestion/status.md b/.forge/features/career-job-ingestion/status.md new file mode 100644 index 000000000..cacaad939 --- /dev/null +++ b/.forge/features/career-job-ingestion/status.md @@ -0,0 +1,47 @@ +# Career job ingestion Status + +Current phase: Implemented, awaiting human review (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 unless employer evidence says otherwise. 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. + +## 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`. +- Should upstream's "recent catch-up" posting of jobs from the first run be ported? Currently skipped. + +## 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..d04c05fe4 --- /dev/null +++ b/.forge/features/career-job-ingestion/test-cases.md @@ -0,0 +1,50 @@ +# 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 and the Greenhouse board | Ingest both | One Job with two observations | +| TC-010 | Same snapshot ingested twice | Ingest | Second run: 0 created, job fields unchanged, `lastSeenAt` advances | +| 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 closed, job inactive | +| TC-015 | Rolling feed missing a listing | Ingest | Job stays active | +| TC-016 | Inactive job reappears | Ingest | Active again, delivery state unchanged | +| 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 | + +## Negative / regression cases + +| ID | Setup | Expected | +| ---------- | ------------------------------------------- | ------------------------- | +| TC-NEG-001 | `complete: false` | Rejected before any write | +| TC-NEG-002 | Two concurrent ingests of one identity | Exactly one Job row | +| TC-NEG-003 | Invalid listing (non-http URL, blank title) | Fails validation | + +## Open questions + +- None. diff --git a/packages/api/package.json b/packages/api/package.json index 1d0c920a6..70bedf4d4 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..5a3abb789 --- /dev/null +++ b/packages/api/src/tests/integration/job-board-ingest.test.ts @@ -0,0 +1,303 @@ +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 { DisposableDatabase } from "@forge/db/testing"; +import type { + CareerJobListing, + CareerJobSourceSnapshot, +} from "@forge/validators"; +import { eq, 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" }; + +describe.skipIf(!canRunDatabaseTests())("job board ingestion", () => { + let client: typeof db; + let schema: typeof JobBoardSchema; + 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); + + 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"); + ({ 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} 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 () => { + await run(snapshot([listing()])); + await run( + snapshot( + [ + listing({ + externalId: "gh-123", + sourceUrl: "https://boards.greenhouse.io/acme", + }), + ], + { + source: greenhouse, + inventory: "full", + }, + ), + ); + + expect(await jobs()).toHaveLength(1); + 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 board = (listings: CareerJobListing[]) => + snapshot(listings, { source: greenhouse, inventory: "full" }); + await run(board([listing()])); + + const closed = await run(board([])); + expect(closed.deactivated).toBe(1); + expect((await jobs())[0]).toMatchObject({ active: false }); + + await run(board([listing()]), { internship: INTERN_CHANNEL }); + expect((await jobs())[0]).toMatchObject({ + active: true, + inactiveAt: null, + deliveryState: "suppressed", + }); + }); + + 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 import("@forge/db/schemas/knight-hacks"); + 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); + await client.delete(Company).where(eq(Company.id, company?.id ?? "")); + }); + + it("counts rejected listings by reason", async () => { + const result = await run( + snapshot([ + listing({ externalId: "senior", title: "Senior Engineer" }), + listing({ externalId: "uk", locationTexts: ["London, UK"] }), + ]), + ); + expect(result.rejected).toEqual({ not_student_role: 1, non_us: 1 }); + expect(await jobs()).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 two sources ingest the same identity at once", async () => { + await Promise.all([ + run(snapshot([listing()])), + run( + snapshot([listing({ externalId: "gh" })], { + source: greenhouse, + inventory: "full", + }), + ), + ]); + expect(await jobs()).toHaveLength(1); + expect(await client.select().from(schema.JobObservation)).toHaveLength(2); + }); +}); 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..fcc08dafc --- /dev/null +++ b/packages/api/src/tests/job-board/ingestion-rules.test.ts @@ -0,0 +1,230 @@ +import { describe, expect, it } from "vitest"; + +import type { CareerJobListing } from "@forge/validators"; +import { careerJobSourceSnapshotSchema } 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 { parseLocation } from "../../utils/job-board/locations"; +import { + cleanApplyUrl, + identityHash, + identityKeys, + preferredApplyUrl, +} from "../../utils/job-board/normalize"; + +const source = { provider: "github", boardKey: "simplify/internships" }; + +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:github:simplify/internships:row-1", + ]); + 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:github:simplify/internships:row-1", + ]); + }); + + 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("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("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")).toMatchObject({ + kind: "unknown", + sourceText: "Remote", + }); + 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", + }); + }); +}); + +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("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("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..20d94ab0a --- /dev/null +++ b/packages/api/src/utils/job-board/ingest.ts @@ -0,0 +1,360 @@ +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 { + careerJobSourceSnapshotSchema, + normalizeCompanyName, +} from "@forge/validators"; + +import type { TransactionDb } from "../db"; +import type { ListingRejection, PreparedListing } from "./listing"; +import { prepareListing } from "./listing"; +import { 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}$/; + +/** 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) { + ids.set(normalizeCompanyName(alias), company.id); + } + } + // Display names win over aliases that collide with them. + for (const company of companies) { + ids.set(company.normalizedDisplayName, 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] ?? listing.externalId; + 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(); + // A concurrent ingest inserted the same identity first; use its row. + job = inserted ?? (await findJob(tx, sourceId, listing)); + if (!job) + throw new Error( + `Job ${identityKey} vanished after an insert conflict.`, + ); + created = Boolean(inserted); + } else { + // Track and first-seen never change; a reactivated job is not reposted. + await tx + .update(Job) + .set({ + 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, + companyId: job.companyId ?? companyId, + lastSeenAt: sql`greatest(${Job.lastSeenAt}, ${seenAt})`, + active: true, + inactiveAt: null, + }) + .where(eq(Job.id, job.id)); + } + + 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: { + sourceUrl: listing.sourceUrl, + sourceData: listing.sourceData, + postedAt: listing.postedAt, + lastSeenAt: sql`greatest(${JobObservation.lastSeenAt}, ${seenAt})`, + inactiveAt: null, + }, + }); + + 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) { + return db.transaction(async (tx) => { + const closed = await tx + .update(JobObservation) + .set({ inactiveAt: seenAt }) + .where( + and( + eq(JobObservation.sourceId, sourceId), + isNull(JobObservation.inactiveAt), + lt(JobObservation.lastSeenAt, seenAt), + ), + ) + .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. + */ +export async function ingestJobSnapshot( + input: CareerJobSourceSnapshot, + destinations: JobDestinations, +): Promise { + const snapshot = careerJobSourceSnapshotSchema.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 prepared = prepareListing(raw, source); + 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); + } + + const now = new Date(); + await db + .update(JobSource) + .set({ + baselineCompletedAt: source.baselineCompletedAt ?? now, + lastSuccessAt: now, + }) + .where(eq(JobSource.id, source.id)); + result.baselined = source.baselineCompletedAt === null; + 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..b95e9eb90 --- /dev/null +++ b/packages/api/src/utils/job-board/listing.ts @@ -0,0 +1,83 @@ +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_apply_url" + | "not_student_role" + | "non_us"; + +export interface PreparedListing { + externalId: string; + identityKeys: 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" }; + + 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: companyKey(listing.companyLabel), + 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..7a73e2e2d --- /dev/null +++ b/packages/api/src/utils/job-board/locations.ts @@ -0,0 +1,205 @@ +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|\bU\.S\.(?=\s|$|[,)\]-])|\bUS\b|\bNYC\b|\bSF\b|\b(?:${STATE_NAMES})\b`, + "i", +); +// Case-sensitive: case-insensitive `IN`/`OR` would turn prose into U.S. evidence. +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|(? 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; +} + +/** Whether a location's text is explicitly outside the U.S. */ +export function isForeignLocation(text: string) { + return FOREIGN.test(text) || CANADIAN_PROVINCE.test(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)) { + const usEvidence = EXPLICIT_US.test(text) || US_STATE_CODE.test(text); + return usEvidence ? { ...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"). */ +export function splitLocationTexts(texts: string[]) { + return texts + .flatMap((text) => text.split(/\s*(?:;|\||\s\/\s|)\s*/i)) + .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..b41fb7c9b --- /dev/null +++ b/packages/api/src/utils/job-board/normalize.ts @@ -0,0 +1,135 @@ +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 fragment, no + * tracking params, no duplicate or trailing slashes, no trailing `/apply`. + * 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; + + url.hash = ""; + 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 || "/"; + + return url.toString(); +} + +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; +} + +/** 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[] = []; + + const ghJid = url.searchParams.get("gh_jid"); + if (ghJid) keys.push(`ats:greenhouse:${ghJid}`); + if (host.endsWith("greenhouse.io")) { + const jobId = parts[parts.indexOf("jobs") + 1]; + if (parts.includes("jobs") && 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 ( + host.includes("myworkdayjobs.com") || + host.includes("myworkdaysite.com") + ) { + const tenant = host.split(".")[0]; + const requisition = parts.at(-1)?.split("_").at(-1)?.toLowerCase(); + if (tenant && requisition) { + keys.push(`ats:workday:${tenant}:${requisition}`); + } + } + return [...new Set(keys)]; +} + +/** + * Every identity a listing can be matched by, strongest first. The first entry + * becomes a new job's `identityKey`; lookups try all of them. + */ +export function identityKeys(input: { + applyUrl: string; + provider: string; + boardKey: string; + externalId: string; +}): string[] { + const keys = atsKeys(new URL(input.applyUrl)); + // An aggregator URL wraps someone else's posting, so it identifies nothing. + if (!isAggregatorUrl(input.applyUrl)) keys.push(`url:${input.applyUrl}`); + keys.push(`source:${input.provider}:${input.boardKey}:${input.externalId}`); + 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; falls back to the raw label when it has no ASCII. */ +export function companyKey(label: string) { + const normalized = normalizeCompanyName(label) || label.trim().toLowerCase(); + return normalized.slice(0, 120); +} diff --git a/packages/consts/src/job-board.ts b/packages/consts/src/job-board.ts index 7b930a38b..10b9b8eb7 100644 --- a/packages/consts/src/job-board.ts +++ b/packages/consts/src/job-board.ts @@ -195,3 +195,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 8a1d0c971..e6681dee8 100644 --- a/packages/validators/src/job-board.ts +++ b/packages/validators/src/job-board.ts @@ -276,3 +276,55 @@ export type AlertPreferenceInput = z.infer< typeof alertPreferenceCreateInputSchema >; export type DigestOptInInput = z.infer; + +const nonBlankText = (max: number) => z.string().trim().min(1).max(max); + +/** + * 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(), + description: z.string().max(20_000).optional(), + compensation: z.string().trim().max(200).optional(), + locationTexts: z.array(z.string().trim().min(1).max(500)).max(100), + sourceUrl: z.url({ protocol: /^https?$/ }).max(4_096), + sourceData: z.record(z.string(), z.unknown()), + }) + .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; +export type CareerJobSourceSnapshot = z.infer< + typeof careerJobSourceSnapshotSchema +>; From cc92470d4303beb8e615e5e57983345a6679c0f0 Mon Sep 17 00:00:00 2001 From: Jesus Gonzalez Date: Thu, 19 Nov 2026 16:23:41 -0500 Subject: [PATCH 2/3] fixed job ingestion issues from review Co-Authored-By: Claude Opus 5.5 --- .forge/features/career-job-ingestion/srd.md | 37 ++++-- .../features/career-job-ingestion/status.md | 7 +- .../career-job-ingestion/test-cases.md | 24 ++-- .../integration/job-board-ingest.test.ts | 120 ++++++++++++++---- .../tests/job-board/ingestion-rules.test.ts | 55 +++++++- packages/api/src/utils/job-board/ingest.ts | 36 ++++-- packages/api/src/utils/job-board/listing.ts | 8 +- packages/api/src/utils/job-board/locations.ts | 30 +++-- packages/api/src/utils/job-board/normalize.ts | 45 +++++-- packages/validators/src/job-board.ts | 6 +- 10 files changed, 293 insertions(+), 75 deletions(-) diff --git a/.forge/features/career-job-ingestion/srd.md b/.forge/features/career-job-ingestion/srd.md index c6b733463..66ab747b9 100644 --- a/.forge/features/career-job-ingestion/srd.md +++ b/.forge/features/career-job-ingestion/srd.md @@ -29,9 +29,11 @@ for cron. Nothing in Blade imports it. `careerJobSourceSnapshotSchema` validator checks. 2. Cron reads channel IDs from the #648 config keys and calls `ingestJobSnapshot(snapshot, destinations)`. -3. Ingestion rejects the snapshot if `complete` is false. Otherwise it finds or +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 goes through a pure prepare step: clean the apply URL, decide the +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: @@ -41,14 +43,17 @@ for cron. Nothing in Blade imports it. - 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), `lastSuccessAt`, and - `lastAttemptAt`. +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:`; + - `url:`, only when the URL identifies one posting (a digit + in its last path segment or in a query value). A shared careers landing page + or an aggregator URL is never an identity. A Workday key needs a + `_` suffix; - `source:::`. - 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. @@ -58,6 +63,10 @@ for cron. Nothing in Blade imports it. - 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: a job stores only one identity key, taken from its first listing. + If an aggregator listing (source key only) creates the job and an employer + board later lists the same posting, they don't match, and the job is posted + twice. Fixing that needs a per-job key table (a schema change); not in #649. ### Field rules @@ -72,7 +81,10 @@ for cron. Nothing in Blade imports it. normalized alias, following `mergedIntoCompanyId`. Ingestion never inserts a `Company`. - A job that reappears gets `active = true` and `inactiveAt = null`. Its delivery - state stays as it was, so it isn't posted again. + state stays as it was, so it isn't posted again. A snapshot fetched before the + job (or observation) closed is stale and doesn't reopen it. +- A listing rejected this run counts as unseen, so a full inventory closes its + job. ### Delivery state on insert @@ -86,7 +98,12 @@ for cron. Nothing in Blade imports it. - `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. +- `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. - No locations, or unparsed text, keeps the job with an `unknown` location. ## tRPC/API behavior @@ -101,8 +118,10 @@ No procedures. `ingestJobSnapshot` returns: 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 an optional -`track`. +`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 diff --git a/.forge/features/career-job-ingestion/status.md b/.forge/features/career-job-ingestion/status.md index cacaad939..bfd1ec8ce 100644 --- a/.forge/features/career-job-ingestion/status.md +++ b/.forge/features/career-job-ingestion/status.md @@ -1,6 +1,6 @@ # Career job ingestion Status -Current phase: Implemented, awaiting human review (not committed) +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. @@ -11,10 +11,13 @@ Current phase: Implemented, awaiting human review (not committed) - 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 unless employer evidence says otherwise. A changed track never causes a repost. +- 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-19: A listing rejected this run counts as unseen, so a full inventory closes its job. +- 2026-11-19: Known limit: one identity key per job. An aggregator-first job and a later employer listing of the same posting aren't matched. A per-job key table would fix it (schema change, out of #649). ## Open questions diff --git a/.forge/features/career-job-ingestion/test-cases.md b/.forge/features/career-job-ingestion/test-cases.md index d04c05fe4..78aa036ee 100644 --- a/.forge/features/career-job-ingestion/test-cases.md +++ b/.forge/features/career-job-ingestion/test-cases.md @@ -26,24 +26,32 @@ The rules and ingest flow in `@forge/api` `utils/job-board`. | 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 and the Greenhouse board | Ingest both | One Job with two observations | -| TC-010 | Same snapshot ingested twice | Ingest | Second run: 0 created, job fields unchanged, `lastSeenAt` advances | +| 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 closed, job inactive | +| 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 job reappears | Ingest | Active again, delivery state unchanged | +| TC-016 | Inactive `pending` job reappears | Ingest | Active again, observation open, still `pending` | | 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` | ## Negative / regression cases -| ID | Setup | Expected | -| ---------- | ------------------------------------------- | ------------------------- | -| TC-NEG-001 | `complete: false` | Rejected before any write | -| TC-NEG-002 | Two concurrent ingests of one identity | Exactly one Job row | -| TC-NEG-003 | Invalid listing (non-http URL, blank title) | Fails validation | +| 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 diff --git a/packages/api/src/tests/integration/job-board-ingest.test.ts b/packages/api/src/tests/integration/job-board-ingest.test.ts index 5a3abb789..d8acf8a3e 100644 --- a/packages/api/src/tests/integration/job-board-ingest.test.ts +++ b/packages/api/src/tests/integration/job-board-ingest.test.ts @@ -10,12 +10,13 @@ import { 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 { eq, sql } from "@forge/db"; +import { sql } from "@forge/db"; import { canRunDatabaseTests, provisionDisposableDatabase, @@ -61,6 +62,7 @@ const greenhouse = { provider: "greenhouse", boardKey: "acme", 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; @@ -73,19 +75,23 @@ describe.skipIf(!canRunDatabaseTests())("job board ingestion", () => { 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" }); 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} CASCADE`, + sql`TRUNCATE ${schema.JobLocation}, ${schema.JobObservation}, ${schema.Job}, ${schema.JobSource}, ${Company} CASCADE`, ); }); @@ -183,22 +189,67 @@ describe.skipIf(!canRunDatabaseTests())("job board ingestion", () => { }); it("TC-014/TC-016 closes jobs missing from a full inventory and reopens them silently", async () => { - const board = (listings: CareerJobListing[]) => - snapshot(listings, { source: greenhouse, inventory: "full" }); - await run(board([listing()])); + const destinations = { internship: INTERN_CHANNEL }; + await run(board([])); + await run(board([listing()]), destinations); + expect((await jobs())[0]).toMatchObject({ deliveryState: "pending" }); const closed = await run(board([])); expect(closed.deactivated).toBe(1); - expect((await jobs())[0]).toMatchObject({ active: false }); + 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()]), { internship: INTERN_CHANNEL }); + await run(board([listing()]), destinations); expect((await jobs())[0]).toMatchObject({ active: true, inactiveAt: null, - deliveryState: "suppressed", + deliveryState: "pending", + }); + 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("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([])); @@ -252,7 +303,6 @@ describe.skipIf(!canRunDatabaseTests())("job board ingestion", () => { }); it("TC-019 links an approved Guild company by alias without creating one", async () => { - const { Company } = await import("@forge/db/schemas/knight-hacks"); const [company] = await client .insert(Company) .values({ @@ -266,18 +316,37 @@ describe.skipIf(!canRunDatabaseTests())("job board ingestion", () => { await run(snapshot([listing()])); expect((await jobs())[0]?.companyId).toBe(company?.id); expect(await client.select().from(Company)).toHaveLength(1); - await client.delete(Company).where(eq(Company.id, company?.id ?? "")); }); - it("counts rejected listings by reason", async () => { + 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 }); - expect(await jobs()).toHaveLength(0); + 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 () => { @@ -287,17 +356,22 @@ describe.skipIf(!canRunDatabaseTests())("job board ingestion", () => { expect(await client.select().from(schema.JobSource)).toHaveLength(0); }); - it("TC-NEG-002 creates one job when two sources ingest the same identity at once", async () => { - await Promise.all([ - run(snapshot([listing()])), - run( - snapshot([listing({ externalId: "gh" })], { - source: greenhouse, - inventory: "full", - }), + 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 client.select().from(schema.JobObservation)).toHaveLength(2); + 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 index fcc08dafc..ee7507b0b 100644 --- a/packages/api/src/tests/job-board/ingestion-rules.test.ts +++ b/packages/api/src/tests/job-board/ingestion-rules.test.ts @@ -1,7 +1,10 @@ import { describe, expect, it } from "vitest"; import type { CareerJobListing } from "@forge/validators"; -import { careerJobSourceSnapshotSchema } from "@forge/validators"; +import { + careerJobSourceSnapshotSchema, + companyKeySchema, +} from "@forge/validators"; import { findUsCity } from "../../utils/career/us-cities"; import { @@ -9,9 +12,13 @@ import { classifyTrack, } from "../../utils/job-board/classify"; import { prepareListing } from "../../utils/job-board/listing"; -import { parseLocation } from "../../utils/job-board/locations"; +import { + isForeignLocation, + parseLocation, +} from "../../utils/job-board/locations"; import { cleanApplyUrl, + companyKey, identityHash, identityKeys, preferredApplyUrl, @@ -65,6 +72,20 @@ describe("job identity", () => { ]); }); + it("never uses a shared careers landing page as an identity", () => { + for (const landing of [ + "https://acme.com/careers", + "https://acme.wd1.myworkdayjobs.com/en-US/Careers", + ]) { + expect(keysFor(landing)).toEqual([ + "source:github:simplify/internships:row-1", + ]); + } + expect(keysFor("https://acme.com/careers?jobId=42")[0]).toBe( + "url:https://acme.com/careers?jobId=42", + ); + }); + it("TC-002 strips tracking params, fragments, and a trailing /apply", () => { expect( cleanApplyUrl( @@ -82,6 +103,12 @@ describe("job identity", () => { 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", @@ -151,6 +178,9 @@ describe("locations", () => { 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", @@ -182,6 +212,21 @@ describe("locations", () => { kind: "city", }); }); + + it("keeps U.S. places that look foreign", () => { + for (const text of [ + "ON-SITE - Austin, TX", + "Austin, TX (ON SITE)", + "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", () => { @@ -194,6 +239,12 @@ describe("prepared listing", () => { }); }); + 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([]); diff --git a/packages/api/src/utils/job-board/ingest.ts b/packages/api/src/utils/job-board/ingest.ts index 20d94ab0a..69fa333fb 100644 --- a/packages/api/src/utils/job-board/ingest.ts +++ b/packages/api/src/utils/job-board/ingest.ts @@ -1,3 +1,5 @@ +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"; @@ -10,14 +12,14 @@ import { } from "@forge/db/schemas/job-board"; import { Company } from "@forge/db/schemas/knight-hacks"; import { + careerJobListingSchema, careerJobSourceSnapshotSchema, - normalizeCompanyName, } from "@forge/validators"; import type { TransactionDb } from "../db"; import type { ListingRejection, PreparedListing } from "./listing"; import { prepareListing } from "./listing"; -import { identityHash, preferredApplyUrl } from "./normalize"; +import { companyKey, identityHash, preferredApplyUrl } from "./normalize"; /** Discord channel per track, read by cron from the Career config keys (#648). */ export type JobDestinations = Partial< @@ -35,6 +37,12 @@ export interface JobIngestResult { 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 {} @@ -76,12 +84,14 @@ async function loadCompanyIds() { const ids = new Map(); for (const company of companies) { for (const alias of company.aliases) { - ids.set(normalizeCompanyName(alias), company.id); + 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) { - ids.set(company.normalizedDisplayName, company.id); + const key = companyKey(company.normalizedDisplayName); + if (key) ids.set(key, company.id); } return ids; } @@ -157,7 +167,7 @@ async function ingestListing( discordChannelId: channel, } : {}; - const identityKey = listing.identityKeys[0] ?? listing.externalId; + const identityKey = listing.identityKeys[0]; const [inserted] = await tx .insert(Job) .values({ @@ -188,6 +198,8 @@ async function ingestListing( created = Boolean(inserted); } else { // Track and first-seen never change; a reactivated job is not reposted. + // A snapshot fetched before the job closed is stale and must not reopen it. + const reopen = job.inactiveAt === null || job.inactiveAt < seenAt; await tx .update(Job) .set({ @@ -200,8 +212,7 @@ async function ingestListing( postedAt: listing.postedAt ?? job.postedAt, companyId: job.companyId ?? companyId, lastSeenAt: sql`greatest(${Job.lastSeenAt}, ${seenAt})`, - active: true, - inactiveAt: null, + ...(reopen && { active: true, inactiveAt: null }), }) .where(eq(Job.id, job.id)); } @@ -225,7 +236,8 @@ async function ingestListing( sourceData: listing.sourceData, postedAt: listing.postedAt, lastSeenAt: sql`greatest(${JobObservation.lastSeenAt}, ${seenAt})`, - inactiveAt: null, + // 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`, }, }); @@ -302,7 +314,7 @@ export async function ingestJobSnapshot( input: CareerJobSourceSnapshot, destinations: JobDestinations, ): Promise { - const snapshot = careerJobSourceSnapshotSchema.parse(input); + const snapshot = snapshotEnvelopeSchema.parse(input); if (!snapshot.complete) { throw new Error( `Job source ${snapshot.source.provider}:${snapshot.source.boardKey} sent an incomplete snapshot.`, @@ -332,7 +344,11 @@ export async function ingestJobSnapshot( }; for (const raw of snapshot.listings) { - const prepared = prepareListing(raw, source); + 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; diff --git a/packages/api/src/utils/job-board/listing.ts b/packages/api/src/utils/job-board/listing.ts index b95e9eb90..ac5ed9ad7 100644 --- a/packages/api/src/utils/job-board/listing.ts +++ b/packages/api/src/utils/job-board/listing.ts @@ -12,13 +12,14 @@ import { 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[]; + identityKeys: [string, ...string[]]; track: JOB_BOARD.JobTrack; category: JOB_BOARD.JobCategory; companyLabel: string; @@ -43,6 +44,9 @@ export function prepareListing( | { 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" }; @@ -68,7 +72,7 @@ export function prepareListing( track, category: classifyCategory(listing.title, description), companyLabel: listing.companyLabel, - companyKey: companyKey(listing.companyLabel), + companyKey: key, title: listing.title, applyUrl, description: description || null, diff --git a/packages/api/src/utils/job-board/locations.ts b/packages/api/src/utils/job-board/locations.ts index 7a73e2e2d..9bbc25a6a 100644 --- a/packages/api/src/utils/job-board/locations.ts +++ b/packages/api/src/utils/job-board/locations.ts @@ -67,10 +67,12 @@ const CITY_ALIASES: Record = { }; const EXPLICIT_US = new RegExp( - String.raw`\bUnited States\b|\bUSA\b|\bU\.S\.(?=\s|$|[,)\]-])|\bUS\b|\bNYC\b|\bSF\b|\b(?:${STATE_NAMES})\b`, + String.raw`\bUnited States\b|\bUSA\b|\bNYC\b|\bSF\b|\b(?:${STATE_NAMES})\b`, "i", ); -// Case-sensitive: case-insensitive `IN`/`OR` would turn prose into U.S. evidence. +// 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`, ); @@ -84,8 +86,8 @@ const FOREIGN = new RegExp( String.raw`South Africa|Argentina|Chile|Colombia|Peru)\b`, "i", ); -const CANADIAN_PROVINCE = - /(?:,\s*|\b)(?:AB|BC|MB|NB|NL|NS|NT|NU|ON|PE|QC|SK|YT)\b/; +// Only after a comma: a bare `ON` is usually "ON-SITE", not Ontario. +const CANADIAN_PROVINCE = /,\s*(?:AB|BC|MB|NB|NL|NS|NT|NU|ON|PE|QC|SK|YT)\b/; const COUNTRY_SUFFIX = /,?\s*\b(?:united states(?: of america)?|usa|us)\.?$/i; const COUNTRY_PREFIX = /^(?:united states|usa|us)\s*[,-]\s*/i; @@ -140,9 +142,22 @@ function parseCityState(text: string) { return null; } -/** Whether a location's text is explicitly outside the U.S. */ +function hasUsEvidence(text: string) { + return ( + EXPLICIT_US.test(text) || + US_ABBREVIATION.test(text) || + US_STATE_CODE.test(text) + ); +} + +/** + * 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); + return ( + (FOREIGN.test(text) || CANADIAN_PROVINCE.test(text)) && !hasUsEvidence(text) + ); } /** @@ -159,8 +174,7 @@ export function parseLocation(sourceText: string): ParsedLocation { }; if (/\bremote\b/i.test(text)) { - const usEvidence = EXPLICIT_US.test(text) || US_STATE_CODE.test(text); - return usEvidence ? { ...unknown, kind: "remote_us" } : unknown; + return hasUsEvidence(text) ? { ...unknown, kind: "remote_us" } : unknown; } const stripped = text diff --git a/packages/api/src/utils/job-board/normalize.ts b/packages/api/src/utils/job-board/normalize.ts index b41fb7c9b..9a7a8542c 100644 --- a/packages/api/src/utils/job-board/normalize.ts +++ b/packages/api/src/utils/job-board/normalize.ts @@ -94,8 +94,11 @@ function atsKeys(url: URL): string[] { host.includes("myworkdayjobs.com") || host.includes("myworkdaysite.com") ) { + // Only a posting URL ends in `_<requisition>`; landing pages don't. const tenant = host.split(".")[0]; - const requisition = parts.at(-1)?.split("_").at(-1)?.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}`); } @@ -103,20 +106,40 @@ function atsKeys(url: URL): string[] { return [...new Set(keys)]; } +/** + * Whether a URL points at one posting rather than a careers landing page that + * many listings share. A posting URL carries an ID: a digit in its last path + * segment or in a query value. + */ +function identifiesPosting(url: URL) { + const last = url.pathname.split("/").filter(Boolean).at(-1) ?? ""; + return ( + /[0-9]/.test(last) || + [...url.searchParams.values()].some((value) => /[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. + * 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[] { - const keys = atsKeys(new URL(input.applyUrl)); - // An aggregator URL wraps someone else's posting, so it identifies nothing. - if (!isAggregatorUrl(input.applyUrl)) keys.push(`url:${input.applyUrl}`); - keys.push(`source:${input.provider}:${input.boardKey}:${input.externalId}`); +}): [string, ...string[]] { + const url = new URL(input.applyUrl); + const keys: [string, ...string[]] = [ + `source:${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; } @@ -128,8 +151,10 @@ export function identityHash(key: string) { return createHash("sha256").update(key, "utf8").digest("hex"); } -/** Grouping key for a company label; falls back to the raw label when it has no ASCII. */ +/** + * 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) { - const normalized = normalizeCompanyName(label) || label.trim().toLowerCase(); - return normalized.slice(0, 120); + return normalizeCompanyName(label).slice(0, 120).trim(); } diff --git a/packages/validators/src/job-board.ts b/packages/validators/src/job-board.ts index e6681dee8..6e27f42e3 100644 --- a/packages/validators/src/job-board.ts +++ b/packages/validators/src/job-board.ts @@ -292,7 +292,11 @@ export const careerJobListingSchema = z title: nonBlankText(500), applyUrl: z.url({ protocol: /^https?$/ }).max(4_096), postedAt: z.date().optional(), - description: z.string().max(20_000).optional(), + // Truncated, not rejected: long HTML job bodies are common on ATS boards. + description: z + .string() + .transform((value) => value.slice(0, 20_000)) + .optional(), compensation: z.string().trim().max(200).optional(), locationTexts: z.array(z.string().trim().min(1).max(500)).max(100), sourceUrl: z.url({ protocol: /^https?$/ }).max(4_096), From 0d7325e767813d9b949a56f4ebef368e46e0d43d Mon Sep 17 00:00:00 2001 From: Jesus Gonzalez <reychucho859@gmail.com> Date: Thu, 19 Nov 2026 16:29:56 -0500 Subject: [PATCH 3/3] updated job ingestion spec and srd after review Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .forge/features/career-job-ingestion/spec.md | 19 ++++++++++++++----- .forge/features/career-job-ingestion/srd.md | 13 ++++++++----- .../features/career-job-ingestion/status.md | 5 +++-- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/.forge/features/career-job-ingestion/spec.md b/.forge/features/career-job-ingestion/spec.md index eb69aef1f..dd7bb0ac8 100644 --- a/.forge/features/career-job-ingestion/spec.md +++ b/.forge/features/career-job-ingestion/spec.md @@ -1,6 +1,6 @@ # Career job ingestion -Status: Approved (2026-11-17) +Status: Approved (2026-11-17), amended 2026-11-19 after review (pending approval) ## User-facing purpose @@ -58,7 +58,8 @@ and apply link. Adds no UI of its own. ## Acceptance criteria -- The same opening from two sources appears as one job. +- 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. @@ -69,11 +70,19 @@ and apply link. Adds no UI of its own. - 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. - The employer's own apply link wins over an aggregator's. +- 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 -- Should upstream's "recent catch-up" of baseline jobs be ported? Currently skipped. +- 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 index 66ab747b9..7ef5f2403 100644 --- a/.forge/features/career-job-ingestion/srd.md +++ b/.forge/features/career-job-ingestion/srd.md @@ -63,10 +63,13 @@ for cron. Nothing in Blade imports it. - 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: a job stores only one identity key, taken from its first listing. - If an aggregator listing (source key only) creates the job and an employer - board later lists the same posting, they don't match, and the job is posted - twice. Fixing that needs a per-job key table (a schema change); not in #649. +- 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 @@ -151,4 +154,4 @@ None. ## Open questions -- Should upstream's recent catch-up of baseline jobs be ported? Currently skipped. +- 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 index bfd1ec8ce..ae9f5ab14 100644 --- a/.forge/features/career-job-ingestion/status.md +++ b/.forge/features/career-job-ingestion/status.md @@ -16,13 +16,14 @@ Current phase: Implemented; review fixes applied, awaiting human review (fixes n - 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-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: one identity key per job. An aggregator-first job and a later employer listing of the same posting aren't matched. A per-job key table would fix it (schema change, out of #649). +- 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`. -- Should upstream's "recent catch-up" posting of jobs from the first run be ported? Currently skipped. +- 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