job-apply-cli 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. job_apply_agent/__init__.py +3 -0
  2. job_apply_agent/api.py +340 -0
  3. job_apply_agent/ats/__init__.py +12 -0
  4. job_apply_agent/ats/answer_binding.py +308 -0
  5. job_apply_agent/ats/base.py +64 -0
  6. job_apply_agent/ats/captcha.py +76 -0
  7. job_apply_agent/ats/codex_planner.py +174 -0
  8. job_apply_agent/ats/cua_harness.py +846 -0
  9. job_apply_agent/ats/dom_browser.py +275 -0
  10. job_apply_agent/ats/form_preparation.py +452 -0
  11. job_apply_agent/ats/hybrid_harness.py +379 -0
  12. job_apply_agent/ats/lcu_bridge.mjs +94 -0
  13. job_apply_agent/ats/lcu_harness.py +226 -0
  14. job_apply_agent/ats/lcu_worker.sh +12 -0
  15. job_apply_agent/ats/page_readiness.py +119 -0
  16. job_apply_agent/ats/playwright_adapter.py +561 -0
  17. job_apply_agent/cli.py +108 -0
  18. job_apply_agent/collectors/__init__.py +7 -0
  19. job_apply_agent/collectors/ashby.py +64 -0
  20. job_apply_agent/collectors/base.py +75 -0
  21. job_apply_agent/collectors/greenhouse.py +50 -0
  22. job_apply_agent/collectors/job_link.py +471 -0
  23. job_apply_agent/collectors/lever.py +42 -0
  24. job_apply_agent/collectors/normalizer.py +156 -0
  25. job_apply_agent/config.py +190 -0
  26. job_apply_agent/db.py +40 -0
  27. job_apply_agent/domain/__init__.py +11 -0
  28. job_apply_agent/domain/enums.py +50 -0
  29. job_apply_agent/domain/schemas.py +173 -0
  30. job_apply_agent/examples/__init__.py +1 -0
  31. job_apply_agent/examples/answer-bank.json +7 -0
  32. job_apply_agent/examples/experiences.json +8 -0
  33. job_apply_agent/examples/profile.json +24 -0
  34. job_apply_agent/examples/search-policy.json +15 -0
  35. job_apply_agent/examples/source-boards.json +10 -0
  36. job_apply_agent/experience/__init__.py +1 -0
  37. job_apply_agent/experience/benchmark.py +199 -0
  38. job_apply_agent/experience/library.py +140 -0
  39. job_apply_agent/experience/reasoning.py +240 -0
  40. job_apply_agent/experience/retrieval.py +221 -0
  41. job_apply_agent/managed_apply.py +104 -0
  42. job_apply_agent/managed_backlog.py +410 -0
  43. job_apply_agent/models.py +133 -0
  44. job_apply_agent/onboarding.py +152 -0
  45. job_apply_agent/repository.py +54 -0
  46. job_apply_agent/resume/__init__.py +3 -0
  47. job_apply_agent/resume/composer.py +121 -0
  48. job_apply_agent/scheduler.py +115 -0
  49. job_apply_agent/services/__init__.py +18 -0
  50. job_apply_agent/services/answer_derivation.py +59 -0
  51. job_apply_agent/services/answers.py +71 -0
  52. job_apply_agent/services/application_report.py +144 -0
  53. job_apply_agent/services/artifacts.py +38 -0
  54. job_apply_agent/services/codex_narratives.py +64 -0
  55. job_apply_agent/services/facts.py +57 -0
  56. job_apply_agent/services/model_errors.py +93 -0
  57. job_apply_agent/services/narratives.py +278 -0
  58. job_apply_agent/services/orchestrator.py +149 -0
  59. job_apply_agent/services/policy.py +173 -0
  60. job_apply_agent/services/quota.py +88 -0
  61. job_apply_agent/services/resumes.py +86 -0
  62. job_apply_agent/services/review_actions.py +120 -0
  63. job_apply_agent/tasks.py +775 -0
  64. job_apply_agent/telegram/__init__.py +1 -0
  65. job_apply_agent/telegram/experiences.py +105 -0
  66. job_apply_agent/telegram/review.py +494 -0
  67. job_apply_cli-0.2.0.dist-info/METADATA +330 -0
  68. job_apply_cli-0.2.0.dist-info/RECORD +71 -0
  69. job_apply_cli-0.2.0.dist-info/WHEEL +4 -0
  70. job_apply_cli-0.2.0.dist-info/entry_points.txt +3 -0
  71. job_apply_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,3 @@
