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,561 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import re
5
+ from pathlib import Path
6
+ from typing import Any
7
+ from urllib.parse import urldefrag, urljoin, urlparse
8
+
9
+ from job_apply_agent.config import Settings, get_settings
10
+ from job_apply_agent.domain.enums import BlockerKind, Sensitivity
11
+ from job_apply_agent.domain.schemas import FormQuestion, ResolvedAnswer
12
+
13
+ from .base import ApplicationResult, ATSAdapter, ATSBlocked, InspectionResult, SubmissionClaim
14
+ from .captcha import inspect_captcha
15
+ from .page_readiness import FieldBindingError, locate_inspected_field, wait_for_application_surface
16
+
17
+ SENSITIVE_PATTERNS: tuple[tuple[str, str], ...] = (
18
+ (r"visa|sponsor|work authori[sz]", "work_authorization"),
19
+ (r"salary|compensation|pay expectation", "salary_expectation"),
20
+ (r"gender|sex", "eeo_gender"),
21
+ (r"race|ethnic", "eeo_race_ethnicity"),
22
+ (r"disab", "eeo_disability"),
23
+ (r"veteran", "eeo_veteran"),
24
+ (r"criminal|background check", "background_check"),
25
+ )
26
+
27
+ NORMAL_PATTERNS: tuple[tuple[str, str], ...] = (
28
+ (r"first name", "first_name"),
29
+ (r"last name|surname|family name", "last_name"),
30
+ (r"full name|your name|^name\s*\*?$", "full_name"),
31
+ (r"e-?mail", "email"),
32
+ (r"phone|mobile", "phone"),
33
+ (r"linkedin", "linkedin_url"),
34
+ (r"github", "github_url"),
35
+ (r"portfolio|website", "website_url"),
36
+ (r"resume|curriculum vitae|\bcv\b", "resume_upload"),
37
+ (r"cover letter", "cover_letter_upload"),
38
+ )
39
+
40
+
41
+ class PlaywrightATSAdapter(ATSAdapter):
42
+ field_selector = "input, textarea, select, [role=combobox]"
43
+ submit_selectors = (
44
+ 'button[type="submit"]',
45
+ 'input[type="submit"]',
46
+ 'button:has-text("Submit application")',
47
+ 'button:has-text("Submit")',
48
+ )
49
+ success_url_pattern = re.compile(
50
+ r"(?:confirmation|application[-_/]?submitted|thank[-_/]?you|success)", re.IGNORECASE
51
+ )
52
+ success_text_pattern = re.compile(
53
+ r"(?:thank you for (?:your )?(?:application|applying)|"
54
+ r"application (?:has been |was )?(?:successfully )?(?:submitted|received)|"
55
+ r"we(?:'ve| have) received your application|"
56
+ r"successfully submitted)",
57
+ re.IGNORECASE,
58
+ )
59
+
60
+ def __init__(self, settings: Settings | None = None) -> None:
61
+ self.settings = settings or get_settings()
62
+ self._uploaded_file_names: dict[str, str] = {}
63
+ self._field_bindings: dict[str, dict[str, Any]] = {}
64
+ self.captcha_evidence: dict[str, Any] = {}
65
+
66
+ async def wait_until_ready(self, page: Any) -> dict:
67
+ return await wait_for_application_surface(
68
+ page, timeout_ms=self.settings.browser_page_ready_timeout_seconds * 1000
69
+ )
70
+
71
+ async def inspect(self, page: Any) -> InspectionResult:
72
+ blocker = await self._detect_blocker(page)
73
+ if blocker:
74
+ return InspectionResult(questions=[], blocker=blocker[0], blocker_detail=blocker[1])
75
+ raw_fields = await page.eval_on_selector_all(
76
+ self.field_selector,
77
+ """
78
+ els => els.filter(el => {
79
+ if (el.type === 'hidden' || el.disabled) return false;
80
+ // Upload controls may be intentionally hidden behind an upload button.
81
+ if (el.type === 'file') return true;
82
+ return el.getClientRects().length > 0 &&
83
+ window.getComputedStyle(el).visibility !== 'hidden';
84
+ }).map((el, index) => {
85
+ const fieldId = (
86
+ el.getAttribute('data-job-apply-field-id') || el.id || el.name || `field-${index}`
87
+ );
88
+ el.setAttribute('data-job-apply-field-id', fieldId);
89
+ const labels = el.labels ? Array.from(el.labels).map(x => x.innerText).join(' ') : '';
90
+ const described = el.getAttribute('aria-labelledby');
91
+ const ariaText = described
92
+ ? (document.getElementById(described)?.innerText || '')
93
+ : '';
94
+ const group = el.closest('fieldset,.ashby-application-form-field-entry,.application-question');
95
+ const groupLabel = (group?.querySelector('legend,.ashby-application-form-question-title,.application-label')?.textContent || '').trim();
96
+ return {
97
+ field_id: fieldId,
98
+ dom_id: el.id || '',
99
+ dom_name: el.name || '',
100
+ role: el.getAttribute('role') || '',
101
+ controls: el.getAttribute('aria-controls') || '',
102
+ owns: el.getAttribute('aria-owns') || '',
103
+ expanded: el.getAttribute('aria-expanded') || '',
104
+ widget: el.matches('.ashby-application-form-input-autocomplete') ? 'ashby_autocomplete' : '',
105
+ group_label: groupLabel,
106
+ label: (
107
+ (el.type === 'file' && groupLabel ? groupLabel : '') ||
108
+ labels || el.getAttribute('aria-label') || ariaText ||
109
+ el.placeholder || el.name || ''
110
+ ).trim(),
111
+ input_type: (el.type || '').toLowerCase(),
112
+ tag_name: el.tagName.toLowerCase(),
113
+ max_length: el.maxLength >= 0 ? el.maxLength : null,
114
+ required: !!el.required || el.getAttribute('aria-required') === 'true' ||
115
+ [...(group?.querySelector('.ashby-application-form-question-title')?.classList || [])]
116
+ .some(name => name.startsWith('_required_')),
117
+ options: el.tagName === 'SELECT'
118
+ ? Array.from(el.options).map(o => o.text.trim()).filter(Boolean)
119
+ : []
120
+ };
121
+ })
122
+ """,
123
+ )
124
+ self._field_bindings = {item["field_id"]: item for item in raw_fields}
125
+ return InspectionResult(questions=[self._question(item) for item in raw_fields])
126
+
127
+ async def fill(
128
+ self,
129
+ page: Any,
130
+ answers: list[ResolvedAnswer],
131
+ *,
132
+ resume_path: Path,
133
+ cover_letter_path: Path | None = None,
134
+ ) -> None:
135
+ for answer in answers:
136
+ if answer.requires_human:
137
+ raise ATSBlocked(
138
+ answer.blocker or BlockerKind.UNKNOWN_QUESTION, answer.reason or ""
139
+ )
140
+ if answer.value is None:
141
+ continue
142
+ binding = self._field_bindings.get(answer.field_id)
143
+ if binding is None:
144
+ raise FieldBindingError(f"field was not inspected: {answer.field_id}")
145
+ locator = await locate_inspected_field(page, binding)
146
+ if answer.value == "UPLOAD_RESUME":
147
+ await locator.set_input_files(str(resume_path))
148
+ self._uploaded_file_names[answer.field_id] = resume_path.name
149
+ elif answer.value == "UPLOAD_COVER_LETTER":
150
+ if cover_letter_path is None:
151
+ raise ATSBlocked(
152
+ BlockerKind.UNKNOWN_QUESTION, "cover letter requested but absent"
153
+ )
154
+ await locator.set_input_files(str(cover_letter_path))
155
+ self._uploaded_file_names[answer.field_id] = cover_letter_path.name
156
+ else:
157
+ tag = await locator.evaluate("el => el.tagName")
158
+ if tag == "SELECT":
159
+ await locator.select_option(label=answer.value)
160
+ else:
161
+ await locator.fill(answer.value)
162
+
163
+ async def verify(self, page: Any) -> list[str]:
164
+ return await page.eval_on_selector_all(
165
+ "input[required], textarea[required], select[required], [aria-required=true]",
166
+ """
167
+ els => els.filter(el => {
168
+ if (el.disabled || el.type === 'hidden') return false;
169
+ const style = window.getComputedStyle(el);
170
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
171
+ if (el.type === 'checkbox') return !el.checked;
172
+ if (el.type === 'radio') {
173
+ if (!el.name) return !el.checked;
174
+ const group = Array.from(document.querySelectorAll('input[type=radio]'))
175
+ .filter(item => item.name === el.name && !item.disabled);
176
+ return !group.some(item => item.checked);
177
+ }
178
+ const value = el.value ?? el.getAttribute('aria-valuetext') ?? '';
179
+ return !String(value).trim();
180
+ }).map(el => el.id || el.name || el.getAttribute('aria-label') || 'unknown')
181
+ """,
182
+ )
183
+
184
+ async def readiness_issues(self, page: Any) -> list[str]:
185
+ """Return deterministic reasons the host must not submit yet."""
186
+ blocker = await self._detect_blocker(page)
187
+ if blocker:
188
+ raise ATSBlocked(*blocker)
189
+ issues = [f"required field is empty: {field_id}" for field_id in await self.verify(page)]
190
+ visible_submit = None
191
+ for selector in self.submit_selectors:
192
+ button = page.locator(selector).first
193
+ if await button.count() and await button.is_visible():
194
+ visible_submit = button
195
+ break
196
+ if visible_submit is None:
197
+ issues.append("final submit control is not visible")
198
+ elif not await visible_submit.is_enabled():
199
+ issues.append("final submit control is disabled")
200
+ return issues
201
+
202
+ async def submit(self, page: Any, claim: SubmissionClaim) -> ApplicationResult:
203
+ live_error = self.settings.live_submission_error()
204
+ if live_error:
205
+ raise PermissionError(live_error)
206
+ blocker = await self._detect_blocker(page)
207
+ if blocker:
208
+ raise ATSBlocked(*blocker)
209
+ missing = await self.verify(page)
210
+ if missing:
211
+ raise ATSBlocked(BlockerKind.UNKNOWN_QUESTION, f"required fields missing: {missing}")
212
+ button = await self._visible_submit_control(page)
213
+ if button is None:
214
+ raise ATSBlocked(BlockerKind.UNKNOWN_QUESTION, "submit control not found")
215
+ if not claim.claim():
216
+ return ApplicationResult(submitted=False, receipt={"reason": "already_claimed"})
217
+ before_url = page.url
218
+ await button.click()
219
+ confirmed = await self._wait_for_submission_confirmation(page, before_url)
220
+ if not confirmed:
221
+ raise ATSBlocked(
222
+ BlockerKind.SUBMIT_OUTCOME_UNKNOWN,
223
+ "submit was clicked but no ATS confirmation was observed; do not retry",
224
+ evidence={"before_url": before_url, "final_url": page.url},
225
+ )
226
+ receipt = {
227
+ "url": page.url,
228
+ "status": "submission_confirmed",
229
+ "confirmation": confirmed,
230
+ }
231
+ claim.complete(receipt)
232
+ return ApplicationResult(submitted=True, receipt=receipt)
233
+
234
+ async def _visible_submit_control(self, page: Any) -> Any | None:
235
+ for selector in self.submit_selectors:
236
+ button = page.locator(selector).first
237
+ if await button.count() and await button.is_visible():
238
+ return button
239
+ return None
240
+
241
+ async def _wait_for_submission_confirmation(self, page: Any, before_url: str) -> str | None:
242
+ deadline = (
243
+ asyncio.get_running_loop().time() + self.settings.submit_confirmation_timeout_seconds
244
+ )
245
+ while asyncio.get_running_loop().time() < deadline:
246
+ current_url = page.url
247
+ url_confirmation = self._url_confirmation(current_url, before_url)
248
+ if url_confirmation:
249
+ return url_confirmation
250
+ ashby_success = page.locator(".ashby-application-form-success-container").first
251
+ if await ashby_success.count() and await ashby_success.is_visible():
252
+ return "ashby_success_container"
253
+ ashby_failure = page.locator(".ashby-application-form-failure-container").first
254
+ if await ashby_failure.count() and await ashby_failure.is_visible():
255
+ raise ATSBlocked(
256
+ BlockerKind.SUBMIT_OUTCOME_UNKNOWN,
257
+ "Ashby displayed a submission failure after the submit claim; "
258
+ "reconcile before retrying",
259
+ )
260
+ try:
261
+ body_text = await page.locator("body").inner_text(timeout=2_000)
262
+ except Exception: # noqa: BLE001 - normalize optional Playwright failures
263
+ body_text = ""
264
+ if self.success_text_pattern.search(body_text):
265
+ return "success_text"
266
+ await asyncio.sleep(0.5)
267
+ return None
268
+
269
+ def _url_confirmation(self, current_url: str, before_url: str) -> str | None:
270
+ if current_url != before_url and self.success_url_pattern.search(current_url):
271
+ return "success_url"
272
+ return None
273
+
274
+ async def _detect_blocker(self, page: Any) -> tuple[BlockerKind, str] | None:
275
+ self.captcha_evidence = await inspect_captcha(page)
276
+ if self.captcha_evidence["blocking"]:
277
+ return (
278
+ BlockerKind.CAPTCHA,
279
+ "active or unclassified visible CAPTCHA requires manual takeover",
280
+ )
281
+ if await page.locator(
282
+ 'input[autocomplete="one-time-code"], input[name*="otp" i], input[id*="otp" i]'
283
+ ).count():
284
+ return BlockerKind.TWO_FACTOR, "2FA requires manual takeover"
285
+ if await page.locator('input[type="password"]').count():
286
+ return BlockerKind.LOGIN_REQUIRED, "login requires manual takeover"
287
+ return None
288
+
289
+ @staticmethod
290
+ def _question(item: dict[str, Any]) -> FormQuestion:
291
+ input_type = item.get("input_type", "")
292
+ if input_type == "file":
293
+ semantic_key = (
294
+ "cover_letter_upload"
295
+ if re.search(r"cover letter", item["label"], re.IGNORECASE)
296
+ else "resume_upload"
297
+ )
298
+ return FormQuestion(**item, semantic_key=semantic_key)
299
+ label = item.get("group_label") or item["label"]
300
+ # Composite selectors can contain anonymous helper inputs inside a Phone
301
+ # or Country question. Group context alone does not make them writable
302
+ # answers; leave custom selectors and unnamed helpers to inspected actions.
303
+ if (
304
+ item.get("tag_name", "input") not in {"input", "textarea", "select"}
305
+ or (item.get("role") == "combobox" and item.get("tag_name") != "select")
306
+ or not (item["label"] or item.get("dom_id") or item.get("dom_name"))
307
+ ):
308
+ return FormQuestion(**item)
309
+ # A choice mentioning Email/LinkedIn is not a contact text field. Keep
310
+ # choices unresolved until a question-specific answer is available.
311
+ if input_type in {"checkbox", "radio", "button", "submit"}:
312
+ return FormQuestion(**item)
313
+ for pattern, semantic_key in SENSITIVE_PATTERNS:
314
+ if re.search(pattern, label, re.IGNORECASE):
315
+ return FormQuestion(
316
+ **item,
317
+ semantic_key=semantic_key,
318
+ sensitivity=Sensitivity.SENSITIVE,
319
+ )
320
+ for pattern, semantic_key in NORMAL_PATTERNS:
321
+ if re.search(pattern, label, re.IGNORECASE):
322
+ return FormQuestion(**item, semantic_key=semantic_key)
323
+ return FormQuestion(**item)
324
+
325
+
326
+ class GreenhouseAdapter(PlaywrightATSAdapter):
327
+ pass
328
+
329
+
330
+ class LeverAdapter(PlaywrightATSAdapter):
331
+ """Lever hosted forms put hCaptcha in front of the real form POST.
332
+
333
+ The visible button only asks hCaptcha for a token. Intercept the actual
334
+ application POST and acquire the durable claim immediately before that
335
+ request is released to the network. A CAPTCHA that never releases a POST
336
+ therefore remains safely retryable instead of becoming an unknown submit.
337
+ """
338
+
339
+ async def submit(self, page: Any, claim: SubmissionClaim) -> ApplicationResult:
340
+ live_error = self.settings.live_submission_error()
341
+ if live_error:
342
+ raise PermissionError(live_error)
343
+ blocker = await self._detect_blocker(page)
344
+ if blocker:
345
+ raise ATSBlocked(*blocker)
346
+ missing = await self.verify(page)
347
+ if missing:
348
+ raise ATSBlocked(BlockerKind.UNKNOWN_QUESTION, f"required fields missing: {missing}")
349
+ button = await self._visible_submit_control(page)
350
+ if button is None:
351
+ raise ATSBlocked(BlockerKind.UNKNOWN_QUESTION, "submit control not found")
352
+
353
+ before_url = page.url
354
+ form = page.locator("form#application-form, form").first
355
+ action = await form.get_attribute("action") if await form.count() else None
356
+ submission_url = urldefrag(urljoin(before_url, action or before_url)).url
357
+ request_seen = asyncio.Event()
358
+ response_seen = asyncio.Event()
359
+ evidence: dict[str, Any] = {
360
+ "request_observed": False,
361
+ "request_url": submission_url,
362
+ }
363
+ claim_error: Exception | None = None
364
+
365
+ async def guard_submission(route: Any, request: Any) -> None:
366
+ nonlocal claim_error
367
+ if request.method.upper() != "POST":
368
+ await route.fallback()
369
+ return
370
+ if evidence["request_observed"]:
371
+ evidence["duplicate_request_blocked"] = True
372
+ await route.abort("blockedbyclient")
373
+ return
374
+ evidence["request_observed"] = True
375
+ try:
376
+ evidence["claim_acquired"] = claim.claim()
377
+ except Exception as exc: # noqa: BLE001 - surface durable-claim failures to caller
378
+ claim_error = exc
379
+ evidence["claim_acquired"] = False
380
+ request_seen.set()
381
+ if not evidence["claim_acquired"]:
382
+ await route.abort("blockedbyclient")
383
+ return
384
+ await route.fallback()
385
+
386
+ def record_response(response: Any) -> None:
387
+ request = response.request
388
+ if request.method.upper() == "POST" and urldefrag(request.url).url == submission_url:
389
+ evidence["response_status"] = response.status
390
+ evidence["response_url"] = response.url
391
+ response_seen.set()
392
+
393
+ await page.route(submission_url, guard_submission)
394
+ page.on("response", record_response)
395
+ try:
396
+ # The click itself is not a submit boundary on Lever: it may only
397
+ # launch hCaptcha. The route above owns the real boundary.
398
+ await button.click(no_wait_after=True)
399
+ await self._wait_for_lever_submission_request(page, request_seen)
400
+ if claim_error is not None:
401
+ raise claim_error
402
+ if not evidence["request_observed"]:
403
+ invalid = await page.eval_on_selector_all(
404
+ "form#application-form :invalid, form :invalid",
405
+ "els => els.map(el => el.id || el.name || el.getAttribute('aria-label') || 'unknown')",
406
+ )
407
+ evidence["invalid_fields"] = invalid
408
+ if invalid:
409
+ raise ATSBlocked(
410
+ BlockerKind.UNKNOWN_QUESTION,
411
+ "Lever rejected the form before sending a submit request because fields "
412
+ f"remain invalid: {invalid}",
413
+ evidence=evidence,
414
+ )
415
+ if await page.locator(
416
+ '#h-captcha, .h-captcha, iframe[src*="hcaptcha" i], '
417
+ 'iframe[src*="captcha" i], [name="h-captcha-response"]'
418
+ ).count():
419
+ raise ATSBlocked(
420
+ BlockerKind.CAPTCHA,
421
+ "Lever hCaptcha did not release the application POST; no submit request "
422
+ "was sent and no durable submit claim was created",
423
+ evidence=evidence,
424
+ )
425
+ raise ATSBlocked(
426
+ BlockerKind.UNKNOWN_QUESTION,
427
+ "Lever submit control did not produce an application POST; no durable submit "
428
+ "claim was created",
429
+ evidence=evidence,
430
+ )
431
+ if not evidence.get("claim_acquired"):
432
+ return ApplicationResult(
433
+ submitted=False,
434
+ receipt={"reason": "already_claimed", "submission": evidence},
435
+ )
436
+
437
+ confirmed = await self._wait_for_submission_confirmation(page, before_url)
438
+ if not confirmed:
439
+ # A claimed POST can still be in flight when confirmation exits.
440
+ # Collect a bounded response signal without releasing/retrying it.
441
+ try:
442
+ await asyncio.wait_for(response_seen.wait(), timeout=2)
443
+ except TimeoutError:
444
+ pass
445
+ raise ATSBlocked(
446
+ BlockerKind.SUBMIT_OUTCOME_UNKNOWN,
447
+ "Lever application POST was sent but no ATS confirmation was observed; "
448
+ "do not retry",
449
+ evidence=evidence,
450
+ )
451
+ receipt = {
452
+ "url": page.url,
453
+ "status": "submission_confirmed",
454
+ "confirmation": confirmed,
455
+ "submission": evidence,
456
+ }
457
+ claim.complete(receipt)
458
+ return ApplicationResult(submitted=True, receipt=receipt)
459
+ finally:
460
+ page.remove_listener("response", record_response)
461
+ await page.unroute(submission_url, guard_submission)
462
+
463
+ async def _wait_for_lever_submission_request(
464
+ self, page: Any, request_seen: asyncio.Event
465
+ ) -> None:
466
+ deadline = (
467
+ asyncio.get_running_loop().time() + self.settings.submit_confirmation_timeout_seconds
468
+ )
469
+ while not request_seen.is_set() and asyncio.get_running_loop().time() < deadline:
470
+ blocker = await self._detect_blocker(page)
471
+ if blocker:
472
+ return
473
+ remaining = deadline - asyncio.get_running_loop().time()
474
+ try:
475
+ await asyncio.wait_for(request_seen.wait(), timeout=min(0.25, remaining))
476
+ except TimeoutError:
477
+ pass
478
+
479
+ def _url_confirmation(self, current_url: str, before_url: str) -> str | None:
480
+ if current_url != before_url:
481
+ path = urlparse(current_url).path.lower().rstrip("/")
482
+ if path.endswith("/thanks"):
483
+ return "lever_thanks_url"
484
+ if path.endswith("/already-received"):
485
+ return "lever_already_received_url"
486
+ return super()._url_confirmation(current_url, before_url)
487
+
488
+
489
+ class AshbyAdapter(PlaywrightATSAdapter):
490
+ async def verify(self, page: Any) -> list[str]:
491
+ missing = await super().verify(page)
492
+ fields = await page.locator(".ashby-application-form-field-entry, fieldset").evaluate_all(
493
+ """(fields, uploaded) => {
494
+ const visible = el => el && el.getClientRects().length > 0 &&
495
+ getComputedStyle(el).visibility !== 'hidden';
496
+ return fields.filter(visible).flatMap(field => {
497
+ const heading = field.querySelector(
498
+ '.ashby-application-form-question-title, legend'
499
+ );
500
+ if (!heading || !Array.from(heading.classList).some(
501
+ name => name.startsWith('_required_')
502
+ )) return [];
503
+ const controls = Array.from(field.querySelectorAll('input, textarea, select'));
504
+ const ids = controls.flatMap(el => [el.id, el.name,
505
+ el.getAttribute('data-job-apply-field-id')]).filter(Boolean);
506
+ const key = field.getAttribute('data-field-path') || ids[0] ||
507
+ heading.textContent.trim();
508
+ let ready = false;
509
+ const file = field.querySelector('input[type=file]');
510
+ const toggles = field.querySelectorAll('button[aria-pressed]');
511
+ if (file) {
512
+ const expected = uploaded[file.getAttribute('data-job-apply-field-id')] ||
513
+ uploaded[file.id];
514
+ const items = Array.from(field.querySelectorAll(
515
+ '.ashby-application-form-input-file-item'
516
+ )).filter(visible);
517
+ ready = !!expected && items.length === 1 &&
518
+ items[0].querySelector('.ashby-application-form-input-file-item-name')
519
+ ?.textContent.trim() === expected &&
520
+ !!items[0].querySelector('.ashby-application-form-input-file-item-delete');
521
+ } else if (toggles.length) {
522
+ ready = Array.from(toggles).filter(
523
+ el => el.getAttribute('aria-pressed') === 'true'
524
+ ).length === 1;
525
+ } else if (field.querySelector('input[type=radio]')) {
526
+ ready = !!field.querySelector('input[type=radio]:checked');
527
+ } else if (field.querySelector('input[type=checkbox]')) {
528
+ ready = !!field.querySelector('input[type=checkbox]:checked');
529
+ } else {
530
+ const values = controls.filter(el => el.type !== 'hidden' &&
531
+ !el.disabled && visible(el));
532
+ ready = values.length > 0 && values.every(el =>
533
+ String(el.value || '').trim() && el.getAttribute('aria-expanded') !== 'true');
534
+ }
535
+ if (field.querySelector('[aria-invalid=true], [aria-busy=true]') ||
536
+ Array.from(field.querySelectorAll('[role=alert]')).some(visible)) ready = false;
537
+ return [{key, ids, ready, label: heading.textContent.trim()}];
538
+ });
539
+ }""",
540
+ self._uploaded_file_names,
541
+ )
542
+ self._required_field_labels = {
543
+ key: field["label"] for field in fields for key in [field["key"], *field["ids"]]
544
+ }
545
+ for field in fields:
546
+ if field["ready"]:
547
+ missing = [value for value in missing if value not in field["ids"]]
548
+ elif field["key"] not in missing:
549
+ missing.append(field["key"])
550
+ return missing
551
+
552
+ async def readiness_issues(self, page: Any) -> list[str]:
553
+ issues = await super().readiness_issues(page)
554
+ labels = getattr(self, "_required_field_labels", {})
555
+ prefix = "required field is empty: "
556
+ return [
557
+ f"{issue} ({labels[issue.removeprefix(prefix)]})"
558
+ if issue.startswith(prefix) and issue.removeprefix(prefix) in labels
559
+ else issue
560
+ for issue in issues
561
+ ]
job_apply_agent/cli.py ADDED
@@ -0,0 +1,108 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from dataclasses import asdict
6
+ from pathlib import Path
7
+
8
+ import uvicorn
9
+
10
+ from . import __version__
11
+ from .db import Base, get_engine
12
+
13
+
14
+ def main() -> None:
15
+ parser = argparse.ArgumentParser(prog="job-apply-agent")
16
+ parser.add_argument("--version", action="version", version=__version__)
17
+ subparsers = parser.add_subparsers(dest="command", required=True)
18
+ subparsers.add_parser("init-db", help="create database tables for local development")
19
+ onboarding = subparsers.add_parser(
20
+ "onboard", help="initialize and check private candidate files"
21
+ )
22
+ onboarding.add_argument("action", choices=("init", "check", "import-answers"))
23
+ onboarding.add_argument("--directory", type=Path, default=Path("private/candidate"))
24
+ serve = subparsers.add_parser("serve", help="run the FastAPI service")
25
+ serve.add_argument("--host", default="127.0.0.1")
26
+ serve.add_argument("--port", default=8000, type=int)
27
+ managed_apply = subparsers.add_parser(
28
+ "managed-apply",
29
+ help="queue a complete worker-owned application run and exit",
30
+ )
31
+ managed_apply.add_argument("application_id")
32
+ report = subparsers.add_parser(
33
+ "application-report",
34
+ help="analyze persisted outcomes without modifying or dispatching jobs",
35
+ )
36
+ report.add_argument("--application-id", action="append", dest="application_ids")
37
+ managed_backlog = subparsers.add_parser(
38
+ "managed-backlog",
39
+ help="start, inspect, or stop the worker-owned application backlog",
40
+ )
41
+ managed_backlog.add_argument("action", choices=("start", "status", "stop"))
42
+ managed_backlog.add_argument("--application-id", action="append", dest="application_ids")
43
+ args = parser.parse_args()
44
+ if args.command == "onboard":
45
+ from .config import get_settings
46
+ from .onboarding import check, import_answers, initialize, read_answers
47
+
48
+ if args.action == "init":
49
+ print(json.dumps({"created": initialize(args.directory)}, indent=2))
50
+ elif args.action == "check":
51
+ result = check(get_settings())
52
+ print(json.dumps(result, indent=2))
53
+ if not result["ready"]:
54
+ raise SystemExit(1)
55
+ else:
56
+ from .db import get_session_factory
57
+
58
+ try:
59
+ entries = read_answers(get_settings().answer_bank_path)
60
+ with get_session_factory()() as session:
61
+ count = import_answers(session, entries)
62
+ session.commit()
63
+ except (OSError, ValueError, TypeError):
64
+ parser.exit(1, "Invalid answer file or conflicting scopes; no answers imported.\n")
65
+ print(json.dumps({"imported": count}))
66
+ elif args.command == "init-db":
67
+ import job_apply_agent.models # noqa: F401
68
+
69
+ Base.metadata.create_all(get_engine())
70
+ elif args.command == "serve":
71
+ uvicorn.run("job_apply_agent.api:app", host=args.host, port=args.port)
72
+ elif args.command == "managed-apply":
73
+ from .managed_apply import dispatch_managed_application
74
+
75
+ dispatch = dispatch_managed_application(args.application_id)
76
+ print(json.dumps(asdict(dispatch), sort_keys=True))
77
+ elif args.command == "application-report":
78
+ from .db import get_session_factory
79
+ from .services.application_report import application_report
80
+
81
+ with get_session_factory()() as session:
82
+ result = application_report(session, application_ids=args.application_ids)
83
+ print(json.dumps(result, sort_keys=True, indent=2))
84
+ elif args.command == "managed-backlog":
85
+ from .managed_backlog import (
86
+ dispatch_managed_backlog_if_enabled,
87
+ get_managed_backlog_status,
88
+ start_managed_backlog,
89
+ stop_managed_backlog,
90
+ )
91
+
92
+ if args.action == "start":
93
+ start = start_managed_backlog(application_ids=args.application_ids)
94
+ tick = dispatch_managed_backlog_if_enabled()
95
+ print(
96
+ json.dumps(
97
+ {"start": asdict(start), "tick": asdict(tick)},
98
+ sort_keys=True,
99
+ )
100
+ )
101
+ elif args.action == "status":
102
+ print(json.dumps(get_managed_backlog_status(), sort_keys=True))
103
+ else:
104
+ print(json.dumps(stop_managed_backlog(), sort_keys=True))
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
@@ -0,0 +1,7 @@
1
+ from .ashby import AshbySource
2
+ from .base import BoardConfig
3
+ from .greenhouse import GreenhouseSource
4
+ from .lever import LeverSource
5
+ from .normalizer import JobNormalizer
6
+
7
+ __all__ = ["AshbySource", "BoardConfig", "GreenhouseSource", "JobNormalizer", "LeverSource"]