diff --git a/internal/dict/location/eligibility.go b/internal/dict/location/eligibility.go index 4bd946eccd..4d6a2e48ce 100644 --- a/internal/dict/location/eligibility.go +++ b/internal/dict/location/eligibility.go @@ -147,7 +147,7 @@ var sponsorshipTail = regexp.MustCompile( // whole words (or, for "n't"/"non-", as a suffix/prefix of one) against the sentence the // phrase sits in, not the phrase itself ("does not require US citizenship"). var negationWords = map[string]bool{ - "not": true, "no": true, "cannot": true, "never": true, + "not": true, "no": true, "cannot": true, "never": true, "unable": true, "without": true, "except": true, "unless": true, "excluding": true, } @@ -222,7 +222,7 @@ func negatedSentence(sentence string) bool { sentence = sponsorshipTail.ReplaceAllString(sentence, " ") for _, word := range strings.Fields(sentence) { word = strings.Trim(word, ".,;:!?()\"'") - if negationWords[word] || strings.HasSuffix(word, "n't") || strings.HasPrefix(word, "non-") { + if negationWords[word] || strings.HasSuffix(word, "n't") || strings.HasSuffix(word, "n’t") || strings.HasPrefix(word, "non-") { return true } } diff --git a/internal/dict/location/region_scope.go b/internal/dict/location/region_scope.go index 082e853d32..db2d245ff1 100644 --- a/internal/dict/location/region_scope.go +++ b/internal/dict/location/region_scope.go @@ -49,6 +49,15 @@ const clauseWindow = 200 // tokens the dictionaries resolve contribute, so "nearby time zones" is skipped. A phrase in a // sentence that denies it ("not restricted to the US") is not a match. func RegionScopeFromDescription(desc string) (countries, regions []string) { + countries, regions = regionScopeFromProse(desc) + if len(countries)+len(regions) > 0 || !strings.Contains(desc, " - ") { + return countries, regions + } + countries, regions, _ = remoteScopeFromLabels(descriptionScopeText(desc)) + return countries, regions +} + +func regionScopeFromProse(desc string) (countries, regions []string) { lower := strings.ToLower(htmltext.ToTextFull(joinWrappedRegionLists(desc))) lower = strings.NewReplacer("u.s.a.", "usa", "u.s.", "us", "u.k.", "uk").Replace(lower) // Keep phrase priority, but let an unresolved clause yield to a later anchor. diff --git a/internal/dict/location/remote_scope.go b/internal/dict/location/remote_scope.go new file mode 100644 index 0000000000..3849ac1ebc --- /dev/null +++ b/internal/dict/location/remote_scope.go @@ -0,0 +1,256 @@ +package location + +import ( + "html" + "regexp" + "slices" + "strings" + + "golang.org/x/text/language" + "golang.org/x/text/language/display" + + "github.com/strelov1/freehire/internal/platform/stringset" +) + +var ( + scopeBlockTag = regexp.MustCompile(`(?i)?(?:p|div|li|br|h[1-6])\b[^>]*>`) + scopeSpace = regexp.MustCompile(`[\t\r \x{00a0}]+`) + placeListJoin = strings.NewReplacer(" and ", ",", " or ", ",") +) + +func descriptionScopeText(desc string) string { + desc = scopeBlockTag.ReplaceAllString(desc, "\n") + return scopeSpace.ReplaceAllString(strings.ToLower(html.UnescapeString(stripTags(desc))), " ") +} + +func remoteScopeFromLabels(text string) (countries, regions, statedRegions []string) { + for line := range strings.SplitSeq(text, "\n") { + if !strings.Contains(line, " - remote") { + continue + } + c, r, stated := remoteScopeLabel(line) + countries = append(countries, c...) + regions = append(regions, r...) + statedRegions = append(statedRegions, stated...) + } + slices.Sort(countries) + slices.Sort(regions) + slices.Sort(statedRegions) + return slices.Compact(countries), slices.Compact(regions), slices.Compact(statedRegions) +} + +// remoteScopeLabel reads a complete location label, including lists such as +// "United States - Remote, EMEA - Remote". Treat the entire line as a label +// only when every entry is a known country or region followed by the remote marker. +func remoteScopeLabel(line string) (countries, regions, statedRegions []string) { + fields, _, _ := strings.Cut(line, " please note that ") + label, value, hasLabel := strings.Cut(fields, ":") + if hasLabel { + switch strings.Trim(label, " *") { + case "headquarters": + // Some boards put remote locations under this heading. Require + // a list of explicitly remote entries before using it as scope. + if !strings.Contains(value, ",") { + return nil, nil, nil + } + case "location", "locations": + default: + return nil, nil, nil + } + fields = strings.TrimLeft(value, " *") + } + countrySet := map[string]struct{}{} + regionSet := map[string]struct{}{} + statedSet := map[string]struct{}{} + for _, field := range strings.Split(fields, ",") { + place, ok := strings.CutSuffix(strings.TrimSpace(field), " - remote") + if !ok { + return nil, nil, nil + } + rs := normalizeRegion(place) + if len(rs) == 0 || slices.Contains(rs, globalRegion) { + return nil, nil, nil + } + if c := NormalizeCountry(place); c != "" { + countrySet[c] = struct{}{} + } + if nameToRegion[place] != "" || len(regionAliases[place]) > 0 { + for _, r := range rs { + statedSet[r] = struct{}{} + } + } + for _, r := range rs { + regionSet[r] = struct{}{} + } + } + return stringset.Sorted(countrySet), stringset.Sorted(regionSet), stringset.Sorted(statedSet) +} + +var countryExclusion = regexp.MustCompile( + `\b(?:(?:unable to|cannot|can['’]t|(?:do|does|will) not|not able to) (?:accept|consider) (?:applications from )?|not open to |excluding )` + + `(?:candidates|applicants) (?:based|located|residing) in\b|` + + `\b(?:remote (?:worldwide|globally)|hiring worldwide) *,? (?:except in|excluding)\b`) + +// ExcludedCountriesFromDescription reads explicit refusals tied to where +// applicants live, including exceptions to a worldwide scope. Country lists +// must resolve in full so a city followed by its country is never an exclusion +// of the whole country. +func ExcludedCountriesFromDescription(desc string) []string { + lower := strings.ToLower(desc) + applicantDenial := containsAny(lower, []string{"candidates", "applicants"}) && + containsAny(lower, []string{"unable", "not", "cannot", "can't", "can’t", "excluding"}) + worldwideException := containsAny(lower, []string{"worldwide", "globally"}) && + containsAny(lower, []string{"except", "excluding"}) + if !applicantDenial && !worldwideException { + return nil + } + return excludedCountries(descriptionScopeText(lower)) +} + +func excludedCountries(text string) []string { + var countries []string + for _, match := range countryExclusion.FindAllStringIndex(text, -1) { + start, end := match[0], match[1] + prefix := sentenceAround(text[:start], start, start) + prefix = prefix[strings.LastIndexByte(prefix, ';')+1:] + if negatedSentence(prefix) { + continue + } + var list []string + valid := true + clause, _, _ := strings.Cut(clauseAfterPhrase(text, end), ";") + clause = strings.TrimSuffix(strings.TrimSpace(clause), " for this role") + for tok := range strings.SplitSeq(placeListJoin.Replace(clause), ",") { + tok = strings.TrimPrefix(strings.TrimSpace(tok), "the ") + if tok == "" { + continue + } + if c := namedCountry(tok); c != "" { + list = append(list, c) + } else { + valid = false + break + } + } + if valid { + countries = append(countries, list...) + } + } + slices.Sort(countries) + return slices.Compact(countries) +} + +// The location dictionary includes cities and subdivisions as aliases for +// their countries. A country exclusion needs the country itself. +func namedCountry(name string) string { + c := NormalizeCountry(name) + if c == "" { + return "" + } + region, err := language.ParseRegion(strings.ToUpper(c)) + if err == nil && strings.EqualFold(name, display.English.Regions().Name(region)) { + return c + } + switch name { + case "us", "usa", "uk": + return c + } + return "" +} + +var worldwideArrangement = regexp.MustCompile( + `\b(?:(?:this|the) (?:role|position|job) is (?:fully |100% )?remote (?:and open )?(?:worldwide|globally|from anywhere in the world)` + + `|this is a (?:fully |100% )?remote (?:role|position|job) open (?:worldwide|to (?:candidates|applicants) anywhere in the world)` + + `|we (?:accommodate|offer|support) (?:fully |100% )?remote work *,? with (?:teammates|employees|colleagues) living (?:around the globe|around the world|worldwide))\b`) + +var worldwideConflict = regexp.MustCompile( + `\b(?:(?:must|(?:is|are) required to) (?:live|reside|be|be located|be based) in|open to [^.!?\n]{1,55} (?:applicants|candidates) only|` + + `(?:remote|hiring) only (?:in|within|from)|remote (?:in|within|from) [^.!?\n]{1,65} only|` + + `(?:on[- ]?site|in[- ]office) (?:only|required|role|position)|fully (?:on[- ]?site|in[- ]office)|` + + `must (?:be|work) (?:on[- ]?site|from (?:our|the) office)|work from (?:our|the) office|` + + `days (?:per week |a week )?(?:in (?:(?:our|the) )?office|on[- ]?site)|hybrid (?:role|position|schedule|arrangement)|` + + `except (?:in|for)|excluding)\b`) + +// WorldwideRemoteFromDescription reports a worldwide work arrangement stated +// in the body. A distributed team or a temporary work-from-anywhere perk +// alone doesn't assert the scope of the role. +func WorldwideRemoteFromDescription(desc string) bool { + lower := strings.ToLower(desc) + if !containsAny(lower, []string{"worldwide", "globally", "the globe", "the world"}) || !strings.Contains(lower, "remote") { + return false + } + text := descriptionScopeText(desc) + for _, match := range worldwideArrangement.FindAllStringIndex(text, -1) { + if negatedSentence(sentenceAround(text, match[0], match[1])) || + travelPerkQualified(text, match[0], match[1]) { + continue + } + c, r := RegionScopeFromDescription(desc) + return len(c)+len(r) == 0 && !worldwideConflict.MatchString(text) && + len(excludedCountries(text)) == 0 && !RemoteContradicted(desc) && !hasEligibilityRestriction(text) + } + return false +} + +func hasEligibilityRestriction(text string) bool { + return slices.ContainsFunc(eligibilityRules, func(rule eligibilityRule) bool { return ruleAsserted(text, rule) }) +} + +// IsRemoteOfficeList reports whether the location line lists only a standalone +// remote marker and recognizable city names. A country, region, or qualified +// remote marker can express hiring scope and must retain precedence. +func IsRemoteOfficeList(line string, cities []string) bool { + if len(cities) < 2 { + return false + } + remote := false + for _, field := range strings.Split(separatorReplacer.Replace(strings.ToLower(line)), ",") { + field = strings.TrimSpace(field) + if field == "remote" { + remote = true + continue + } + if !slices.Contains(cities, cityDict[field].Name) || namedCountry(field) != "" { + return false + } + } + return remote +} + +// WithoutExcludedGeography removes excluded countries and the regions supported +// only by those countries. A macro-region named separately in the location +// line or in a description's remote location labels remains a valid scope. +func WithoutExcludedGeography(countries, regions, excluded []string, line, description string) ([]string, []string) { + if len(excluded) == 0 { + return countries, regions + } + var removedRegions []string + kept := slices.DeleteFunc(slices.Clone(countries), func(c string) bool { + if !slices.Contains(excluded, c) { + return false + } + removedRegions = append(removedRegions, countryToRegion[c]) + return true + }) + var statedRegions []string + if len(removedRegions) > 0 && strings.Contains(description, " - ") { + _, _, statedRegions = remoteScopeFromLabels(descriptionScopeText(description)) + } + regions = slices.DeleteFunc(slices.Clone(regions), func(r string) bool { + if r == globalRegion { + return true + } + if !slices.Contains(removedRegions, r) || slices.Contains(statedRegions, r) || + slices.ContainsFunc(kept, func(c string) bool { return countryToRegion[c] == r }) { + return false + } + for tok := range strings.SplitSeq(separatorReplacer.Replace(strings.ToLower(line)), ",") { + tok = strings.TrimSpace(tok) + if nameToRegion[tok] == r || slices.Contains(regionAliases[tok], r) { + return false + } + } + return true + }) + return kept, regions +} diff --git a/internal/dict/location/remote_scope_places.go b/internal/dict/location/remote_scope_places.go new file mode 100644 index 0000000000..3b7627ce8c --- /dev/null +++ b/internal/dict/location/remote_scope_places.go @@ -0,0 +1,43 @@ +package location + +import ( + "slices" + "strings" +) + +// WithoutExcludedPlaces removes metros and cities whose country can be +// established as excluded. For a shared city name, the source's country +// context must resolve it before the exclusion can apply. +func WithoutExcludedPlaces(cities, metros, sourceCountries, excluded []string) ([]string, []string) { + if len(excluded) == 0 { + return cities, metros + } + cities = slices.DeleteFunc(slices.Clone(cities), func(city string) bool { + name, qualifier, _ := strings.Cut(strings.ToLower(city), ",") + qualifier = strings.TrimSpace(qualifier[strings.LastIndexByte(qualifier, ',')+1:]) + if country := namedCountry(qualifier); country != "" { + return slices.Contains(excluded, country) + } + name = strings.TrimSpace(name) + if entry, ok := cityDict[name]; ok && !entry.Contested { + return slices.Contains(excluded, entry.Country) + } + found := false + for _, country := range sourceCountries { + if !hasPlaceIn(name, country) { + continue + } + if !slices.Contains(excluded, country) { + return false + } + found = true + } + return found + }) + metros = slices.DeleteFunc(slices.Clone(metros), func(metro string) bool { + return slices.ContainsFunc(excluded, func(country string) bool { + return strings.HasSuffix(metro, " ("+strings.ToUpper(country)+")") + }) + }) + return cities, metros +} diff --git a/internal/dict/location/remote_scope_test.go b/internal/dict/location/remote_scope_test.go new file mode 100644 index 0000000000..447cd13008 --- /dev/null +++ b/internal/dict/location/remote_scope_test.go @@ -0,0 +1,131 @@ +package location + +import ( + "slices" + "testing" +) + +func TestWorldwideRemoteFromDescription(t *testing.T) { + const policy = "We accommodate 100% remote work, with teammates living around the globe." + tests := []struct { + name, description string + want bool + }{ + {"worldwide remote policy", "
" + policy + "
", true}, + {"role explicitly open worldwide", "This role is fully remote and open worldwide.", true}, + {"team description only", "We are a fully remote team with colleagues around the globe.", false}, + {"explicit residence requirement", policy + " Applicants are required to reside in Germany.", false}, + {"optional residence", policy + " Applicants are not required to reside in Germany.", true}, + {"country restriction", policy + " You must be based in Canada.", false}, + {"country exception", "This role is remote worldwide, except in Germany.", false}, + {"temporary worldwide perk", "This role is fully remote from anywhere in the world for up to four weeks per year.", false}, + {"work authorization", policy + " You must be authorized to work in the United States.", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := WorldwideRemoteFromDescription(tt.description); got != tt.want { + t.Errorf("WorldwideRemoteFromDescription() = %t, want %t", got, tt.want) + } + }) + } +} + +func TestExcludedCountriesFromDescription(t *testing.T) { + tests := []struct { + name, description string + want []string + }{ + {"applicant refusal", "We are unable to consider applications from candidates based in France, Italy, or Germany for this role.
", []string{"de", "fr", "it"}}, + {"worldwide exception", "This role is remote worldwide, except in Germany.", []string{"de"}}, + {"contracted wording", "We can’t consider candidates located in the UK.", []string{"gb"}}, + {"unrelated earlier denial", "We do not sponsor visas; we cannot accept applications from candidates based in Germany; see the location details.", []string{"de"}}, + {"negated refusal", "It is not true that we cannot accept applications from candidates based in Germany.", nil}, + {"city and country", "We cannot accept applicants based in Berlin, Germany.", nil}, + {"no residence requirement", "Applicants are not required to be based in France.", nil}, + {"ordinary hiring location", "We're hiring in France or Germany.", nil}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ExcludedCountriesFromDescription(tt.description); !slices.Equal(got, tt.want) { + t.Errorf("ExcludedCountriesFromDescription() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestRegionScopeFromDescription_RemoteLocationLabels(t *testing.T) { + for _, desc := range []string{ + "Headquarters: United States - Remote, EMEA - Remote
", + "Headquarters: United States - Remote, EMEA - Remote Please note that this role requires English.", + } { + countries, regions := RegionScopeFromDescription(desc) + if !slices.Equal(countries, []string{"us"}) || !slices.Equal(regions, []string{"africa", "eu", "mena", "north_america", "uk"}) { + t.Errorf("RegionScopeFromDescription(%q) = %v / %v, want US and EMEA", desc, countries, regions) + } + } + countries, regions := RegionScopeFromDescription("Location: United States - Remote
Location: Canada - Remote
") + if !slices.Equal(countries, []string{"ca", "us"}) || !slices.Equal(regions, []string{"north_america"}) { + t.Errorf("two location labels = %v / %v, want US and Canada", countries, regions) + } + if countries, regions := RegionScopeFromDescription("Headquarters: United States - Remote"); len(countries)+len(regions) != 0 { + t.Errorf("single headquarters = %v / %v, want no role scope", countries, regions) + } +} + +func TestIsRemoteOfficeList(t *testing.T) { + for _, tt := range []struct { + line string + want bool + }{ + {"Remote / Boston / New York", true}, + {"Remote / Canada / Boston / New York", false}, + {"Remote / Boston", false}, + {"Berlin / Munich", false}, + } { + t.Run(tt.line, func(t *testing.T) { + if got := IsRemoteOfficeList(tt.line, Parse(tt.line).Cities); got != tt.want { + t.Errorf("IsRemoteOfficeList() = %t, want %t", got, tt.want) + } + }) + } +} + +func TestWithoutExcludedGeography(t *testing.T) { + countries := []string{"ca", "de"} + regions := []string{"eu", "global", "north_america"} + wantCountries := []string{"ca"} + for _, tt := range []struct { + line string + want []string + }{ + {"Remote / Canada / Germany", []string{"north_america"}}, + {"Remote / Europe / Canada / Germany", []string{"eu", "north_america"}}, + } { + t.Run(tt.line, func(t *testing.T) { + gotCountries, gotRegions := WithoutExcludedGeography(countries, regions, []string{"de"}, tt.line, "") + if !slices.Equal(gotCountries, wantCountries) || !slices.Equal(gotRegions, tt.want) { + t.Errorf("WithoutExcludedGeography() = %v / %v, want %v / %v", gotCountries, gotRegions, wantCountries, tt.want) + } + }) + } +} + +func TestWithoutExcludedPlaces(t *testing.T) { + cities := []string{"Berlin", "Toronto", "Uncatalogued Place"} + metros := []string{"Berlin (DE)", "Toronto (CA)"} + gotCities, gotMetros := WithoutExcludedPlaces(cities, metros, []string{"de", "ca"}, []string{"de"}) + if !slices.Equal(gotCities, []string{"Toronto", "Uncatalogued Place"}) || + !slices.Equal(gotMetros, []string{"Toronto (CA)"}) { + t.Errorf("places = %v / %v, want Toronto and the unresolved city", gotCities, gotMetros) + } + qualifiedCities := []string{"Berlin, Germany", "Paris, Île-de-France, France", "Berlin, United States"} + gotCities, _ = WithoutExcludedPlaces(qualifiedCities, nil, nil, []string{"de", "fr"}) + if !slices.Equal(gotCities, []string{"Berlin, United States"}) { + t.Errorf("qualified cities = %v, want [Berlin, United States]", gotCities) + } + gotCities, gotMetros = WithoutExcludedPlaces(cities, metros, nil, nil) + if !slices.Equal(gotCities, []string{"Berlin", "Toronto", "Uncatalogued Place"}) || + !slices.Equal(gotMetros, []string{"Berlin (DE)", "Toronto (CA)"}) { + t.Errorf("without exclusions, places changed to %v / %v", gotCities, gotMetros) + } +} diff --git a/internal/job/jobderive/jobderive.go b/internal/job/jobderive/jobderive.go index 096079a7fe..f70ceb9c42 100644 --- a/internal/job/jobderive/jobderive.go +++ b/internal/job/jobderive/jobderive.go @@ -38,6 +38,96 @@ func Derive(in Input) Derived { // structured country is final (it replaces the countries below); a fallback one is // read only once it is what the posting ends up placed in, below. geo := location.ParseIn(in.Location, in.Countries) + workMode := resolveWorkMode(in, geo.WorkMode) + countries, regions, cities, metros := deriveGeography(in, title, geo, workMode) + class := classify.Parse(title) + // Seniority precedence: structured source signal → title dictionary → description + // phrase. Each lower source only fills a grade the higher ones left empty. + seniority := in.Seniority + if seniority == "" { + seniority = class.Seniority + } + if seniority == "" { + seniority = classify.SeniorityFromDescription(in.Description) + } + // Category precedence: structured source signal → title dictionary → a + // non-tech match in the description (NonTechFromDescription resolves only + // non-technical categories, feeding the enrichment cost gate; a title-silent + // tech job stays empty). Each lower source only fills what the higher left empty. + category := in.Category + if category == "" { + category = class.Category + } + if category == "" { + category = classify.NonTechFromDescription(in.Description) + } + isTech := deriveIsTech(category, title, in.IsTechHint) + clearanceLevels := location.ClearanceLevelsFromDescription(in.Description) + // Employment-type precedence: structured source signal (an ATS timeType / + // typeOfEmployment enum) → free-text description parse. The source's own value wins. + employmentType := in.EmploymentType + if employmentType == "" { + employmentType = jobfacts.EmploymentType(title, in.Description) + } + // Experience precedence: structured source signal → description text parse. + // + // The ceiling is applied AFTER the choice, to whichever source won, because both + // can overshoot: the text parse cannot tell a candidate's years from an employer's ("over + // 40 years of … experience, chipmakers rely on KLA"), and a structured field can carry an + // undeclared unit. One bound after the merge catches both. See vocab.MaxExperienceYears. + experience := in.ExperienceYearsMin + if experience == nil { + experience = jobfacts.ExperienceYearsMin(in.Description) + } + experience = believableExperience(experience) + // Education and English precedence: structured source signal → description text + // parse. Both matchers read English prose only, so on a posting written in another + // language they are the weaker source by a wide margin, not merely the later one. + educationLevel := in.EducationLevel + if educationLevel == "" { + educationLevel = jobfacts.EducationLevel(in.Description) + } + englishLevel := in.EnglishLevel + if englishLevel == "" { + englishLevel = jobfacts.EnglishLevel(in.Description) + } + return Derived{ + CompanySlug: normalize.CompanySlug(in.Company), + PublicSlug: normalize.JobSlug(in.Title, in.Company, in.Source, in.ExternalID), + Countries: countries, + Regions: regions, + Cities: cities, + Metros: metros, + WorkMode: workMode, + // Skills is a set: the structured source skills are unioned with the + // dictionary skills, neither replacing the other. The category-scoped + // acronym tier (e.g. RAG on an ai_engineering/ml_ai job) takes the + // resolved local `category` — NOT in.Category — so it also fires when the + // title dictionary supplied the category, the common case since most + // sources carry no structured category signal. + Skills: unionSkills(in.Skills, skilltag.Parse(in.Description, skilltag.WithAcronymCategory(category))), + Seniority: seniority, + Category: category, + IsTech: isTech, + RequiresClearance: trueOrNil(len(clearanceLevels) > 0), + ViaRecruiter: trueOrNil(jobfacts.ViaRecruiter(in.Description)), + Equity: jobfacts.Equity(in.Title, in.Description), + ClearanceLevels: clearanceLevels, + Perks: perks.FromDescription(in.Description), + Engagement: deriveEngagement(in.Engagement, title, in.Description), + PostingLanguage: lang.Detect(in.Description), + EmploymentType: employmentType, + EducationLevel: educationLevel, + EnglishLevel: englishLevel, + ExperienceYearsMin: experience, + SalaryMin: in.SalaryMin, + SalaryMax: in.SalaryMax, + SalaryCurrency: in.SalaryCurrency, + SalaryPeriod: in.SalaryPeriod, + } +} + +func deriveGeography(in Input, title string, geo location.Geo, workMode string) ([]string, []string, []string, []string) { // Geography precedence: the location dictionary → a title-embedded restriction // marker → an eligibility signal in the description → an explicit region-scoping // statement in the description → the caller's FallbackCountries. When the location left the geography unpinned (no @@ -46,7 +136,9 @@ func Derive(in Input) Derived { // source left blank — a resolved place, from the location or from a higher // source in this chain, is never overridden. This is the same shape the // work-mode fallback below uses. - countries, regions := geo.Countries, geo.Regions + structuredRegions := location.NormalizeRegions(in.Regions) + excluded := location.ExcludedCountriesFromDescription(in.Description) + countries, regions := location.WithoutExcludedGeography(geo.Countries, geo.Regions, excluded, in.Location, "") if geoUnpinned(countries, regions) { // A title-embedded restriction marker ("[Remote-US]", "(Location - Australia // or New Zealand)") is a more literal, ATS-authored signal than prose, so it @@ -68,10 +160,18 @@ func Derive(in Input) Derived { countries, regions = c, r } } + // A clearly stated worldwide arrangement can outweigh a list of offices. + if workMode == "remote" && len(in.Countries) == 0 && len(structuredRegions) == 0 && + (geoUnpinned(countries, regions) || location.IsRemoteOfficeList(in.Location, geo.Cities)) && + location.WorldwideRemoteFromDescription(in.Description) { + if c, r := location.RestrictionFromTitle(title); geoUnpinned(c, r) { + return nil, []string{"global"}, in.Cities, nil + } + } // The fallback country fills only a posting that stated NO geography — not even an // explicit open-anywhere marker, which geoUnpinned counts as unpinned but which a // headquarters office must not narrow to one country. - if len(countries) == 0 && len(regions) == 0 && len(in.FallbackCountries) > 0 { + if len(countries) == 0 && len(regions) == 0 && len(excluded) == 0 && len(in.FallbackCountries) > 0 { countries = in.FallbackCountries regions = regionsForCountries(in.FallbackCountries) if len(in.Countries) == 0 { @@ -87,7 +187,7 @@ func Derive(in Input) Derived { // adapter's country is an office address (Ashby's postalAddress US beside "Remote | // North America or Europe"), and replacing the line with it narrowed a Europe-open // role to one country. - worldwide := worldwideLine(geo, in.Location) + worldwide := len(excluded) == 0 && worldwideLine(geo, in.Location) lineWins := len(in.Countries) > 0 && (worldwide || lineOutranksCountries(geo, in.Countries)) if len(in.Countries) > 0 && !lineWins { countries = in.Countries @@ -99,15 +199,17 @@ func Derive(in Input) Derived { // row fed back by backfill-derive) stating a country, a subdivision or a free // phrase as a "region" must not reach the facet, and one that folds to nothing // is no signal at all. - if r := location.NormalizeRegions(in.Regions); len(r) > 0 && !worldwide { + if len(structuredRegions) > 0 && !worldwide { if lineWins { // rederive feeds a stored row's regions back beside its country; a line that // outranks the country must not be narrowed back by them. - regions = unionSorted(regions, r) + regions = unionSorted(regions, structuredRegions) } else { - regions = r + regions = structuredRegions } } + // An explicit exclusion also applies to source-provided geography. + countries, regions = location.WithoutExcludedGeography(countries, regions, excluded, in.Location, in.Description) // Parse already drops a global the location line contradicts; this applies the same // rule to the final answer, whose countries and regions may come from a structured // signal instead — an adapter's own country beside an "Anywhere" line, or a stored @@ -119,11 +221,20 @@ func Derive(in Input) Derived { cities = in.Cities } metros := metrosForOverride(geo.Metros, in.Cities, in.Countries, countries) + cityCountries := geo.Countries + if len(in.Cities) > 0 && len(in.Countries) > 0 { + cityCountries = in.Countries + } + cities, metros = location.WithoutExcludedPlaces(cities, metros, cityCountries, excluded) + return countries, regions, cities, metros +} + +func resolveWorkMode(in Input, hint string) string { // Work-mode precedence: structured (ATS) → location marker → description phrase. // Each lower source only fills a value the higher ones left empty. workMode := in.WorkMode if workMode == "" { - workMode = geo.WorkMode + workMode = hint } if workMode == "" { workMode = location.WorkModeFromDescription(in.Description) @@ -139,91 +250,7 @@ func Derive(in Input) Derived { workMode = "onsite" } } - class := classify.Parse(title) - // Seniority precedence: structured source signal → title dictionary → description - // phrase. Each lower source only fills a grade the higher ones left empty. - seniority := in.Seniority - if seniority == "" { - seniority = class.Seniority - } - if seniority == "" { - seniority = classify.SeniorityFromDescription(in.Description) - } - // Category precedence: structured source signal → title dictionary → a - // non-tech match in the description (NonTechFromDescription resolves only - // non-technical categories, feeding the enrichment cost gate; a title-silent - // tech job stays empty). Each lower source only fills what the higher left empty. - category := in.Category - if category == "" { - category = class.Category - } - if category == "" { - category = classify.NonTechFromDescription(in.Description) - } - isTech := deriveIsTech(category, title, in.IsTechHint) - clearanceLevels := location.ClearanceLevelsFromDescription(in.Description) - // Employment-type precedence: structured source signal (an ATS timeType / - // typeOfEmployment enum) → free-text description parse. The source's own value wins. - employmentType := in.EmploymentType - if employmentType == "" { - employmentType = jobfacts.EmploymentType(title, in.Description) - } - // Experience precedence: structured source signal → description text parse. - // - // The ceiling is applied AFTER the choice, to whichever source won, because both - // can overshoot: the text parse cannot tell a candidate's years from an employer's ("over - // 40 years of … experience, chipmakers rely on KLA"), and a structured field can carry an - // undeclared unit. One bound after the merge catches both. See vocab.MaxExperienceYears. - experience := in.ExperienceYearsMin - if experience == nil { - experience = jobfacts.ExperienceYearsMin(in.Description) - } - experience = believableExperience(experience) - // Education and English precedence: structured source signal → description text - // parse. Both matchers read English prose only, so on a posting written in another - // language they are the weaker source by a wide margin, not merely the later one. - educationLevel := in.EducationLevel - if educationLevel == "" { - educationLevel = jobfacts.EducationLevel(in.Description) - } - englishLevel := in.EnglishLevel - if englishLevel == "" { - englishLevel = jobfacts.EnglishLevel(in.Description) - } - return Derived{ - CompanySlug: normalize.CompanySlug(in.Company), - PublicSlug: normalize.JobSlug(in.Title, in.Company, in.Source, in.ExternalID), - Countries: countries, - Regions: regions, - Cities: cities, - Metros: metros, - WorkMode: workMode, - // Skills is a set: the structured source skills are unioned with the - // dictionary skills, neither replacing the other. The category-scoped - // acronym tier (e.g. RAG on an ai_engineering/ml_ai job) takes the - // resolved local `category` — NOT in.Category — so it also fires when the - // title dictionary supplied the category, the common case since most - // sources carry no structured category signal. - Skills: unionSkills(in.Skills, skilltag.Parse(in.Description, skilltag.WithAcronymCategory(category))), - Seniority: seniority, - Category: category, - IsTech: isTech, - RequiresClearance: trueOrNil(len(clearanceLevels) > 0), - ViaRecruiter: trueOrNil(jobfacts.ViaRecruiter(in.Description)), - Equity: jobfacts.Equity(in.Title, in.Description), - ClearanceLevels: clearanceLevels, - Perks: perks.FromDescription(in.Description), - Engagement: deriveEngagement(in.Engagement, title, in.Description), - PostingLanguage: lang.Detect(in.Description), - EmploymentType: employmentType, - EducationLevel: educationLevel, - EnglishLevel: englishLevel, - ExperienceYearsMin: experience, - SalaryMin: in.SalaryMin, - SalaryMax: in.SalaryMax, - SalaryCurrency: in.SalaryCurrency, - SalaryPeriod: in.SalaryPeriod, - } + return workMode } func RetainEmploymentType(stored, title, description string) string { diff --git a/internal/job/jobderive/remote_scope_test.go b/internal/job/jobderive/remote_scope_test.go new file mode 100644 index 0000000000..6aaafdcc34 --- /dev/null +++ b/internal/job/jobderive/remote_scope_test.go @@ -0,0 +1,178 @@ +package jobderive + +import ( + "slices" + "testing" +) + +func TestDerive_WorldwideRemoteWithOfficeLocations(t *testing.T) { + const offices = "Remote / Boston / Salt Lake City / San Francisco / New York" + const worldwide = "We accommodate 100% remote work, with teammates living around the globe and paid in their local currency." + tests := []struct { + name, title, location, description, workMode string + structuredCountries, countries, regions []string + }{ + {name: "worldwide arrangement overrides office list", location: offices, + description: "We accommodate 100% remote work, with teammates living around the globe and paid in their local currency.
", + regions: []string{"global"}}, + {name: "role explicitly open worldwide", location: offices, + description: "This role is fully remote and open worldwide.", regions: []string{"global"}}, + {name: "worldwide application scope", location: offices, + description: "This is a fully remote position open to candidates anywhere in the world.", regions: []string{"global"}}, + {name: "restricted despite generic remote policy", location: offices, + description: worldwide + " Applicants must be in Europe.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "distributed team boilerplate", location: offices, + description: "We are a fully remote team with colleagues around the globe.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "temporary work from anywhere perk", location: offices, + description: "You can work from anywhere in the world for up to four weeks per year.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "explicit home location restriction", location: offices, + description: worldwide + " You must be based in the United States.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "explicit residence requirement", location: "Remote / Berlin / Munich", + description: worldwide + " Applicants are required to reside in Germany.", + countries: []string{"de"}, regions: []string{"eu"}}, + {name: "optional residence does not restrict", location: "Remote / Berlin / Munich", + description: worldwide + " Applicants are not required to reside in Germany.", + regions: []string{"global"}}, + {name: "country only restriction", location: offices, + description: worldwide + " This position is open to US applicants only.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "country in location field", location: "Remote / United States", description: worldwide, + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "title restriction", title: "Engineer [Remote-US]", location: offices, description: worldwide, + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "onsite required", location: offices, + description: worldwide + " For this role, you must work from our office in Boston.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "remote explicitly denied for the role", location: offices, + description: worldwide + " This position is 100% on-site.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "fully onsite requirement in body", location: offices, + description: worldwide + " This role is fully on-site.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "required days in office", location: offices, + description: worldwide + " This position requires 3 days in office.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "remote only in a named country", location: offices, + description: worldwide + " Remote in the United States only.", + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "hybrid required", location: offices, workMode: "hybrid", description: worldwide, + countries: []string{"us"}, regions: []string{"north_america"}}, + {name: "structured country", location: offices, description: worldwide, + structuredCountries: []string{"ca"}, countries: []string{"ca"}, regions: []string{"north_america"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := Derive(Input{Title: tt.title, Location: tt.location, Description: tt.description, + WorkMode: tt.workMode, Countries: tt.structuredCountries}) + if !slices.Equal(got.Countries, tt.countries) || !slices.Equal(got.Regions, tt.regions) { + t.Fatalf("geography = %v / %v, want %v / %v", got.Countries, got.Regions, tt.countries, tt.regions) + } + if slices.Contains(tt.regions, "global") && (len(got.Cities) != 0 || len(got.Metros) != 0) { + t.Errorf("worldwide role still has office facets: %v / %v", got.Cities, got.Metros) + } + }) + } +} + +func TestDerive_ExcludedCountriesAreNotPositiveGeography(t *testing.T) { + const exclusion = "We are unable to consider applications from candidates based in France, Italy, or Germany" + cases := []struct { + location, description string + }{ + {"Anywhere in the World", "Headquarters: United States - Remote, EMEA - Remote
" + + "Please note that " + exclusion + " for this role.
"}, + {"Remote / Worldwide", "Headquarters: United States - Remote, EMEA - Remote Please note that " + + exclusion + " for this role. Join a remote-first, global team."}, + } + for _, tc := range cases { + t.Run(tc.location, func(t *testing.T) { + got := Derive(Input{Location: tc.location, Description: tc.description}) + wantRegions := []string{"africa", "eu", "mena", "north_america", "uk"} + if !slices.Equal(got.Countries, []string{"us"}) || !slices.Equal(got.Regions, wantRegions) { + t.Errorf("geography = %v / %v, want [us] / %v", got.Countries, got.Regions, wantRegions) + } + }) + } + t.Run("an exclusion alone cannot become a positive facet", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Worldwide", Description: exclusion + ".", FallbackCountries: []string{"us"}}) + if len(got.Countries) != 0 || len(got.Regions) != 0 { + t.Errorf("geography = %v / %v, want no positive geography", got.Countries, got.Regions) + } + }) + t.Run("a worldwide exception leaves the positive scope unspecified", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Worldwide", Description: "This role is remote worldwide, except in Germany."}) + if len(got.Countries) != 0 || len(got.Regions) != 0 { + t.Errorf("geography = %v / %v, want no positive geography", got.Countries, got.Regions) + } + }) + t.Run("explicit restriction takes precedence over remote headquarters", func(t *testing.T) { + got := Derive(Input{Location: "Remote", + Description: "Headquarters: United States - Remote, EMEA - Remote
Candidates must meet the requirements. You must be based in Canada.
"}) + if !slices.Equal(got.Countries, []string{"ca"}) || !slices.Equal(got.Regions, []string{"north_america"}) { + t.Errorf("geography = %v / %v, want [ca] / [north_america]", got.Countries, got.Regions) + } + }) + t.Run("structured scope cannot restore an explicitly excluded country", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Worldwide", Countries: []string{"de"}, Regions: []string{"eu", "global"}, + Description: "This role is remote worldwide, except in Germany."}) + if len(got.Countries) != 0 || len(got.Regions) != 0 { + t.Errorf("geography = %v / %v, want no positive geography", got.Countries, got.Regions) + } + }) + t.Run("search continues after rejected clause", func(t *testing.T) { + got := Derive(Input{Location: "Remote", Description: exclusion + ". We are hiring in Canada and the UK."}) + if !slices.Equal(got.Countries, []string{"ca", "gb"}) || !slices.Equal(got.Regions, []string{"north_america", "uk"}) { + t.Errorf("geography = %v / %v, want [ca gb] / [north_america uk]", got.Countries, got.Regions) + } + }) + t.Run("inferred location list contains both allowed and excluded countries", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Canada / France", Description: exclusion + "."}) + if !slices.Equal(got.Countries, []string{"ca"}) || !slices.Equal(got.Regions, []string{"north_america"}) { + t.Errorf("geography = %v / %v, want [ca] / [north_america]", got.Countries, got.Regions) + } + }) + t.Run("city exclusion does not exclude its country", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Germany", + Description: "We cannot accept applications from candidates based in Berlin, Germany."}) + if !slices.Equal(got.Countries, []string{"de"}) || !slices.Equal(got.Regions, []string{"eu"}) { + t.Errorf("geography = %v / %v, want [de] / [eu]", got.Countries, got.Regions) + } + }) + t.Run("a separately named region survives a country exclusion", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Europe / France", Description: exclusion + "."}) + if len(got.Countries) != 0 || !slices.Equal(got.Regions, []string{"eu"}) { + t.Errorf("geography = %v / %v, want [] / [eu]", got.Countries, got.Regions) + } + }) + t.Run("a macro-region from a description label survives a country exclusion", func(t *testing.T) { + got := Derive(Input{Location: "Remote", Description: "Locations: France - Remote, EMEA - Remote\n" + + "We cannot accept applications from candidates based in France."}) + if len(got.Countries) != 0 || !slices.Equal(got.Regions, []string{"africa", "eu", "mena", "uk"}) { + t.Errorf("geography = %v / %v, want [] / [africa eu mena uk]", got.Countries, got.Regions) + } + }) + t.Run("structured city in the excluded country is removed", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Worldwide", Countries: []string{"de"}, Cities: []string{"Berlin"}, + Description: "This role is remote worldwide, except in Germany."}) + if len(got.Cities)+len(got.Metros) != 0 { + t.Errorf("places = %v / %v, want none", got.Cities, got.Metros) + } + }) + t.Run("parsed city in the excluded country is removed", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Berlin, Germany / Toronto, Canada", Description: exclusion + "."}) + if !slices.Equal(got.Cities, []string{"Toronto"}) { + t.Errorf("cities = %v, want [Toronto]", got.Cities) + } + }) + t.Run("optional restriction is still a denial", func(t *testing.T) { + got := Derive(Input{Location: "Remote / Worldwide", + Description: "Applications are open worldwide. Candidates are not required to be based in France."}) + if len(got.Countries) != 0 || !slices.Equal(got.Regions, []string{"global"}) { + t.Errorf("geography = %v / %v, want [] / [global]", got.Countries, got.Regions) + } + }) +} diff --git a/internal/job/jobview/jobview.go b/internal/job/jobview/jobview.go index 7a076525ec..6a58a96158 100644 --- a/internal/job/jobview/jobview.go +++ b/internal/job/jobview/jobview.go @@ -191,6 +191,24 @@ func FromDomain(j job.Job, x job.Extras) (Job, error) { // below (dict wins). e := f.Enrichment + // Search indexing uses this same projection. Do not let stale model + // geography replace an explicit worldwide arrangement or revive exclusions. + if len(e.Countries)+len(e.Regions)+len(e.Cities) > 0 { + pinned := geoPinned(f.Countries, f.Regions) + if !pinned && slices.Contains(f.Regions, "global") && f.WorkMode == "remote" && + location.WorldwideRemoteFromDescription(f.Description) { + e.Countries, e.Regions, e.Cities = nil, nil, nil + } else if !pinned || (len(f.Cities) == 0 && len(e.Cities) > 0) { + if excluded := location.ExcludedCountriesFromDescription(f.Description); len(excluded) > 0 { + enrichmentCountries := normalizeSet(e.Countries) + if !pinned { + e.Countries, e.Regions = location.WithoutExcludedGeography( + enrichmentCountries, location.NormalizeRegions(e.Regions), excluded, f.Location, f.Description) + } + e.Cities, _ = location.WithoutExcludedPlaces(e.Cities, nil, enrichmentCountries, excluded) + } + } + } countries, regions := geoFacet(f.Countries, f.Regions, e.Countries, e.Regions) workMode := f.WorkMode // Seniority and the synthetic facets are always the dictionary column value, kept nested diff --git a/internal/job/jobview/jobview_test.go b/internal/job/jobview/jobview_test.go index a46633d4c9..627e90fcfa 100644 --- a/internal/job/jobview/jobview_test.go +++ b/internal/job/jobview/jobview_test.go @@ -521,3 +521,56 @@ func TestFromRow_CarriesClosedAt(t *testing.T) { t.Fatalf("open job ClosedAt = %v, want nil", *open.ClosedAt) } } + +func TestFromRow_DescriptionGeographySurvivesEnrichment(t *testing.T) { + t.Run("worldwide arrangement survives stale office enrichment", func(t *testing.T) { + view, err := FromRow(db.Job{ID: 1, PublicSlug: "x-1", WorkMode: "remote", + Regions: []string{"global"}, Location: "Remote / Boston / San Francisco", + Description: "We accommodate 100% remote work, with teammates living around the globe and paid in their local currency.", + Enrichment: []byte(`{"countries":["us"],"regions":["north_america"],"cities":["Boston"]}`), + }) + if err != nil { + t.Fatal(err) + } + if len(view.Countries) != 0 || !slices.Equal(view.Regions, []string{"global"}) || len(view.Cities) != 0 { + t.Errorf("geography = %v / %v / %v, want [] / [global] / []", view.Countries, view.Regions, view.Cities) + } + }) + t.Run("region-only fallback cannot restore global after an exclusion", func(t *testing.T) { + view, err := FromRow(db.Job{ID: 1, PublicSlug: "x-1", WorkMode: "remote", + Description: "This role is remote worldwide, except in Germany.", + Enrichment: []byte(`{"regions":["global"]}`), + }) + if err != nil { + t.Fatal(err) + } + if len(view.Regions) != 0 { + t.Errorf("regions = %v, want none", view.Regions) + } + }) + t.Run("city fallback cannot restore an excluded place on pinned geography", func(t *testing.T) { + view, err := FromRow(db.Job{ID: 1, PublicSlug: "x-1", WorkMode: "remote", + Countries: []string{"ca"}, Regions: []string{"north_america"}, + Description: "This role is remote worldwide, except in Germany.", + Enrichment: []byte(`{"cities":["Berlin, Germany","Toronto, Canada"]}`), + }) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(view.Cities, []string{"Toronto"}) { + t.Errorf("cities = %v, want [Toronto]", view.Cities) + } + }) + t.Run("fallback cannot reintroduce excluded countries", func(t *testing.T) { + view, err := FromRow(db.Job{ID: 1, PublicSlug: "x-1", WorkMode: "remote", + Description: "We cannot accept applications from candidates based in France or Germany for this role.", + Enrichment: []byte(`{"countries":["fr","de","ca"],"regions":["eu","north_america"]}`), + }) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(view.Countries, []string{"ca"}) { + t.Errorf("countries = %v, want [ca]", view.Countries) + } + }) +}