1
+ """Job Apply Agent package."""
2
+
3
+ __version__ = "0.2.0" # x-release-please-version
job_apply_agent/api.py ADDED
@@ -0,0 +1,340 @@
1
+ from __future__ import annotations
2
+
3
+ import secrets
4
+ from collections.abc import Callable
5
+ from datetime import date, datetime, time, timezone
6
+ from typing import Annotated, Any
7
+
8
+ from fastapi import Depends, FastAPI, HTTPException, Query, Request
9
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
10
+ from pydantic import BaseModel
11
+ from sqlalchemy import func, select
12
+ from sqlalchemy.orm import Session
13
+
14
+ from .collectors.normalizer import JobNormalizer
15
+ from .config import get_settings
16
+ from .db import get_session
17
+ from .domain.enums import ApplicationState, RunStatus
18
+ from .domain.schemas import CandidateProfile, RawJob, SearchPolicy
19
+ from .models import JobPostingRecord
20
+ from .services.orchestrator import ApplicationOrchestrator
21
+ from .services.policy import PriorityPolicy
22
+ from .services.quota import DailyQuotaService
23
+
24
+ SessionDep = Annotated[Session, Depends(get_session)]
25
+ SettingsDep = Annotated[Any, Depends(get_settings)]
26
+ bearer = HTTPBearer(auto_error=False)
27
+
28
+
29
+ def require_api_token(
30
+ request: Request,
31
+ settings: SettingsDep,
32
+ credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)],
33
+ ) -> None:
34
+ if request.url.path == "/health":
35
+ return
36
+ expected = settings.api_token
37
+ if not expected or len(expected) < 32:
38
+ raise HTTPException(status_code=503, detail="API authentication is not configured")
39
+ if credentials is None or not secrets.compare_digest(
40
+ credentials.credentials.encode(), expected.encode()
41
+ ):
42
+ raise HTTPException(
43
+ status_code=401,
44
+ detail="Invalid API credentials",
45
+ headers={"WWW-Authenticate": "Bearer"},
46
+ )
47
+
48
+
49
+ app = FastAPI(title="Job Apply Agent", version="0.2.0", dependencies=[Depends(require_api_token)])
50
+
51
+
52
+ class AssessRequest(BaseModel):
53
+ job: RawJob
54
+ profile: CandidateProfile
55
+ policy: SearchPolicy
56
+
57
+
58
+ class CollectionRequest(BaseModel):
59
+ boards: list[dict[str, Any]] | None = None
60
+ profile: dict[str, Any] | None = None
61
+ policy: dict[str, Any] | None = None
62
+
63
+
64
+ def get_dispatcher() -> Callable[[list[dict], dict, dict], Any]:
65
+ def dispatch(boards: list[dict], profile: dict, policy: dict) -> Any:
66
+ from .tasks import collect_configured_boards
67
+
68
+ return collect_configured_boards.send(
69
+ boards=boards, profile_payload=profile, policy_payload=policy
70
+ )
71
+
72
+ return dispatch
73
+
74
+
75
+ DispatcherDep = Annotated[Callable, Depends(get_dispatcher)]
76
+
77
+
78
+ @app.get("/health")
79
+ def health() -> dict[str, str]:
80
+ return {"status": "ok"}
81
+
82
+
83
+ def _state_counts(session: Session) -> dict[str, int]:
84
+ return dict(
85
+ session.execute(
86
+ select(JobPostingRecord.application_state, func.count())
87
+ .group_by(JobPostingRecord.application_state)
88
+ .order_by(JobPostingRecord.application_state)
89
+ ).all()
90
+ )
91
+
92
+
93
+ @app.get("/v1/ops/status")
94
+ def operations_status(session: SessionDep, settings: SettingsDep) -> dict:
95
+ now = datetime.now(timezone.utc)
96
+ today_start = datetime.combine(now.date(), time.min, tzinfo=timezone.utc)
97
+ useful = (
98
+ JobPostingRecord.eligible.is_(True),
99
+ JobPostingRecord.score >= settings.high_value_threshold,
100
+ )
101
+ jobs_total = session.scalar(select(func.count()).select_from(JobPostingRecord)) or 0
102
+ jobs_today = (
103
+ session.scalar(
104
+ select(func.count())
105
+ .select_from(JobPostingRecord)
106
+ .where(JobPostingRecord.first_seen_at >= today_start)
107
+ )
108
+ or 0
109
+ )
110
+ useful_total = (
111
+ session.scalar(select(func.count()).select_from(JobPostingRecord).where(*useful)) or 0
112
+ )
113
+ useful_today = (
114
+ session.scalar(
115
+ select(func.count())
116
+ .select_from(JobPostingRecord)
117
+ .where(*useful, JobPostingRecord.first_seen_at >= today_start)
118
+ )
119
+ or 0
120
+ )
121
+ states = _state_counts(session)
122
+ active_states = {ApplicationState.FILLING.value, ApplicationState.SUBMITTING.value}
123
+ active_applications = sum(states.get(state, 0) for state in active_states)
124
+ queued = sum(
125
+ states.get(state, 0)
126
+ for state in {
127
+ ApplicationState.AUTO_APPLY_QUEUED.value,
128
+ ApplicationState.MATERIALS_READY.value,
129
+ }
130
+ )
131
+ active_submissions = (
132
+ session.scalar(
133
+ select(func.count())
134
+ .select_from(JobPostingRecord)
135
+ .where(JobPostingRecord.submission_status == RunStatus.RUNNING.value)
136
+ )
137
+ or 0
138
+ )
139
+ quota = DailyQuotaService(
140
+ fetch_limit=settings.daily_fetch_limit,
141
+ apply_limit=settings.daily_auto_submit_limit,
142
+ ).snapshot(session)
143
+ top = list(
144
+ session.scalars(
145
+ select(JobPostingRecord)
146
+ .where(*useful)
147
+ .order_by(JobPostingRecord.score.desc(), JobPostingRecord.first_seen_at.desc())
148
+ .limit(5)
149
+ )
150
+ )
151
+ return {
152
+ "checked_at": now.isoformat(),
153
+ "service": {"status": "ok", "environment": settings.app_env},
154
+ "database": {"status": "ok", "jobs": jobs_total, "tables": 2},
155
+ "discovery": {
156
+ "jobs_today": jobs_today,
157
+ "useful_threshold": settings.high_value_threshold,
158
+ "useful_jobs_today": useful_today,
159
+ "useful_jobs_total": useful_total,
160
+ "quota": {"fetched": quota.fetched_count, "fetch_limit": quota.fetch_limit},
161
+ "top_useful_jobs": [
162
+ {
163
+ "company": job.company,
164
+ "title": job.title,
165
+ "location": job.location,
166
+ "source": job.source,
167
+ "score": job.score,
168
+ "url": job.url,
169
+ }
170
+ for job in top
171
+ ],
172
+ },
173
+ "applications": {
174
+ "active": active_applications > 0 or active_submissions > 0,
175
+ "active_applications": active_applications,
176
+ "active_submissions": active_submissions,
177
+ "queued": queued,
178
+ "states": states,
179
+ },
180
+ }
181
+
182
+
183
+ @app.get("/v1/quotas/{quota_date}")
184
+ def get_quota(quota_date: date, session: SessionDep, settings: SettingsDep) -> dict:
185
+ quota = DailyQuotaService(
186
+ fetch_limit=settings.daily_fetch_limit,
187
+ apply_limit=settings.daily_auto_submit_limit,
188
+ ).snapshot(session, quota_date)
189
+ return {
190
+ "date": quota.quota_date.isoformat(),
191
+ "fetched": quota.fetched_count,
192
+ "fetch_limit": quota.fetch_limit,
193
+ "remaining_fetches": max(0, quota.fetch_limit - quota.fetched_count),
194
+ "applied": quota.applied_count,
195
+ "apply_limit": quota.apply_limit,
196
+ "remaining_applications": max(0, quota.apply_limit - quota.applied_count),
197
+ }
198
+
199
+
200
+ @app.post("/v1/assessments/preview")
201
+ def preview_assessment(request: AssessRequest) -> dict:
202
+ normalized = JobNormalizer().normalize(request.job)
203
+ assessment = PriorityPolicy().score(normalized, request.profile, request.policy)
204
+ return {
205
+ "job": normalized.model_dump(mode="json"),
206
+ "assessment": assessment.model_dump(mode="json"),
207
+ }
208
+
209
+
210
+ @app.post("/v1/jobs", status_code=201)
211
+ def ingest_job(request: AssessRequest, session: SessionDep) -> dict:
212
+ result = ApplicationOrchestrator().ingest(session, request.job, request.profile, request.policy)
213
+ session.commit()
214
+ return result.__dict__
215
+
216
+
217
+ def _job_item(job: JobPostingRecord) -> dict:
218
+ return {
219
+ "job_id": job.id,
220
+ "source": job.source,
221
+ "company": job.company,
222
+ "title": job.title,
223
+ "url": job.url,
224
+ "location": job.location,
225
+ "score": job.score,
226
+ "eligible": job.eligible,
227
+ "state": job.application_state,
228
+ "channel": job.application_channel,
229
+ "created_at": job.created_at.isoformat(),
230
+ }
231
+
232
+
233
+ @app.get("/v1/jobs")
234
+ def list_jobs(
235
+ session: SessionDep,
236
+ limit: Annotated[int, Query(ge=1, le=200)] = 50,
237
+ offset: Annotated[int, Query(ge=0)] = 0,
238
+ source: str | None = None,
239
+ state: str | None = Query(None, max_length=64),
240
+ min_score: float | None = Query(None, ge=0, le=100),
241
+ ) -> dict:
242
+ filters = []
243
+ if source:
244
+ filters.append(JobPostingRecord.source == source)
245
+ if state:
246
+ filters.append(JobPostingRecord.application_state == state)
247
+ if min_score is not None:
248
+ filters.append(JobPostingRecord.score >= min_score)
249
+ total = session.scalar(select(func.count()).select_from(JobPostingRecord).where(*filters)) or 0
250
+ rows = list(
251
+ session.scalars(
252
+ select(JobPostingRecord)
253
+ .where(*filters)
254
+ .order_by(JobPostingRecord.first_seen_at.desc())
255
+ .limit(limit)
256
+ .offset(offset)
257
+ )
258
+ )
259
+ return {"total": total, "items": [_job_item(job) for job in rows]}
260
+
261
+
262
+ @app.get("/v1/applications")
263
+ def list_applications(
264
+ session: SessionDep,
265
+ limit: Annotated[int, Query(ge=1, le=200)] = 50,
266
+ offset: Annotated[int, Query(ge=0)] = 0,
267
+ state: str | None = Query(None, max_length=64),
268
+ channel: str | None = Query(None, max_length=64),
269
+ ) -> dict:
270
+ filters = []
271
+ if state:
272
+ filters.append(JobPostingRecord.application_state == state)
273
+ if channel:
274
+ filters.append(JobPostingRecord.application_channel == channel)
275
+ total = session.scalar(select(func.count()).select_from(JobPostingRecord).where(*filters)) or 0
276
+ rows = list(
277
+ session.scalars(
278
+ select(JobPostingRecord)
279
+ .where(*filters)
280
+ .order_by(JobPostingRecord.id)
281
+ .limit(limit)
282
+ .offset(offset)
283
+ )
284
+ )
285
+ return {
286
+ "total": total,
287
+ "items": [
288
+ {
289
+ "id": job.id,
290
+ "state": job.application_state,
291
+ "channel": job.application_channel,
292
+ "job": {"company": job.company, "title": job.title, "url": job.url},
293
+ "score": job.score,
294
+ }
295
+ for job in rows
296
+ ],
297
+ }
298
+
299
+
300
+ @app.post("/v1/collections/run")
301
+ def run_collections(
302
+ request: CollectionRequest, session: SessionDep, dispatcher: DispatcherDep
303
+ ) -> dict:
304
+ settings = get_settings()
305
+ boards = request.boards if request.boards is not None else settings.source_boards()
306
+ if not boards:
307
+ raise HTTPException(
308
+ status_code=400,
309
+ detail="no source boards configured; pass boards or set SOURCE_BOARDS_JSON",
310
+ )
311
+ profile = request.profile if request.profile is not None else settings.candidate_profile()
312
+ policy = request.policy if request.policy is not None else settings.search_policy()
313
+ try:
314
+ dispatcher(boards, profile, policy)
315
+ except ConnectionError as exc:
316
+ raise HTTPException(status_code=503, detail="queue broker unavailable") from exc
317
+ return {"dispatched": len(boards), "boards": [board.get("board_slug") for board in boards]}
318
+
319
+
320
+ @app.get("/v1/applications/{application_id}")
321
+ def get_application(application_id: str, session: SessionDep) -> dict:
322
+ job = session.get(JobPostingRecord, application_id)
323
+ if job is None:
324
+ raise HTTPException(status_code=404, detail="application not found")
325
+ return {
326
+ "id": job.id,
327
+ "state": job.application_state,
328
+ "channel": job.application_channel,
329
+ "job": {"company": job.company, "title": job.title, "url": job.url},
330
+ "assessment": {
331
+ "score": job.score,
332
+ "breakdown": job.score_breakdown,
333
+ "reasons": job.ranking_reasons,
334
+ },
335
+ "submission": {
336
+ "status": job.submission_status,
337
+ "last_error": job.last_error,
338
+ "receipt": job.receipt,
339
+ },
340
+ }
@@ -0,0 +1,12 @@
1
+ from .base import ApplicationResult, ATSAdapter, ATSBlocked, InspectionResult
2
+ from .playwright_adapter import AshbyAdapter, GreenhouseAdapter, LeverAdapter
3
+
4
+ __all__ = [
5
+ "ATSAdapter",
6
+ "ATSBlocked",
7
+ "ApplicationResult",
8
+ "AshbyAdapter",
9
+ "GreenhouseAdapter",
10
+ "InspectionResult",
11
+ "LeverAdapter",
12
+ ]
@@ -0,0 +1,308 @@
1
+ """Question-scoped approvals for the Codex path; values alone are not authority."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+
8
+ from job_apply_agent.domain.schemas import FormQuestion
9
+ from job_apply_agent.services.answer_derivation import derive_employment_answer
10
+ from job_apply_agent.services.answers import AnswerResolver
11
+ from job_apply_agent.services.narratives import is_narrative_question
12
+
13
+
14
+ def question_key(label: str, group: str = "", context: str = "") -> str:
15
+ text = " ".join((context + " | " + group + " | " + label).casefold().split()).strip(" |*")
16
+ return "question:" + hashlib.sha256(text.encode()).hexdigest()[:20]
17
+
18
+
19
+ def job_region(country: str | None, location: str) -> str | None:
20
+ """A narrow location vocabulary; unknown or multi-country locations stay unknown."""
21
+ names = {
22
+ "canada": "Canada",
23
+ "united states": "United States",
24
+ "usa": "United States",
25
+ "us": "United States",
26
+ "japan": "Japan",
27
+ "china": "China",
28
+ "cn": "China",
29
+ }
30
+ declared = (country or "").strip()
31
+ explicit = names.get(declared.casefold())
32
+ if declared and not explicit:
33
+ # A provider's single full country name is context, not a candidate fact.
34
+ # Avoid a growing list of per-country candidate approvals. Ambiguous
35
+ # regions/codes still need internal job-location resolution.
36
+ if (
37
+ len(declared) <= 2
38
+ or not re.fullmatch(r"[\wÀ-ÿ .'-]+", declared)
39
+ or re.search(r"\b(?:and|or)\b", declared, re.IGNORECASE)
40
+ or declared.casefold()
41
+ in {
42
+ "remote",
43
+ "unknown",
44
+ "global",
45
+ "worldwide",
46
+ "anywhere",
47
+ "emea",
48
+ "apac",
49
+ "europe",
50
+ "asia",
51
+ "africa",
52
+ "americas",
53
+ "north america",
54
+ "south america",
55
+ }
56
+ ):
57
+ return None
58
+ explicit = declared
59
+ regions = set()
60
+ unknown_location = False
61
+ for part in re.split(r"[·;|]", location.casefold()):
62
+ part = part.strip()
63
+ if re.fullmatch(r"(?:remote\s*\()?canada\)?|(?:toronto|vancouver|montreal), canada", part):
64
+ regions.add("Canada")
65
+ elif part in {"san francisco, ca", "new york, ny", "united states", "usa"}:
66
+ regions.add("United States")
67
+ elif part in {"tokyo, japan", "japan"}:
68
+ regions.add("Japan")
69
+ elif part in {"china", "beijing, china", "shanghai, china"}:
70
+ regions.add("China")
71
+ elif part:
72
+ unknown_location = True
73
+ if explicit:
74
+ return explicit if not regions or regions == {explicit} else None
75
+ return next(iter(regions)) if len(regions) == 1 and not unknown_location else None
76
+
77
+
78
+ def scope_question(
79
+ question: FormQuestion,
80
+ binding: dict,
81
+ entries: list,
82
+ context: str = "",
83
+ *,
84
+ region: str | None = None,
85
+ ) -> FormQuestion:
86
+ """Use a confirmed exact question, or a small unambiguous fact vocabulary."""
87
+ exact = question_key(question.label, binding.get("group_label", ""), context)
88
+ if any(e.semantic_key == exact for e in entries):
89
+ return question.model_copy(update={"semantic_key": exact})
90
+ label = " ".join((binding.get("group_label") or question.label).casefold().split())
91
+ label = label.strip(" *:")
92
+ question_label = " ".join(question.label.casefold().split()).strip(" *:?")
93
+ # A widget placeholder is not the question. Keep specific sublabels such as
94
+ # Phone / Country intact instead of blindly inheriting group authority.
95
+ if question_label in {"start typing...", "select...", "select", ""}:
96
+ question_label = label.strip(" *:?")
97
+ # Reuse approved specific facts; never route country-specific authorization
98
+ # through the historical generic work_authorization key.
99
+ known_questions = (
100
+ (
101
+ r"are you (?:legally eligible|legally authorized|authorised) to work in canada",
102
+ "work_authorization_canada",
103
+ ),
104
+ (
105
+ r"(?:what is the location where you permanently reside|country of residence)",
106
+ "country_of_residence",
107
+ ),
108
+ (r"are you open to relocation for this role", "relocation_willingness"),
109
+ (
110
+ r"are you open to working in-person in one of our offices 25% of the time",
111
+ "onsite_availability",
112
+ ),
113
+ (r"have you ever interviewed at anthropic before", "prior_anthropic_interviews"),
114
+ (r"ai policy for application", "ai_policy_acknowledgment"),
115
+ (
116
+ r"please read the arbitration agreement below|agreement to arbitrate",
117
+ "arbitration_agreement",
118
+ ),
119
+ (r"what are your salary expectations \(annually\)", "salary_expectations"),
120
+ (r"have you previously worked at stackadapt", "prior_employer_relationship"),
121
+ (
122
+ r"which statement best describes how you currently use ai tools in (?:your )?(?:work/life|work or life|work and life)",
123
+ "ai_tool_usage",
124
+ ),
125
+ )
126
+ for pattern, key in known_questions:
127
+ if re.fullmatch(pattern, question_label):
128
+ return question.model_copy(update={"semantic_key": key})
129
+ country_questions = (
130
+ (
131
+ r"are you legally authorized to work in the country the job you are applying for is primarily located",
132
+ "authorization",
133
+ ),
134
+ (r"do you require visa sponsorship", "sponsorship"),
135
+ (
136
+ r"will you now or will you in the future require employment visa sponsorship to work in the country in which the job you're applying for is located",
137
+ "sponsorship",
138
+ ),
139
+ (
140
+ r"do you now or will you in the future require stackadapt to sponsor you for authorization to work in the country the job you are applying for is primarily located",
141
+ "sponsorship",
142
+ ),
143
+ )
144
+ for pattern, kind in country_questions:
145
+ if re.fullmatch(pattern, question_label):
146
+ keys = {
147
+ ("Canada", "authorization"): "work_authorization_canada",
148
+ ("China", "authorization"): "work_authorization_china",
149
+ ("United States", "authorization"): "us_work_authorized",
150
+ ("Canada", "sponsorship"): "sponsorship_required_canada",
151
+ ("China", "sponsorship"): "sponsorship_required_china",
152
+ ("United States", "sponsorship"): "sponsorship_required_united_states",
153
+ }
154
+ fallback = (
155
+ "sponsorship_by_country"
156
+ if kind == "sponsorship"
157
+ else "work_authorization_by_country"
158
+ )
159
+ return question.model_copy(
160
+ update={"semantic_key": keys.get((region or "", kind), fallback)}
161
+ )
162
+ if question_label == (
163
+ "if hired by stackadapt, do you intend to hold any secondary employment, advisory position "
164
+ "(e.g. membership on a board of directors), or volunteer position that (1) is on behalf of a "
165
+ "business that would be competitive in nature to the business of stackadapt, (2) conflict "
166
+ "with your ability to perform your duties at stackadapt, or (3) conflict with your working "
167
+ "hours at stackadapt"
168
+ ):
169
+ return question.model_copy(update={"semantic_key": "secondary_positions"})
170
+ patterns = (
171
+ (r"(?:first|given) name", "first_name"),
172
+ (r"(?:last|family) name|surname", "last_name"),
173
+ (r"(?:full |your )?name", "full_name"),
174
+ (r"(?:your )?e-?mail(?: address)?", "email"),
175
+ (r"(?:your )?(?:phone|mobile)(?: number)?", "phone"),
176
+ (r"linkedin(?: (?:profile|url|profile url))?", "linkedin_url"),
177
+ (r"github(?: (?:profile|url|profile url))?", "github_url"),
178
+ (r"(?:personal )?(?:website|portfolio)(?: url)?", "website_url"),
179
+ (r"current (?:company|employer)", "current_employer"),
180
+ (r"(?:most recent|previous|last) (?:company|employer)", "most_recent_employer"),
181
+ )
182
+ # Choice labels do not inherit contact-field authority from their words/group.
183
+ simple = binding.get("input_type") not in {"checkbox", "radio", "button", "submit"}
184
+ simple &= binding.get("role") != "combobox" or binding.get("tag_name") == "select"
185
+ simple &= bool(binding.get("label") or binding.get("dom_id") or binding.get("dom_name"))
186
+ if simple:
187
+ for pattern, key in patterns:
188
+ if re.fullmatch(pattern, label):
189
+ return question.model_copy(update={"semantic_key": key})
190
+ if question.input_type == "file":
191
+ # Generic Attach buttons and anonymous resume-autofill inputs are not
192
+ # proof of a resume question. Prefer the document label, then native ID.
193
+ document = label
194
+ if not re.search(r"resume|curriculum vitae|\bcv\b|cover letter", document):
195
+ document = re.sub(
196
+ r"[_-]+", " ", binding.get("dom_id", "") + " " + binding.get("dom_name", "")
197
+ )
198
+ key = (
199
+ "cover_letter_upload"
200
+ if re.search(r"cover letter", document, re.IGNORECASE)
201
+ else (
202
+ "resume_upload"
203
+ if re.search(r"resume|curriculum vitae|\bcv\b", document, re.IGNORECASE)
204
+ else exact
205
+ )
206
+ )
207
+ return question.model_copy(update={"semantic_key": key})
208
+ # Preserve fact-grounded essay composition, but never turn a fact/choice or
209
+ # an employment/contact question into an essay to fill a missing fact.
210
+ fact_words = r"company|employer|sponsor|visa|authori[sz]|citizen|residen|salary|gender|race|disab|veteran|hear about|referr|e-?mail|phone|linkedin|github"
211
+ choice = (
212
+ binding.get("role") == "combobox"
213
+ or binding.get("widget")
214
+ or binding.get("tag_name") in {"select", "choice_group"}
215
+ )
216
+ if not choice and not re.search(fact_words, label) and is_narrative_question(question):
217
+ return question
218
+ return question.model_copy(update={"semantic_key": exact})
219
+
220
+
221
+ def resolve_scoped_answer(
222
+ question: FormQuestion, binding: dict, entries: list, *, job_country: str | None = None
223
+ ):
224
+ """Normalize an explicit affirmative/negative only on a bound choice question."""
225
+ key = question.semantic_key or ""
226
+ if key in {"sponsorship_by_country", "work_authorization_by_country"}:
227
+ return derive_employment_answer(question, entries, region=job_country)
228
+ is_choice = (
229
+ bool(binding.get("widget"))
230
+ or binding.get("role") == "combobox"
231
+ or binding.get("tag_name")
232
+ in {
233
+ "select",
234
+ "choice_group",
235
+ }
236
+ )
237
+ region = {
238
+ "work_authorization_canada": "Canada",
239
+ "sponsorship_required_canada": "Canada",
240
+ "us_work_authorized": "United States",
241
+ "sponsorship_required_united_states": "United States",
242
+ "work_authorization_china": "China",
243
+ "sponsorship_required_china": "China",
244
+ }.get(key)
245
+ # Resolve conflicts/expiry/region BEFORE normalization. Two different Yes
246
+ # statements must not collapse into a single apparently approved answer.
247
+ resolver = AnswerResolver()
248
+ result = resolver.resolve(question.model_copy(update={"options": []}), entries, region=region)
249
+ if not result.value or result.requires_human:
250
+ return result
251
+ value = result.value
252
+ if is_choice:
253
+ match = re.match(r"^(yes|no)\b", value.strip(), re.IGNORECASE)
254
+ if match:
255
+ value = match[1].capitalize()
256
+ elif key == "ai_policy_acknowledgment" and value == (
257
+ "I acknowledge and agree to the company's policy on AI use in the application process."
258
+ ):
259
+ value = "Yes"
260
+ elif key == "arbitration_agreement" and value == "I agree to the arbitration agreement.":
261
+ # Only exact observed wording of this explicitly approved agreement.
262
+ options = {
263
+ "I will read the arbitration agreement below.",
264
+ "I understand and agree to the terms of the Agreement to Arbitrate set forth above.",
265
+ }
266
+ available = options.intersection(question.options)
267
+ if len(available) == 1:
268
+ value = next(iter(available))
269
+ if question.options and value not in question.options:
270
+ return resolver._block(question, "stored answer does not match available options")
271
+ return result.model_copy(update={"value": value})
272
+
273
+
274
+ def matching_bindings(target: dict, bindings: tuple[dict, ...]) -> list[dict]:
275
+ """Only the exact observed question may authorize a value on this control."""
276
+
277
+ def norm(value):
278
+ return " ".join(str(value or "").split()).casefold()
279
+
280
+ matches = []
281
+ for binding in bindings:
282
+ # Shared inspection currently covers the main frame only.
283
+ if target.get("frame", 0) != 0:
284
+ continue
285
+ if target.get("role") == "option" and target.get("listbox_id"):
286
+ owned = (binding.get("controls", "") + " " + binding.get("owns", "")).split()
287
+ if (
288
+ binding.get("role") == "combobox"
289
+ and binding.get("expanded") == "true"
290
+ and target["listbox_id"] in owned
291
+ ):
292
+ matches.append(binding)
293
+ continue
294
+ if any(
295
+ norm(target.get(a)) != norm(binding.get(b))
296
+ for a, b in (
297
+ ("tag", "tag_name"),
298
+ ("type", "input_type"),
299
+ ("label", "label"),
300
+ ("group", "group_label"),
301
+ )
302
+ ):
303
+ continue
304
+ native = next((k for k in ("dom_id", "dom_name") if binding.get(k)), None)
305
+ if native and target.get(native) != binding[native]:
306
+ continue
307
+ matches.append(binding)
308
+ return matches